repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/configs.rs | crates/router/src/configs.rs | use hyperswitch_interfaces::secrets_interface::secret_state::RawSecret;
pub(crate) mod defaults;
pub mod secrets_transformers;
pub mod settings;
mod validations;
pub type Settings = settings::Settings<RawSecret>;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/routes.rs | crates/router/src/routes.rs | pub mod admin;
pub mod api_keys;
pub mod app;
#[cfg(feature = "v1")]
pub mod apple_pay_certificates_migration;
pub mod authentication;
#[cfg(all(feature = "olap", feature = "v1"))]
pub mod blocklist;
pub mod cache;
pub mod cards_info;
pub mod configs;
#[cfg(feature = "olap")]
pub mod connector_onboarding;
#[cfg(any(feature = "olap", feature = "oltp"))]
pub mod currency;
pub mod customers;
pub mod disputes;
#[cfg(feature = "dummy_connector")]
pub mod dummy_connector;
pub mod ephemeral_key;
pub mod feature_matrix;
pub mod files;
#[cfg(feature = "frm")]
pub mod fraud_check;
pub mod gsm;
pub mod health;
pub mod hypersense;
pub mod lock_utils;
#[cfg(feature = "v1")]
pub mod locker_migration;
pub mod mandates;
pub mod metrics;
pub mod oidc;
#[cfg(feature = "v1")]
pub mod payment_link;
pub mod payment_methods;
pub mod payments;
#[cfg(feature = "payouts")]
pub mod payout_link;
#[cfg(feature = "payouts")]
pub mod payouts;
#[cfg(any(feature = "olap", feature = "oltp"))]
pub mod pm_auth;
pub mod poll;
#[cfg(feature = "olap")]
pub mod profile_acquirer;
#[cfg(feature = "olap")]
pub mod profiles;
#[cfg(feature = "recon")]
pub mod recon;
pub mod refunds;
#[cfg(feature = "v2")]
pub mod revenue_recovery_data_backfill;
#[cfg(feature = "v2")]
pub mod revenue_recovery_redis;
#[cfg(feature = "olap")]
pub mod routing;
#[cfg(feature = "v1")]
pub mod subscription;
pub mod three_ds_decision_rule;
pub mod tokenization;
#[cfg(feature = "olap")]
pub mod user;
#[cfg(feature = "olap")]
pub mod user_role;
#[cfg(feature = "olap")]
pub mod verification;
#[cfg(feature = "olap")]
pub mod verify_connector;
#[cfg(all(feature = "olap", feature = "v1"))]
pub mod webhook_events;
pub mod webhooks;
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
pub mod recovery_webhooks;
pub mod relay;
#[cfg(feature = "olap")]
pub mod process_tracker;
#[cfg(feature = "v2")]
pub mod proxy;
pub mod chat;
#[cfg(feature = "dummy_connector")]
pub use self::app::DummyConnector;
#[cfg(feature = "v2")]
pub use self::app::PaymentMethodSession;
#[cfg(all(feature = "oltp", feature = "v2"))]
pub use self::app::Proxy;
#[cfg(all(feature = "olap", feature = "recon", feature = "v1"))]
pub use self::app::Recon;
pub use self::app::{
ApiKeys, AppState, ApplePayCertificatesMigration, Authentication, Cache, Cards, Chat, Configs,
ConnectorOnboarding, Customers, Disputes, EphemeralKey, FeatureMatrix, Files, Forex, Gsm,
Health, Hypersense, Mandates, MerchantAccount, MerchantConnectorAccount, Oidc, PaymentLink,
PaymentMethods, Payments, Poll, ProcessTracker, ProcessTrackerDeprecated, Profile,
ProfileAcquirer, ProfileNew, Refunds, Relay, RelayWebhooks, SessionState, ThreeDsDecisionRule,
User, UserDeprecated, Webhooks,
};
#[cfg(feature = "olap")]
pub use self::app::{Blocklist, Organization, Routing, Subscription, Verify, WebhookEvents};
#[cfg(feature = "payouts")]
pub use self::app::{PayoutLink, Payouts};
#[cfg(feature = "v2")]
pub use self::app::{RecoveryDataBackfill, Tokenization};
#[cfg(all(feature = "stripe", feature = "v1"))]
pub use super::compatibility::stripe::StripeApis;
#[cfg(feature = "olap")]
pub use crate::analytics::routes::{self as analytics, Analytics};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/locale.rs | crates/router/src/locale.rs | use rust_i18n::i18n;
i18n!("locales", fallback = "en");
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/analytics.rs | crates/router/src/analytics.rs | pub use analytics::*;
pub mod routes {
use std::{
collections::{HashMap, HashSet},
sync::Arc,
};
use actix_web::{web, Responder, Scope};
use analytics::{
api_event::api_events_core, connector_events::connector_events_core, enums::AuthInfo,
errors::AnalyticsError, lambda_utils::invoke_lambda, opensearch::OpenSearchError,
outgoing_webhook_event::outgoing_webhook_events_core, routing_events::routing_events_core,
sdk_events::sdk_events_core, AnalyticsFlow,
};
use api_models::analytics::{
api_event::QueryType,
search::{
GetGlobalSearchRequest, GetSearchRequest, GetSearchRequestWithIndex, SearchIndex,
},
AnalyticsRequest, GenerateReportRequest, GetActivePaymentsMetricRequest,
GetApiEventFiltersRequest, GetApiEventMetricRequest, GetAuthEventFilterRequest,
GetAuthEventMetricRequest, GetDisputeMetricRequest, GetFrmFilterRequest,
GetFrmMetricRequest, GetPaymentFiltersRequest, GetPaymentIntentFiltersRequest,
GetPaymentIntentMetricRequest, GetPaymentMetricRequest, GetRefundFilterRequest,
GetRefundMetricRequest, GetSdkEventFiltersRequest, GetSdkEventMetricRequest, ReportRequest,
};
use common_enums::EntityType;
use common_utils::types::TimeRange;
use error_stack::{report, ResultExt};
use futures::{stream::FuturesUnordered, StreamExt};
use crate::{
analytics_validator::request_validator,
consts::opensearch::SEARCH_INDEXES,
core::{api_locking, errors::user::UserErrors, verification::utils},
db::{user::UserInterface, user_role::ListUserRolesByUserIdPayload},
routes::AppState,
services::{
api,
authentication::{self as auth, AuthenticationData, UserFromToken},
authorization::{permissions::Permission, roles::RoleInfo},
ApplicationResponse,
},
types::{domain::UserEmail, storage::UserRole},
};
pub struct Analytics;
impl Analytics {
#[cfg(feature = "v2")]
pub fn server(state: AppState) -> Scope {
web::scope("/analytics").app_data(web::Data::new(state))
}
#[cfg(feature = "v1")]
pub fn server(state: AppState) -> Scope {
web::scope("/analytics")
.app_data(web::Data::new(state))
.service(
web::scope("/v1")
.service(
web::resource("metrics/payments")
.route(web::post().to(get_merchant_payment_metrics)),
)
.service(
web::resource("metrics/routing")
.route(web::post().to(get_merchant_payment_metrics)),
)
.service(
web::resource("metrics/refunds")
.route(web::post().to(get_merchant_refund_metrics)),
)
.service(
web::resource("filters/payments")
.route(web::post().to(get_merchant_payment_filters)),
)
.service(
web::resource("filters/routing")
.route(web::post().to(get_merchant_payment_filters)),
)
.service(
web::resource("filters/frm").route(web::post().to(get_frm_filters)),
)
.service(
web::resource("filters/refunds")
.route(web::post().to(get_merchant_refund_filters)),
)
.service(web::resource("{domain}/info").route(web::get().to(get_info)))
.service(
web::resource("report/dispute")
.route(web::post().to(generate_merchant_dispute_report)),
)
.service(
web::resource("report/refunds")
.route(web::post().to(generate_merchant_refund_report)),
)
.service(
web::resource("report/payments")
.route(web::post().to(generate_merchant_payment_report)),
)
.service(
web::resource("report/payouts")
.route(web::post().to(generate_merchant_payout_report)),
)
.service(
web::resource("report/authentications")
.route(web::post().to(generate_merchant_authentication_report)),
)
.service(
web::resource("metrics/sdk_events")
.route(web::post().to(get_sdk_event_metrics)),
)
.service(
web::resource("metrics/active_payments")
.route(web::post().to(get_active_payments_metrics)),
)
.service(
web::resource("filters/sdk_events")
.route(web::post().to(get_sdk_event_filters)),
)
.service(
web::resource("metrics/auth_events")
.route(web::post().to(get_merchant_auth_event_metrics)),
)
.service(
web::resource("filters/auth_events")
.route(web::post().to(get_merchant_auth_events_filters)),
)
.service(
web::resource("metrics/frm").route(web::post().to(get_frm_metrics)),
)
.service(
web::resource("api_event_logs")
.route(web::get().to(get_profile_api_events)),
)
.service(
web::resource("sdk_event_logs")
.route(web::post().to(get_profile_sdk_events)),
)
.service(
web::resource("connector_event_logs")
.route(web::get().to(get_profile_connector_events)),
)
.service(
web::resource("routing_event_logs")
.route(web::get().to(get_profile_routing_events)),
)
.service(
web::resource("outgoing_webhook_event_logs")
.route(web::get().to(get_profile_outgoing_webhook_events)),
)
.service(
web::resource("metrics/api_events")
.route(web::post().to(get_merchant_api_events_metrics)),
)
.service(
web::resource("filters/api_events")
.route(web::post().to(get_merchant_api_event_filters)),
)
.service(
web::resource("search")
.route(web::post().to(get_global_search_results)),
)
.service(
web::resource("search/{domain}")
.route(web::post().to(get_search_results)),
)
.service(
web::resource("metrics/disputes")
.route(web::post().to(get_merchant_dispute_metrics)),
)
.service(
web::resource("filters/disputes")
.route(web::post().to(get_merchant_dispute_filters)),
)
.service(
web::resource("metrics/sankey")
.route(web::post().to(get_merchant_sankey)),
)
.service(
web::resource("metrics/auth_events/sankey")
.route(web::post().to(get_merchant_auth_event_sankey)),
)
.service(
web::scope("/merchant")
.service(
web::resource("metrics/payments")
.route(web::post().to(get_merchant_payment_metrics)),
)
.service(
web::resource("metrics/routing")
.route(web::post().to(get_merchant_payment_metrics)),
)
.service(
web::resource("metrics/refunds")
.route(web::post().to(get_merchant_refund_metrics)),
)
.service(
web::resource("metrics/auth_events")
.route(web::post().to(get_merchant_auth_event_metrics)),
)
.service(
web::resource("filters/payments")
.route(web::post().to(get_merchant_payment_filters)),
)
.service(
web::resource("filters/routing")
.route(web::post().to(get_merchant_payment_filters)),
)
.service(
web::resource("filters/refunds")
.route(web::post().to(get_merchant_refund_filters)),
)
.service(
web::resource("filters/auth_events")
.route(web::post().to(get_merchant_auth_events_filters)),
)
.service(
web::resource("{domain}/info").route(web::get().to(get_info)),
)
.service(
web::resource("report/dispute")
.route(web::post().to(generate_merchant_dispute_report)),
)
.service(
web::resource("report/refunds")
.route(web::post().to(generate_merchant_refund_report)),
)
.service(
web::resource("report/payments")
.route(web::post().to(generate_merchant_payment_report)),
)
.service(
web::resource("report/payouts")
.route(web::post().to(generate_merchant_payout_report)),
)
.service(
web::resource("report/authentications").route(
web::post().to(generate_merchant_authentication_report),
),
)
.service(
web::resource("metrics/api_events")
.route(web::post().to(get_merchant_api_events_metrics)),
)
.service(
web::resource("filters/api_events")
.route(web::post().to(get_merchant_api_event_filters)),
)
.service(
web::resource("metrics/disputes")
.route(web::post().to(get_merchant_dispute_metrics)),
)
.service(
web::resource("filters/disputes")
.route(web::post().to(get_merchant_dispute_filters)),
)
.service(
web::resource("metrics/sankey")
.route(web::post().to(get_merchant_sankey)),
)
.service(
web::resource("metrics/auth_events/sankey")
.route(web::post().to(get_merchant_auth_event_sankey)),
),
)
.service(
web::scope("/org")
.service(
web::resource("{domain}/info").route(web::get().to(get_info)),
)
.service(
web::resource("metrics/payments")
.route(web::post().to(get_org_payment_metrics)),
)
.service(
web::resource("filters/payments")
.route(web::post().to(get_org_payment_filters)),
)
.service(
web::resource("metrics/routing")
.route(web::post().to(get_org_payment_metrics)),
)
.service(
web::resource("filters/routing")
.route(web::post().to(get_org_payment_filters)),
)
.service(
web::resource("metrics/refunds")
.route(web::post().to(get_org_refund_metrics)),
)
.service(
web::resource("filters/refunds")
.route(web::post().to(get_org_refund_filters)),
)
.service(
web::resource("metrics/disputes")
.route(web::post().to(get_org_dispute_metrics)),
)
.service(
web::resource("metrics/auth_events")
.route(web::post().to(get_org_auth_event_metrics)),
)
.service(
web::resource("filters/disputes")
.route(web::post().to(get_org_dispute_filters)),
)
.service(
web::resource("filters/auth_events")
.route(web::post().to(get_org_auth_events_filters)),
)
.service(
web::resource("report/dispute")
.route(web::post().to(generate_org_dispute_report)),
)
.service(
web::resource("report/refunds")
.route(web::post().to(generate_org_refund_report)),
)
.service(
web::resource("report/payments")
.route(web::post().to(generate_org_payment_report)),
)
.service(
web::resource("report/payouts")
.route(web::post().to(generate_org_payout_report)),
)
.service(
web::resource("report/authentications")
.route(web::post().to(generate_org_authentication_report)),
)
.service(
web::resource("metrics/sankey")
.route(web::post().to(get_org_sankey)),
)
.service(
web::resource("metrics/auth_events/sankey")
.route(web::post().to(get_org_auth_event_sankey)),
),
)
.service(
web::scope("/profile")
.service(
web::resource("{domain}/info").route(web::get().to(get_info)),
)
.service(
web::resource("metrics/payments")
.route(web::post().to(get_profile_payment_metrics)),
)
.service(
web::resource("filters/payments")
.route(web::post().to(get_profile_payment_filters)),
)
.service(
web::resource("metrics/routing")
.route(web::post().to(get_profile_payment_metrics)),
)
.service(
web::resource("filters/routing")
.route(web::post().to(get_profile_payment_filters)),
)
.service(
web::resource("metrics/refunds")
.route(web::post().to(get_profile_refund_metrics)),
)
.service(
web::resource("filters/refunds")
.route(web::post().to(get_profile_refund_filters)),
)
.service(
web::resource("metrics/disputes")
.route(web::post().to(get_profile_dispute_metrics)),
)
.service(
web::resource("metrics/auth_events")
.route(web::post().to(get_profile_auth_event_metrics)),
)
.service(
web::resource("filters/disputes")
.route(web::post().to(get_profile_dispute_filters)),
)
.service(
web::resource("filters/auth_events")
.route(web::post().to(get_profile_auth_events_filters)),
)
.service(
web::resource("connector_event_logs")
.route(web::get().to(get_profile_connector_events)),
)
.service(
web::resource("routing_event_logs")
.route(web::get().to(get_profile_routing_events)),
)
.service(
web::resource("outgoing_webhook_event_logs")
.route(web::get().to(get_profile_outgoing_webhook_events)),
)
.service(
web::resource("report/dispute")
.route(web::post().to(generate_profile_dispute_report)),
)
.service(
web::resource("report/refunds")
.route(web::post().to(generate_profile_refund_report)),
)
.service(
web::resource("report/payments")
.route(web::post().to(generate_profile_payment_report)),
)
.service(
web::resource("report/payouts")
.route(web::post().to(generate_profile_payout_report)),
)
.service(
web::resource("report/authentications").route(
web::post().to(generate_profile_authentication_report),
),
)
.service(
web::resource("api_event_logs")
.route(web::get().to(get_profile_api_events)),
)
.service(
web::resource("sdk_event_logs")
.route(web::post().to(get_profile_sdk_events)),
)
.service(
web::resource("metrics/sankey")
.route(web::post().to(get_profile_sankey)),
)
.service(
web::resource("metrics/auth_events/sankey")
.route(web::post().to(get_profile_auth_event_sankey)),
),
),
)
.service(
web::scope("/v2")
.service(
web::resource("/metrics/payments")
.route(web::post().to(get_merchant_payment_intent_metrics)),
)
.service(
web::resource("/filters/payments")
.route(web::post().to(get_payment_intents_filters)),
)
.service(
web::scope("/merchant")
.service(
web::resource("/metrics/payments")
.route(web::post().to(get_merchant_payment_intent_metrics)),
)
.service(
web::resource("/filters/payments")
.route(web::post().to(get_payment_intents_filters)),
),
)
.service(
web::scope("/org").service(
web::resource("/metrics/payments")
.route(web::post().to(get_org_payment_intent_metrics)),
),
)
.service(
web::scope("/profile").service(
web::resource("/metrics/payments")
.route(web::post().to(get_profile_payment_intent_metrics)),
),
),
)
}
}
pub async fn get_info(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
domain: web::Path<analytics::AnalyticsDomain>,
) -> impl Responder {
let flow = AnalyticsFlow::GetInfo;
Box::pin(api::server_wrap(
flow,
state,
&req,
domain.into_inner(),
|_, _: (), domain: analytics::AnalyticsDomain, _| async {
analytics::core::get_domain_info(domain)
.await
.map(ApplicationResponse::Json)
},
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
/// # Panics
///
/// Panics if `json_payload` array does not contain one `GetPaymentMetricRequest` element.
pub async fn get_merchant_payment_metrics(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<[GetPaymentMetricRequest; 1]>,
) -> impl Responder {
// safety: This shouldn't panic owing to the data type
#[allow(clippy::expect_used)]
let payload = json_payload
.into_inner()
.to_vec()
.pop()
.expect("Couldn't get GetPaymentMetricRequest");
let flow = AnalyticsFlow::GetPaymentMetrics;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: AuthenticationData, req, _| async move {
let org_id = auth.platform.get_processor().get_account().get_org_id();
let merchant_id = auth.platform.get_processor().get_account().get_id();
let auth: AuthInfo = AuthInfo::MerchantLevel {
org_id: org_id.clone(),
merchant_ids: vec![merchant_id.clone()],
};
let validator_response = request_validator(
AnalyticsRequest {
payment_attempt: Some(req.clone()),
..Default::default()
},
&state,
)
.await?;
let ex_rates = validator_response;
analytics::payments::get_metrics(&state.pool, &ex_rates, &auth, req)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// # Panics
///
/// Panics if `json_payload` array does not contain one `GetPaymentMetricRequest` element.
pub async fn get_org_payment_metrics(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<[GetPaymentMetricRequest; 1]>,
) -> impl Responder {
// safety: This shouldn't panic owing to the data type
#[allow(clippy::expect_used)]
let payload = json_payload
.into_inner()
.to_vec()
.pop()
.expect("Couldn't get GetPaymentMetricRequest");
let flow = AnalyticsFlow::GetPaymentMetrics;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: AuthenticationData, req, _| async move {
let org_id = auth.platform.get_processor().get_account().get_org_id();
let auth: AuthInfo = AuthInfo::OrgLevel {
org_id: org_id.clone(),
};
let validator_response = request_validator(
AnalyticsRequest {
payment_attempt: Some(req.clone()),
..Default::default()
},
&state,
)
.await?;
let ex_rates = validator_response;
analytics::payments::get_metrics(&state.pool, &ex_rates, &auth, req)
.await
.map(ApplicationResponse::Json)
},
auth::auth_type(
&auth::PlatformOrgAdminAuth {
is_admin_auth_allowed: false,
organization_id: None,
},
&auth::JWTAuth {
permission: Permission::OrganizationAnalyticsRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
#[cfg(feature = "v1")]
/// # Panics
///
/// Panics if `json_payload` array does not contain one `GetPaymentMetricRequest` element.
pub async fn get_profile_payment_metrics(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<[GetPaymentMetricRequest; 1]>,
) -> impl Responder {
// safety: This shouldn't panic owing to the data type
#[allow(clippy::expect_used)]
let payload = json_payload
.into_inner()
.to_vec()
.pop()
.expect("Couldn't get GetPaymentMetricRequest");
let flow = AnalyticsFlow::GetPaymentMetrics;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: AuthenticationData, req, _| async move {
let org_id = auth.platform.get_processor().get_account().get_org_id();
let merchant_id = auth.platform.get_processor().get_account().get_id();
let profile_id = auth
.profile
.ok_or(report!(UserErrors::JwtProfileIdMissing))
.change_context(AnalyticsError::AccessForbiddenError)?
.get_id()
.clone();
let auth: AuthInfo = AuthInfo::ProfileLevel {
org_id: org_id.clone(),
merchant_id: merchant_id.clone(),
profile_ids: vec![profile_id.clone()],
};
let validator_response = request_validator(
AnalyticsRequest {
payment_attempt: Some(req.clone()),
..Default::default()
},
&state,
)
.await?;
let ex_rates = validator_response;
analytics::payments::get_metrics(&state.pool, &ex_rates, &auth, req)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
/// # Panics
///
/// Panics if `json_payload` array does not contain one `GetPaymentIntentMetricRequest` element.
pub async fn get_merchant_payment_intent_metrics(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<[GetPaymentIntentMetricRequest; 1]>,
) -> impl Responder {
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/kafka.rs | crates/router/src/services/kafka.rs | use std::{collections::HashMap, sync::Arc};
use common_utils::{errors::CustomResult, types::TenantConfig};
use error_stack::{report, ResultExt};
use events::{EventsError, Message, MessagingInterface};
use num_traits::ToPrimitive;
use rdkafka::{
config::FromClientConfig,
message::{Header, OwnedHeaders},
producer::{BaseRecord, DefaultProducerContext, Producer, ThreadedProducer},
};
use serde_json::Value;
#[cfg(feature = "payouts")]
pub mod payout;
use diesel_models::fraud_check::FraudCheck;
use crate::{events::EventType, services::kafka::fraud_check_event::KafkaFraudCheckEvent};
mod authentication;
mod authentication_event;
mod dispute;
mod dispute_event;
mod fraud_check;
mod fraud_check_event;
mod payment_attempt;
mod payment_attempt_event;
mod payment_intent;
mod payment_intent_event;
mod refund;
mod refund_event;
pub mod revenue_recovery;
use diesel_models::refund::Refund;
use hyperswitch_domain_models::payments::{payment_attempt::PaymentAttempt, PaymentIntent};
use serde::Serialize;
use time::{OffsetDateTime, PrimitiveDateTime};
#[cfg(feature = "payouts")]
use self::payout::KafkaPayout;
use self::{
authentication::KafkaAuthentication, authentication_event::KafkaAuthenticationEvent,
dispute::KafkaDispute, dispute_event::KafkaDisputeEvent, payment_attempt::KafkaPaymentAttempt,
payment_attempt_event::KafkaPaymentAttemptEvent, payment_intent::KafkaPaymentIntent,
payment_intent_event::KafkaPaymentIntentEvent, refund::KafkaRefund,
refund_event::KafkaRefundEvent,
};
use crate::{services::kafka::fraud_check::KafkaFraudCheck, types::storage::Dispute};
// Using message queue result here to avoid confusion with Kafka result provided by library
pub type MQResult<T> = CustomResult<T, KafkaError>;
use crate::db::kafka_store::TenantID;
pub trait KafkaMessage
where
Self: Serialize + std::fmt::Debug,
{
fn value(&self) -> MQResult<Vec<u8>> {
// Add better error logging here
serde_json::to_vec(&self).change_context(KafkaError::GenericError)
}
fn key(&self) -> String;
fn event_type(&self) -> EventType;
fn creation_timestamp(&self) -> Option<i64> {
None
}
}
#[derive(serde::Serialize, Debug)]
struct KafkaEvent<'a, T: KafkaMessage> {
#[serde(flatten)]
event: &'a T,
sign_flag: i32,
tenant_id: TenantID,
clickhouse_database: Option<String>,
}
impl<'a, T: KafkaMessage> KafkaEvent<'a, T> {
fn new(event: &'a T, tenant_id: TenantID, clickhouse_database: Option<String>) -> Self {
Self {
event,
sign_flag: 1,
tenant_id,
clickhouse_database,
}
}
fn old(event: &'a T, tenant_id: TenantID, clickhouse_database: Option<String>) -> Self {
Self {
event,
sign_flag: -1,
tenant_id,
clickhouse_database,
}
}
}
impl<T: KafkaMessage> KafkaMessage for KafkaEvent<'_, T> {
fn key(&self) -> String {
self.event.key()
}
fn event_type(&self) -> EventType {
self.event.event_type()
}
fn creation_timestamp(&self) -> Option<i64> {
self.event.creation_timestamp()
}
}
#[derive(serde::Serialize, Debug)]
struct KafkaConsolidatedLog<'a, T: KafkaMessage> {
#[serde(flatten)]
event: &'a T,
tenant_id: TenantID,
}
#[derive(serde::Serialize, Debug)]
struct KafkaConsolidatedEvent<'a, T: KafkaMessage> {
log: KafkaConsolidatedLog<'a, T>,
log_type: EventType,
}
impl<'a, T: KafkaMessage> KafkaConsolidatedEvent<'a, T> {
fn new(event: &'a T, tenant_id: TenantID) -> Self {
Self {
log: KafkaConsolidatedLog { event, tenant_id },
log_type: event.event_type(),
}
}
}
impl<T: KafkaMessage> KafkaMessage for KafkaConsolidatedEvent<'_, T> {
fn key(&self) -> String {
self.log.event.key()
}
fn event_type(&self) -> EventType {
EventType::Consolidated
}
fn creation_timestamp(&self) -> Option<i64> {
self.log.event.creation_timestamp()
}
}
#[derive(Debug, serde::Deserialize, Clone, Default)]
#[serde(default)]
pub struct KafkaSettings {
brokers: Vec<String>,
fraud_check_analytics_topic: String,
intent_analytics_topic: String,
attempt_analytics_topic: String,
refund_analytics_topic: String,
api_logs_topic: String,
connector_logs_topic: String,
outgoing_webhook_logs_topic: String,
dispute_analytics_topic: String,
audit_events_topic: String,
#[cfg(feature = "payouts")]
payout_analytics_topic: String,
consolidated_events_topic: String,
authentication_analytics_topic: String,
routing_logs_topic: String,
revenue_recovery_topic: String,
}
impl KafkaSettings {
pub fn validate(&self) -> Result<(), crate::core::errors::ApplicationError> {
use common_utils::ext_traits::ConfigExt;
use crate::core::errors::ApplicationError;
common_utils::fp_utils::when(self.brokers.is_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka brokers must not be empty".into(),
))
})?;
common_utils::fp_utils::when(self.intent_analytics_topic.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka Intent Analytics topic must not be empty".into(),
))
})?;
common_utils::fp_utils::when(self.attempt_analytics_topic.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka Attempt Analytics topic must not be empty".into(),
))
})?;
common_utils::fp_utils::when(self.refund_analytics_topic.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka Refund Analytics topic must not be empty".into(),
))
})?;
common_utils::fp_utils::when(self.api_logs_topic.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka API event Analytics topic must not be empty".into(),
))
})?;
common_utils::fp_utils::when(self.connector_logs_topic.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka Connector Logs topic must not be empty".into(),
))
})?;
common_utils::fp_utils::when(
self.outgoing_webhook_logs_topic.is_default_or_empty(),
|| {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka Outgoing Webhook Logs topic must not be empty".into(),
))
},
)?;
common_utils::fp_utils::when(self.dispute_analytics_topic.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka Dispute Logs topic must not be empty".into(),
))
})?;
common_utils::fp_utils::when(self.audit_events_topic.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka Audit Events topic must not be empty".into(),
))
})?;
#[cfg(feature = "payouts")]
common_utils::fp_utils::when(self.payout_analytics_topic.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka Payout Analytics topic must not be empty".into(),
))
})?;
common_utils::fp_utils::when(self.consolidated_events_topic.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Consolidated Events topic must not be empty".into(),
))
})?;
common_utils::fp_utils::when(
self.authentication_analytics_topic.is_default_or_empty(),
|| {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka Authentication Analytics topic must not be empty".into(),
))
},
)?;
common_utils::fp_utils::when(self.routing_logs_topic.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka Routing Logs topic must not be empty".into(),
))
})?;
Ok(())
}
}
#[derive(Clone, Debug)]
pub struct KafkaProducer {
producer: Arc<RdKafkaProducer>,
intent_analytics_topic: String,
fraud_check_analytics_topic: String,
attempt_analytics_topic: String,
refund_analytics_topic: String,
api_logs_topic: String,
connector_logs_topic: String,
outgoing_webhook_logs_topic: String,
dispute_analytics_topic: String,
audit_events_topic: String,
#[cfg(feature = "payouts")]
payout_analytics_topic: String,
consolidated_events_topic: String,
authentication_analytics_topic: String,
ckh_database_name: Option<String>,
routing_logs_topic: String,
revenue_recovery_topic: String,
}
struct RdKafkaProducer(ThreadedProducer<DefaultProducerContext>);
impl std::fmt::Debug for RdKafkaProducer {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("RdKafkaProducer")
}
}
#[derive(Debug, Clone, thiserror::Error)]
pub enum KafkaError {
#[error("Generic Kafka Error")]
GenericError,
#[error("Kafka not implemented")]
NotImplemented,
#[error("Kafka Initialization Error")]
InitializationError,
}
#[allow(unused)]
impl KafkaProducer {
pub fn set_tenancy(&mut self, tenant_config: &dyn TenantConfig) {
self.ckh_database_name = Some(tenant_config.get_clickhouse_database().to_string());
}
pub async fn create(conf: &KafkaSettings) -> MQResult<Self> {
Ok(Self {
producer: Arc::new(RdKafkaProducer(
ThreadedProducer::from_config(
rdkafka::ClientConfig::new().set("bootstrap.servers", conf.brokers.join(",")),
)
.change_context(KafkaError::InitializationError)?,
)),
fraud_check_analytics_topic: conf.fraud_check_analytics_topic.clone(),
intent_analytics_topic: conf.intent_analytics_topic.clone(),
attempt_analytics_topic: conf.attempt_analytics_topic.clone(),
refund_analytics_topic: conf.refund_analytics_topic.clone(),
api_logs_topic: conf.api_logs_topic.clone(),
connector_logs_topic: conf.connector_logs_topic.clone(),
outgoing_webhook_logs_topic: conf.outgoing_webhook_logs_topic.clone(),
dispute_analytics_topic: conf.dispute_analytics_topic.clone(),
audit_events_topic: conf.audit_events_topic.clone(),
#[cfg(feature = "payouts")]
payout_analytics_topic: conf.payout_analytics_topic.clone(),
consolidated_events_topic: conf.consolidated_events_topic.clone(),
authentication_analytics_topic: conf.authentication_analytics_topic.clone(),
ckh_database_name: None,
routing_logs_topic: conf.routing_logs_topic.clone(),
revenue_recovery_topic: conf.revenue_recovery_topic.clone(),
})
}
pub fn log_event<T: KafkaMessage>(&self, event: &T) -> MQResult<()> {
router_env::logger::debug!("Logging Kafka Event {event:?}");
let topic = self.get_topic(event.event_type());
self.producer
.0
.send(
BaseRecord::to(topic)
.key(&event.key())
.payload(&event.value()?)
.timestamp(event.creation_timestamp().unwrap_or_else(|| {
(OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000)
.try_into()
.unwrap_or_else(|_| {
// kafka producer accepts milliseconds
// try converting nanos to millis if that fails convert seconds to millis
OffsetDateTime::now_utc().unix_timestamp() * 1_000
})
})),
)
.map_err(|(error, record)| report!(error).attach_printable(format!("{record:?}")))
.change_context(KafkaError::GenericError)
}
pub async fn log_fraud_check(
&self,
attempt: &FraudCheck,
old_attempt: Option<FraudCheck>,
tenant_id: TenantID,
) -> MQResult<()> {
if let Some(negative_event) = old_attempt {
self.log_event(&KafkaEvent::old(
&KafkaFraudCheck::from_storage(&negative_event),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add negative fraud check event {negative_event:?}")
})?;
};
self.log_event(&KafkaEvent::new(
&KafkaFraudCheck::from_storage(attempt),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add positive fraud check event {attempt:?}")
})?;
self.log_event(&KafkaConsolidatedEvent::new(
&KafkaFraudCheckEvent::from_storage(attempt),
tenant_id.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add consolidated fraud check event {attempt:?}")
})
}
pub async fn log_payment_attempt(
&self,
attempt: &PaymentAttempt,
old_attempt: Option<PaymentAttempt>,
tenant_id: TenantID,
) -> MQResult<()> {
if let Some(negative_event) = old_attempt {
self.log_event(&KafkaEvent::old(
&KafkaPaymentAttempt::from_storage(&negative_event),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add negative attempt event {negative_event:?}")
})?;
};
self.log_event(&KafkaEvent::new(
&KafkaPaymentAttempt::from_storage(attempt),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| format!("Failed to add positive attempt event {attempt:?}"))?;
self.log_event(&KafkaConsolidatedEvent::new(
&KafkaPaymentAttemptEvent::from_storage(attempt),
tenant_id.clone(),
))
.attach_printable_lazy(|| format!("Failed to add consolidated attempt event {attempt:?}"))
}
pub async fn log_payment_attempt_delete(
&self,
delete_old_attempt: &PaymentAttempt,
tenant_id: TenantID,
) -> MQResult<()> {
self.log_event(&KafkaEvent::old(
&KafkaPaymentAttempt::from_storage(delete_old_attempt),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add negative attempt event {delete_old_attempt:?}")
})
}
pub async fn log_authentication(
&self,
authentication: &hyperswitch_domain_models::authentication::Authentication,
old_authentication: Option<hyperswitch_domain_models::authentication::Authentication>,
tenant_id: TenantID,
) -> MQResult<()> {
if let Some(negative_event) = old_authentication {
self.log_event(&KafkaEvent::old(
&KafkaAuthentication::from_storage(&negative_event),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add negative authentication event {negative_event:?}")
})?;
};
self.log_event(&KafkaEvent::new(
&KafkaAuthentication::from_storage(authentication),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add positive authentication event {authentication:?}")
})?;
self.log_event(&KafkaConsolidatedEvent::new(
&KafkaAuthenticationEvent::from_storage(authentication),
tenant_id.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add consolidated authentication event {authentication:?}")
})
}
pub async fn log_payment_intent(
&self,
intent: &PaymentIntent,
old_intent: Option<PaymentIntent>,
tenant_id: TenantID,
infra_values: Option<Value>,
) -> MQResult<()> {
if let Some(negative_event) = old_intent {
self.log_event(&KafkaEvent::old(
&KafkaPaymentIntent::from_storage(&negative_event, infra_values.clone()),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add negative intent event {negative_event:?}")
})?;
};
self.log_event(&KafkaEvent::new(
&KafkaPaymentIntent::from_storage(intent, infra_values.clone()),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| format!("Failed to add positive intent event {intent:?}"))?;
self.log_event(&KafkaConsolidatedEvent::new(
&KafkaPaymentIntentEvent::from_storage(intent, infra_values.clone()),
tenant_id.clone(),
))
.attach_printable_lazy(|| format!("Failed to add consolidated intent event {intent:?}"))
}
pub async fn log_payment_intent_delete(
&self,
delete_old_intent: &PaymentIntent,
tenant_id: TenantID,
infra_values: Option<Value>,
) -> MQResult<()> {
self.log_event(&KafkaEvent::old(
&KafkaPaymentIntent::from_storage(delete_old_intent, infra_values),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add negative intent event {delete_old_intent:?}")
})
}
pub async fn log_refund(
&self,
refund: &Refund,
old_refund: Option<Refund>,
tenant_id: TenantID,
) -> MQResult<()> {
if let Some(negative_event) = old_refund {
self.log_event(&KafkaEvent::old(
&KafkaRefund::from_storage(&negative_event),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add negative refund event {negative_event:?}")
})?;
};
self.log_event(&KafkaEvent::new(
&KafkaRefund::from_storage(refund),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| format!("Failed to add positive refund event {refund:?}"))?;
self.log_event(&KafkaConsolidatedEvent::new(
&KafkaRefundEvent::from_storage(refund),
tenant_id.clone(),
))
.attach_printable_lazy(|| format!("Failed to add consolidated refund event {refund:?}"))
}
pub async fn log_refund_delete(
&self,
delete_old_refund: &Refund,
tenant_id: TenantID,
) -> MQResult<()> {
self.log_event(&KafkaEvent::old(
&KafkaRefund::from_storage(delete_old_refund),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add negative refund event {delete_old_refund:?}")
})
}
pub async fn log_dispute(
&self,
dispute: &Dispute,
old_dispute: Option<Dispute>,
tenant_id: TenantID,
) -> MQResult<()> {
if let Some(negative_event) = old_dispute {
self.log_event(&KafkaEvent::old(
&KafkaDispute::from_storage(&negative_event),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add negative dispute event {negative_event:?}")
})?;
};
self.log_event(&KafkaEvent::new(
&KafkaDispute::from_storage(dispute),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| format!("Failed to add positive dispute event {dispute:?}"))?;
self.log_event(&KafkaConsolidatedEvent::new(
&KafkaDisputeEvent::from_storage(dispute),
tenant_id.clone(),
))
.attach_printable_lazy(|| format!("Failed to add consolidated dispute event {dispute:?}"))
}
pub async fn log_dispute_delete(
&self,
delete_old_dispute: &Dispute,
tenant_id: TenantID,
) -> MQResult<()> {
self.log_event(&KafkaEvent::old(
&KafkaDispute::from_storage(delete_old_dispute),
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add negative dispute event {delete_old_dispute:?}")
})
}
#[cfg(feature = "payouts")]
pub async fn log_payout(
&self,
payout: &KafkaPayout<'_>,
old_payout: Option<KafkaPayout<'_>>,
tenant_id: TenantID,
) -> MQResult<()> {
if let Some(negative_event) = old_payout {
self.log_event(&KafkaEvent::old(
&negative_event,
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add negative payout event {negative_event:?}")
})?;
};
self.log_event(&KafkaEvent::new(
payout,
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| format!("Failed to add positive payout event {payout:?}"))
}
#[cfg(feature = "payouts")]
pub async fn log_payout_delete(
&self,
delete_old_payout: &KafkaPayout<'_>,
tenant_id: TenantID,
) -> MQResult<()> {
self.log_event(&KafkaEvent::old(
delete_old_payout,
tenant_id.clone(),
self.ckh_database_name.clone(),
))
.attach_printable_lazy(|| {
format!("Failed to add negative payout event {delete_old_payout:?}")
})
}
pub fn get_topic(&self, event: EventType) -> &str {
match event {
EventType::FraudCheck => &self.fraud_check_analytics_topic,
EventType::ApiLogs => &self.api_logs_topic,
EventType::PaymentAttempt => &self.attempt_analytics_topic,
EventType::PaymentIntent => &self.intent_analytics_topic,
EventType::Refund => &self.refund_analytics_topic,
EventType::ConnectorApiLogs => &self.connector_logs_topic,
EventType::OutgoingWebhookLogs => &self.outgoing_webhook_logs_topic,
EventType::Dispute => &self.dispute_analytics_topic,
EventType::AuditEvent => &self.audit_events_topic,
#[cfg(feature = "payouts")]
EventType::Payout => &self.payout_analytics_topic,
EventType::Consolidated => &self.consolidated_events_topic,
EventType::Authentication => &self.authentication_analytics_topic,
EventType::RoutingApiLogs => &self.routing_logs_topic,
EventType::RevenueRecovery => &self.revenue_recovery_topic,
}
}
}
impl Drop for RdKafkaProducer {
fn drop(&mut self) {
// Flush the producer to send any pending messages
match self.0.flush(rdkafka::util::Timeout::After(
std::time::Duration::from_secs(5),
)) {
Ok(_) => router_env::logger::info!("Kafka events flush Successful"),
Err(error) => router_env::logger::error!("Failed to flush Kafka Events {error:?}"),
}
}
}
impl MessagingInterface for KafkaProducer {
type MessageClass = EventType;
fn send_message<T>(
&self,
data: T,
metadata: HashMap<String, String>,
timestamp: PrimitiveDateTime,
) -> error_stack::Result<(), EventsError>
where
T: Message<Class = Self::MessageClass> + masking::ErasedMaskSerialize,
{
let topic = self.get_topic(data.get_message_class());
let json_data = data
.masked_serialize()
.and_then(|mut value| {
if let Value::Object(ref mut map) = value {
if let Some(db_name) = self.ckh_database_name.clone() {
map.insert("clickhouse_database".to_string(), Value::String(db_name));
}
}
serde_json::to_vec(&value)
})
.change_context(EventsError::SerializationError)?;
let mut headers = OwnedHeaders::new();
for (k, v) in metadata.iter() {
headers = headers.insert(Header {
key: k.as_str(),
value: Some(v),
});
}
headers = headers.insert(Header {
key: "clickhouse_database",
value: self.ckh_database_name.as_ref(),
});
self.producer
.0
.send(
BaseRecord::to(topic)
.key(&data.identifier())
.payload(&json_data)
.headers(headers)
.timestamp(
(timestamp.assume_utc().unix_timestamp_nanos() / 1_000_000)
.to_i64()
.unwrap_or_else(|| {
// kafka producer accepts milliseconds
// try converting nanos to millis if that fails convert seconds to millis
timestamp.assume_utc().unix_timestamp() * 1_000
}),
),
)
.map_err(|(error, record)| report!(error).attach_printable(format!("{record:?}")))
.change_context(KafkaError::GenericError)
.change_context(EventsError::PublishError)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/email.rs | crates/router/src/services/email.rs | pub mod types;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/jwt.rs | crates/router/src/services/jwt.rs | use common_utils::errors::CustomResult;
use error_stack::ResultExt;
use jsonwebtoken::{encode, EncodingKey, Header};
use masking::PeekInterface;
use crate::{configs::Settings, core::errors::UserErrors};
pub fn generate_exp(
exp_duration: std::time::Duration,
) -> CustomResult<std::time::Duration, UserErrors> {
std::time::SystemTime::now()
.checked_add(exp_duration)
.ok_or(UserErrors::InternalServerError)?
.duration_since(std::time::UNIX_EPOCH)
.change_context(UserErrors::InternalServerError)
}
pub async fn generate_jwt<T>(
claims_data: &T,
settings: &Settings,
) -> CustomResult<String, UserErrors>
where
T: serde::ser::Serialize,
{
let jwt_secret = &settings.secrets.get_inner().jwt_secret;
encode(
&Header::default(),
claims_data,
&EncodingKey::from_secret(jwt_secret.peek().as_bytes()),
)
.change_context(UserErrors::InternalServerError)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/logger.rs | crates/router/src/services/logger.rs | //! Logger of the system.
pub use crate::logger::*;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/encryption.rs | crates/router/src/services/encryption.rs | use std::str;
use error_stack::{report, ResultExt};
use josekit::{jwe, jws};
use serde::{Deserialize, Serialize};
use crate::{
core::errors::{self, CustomResult},
utils,
};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct JwsBody {
pub header: String,
pub payload: String,
pub signature: String,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JweBody {
pub header: String,
pub iv: String,
pub encrypted_payload: String,
pub tag: String,
pub encrypted_key: String,
}
#[derive(Debug, Eq, PartialEq, Copy, Clone, strum::AsRefStr, strum::Display)]
pub enum EncryptionAlgorithm {
A128GCM,
A256GCM,
}
pub async fn encrypt_jwe(
payload: &[u8],
public_key: impl AsRef<[u8]>,
algorithm: EncryptionAlgorithm,
key_id: Option<&str>,
) -> CustomResult<String, errors::EncryptionError> {
let alg = jwe::RSA_OAEP_256;
let mut src_header = jwe::JweHeader::new();
let enc_str = algorithm.as_ref();
src_header.set_content_encryption(enc_str);
src_header.set_token_type("JWT");
if let Some(key_id) = key_id {
src_header.set_key_id(key_id);
}
let encrypter = alg
.encrypter_from_pem(public_key)
.change_context(errors::EncryptionError)
.attach_printable("Error getting JweEncryptor")?;
jwe::serialize_compact(payload, &src_header, &encrypter)
.change_context(errors::EncryptionError)
.attach_printable("Error getting jwt string")
}
pub enum KeyIdCheck<'a> {
RequestResponseKeyId((&'a str, &'a str)),
SkipKeyIdCheck,
}
pub async fn decrypt_jwe(
jwt: &str,
key_ids: KeyIdCheck<'_>,
private_key: impl AsRef<[u8]>,
alg: jwe::alg::rsaes::RsaesJweAlgorithm,
) -> CustomResult<String, errors::EncryptionError> {
if let KeyIdCheck::RequestResponseKeyId((req_key_id, resp_key_id)) = key_ids {
utils::when(req_key_id.ne(resp_key_id), || {
Err(report!(errors::EncryptionError)
.attach_printable("key_id mismatch, Error authenticating response"))
})?;
}
let decrypter = alg
.decrypter_from_pem(private_key)
.change_context(errors::EncryptionError)
.attach_printable("Error getting JweDecryptor")?;
let (dst_payload, _dst_header) = jwe::deserialize_compact(jwt, &decrypter)
.change_context(errors::EncryptionError)
.attach_printable("Error getting Decrypted jwe")?;
String::from_utf8(dst_payload)
.change_context(errors::EncryptionError)
.attach_printable("Could not decode JWE payload from UTF-8")
}
pub async fn jws_sign_payload(
payload: &[u8],
kid: &str,
private_key: impl AsRef<[u8]>,
) -> CustomResult<String, errors::EncryptionError> {
let alg = jws::RS256;
let mut src_header = jws::JwsHeader::new();
src_header.set_key_id(kid);
let signer = alg
.signer_from_pem(private_key)
.change_context(errors::EncryptionError)
.attach_printable("Error getting signer")?;
let jwt = jws::serialize_compact(payload, &src_header, &signer)
.change_context(errors::EncryptionError)
.attach_printable("Error getting signed jwt string")?;
Ok(jwt)
}
pub fn verify_sign(
jws_body: String,
key: impl AsRef<[u8]>,
) -> CustomResult<String, errors::EncryptionError> {
let alg = jws::RS256;
let input = jws_body.as_bytes();
let verifier = alg
.verifier_from_pem(key)
.change_context(errors::EncryptionError)
.attach_printable("Error getting verifier")?;
let (dst_payload, _dst_header) = jws::deserialize_compact(input, &verifier)
.change_context(errors::EncryptionError)
.attach_printable("Error getting Decrypted jws")?;
let resp = String::from_utf8(dst_payload)
.change_context(errors::EncryptionError)
.attach_printable("Could not convert to UTF-8")?;
Ok(resp)
}
#[cfg(test)]
mod tests {
use super::*;
// Keys used for tests
// Can be generated using the following commands:
// `openssl genrsa -out private_key.pem 2048`
// `openssl rsa -in private_key.pem -pubout -out public_key.pem`
const ENCRYPTION_KEY: &str = "\
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwa6siKaSYqD1o4J3AbHq
Km8oVTvep7GoN/C45qY60C7DO72H1O7Ujt6ZsSiK83EyI0CaUg3ORPS3ayobFNmu
zR366ckK8GIf3BG7sVI6u/9751z4OvBHZMM9JFWa7Bx/RCPQ8aeM+iJoqf9auuQm
3NCTlfaZJif45pShswR+xuZTR/bqnsOSP/MFROI9ch0NE7KRogy0tvrZe21lP24i
Ro2LJJG+bYshxBddhxQf2ryJ85+/Trxdu16PunodGzCl6EMT3bvb4ZC41i15omqU
aXXV1Z1wYUhlsO0jyd1bVvjyuE/KE1TbBS0gfR/RkacODmmE2zEdZ0EyyiXwqkmc
oQIDAQAB
-----END PUBLIC KEY-----
";
const DECRYPTION_KEY: &str = "\
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAwa6siKaSYqD1o4J3AbHqKm8oVTvep7GoN/C45qY60C7DO72H
1O7Ujt6ZsSiK83EyI0CaUg3ORPS3ayobFNmuzR366ckK8GIf3BG7sVI6u/9751z4
OvBHZMM9JFWa7Bx/RCPQ8aeM+iJoqf9auuQm3NCTlfaZJif45pShswR+xuZTR/bq
nsOSP/MFROI9ch0NE7KRogy0tvrZe21lP24iRo2LJJG+bYshxBddhxQf2ryJ85+/
Trxdu16PunodGzCl6EMT3bvb4ZC41i15omqUaXXV1Z1wYUhlsO0jyd1bVvjyuE/K
E1TbBS0gfR/RkacODmmE2zEdZ0EyyiXwqkmcoQIDAQABAoIBAEavZwxgLmCMedl4
zdHyipF+C+w/c10kO05fLjwPQrujtWDiJOaTW0Pg/ZpoP33lO/UdqLR1kWgdH6ue
rE+Jun/lhyM3WiSsyw/X8PYgGotuDFw90+I+uu+NSY0vKOEu7UuC/siS66KGWEhi
h0xZ480G2jYKz43bXL1aVUEuTM5tsjtt0a/zm08DEluYwrmxaaTvHW2+8FOn3z8g
UMClV2mN9X3rwlRhKAI1RVlymV95LmkTgzA4wW/M4j0kk108ouY8bo9vowoqidpo
0zKGfnqbQCIZP1QY6Xj8f3fqMY7IrFDdFHCEBXs29DnRz4oS8gYCAUXDx5iEVa1R
KVxic5kCgYEA4vGWOANuv+RoxSnNQNnZjqHKjhd+9lXARnK6qVVXcJGTps72ILGJ
CNrS/L6ndBePQGhtLtVyrvtS3ZvYhsAzJeMeeFUSZhQ2SOP5SCFWRnLJIBObJ5/x
fFwrCbp38qsEBlqJXue4JQCOxqO4P6YYUmeE8fxLPmdVNWq5fNe2YtsCgYEA2nrl
iMfttvNfQGX4pB3yEh/eWwqq4InFQdmWVDYPKJFG4TtUKJ48vzQXJqKfCBZ2q387
bH4KaKNWD7rYz4NBfE6z6lUc8We9w1tjVaqs5omBKUuovz8/8miUtxf2W5T2ta1/
zl9NyQ57duO423PeaCgPKKz3ftaxlz8G1CKYMTMCgYEAqkR7YhchNpOWD6cnOeq4
kYzNvgHe3c7EbZaSeY1wByMR1mscura4i44yEjKwzCcI8Vfn4uV+H86sA1xz/dWi
CmD2cW3SWgf8GoAAfZ+VbVGdmJVdKUOVGKrGF4xxhf3NDT9MJYpQ3GIovNwE1qw1
P04vrqaNhYpdobAq7oGhc1UCgYAkimNzcgTHEYM/0Q453KxM7bmRvoH/1esA7XRg
Fz6HyWxyZSrZNEXysLKiipZQkvk8C6aTqazx/Ud6kASNCGXedYdPzPZvRauOTe2a
OVZ7pEnO71GE0v5N+8HLsZ1JieuNTTxP9s6aruplYwba5VEwWGrYob0vIJdJNYhd
2H9d0wKBgFzqGPvG8u1lVOLYDU9BjhA/3l00C97WHIG0Aal70PVyhFhm5ILNSHU1
Sau7H1Bhzy5G7rwt05LNpU6nFcAGVaZtzl4/+FYfYIulubYjuSEh72yuBHHyvi1/
4Zql8DXhF5kkKx75cMcIxZ/ceiRiQyjzYv3LoTTADHHjzsiBEiQY
-----END RSA PRIVATE KEY-----
";
const SIGNATURE_VERIFICATION_KEY: &str = "\
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA5Z/K0JWds8iHhWCa+rj0
rhOQX1nVs/ArQ1D0vh3UlSPR2vZUTrkdP7i3amv4d2XDC+3+5/YWExTkpxqnfl1T
9J37leN2guAARed6oYoTDEP/OoKtnUrKK2xk/+V5DNOWcRiSpcCrJOOIEoACOlPI
rXQSg16KDZQb0QTMntnsiPIJDbsOGcdKytRAcNaokiKLnia1v13N3bk6dSplrj1Y
zawslZfgqD0eov4FjzBMoA19yNtlVLLf6kOkLcFQjTKXJLP1tLflLUBPTg8fm9wg
APK2BjMQ2AMkUxx0ubbtw/9CeJ+bFWrqGnEhlvfDMlyAV77sAiIdQ4mXs3TLcLb/
AQIDAQAB
-----END PUBLIC KEY-----
";
const SIGNING_KEY: &str = "\
-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEA5Z/K0JWds8iHhWCa+rj0rhOQX1nVs/ArQ1D0vh3UlSPR2vZU
TrkdP7i3amv4d2XDC+3+5/YWExTkpxqnfl1T9J37leN2guAARed6oYoTDEP/OoKt
nUrKK2xk/+V5DNOWcRiSpcCrJOOIEoACOlPIrXQSg16KDZQb0QTMntnsiPIJDbsO
GcdKytRAcNaokiKLnia1v13N3bk6dSplrj1YzawslZfgqD0eov4FjzBMoA19yNtl
VLLf6kOkLcFQjTKXJLP1tLflLUBPTg8fm9wgAPK2BjMQ2AMkUxx0ubbtw/9CeJ+b
FWrqGnEhlvfDMlyAV77sAiIdQ4mXs3TLcLb/AQIDAQABAoIBAGNekD1N0e5AZG1S
zh6cNb6zVrH8xV9WGtLJ0PAJJrrXwnQYT4m10DOIM0+Jo/+/ePXLq5kkRI9DZmPu
Q/eKWc+tInfN9LZUS6n0r3wCrZWMQ4JFlO5RtEWwZdDbtFPZqOwObz/treKL2JHw
9YXaRijR50UUf3e61YLRqd9AfX0RNuuG8H+WgU3Gwuh5TwRnljM3JGaDPHsf7HLS
tNkqJuByp26FEbOLTokZDbHN0sy7/6hufxnIS9AK4vp8y9mZAjghG26Rbg/H71mp
Z+Q6P1y7xdgAKbhq7usG3/o4Y1e9wnghHvFS7DPwGekHQH2+LsYNEYOir1iRjXxH
GUXOhfUCgYEA+cR9jONQFco8Zp6z0wdGlBeYoUHVMjThQWEblWL2j4RG/qQd/y0j
uhVeU0/PmkYK2mgcjrh/pgDTtPymc+QuxBi+lexs89ppuJIAgMvLUiJT67SBHguP
l4+oL9U78KGh7PfJpMKH+Pk5yc1xucAevk0wWmr5Tz2vKRDavFTPV+MCgYEA61qg
Y7yN0cDtxtqlZdMC8BJPFCQ1+s3uB0wetAY3BEKjfYc2O/4sMbixXzt5PkZqZy96
QBUBxhcM/rIolpM3nrgN7h1nmJdk9ljCTjWoTJ6fDk8BUh8+0GrVhTbe7xZ+bFUN
UioIqvfapr/q/k7Ah2mCBE04wTZFry9fndrH2ssCgYEAh1T2Cj6oiAX6UEgxe2h3
z4oxgz6efAO3AavSPFFQ81Zi+VqHflpA/3TQlSerfxXwj4LV5mcFkzbjfy9eKXE7
/bjCm41tQ3vWyNEjQKYr1qcO/aniRBtThHWsVa6eObX6fOGN+p4E+txfeX693j3A
6q/8QSGxUERGAmRFgMIbTq0CgYAmuTeQkXKII4U75be3BDwEgg6u0rJq/L0ASF74
4djlg41g1wFuZ4if+bJ9Z8ywGWfiaGZl6s7q59oEgg25kKljHQd1uTLVYXuEKOB3
e86gJK0o7ojaGTf9lMZi779IeVv9uRTDAxWAA93e987TXuPAo/R3frkq2SIoC9Rg
paGidwKBgBqYd/iOJWsUZ8cWEhSE1Huu5rDEpjra8JPXHqQdILirxt1iCA5aEQou
BdDGaDr8sepJbGtjwTyiG8gEaX1DD+KsF2+dQRQdQfcYC40n8fKkvpFwrKjDj1ac
VuY3OeNxi+dC2r7HppP3O/MJ4gX/RJJfSrcaGP8/Ke1W5+jE97Qy
-----END RSA PRIVATE KEY-----
";
#[actix_rt::test]
async fn test_jwe() {
let jwt = encrypt_jwe(
"request_payload".as_bytes(),
ENCRYPTION_KEY,
EncryptionAlgorithm::A256GCM,
None,
)
.await
.unwrap();
let alg = jwe::RSA_OAEP_256;
let payload = decrypt_jwe(&jwt, KeyIdCheck::SkipKeyIdCheck, DECRYPTION_KEY, alg)
.await
.unwrap();
assert_eq!("request_payload".to_string(), payload)
}
#[actix_rt::test]
async fn test_jws() {
let jwt = jws_sign_payload("jws payload".as_bytes(), "1", SIGNING_KEY)
.await
.unwrap();
let payload = verify_sign(jwt, SIGNATURE_VERIFICATION_KEY).unwrap();
assert_eq!("jws payload".to_string(), payload)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/pm_auth.rs | crates/router/src/services/pm_auth.rs | use pm_auth::{
consts,
core::errors::ConnectorError,
types::{self as pm_auth_types, api::BoxedConnectorIntegration, PaymentAuthRouterData},
};
use crate::{
core::errors::{self},
logger,
routes::SessionState,
services::{self},
};
pub async fn execute_connector_processing_step<'b, T, Req, Resp>(
state: &'b SessionState,
connector_integration: BoxedConnectorIntegration<'_, T, Req, Resp>,
req: &'b PaymentAuthRouterData<T, Req, Resp>,
connector: &pm_auth_types::PaymentMethodAuthConnectors,
) -> errors::CustomResult<PaymentAuthRouterData<T, Req, Resp>, ConnectorError>
where
T: Clone + 'static,
Req: Clone + 'static,
Resp: Clone + 'static,
{
let mut router_data = req.clone();
let connector_request = connector_integration.build_request(req, connector)?;
match connector_request {
Some(request) => {
logger::debug!(connector_request=?request);
let response = services::api::call_connector_api(
state,
request,
"execute_connector_processing_step",
)
.await;
logger::debug!(connector_response=?response);
match response {
Ok(body) => {
let response = match body {
Ok(body) => {
let body = pm_auth_types::Response {
headers: body.headers,
response: body.response,
status_code: body.status_code,
};
let connector_http_status_code = Some(body.status_code);
let mut data =
connector_integration.handle_response(&router_data, body)?;
data.connector_http_status_code = connector_http_status_code;
data
}
Err(body) => {
let body = pm_auth_types::Response {
headers: body.headers,
response: body.response,
status_code: body.status_code,
};
router_data.connector_http_status_code = Some(body.status_code);
let error = match body.status_code {
500..=511 => connector_integration.get_5xx_error_response(body)?,
_ => connector_integration.get_error_response(body)?,
};
router_data.response = Err(error);
router_data
}
};
Ok(response)
}
Err(error) => {
if error.current_context().is_upstream_timeout() {
let error_response = pm_auth_types::ErrorResponse {
code: consts::REQUEST_TIMEOUT_ERROR_CODE.to_string(),
message: consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string(),
reason: Some(consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string()),
status_code: 504,
};
router_data.response = Err(error_response);
router_data.connector_http_status_code = Some(504);
Ok(router_data)
} else {
Err(error.change_context(ConnectorError::ProcessingStepFailed(None)))
}
}
}
}
None => Ok(router_data),
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/card_testing_guard.rs | crates/router/src/services/card_testing_guard.rs | use std::sync::Arc;
use error_stack::ResultExt;
use redis_interface::RedisConnectionPool;
use crate::{
core::errors::{ApiErrorResponse, RouterResult},
routes::app::SessionStateInfo,
};
fn get_redis_connection<A: SessionStateInfo>(state: &A) -> RouterResult<Arc<RedisConnectionPool>> {
state
.store()
.get_redis_conn()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")
}
pub async fn set_blocked_count_in_cache<A>(
state: &A,
cache_key: &str,
value: i32,
expiry: i64,
) -> RouterResult<()>
where
A: SessionStateInfo + Sync,
{
let redis_conn = get_redis_connection(state)?;
redis_conn
.set_key_with_expiry(&cache_key.into(), value, expiry)
.await
.change_context(ApiErrorResponse::InternalServerError)
}
pub async fn get_blocked_count_from_cache<A>(
state: &A,
cache_key: &str,
) -> RouterResult<Option<i32>>
where
A: SessionStateInfo + Sync,
{
let redis_conn = get_redis_connection(state)?;
let value: Option<i32> = redis_conn
.get_key(&cache_key.into())
.await
.change_context(ApiErrorResponse::InternalServerError)?;
Ok(value)
}
pub async fn increment_blocked_count_in_cache<A>(
state: &A,
cache_key: &str,
expiry: i64,
) -> RouterResult<()>
where
A: SessionStateInfo + Sync,
{
let redis_conn = get_redis_connection(state)?;
let value: Option<i32> = redis_conn
.get_key(&cache_key.into())
.await
.change_context(ApiErrorResponse::InternalServerError)?;
let mut incremented_blocked_count: i32 = 1;
if let Some(actual_value) = value {
incremented_blocked_count = actual_value + 1;
}
redis_conn
.set_key_with_expiry(&cache_key.into(), incremented_blocked_count, expiry)
.await
.change_context(ApiErrorResponse::InternalServerError)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/api.rs | crates/router/src/services/api.rs | pub mod client;
pub mod generic_link_response;
pub mod request;
use std::{
collections::{HashMap, HashSet},
fmt::Debug,
future::Future,
str,
sync::Arc,
time::{Duration, Instant},
};
use actix_http::header::HeaderMap;
use actix_web::{
body,
http::header::{HeaderName, HeaderValue},
web, FromRequest, HttpRequest, HttpResponse, Responder, ResponseError,
};
pub use client::{ApiClient, MockApiClient, ProxyClient};
pub use common_enums::enums::PaymentAction;
pub use common_utils::request::{ContentType, Method, Request, RequestBuilder};
use common_utils::{
consts::{DEFAULT_TENANT, TENANT_HEADER, X_HS_LATENCY},
errors::{ErrorSwitch, ReportSwitchExt},
};
use error_stack::{Report, ResultExt};
use hyperswitch_domain_models::router_data_v2::flow_common_types as common_types;
pub use hyperswitch_domain_models::{
api::{
ApplicationResponse, GenericExpiredLinkData, GenericLinkFormData, GenericLinkStatusData,
GenericLinks, PaymentLinkAction, RedirectionFormData,
},
payment_method_data::PaymentMethodData,
router_response_types::RedirectForm,
};
pub use hyperswitch_interfaces::{
api::{
BoxedConnectorIntegration, CaptureSyncMethod, ConnectorIntegration,
ConnectorIntegrationAny, ConnectorRedirectResponse, ConnectorSpecifications,
ConnectorValidation,
},
api_client::{
call_connector_api, execute_connector_processing_step, handle_response,
store_raw_connector_response_if_required,
},
connector_integration_v2::{
BoxedConnectorIntegrationV2, ConnectorIntegrationAnyV2, ConnectorIntegrationV2,
},
};
use masking::{Maskable, PeekInterface};
pub use payment_link::{PaymentLinkFormData, PaymentLinkStatusData};
use router_env::{instrument, tracing, RequestId, Tag};
use serde::Serialize;
use super::{
authentication::AuthenticateAndFetch,
connector_integration_interface::BoxedConnectorIntegrationInterface,
};
use crate::{
configs::Settings,
core::{
api_locking,
errors::{self, CustomResult},
},
events::api_logs::{ApiEvent, ApiEventMetric, ApiEventsType},
headers, logger,
routes::{
app::{AppStateInfo, ReqState, SessionStateInfo},
metrics, AppState, SessionState,
},
services::generic_link_response::build_generic_link_html,
types::api,
utils,
};
pub type BoxedPaymentConnectorIntegrationInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::PaymentFlowData, Req, Resp>;
pub type BoxedRefundConnectorIntegrationInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::RefundFlowData, Req, Resp>;
#[cfg(feature = "frm")]
pub type BoxedFrmConnectorIntegrationInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::FrmFlowData, Req, Resp>;
pub type BoxedDisputeConnectorIntegrationInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::DisputesFlowData, Req, Resp>;
pub type BoxedMandateRevokeConnectorIntegrationInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::MandateRevokeFlowData, Req, Resp>;
#[cfg(feature = "payouts")]
pub type BoxedPayoutConnectorIntegrationInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::PayoutFlowData, Req, Resp>;
pub type BoxedWebhookSourceVerificationConnectorIntegrationInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::WebhookSourceVerifyData, Req, Resp>;
pub type BoxedExternalAuthenticationConnectorIntegrationInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::ExternalAuthenticationFlowData, Req, Resp>;
pub type BoxedAuthenticationTokenConnectorIntegrationInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::AuthenticationTokenFlowData, Req, Resp>;
pub type BoxedAccessTokenConnectorIntegrationInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::AccessTokenFlowData, Req, Resp>;
pub type BoxedFilesConnectorIntegrationInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::FilesFlowData, Req, Resp>;
pub type BoxedRevenueRecoveryRecordBackInterface<T, Req, Res> =
BoxedConnectorIntegrationInterface<T, common_types::InvoiceRecordBackData, Req, Res>;
pub type BoxedGetSubscriptionPlansInterface<T, Req, Res> =
BoxedConnectorIntegrationInterface<T, common_types::GetSubscriptionItemsData, Req, Res>;
pub type BoxedGetSubscriptionPlanPricesInterface<T, Req, Res> =
BoxedConnectorIntegrationInterface<T, common_types::GetSubscriptionItemPricesData, Req, Res>;
pub type BoxedGetSubscriptionEstimateInterface<T, Req, Res> =
BoxedConnectorIntegrationInterface<T, common_types::GetSubscriptionEstimateData, Req, Res>;
pub type BoxedSubscriptionPauseInterface<T, Req, Res> =
BoxedConnectorIntegrationInterface<T, common_types::SubscriptionPauseData, Req, Res>;
pub type BoxedSubscriptionResumeInterface<T, Req, Res> =
BoxedConnectorIntegrationInterface<T, common_types::SubscriptionResumeData, Req, Res>;
pub type BoxedSubscriptionCancelInterface<T, Req, Res> =
BoxedConnectorIntegrationInterface<T, common_types::SubscriptionCancelData, Req, Res>;
pub type BoxedBillingConnectorInvoiceSyncIntegrationInterface<T, Req, Res> =
BoxedConnectorIntegrationInterface<
T,
common_types::BillingConnectorInvoiceSyncFlowData,
Req,
Res,
>;
pub type BoxedUnifiedAuthenticationServiceInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::UasFlowData, Req, Resp>;
pub type BoxedBillingConnectorPaymentsSyncIntegrationInterface<T, Req, Res> =
BoxedConnectorIntegrationInterface<
T,
common_types::BillingConnectorPaymentsSyncFlowData,
Req,
Res,
>;
pub type BoxedVaultConnectorIntegrationInterface<T, Req, Res> =
BoxedConnectorIntegrationInterface<T, common_types::VaultConnectorFlowData, Req, Res>;
pub type BoxedGiftCardBalanceCheckIntegrationInterface<T, Req, Res> =
BoxedConnectorIntegrationInterface<T, common_types::GiftCardBalanceCheckFlowData, Req, Res>;
pub type BoxedSubscriptionConnectorIntegrationInterface<T, Req, Res> =
BoxedConnectorIntegrationInterface<T, common_types::SubscriptionCreateData, Req, Res>;
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct ApplicationRedirectResponse {
pub url: String,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum AuthFlow {
Client,
Merchant,
}
#[allow(clippy::too_many_arguments)]
#[instrument(
skip(request, payload, state, func, api_auth, incoming_request_header),
fields(merchant_id)
)]
pub async fn server_wrap_util<'a, 'b, U, T, Q, F, Fut, E, OErr>(
flow: &'a impl router_env::types::FlowMetric,
state: web::Data<AppState>,
incoming_request_header: &HeaderMap,
request: &'a HttpRequest,
payload: T,
func: F,
api_auth: &dyn AuthenticateAndFetch<U, SessionState>,
lock_action: api_locking::LockAction,
) -> CustomResult<ApplicationResponse<Q>, OErr>
where
F: Fn(SessionState, U, T, ReqState) -> Fut,
'b: 'a,
Fut: Future<Output = CustomResult<ApplicationResponse<Q>, E>>,
Q: Serialize + Debug + 'a + ApiEventMetric,
T: Debug + Serialize + ApiEventMetric,
E: ErrorSwitch<OErr> + error_stack::Context,
OErr: ResponseError + error_stack::Context + Serialize,
errors::ApiErrorResponse: ErrorSwitch<OErr>,
{
let request_id = RequestId::extract(request)
.await
.attach_printable("Unable to extract request id from request")
.change_context(errors::ApiErrorResponse::InternalServerError.switch())?;
let mut app_state = state.get_ref().clone();
let start_instant = Instant::now();
let serialized_request = masking::masked_serialize(&payload)
.attach_printable("Failed to serialize json request")
.change_context(errors::ApiErrorResponse::InternalServerError.switch())?;
let mut event_type = payload.get_api_event_type();
let tenant_id = if !state.conf.multitenancy.enabled {
common_utils::id_type::TenantId::try_from_string(DEFAULT_TENANT.to_owned())
.attach_printable("Unable to get default tenant id")
.change_context(errors::ApiErrorResponse::InternalServerError.switch())?
} else {
let request_tenant_id = incoming_request_header
.get(TENANT_HEADER)
.and_then(|value| value.to_str().ok())
.ok_or_else(|| errors::ApiErrorResponse::MissingTenantId.switch())
.and_then(|header_value| {
common_utils::id_type::TenantId::try_from_string(header_value.to_string()).map_err(
|_| {
errors::ApiErrorResponse::InvalidRequestData {
message: format!("`{}` header is invalid", headers::X_TENANT_ID),
}
.switch()
},
)
})?;
state
.conf
.multitenancy
.get_tenant(&request_tenant_id)
.map(|tenant| tenant.tenant_id.clone())
.ok_or(
errors::ApiErrorResponse::InvalidTenant {
tenant_id: request_tenant_id.get_string_repr().to_string(),
}
.switch(),
)?
};
let locale = utils::get_locale_from_header(&incoming_request_header.clone());
let mut session_state =
Arc::new(app_state.clone()).get_session_state(&tenant_id, Some(locale), || {
errors::ApiErrorResponse::InvalidTenant {
tenant_id: tenant_id.get_string_repr().to_string(),
}
.switch()
})?;
session_state.add_request_id(request_id.clone());
let mut request_state = session_state.get_req_state();
request_state.event_context.record_info(request_id.clone());
request_state
.event_context
.record_info(("flow".to_string(), flow.to_string()));
request_state.event_context.record_info((
"tenant_id".to_string(),
tenant_id.get_string_repr().to_string(),
));
// Currently auth failures are not recorded as API events
let (auth_out, auth_type) = api_auth
.authenticate_and_fetch(request.headers(), &session_state)
.await
.switch()?;
request_state.event_context.record_info(auth_type.clone());
let merchant_id = auth_type
.get_merchant_id()
.cloned()
.unwrap_or(common_utils::id_type::MerchantId::get_merchant_id_not_found());
app_state.add_flow_name(flow.to_string());
tracing::Span::current().record("merchant_id", merchant_id.get_string_repr().to_owned());
let output = {
lock_action
.clone()
.perform_locking_action(&session_state, merchant_id.to_owned())
.await
.switch()?;
let res = func(session_state.clone(), auth_out, payload, request_state)
.await
.switch();
lock_action
.free_lock_action(&session_state, merchant_id.to_owned())
.await
.switch()?;
res
};
let request_duration = Instant::now()
.saturating_duration_since(start_instant)
.as_millis();
let mut serialized_response = None;
let mut error = None;
let mut overhead_latency = None;
let status_code = match output.as_ref() {
Ok(res) => {
let mut extracted_status_code: Option<http::StatusCode> = None;
if let ApplicationResponse::Json(data) = res {
serialized_response.replace(
masking::masked_serialize(&data)
.attach_printable("Failed to serialize json response")
.change_context(errors::ApiErrorResponse::InternalServerError.switch())?,
);
} else if let ApplicationResponse::JsonWithHeaders((data, headers)) = res {
serialized_response.replace(
masking::masked_serialize(&data)
.attach_printable("Failed to serialize json response")
.change_context(errors::ApiErrorResponse::InternalServerError.switch())?,
);
if let Some((_, value)) = headers.iter().find(|(key, _)| key == X_HS_LATENCY) {
if let Ok(external_latency) = value.clone().into_inner().parse::<u128>() {
overhead_latency.replace(external_latency);
}
}
// Extract connector HTTP status code for ApiEvent logging
extracted_status_code = state
.conf
.proxy_status_mapping
.extract_connector_http_status_code(headers);
}
event_type = res.get_api_event_type().or(event_type);
// Use extracted status code if available, otherwise fall back to default
extracted_status_code
.map(|code| code.as_u16().into())
.unwrap_or_else(|| metrics::request::track_response_status_code(res))
}
Err(err) => {
error.replace(
serde_json::to_value(err.current_context())
.attach_printable("Failed to serialize json response")
.change_context(errors::ApiErrorResponse::InternalServerError.switch())
.ok()
.into(),
);
err.current_context().status_code().as_u16().into()
}
};
let values: Vec<&serde_json::Value> = [Some(&serialized_request), serialized_response.as_ref()]
.into_iter()
.flatten()
.collect();
let infra = extract_mapped_fields(
&values,
state.enhancement.as_ref(),
state.infra_components.as_ref(),
);
let api_event = ApiEvent::new(
tenant_id,
Some(merchant_id.clone()),
flow,
&request_id,
request_duration,
status_code,
serialized_request,
serialized_response,
overhead_latency,
auth_type,
error,
event_type.unwrap_or(ApiEventsType::Miscellaneous),
request,
request.method(),
infra.clone(),
);
state.event_handler().log_event(&api_event);
output
}
#[instrument(
skip(request, state, func, api_auth, payload),
fields(request_method, request_url_path, status_code)
)]
pub async fn server_wrap<'a, T, U, Q, F, Fut, E>(
flow: impl router_env::types::FlowMetric,
state: web::Data<AppState>,
request: &'a HttpRequest,
payload: T,
func: F,
api_auth: &dyn AuthenticateAndFetch<U, SessionState>,
lock_action: api_locking::LockAction,
) -> HttpResponse
where
F: Fn(SessionState, U, T, ReqState) -> Fut,
Fut: Future<Output = CustomResult<ApplicationResponse<Q>, E>>,
Q: Serialize + Debug + ApiEventMetric + 'a,
T: Debug + Serialize + ApiEventMetric,
ApplicationResponse<Q>: Debug,
E: ErrorSwitch<api_models::errors::types::ApiErrorResponse> + error_stack::Context,
{
let request_method = request.method().as_str();
let url_path = request.path();
let unmasked_incoming_header_keys = state.conf().unmasked_headers.keys;
let incoming_request_header = request.headers();
let incoming_header_to_log: HashMap<String, HeaderValue> =
incoming_request_header
.iter()
.fold(HashMap::new(), |mut acc, (key, value)| {
let key = key.to_string();
if unmasked_incoming_header_keys.contains(&key.as_str().to_lowercase()) {
acc.insert(key.clone(), value.clone());
} else {
acc.insert(key.clone(), HeaderValue::from_static("**MASKED**"));
}
acc
});
tracing::Span::current().record("request_method", request_method);
tracing::Span::current().record("request_url_path", url_path);
let start_instant = Instant::now();
logger::info!(
tag = ?Tag::BeginRequest, payload = ?payload,
headers = ?incoming_header_to_log);
let server_wrap_util_res = server_wrap_util(
&flow,
state.clone(),
incoming_request_header,
request,
payload,
func,
api_auth,
lock_action,
)
.await
.map(|response| {
logger::info!(api_response =? response);
response
});
let res = match server_wrap_util_res {
Ok(ApplicationResponse::Json(response)) => match serde_json::to_string(&response) {
Ok(res) => http_response_json(res),
Err(_) => http_response_err(
r#"{
"error": {
"message": "Error serializing response from connector"
}
}"#,
),
},
Ok(ApplicationResponse::StatusOk) => http_response_ok(),
Ok(ApplicationResponse::TextPlain(text)) => http_response_plaintext(text),
Ok(ApplicationResponse::FileData((file_data, content_type))) => {
http_response_file_data(file_data, content_type)
}
Ok(ApplicationResponse::JsonForRedirection(response)) => {
match serde_json::to_string(&response) {
Ok(res) => http_redirect_response(res, response),
Err(_) => http_response_err(
r#"{
"error": {
"message": "Error serializing response from connector"
}
}"#,
),
}
}
Ok(ApplicationResponse::Form(redirection_data)) => {
let config = state.conf();
build_redirection_form(
&redirection_data.redirect_form,
redirection_data.payment_method_data,
redirection_data.amount,
redirection_data.currency,
config,
)
.respond_to(request)
.map_into_boxed_body()
}
Ok(ApplicationResponse::GenericLinkForm(boxed_generic_link_data)) => {
let link_type = boxed_generic_link_data.data.to_string();
match build_generic_link_html(
boxed_generic_link_data.data,
boxed_generic_link_data.locale,
) {
Ok(rendered_html) => {
let headers = if !boxed_generic_link_data.allowed_domains.is_empty() {
let domains_str = boxed_generic_link_data
.allowed_domains
.into_iter()
.collect::<Vec<String>>()
.join(" ");
let csp_header = format!("frame-ancestors 'self' {domains_str};");
Some(HashSet::from([("content-security-policy", csp_header)]))
} else {
None
};
http_response_html_data(rendered_html, headers)
}
Err(_) => http_response_err(format!("Error while rendering {link_type} HTML page")),
}
}
Ok(ApplicationResponse::PaymentLinkForm(boxed_payment_link_data)) => {
match *boxed_payment_link_data {
PaymentLinkAction::PaymentLinkFormData(payment_link_data) => {
match build_payment_link_html(payment_link_data) {
Ok(rendered_html) => http_response_html_data(rendered_html, None),
Err(_) => http_response_err(
r#"{
"error": {
"message": "Error while rendering payment link html page"
}
}"#,
),
}
}
PaymentLinkAction::PaymentLinkStatus(payment_link_data) => {
match get_payment_link_status(payment_link_data) {
Ok(rendered_html) => http_response_html_data(rendered_html, None),
Err(_) => http_response_err(
r#"{
"error": {
"message": "Error while rendering payment link status page"
}
}"#,
),
}
}
}
}
Ok(ApplicationResponse::JsonWithHeaders((response, headers))) => {
let request_elapsed_time = request.headers().get(X_HS_LATENCY).and_then(|value| {
if value == "true" {
Some(start_instant.elapsed())
} else {
None
}
});
let proxy_connector_http_status_code = state
.conf
.proxy_status_mapping
.extract_connector_http_status_code(&headers);
match serde_json::to_string(&response) {
Ok(res) => http_response_json_with_headers(
res,
headers,
request_elapsed_time,
proxy_connector_http_status_code,
),
Err(_) => http_response_err(
r#"{
"error": {
"message": "Error serializing response from connector"
}
}"#,
),
}
}
Err(error) => log_and_return_error_response(error),
};
let response_code = res.status().as_u16();
tracing::Span::current().record("status_code", response_code);
let end_instant = Instant::now();
let request_duration = end_instant.saturating_duration_since(start_instant);
logger::info!(
tag = ?Tag::EndRequest,
time_taken_ms = request_duration.as_millis(),
);
res
}
pub fn log_and_return_error_response<T>(error: Report<T>) -> HttpResponse
where
T: error_stack::Context + Clone + ResponseError,
{
logger::error!(?error);
HttpResponse::from_error(error.current_context().clone())
}
pub fn http_response_json<T: body::MessageBody + 'static>(response: T) -> HttpResponse {
HttpResponse::Ok()
.content_type(mime::APPLICATION_JSON)
.body(response)
}
pub fn http_server_error_json_response<T: body::MessageBody + 'static>(
response: T,
) -> HttpResponse {
HttpResponse::InternalServerError()
.content_type(mime::APPLICATION_JSON)
.body(response)
}
pub fn http_response_json_with_headers<T: body::MessageBody + 'static>(
response: T,
headers: Vec<(String, Maskable<String>)>,
request_duration: Option<Duration>,
status_code: Option<http::StatusCode>,
) -> HttpResponse {
let mut response_builder = HttpResponse::build(status_code.unwrap_or(http::StatusCode::OK));
for (header_name, header_value) in headers {
let is_sensitive_header = header_value.is_masked();
let mut header_value = header_value.into_inner();
if header_name == X_HS_LATENCY {
if let Some(request_duration) = request_duration {
if let Ok(external_latency) = header_value.parse::<u128>() {
let updated_duration = request_duration.as_millis() - external_latency;
header_value = updated_duration.to_string();
}
}
}
let mut header_value = match HeaderValue::from_str(header_value.as_str()) {
Ok(header_value) => header_value,
Err(error) => {
logger::error!(?error);
return http_server_error_json_response("Something Went Wrong");
}
};
if is_sensitive_header {
header_value.set_sensitive(true);
}
response_builder.append_header((header_name, header_value));
}
response_builder
.content_type(mime::APPLICATION_JSON)
.body(response)
}
pub fn http_response_plaintext<T: body::MessageBody + 'static>(res: T) -> HttpResponse {
HttpResponse::Ok().content_type(mime::TEXT_PLAIN).body(res)
}
pub fn http_response_file_data<T: body::MessageBody + 'static>(
res: T,
content_type: mime::Mime,
) -> HttpResponse {
HttpResponse::Ok().content_type(content_type).body(res)
}
pub fn http_response_html_data<T: body::MessageBody + 'static>(
res: T,
optional_headers: Option<HashSet<(&'static str, String)>>,
) -> HttpResponse {
let mut res_builder = HttpResponse::Ok();
res_builder.content_type(mime::TEXT_HTML);
if let Some(headers) = optional_headers {
for (key, value) in headers {
if let Ok(header_val) = HeaderValue::try_from(value) {
res_builder.insert_header((HeaderName::from_static(key), header_val));
}
}
}
res_builder.body(res)
}
pub fn http_response_ok() -> HttpResponse {
HttpResponse::Ok().finish()
}
pub fn http_redirect_response<T: body::MessageBody + 'static>(
response: T,
redirection_response: api::RedirectionResponse,
) -> HttpResponse {
HttpResponse::Ok()
.content_type(mime::APPLICATION_JSON)
.append_header((
"Location",
redirection_response.return_url_with_query_params,
))
.status(http::StatusCode::FOUND)
.body(response)
}
pub fn http_response_err<T: body::MessageBody + 'static>(response: T) -> HttpResponse {
HttpResponse::BadRequest()
.content_type(mime::APPLICATION_JSON)
.body(response)
}
pub trait Authenticate {
fn get_client_secret(&self) -> Option<&String> {
None
}
fn should_return_raw_response(&self) -> Option<bool> {
None
}
fn is_external_three_ds_data_passed_by_merchant(&self) -> bool {
false
}
}
#[cfg(feature = "v2")]
impl Authenticate for api_models::payments::PaymentsConfirmIntentRequest {
fn should_return_raw_response(&self) -> Option<bool> {
self.return_raw_connector_response
}
}
#[cfg(feature = "v2")]
impl Authenticate for api_models::payments::ProxyPaymentsRequest {}
#[cfg(feature = "v2")]
impl Authenticate for api_models::payments::ExternalVaultProxyPaymentsRequest {}
#[cfg(feature = "v1")]
impl Authenticate for api_models::payments::PaymentsRequest {
fn get_client_secret(&self) -> Option<&String> {
self.client_secret.as_ref()
}
fn should_return_raw_response(&self) -> Option<bool> {
// In v1, this maps to `all_keys_required` to retain backward compatibility.
// The equivalent field in v2 is `return_raw_connector_response`.
self.all_keys_required
}
fn is_external_three_ds_data_passed_by_merchant(&self) -> bool {
self.three_ds_data.is_some()
}
}
#[cfg(feature = "v1")]
impl Authenticate for api_models::payment_methods::PaymentMethodListRequest {
fn get_client_secret(&self) -> Option<&String> {
self.client_secret.as_ref()
}
}
#[cfg(feature = "v1")]
impl Authenticate for api_models::payments::PaymentsSessionRequest {
fn get_client_secret(&self) -> Option<&String> {
Some(&self.client_secret)
}
}
impl Authenticate for api_models::payments::PaymentsDynamicTaxCalculationRequest {
fn get_client_secret(&self) -> Option<&String> {
Some(self.client_secret.peek())
}
}
impl Authenticate for api_models::payments::PaymentsPostSessionTokensRequest {
fn get_client_secret(&self) -> Option<&String> {
Some(self.client_secret.peek())
}
}
impl Authenticate for api_models::payments::PaymentsUpdateMetadataRequest {}
impl Authenticate for api_models::payments::PaymentsRetrieveRequest {
#[cfg(feature = "v2")]
fn should_return_raw_response(&self) -> Option<bool> {
self.return_raw_connector_response
}
#[cfg(feature = "v1")]
fn should_return_raw_response(&self) -> Option<bool> {
// In v1, this maps to `all_keys_required` to retain backward compatibility.
// The equivalent field in v2 is `return_raw_connector_response`.
self.all_keys_required
}
}
impl Authenticate for api_models::payments::PaymentsCancelRequest {}
impl Authenticate for api_models::payments::PaymentsCancelPostCaptureRequest {}
impl Authenticate for api_models::payments::PaymentsCaptureRequest {
#[cfg(feature = "v2")]
fn should_return_raw_response(&self) -> Option<bool> {
self.return_raw_connector_response
}
#[cfg(feature = "v1")]
fn should_return_raw_response(&self) -> Option<bool> {
// In v1, this maps to `all_keys_required` to retain backward compatibility.
// The equivalent field in v2 is `return_raw_connector_response`.
self.all_keys_required
}
}
impl Authenticate for api_models::payments::PaymentsIncrementalAuthorizationRequest {}
impl Authenticate for api_models::payments::PaymentsExtendAuthorizationRequest {}
impl Authenticate for api_models::payments::PaymentsStartRequest {}
// impl Authenticate for api_models::payments::PaymentsApproveRequest {}
impl Authenticate for api_models::payments::PaymentsRejectRequest {}
// #[cfg(feature = "v2")]
// impl Authenticate for api_models::payments::PaymentsIntentResponse {}
pub fn build_redirection_form(
form: &RedirectForm,
payment_method_data: Option<PaymentMethodData>,
amount: String,
currency: String,
config: Settings,
) -> maud::Markup {
use maud::PreEscaped;
let logging_template =
include_str!("redirection/assets/redirect_error_logs_push.js").to_string();
match form {
RedirectForm::Form {
endpoint,
method,
form_fields,
} => maud::html! {
(maud::DOCTYPE)
html {
meta name="viewport" content="width=device-width, initial-scale=1";
head {
style {
r##"
"##
}
(PreEscaped(r##"
<style>
#loader1 {
width: 500px,
}
@media (max-width: 600px) {
#loader1 {
width: 200px
}
}
</style>
"##))
}
body style="background-color: #ffffff; padding: 20px; font-family: Arial, Helvetica, Sans-Serif;" {
div id="loader1" class="lottie" style="height: 150px; display: block; position: relative; margin-left: auto; margin-right: auto;" { "" }
(PreEscaped(r#"<script src="https://cdnjs.cloudflare.com/ajax/libs/bodymovin/5.7.4/lottie.min.js"></script>"#))
(PreEscaped(r#"
<script>
var anime = bodymovin.loadAnimation({
container: document.getElementById('loader1'),
renderer: 'svg',
loop: true,
autoplay: true,
name: 'hyperswitch loader',
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/openidconnect.rs | crates/router/src/services/openidconnect.rs | use common_utils::errors::ErrorSwitch;
use error_stack::ResultExt;
use external_services::http_client::client;
use masking::{ExposeInterface, Secret};
use oidc::TokenResponse;
use openidconnect::{self as oidc, core as oidc_core};
use redis_interface::RedisConnectionPool;
use storage_impl::errors::ApiClientError;
use crate::{
consts,
core::errors::{UserErrors, UserResult},
routes::SessionState,
types::domain::user::UserEmail,
};
pub async fn get_authorization_url(
state: SessionState,
redirect_url: String,
redirect_state: Secret<String>,
base_url: Secret<String>,
client_id: Secret<String>,
) -> UserResult<url::Url> {
let discovery_document = get_discovery_document(base_url, &state).await?;
let (auth_url, csrf_token, nonce) =
get_oidc_core_client(discovery_document, client_id, None, redirect_url)?
.authorize_url(
oidc_core::CoreAuthenticationFlow::AuthorizationCode,
|| oidc::CsrfToken::new(redirect_state.expose()),
oidc::Nonce::new_random,
)
.add_scope(oidc::Scope::new("email".to_string()))
.url();
// Save csrf & nonce as key value respectively
let key = get_oidc_redis_key(csrf_token.secret());
get_redis_connection_for_global_tenant(&state)?
.set_key_with_expiry(&key.into(), nonce.secret(), consts::user::REDIS_SSO_TTL)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to save csrf-nonce in redis")?;
Ok(auth_url)
}
pub async fn get_user_email_from_oidc_provider(
state: &SessionState,
redirect_url: String,
redirect_state: Secret<String>,
base_url: Secret<String>,
client_id: Secret<String>,
authorization_code: Secret<String>,
client_secret: Secret<String>,
) -> UserResult<UserEmail> {
let nonce = get_nonce_from_redis(state, &redirect_state).await?;
let discovery_document = get_discovery_document(base_url, state).await?;
let client = get_oidc_core_client(
discovery_document,
client_id,
Some(client_secret),
redirect_url,
)?;
let nonce_clone = nonce.clone();
client
.authorize_url(
oidc_core::CoreAuthenticationFlow::AuthorizationCode,
|| oidc::CsrfToken::new(redirect_state.expose()),
|| nonce_clone,
)
.add_scope(oidc::Scope::new("email".to_string()));
// Send request to OpenId provider with authorization code
let token_response = client
.exchange_code(oidc::AuthorizationCode::new(authorization_code.expose()))
.request_async(|req| get_oidc_reqwest_client(state, req))
.await
.map_err(|e| match e {
oidc::RequestTokenError::ServerResponse(resp)
if resp.error() == &oidc_core::CoreErrorResponseType::InvalidGrant =>
{
UserErrors::SSOFailed
}
_ => UserErrors::InternalServerError,
})
.attach_printable("Failed to exchange code and fetch oidc token")?;
// Fetch id token from response
let id_token = token_response
.id_token()
.ok_or(UserErrors::InternalServerError)
.attach_printable("Id Token not provided in token response")?;
// Verify id token
let id_token_claims = id_token
.claims(&client.id_token_verifier(), &nonce)
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to verify id token")?;
// Get email from token
let email_from_token = id_token_claims
.email()
.map(|email| email.to_string())
.ok_or(UserErrors::InternalServerError)
.attach_printable("OpenID Provider Didnt provide email")?;
UserEmail::new(Secret::new(email_from_token))
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to create email type")
}
// TODO: Cache Discovery Document
async fn get_discovery_document(
base_url: Secret<String>,
state: &SessionState,
) -> UserResult<oidc_core::CoreProviderMetadata> {
let issuer_url =
oidc::IssuerUrl::new(base_url.expose()).change_context(UserErrors::InternalServerError)?;
oidc_core::CoreProviderMetadata::discover_async(issuer_url, |req| {
get_oidc_reqwest_client(state, req)
})
.await
.change_context(UserErrors::InternalServerError)
}
fn get_oidc_core_client(
discovery_document: oidc_core::CoreProviderMetadata,
client_id: Secret<String>,
client_secret: Option<Secret<String>>,
redirect_url: String,
) -> UserResult<oidc_core::CoreClient> {
let client_id = oidc::ClientId::new(client_id.expose());
let client_secret = client_secret.map(|secret| oidc::ClientSecret::new(secret.expose()));
let redirect_url = oidc::RedirectUrl::new(redirect_url)
.change_context(UserErrors::InternalServerError)
.attach_printable("Error creating redirect URL type")?;
Ok(
oidc_core::CoreClient::from_provider_metadata(discovery_document, client_id, client_secret)
.set_redirect_uri(redirect_url),
)
}
async fn get_nonce_from_redis(
state: &SessionState,
redirect_state: &Secret<String>,
) -> UserResult<oidc::Nonce> {
let redis_connection = get_redis_connection_for_global_tenant(state)?;
let redirect_state = redirect_state.clone().expose();
let key = get_oidc_redis_key(&redirect_state);
redis_connection
.get_key::<Option<String>>(&key.into())
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Error Fetching CSRF from redis")?
.map(oidc::Nonce::new)
.ok_or(UserErrors::SSOFailed)
.attach_printable("Cannot find csrf in redis. Csrf invalid or expired")
}
async fn get_oidc_reqwest_client(
state: &SessionState,
request: oidc::HttpRequest,
) -> Result<oidc::HttpResponse, ApiClientError> {
let client = client::create_client(&state.conf.proxy, None, None, None)
.map_err(|e| e.current_context().switch())?;
let mut request_builder = client
.request(request.method, request.url)
.body(request.body);
for (name, value) in &request.headers {
request_builder = request_builder.header(name.as_str(), value.as_bytes());
}
let request = request_builder
.build()
.map_err(|_| ApiClientError::ClientConstructionFailed)?;
let response = client
.execute(request)
.await
.map_err(|_| ApiClientError::RequestNotSent("OpenIDConnect".to_string()))?;
Ok(oidc::HttpResponse {
status_code: response.status(),
headers: response.headers().to_owned(),
body: response
.bytes()
.await
.map_err(|_| ApiClientError::ResponseDecodingFailed)?
.to_vec(),
})
}
fn get_oidc_redis_key(csrf: &str) -> String {
format!("{}OIDC_{}", consts::user::REDIS_SSO_PREFIX, csrf)
}
fn get_redis_connection_for_global_tenant(
state: &SessionState,
) -> UserResult<std::sync::Arc<RedisConnectionPool>> {
state
.global_store
.get_redis_conn()
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to get redis connection")
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/authentication.rs | crates/router/src/services/authentication.rs | use std::{marker::PhantomData, str::FromStr};
use actix_web::http::header::HeaderMap;
#[cfg(feature = "v2")]
use api_models::payment_methods::PaymentMethodIntentConfirm;
#[cfg(feature = "v1")]
use api_models::payment_methods::{PaymentMethodCreate, PaymentMethodListRequest};
use api_models::payments;
#[cfg(feature = "payouts")]
use api_models::payouts;
use async_trait::async_trait;
use base64::Engine;
use common_enums::{MerchantAccountType, TokenPurpose};
use common_utils::{date_time, fp_utils, id_type};
#[cfg(feature = "v2")]
use diesel_models::ephemeral_key;
use error_stack::{report, ResultExt};
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
#[cfg(feature = "v2")]
use masking::ExposeInterface;
use masking::PeekInterface;
use router_env::logger;
use serde::Serialize;
use self::blacklist::BlackList;
#[cfg(all(feature = "partial-auth", feature = "v1"))]
use self::detached::ExtractedPayload;
#[cfg(feature = "partial-auth")]
use self::detached::GetAuthType;
use super::authorization::{self, permissions::Permission};
#[cfg(feature = "olap")]
use super::jwt;
#[cfg(feature = "olap")]
use crate::configs::Settings;
#[cfg(feature = "olap")]
use crate::consts;
#[cfg(feature = "olap")]
use crate::core::errors::UserResult;
#[cfg(all(feature = "partial-auth", feature = "v1"))]
use crate::core::metrics;
use crate::{
configs::settings,
consts::BASE64_ENGINE,
core::{
api_keys,
errors::{self, utils::StorageErrorExt, RouterResult},
},
headers,
routes::app::SessionStateInfo,
services::api,
types::{domain, storage},
utils::OptionExt,
};
pub mod blacklist;
pub mod cookies;
pub mod decision;
#[cfg(feature = "partial-auth")]
mod detached;
#[cfg(feature = "v1")]
#[derive(Clone, Debug)]
pub struct AuthenticationData {
pub platform: domain::Platform,
pub profile: Option<domain::Profile>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug)]
pub struct AuthenticationData {
pub platform: domain::Platform,
pub profile: domain::Profile,
}
#[derive(Clone, Debug)]
pub struct PlatformAccountWithKeyStore {
account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
}
#[derive(Clone, Debug)]
pub struct AuthenticationDataWithoutProfile {
pub merchant_account: domain::MerchantAccount,
pub key_store: domain::MerchantKeyStore,
}
#[derive(Clone, Debug)]
pub struct AuthenticationDataWithMultipleProfiles {
pub merchant_account: domain::MerchantAccount,
pub key_store: domain::MerchantKeyStore,
pub profile_id_list: Option<Vec<id_type::ProfileId>>,
}
#[derive(Clone, Debug)]
pub struct AuthenticationDataWithUser {
pub merchant_account: domain::MerchantAccount,
pub key_store: domain::MerchantKeyStore,
pub user: storage::User,
pub profile_id: id_type::ProfileId,
}
#[derive(Clone, Debug)]
pub struct AuthenticationDataWithOrg {
pub organization_id: id_type::OrganizationId,
}
#[derive(Clone)]
pub struct UserFromTokenWithRoleInfo {
pub user: UserFromToken,
pub role_info: authorization::roles::RoleInfo,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(
tag = "api_auth_type",
content = "authentication_data",
rename_all = "snake_case"
)]
pub enum AuthenticationType {
ApiKey {
merchant_id: id_type::MerchantId,
key_id: id_type::ApiKeyId,
},
AdminApiKey,
AdminApiAuthWithMerchantId {
merchant_id: id_type::MerchantId,
},
OrganizationJwt {
org_id: id_type::OrganizationId,
user_id: String,
},
BasicAuth {
username: String,
},
MerchantJwt {
merchant_id: id_type::MerchantId,
user_id: Option<String>,
},
MerchantJwtWithProfileId {
merchant_id: id_type::MerchantId,
profile_id: Option<id_type::ProfileId>,
user_id: String,
},
UserJwt {
user_id: String,
},
SinglePurposeJwt {
user_id: String,
purpose: TokenPurpose,
},
SinglePurposeOrLoginJwt {
user_id: String,
purpose: Option<TokenPurpose>,
role_id: Option<String>,
},
MerchantId {
merchant_id: id_type::MerchantId,
},
PublishableKey {
merchant_id: id_type::MerchantId,
},
WebhookAuth {
merchant_id: id_type::MerchantId,
},
InternalMerchantIdProfileId {
merchant_id: id_type::MerchantId,
profile_id: Option<id_type::ProfileId>,
},
NoAuth,
}
impl events::EventInfo for AuthenticationType {
type Data = Self;
fn data(&self) -> error_stack::Result<Self::Data, events::EventsError> {
Ok(self.clone())
}
fn key(&self) -> String {
"auth_info".to_string()
}
}
impl AuthenticationType {
pub fn get_merchant_id(&self) -> Option<&id_type::MerchantId> {
match self {
Self::ApiKey {
merchant_id,
key_id: _,
}
| Self::AdminApiAuthWithMerchantId { merchant_id }
| Self::MerchantId { merchant_id }
| Self::PublishableKey { merchant_id }
| Self::MerchantJwt {
merchant_id,
user_id: _,
}
| Self::MerchantJwtWithProfileId { merchant_id, .. }
| Self::WebhookAuth { merchant_id }
| Self::InternalMerchantIdProfileId { merchant_id, .. } => Some(merchant_id),
Self::AdminApiKey
| Self::OrganizationJwt { .. }
| Self::BasicAuth { .. }
| Self::UserJwt { .. }
| Self::SinglePurposeJwt { .. }
| Self::SinglePurposeOrLoginJwt { .. }
| Self::NoAuth => None,
}
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, serde::Deserialize, strum::Display)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum ExternalServiceType {
Hypersense,
}
#[cfg(feature = "olap")]
#[derive(Clone, Debug)]
pub struct UserFromSinglePurposeToken {
pub user_id: String,
pub origin: domain::Origin,
pub path: Vec<TokenPurpose>,
pub tenant_id: Option<id_type::TenantId>,
}
#[cfg(feature = "olap")]
#[derive(serde::Serialize, serde::Deserialize)]
pub struct SinglePurposeToken {
pub user_id: String,
pub purpose: TokenPurpose,
pub origin: domain::Origin,
pub path: Vec<TokenPurpose>,
pub exp: u64,
pub tenant_id: Option<id_type::TenantId>,
}
#[cfg(feature = "olap")]
impl SinglePurposeToken {
pub async fn new_token(
user_id: String,
purpose: TokenPurpose,
origin: domain::Origin,
settings: &Settings,
path: Vec<TokenPurpose>,
tenant_id: Option<id_type::TenantId>,
) -> UserResult<String> {
let exp_duration =
std::time::Duration::from_secs(consts::SINGLE_PURPOSE_TOKEN_TIME_IN_SECS);
let exp = jwt::generate_exp(exp_duration)?.as_secs();
let token_payload = Self {
user_id,
purpose,
origin,
exp,
path,
tenant_id,
};
jwt::generate_jwt(&token_payload, settings).await
}
}
#[derive(serde::Serialize, serde::Deserialize)]
pub struct AuthToken {
pub user_id: String,
pub merchant_id: id_type::MerchantId,
pub role_id: String,
pub exp: u64,
pub org_id: id_type::OrganizationId,
pub profile_id: id_type::ProfileId,
pub tenant_id: Option<id_type::TenantId>,
}
#[cfg(feature = "olap")]
impl AuthToken {
pub async fn new_token(
user_id: String,
merchant_id: id_type::MerchantId,
role_id: String,
settings: &Settings,
org_id: id_type::OrganizationId,
profile_id: id_type::ProfileId,
tenant_id: Option<id_type::TenantId>,
) -> UserResult<String> {
let exp_duration = std::time::Duration::from_secs(consts::JWT_TOKEN_TIME_IN_SECS);
let exp = jwt::generate_exp(exp_duration)?.as_secs();
let token_payload = Self {
user_id,
merchant_id,
role_id,
exp,
org_id,
profile_id,
tenant_id,
};
jwt::generate_jwt(&token_payload, settings).await
}
}
#[derive(Clone)]
pub struct UserFromToken {
pub user_id: String,
pub merchant_id: id_type::MerchantId,
pub role_id: String,
pub org_id: id_type::OrganizationId,
pub profile_id: id_type::ProfileId,
pub tenant_id: Option<id_type::TenantId>,
}
pub struct UserIdFromAuth {
pub user_id: String,
pub tenant_id: Option<id_type::TenantId>,
}
#[cfg(feature = "olap")]
#[derive(serde::Serialize, serde::Deserialize)]
pub struct SinglePurposeOrLoginToken {
pub user_id: String,
pub role_id: Option<String>,
pub purpose: Option<TokenPurpose>,
pub exp: u64,
pub tenant_id: Option<id_type::TenantId>,
}
#[async_trait]
pub trait AuthenticateAndFetch<T, A>
where
A: SessionStateInfo,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(T, AuthenticationType)>;
}
#[derive(Debug, Default)]
pub struct ApiKeyAuth {
pub is_connected_allowed: bool,
pub is_platform_allowed: bool,
}
pub struct NoAuth;
pub trait BasicAuthProvider {
type Identity;
fn get_credentials<A>(
state: &A,
identifier: &str,
) -> RouterResult<(Self::Identity, masking::Secret<String>)>
where
A: SessionStateInfo;
}
#[derive(Debug, Default)]
pub struct BasicAuth<P> {
_marker: PhantomData<P>,
}
impl<P> BasicAuth<P> {
pub const fn new() -> Self {
Self {
_marker: PhantomData,
}
}
}
pub struct OidcAuthProvider;
impl BasicAuthProvider for OidcAuthProvider {
type Identity = String;
fn get_credentials<A>(
state: &A,
identifier: &str,
) -> RouterResult<(Self::Identity, masking::Secret<String>)>
where
A: SessionStateInfo,
{
let session = state.session_state();
let client = session
.conf
.oidc
.get_inner()
.get_client(identifier)
.ok_or(errors::ApiErrorResponse::InvalidBasicAuth)?;
Ok((client.client_id.clone(), client.client_secret.clone()))
}
}
pub const OIDC_CLIENT_AUTH: BasicAuth<OidcAuthProvider> = BasicAuth::<OidcAuthProvider>::new();
#[cfg(feature = "partial-auth")]
impl GetAuthType for ApiKeyAuth {
fn get_auth_type(&self) -> detached::PayloadType {
detached::PayloadType::ApiKey
}
}
#[cfg(feature = "partial-auth")]
pub trait GetMerchantAccessFlags {
fn get_is_connected_allowed(&self) -> bool;
fn get_is_platform_allowed(&self) -> bool;
}
#[cfg(feature = "partial-auth")]
impl GetMerchantAccessFlags for ApiKeyAuth {
fn get_is_connected_allowed(&self) -> bool {
self.is_connected_allowed
}
fn get_is_platform_allowed(&self) -> bool {
self.is_platform_allowed
}
}
//
// # Header Auth
//
// Header Auth is a feature that allows you to authenticate requests using custom headers. This is
// done by checking whether the request contains the specified headers.
// - `x-merchant-id` header is used to authenticate the merchant.
//
// ## Checksum
// - `x-auth-checksum` header is used to authenticate the request. The checksum is calculated using the
// above mentioned headers is generated by hashing the headers mentioned above concatenated with `:` and then hashed with the detached authentication key.
//
// When the [`partial-auth`] feature is disabled the implementation for [`AuthenticateAndFetch`]
// changes where the authentication is done by the [`I`] implementation.
//
pub struct HeaderAuth<I>(pub I);
#[async_trait]
impl<A> AuthenticateAndFetch<(), A> for NoAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
_request_headers: &HeaderMap,
_state: &A,
) -> RouterResult<((), AuthenticationType)> {
Ok(((), AuthenticationType::NoAuth))
}
}
#[async_trait]
impl<A, T> AuthenticateAndFetch<Option<T>, A> for NoAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
_request_headers: &HeaderMap,
_state: &A,
) -> RouterResult<(Option<T>, AuthenticationType)> {
Ok((None, AuthenticationType::NoAuth))
}
}
#[async_trait]
impl<A, P> AuthenticateAndFetch<P::Identity, A> for BasicAuth<P>
where
A: SessionStateInfo + Sync,
P: BasicAuthProvider + Send + Sync,
P::Identity: Clone,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(P::Identity, AuthenticationType)> {
let (provided_identifier, provided_secret) = parse_basic_auth_credentials(request_headers)?;
let (authenticated_entity, expected_secret) =
P::get_credentials(state, &provided_identifier)?;
if provided_secret.peek() != expected_secret.peek() {
return Err(errors::ApiErrorResponse::InvalidBasicAuth.into());
}
Ok((
authenticated_entity.clone(),
AuthenticationType::BasicAuth {
username: provided_identifier,
},
))
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for ApiKeyAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let api_key = get_api_key(request_headers)
.change_context(errors::ApiErrorResponse::Unauthorized)?
.trim();
if api_key.is_empty() {
return Err(errors::ApiErrorResponse::Unauthorized)
.attach_printable("API key is empty");
}
let profile_id = HeaderMapStruct::new(request_headers)
.get_id_type_from_header::<id_type::ProfileId>(headers::X_PROFILE_ID)?;
let api_key = api_keys::PlaintextApiKey::from(api_key);
let hash_key = {
let config = state.conf();
config.api_keys.get_inner().get_hash_key()?
};
let hashed_api_key = api_key.keyed_hash(hash_key.peek());
let stored_api_key = state
.store()
.find_api_key_by_hash_optional(hashed_api_key.into())
.await
.change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed
.attach_printable("Failed to retrieve API key")?
.ok_or(report!(errors::ApiErrorResponse::Unauthorized)) // If retrieve returned `None`
.attach_printable("Merchant not authenticated")?;
if stored_api_key
.expires_at
.map(|expires_at| expires_at < date_time::now())
.unwrap_or(false)
{
return Err(report!(errors::ApiErrorResponse::Unauthorized))
.attach_printable("API key has expired");
}
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
&stored_api_key.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let initiator_merchant = state
.store()
.find_merchant_account_by_merchant_id(&stored_api_key.merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let profile = state
.store()
.find_business_profile_by_profile_id(&key_store, &profile_id)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
check_merchant_access(
state,
initiator_merchant.merchant_account_type,
self.is_connected_allowed,
self.is_platform_allowed,
)?;
let platform = resolve_platform(
state,
request_headers,
initiator_merchant.clone(),
key_store,
)
.await?;
let auth = AuthenticationData { platform, profile };
Ok((
auth.clone(),
AuthenticationType::ApiKey {
merchant_id: initiator_merchant.get_id().clone(),
key_id: stored_api_key.key_id,
},
))
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for ApiKeyAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let api_key = get_api_key(request_headers)
.change_context(errors::ApiErrorResponse::Unauthorized)?
.trim();
if api_key.is_empty() {
return Err(errors::ApiErrorResponse::Unauthorized)
.attach_printable("API key is empty");
}
let api_key = api_keys::PlaintextApiKey::from(api_key);
let hash_key = {
let config = state.conf();
config.api_keys.get_inner().get_hash_key()?
};
let hashed_api_key = api_key.keyed_hash(hash_key.peek());
let stored_api_key = state
.store()
.find_api_key_by_hash_optional(hashed_api_key.into())
.await
.change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed
.attach_printable("Failed to retrieve API key")?
.ok_or(report!(errors::ApiErrorResponse::Unauthorized)) // If retrieve returned `None`
.attach_printable("Merchant not authenticated")?;
if stored_api_key
.expires_at
.map(|expires_at| expires_at < date_time::now())
.unwrap_or(false)
{
return Err(report!(errors::ApiErrorResponse::Unauthorized))
.attach_printable("API key has expired");
}
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
&stored_api_key.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let profile_id =
get_header_value_by_key(headers::X_PROFILE_ID.to_string(), request_headers)?
.map(id_type::ProfileId::from_str)
.transpose()
.change_context(errors::ValidationError::IncorrectValueProvided {
field_name: "X-Profile-Id",
})
.change_context(errors::ApiErrorResponse::Unauthorized)?;
let initiator_merchant = state
.store()
.find_merchant_account_by_merchant_id(&stored_api_key.merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
check_merchant_access(
state,
initiator_merchant.merchant_account_type,
self.is_connected_allowed,
self.is_platform_allowed,
)?;
let platform = resolve_platform(
state,
request_headers,
initiator_merchant.clone(),
key_store.clone(),
)
.await?;
let profile = match profile_id {
Some(profile_id) => {
let profile = state
.store()
.find_business_profile_by_profile_id(
platform.get_processor().get_key_store(),
&profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
Some(profile)
}
None => None,
};
let auth = AuthenticationData { platform, profile };
Ok((
auth.clone(),
AuthenticationType::ApiKey {
merchant_id: initiator_merchant.get_id().clone(),
key_id: stored_api_key.key_id,
},
))
}
}
#[derive(Debug)]
pub struct ApiKeyAuthWithMerchantIdFromRoute(pub id_type::MerchantId);
#[cfg(feature = "partial-auth")]
impl GetAuthType for ApiKeyAuthWithMerchantIdFromRoute {
fn get_auth_type(&self) -> detached::PayloadType {
detached::PayloadType::ApiKey
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for ApiKeyAuthWithMerchantIdFromRoute
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let api_auth = ApiKeyAuth {
is_connected_allowed: true,
is_platform_allowed: false,
};
let (auth_data, auth_type) = api_auth
.authenticate_and_fetch(request_headers, state)
.await?;
let merchant_id_from_route = self.0.clone();
let merchant_id_from_api_key = auth_type
.get_merchant_id()
.ok_or(report!(errors::ApiErrorResponse::Unauthorized))
.attach_printable("Merchant ID not found in API key authentication type")?;
if merchant_id_from_route != *merchant_id_from_api_key {
return Err(report!(errors::ApiErrorResponse::Unauthorized)).attach_printable(
"Merchant ID from route and Merchant ID from api-key in header do not match",
);
}
Ok((auth_data, auth_type))
}
}
#[derive(Debug, Default)]
pub struct PlatformOrgAdminAuth {
pub is_admin_auth_allowed: bool,
pub organization_id: Option<id_type::OrganizationId>,
}
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<Option<AuthenticationDataWithOrg>, A> for PlatformOrgAdminAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(Option<AuthenticationDataWithOrg>, AuthenticationType)> {
// Step 1: Admin API Key and API Key Fallback (if allowed)
if self.is_admin_auth_allowed {
let admin_auth = AdminApiAuthWithApiKeyFallback {
organization_id: self.organization_id.clone(),
};
match admin_auth
.authenticate_and_fetch(request_headers, state)
.await
{
Ok((auth, auth_type)) => {
return Ok((auth, auth_type));
}
Err(e) => {
logger::warn!("Admin API Auth failed: {:?}", e);
}
}
}
// Step 2: Try Platform Auth
let api_key = get_api_key(request_headers)
.change_context(errors::ApiErrorResponse::Unauthorized)?
.trim();
if api_key.is_empty() {
return Err(errors::ApiErrorResponse::Unauthorized)
.attach_printable("API key is empty");
}
let api_key_plaintext = api_keys::PlaintextApiKey::from(api_key);
let hash_key = state.conf().api_keys.get_inner().get_hash_key()?;
let hashed_api_key = api_key_plaintext.keyed_hash(hash_key.peek());
let stored_api_key = state
.store()
.find_api_key_by_hash_optional(hashed_api_key.into())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve API key")?
.ok_or_else(|| report!(errors::ApiErrorResponse::Unauthorized))
.attach_printable("Merchant not authenticated via API key")?;
if stored_api_key
.expires_at
.map(|expires_at| expires_at < date_time::now())
.unwrap_or(false)
{
return Err(report!(errors::ApiErrorResponse::Unauthorized))
.attach_printable("API key has expired");
}
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
&stored_api_key.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let merchant_account = state
.store()
.find_merchant_account_by_merchant_id(&stored_api_key.merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Merchant account not found")?;
if !(state.conf().platform.enabled && merchant_account.is_platform_account()) {
return Err(report!(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Platform authentication check failed"));
}
fp_utils::when(
self.organization_id
.as_ref()
.is_some_and(|org_id| org_id != merchant_account.get_org_id()),
|| {
Err(report!(errors::ApiErrorResponse::Unauthorized))
.attach_printable("Organization ID does not match")
},
)?;
Ok((
Some(AuthenticationDataWithOrg {
organization_id: merchant_account.get_org_id().clone(),
}),
AuthenticationType::ApiKey {
merchant_id: merchant_account.get_id().clone(),
key_id: stored_api_key.key_id,
},
))
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for PlatformOrgAdminAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let api_key = get_api_key(request_headers)
.change_context(errors::ApiErrorResponse::Unauthorized)?
.trim();
if api_key.is_empty() {
return Err(errors::ApiErrorResponse::Unauthorized)
.attach_printable("API key is empty");
}
let api_key_plaintext = api_keys::PlaintextApiKey::from(api_key);
let hash_key = state.conf().api_keys.get_inner().get_hash_key()?;
let hashed_api_key = api_key_plaintext.keyed_hash(hash_key.peek());
let stored_api_key = state
.store()
.find_api_key_by_hash_optional(hashed_api_key.into())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve API key")?
.ok_or_else(|| report!(errors::ApiErrorResponse::Unauthorized))
.attach_printable("Merchant not authenticated via API key")?;
if stored_api_key
.expires_at
.map(|expires_at| expires_at < date_time::now())
.unwrap_or(false)
{
return Err(report!(errors::ApiErrorResponse::Unauthorized))
.attach_printable("API key has expired");
}
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
&stored_api_key.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let initiator_merchant_account = state
.store()
.find_merchant_account_by_merchant_id(&stored_api_key.merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Merchant account not found")?;
if !(state.conf().platform.enabled && initiator_merchant_account.is_platform_account()) {
return Err(report!(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Platform authentication check failed"));
}
fp_utils::when(
self.organization_id
.as_ref()
.is_some_and(|org_id| org_id != initiator_merchant_account.get_org_id()),
|| {
Err(report!(errors::ApiErrorResponse::Unauthorized))
.attach_printable("Organization ID does not match")
},
)?;
let initiator = Some(domain::Initiator::Api {
merchant_id: initiator_merchant_account.get_id().clone(),
merchant_account_type: initiator_merchant_account.merchant_account_type,
});
let platform = domain::Platform::new(
initiator_merchant_account.clone(),
key_store.clone(),
initiator_merchant_account.clone(),
key_store,
initiator,
);
let auth = AuthenticationData {
platform,
profile: None,
};
Ok((
auth.clone(),
AuthenticationType::ApiKey {
merchant_id: initiator_merchant_account.get_id().clone(),
key_id: stored_api_key.key_id,
},
))
}
}
#[derive(Debug)]
pub struct PlatformOrgAdminAuthWithMerchantIdFromRoute {
pub merchant_id_from_route: id_type::MerchantId,
pub is_admin_auth_allowed: bool,
}
#[cfg(feature = "v1")]
impl PlatformOrgAdminAuthWithMerchantIdFromRoute {
async fn fetch_key_store_and_account<A: SessionStateInfo + Sync>(
merchant_id: &id_type::MerchantId,
state: &A,
) -> RouterResult<(domain::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::Unauthorized)?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
Ok((key_store, merchant))
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for PlatformOrgAdminAuthWithMerchantIdFromRoute
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let route_merchant_id = self.merchant_id_from_route.clone();
// Step 1: Admin API Key and API Key Fallback (if allowed)
if self.is_admin_auth_allowed {
let admin_auth =
AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute(route_merchant_id.clone());
match admin_auth
.authenticate_and_fetch(request_headers, state)
.await
{
Ok((auth_data, auth_type)) => return Ok((auth_data, auth_type)),
Err(e) => {
logger::warn!("Admin API Auth failed: {:?}", e);
}
}
}
// Step 2: Platform authentication
let api_key = get_api_key(request_headers)
.change_context(errors::ApiErrorResponse::Unauthorized)?
.trim();
if api_key.is_empty() {
return Err(errors::ApiErrorResponse::Unauthorized)
.attach_printable("API key is empty");
}
let api_key_plaintext = api_keys::PlaintextApiKey::from(api_key);
let hash_key = {
let config = state.conf();
config.api_keys.get_inner().get_hash_key()?
};
let hashed_api_key = api_key_plaintext.keyed_hash(hash_key.peek());
let stored_api_key = state
.store()
.find_api_key_by_hash_optional(hashed_api_key.into())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve API key")?
.ok_or_else(|| report!(errors::ApiErrorResponse::Unauthorized))
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/authorization.rs | crates/router/src/services/authorization.rs | use std::sync::Arc;
use common_utils::id_type;
use error_stack::ResultExt;
use redis_interface::RedisConnectionPool;
use router_env::logger;
use super::authentication::AuthToken;
use crate::{
consts,
core::errors::{ApiErrorResponse, RouterResult, StorageErrorExt},
routes::app::SessionStateInfo,
};
#[cfg(feature = "olap")]
pub mod info;
pub mod permission_groups;
pub mod permissions;
pub mod roles;
pub async fn get_role_info<A>(state: &A, token: &AuthToken) -> RouterResult<roles::RoleInfo>
where
A: SessionStateInfo + Sync,
{
if let Some(role_info) = roles::predefined_roles::PREDEFINED_ROLES.get(token.role_id.as_str()) {
return Ok(role_info.clone());
}
if let Ok(role_info) = get_role_info_from_cache(state, &token.role_id)
.await
.map_err(|e| logger::error!("Failed to get permissions from cache {e:?}"))
{
return Ok(role_info.clone());
}
let role_info = get_role_info_from_db(
state,
&token.role_id,
&token.org_id,
token
.tenant_id
.as_ref()
.unwrap_or(&state.session_state().tenant.tenant_id),
)
.await?;
let token_expiry =
i64::try_from(token.exp).change_context(ApiErrorResponse::InternalServerError)?;
let cache_ttl = token_expiry - common_utils::date_time::now_unix_timestamp();
if cache_ttl > 0 {
set_role_info_in_cache(state, &token.role_id, &role_info, cache_ttl)
.await
.map_err(|e| logger::error!("Failed to set role info in cache {e:?}"))
.ok();
}
Ok(role_info)
}
async fn get_role_info_from_cache<A>(state: &A, role_id: &str) -> RouterResult<roles::RoleInfo>
where
A: SessionStateInfo + Sync,
{
let redis_conn = get_redis_connection_for_global_tenant(state)?;
redis_conn
.get_and_deserialize_key(&get_cache_key_from_role_id(role_id).into(), "RoleInfo")
.await
.change_context(ApiErrorResponse::InternalServerError)
}
pub fn get_cache_key_from_role_id(role_id: &str) -> String {
format!("{}{}", consts::ROLE_INFO_CACHE_PREFIX, role_id)
}
async fn get_role_info_from_db<A>(
state: &A,
role_id: &str,
org_id: &id_type::OrganizationId,
tenant_id: &id_type::TenantId,
) -> RouterResult<roles::RoleInfo>
where
A: SessionStateInfo + Sync,
{
state
.session_state()
.global_store
.find_by_role_id_org_id_tenant_id(role_id, org_id, tenant_id)
.await
.map(roles::RoleInfo::from)
.to_not_found_response(ApiErrorResponse::InvalidJwtToken)
}
pub async fn set_role_info_in_cache<A>(
state: &A,
role_id: &str,
role_info: &roles::RoleInfo,
expiry: i64,
) -> RouterResult<()>
where
A: SessionStateInfo + Sync,
{
let redis_conn = get_redis_connection_for_global_tenant(state)?;
redis_conn
.serialize_and_set_key_with_expiry(
&get_cache_key_from_role_id(role_id).into(),
role_info,
expiry,
)
.await
.change_context(ApiErrorResponse::InternalServerError)
}
pub fn check_permission(
required_permission: permissions::Permission,
role_info: &roles::RoleInfo,
) -> RouterResult<()> {
role_info
.check_permission_exists(required_permission)
.then_some(())
.ok_or(
ApiErrorResponse::AccessForbidden {
resource: required_permission.to_string(),
}
.into(),
)
}
pub fn check_tenant(
token_tenant_id: Option<id_type::TenantId>,
header_tenant_id: &id_type::TenantId,
) -> RouterResult<()> {
if let Some(tenant_id) = token_tenant_id {
if tenant_id != *header_tenant_id {
return Err(ApiErrorResponse::InvalidJwtToken).attach_printable(format!(
"Token tenant ID: '{}' does not match Header tenant ID: '{}'",
tenant_id.get_string_repr().to_owned(),
header_tenant_id.get_string_repr().to_owned()
));
}
}
Ok(())
}
fn get_redis_connection_for_global_tenant<A: SessionStateInfo>(
state: &A,
) -> RouterResult<Arc<RedisConnectionPool>> {
state
.global_store()
.get_redis_conn()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/connector_integration_interface.rs | crates/router/src/services/connector_integration_interface.rs | pub use hyperswitch_interfaces::{
authentication::ExternalAuthenticationPayload, connector_integration_interface::*,
connector_integration_v2::ConnectorIntegrationV2, webhooks::IncomingWebhookFlowError,
};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/oidc_provider.rs | crates/router/src/services/oidc_provider.rs | use api_models::oidc::{
Jwk, JwksResponse, KeyType, KeyUse, OidcDiscoveryResponse, SigningAlgorithm,
};
use error_stack::ResultExt;
use once_cell::sync::OnceCell;
use crate::{
core::errors::{ApiErrorResponse, RouterResponse},
routes::app::SessionState,
services::api::ApplicationResponse,
utils::user as user_utils,
};
/// Build OIDC discovery document
pub async fn get_discovery_document(state: SessionState) -> RouterResponse<OidcDiscoveryResponse> {
let backend_base_url = state.tenant.base_url.clone();
let control_center_url = user_utils::get_base_url(&state);
Ok(ApplicationResponse::Json(OidcDiscoveryResponse::new(
backend_base_url,
control_center_url.into(),
)))
}
static CACHED_JWKS: OnceCell<JwksResponse> = OnceCell::new();
/// Build JWKS response with public keys (all keys for token validation)
pub async fn get_jwks(state: SessionState) -> RouterResponse<&'static JwksResponse> {
CACHED_JWKS
.get_or_try_init(|| {
let oidc_keys = state.conf.oidc.get_inner().get_all_keys();
let mut keys = Vec::with_capacity(oidc_keys.len());
for key_config in oidc_keys {
let (n, e) = common_utils::crypto::extract_rsa_public_key_components(
&key_config.private_key,
)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to extract public key from private key")?;
let jwk = Jwk {
kty: KeyType::Rsa,
kid: key_config.kid.clone(),
key_use: KeyUse::Sig,
alg: SigningAlgorithm::Rs256,
n,
e,
};
keys.push(jwk);
}
Ok::<_, error_stack::Report<ApiErrorResponse>>(JwksResponse { keys })
})
.map(ApplicationResponse::Json)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/authorization/permission_groups.rs | crates/router/src/services/authorization/permission_groups.rs | use std::{collections::HashMap, ops::Not};
use common_enums::{EntityType, ParentGroup, PermissionGroup, PermissionScope, Resource};
use strum::IntoEnumIterator;
use super::permissions;
pub trait PermissionGroupExt {
fn scope(&self) -> PermissionScope;
fn parent(&self) -> ParentGroup;
fn resources(&self) -> Vec<Resource>;
fn accessible_groups(&self) -> Vec<PermissionGroup>;
}
impl PermissionGroupExt for PermissionGroup {
fn scope(&self) -> PermissionScope {
match self {
Self::OperationsView
| Self::ConnectorsView
| Self::WorkflowsView
| Self::AnalyticsView
| Self::UsersView
| Self::AccountView
| Self::ReconOpsView
| Self::ReconReportsView
| Self::ThemeView => PermissionScope::Read,
Self::OperationsManage
| Self::ConnectorsManage
| Self::WorkflowsManage
| Self::UsersManage
| Self::AccountManage
| Self::ReconOpsManage
| Self::ReconReportsManage
| Self::InternalManage
| Self::ThemeManage => PermissionScope::Write,
}
}
fn parent(&self) -> ParentGroup {
match self {
Self::OperationsView | Self::OperationsManage => ParentGroup::Operations,
Self::ConnectorsView | Self::ConnectorsManage => ParentGroup::Connectors,
Self::WorkflowsView | Self::WorkflowsManage => ParentGroup::Workflows,
Self::AnalyticsView => ParentGroup::Analytics,
Self::UsersView | Self::UsersManage => ParentGroup::Users,
Self::AccountView | Self::AccountManage => ParentGroup::Account,
Self::ThemeView | Self::ThemeManage => ParentGroup::Theme,
Self::ReconOpsView | Self::ReconOpsManage => ParentGroup::ReconOps,
Self::ReconReportsView | Self::ReconReportsManage => ParentGroup::ReconReports,
Self::InternalManage => ParentGroup::Internal,
}
}
fn resources(&self) -> Vec<Resource> {
self.parent().resources()
}
fn accessible_groups(&self) -> Vec<Self> {
match self {
Self::OperationsView => vec![Self::OperationsView, Self::ConnectorsView],
Self::OperationsManage => vec![
Self::OperationsView,
Self::OperationsManage,
Self::ConnectorsView,
],
Self::ConnectorsView => vec![Self::ConnectorsView],
Self::ConnectorsManage => vec![Self::ConnectorsView, Self::ConnectorsManage],
Self::WorkflowsView => vec![Self::WorkflowsView, Self::ConnectorsView],
Self::WorkflowsManage => vec![
Self::WorkflowsView,
Self::WorkflowsManage,
Self::ConnectorsView,
],
Self::AnalyticsView => vec![Self::AnalyticsView, Self::OperationsView],
Self::UsersView => vec![Self::UsersView],
Self::UsersManage => {
vec![Self::UsersView, Self::UsersManage]
}
Self::ReconOpsView => vec![Self::ReconOpsView],
Self::ReconOpsManage => vec![Self::ReconOpsView, Self::ReconOpsManage],
Self::ReconReportsView => vec![Self::ReconReportsView],
Self::ReconReportsManage => vec![Self::ReconReportsView, Self::ReconReportsManage],
Self::AccountView => vec![Self::AccountView],
Self::AccountManage => vec![Self::AccountView, Self::AccountManage],
Self::InternalManage => vec![Self::InternalManage],
Self::ThemeView => vec![Self::ThemeView, Self::AccountView],
Self::ThemeManage => vec![Self::ThemeManage, Self::AccountView],
}
}
}
pub trait ParentGroupExt {
fn resources(&self) -> Vec<Resource>;
fn get_descriptions_for_groups(
entity_type: EntityType,
groups: Vec<PermissionGroup>,
) -> Option<HashMap<ParentGroup, String>>;
fn get_available_scopes(&self) -> Vec<PermissionScope>;
}
impl ParentGroupExt for ParentGroup {
fn resources(&self) -> Vec<Resource> {
match self {
Self::Operations => OPERATIONS.to_vec(),
Self::Connectors => CONNECTORS.to_vec(),
Self::Workflows => WORKFLOWS.to_vec(),
Self::Analytics => ANALYTICS.to_vec(),
Self::Users => USERS.to_vec(),
Self::Account => ACCOUNT.to_vec(),
Self::ReconOps => RECON_OPS.to_vec(),
Self::ReconReports => RECON_REPORTS.to_vec(),
Self::Internal => INTERNAL.to_vec(),
Self::Theme => THEME.to_vec(),
}
}
fn get_descriptions_for_groups(
entity_type: EntityType,
groups: Vec<PermissionGroup>,
) -> Option<HashMap<Self, String>> {
let descriptions_map = Self::iter()
.filter_map(|parent| {
if !groups.iter().any(|group| group.parent() == parent) {
return None;
}
let filtered_resources =
permissions::filter_resources_by_entity_type(parent.resources(), entity_type)?;
let description = filtered_resources
.iter()
.map(|res| permissions::get_resource_name(*res, entity_type))
.collect::<Option<Vec<_>>>()?
.join(", ");
Some((parent, description))
})
.collect::<HashMap<_, _>>();
descriptions_map
.is_empty()
.not()
.then_some(descriptions_map)
}
fn get_available_scopes(&self) -> Vec<PermissionScope> {
PermissionGroup::iter()
.filter(|group| group.parent() == *self)
.map(|group| group.scope())
.collect()
}
}
pub static OPERATIONS: [Resource; 8] = [
Resource::Payment,
Resource::Refund,
Resource::Mandate,
Resource::Dispute,
Resource::Customer,
Resource::Payout,
Resource::Report,
Resource::Account,
];
pub static CONNECTORS: [Resource; 2] = [Resource::Connector, Resource::Account];
pub static WORKFLOWS: [Resource; 5] = [
Resource::Routing,
Resource::ThreeDsDecisionManager,
Resource::SurchargeDecisionManager,
Resource::Account,
Resource::RevenueRecovery,
];
pub static ANALYTICS: [Resource; 3] = [Resource::Analytics, Resource::Report, Resource::Account];
pub static USERS: [Resource; 2] = [Resource::User, Resource::Account];
pub static ACCOUNT: [Resource; 3] = [Resource::Account, Resource::ApiKey, Resource::WebhookEvent];
pub static RECON_OPS: [Resource; 8] = [
Resource::ReconToken,
Resource::ReconFiles,
Resource::ReconUpload,
Resource::RunRecon,
Resource::ReconConfig,
Resource::ReconAndSettlementAnalytics,
Resource::ReconReports,
Resource::Account,
];
pub static INTERNAL: [Resource; 1] = [Resource::InternalConnector];
pub static RECON_REPORTS: [Resource; 4] = [
Resource::ReconToken,
Resource::ReconAndSettlementAnalytics,
Resource::ReconReports,
Resource::Account,
];
pub static THEME: [Resource; 1] = [Resource::Theme];
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/authorization/permissions.rs | crates/router/src/services/authorization/permissions.rs | use common_enums::{EntityType, PermissionScope, Resource};
use router_derive::generate_permissions;
generate_permissions! {
permissions: [
Payment: {
scopes: [Read, Write],
entities: [Profile, Merchant]
},
Refund: {
scopes: [Read, Write],
entities: [Profile, Merchant]
},
Dispute: {
scopes: [Read, Write],
entities: [Profile, Merchant]
},
Mandate: {
scopes: [Read, Write],
entities: [Merchant]
},
Customer: {
scopes: [Read, Write],
entities: [Merchant]
},
Payout: {
scopes: [Read],
entities: [Profile, Merchant]
},
ApiKey: {
scopes: [Read, Write],
entities: [Merchant]
},
Account: {
scopes: [Read, Write],
entities: [Profile, Merchant, Organization, Tenant]
},
Connector: {
scopes: [Read, Write],
entities: [Profile, Merchant]
},
Routing: {
scopes: [Read, Write],
entities: [Profile, Merchant]
},
Subscription: {
scopes: [Read, Write],
entities: [Profile, Merchant]
},
ThreeDsDecisionManager: {
scopes: [Read, Write],
entities: [Merchant, Profile]
},
SurchargeDecisionManager: {
scopes: [Read, Write],
entities: [Merchant]
},
Analytics: {
scopes: [Read],
entities: [Profile, Merchant, Organization]
},
Report: {
scopes: [Read],
entities: [Profile, Merchant, Organization]
},
User: {
scopes: [Read, Write],
entities: [Profile, Merchant]
},
WebhookEvent: {
scopes: [Read, Write],
entities: [Profile, Merchant]
},
ReconToken: {
scopes: [Read],
entities: [Merchant]
},
ReconFiles: {
scopes: [Read, Write],
entities: [Merchant]
},
ReconAndSettlementAnalytics: {
scopes: [Read],
entities: [Merchant]
},
ReconUpload: {
scopes: [Read, Write],
entities: [Merchant]
},
ReconReports: {
scopes: [Read, Write],
entities: [Merchant]
},
RunRecon: {
scopes: [Read, Write],
entities: [Merchant]
},
ReconConfig: {
scopes: [Read, Write],
entities: [Merchant]
},
RevenueRecovery: {
scopes: [Read],
entities: [Profile]
},
InternalConnector: {
scopes: [Write],
entities: [Merchant]
},
Theme: {
scopes: [Read,Write],
entities: [Organization]
}
]
}
pub fn get_resource_name(resource: Resource, entity_type: EntityType) -> Option<&'static str> {
match (resource, entity_type) {
(Resource::Payment, _) => Some("Payments"),
(Resource::Refund, _) => Some("Refunds"),
(Resource::Dispute, _) => Some("Disputes"),
(Resource::Mandate, _) => Some("Mandates"),
(Resource::Customer, _) => Some("Customers"),
(Resource::Payout, _) => Some("Payouts"),
(Resource::ApiKey, _) => Some("Api Keys"),
(Resource::Connector, _) => {
Some("Payment Processors, Payout Processors, Fraud & Risk Managers")
}
(Resource::Routing, _) => Some("Routing"),
(Resource::Subscription, _) => Some("Subscription"),
(Resource::RevenueRecovery, _) => Some("Revenue Recovery"),
(Resource::ThreeDsDecisionManager, _) => Some("3DS Decision Manager"),
(Resource::SurchargeDecisionManager, _) => Some("Surcharge Decision Manager"),
(Resource::Analytics, _) => Some("Analytics"),
(Resource::Report, _) => Some("Operation Reports"),
(Resource::User, _) => Some("Users"),
(Resource::WebhookEvent, _) => Some("Webhook Events"),
(Resource::ReconUpload, _) => Some("Reconciliation File Upload"),
(Resource::RunRecon, _) => Some("Run Reconciliation Process"),
(Resource::ReconConfig, _) => Some("Reconciliation Configurations"),
(Resource::ReconToken, _) => Some("Generate & Verify Reconciliation Token"),
(Resource::ReconFiles, _) => Some("Reconciliation Process Manager"),
(Resource::ReconReports, _) => Some("Reconciliation Reports"),
(Resource::ReconAndSettlementAnalytics, _) => Some("Reconciliation Analytics"),
(Resource::Account, EntityType::Profile) => Some("Business Profile Account"),
(Resource::Account, EntityType::Merchant) => Some("Merchant Account"),
(Resource::Account, EntityType::Organization) => Some("Organization Account"),
(Resource::Account, EntityType::Tenant) => Some("Tenant Account"),
(Resource::Theme, _) => Some("Themes"),
(Resource::InternalConnector, _) => None,
}
}
pub fn get_scope_name(scope: PermissionScope) -> &'static str {
match scope {
PermissionScope::Read => "View",
PermissionScope::Write => "View and Manage",
}
}
pub fn filter_resources_by_entity_type(
resources: Vec<Resource>,
entity_type: EntityType,
) -> Option<Vec<Resource>> {
let filtered: Vec<Resource> = resources
.into_iter()
.filter(|res| res.entities().iter().any(|entity| entity <= &entity_type))
.collect();
(!filtered.is_empty()).then_some(filtered)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/authorization/info.rs | crates/router/src/services/authorization/info.rs | use std::ops::Not;
use api_models::user_role::GroupInfo;
use common_enums::{ParentGroup, PermissionGroup};
use strum::IntoEnumIterator;
// TODO: To be deprecated
pub fn get_group_authorization_info() -> Option<Vec<GroupInfo>> {
let groups = PermissionGroup::iter()
.filter_map(get_group_info_from_permission_group)
.collect::<Vec<_>>();
groups.is_empty().not().then_some(groups)
}
// TODO: To be deprecated
fn get_group_info_from_permission_group(group: PermissionGroup) -> Option<GroupInfo> {
let description = get_group_description(group)?;
Some(GroupInfo { group, description })
}
// TODO: To be deprecated
fn get_group_description(group: PermissionGroup) -> Option<&'static str> {
match group {
PermissionGroup::OperationsView => {
Some("View Payments, Refunds, Payouts, Mandates, Disputes and Customers")
}
PermissionGroup::OperationsManage => {
Some("Create, modify and delete Payments, Refunds, Payouts, Mandates, Disputes and Customers")
}
PermissionGroup::ConnectorsView => {
Some("View connected Payment Processors, Payout Processors and Fraud & Risk Manager details")
}
PermissionGroup::ConnectorsManage => Some("Create, modify and delete connectors like Payment Processors, Payout Processors and Fraud & Risk Manager"),
PermissionGroup::WorkflowsView => {
Some("View Routing, 3DS Decision Manager, Surcharge Decision Manager")
}
PermissionGroup::WorkflowsManage => {
Some("Create, modify and delete Routing, 3DS Decision Manager, Surcharge Decision Manager")
}
PermissionGroup::AnalyticsView => Some("View Analytics"),
PermissionGroup::UsersView => Some("View Users"),
PermissionGroup::UsersManage => Some("Manage and invite Users to the Team"),
PermissionGroup::AccountView => Some("View Merchant Details"),
PermissionGroup::AccountManage => Some("Create, modify and delete Merchant Details like api keys, webhooks, etc"),
PermissionGroup::ReconReportsView => Some("View reconciliation reports and analytics"),
PermissionGroup::ReconReportsManage => Some("Manage reconciliation reports"),
PermissionGroup::ReconOpsView => Some("View and access all reconciliation operations including reports and analytics"),
PermissionGroup::ReconOpsManage => Some("Manage all reconciliation operations including reports and analytics"),
PermissionGroup::ThemeView => Some("View Themes"),
PermissionGroup::ThemeManage => Some("Manage Themes"),
PermissionGroup::InternalManage => None, // Internal group, no user-facing description
}
}
pub fn get_parent_group_description(group: ParentGroup) -> Option<&'static str> {
match group {
ParentGroup::Operations => Some("Payments, Refunds, Payouts, Mandates, Disputes and Customers"),
ParentGroup::Connectors => Some("Create, modify and delete connectors like Payment Processors, Payout Processors and Fraud & Risk Manager"),
ParentGroup::Workflows => Some("Create, modify and delete Routing, 3DS Decision Manager, Surcharge Decision Manager"),
ParentGroup::Analytics => Some("View Analytics"),
ParentGroup::Users => Some("Manage and invite Users to the Team"),
ParentGroup::Account => Some("Create, modify and delete Merchant Details like api keys, webhooks, etc"),
ParentGroup::ReconOps => Some("View, manage reconciliation operations like upload and process files, run reconciliation etc"),
ParentGroup::ReconReports => Some("View, manage reconciliation reports and analytics"),
ParentGroup::Theme => Some("Manage and view themes for the organization"),
ParentGroup::Internal => None, // Internal group, no user-facing description
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/authorization/roles.rs | crates/router/src/services/authorization/roles.rs | #[cfg(feature = "recon")]
use std::collections::HashMap;
use std::collections::HashSet;
#[cfg(feature = "recon")]
use api_models::enums::ReconPermissionScope;
use common_enums::{EntityType, PermissionGroup, Resource, RoleScope};
use common_utils::{errors::CustomResult, id_type};
#[cfg(feature = "recon")]
use super::permission_groups::{RECON_OPS, RECON_REPORTS};
use super::{permission_groups::PermissionGroupExt, permissions::Permission};
use crate::{core::errors, routes::SessionState};
pub mod predefined_roles;
#[derive(Clone, serde::Serialize, serde::Deserialize, Debug)]
pub struct RoleInfo {
role_id: String,
role_name: String,
groups: Vec<PermissionGroup>,
scope: RoleScope,
entity_type: EntityType,
is_invitable: bool,
is_deletable: bool,
is_updatable: bool,
is_internal: bool,
}
impl RoleInfo {
pub fn get_role_id(&self) -> &str {
&self.role_id
}
pub fn get_role_name(&self) -> &str {
&self.role_name
}
pub fn get_permission_groups(&self) -> Vec<PermissionGroup> {
self.groups
.iter()
.flat_map(|group| group.accessible_groups())
.collect::<HashSet<_>>()
.into_iter()
.collect()
}
pub fn get_scope(&self) -> RoleScope {
self.scope
}
pub fn get_entity_type(&self) -> EntityType {
self.entity_type
}
pub fn is_invitable(&self) -> bool {
self.is_invitable
}
pub fn is_deletable(&self) -> bool {
self.is_deletable
}
pub fn is_internal(&self) -> bool {
self.is_internal
}
pub fn is_updatable(&self) -> bool {
self.is_updatable
}
pub fn get_resources_set(&self) -> HashSet<Resource> {
self.get_permission_groups()
.iter()
.flat_map(|group| group.resources())
.collect()
}
pub fn check_permission_exists(&self, required_permission: Permission) -> bool {
required_permission.entity_type() <= self.entity_type
&& self.get_permission_groups().iter().any(|group| {
required_permission.scope() <= group.scope()
&& group.resources().contains(&required_permission.resource())
})
}
#[cfg(feature = "recon")]
pub fn get_recon_acl(&self) -> HashMap<Resource, ReconPermissionScope> {
let mut acl: HashMap<Resource, ReconPermissionScope> = HashMap::new();
let mut recon_resources = RECON_OPS.to_vec();
recon_resources.extend(RECON_REPORTS);
let recon_internal_resources = [Resource::ReconToken];
self.get_permission_groups()
.iter()
.for_each(|permission_group| {
permission_group.resources().iter().for_each(|resource| {
if recon_resources.contains(resource)
&& !recon_internal_resources.contains(resource)
{
let scope = match resource {
Resource::ReconAndSettlementAnalytics => ReconPermissionScope::Read,
_ => ReconPermissionScope::from(permission_group.scope()),
};
acl.entry(*resource)
.and_modify(|curr_scope| {
*curr_scope = if (*curr_scope) < scope {
scope
} else {
*curr_scope
}
})
.or_insert(scope);
}
})
});
acl
}
pub fn from_predefined_roles(role_id: &str) -> Option<Self> {
predefined_roles::PREDEFINED_ROLES.get(role_id).cloned()
}
pub async fn from_role_id_in_lineage(
state: &SessionState,
role_id: &str,
merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
profile_id: &id_type::ProfileId,
tenant_id: &id_type::TenantId,
) -> CustomResult<Self, errors::StorageError> {
if let Some(role) = predefined_roles::PREDEFINED_ROLES.get(role_id) {
Ok(role.clone())
} else {
state
.global_store
.find_role_by_role_id_in_lineage(
role_id,
merchant_id,
org_id,
profile_id,
tenant_id,
)
.await
.map(Self::from)
}
}
// TODO: To evaluate whether we can omit org_id and tenant_id for this function
pub async fn from_role_id_org_id_tenant_id(
state: &SessionState,
role_id: &str,
org_id: &id_type::OrganizationId,
tenant_id: &id_type::TenantId,
) -> CustomResult<Self, errors::StorageError> {
if let Some(role) = predefined_roles::PREDEFINED_ROLES.get(role_id) {
Ok(role.clone())
} else {
state
.global_store
.find_by_role_id_org_id_tenant_id(role_id, org_id, tenant_id)
.await
.map(Self::from)
}
}
}
impl From<diesel_models::role::Role> for RoleInfo {
fn from(role: diesel_models::role::Role) -> Self {
Self {
role_id: role.role_id,
role_name: role.role_name,
groups: role.groups,
scope: role.scope,
entity_type: role.entity_type,
is_invitable: true,
is_deletable: true,
is_updatable: true,
is_internal: false,
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/authorization/roles/predefined_roles.rs | crates/router/src/services/authorization/roles/predefined_roles.rs | use std::{collections::HashMap, sync::LazyLock};
use common_enums::{EntityType, PermissionGroup, RoleScope};
use super::RoleInfo;
use crate::consts;
pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLock::new(|| {
let mut roles = HashMap::new();
// Internal Roles
roles.insert(
common_utils::consts::ROLE_ID_INTERNAL_ADMIN,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::OperationsManage,
PermissionGroup::ConnectorsView,
PermissionGroup::ConnectorsManage,
PermissionGroup::WorkflowsView,
PermissionGroup::WorkflowsManage,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::UsersManage,
PermissionGroup::AccountView,
PermissionGroup::AccountManage,
PermissionGroup::ReconOpsView,
PermissionGroup::ReconOpsManage,
PermissionGroup::ReconReportsView,
PermissionGroup::ReconReportsManage,
],
role_id: common_utils::consts::ROLE_ID_INTERNAL_ADMIN.to_string(),
role_name: "internal_admin".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Merchant,
is_invitable: false,
is_deletable: false,
is_updatable: false,
is_internal: true,
},
);
roles.insert(
common_utils::consts::ROLE_ID_INTERNAL_VIEW_ONLY_USER,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::ConnectorsView,
PermissionGroup::WorkflowsView,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::AccountView,
PermissionGroup::ReconOpsView,
PermissionGroup::ReconReportsView,
],
role_id: common_utils::consts::ROLE_ID_INTERNAL_VIEW_ONLY_USER.to_string(),
role_name: "internal_view_only".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Merchant,
is_invitable: false,
is_deletable: false,
is_updatable: false,
is_internal: true,
},
);
roles.insert(
common_utils::consts::ROLE_ID_INTERNAL_DEMO,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::ConnectorsView,
PermissionGroup::WorkflowsView,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::AccountView,
PermissionGroup::ReconOpsView,
PermissionGroup::ReconReportsView,
PermissionGroup::InternalManage,
],
role_id: common_utils::consts::ROLE_ID_INTERNAL_DEMO.to_string(),
role_name: "internal_demo".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Merchant,
is_invitable: false,
is_deletable: false,
is_updatable: false,
is_internal: true,
},
);
// Tenant Roles
roles.insert(
common_utils::consts::ROLE_ID_TENANT_ADMIN,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::OperationsManage,
PermissionGroup::ConnectorsView,
PermissionGroup::ConnectorsManage,
PermissionGroup::WorkflowsView,
PermissionGroup::WorkflowsManage,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::UsersManage,
PermissionGroup::AccountView,
PermissionGroup::AccountManage,
PermissionGroup::ReconOpsView,
PermissionGroup::ReconOpsManage,
PermissionGroup::ReconReportsView,
PermissionGroup::ReconReportsManage,
],
role_id: common_utils::consts::ROLE_ID_TENANT_ADMIN.to_string(),
role_name: "tenant_admin".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Tenant,
is_invitable: false,
is_deletable: false,
is_updatable: false,
is_internal: false,
},
);
// Organization Roles
roles.insert(
common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::OperationsManage,
PermissionGroup::ConnectorsView,
PermissionGroup::ConnectorsManage,
PermissionGroup::WorkflowsView,
PermissionGroup::WorkflowsManage,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::UsersManage,
PermissionGroup::AccountView,
PermissionGroup::AccountManage,
PermissionGroup::ReconOpsView,
PermissionGroup::ReconOpsManage,
PermissionGroup::ReconReportsView,
PermissionGroup::ReconReportsManage,
PermissionGroup::ThemeView,
PermissionGroup::ThemeManage,
],
role_id: common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
role_name: "organization_admin".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Organization,
is_invitable: true,
is_deletable: true,
is_updatable: true,
is_internal: false,
},
);
// MERCHANT ROLES
roles.insert(
consts::user_role::ROLE_ID_MERCHANT_ADMIN,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::OperationsManage,
PermissionGroup::ConnectorsView,
PermissionGroup::ConnectorsManage,
PermissionGroup::WorkflowsView,
PermissionGroup::WorkflowsManage,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::UsersManage,
PermissionGroup::AccountView,
PermissionGroup::AccountManage,
PermissionGroup::ReconOpsView,
PermissionGroup::ReconOpsManage,
PermissionGroup::ReconReportsView,
PermissionGroup::ReconReportsManage,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_ADMIN.to_string(),
role_name: "merchant_admin".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Merchant,
is_invitable: true,
is_deletable: true,
is_updatable: true,
is_internal: false,
},
);
roles.insert(
consts::user_role::ROLE_ID_MERCHANT_VIEW_ONLY,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::ConnectorsView,
PermissionGroup::WorkflowsView,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::AccountView,
PermissionGroup::ReconOpsView,
PermissionGroup::ReconReportsView,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_VIEW_ONLY.to_string(),
role_name: "merchant_view_only".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Merchant,
is_invitable: true,
is_deletable: true,
is_updatable: true,
is_internal: false,
},
);
roles.insert(
consts::user_role::ROLE_ID_MERCHANT_IAM_ADMIN,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::UsersManage,
PermissionGroup::AccountView,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_IAM_ADMIN.to_string(),
role_name: "merchant_iam".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Merchant,
is_invitable: true,
is_deletable: true,
is_updatable: true,
is_internal: false,
},
);
roles.insert(
consts::user_role::ROLE_ID_MERCHANT_DEVELOPER,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::ConnectorsView,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::AccountView,
PermissionGroup::AccountManage,
PermissionGroup::ReconOpsView,
PermissionGroup::ReconReportsView,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_DEVELOPER.to_string(),
role_name: "merchant_developer".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Merchant,
is_invitable: true,
is_deletable: true,
is_updatable: true,
is_internal: false,
},
);
roles.insert(
consts::user_role::ROLE_ID_MERCHANT_OPERATOR,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::OperationsManage,
PermissionGroup::ConnectorsView,
PermissionGroup::WorkflowsView,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::AccountView,
PermissionGroup::ReconOpsView,
PermissionGroup::ReconOpsManage,
PermissionGroup::ReconReportsView,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_OPERATOR.to_string(),
role_name: "merchant_operator".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Merchant,
is_invitable: true,
is_deletable: true,
is_updatable: true,
is_internal: false,
},
);
roles.insert(
consts::user_role::ROLE_ID_MERCHANT_CUSTOMER_SUPPORT,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::AccountView,
PermissionGroup::ReconOpsView,
PermissionGroup::ReconReportsView,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_CUSTOMER_SUPPORT.to_string(),
role_name: "customer_support".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Merchant,
is_invitable: true,
is_deletable: true,
is_updatable: true,
is_internal: false,
},
);
// Profile Roles
roles.insert(
consts::user_role::ROLE_ID_PROFILE_ADMIN,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::OperationsManage,
PermissionGroup::ConnectorsView,
PermissionGroup::ConnectorsManage,
PermissionGroup::WorkflowsView,
PermissionGroup::WorkflowsManage,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::UsersManage,
PermissionGroup::AccountView,
PermissionGroup::AccountManage,
],
role_id: consts::user_role::ROLE_ID_PROFILE_ADMIN.to_string(),
role_name: "profile_admin".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Profile,
is_invitable: true,
is_deletable: true,
is_updatable: true,
is_internal: false,
},
);
roles.insert(
consts::user_role::ROLE_ID_PROFILE_VIEW_ONLY,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::ConnectorsView,
PermissionGroup::WorkflowsView,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::AccountView,
],
role_id: consts::user_role::ROLE_ID_PROFILE_VIEW_ONLY.to_string(),
role_name: "profile_view_only".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Profile,
is_invitable: true,
is_deletable: true,
is_updatable: true,
is_internal: false,
},
);
roles.insert(
consts::user_role::ROLE_ID_PROFILE_IAM_ADMIN,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::UsersManage,
PermissionGroup::AccountView,
],
role_id: consts::user_role::ROLE_ID_PROFILE_IAM_ADMIN.to_string(),
role_name: "profile_iam".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Profile,
is_invitable: true,
is_deletable: true,
is_updatable: true,
is_internal: false,
},
);
roles.insert(
consts::user_role::ROLE_ID_PROFILE_DEVELOPER,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::ConnectorsView,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::AccountView,
PermissionGroup::AccountManage,
],
role_id: consts::user_role::ROLE_ID_PROFILE_DEVELOPER.to_string(),
role_name: "profile_developer".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Profile,
is_invitable: true,
is_deletable: true,
is_updatable: true,
is_internal: false,
},
);
roles.insert(
consts::user_role::ROLE_ID_PROFILE_OPERATOR,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::OperationsManage,
PermissionGroup::ConnectorsView,
PermissionGroup::WorkflowsView,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::AccountView,
],
role_id: consts::user_role::ROLE_ID_PROFILE_OPERATOR.to_string(),
role_name: "profile_operator".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Profile,
is_invitable: true,
is_deletable: true,
is_updatable: true,
is_internal: false,
},
);
roles.insert(
consts::user_role::ROLE_ID_PROFILE_CUSTOMER_SUPPORT,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::AccountView,
],
role_id: consts::user_role::ROLE_ID_PROFILE_CUSTOMER_SUPPORT.to_string(),
role_name: "profile_customer_support".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Profile,
is_invitable: true,
is_deletable: true,
is_updatable: true,
is_internal: false,
},
);
roles
});
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/authentication/detached.rs | crates/router/src/services/authentication/detached.rs | use std::{borrow::Cow, string::ToString};
use actix_web::http::header::HeaderMap;
use common_utils::{
crypto::VerifySignature,
id_type::{ApiKeyId, MerchantId},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse;
use crate::core::errors::RouterResult;
const HEADER_AUTH_TYPE: &str = "x-auth-type";
const HEADER_MERCHANT_ID: &str = "x-merchant-id";
const HEADER_KEY_ID: &str = "x-key-id";
const HEADER_CHECKSUM: &str = "x-checksum";
#[derive(Debug)]
pub struct ExtractedPayload {
pub payload_type: PayloadType,
pub merchant_id: Option<MerchantId>,
pub key_id: Option<ApiKeyId>,
}
#[derive(strum::EnumString, strum::Display, PartialEq, Debug)]
#[strum(serialize_all = "snake_case")]
pub enum PayloadType {
ApiKey,
PublishableKey,
}
pub trait GetAuthType {
fn get_auth_type(&self) -> PayloadType;
}
impl ExtractedPayload {
pub fn from_headers(headers: &HeaderMap) -> RouterResult<Self> {
let merchant_id = headers
.get(HEADER_MERCHANT_ID)
.and_then(|value| value.to_str().ok())
.ok_or_else(|| ApiErrorResponse::InvalidRequestData {
message: format!("`{HEADER_MERCHANT_ID}` header is invalid or not present"),
})
.map_err(error_stack::Report::from)
.and_then(|merchant_id| {
MerchantId::try_from(Cow::from(merchant_id.to_string())).change_context(
ApiErrorResponse::InvalidRequestData {
message: format!(
"`{HEADER_MERCHANT_ID}` header is invalid or not present",
),
},
)
})?;
let auth_type: PayloadType = headers
.get(HEADER_AUTH_TYPE)
.and_then(|inner| inner.to_str().ok())
.ok_or_else(|| ApiErrorResponse::InvalidRequestData {
message: format!("`{HEADER_AUTH_TYPE}` header not present"),
})?
.parse::<PayloadType>()
.change_context(ApiErrorResponse::InvalidRequestData {
message: format!("`{HEADER_AUTH_TYPE}` header not present"),
})?;
let key_id = headers
.get(HEADER_KEY_ID)
.and_then(|value| value.to_str().ok())
.map(|key_id| ApiKeyId::try_from(Cow::from(key_id.to_string())))
.transpose()
.change_context(ApiErrorResponse::InvalidRequestData {
message: format!("`{HEADER_KEY_ID}` header is invalid or not present"),
})?;
Ok(Self {
payload_type: auth_type,
merchant_id: Some(merchant_id),
key_id,
})
}
pub fn verify_checksum(
&self,
headers: &HeaderMap,
algo: impl VerifySignature,
secret: &[u8],
) -> bool {
let output = || {
let checksum = headers.get(HEADER_CHECKSUM)?.to_str().ok()?;
let payload = self.generate_payload();
algo.verify_signature(secret, &hex::decode(checksum).ok()?, payload.as_bytes())
.ok()
};
output().unwrap_or(false)
}
// The payload should be `:` separated strings of all the fields
fn generate_payload(&self) -> String {
append_option(
&self.payload_type.to_string(),
&self
.merchant_id
.as_ref()
.map(|inner| append_api_key(inner.get_string_repr(), &self.key_id)),
)
}
}
#[inline]
fn append_option(prefix: &str, data: &Option<String>) -> String {
match data {
Some(inner) => format!("{prefix}:{inner}"),
None => prefix.to_string(),
}
}
#[inline]
fn append_api_key(prefix: &str, data: &Option<ApiKeyId>) -> String {
match data {
Some(inner) => format!("{}:{}", prefix, inner.get_string_repr()),
None => prefix.to_string(),
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/authentication/cookies.rs | crates/router/src/services/authentication/cookies.rs | use cookie::Cookie;
#[cfg(feature = "olap")]
use cookie::{
time::{Duration, OffsetDateTime},
SameSite,
};
use error_stack::{report, ResultExt};
#[cfg(feature = "olap")]
use masking::Mask;
#[cfg(feature = "olap")]
use masking::{ExposeInterface, Secret};
use crate::{
consts::JWT_TOKEN_COOKIE_NAME,
core::errors::{ApiErrorResponse, RouterResult},
};
#[cfg(feature = "olap")]
use crate::{
consts::JWT_TOKEN_TIME_IN_SECS,
core::errors::{UserErrors, UserResponse},
services::ApplicationResponse,
};
#[cfg(feature = "olap")]
pub fn set_cookie_response<R>(response: R, token: Secret<String>) -> UserResponse<R> {
let jwt_expiry_in_seconds = JWT_TOKEN_TIME_IN_SECS
.try_into()
.map_err(|_| UserErrors::InternalServerError)?;
let (expiry, max_age) = get_expiry_and_max_age_from_seconds(jwt_expiry_in_seconds);
let header_value = create_cookie(token, expiry, max_age)
.to_string()
.into_masked();
let header_key = get_set_cookie_header();
let header = vec![(header_key, header_value)];
Ok(ApplicationResponse::JsonWithHeaders((response, header)))
}
#[cfg(feature = "olap")]
pub fn remove_cookie_response() -> UserResponse<()> {
let (expiry, max_age) = get_expiry_and_max_age_from_seconds(0);
let header_key = get_set_cookie_header();
let header_value = create_cookie("".to_string().into(), expiry, max_age)
.to_string()
.into_masked();
let header = vec![(header_key, header_value)];
Ok(ApplicationResponse::JsonWithHeaders(((), header)))
}
pub fn get_jwt_from_cookies(cookies: &str) -> RouterResult<String> {
Cookie::split_parse(cookies)
.find_map(|cookie| {
cookie
.ok()
.filter(|parsed_cookie| parsed_cookie.name() == JWT_TOKEN_COOKIE_NAME)
.map(|parsed_cookie| parsed_cookie.value().to_owned())
})
.ok_or(report!(ApiErrorResponse::InvalidJwtToken))
.attach_printable("Unable to find JWT token in cookies")
}
#[cfg(feature = "olap")]
fn create_cookie<'c>(
token: Secret<String>,
expires: OffsetDateTime,
max_age: Duration,
) -> Cookie<'c> {
Cookie::build((JWT_TOKEN_COOKIE_NAME, token.expose()))
.http_only(true)
.secure(true)
.same_site(SameSite::Strict)
.path("/")
.expires(expires)
.max_age(max_age)
.build()
}
#[cfg(feature = "olap")]
fn get_expiry_and_max_age_from_seconds(seconds: i64) -> (OffsetDateTime, Duration) {
let max_age = Duration::seconds(seconds);
let expiry = OffsetDateTime::now_utc().saturating_add(max_age);
(expiry, max_age)
}
#[cfg(feature = "olap")]
fn get_set_cookie_header() -> String {
actix_http::header::SET_COOKIE.to_string()
}
pub fn get_cookie_header() -> String {
actix_http::header::COOKIE.to_string()
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/authentication/decision.rs | crates/router/src/services/authentication/decision.rs | use common_utils::{errors::CustomResult, request::RequestContent};
use masking::{ErasedMaskSerialize, Secret};
use serde::Serialize;
use storage_impl::errors::ApiClientError;
use crate::{
core::metrics,
routes::{app::settings::DecisionConfig, SessionState},
};
// # Consts
//
const DECISION_ENDPOINT: &str = "/rule";
const RULE_ADD_METHOD: common_utils::request::Method = common_utils::request::Method::Post;
const RULE_DELETE_METHOD: common_utils::request::Method = common_utils::request::Method::Delete;
pub const REVOKE: &str = "REVOKE";
pub const ADD: &str = "ADD";
// # Types
//
/// [`RuleRequest`] is a request body used to register a new authentication method in the proxy.
#[derive(Debug, Serialize)]
pub struct RuleRequest {
/// [`tag`] similar to a partition key, which can be used by the decision service to tag rules
/// by partitioning identifiers. (e.g. `tenant_id`)
pub tag: String,
/// [`variant`] is the type of authentication method to be registered.
#[serde(flatten)]
pub variant: AuthRuleType,
/// [`expiry`] is the time **in seconds** after which the rule should be removed
pub expiry: Option<u64>,
}
#[derive(Debug, Serialize)]
pub struct RuleDeleteRequest {
pub tag: String,
#[serde(flatten)]
pub variant: AuthType,
}
#[derive(Debug, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum AuthType {
/// [`ApiKey`] is an authentication method that uses an API key. This is used with [`ApiKey`]
ApiKey { api_key: Secret<String> },
}
#[derive(Debug, Serialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum AuthRuleType {
/// [`ApiKey`] is an authentication method that uses an API key. This is used with [`ApiKey`]
/// and [`PublishableKey`] authentication methods.
ApiKey {
api_key: Secret<String>,
identifiers: Identifiers,
},
}
#[allow(clippy::enum_variant_names)]
#[derive(Debug, Serialize, Clone)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Identifiers {
/// [`ApiKey`] is an authentication method that uses an API key. This is used with [`ApiKey`]
ApiKey {
merchant_id: common_utils::id_type::MerchantId,
key_id: common_utils::id_type::ApiKeyId,
},
/// [`PublishableKey`] is an authentication method that uses a publishable key. This is used with [`PublishableKey`]
PublishableKey { merchant_id: String },
}
// # Decision Service
//
pub async fn add_api_key(
state: &SessionState,
api_key: Secret<String>,
merchant_id: common_utils::id_type::MerchantId,
key_id: common_utils::id_type::ApiKeyId,
expiry: Option<u64>,
) -> CustomResult<(), ApiClientError> {
let decision_config = if let Some(config) = &state.conf.decision {
config
} else {
return Ok(());
};
let rule = RuleRequest {
tag: state.tenant.schema.clone(),
expiry,
variant: AuthRuleType::ApiKey {
api_key,
identifiers: Identifiers::ApiKey {
merchant_id,
key_id,
},
},
};
call_decision_service(state, decision_config, rule, RULE_ADD_METHOD).await
}
pub async fn add_publishable_key(
state: &SessionState,
api_key: Secret<String>,
merchant_id: common_utils::id_type::MerchantId,
expiry: Option<u64>,
) -> CustomResult<(), ApiClientError> {
let decision_config = if let Some(config) = &state.conf.decision {
config
} else {
return Ok(());
};
let rule = RuleRequest {
tag: state.tenant.schema.clone(),
expiry,
variant: AuthRuleType::ApiKey {
api_key,
identifiers: Identifiers::PublishableKey {
merchant_id: merchant_id.get_string_repr().to_owned(),
},
},
};
call_decision_service(state, decision_config, rule, RULE_ADD_METHOD).await
}
async fn call_decision_service<T: ErasedMaskSerialize + Send + 'static>(
state: &SessionState,
decision_config: &DecisionConfig,
rule: T,
method: common_utils::request::Method,
) -> CustomResult<(), ApiClientError> {
let mut request = common_utils::request::Request::new(
method,
&(decision_config.base_url.clone() + DECISION_ENDPOINT),
);
request.set_body(RequestContent::Json(Box::new(rule)));
request.add_default_headers();
let response = state
.api_client
.send_request(state, request, None, false)
.await;
match response {
Err(error) => {
router_env::error!("Failed while calling the decision service: {:?}", error);
Err(error)
}
Ok(response) => {
router_env::info!("Decision service response: {:?}", response);
Ok(())
}
}
}
pub async fn revoke_api_key(
state: &SessionState,
api_key: Secret<String>,
) -> CustomResult<(), ApiClientError> {
let decision_config = if let Some(config) = &state.conf.decision {
config
} else {
return Ok(());
};
let rule = RuleDeleteRequest {
tag: state.tenant.schema.clone(),
variant: AuthType::ApiKey { api_key },
};
call_decision_service(state, decision_config, rule, RULE_DELETE_METHOD).await
}
/// Safety: i64::MAX < u64::MAX
#[allow(clippy::as_conversions)]
pub fn convert_expiry(expiry: time::PrimitiveDateTime) -> u64 {
let now = common_utils::date_time::now();
let duration = expiry - now;
let output = duration.whole_seconds();
match output {
i64::MIN..=0 => 0,
_ => output as u64,
}
}
pub fn spawn_tracked_job<E, F>(future: F, request_type: &'static str)
where
E: std::fmt::Debug,
F: futures::Future<Output = Result<(), E>> + Send + 'static,
{
metrics::API_KEY_REQUEST_INITIATED
.add(1, router_env::metric_attributes!(("type", request_type)));
tokio::spawn(async move {
match future.await {
Ok(_) => {
metrics::API_KEY_REQUEST_COMPLETED
.add(1, router_env::metric_attributes!(("type", request_type)));
}
Err(e) => {
router_env::error!("Error in tracked job: {:?}", e);
}
}
});
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/authentication/blacklist.rs | crates/router/src/services/authentication/blacklist.rs | use std::sync::Arc;
#[cfg(feature = "olap")]
use common_utils::date_time;
use error_stack::ResultExt;
use redis_interface::RedisConnectionPool;
use super::AuthToken;
#[cfg(feature = "olap")]
use super::{SinglePurposeOrLoginToken, SinglePurposeToken};
#[cfg(feature = "email")]
use crate::consts::{EMAIL_TOKEN_BLACKLIST_PREFIX, EMAIL_TOKEN_TIME_IN_SECS};
use crate::{
consts::{JWT_TOKEN_TIME_IN_SECS, ROLE_BLACKLIST_PREFIX, USER_BLACKLIST_PREFIX},
core::errors::{ApiErrorResponse, RouterResult},
routes::app::SessionStateInfo,
};
#[cfg(feature = "olap")]
use crate::{
core::errors::{UserErrors, UserResult},
routes::SessionState,
services::authorization as authz,
};
#[cfg(feature = "olap")]
pub async fn insert_user_in_blacklist(state: &SessionState, user_id: &str) -> UserResult<()> {
let user_blacklist_key = format!("{USER_BLACKLIST_PREFIX}{user_id}");
let expiry =
expiry_to_i64(JWT_TOKEN_TIME_IN_SECS).change_context(UserErrors::InternalServerError)?;
let redis_conn = get_redis_connection_for_global_tenant(state)
.change_context(UserErrors::InternalServerError)?;
redis_conn
.set_key_with_expiry(
&user_blacklist_key.as_str().into(),
date_time::now_unix_timestamp(),
expiry,
)
.await
.change_context(UserErrors::InternalServerError)
}
#[cfg(feature = "olap")]
pub async fn insert_role_in_blacklist(state: &SessionState, role_id: &str) -> UserResult<()> {
let role_blacklist_key = format!("{ROLE_BLACKLIST_PREFIX}{role_id}");
let expiry =
expiry_to_i64(JWT_TOKEN_TIME_IN_SECS).change_context(UserErrors::InternalServerError)?;
let redis_conn = get_redis_connection_for_global_tenant(state)
.change_context(UserErrors::InternalServerError)?;
redis_conn
.set_key_with_expiry(
&role_blacklist_key.as_str().into(),
date_time::now_unix_timestamp(),
expiry,
)
.await
.change_context(UserErrors::InternalServerError)?;
invalidate_role_cache(state, role_id)
.await
.change_context(UserErrors::InternalServerError)
}
#[cfg(feature = "olap")]
async fn invalidate_role_cache(state: &SessionState, role_id: &str) -> RouterResult<()> {
let redis_conn = get_redis_connection_for_global_tenant(state)?;
redis_conn
.delete_key(&authz::get_cache_key_from_role_id(role_id).as_str().into())
.await
.map(|_| ())
.change_context(ApiErrorResponse::InternalServerError)
}
pub async fn check_user_in_blacklist<A: SessionStateInfo>(
state: &A,
user_id: &str,
token_expiry: u64,
) -> RouterResult<bool> {
let token = format!("{USER_BLACKLIST_PREFIX}{user_id}");
let token_issued_at = expiry_to_i64(token_expiry - JWT_TOKEN_TIME_IN_SECS)?;
let redis_conn = get_redis_connection_for_global_tenant(state)?;
redis_conn
.get_key::<Option<i64>>(&token.as_str().into())
.await
.change_context(ApiErrorResponse::InternalServerError)
.map(|timestamp| timestamp > Some(token_issued_at))
}
pub async fn check_role_in_blacklist<A: SessionStateInfo>(
state: &A,
role_id: &str,
token_expiry: u64,
) -> RouterResult<bool> {
let token = format!("{ROLE_BLACKLIST_PREFIX}{role_id}");
let token_issued_at = expiry_to_i64(token_expiry - JWT_TOKEN_TIME_IN_SECS)?;
let redis_conn = get_redis_connection_for_global_tenant(state)?;
redis_conn
.get_key::<Option<i64>>(&token.as_str().into())
.await
.change_context(ApiErrorResponse::InternalServerError)
.map(|timestamp| timestamp > Some(token_issued_at))
}
#[cfg(feature = "email")]
pub async fn insert_email_token_in_blacklist(state: &SessionState, token: &str) -> UserResult<()> {
let redis_conn = get_redis_connection_for_global_tenant(state)
.change_context(UserErrors::InternalServerError)?;
let blacklist_key = format!("{EMAIL_TOKEN_BLACKLIST_PREFIX}{token}");
let expiry =
expiry_to_i64(EMAIL_TOKEN_TIME_IN_SECS).change_context(UserErrors::InternalServerError)?;
redis_conn
.set_key_with_expiry(&blacklist_key.as_str().into(), true, expiry)
.await
.change_context(UserErrors::InternalServerError)
}
#[cfg(feature = "email")]
pub async fn check_email_token_in_blacklist(state: &SessionState, token: &str) -> UserResult<()> {
let redis_conn = get_redis_connection_for_global_tenant(state)
.change_context(UserErrors::InternalServerError)?;
let blacklist_key = format!("{EMAIL_TOKEN_BLACKLIST_PREFIX}{token}");
let key_exists = redis_conn
.exists::<()>(&blacklist_key.as_str().into())
.await
.change_context(UserErrors::InternalServerError)?;
if key_exists {
return Err(UserErrors::LinkInvalid.into());
}
Ok(())
}
fn get_redis_connection_for_global_tenant<A: SessionStateInfo>(
state: &A,
) -> RouterResult<Arc<RedisConnectionPool>> {
state
.global_store()
.get_redis_conn()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")
}
fn expiry_to_i64(expiry: u64) -> RouterResult<i64> {
i64::try_from(expiry).change_context(ApiErrorResponse::InternalServerError)
}
#[async_trait::async_trait]
pub trait BlackList {
async fn check_in_blacklist<A>(&self, state: &A) -> RouterResult<bool>
where
A: SessionStateInfo + Sync;
}
#[async_trait::async_trait]
impl BlackList for AuthToken {
async fn check_in_blacklist<A>(&self, state: &A) -> RouterResult<bool>
where
A: SessionStateInfo + Sync,
{
Ok(
check_user_in_blacklist(state, &self.user_id, self.exp).await?
|| check_role_in_blacklist(state, &self.role_id, self.exp).await?,
)
}
}
#[cfg(feature = "olap")]
#[async_trait::async_trait]
impl BlackList for SinglePurposeToken {
async fn check_in_blacklist<A>(&self, state: &A) -> RouterResult<bool>
where
A: SessionStateInfo + Sync,
{
check_user_in_blacklist(state, &self.user_id, self.exp).await
}
}
#[cfg(feature = "olap")]
#[async_trait::async_trait]
impl BlackList for SinglePurposeOrLoginToken {
async fn check_in_blacklist<A>(&self, state: &A) -> RouterResult<bool>
where
A: SessionStateInfo + Sync,
{
check_user_in_blacklist(state, &self.user_id, self.exp).await
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/api/client.rs | crates/router/src/services/api/client.rs | use std::time::Duration;
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
pub use external_services::http_client::{self, client};
use http::{HeaderValue, Method};
pub use hyperswitch_interfaces::{
api_client::{ApiClient, ApiClientWrapper, RequestBuilder},
types::Proxy,
};
use masking::PeekInterface;
use reqwest::multipart::Form;
use router_env::RequestId;
use super::{request::Maskable, Request};
use crate::core::errors::{ApiClientError, CustomResult};
#[derive(Clone)]
pub struct ProxyClient {
proxy_config: Proxy,
client: reqwest::Client,
request_id: Option<RequestId>,
}
impl ProxyClient {
pub fn new(proxy_config: &Proxy) -> CustomResult<Self, ApiClientError> {
let client = client::get_client_builder(proxy_config)
.switch()?
.build()
.change_context(ApiClientError::InvalidProxyConfiguration)?;
Ok(Self {
proxy_config: proxy_config.clone(),
client,
request_id: None,
})
}
pub fn get_reqwest_client(
&self,
client_certificate: Option<masking::Secret<String>>,
client_certificate_key: Option<masking::Secret<String>>,
) -> CustomResult<reqwest::Client, ApiClientError> {
match (client_certificate, client_certificate_key) {
(Some(certificate), Some(certificate_key)) => {
let client_builder = client::get_client_builder(&self.proxy_config).switch()?;
let identity =
client::create_identity_from_certificate_and_key(certificate, certificate_key)
.switch()?;
Ok(client_builder
.identity(identity)
.build()
.change_context(ApiClientError::ClientConstructionFailed)
.attach_printable(
"Failed to construct client with certificate and certificate key",
)?)
}
(_, _) => Ok(self.client.clone()),
}
}
}
pub struct RouterRequestBuilder {
// Using option here to get around the reinitialization problem
// request builder follows a chain pattern where the value is consumed and a newer requestbuilder is returned
// Since for this brief period of time between the value being consumed & newer request builder
// since requestbuilder does not allow moving the value
// leaves our struct in an inconsistent state, we are using option to get around rust semantics
inner: Option<reqwest::RequestBuilder>,
}
impl RequestBuilder for RouterRequestBuilder {
fn json(&mut self, body: serde_json::Value) {
self.inner = self.inner.take().map(|r| r.json(&body));
}
fn url_encoded_form(&mut self, body: serde_json::Value) {
self.inner = self.inner.take().map(|r| r.form(&body));
}
fn timeout(&mut self, timeout: Duration) {
self.inner = self.inner.take().map(|r| r.timeout(timeout));
}
fn multipart(&mut self, form: Form) {
self.inner = self.inner.take().map(|r| r.multipart(form));
}
fn header(&mut self, key: String, value: Maskable<String>) -> CustomResult<(), ApiClientError> {
let header_value = match value {
Maskable::Masked(hvalue) => HeaderValue::from_str(hvalue.peek()).map(|mut h| {
h.set_sensitive(true);
h
}),
Maskable::Normal(hvalue) => HeaderValue::from_str(&hvalue),
}
.change_context(ApiClientError::HeaderMapConstructionFailed)?;
self.inner = self.inner.take().map(|r| r.header(key, header_value));
Ok(())
}
fn send(
self,
) -> CustomResult<
Box<dyn core::future::Future<Output = Result<reqwest::Response, reqwest::Error>> + 'static>,
ApiClientError,
> {
Ok(Box::new(
self.inner.ok_or(ApiClientError::UnexpectedState)?.send(),
))
}
}
#[async_trait::async_trait]
impl ApiClient for ProxyClient {
fn request(
&self,
method: Method,
url: String,
) -> CustomResult<Box<dyn RequestBuilder>, ApiClientError> {
self.request_with_certificate(method, url, None, None)
}
fn request_with_certificate(
&self,
method: Method,
url: String,
certificate: Option<masking::Secret<String>>,
certificate_key: Option<masking::Secret<String>>,
) -> CustomResult<Box<dyn RequestBuilder>, ApiClientError> {
let client_builder = self
.get_reqwest_client(certificate, certificate_key)
.change_context(ApiClientError::ClientConstructionFailed)?;
Ok(Box::new(RouterRequestBuilder {
inner: Some(client_builder.request(method, url)),
}))
}
async fn send_request(
&self,
api_client: &dyn ApiClientWrapper,
request: Request,
option_timeout_secs: Option<u64>,
_forward_to_kafka: bool,
) -> CustomResult<reqwest::Response, ApiClientError> {
http_client::send_request(&api_client.get_proxy(), request, option_timeout_secs)
.await
.switch()
}
fn add_request_id(&mut self, request_id: RequestId) {
self.request_id = Some(request_id);
}
fn get_request_id(&self) -> Option<RequestId> {
self.request_id.clone()
}
fn get_request_id_str(&self) -> Option<String> {
self.request_id.as_ref().map(|id| id.to_string())
}
fn add_flow_name(&mut self, _flow_name: String) {}
}
/// Api client for testing sending request
#[derive(Clone)]
pub struct MockApiClient;
#[async_trait::async_trait]
impl ApiClient for MockApiClient {
fn request(
&self,
_method: Method,
_url: String,
) -> CustomResult<Box<dyn RequestBuilder>, ApiClientError> {
// [#2066]: Add Mock implementation for ApiClient
Err(ApiClientError::UnexpectedState.into())
}
fn request_with_certificate(
&self,
_method: Method,
_url: String,
_certificate: Option<masking::Secret<String>>,
_certificate_key: Option<masking::Secret<String>>,
) -> CustomResult<Box<dyn RequestBuilder>, ApiClientError> {
// [#2066]: Add Mock implementation for ApiClient
Err(ApiClientError::UnexpectedState.into())
}
async fn send_request(
&self,
_state: &dyn ApiClientWrapper,
_request: Request,
_option_timeout_secs: Option<u64>,
_forward_to_kafka: bool,
) -> CustomResult<reqwest::Response, ApiClientError> {
// [#2066]: Add Mock implementation for ApiClient
Err(ApiClientError::UnexpectedState.into())
}
fn add_request_id(&mut self, _request_id: RequestId) {
// [#2066]: Add Mock implementation for ApiClient
}
fn get_request_id(&self) -> Option<RequestId> {
// [#2066]: Add Mock implementation for ApiClient
None
}
fn get_request_id_str(&self) -> Option<String> {
// [#2066]: Add Mock implementation for ApiClient
None
}
fn add_flow_name(&mut self, _flow_name: String) {}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/api/request.rs | crates/router/src/services/api/request.rs | pub use common_utils::request::ContentType;
pub use masking::{Mask, Maskable};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/api/generic_link_response.rs | crates/router/src/services/api/generic_link_response.rs | use common_utils::errors::CustomResult;
use error_stack::ResultExt;
use hyperswitch_domain_models::api::{
GenericExpiredLinkData, GenericLinkFormData, GenericLinkStatusData, GenericLinksData,
};
use tera::{Context, Tera};
use super::build_secure_payment_link_html;
use crate::core::errors;
pub mod context;
pub fn build_generic_link_html(
boxed_generic_link_data: GenericLinksData,
locale: String,
) -> CustomResult<String, errors::ApiErrorResponse> {
match boxed_generic_link_data {
GenericLinksData::ExpiredLink(link_data) => build_generic_expired_link_html(&link_data),
GenericLinksData::PaymentMethodCollect(pm_collect_data) => {
build_pm_collect_link_html(&pm_collect_data)
}
GenericLinksData::PaymentMethodCollectStatus(pm_collect_data) => {
build_pm_collect_link_status_html(&pm_collect_data)
}
GenericLinksData::PayoutLink(payout_link_data) => {
build_payout_link_html(&payout_link_data, locale.as_str())
}
GenericLinksData::PayoutLinkStatus(pm_collect_data) => {
build_payout_link_status_html(&pm_collect_data, locale.as_str())
}
GenericLinksData::SecurePaymentLink(payment_link_data) => {
build_secure_payment_link_html(payment_link_data)
}
}
}
pub fn build_generic_expired_link_html(
link_data: &GenericExpiredLinkData,
) -> CustomResult<String, errors::ApiErrorResponse> {
let mut tera = Tera::default();
let mut context = Context::new();
// Build HTML
let html_template = include_str!("../../core/generic_link/expired_link/index.html").to_string();
let _ = tera.add_raw_template("generic_expired_link", &html_template);
context.insert("title", &link_data.title);
context.insert("message", &link_data.message);
context.insert("theme", &link_data.theme);
tera.render("generic_expired_link", &context)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to render expired link HTML template")
}
fn build_html_template(
link_data: &GenericLinkFormData,
document: &'static str,
styles: &'static str,
) -> CustomResult<(Tera, Context), errors::ApiErrorResponse> {
let mut tera: Tera = Tera::default();
let mut context = Context::new();
// Insert dynamic context in CSS
let css_dynamic_context = "{{ color_scheme }}";
let css_template = styles.to_string();
let final_css = format!("{css_dynamic_context}\n{css_template}");
let _ = tera.add_raw_template("document_styles", &final_css);
context.insert("color_scheme", &link_data.css_data);
let css_style_tag = tera
.render("document_styles", &context)
.map(|css| format!("<style>{css}</style>"))
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to render CSS template")?;
// Insert HTML context
let html_template = document.to_string();
let _ = tera.add_raw_template("html_template", &html_template);
context.insert("css_style_tag", &css_style_tag);
Ok((tera, context))
}
pub fn build_payout_link_html(
link_data: &GenericLinkFormData,
locale: &str,
) -> CustomResult<String, errors::ApiErrorResponse> {
let document = include_str!("../../core/generic_link/payout_link/initiate/index.html");
let styles = include_str!("../../core/generic_link/payout_link/initiate/styles.css");
let (mut tera, mut context) = build_html_template(link_data, document, styles)
.attach_printable("Failed to build context for payout link's HTML template")?;
// Insert dynamic context in JS
let script = include_str!("../../core/generic_link/payout_link/initiate/script.js");
let js_template = script.to_string();
let js_dynamic_context = "{{ script_data }}";
let final_js = format!("{js_dynamic_context}\n{js_template}");
let _ = tera.add_raw_template("document_scripts", &final_js);
context.insert("script_data", &link_data.js_data);
context::insert_locales_in_context_for_payout_link(&mut context, locale);
let js_script_tag = tera
.render("document_scripts", &context)
.map(|js| format!("<script>{js}</script>"))
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to render JS template")?;
context.insert("js_script_tag", &js_script_tag);
context.insert(
"hyper_sdk_loader_script_tag",
&format!(
r#"<script src="{}" onload="initializePayoutSDK()"></script>"#,
link_data.sdk_url
),
);
// Render HTML template
tera.render("html_template", &context)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to render payout link's HTML template")
}
pub fn build_pm_collect_link_html(
link_data: &GenericLinkFormData,
) -> CustomResult<String, errors::ApiErrorResponse> {
let document =
include_str!("../../core/generic_link/payment_method_collect/initiate/index.html");
let styles = include_str!("../../core/generic_link/payment_method_collect/initiate/styles.css");
let (mut tera, mut context) = build_html_template(link_data, document, styles)
.attach_printable(
"Failed to build context for payment method collect link's HTML template",
)?;
// Insert dynamic context in JS
let script = include_str!("../../core/generic_link/payment_method_collect/initiate/script.js");
let js_template = script.to_string();
let js_dynamic_context = "{{ script_data }}";
let final_js = format!("{js_dynamic_context}\n{js_template}");
let _ = tera.add_raw_template("document_scripts", &final_js);
context.insert("script_data", &link_data.js_data);
let js_script_tag = tera
.render("document_scripts", &context)
.map(|js| format!("<script>{js}</script>"))
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to render JS template")?;
context.insert("js_script_tag", &js_script_tag);
context.insert(
"hyper_sdk_loader_script_tag",
&format!(
r#"<script src="{}" onload="initializeCollectSDK()"></script>"#,
link_data.sdk_url
),
);
// Render HTML template
tera.render("html_template", &context)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to render payment method collect link's HTML template")
}
pub fn build_payout_link_status_html(
link_data: &GenericLinkStatusData,
locale: &str,
) -> CustomResult<String, errors::ApiErrorResponse> {
let mut tera = Tera::default();
let mut context = Context::new();
// Insert dynamic context in CSS
let css_dynamic_context = "{{ color_scheme }}";
let css_template =
include_str!("../../core/generic_link/payout_link/status/styles.css").to_string();
let final_css = format!("{css_dynamic_context}\n{css_template}");
let _ = tera.add_raw_template("payout_link_status_styles", &final_css);
context.insert("color_scheme", &link_data.css_data);
let css_style_tag = tera
.render("payout_link_status_styles", &context)
.map(|css| format!("<style>{css}</style>"))
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to render payout link status CSS template")?;
// Insert dynamic context in JS
let js_dynamic_context = "{{ script_data }}";
let js_template =
include_str!("../../core/generic_link/payout_link/status/script.js").to_string();
let final_js = format!("{js_dynamic_context}\n{js_template}");
let _ = tera.add_raw_template("payout_link_status_script", &final_js);
context.insert("script_data", &link_data.js_data);
context::insert_locales_in_context_for_payout_link_status(&mut context, locale);
let js_script_tag = tera
.render("payout_link_status_script", &context)
.map(|js| format!("<script>{js}</script>"))
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to render payout link status JS template")?;
// Build HTML
let html_template =
include_str!("../../core/generic_link/payout_link/status/index.html").to_string();
let _ = tera.add_raw_template("payout_status_link", &html_template);
context.insert("css_style_tag", &css_style_tag);
context.insert("js_script_tag", &js_script_tag);
tera.render("payout_status_link", &context)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to render payout link status HTML template")
}
pub fn build_pm_collect_link_status_html(
link_data: &GenericLinkStatusData,
) -> CustomResult<String, errors::ApiErrorResponse> {
let mut tera = Tera::default();
let mut context = Context::new();
// Insert dynamic context in CSS
let css_dynamic_context = "{{ color_scheme }}";
let css_template =
include_str!("../../core/generic_link/payment_method_collect/status/styles.css")
.to_string();
let final_css = format!("{css_dynamic_context}\n{css_template}");
let _ = tera.add_raw_template("pm_collect_link_status_styles", &final_css);
context.insert("color_scheme", &link_data.css_data);
let css_style_tag = tera
.render("pm_collect_link_status_styles", &context)
.map(|css| format!("<style>{css}</style>"))
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to render payment method collect link status CSS template")?;
// Insert dynamic context in JS
let js_dynamic_context = "{{ collect_link_status_context }}";
let js_template =
include_str!("../../core/generic_link/payment_method_collect/status/script.js").to_string();
let final_js = format!("{js_dynamic_context}\n{js_template}");
let _ = tera.add_raw_template("pm_collect_link_status_script", &final_js);
context.insert("collect_link_status_context", &link_data.js_data);
let js_script_tag = tera
.render("pm_collect_link_status_script", &context)
.map(|js| format!("<script>{js}</script>"))
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to render payment method collect link status JS template")?;
// Build HTML
let html_template =
include_str!("../../core/generic_link/payment_method_collect/status/index.html")
.to_string();
let _ = tera.add_raw_template("payment_method_collect_status_link", &html_template);
context.insert("css_style_tag", &css_style_tag);
context.insert("js_script_tag", &js_script_tag);
tera.render("payment_method_collect_status_link", &context)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to render payment method collect link status HTML template")
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/api/generic_link_response/context.rs | crates/router/src/services/api/generic_link_response/context.rs | use common_utils::consts::DEFAULT_LOCALE;
use rust_i18n::t;
use tera::Context;
fn get_language(locale_str: &str) -> String {
let lowercase_str = locale_str.to_lowercase();
let primary_locale = lowercase_str.split(',').next().unwrap_or("").trim();
if primary_locale.is_empty() {
return DEFAULT_LOCALE.to_string();
}
let parts = primary_locale.split('-').collect::<Vec<&str>>();
let language = *parts.first().unwrap_or(&DEFAULT_LOCALE);
let country = parts.get(1).copied();
match (language, country) {
("en", Some("gb")) => "en_gb".to_string(),
("fr", Some("be")) => "fr_be".to_string(),
(lang, _) => lang.to_string(),
}
}
pub fn insert_locales_in_context_for_payout_link(context: &mut Context, locale: &str) {
let language = get_language(locale);
let locale = language.as_str();
let i18n_payout_link_title = t!("payout_link.initiate.title", locale = locale);
let i18n_january = t!("months.january", locale = locale);
let i18n_february = t!("months.february", locale = locale);
let i18n_march = t!("months.march", locale = locale);
let i18n_april = t!("months.april", locale = locale);
let i18n_may = t!("months.may", locale = locale);
let i18n_june = t!("months.june", locale = locale);
let i18n_july = t!("months.july", locale = locale);
let i18n_august = t!("months.august", locale = locale);
let i18n_september = t!("months.september", locale = locale);
let i18n_october = t!("months.october", locale = locale);
let i18n_november = t!("months.november", locale = locale);
let i18n_december = t!("months.december", locale = locale);
let i18n_not_allowed = t!("payout_link.initiate.not_allowed", locale = locale);
let i18n_am = t!("time.am", locale = locale);
let i18n_pm = t!("time.pm", locale = locale);
context.insert("i18n_payout_link_title", &i18n_payout_link_title);
context.insert("i18n_january", &i18n_january);
context.insert("i18n_february", &i18n_february);
context.insert("i18n_march", &i18n_march);
context.insert("i18n_april", &i18n_april);
context.insert("i18n_may", &i18n_may);
context.insert("i18n_june", &i18n_june);
context.insert("i18n_july", &i18n_july);
context.insert("i18n_august", &i18n_august);
context.insert("i18n_september", &i18n_september);
context.insert("i18n_october", &i18n_october);
context.insert("i18n_november", &i18n_november);
context.insert("i18n_december", &i18n_december);
context.insert("i18n_not_allowed", &i18n_not_allowed);
context.insert("i18n_am", &i18n_am);
context.insert("i18n_pm", &i18n_pm);
}
pub fn insert_locales_in_context_for_payout_link_status(context: &mut Context, locale: &str) {
let language = get_language(locale);
let locale = language.as_str();
let i18n_payout_link_status_title = t!("payout_link.status.title", locale = locale);
let i18n_success_text = t!("payout_link.status.text.success", locale = locale);
let i18n_success_message = t!("payout_link.status.message.success", locale = locale);
let i18n_pending_text = t!("payout_link.status.text.processing", locale = locale);
let i18n_pending_message = t!("payout_link.status.message.processing", locale = locale);
let i18n_failed_text = t!("payout_link.status.text.failed", locale = locale);
let i18n_failed_message = t!("payout_link.status.message.failed", locale = locale);
let i18n_ref_id_text = t!("payout_link.status.info.ref_id", locale = locale);
let i18n_error_code_text = t!("payout_link.status.info.error_code", locale = locale);
let i18n_error_message = t!("payout_link.status.info.error_message", locale = locale);
let i18n_redirecting_text = t!(
"payout_link.status.redirection_text.redirecting",
locale = locale
);
let i18n_redirecting_in_text = t!(
"payout_link.status.redirection_text.redirecting_in",
locale = locale
);
let i18n_seconds_text = t!(
"payout_link.status.redirection_text.seconds",
locale = locale
);
context.insert(
"i18n_payout_link_status_title",
&i18n_payout_link_status_title,
);
context.insert("i18n_success_text", &i18n_success_text);
context.insert("i18n_success_message", &i18n_success_message);
context.insert("i18n_pending_text", &i18n_pending_text);
context.insert("i18n_pending_message", &i18n_pending_message);
context.insert("i18n_failed_text", &i18n_failed_text);
context.insert("i18n_failed_message", &i18n_failed_message);
context.insert("i18n_ref_id_text", &i18n_ref_id_text);
context.insert("i18n_error_code_text", &i18n_error_code_text);
context.insert("i18n_error_message", &i18n_error_message);
context.insert("i18n_redirecting_text", &i18n_redirecting_text);
context.insert("i18n_redirecting_in_text", &i18n_redirecting_in_text);
context.insert("i18n_seconds_text", &i18n_seconds_text);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/email/types.rs | crates/router/src/services/email/types.rs | use api_models::user::dashboard_metadata::ProdIntent;
use common_enums::{EntityType, MerchantProductType};
use common_utils::{errors::CustomResult, pii, types::user::EmailThemeConfig};
use error_stack::ResultExt;
use external_services::email::{EmailContents, EmailData, EmailError};
use masking::{ExposeInterface, PeekInterface, Secret};
use crate::{configs, consts, routes::SessionState};
#[cfg(feature = "olap")]
use crate::{
core::errors::{UserErrors, UserResult},
services::jwt,
types::domain,
};
pub enum EmailBody {
Verify {
link: String,
entity_name: String,
entity_logo_url: String,
primary_color: String,
background_color: String,
foreground_color: String,
},
Reset {
link: String,
user_name: String,
entity_name: String,
entity_logo_url: String,
primary_color: String,
background_color: String,
foreground_color: String,
},
MagicLink {
link: String,
user_name: String,
entity_name: String,
entity_logo_url: String,
primary_color: String,
background_color: String,
foreground_color: String,
},
InviteUser {
link: String,
user_name: String,
entity_name: String,
entity_logo_url: String,
primary_color: String,
background_color: String,
foreground_color: String,
},
AcceptInviteFromEmail {
link: String,
user_name: String,
entity_name: String,
entity_logo_url: String,
primary_color: String,
background_color: String,
foreground_color: String,
},
BizEmailProd {
user_name: String,
poc_email: String,
legal_business_name: String,
business_location: String,
business_website: String,
product_type: MerchantProductType,
},
ReconActivation {
user_name: String,
},
ProFeatureRequest {
feature_name: String,
merchant_id: common_utils::id_type::MerchantId,
user_name: String,
user_email: String,
},
ApiKeyExpiryReminder {
expires_in: u8,
api_key_name: String,
prefix: String,
},
WelcomeToCommunity,
}
pub mod html {
use crate::services::email::types::EmailBody;
pub fn get_html_body(email_body: EmailBody) -> String {
match email_body {
EmailBody::Verify {
link,
entity_name,
entity_logo_url,
primary_color,
background_color,
foreground_color,
} => {
format!(
include_str!("assets/verify.html"),
link = link,
entity_name = entity_name,
entity_logo_url = entity_logo_url,
primary_color = primary_color,
background_color = background_color,
foreground_color = foreground_color
)
}
EmailBody::Reset {
link,
user_name,
entity_name,
entity_logo_url,
primary_color,
background_color,
foreground_color,
} => {
format!(
include_str!("assets/reset.html"),
link = link,
username = user_name,
entity_name = entity_name,
entity_logo_url = entity_logo_url,
primary_color = primary_color,
background_color = background_color,
foreground_color = foreground_color
)
}
EmailBody::MagicLink {
link,
user_name,
entity_name,
entity_logo_url,
primary_color,
background_color,
foreground_color,
} => {
format!(
include_str!("assets/magic_link.html"),
username = user_name,
link = link,
entity_name = entity_name,
entity_logo_url = entity_logo_url,
primary_color = primary_color,
background_color = background_color,
foreground_color = foreground_color
)
}
EmailBody::InviteUser {
link,
user_name,
entity_name,
entity_logo_url,
primary_color,
background_color,
foreground_color,
} => {
format!(
include_str!("assets/invite.html"),
username = user_name,
link = link,
entity_name = entity_name,
entity_logo_url = entity_logo_url,
primary_color = primary_color,
background_color = background_color,
foreground_color = foreground_color
)
}
// TODO: Change the linked html for accept invite from email
EmailBody::AcceptInviteFromEmail {
link,
user_name,
entity_name,
entity_logo_url,
primary_color,
background_color,
foreground_color,
} => {
format!(
include_str!("assets/invite.html"),
username = user_name,
link = link,
entity_name = entity_name,
entity_logo_url = entity_logo_url,
primary_color = primary_color,
background_color = background_color,
foreground_color = foreground_color
)
}
EmailBody::ReconActivation { user_name } => {
format!(
include_str!("assets/recon_activation.html"),
username = user_name,
)
}
EmailBody::BizEmailProd {
user_name,
poc_email,
legal_business_name,
business_location,
business_website,
product_type,
} => {
format!(
include_str!("assets/bizemailprod.html"),
poc_email = poc_email,
legal_business_name = legal_business_name,
business_location = business_location,
business_website = business_website,
username = user_name,
product_type = product_type
)
}
EmailBody::ProFeatureRequest {
feature_name,
merchant_id,
user_name,
user_email,
} => format!(
"Dear Hyperswitch Support Team,
Dashboard Pro Feature Request,
Feature name : {feature_name}
Merchant ID : {}
Merchant Name : {user_name}
Email : {user_email}
(note: This is an auto generated email. Use merchant email for any further communications)",
merchant_id.get_string_repr()
),
EmailBody::ApiKeyExpiryReminder {
expires_in,
api_key_name,
prefix,
} => format!(
include_str!("assets/api_key_expiry_reminder.html"),
api_key_name = api_key_name,
prefix = prefix,
expires_in = expires_in,
),
EmailBody::WelcomeToCommunity => {
include_str!("assets/welcome_to_community.html").to_string()
}
}
}
}
#[derive(serde::Serialize, serde::Deserialize)]
pub struct EmailToken {
email: String,
flow: domain::Origin,
exp: u64,
entity: Option<Entity>,
}
#[derive(serde::Serialize, serde::Deserialize, Clone)]
pub struct Entity {
pub entity_id: String,
pub entity_type: EntityType,
}
impl Entity {
pub fn get_entity_type(&self) -> EntityType {
self.entity_type
}
pub fn get_entity_id(&self) -> &str {
&self.entity_id
}
}
impl EmailToken {
pub async fn new_token(
email: domain::UserEmail,
entity: Option<Entity>,
flow: domain::Origin,
settings: &configs::Settings,
) -> UserResult<String> {
let expiration_duration = std::time::Duration::from_secs(consts::EMAIL_TOKEN_TIME_IN_SECS);
let exp = jwt::generate_exp(expiration_duration)?.as_secs();
let token_payload = Self {
email: email.get_secret().expose(),
flow,
exp,
entity,
};
jwt::generate_jwt(&token_payload, settings).await
}
pub fn get_email(&self) -> UserResult<domain::UserEmail> {
pii::Email::try_from(self.email.clone())
.change_context(UserErrors::InternalServerError)
.and_then(domain::UserEmail::from_pii_email)
}
pub fn get_entity(&self) -> Option<&Entity> {
self.entity.as_ref()
}
pub fn get_flow(&self) -> domain::Origin {
self.flow.clone()
}
}
pub fn get_link_with_token(
base_url: impl std::fmt::Display,
token: impl std::fmt::Display,
action: impl std::fmt::Display,
auth_id: &Option<impl std::fmt::Display>,
theme_id: &Option<impl std::fmt::Display>,
) -> String {
let mut email_url = format!("{base_url}/user/{action}?token={token}");
if let Some(auth_id) = auth_id {
email_url = format!("{email_url}&auth_id={auth_id}");
}
if let Some(theme_id) = theme_id {
email_url = format!("{email_url}&theme_id={theme_id}");
}
email_url
}
pub struct VerifyEmail {
pub recipient_email: domain::UserEmail,
pub settings: std::sync::Arc<configs::Settings>,
pub auth_id: Option<String>,
pub theme_id: Option<String>,
pub theme_config: EmailThemeConfig,
}
/// Currently only HTML is supported
#[async_trait::async_trait]
impl EmailData for VerifyEmail {
async fn get_email_data(&self, base_url: &str) -> CustomResult<EmailContents, EmailError> {
let token = EmailToken::new_token(
self.recipient_email.clone(),
None,
domain::Origin::VerifyEmail,
&self.settings,
)
.await
.change_context(EmailError::TokenGenerationFailure)?;
let verify_email_link = get_link_with_token(
base_url,
token,
"verify_email",
&self.auth_id,
&self.theme_id,
);
let body = html::get_html_body(EmailBody::Verify {
link: verify_email_link,
entity_name: self.theme_config.entity_name.clone(),
entity_logo_url: self.theme_config.entity_logo_url.clone(),
primary_color: self.theme_config.primary_color.clone(),
background_color: self.theme_config.background_color.clone(),
foreground_color: self.theme_config.foreground_color.clone(),
});
Ok(EmailContents {
subject: format!(
"Welcome to the {} community!",
self.theme_config.entity_name
),
body: external_services::email::IntermediateString::new(body),
recipient: self.recipient_email.clone().into_inner(),
})
}
}
pub struct ResetPassword {
pub recipient_email: domain::UserEmail,
pub user_name: domain::UserName,
pub settings: std::sync::Arc<configs::Settings>,
pub auth_id: Option<String>,
pub theme_id: Option<String>,
pub theme_config: EmailThemeConfig,
}
#[async_trait::async_trait]
impl EmailData for ResetPassword {
async fn get_email_data(&self, base_url: &str) -> CustomResult<EmailContents, EmailError> {
let token = EmailToken::new_token(
self.recipient_email.clone(),
None,
domain::Origin::ResetPassword,
&self.settings,
)
.await
.change_context(EmailError::TokenGenerationFailure)?;
let reset_password_link = get_link_with_token(
base_url,
token,
"set_password",
&self.auth_id,
&self.theme_id,
);
let body = html::get_html_body(EmailBody::Reset {
link: reset_password_link,
user_name: self.user_name.clone().get_secret().expose(),
entity_name: self.theme_config.entity_name.clone(),
entity_logo_url: self.theme_config.entity_logo_url.clone(),
primary_color: self.theme_config.primary_color.clone(),
background_color: self.theme_config.background_color.clone(),
foreground_color: self.theme_config.foreground_color.clone(),
});
Ok(EmailContents {
subject: format!(
"Get back to {} - Reset Your Password Now!",
self.theme_config.entity_name
),
body: external_services::email::IntermediateString::new(body),
recipient: self.recipient_email.clone().into_inner(),
})
}
}
pub struct MagicLink {
pub recipient_email: domain::UserEmail,
pub user_name: domain::UserName,
pub settings: std::sync::Arc<configs::Settings>,
pub auth_id: Option<String>,
pub theme_id: Option<String>,
pub theme_config: EmailThemeConfig,
}
#[async_trait::async_trait]
impl EmailData for MagicLink {
async fn get_email_data(&self, base_url: &str) -> CustomResult<EmailContents, EmailError> {
let token = EmailToken::new_token(
self.recipient_email.clone(),
None,
domain::Origin::MagicLink,
&self.settings,
)
.await
.change_context(EmailError::TokenGenerationFailure)?;
let magic_link_login = get_link_with_token(
base_url,
token,
"verify_email",
&self.auth_id,
&self.theme_id,
);
let body = html::get_html_body(EmailBody::MagicLink {
link: magic_link_login,
user_name: self.user_name.clone().get_secret().expose(),
entity_name: self.theme_config.entity_name.clone(),
entity_logo_url: self.theme_config.entity_logo_url.clone(),
primary_color: self.theme_config.primary_color.clone(),
background_color: self.theme_config.background_color.clone(),
foreground_color: self.theme_config.foreground_color.clone(),
});
Ok(EmailContents {
subject: format!(
"Unlock {}: Use Your Magic Link to Sign In",
self.theme_config.entity_name
),
body: external_services::email::IntermediateString::new(body),
recipient: self.recipient_email.clone().into_inner(),
})
}
}
pub struct InviteUser {
pub recipient_email: domain::UserEmail,
pub user_name: domain::UserName,
pub settings: std::sync::Arc<configs::Settings>,
pub entity: Entity,
pub auth_id: Option<String>,
pub theme_id: Option<String>,
pub theme_config: EmailThemeConfig,
}
#[async_trait::async_trait]
impl EmailData for InviteUser {
async fn get_email_data(&self, base_url: &str) -> CustomResult<EmailContents, EmailError> {
let token = EmailToken::new_token(
self.recipient_email.clone(),
Some(self.entity.clone()),
domain::Origin::AcceptInvitationFromEmail,
&self.settings,
)
.await
.change_context(EmailError::TokenGenerationFailure)?;
let invite_user_link = get_link_with_token(
base_url,
token,
"accept_invite_from_email",
&self.auth_id,
&self.theme_id,
);
let body = html::get_html_body(EmailBody::AcceptInviteFromEmail {
link: invite_user_link,
user_name: self.user_name.clone().get_secret().expose(),
entity_name: self.theme_config.entity_name.clone(),
entity_logo_url: self.theme_config.entity_logo_url.clone(),
primary_color: self.theme_config.primary_color.clone(),
background_color: self.theme_config.background_color.clone(),
foreground_color: self.theme_config.foreground_color.clone(),
});
Ok(EmailContents {
subject: format!(
"You have been invited to join {} Community!",
self.theme_config.entity_name
),
body: external_services::email::IntermediateString::new(body),
recipient: self.recipient_email.clone().into_inner(),
})
}
}
pub struct ReconActivation {
pub recipient_email: domain::UserEmail,
pub user_name: domain::UserName,
pub subject: &'static str,
pub theme_id: Option<String>,
pub theme_config: EmailThemeConfig,
}
#[async_trait::async_trait]
impl EmailData for ReconActivation {
async fn get_email_data(&self, _base_url: &str) -> CustomResult<EmailContents, EmailError> {
let body = html::get_html_body(EmailBody::ReconActivation {
user_name: self.user_name.clone().get_secret().expose(),
});
Ok(EmailContents {
subject: self.subject.to_string(),
body: external_services::email::IntermediateString::new(body),
recipient: self.recipient_email.clone().into_inner(),
})
}
}
pub struct BizEmailProd {
pub recipient_email: domain::UserEmail,
pub user_name: Secret<String>,
pub poc_email: Secret<String>,
pub legal_business_name: String,
pub business_location: String,
pub business_website: String,
pub settings: std::sync::Arc<configs::Settings>,
pub theme_id: Option<String>,
pub theme_config: EmailThemeConfig,
pub product_type: MerchantProductType,
}
impl BizEmailProd {
pub fn new(
state: &SessionState,
data: ProdIntent,
theme_id: Option<String>,
theme_config: EmailThemeConfig,
) -> UserResult<Self> {
Ok(Self {
recipient_email: domain::UserEmail::from_pii_email(
state.conf.email.prod_intent_recipient_email.clone(),
)?,
settings: state.conf.clone(),
user_name: data
.poc_name
.map(|s| Secret::new(s.peek().clone().into_inner()))
.unwrap_or_default(),
poc_email: data
.poc_email
.map(|s| Secret::new(s.peek().clone()))
.unwrap_or_default(),
legal_business_name: data
.legal_business_name
.map(|s| s.into_inner())
.unwrap_or_default(),
business_location: data
.business_location
.unwrap_or(common_enums::CountryAlpha2::AD)
.to_string(),
business_website: data
.business_website
.map(|s| s.into_inner())
.unwrap_or_default(),
theme_id,
theme_config,
product_type: data.product_type,
})
}
}
#[async_trait::async_trait]
impl EmailData for BizEmailProd {
async fn get_email_data(&self, _base_url: &str) -> CustomResult<EmailContents, EmailError> {
let body = html::get_html_body(EmailBody::BizEmailProd {
user_name: self.user_name.clone().expose(),
poc_email: self.poc_email.clone().expose(),
legal_business_name: self.legal_business_name.clone(),
business_location: self.business_location.clone(),
business_website: self.business_website.clone(),
product_type: self.product_type,
});
Ok(EmailContents {
subject: "New Prod Intent".to_string(),
body: external_services::email::IntermediateString::new(body),
recipient: self.recipient_email.clone().into_inner(),
})
}
}
pub struct ProFeatureRequest {
pub recipient_email: domain::UserEmail,
pub feature_name: String,
pub merchant_id: common_utils::id_type::MerchantId,
pub user_name: domain::UserName,
pub user_email: domain::UserEmail,
pub subject: String,
pub theme_id: Option<String>,
pub theme_config: EmailThemeConfig,
}
#[async_trait::async_trait]
impl EmailData for ProFeatureRequest {
async fn get_email_data(&self, _base_url: &str) -> CustomResult<EmailContents, EmailError> {
let recipient = self.recipient_email.clone().into_inner();
let body = html::get_html_body(EmailBody::ProFeatureRequest {
user_name: self.user_name.clone().get_secret().expose(),
feature_name: self.feature_name.clone(),
merchant_id: self.merchant_id.clone(),
user_email: self.user_email.clone().get_secret().expose(),
});
Ok(EmailContents {
subject: self.subject.clone(),
body: external_services::email::IntermediateString::new(body),
recipient,
})
}
}
pub struct ApiKeyExpiryReminder {
pub recipient_email: domain::UserEmail,
pub subject: &'static str,
pub expires_in: u8,
pub api_key_name: String,
pub prefix: String,
pub theme_id: Option<String>,
pub theme_config: EmailThemeConfig,
}
#[async_trait::async_trait]
impl EmailData for ApiKeyExpiryReminder {
async fn get_email_data(&self, _base_url: &str) -> CustomResult<EmailContents, EmailError> {
let recipient = self.recipient_email.clone().into_inner();
let body = html::get_html_body(EmailBody::ApiKeyExpiryReminder {
expires_in: self.expires_in,
api_key_name: self.api_key_name.clone(),
prefix: self.prefix.clone(),
});
Ok(EmailContents {
subject: self.subject.to_string(),
body: external_services::email::IntermediateString::new(body),
recipient,
})
}
}
pub struct WelcomeToCommunity {
pub recipient_email: domain::UserEmail,
}
#[async_trait::async_trait]
impl EmailData for WelcomeToCommunity {
async fn get_email_data(&self, _base_url: &str) -> CustomResult<EmailContents, EmailError> {
let body = html::get_html_body(EmailBody::WelcomeToCommunity);
Ok(EmailContents {
subject: "Thank you for signing up on Hyperswitch Dashboard!".to_string(),
body: external_services::email::IntermediateString::new(body),
recipient: self.recipient_email.clone().into_inner(),
})
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/kafka/payment_attempt.rs | crates/router/src/services/kafka/payment_attempt.rs | #[cfg(feature = "v2")]
use common_types::payments;
#[cfg(feature = "v2")]
use common_utils::types;
use common_utils::{id_type, types::MinorUnit};
use diesel_models::enums as storage_enums;
#[cfg(feature = "v2")]
use diesel_models::payment_attempt;
#[cfg(feature = "v2")]
use hyperswitch_domain_models::{
address, payments::payment_attempt::PaymentAttemptFeatureMetadata,
router_response_types::RedirectForm,
};
use hyperswitch_domain_models::{
mandates::MandateDetails, payments::payment_attempt::PaymentAttempt,
};
use time::OffsetDateTime;
#[cfg(feature = "v1")]
#[derive(serde::Serialize, Debug)]
pub struct KafkaPaymentAttempt<'a> {
pub payment_id: &'a id_type::PaymentId,
pub merchant_id: &'a id_type::MerchantId,
pub attempt_id: &'a String,
pub status: storage_enums::AttemptStatus,
pub amount: MinorUnit,
pub currency: Option<storage_enums::Currency>,
pub save_to_locker: Option<bool>,
pub connector: Option<&'a String>,
pub error_message: Option<&'a String>,
pub offer_amount: Option<MinorUnit>,
pub surcharge_amount: Option<MinorUnit>,
pub tax_amount: Option<MinorUnit>,
pub payment_method_id: Option<&'a String>,
pub payment_method: Option<storage_enums::PaymentMethod>,
pub connector_transaction_id: Option<&'a String>,
pub capture_method: Option<storage_enums::CaptureMethod>,
#[serde(default, with = "time::serde::timestamp::option")]
pub capture_on: Option<OffsetDateTime>,
pub confirm: bool,
pub authentication_type: Option<storage_enums::AuthenticationType>,
#[serde(with = "time::serde::timestamp")]
pub created_at: OffsetDateTime,
#[serde(with = "time::serde::timestamp")]
pub modified_at: OffsetDateTime,
#[serde(default, with = "time::serde::timestamp::option")]
pub last_synced: Option<OffsetDateTime>,
pub cancellation_reason: Option<&'a String>,
pub amount_to_capture: Option<MinorUnit>,
pub mandate_id: Option<&'a String>,
pub browser_info: Option<String>,
pub error_code: Option<&'a String>,
pub connector_metadata: Option<String>,
// TODO: These types should implement copy ideally
pub payment_experience: Option<&'a storage_enums::PaymentExperience>,
pub payment_method_type: Option<&'a storage_enums::PaymentMethodType>,
pub payment_method_data: Option<String>,
pub error_reason: Option<&'a String>,
pub multiple_capture_count: Option<i16>,
pub amount_capturable: MinorUnit,
pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>,
pub net_amount: MinorUnit,
pub unified_code: Option<&'a String>,
pub unified_message: Option<&'a String>,
pub mandate_data: Option<&'a MandateDetails>,
pub client_source: Option<&'a String>,
pub client_version: Option<&'a String>,
pub profile_id: &'a id_type::ProfileId,
pub organization_id: &'a id_type::OrganizationId,
pub card_network: Option<String>,
pub card_discovery: Option<String>,
pub routing_approach: Option<storage_enums::RoutingApproach>,
pub debit_routing_savings: Option<MinorUnit>,
pub signature_network: Option<common_enums::CardNetwork>,
pub is_issuer_regulated: Option<bool>,
}
#[cfg(feature = "v1")]
impl<'a> KafkaPaymentAttempt<'a> {
pub fn from_storage(attempt: &'a PaymentAttempt) -> Self {
let card_payment_method_data = attempt
.get_payment_method_data()
.and_then(|data| data.get_additional_card_info());
Self {
payment_id: &attempt.payment_id,
merchant_id: &attempt.merchant_id,
attempt_id: &attempt.attempt_id,
status: attempt.status,
amount: attempt.net_amount.get_order_amount(),
currency: attempt.currency,
save_to_locker: attempt.save_to_locker,
connector: attempt.connector.as_ref(),
error_message: attempt.error_message.as_ref(),
offer_amount: attempt.offer_amount,
surcharge_amount: attempt.net_amount.get_surcharge_amount(),
tax_amount: attempt.net_amount.get_tax_on_surcharge(),
payment_method_id: attempt.payment_method_id.as_ref(),
payment_method: attempt.payment_method,
connector_transaction_id: attempt.connector_transaction_id.as_ref(),
capture_method: attempt.capture_method,
capture_on: attempt.capture_on.map(|i| i.assume_utc()),
confirm: attempt.confirm,
authentication_type: attempt.authentication_type,
created_at: attempt.created_at.assume_utc(),
modified_at: attempt.modified_at.assume_utc(),
last_synced: attempt.last_synced.map(|i| i.assume_utc()),
cancellation_reason: attempt.cancellation_reason.as_ref(),
amount_to_capture: attempt.amount_to_capture,
mandate_id: attempt.mandate_id.as_ref(),
browser_info: attempt.browser_info.as_ref().map(|v| v.to_string()),
error_code: attempt.error_code.as_ref(),
connector_metadata: attempt.connector_metadata.as_ref().map(|v| v.to_string()),
payment_experience: attempt.payment_experience.as_ref(),
payment_method_type: attempt.payment_method_type.as_ref(),
payment_method_data: attempt.payment_method_data.as_ref().map(|v| v.to_string()),
error_reason: attempt.error_reason.as_ref(),
multiple_capture_count: attempt.multiple_capture_count,
amount_capturable: attempt.amount_capturable,
merchant_connector_id: attempt.merchant_connector_id.as_ref(),
net_amount: attempt.net_amount.get_total_amount(),
unified_code: attempt.unified_code.as_ref(),
unified_message: attempt.unified_message.as_ref(),
mandate_data: attempt.mandate_data.as_ref(),
client_source: attempt.client_source.as_ref(),
client_version: attempt.client_version.as_ref(),
profile_id: &attempt.profile_id,
organization_id: &attempt.organization_id,
card_network: attempt
.payment_method_data
.as_ref()
.and_then(|data| data.as_object())
.and_then(|pm| pm.get("card"))
.and_then(|data| data.as_object())
.and_then(|card| card.get("card_network"))
.and_then(|network| network.as_str())
.map(|network| network.to_string()),
card_discovery: attempt
.card_discovery
.map(|discovery| discovery.to_string()),
routing_approach: attempt.routing_approach.clone(),
debit_routing_savings: attempt.debit_routing_savings,
signature_network: card_payment_method_data
.as_ref()
.and_then(|data| data.signature_network.clone()),
is_issuer_regulated: card_payment_method_data.and_then(|data| data.is_regulated),
}
}
}
#[cfg(feature = "v2")]
#[derive(serde::Serialize, Debug)]
pub struct KafkaPaymentAttempt<'a> {
pub payment_id: &'a id_type::GlobalPaymentId,
pub merchant_id: &'a id_type::MerchantId,
pub attempt_id: &'a id_type::GlobalAttemptId,
pub attempts_group_id: Option<&'a id_type::GlobalAttemptGroupId>,
pub status: storage_enums::AttemptStatus,
pub amount: MinorUnit,
pub connector: Option<&'a String>,
pub error_message: Option<&'a String>,
pub surcharge_amount: Option<MinorUnit>,
pub tax_amount: Option<MinorUnit>,
pub payment_method_id: Option<&'a id_type::GlobalPaymentMethodId>,
pub payment_method: storage_enums::PaymentMethod,
pub connector_transaction_id: Option<&'a String>,
pub authentication_type: storage_enums::AuthenticationType,
#[serde(with = "time::serde::timestamp")]
pub created_at: OffsetDateTime,
#[serde(with = "time::serde::timestamp")]
pub modified_at: OffsetDateTime,
#[serde(default, with = "time::serde::timestamp::option")]
pub last_synced: Option<OffsetDateTime>,
pub cancellation_reason: Option<&'a String>,
pub amount_to_capture: Option<MinorUnit>,
pub browser_info: Option<&'a types::BrowserInformation>,
pub error_code: Option<&'a String>,
pub connector_metadata: Option<String>,
// TODO: These types should implement copy ideally
pub payment_experience: Option<&'a storage_enums::PaymentExperience>,
pub payment_method_type: &'a storage_enums::PaymentMethodType,
pub payment_method_data: Option<String>,
pub error_reason: Option<&'a String>,
pub multiple_capture_count: Option<i16>,
pub amount_capturable: MinorUnit,
pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>,
pub net_amount: MinorUnit,
pub unified_code: Option<&'a String>,
pub unified_message: Option<&'a String>,
pub client_source: Option<&'a String>,
pub client_version: Option<&'a String>,
pub profile_id: &'a id_type::ProfileId,
pub organization_id: &'a id_type::OrganizationId,
pub card_network: Option<String>,
pub card_discovery: Option<String>,
pub connector_payment_id: Option<types::ConnectorTransactionId>,
pub payment_token: Option<String>,
pub preprocessing_step_id: Option<String>,
pub connector_response_reference_id: Option<String>,
pub updated_by: &'a String,
pub encoded_data: Option<&'a masking::Secret<String>>,
pub external_three_ds_authentication_attempted: Option<bool>,
pub authentication_connector: Option<String>,
pub authentication_id: Option<String>,
pub fingerprint_id: Option<String>,
pub customer_acceptance: Option<&'a masking::Secret<payments::CustomerAcceptance>>,
pub shipping_cost: Option<MinorUnit>,
pub order_tax_amount: Option<MinorUnit>,
pub charges: Option<payments::ConnectorChargeResponseData>,
pub processor_merchant_id: &'a id_type::MerchantId,
pub created_by: Option<&'a types::CreatedBy>,
pub payment_method_type_v2: storage_enums::PaymentMethod,
pub payment_method_subtype: storage_enums::PaymentMethodType,
pub routing_result: Option<serde_json::Value>,
pub authentication_applied: Option<common_enums::AuthenticationType>,
pub external_reference_id: Option<String>,
pub tax_on_surcharge: Option<MinorUnit>,
pub payment_method_billing_address: Option<masking::Secret<&'a address::Address>>, // adjusted from Encryption
pub redirection_data: Option<&'a RedirectForm>,
pub connector_payment_data: Option<String>,
pub connector_token_details: Option<&'a payment_attempt::ConnectorTokenDetails>,
pub feature_metadata: Option<&'a PaymentAttemptFeatureMetadata>,
pub network_advice_code: Option<String>,
pub network_decline_code: Option<String>,
pub network_error_message: Option<String>,
pub connector_request_reference_id: Option<String>,
}
#[cfg(feature = "v2")]
impl<'a> KafkaPaymentAttempt<'a> {
pub fn from_storage(attempt: &'a PaymentAttempt) -> Self {
use masking::PeekInterface;
let PaymentAttempt {
payment_id,
merchant_id,
attempts_group_id,
amount_details,
status,
connector,
error,
authentication_type,
created_at,
modified_at,
last_synced,
cancellation_reason,
browser_info,
payment_token,
connector_metadata,
payment_experience,
payment_method_data,
routing_result,
preprocessing_step_id,
multiple_capture_count,
connector_response_reference_id,
updated_by,
redirection_data,
encoded_data,
merchant_connector_id,
external_three_ds_authentication_attempted,
authentication_connector,
authentication_id,
fingerprint_id,
client_source,
client_version,
customer_acceptance,
profile_id,
organization_id,
payment_method_type,
payment_method_id,
connector_payment_id,
payment_method_subtype,
authentication_applied,
external_reference_id,
payment_method_billing_address,
id,
connector_token_details,
card_discovery,
charges,
feature_metadata,
processor_merchant_id,
created_by,
connector_request_reference_id,
network_transaction_id: _,
authorized_amount: _,
} = attempt;
let (connector_payment_id, connector_payment_data) = connector_payment_id
.clone()
.map(types::ConnectorTransactionId::form_id_and_data)
.map(|(txn_id, txn_data)| (Some(txn_id), txn_data))
.unwrap_or((None, None));
Self {
payment_id,
merchant_id,
attempt_id: id,
attempts_group_id: attempts_group_id.as_ref(),
status: *status,
amount: amount_details.get_net_amount(),
connector: connector.as_ref(),
error_message: error.as_ref().map(|error_details| &error_details.message),
surcharge_amount: amount_details.get_surcharge_amount(),
tax_amount: amount_details.get_tax_on_surcharge(),
payment_method_id: payment_method_id.as_ref(),
payment_method: *payment_method_type,
connector_transaction_id: connector_response_reference_id.as_ref(),
authentication_type: *authentication_type,
created_at: created_at.assume_utc(),
modified_at: modified_at.assume_utc(),
last_synced: last_synced.map(|i| i.assume_utc()),
cancellation_reason: cancellation_reason.as_ref(),
amount_to_capture: amount_details.get_amount_to_capture(),
browser_info: browser_info.as_ref(),
error_code: error.as_ref().map(|error_details| &error_details.code),
connector_metadata: connector_metadata.as_ref().map(|v| v.peek().to_string()),
payment_experience: payment_experience.as_ref(),
payment_method_type: payment_method_subtype,
payment_method_data: payment_method_data.as_ref().map(|v| v.peek().to_string()),
error_reason: error
.as_ref()
.and_then(|error_details| error_details.reason.as_ref()),
multiple_capture_count: *multiple_capture_count,
amount_capturable: amount_details.get_amount_capturable(),
merchant_connector_id: merchant_connector_id.as_ref(),
net_amount: amount_details.get_net_amount(),
unified_code: error
.as_ref()
.and_then(|error_details| error_details.unified_code.as_ref()),
unified_message: error
.as_ref()
.and_then(|error_details| error_details.unified_message.as_ref()),
client_source: client_source.as_ref(),
client_version: client_version.as_ref(),
profile_id,
organization_id,
card_network: payment_method_data
.as_ref()
.map(|data| data.peek())
.and_then(|data| data.as_object())
.and_then(|pm| pm.get("card"))
.and_then(|data| data.as_object())
.and_then(|card| card.get("card_network"))
.and_then(|network| network.as_str())
.map(|network| network.to_string()),
card_discovery: card_discovery.map(|discovery| discovery.to_string()),
payment_token: payment_token.clone(),
preprocessing_step_id: preprocessing_step_id.clone(),
connector_response_reference_id: connector_response_reference_id.clone(),
updated_by,
encoded_data: encoded_data.as_ref(),
external_three_ds_authentication_attempted: *external_three_ds_authentication_attempted,
authentication_connector: authentication_connector.clone(),
authentication_id: authentication_id
.as_ref()
.map(|id| id.get_string_repr().to_string().clone()),
fingerprint_id: fingerprint_id.clone(),
customer_acceptance: customer_acceptance.as_ref(),
shipping_cost: amount_details.get_shipping_cost(),
order_tax_amount: amount_details.get_order_tax_amount(),
charges: charges.clone(),
processor_merchant_id,
created_by: created_by.as_ref(),
payment_method_type_v2: *payment_method_type,
connector_payment_id: connector_payment_id.as_ref().cloned(),
payment_method_subtype: *payment_method_subtype,
routing_result: routing_result.clone(),
authentication_applied: *authentication_applied,
external_reference_id: external_reference_id.clone(),
tax_on_surcharge: amount_details.get_tax_on_surcharge(),
payment_method_billing_address: payment_method_billing_address
.as_ref()
.map(|v| masking::Secret::new(v.get_inner())),
redirection_data: redirection_data.as_ref(),
connector_payment_data,
connector_token_details: connector_token_details.as_ref(),
feature_metadata: feature_metadata.as_ref(),
network_advice_code: error
.as_ref()
.and_then(|details| details.network_advice_code.clone()),
network_decline_code: error
.as_ref()
.and_then(|details| details.network_decline_code.clone()),
network_error_message: error
.as_ref()
.and_then(|details| details.network_error_message.clone()),
connector_request_reference_id: connector_request_reference_id.clone(),
}
}
}
impl super::KafkaMessage for KafkaPaymentAttempt<'_> {
#[cfg(feature = "v1")]
fn key(&self) -> String {
format!(
"{}_{}_{}",
self.merchant_id.get_string_repr(),
self.payment_id.get_string_repr(),
self.attempt_id
)
}
#[cfg(feature = "v2")]
fn key(&self) -> String {
format!(
"{}_{}_{}",
self.merchant_id.get_string_repr(),
self.payment_id.get_string_repr(),
self.attempt_id.get_string_repr()
)
}
fn event_type(&self) -> crate::events::EventType {
crate::events::EventType::PaymentAttempt
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/kafka/fraud_check.rs | crates/router/src/services/kafka/fraud_check.rs | // use diesel_models::enums as storage_enums;
use diesel_models::{
enums as storage_enums,
enums::{FraudCheckLastStep, FraudCheckStatus, FraudCheckType},
fraud_check::FraudCheck,
};
use time::OffsetDateTime;
#[derive(serde::Serialize, Debug)]
pub struct KafkaFraudCheck<'a> {
pub frm_id: &'a String,
pub payment_id: &'a common_utils::id_type::PaymentId,
pub merchant_id: &'a common_utils::id_type::MerchantId,
pub attempt_id: &'a String,
#[serde(with = "time::serde::timestamp")]
pub created_at: OffsetDateTime,
pub frm_name: &'a String,
pub frm_transaction_id: Option<&'a String>,
pub frm_transaction_type: FraudCheckType,
pub frm_status: FraudCheckStatus,
pub frm_score: Option<i32>,
pub frm_reason: Option<serde_json::Value>,
pub frm_error: Option<&'a String>,
pub payment_details: Option<serde_json::Value>,
pub metadata: Option<serde_json::Value>,
#[serde(with = "time::serde::timestamp")]
pub modified_at: OffsetDateTime,
pub last_step: FraudCheckLastStep,
pub payment_capture_method: Option<storage_enums::CaptureMethod>, // In postFrm, we are updating capture method from automatic to manual. To store the merchant actual capture method, we are storing the actual capture method in payment_capture_method. It will be useful while approving the FRM decision.
}
impl<'a> KafkaFraudCheck<'a> {
pub fn from_storage(check: &'a FraudCheck) -> Self {
Self {
frm_id: &check.frm_id,
payment_id: &check.payment_id,
merchant_id: &check.merchant_id,
attempt_id: &check.attempt_id,
created_at: check.created_at.assume_utc(),
frm_name: &check.frm_name,
frm_transaction_id: check.frm_transaction_id.as_ref(),
frm_transaction_type: check.frm_transaction_type,
frm_status: check.frm_status,
frm_score: check.frm_score,
frm_reason: check.frm_reason.clone(),
frm_error: check.frm_error.as_ref(),
payment_details: check.payment_details.clone(),
metadata: check.metadata.clone(),
modified_at: check.modified_at.assume_utc(),
last_step: check.last_step,
payment_capture_method: check.payment_capture_method,
}
}
}
impl super::KafkaMessage for KafkaFraudCheck<'_> {
fn key(&self) -> String {
format!(
"{}_{}_{}_{}",
self.merchant_id.get_string_repr(),
self.payment_id.get_string_repr(),
self.attempt_id,
self.frm_id
)
}
fn event_type(&self) -> crate::events::EventType {
crate::events::EventType::FraudCheck
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/kafka/payment_intent_event.rs | crates/router/src/services/kafka/payment_intent_event.rs | #[cfg(feature = "v2")]
use ::common_types::{
payments,
primitive_wrappers::{EnablePartialAuthorizationBool, RequestExtendedAuthorizationBool},
};
#[cfg(feature = "v2")]
use common_enums::{self, RequestIncrementalAuthorization};
use common_utils::{
crypto::Encryptable, hashing::HashedString, id_type, pii, types as common_types,
};
use diesel_models::enums as storage_enums;
#[cfg(feature = "v2")]
use diesel_models::{types as diesel_types, PaymentLinkConfigRequestForPayments};
#[cfg(feature = "v2")]
use diesel_models::{types::OrderDetailsWithAmount, TaxDetails};
use hyperswitch_domain_models::payments::PaymentIntent;
#[cfg(feature = "v2")]
use hyperswitch_domain_models::{address, routing};
use masking::{PeekInterface, Secret};
use serde_json::Value;
use time::OffsetDateTime;
#[cfg(feature = "v1")]
#[serde_with::skip_serializing_none]
#[derive(serde::Serialize, Debug)]
pub struct KafkaPaymentIntentEvent<'a> {
pub payment_id: &'a id_type::PaymentId,
pub merchant_id: &'a id_type::MerchantId,
pub status: storage_enums::IntentStatus,
pub amount: common_types::MinorUnit,
pub currency: Option<storage_enums::Currency>,
pub amount_captured: Option<common_types::MinorUnit>,
pub customer_id: Option<&'a id_type::CustomerId>,
pub description: Option<&'a String>,
pub return_url: Option<&'a String>,
pub metadata: Option<String>,
pub connector_id: Option<&'a String>,
pub statement_descriptor_name: Option<&'a String>,
pub statement_descriptor_suffix: Option<&'a String>,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub created_at: OffsetDateTime,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub modified_at: OffsetDateTime,
#[serde(default, with = "time::serde::timestamp::nanoseconds::option")]
pub last_synced: Option<OffsetDateTime>,
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub off_session: Option<bool>,
pub client_secret: Option<&'a String>,
pub active_attempt_id: String,
pub business_country: Option<storage_enums::CountryAlpha2>,
pub business_label: Option<&'a String>,
pub attempt_count: i16,
pub profile_id: Option<&'a id_type::ProfileId>,
pub payment_confirm_source: Option<storage_enums::PaymentSource>,
pub billing_details: Option<Encryptable<Secret<Value>>>,
pub shipping_details: Option<Encryptable<Secret<Value>>>,
pub customer_email: Option<HashedString<pii::EmailStrategy>>,
pub feature_metadata: Option<&'a Value>,
pub merchant_order_reference_id: Option<&'a String>,
pub organization_id: &'a id_type::OrganizationId,
#[serde(flatten)]
pub infra_values: Option<Value>,
}
#[cfg(feature = "v2")]
#[serde_with::skip_serializing_none]
#[derive(serde::Serialize, Debug)]
pub struct KafkaPaymentIntentEvent<'a> {
pub payment_id: &'a id_type::GlobalPaymentId,
pub merchant_id: &'a id_type::MerchantId,
pub status: storage_enums::IntentStatus,
pub amount: common_types::MinorUnit,
pub currency: storage_enums::Currency,
pub amount_captured: Option<common_types::MinorUnit>,
pub customer_id: Option<&'a id_type::GlobalCustomerId>,
pub description: Option<&'a common_types::Description>,
pub return_url: Option<&'a common_types::Url>,
pub metadata: Option<&'a Secret<Value>>,
pub statement_descriptor: Option<&'a common_types::StatementDescriptor>,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub created_at: OffsetDateTime,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub modified_at: OffsetDateTime,
#[serde(default, with = "time::serde::timestamp::nanoseconds::option")]
pub last_synced: Option<OffsetDateTime>,
pub setup_future_usage: storage_enums::FutureUsage,
pub off_session: bool,
pub active_attempt_id: Option<&'a id_type::GlobalAttemptId>,
pub active_attempt_id_type: common_enums::ActiveAttemptIDType,
pub active_attempts_group_id: Option<&'a id_type::GlobalAttemptGroupId>,
pub attempt_count: i16,
pub profile_id: &'a id_type::ProfileId,
pub customer_email: Option<HashedString<pii::EmailStrategy>>,
pub feature_metadata: Option<&'a diesel_types::FeatureMetadata>,
pub organization_id: &'a id_type::OrganizationId,
pub order_details: Option<&'a Vec<Secret<OrderDetailsWithAmount>>>,
pub allowed_payment_method_types: Option<&'a Vec<common_enums::PaymentMethodType>>,
pub connector_metadata: Option<&'a api_models::payments::ConnectorMetadata>,
pub payment_link_id: Option<&'a String>,
pub updated_by: &'a String,
pub surcharge_applicable: Option<bool>,
pub request_incremental_authorization: RequestIncrementalAuthorization,
pub split_txns_enabled: common_enums::SplitTxnsEnabled,
pub authorization_count: Option<i32>,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub session_expiry: OffsetDateTime,
pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest,
pub frm_metadata: Option<Secret<&'a Value>>,
pub customer_details: Option<Secret<&'a Value>>,
pub shipping_cost: Option<common_types::MinorUnit>,
pub tax_details: Option<TaxDetails>,
pub skip_external_tax_calculation: bool,
pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>,
pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>,
pub split_payments: Option<&'a payments::SplitPaymentsRequest>,
pub platform_merchant_id: Option<&'a id_type::MerchantId>,
pub force_3ds_challenge: Option<bool>,
pub force_3ds_challenge_trigger: Option<bool>,
pub processor_merchant_id: &'a id_type::MerchantId,
pub created_by: Option<&'a common_types::CreatedBy>,
pub is_iframe_redirection_enabled: Option<bool>,
pub merchant_reference_id: Option<&'a id_type::PaymentReferenceId>,
pub capture_method: storage_enums::CaptureMethod,
pub authentication_type: Option<common_enums::AuthenticationType>,
pub prerouting_algorithm: Option<&'a routing::PaymentRoutingInfo>,
pub surcharge_amount: Option<common_types::MinorUnit>,
pub billing_address: Option<Secret<&'a address::Address>>,
pub shipping_address: Option<Secret<&'a address::Address>>,
pub tax_on_surcharge: Option<common_types::MinorUnit>,
pub frm_merchant_decision: Option<common_enums::MerchantDecision>,
pub enable_payment_link: common_enums::EnablePaymentLinkRequest,
pub apply_mit_exemption: common_enums::MitExemptionRequest,
pub customer_present: common_enums::PresenceOfCustomerDuringPayment,
pub routing_algorithm_id: Option<&'a id_type::RoutingId>,
pub payment_link_config: Option<&'a PaymentLinkConfigRequestForPayments>,
pub enable_partial_authorization: Option<EnablePartialAuthorizationBool>,
#[serde(flatten)]
infra_values: Option<Value>,
}
impl KafkaPaymentIntentEvent<'_> {
#[cfg(feature = "v1")]
pub fn get_id(&self) -> &id_type::PaymentId {
self.payment_id
}
#[cfg(feature = "v2")]
pub fn get_id(&self) -> &id_type::GlobalPaymentId {
self.payment_id
}
}
#[cfg(feature = "v1")]
impl<'a> KafkaPaymentIntentEvent<'a> {
pub fn from_storage(intent: &'a PaymentIntent, infra_values: Option<Value>) -> Self {
Self {
payment_id: &intent.payment_id,
merchant_id: &intent.merchant_id,
status: intent.status,
amount: intent.amount,
currency: intent.currency,
amount_captured: intent.amount_captured,
customer_id: intent.customer_id.as_ref(),
description: intent.description.as_ref(),
return_url: intent.return_url.as_ref(),
metadata: intent.metadata.as_ref().map(|x| x.to_string()),
connector_id: intent.connector_id.as_ref(),
statement_descriptor_name: intent.statement_descriptor_name.as_ref(),
statement_descriptor_suffix: intent.statement_descriptor_suffix.as_ref(),
created_at: intent.created_at.assume_utc(),
modified_at: intent.modified_at.assume_utc(),
last_synced: intent.last_synced.map(|i| i.assume_utc()),
setup_future_usage: intent.setup_future_usage,
off_session: intent.off_session,
client_secret: intent.client_secret.as_ref(),
active_attempt_id: intent.active_attempt.get_id(),
business_country: intent.business_country,
business_label: intent.business_label.as_ref(),
attempt_count: intent.attempt_count,
profile_id: intent.profile_id.as_ref(),
payment_confirm_source: intent.payment_confirm_source,
// TODO: use typed information here to avoid PII logging
billing_details: None,
shipping_details: None,
customer_email: intent
.customer_details
.as_ref()
.and_then(|value| value.get_inner().peek().as_object())
.and_then(|obj| obj.get("email"))
.and_then(|email| email.as_str())
.map(|email| HashedString::from(Secret::new(email.to_string()))),
feature_metadata: intent.feature_metadata.as_ref(),
merchant_order_reference_id: intent.merchant_order_reference_id.as_ref(),
organization_id: &intent.organization_id,
infra_values: infra_values.clone(),
}
}
}
#[cfg(feature = "v2")]
impl<'a> KafkaPaymentIntentEvent<'a> {
pub fn from_storage(intent: &'a PaymentIntent, infra_values: Option<Value>) -> Self {
let PaymentIntent {
id,
merchant_id,
status,
amount_details,
amount_captured,
customer_id,
description,
return_url,
metadata,
statement_descriptor,
created_at,
modified_at,
last_synced,
setup_future_usage,
active_attempt_id,
active_attempt_id_type,
active_attempts_group_id,
order_details,
allowed_payment_method_types,
connector_metadata,
feature_metadata,
attempt_count,
profile_id,
payment_link_id,
frm_merchant_decision,
updated_by,
request_incremental_authorization,
split_txns_enabled,
authorization_count,
session_expiry,
request_external_three_ds_authentication,
frm_metadata,
customer_details,
merchant_reference_id,
billing_address,
shipping_address,
capture_method,
authentication_type,
prerouting_algorithm,
organization_id,
enable_payment_link,
apply_mit_exemption,
customer_present,
payment_link_config,
routing_algorithm_id,
split_payments,
force_3ds_challenge,
force_3ds_challenge_trigger,
processor_merchant_id,
created_by,
is_iframe_redirection_enabled,
is_payment_id_from_merchant,
enable_partial_authorization,
} = intent;
Self {
payment_id: id,
merchant_id,
status: *status,
amount: amount_details.order_amount,
currency: amount_details.currency,
amount_captured: *amount_captured,
customer_id: customer_id.as_ref(),
description: description.as_ref(),
return_url: return_url.as_ref(),
metadata: metadata.as_ref(),
statement_descriptor: statement_descriptor.as_ref(),
created_at: created_at.assume_utc(),
modified_at: modified_at.assume_utc(),
last_synced: last_synced.map(|t| t.assume_utc()),
setup_future_usage: *setup_future_usage,
off_session: setup_future_usage.is_off_session(),
active_attempt_id: active_attempt_id.as_ref(),
active_attempt_id_type: *active_attempt_id_type,
active_attempts_group_id: active_attempts_group_id.as_ref(),
attempt_count: *attempt_count,
profile_id,
customer_email: None,
feature_metadata: feature_metadata.as_ref(),
organization_id,
order_details: order_details.as_ref(),
allowed_payment_method_types: allowed_payment_method_types.as_ref(),
connector_metadata: connector_metadata.as_ref(),
payment_link_id: payment_link_id.as_ref(),
updated_by,
surcharge_applicable: None,
request_incremental_authorization: *request_incremental_authorization,
split_txns_enabled: *split_txns_enabled,
authorization_count: *authorization_count,
session_expiry: session_expiry.assume_utc(),
request_external_three_ds_authentication: *request_external_three_ds_authentication,
frm_metadata: frm_metadata
.as_ref()
.map(|frm_metadata| frm_metadata.as_ref()),
customer_details: customer_details
.as_ref()
.map(|customer_details| customer_details.get_inner().as_ref()),
shipping_cost: amount_details.shipping_cost,
tax_details: amount_details.tax_details.clone(),
skip_external_tax_calculation: amount_details.get_external_tax_action_as_bool(),
request_extended_authorization: None,
psd2_sca_exemption_type: None,
split_payments: split_payments.as_ref(),
platform_merchant_id: None,
force_3ds_challenge: *force_3ds_challenge,
force_3ds_challenge_trigger: *force_3ds_challenge_trigger,
processor_merchant_id,
created_by: created_by.as_ref(),
is_iframe_redirection_enabled: *is_iframe_redirection_enabled,
merchant_reference_id: merchant_reference_id.as_ref(),
billing_address: billing_address
.as_ref()
.map(|billing_address| Secret::new(billing_address.get_inner())),
shipping_address: shipping_address
.as_ref()
.map(|shipping_address| Secret::new(shipping_address.get_inner())),
capture_method: *capture_method,
authentication_type: *authentication_type,
prerouting_algorithm: prerouting_algorithm.as_ref(),
surcharge_amount: amount_details.surcharge_amount,
tax_on_surcharge: amount_details.tax_on_surcharge,
frm_merchant_decision: *frm_merchant_decision,
enable_payment_link: *enable_payment_link,
apply_mit_exemption: *apply_mit_exemption,
customer_present: *customer_present,
routing_algorithm_id: routing_algorithm_id.as_ref(),
payment_link_config: payment_link_config.as_ref(),
infra_values,
enable_partial_authorization: Some(*enable_partial_authorization),
}
}
}
impl super::KafkaMessage for KafkaPaymentIntentEvent<'_> {
fn key(&self) -> String {
format!(
"{}_{}",
self.merchant_id.get_string_repr(),
self.get_id().get_string_repr(),
)
}
fn event_type(&self) -> crate::events::EventType {
crate::events::EventType::PaymentIntent
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/kafka/dispute_event.rs | crates/router/src/services/kafka/dispute_event.rs | use common_utils::{
ext_traits::StringExt,
types::{AmountConvertor, MinorUnit, StringMinorUnitForConnector},
};
use diesel_models::enums as storage_enums;
use masking::Secret;
use time::OffsetDateTime;
use crate::types::storage::dispute::Dispute;
#[serde_with::skip_serializing_none]
#[derive(serde::Serialize, Debug)]
pub struct KafkaDisputeEvent<'a> {
pub dispute_id: &'a String,
pub dispute_amount: MinorUnit,
pub currency: storage_enums::Currency,
pub dispute_stage: &'a storage_enums::DisputeStage,
pub dispute_status: &'a storage_enums::DisputeStatus,
pub payment_id: &'a common_utils::id_type::PaymentId,
pub attempt_id: &'a String,
pub merchant_id: &'a common_utils::id_type::MerchantId,
pub connector_status: &'a String,
pub connector_dispute_id: &'a String,
pub connector_reason: Option<&'a String>,
pub connector_reason_code: Option<&'a String>,
#[serde(default, with = "time::serde::timestamp::nanoseconds::option")]
pub challenge_required_by: Option<OffsetDateTime>,
#[serde(default, with = "time::serde::timestamp::nanoseconds::option")]
pub connector_created_at: Option<OffsetDateTime>,
#[serde(default, with = "time::serde::timestamp::nanoseconds::option")]
pub connector_updated_at: Option<OffsetDateTime>,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub created_at: OffsetDateTime,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub modified_at: OffsetDateTime,
pub connector: &'a String,
pub evidence: &'a Secret<serde_json::Value>,
pub profile_id: Option<&'a common_utils::id_type::ProfileId>,
pub merchant_connector_id: Option<&'a common_utils::id_type::MerchantConnectorAccountId>,
pub organization_id: &'a common_utils::id_type::OrganizationId,
}
impl<'a> KafkaDisputeEvent<'a> {
pub fn from_storage(dispute: &'a Dispute) -> Self {
let currency = dispute.dispute_currency.unwrap_or(
dispute
.currency
.to_uppercase()
.parse_enum("Currency")
.unwrap_or_default(),
);
Self {
dispute_id: &dispute.dispute_id,
dispute_amount: StringMinorUnitForConnector::convert_back(
&StringMinorUnitForConnector,
dispute.amount.clone(),
currency,
)
.unwrap_or_else(|e| {
router_env::logger::error!("Failed to convert dispute amount: {e:?}");
MinorUnit::new(0)
}),
currency,
dispute_stage: &dispute.dispute_stage,
dispute_status: &dispute.dispute_status,
payment_id: &dispute.payment_id,
attempt_id: &dispute.attempt_id,
merchant_id: &dispute.merchant_id,
connector_status: &dispute.connector_status,
connector_dispute_id: &dispute.connector_dispute_id,
connector_reason: dispute.connector_reason.as_ref(),
connector_reason_code: dispute.connector_reason_code.as_ref(),
challenge_required_by: dispute.challenge_required_by.map(|i| i.assume_utc()),
connector_created_at: dispute.connector_created_at.map(|i| i.assume_utc()),
connector_updated_at: dispute.connector_updated_at.map(|i| i.assume_utc()),
created_at: dispute.created_at.assume_utc(),
modified_at: dispute.modified_at.assume_utc(),
connector: &dispute.connector,
evidence: &dispute.evidence,
profile_id: dispute.profile_id.as_ref(),
merchant_connector_id: dispute.merchant_connector_id.as_ref(),
organization_id: &dispute.organization_id,
}
}
}
impl super::KafkaMessage for KafkaDisputeEvent<'_> {
fn key(&self) -> String {
format!(
"{}_{}_{}",
self.merchant_id.get_string_repr(),
self.payment_id.get_string_repr(),
self.dispute_id
)
}
fn event_type(&self) -> crate::events::EventType {
crate::events::EventType::Dispute
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/kafka/payment_attempt_event.rs | crates/router/src/services/kafka/payment_attempt_event.rs | #[cfg(feature = "v2")]
use common_types::payments;
#[cfg(feature = "v2")]
use common_utils::types;
use common_utils::{id_type, types::MinorUnit};
use diesel_models::enums as storage_enums;
#[cfg(feature = "v2")]
use diesel_models::payment_attempt;
#[cfg(feature = "v2")]
use hyperswitch_domain_models::{
address, payments::payment_attempt::PaymentAttemptFeatureMetadata,
router_response_types::RedirectForm,
};
use hyperswitch_domain_models::{
mandates::MandateDetails, payments::payment_attempt::PaymentAttempt,
};
use time::OffsetDateTime;
#[cfg(feature = "v1")]
#[serde_with::skip_serializing_none]
#[derive(serde::Serialize, Debug)]
pub struct KafkaPaymentAttemptEvent<'a> {
pub payment_id: &'a id_type::PaymentId,
pub merchant_id: &'a id_type::MerchantId,
pub attempt_id: &'a String,
pub status: storage_enums::AttemptStatus,
pub amount: MinorUnit,
pub currency: Option<storage_enums::Currency>,
pub save_to_locker: Option<bool>,
pub connector: Option<&'a String>,
pub error_message: Option<&'a String>,
pub offer_amount: Option<MinorUnit>,
pub surcharge_amount: Option<MinorUnit>,
pub tax_amount: Option<MinorUnit>,
pub payment_method_id: Option<&'a String>,
pub payment_method: Option<storage_enums::PaymentMethod>,
pub connector_transaction_id: Option<&'a String>,
pub capture_method: Option<storage_enums::CaptureMethod>,
#[serde(default, with = "time::serde::timestamp::nanoseconds::option")]
pub capture_on: Option<OffsetDateTime>,
pub confirm: bool,
pub authentication_type: Option<storage_enums::AuthenticationType>,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub created_at: OffsetDateTime,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub modified_at: OffsetDateTime,
#[serde(default, with = "time::serde::timestamp::nanoseconds::option")]
pub last_synced: Option<OffsetDateTime>,
pub cancellation_reason: Option<&'a String>,
pub amount_to_capture: Option<MinorUnit>,
pub mandate_id: Option<&'a String>,
pub browser_info: Option<String>,
pub error_code: Option<&'a String>,
pub connector_metadata: Option<String>,
// TODO: These types should implement copy ideally
pub payment_experience: Option<&'a storage_enums::PaymentExperience>,
pub payment_method_type: Option<&'a storage_enums::PaymentMethodType>,
pub payment_method_data: Option<String>,
pub error_reason: Option<&'a String>,
pub multiple_capture_count: Option<i16>,
pub amount_capturable: MinorUnit,
pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>,
pub net_amount: MinorUnit,
pub unified_code: Option<&'a String>,
pub unified_message: Option<&'a String>,
pub mandate_data: Option<&'a MandateDetails>,
pub client_source: Option<&'a String>,
pub client_version: Option<&'a String>,
pub profile_id: &'a id_type::ProfileId,
pub organization_id: &'a id_type::OrganizationId,
pub card_network: Option<String>,
pub card_discovery: Option<String>,
pub routing_approach: Option<storage_enums::RoutingApproach>,
pub debit_routing_savings: Option<MinorUnit>,
pub signature_network: Option<common_enums::CardNetwork>,
pub is_issuer_regulated: Option<bool>,
}
#[cfg(feature = "v1")]
impl<'a> KafkaPaymentAttemptEvent<'a> {
pub fn from_storage(attempt: &'a PaymentAttempt) -> Self {
let card_payment_method_data = attempt
.get_payment_method_data()
.and_then(|data| data.get_additional_card_info());
Self {
payment_id: &attempt.payment_id,
merchant_id: &attempt.merchant_id,
attempt_id: &attempt.attempt_id,
status: attempt.status,
amount: attempt.net_amount.get_order_amount(),
currency: attempt.currency,
save_to_locker: attempt.save_to_locker,
connector: attempt.connector.as_ref(),
error_message: attempt.error_message.as_ref(),
offer_amount: attempt.offer_amount,
surcharge_amount: attempt.net_amount.get_surcharge_amount(),
tax_amount: attempt.net_amount.get_tax_on_surcharge(),
payment_method_id: attempt.payment_method_id.as_ref(),
payment_method: attempt.payment_method,
connector_transaction_id: attempt.connector_transaction_id.as_ref(),
capture_method: attempt.capture_method,
capture_on: attempt.capture_on.map(|i| i.assume_utc()),
confirm: attempt.confirm,
authentication_type: attempt.authentication_type,
created_at: attempt.created_at.assume_utc(),
modified_at: attempt.modified_at.assume_utc(),
last_synced: attempt.last_synced.map(|i| i.assume_utc()),
cancellation_reason: attempt.cancellation_reason.as_ref(),
amount_to_capture: attempt.amount_to_capture,
mandate_id: attempt.mandate_id.as_ref(),
browser_info: attempt.browser_info.as_ref().map(|v| v.to_string()),
error_code: attempt.error_code.as_ref(),
connector_metadata: attempt.connector_metadata.as_ref().map(|v| v.to_string()),
payment_experience: attempt.payment_experience.as_ref(),
payment_method_type: attempt.payment_method_type.as_ref(),
payment_method_data: attempt.payment_method_data.as_ref().map(|v| v.to_string()),
error_reason: attempt.error_reason.as_ref(),
multiple_capture_count: attempt.multiple_capture_count,
amount_capturable: attempt.amount_capturable,
merchant_connector_id: attempt.merchant_connector_id.as_ref(),
net_amount: attempt.net_amount.get_total_amount(),
unified_code: attempt.unified_code.as_ref(),
unified_message: attempt.unified_message.as_ref(),
mandate_data: attempt.mandate_data.as_ref(),
client_source: attempt.client_source.as_ref(),
client_version: attempt.client_version.as_ref(),
profile_id: &attempt.profile_id,
organization_id: &attempt.organization_id,
card_network: attempt
.payment_method_data
.as_ref()
.and_then(|data| data.as_object())
.and_then(|pm| pm.get("card"))
.and_then(|data| data.as_object())
.and_then(|card| card.get("card_network"))
.and_then(|network| network.as_str())
.map(|network| network.to_string()),
card_discovery: attempt
.card_discovery
.map(|discovery| discovery.to_string()),
routing_approach: attempt.routing_approach.clone(),
debit_routing_savings: attempt.debit_routing_savings,
signature_network: card_payment_method_data
.as_ref()
.and_then(|data| data.signature_network.clone()),
is_issuer_regulated: card_payment_method_data.and_then(|data| data.is_regulated),
}
}
}
#[cfg(feature = "v2")]
#[serde_with::skip_serializing_none]
#[derive(serde::Serialize, Debug)]
pub struct KafkaPaymentAttemptEvent<'a> {
pub payment_id: &'a id_type::GlobalPaymentId,
pub merchant_id: &'a id_type::MerchantId,
pub attempt_id: &'a id_type::GlobalAttemptId,
pub attempts_group_id: Option<&'a id_type::GlobalAttemptGroupId>,
pub status: storage_enums::AttemptStatus,
pub amount: MinorUnit,
pub connector: Option<&'a String>,
pub error_message: Option<&'a String>,
pub surcharge_amount: Option<MinorUnit>,
pub tax_amount: Option<MinorUnit>,
pub payment_method_id: Option<&'a id_type::GlobalPaymentMethodId>,
pub payment_method: storage_enums::PaymentMethod,
pub connector_transaction_id: Option<&'a String>,
pub authentication_type: storage_enums::AuthenticationType,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub created_at: OffsetDateTime,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub modified_at: OffsetDateTime,
#[serde(default, with = "time::serde::timestamp::nanoseconds::option")]
pub last_synced: Option<OffsetDateTime>,
pub cancellation_reason: Option<&'a String>,
pub amount_to_capture: Option<MinorUnit>,
pub browser_info: Option<&'a types::BrowserInformation>,
pub error_code: Option<&'a String>,
pub connector_metadata: Option<String>,
// TODO: These types should implement copy ideally
pub payment_experience: Option<&'a storage_enums::PaymentExperience>,
pub payment_method_type: &'a storage_enums::PaymentMethodType,
pub payment_method_data: Option<String>,
pub error_reason: Option<&'a String>,
pub multiple_capture_count: Option<i16>,
pub amount_capturable: MinorUnit,
pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>,
pub net_amount: MinorUnit,
pub unified_code: Option<&'a String>,
pub unified_message: Option<&'a String>,
pub client_source: Option<&'a String>,
pub client_version: Option<&'a String>,
pub profile_id: &'a id_type::ProfileId,
pub organization_id: &'a id_type::OrganizationId,
pub card_network: Option<String>,
pub card_discovery: Option<String>,
pub connector_payment_id: Option<types::ConnectorTransactionId>,
pub payment_token: Option<String>,
pub preprocessing_step_id: Option<String>,
pub connector_response_reference_id: Option<String>,
pub updated_by: &'a String,
pub encoded_data: Option<&'a masking::Secret<String>>,
pub external_three_ds_authentication_attempted: Option<bool>,
pub authentication_connector: Option<String>,
pub authentication_id: Option<String>,
pub fingerprint_id: Option<String>,
pub customer_acceptance: Option<&'a masking::Secret<payments::CustomerAcceptance>>,
pub shipping_cost: Option<MinorUnit>,
pub order_tax_amount: Option<MinorUnit>,
pub charges: Option<payments::ConnectorChargeResponseData>,
pub processor_merchant_id: &'a id_type::MerchantId,
pub created_by: Option<&'a types::CreatedBy>,
pub payment_method_type_v2: storage_enums::PaymentMethod,
pub payment_method_subtype: storage_enums::PaymentMethodType,
pub routing_result: Option<serde_json::Value>,
pub authentication_applied: Option<common_enums::AuthenticationType>,
pub external_reference_id: Option<String>,
pub tax_on_surcharge: Option<MinorUnit>,
pub payment_method_billing_address: Option<masking::Secret<&'a address::Address>>, // adjusted from Encryption
pub redirection_data: Option<&'a RedirectForm>,
pub connector_payment_data: Option<String>,
pub connector_token_details: Option<&'a payment_attempt::ConnectorTokenDetails>,
pub feature_metadata: Option<&'a PaymentAttemptFeatureMetadata>,
pub network_advice_code: Option<String>,
pub network_decline_code: Option<String>,
pub network_error_message: Option<String>,
pub connector_request_reference_id: Option<String>,
}
#[cfg(feature = "v2")]
impl<'a> KafkaPaymentAttemptEvent<'a> {
pub fn from_storage(attempt: &'a PaymentAttempt) -> Self {
use masking::PeekInterface;
let PaymentAttempt {
payment_id,
merchant_id,
attempts_group_id,
amount_details,
status,
connector,
error,
authentication_type,
created_at,
modified_at,
last_synced,
cancellation_reason,
browser_info,
payment_token,
connector_metadata,
payment_experience,
payment_method_data,
routing_result,
preprocessing_step_id,
multiple_capture_count,
connector_response_reference_id,
updated_by,
redirection_data,
encoded_data,
merchant_connector_id,
external_three_ds_authentication_attempted,
authentication_connector,
authentication_id,
fingerprint_id,
client_source,
client_version,
customer_acceptance,
profile_id,
organization_id,
payment_method_type,
payment_method_id,
connector_payment_id,
payment_method_subtype,
authentication_applied,
external_reference_id,
payment_method_billing_address,
id,
connector_token_details,
card_discovery,
charges,
feature_metadata,
processor_merchant_id,
created_by,
connector_request_reference_id,
network_transaction_id: _,
authorized_amount: _,
} = attempt;
let (connector_payment_id, connector_payment_data) = connector_payment_id
.clone()
.map(types::ConnectorTransactionId::form_id_and_data)
.map(|(txn_id, txn_data)| (Some(txn_id), txn_data))
.unwrap_or((None, None));
Self {
payment_id,
merchant_id,
attempt_id: id,
attempts_group_id: attempts_group_id.as_ref(),
status: *status,
amount: amount_details.get_net_amount(),
connector: connector.as_ref(),
error_message: error.as_ref().map(|error_details| &error_details.message),
surcharge_amount: amount_details.get_surcharge_amount(),
tax_amount: amount_details.get_tax_on_surcharge(),
payment_method_id: payment_method_id.as_ref(),
payment_method: *payment_method_type,
connector_transaction_id: connector_response_reference_id.as_ref(),
authentication_type: *authentication_type,
created_at: created_at.assume_utc(),
modified_at: modified_at.assume_utc(),
last_synced: last_synced.map(|i| i.assume_utc()),
cancellation_reason: cancellation_reason.as_ref(),
amount_to_capture: amount_details.get_amount_to_capture(),
browser_info: browser_info.as_ref(),
error_code: error.as_ref().map(|error_details| &error_details.code),
connector_metadata: connector_metadata.as_ref().map(|v| v.peek().to_string()),
payment_experience: payment_experience.as_ref(),
payment_method_type: payment_method_subtype,
payment_method_data: payment_method_data.as_ref().map(|v| v.peek().to_string()),
error_reason: error
.as_ref()
.and_then(|error_details| error_details.reason.as_ref()),
multiple_capture_count: *multiple_capture_count,
amount_capturable: amount_details.get_amount_capturable(),
merchant_connector_id: merchant_connector_id.as_ref(),
net_amount: amount_details.get_net_amount(),
unified_code: error
.as_ref()
.and_then(|error_details| error_details.unified_code.as_ref()),
unified_message: error
.as_ref()
.and_then(|error_details| error_details.unified_message.as_ref()),
client_source: client_source.as_ref(),
client_version: client_version.as_ref(),
profile_id,
organization_id,
card_network: payment_method_data
.as_ref()
.map(|data| data.peek())
.and_then(|data| data.as_object())
.and_then(|pm| pm.get("card"))
.and_then(|data| data.as_object())
.and_then(|card| card.get("card_network"))
.and_then(|network| network.as_str())
.map(|network| network.to_string()),
card_discovery: card_discovery.map(|discovery| discovery.to_string()),
payment_token: payment_token.clone(),
preprocessing_step_id: preprocessing_step_id.clone(),
connector_response_reference_id: connector_response_reference_id.clone(),
updated_by,
encoded_data: encoded_data.as_ref(),
external_three_ds_authentication_attempted: *external_three_ds_authentication_attempted,
authentication_connector: authentication_connector.clone(),
authentication_id: authentication_id
.as_ref()
.map(|id| id.get_string_repr().to_string()),
fingerprint_id: fingerprint_id.clone(),
customer_acceptance: customer_acceptance.as_ref(),
shipping_cost: amount_details.get_shipping_cost(),
order_tax_amount: amount_details.get_order_tax_amount(),
charges: charges.clone(),
processor_merchant_id,
created_by: created_by.as_ref(),
payment_method_type_v2: *payment_method_type,
connector_payment_id: connector_payment_id.as_ref().cloned(),
payment_method_subtype: *payment_method_subtype,
routing_result: routing_result.clone(),
authentication_applied: *authentication_applied,
external_reference_id: external_reference_id.clone(),
tax_on_surcharge: amount_details.get_tax_on_surcharge(),
payment_method_billing_address: payment_method_billing_address
.as_ref()
.map(|v| masking::Secret::new(v.get_inner())),
redirection_data: redirection_data.as_ref(),
connector_payment_data,
connector_token_details: connector_token_details.as_ref(),
feature_metadata: feature_metadata.as_ref(),
network_advice_code: error
.as_ref()
.and_then(|details| details.network_advice_code.clone()),
network_decline_code: error
.as_ref()
.and_then(|details| details.network_decline_code.clone()),
network_error_message: error
.as_ref()
.and_then(|details| details.network_error_message.clone()),
connector_request_reference_id: connector_request_reference_id.clone(),
}
}
}
impl super::KafkaMessage for KafkaPaymentAttemptEvent<'_> {
#[cfg(feature = "v1")]
fn key(&self) -> String {
format!(
"{}_{}_{}",
self.merchant_id.get_string_repr(),
self.payment_id.get_string_repr(),
self.attempt_id
)
}
#[cfg(feature = "v2")]
fn key(&self) -> String {
format!(
"{}_{}_{}",
self.merchant_id.get_string_repr(),
self.payment_id.get_string_repr(),
self.attempt_id.get_string_repr()
)
}
fn event_type(&self) -> crate::events::EventType {
crate::events::EventType::PaymentAttempt
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/kafka/revenue_recovery.rs | crates/router/src/services/kafka/revenue_recovery.rs | use common_utils::{id_type, types::MinorUnit};
use masking::Secret;
use time::OffsetDateTime;
#[derive(serde::Serialize, Debug)]
pub struct RevenueRecovery<'a> {
pub merchant_id: &'a id_type::MerchantId,
pub invoice_amount: MinorUnit,
pub invoice_currency: &'a common_enums::Currency,
#[serde(default, with = "time::serde::timestamp::nanoseconds::option")]
pub invoice_due_date: Option<OffsetDateTime>,
#[serde(with = "time::serde::timestamp::nanoseconds::option")]
pub invoice_date: Option<OffsetDateTime>,
pub billing_country: Option<&'a common_enums::CountryAlpha2>,
pub billing_state: Option<Secret<String>>,
pub billing_city: Option<Secret<String>>,
pub attempt_amount: MinorUnit,
pub attempt_currency: &'a common_enums::Currency,
pub attempt_status: &'a common_enums::AttemptStatus,
pub pg_error_code: Option<String>,
pub network_advice_code: Option<String>,
pub network_error_code: Option<String>,
pub first_pg_error_code: Option<String>,
pub first_network_advice_code: Option<String>,
pub first_network_error_code: Option<String>,
#[serde(default, with = "time::serde::timestamp::nanoseconds")]
pub attempt_created_at: OffsetDateTime,
pub payment_method_type: Option<&'a common_enums::PaymentMethod>,
pub payment_method_subtype: Option<&'a common_enums::PaymentMethodType>,
pub card_network: Option<&'a common_enums::CardNetwork>,
pub card_issuer: Option<String>,
pub retry_count: Option<i32>,
pub payment_gateway: Option<common_enums::connector_enums::Connector>,
}
impl super::KafkaMessage for RevenueRecovery<'_> {
fn key(&self) -> String {
self.merchant_id.get_string_repr().to_string()
}
fn event_type(&self) -> crate::events::EventType {
crate::events::EventType::RevenueRecovery
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/kafka/dispute.rs | crates/router/src/services/kafka/dispute.rs | use common_utils::{
ext_traits::StringExt,
id_type,
types::{AmountConvertor, MinorUnit, StringMinorUnitForConnector},
};
use diesel_models::enums as storage_enums;
use masking::Secret;
use time::OffsetDateTime;
use crate::types::storage::dispute::Dispute;
#[derive(serde::Serialize, Debug)]
pub struct KafkaDispute<'a> {
pub dispute_id: &'a String,
pub dispute_amount: MinorUnit,
pub currency: storage_enums::Currency,
pub dispute_stage: &'a storage_enums::DisputeStage,
pub dispute_status: &'a storage_enums::DisputeStatus,
pub payment_id: &'a id_type::PaymentId,
pub attempt_id: &'a String,
pub merchant_id: &'a id_type::MerchantId,
pub connector_status: &'a String,
pub connector_dispute_id: &'a String,
pub connector_reason: Option<&'a String>,
pub connector_reason_code: Option<&'a String>,
#[serde(default, with = "time::serde::timestamp::option")]
pub challenge_required_by: Option<OffsetDateTime>,
#[serde(default, with = "time::serde::timestamp::option")]
pub connector_created_at: Option<OffsetDateTime>,
#[serde(default, with = "time::serde::timestamp::option")]
pub connector_updated_at: Option<OffsetDateTime>,
#[serde(default, with = "time::serde::timestamp")]
pub created_at: OffsetDateTime,
#[serde(default, with = "time::serde::timestamp")]
pub modified_at: OffsetDateTime,
pub connector: &'a String,
pub evidence: &'a Secret<serde_json::Value>,
pub profile_id: Option<&'a id_type::ProfileId>,
pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>,
pub organization_id: &'a id_type::OrganizationId,
}
impl<'a> KafkaDispute<'a> {
pub fn from_storage(dispute: &'a Dispute) -> Self {
let currency = dispute.dispute_currency.unwrap_or(
dispute
.currency
.to_uppercase()
.parse_enum("Currency")
.unwrap_or_default(),
);
Self {
dispute_id: &dispute.dispute_id,
dispute_amount: StringMinorUnitForConnector::convert_back(
&StringMinorUnitForConnector,
dispute.amount.clone(),
currency,
)
.unwrap_or_else(|e| {
router_env::logger::error!("Failed to convert dispute amount: {e:?}");
MinorUnit::new(0)
}),
currency,
dispute_stage: &dispute.dispute_stage,
dispute_status: &dispute.dispute_status,
payment_id: &dispute.payment_id,
attempt_id: &dispute.attempt_id,
merchant_id: &dispute.merchant_id,
connector_status: &dispute.connector_status,
connector_dispute_id: &dispute.connector_dispute_id,
connector_reason: dispute.connector_reason.as_ref(),
connector_reason_code: dispute.connector_reason_code.as_ref(),
challenge_required_by: dispute.challenge_required_by.map(|i| i.assume_utc()),
connector_created_at: dispute.connector_created_at.map(|i| i.assume_utc()),
connector_updated_at: dispute.connector_updated_at.map(|i| i.assume_utc()),
created_at: dispute.created_at.assume_utc(),
modified_at: dispute.modified_at.assume_utc(),
connector: &dispute.connector,
evidence: &dispute.evidence,
profile_id: dispute.profile_id.as_ref(),
merchant_connector_id: dispute.merchant_connector_id.as_ref(),
organization_id: &dispute.organization_id,
}
}
}
impl super::KafkaMessage for KafkaDispute<'_> {
fn key(&self) -> String {
format!(
"{}_{}_{}",
self.merchant_id.get_string_repr(),
self.payment_id.get_string_repr(),
self.dispute_id
)
}
fn event_type(&self) -> crate::events::EventType {
crate::events::EventType::Dispute
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/kafka/payment_intent.rs | crates/router/src/services/kafka/payment_intent.rs | #[cfg(feature = "v2")]
use ::common_types::{
payments,
primitive_wrappers::{EnablePartialAuthorizationBool, RequestExtendedAuthorizationBool},
};
#[cfg(feature = "v2")]
use common_enums::RequestIncrementalAuthorization;
use common_utils::{
crypto::Encryptable, hashing::HashedString, id_type, pii, types as common_types,
};
use diesel_models::enums as storage_enums;
#[cfg(feature = "v2")]
use diesel_models::{types as diesel_types, PaymentLinkConfigRequestForPayments};
#[cfg(feature = "v2")]
use diesel_models::{types::OrderDetailsWithAmount, TaxDetails};
use hyperswitch_domain_models::payments::PaymentIntent;
#[cfg(feature = "v2")]
use hyperswitch_domain_models::{address, routing};
use masking::{PeekInterface, Secret};
use serde_json::Value;
use time::OffsetDateTime;
#[cfg(feature = "v1")]
#[derive(serde::Serialize, Debug)]
pub struct KafkaPaymentIntent<'a> {
pub payment_id: &'a id_type::PaymentId,
pub merchant_id: &'a id_type::MerchantId,
pub status: storage_enums::IntentStatus,
pub amount: common_types::MinorUnit,
pub currency: Option<storage_enums::Currency>,
pub amount_captured: Option<common_types::MinorUnit>,
pub customer_id: Option<&'a id_type::CustomerId>,
pub description: Option<&'a String>,
pub return_url: Option<&'a String>,
pub metadata: Option<String>,
pub connector_id: Option<&'a String>,
pub statement_descriptor_name: Option<&'a String>,
pub statement_descriptor_suffix: Option<&'a String>,
#[serde(with = "time::serde::timestamp")]
pub created_at: OffsetDateTime,
#[serde(with = "time::serde::timestamp")]
pub modified_at: OffsetDateTime,
#[serde(default, with = "time::serde::timestamp::option")]
pub last_synced: Option<OffsetDateTime>,
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub off_session: Option<bool>,
pub client_secret: Option<&'a String>,
pub active_attempt_id: String,
pub business_country: Option<storage_enums::CountryAlpha2>,
pub business_label: Option<&'a String>,
pub attempt_count: i16,
pub profile_id: Option<&'a id_type::ProfileId>,
pub payment_confirm_source: Option<storage_enums::PaymentSource>,
pub billing_details: Option<Encryptable<Secret<Value>>>,
pub shipping_details: Option<Encryptable<Secret<Value>>>,
pub customer_email: Option<HashedString<pii::EmailStrategy>>,
pub feature_metadata: Option<&'a Value>,
pub merchant_order_reference_id: Option<&'a String>,
pub organization_id: &'a id_type::OrganizationId,
#[serde(flatten)]
infra_values: Option<Value>,
}
#[cfg(feature = "v1")]
impl<'a> KafkaPaymentIntent<'a> {
pub fn from_storage(intent: &'a PaymentIntent, infra_values: Option<Value>) -> Self {
Self {
payment_id: &intent.payment_id,
merchant_id: &intent.merchant_id,
status: intent.status,
amount: intent.amount,
currency: intent.currency,
amount_captured: intent.amount_captured,
customer_id: intent.customer_id.as_ref(),
description: intent.description.as_ref(),
return_url: intent.return_url.as_ref(),
metadata: intent.metadata.as_ref().map(|x| x.to_string()),
connector_id: intent.connector_id.as_ref(),
statement_descriptor_name: intent.statement_descriptor_name.as_ref(),
statement_descriptor_suffix: intent.statement_descriptor_suffix.as_ref(),
created_at: intent.created_at.assume_utc(),
modified_at: intent.modified_at.assume_utc(),
last_synced: intent.last_synced.map(|i| i.assume_utc()),
setup_future_usage: intent.setup_future_usage,
off_session: intent.off_session,
client_secret: intent.client_secret.as_ref(),
active_attempt_id: intent.active_attempt.get_id(),
business_country: intent.business_country,
business_label: intent.business_label.as_ref(),
attempt_count: intent.attempt_count,
profile_id: intent.profile_id.as_ref(),
payment_confirm_source: intent.payment_confirm_source,
// TODO: use typed information here to avoid PII logging
billing_details: None,
shipping_details: None,
customer_email: intent
.customer_details
.as_ref()
.and_then(|value| value.get_inner().peek().as_object())
.and_then(|obj| obj.get("email"))
.and_then(|email| email.as_str())
.map(|email| HashedString::from(Secret::new(email.to_string()))),
feature_metadata: intent.feature_metadata.as_ref(),
merchant_order_reference_id: intent.merchant_order_reference_id.as_ref(),
organization_id: &intent.organization_id,
infra_values,
}
}
}
#[cfg(feature = "v2")]
#[derive(serde::Serialize, Debug)]
pub struct KafkaPaymentIntent<'a> {
pub payment_id: &'a id_type::GlobalPaymentId,
pub merchant_id: &'a id_type::MerchantId,
pub status: storage_enums::IntentStatus,
pub amount: common_types::MinorUnit,
pub currency: storage_enums::Currency,
pub amount_captured: Option<common_types::MinorUnit>,
pub customer_id: Option<&'a id_type::GlobalCustomerId>,
pub description: Option<&'a common_types::Description>,
pub return_url: Option<&'a common_types::Url>,
pub metadata: Option<&'a Secret<Value>>,
pub statement_descriptor: Option<&'a common_types::StatementDescriptor>,
#[serde(with = "time::serde::timestamp")]
pub created_at: OffsetDateTime,
#[serde(with = "time::serde::timestamp")]
pub modified_at: OffsetDateTime,
#[serde(default, with = "time::serde::timestamp::option")]
pub last_synced: Option<OffsetDateTime>,
pub setup_future_usage: storage_enums::FutureUsage,
pub off_session: bool,
pub active_attempt_id: Option<&'a id_type::GlobalAttemptId>,
pub active_attempt_id_type: common_enums::ActiveAttemptIDType,
pub active_attempts_group_id: Option<&'a id_type::GlobalAttemptGroupId>,
pub attempt_count: i16,
pub profile_id: &'a id_type::ProfileId,
pub customer_email: Option<HashedString<pii::EmailStrategy>>,
pub feature_metadata: Option<&'a diesel_types::FeatureMetadata>,
pub organization_id: &'a id_type::OrganizationId,
pub order_details: Option<&'a Vec<Secret<OrderDetailsWithAmount>>>,
pub allowed_payment_method_types: Option<&'a Vec<common_enums::PaymentMethodType>>,
pub connector_metadata: Option<&'a api_models::payments::ConnectorMetadata>,
pub payment_link_id: Option<&'a String>,
pub updated_by: &'a String,
pub surcharge_applicable: Option<bool>,
pub request_incremental_authorization: RequestIncrementalAuthorization,
pub split_txns_enabled: common_enums::SplitTxnsEnabled,
pub authorization_count: Option<i32>,
#[serde(with = "time::serde::timestamp")]
pub session_expiry: OffsetDateTime,
pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest,
pub frm_metadata: Option<Secret<&'a Value>>,
pub customer_details: Option<Secret<&'a Value>>,
pub shipping_cost: Option<common_types::MinorUnit>,
pub tax_details: Option<TaxDetails>,
pub skip_external_tax_calculation: bool,
pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>,
pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>,
pub split_payments: Option<&'a payments::SplitPaymentsRequest>,
pub platform_merchant_id: Option<&'a id_type::MerchantId>,
pub force_3ds_challenge: Option<bool>,
pub force_3ds_challenge_trigger: Option<bool>,
pub processor_merchant_id: &'a id_type::MerchantId,
pub created_by: Option<&'a common_types::CreatedBy>,
pub is_iframe_redirection_enabled: Option<bool>,
pub merchant_reference_id: Option<&'a id_type::PaymentReferenceId>,
pub capture_method: storage_enums::CaptureMethod,
pub authentication_type: Option<common_enums::AuthenticationType>,
pub prerouting_algorithm: Option<&'a routing::PaymentRoutingInfo>,
pub surcharge_amount: Option<common_types::MinorUnit>,
pub billing_address: Option<Secret<&'a address::Address>>,
pub shipping_address: Option<Secret<&'a address::Address>>,
pub tax_on_surcharge: Option<common_types::MinorUnit>,
pub frm_merchant_decision: Option<common_enums::MerchantDecision>,
pub enable_payment_link: common_enums::EnablePaymentLinkRequest,
pub apply_mit_exemption: common_enums::MitExemptionRequest,
pub customer_present: common_enums::PresenceOfCustomerDuringPayment,
pub routing_algorithm_id: Option<&'a id_type::RoutingId>,
pub payment_link_config: Option<&'a PaymentLinkConfigRequestForPayments>,
pub enable_partial_authorization: Option<EnablePartialAuthorizationBool>,
#[serde(flatten)]
infra_values: Option<Value>,
}
#[cfg(feature = "v2")]
impl<'a> KafkaPaymentIntent<'a> {
pub fn from_storage(intent: &'a PaymentIntent, infra_values: Option<Value>) -> Self {
let PaymentIntent {
id,
merchant_id,
status,
amount_details,
amount_captured,
customer_id,
description,
return_url,
metadata,
statement_descriptor,
created_at,
modified_at,
last_synced,
setup_future_usage,
active_attempt_id,
active_attempt_id_type,
active_attempts_group_id,
order_details,
allowed_payment_method_types,
connector_metadata,
feature_metadata,
attempt_count,
profile_id,
payment_link_id,
frm_merchant_decision,
updated_by,
request_incremental_authorization,
split_txns_enabled,
authorization_count,
session_expiry,
request_external_three_ds_authentication,
frm_metadata,
customer_details,
merchant_reference_id,
billing_address,
shipping_address,
capture_method,
authentication_type,
prerouting_algorithm,
organization_id,
enable_payment_link,
apply_mit_exemption,
customer_present,
payment_link_config,
routing_algorithm_id,
split_payments,
force_3ds_challenge,
force_3ds_challenge_trigger,
processor_merchant_id,
created_by,
is_iframe_redirection_enabled,
is_payment_id_from_merchant,
enable_partial_authorization,
} = intent;
Self {
payment_id: id,
merchant_id,
status: *status,
amount: amount_details.order_amount,
currency: amount_details.currency,
amount_captured: *amount_captured,
customer_id: customer_id.as_ref(),
description: description.as_ref(),
return_url: return_url.as_ref(),
metadata: metadata.as_ref(),
statement_descriptor: statement_descriptor.as_ref(),
created_at: created_at.assume_utc(),
modified_at: modified_at.assume_utc(),
last_synced: last_synced.map(|t| t.assume_utc()),
setup_future_usage: *setup_future_usage,
off_session: setup_future_usage.is_off_session(),
active_attempt_id: active_attempt_id.as_ref(),
active_attempt_id_type: *active_attempt_id_type,
active_attempts_group_id: active_attempts_group_id.as_ref(),
attempt_count: *attempt_count,
profile_id,
customer_email: None,
feature_metadata: feature_metadata.as_ref(),
organization_id,
order_details: order_details.as_ref(),
allowed_payment_method_types: allowed_payment_method_types.as_ref(),
connector_metadata: connector_metadata.as_ref(),
payment_link_id: payment_link_id.as_ref(),
updated_by,
surcharge_applicable: None,
request_incremental_authorization: *request_incremental_authorization,
split_txns_enabled: *split_txns_enabled,
authorization_count: *authorization_count,
session_expiry: session_expiry.assume_utc(),
request_external_three_ds_authentication: *request_external_three_ds_authentication,
frm_metadata: frm_metadata
.as_ref()
.map(|frm_metadata| frm_metadata.as_ref()),
customer_details: customer_details
.as_ref()
.map(|customer_details| customer_details.get_inner().as_ref()),
shipping_cost: amount_details.shipping_cost,
tax_details: amount_details.tax_details.clone(),
skip_external_tax_calculation: amount_details.get_external_tax_action_as_bool(),
request_extended_authorization: None,
psd2_sca_exemption_type: None,
split_payments: split_payments.as_ref(),
platform_merchant_id: None,
force_3ds_challenge: *force_3ds_challenge,
force_3ds_challenge_trigger: *force_3ds_challenge_trigger,
processor_merchant_id,
created_by: created_by.as_ref(),
is_iframe_redirection_enabled: *is_iframe_redirection_enabled,
merchant_reference_id: merchant_reference_id.as_ref(),
billing_address: billing_address
.as_ref()
.map(|billing_address| Secret::new(billing_address.get_inner())),
shipping_address: shipping_address
.as_ref()
.map(|shipping_address| Secret::new(shipping_address.get_inner())),
capture_method: *capture_method,
authentication_type: *authentication_type,
prerouting_algorithm: prerouting_algorithm.as_ref(),
surcharge_amount: amount_details.surcharge_amount,
tax_on_surcharge: amount_details.tax_on_surcharge,
frm_merchant_decision: *frm_merchant_decision,
enable_payment_link: *enable_payment_link,
apply_mit_exemption: *apply_mit_exemption,
customer_present: *customer_present,
routing_algorithm_id: routing_algorithm_id.as_ref(),
payment_link_config: payment_link_config.as_ref(),
infra_values,
enable_partial_authorization: Some(*enable_partial_authorization),
}
}
}
impl KafkaPaymentIntent<'_> {
#[cfg(feature = "v1")]
fn get_id(&self) -> &id_type::PaymentId {
self.payment_id
}
#[cfg(feature = "v2")]
fn get_id(&self) -> &id_type::GlobalPaymentId {
self.payment_id
}
}
impl super::KafkaMessage for KafkaPaymentIntent<'_> {
fn key(&self) -> String {
format!(
"{}_{}",
self.merchant_id.get_string_repr(),
self.get_id().get_string_repr(),
)
}
fn event_type(&self) -> crate::events::EventType {
crate::events::EventType::PaymentIntent
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/kafka/authentication_event.rs | crates/router/src/services/kafka/authentication_event.rs | use diesel_models::enums as storage_enums;
use time::OffsetDateTime;
#[serde_with::skip_serializing_none]
#[derive(serde::Serialize, Debug)]
pub struct KafkaAuthenticationEvent<'a> {
pub authentication_id: &'a common_utils::id_type::AuthenticationId,
pub merchant_id: &'a common_utils::id_type::MerchantId,
pub authentication_connector: Option<&'a String>,
pub connector_authentication_id: Option<&'a String>,
pub authentication_data: Option<serde_json::Value>,
pub payment_method_id: &'a String,
pub authentication_type: Option<storage_enums::DecoupledAuthenticationType>,
pub authentication_status: storage_enums::AuthenticationStatus,
pub authentication_lifecycle_status: storage_enums::AuthenticationLifecycleStatus,
#[serde(default, with = "time::serde::timestamp::milliseconds")]
pub created_at: OffsetDateTime,
#[serde(default, with = "time::serde::timestamp::milliseconds")]
pub modified_at: OffsetDateTime,
pub error_message: Option<&'a String>,
pub error_code: Option<&'a String>,
pub connector_metadata: Option<serde_json::Value>,
pub maximum_supported_version: Option<common_utils::types::SemanticVersion>,
pub threeds_server_transaction_id: Option<&'a String>,
pub cavv: Option<&'a String>,
pub authentication_flow_type: Option<&'a String>,
pub message_version: Option<common_utils::types::SemanticVersion>,
pub eci: Option<&'a String>,
pub trans_status: Option<storage_enums::TransactionStatus>,
pub acquirer_bin: Option<&'a String>,
pub acquirer_merchant_id: Option<&'a String>,
pub three_ds_method_data: Option<&'a String>,
pub three_ds_method_url: Option<&'a String>,
pub acs_url: Option<&'a String>,
pub challenge_request: Option<&'a String>,
pub acs_reference_number: Option<&'a String>,
pub acs_trans_id: Option<&'a String>,
pub acs_signed_content: Option<&'a String>,
pub profile_id: &'a common_utils::id_type::ProfileId,
pub payment_id: Option<&'a common_utils::id_type::PaymentId>,
pub merchant_connector_id: Option<&'a common_utils::id_type::MerchantConnectorAccountId>,
pub ds_trans_id: Option<&'a String>,
pub directory_server_id: Option<&'a String>,
pub acquirer_country_code: Option<&'a String>,
pub organization_id: &'a common_utils::id_type::OrganizationId,
}
impl<'a> KafkaAuthenticationEvent<'a> {
pub fn from_storage(
authentication: &'a hyperswitch_domain_models::authentication::Authentication,
) -> Self {
Self {
created_at: authentication.created_at.assume_utc(),
modified_at: authentication.modified_at.assume_utc(),
authentication_id: &authentication.authentication_id,
merchant_id: &authentication.merchant_id,
authentication_status: authentication.authentication_status,
authentication_connector: authentication.authentication_connector.as_ref(),
connector_authentication_id: authentication.connector_authentication_id.as_ref(),
authentication_data: authentication.authentication_data.clone(),
payment_method_id: &authentication.payment_method_id,
authentication_type: authentication.authentication_type,
authentication_lifecycle_status: authentication.authentication_lifecycle_status,
error_code: authentication.error_code.as_ref(),
error_message: authentication.error_message.as_ref(),
connector_metadata: authentication.connector_metadata.clone(),
maximum_supported_version: authentication.maximum_supported_version.clone(),
threeds_server_transaction_id: authentication.threeds_server_transaction_id.as_ref(),
cavv: authentication.cavv.as_ref(),
authentication_flow_type: authentication.authentication_flow_type.as_ref(),
message_version: authentication.message_version.clone(),
eci: authentication.eci.as_ref(),
trans_status: authentication.trans_status.clone(),
acquirer_bin: authentication.acquirer_bin.as_ref(),
acquirer_merchant_id: authentication.acquirer_merchant_id.as_ref(),
three_ds_method_data: authentication.three_ds_method_data.as_ref(),
three_ds_method_url: authentication.three_ds_method_url.as_ref(),
acs_url: authentication.acs_url.as_ref(),
challenge_request: authentication.challenge_request.as_ref(),
acs_reference_number: authentication.acs_reference_number.as_ref(),
acs_trans_id: authentication.acs_trans_id.as_ref(),
acs_signed_content: authentication.acs_signed_content.as_ref(),
profile_id: &authentication.profile_id,
payment_id: authentication.payment_id.as_ref(),
merchant_connector_id: authentication.merchant_connector_id.as_ref(),
ds_trans_id: authentication.ds_trans_id.as_ref(),
directory_server_id: authentication.directory_server_id.as_ref(),
acquirer_country_code: authentication.acquirer_country_code.as_ref(),
organization_id: &authentication.organization_id,
}
}
}
impl super::KafkaMessage for KafkaAuthenticationEvent<'_> {
fn key(&self) -> String {
format!(
"{}_{}",
self.merchant_id.get_string_repr(),
self.authentication_id.get_string_repr()
)
}
fn event_type(&self) -> crate::events::EventType {
crate::events::EventType::Authentication
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/kafka/refund_event.rs | crates/router/src/services/kafka/refund_event.rs | #[cfg(feature = "v2")]
use common_utils::pii;
#[cfg(feature = "v2")]
use common_utils::types::{self, ChargeRefunds};
use common_utils::{
id_type,
types::{ConnectorTransactionIdTrait, MinorUnit},
};
use diesel_models::{enums as storage_enums, refund::Refund};
use time::OffsetDateTime;
use crate::events;
#[cfg(feature = "v1")]
#[serde_with::skip_serializing_none]
#[derive(serde::Serialize, Debug)]
pub struct KafkaRefundEvent<'a> {
pub internal_reference_id: &'a String,
pub refund_id: &'a String, //merchant_reference id
pub payment_id: &'a id_type::PaymentId,
pub merchant_id: &'a id_type::MerchantId,
pub connector_transaction_id: &'a String,
pub connector: &'a String,
pub connector_refund_id: Option<&'a String>,
pub external_reference_id: Option<&'a String>,
pub refund_type: &'a storage_enums::RefundType,
pub total_amount: &'a MinorUnit,
pub currency: &'a storage_enums::Currency,
pub refund_amount: &'a MinorUnit,
pub refund_status: &'a storage_enums::RefundStatus,
pub sent_to_gateway: &'a bool,
pub refund_error_message: Option<&'a String>,
pub refund_arn: Option<&'a String>,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub created_at: OffsetDateTime,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub modified_at: OffsetDateTime,
pub description: Option<&'a String>,
pub attempt_id: &'a String,
pub refund_reason: Option<&'a String>,
pub refund_error_code: Option<&'a String>,
pub profile_id: Option<&'a id_type::ProfileId>,
pub organization_id: &'a id_type::OrganizationId,
}
#[cfg(feature = "v1")]
impl<'a> KafkaRefundEvent<'a> {
pub fn from_storage(refund: &'a Refund) -> Self {
Self {
internal_reference_id: &refund.internal_reference_id,
refund_id: &refund.refund_id,
payment_id: &refund.payment_id,
merchant_id: &refund.merchant_id,
connector_transaction_id: refund.get_connector_transaction_id(),
connector: &refund.connector,
connector_refund_id: refund.get_optional_connector_refund_id(),
external_reference_id: refund.external_reference_id.as_ref(),
refund_type: &refund.refund_type,
total_amount: &refund.total_amount,
currency: &refund.currency,
refund_amount: &refund.refund_amount,
refund_status: &refund.refund_status,
sent_to_gateway: &refund.sent_to_gateway,
refund_error_message: refund.refund_error_message.as_ref(),
refund_arn: refund.refund_arn.as_ref(),
created_at: refund.created_at.assume_utc(),
modified_at: refund.modified_at.assume_utc(),
description: refund.description.as_ref(),
attempt_id: &refund.attempt_id,
refund_reason: refund.refund_reason.as_ref(),
refund_error_code: refund.refund_error_code.as_ref(),
profile_id: refund.profile_id.as_ref(),
organization_id: &refund.organization_id,
}
}
}
#[cfg(feature = "v2")]
#[serde_with::skip_serializing_none]
#[derive(serde::Serialize, Debug)]
pub struct KafkaRefundEvent<'a> {
pub refund_id: &'a id_type::GlobalRefundId,
pub merchant_reference_id: &'a id_type::RefundReferenceId,
pub payment_id: &'a id_type::GlobalPaymentId,
pub merchant_id: &'a id_type::MerchantId,
pub connector_transaction_id: &'a types::ConnectorTransactionId,
pub connector: &'a String,
pub connector_refund_id: Option<&'a types::ConnectorTransactionId>,
pub external_reference_id: Option<&'a String>,
pub refund_type: &'a storage_enums::RefundType,
pub total_amount: &'a MinorUnit,
pub currency: &'a storage_enums::Currency,
pub refund_amount: &'a MinorUnit,
pub refund_status: &'a storage_enums::RefundStatus,
pub sent_to_gateway: &'a bool,
pub refund_error_message: Option<&'a String>,
pub refund_arn: Option<&'a String>,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub created_at: OffsetDateTime,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub modified_at: OffsetDateTime,
pub description: Option<&'a String>,
pub attempt_id: &'a id_type::GlobalAttemptId,
pub refund_reason: Option<&'a String>,
pub refund_error_code: Option<&'a String>,
pub profile_id: Option<&'a id_type::ProfileId>,
pub organization_id: &'a id_type::OrganizationId,
pub metadata: Option<&'a pii::SecretSerdeValue>,
pub updated_by: &'a String,
pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>,
pub charges: Option<&'a ChargeRefunds>,
pub connector_refund_data: Option<&'a String>,
pub connector_transaction_data: Option<&'a String>,
pub split_refunds: Option<&'a common_types::refunds::SplitRefund>,
pub unified_code: Option<&'a String>,
pub unified_message: Option<&'a String>,
pub processor_refund_data: Option<&'a String>,
pub processor_transaction_data: Option<&'a String>,
}
#[cfg(feature = "v2")]
impl<'a> KafkaRefundEvent<'a> {
pub fn from_storage(refund: &'a Refund) -> Self {
let Refund {
payment_id,
merchant_id,
connector_transaction_id,
connector,
connector_refund_id,
external_reference_id,
refund_type,
total_amount,
currency,
refund_amount,
refund_status,
sent_to_gateway,
refund_error_message,
metadata,
refund_arn,
created_at,
modified_at,
description,
attempt_id,
refund_reason,
refund_error_code,
profile_id,
updated_by,
charges,
organization_id,
split_refunds,
unified_code,
unified_message,
processor_refund_data,
processor_transaction_data,
id,
merchant_reference_id,
connector_id,
} = refund;
Self {
refund_id: id,
merchant_reference_id,
payment_id,
merchant_id,
connector_transaction_id,
connector,
connector_refund_id: connector_refund_id.as_ref(),
external_reference_id: external_reference_id.as_ref(),
refund_type,
total_amount,
currency,
refund_amount,
refund_status,
sent_to_gateway,
refund_error_message: refund_error_message.as_ref(),
refund_arn: refund_arn.as_ref(),
created_at: created_at.assume_utc(),
modified_at: modified_at.assume_utc(),
description: description.as_ref(),
attempt_id,
refund_reason: refund_reason.as_ref(),
refund_error_code: refund_error_code.as_ref(),
profile_id: profile_id.as_ref(),
organization_id,
metadata: metadata.as_ref(),
updated_by,
merchant_connector_id: connector_id.as_ref(),
charges: charges.as_ref(),
connector_refund_data: processor_refund_data.as_ref(),
connector_transaction_data: processor_transaction_data.as_ref(),
split_refunds: split_refunds.as_ref(),
unified_code: unified_code.as_ref(),
unified_message: unified_message.as_ref(),
processor_refund_data: processor_refund_data.as_ref(),
processor_transaction_data: processor_transaction_data.as_ref(),
}
}
}
#[cfg(feature = "v1")]
impl super::KafkaMessage for KafkaRefundEvent<'_> {
fn key(&self) -> String {
format!(
"{}_{}_{}_{}",
self.merchant_id.get_string_repr(),
self.payment_id.get_string_repr(),
self.attempt_id,
self.refund_id
)
}
fn event_type(&self) -> events::EventType {
events::EventType::Refund
}
}
#[cfg(feature = "v2")]
impl super::KafkaMessage for KafkaRefundEvent<'_> {
fn key(&self) -> String {
format!(
"{}_{}_{}_{}",
self.merchant_id.get_string_repr(),
self.payment_id.get_string_repr(),
self.attempt_id.get_string_repr(),
self.merchant_reference_id.get_string_repr()
)
}
fn event_type(&self) -> events::EventType {
events::EventType::Refund
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/kafka/fraud_check_event.rs | crates/router/src/services/kafka/fraud_check_event.rs | use diesel_models::{
enums as storage_enums,
enums::{FraudCheckLastStep, FraudCheckStatus, FraudCheckType},
fraud_check::FraudCheck,
};
use time::OffsetDateTime;
#[derive(serde::Serialize, Debug)]
pub struct KafkaFraudCheckEvent<'a> {
pub frm_id: &'a String,
pub payment_id: &'a common_utils::id_type::PaymentId,
pub merchant_id: &'a common_utils::id_type::MerchantId,
pub attempt_id: &'a String,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub created_at: OffsetDateTime,
pub frm_name: &'a String,
pub frm_transaction_id: Option<&'a String>,
pub frm_transaction_type: FraudCheckType,
pub frm_status: FraudCheckStatus,
pub frm_score: Option<i32>,
pub frm_reason: Option<serde_json::Value>,
pub frm_error: Option<&'a String>,
pub payment_details: Option<serde_json::Value>,
pub metadata: Option<serde_json::Value>,
#[serde(with = "time::serde::timestamp::nanoseconds")]
pub modified_at: OffsetDateTime,
pub last_step: FraudCheckLastStep,
pub payment_capture_method: Option<storage_enums::CaptureMethod>, // In postFrm, we are updating capture method from automatic to manual. To store the merchant actual capture method, we are storing the actual capture method in payment_capture_method. It will be useful while approving the FRM decision.
}
impl<'a> KafkaFraudCheckEvent<'a> {
pub fn from_storage(check: &'a FraudCheck) -> Self {
Self {
frm_id: &check.frm_id,
payment_id: &check.payment_id,
merchant_id: &check.merchant_id,
attempt_id: &check.attempt_id,
created_at: check.created_at.assume_utc(),
frm_name: &check.frm_name,
frm_transaction_id: check.frm_transaction_id.as_ref(),
frm_transaction_type: check.frm_transaction_type,
frm_status: check.frm_status,
frm_score: check.frm_score,
frm_reason: check.frm_reason.clone(),
frm_error: check.frm_error.as_ref(),
payment_details: check.payment_details.clone(),
metadata: check.metadata.clone(),
modified_at: check.modified_at.assume_utc(),
last_step: check.last_step,
payment_capture_method: check.payment_capture_method,
}
}
}
impl super::KafkaMessage for KafkaFraudCheckEvent<'_> {
fn key(&self) -> String {
format!(
"{}_{}_{}_{}",
self.merchant_id.get_string_repr(),
self.payment_id.get_string_repr(),
self.attempt_id,
self.frm_id
)
}
fn event_type(&self) -> crate::events::EventType {
crate::events::EventType::FraudCheck
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/kafka/payout.rs | crates/router/src/services/kafka/payout.rs | use common_utils::{id_type, pii, types::MinorUnit};
use diesel_models::enums as storage_enums;
use hyperswitch_domain_models::payouts::{payout_attempt::PayoutAttempt, payouts::Payouts};
use time::OffsetDateTime;
#[derive(serde::Serialize, Debug)]
pub struct KafkaPayout<'a> {
pub payout_id: &'a id_type::PayoutId,
pub payout_attempt_id: &'a String,
pub merchant_id: &'a id_type::MerchantId,
pub customer_id: Option<&'a id_type::CustomerId>,
pub address_id: Option<&'a String>,
pub profile_id: &'a id_type::ProfileId,
pub payout_method_id: Option<&'a String>,
pub payout_type: Option<storage_enums::PayoutType>,
pub amount: MinorUnit,
pub destination_currency: storage_enums::Currency,
pub source_currency: storage_enums::Currency,
pub description: Option<&'a String>,
pub recurring: bool,
pub auto_fulfill: bool,
pub return_url: Option<&'a String>,
pub entity_type: storage_enums::PayoutEntityType,
pub metadata: Option<pii::SecretSerdeValue>,
#[serde(with = "time::serde::timestamp")]
pub created_at: OffsetDateTime,
#[serde(with = "time::serde::timestamp")]
pub last_modified_at: OffsetDateTime,
pub attempt_count: i16,
pub status: storage_enums::PayoutStatus,
pub priority: Option<storage_enums::PayoutSendPriority>,
pub connector: Option<&'a String>,
pub connector_payout_id: Option<&'a String>,
pub is_eligible: Option<bool>,
pub error_message: Option<&'a String>,
pub error_code: Option<&'a String>,
pub business_country: Option<storage_enums::CountryAlpha2>,
pub business_label: Option<&'a String>,
pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>,
pub organization_id: Option<&'a id_type::OrganizationId>,
}
impl<'a> KafkaPayout<'a> {
pub fn from_storage(payouts: &'a Payouts, payout_attempt: &'a PayoutAttempt) -> Self {
Self {
payout_id: &payouts.payout_id,
payout_attempt_id: &payout_attempt.payout_attempt_id,
merchant_id: &payouts.merchant_id,
customer_id: payouts.customer_id.as_ref(),
address_id: payouts.address_id.as_ref(),
profile_id: &payouts.profile_id,
payout_method_id: payouts.payout_method_id.as_ref(),
payout_type: payouts.payout_type,
amount: payouts.amount,
destination_currency: payouts.destination_currency,
source_currency: payouts.source_currency,
description: payouts.description.as_ref(),
recurring: payouts.recurring,
auto_fulfill: payouts.auto_fulfill,
return_url: payouts.return_url.as_ref(),
entity_type: payouts.entity_type,
metadata: payouts.metadata.clone(),
created_at: payouts.created_at.assume_utc(),
last_modified_at: payouts.last_modified_at.assume_utc(),
attempt_count: payouts.attempt_count,
status: payouts.status,
priority: payouts.priority,
connector: payout_attempt.connector.as_ref(),
connector_payout_id: payout_attempt.connector_payout_id.as_ref(),
is_eligible: payout_attempt.is_eligible,
error_message: payout_attempt.error_message.as_ref(),
error_code: payout_attempt.error_code.as_ref(),
business_country: payout_attempt.business_country,
business_label: payout_attempt.business_label.as_ref(),
merchant_connector_id: payout_attempt.merchant_connector_id.as_ref(),
organization_id: payouts.organization_id.as_ref(),
}
}
}
impl super::KafkaMessage for KafkaPayout<'_> {
fn key(&self) -> String {
format!(
"{}_{}",
self.merchant_id.get_string_repr(),
self.payout_attempt_id
)
}
fn event_type(&self) -> crate::events::EventType {
crate::events::EventType::Payout
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/kafka/authentication.rs | crates/router/src/services/kafka/authentication.rs | use api_models::payments::DeviceChannel;
use common_enums::MerchantCategoryCode;
use diesel_models::enums as storage_enums;
use time::OffsetDateTime;
#[derive(serde::Serialize, Debug)]
pub struct KafkaAuthentication<'a> {
pub authentication_id: &'a common_utils::id_type::AuthenticationId,
pub merchant_id: &'a common_utils::id_type::MerchantId,
pub authentication_connector: Option<&'a String>,
pub connector_authentication_id: Option<&'a String>,
pub authentication_data: Option<serde_json::Value>,
pub payment_method_id: &'a String,
pub authentication_type: Option<storage_enums::DecoupledAuthenticationType>,
pub authentication_status: storage_enums::AuthenticationStatus,
pub authentication_lifecycle_status: storage_enums::AuthenticationLifecycleStatus,
#[serde(default, with = "time::serde::timestamp::milliseconds")]
pub created_at: OffsetDateTime,
#[serde(default, with = "time::serde::timestamp::milliseconds")]
pub modified_at: OffsetDateTime,
pub error_message: Option<&'a String>,
pub error_code: Option<&'a String>,
pub connector_metadata: Option<serde_json::Value>,
pub maximum_supported_version: Option<common_utils::types::SemanticVersion>,
pub threeds_server_transaction_id: Option<&'a String>,
pub cavv: Option<&'a String>,
pub authentication_flow_type: Option<&'a String>,
pub message_version: Option<common_utils::types::SemanticVersion>,
pub eci: Option<&'a String>,
pub trans_status: Option<storage_enums::TransactionStatus>,
pub acquirer_bin: Option<&'a String>,
pub acquirer_merchant_id: Option<&'a String>,
pub three_ds_method_data: Option<&'a String>,
pub three_ds_method_url: Option<&'a String>,
pub acs_url: Option<&'a String>,
pub challenge_request: Option<&'a String>,
pub acs_reference_number: Option<&'a String>,
pub acs_trans_id: Option<&'a String>,
pub acs_signed_content: Option<&'a String>,
pub profile_id: &'a common_utils::id_type::ProfileId,
pub payment_id: Option<&'a common_utils::id_type::PaymentId>,
pub merchant_connector_id: Option<&'a common_utils::id_type::MerchantConnectorAccountId>,
pub ds_trans_id: Option<&'a String>,
pub directory_server_id: Option<&'a String>,
pub acquirer_country_code: Option<&'a String>,
pub organization_id: &'a common_utils::id_type::OrganizationId,
pub platform: Option<&'a DeviceChannel>,
pub mcc: Option<&'a MerchantCategoryCode>,
pub currency: Option<&'a common_enums::Currency>,
pub amount: Option<&'a common_utils::types::MinorUnit>,
pub merchant_country: Option<&'a String>,
pub billing_country: Option<&'a String>,
pub shipping_country: Option<&'a String>,
pub issuer_country: Option<&'a String>,
pub earliest_supported_version: Option<common_utils::types::SemanticVersion>,
pub latest_supported_version: Option<common_utils::types::SemanticVersion>,
pub device_type: Option<&'a String>,
pub device_brand: Option<&'a String>,
pub device_os: Option<&'a String>,
pub device_display: Option<&'a String>,
pub browser_name: Option<&'a String>,
pub browser_version: Option<&'a String>,
pub issuer_id: Option<&'a String>,
pub scheme_name: Option<&'a String>,
pub exemption_requested: Option<bool>,
pub exemption_accepted: Option<bool>,
}
impl<'a> KafkaAuthentication<'a> {
pub fn from_storage(
authentication: &'a hyperswitch_domain_models::authentication::Authentication,
) -> Self {
Self {
created_at: authentication.created_at.assume_utc(),
modified_at: authentication.modified_at.assume_utc(),
authentication_id: &authentication.authentication_id,
merchant_id: &authentication.merchant_id,
authentication_status: authentication.authentication_status,
authentication_connector: authentication.authentication_connector.as_ref(),
connector_authentication_id: authentication.connector_authentication_id.as_ref(),
authentication_data: authentication.authentication_data.clone(),
payment_method_id: &authentication.payment_method_id,
authentication_type: authentication.authentication_type,
authentication_lifecycle_status: authentication.authentication_lifecycle_status,
error_code: authentication.error_code.as_ref(),
error_message: authentication.error_message.as_ref(),
connector_metadata: authentication.connector_metadata.clone(),
maximum_supported_version: authentication.maximum_supported_version.clone(),
threeds_server_transaction_id: authentication.threeds_server_transaction_id.as_ref(),
cavv: authentication.cavv.as_ref(),
authentication_flow_type: authentication.authentication_flow_type.as_ref(),
message_version: authentication.message_version.clone(),
eci: authentication.eci.as_ref(),
trans_status: authentication.trans_status.clone(),
acquirer_bin: authentication.acquirer_bin.as_ref(),
acquirer_merchant_id: authentication.acquirer_merchant_id.as_ref(),
three_ds_method_data: authentication.three_ds_method_data.as_ref(),
three_ds_method_url: authentication.three_ds_method_url.as_ref(),
acs_url: authentication.acs_url.as_ref(),
challenge_request: authentication.challenge_request.as_ref(),
acs_reference_number: authentication.acs_reference_number.as_ref(),
acs_trans_id: authentication.acs_trans_id.as_ref(),
acs_signed_content: authentication.acs_signed_content.as_ref(),
profile_id: &authentication.profile_id,
payment_id: authentication.payment_id.as_ref(),
merchant_connector_id: authentication.merchant_connector_id.as_ref(),
ds_trans_id: authentication.ds_trans_id.as_ref(),
directory_server_id: authentication.directory_server_id.as_ref(),
acquirer_country_code: authentication.acquirer_country_code.as_ref(),
organization_id: &authentication.organization_id,
platform: authentication.platform.as_ref(),
mcc: authentication.mcc.as_ref(),
currency: authentication.currency.as_ref(),
amount: authentication.amount.as_ref(),
merchant_country: authentication.merchant_country_code.as_ref(),
billing_country: authentication.billing_country.as_ref(),
shipping_country: authentication.shipping_country.as_ref(),
issuer_country: authentication.issuer_country.as_ref(),
earliest_supported_version: authentication.earliest_supported_version.clone(),
latest_supported_version: authentication.latest_supported_version.clone(),
device_type: authentication.device_type.as_ref(),
device_brand: authentication.device_brand.as_ref(),
device_os: authentication.device_os.as_ref(),
device_display: authentication.device_display.as_ref(),
browser_name: authentication.browser_name.as_ref(),
browser_version: authentication.browser_version.as_ref(),
issuer_id: authentication.issuer_id.as_ref(),
scheme_name: authentication.scheme_name.as_ref(),
exemption_requested: authentication.exemption_requested,
exemption_accepted: authentication.exemption_accepted,
}
}
}
impl super::KafkaMessage for KafkaAuthentication<'_> {
fn key(&self) -> String {
format!(
"{}_{}",
self.merchant_id.get_string_repr(),
self.authentication_id.get_string_repr()
)
}
fn event_type(&self) -> crate::events::EventType {
crate::events::EventType::Authentication
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/services/kafka/refund.rs | crates/router/src/services/kafka/refund.rs | #[cfg(feature = "v2")]
use common_utils::pii;
#[cfg(feature = "v2")]
use common_utils::types::{self, ChargeRefunds};
use common_utils::{
id_type,
types::{ConnectorTransactionIdTrait, MinorUnit},
};
use diesel_models::{enums as storage_enums, refund::Refund};
use time::OffsetDateTime;
use crate::events;
#[cfg(feature = "v1")]
#[derive(serde::Serialize, Debug)]
pub struct KafkaRefund<'a> {
pub internal_reference_id: &'a String,
pub refund_id: &'a String, //merchant_reference id
pub payment_id: &'a id_type::PaymentId,
pub merchant_id: &'a id_type::MerchantId,
pub connector_transaction_id: &'a String,
pub connector: &'a String,
pub connector_refund_id: Option<&'a String>,
pub external_reference_id: Option<&'a String>,
pub refund_type: &'a storage_enums::RefundType,
pub total_amount: &'a MinorUnit,
pub currency: &'a storage_enums::Currency,
pub refund_amount: &'a MinorUnit,
pub refund_status: &'a storage_enums::RefundStatus,
pub sent_to_gateway: &'a bool,
pub refund_error_message: Option<&'a String>,
pub refund_arn: Option<&'a String>,
#[serde(default, with = "time::serde::timestamp")]
pub created_at: OffsetDateTime,
#[serde(default, with = "time::serde::timestamp")]
pub modified_at: OffsetDateTime,
pub description: Option<&'a String>,
pub attempt_id: &'a String,
pub refund_reason: Option<&'a String>,
pub refund_error_code: Option<&'a String>,
pub profile_id: Option<&'a id_type::ProfileId>,
pub organization_id: &'a id_type::OrganizationId,
}
#[cfg(feature = "v1")]
impl<'a> KafkaRefund<'a> {
pub fn from_storage(refund: &'a Refund) -> Self {
Self {
internal_reference_id: &refund.internal_reference_id,
refund_id: &refund.refund_id,
payment_id: &refund.payment_id,
merchant_id: &refund.merchant_id,
connector_transaction_id: refund.get_connector_transaction_id(),
connector: &refund.connector,
connector_refund_id: refund.get_optional_connector_refund_id(),
external_reference_id: refund.external_reference_id.as_ref(),
refund_type: &refund.refund_type,
total_amount: &refund.total_amount,
currency: &refund.currency,
refund_amount: &refund.refund_amount,
refund_status: &refund.refund_status,
sent_to_gateway: &refund.sent_to_gateway,
refund_error_message: refund.refund_error_message.as_ref(),
refund_arn: refund.refund_arn.as_ref(),
created_at: refund.created_at.assume_utc(),
modified_at: refund.modified_at.assume_utc(),
description: refund.description.as_ref(),
attempt_id: &refund.attempt_id,
refund_reason: refund.refund_reason.as_ref(),
refund_error_code: refund.refund_error_code.as_ref(),
profile_id: refund.profile_id.as_ref(),
organization_id: &refund.organization_id,
}
}
}
#[cfg(feature = "v2")]
#[derive(serde::Serialize, Debug)]
pub struct KafkaRefund<'a> {
pub refund_id: &'a id_type::GlobalRefundId,
pub merchant_reference_id: &'a id_type::RefundReferenceId,
pub payment_id: &'a id_type::GlobalPaymentId,
pub merchant_id: &'a id_type::MerchantId,
pub connector_transaction_id: &'a types::ConnectorTransactionId,
pub connector: &'a String,
pub connector_refund_id: Option<&'a types::ConnectorTransactionId>,
pub external_reference_id: Option<&'a String>,
pub refund_type: &'a storage_enums::RefundType,
pub total_amount: &'a MinorUnit,
pub currency: &'a storage_enums::Currency,
pub refund_amount: &'a MinorUnit,
pub refund_status: &'a storage_enums::RefundStatus,
pub sent_to_gateway: &'a bool,
pub refund_error_message: Option<&'a String>,
pub refund_arn: Option<&'a String>,
#[serde(default, with = "time::serde::timestamp")]
pub created_at: OffsetDateTime,
#[serde(default, with = "time::serde::timestamp")]
pub modified_at: OffsetDateTime,
pub description: Option<&'a String>,
pub attempt_id: &'a id_type::GlobalAttemptId,
pub refund_reason: Option<&'a String>,
pub refund_error_code: Option<&'a String>,
pub profile_id: Option<&'a id_type::ProfileId>,
pub organization_id: &'a id_type::OrganizationId,
pub metadata: Option<&'a pii::SecretSerdeValue>,
pub updated_by: &'a String,
pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>,
pub charges: Option<&'a ChargeRefunds>,
pub connector_refund_data: Option<&'a String>,
pub connector_transaction_data: Option<&'a String>,
pub split_refunds: Option<&'a common_types::refunds::SplitRefund>,
pub unified_code: Option<&'a String>,
pub unified_message: Option<&'a String>,
pub processor_refund_data: Option<&'a String>,
pub processor_transaction_data: Option<&'a String>,
}
#[cfg(feature = "v2")]
impl<'a> KafkaRefund<'a> {
pub fn from_storage(refund: &'a Refund) -> Self {
let Refund {
payment_id,
merchant_id,
connector_transaction_id,
connector,
connector_refund_id,
external_reference_id,
refund_type,
total_amount,
currency,
refund_amount,
refund_status,
sent_to_gateway,
refund_error_message,
metadata,
refund_arn,
created_at,
modified_at,
description,
attempt_id,
refund_reason,
refund_error_code,
profile_id,
updated_by,
charges,
organization_id,
split_refunds,
unified_code,
unified_message,
processor_refund_data,
processor_transaction_data,
id,
merchant_reference_id,
connector_id,
} = refund;
Self {
refund_id: id,
merchant_reference_id,
payment_id,
merchant_id,
connector_transaction_id,
connector,
connector_refund_id: connector_refund_id.as_ref(),
external_reference_id: external_reference_id.as_ref(),
refund_type,
total_amount,
currency,
refund_amount,
refund_status,
sent_to_gateway,
refund_error_message: refund_error_message.as_ref(),
refund_arn: refund_arn.as_ref(),
created_at: created_at.assume_utc(),
modified_at: modified_at.assume_utc(),
description: description.as_ref(),
attempt_id,
refund_reason: refund_reason.as_ref(),
refund_error_code: refund_error_code.as_ref(),
profile_id: profile_id.as_ref(),
organization_id,
metadata: metadata.as_ref(),
updated_by,
merchant_connector_id: connector_id.as_ref(),
charges: charges.as_ref(),
connector_refund_data: processor_refund_data.as_ref(),
connector_transaction_data: processor_transaction_data.as_ref(),
split_refunds: split_refunds.as_ref(),
unified_code: unified_code.as_ref(),
unified_message: unified_message.as_ref(),
processor_refund_data: processor_refund_data.as_ref(),
processor_transaction_data: processor_transaction_data.as_ref(),
}
}
}
impl super::KafkaMessage for KafkaRefund<'_> {
#[cfg(feature = "v1")]
fn key(&self) -> String {
format!(
"{}_{}_{}_{}",
self.merchant_id.get_string_repr(),
self.payment_id.get_string_repr(),
self.attempt_id,
self.refund_id
)
}
#[cfg(feature = "v2")]
fn key(&self) -> String {
format!(
"{}_{}_{}_{}",
self.merchant_id.get_string_repr(),
self.payment_id.get_string_repr(),
self.attempt_id.get_string_repr(),
self.merchant_reference_id.get_string_repr()
)
}
fn event_type(&self) -> events::EventType {
events::EventType::Refund
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/workflows/process_dispute.rs | crates/router/src/workflows/process_dispute.rs | use common_utils::ext_traits::{StringExt, ValueExt};
use diesel_models::process_tracker::business_status;
use error_stack::ResultExt;
use router_env::logger;
use scheduler::{
consumer::{self, types::process_data, workflows::ProcessTrackerWorkflow},
errors as sch_errors, utils as scheduler_utils,
};
#[cfg(feature = "v1")]
use crate::core::webhooks::incoming::get_payment_attempt_from_object_reference_id;
use crate::{
core::disputes,
db::StorageInterface,
errors,
routes::SessionState,
types::{api, domain, storage},
};
pub struct ProcessDisputeWorkflow;
/// This workflow inserts only new dispute records into the dispute table and triggers related outgoing webhook
#[async_trait::async_trait]
impl ProcessTrackerWorkflow<SessionState> for ProcessDisputeWorkflow {
#[cfg(feature = "v2")]
async fn execute_workflow<'a>(
&'a self,
_state: &'a SessionState,
_process: storage::ProcessTracker,
) -> Result<(), sch_errors::ProcessTrackerError> {
todo!()
}
#[cfg(feature = "v1")]
async fn execute_workflow<'a>(
&'a self,
state: &'a SessionState,
process: storage::ProcessTracker,
) -> Result<(), sch_errors::ProcessTrackerError> {
let db: &dyn StorageInterface = &*state.store;
let tracking_data: api::ProcessDisputePTData = process
.tracking_data
.clone()
.parse_value("ProcessDisputePTData")?;
let key_store = db
.get_merchant_key_store_by_merchant_id(
&tracking_data.merchant_id,
&db.get_master_key().to_vec().into(),
)
.await?;
let merchant_account = db
.find_merchant_account_by_merchant_id(&tracking_data.merchant_id, &key_store)
.await?;
let platform = domain::Platform::new(
merchant_account.clone(),
key_store.clone(),
merchant_account,
key_store,
None,
);
let payment_attempt = get_payment_attempt_from_object_reference_id(
state,
tracking_data.dispute_payload.object_reference_id.clone(),
&platform,
)
.await?;
let business_profile = state
.store
.find_business_profile_by_profile_id(
platform.get_processor().get_key_store(),
&payment_attempt.profile_id,
)
.await?;
// Check if the dispute already exists
let dispute = state
.store
.find_by_merchant_id_payment_id_connector_dispute_id(
platform.get_processor().get_account().get_id(),
&payment_attempt.payment_id,
&tracking_data.dispute_payload.connector_dispute_id,
)
.await
.ok()
.flatten();
if dispute.is_some() {
// Dispute already exists — mark the process as complete
state
.store
.as_scheduler()
.finish_process_with_business_status(process, business_status::COMPLETED_BY_PT)
.await?;
} else {
// Update dispute data
let response = disputes::update_dispute_data(
state,
platform,
business_profile,
dispute,
tracking_data.dispute_payload,
payment_attempt,
tracking_data.connector_name.as_str(),
)
.await
.map_err(|error| logger::error!("Dispute update failed: {error}"));
match response {
Ok(_) => {
state
.store
.as_scheduler()
.finish_process_with_business_status(
process,
business_status::COMPLETED_BY_PT,
)
.await?;
}
Err(_) => {
retry_sync_task(
db,
tracking_data.connector_name,
tracking_data.merchant_id,
process,
)
.await?;
}
}
}
Ok(())
}
async fn error_handler<'a>(
&'a self,
state: &'a SessionState,
process: storage::ProcessTracker,
error: sch_errors::ProcessTrackerError,
) -> errors::CustomResult<(), sch_errors::ProcessTrackerError> {
consumer::consumer_error_handler(state.store.as_scheduler(), process, error).await
}
}
pub async fn get_sync_process_schedule_time(
db: &dyn StorageInterface,
connector: &str,
merchant_id: &common_utils::id_type::MerchantId,
retry_count: i32,
) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> {
let mapping: common_utils::errors::CustomResult<
process_data::ConnectorPTMapping,
errors::StorageError,
> = db
.find_config_by_key(&format!("pt_mapping_{connector}"))
.await
.map(|value| value.config)
.and_then(|config| {
config
.parse_struct("ConnectorPTMapping")
.change_context(errors::StorageError::DeserializationFailed)
});
let mapping = match mapping {
Ok(x) => x,
Err(error) => {
logger::info!(?error, "Redis Mapping Error");
process_data::ConnectorPTMapping::default()
}
};
let time_delta = scheduler_utils::get_schedule_time(mapping, merchant_id, retry_count);
Ok(scheduler_utils::get_time_from_delta(time_delta))
}
/// Schedule the task for retry
///
/// Returns bool which indicates whether this was the last retry or not
pub async fn retry_sync_task(
db: &dyn StorageInterface,
connector: String,
merchant_id: common_utils::id_type::MerchantId,
pt: storage::ProcessTracker,
) -> Result<bool, sch_errors::ProcessTrackerError> {
let schedule_time =
get_sync_process_schedule_time(db, &connector, &merchant_id, pt.retry_count + 1).await?;
match schedule_time {
Some(s_time) => {
db.as_scheduler().retry_process(pt, s_time).await?;
Ok(false)
}
None => {
db.as_scheduler()
.finish_process_with_business_status(pt, business_status::RETRIES_EXCEEDED)
.await?;
Ok(true)
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/workflows/payment_sync.rs | crates/router/src/workflows/payment_sync.rs | #[cfg(feature = "v2")]
use common_utils::ext_traits::AsyncExt;
use common_utils::ext_traits::{OptionExt, StringExt, ValueExt};
use diesel_models::process_tracker::business_status;
use error_stack::ResultExt;
use router_env::logger;
use scheduler::{
consumer::{self, types::process_data, workflows::ProcessTrackerWorkflow},
errors as sch_errors, utils as scheduler_utils,
};
#[cfg(feature = "v2")]
use crate::workflows::revenue_recovery::update_token_expiry_based_on_schedule_time;
use crate::{
consts,
core::{
errors::StorageErrorExt,
payments::{self as payment_flows, operations},
},
db::StorageInterface,
errors,
routes::SessionState,
services,
types::{
api, domain,
storage::{self, enums},
},
utils,
};
pub struct PaymentsSyncWorkflow;
#[async_trait::async_trait]
impl ProcessTrackerWorkflow<SessionState> for PaymentsSyncWorkflow {
#[cfg(feature = "v2")]
async fn execute_workflow<'a>(
&'a self,
_state: &'a SessionState,
_process: storage::ProcessTracker,
) -> Result<(), sch_errors::ProcessTrackerError> {
todo!()
}
#[cfg(feature = "v1")]
async fn execute_workflow<'a>(
&'a self,
state: &'a SessionState,
process: storage::ProcessTracker,
) -> Result<(), sch_errors::ProcessTrackerError> {
let db: &dyn StorageInterface = &*state.store;
let tracking_data: api::PaymentsRetrieveRequest = process
.tracking_data
.clone()
.parse_value("PaymentsRetrieveRequest")?;
let key_store = db
.get_merchant_key_store_by_merchant_id(
tracking_data
.merchant_id
.as_ref()
.get_required_value("merchant_id")?,
&db.get_master_key().to_vec().into(),
)
.await?;
let merchant_account = db
.find_merchant_account_by_merchant_id(
tracking_data
.merchant_id
.as_ref()
.get_required_value("merchant_id")?,
&key_store,
)
.await?;
let platform = domain::Platform::new(
merchant_account.clone(),
key_store.clone(),
merchant_account.clone(),
key_store.clone(),
None,
);
// TODO: Add support for ReqState in PT flows
let (mut payment_data, _, customer, _, _) =
Box::pin(payment_flows::payments_operation_core::<
api::PSync,
_,
_,
_,
payment_flows::PaymentData<api::PSync>,
>(
state,
state.get_req_state(),
&platform,
None,
operations::PaymentStatus,
tracking_data.clone(),
payment_flows::CallConnectorAction::Trigger,
None,
services::AuthFlow::Client,
None,
hyperswitch_domain_models::payments::HeaderPayload::default(),
))
.await?;
let terminal_status = [
enums::AttemptStatus::RouterDeclined,
enums::AttemptStatus::Charged,
enums::AttemptStatus::AutoRefunded,
enums::AttemptStatus::Voided,
enums::AttemptStatus::VoidFailed,
enums::AttemptStatus::CaptureFailed,
enums::AttemptStatus::Failure,
];
match &payment_data.payment_attempt.status {
status if terminal_status.contains(status) => {
state
.store
.as_scheduler()
.finish_process_with_business_status(process, business_status::COMPLETED_BY_PT)
.await?
}
_ => {
let connector = payment_data
.payment_attempt
.connector
.clone()
.ok_or(sch_errors::ProcessTrackerError::MissingRequiredField)?;
let is_last_retry = retry_sync_task(
db,
connector,
payment_data.payment_attempt.merchant_id.clone(),
process,
)
.await?;
// If the payment status is still processing and there is no connector transaction_id
// then change the payment status to failed if all retries exceeded
if is_last_retry
&& payment_data.payment_attempt.status == enums::AttemptStatus::Pending
&& payment_data
.payment_attempt
.connector_transaction_id
.as_ref()
.is_none()
{
let payment_intent_update = hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::PGStatusUpdate { status: api_models::enums::IntentStatus::Failed,updated_by: merchant_account.storage_scheme.to_string(), incremental_authorization_allowed: Some(false), feature_metadata: payment_data.payment_intent.feature_metadata.clone().map(masking::Secret::new), };
let payment_attempt_update =
hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptUpdate::ErrorUpdate {
connector: None,
status: api_models::enums::AttemptStatus::Failure,
error_code: None,
error_message: None,
error_reason: Some(Some(
consts::REQUEST_TIMEOUT_ERROR_MESSAGE_FROM_PSYNC.to_string(),
)),
amount_capturable: Some(common_utils::types::MinorUnit::new(0)),
updated_by: merchant_account.storage_scheme.to_string(),
unified_code: None,
unified_message: None,
connector_transaction_id: None,
payment_method_data: None,
authentication_type: None,
issuer_error_code: None,
issuer_error_message: None,
network_details:None,
encrypted_payment_method_data: None,
};
payment_data.payment_attempt = db
.update_payment_attempt_with_attempt_id(
payment_data.payment_attempt,
payment_attempt_update,
merchant_account.storage_scheme,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
payment_data.payment_intent = db
.update_payment_intent(
payment_data.payment_intent,
payment_intent_update,
&key_store,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let profile_id = payment_data
.payment_intent
.profile_id
.as_ref()
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not find profile_id in payment intent")?;
let business_profile = db
.find_business_profile_by_profile_id(&key_store, profile_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
// Trigger the outgoing webhook to notify the merchant about failed payment
let operation = operations::PaymentStatus;
Box::pin(utils::trigger_payments_webhook(
platform,
business_profile,
payment_data,
customer,
state,
operation,
))
.await
.map_err(|error| logger::warn!(payments_outgoing_webhook_error=?error))
.ok();
}
}
};
Ok(())
}
async fn error_handler<'a>(
&'a self,
state: &'a SessionState,
process: storage::ProcessTracker,
error: sch_errors::ProcessTrackerError,
) -> errors::CustomResult<(), sch_errors::ProcessTrackerError> {
consumer::consumer_error_handler(state.store.as_scheduler(), process, error).await
}
}
/// Get the next schedule time
///
/// The schedule time can be configured in configs by this key `pt_mapping_trustpay`
/// ```json
/// {
/// "default_mapping": {
/// "start_after": 60,
/// "frequency": [300],
/// "count": [5]
/// },
/// "max_retries_count": 5
/// }
/// ```
///
/// This config represents
///
/// `start_after`: The first psync should happen after 60 seconds
///
/// `frequency` and `count`: The next 5 retries should have an interval of 300 seconds between them
pub async fn get_sync_process_schedule_time(
db: &dyn StorageInterface,
connector: &str,
merchant_id: &common_utils::id_type::MerchantId,
retry_count: i32,
) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> {
let mapping: common_utils::errors::CustomResult<
process_data::ConnectorPTMapping,
errors::StorageError,
> = db
.find_config_by_key(&format!("pt_mapping_{connector}"))
.await
.map(|value| value.config)
.and_then(|config| {
config
.parse_struct("ConnectorPTMapping")
.change_context(errors::StorageError::DeserializationFailed)
});
let mapping = match mapping {
Ok(x) => x,
Err(error) => {
logger::info!(?error, "Redis Mapping Error");
process_data::ConnectorPTMapping::default()
}
};
let time_delta = scheduler_utils::get_schedule_time(mapping, merchant_id, retry_count);
Ok(scheduler_utils::get_time_from_delta(time_delta))
}
/// Schedule the task for retry
///
/// Returns bool which indicates whether this was the last retry or not
pub async fn retry_sync_task(
db: &dyn StorageInterface,
connector: String,
merchant_id: common_utils::id_type::MerchantId,
pt: storage::ProcessTracker,
) -> Result<bool, sch_errors::ProcessTrackerError> {
let schedule_time =
get_sync_process_schedule_time(db, &connector, &merchant_id, pt.retry_count + 1).await?;
match schedule_time {
Some(s_time) => {
db.as_scheduler().retry_process(pt, s_time).await?;
Ok(false)
}
None => {
db.as_scheduler()
.finish_process_with_business_status(pt, business_status::RETRIES_EXCEEDED)
.await?;
Ok(true)
}
}
}
/// Schedule the task for retry and update redis token expiry time
///
/// Returns bool which indicates whether this was the last retry or not
#[cfg(feature = "v2")]
pub async fn recovery_retry_sync_task(
state: &SessionState,
connector_customer_id: Option<String>,
connector: String,
merchant_id: common_utils::id_type::MerchantId,
pt: storage::ProcessTracker,
) -> Result<bool, sch_errors::ProcessTrackerError> {
let db = &*state.store;
let schedule_time =
get_sync_process_schedule_time(db, &connector, &merchant_id, pt.retry_count + 1).await?;
match schedule_time {
Some(s_time) => {
db.as_scheduler().retry_process(pt, s_time).await?;
connector_customer_id
.async_map(|id| async move {
let _ = update_token_expiry_based_on_schedule_time(state, &id, s_time)
.await
.map_err(|e| {
logger::error!(
error = ?e,
connector_customer_id = %id,
"Failed to update the token expiry time in redis"
);
e
});
})
.await;
Ok(false)
}
None => {
db.as_scheduler()
.finish_process_with_business_status(pt, business_status::RETRIES_EXCEEDED)
.await?;
Ok(true)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_get_default_schedule_time() {
let merchant_id =
common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from("-")).unwrap();
let schedule_time_delta = scheduler_utils::get_schedule_time(
process_data::ConnectorPTMapping::default(),
&merchant_id,
0,
)
.unwrap();
let first_retry_time_delta = scheduler_utils::get_schedule_time(
process_data::ConnectorPTMapping::default(),
&merchant_id,
1,
)
.unwrap();
let cpt_default = process_data::ConnectorPTMapping::default().default_mapping;
assert_eq!(
vec![schedule_time_delta, first_retry_time_delta],
vec![
cpt_default.start_after,
cpt_default.frequencies.first().unwrap().0
]
);
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/workflows/refund_router.rs | crates/router/src/workflows/refund_router.rs | use scheduler::consumer::workflows::ProcessTrackerWorkflow;
#[cfg(feature = "v1")]
use crate::core::refunds as refund_flow;
use crate::{errors, logger::error, routes::SessionState, types::storage};
pub struct RefundWorkflowRouter;
#[async_trait::async_trait]
impl ProcessTrackerWorkflow<SessionState> for RefundWorkflowRouter {
#[cfg(feature = "v1")]
async fn execute_workflow<'a>(
&'a self,
state: &'a SessionState,
process: storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
Ok(Box::pin(refund_flow::start_refund_workflow(state, &process)).await?)
}
#[cfg(feature = "v2")]
async fn execute_workflow<'a>(
&'a self,
_state: &'a SessionState,
_process: storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
todo!()
}
async fn error_handler<'a>(
&'a self,
_state: &'a SessionState,
process: storage::ProcessTracker,
_error: errors::ProcessTrackerError,
) -> errors::CustomResult<(), errors::ProcessTrackerError> {
error!(%process.id, "Failed while executing workflow");
Ok(())
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/workflows/invoice_sync.rs | crates/router/src/workflows/invoice_sync.rs | use async_trait::async_trait;
use common_enums::connector_enums::InvoiceStatus;
use common_utils::{errors::CustomResult, ext_traits::ValueExt};
use router_env::logger;
use scheduler::{
consumer::{self, workflows::ProcessTrackerWorkflow},
errors,
};
use crate::{routes::SessionState, types::storage, utils};
const INVOICE_SYNC_WORKFLOW: &str = "INVOICE_SYNC";
pub struct InvoiceSyncWorkflow;
#[async_trait]
impl ProcessTrackerWorkflow<SessionState> for InvoiceSyncWorkflow {
#[cfg(feature = "v1")]
async fn execute_workflow<'a>(
&'a self,
state: &'a SessionState,
process: storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
let tracking_data = process
.tracking_data
.clone()
.parse_value::<subscriptions::storage::invoice_sync::InvoiceSyncTrackingData>(
"InvoiceSyncTrackingData",
)?;
let subscription_state = state.clone().into();
match process.name.as_deref() {
Some(INVOICE_SYNC_WORKFLOW) => {
let (handler, payments_response) =
Box::pin(subscriptions::workflows::perform_subscription_invoice_sync(
&subscription_state,
process,
tracking_data,
))
.await?;
if handler.invoice.status == InvoiceStatus::InvoicePaid
|| handler.invoice.status == InvoiceStatus::PaymentSucceeded
|| handler.invoice.status == InvoiceStatus::PaymentFailed
{
let _ = utils::trigger_subscriptions_outgoing_webhook(
state,
payments_response,
&handler.invoice,
&handler.subscription,
&handler.merchant_account,
&handler.key_store,
&handler.profile,
)
.await
.map_err(|e| {
logger::error!("Failed to trigger subscriptions outgoing webhook: {e:?}");
errors::ProcessTrackerError::FlowExecutionError {
flow: "Trigger Subscriptions Outgoing Webhook",
}
})?;
}
Ok(())
}
_ => Err(errors::ProcessTrackerError::JobNotFound),
}
}
async fn error_handler<'a>(
&'a self,
state: &'a SessionState,
process: storage::ProcessTracker,
error: errors::ProcessTrackerError,
) -> CustomResult<(), errors::ProcessTrackerError> {
logger::error!("Encountered error");
consumer::consumer_error_handler(state.store.as_scheduler(), process, error).await
}
#[cfg(feature = "v2")]
async fn execute_workflow<'a>(
&'a self,
state: &'a SessionState,
process: storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
Ok(())
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/workflows/revenue_recovery.rs | crates/router/src/workflows/revenue_recovery.rs | #[cfg(feature = "v2")]
use std::collections::HashMap;
#[cfg(feature = "v2")]
use api_models::{
enums::{CardNetwork, RevenueRecoveryAlgorithmType},
payments::PaymentsGetIntentRequest,
};
use common_utils::errors::CustomResult;
#[cfg(feature = "v2")]
use common_utils::{
ext_traits::AsyncExt,
ext_traits::{StringExt, ValueExt},
id_type,
pii::PhoneNumberStrategy,
};
#[cfg(feature = "v2")]
use diesel_models::types::BillingConnectorPaymentMethodDetails;
#[cfg(feature = "v2")]
use error_stack::{Report, ResultExt};
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
use external_services::{
date_time, grpc_client::revenue_recovery::recovery_decider_client as external_grpc_client,
};
#[cfg(feature = "v2")]
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
payments::{payment_attempt, PaymentConfirmData, PaymentIntent, PaymentIntentData},
router_flow_types,
router_flow_types::Authorize,
};
#[cfg(feature = "v2")]
use masking::{ExposeInterface, PeekInterface, Secret};
#[cfg(feature = "v2")]
use rand::Rng;
use router_env::{
logger,
tracing::{self, instrument},
};
use scheduler::{
consumer::{self, workflows::ProcessTrackerWorkflow},
errors,
};
#[cfg(feature = "v2")]
use scheduler::{types::process_data, utils as scheduler_utils};
#[cfg(feature = "v2")]
use storage_impl::errors as storage_errors;
#[cfg(feature = "v2")]
use time::Date;
#[cfg(feature = "v2")]
use crate::core::payments::operations;
#[cfg(feature = "v2")]
use crate::routes::app::ReqState;
#[cfg(feature = "v2")]
use crate::services;
#[cfg(feature = "v2")]
use crate::types::storage::{
revenue_recovery::RetryLimitsConfig,
revenue_recovery_redis_operation::{
PaymentProcessorTokenStatus, PaymentProcessorTokenWithRetryInfo, RedisTokenManager,
},
};
#[cfg(feature = "v2")]
use crate::workflows::revenue_recovery::pcr::api;
#[cfg(feature = "v2")]
use crate::{
consts,
core::{
payments,
revenue_recovery::{self as pcr},
},
db::StorageInterface,
errors::StorageError,
types::{
api::{self as api_types},
domain,
storage::{
revenue_recovery as pcr_storage_types,
revenue_recovery_redis_operation::PaymentProcessorTokenDetails,
},
},
};
use crate::{routes::SessionState, types::storage};
pub struct ExecutePcrWorkflow;
#[cfg(feature = "v2")]
pub const REVENUE_RECOVERY: &str = "revenue_recovery";
#[cfg(feature = "v2")]
const TOTAL_SLOTS_IN_MONTH: i32 = 720;
#[async_trait::async_trait]
impl ProcessTrackerWorkflow<SessionState> for ExecutePcrWorkflow {
#[cfg(feature = "v1")]
async fn execute_workflow<'a>(
&'a self,
_state: &'a SessionState,
_process: storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
Ok(())
}
#[cfg(feature = "v2")]
async fn execute_workflow<'a>(
&'a self,
state: &'a SessionState,
process: storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
let tracking_data = process
.tracking_data
.clone()
.parse_value::<pcr_storage_types::RevenueRecoveryWorkflowTrackingData>(
"PCRWorkflowTrackingData",
)?;
let request = PaymentsGetIntentRequest {
id: tracking_data.global_payment_id.clone(),
};
let revenue_recovery_payment_data =
extract_data_and_perform_action(state, &tracking_data).await?;
let platform_from_revenue_recovery_payment_data = domain::Platform::new(
revenue_recovery_payment_data.merchant_account.clone(),
revenue_recovery_payment_data.key_store.clone(),
revenue_recovery_payment_data.merchant_account.clone(),
revenue_recovery_payment_data.key_store.clone(),
None,
);
let (payment_data, _, _) = payments::payments_intent_operation_core::<
api_types::PaymentGetIntent,
_,
_,
PaymentIntentData<api_types::PaymentGetIntent>,
>(
state,
state.get_req_state(),
platform_from_revenue_recovery_payment_data.clone(),
revenue_recovery_payment_data.profile.clone(),
payments::operations::PaymentGetIntent,
request,
tracking_data.global_payment_id.clone(),
hyperswitch_domain_models::payments::HeaderPayload::default(),
)
.await?;
match process.name.as_deref() {
Some("EXECUTE_WORKFLOW") => {
Box::pin(pcr::perform_execute_payment(
state,
&process,
&revenue_recovery_payment_data.profile.clone(),
platform_from_revenue_recovery_payment_data.clone(),
&tracking_data,
&revenue_recovery_payment_data,
&payment_data.payment_intent,
))
.await
}
Some("PSYNC_WORKFLOW") => {
Box::pin(pcr::perform_payments_sync(
state,
&process,
&revenue_recovery_payment_data.profile.clone(),
platform_from_revenue_recovery_payment_data.clone(),
&tracking_data,
&revenue_recovery_payment_data,
&payment_data.payment_intent,
))
.await?;
Ok(())
}
Some("CALCULATE_WORKFLOW") => {
Box::pin(pcr::perform_calculate_workflow(
state,
&process,
&revenue_recovery_payment_data.profile.clone(),
platform_from_revenue_recovery_payment_data,
&tracking_data,
&revenue_recovery_payment_data,
&payment_data.payment_intent,
))
.await
}
_ => Err(errors::ProcessTrackerError::JobNotFound),
}
}
#[instrument(skip_all)]
async fn error_handler<'a>(
&'a self,
state: &'a SessionState,
process: storage::ProcessTracker,
error: errors::ProcessTrackerError,
) -> CustomResult<(), errors::ProcessTrackerError> {
logger::error!("Encountered error");
consumer::consumer_error_handler(state.store.as_scheduler(), process, error).await
}
}
#[cfg(feature = "v2")]
pub(crate) async fn extract_data_and_perform_action(
state: &SessionState,
tracking_data: &pcr_storage_types::RevenueRecoveryWorkflowTrackingData,
) -> Result<pcr_storage_types::RevenueRecoveryPaymentData, errors::ProcessTrackerError> {
let db = &state.store;
let key_store = db
.get_merchant_key_store_by_merchant_id(
&tracking_data.merchant_id,
&db.get_master_key().to_vec().into(),
)
.await?;
let merchant_account = db
.find_merchant_account_by_merchant_id(&tracking_data.merchant_id, &key_store)
.await?;
let profile = db
.find_business_profile_by_profile_id(&key_store, &tracking_data.profile_id)
.await?;
let billing_mca = db
.find_merchant_connector_account_by_id(&tracking_data.billing_mca_id, &key_store)
.await?;
let pcr_payment_data = pcr_storage_types::RevenueRecoveryPaymentData {
merchant_account,
profile: profile.clone(),
key_store,
billing_mca,
retry_algorithm: profile
.revenue_recovery_retry_algorithm_type
.unwrap_or(tracking_data.revenue_recovery_retry),
psync_data: None,
};
Ok(pcr_payment_data)
}
#[cfg(feature = "v2")]
pub(crate) async fn get_schedule_time_to_retry_mit_payments(
db: &dyn StorageInterface,
merchant_id: &id_type::MerchantId,
retry_count: i32,
) -> Option<time::PrimitiveDateTime> {
let key = "pt_mapping_pcr_retries";
let result = db
.find_config_by_key(key)
.await
.map(|value| value.config)
.and_then(|config| {
config
.parse_struct("RevenueRecoveryPaymentProcessTrackerMapping")
.change_context(StorageError::DeserializationFailed)
});
let mapping = result.map_or_else(
|error| {
if error.current_context().is_db_not_found() {
logger::debug!("Revenue Recovery retry config `{key}` not found, ignoring");
} else {
logger::error!(
?error,
"Failed to read Revenue Recovery retry config `{key}`"
);
}
process_data::RevenueRecoveryPaymentProcessTrackerMapping::default()
},
|mapping| {
logger::debug!(?mapping, "Using custom pcr payments retry config");
mapping
},
);
let time_delta =
scheduler_utils::get_pcr_payments_retry_schedule_time(mapping, merchant_id, retry_count);
scheduler_utils::get_time_from_delta(time_delta)
}
#[derive(Debug, Clone)]
pub struct RetryDecision {
pub retry_time: time::PrimitiveDateTime,
pub decision_threshold: Option<f64>,
}
#[cfg(feature = "v2")]
pub(crate) async fn get_schedule_time_for_smart_retry(
state: &SessionState,
payment_intent: &PaymentIntent,
retry_after_time: Option<prost_types::Timestamp>,
token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,
) -> Result<Option<RetryDecision>, errors::ProcessTrackerError> {
let card_config = &state.conf.revenue_recovery.card_config;
// Not populating it right now
let first_error_message = "None".to_string();
let retry_count_left = token_with_retry_info.monthly_retry_remaining;
let pg_error_code = token_with_retry_info.token_status.error_code.clone();
let card_info = token_with_retry_info
.token_status
.payment_processor_token_details
.clone();
let billing_state = payment_intent
.billing_address
.as_ref()
.and_then(|addr_enc| addr_enc.get_inner().address.as_ref())
.and_then(|details| details.state.as_ref())
.cloned();
let revenue_recovery_metadata = payment_intent
.feature_metadata
.as_ref()
.and_then(|metadata| metadata.payment_revenue_recovery_metadata.as_ref());
let card_network = card_info.card_network.clone();
let total_retry_count_within_network = card_config.get_network_config(card_network.clone());
let card_network_str = card_network.map(|network| network.to_string());
let card_issuer_str = card_info
.card_issuer
.clone()
.filter(|card_issuer| !card_issuer.is_empty());
let card_funding_str = match card_info.card_type.as_deref() {
Some("card") => None,
Some(s) => Some(s.to_string()),
None => None,
};
let start_time_primitive = payment_intent.created_at;
let recovery_timestamp_config = &state.conf.revenue_recovery.recovery_timestamp;
let modified_start_time_primitive = start_time_primitive.saturating_add(
time::Duration::seconds(recovery_timestamp_config.initial_timestamp_in_seconds),
);
let start_time_proto = date_time::convert_to_prost_timestamp(modified_start_time_primitive);
let merchant_id = Some(payment_intent.merchant_id.get_string_repr().to_string());
let invoice_amount = Some(
payment_intent
.amount_details
.order_amount
.get_amount_as_i64(),
);
let invoice_currency = Some(payment_intent.amount_details.currency.to_string());
let billing_country = payment_intent
.billing_address
.as_ref()
.and_then(|addr_enc| addr_enc.get_inner().address.as_ref())
.and_then(|details| details.country.as_ref())
.map(|country| country.to_string());
let billing_city = payment_intent
.billing_address
.as_ref()
.and_then(|addr_enc| addr_enc.get_inner().address.as_ref())
.and_then(|details| details.city.as_ref())
.cloned();
let first_pg_error_code = revenue_recovery_metadata
.and_then(|metadata| metadata.first_payment_attempt_pg_error_code.clone());
let first_network_advice_code = revenue_recovery_metadata
.and_then(|metadata| metadata.first_payment_attempt_network_advice_code.clone());
let first_network_error_code = revenue_recovery_metadata
.and_then(|metadata| metadata.first_payment_attempt_network_decline_code.clone());
let invoice_due_date = revenue_recovery_metadata
.and_then(|metadata| metadata.invoice_next_billing_time)
.map(date_time::convert_to_prost_timestamp);
let decider_request = InternalDeciderRequest {
first_error_message,
billing_state,
card_funding: card_funding_str,
card_network: card_network_str,
card_issuer: card_issuer_str,
invoice_start_time: Some(start_time_proto),
retry_count: Some(token_with_retry_info.total_30_day_retries.into()),
merchant_id,
invoice_amount,
invoice_currency,
invoice_due_date,
billing_country,
billing_city,
attempt_currency: None,
attempt_status: None,
attempt_amount: None,
pg_error_code,
network_advice_code: None,
network_error_code: None,
first_pg_error_code,
first_network_advice_code,
first_network_error_code,
attempt_response_time: None,
payment_method_type: None,
payment_gateway: None,
retry_count_left: Some(retry_count_left.into()),
total_retry_count_within_network: Some(
total_retry_count_within_network
.max_retry_count_for_thirty_day
.into(),
),
first_error_msg_time: None,
wait_time: retry_after_time,
payment_id: Some(payment_intent.get_id().get_string_repr().to_string()),
hourly_retry_history: Some(
token_with_retry_info
.token_status
.daily_retry_history
.clone(),
),
previous_threshold: token_with_retry_info.token_status.decision_threshold,
};
if let Some(mut client) = state.grpc_client.recovery_decider_client.clone() {
match client
.decide_on_retry(decider_request.into(), state.get_recovery_grpc_headers())
.await
{
Ok(grpc_response) => Ok(grpc_response
.retry_flag
.then_some(())
.and(grpc_response.retry_time)
.and_then(|prost_ts| {
match date_time::convert_from_prost_timestamp(&prost_ts) {
Ok(pdt) => {
let response = RetryDecision {
retry_time: pdt,
decision_threshold: grpc_response.decision_threshold,
};
Some(response)
}
Err(e) => {
logger::error!(
"Failed to convert retry_time from prost::Timestamp: {e:?}"
);
None // If conversion fails, treat as no valid retry time
}
}
})),
Err(e) => {
logger::error!("Recovery decider gRPC call failed: {e:?}");
Ok(None)
}
}
} else {
logger::debug!("Recovery decider client is not configured");
Ok(None)
}
}
#[cfg(feature = "v2")]
async fn should_force_schedule_due_to_missed_slots(
state: &SessionState,
card_network: Option<CardNetwork>,
token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,
) -> CustomResult<bool, StorageError> {
// Check monthly retry remaining first
let has_monthly_retries = token_with_retry_info.monthly_retry_remaining >= 1;
// If no monthly retries available, don't force schedule
if !has_monthly_retries {
return Ok(false);
}
Ok(RedisTokenManager::find_nearest_date_from_current(
&token_with_retry_info.token_status.daily_retry_history,
)
// Filter: only consider entries with actual retries (retry_count > 0)
.filter(|(_, retry_count)| *retry_count > 0)
.map(|(most_recent_date, _retry_count)| {
let threshold_hours = TOTAL_SLOTS_IN_MONTH
/ state
.conf
.revenue_recovery
.card_config
.get_network_config(card_network.clone())
.max_retry_count_for_thirty_day;
// Calculate time difference since last retry and compare with threshold
(time::OffsetDateTime::now_utc() - most_recent_date.assume_utc()).whole_hours()
> threshold_hours.into()
})
// Default to false if no valid retry history found (either none exists or all have retry_count = 0)
.unwrap_or(false))
}
#[cfg(feature = "v2")]
pub fn convert_hourly_retry_history(
input: Option<HashMap<time::PrimitiveDateTime, i32>>,
) -> HashMap<String, i32> {
let fmt = time::macros::format_description!(
"[year]-[month]-[day] [hour]:[minute]:[second].[subsecond]"
);
match input {
Some(map) => map
.into_iter()
.map(|(dt, count)| (dt.format(&fmt).unwrap_or(dt.to_string()), count))
.collect(),
None => HashMap::new(),
}
}
#[cfg(feature = "v2")]
#[derive(Debug)]
struct InternalDeciderRequest {
first_error_message: String,
billing_state: Option<Secret<String>>,
card_funding: Option<String>,
card_network: Option<String>,
card_issuer: Option<String>,
invoice_start_time: Option<prost_types::Timestamp>,
retry_count: Option<i64>,
merchant_id: Option<String>,
invoice_amount: Option<i64>,
invoice_currency: Option<String>,
invoice_due_date: Option<prost_types::Timestamp>,
billing_country: Option<String>,
billing_city: Option<String>,
attempt_currency: Option<String>,
attempt_status: Option<String>,
attempt_amount: Option<i64>,
pg_error_code: Option<String>,
network_advice_code: Option<String>,
network_error_code: Option<String>,
first_pg_error_code: Option<String>,
first_network_advice_code: Option<String>,
first_network_error_code: Option<String>,
attempt_response_time: Option<prost_types::Timestamp>,
payment_method_type: Option<String>,
payment_gateway: Option<String>,
retry_count_left: Option<i64>,
total_retry_count_within_network: Option<i64>,
first_error_msg_time: Option<prost_types::Timestamp>,
wait_time: Option<prost_types::Timestamp>,
payment_id: Option<String>,
hourly_retry_history: Option<HashMap<time::PrimitiveDateTime, i32>>,
previous_threshold: Option<f64>,
}
#[cfg(feature = "v2")]
impl From<InternalDeciderRequest> for external_grpc_client::DeciderRequest {
fn from(internal_request: InternalDeciderRequest) -> Self {
Self {
first_error_message: internal_request.first_error_message,
billing_state: internal_request.billing_state.map(|s| s.peek().to_string()),
card_funding: internal_request.card_funding,
card_network: internal_request.card_network,
card_issuer: internal_request.card_issuer,
invoice_start_time: internal_request.invoice_start_time,
retry_count: internal_request.retry_count,
merchant_id: internal_request.merchant_id,
invoice_amount: internal_request.invoice_amount,
invoice_currency: internal_request.invoice_currency,
invoice_due_date: internal_request.invoice_due_date,
billing_country: internal_request.billing_country,
billing_city: internal_request.billing_city,
attempt_currency: internal_request.attempt_currency,
attempt_status: internal_request.attempt_status,
attempt_amount: internal_request.attempt_amount,
pg_error_code: internal_request.pg_error_code,
network_advice_code: internal_request.network_advice_code,
network_error_code: internal_request.network_error_code,
first_pg_error_code: internal_request.first_pg_error_code,
first_network_advice_code: internal_request.first_network_advice_code,
first_network_error_code: internal_request.first_network_error_code,
attempt_response_time: internal_request.attempt_response_time,
payment_method_type: internal_request.payment_method_type,
payment_gateway: internal_request.payment_gateway,
retry_count_left: internal_request.retry_count_left,
total_retry_count_within_network: internal_request.total_retry_count_within_network,
first_error_msg_time: internal_request.first_error_msg_time,
wait_time: internal_request.wait_time,
payment_id: internal_request.payment_id,
hourly_retry_history: convert_hourly_retry_history(
internal_request.hourly_retry_history,
),
previous_threshold: internal_request.previous_threshold,
}
}
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone)]
pub struct ScheduledToken {
pub token_details: PaymentProcessorTokenDetails,
pub retry_decision: RetryDecision,
}
#[cfg(feature = "v2")]
#[derive(Debug)]
struct TokenProcessResult {
scheduled_token: Option<ScheduledToken>,
force_scheduled: bool,
}
#[cfg(feature = "v2")]
pub fn calculate_difference_in_seconds(scheduled_time: time::PrimitiveDateTime) -> i64 {
let now_utc = time::OffsetDateTime::now_utc();
let scheduled_offset_dt = scheduled_time.assume_utc();
let difference = scheduled_offset_dt - now_utc;
difference.whole_seconds()
}
#[cfg(feature = "v2")]
pub async fn update_token_expiry_based_on_schedule_time(
state: &SessionState,
connector_customer_id: &str,
delayed_schedule_time: time::PrimitiveDateTime,
) -> CustomResult<(), errors::ProcessTrackerError> {
let expiry_buffer = state
.conf
.revenue_recovery
.recovery_timestamp
.redis_ttl_buffer_in_seconds;
let expiry_time = calculate_difference_in_seconds(delayed_schedule_time) + expiry_buffer;
RedisTokenManager::update_connector_customer_lock_ttl(
state,
connector_customer_id,
expiry_time,
)
.await
.change_context(errors::ProcessTrackerError::ERedisError(
errors::RedisError::RedisConnectionError.into(),
));
Ok(())
}
#[cfg(feature = "v2")]
#[derive(Debug)]
pub enum PaymentProcessorTokenResponse {
/// Token HardDecline
HardDecline,
/// Token can be retried at this specific time
ScheduledTime {
scheduled_time: time::PrimitiveDateTime,
},
/// Token locked or unavailable, next attempt possible
NextAvailableTime {
next_available_time: time::PrimitiveDateTime,
},
/// No retry info available / nothing to do yet
None,
}
#[cfg(feature = "v2")]
pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type(
state: &SessionState,
connector_customer_id: &str,
payment_intent: &PaymentIntent,
retry_algorithm_type: RevenueRecoveryAlgorithmType,
retry_count: i32,
) -> CustomResult<PaymentProcessorTokenResponse, errors::ProcessTrackerError> {
let mut payment_processor_token_response = PaymentProcessorTokenResponse::None;
match retry_algorithm_type {
RevenueRecoveryAlgorithmType::Monitoring => {
logger::error!("Monitoring type found for Revenue Recovery retry payment");
}
RevenueRecoveryAlgorithmType::Cascading => {
let time = get_schedule_time_to_retry_mit_payments(
state.store.as_ref(),
&payment_intent.merchant_id,
retry_count,
)
.await
.ok_or(errors::ProcessTrackerError::EApiErrorResponse)?;
let payment_processor_token = payment_intent
.feature_metadata
.as_ref()
.and_then(|metadata| metadata.payment_revenue_recovery_metadata.as_ref())
.map(|recovery_metadata| {
recovery_metadata
.billing_connector_payment_details
.payment_processor_token
.clone()
});
let payment_processor_tokens_details =
RedisTokenManager::get_payment_processor_metadata_for_connector_customer(
state,
connector_customer_id,
)
.await
.change_context(errors::ProcessTrackerError::ERedisError(
errors::RedisError::RedisConnectionError.into(),
))?;
// Get the token info from redis
let payment_processor_tokens_details_with_retry_info = payment_processor_token
.as_ref()
.and_then(|t| payment_processor_tokens_details.get(t));
// If payment_processor_tokens_details_with_retry_info is None, then no schedule time
match payment_processor_tokens_details_with_retry_info {
None => {
payment_processor_token_response = PaymentProcessorTokenResponse::None;
logger::debug!("No payment processor token found for cascading retry");
}
Some(payment_token) => {
if payment_token.token_status.is_hard_decline.unwrap_or(false) {
payment_processor_token_response =
PaymentProcessorTokenResponse::HardDecline;
} else if payment_token.retry_wait_time_hours > 0 {
let utc_schedule_time: time::OffsetDateTime =
time::OffsetDateTime::now_utc()
+ time::Duration::hours(payment_token.retry_wait_time_hours);
let next_available_time = time::PrimitiveDateTime::new(
utc_schedule_time.date(),
utc_schedule_time.time(),
);
payment_processor_token_response =
PaymentProcessorTokenResponse::NextAvailableTime {
next_available_time,
};
} else {
payment_processor_token_response =
PaymentProcessorTokenResponse::ScheduledTime {
scheduled_time: time,
};
}
}
}
}
RevenueRecoveryAlgorithmType::Smart => {
payment_processor_token_response = get_best_psp_token_available_for_smart_retry(
state,
connector_customer_id,
payment_intent,
)
.await
.change_context(errors::ProcessTrackerError::EApiErrorResponse)?;
}
}
match &mut payment_processor_token_response {
PaymentProcessorTokenResponse::HardDecline => {
logger::debug!("Token is hard declined");
}
PaymentProcessorTokenResponse::ScheduledTime { scheduled_time } => {
// Add random delay to schedule time
*scheduled_time = add_random_delay_to_schedule_time(state, *scheduled_time);
// Log the scheduled retry time at debug level
logger::info!("Retry scheduled at {:?}", scheduled_time);
// Update token expiry based on schedule time
update_token_expiry_based_on_schedule_time(
state,
connector_customer_id,
*scheduled_time,
)
.await;
}
PaymentProcessorTokenResponse::NextAvailableTime {
next_available_time,
} => {
logger::info!("Next available retry at {:?}", next_available_time);
}
PaymentProcessorTokenResponse::None => {
logger::debug!("No retry info available");
}
}
Ok(payment_processor_token_response)
}
#[cfg(feature = "v2")]
pub async fn get_best_psp_token_available_for_smart_retry(
state: &SessionState,
connector_customer_id: &str,
payment_intent: &PaymentIntent,
) -> CustomResult<PaymentProcessorTokenResponse, errors::ProcessTrackerError> {
// Lock using payment_id
let locked_acquired = RedisTokenManager::lock_connector_customer_status(
state,
connector_customer_id,
&payment_intent.id,
)
.await
.change_context(errors::ProcessTrackerError::ERedisError(
errors::RedisError::RedisConnectionError.into(),
))?;
match (locked_acquired, payment_intent.status) {
(true, _) | (false, common_enums::IntentStatus::PartiallyCaptured) => {
let payment_processor_token_response = get_payment_processor_token_by_calling_decider(
state,
payment_intent,
connector_customer_id,
)
.await?;
Ok(payment_processor_token_response)
}
(false, _) => {
let token_details =
RedisTokenManager::get_payment_processor_metadata_for_connector_customer(
state,
connector_customer_id,
)
.await
.change_context(errors::ProcessTrackerError::ERedisError(
errors::RedisError::RedisConnectionError.into(),
))?;
// Check token with schedule time in Redis
let token_info_with_schedule_time = token_details
.values()
.find(|info| info.token_status.scheduled_at.is_some());
// Check for hard decline if info is none
let hard_decline_status = token_details
.values()
.all(|token| token.token_status.is_hard_decline.unwrap_or(false));
let mut payment_processor_token_response = PaymentProcessorTokenResponse::None;
if hard_decline_status {
payment_processor_token_response = PaymentProcessorTokenResponse::HardDecline;
} else {
payment_processor_token_response = match token_info_with_schedule_time
.as_ref()
.and_then(|t| t.token_status.scheduled_at)
{
Some(scheduled_time) => PaymentProcessorTokenResponse::NextAvailableTime {
next_available_time: scheduled_time,
},
None => PaymentProcessorTokenResponse::None,
};
}
Ok(payment_processor_token_response)
}
}
}
#[cfg(feature = "v2")]
async fn get_payment_processor_token_by_calling_decider(
state: &SessionState,
payment_intent: &PaymentIntent,
connector_customer_id: &str,
) -> CustomResult<PaymentProcessorTokenResponse, errors::ProcessTrackerError> {
// Get existing tokens from Redis
let existing_tokens = RedisTokenManager::get_connector_customer_payment_processor_tokens(
state,
connector_customer_id,
)
.await
.change_context(errors::ProcessTrackerError::ERedisError(
errors::RedisError::RedisConnectionError.into(),
))?;
let active_tokens: HashMap<_, _> = existing_tokens
.into_iter()
.filter(|(_, token_status)| token_status.is_active != Some(false))
.collect();
let result = RedisTokenManager::get_tokens_with_retry_metadata(state, &active_tokens);
let payment_processor_token_response =
call_decider_for_payment_processor_tokens_select_closest_time(
state,
&result,
payment_intent,
connector_customer_id,
)
.await
.change_context(errors::ProcessTrackerError::EApiErrorResponse)?;
Ok(payment_processor_token_response)
}
#[cfg(feature = "v2")]
pub async fn calculate_smart_retry_time(
state: &SessionState,
payment_intent: &PaymentIntent,
token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,
) -> Result<(Option<RetryDecision>, bool), errors::ProcessTrackerError> {
let wait_hours = token_with_retry_info.retry_wait_time_hours;
let current_time = time::OffsetDateTime::now_utc();
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/workflows/api_key_expiry.rs | crates/router/src/workflows/api_key_expiry.rs | use common_utils::{errors::ValidationError, ext_traits::ValueExt, types::user::ThemeLineage};
use diesel_models::{
enums as storage_enums, process_tracker::business_status, ApiKeyExpiryTrackingData,
};
use router_env::logger;
use scheduler::{workflows::ProcessTrackerWorkflow, SchedulerSessionState};
use crate::{
consts, errors,
logger::error,
routes::{metrics, SessionState},
services::email::types::ApiKeyExpiryReminder,
types::{api, domain::UserEmail, storage},
utils::{
user::{self as user_utils, theme as theme_utils},
OptionExt,
},
};
pub struct ApiKeyExpiryWorkflow;
#[async_trait::async_trait]
impl ProcessTrackerWorkflow<SessionState> for ApiKeyExpiryWorkflow {
async fn execute_workflow<'a>(
&'a self,
state: &'a SessionState,
process: storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
let db = &*state.store;
let tracking_data: ApiKeyExpiryTrackingData = process
.tracking_data
.clone()
.parse_value("ApiKeyExpiryTrackingData")?;
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
&tracking_data.merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await?;
let merchant_account = db
.find_merchant_account_by_merchant_id(&tracking_data.merchant_id, &key_store)
.await?;
let email_id = merchant_account
.merchant_details
.clone()
.parse_value::<api::MerchantDetails>("MerchantDetails")?
.primary_email
.ok_or(errors::ProcessTrackerError::EValidationError(
ValidationError::MissingRequiredField {
field_name: "email".to_string(),
}
.into(),
))?;
let task_id = process.id.clone();
let retry_count = process.retry_count;
let api_key_name = tracking_data.api_key_name.clone();
let prefix = tracking_data.prefix.clone();
let expires_in = tracking_data
.expiry_reminder_days
.get(
usize::try_from(retry_count)
.map_err(|_| errors::ProcessTrackerError::TypeConversionError)?,
)
.ok_or(errors::ProcessTrackerError::EApiErrorResponse)?;
let theme = theme_utils::get_most_specific_theme_using_lineage(
state,
ThemeLineage::Merchant {
tenant_id: state.tenant.tenant_id.clone(),
org_id: merchant_account.get_org_id().clone(),
merchant_id: merchant_account.get_id().clone(),
},
)
.await
.map_err(|err| {
logger::error!(?err, "Failed to get theme");
errors::ProcessTrackerError::EApiErrorResponse
})?;
let email_contents = ApiKeyExpiryReminder {
recipient_email: UserEmail::from_pii_email(email_id).map_err(|error| {
logger::error!(
?error,
"Failed to convert recipient's email to UserEmail from pii::Email"
);
errors::ProcessTrackerError::EApiErrorResponse
})?,
subject: consts::EMAIL_SUBJECT_API_KEY_EXPIRY,
expires_in: *expires_in,
api_key_name,
prefix,
theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()),
theme_config: theme
.map(|theme| theme.email_config())
.unwrap_or(state.conf.theme.email_config.clone()),
};
state
.email_client
.clone()
.compose_and_send_email(
user_utils::get_base_url(state),
Box::new(email_contents),
state.conf.proxy.https_url.as_ref(),
)
.await
.map_err(errors::ProcessTrackerError::EEmailError)?;
// If all the mails have been sent, then retry_count would be equal to length of the expiry_reminder_days vector
if retry_count
== i32::try_from(tracking_data.expiry_reminder_days.len() - 1)
.map_err(|_| errors::ProcessTrackerError::TypeConversionError)?
{
state
.get_db()
.as_scheduler()
.finish_process_with_business_status(process, business_status::COMPLETED_BY_PT)
.await?
}
// If tasks are remaining that has to be scheduled
else {
let expiry_reminder_day = tracking_data
.expiry_reminder_days
.get(
usize::try_from(retry_count + 1)
.map_err(|_| errors::ProcessTrackerError::TypeConversionError)?,
)
.ok_or(errors::ProcessTrackerError::EApiErrorResponse)?;
let updated_schedule_time = tracking_data.api_key_expiry.map(|api_key_expiry| {
api_key_expiry.saturating_sub(time::Duration::days(i64::from(*expiry_reminder_day)))
});
let updated_process_tracker_data = storage::ProcessTrackerUpdate::Update {
name: None,
retry_count: Some(retry_count + 1),
schedule_time: updated_schedule_time,
tracking_data: None,
business_status: None,
status: Some(storage_enums::ProcessTrackerStatus::New),
updated_at: Some(common_utils::date_time::now()),
};
let task_ids = vec![task_id];
db.process_tracker_update_process_status_by_ids(task_ids, updated_process_tracker_data)
.await?;
// Remaining tasks are re-scheduled, so will be resetting the added count
metrics::TASKS_RESET_COUNT
.add(1, router_env::metric_attributes!(("flow", "ApiKeyExpiry")));
}
Ok(())
}
async fn error_handler<'a>(
&'a self,
_state: &'a SessionState,
process: storage::ProcessTracker,
_error: errors::ProcessTrackerError,
) -> errors::CustomResult<(), errors::ProcessTrackerError> {
error!(%process.id, "Failed while executing workflow");
Ok(())
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/workflows/attach_payout_account_workflow.rs | crates/router/src/workflows/attach_payout_account_workflow.rs | use common_utils::{
consts::DEFAULT_LOCALE,
ext_traits::{OptionExt, ValueExt},
};
use scheduler::{
consumer::{self, workflows::ProcessTrackerWorkflow},
errors,
};
use crate::{
core::payouts,
errors as core_errors,
routes::SessionState,
types::{api, domain, storage},
};
pub struct AttachPayoutAccountWorkflow;
#[async_trait::async_trait]
impl ProcessTrackerWorkflow<SessionState> for AttachPayoutAccountWorkflow {
async fn execute_workflow<'a>(
&'a self,
state: &'a SessionState,
process: storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
// Gather context
let db = &*state.store;
let tracking_data: api::PayoutRetrieveRequest = process
.tracking_data
.clone()
.parse_value("PayoutRetrieveRequest")?;
let merchant_id = tracking_data
.merchant_id
.clone()
.get_required_value("merchant_id")?;
let key_store = db
.get_merchant_key_store_by_merchant_id(
&merchant_id,
&db.get_master_key().to_vec().into(),
)
.await?;
let merchant_account = db
.find_merchant_account_by_merchant_id(&merchant_id, &key_store)
.await?;
let request = api::payouts::PayoutRequest::PayoutRetrieveRequest(tracking_data);
let platform = domain::Platform::new(
merchant_account.clone(),
key_store.clone(),
merchant_account,
key_store,
None,
);
let mut payout_data = Box::pin(payouts::make_payout_data(
state,
&platform,
None,
&request,
DEFAULT_LOCALE,
))
.await?;
payouts::payouts_core(state, &platform, &mut payout_data, None, None).await?;
Ok(())
}
async fn error_handler<'a>(
&'a self,
state: &'a SessionState,
process: storage::ProcessTracker,
error: errors::ProcessTrackerError,
) -> core_errors::CustomResult<(), errors::ProcessTrackerError> {
consumer::consumer_error_handler(state.store.as_scheduler(), process, error).await
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/workflows/tokenized_data.rs | crates/router/src/workflows/tokenized_data.rs | use scheduler::consumer::workflows::ProcessTrackerWorkflow;
#[cfg(feature = "v1")]
use crate::core::payment_methods::vault;
use crate::{errors, logger::error, routes::SessionState, types::storage};
pub struct DeleteTokenizeDataWorkflow;
#[async_trait::async_trait]
impl ProcessTrackerWorkflow<SessionState> for DeleteTokenizeDataWorkflow {
#[cfg(feature = "v1")]
async fn execute_workflow<'a>(
&'a self,
state: &'a SessionState,
process: storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
Ok(vault::start_tokenize_data_workflow(state, &process).await?)
}
#[cfg(feature = "v2")]
async fn execute_workflow<'a>(
&'a self,
_state: &'a SessionState,
_process: storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
todo!()
}
async fn error_handler<'a>(
&'a self,
_state: &'a SessionState,
process: storage::ProcessTracker,
_error: errors::ProcessTrackerError,
) -> errors::CustomResult<(), errors::ProcessTrackerError> {
error!(%process.id, "Failed while executing workflow");
Ok(())
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/workflows/outgoing_webhook_retry.rs | crates/router/src/workflows/outgoing_webhook_retry.rs | #[cfg(feature = "payouts")]
use api_models::payouts as payout_models;
use api_models::{
enums::EventType,
webhook_events::OutgoingWebhookRequestContent,
webhooks::{OutgoingWebhook, OutgoingWebhookContent},
};
use common_utils::{
consts::DEFAULT_LOCALE,
ext_traits::{StringExt, ValueExt},
id_type,
};
use diesel_models::process_tracker::business_status;
use error_stack::ResultExt;
use masking::PeekInterface;
use router_env::tracing::{self, instrument};
use scheduler::{
consumer::{self, workflows::ProcessTrackerWorkflow},
types::process_data,
utils as scheduler_utils,
};
#[cfg(feature = "v1")]
use subscriptions::workflows::invoice_sync;
#[cfg(feature = "payouts")]
use crate::core::payouts;
use crate::{
core::{
payments,
webhooks::{self as webhooks_core, types::OutgoingWebhookTrackingData},
},
db::StorageInterface,
errors, logger,
routes::{app::ReqState, SessionState},
types::{domain, storage},
};
pub struct OutgoingWebhookRetryWorkflow;
#[async_trait::async_trait]
impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow {
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn execute_workflow<'a>(
&'a self,
state: &'a SessionState,
process: storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
let delivery_attempt = storage::enums::WebhookDeliveryAttempt::AutomaticRetry;
let tracking_data: OutgoingWebhookTrackingData = process
.tracking_data
.clone()
.parse_value("OutgoingWebhookTrackingData")?;
let db = &*state.store;
let key_store = db
.get_merchant_key_store_by_merchant_id(
&tracking_data.merchant_id,
&db.get_master_key().to_vec().into(),
)
.await?;
let business_profile = db
.find_business_profile_by_profile_id(&key_store, &tracking_data.business_profile_id)
.await?;
let event_id = webhooks_core::utils::generate_event_id();
let idempotent_event_id = webhooks_core::utils::get_idempotent_event_id(
&tracking_data.primary_object_id,
tracking_data.event_type,
delivery_attempt,
)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to generate idempotent event ID")?;
let initial_event = match &tracking_data.initial_attempt_id {
Some(initial_attempt_id) => {
db.find_event_by_merchant_id_event_id(
&business_profile.merchant_id,
initial_attempt_id,
&key_store,
)
.await?
}
// Tracking data inserted by old version of application, fetch event using old event ID
// format
None => {
let old_event_id = format!(
"{}_{}",
tracking_data.primary_object_id, tracking_data.event_type
);
db.find_event_by_merchant_id_event_id(
&business_profile.merchant_id,
&old_event_id,
&key_store,
)
.await?
}
};
let now = common_utils::date_time::now();
let new_event = domain::Event {
event_id,
event_type: initial_event.event_type,
event_class: initial_event.event_class,
is_webhook_notified: false,
primary_object_id: initial_event.primary_object_id,
primary_object_type: initial_event.primary_object_type,
created_at: now,
merchant_id: Some(business_profile.merchant_id.clone()),
business_profile_id: Some(business_profile.get_id().to_owned()),
primary_object_created_at: initial_event.primary_object_created_at,
idempotent_event_id: Some(idempotent_event_id),
initial_attempt_id: Some(initial_event.event_id.clone()),
request: initial_event.request,
response: None,
delivery_attempt: Some(delivery_attempt),
metadata: initial_event.metadata,
is_overall_delivery_successful: Some(false),
};
let event = db
.insert_event(new_event, &key_store)
.await
.inspect_err(|error| {
logger::error!(?error, "Failed to insert event in events table");
})?;
match &event.request {
Some(request) => {
let request_content: OutgoingWebhookRequestContent = request
.get_inner()
.peek()
.parse_struct("OutgoingWebhookRequestContent")?;
Box::pin(webhooks_core::trigger_webhook_and_raise_event(
state.clone(),
business_profile,
&key_store,
event,
request_content,
delivery_attempt,
None,
Some(process),
))
.await;
}
// Event inserted by old version of application, fetch current information about
// resource
None => {
let merchant_account = db
.find_merchant_account_by_merchant_id(&tracking_data.merchant_id, &key_store)
.await?;
let platform = domain::Platform::new(
merchant_account.clone(),
key_store.clone(),
merchant_account.clone(),
key_store.clone(),
None,
);
// TODO: Add request state for the PT flows as well
let (content, event_type) = Box::pin(get_outgoing_webhook_content_and_event_type(
state.clone(),
state.get_req_state(),
merchant_account.clone(),
key_store.clone(),
&tracking_data,
))
.await?;
match event_type {
// Resource status is same as the event type of the current event
Some(event_type) if event_type == tracking_data.event_type => {
let outgoing_webhook = OutgoingWebhook {
merchant_id: tracking_data.merchant_id.clone(),
event_id: event.event_id.clone(),
event_type,
content: content.clone(),
timestamp: event.created_at,
};
let request_content = webhooks_core::get_outgoing_webhook_request(
&platform,
outgoing_webhook,
&business_profile,
)
.map_err(|error| {
logger::error!(
?error,
"Failed to obtain outgoing webhook request content"
);
errors::ProcessTrackerError::EApiErrorResponse
})?;
Box::pin(webhooks_core::trigger_webhook_and_raise_event(
state.clone(),
business_profile,
&key_store,
event,
request_content,
delivery_attempt,
Some(content),
Some(process),
))
.await;
}
// Resource status has changed since the event was created, finish task
_ => {
logger::warn!(
%event.event_id,
"The current status of the resource `{:?}` (event type: {:?}) and the status of \
the resource when the event was created (event type: {:?}) differ, finishing task",
tracking_data.primary_object_id,
event_type,
tracking_data.event_type
);
db.as_scheduler()
.finish_process_with_business_status(
process.clone(),
business_status::RESOURCE_STATUS_MISMATCH,
)
.await?;
}
}
}
};
Ok(())
}
#[cfg(feature = "v2")]
async fn execute_workflow<'a>(
&'a self,
_state: &'a SessionState,
_process: storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
todo!()
}
#[instrument(skip_all)]
async fn error_handler<'a>(
&'a self,
state: &'a SessionState,
process: storage::ProcessTracker,
error: errors::ProcessTrackerError,
) -> errors::CustomResult<(), errors::ProcessTrackerError> {
consumer::consumer_error_handler(state.store.as_scheduler(), process, error).await
}
}
/// Get the schedule time for the specified retry count.
///
/// The schedule time can be configured in configs with this key: `pt_mapping_outgoing_webhooks`.
///
/// ```json
/// {
/// "default_mapping": {
/// "start_after": 60,
/// "frequency": [300],
/// "count": [5]
/// },
/// "custom_merchant_mapping": {
/// "merchant_id1": {
/// "start_after": 30,
/// "frequency": [300],
/// "count": [2]
/// }
/// }
/// }
/// ```
///
/// This configuration value represents:
/// - `default_mapping.start_after`: The first retry attempt should happen after 60 seconds by
/// default.
/// - `default_mapping.frequency` and `count`: The next 5 retries should have an interval of 300
/// seconds between them by default.
/// - `custom_merchant_mapping.merchant_id1`: Merchant-specific retry configuration for merchant
/// with merchant ID `merchant_id1`.
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub(crate) async fn get_webhook_delivery_retry_schedule_time(
db: &dyn StorageInterface,
merchant_id: &id_type::MerchantId,
retry_count: i32,
) -> Option<time::PrimitiveDateTime> {
let key = "pt_mapping_outgoing_webhooks";
let result = db
.find_config_by_key(key)
.await
.map(|value| value.config)
.and_then(|config| {
config
.parse_struct("OutgoingWebhookRetryProcessTrackerMapping")
.change_context(errors::StorageError::DeserializationFailed)
});
let mapping = result.map_or_else(
|error| {
if error.current_context().is_db_not_found() {
logger::debug!("Outgoing webhooks retry config `{key}` not found, ignoring");
} else {
logger::error!(
?error,
"Failed to read outgoing webhooks retry config `{key}`"
);
}
process_data::OutgoingWebhookRetryProcessTrackerMapping::default()
},
|mapping| {
logger::debug!(?mapping, "Using custom outgoing webhooks retry config");
mapping
},
);
let time_delta = scheduler_utils::get_outgoing_webhook_retry_schedule_time(
mapping,
merchant_id,
retry_count,
);
scheduler_utils::get_time_from_delta(time_delta)
}
/// Schedule the webhook delivery task for retry
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub(crate) async fn retry_webhook_delivery_task(
db: &dyn StorageInterface,
merchant_id: &id_type::MerchantId,
process: storage::ProcessTracker,
) -> errors::CustomResult<(), errors::StorageError> {
let schedule_time =
get_webhook_delivery_retry_schedule_time(db, merchant_id, process.retry_count + 1).await;
match schedule_time {
Some(schedule_time) => {
db.as_scheduler()
.retry_process(process, schedule_time)
.await
}
None => {
db.as_scheduler()
.finish_process_with_business_status(process, business_status::RETRIES_EXCEEDED)
.await
}
}
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn get_outgoing_webhook_content_and_event_type(
state: SessionState,
req_state: ReqState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
tracking_data: &OutgoingWebhookTrackingData,
) -> Result<(OutgoingWebhookContent, Option<EventType>), errors::ProcessTrackerError> {
use api_models::{
disputes::DisputeRetrieveRequest,
mandates::MandateId,
payments::{PaymentIdType, PaymentsResponse, PaymentsRetrieveRequest},
refunds::{RefundResponse, RefundsRetrieveRequest},
};
use crate::{
core::{
disputes::retrieve_dispute,
mandate::get_mandate,
payments::{payments_core, CallConnectorAction, PaymentStatus},
refunds::refund_retrieve_core_with_refund_id,
},
services::{ApplicationResponse, AuthFlow},
types::{api::PSync, transformers::ForeignFrom},
};
let platform = domain::Platform::new(
merchant_account.clone(),
key_store.clone(),
merchant_account.clone(),
key_store.clone(),
None,
);
match tracking_data.event_class {
diesel_models::enums::EventClass::Payments => {
let payment_id = tracking_data.primary_object_id.clone();
let payment_id = id_type::PaymentId::try_from(std::borrow::Cow::Owned(payment_id))
.map_err(|payment_id_parsing_error| {
logger::error!(
?payment_id_parsing_error,
"Failed to parse payment ID from tracking data"
);
errors::ProcessTrackerError::DeserializationFailed
})?;
let request = PaymentsRetrieveRequest {
resource_id: PaymentIdType::PaymentIntentId(payment_id),
merchant_id: Some(tracking_data.merchant_id.clone()),
force_sync: false,
..Default::default()
};
let payments_response = match Box::pin(payments_core::<
PSync,
PaymentsResponse,
_,
_,
_,
payments::PaymentData<PSync>,
>(
state,
req_state,
platform.clone(),
None,
PaymentStatus,
request,
AuthFlow::Client,
CallConnectorAction::Avoid,
None,
None,
hyperswitch_domain_models::payments::HeaderPayload::default(),
))
.await?
{
ApplicationResponse::Json(payments_response)
| ApplicationResponse::JsonWithHeaders((payments_response, _)) => {
Ok(payments_response)
}
ApplicationResponse::StatusOk
| ApplicationResponse::TextPlain(_)
| ApplicationResponse::JsonForRedirection(_)
| ApplicationResponse::Form(_)
| ApplicationResponse::GenericLinkForm(_)
| ApplicationResponse::PaymentLinkForm(_)
| ApplicationResponse::FileData(_) => {
Err(errors::ProcessTrackerError::ResourceFetchingFailed {
resource_name: tracking_data.primary_object_id.clone(),
})
}
}?;
let event_type: Option<EventType> = payments_response.status.into();
logger::debug!(current_resource_status=%payments_response.status);
Ok((
OutgoingWebhookContent::PaymentDetails(Box::new(payments_response)),
event_type,
))
}
diesel_models::enums::EventClass::Refunds => {
let refund_id = tracking_data.primary_object_id.clone();
let request = RefundsRetrieveRequest {
refund_id,
force_sync: Some(false),
merchant_connector_details: None,
all_keys_required: None,
};
let (refund, _) = Box::pin(refund_retrieve_core_with_refund_id(
state,
platform.clone(),
None,
request,
))
.await?;
let event_type: Option<EventType> = refund.refund_status.into();
logger::debug!(current_resource_status=%refund.refund_status);
let refund_response = RefundResponse::foreign_from(refund);
Ok((
OutgoingWebhookContent::RefundDetails(Box::new(refund_response)),
event_type,
))
}
diesel_models::enums::EventClass::Disputes => {
let dispute_id = tracking_data.primary_object_id.clone();
let request = DisputeRetrieveRequest {
dispute_id,
force_sync: None,
};
let dispute_response =
match Box::pin(retrieve_dispute(state, platform.clone(), None, request)).await? {
ApplicationResponse::Json(dispute_response)
| ApplicationResponse::JsonWithHeaders((dispute_response, _)) => {
Ok(dispute_response)
}
ApplicationResponse::StatusOk
| ApplicationResponse::TextPlain(_)
| ApplicationResponse::JsonForRedirection(_)
| ApplicationResponse::Form(_)
| ApplicationResponse::GenericLinkForm(_)
| ApplicationResponse::PaymentLinkForm(_)
| ApplicationResponse::FileData(_) => {
Err(errors::ProcessTrackerError::ResourceFetchingFailed {
resource_name: tracking_data.primary_object_id.clone(),
})
}
}
.map(Box::new)?;
let event_type = Some(EventType::from(dispute_response.dispute_status));
logger::debug!(current_resource_status=%dispute_response.dispute_status);
Ok((
OutgoingWebhookContent::DisputeDetails(dispute_response),
event_type,
))
}
diesel_models::enums::EventClass::Mandates => {
let mandate_id = tracking_data.primary_object_id.clone();
let request = MandateId { mandate_id };
let mandate_response = match get_mandate(state, platform.clone(), request).await? {
ApplicationResponse::Json(mandate_response)
| ApplicationResponse::JsonWithHeaders((mandate_response, _)) => {
Ok(mandate_response)
}
ApplicationResponse::StatusOk
| ApplicationResponse::TextPlain(_)
| ApplicationResponse::JsonForRedirection(_)
| ApplicationResponse::Form(_)
| ApplicationResponse::GenericLinkForm(_)
| ApplicationResponse::PaymentLinkForm(_)
| ApplicationResponse::FileData(_) => {
Err(errors::ProcessTrackerError::ResourceFetchingFailed {
resource_name: tracking_data.primary_object_id.clone(),
})
}
}
.map(Box::new)?;
let event_type: Option<EventType> = mandate_response.status.into();
logger::debug!(current_resource_status=%mandate_response.status);
Ok((
OutgoingWebhookContent::MandateDetails(mandate_response),
event_type,
))
}
#[cfg(feature = "payouts")]
diesel_models::enums::EventClass::Payouts => {
let payout_id = tracking_data.primary_object_id.clone();
let request = payout_models::PayoutRequest::PayoutActionRequest(
payout_models::PayoutActionRequest {
payout_id: id_type::PayoutId::try_from(std::borrow::Cow::Owned(payout_id))?,
},
);
let payout_data = Box::pin(payouts::make_payout_data(
&state,
&platform,
None,
&request,
DEFAULT_LOCALE,
))
.await?;
let payout_create_response =
payouts::response_handler(&state, &platform, &payout_data).await?;
let event_type: Option<EventType> = payout_data.payout_attempt.status.into();
logger::debug!(current_resource_status=%payout_data.payout_attempt.status);
Ok((
OutgoingWebhookContent::PayoutDetails(Box::new(payout_create_response)),
event_type,
))
}
diesel_models::enums::EventClass::Subscriptions => {
let invoice_id = tracking_data.primary_object_id.clone();
let profile_id = &tracking_data.business_profile_id;
let response = Box::pin(
invoice_sync::InvoiceSyncHandler::form_response_for_retry_outgoing_webhook_task(
state.clone().into(),
&key_store,
invoice_id,
profile_id,
&merchant_account,
),
)
.await
.inspect_err(|e| {
logger::error!(
"Failed to generate response for subscription outgoing webhook: {e:?}"
);
})?;
Ok((
OutgoingWebhookContent::SubscriptionDetails(Box::new(response)),
Some(EventType::InvoicePaid),
))
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/workflows/dispute_list.rs | crates/router/src/workflows/dispute_list.rs | use std::ops::Deref;
use common_utils::ext_traits::{StringExt, ValueExt};
use diesel_models::process_tracker::business_status;
use error_stack::ResultExt;
use router_env::{logger, tracing::Instrument};
use scheduler::{
consumer::{self, types::process_data, workflows::ProcessTrackerWorkflow},
errors as sch_errors, utils as scheduler_utils,
};
use crate::{
core::disputes,
db::StorageInterface,
errors,
routes::SessionState,
types::{api, domain, storage},
};
pub struct DisputeListWorkflow;
/// This workflow fetches disputes from the connector for a given time range
/// and creates a process tracker task for each dispute.
/// It also schedules the next dispute list sync after dispute_polling_hours.
#[async_trait::async_trait]
impl ProcessTrackerWorkflow<SessionState> for DisputeListWorkflow {
#[cfg(feature = "v2")]
async fn execute_workflow<'a>(
&'a self,
_state: &'a SessionState,
_process: storage::ProcessTracker,
) -> Result<(), sch_errors::ProcessTrackerError> {
todo!()
}
#[cfg(feature = "v1")]
async fn execute_workflow<'a>(
&'a self,
state: &'a SessionState,
process: storage::ProcessTracker,
) -> Result<(), sch_errors::ProcessTrackerError> {
let db = &*state.store;
let tracking_data: api::DisputeListPTData = process
.tracking_data
.clone()
.parse_value("ProcessDisputePTData")?;
let key_store = db
.get_merchant_key_store_by_merchant_id(
&tracking_data.merchant_id,
&db.get_master_key().to_vec().into(),
)
.await?;
let merchant_account = db
.find_merchant_account_by_merchant_id(&tracking_data.merchant_id.clone(), &key_store)
.await?;
let platform = domain::Platform::new(
merchant_account.clone(),
key_store.clone(),
merchant_account,
key_store,
None,
);
let business_profile = state
.store
.find_business_profile_by_profile_id(
platform.get_processor().get_key_store(),
&tracking_data.profile_id,
)
.await?;
if process.retry_count == 0 {
let m_db = state.clone().store;
let m_tracking_data = tracking_data.clone();
let dispute_polling_interval = *business_profile
.dispute_polling_interval
.unwrap_or_default()
.deref();
let application_source = state.conf.application_source;
tokio::spawn(
async move {
schedule_next_dispute_list_task(
&*m_db,
&m_tracking_data,
dispute_polling_interval,
application_source,
)
.await
.map_err(|error| {
logger::error!(
"Failed to add dispute list task to process tracker: {error}"
)
})
}
.in_current_span(),
);
};
let response = Box::pin(disputes::fetch_disputes_from_connector(
state.clone(),
platform,
tracking_data.merchant_connector_id,
hyperswitch_domain_models::router_request_types::FetchDisputesRequestData {
created_from: tracking_data.created_from,
created_till: tracking_data.created_till,
},
))
.await
.attach_printable("Dispute update failed");
if response.is_err() {
retry_sync_task(
db,
tracking_data.connector_name,
tracking_data.merchant_id,
process,
)
.await?;
} else {
state
.store
.as_scheduler()
.finish_process_with_business_status(process, business_status::COMPLETED_BY_PT)
.await?
}
Ok(())
}
async fn error_handler<'a>(
&'a self,
state: &'a SessionState,
process: storage::ProcessTracker,
error: sch_errors::ProcessTrackerError,
) -> errors::CustomResult<(), sch_errors::ProcessTrackerError> {
consumer::consumer_error_handler(state.store.as_scheduler(), process, error).await
}
}
pub async fn get_sync_process_schedule_time(
db: &dyn StorageInterface,
connector: &str,
merchant_id: &common_utils::id_type::MerchantId,
retry_count: i32,
) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> {
let mapping: common_utils::errors::CustomResult<
process_data::ConnectorPTMapping,
errors::StorageError,
> = db
.find_config_by_key(&format!("pt_mapping_{connector}"))
.await
.map(|value| value.config)
.and_then(|config| {
config
.parse_struct("ConnectorPTMapping")
.change_context(errors::StorageError::DeserializationFailed)
});
let mapping = match mapping {
Ok(x) => x,
Err(error) => {
logger::info!(?error, "Redis Mapping Error");
process_data::ConnectorPTMapping::default()
}
};
let time_delta = scheduler_utils::get_schedule_time(mapping, merchant_id, retry_count);
Ok(scheduler_utils::get_time_from_delta(time_delta))
}
/// Schedule the task for retry
///
/// Returns bool which indicates whether this was the last retry or not
pub async fn retry_sync_task(
db: &dyn StorageInterface,
connector: String,
merchant_id: common_utils::id_type::MerchantId,
pt: storage::ProcessTracker,
) -> Result<bool, sch_errors::ProcessTrackerError> {
let schedule_time: Option<time::PrimitiveDateTime> =
get_sync_process_schedule_time(db, &connector, &merchant_id, pt.retry_count + 1).await?;
match schedule_time {
Some(s_time) => {
db.as_scheduler().retry_process(pt, s_time).await?;
Ok(false)
}
None => {
db.as_scheduler()
.finish_process_with_business_status(pt, business_status::RETRIES_EXCEEDED)
.await?;
Ok(true)
}
}
}
#[cfg(feature = "v1")]
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
.checked_add(time::Duration::hours(i64::from(dispute_polling_interval)))
.ok_or(sch_errors::ProcessTrackerError::TypeConversionError)?;
let fetch_request = hyperswitch_domain_models::router_request_types::FetchDisputesRequestData {
created_from: tracking_data.created_till,
created_till: new_created_till,
};
disputes::add_dispute_list_task_to_pt(
db,
&tracking_data.connector_name,
tracking_data.merchant_id.clone(),
tracking_data.merchant_connector_id.clone(),
tracking_data.profile_id.clone(),
fetch_request,
application_source,
)
.await?;
Ok(())
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/workflows/payment_method_status_update.rs | crates/router/src/workflows/payment_method_status_update.rs | use common_utils::ext_traits::ValueExt;
use error_stack::ResultExt;
use scheduler::{
consumer::types::process_data, utils as pt_utils, workflows::ProcessTrackerWorkflow,
};
use crate::{
errors,
logger::error,
routes::SessionState,
types::storage::{self, PaymentMethodStatusTrackingData},
};
pub struct PaymentMethodStatusUpdateWorkflow;
#[async_trait::async_trait]
impl ProcessTrackerWorkflow<SessionState> for PaymentMethodStatusUpdateWorkflow {
#[cfg(feature = "v1")]
async fn execute_workflow<'a>(
&'a self,
state: &'a SessionState,
process: storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
let db = &*state.store;
let tracking_data: PaymentMethodStatusTrackingData = process
.tracking_data
.clone()
.parse_value("PaymentMethodStatusTrackingData")?;
let retry_count = process.retry_count;
let pm_id = tracking_data.payment_method_id;
let prev_pm_status = tracking_data.prev_status;
let curr_pm_status = tracking_data.curr_status;
let merchant_id = tracking_data.merchant_id;
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
&merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await?;
let merchant_account = db
.find_merchant_account_by_merchant_id(&merchant_id, &key_store)
.await?;
let payment_method = db
.find_payment_method(&key_store, &pm_id, merchant_account.storage_scheme)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to decode billing address")?;
if payment_method.status != prev_pm_status {
return db
.as_scheduler()
.finish_process_with_business_status(process, "PROCESS_ALREADY_COMPLETED")
.await
.map_err(Into::<errors::ProcessTrackerError>::into);
}
let pm_update = storage::PaymentMethodUpdate::StatusUpdate {
status: Some(curr_pm_status),
last_modified_by: None,
};
let res = db
.update_payment_method(
&key_store,
payment_method,
pm_update,
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update payment method");
if let Ok(_pm) = res {
db.as_scheduler()
.finish_process_with_business_status(process, "COMPLETED_BY_PT")
.await?;
} else {
let mapping = process_data::PaymentMethodsPTMapping::default();
let time_delta = if retry_count == 0 {
Some(mapping.default_mapping.start_after)
} else {
pt_utils::get_delay(retry_count + 1, &mapping.default_mapping.frequencies)
};
let schedule_time = pt_utils::get_time_from_delta(time_delta);
match schedule_time {
Some(s_time) => db
.as_scheduler()
.retry_process(process, s_time)
.await
.map_err(Into::<errors::ProcessTrackerError>::into)?,
None => db
.as_scheduler()
.finish_process_with_business_status(process, "RETRIES_EXCEEDED")
.await
.map_err(Into::<errors::ProcessTrackerError>::into)?,
};
};
Ok(())
}
#[cfg(feature = "v2")]
async fn execute_workflow<'a>(
&'a self,
_state: &'a SessionState,
_process: storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
todo!()
}
async fn error_handler<'a>(
&'a self,
_state: &'a SessionState,
process: storage::ProcessTracker,
_error: errors::ProcessTrackerError,
) -> errors::CustomResult<(), errors::ProcessTrackerError> {
error!(%process.id, "Failed while executing workflow");
Ok(())
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/consts/user.rs | crates/router/src/consts/user.rs | use common_utils::consts::MAX_ALLOWED_MERCHANT_NAME_LENGTH;
pub const MAX_NAME_LENGTH: usize = 70;
/// The max length of company name and merchant should be same
/// because we are deriving the merchant name from company name
pub const MAX_COMPANY_NAME_LENGTH: usize = MAX_ALLOWED_MERCHANT_NAME_LENGTH;
pub const RECOVERY_CODES_COUNT: usize = 8;
pub const RECOVERY_CODE_LENGTH: usize = 8; // This is without counting the hyphen in between
/// The number of digits composing the auth code.
pub const TOTP_DIGITS: usize = 6;
/// Duration in seconds of a step.
pub const TOTP_VALIDITY_DURATION_IN_SECONDS: u64 = 30;
/// Number of totps allowed as network delay. 1 would mean one totp before current totp and one totp after are valids.
pub const TOTP_TOLERANCE: u8 = 1;
/// Number of maximum attempts user has for totp
pub const TOTP_MAX_ATTEMPTS: u8 = 4;
/// Number of maximum attempts user has for recovery code
pub const RECOVERY_CODE_MAX_ATTEMPTS: u8 = 4;
/// The default number of organizations to fetch for a tenant-level user
pub const ORG_LIST_LIMIT_FOR_TENANT: u32 = 20;
pub const MAX_PASSWORD_LENGTH: usize = 70;
pub const MIN_PASSWORD_LENGTH: usize = 8;
pub const REDIS_TOTP_PREFIX: &str = "TOTP_";
pub const REDIS_RECOVERY_CODE_PREFIX: &str = "RC_";
pub const REDIS_TOTP_SECRET_PREFIX: &str = "TOTP_SEC_";
pub const REDIS_TOTP_SECRET_TTL_IN_SECS: i64 = 15 * 60; // 15 minutes
pub const REDIS_TOTP_ATTEMPTS_PREFIX: &str = "TOTP_ATTEMPTS_";
pub const REDIS_RECOVERY_CODE_ATTEMPTS_PREFIX: &str = "RC_ATTEMPTS_";
pub const REDIS_TOTP_ATTEMPTS_TTL_IN_SECS: i64 = 5 * 60; // 5 mins
pub const REDIS_RECOVERY_CODE_ATTEMPTS_TTL_IN_SECS: i64 = 10 * 60; // 10 mins
pub const REDIS_SSO_PREFIX: &str = "SSO_";
pub const REDIS_SSO_TTL: i64 = 5 * 60; // 5 minutes
pub const DEFAULT_PROFILE_NAME: &str = "default";
pub const DEFAULT_PRODUCT_TYPE: common_enums::MerchantProductType =
common_enums::MerchantProductType::Orchestration;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/consts/opensearch.rs | crates/router/src/consts/opensearch.rs | use api_models::analytics::search::SearchIndex;
pub const fn get_search_indexes() -> [SearchIndex; 9] {
[
SearchIndex::PaymentAttempts,
SearchIndex::PaymentIntents,
SearchIndex::Refunds,
SearchIndex::Disputes,
SearchIndex::Payouts,
SearchIndex::SessionizerPaymentAttempts,
SearchIndex::SessionizerPaymentIntents,
SearchIndex::SessionizerRefunds,
SearchIndex::SessionizerDisputes,
]
}
pub const SEARCH_INDEXES: [SearchIndex; 9] = get_search_indexes();
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/consts/user_role.rs | crates/router/src/consts/user_role.rs | // User Roles
pub const ROLE_ID_MERCHANT_ADMIN: &str = "merchant_admin";
pub const ROLE_ID_MERCHANT_VIEW_ONLY: &str = "merchant_view_only";
pub const ROLE_ID_MERCHANT_IAM_ADMIN: &str = "merchant_iam_admin";
pub const ROLE_ID_MERCHANT_DEVELOPER: &str = "merchant_developer";
pub const ROLE_ID_MERCHANT_OPERATOR: &str = "merchant_operator";
pub const ROLE_ID_MERCHANT_CUSTOMER_SUPPORT: &str = "merchant_customer_support";
pub const ROLE_ID_PROFILE_ADMIN: &str = "profile_admin";
pub const ROLE_ID_PROFILE_VIEW_ONLY: &str = "profile_view_only";
pub const ROLE_ID_PROFILE_IAM_ADMIN: &str = "profile_iam_admin";
pub const ROLE_ID_PROFILE_DEVELOPER: &str = "profile_developer";
pub const ROLE_ID_PROFILE_OPERATOR: &str = "profile_operator";
pub const ROLE_ID_PROFILE_CUSTOMER_SUPPORT: &str = "profile_customer_support";
pub const INTERNAL_USER_MERCHANT_ID: &str = "juspay000";
pub const MAX_ROLE_NAME_LENGTH: usize = 64;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/consts/oidc.rs | crates/router/src/consts/oidc.rs | pub const REDIS_AUTH_CODE_PREFIX: &str = "OIDC_AUTH_CODE_";
pub const AUTH_CODE_TTL_IN_SECS: i64 = 60 * 5; // 5 minutes
pub const ID_TOKEN_TTL_IN_SECS: u64 = 60 * 60; // 1 hour
pub const AUTH_CODE_LENGTH: usize = 32;
pub const TOKEN_TYPE_BEARER: &str = "Bearer";
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/api_keys.rs | crates/router/src/db/api_keys.rs | use error_stack::report;
use router_env::{instrument, tracing};
#[cfg(feature = "accounts_cache")]
use storage_impl::redis::cache::{self, CacheKind, ACCOUNTS_CACHE};
use super::{MockDb, Store};
use crate::{
connection,
core::errors::{self, CustomResult},
types::storage,
};
#[async_trait::async_trait]
pub trait ApiKeyInterface {
async fn insert_api_key(
&self,
api_key: storage::ApiKeyNew,
) -> CustomResult<storage::ApiKey, errors::StorageError>;
async fn update_api_key(
&self,
merchant_id: common_utils::id_type::MerchantId,
key_id: common_utils::id_type::ApiKeyId,
api_key: storage::ApiKeyUpdate,
) -> CustomResult<storage::ApiKey, errors::StorageError>;
async fn revoke_api_key(
&self,
merchant_id: &common_utils::id_type::MerchantId,
key_id: &common_utils::id_type::ApiKeyId,
) -> CustomResult<bool, errors::StorageError>;
async fn find_api_key_by_merchant_id_key_id_optional(
&self,
merchant_id: &common_utils::id_type::MerchantId,
key_id: &common_utils::id_type::ApiKeyId,
) -> CustomResult<Option<storage::ApiKey>, errors::StorageError>;
async fn find_api_key_by_hash_optional(
&self,
hashed_api_key: storage::HashedApiKey,
) -> CustomResult<Option<storage::ApiKey>, errors::StorageError>;
async fn list_api_keys_by_merchant_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
limit: Option<i64>,
offset: Option<i64>,
) -> CustomResult<Vec<storage::ApiKey>, errors::StorageError>;
}
#[async_trait::async_trait]
impl ApiKeyInterface for Store {
#[instrument(skip_all)]
async fn insert_api_key(
&self,
api_key: storage::ApiKeyNew,
) -> CustomResult<storage::ApiKey, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
api_key
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn update_api_key(
&self,
merchant_id: common_utils::id_type::MerchantId,
key_id: common_utils::id_type::ApiKeyId,
api_key: storage::ApiKeyUpdate,
) -> CustomResult<storage::ApiKey, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
let _merchant_id = merchant_id.clone();
let _key_id = key_id.clone();
let update_call = || async {
storage::ApiKey::update_by_merchant_id_key_id(&conn, merchant_id, key_id, api_key)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
};
#[cfg(not(feature = "accounts_cache"))]
{
update_call().await
}
#[cfg(feature = "accounts_cache")]
{
use error_stack::report;
// We need to fetch api_key here because the key that's saved in cache in HashedApiKey.
// Used function from storage model to reuse the connection that made here instead of
// creating new.
let api_key = storage::ApiKey::find_optional_by_merchant_id_key_id(
&conn,
&_merchant_id,
&_key_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))?
.ok_or(report!(errors::StorageError::ValueNotFound(format!(
"ApiKey of {} not found",
_key_id.get_string_repr()
))))?;
cache::publish_and_redact(
self,
CacheKind::Accounts(api_key.hashed_api_key.into_inner().into()),
update_call,
)
.await
}
}
#[instrument(skip_all)]
async fn revoke_api_key(
&self,
merchant_id: &common_utils::id_type::MerchantId,
key_id: &common_utils::id_type::ApiKeyId,
) -> CustomResult<bool, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
let delete_call = || async {
storage::ApiKey::revoke_by_merchant_id_key_id(&conn, merchant_id, key_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
};
#[cfg(not(feature = "accounts_cache"))]
{
delete_call().await
}
#[cfg(feature = "accounts_cache")]
{
use error_stack::report;
// We need to fetch api_key here because the key that's saved in cache in HashedApiKey.
// Used function from storage model to reuse the connection that made here instead of
// creating new.
let api_key =
storage::ApiKey::find_optional_by_merchant_id_key_id(&conn, merchant_id, key_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))?
.ok_or(report!(errors::StorageError::ValueNotFound(format!(
"ApiKey of {} not found",
key_id.get_string_repr()
))))?;
cache::publish_and_redact(
self,
CacheKind::Accounts(api_key.hashed_api_key.into_inner().into()),
delete_call,
)
.await
}
}
#[instrument(skip_all)]
async fn find_api_key_by_merchant_id_key_id_optional(
&self,
merchant_id: &common_utils::id_type::MerchantId,
key_id: &common_utils::id_type::ApiKeyId,
) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::ApiKey::find_optional_by_merchant_id_key_id(&conn, merchant_id, key_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_api_key_by_hash_optional(
&self,
hashed_api_key: storage::HashedApiKey,
) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> {
let _hashed_api_key = hashed_api_key.clone();
let find_call = || async {
let conn = connection::pg_connection_read(self).await?;
storage::ApiKey::find_optional_by_hashed_api_key(&conn, hashed_api_key)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
};
#[cfg(not(feature = "accounts_cache"))]
{
find_call().await
}
#[cfg(feature = "accounts_cache")]
{
cache::get_or_populate_in_memory(
self,
&_hashed_api_key.into_inner(),
find_call,
&ACCOUNTS_CACHE,
)
.await
}
}
#[instrument(skip_all)]
async fn list_api_keys_by_merchant_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
limit: Option<i64>,
offset: Option<i64>,
) -> CustomResult<Vec<storage::ApiKey>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::ApiKey::find_by_merchant_id(&conn, merchant_id, limit, offset)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
#[async_trait::async_trait]
impl ApiKeyInterface for MockDb {
async fn insert_api_key(
&self,
api_key: storage::ApiKeyNew,
) -> CustomResult<storage::ApiKey, errors::StorageError> {
let mut locked_api_keys = self.api_keys.lock().await;
// don't allow duplicate key_ids, a those would be a unique constraint violation in the
// real db as it is used as the primary key
if locked_api_keys.iter().any(|k| k.key_id == api_key.key_id) {
Err(errors::StorageError::MockDbError)?;
}
let stored_key = storage::ApiKey {
key_id: api_key.key_id,
merchant_id: api_key.merchant_id,
name: api_key.name,
description: api_key.description,
hashed_api_key: api_key.hashed_api_key,
prefix: api_key.prefix,
created_at: api_key.created_at,
expires_at: api_key.expires_at,
last_used: api_key.last_used,
};
locked_api_keys.push(stored_key.clone());
Ok(stored_key)
}
async fn update_api_key(
&self,
merchant_id: common_utils::id_type::MerchantId,
key_id: common_utils::id_type::ApiKeyId,
api_key: storage::ApiKeyUpdate,
) -> CustomResult<storage::ApiKey, errors::StorageError> {
let mut locked_api_keys = self.api_keys.lock().await;
// find a key with the given merchant_id and key_id and update, otherwise return an error
let key_to_update = locked_api_keys
.iter_mut()
.find(|k| k.merchant_id == merchant_id && k.key_id == key_id)
.ok_or(errors::StorageError::MockDbError)?;
match api_key {
storage::ApiKeyUpdate::Update {
name,
description,
expires_at,
last_used,
} => {
if let Some(name) = name {
key_to_update.name = name;
}
// only update these fields if the value was Some(_)
if description.is_some() {
key_to_update.description = description;
}
if let Some(expires_at) = expires_at {
key_to_update.expires_at = expires_at;
}
if last_used.is_some() {
key_to_update.last_used = last_used
}
}
storage::ApiKeyUpdate::LastUsedUpdate { last_used } => {
key_to_update.last_used = Some(last_used);
}
}
Ok(key_to_update.clone())
}
async fn revoke_api_key(
&self,
merchant_id: &common_utils::id_type::MerchantId,
key_id: &common_utils::id_type::ApiKeyId,
) -> CustomResult<bool, errors::StorageError> {
let mut locked_api_keys = self.api_keys.lock().await;
// find the key to remove, if it exists
if let Some(pos) = locked_api_keys
.iter()
.position(|k| k.merchant_id == *merchant_id && k.key_id == *key_id)
{
// use `remove` instead of `swap_remove` so we have a consistent order, which might
// matter to someone using limit/offset in `list_api_keys_by_merchant_id`
locked_api_keys.remove(pos);
Ok(true)
} else {
Ok(false)
}
}
async fn find_api_key_by_merchant_id_key_id_optional(
&self,
merchant_id: &common_utils::id_type::MerchantId,
key_id: &common_utils::id_type::ApiKeyId,
) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> {
Ok(self
.api_keys
.lock()
.await
.iter()
.find(|k| k.merchant_id == *merchant_id && k.key_id == *key_id)
.cloned())
}
async fn find_api_key_by_hash_optional(
&self,
hashed_api_key: storage::HashedApiKey,
) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> {
Ok(self
.api_keys
.lock()
.await
.iter()
.find(|k| k.hashed_api_key == hashed_api_key)
.cloned())
}
async fn list_api_keys_by_merchant_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
limit: Option<i64>,
offset: Option<i64>,
) -> CustomResult<Vec<storage::ApiKey>, errors::StorageError> {
// mimic the SQL limit/offset behavior
let offset: usize = if let Some(offset) = offset {
if offset < 0 {
Err(errors::StorageError::MockDbError)?;
}
offset
.try_into()
.map_err(|_| errors::StorageError::MockDbError)?
} else {
0
};
let limit: usize = if let Some(limit) = limit {
if limit < 0 {
Err(errors::StorageError::MockDbError)?;
}
limit
.try_into()
.map_err(|_| errors::StorageError::MockDbError)?
} else {
usize::MAX
};
let keys_for_merchant_id: Vec<storage::ApiKey> = self
.api_keys
.lock()
.await
.iter()
.filter(|k| k.merchant_id == *merchant_id)
.skip(offset)
.take(limit)
.cloned()
.collect();
Ok(keys_for_merchant_id)
}
}
#[cfg(test)]
mod tests {
use std::borrow::Cow;
use common_utils::types::keymanager::KeyManagerState;
use storage_impl::redis::{
cache::{self, CacheKey, CacheKind, ACCOUNTS_CACHE},
kv_store::RedisConnInterface,
pub_sub::PubSubInterface,
};
use time::macros::datetime;
use crate::{
db::{api_keys::ApiKeyInterface, MockDb},
types::storage,
};
#[tokio::test]
async fn test_mockdb_api_key_interface() {
#[allow(clippy::expect_used)]
let mockdb = MockDb::new(
&redis_interface::RedisSettings::default(),
KeyManagerState::new(),
)
.await
.expect("Failed to create Mock store");
let merchant_id =
common_utils::id_type::MerchantId::try_from(Cow::from("merchant1")).unwrap();
let key_id1 = common_utils::id_type::ApiKeyId::try_from(Cow::from("key_id1")).unwrap();
let key_id2 = common_utils::id_type::ApiKeyId::try_from(Cow::from("key_id2")).unwrap();
let non_existent_key_id =
common_utils::id_type::ApiKeyId::try_from(Cow::from("does_not_exist")).unwrap();
let key1 = mockdb
.insert_api_key(storage::ApiKeyNew {
key_id: key_id1.clone(),
merchant_id: merchant_id.clone(),
name: "Key 1".into(),
description: None,
hashed_api_key: "hashed_key1".to_string().into(),
prefix: "abc".into(),
created_at: datetime!(2023-02-01 0:00),
expires_at: Some(datetime!(2023-03-01 0:00)),
last_used: None,
})
.await
.unwrap();
mockdb
.insert_api_key(storage::ApiKeyNew {
key_id: key_id2.clone(),
merchant_id: merchant_id.clone(),
name: "Key 2".into(),
description: None,
hashed_api_key: "hashed_key2".to_string().into(),
prefix: "abc".into(),
created_at: datetime!(2023-03-01 0:00),
expires_at: None,
last_used: None,
})
.await
.unwrap();
let found_key1 = mockdb
.find_api_key_by_merchant_id_key_id_optional(&merchant_id, &key_id1)
.await
.unwrap()
.unwrap();
assert_eq!(found_key1.key_id, key1.key_id);
assert!(mockdb
.find_api_key_by_merchant_id_key_id_optional(&merchant_id, &non_existent_key_id)
.await
.unwrap()
.is_none());
mockdb
.update_api_key(
merchant_id.clone(),
key_id1.clone(),
storage::ApiKeyUpdate::LastUsedUpdate {
last_used: datetime!(2023-02-04 1:11),
},
)
.await
.unwrap();
let updated_key1 = mockdb
.find_api_key_by_merchant_id_key_id_optional(&merchant_id, &key_id1)
.await
.unwrap()
.unwrap();
assert_eq!(updated_key1.last_used, Some(datetime!(2023-02-04 1:11)));
assert_eq!(
mockdb
.list_api_keys_by_merchant_id(&merchant_id, None, None)
.await
.unwrap()
.len(),
2
);
mockdb.revoke_api_key(&merchant_id, &key_id1).await.unwrap();
assert_eq!(
mockdb
.list_api_keys_by_merchant_id(&merchant_id, None, None)
.await
.unwrap()
.len(),
1
);
}
#[tokio::test]
async fn test_api_keys_cache() {
let merchant_id =
common_utils::id_type::MerchantId::try_from(Cow::from("test_merchant")).unwrap();
let db = MockDb::new(
&redis_interface::RedisSettings::default(),
KeyManagerState::new(),
)
.await
.expect("Failed to create Mock store");
let redis_conn = db.get_redis_conn().unwrap();
redis_conn
.subscribe("hyperswitch_invalidate")
.await
.unwrap();
let test_key = common_utils::id_type::ApiKeyId::try_from(Cow::from("test_ey")).unwrap();
let api = storage::ApiKeyNew {
key_id: test_key.clone(),
merchant_id: merchant_id.clone(),
name: "My test key".into(),
description: None,
hashed_api_key: "a_hashed_key".to_string().into(),
prefix: "pre".into(),
created_at: datetime!(2023-06-01 0:00),
expires_at: None,
last_used: None,
};
let api = db.insert_api_key(api).await.unwrap();
let hashed_api_key = api.hashed_api_key.clone();
let find_call = || async {
db.find_api_key_by_hash_optional(hashed_api_key.clone())
.await
};
let _: Option<storage::ApiKey> = cache::get_or_populate_in_memory(
&db,
&format!(
"{}_{}",
merchant_id.get_string_repr(),
hashed_api_key.clone().into_inner()
),
find_call,
&ACCOUNTS_CACHE,
)
.await
.unwrap();
let delete_call = || async { db.revoke_api_key(&merchant_id, &api.key_id).await };
cache::publish_and_redact(
&db,
CacheKind::Accounts(
format!(
"{}_{}",
merchant_id.get_string_repr(),
hashed_api_key.clone().into_inner()
)
.into(),
),
delete_call,
)
.await
.unwrap();
assert!(ACCOUNTS_CACHE
.get_val::<storage::ApiKey>(CacheKey {
key: format!(
"{}_{}",
merchant_id.get_string_repr(),
hashed_api_key.into_inner()
),
prefix: String::default(),
},)
.await
.is_none())
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/locker_mock_up.rs | crates/router/src/db/locker_mock_up.rs | use error_stack::report;
use router_env::{instrument, tracing};
use super::{MockDb, Store};
use crate::{
connection,
core::errors::{self, CustomResult},
types::storage,
};
#[async_trait::async_trait]
pub trait LockerMockUpInterface {
async fn find_locker_by_card_id(
&self,
card_id: &str,
) -> CustomResult<storage::LockerMockUp, errors::StorageError>;
async fn insert_locker_mock_up(
&self,
new: storage::LockerMockUpNew,
) -> CustomResult<storage::LockerMockUp, errors::StorageError>;
async fn delete_locker_mock_up(
&self,
card_id: &str,
) -> CustomResult<storage::LockerMockUp, errors::StorageError>;
}
#[async_trait::async_trait]
impl LockerMockUpInterface for Store {
#[instrument(skip_all)]
async fn find_locker_by_card_id(
&self,
card_id: &str,
) -> CustomResult<storage::LockerMockUp, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::LockerMockUp::find_by_card_id(&conn, card_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn insert_locker_mock_up(
&self,
new: storage::LockerMockUpNew,
) -> CustomResult<storage::LockerMockUp, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
new.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn delete_locker_mock_up(
&self,
card_id: &str,
) -> CustomResult<storage::LockerMockUp, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::LockerMockUp::delete_by_card_id(&conn, card_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
#[async_trait::async_trait]
impl LockerMockUpInterface for MockDb {
async fn find_locker_by_card_id(
&self,
card_id: &str,
) -> CustomResult<storage::LockerMockUp, errors::StorageError> {
self.lockers
.lock()
.await
.iter()
.find(|l| l.card_id == card_id)
.cloned()
.ok_or(errors::StorageError::MockDbError.into())
}
async fn insert_locker_mock_up(
&self,
new: storage::LockerMockUpNew,
) -> CustomResult<storage::LockerMockUp, errors::StorageError> {
let mut locked_lockers = self.lockers.lock().await;
if locked_lockers.iter().any(|l| l.card_id == new.card_id) {
Err(errors::StorageError::MockDbError)?;
}
let created_locker = storage::LockerMockUp {
card_id: new.card_id,
external_id: new.external_id,
card_fingerprint: new.card_fingerprint,
card_global_fingerprint: new.card_global_fingerprint,
merchant_id: new.merchant_id,
card_number: new.card_number,
card_exp_year: new.card_exp_year,
card_exp_month: new.card_exp_month,
name_on_card: new.name_on_card,
nickname: None,
customer_id: new.customer_id,
duplicate: None,
card_cvc: new.card_cvc,
payment_method_id: new.payment_method_id,
enc_card_data: new.enc_card_data,
};
locked_lockers.push(created_locker.clone());
Ok(created_locker)
}
async fn delete_locker_mock_up(
&self,
card_id: &str,
) -> CustomResult<storage::LockerMockUp, errors::StorageError> {
let mut locked_lockers = self.lockers.lock().await;
let position = locked_lockers
.iter()
.position(|l| l.card_id == card_id)
.ok_or(errors::StorageError::MockDbError)?;
Ok(locked_lockers.remove(position))
}
}
#[cfg(test)]
mod tests {
mod mockdb_locker_mock_up_interface {
use common_utils::{
generate_customer_id_of_default_length, id_type, types::keymanager::KeyManagerState,
};
use crate::{
db::{locker_mock_up::LockerMockUpInterface, MockDb},
types::storage,
};
pub struct LockerMockUpIds {
card_id: String,
external_id: String,
merchant_id: id_type::MerchantId,
customer_id: id_type::CustomerId,
}
fn create_locker_mock_up_new(locker_ids: LockerMockUpIds) -> storage::LockerMockUpNew {
storage::LockerMockUpNew {
card_id: locker_ids.card_id,
external_id: locker_ids.external_id,
card_fingerprint: "card_fingerprint".into(),
card_global_fingerprint: "card_global_fingerprint".into(),
merchant_id: locker_ids.merchant_id,
card_number: "1234123412341234".into(),
card_exp_year: "2023".into(),
card_exp_month: "06".into(),
name_on_card: Some("name_on_card".into()),
card_cvc: Some("123".into()),
payment_method_id: Some("payment_method_id".into()),
customer_id: Some(locker_ids.customer_id),
nickname: Some("card_holder_nickname".into()),
enc_card_data: Some("enc_card_data".into()),
}
}
#[tokio::test]
async fn find_locker_by_card_id() {
let mockdb = MockDb::new(
&redis_interface::RedisSettings::default(),
KeyManagerState::new(),
)
.await
.expect("Failed to create Mock store");
let created_locker = mockdb
.insert_locker_mock_up(create_locker_mock_up_new(LockerMockUpIds {
card_id: "card_1".into(),
external_id: "external_1".into(),
merchant_id: id_type::MerchantId::default(),
customer_id: generate_customer_id_of_default_length(),
}))
.await
.unwrap();
let _ = mockdb
.insert_locker_mock_up(create_locker_mock_up_new(LockerMockUpIds {
card_id: "card_2".into(),
external_id: "external_1".into(),
merchant_id: id_type::MerchantId::default(),
customer_id: generate_customer_id_of_default_length(),
}))
.await;
let found_locker = mockdb.find_locker_by_card_id("card_1").await.unwrap();
assert_eq!(created_locker, found_locker)
}
#[tokio::test]
async fn insert_locker_mock_up() {
let mockdb = MockDb::new(
&redis_interface::RedisSettings::default(),
KeyManagerState::new(),
)
.await
.expect("Failed to create Mock store");
let created_locker = mockdb
.insert_locker_mock_up(create_locker_mock_up_new(LockerMockUpIds {
card_id: "card_1".into(),
external_id: "external_1".into(),
merchant_id: id_type::MerchantId::default(),
customer_id: generate_customer_id_of_default_length(),
}))
.await
.unwrap();
let found_locker = mockdb
.lockers
.lock()
.await
.iter()
.find(|l| l.card_id == "card_1")
.cloned();
assert!(found_locker.is_some());
assert_eq!(created_locker, found_locker.unwrap())
}
#[tokio::test]
async fn delete_locker_mock_up() {
let mockdb = MockDb::new(
&redis_interface::RedisSettings::default(),
KeyManagerState::new(),
)
.await
.expect("Failed to create Mock store");
let created_locker = mockdb
.insert_locker_mock_up(create_locker_mock_up_new(LockerMockUpIds {
card_id: "card_1".into(),
external_id: "external_1".into(),
merchant_id: id_type::MerchantId::default(),
customer_id: generate_customer_id_of_default_length(),
}))
.await
.unwrap();
let deleted_locker = mockdb.delete_locker_mock_up("card_1").await.unwrap();
assert_eq!(created_locker, deleted_locker);
let exist = mockdb
.lockers
.lock()
.await
.iter()
.any(|l| l.card_id == "card_1");
assert!(!exist)
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/user.rs | crates/router/src/db/user.rs | use diesel_models::user as storage;
use error_stack::report;
use masking::Secret;
use router_env::{instrument, tracing};
use super::{domain, MockDb};
use crate::{
connection,
core::errors::{self, CustomResult},
services::Store,
};
pub mod sample_data;
pub mod theme;
#[async_trait::async_trait]
pub trait UserInterface {
async fn insert_user(
&self,
user_data: storage::UserNew,
) -> CustomResult<storage::User, errors::StorageError>;
async fn find_user_by_email(
&self,
user_email: &domain::UserEmail,
) -> CustomResult<storage::User, errors::StorageError>;
async fn find_user_by_id(
&self,
user_id: &str,
) -> CustomResult<storage::User, errors::StorageError>;
async fn update_user_by_user_id(
&self,
user_id: &str,
user: storage::UserUpdate,
) -> CustomResult<storage::User, errors::StorageError>;
async fn update_user_by_email(
&self,
user_email: &domain::UserEmail,
user: storage::UserUpdate,
) -> CustomResult<storage::User, errors::StorageError>;
async fn delete_user_by_user_id(
&self,
user_id: &str,
) -> CustomResult<bool, errors::StorageError>;
async fn find_users_by_user_ids(
&self,
user_ids: Vec<String>,
) -> CustomResult<Vec<storage::User>, errors::StorageError>;
}
#[async_trait::async_trait]
impl UserInterface for Store {
#[instrument(skip_all)]
async fn insert_user(
&self,
user_data: storage::UserNew,
) -> CustomResult<storage::User, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
user_data
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_user_by_email(
&self,
user_email: &domain::UserEmail,
) -> CustomResult<storage::User, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::User::find_by_user_email(&conn, user_email.get_inner())
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_user_by_id(
&self,
user_id: &str,
) -> CustomResult<storage::User, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::User::find_by_user_id(&conn, user_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn update_user_by_user_id(
&self,
user_id: &str,
user: storage::UserUpdate,
) -> CustomResult<storage::User, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::User::update_by_user_id(&conn, user_id, user)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn update_user_by_email(
&self,
user_email: &domain::UserEmail,
user: storage::UserUpdate,
) -> CustomResult<storage::User, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::User::update_by_user_email(&conn, user_email.get_inner(), user)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn delete_user_by_user_id(
&self,
user_id: &str,
) -> CustomResult<bool, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::User::delete_by_user_id(&conn, user_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
async fn find_users_by_user_ids(
&self,
user_ids: Vec<String>,
) -> CustomResult<Vec<storage::User>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::User::find_users_by_user_ids(&conn, user_ids)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
#[async_trait::async_trait]
impl UserInterface for MockDb {
async fn insert_user(
&self,
user_data: storage::UserNew,
) -> CustomResult<storage::User, errors::StorageError> {
let mut users = self.users.lock().await;
if users
.iter()
.any(|user| user.email == user_data.email || user.user_id == user_data.user_id)
{
Err(errors::StorageError::DuplicateValue {
entity: "email or user_id",
key: None,
})?
}
let time_now = common_utils::date_time::now();
let user = storage::User {
user_id: user_data.user_id,
email: user_data.email,
name: user_data.name,
password: user_data.password,
is_verified: user_data.is_verified,
created_at: user_data.created_at.unwrap_or(time_now),
last_modified_at: user_data.created_at.unwrap_or(time_now),
totp_status: user_data.totp_status,
totp_secret: user_data.totp_secret,
totp_recovery_codes: user_data.totp_recovery_codes,
last_password_modified_at: user_data.last_password_modified_at,
lineage_context: user_data.lineage_context,
};
users.push(user.clone());
Ok(user)
}
async fn find_user_by_email(
&self,
user_email: &domain::UserEmail,
) -> CustomResult<storage::User, errors::StorageError> {
let users = self.users.lock().await;
users
.iter()
.find(|user| user.email.eq(user_email.get_inner()))
.cloned()
.ok_or(
errors::StorageError::ValueNotFound(format!(
"No user available for email = {user_email:?}"
))
.into(),
)
}
async fn find_user_by_id(
&self,
user_id: &str,
) -> CustomResult<storage::User, errors::StorageError> {
let users = self.users.lock().await;
users
.iter()
.find(|user| user.user_id == user_id)
.cloned()
.ok_or(
errors::StorageError::ValueNotFound(format!(
"No user available for user_id = {user_id}"
))
.into(),
)
}
async fn update_user_by_user_id(
&self,
user_id: &str,
update_user: storage::UserUpdate,
) -> CustomResult<storage::User, errors::StorageError> {
let mut users = self.users.lock().await;
let last_modified_at = common_utils::date_time::now();
users
.iter_mut()
.find(|user| user.user_id == user_id)
.map(|user| {
*user = match &update_user {
storage::UserUpdate::VerifyUser => storage::User {
last_modified_at,
is_verified: true,
..user.to_owned()
},
storage::UserUpdate::AccountUpdate { name, is_verified } => storage::User {
name: name.clone().map(Secret::new).unwrap_or(user.name.clone()),
last_modified_at,
is_verified: is_verified.unwrap_or(user.is_verified),
..user.to_owned()
},
storage::UserUpdate::TotpUpdate {
totp_status,
totp_secret,
totp_recovery_codes,
} => storage::User {
last_modified_at,
totp_status: totp_status.unwrap_or(user.totp_status),
totp_secret: totp_secret.clone().or(user.totp_secret.clone()),
totp_recovery_codes: totp_recovery_codes
.clone()
.or(user.totp_recovery_codes.clone()),
..user.to_owned()
},
storage::UserUpdate::PasswordUpdate { password } => storage::User {
password: Some(password.clone()),
last_password_modified_at: Some(common_utils::date_time::now()),
..user.to_owned()
},
storage::UserUpdate::LineageContextUpdate { lineage_context } => {
storage::User {
last_modified_at,
lineage_context: Some(lineage_context.clone()),
..user.to_owned()
}
}
};
user.to_owned()
})
.ok_or(
errors::StorageError::ValueNotFound(format!(
"No user available for user_id = {user_id}"
))
.into(),
)
}
async fn update_user_by_email(
&self,
user_email: &domain::UserEmail,
update_user: storage::UserUpdate,
) -> CustomResult<storage::User, errors::StorageError> {
let mut users = self.users.lock().await;
let last_modified_at = common_utils::date_time::now();
users
.iter_mut()
.find(|user| user.email.eq(user_email.get_inner()))
.map(|user| {
*user = match &update_user {
storage::UserUpdate::VerifyUser => storage::User {
last_modified_at,
is_verified: true,
..user.to_owned()
},
storage::UserUpdate::AccountUpdate { name, is_verified } => storage::User {
name: name.clone().map(Secret::new).unwrap_or(user.name.clone()),
last_modified_at,
is_verified: is_verified.unwrap_or(user.is_verified),
..user.to_owned()
},
storage::UserUpdate::TotpUpdate {
totp_status,
totp_secret,
totp_recovery_codes,
} => storage::User {
last_modified_at,
totp_status: totp_status.unwrap_or(user.totp_status),
totp_secret: totp_secret.clone().or(user.totp_secret.clone()),
totp_recovery_codes: totp_recovery_codes
.clone()
.or(user.totp_recovery_codes.clone()),
..user.to_owned()
},
storage::UserUpdate::PasswordUpdate { password } => storage::User {
password: Some(password.clone()),
last_password_modified_at: Some(common_utils::date_time::now()),
..user.to_owned()
},
storage::UserUpdate::LineageContextUpdate { lineage_context } => {
storage::User {
last_modified_at,
lineage_context: Some(lineage_context.clone()),
..user.to_owned()
}
}
};
user.to_owned()
})
.ok_or(
errors::StorageError::ValueNotFound(format!(
"No user available for user_email = {user_email:?}"
))
.into(),
)
}
async fn delete_user_by_user_id(
&self,
user_id: &str,
) -> CustomResult<bool, errors::StorageError> {
let mut users = self.users.lock().await;
let user_index = users
.iter()
.position(|user| user.user_id == user_id)
.ok_or(errors::StorageError::ValueNotFound(format!(
"No user available for user_id = {user_id}"
)))?;
users.remove(user_index);
Ok(true)
}
async fn find_users_by_user_ids(
&self,
_user_ids: Vec<String>,
) -> CustomResult<Vec<storage::User>, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/blocklist_fingerprint.rs | crates/router/src/db/blocklist_fingerprint.rs | use error_stack::report;
use router_env::{instrument, tracing};
use storage_impl::MockDb;
use super::Store;
use crate::{
connection,
core::errors::{self, CustomResult},
db::kafka_store::KafkaStore,
types::storage,
};
#[async_trait::async_trait]
pub trait BlocklistFingerprintInterface {
async fn insert_blocklist_fingerprint_entry(
&self,
pm_fingerprint_new: storage::BlocklistFingerprintNew,
) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError>;
async fn find_blocklist_fingerprint_by_merchant_id_fingerprint_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
fingerprint_id: &str,
) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError>;
}
#[async_trait::async_trait]
impl BlocklistFingerprintInterface for Store {
#[instrument(skip_all)]
async fn insert_blocklist_fingerprint_entry(
&self,
pm_fingerprint_new: storage::BlocklistFingerprintNew,
) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
pm_fingerprint_new
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_blocklist_fingerprint_by_merchant_id_fingerprint_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
fingerprint_id: &str,
) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::BlocklistFingerprint::find_by_merchant_id_fingerprint_id(
&conn,
merchant_id,
fingerprint_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
#[async_trait::async_trait]
impl BlocklistFingerprintInterface for MockDb {
async fn insert_blocklist_fingerprint_entry(
&self,
_pm_fingerprint_new: storage::BlocklistFingerprintNew,
) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
async fn find_blocklist_fingerprint_by_merchant_id_fingerprint_id(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_fingerprint_id: &str,
) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
}
#[async_trait::async_trait]
impl BlocklistFingerprintInterface for KafkaStore {
#[instrument(skip_all)]
async fn insert_blocklist_fingerprint_entry(
&self,
pm_fingerprint_new: storage::BlocklistFingerprintNew,
) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> {
self.diesel_store
.insert_blocklist_fingerprint_entry(pm_fingerprint_new)
.await
}
#[instrument(skip_all)]
async fn find_blocklist_fingerprint_by_merchant_id_fingerprint_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
fingerprint: &str,
) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> {
self.diesel_store
.find_blocklist_fingerprint_by_merchant_id_fingerprint_id(merchant_id, fingerprint)
.await
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/blocklist.rs | crates/router/src/db/blocklist.rs | use error_stack::report;
use router_env::{instrument, tracing};
use storage_impl::MockDb;
use super::Store;
use crate::{
connection,
core::errors::{self, CustomResult},
db::kafka_store::KafkaStore,
types::storage,
};
#[async_trait::async_trait]
pub trait BlocklistInterface {
async fn insert_blocklist_entry(
&self,
pm_blocklist_new: storage::BlocklistNew,
) -> CustomResult<storage::Blocklist, errors::StorageError>;
async fn find_blocklist_entry_by_merchant_id_fingerprint_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
fingerprint_id: &str,
) -> CustomResult<storage::Blocklist, errors::StorageError>;
async fn delete_blocklist_entry_by_merchant_id_fingerprint_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
fingerprint_id: &str,
) -> CustomResult<storage::Blocklist, errors::StorageError>;
async fn list_blocklist_entries_by_merchant_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError>;
async fn list_blocklist_entries_by_merchant_id_data_kind(
&self,
merchant_id: &common_utils::id_type::MerchantId,
data_kind: common_enums::BlocklistDataKind,
limit: i64,
offset: i64,
) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError>;
}
#[async_trait::async_trait]
impl BlocklistInterface for Store {
#[instrument(skip_all)]
async fn insert_blocklist_entry(
&self,
pm_blocklist: storage::BlocklistNew,
) -> CustomResult<storage::Blocklist, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
pm_blocklist
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_blocklist_entry_by_merchant_id_fingerprint_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
fingerprint_id: &str,
) -> CustomResult<storage::Blocklist, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::Blocklist::find_by_merchant_id_fingerprint_id(&conn, merchant_id, fingerprint_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn list_blocklist_entries_by_merchant_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::Blocklist::list_by_merchant_id(&conn, merchant_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn list_blocklist_entries_by_merchant_id_data_kind(
&self,
merchant_id: &common_utils::id_type::MerchantId,
data_kind: common_enums::BlocklistDataKind,
limit: i64,
offset: i64,
) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::Blocklist::list_by_merchant_id_data_kind(
&conn,
merchant_id,
data_kind,
limit,
offset,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn delete_blocklist_entry_by_merchant_id_fingerprint_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
fingerprint_id: &str,
) -> CustomResult<storage::Blocklist, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::Blocklist::delete_by_merchant_id_fingerprint_id(&conn, merchant_id, fingerprint_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
#[async_trait::async_trait]
impl BlocklistInterface for MockDb {
#[instrument(skip_all)]
async fn insert_blocklist_entry(
&self,
_pm_blocklist: storage::BlocklistNew,
) -> CustomResult<storage::Blocklist, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
async fn find_blocklist_entry_by_merchant_id_fingerprint_id(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_fingerprint_id: &str,
) -> CustomResult<storage::Blocklist, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
async fn list_blocklist_entries_by_merchant_id(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
async fn list_blocklist_entries_by_merchant_id_data_kind(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_data_kind: common_enums::BlocklistDataKind,
_limit: i64,
_offset: i64,
) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
async fn delete_blocklist_entry_by_merchant_id_fingerprint_id(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_fingerprint_id: &str,
) -> CustomResult<storage::Blocklist, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
}
#[async_trait::async_trait]
impl BlocklistInterface for KafkaStore {
#[instrument(skip_all)]
async fn insert_blocklist_entry(
&self,
pm_blocklist: storage::BlocklistNew,
) -> CustomResult<storage::Blocklist, errors::StorageError> {
self.diesel_store.insert_blocklist_entry(pm_blocklist).await
}
#[instrument(skip_all)]
async fn find_blocklist_entry_by_merchant_id_fingerprint_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
fingerprint: &str,
) -> CustomResult<storage::Blocklist, errors::StorageError> {
self.diesel_store
.find_blocklist_entry_by_merchant_id_fingerprint_id(merchant_id, fingerprint)
.await
}
#[instrument(skip_all)]
async fn delete_blocklist_entry_by_merchant_id_fingerprint_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
fingerprint: &str,
) -> CustomResult<storage::Blocklist, errors::StorageError> {
self.diesel_store
.delete_blocklist_entry_by_merchant_id_fingerprint_id(merchant_id, fingerprint)
.await
}
#[instrument(skip_all)]
async fn list_blocklist_entries_by_merchant_id_data_kind(
&self,
merchant_id: &common_utils::id_type::MerchantId,
data_kind: common_enums::BlocklistDataKind,
limit: i64,
offset: i64,
) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {
self.diesel_store
.list_blocklist_entries_by_merchant_id_data_kind(merchant_id, data_kind, limit, offset)
.await
}
#[instrument(skip_all)]
async fn list_blocklist_entries_by_merchant_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {
self.diesel_store
.list_blocklist_entries_by_merchant_id(merchant_id)
.await
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/fraud_check.rs | crates/router/src/db/fraud_check.rs | use diesel_models::fraud_check::{self as storage, FraudCheck, FraudCheckUpdate};
use error_stack::report;
use router_env::{instrument, tracing};
use super::MockDb;
use crate::{
connection,
core::errors::{self, CustomResult},
services::Store,
};
#[async_trait::async_trait]
pub trait FraudCheckInterface {
async fn insert_fraud_check_response(
&self,
new: storage::FraudCheckNew,
) -> CustomResult<FraudCheck, errors::StorageError>;
async fn update_fraud_check_response_with_attempt_id(
&self,
this: FraudCheck,
fraud_check: FraudCheckUpdate,
) -> CustomResult<FraudCheck, errors::StorageError>;
async fn find_fraud_check_by_payment_id(
&self,
payment_id: common_utils::id_type::PaymentId,
merchant_id: common_utils::id_type::MerchantId,
) -> CustomResult<FraudCheck, errors::StorageError>;
async fn find_fraud_check_by_payment_id_if_present(
&self,
payment_id: common_utils::id_type::PaymentId,
merchant_id: common_utils::id_type::MerchantId,
) -> CustomResult<Option<FraudCheck>, errors::StorageError>;
}
#[async_trait::async_trait]
impl FraudCheckInterface for Store {
#[instrument(skip_all)]
async fn insert_fraud_check_response(
&self,
new: storage::FraudCheckNew,
) -> CustomResult<FraudCheck, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
new.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn update_fraud_check_response_with_attempt_id(
&self,
this: FraudCheck,
fraud_check: FraudCheckUpdate,
) -> CustomResult<FraudCheck, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
this.update_with_attempt_id(&conn, fraud_check)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_fraud_check_by_payment_id(
&self,
payment_id: common_utils::id_type::PaymentId,
merchant_id: common_utils::id_type::MerchantId,
) -> CustomResult<FraudCheck, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
FraudCheck::get_with_payment_id(&conn, payment_id, merchant_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_fraud_check_by_payment_id_if_present(
&self,
payment_id: common_utils::id_type::PaymentId,
merchant_id: common_utils::id_type::MerchantId,
) -> CustomResult<Option<FraudCheck>, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
FraudCheck::get_with_payment_id_if_present(&conn, payment_id, merchant_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
#[async_trait::async_trait]
impl FraudCheckInterface for MockDb {
async fn insert_fraud_check_response(
&self,
_new: storage::FraudCheckNew,
) -> CustomResult<FraudCheck, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
async fn update_fraud_check_response_with_attempt_id(
&self,
_this: FraudCheck,
_fraud_check: FraudCheckUpdate,
) -> CustomResult<FraudCheck, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
async fn find_fraud_check_by_payment_id(
&self,
_payment_id: common_utils::id_type::PaymentId,
_merchant_id: common_utils::id_type::MerchantId,
) -> CustomResult<FraudCheck, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
async fn find_fraud_check_by_payment_id_if_present(
&self,
_payment_id: common_utils::id_type::PaymentId,
_merchant_id: common_utils::id_type::MerchantId,
) -> CustomResult<Option<FraudCheck>, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/callback_mapper.rs | crates/router/src/db/callback_mapper.rs | use error_stack::report;
use hyperswitch_domain_models::callback_mapper as domain;
use router_env::{instrument, tracing};
use storage_impl::{DataModelExt, MockDb};
use super::Store;
use crate::{
connection,
core::errors::{self, CustomResult},
types::storage,
};
#[async_trait::async_trait]
pub trait CallbackMapperInterface {
async fn insert_call_back_mapper(
&self,
call_back_mapper: domain::CallbackMapper,
) -> CustomResult<domain::CallbackMapper, errors::StorageError>;
async fn find_call_back_mapper_by_id(
&self,
id: &str,
) -> CustomResult<domain::CallbackMapper, errors::StorageError>;
}
#[async_trait::async_trait]
impl CallbackMapperInterface for Store {
#[instrument(skip_all)]
async fn insert_call_back_mapper(
&self,
call_back_mapper: domain::CallbackMapper,
) -> CustomResult<domain::CallbackMapper, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
call_back_mapper
.to_storage_model()
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
.map(domain::CallbackMapper::from_storage_model)
}
#[instrument(skip_all)]
async fn find_call_back_mapper_by_id(
&self,
id: &str,
) -> CustomResult<domain::CallbackMapper, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::CallbackMapper::find_by_id(&conn, id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
.map(domain::CallbackMapper::from_storage_model)
}
}
#[async_trait::async_trait]
impl CallbackMapperInterface for MockDb {
#[instrument(skip_all)]
async fn insert_call_back_mapper(
&self,
_call_back_mapper: domain::CallbackMapper,
) -> CustomResult<domain::CallbackMapper, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
#[instrument(skip_all)]
async fn find_call_back_mapper_by_id(
&self,
_id: &str,
) -> CustomResult<domain::CallbackMapper, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/dynamic_routing_stats.rs | crates/router/src/db/dynamic_routing_stats.rs | use error_stack::report;
use router_env::{instrument, tracing};
use storage_impl::MockDb;
use super::Store;
use crate::{
connection,
core::errors::{self, CustomResult},
db::kafka_store::KafkaStore,
types::storage,
};
#[async_trait::async_trait]
pub trait DynamicRoutingStatsInterface {
async fn insert_dynamic_routing_stat_entry(
&self,
dynamic_routing_stat_new: storage::DynamicRoutingStatsNew,
) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError>;
async fn find_dynamic_routing_stats_optional_by_attempt_id_merchant_id(
&self,
attempt_id: String,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Option<storage::DynamicRoutingStats>, errors::StorageError>;
async fn update_dynamic_routing_stats(
&self,
attempt_id: String,
merchant_id: &common_utils::id_type::MerchantId,
data: storage::DynamicRoutingStatsUpdate,
) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError>;
}
#[async_trait::async_trait]
impl DynamicRoutingStatsInterface for Store {
#[instrument(skip_all)]
async fn insert_dynamic_routing_stat_entry(
&self,
dynamic_routing_stat: storage::DynamicRoutingStatsNew,
) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
dynamic_routing_stat
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
async fn find_dynamic_routing_stats_optional_by_attempt_id_merchant_id(
&self,
attempt_id: String,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Option<storage::DynamicRoutingStats>, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::DynamicRoutingStats::find_optional_by_attempt_id_merchant_id(
&conn,
attempt_id,
merchant_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
async fn update_dynamic_routing_stats(
&self,
attempt_id: String,
merchant_id: &common_utils::id_type::MerchantId,
data: storage::DynamicRoutingStatsUpdate,
) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::DynamicRoutingStats::update(&conn, attempt_id, merchant_id, data)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
#[async_trait::async_trait]
impl DynamicRoutingStatsInterface for MockDb {
#[instrument(skip_all)]
async fn insert_dynamic_routing_stat_entry(
&self,
_dynamic_routing_stat: storage::DynamicRoutingStatsNew,
) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
async fn find_dynamic_routing_stats_optional_by_attempt_id_merchant_id(
&self,
_attempt_id: String,
_merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Option<storage::DynamicRoutingStats>, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
async fn update_dynamic_routing_stats(
&self,
_attempt_id: String,
_merchant_id: &common_utils::id_type::MerchantId,
_data: storage::DynamicRoutingStatsUpdate,
) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
}
#[async_trait::async_trait]
impl DynamicRoutingStatsInterface for KafkaStore {
#[instrument(skip_all)]
async fn insert_dynamic_routing_stat_entry(
&self,
dynamic_routing_stat: storage::DynamicRoutingStatsNew,
) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> {
self.diesel_store
.insert_dynamic_routing_stat_entry(dynamic_routing_stat)
.await
}
async fn find_dynamic_routing_stats_optional_by_attempt_id_merchant_id(
&self,
attempt_id: String,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Option<storage::DynamicRoutingStats>, errors::StorageError> {
self.diesel_store
.find_dynamic_routing_stats_optional_by_attempt_id_merchant_id(attempt_id, merchant_id)
.await
}
async fn update_dynamic_routing_stats(
&self,
attempt_id: String,
merchant_id: &common_utils::id_type::MerchantId,
data: storage::DynamicRoutingStatsUpdate,
) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> {
self.diesel_store
.update_dynamic_routing_stats(attempt_id, merchant_id, data)
.await
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/address.rs | crates/router/src/db/address.rs | use common_utils::id_type;
use diesel_models::{address::AddressUpdateInternal, enums::MerchantStorageScheme};
use error_stack::ResultExt;
use super::MockDb;
use crate::{
core::errors::{self, CustomResult},
types::{
domain::{
self,
behaviour::{Conversion, ReverseConversion},
},
storage as storage_types,
},
};
#[async_trait::async_trait]
pub trait AddressInterface
where
domain::Address:
Conversion<DstType = storage_types::Address, NewDstType = storage_types::AddressNew>,
{
async fn update_address(
&self,
address_id: String,
address: storage_types::AddressUpdate,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Address, errors::StorageError>;
async fn update_address_for_payments(
&self,
this: domain::PaymentAddress,
address: domain::AddressUpdate,
payment_id: id_type::PaymentId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::PaymentAddress, errors::StorageError>;
async fn find_address_by_address_id(
&self,
address_id: &str,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Address, errors::StorageError>;
async fn insert_address_for_payments(
&self,
payment_id: &id_type::PaymentId,
address: domain::PaymentAddress,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::PaymentAddress, errors::StorageError>;
async fn insert_address_for_customers(
&self,
address: domain::CustomerAddress,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Address, errors::StorageError>;
async fn find_address_by_merchant_id_payment_id_address_id(
&self,
merchant_id: &id_type::MerchantId,
payment_id: &id_type::PaymentId,
address_id: &str,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::PaymentAddress, errors::StorageError>;
async fn update_address_by_merchant_id_customer_id(
&self,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
address: storage_types::AddressUpdate,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Address>, errors::StorageError>;
}
#[cfg(not(feature = "kv_store"))]
mod storage {
use common_utils::{ext_traits::AsyncExt, id_type, types::keymanager::KeyManagerState};
use error_stack::{report, ResultExt};
use router_env::{instrument, tracing};
use super::AddressInterface;
use crate::{
connection,
core::errors::{self, CustomResult},
services::Store,
types::{
domain::{
self,
behaviour::{Conversion, ReverseConversion},
},
storage::{self as storage_types, enums::MerchantStorageScheme},
},
};
#[async_trait::async_trait]
impl AddressInterface for Store {
#[instrument(skip_all)]
async fn find_address_by_address_id(
&self,
address_id: &str,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Address, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage_types::Address::find_by_address_id(&conn, address_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
.async_and_then(|address| async {
address
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
})
.await
}
#[instrument(skip_all)]
async fn find_address_by_merchant_id_payment_id_address_id(
&self,
merchant_id: &id_type::MerchantId,
payment_id: &id_type::PaymentId,
address_id: &str,
key_store: &domain::MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::PaymentAddress, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage_types::Address::find_by_merchant_id_payment_id_address_id(
&conn,
merchant_id,
payment_id,
address_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
.async_and_then(|address| async {
address
.convert(state, key_store.key.get_inner(), merchant_id.clone().into())
.await
.change_context(errors::StorageError::DecryptionError)
})
.await
}
#[instrument(skip_all)]
async fn update_address(
&self,
address_id: String,
address: storage_types::AddressUpdate,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Address, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage_types::Address::update_by_address_id(&conn, address_id, address.into())
.await
.map_err(|error| report!(errors::StorageError::from(error)))
.async_and_then(|address| async {
address
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
})
.await
}
#[instrument(skip_all)]
async fn update_address_for_payments(
&self,
this: domain::PaymentAddress,
address_update: domain::AddressUpdate,
_payment_id: id_type::PaymentId,
key_store: &domain::MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::PaymentAddress, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
let address = Conversion::convert(this)
.await
.change_context(errors::StorageError::EncryptionError)?;
address
.update(&conn, address_update.into())
.await
.map_err(|error| report!(errors::StorageError::from(error)))
.async_and_then(|address| async {
address
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
})
.await
}
#[instrument(skip_all)]
async fn insert_address_for_payments(
&self,
_payment_id: &id_type::PaymentId,
address: domain::PaymentAddress,
key_store: &domain::MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::PaymentAddress, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
address
.construct_new()
.await
.change_context(errors::StorageError::EncryptionError)?
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
.async_and_then(|address| async {
address
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
})
.await
}
#[instrument(skip_all)]
async fn insert_address_for_customers(
&self,
address: domain::CustomerAddress,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Address, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
address
.construct_new()
.await
.change_context(errors::StorageError::EncryptionError)?
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
.async_and_then(|address| async {
address
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
})
.await
}
#[instrument(skip_all)]
async fn update_address_by_merchant_id_customer_id(
&self,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
address: storage_types::AddressUpdate,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Address>, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage_types::Address::update_by_merchant_id_customer_id(
&conn,
customer_id,
merchant_id,
address.into(),
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
.async_and_then(|addresses| async {
let mut output = Vec::with_capacity(addresses.len());
for address in addresses.into_iter() {
output.push(
address
.convert(state, key_store.key.get_inner(), merchant_id.clone().into())
.await
.change_context(errors::StorageError::DecryptionError)?,
)
}
Ok(output)
})
.await
}
}
}
#[cfg(feature = "kv_store")]
mod storage {
use common_utils::{ext_traits::AsyncExt, id_type};
use diesel_models::{enums::MerchantStorageScheme, AddressUpdateInternal};
use error_stack::{report, ResultExt};
use redis_interface::HsetnxReply;
use router_env::{instrument, tracing};
use storage_impl::redis::kv_store::{
decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey,
};
use super::AddressInterface;
use crate::{
connection,
core::errors::{self, CustomResult},
services::Store,
types::{
domain::{
self,
behaviour::{Conversion, ReverseConversion},
},
storage::{self as storage_types, kv},
},
utils::db_utils,
};
#[async_trait::async_trait]
impl AddressInterface for Store {
#[instrument(skip_all)]
async fn find_address_by_address_id(
&self,
address_id: &str,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Address, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage_types::Address::find_by_address_id(&conn, address_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
.async_and_then(|address| async {
address
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
})
.await
}
#[instrument(skip_all)]
async fn find_address_by_merchant_id_payment_id_address_id(
&self,
merchant_id: &id_type::MerchantId,
payment_id: &id_type::PaymentId,
address_id: &str,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::PaymentAddress, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
let database_call = || async {
storage_types::Address::find_by_merchant_id_payment_id_address_id(
&conn,
merchant_id,
payment_id,
address_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
};
let storage_scheme = Box::pin(decide_storage_scheme::<_, storage_types::Address>(
self,
storage_scheme,
Op::Find,
))
.await;
let address = match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
MerchantStorageScheme::RedisKv => {
let key = PartitionKey::MerchantIdPaymentId {
merchant_id,
payment_id,
};
let field = format!("add_{address_id}");
Box::pin(db_utils::try_redis_get_else_try_database_get(
async {
Box::pin(kv_wrapper(
self,
KvOperation::<diesel_models::Address>::HGet(&field),
key,
))
.await?
.try_into_hget()
},
database_call,
))
.await
}
}?;
address
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
key_store.key.get_inner(),
common_utils::types::keymanager::Identifier::Merchant(
key_store.merchant_id.clone(),
),
)
.await
.change_context(errors::StorageError::DecryptionError)
}
#[instrument(skip_all)]
async fn update_address(
&self,
address_id: String,
address: storage_types::AddressUpdate,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Address, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage_types::Address::update_by_address_id(&conn, address_id, address.into())
.await
.map_err(|error| report!(errors::StorageError::from(error)))
.async_and_then(|address| async {
address
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
})
.await
}
#[instrument(skip_all)]
async fn update_address_for_payments(
&self,
this: domain::PaymentAddress,
address_update: domain::AddressUpdate,
payment_id: id_type::PaymentId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::PaymentAddress, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
let address = Conversion::convert(this)
.await
.change_context(errors::StorageError::EncryptionError)?;
let merchant_id = address.merchant_id.clone();
let key = PartitionKey::MerchantIdPaymentId {
merchant_id: &merchant_id,
payment_id: &payment_id,
};
let field = format!("add_{}", address.address_id);
let storage_scheme = Box::pin(decide_storage_scheme::<_, storage_types::Address>(
self,
storage_scheme,
Op::Update(key.clone(), &field, Some(address.updated_by.as_str())),
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
address
.update(&conn, address_update.into())
.await
.map_err(|error| report!(errors::StorageError::from(error)))
.async_and_then(|address| async {
address
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
})
.await
}
MerchantStorageScheme::RedisKv => {
let updated_address = AddressUpdateInternal::from(address_update.clone())
.create_address(address.clone());
let redis_value = serde_json::to_string(&updated_address)
.change_context(errors::StorageError::KVError)?;
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Update {
updatable: Box::new(kv::Updateable::AddressUpdate(Box::new(
kv::AddressUpdateMems {
orig: address,
update_data: address_update.into(),
},
))),
},
};
Box::pin(kv_wrapper::<(), _, _>(
self,
KvOperation::Hset::<storage_types::Address>(
(&field, redis_value),
redis_entry,
),
key,
))
.await
.change_context(errors::StorageError::KVError)?
.try_into_hset()
.change_context(errors::StorageError::KVError)?;
updated_address
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
}
}
}
#[instrument(skip_all)]
async fn insert_address_for_payments(
&self,
payment_id: &id_type::PaymentId,
address: domain::PaymentAddress,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::PaymentAddress, errors::StorageError> {
let address_new = address
.clone()
.construct_new()
.await
.change_context(errors::StorageError::EncryptionError)?;
let merchant_id = address_new.merchant_id.clone();
let storage_scheme = Box::pin(decide_storage_scheme::<_, storage_types::Address>(
self,
storage_scheme,
Op::Insert,
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
let conn = connection::pg_connection_write(self).await?;
address_new
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
.async_and_then(|address| async {
address
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
})
.await
}
MerchantStorageScheme::RedisKv => {
let key = PartitionKey::MerchantIdPaymentId {
merchant_id: &merchant_id,
payment_id,
};
let field = format!("add_{}", &address_new.address_id);
let created_address = diesel_models::Address {
address_id: address_new.address_id.clone(),
city: address_new.city.clone(),
country: address_new.country,
line1: address_new.line1.clone(),
line2: address_new.line2.clone(),
line3: address_new.line3.clone(),
state: address_new.state.clone(),
zip: address_new.zip.clone(),
first_name: address_new.first_name.clone(),
last_name: address_new.last_name.clone(),
phone_number: address_new.phone_number.clone(),
country_code: address_new.country_code.clone(),
created_at: address_new.created_at,
modified_at: address_new.modified_at,
customer_id: address_new.customer_id.clone(),
merchant_id: address_new.merchant_id.clone(),
payment_id: address_new.payment_id.clone(),
updated_by: storage_scheme.to_string(),
email: address_new.email.clone(),
origin_zip: address_new.origin_zip.clone(),
};
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
insertable: Box::new(kv::Insertable::Address(Box::new(address_new))),
},
};
match Box::pin(kv_wrapper::<diesel_models::Address, _, _>(
self,
KvOperation::HSetNx::<diesel_models::Address>(
&field,
&created_address,
redis_entry,
),
key,
))
.await
.change_context(errors::StorageError::KVError)?
.try_into_hsetnx()
{
Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue {
entity: "address",
key: Some(created_address.address_id),
}
.into()),
Ok(HsetnxReply::KeySet) => Ok(created_address
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?),
Err(er) => Err(er).change_context(errors::StorageError::KVError),
}
}
}
}
#[instrument(skip_all)]
async fn insert_address_for_customers(
&self,
address: domain::CustomerAddress,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Address, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
address
.construct_new()
.await
.change_context(errors::StorageError::EncryptionError)?
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
.async_and_then(|address| async {
address
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
})
.await
}
#[instrument(skip_all)]
async fn update_address_by_merchant_id_customer_id(
&self,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
address: storage_types::AddressUpdate,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Address>, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage_types::Address::update_by_merchant_id_customer_id(
&conn,
customer_id,
merchant_id,
address.into(),
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
.async_and_then(|addresses| async {
let mut output = Vec::with_capacity(addresses.len());
for address in addresses.into_iter() {
output.push(
address
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?,
)
}
Ok(output)
})
.await
}
}
}
#[async_trait::async_trait]
impl AddressInterface for MockDb {
async fn find_address_by_address_id(
&self,
address_id: &str,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Address, errors::StorageError> {
match self
.addresses
.lock()
.await
.iter()
.find(|address| address.address_id == address_id)
{
Some(address) => address
.clone()
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError),
None => {
return Err(
errors::StorageError::ValueNotFound("address not found".to_string()).into(),
)
}
}
}
async fn find_address_by_merchant_id_payment_id_address_id(
&self,
_merchant_id: &id_type::MerchantId,
_payment_id: &id_type::PaymentId,
address_id: &str,
key_store: &domain::MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::PaymentAddress, errors::StorageError> {
match self
.addresses
.lock()
.await
.iter()
.find(|address| address.address_id == address_id)
{
Some(address) => address
.clone()
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError),
None => {
return Err(
errors::StorageError::ValueNotFound("address not found".to_string()).into(),
)
}
}
}
async fn update_address(
&self,
address_id: String,
address_update: storage_types::AddressUpdate,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Address, errors::StorageError> {
let updated_addr = self
.addresses
.lock()
.await
.iter_mut()
.find(|address| address.address_id == address_id)
.map(|a| {
let address_updated =
AddressUpdateInternal::from(address_update).create_address(a.clone());
*a = address_updated.clone();
address_updated
});
match updated_addr {
Some(address_updated) => address_updated
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError),
None => Err(errors::StorageError::ValueNotFound(
"cannot find address to update".to_string(),
)
.into()),
}
}
async fn update_address_for_payments(
&self,
this: domain::PaymentAddress,
address_update: domain::AddressUpdate,
_payment_id: id_type::PaymentId,
key_store: &domain::MerchantKeyStore,
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/customers.rs | crates/router/src/db/customers.rs | pub use hyperswitch_domain_models::customer::{CustomerInterface, CustomerListConstraints};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/user_authentication_method.rs | crates/router/src/db/user_authentication_method.rs | use diesel_models::user_authentication_method as storage;
use error_stack::report;
use router_env::{instrument, tracing};
use super::MockDb;
use crate::{
connection,
core::errors::{self, CustomResult},
services::Store,
};
#[async_trait::async_trait]
pub trait UserAuthenticationMethodInterface {
async fn insert_user_authentication_method(
&self,
user_authentication_method: storage::UserAuthenticationMethodNew,
) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError>;
async fn get_user_authentication_method_by_id(
&self,
id: &str,
) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError>;
async fn list_user_authentication_methods_for_auth_id(
&self,
auth_id: &str,
) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError>;
async fn list_user_authentication_methods_for_owner_id(
&self,
owner_id: &str,
) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError>;
async fn update_user_authentication_method(
&self,
id: &str,
user_authentication_method_update: storage::UserAuthenticationMethodUpdate,
) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError>;
async fn list_user_authentication_methods_for_email_domain(
&self,
email_domain: &str,
) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError>;
}
#[async_trait::async_trait]
impl UserAuthenticationMethodInterface for Store {
#[instrument(skip_all)]
async fn insert_user_authentication_method(
&self,
user_authentication_method: storage::UserAuthenticationMethodNew,
) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
user_authentication_method
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn get_user_authentication_method_by_id(
&self,
id: &str,
) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::UserAuthenticationMethod::get_user_authentication_method_by_id(&conn, id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn list_user_authentication_methods_for_auth_id(
&self,
auth_id: &str,
) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::UserAuthenticationMethod::list_user_authentication_methods_for_auth_id(
&conn, auth_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn list_user_authentication_methods_for_owner_id(
&self,
owner_id: &str,
) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::UserAuthenticationMethod::list_user_authentication_methods_for_owner_id(
&conn, owner_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn update_user_authentication_method(
&self,
id: &str,
user_authentication_method_update: storage::UserAuthenticationMethodUpdate,
) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::UserAuthenticationMethod::update_user_authentication_method(
&conn,
id,
user_authentication_method_update,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn list_user_authentication_methods_for_email_domain(
&self,
email_domain: &str,
) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::UserAuthenticationMethod::list_user_authentication_methods_for_email_domain(
&conn,
email_domain,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
#[async_trait::async_trait]
impl UserAuthenticationMethodInterface for MockDb {
async fn insert_user_authentication_method(
&self,
user_authentication_method: storage::UserAuthenticationMethodNew,
) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> {
let mut user_authentication_methods = self.user_authentication_methods.lock().await;
let existing_auth_id = user_authentication_methods
.iter()
.find(|uam| uam.owner_id == user_authentication_method.owner_id)
.map(|uam| uam.auth_id.clone());
let auth_id = existing_auth_id.unwrap_or_else(|| uuid::Uuid::new_v4().to_string());
let user_authentication_method = storage::UserAuthenticationMethod {
id: uuid::Uuid::new_v4().to_string(),
auth_id,
owner_id: user_authentication_method.auth_id,
owner_type: user_authentication_method.owner_type,
auth_type: user_authentication_method.auth_type,
public_config: user_authentication_method.public_config,
private_config: user_authentication_method.private_config,
allow_signup: user_authentication_method.allow_signup,
created_at: user_authentication_method.created_at,
last_modified_at: user_authentication_method.last_modified_at,
email_domain: user_authentication_method.email_domain,
};
user_authentication_methods.push(user_authentication_method.clone());
Ok(user_authentication_method)
}
#[instrument(skip_all)]
async fn get_user_authentication_method_by_id(
&self,
id: &str,
) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> {
let user_authentication_methods = self.user_authentication_methods.lock().await;
let user_authentication_method = user_authentication_methods
.iter()
.find(|&auth_method_inner| auth_method_inner.id == id);
if let Some(user_authentication_method) = user_authentication_method {
Ok(user_authentication_method.to_owned())
} else {
return Err(errors::StorageError::ValueNotFound(format!(
"No user authentication method found for id = {id}",
))
.into());
}
}
async fn list_user_authentication_methods_for_auth_id(
&self,
auth_id: &str,
) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> {
let user_authentication_methods = self.user_authentication_methods.lock().await;
let user_authentication_methods_list: Vec<_> = user_authentication_methods
.iter()
.filter(|auth_method_inner| auth_method_inner.auth_id == auth_id)
.cloned()
.collect();
if user_authentication_methods_list.is_empty() {
return Err(errors::StorageError::ValueNotFound(format!(
"No user authentication method found for auth_id = {auth_id}",
))
.into());
}
Ok(user_authentication_methods_list)
}
async fn list_user_authentication_methods_for_owner_id(
&self,
owner_id: &str,
) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> {
let user_authentication_methods = self.user_authentication_methods.lock().await;
let user_authentication_methods_list: Vec<_> = user_authentication_methods
.iter()
.filter(|auth_method_inner| auth_method_inner.owner_id == owner_id)
.cloned()
.collect();
if user_authentication_methods_list.is_empty() {
return Err(errors::StorageError::ValueNotFound(format!(
"No user authentication method found for owner_id = {owner_id}",
))
.into());
}
Ok(user_authentication_methods_list)
}
async fn update_user_authentication_method(
&self,
id: &str,
user_authentication_method_update: storage::UserAuthenticationMethodUpdate,
) -> CustomResult<storage::UserAuthenticationMethod, errors::StorageError> {
let mut user_authentication_methods = self.user_authentication_methods.lock().await;
user_authentication_methods
.iter_mut()
.find(|auth_method_inner| auth_method_inner.id == id)
.map(|auth_method_inner| {
*auth_method_inner = match user_authentication_method_update {
storage::UserAuthenticationMethodUpdate::UpdateConfig {
private_config,
public_config,
} => storage::UserAuthenticationMethod {
private_config,
public_config,
last_modified_at: common_utils::date_time::now(),
..auth_method_inner.to_owned()
},
storage::UserAuthenticationMethodUpdate::EmailDomain { email_domain } => {
storage::UserAuthenticationMethod {
email_domain: email_domain.to_owned(),
last_modified_at: common_utils::date_time::now(),
..auth_method_inner.to_owned()
}
}
};
auth_method_inner.to_owned()
})
.ok_or(
errors::StorageError::ValueNotFound(format!(
"No authentication method available for the id = {id}"
))
.into(),
)
}
#[instrument(skip_all)]
async fn list_user_authentication_methods_for_email_domain(
&self,
email_domain: &str,
) -> CustomResult<Vec<storage::UserAuthenticationMethod>, errors::StorageError> {
let user_authentication_methods = self.user_authentication_methods.lock().await;
let user_authentication_methods_list: Vec<_> = user_authentication_methods
.iter()
.filter(|auth_method_inner| auth_method_inner.email_domain == email_domain)
.cloned()
.collect();
Ok(user_authentication_methods_list)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/capture.rs | crates/router/src/db/capture.rs | use router_env::{instrument, tracing};
use super::MockDb;
use crate::{
core::errors::{self, CustomResult},
types::storage::{self as types, enums},
};
#[async_trait::async_trait]
pub trait CaptureInterface {
async fn insert_capture(
&self,
capture: types::CaptureNew,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<types::Capture, errors::StorageError>;
async fn find_all_captures_by_merchant_id_payment_id_authorized_attempt_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
authorized_attempt_id: &str,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<types::Capture>, errors::StorageError>;
async fn update_capture_with_capture_id(
&self,
this: types::Capture,
capture: types::CaptureUpdate,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<types::Capture, errors::StorageError>;
}
#[cfg(feature = "kv_store")]
mod storage {
use error_stack::report;
use router_env::{instrument, tracing};
use super::CaptureInterface;
use crate::{
connection,
core::errors::{self, CustomResult},
services::Store,
types::storage::{capture::*, enums},
};
#[async_trait::async_trait]
impl CaptureInterface for Store {
#[instrument(skip_all)]
async fn insert_capture(
&self,
capture: CaptureNew,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Capture, errors::StorageError> {
let db_call = || async {
let conn = connection::pg_connection_write(self).await?;
capture
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
};
db_call().await
}
#[instrument(skip_all)]
async fn update_capture_with_capture_id(
&self,
this: Capture,
capture: CaptureUpdate,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Capture, errors::StorageError> {
let db_call = || async {
let conn = connection::pg_connection_write(self).await?;
this.update_with_capture_id(&conn, capture)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
};
db_call().await
}
#[instrument(skip_all)]
async fn find_all_captures_by_merchant_id_payment_id_authorized_attempt_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
authorized_attempt_id: &str,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<Capture>, errors::StorageError> {
let db_call = || async {
let conn = connection::pg_connection_read(self).await?;
Capture::find_all_by_merchant_id_payment_id_authorized_attempt_id(
merchant_id,
payment_id,
authorized_attempt_id,
&conn,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
};
db_call().await
}
}
}
#[cfg(not(feature = "kv_store"))]
mod storage {
use error_stack::report;
use router_env::{instrument, tracing};
use super::CaptureInterface;
use crate::{
connection,
core::errors::{self, CustomResult},
services::Store,
types::storage::{capture::*, enums},
};
#[async_trait::async_trait]
impl CaptureInterface for Store {
#[instrument(skip_all)]
async fn insert_capture(
&self,
capture: CaptureNew,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Capture, errors::StorageError> {
let db_call = || async {
let conn = connection::pg_connection_write(self).await?;
capture
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
};
db_call().await
}
#[instrument(skip_all)]
async fn update_capture_with_capture_id(
&self,
this: Capture,
capture: CaptureUpdate,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Capture, errors::StorageError> {
let db_call = || async {
let conn = connection::pg_connection_write(self).await?;
this.update_with_capture_id(&conn, capture)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
};
db_call().await
}
#[instrument(skip_all)]
async fn find_all_captures_by_merchant_id_payment_id_authorized_attempt_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
authorized_attempt_id: &str,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<Capture>, errors::StorageError> {
let db_call = || async {
let conn = connection::pg_connection_read(self).await?;
Capture::find_all_by_merchant_id_payment_id_authorized_attempt_id(
merchant_id,
payment_id,
authorized_attempt_id,
&conn,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
};
db_call().await
}
}
}
#[async_trait::async_trait]
impl CaptureInterface for MockDb {
async fn insert_capture(
&self,
capture: types::CaptureNew,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<types::Capture, errors::StorageError> {
let mut captures = self.captures.lock().await;
let capture = types::Capture {
capture_id: capture.capture_id,
payment_id: capture.payment_id,
merchant_id: capture.merchant_id,
status: capture.status,
amount: capture.amount,
currency: capture.currency,
connector: capture.connector,
error_message: capture.error_message,
error_code: capture.error_code,
error_reason: capture.error_reason,
tax_amount: capture.tax_amount,
created_at: capture.created_at,
modified_at: capture.modified_at,
authorized_attempt_id: capture.authorized_attempt_id,
capture_sequence: capture.capture_sequence,
connector_capture_id: capture.connector_capture_id,
connector_response_reference_id: capture.connector_response_reference_id,
processor_capture_data: capture.processor_capture_data,
// Below fields are deprecated. Please add any new fields above this line.
connector_capture_data: None,
};
captures.push(capture.clone());
Ok(capture)
}
#[instrument(skip_all)]
async fn update_capture_with_capture_id(
&self,
_this: types::Capture,
_capture: types::CaptureUpdate,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<types::Capture, errors::StorageError> {
//Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
}
async fn find_all_captures_by_merchant_id_payment_id_authorized_attempt_id(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_payment_id: &common_utils::id_type::PaymentId,
_authorized_attempt_id: &str,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<types::Capture>, errors::StorageError> {
//Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/payment_link.rs | crates/router/src/db/payment_link.rs | use error_stack::report;
use router_env::{instrument, tracing};
use crate::{
connection,
core::errors::{self, CustomResult},
db::MockDb,
services::Store,
types::storage::{self, PaymentLinkDbExt},
};
#[async_trait::async_trait]
pub trait PaymentLinkInterface {
async fn find_payment_link_by_payment_link_id(
&self,
payment_link_id: &str,
) -> CustomResult<storage::PaymentLink, errors::StorageError>;
async fn insert_payment_link(
&self,
_payment_link: storage::PaymentLinkNew,
) -> CustomResult<storage::PaymentLink, errors::StorageError>;
async fn list_payment_link_by_merchant_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
payment_link_constraints: api_models::payments::PaymentLinkListConstraints,
) -> CustomResult<Vec<storage::PaymentLink>, errors::StorageError>;
}
#[async_trait::async_trait]
impl PaymentLinkInterface for Store {
#[instrument(skip_all)]
async fn find_payment_link_by_payment_link_id(
&self,
payment_link_id: &str,
) -> CustomResult<storage::PaymentLink, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::PaymentLink::find_link_by_payment_link_id(&conn, payment_link_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn insert_payment_link(
&self,
payment_link_config: storage::PaymentLinkNew,
) -> CustomResult<storage::PaymentLink, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
payment_link_config
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn list_payment_link_by_merchant_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
payment_link_constraints: api_models::payments::PaymentLinkListConstraints,
) -> CustomResult<Vec<storage::PaymentLink>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::PaymentLink::filter_by_constraints(&conn, merchant_id, payment_link_constraints)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
#[async_trait::async_trait]
impl PaymentLinkInterface for MockDb {
async fn insert_payment_link(
&self,
_payment_link: storage::PaymentLinkNew,
) -> CustomResult<storage::PaymentLink, errors::StorageError> {
// TODO: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
}
async fn find_payment_link_by_payment_link_id(
&self,
_payment_link_id: &str,
) -> CustomResult<storage::PaymentLink, errors::StorageError> {
// TODO: Implement function for `MockDb`x
Err(errors::StorageError::MockDbError)?
}
async fn list_payment_link_by_merchant_id(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_payment_link_constraints: api_models::payments::PaymentLinkListConstraints,
) -> CustomResult<Vec<storage::PaymentLink>, errors::StorageError> {
// TODO: Implement function for `MockDb`x
Err(errors::StorageError::MockDbError)?
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/dispute.rs | crates/router/src/db/dispute.rs | use std::collections::HashMap;
use error_stack::report;
use hyperswitch_domain_models::disputes;
use router_env::{instrument, tracing};
use super::{MockDb, Store};
use crate::{
connection,
core::errors::{self, CustomResult},
types::storage::{self, DisputeDbExt},
};
#[async_trait::async_trait]
pub trait DisputeInterface {
async fn insert_dispute(
&self,
dispute: storage::DisputeNew,
) -> CustomResult<storage::Dispute, errors::StorageError>;
async fn find_by_merchant_id_payment_id_connector_dispute_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
connector_dispute_id: &str,
) -> CustomResult<Option<storage::Dispute>, errors::StorageError>;
async fn find_dispute_by_merchant_id_dispute_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
dispute_id: &str,
) -> CustomResult<storage::Dispute, errors::StorageError>;
async fn find_disputes_by_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
dispute_constraints: &disputes::DisputeListConstraints,
) -> CustomResult<Vec<storage::Dispute>, errors::StorageError>;
async fn find_disputes_by_merchant_id_payment_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
) -> CustomResult<Vec<storage::Dispute>, errors::StorageError>;
async fn update_dispute(
&self,
this: storage::Dispute,
dispute: storage::DisputeUpdate,
) -> CustomResult<storage::Dispute, errors::StorageError>;
async fn get_dispute_status_with_count(
&self,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(common_enums::enums::DisputeStatus, i64)>, errors::StorageError>;
}
#[async_trait::async_trait]
impl DisputeInterface for Store {
#[instrument(skip_all)]
async fn insert_dispute(
&self,
dispute: storage::DisputeNew,
) -> CustomResult<storage::Dispute, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
dispute
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_by_merchant_id_payment_id_connector_dispute_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
connector_dispute_id: &str,
) -> CustomResult<Option<storage::Dispute>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Dispute::find_by_merchant_id_payment_id_connector_dispute_id(
&conn,
merchant_id,
payment_id,
connector_dispute_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_dispute_by_merchant_id_dispute_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
dispute_id: &str,
) -> CustomResult<storage::Dispute, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Dispute::find_by_merchant_id_dispute_id(&conn, merchant_id, dispute_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_disputes_by_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
dispute_constraints: &disputes::DisputeListConstraints,
) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Dispute::filter_by_constraints(&conn, merchant_id, dispute_constraints)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_disputes_by_merchant_id_payment_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Dispute::find_by_merchant_id_payment_id(&conn, merchant_id, payment_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn update_dispute(
&self,
this: storage::Dispute,
dispute: storage::DisputeUpdate,
) -> CustomResult<storage::Dispute, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
this.update(&conn, dispute)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn get_dispute_status_with_count(
&self,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Dispute::get_dispute_status_with_count(
&conn,
merchant_id,
profile_id_list,
time_range,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
#[async_trait::async_trait]
impl DisputeInterface for MockDb {
async fn insert_dispute(
&self,
dispute: storage::DisputeNew,
) -> CustomResult<storage::Dispute, errors::StorageError> {
let evidence = dispute.evidence.ok_or(errors::StorageError::MockDbError)?;
let mut locked_disputes = self.disputes.lock().await;
if locked_disputes
.iter()
.any(|d| d.dispute_id == dispute.dispute_id)
{
Err(errors::StorageError::MockDbError)?;
}
let now = common_utils::date_time::now();
let new_dispute = storage::Dispute {
dispute_id: dispute.dispute_id,
amount: dispute.amount,
currency: dispute.currency,
dispute_stage: dispute.dispute_stage,
dispute_status: dispute.dispute_status,
payment_id: dispute.payment_id,
attempt_id: dispute.attempt_id,
merchant_id: dispute.merchant_id,
connector_status: dispute.connector_status,
connector_dispute_id: dispute.connector_dispute_id,
connector_reason: dispute.connector_reason,
connector_reason_code: dispute.connector_reason_code,
challenge_required_by: dispute.challenge_required_by,
connector_created_at: dispute.connector_created_at,
connector_updated_at: dispute.connector_updated_at,
created_at: now,
modified_at: now,
connector: dispute.connector,
profile_id: dispute.profile_id,
evidence,
merchant_connector_id: dispute.merchant_connector_id,
dispute_amount: dispute.dispute_amount,
organization_id: dispute.organization_id,
dispute_currency: dispute.dispute_currency,
};
locked_disputes.push(new_dispute.clone());
Ok(new_dispute)
}
async fn find_by_merchant_id_payment_id_connector_dispute_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
connector_dispute_id: &str,
) -> CustomResult<Option<storage::Dispute>, errors::StorageError> {
Ok(self
.disputes
.lock()
.await
.iter()
.find(|d| {
d.merchant_id == *merchant_id
&& d.payment_id == *payment_id
&& d.connector_dispute_id == connector_dispute_id
})
.cloned())
}
async fn find_dispute_by_merchant_id_dispute_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
dispute_id: &str,
) -> CustomResult<storage::Dispute, errors::StorageError> {
let locked_disputes = self.disputes.lock().await;
locked_disputes
.iter()
.find(|d| d.merchant_id == *merchant_id && d.dispute_id == dispute_id)
.cloned()
.ok_or(errors::StorageError::ValueNotFound(format!("No dispute available for merchant_id = {merchant_id:?} and dispute_id = {dispute_id}"))
.into())
}
async fn find_disputes_by_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
dispute_constraints: &disputes::DisputeListConstraints,
) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> {
let locked_disputes = self.disputes.lock().await;
let limit_usize = dispute_constraints
.limit
.unwrap_or(u32::MAX)
.try_into()
.unwrap_or(usize::MAX);
let offset_usize = dispute_constraints
.offset
.unwrap_or(0)
.try_into()
.unwrap_or(usize::MIN);
let filtered_disputes: Vec<storage::Dispute> = locked_disputes
.iter()
.filter(|dispute| {
dispute.merchant_id == *merchant_id
&& dispute_constraints
.dispute_id
.as_ref()
.is_none_or(|id| &dispute.dispute_id == id)
&& dispute_constraints
.payment_id
.as_ref()
.is_none_or(|id| &dispute.payment_id == id)
&& dispute_constraints
.profile_id
.as_ref()
.is_none_or(|profile_ids| {
dispute
.profile_id
.as_ref()
.is_none_or(|id| profile_ids.contains(id))
})
&& dispute_constraints
.dispute_status
.as_ref()
.is_none_or(|statuses| statuses.contains(&dispute.dispute_status))
&& dispute_constraints
.dispute_stage
.as_ref()
.is_none_or(|stages| stages.contains(&dispute.dispute_stage))
&& dispute_constraints.reason.as_ref().is_none_or(|reason| {
dispute
.connector_reason
.as_ref()
.is_none_or(|d_reason| d_reason == reason)
})
&& dispute_constraints
.connector
.as_ref()
.is_none_or(|connectors| {
connectors
.iter()
.any(|connector| dispute.connector.as_str() == *connector)
})
&& dispute_constraints
.merchant_connector_id
.as_ref()
.is_none_or(|id| dispute.merchant_connector_id.as_ref() == Some(id))
&& dispute_constraints
.currency
.as_ref()
.is_none_or(|currencies| {
currencies.iter().any(|currency| {
dispute
.dispute_currency
.map(|dispute_currency| &dispute_currency == currency)
.unwrap_or(dispute.currency.as_str() == currency.to_string())
})
})
&& dispute_constraints.time_range.as_ref().is_none_or(|range| {
let dispute_time = dispute.created_at;
dispute_time >= range.start_time
&& range
.end_time
.is_none_or(|end_time| dispute_time <= end_time)
})
})
.skip(offset_usize)
.take(limit_usize)
.cloned()
.collect();
Ok(filtered_disputes)
}
async fn find_disputes_by_merchant_id_payment_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> {
let locked_disputes = self.disputes.lock().await;
Ok(locked_disputes
.iter()
.filter(|d| d.merchant_id == *merchant_id && d.payment_id == *payment_id)
.cloned()
.collect())
}
async fn update_dispute(
&self,
this: storage::Dispute,
dispute: storage::DisputeUpdate,
) -> CustomResult<storage::Dispute, errors::StorageError> {
let mut locked_disputes = self.disputes.lock().await;
let dispute_to_update = locked_disputes
.iter_mut()
.find(|d| d.dispute_id == this.dispute_id)
.ok_or(errors::StorageError::MockDbError)?;
let now = common_utils::date_time::now();
match dispute {
storage::DisputeUpdate::Update {
dispute_stage,
dispute_status,
connector_status,
connector_reason,
connector_reason_code,
challenge_required_by,
connector_updated_at,
} => {
if connector_reason.is_some() {
dispute_to_update.connector_reason = connector_reason;
}
if connector_reason_code.is_some() {
dispute_to_update.connector_reason_code = connector_reason_code;
}
if challenge_required_by.is_some() {
dispute_to_update.challenge_required_by = challenge_required_by;
}
if connector_updated_at.is_some() {
dispute_to_update.connector_updated_at = connector_updated_at;
}
dispute_to_update.dispute_stage = dispute_stage;
dispute_to_update.dispute_status = dispute_status;
dispute_to_update.connector_status = connector_status;
}
storage::DisputeUpdate::StatusUpdate {
dispute_status,
connector_status,
} => {
if let Some(status) = connector_status {
dispute_to_update.connector_status = status;
}
dispute_to_update.dispute_status = dispute_status;
}
storage::DisputeUpdate::EvidenceUpdate { evidence } => {
dispute_to_update.evidence = evidence;
}
}
dispute_to_update.modified_at = now;
Ok(dispute_to_update.clone())
}
async fn get_dispute_status_with_count(
&self,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::StorageError> {
let locked_disputes = self.disputes.lock().await;
let filtered_disputes_data = locked_disputes
.iter()
.filter(|d| {
d.merchant_id == *merchant_id
&& d.created_at >= time_range.start_time
&& time_range
.end_time
.as_ref()
.is_none_or(|received_end_time| received_end_time >= &d.created_at)
&& profile_id_list
.as_ref()
.zip(d.profile_id.as_ref())
.is_none_or(|(received_profile_list, received_profile_id)| {
received_profile_list.contains(received_profile_id)
})
})
.cloned()
.collect::<Vec<storage::Dispute>>();
Ok(filtered_disputes_data
.into_iter()
.fold(
HashMap::new(),
|mut acc: HashMap<common_enums::DisputeStatus, i64>, value| {
acc.entry(value.dispute_status)
.and_modify(|value| *value += 1)
.or_insert(1);
acc
},
)
.into_iter()
.collect::<Vec<(common_enums::DisputeStatus, i64)>>())
}
}
#[cfg(test)]
mod tests {
mod mockdb_dispute_interface {
use std::borrow::Cow;
use common_enums::enums::Currency;
use common_utils::types::{
keymanager::KeyManagerState, AmountConvertor, MinorUnit, StringMinorUnitForConnector,
};
use diesel_models::{
dispute::DisputeNew,
enums::{DisputeStage, DisputeStatus},
};
use hyperswitch_domain_models::disputes::DisputeListConstraints;
use masking::Secret;
use redis_interface::RedisSettings;
use serde_json::Value;
use time::macros::datetime;
use crate::db::{dispute::DisputeInterface, MockDb};
pub struct DisputeNewIds {
dispute_id: String,
payment_id: common_utils::id_type::PaymentId,
attempt_id: String,
merchant_id: common_utils::id_type::MerchantId,
connector_dispute_id: String,
}
fn create_dispute_new(dispute_ids: DisputeNewIds) -> DisputeNew {
DisputeNew {
dispute_id: dispute_ids.dispute_id,
amount: StringMinorUnitForConnector::convert(
&StringMinorUnitForConnector,
MinorUnit::new(0),
Currency::USD,
)
.expect("Amount Conversion Error"),
currency: "currency".into(),
dispute_stage: DisputeStage::Dispute,
dispute_status: DisputeStatus::DisputeOpened,
payment_id: dispute_ids.payment_id,
attempt_id: dispute_ids.attempt_id,
merchant_id: dispute_ids.merchant_id,
connector_status: "connector_status".into(),
connector_dispute_id: dispute_ids.connector_dispute_id,
connector_reason: Some("connector_reason".into()),
connector_reason_code: Some("connector_reason_code".into()),
challenge_required_by: Some(datetime!(2019-01-01 0:00)),
connector_created_at: Some(datetime!(2019-01-02 0:00)),
connector_updated_at: Some(datetime!(2019-01-03 0:00)),
connector: "connector".into(),
evidence: Some(Secret::from(Value::String("evidence".into()))),
profile_id: Some(common_utils::generate_profile_id_of_default_length()),
merchant_connector_id: None,
dispute_amount: MinorUnit::new(1040),
organization_id: common_utils::id_type::OrganizationId::default(),
dispute_currency: Some(Currency::default()),
}
}
#[tokio::test]
async fn test_insert_dispute() {
let mockdb = MockDb::new(&RedisSettings::default(), KeyManagerState::new())
.await
.expect("Failed to create a mock DB");
let merchant_id =
common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap();
let created_dispute = mockdb
.insert_dispute(create_dispute_new(DisputeNewIds {
dispute_id: "dispute_1".into(),
attempt_id: "attempt_1".into(),
merchant_id: merchant_id.clone(),
payment_id: common_utils::id_type::PaymentId::try_from(Cow::Borrowed(
"payment_1",
))
.unwrap(),
connector_dispute_id: "connector_dispute_1".into(),
}))
.await
.unwrap();
let found_dispute = mockdb
.disputes
.lock()
.await
.iter()
.find(|d| d.dispute_id == created_dispute.dispute_id)
.cloned();
assert!(found_dispute.is_some());
assert_eq!(created_dispute, found_dispute.unwrap());
}
#[tokio::test]
async fn test_find_by_merchant_id_payment_id_connector_dispute_id() {
let merchant_id =
common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap();
let mockdb = MockDb::new(&RedisSettings::default(), KeyManagerState::new())
.await
.expect("Failed to create Mock store");
let created_dispute = mockdb
.insert_dispute(create_dispute_new(DisputeNewIds {
dispute_id: "dispute_1".into(),
attempt_id: "attempt_1".into(),
merchant_id: merchant_id.clone(),
payment_id: common_utils::id_type::PaymentId::try_from(Cow::Borrowed(
"payment_1",
))
.unwrap(),
connector_dispute_id: "connector_dispute_1".into(),
}))
.await
.unwrap();
let _ = mockdb
.insert_dispute(create_dispute_new(DisputeNewIds {
dispute_id: "dispute_2".into(),
attempt_id: "attempt_1".into(),
merchant_id: merchant_id.clone(),
payment_id: common_utils::id_type::PaymentId::try_from(Cow::Borrowed(
"payment_1",
))
.unwrap(),
connector_dispute_id: "connector_dispute_2".into(),
}))
.await
.unwrap();
let found_dispute = mockdb
.find_by_merchant_id_payment_id_connector_dispute_id(
&merchant_id,
&common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1"))
.unwrap(),
"connector_dispute_1",
)
.await
.unwrap();
assert!(found_dispute.is_some());
assert_eq!(created_dispute, found_dispute.unwrap());
}
#[tokio::test]
async fn test_find_dispute_by_merchant_id_dispute_id() {
let merchant_id =
common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap();
let payment_id =
common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1")).unwrap();
let mockdb = MockDb::new(&RedisSettings::default(), KeyManagerState::new())
.await
.expect("Failed to create Mock store");
let created_dispute = mockdb
.insert_dispute(create_dispute_new(DisputeNewIds {
dispute_id: "dispute_1".into(),
attempt_id: "attempt_1".into(),
merchant_id: merchant_id.clone(),
payment_id: payment_id.clone(),
connector_dispute_id: "connector_dispute_1".into(),
}))
.await
.unwrap();
let _ = mockdb
.insert_dispute(create_dispute_new(DisputeNewIds {
dispute_id: "dispute_2".into(),
attempt_id: "attempt_1".into(),
merchant_id: merchant_id.clone(),
payment_id: payment_id.clone(),
connector_dispute_id: "connector_dispute_1".into(),
}))
.await
.unwrap();
let found_dispute = mockdb
.find_dispute_by_merchant_id_dispute_id(&merchant_id, "dispute_1")
.await
.unwrap();
assert_eq!(created_dispute, found_dispute);
}
#[tokio::test]
async fn test_find_disputes_by_merchant_id() {
let merchant_id =
common_utils::id_type::MerchantId::try_from(Cow::from("merchant_2")).unwrap();
let payment_id =
common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1")).unwrap();
let mockdb = MockDb::new(&RedisSettings::default(), KeyManagerState::new())
.await
.expect("Failed to create Mock store");
let created_dispute = mockdb
.insert_dispute(create_dispute_new(DisputeNewIds {
dispute_id: "dispute_1".into(),
attempt_id: "attempt_1".into(),
merchant_id: merchant_id.clone(),
payment_id: payment_id.clone(),
connector_dispute_id: "connector_dispute_1".into(),
}))
.await
.unwrap();
let _ = mockdb
.insert_dispute(create_dispute_new(DisputeNewIds {
dispute_id: "dispute_2".into(),
attempt_id: "attempt_1".into(),
merchant_id: merchant_id.clone(),
payment_id: payment_id.clone(),
connector_dispute_id: "connector_dispute_1".into(),
}))
.await
.unwrap();
let found_disputes = mockdb
.find_disputes_by_constraints(
&merchant_id,
&DisputeListConstraints {
dispute_id: None,
payment_id: None,
profile_id: None,
connector: None,
merchant_connector_id: None,
currency: None,
limit: None,
offset: None,
dispute_status: None,
dispute_stage: None,
reason: None,
time_range: None,
},
)
.await
.unwrap();
assert_eq!(2, found_disputes.len());
assert_eq!(created_dispute, found_disputes.first().unwrap().clone());
}
#[tokio::test]
async fn test_find_disputes_by_merchant_id_payment_id() {
let merchant_id =
common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap();
let payment_id =
common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1")).unwrap();
let mockdb = MockDb::new(&RedisSettings::default(), KeyManagerState::new())
.await
.expect("Failed to create Mock store");
let created_dispute = mockdb
.insert_dispute(create_dispute_new(DisputeNewIds {
dispute_id: "dispute_1".into(),
attempt_id: "attempt_1".into(),
merchant_id: merchant_id.clone(),
payment_id: payment_id.clone(),
connector_dispute_id: "connector_dispute_1".into(),
}))
.await
.unwrap();
let _ = mockdb
.insert_dispute(create_dispute_new(DisputeNewIds {
dispute_id: "dispute_2".into(),
attempt_id: "attempt_1".into(),
merchant_id: merchant_id.clone(),
payment_id: payment_id.clone(),
connector_dispute_id: "connector_dispute_1".into(),
}))
.await
.unwrap();
let found_disputes = mockdb
.find_disputes_by_merchant_id_payment_id(&merchant_id, &payment_id)
.await
.unwrap();
assert_eq!(2, found_disputes.len());
assert_eq!(created_dispute, found_disputes.first().unwrap().clone());
}
mod update_dispute {
use std::borrow::Cow;
use diesel_models::{
dispute::DisputeUpdate,
enums::{DisputeStage, DisputeStatus},
};
use masking::Secret;
use serde_json::Value;
use time::macros::datetime;
use crate::db::{
dispute::{
tests::mockdb_dispute_interface::{create_dispute_new, DisputeNewIds},
DisputeInterface,
},
MockDb,
};
#[tokio::test]
async fn test_update_dispute_update() {
let merchant_id =
common_utils::id_type::MerchantId::try_from(Cow::from("merchant_1")).unwrap();
let payment_id =
common_utils::id_type::PaymentId::try_from(Cow::Borrowed("payment_1")).unwrap();
let mockdb = MockDb::new(
&redis_interface::RedisSettings::default(),
common_utils::types::keymanager::KeyManagerState::new(),
)
.await
.expect("Failed to create Mock store");
let created_dispute = mockdb
.insert_dispute(create_dispute_new(DisputeNewIds {
dispute_id: "dispute_1".into(),
attempt_id: "attempt_1".into(),
merchant_id: merchant_id.clone(),
payment_id: payment_id.clone(),
connector_dispute_id: "connector_dispute_1".into(),
}))
.await
.unwrap();
let updated_dispute = mockdb
.update_dispute(
created_dispute.clone(),
DisputeUpdate::Update {
dispute_stage: DisputeStage::PreDispute,
dispute_status: DisputeStatus::DisputeAccepted,
connector_status: "updated_connector_status".into(),
connector_reason: Some("updated_connector_reason".into()),
connector_reason_code: Some("updated_connector_reason_code".into()),
challenge_required_by: Some(datetime!(2019-01-10 0:00)),
connector_updated_at: Some(datetime!(2019-01-11 0:00)),
},
)
.await
.unwrap();
assert_eq!(created_dispute.dispute_id, updated_dispute.dispute_id);
assert_eq!(created_dispute.amount, updated_dispute.amount);
assert_eq!(created_dispute.currency, updated_dispute.currency);
assert_ne!(created_dispute.dispute_stage, updated_dispute.dispute_stage);
assert_ne!(
created_dispute.dispute_status,
updated_dispute.dispute_status
);
assert_eq!(created_dispute.payment_id, updated_dispute.payment_id);
assert_eq!(created_dispute.attempt_id, updated_dispute.attempt_id);
assert_eq!(created_dispute.merchant_id, updated_dispute.merchant_id);
assert_ne!(
created_dispute.connector_status,
updated_dispute.connector_status
);
assert_eq!(
created_dispute.connector_dispute_id,
updated_dispute.connector_dispute_id
);
assert_ne!(
created_dispute.connector_reason,
updated_dispute.connector_reason
);
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/ephemeral_key.rs | crates/router/src/db/ephemeral_key.rs | #[cfg(feature = "v2")]
use common_utils::id_type;
use time::ext::NumericalDuration;
#[cfg(feature = "v2")]
use crate::types::storage::ephemeral_key::{ClientSecretType, ClientSecretTypeNew};
use crate::{
core::errors::{self, CustomResult},
db::MockDb,
types::storage::ephemeral_key::{EphemeralKey, EphemeralKeyNew},
};
#[async_trait::async_trait]
pub trait EphemeralKeyInterface {
#[cfg(feature = "v1")]
async fn create_ephemeral_key(
&self,
_ek: EphemeralKeyNew,
_validity: i64,
) -> CustomResult<EphemeralKey, errors::StorageError>;
#[cfg(feature = "v1")]
async fn get_ephemeral_key(
&self,
_key: &str,
) -> CustomResult<EphemeralKey, errors::StorageError>;
#[cfg(feature = "v1")]
async fn delete_ephemeral_key(
&self,
_id: &str,
) -> CustomResult<EphemeralKey, errors::StorageError>;
}
#[async_trait::async_trait]
pub trait ClientSecretInterface {
#[cfg(feature = "v2")]
async fn create_client_secret(
&self,
_ek: ClientSecretTypeNew,
_validity: i64,
) -> CustomResult<ClientSecretType, errors::StorageError>;
#[cfg(feature = "v2")]
async fn get_client_secret(
&self,
_key: &str,
) -> CustomResult<ClientSecretType, errors::StorageError>;
#[cfg(feature = "v2")]
async fn delete_client_secret(
&self,
_id: &str,
) -> CustomResult<ClientSecretType, errors::StorageError>;
}
mod storage {
use common_utils::date_time;
#[cfg(feature = "v2")]
use common_utils::id_type;
use error_stack::ResultExt;
#[cfg(feature = "v2")]
use masking::PeekInterface;
#[cfg(feature = "v2")]
use redis_interface::errors::RedisError;
use redis_interface::HsetnxReply;
use router_env::{instrument, tracing};
use storage_impl::redis::kv_store::RedisConnInterface;
use time::ext::NumericalDuration;
use super::{ClientSecretInterface, EphemeralKeyInterface};
#[cfg(feature = "v2")]
use crate::types::storage::ephemeral_key::{ClientSecretType, ClientSecretTypeNew};
use crate::{
core::errors::{self, CustomResult},
services::Store,
types::storage::ephemeral_key::{EphemeralKey, EphemeralKeyNew},
};
#[async_trait::async_trait]
impl EphemeralKeyInterface for Store {
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn create_ephemeral_key(
&self,
new: EphemeralKeyNew,
validity: i64,
) -> CustomResult<EphemeralKey, errors::StorageError> {
let secret_key = format!("epkey_{}", &new.secret);
let id_key = format!("epkey_{}", &new.id);
let created_at = date_time::now();
let expires = created_at.saturating_add(validity.hours());
let created_ek = EphemeralKey {
id: new.id,
created_at: created_at.assume_utc().unix_timestamp(),
expires: expires.assume_utc().unix_timestamp(),
customer_id: new.customer_id,
merchant_id: new.merchant_id,
secret: new.secret,
};
match self
.get_redis_conn()
.map_err(Into::<errors::StorageError>::into)?
.serialize_and_set_multiple_hash_field_if_not_exist(
&[
(&secret_key.as_str().into(), &created_ek),
(&id_key.as_str().into(), &created_ek),
],
"ephkey",
None,
)
.await
{
Ok(v) if v.contains(&HsetnxReply::KeyNotSet) => {
Err(errors::StorageError::DuplicateValue {
entity: "ephemeral key",
key: None,
}
.into())
}
Ok(_) => {
let expire_at = expires.assume_utc().unix_timestamp();
self.get_redis_conn()
.map_err(Into::<errors::StorageError>::into)?
.set_expire_at(&secret_key.into(), expire_at)
.await
.change_context(errors::StorageError::KVError)?;
self.get_redis_conn()
.map_err(Into::<errors::StorageError>::into)?
.set_expire_at(&id_key.into(), expire_at)
.await
.change_context(errors::StorageError::KVError)?;
Ok(created_ek)
}
Err(er) => Err(er).change_context(errors::StorageError::KVError),
}
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn get_ephemeral_key(
&self,
key: &str,
) -> CustomResult<EphemeralKey, errors::StorageError> {
let key = format!("epkey_{key}");
self.get_redis_conn()
.map_err(Into::<errors::StorageError>::into)?
.get_hash_field_and_deserialize(&key.into(), "ephkey", "EphemeralKey")
.await
.change_context(errors::StorageError::KVError)
}
#[cfg(feature = "v1")]
async fn delete_ephemeral_key(
&self,
id: &str,
) -> CustomResult<EphemeralKey, errors::StorageError> {
let ek = self.get_ephemeral_key(id).await?;
self.get_redis_conn()
.map_err(Into::<errors::StorageError>::into)?
.delete_key(&format!("epkey_{}", &ek.id).into())
.await
.change_context(errors::StorageError::KVError)?;
self.get_redis_conn()
.map_err(Into::<errors::StorageError>::into)?
.delete_key(&format!("epkey_{}", &ek.secret).into())
.await
.change_context(errors::StorageError::KVError)?;
Ok(ek)
}
}
#[async_trait::async_trait]
impl ClientSecretInterface for Store {
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn create_client_secret(
&self,
new: ClientSecretTypeNew,
validity: i64,
) -> CustomResult<ClientSecretType, errors::StorageError> {
let created_at = date_time::now();
let expires = created_at.saturating_add(validity.hours());
let id_key = new.id.generate_redis_key();
let created_client_secret = ClientSecretType {
id: new.id,
created_at,
expires,
merchant_id: new.merchant_id,
secret: new.secret,
resource_id: new.resource_id,
};
let secret_key = created_client_secret.generate_secret_key();
match self
.get_redis_conn()
.map_err(Into::<errors::StorageError>::into)?
.serialize_and_set_multiple_hash_field_if_not_exist(
&[
(&secret_key.as_str().into(), &created_client_secret),
(&id_key.as_str().into(), &created_client_secret),
],
"csh",
None,
)
.await
{
Ok(v) if v.contains(&HsetnxReply::KeyNotSet) => {
Err(errors::StorageError::DuplicateValue {
entity: "ephemeral key",
key: None,
}
.into())
}
Ok(_) => {
let expire_at = expires.assume_utc().unix_timestamp();
self.get_redis_conn()
.map_err(Into::<errors::StorageError>::into)?
.set_expire_at(&secret_key.into(), expire_at)
.await
.change_context(errors::StorageError::KVError)?;
self.get_redis_conn()
.map_err(Into::<errors::StorageError>::into)?
.set_expire_at(&id_key.into(), expire_at)
.await
.change_context(errors::StorageError::KVError)?;
Ok(created_client_secret)
}
Err(er) => Err(er).change_context(errors::StorageError::KVError),
}
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn get_client_secret(
&self,
key: &str,
) -> CustomResult<ClientSecretType, errors::StorageError> {
let key = format!("cs_{key}");
self.get_redis_conn()
.map_err(Into::<errors::StorageError>::into)?
.get_hash_field_and_deserialize(&key.into(), "csh", "ClientSecretType")
.await
.change_context(errors::StorageError::KVError)
}
#[cfg(feature = "v2")]
async fn delete_client_secret(
&self,
id: &str,
) -> CustomResult<ClientSecretType, errors::StorageError> {
let client_secret = self.get_client_secret(id).await?;
let redis_id_key = client_secret.id.generate_redis_key();
let secret_key = client_secret.generate_secret_key();
self.get_redis_conn()
.map_err(Into::<errors::StorageError>::into)?
.delete_key(&redis_id_key.as_str().into())
.await
.map_err(|err| match err.current_context() {
RedisError::NotFound => {
err.change_context(errors::StorageError::ValueNotFound(redis_id_key))
}
_ => err.change_context(errors::StorageError::KVError),
})?;
self.get_redis_conn()
.map_err(Into::<errors::StorageError>::into)?
.delete_key(&secret_key.as_str().into())
.await
.map_err(|err| match err.current_context() {
RedisError::NotFound => {
err.change_context(errors::StorageError::ValueNotFound(secret_key))
}
_ => err.change_context(errors::StorageError::KVError),
})?;
Ok(client_secret)
}
}
}
#[async_trait::async_trait]
impl EphemeralKeyInterface for MockDb {
#[cfg(feature = "v1")]
async fn create_ephemeral_key(
&self,
ek: EphemeralKeyNew,
validity: i64,
) -> CustomResult<EphemeralKey, errors::StorageError> {
let mut ephemeral_keys = self.ephemeral_keys.lock().await;
let created_at = common_utils::date_time::now();
let expires = created_at.saturating_add(validity.hours());
let ephemeral_key = EphemeralKey {
id: ek.id,
merchant_id: ek.merchant_id,
customer_id: ek.customer_id,
created_at: created_at.assume_utc().unix_timestamp(),
expires: expires.assume_utc().unix_timestamp(),
secret: ek.secret,
};
ephemeral_keys.push(ephemeral_key.clone());
Ok(ephemeral_key)
}
#[cfg(feature = "v1")]
async fn get_ephemeral_key(
&self,
key: &str,
) -> CustomResult<EphemeralKey, errors::StorageError> {
match self
.ephemeral_keys
.lock()
.await
.iter()
.find(|ephemeral_key| ephemeral_key.secret.eq(key))
{
Some(ephemeral_key) => Ok(ephemeral_key.clone()),
None => Err(
errors::StorageError::ValueNotFound("ephemeral key not found".to_string()).into(),
),
}
}
#[cfg(feature = "v1")]
async fn delete_ephemeral_key(
&self,
id: &str,
) -> CustomResult<EphemeralKey, errors::StorageError> {
let mut ephemeral_keys = self.ephemeral_keys.lock().await;
if let Some(pos) = ephemeral_keys.iter().position(|x| (*x.id).eq(id)) {
let ek = ephemeral_keys.remove(pos);
Ok(ek)
} else {
return Err(
errors::StorageError::ValueNotFound("ephemeral key not found".to_string()).into(),
);
}
}
}
#[async_trait::async_trait]
impl ClientSecretInterface for MockDb {
#[cfg(feature = "v2")]
async fn create_client_secret(
&self,
new: ClientSecretTypeNew,
validity: i64,
) -> CustomResult<ClientSecretType, errors::StorageError> {
todo!()
}
#[cfg(feature = "v2")]
async fn get_client_secret(
&self,
key: &str,
) -> CustomResult<ClientSecretType, errors::StorageError> {
todo!()
}
#[cfg(feature = "v2")]
async fn delete_client_secret(
&self,
id: &str,
) -> CustomResult<ClientSecretType, errors::StorageError> {
todo!()
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/organization.rs | crates/router/src/db/organization.rs | use common_utils::{errors::CustomResult, id_type};
use diesel_models::{organization as storage, organization::OrganizationBridge};
use error_stack::report;
use router_env::{instrument, tracing};
use crate::{connection, core::errors, services::Store};
#[async_trait::async_trait]
pub trait OrganizationInterface {
async fn insert_organization(
&self,
organization: storage::OrganizationNew,
) -> CustomResult<storage::Organization, errors::StorageError>;
async fn find_organization_by_org_id(
&self,
org_id: &id_type::OrganizationId,
) -> CustomResult<storage::Organization, errors::StorageError>;
async fn update_organization_by_org_id(
&self,
org_id: &id_type::OrganizationId,
update: storage::OrganizationUpdate,
) -> CustomResult<storage::Organization, errors::StorageError>;
}
#[async_trait::async_trait]
impl OrganizationInterface for Store {
#[instrument(skip_all)]
async fn insert_organization(
&self,
organization: storage::OrganizationNew,
) -> CustomResult<storage::Organization, errors::StorageError> {
let conn = connection::pg_accounts_connection_write(self).await?;
organization
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_organization_by_org_id(
&self,
org_id: &id_type::OrganizationId,
) -> CustomResult<storage::Organization, errors::StorageError> {
let conn = connection::pg_accounts_connection_read(self).await?;
storage::Organization::find_by_org_id(&conn, org_id.to_owned())
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn update_organization_by_org_id(
&self,
org_id: &id_type::OrganizationId,
update: storage::OrganizationUpdate,
) -> CustomResult<storage::Organization, errors::StorageError> {
let conn = connection::pg_accounts_connection_write(self).await?;
storage::Organization::update_by_org_id(&conn, org_id.to_owned(), update)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
#[async_trait::async_trait]
impl OrganizationInterface for super::MockDb {
async fn insert_organization(
&self,
organization: storage::OrganizationNew,
) -> CustomResult<storage::Organization, errors::StorageError> {
let mut organizations = self.organizations.lock().await;
if organizations
.iter()
.any(|org| org.get_organization_id() == organization.get_organization_id())
{
Err(errors::StorageError::DuplicateValue {
entity: "org_id",
key: None,
})?
}
let org = storage::Organization::new(organization);
organizations.push(org.clone());
Ok(org)
}
async fn find_organization_by_org_id(
&self,
org_id: &id_type::OrganizationId,
) -> CustomResult<storage::Organization, errors::StorageError> {
let organizations = self.organizations.lock().await;
organizations
.iter()
.find(|org| org.get_organization_id() == *org_id)
.cloned()
.ok_or(
errors::StorageError::ValueNotFound(format!(
"No organization available for org_id = {org_id:?}",
))
.into(),
)
}
async fn update_organization_by_org_id(
&self,
org_id: &id_type::OrganizationId,
update: storage::OrganizationUpdate,
) -> CustomResult<storage::Organization, errors::StorageError> {
let mut organizations = self.organizations.lock().await;
organizations
.iter_mut()
.find(|org| org.get_organization_id() == *org_id)
.map(|org| match &update {
storage::OrganizationUpdate::Update {
organization_name,
organization_details,
metadata,
platform_merchant_id,
} => {
organization_name
.as_ref()
.map(|org_name| org.set_organization_name(org_name.to_owned()));
organization_details.clone_into(&mut org.organization_details);
metadata.clone_into(&mut org.metadata);
platform_merchant_id.clone_into(&mut org.platform_merchant_id);
org
}
})
.ok_or(
errors::StorageError::ValueNotFound(format!(
"No organization available for org_id = {org_id:?}",
))
.into(),
)
.cloned()
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/merchant_account.rs | crates/router/src/db/merchant_account.rs | pub use hyperswitch_domain_models::merchant_account::{self, MerchantAccountInterface};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/user_key_store.rs | crates/router/src/db/user_key_store.rs | use common_utils::{errors::CustomResult, types::keymanager};
use error_stack::{report, ResultExt};
use masking::Secret;
use router_env::{instrument, tracing};
use storage_impl::MockDb;
use crate::{
connection,
core::errors,
services::Store,
types::domain::{
self,
behaviour::{Conversion, ReverseConversion},
},
};
#[async_trait::async_trait]
pub trait UserKeyStoreInterface {
async fn insert_user_key_store(
&self,
user_key_store: domain::UserKeyStore,
key: &Secret<Vec<u8>>,
) -> CustomResult<domain::UserKeyStore, errors::StorageError>;
async fn get_user_key_store_by_user_id(
&self,
user_id: &str,
key: &Secret<Vec<u8>>,
) -> CustomResult<domain::UserKeyStore, errors::StorageError>;
async fn get_all_user_key_store(
&self,
key: &Secret<Vec<u8>>,
from: u32,
limit: u32,
) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError>;
}
#[async_trait::async_trait]
impl UserKeyStoreInterface for Store {
#[instrument(skip_all)]
async fn insert_user_key_store(
&self,
user_key_store: domain::UserKeyStore,
key: &Secret<Vec<u8>>,
) -> CustomResult<domain::UserKeyStore, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
let user_id = user_key_store.user_id.clone();
user_key_store
.construct_new()
.await
.change_context(errors::StorageError::EncryptionError)?
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))?
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
key,
keymanager::Identifier::User(user_id),
)
.await
.change_context(errors::StorageError::DecryptionError)
}
#[instrument(skip_all)]
async fn get_user_key_store_by_user_id(
&self,
user_id: &str,
key: &Secret<Vec<u8>>,
) -> CustomResult<domain::UserKeyStore, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
diesel_models::user_key_store::UserKeyStore::find_by_user_id(&conn, user_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))?
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
key,
keymanager::Identifier::User(user_id.to_owned()),
)
.await
.change_context(errors::StorageError::DecryptionError)
}
async fn get_all_user_key_store(
&self,
key: &Secret<Vec<u8>>,
from: u32,
limit: u32,
) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
let key_stores = diesel_models::user_key_store::UserKeyStore::get_all_user_key_stores(
&conn, from, limit,
)
.await
.map_err(|err| report!(errors::StorageError::from(err)))?;
futures::future::try_join_all(key_stores.into_iter().map(|key_store| async {
let user_id = key_store.user_id.clone();
key_store
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
key,
keymanager::Identifier::User(user_id),
)
.await
.change_context(errors::StorageError::DecryptionError)
}))
.await
}
}
#[async_trait::async_trait]
impl UserKeyStoreInterface for MockDb {
#[instrument(skip_all)]
async fn insert_user_key_store(
&self,
user_key_store: domain::UserKeyStore,
key: &Secret<Vec<u8>>,
) -> CustomResult<domain::UserKeyStore, errors::StorageError> {
let mut locked_user_key_store = self.user_key_store.lock().await;
if locked_user_key_store
.iter()
.any(|user_key| user_key.user_id == user_key_store.user_id)
{
Err(errors::StorageError::DuplicateValue {
entity: "user_key_store",
key: Some(user_key_store.user_id.clone()),
})?;
}
let user_key_store = Conversion::convert(user_key_store)
.await
.change_context(errors::StorageError::MockDbError)?;
locked_user_key_store.push(user_key_store.clone());
let user_id = user_key_store.user_id.clone();
user_key_store
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
key,
keymanager::Identifier::User(user_id),
)
.await
.change_context(errors::StorageError::DecryptionError)
}
async fn get_all_user_key_store(
&self,
key: &Secret<Vec<u8>>,
_from: u32,
_limit: u32,
) -> CustomResult<Vec<domain::UserKeyStore>, errors::StorageError> {
let user_key_store = self.user_key_store.lock().await;
futures::future::try_join_all(user_key_store.iter().map(|user_key| async {
let user_id = user_key.user_id.clone();
user_key
.to_owned()
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
key,
keymanager::Identifier::User(user_id),
)
.await
.change_context(errors::StorageError::DecryptionError)
}))
.await
}
#[instrument(skip_all)]
async fn get_user_key_store_by_user_id(
&self,
user_id: &str,
key: &Secret<Vec<u8>>,
) -> CustomResult<domain::UserKeyStore, errors::StorageError> {
self.user_key_store
.lock()
.await
.iter()
.find(|user_key_store| user_key_store.user_id == user_id)
.cloned()
.ok_or(errors::StorageError::ValueNotFound(format!(
"No user_key_store is found for user_id={user_id}",
)))?
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
key,
keymanager::Identifier::User(user_id.to_owned()),
)
.await
.change_context(errors::StorageError::DecryptionError)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/generic_link.rs | crates/router/src/db/generic_link.rs | use error_stack::report;
use router_env::{instrument, tracing};
use crate::{
connection,
core::errors::{self, CustomResult},
db::MockDb,
services::Store,
types::storage,
};
#[async_trait::async_trait]
pub trait GenericLinkInterface {
async fn find_generic_link_by_link_id(
&self,
link_id: &str,
) -> CustomResult<storage::GenericLinkState, errors::StorageError>;
async fn find_pm_collect_link_by_link_id(
&self,
link_id: &str,
) -> CustomResult<storage::PaymentMethodCollectLink, errors::StorageError>;
async fn find_payout_link_by_link_id(
&self,
link_id: &str,
) -> CustomResult<storage::PayoutLink, errors::StorageError>;
async fn insert_generic_link(
&self,
_generic_link: storage::GenericLinkNew,
) -> CustomResult<storage::GenericLinkState, errors::StorageError>;
async fn insert_pm_collect_link(
&self,
_pm_collect_link: storage::GenericLinkNew,
) -> CustomResult<storage::PaymentMethodCollectLink, errors::StorageError>;
async fn insert_payout_link(
&self,
_payout_link: storage::GenericLinkNew,
) -> CustomResult<storage::PayoutLink, errors::StorageError>;
async fn update_payout_link(
&self,
payout_link: storage::PayoutLink,
payout_link_update: storage::PayoutLinkUpdate,
) -> CustomResult<storage::PayoutLink, errors::StorageError>;
}
#[async_trait::async_trait]
impl GenericLinkInterface for Store {
#[instrument(skip_all)]
async fn find_generic_link_by_link_id(
&self,
link_id: &str,
) -> CustomResult<storage::GenericLinkState, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::GenericLink::find_generic_link_by_link_id(&conn, link_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_pm_collect_link_by_link_id(
&self,
link_id: &str,
) -> CustomResult<storage::PaymentMethodCollectLink, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::GenericLink::find_pm_collect_link_by_link_id(&conn, link_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_payout_link_by_link_id(
&self,
link_id: &str,
) -> CustomResult<storage::PayoutLink, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::GenericLink::find_payout_link_by_link_id(&conn, link_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn insert_generic_link(
&self,
generic_link: storage::GenericLinkNew,
) -> CustomResult<storage::GenericLinkState, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
generic_link
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn insert_pm_collect_link(
&self,
pm_collect_link: storage::GenericLinkNew,
) -> CustomResult<storage::PaymentMethodCollectLink, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
pm_collect_link
.insert_pm_collect_link(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn insert_payout_link(
&self,
pm_collect_link: storage::GenericLinkNew,
) -> CustomResult<storage::PayoutLink, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
pm_collect_link
.insert_payout_link(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn update_payout_link(
&self,
payout_link: storage::PayoutLink,
payout_link_update: storage::PayoutLinkUpdate,
) -> CustomResult<storage::PayoutLink, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
payout_link
.update_payout_link(&conn, payout_link_update)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
#[async_trait::async_trait]
impl GenericLinkInterface for MockDb {
async fn find_generic_link_by_link_id(
&self,
_generic_link_id: &str,
) -> CustomResult<storage::GenericLinkState, errors::StorageError> {
// TODO: Implement function for `MockDb`x
Err(errors::StorageError::MockDbError)?
}
async fn find_pm_collect_link_by_link_id(
&self,
_generic_link_id: &str,
) -> CustomResult<storage::PaymentMethodCollectLink, errors::StorageError> {
// TODO: Implement function for `MockDb`x
Err(errors::StorageError::MockDbError)?
}
async fn find_payout_link_by_link_id(
&self,
_generic_link_id: &str,
) -> CustomResult<storage::PayoutLink, errors::StorageError> {
// TODO: Implement function for `MockDb`x
Err(errors::StorageError::MockDbError)?
}
async fn insert_generic_link(
&self,
_generic_link: storage::GenericLinkNew,
) -> CustomResult<storage::GenericLinkState, errors::StorageError> {
// TODO: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
}
async fn insert_pm_collect_link(
&self,
_pm_collect_link: storage::GenericLinkNew,
) -> CustomResult<storage::PaymentMethodCollectLink, errors::StorageError> {
// TODO: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
}
async fn insert_payout_link(
&self,
_pm_collect_link: storage::GenericLinkNew,
) -> CustomResult<storage::PayoutLink, errors::StorageError> {
// TODO: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
}
async fn update_payout_link(
&self,
_payout_link: storage::PayoutLink,
_payout_link_update: storage::PayoutLinkUpdate,
) -> CustomResult<storage::PayoutLink, errors::StorageError> {
// TODO: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/user_role.rs | crates/router/src/db/user_role.rs | use common_enums::EntityType;
use common_utils::id_type;
use diesel_models::{
enums::{self, UserStatus},
user_role as storage,
};
use error_stack::{report, ResultExt};
use router_env::{instrument, tracing};
use super::MockDb;
use crate::{
connection,
core::errors::{self, CustomResult},
services::Store,
};
pub struct ListUserRolesByOrgIdPayload<'a> {
pub user_id: Option<&'a String>,
pub tenant_id: &'a id_type::TenantId,
pub org_id: &'a id_type::OrganizationId,
pub merchant_id: Option<&'a id_type::MerchantId>,
pub profile_id: Option<&'a id_type::ProfileId>,
pub version: Option<enums::UserRoleVersion>,
pub limit: Option<u32>,
}
pub struct ListUserRolesByUserIdPayload<'a> {
pub user_id: &'a str,
pub tenant_id: &'a id_type::TenantId,
pub org_id: Option<&'a id_type::OrganizationId>,
pub merchant_id: Option<&'a id_type::MerchantId>,
pub profile_id: Option<&'a id_type::ProfileId>,
pub entity_id: Option<&'a String>,
pub version: Option<enums::UserRoleVersion>,
pub status: Option<UserStatus>,
pub limit: Option<u32>,
}
#[async_trait::async_trait]
pub trait UserRoleInterface {
async fn insert_user_role(
&self,
user_role: storage::UserRoleNew,
) -> CustomResult<storage::UserRole, errors::StorageError>;
async fn find_user_role_by_user_id_and_lineage(
&self,
user_id: &str,
tenant_id: &id_type::TenantId,
org_id: &id_type::OrganizationId,
merchant_id: &id_type::MerchantId,
profile_id: &id_type::ProfileId,
version: enums::UserRoleVersion,
) -> CustomResult<storage::UserRole, errors::StorageError>;
async fn find_user_role_by_user_id_and_lineage_with_entity_type(
&self,
user_id: &str,
tenant_id: &id_type::TenantId,
org_id: &id_type::OrganizationId,
merchant_id: &id_type::MerchantId,
profile_id: &id_type::ProfileId,
version: enums::UserRoleVersion,
) -> CustomResult<storage::UserRole, errors::StorageError>;
#[allow(clippy::too_many_arguments)]
async fn update_user_role_by_user_id_and_lineage(
&self,
user_id: &str,
tenant_id: &id_type::TenantId,
org_id: &id_type::OrganizationId,
merchant_id: Option<&id_type::MerchantId>,
profile_id: Option<&id_type::ProfileId>,
update: storage::UserRoleUpdate,
version: enums::UserRoleVersion,
) -> CustomResult<storage::UserRole, errors::StorageError>;
async fn delete_user_role_by_user_id_and_lineage(
&self,
user_id: &str,
tenant_id: &id_type::TenantId,
org_id: &id_type::OrganizationId,
merchant_id: &id_type::MerchantId,
profile_id: &id_type::ProfileId,
version: enums::UserRoleVersion,
) -> CustomResult<storage::UserRole, errors::StorageError>;
async fn list_user_roles_by_user_id<'a>(
&self,
payload: ListUserRolesByUserIdPayload<'a>,
) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>;
async fn list_user_roles_by_user_id_across_tenants(
&self,
user_id: &str,
limit: Option<u32>,
) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>;
async fn list_user_roles_by_org_id<'a>(
&self,
payload: ListUserRolesByOrgIdPayload<'a>,
) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>;
}
#[async_trait::async_trait]
impl UserRoleInterface for Store {
#[instrument(skip_all)]
async fn insert_user_role(
&self,
user_role: storage::UserRoleNew,
) -> CustomResult<storage::UserRole, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
user_role
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_user_role_by_user_id_and_lineage(
&self,
user_id: &str,
tenant_id: &id_type::TenantId,
org_id: &id_type::OrganizationId,
merchant_id: &id_type::MerchantId,
profile_id: &id_type::ProfileId,
version: enums::UserRoleVersion,
) -> CustomResult<storage::UserRole, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::UserRole::find_by_user_id_tenant_id_org_id_merchant_id_profile_id(
&conn,
user_id.to_owned(),
tenant_id.to_owned(),
org_id.to_owned(),
merchant_id.to_owned(),
profile_id.to_owned(),
version,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_user_role_by_user_id_and_lineage_with_entity_type(
&self,
user_id: &str,
tenant_id: &id_type::TenantId,
org_id: &id_type::OrganizationId,
merchant_id: &id_type::MerchantId,
profile_id: &id_type::ProfileId,
version: enums::UserRoleVersion,
) -> CustomResult<storage::UserRole, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::UserRole::find_by_user_id_tenant_id_org_id_merchant_id_profile_id_with_entity_type(
&conn,
user_id.to_owned(),
tenant_id.to_owned(),
org_id.to_owned(),
merchant_id.to_owned(),
profile_id.to_owned(),
version,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn update_user_role_by_user_id_and_lineage(
&self,
user_id: &str,
tenant_id: &id_type::TenantId,
org_id: &id_type::OrganizationId,
merchant_id: Option<&id_type::MerchantId>,
profile_id: Option<&id_type::ProfileId>,
update: storage::UserRoleUpdate,
version: enums::UserRoleVersion,
) -> CustomResult<storage::UserRole, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::UserRole::update_by_user_id_tenant_id_org_id_merchant_id_profile_id(
&conn,
user_id.to_owned(),
tenant_id.to_owned(),
org_id.to_owned(),
merchant_id.cloned(),
profile_id.cloned(),
update,
version,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn delete_user_role_by_user_id_and_lineage(
&self,
user_id: &str,
tenant_id: &id_type::TenantId,
org_id: &id_type::OrganizationId,
merchant_id: &id_type::MerchantId,
profile_id: &id_type::ProfileId,
version: enums::UserRoleVersion,
) -> CustomResult<storage::UserRole, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::UserRole::delete_by_user_id_tenant_id_org_id_merchant_id_profile_id(
&conn,
user_id.to_owned(),
tenant_id.to_owned(),
org_id.to_owned(),
merchant_id.to_owned(),
profile_id.to_owned(),
version,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
async fn list_user_roles_by_user_id<'a>(
&self,
payload: ListUserRolesByUserIdPayload<'a>,
) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::UserRole::generic_user_roles_list_for_user(
&conn,
payload.user_id.to_owned(),
payload.tenant_id.to_owned(),
payload.org_id.cloned(),
payload.merchant_id.cloned(),
payload.profile_id.cloned(),
payload.entity_id.cloned(),
payload.status,
payload.version,
payload.limit,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
async fn list_user_roles_by_user_id_across_tenants(
&self,
user_id: &str,
limit: Option<u32>,
) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::UserRole::list_user_roles_by_user_id_across_tenants(
&conn,
user_id.to_owned(),
limit,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
async fn list_user_roles_by_org_id<'a>(
&self,
payload: ListUserRolesByOrgIdPayload<'a>,
) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::UserRole::generic_user_roles_list_for_org_and_extra(
&conn,
payload.user_id.cloned(),
payload.tenant_id.to_owned(),
payload.org_id.to_owned(),
payload.merchant_id.cloned(),
payload.profile_id.cloned(),
payload.version,
payload.limit,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
#[async_trait::async_trait]
impl UserRoleInterface for MockDb {
async fn insert_user_role(
&self,
user_role: storage::UserRoleNew,
) -> CustomResult<storage::UserRole, errors::StorageError> {
let mut db_user_roles = self.user_roles.lock().await;
if db_user_roles
.iter()
.any(|user_role_inner| user_role_inner.user_id == user_role.user_id)
{
Err(errors::StorageError::DuplicateValue {
entity: "user_id",
key: None,
})?
}
let user_role = storage::UserRole {
id: i32::try_from(db_user_roles.len())
.change_context(errors::StorageError::MockDbError)?,
user_id: user_role.user_id,
merchant_id: user_role.merchant_id,
role_id: user_role.role_id,
status: user_role.status,
created_by: user_role.created_by,
created_at: user_role.created_at,
last_modified: user_role.last_modified,
last_modified_by: user_role.last_modified_by,
org_id: user_role.org_id,
profile_id: None,
entity_id: None,
entity_type: None,
version: enums::UserRoleVersion::V1,
tenant_id: user_role.tenant_id,
};
db_user_roles.push(user_role.clone());
Ok(user_role)
}
async fn find_user_role_by_user_id_and_lineage(
&self,
user_id: &str,
tenant_id: &id_type::TenantId,
org_id: &id_type::OrganizationId,
merchant_id: &id_type::MerchantId,
profile_id: &id_type::ProfileId,
version: enums::UserRoleVersion,
) -> CustomResult<storage::UserRole, errors::StorageError> {
let user_roles = self.user_roles.lock().await;
for user_role in user_roles.iter() {
let tenant_level_check = user_role.tenant_id == *tenant_id
&& user_role.org_id.is_none()
&& user_role.merchant_id.is_none()
&& user_role.profile_id.is_none();
let org_level_check = user_role.tenant_id == *tenant_id
&& user_role.org_id.as_ref() == Some(org_id)
&& user_role.merchant_id.is_none()
&& user_role.profile_id.is_none();
let merchant_level_check = user_role.tenant_id == *tenant_id
&& user_role.org_id.as_ref() == Some(org_id)
&& user_role.merchant_id.as_ref() == Some(merchant_id)
&& user_role.profile_id.is_none();
let profile_level_check = user_role.tenant_id == *tenant_id
&& user_role.org_id.as_ref() == Some(org_id)
&& user_role.merchant_id.as_ref() == Some(merchant_id)
&& user_role.profile_id.as_ref() == Some(profile_id);
// Check if any condition matches and the version matches
if user_role.user_id == user_id
&& (tenant_level_check
|| org_level_check
|| merchant_level_check
|| profile_level_check)
&& user_role.version == version
{
return Ok(user_role.clone());
}
}
Err(errors::StorageError::ValueNotFound(format!(
"No user role available for user_id = {user_id} in the current token hierarchy",
))
.into())
}
async fn find_user_role_by_user_id_and_lineage_with_entity_type(
&self,
user_id: &str,
tenant_id: &id_type::TenantId,
org_id: &id_type::OrganizationId,
merchant_id: &id_type::MerchantId,
profile_id: &id_type::ProfileId,
version: enums::UserRoleVersion,
) -> CustomResult<storage::UserRole, errors::StorageError> {
let user_roles = self.user_roles.lock().await;
for user_role in user_roles.iter() {
let tenant_level_check = user_role.tenant_id == *tenant_id
&& user_role.entity_type == Some(EntityType::Tenant);
let org_level_check = user_role.tenant_id == *tenant_id
&& user_role.org_id.as_ref() == Some(org_id)
&& user_role.entity_type == Some(EntityType::Organization);
let merchant_level_check = user_role.tenant_id == *tenant_id
&& user_role.org_id.as_ref() == Some(org_id)
&& user_role.merchant_id.as_ref() == Some(merchant_id)
&& user_role.entity_type == Some(EntityType::Merchant);
let profile_level_check = user_role.tenant_id == *tenant_id
&& user_role.org_id.as_ref() == Some(org_id)
&& user_role.merchant_id.as_ref() == Some(merchant_id)
&& user_role.profile_id.as_ref() == Some(profile_id)
&& user_role.entity_type == Some(EntityType::Profile);
// Check if any condition matches and the version matches
if user_role.user_id == user_id
&& (tenant_level_check
|| org_level_check
|| merchant_level_check
|| profile_level_check)
&& user_role.version == version
{
return Ok(user_role.clone());
}
}
Err(errors::StorageError::ValueNotFound(format!(
"No user role available for user_id = {user_id} in the current token hierarchy",
))
.into())
}
async fn update_user_role_by_user_id_and_lineage(
&self,
user_id: &str,
tenant_id: &id_type::TenantId,
org_id: &id_type::OrganizationId,
merchant_id: Option<&id_type::MerchantId>,
profile_id: Option<&id_type::ProfileId>,
update: storage::UserRoleUpdate,
version: enums::UserRoleVersion,
) -> CustomResult<storage::UserRole, errors::StorageError> {
let mut user_roles = self.user_roles.lock().await;
for user_role in user_roles.iter_mut() {
let tenant_level_check = user_role.tenant_id == *tenant_id
&& user_role.org_id.is_none()
&& user_role.merchant_id.is_none()
&& user_role.profile_id.is_none();
let org_level_check = user_role.tenant_id == *tenant_id
&& user_role.org_id.as_ref() == Some(org_id)
&& user_role.merchant_id.is_none()
&& user_role.profile_id.is_none();
let merchant_level_check = user_role.tenant_id == *tenant_id
&& user_role.org_id.as_ref() == Some(org_id)
&& user_role.merchant_id.as_ref() == merchant_id
&& user_role.profile_id.is_none();
let profile_level_check = user_role.tenant_id == *tenant_id
&& user_role.org_id.as_ref() == Some(org_id)
&& user_role.merchant_id.as_ref() == merchant_id
&& user_role.profile_id.as_ref() == profile_id;
// Check if any condition matches and the version matches
if user_role.user_id == user_id
&& (tenant_level_check
|| org_level_check
|| merchant_level_check
|| profile_level_check)
&& user_role.version == version
{
match &update {
storage::UserRoleUpdate::UpdateRole {
role_id,
modified_by,
} => {
user_role.role_id = role_id.to_string();
user_role.last_modified_by = modified_by.to_string();
}
storage::UserRoleUpdate::UpdateStatus {
status,
modified_by,
} => {
user_role.status = *status;
user_role.last_modified_by = modified_by.to_string();
}
}
return Ok(user_role.clone());
}
}
Err(
errors::StorageError::ValueNotFound("Cannot find user role to update".to_string())
.into(),
)
}
async fn delete_user_role_by_user_id_and_lineage(
&self,
user_id: &str,
tenant_id: &id_type::TenantId,
org_id: &id_type::OrganizationId,
merchant_id: &id_type::MerchantId,
profile_id: &id_type::ProfileId,
version: enums::UserRoleVersion,
) -> CustomResult<storage::UserRole, errors::StorageError> {
let mut user_roles = self.user_roles.lock().await;
// Find the position of the user role to delete
let index = user_roles.iter().position(|role| {
let tenant_level_check = role.tenant_id == *tenant_id
&& role.org_id.is_none()
&& role.merchant_id.is_none()
&& role.profile_id.is_none();
let org_level_check = role.tenant_id == *tenant_id
&& role.org_id.as_ref() == Some(org_id)
&& role.merchant_id.is_none()
&& role.profile_id.is_none();
let merchant_level_check = role.tenant_id == *tenant_id
&& role.org_id.as_ref() == Some(org_id)
&& role.merchant_id.as_ref() == Some(merchant_id)
&& role.profile_id.is_none();
let profile_level_check = role.tenant_id == *tenant_id
&& role.org_id.as_ref() == Some(org_id)
&& role.merchant_id.as_ref() == Some(merchant_id)
&& role.profile_id.as_ref() == Some(profile_id);
// Check if the user role matches the conditions and the version matches
role.user_id == user_id
&& (tenant_level_check
|| org_level_check
|| merchant_level_check
|| profile_level_check)
&& role.version == version
});
// Remove and return the user role if found
match index {
Some(idx) => Ok(user_roles.remove(idx)),
None => Err(errors::StorageError::ValueNotFound(
"Cannot find user role to delete".to_string(),
)
.into()),
}
}
async fn list_user_roles_by_user_id<'a>(
&self,
payload: ListUserRolesByUserIdPayload<'a>,
) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
let user_roles = self.user_roles.lock().await;
let mut filtered_roles: Vec<_> = user_roles
.iter()
.filter_map(|role| {
let mut filter_condition = role.user_id == payload.user_id;
role.org_id
.as_ref()
.zip(payload.org_id)
.inspect(|(role_org_id, org_id)| {
filter_condition = filter_condition && role_org_id == org_id
});
role.merchant_id.as_ref().zip(payload.merchant_id).inspect(
|(role_merchant_id, merchant_id)| {
filter_condition = filter_condition && role_merchant_id == merchant_id
},
);
role.profile_id.as_ref().zip(payload.profile_id).inspect(
|(role_profile_id, profile_id)| {
filter_condition = filter_condition && role_profile_id == profile_id
},
);
role.entity_id.as_ref().zip(payload.entity_id).inspect(
|(role_entity_id, entity_id)| {
filter_condition = filter_condition && role_entity_id == entity_id
},
);
payload
.version
.inspect(|ver| filter_condition = filter_condition && ver == &role.version);
payload.status.inspect(|status| {
filter_condition = filter_condition && status == &role.status
});
filter_condition.then(|| role.to_owned())
})
.collect();
if let Some(Ok(limit)) = payload.limit.map(|val| val.try_into()) {
filtered_roles = filtered_roles.into_iter().take(limit).collect();
}
Ok(filtered_roles)
}
async fn list_user_roles_by_user_id_across_tenants(
&self,
user_id: &str,
limit: Option<u32>,
) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
let user_roles = self.user_roles.lock().await;
let filtered_roles: Vec<_> = user_roles
.iter()
.filter(|role| role.user_id == user_id)
.cloned()
.collect();
if let Some(Ok(limit)) = limit.map(|val| val.try_into()) {
return Ok(filtered_roles.into_iter().take(limit).collect());
}
Ok(filtered_roles)
}
async fn list_user_roles_by_org_id<'a>(
&self,
payload: ListUserRolesByOrgIdPayload<'a>,
) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
let user_roles = self.user_roles.lock().await;
let mut filtered_roles = Vec::new();
for role in user_roles.iter() {
let role_org_id = role
.org_id
.as_ref()
.ok_or(report!(errors::StorageError::MockDbError))?;
let mut filter_condition = role_org_id == payload.org_id;
if let Some(user_id) = payload.user_id {
filter_condition = filter_condition && user_id == &role.user_id
}
role.merchant_id.as_ref().zip(payload.merchant_id).inspect(
|(role_merchant_id, merchant_id)| {
filter_condition = filter_condition && role_merchant_id == merchant_id
},
);
role.profile_id.as_ref().zip(payload.profile_id).inspect(
|(role_profile_id, profile_id)| {
filter_condition = filter_condition && role_profile_id == profile_id
},
);
payload
.version
.inspect(|ver| filter_condition = filter_condition && ver == &role.version);
if filter_condition {
filtered_roles.push(role.clone())
}
}
Ok(filtered_roles)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/relay.rs | crates/router/src/db/relay.rs | use diesel_models;
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::behaviour::{Conversion, ReverseConversion};
use storage_impl::MockDb;
use super::domain;
use crate::{
connection,
core::errors::{self, CustomResult},
db::kafka_store::KafkaStore,
services::Store,
};
#[async_trait::async_trait]
pub trait RelayInterface {
async fn insert_relay(
&self,
merchant_key_store: &domain::MerchantKeyStore,
new: hyperswitch_domain_models::relay::Relay,
) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError>;
async fn update_relay(
&self,
merchant_key_store: &domain::MerchantKeyStore,
current_state: hyperswitch_domain_models::relay::Relay,
relay_update: hyperswitch_domain_models::relay::RelayUpdate,
) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError>;
async fn find_relay_by_id(
&self,
merchant_key_store: &domain::MerchantKeyStore,
relay_id: &common_utils::id_type::RelayId,
) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError>;
async fn find_relay_by_profile_id_connector_reference_id(
&self,
merchant_key_store: &domain::MerchantKeyStore,
profile_id: &common_utils::id_type::ProfileId,
connector_reference_id: &str,
) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError>;
}
#[async_trait::async_trait]
impl RelayInterface for Store {
async fn insert_relay(
&self,
merchant_key_store: &domain::MerchantKeyStore,
new: hyperswitch_domain_models::relay::Relay,
) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
new.construct_new()
.await
.change_context(errors::StorageError::EncryptionError)?
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))?
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
}
async fn update_relay(
&self,
merchant_key_store: &domain::MerchantKeyStore,
current_state: hyperswitch_domain_models::relay::Relay,
relay_update: hyperswitch_domain_models::relay::RelayUpdate,
) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
Conversion::convert(current_state)
.await
.change_context(errors::StorageError::EncryptionError)?
.update(
&conn,
diesel_models::relay::RelayUpdateInternal::from(relay_update),
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))?
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
}
async fn find_relay_by_id(
&self,
merchant_key_store: &domain::MerchantKeyStore,
relay_id: &common_utils::id_type::RelayId,
) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
diesel_models::relay::Relay::find_by_id(&conn, relay_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))?
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
}
async fn find_relay_by_profile_id_connector_reference_id(
&self,
merchant_key_store: &domain::MerchantKeyStore,
profile_id: &common_utils::id_type::ProfileId,
connector_reference_id: &str,
) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
diesel_models::relay::Relay::find_by_profile_id_connector_reference_id(
&conn,
profile_id,
connector_reference_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))?
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
}
}
#[async_trait::async_trait]
impl RelayInterface for MockDb {
async fn insert_relay(
&self,
_merchant_key_store: &domain::MerchantKeyStore,
_new: hyperswitch_domain_models::relay::Relay,
) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
async fn update_relay(
&self,
_merchant_key_store: &domain::MerchantKeyStore,
_current_state: hyperswitch_domain_models::relay::Relay,
_relay_update: hyperswitch_domain_models::relay::RelayUpdate,
) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
async fn find_relay_by_id(
&self,
_merchant_key_store: &domain::MerchantKeyStore,
_relay_id: &common_utils::id_type::RelayId,
) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
async fn find_relay_by_profile_id_connector_reference_id(
&self,
_merchant_key_store: &domain::MerchantKeyStore,
_profile_id: &common_utils::id_type::ProfileId,
_connector_reference_id: &str,
) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
}
#[async_trait::async_trait]
impl RelayInterface for KafkaStore {
async fn insert_relay(
&self,
merchant_key_store: &domain::MerchantKeyStore,
new: hyperswitch_domain_models::relay::Relay,
) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> {
self.diesel_store
.insert_relay(merchant_key_store, new)
.await
}
async fn update_relay(
&self,
merchant_key_store: &domain::MerchantKeyStore,
current_state: hyperswitch_domain_models::relay::Relay,
relay_update: hyperswitch_domain_models::relay::RelayUpdate,
) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> {
self.diesel_store
.update_relay(merchant_key_store, current_state, relay_update)
.await
}
async fn find_relay_by_id(
&self,
merchant_key_store: &domain::MerchantKeyStore,
relay_id: &common_utils::id_type::RelayId,
) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> {
self.diesel_store
.find_relay_by_id(merchant_key_store, relay_id)
.await
}
async fn find_relay_by_profile_id_connector_reference_id(
&self,
merchant_key_store: &domain::MerchantKeyStore,
profile_id: &common_utils::id_type::ProfileId,
connector_reference_id: &str,
) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> {
self.diesel_store
.find_relay_by_profile_id_connector_reference_id(
merchant_key_store,
profile_id,
connector_reference_id,
)
.await
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/file.rs | crates/router/src/db/file.rs | use error_stack::report;
use router_env::{instrument, tracing};
use super::{MockDb, Store};
use crate::{
connection,
core::errors::{self, CustomResult},
types::storage,
};
#[async_trait::async_trait]
pub trait FileMetadataInterface {
async fn insert_file_metadata(
&self,
file: storage::FileMetadataNew,
) -> CustomResult<storage::FileMetadata, errors::StorageError>;
async fn find_file_metadata_by_merchant_id_file_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
file_id: &str,
) -> CustomResult<storage::FileMetadata, errors::StorageError>;
async fn delete_file_metadata_by_merchant_id_file_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
file_id: &str,
) -> CustomResult<bool, errors::StorageError>;
async fn update_file_metadata(
&self,
this: storage::FileMetadata,
file_metadata: storage::FileMetadataUpdate,
) -> CustomResult<storage::FileMetadata, errors::StorageError>;
}
#[async_trait::async_trait]
impl FileMetadataInterface for Store {
#[instrument(skip_all)]
async fn insert_file_metadata(
&self,
file: storage::FileMetadataNew,
) -> CustomResult<storage::FileMetadata, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
file.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_file_metadata_by_merchant_id_file_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
file_id: &str,
) -> CustomResult<storage::FileMetadata, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::FileMetadata::find_by_merchant_id_file_id(&conn, merchant_id, file_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn delete_file_metadata_by_merchant_id_file_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
file_id: &str,
) -> CustomResult<bool, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::FileMetadata::delete_by_merchant_id_file_id(&conn, merchant_id, file_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn update_file_metadata(
&self,
this: storage::FileMetadata,
file_metadata: storage::FileMetadataUpdate,
) -> CustomResult<storage::FileMetadata, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
this.update(&conn, file_metadata)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
#[async_trait::async_trait]
impl FileMetadataInterface for MockDb {
async fn insert_file_metadata(
&self,
_file: storage::FileMetadataNew,
) -> CustomResult<storage::FileMetadata, errors::StorageError> {
// TODO: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
}
async fn find_file_metadata_by_merchant_id_file_id(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_file_id: &str,
) -> CustomResult<storage::FileMetadata, errors::StorageError> {
// TODO: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
}
async fn delete_file_metadata_by_merchant_id_file_id(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_file_id: &str,
) -> CustomResult<bool, errors::StorageError> {
// TODO: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
}
async fn update_file_metadata(
&self,
_this: storage::FileMetadata,
_file_metadata: storage::FileMetadataUpdate,
) -> CustomResult<storage::FileMetadata, errors::StorageError> {
// TODO: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/merchant_connector_account.rs | crates/router/src/db/merchant_connector_account.rs | use common_utils::ext_traits::{ByteSliceExt, Encode};
use error_stack::ResultExt;
pub use hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccountInterface;
use router_env::{instrument, tracing};
use storage_impl::redis::kv_store::RedisConnInterface;
use super::{MockDb, Store};
use crate::{
core::errors::{self, CustomResult},
types,
};
#[async_trait::async_trait]
pub trait ConnectorAccessToken {
async fn get_access_token(
&self,
&key: String,
) -> CustomResult<Option<types::AccessToken>, errors::StorageError>;
async fn set_access_token(
&self,
key: String,
access_token: types::AccessToken,
) -> CustomResult<(), errors::StorageError>;
}
#[async_trait::async_trait]
impl ConnectorAccessToken for Store {
#[instrument(skip_all)]
async fn get_access_token(
&self,
key: String,
) -> CustomResult<Option<types::AccessToken>, errors::StorageError> {
//TODO: Handle race condition
// This function should acquire a global lock on some resource, if access token is already
// being refreshed by other request then wait till it finishes and use the same access token
let maybe_token = self
.get_redis_conn()
.map_err(Into::<errors::StorageError>::into)?
.get_key::<Option<Vec<u8>>>(&key.into())
.await
.change_context(errors::StorageError::KVError)
.attach_printable("DB error when getting access token")?;
let access_token = maybe_token
.map(|token| token.parse_struct::<types::AccessToken>("AccessToken"))
.transpose()
.change_context(errors::StorageError::DeserializationFailed)?;
Ok(access_token)
}
#[instrument(skip_all)]
async fn set_access_token(
&self,
key: String,
access_token: types::AccessToken,
) -> CustomResult<(), errors::StorageError> {
let serialized_access_token = access_token
.encode_to_string_of_json()
.change_context(errors::StorageError::SerializationFailed)?;
self.get_redis_conn()
.map_err(Into::<errors::StorageError>::into)?
.set_key_with_expiry(&key.into(), serialized_access_token, access_token.expires)
.await
.change_context(errors::StorageError::KVError)
}
}
#[async_trait::async_trait]
impl ConnectorAccessToken for MockDb {
async fn get_access_token(
&self,
_key: String,
) -> CustomResult<Option<types::AccessToken>, errors::StorageError> {
Ok(None)
}
async fn set_access_token(
&self,
_key: String,
_access_token: types::AccessToken,
) -> CustomResult<(), errors::StorageError> {
Ok(())
}
}
#[cfg(feature = "accounts_cache")]
#[cfg(test)]
mod merchant_connector_account_cache_tests {
use std::sync::Arc;
#[cfg(feature = "v1")]
use api_models::enums::CountryAlpha2;
use common_utils::{
date_time, type_name,
types::keymanager::{Identifier, KeyManagerState},
};
use diesel_models::enums::ConnectorType;
use error_stack::ResultExt;
use hyperswitch_domain_models::master_key::MasterKeyInterface;
use masking::PeekInterface;
use storage_impl::redis::{
cache::{self, CacheKey, CacheKind, ACCOUNTS_CACHE},
kv_store::RedisConnInterface,
pub_sub::PubSubInterface,
};
use time::macros::datetime;
use tokio::sync::oneshot;
use crate::{
core::errors,
db::{
merchant_connector_account::MerchantConnectorAccountInterface,
merchant_key_store::MerchantKeyStoreInterface, MockDb,
},
routes::{
self,
app::{settings::Settings, StorageImpl},
},
services,
types::{
domain::{self, behaviour::Conversion},
storage,
},
};
#[tokio::test]
#[cfg(feature = "v1")]
async fn test_connector_profile_id_cache() {
let conf = Settings::new().unwrap();
let tx: oneshot::Sender<()> = oneshot::channel().0;
let app_state = Box::pin(routes::AppState::with_storage(
conf,
StorageImpl::PostgresqlTest,
tx,
Box::new(services::MockApiClient),
))
.await;
let state = &Arc::new(app_state)
.get_session_state(
&common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(),
None,
|| {},
)
.unwrap();
let db = MockDb::new(
&redis_interface::RedisSettings::default(),
KeyManagerState::new(),
)
.await
.expect("Failed to create Mock store");
let redis_conn = db.get_redis_conn().unwrap();
let master_key = db.get_master_key();
redis_conn
.subscribe("hyperswitch_invalidate")
.await
.unwrap();
let merchant_id =
common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from("test_merchant"))
.unwrap();
let connector_label = "stripe_USA";
let merchant_connector_id = "simple_merchant_connector_id";
let profile_id =
common_utils::id_type::ProfileId::try_from(std::borrow::Cow::from("pro_max_ultra"))
.unwrap();
let key_manager_state = &state.into();
db.insert_merchant_key_store(
domain::MerchantKeyStore {
merchant_id: merchant_id.clone(),
key: domain::types::crypto_operation(
key_manager_state,
type_name!(domain::MerchantKeyStore),
domain::types::CryptoOperation::EncryptLocally(
services::generate_aes256_key().unwrap().to_vec().into(),
),
Identifier::Merchant(merchant_id.clone()),
master_key,
)
.await
.and_then(|val| val.try_into_operation())
.unwrap(),
created_at: datetime!(2023-02-01 0:00),
},
&master_key.to_vec().into(),
)
.await
.unwrap();
let merchant_key = db
.get_merchant_key_store_by_merchant_id(&merchant_id, &master_key.to_vec().into())
.await
.unwrap();
let mca = domain::MerchantConnectorAccount {
merchant_id: merchant_id.to_owned(),
connector_name: "stripe".to_string(),
connector_account_details: domain::types::crypto_operation(
key_manager_state,
type_name!(domain::MerchantConnectorAccount),
domain::types::CryptoOperation::Encrypt(serde_json::Value::default().into()),
Identifier::Merchant(merchant_key.merchant_id.clone()),
merchant_key.key.get_inner().peek(),
)
.await
.and_then(|val| val.try_into_operation())
.unwrap(),
test_mode: None,
disabled: None,
merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId::wrap(
merchant_connector_id.to_string(),
)
.unwrap(),
payment_methods_enabled: None,
connector_type: ConnectorType::FinOperations,
metadata: None,
frm_configs: None,
connector_label: Some(connector_label.to_string()),
business_country: Some(CountryAlpha2::US),
business_label: Some("cloth".to_string()),
business_sub_label: None,
created_at: date_time::now(),
modified_at: date_time::now(),
connector_webhook_details: None,
profile_id: profile_id.to_owned(),
applepay_verified_domains: None,
pm_auth_config: None,
status: common_enums::ConnectorStatus::Inactive,
connector_wallets_details: Some(
domain::types::crypto_operation(
key_manager_state,
type_name!(domain::MerchantConnectorAccount),
domain::types::CryptoOperation::Encrypt(serde_json::Value::default().into()),
Identifier::Merchant(merchant_key.merchant_id.clone()),
merchant_key.key.get_inner().peek(),
)
.await
.and_then(|val| val.try_into_operation())
.unwrap(),
),
additional_merchant_data: None,
version: common_types::consts::API_VERSION,
};
db.insert_merchant_connector_account(mca.clone(), &merchant_key)
.await
.unwrap();
let find_call = || async {
Conversion::convert(
db.find_merchant_connector_account_by_profile_id_connector_name(
&profile_id,
&mca.connector_name,
&merchant_key,
)
.await
.unwrap(),
)
.await
.change_context(errors::StorageError::DecryptionError)
};
let _: storage::MerchantConnectorAccount = cache::get_or_populate_in_memory(
&db,
&format!(
"{}_{}",
merchant_id.get_string_repr(),
profile_id.get_string_repr(),
),
find_call,
&ACCOUNTS_CACHE,
)
.await
.unwrap();
let delete_call = || async {
db.delete_merchant_connector_account_by_merchant_id_merchant_connector_id(
&merchant_id,
&common_utils::id_type::MerchantConnectorAccountId::wrap(
merchant_connector_id.to_string(),
)
.unwrap(),
)
.await
};
cache::publish_and_redact(
&db,
CacheKind::Accounts(
format!("{}_{}", merchant_id.get_string_repr(), connector_label).into(),
),
delete_call,
)
.await
.unwrap();
assert!(ACCOUNTS_CACHE
.get_val::<domain::MerchantConnectorAccount>(CacheKey {
key: format!("{}_{}", merchant_id.get_string_repr(), connector_label),
prefix: String::default(),
},)
.await
.is_none())
}
#[tokio::test]
#[cfg(feature = "v2")]
async fn test_connector_profile_id_cache() {
let conf = Settings::new().unwrap();
let tx: oneshot::Sender<()> = oneshot::channel().0;
let app_state = Box::pin(routes::AppState::with_storage(
conf,
StorageImpl::PostgresqlTest,
tx,
Box::new(services::MockApiClient),
))
.await;
let state = &Arc::new(app_state)
.get_session_state(
&common_utils::id_type::TenantId::try_from_string("public".to_string()).unwrap(),
None,
|| {},
)
.unwrap();
let db = MockDb::new(
&redis_interface::RedisSettings::default(),
KeyManagerState::new(),
)
.await
.expect("Failed to create Mock store");
let redis_conn = db.get_redis_conn().unwrap();
let master_key = db.get_master_key();
redis_conn
.subscribe("hyperswitch_invalidate")
.await
.unwrap();
let merchant_id =
common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from("test_merchant"))
.unwrap();
let connector_label = "stripe_USA";
let id = common_utils::generate_merchant_connector_account_id_of_default_length();
let profile_id =
common_utils::id_type::ProfileId::try_from(std::borrow::Cow::from("pro_max_ultra"))
.unwrap();
let key_manager_state = &state.into();
db.insert_merchant_key_store(
domain::MerchantKeyStore {
merchant_id: merchant_id.clone(),
key: domain::types::crypto_operation(
key_manager_state,
type_name!(domain::MerchantConnectorAccount),
domain::types::CryptoOperation::EncryptLocally(
services::generate_aes256_key().unwrap().to_vec().into(),
),
Identifier::Merchant(merchant_id.clone()),
master_key,
)
.await
.and_then(|val| val.try_into_operation())
.unwrap(),
created_at: datetime!(2023-02-01 0:00),
},
&master_key.to_vec().into(),
)
.await
.unwrap();
let merchant_key = db
.get_merchant_key_store_by_merchant_id(&merchant_id, &master_key.to_vec().into())
.await
.unwrap();
let mca = domain::MerchantConnectorAccount {
id: id.clone(),
merchant_id: merchant_id.clone(),
connector_name: common_enums::connector_enums::Connector::Stripe,
connector_account_details: domain::types::crypto_operation(
key_manager_state,
type_name!(domain::MerchantConnectorAccount),
domain::types::CryptoOperation::Encrypt(serde_json::Value::default().into()),
Identifier::Merchant(merchant_key.merchant_id.clone()),
merchant_key.key.get_inner().peek(),
)
.await
.and_then(|val| val.try_into_operation())
.unwrap(),
disabled: None,
payment_methods_enabled: None,
connector_type: ConnectorType::FinOperations,
metadata: None,
frm_configs: None,
connector_label: Some(connector_label.to_string()),
created_at: date_time::now(),
modified_at: date_time::now(),
connector_webhook_details: None,
profile_id: profile_id.to_owned(),
applepay_verified_domains: None,
pm_auth_config: None,
status: common_enums::ConnectorStatus::Inactive,
connector_wallets_details: Some(
domain::types::crypto_operation(
key_manager_state,
type_name!(domain::MerchantConnectorAccount),
domain::types::CryptoOperation::Encrypt(serde_json::Value::default().into()),
Identifier::Merchant(merchant_key.merchant_id.clone()),
merchant_key.key.get_inner().peek(),
)
.await
.and_then(|val| val.try_into_operation())
.unwrap(),
),
additional_merchant_data: None,
version: common_types::consts::API_VERSION,
feature_metadata: None,
};
db.insert_merchant_connector_account(mca.clone(), &merchant_key)
.await
.unwrap();
let find_call = || async {
#[cfg(feature = "v1")]
let mca = db
.find_merchant_connector_account_by_profile_id_connector_name(
profile_id,
&mca.connector_name,
&merchant_key,
)
.await
.unwrap();
#[cfg(feature = "v2")]
let mca: domain::MerchantConnectorAccount = { todo!() };
Conversion::convert(mca)
.await
.change_context(errors::StorageError::DecryptionError)
};
let _: storage::MerchantConnectorAccount = cache::get_or_populate_in_memory(
&db,
&format!(
"{}_{}",
merchant_id.clone().get_string_repr(),
profile_id.get_string_repr()
),
find_call,
&ACCOUNTS_CACHE,
)
.await
.unwrap();
let delete_call = || async { db.delete_merchant_connector_account_by_id(&id).await };
cache::publish_and_redact(
&db,
CacheKind::Accounts(
format!("{}_{}", merchant_id.get_string_repr(), connector_label).into(),
),
delete_call,
)
.await
.unwrap();
assert!(ACCOUNTS_CACHE
.get_val::<domain::MerchantConnectorAccount>(CacheKey {
key: format!("{}_{}", merchant_id.get_string_repr(), connector_label),
prefix: String::default(),
},)
.await
.is_none())
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/blocklist_lookup.rs | crates/router/src/db/blocklist_lookup.rs | use error_stack::report;
use router_env::{instrument, tracing};
use storage_impl::MockDb;
use super::Store;
use crate::{
connection,
core::errors::{self, CustomResult},
db::kafka_store::KafkaStore,
types::storage,
};
#[async_trait::async_trait]
pub trait BlocklistLookupInterface {
async fn insert_blocklist_lookup_entry(
&self,
blocklist_lookup_new: storage::BlocklistLookupNew,
) -> CustomResult<storage::BlocklistLookup, errors::StorageError>;
async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint(
&self,
merchant_id: &common_utils::id_type::MerchantId,
fingerprint: &str,
) -> CustomResult<storage::BlocklistLookup, errors::StorageError>;
async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint(
&self,
merchant_id: &common_utils::id_type::MerchantId,
fingerprint: &str,
) -> CustomResult<storage::BlocklistLookup, errors::StorageError>;
}
#[async_trait::async_trait]
impl BlocklistLookupInterface for Store {
#[instrument(skip_all)]
async fn insert_blocklist_lookup_entry(
&self,
blocklist_lookup_entry: storage::BlocklistLookupNew,
) -> CustomResult<storage::BlocklistLookup, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
blocklist_lookup_entry
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint(
&self,
merchant_id: &common_utils::id_type::MerchantId,
fingerprint: &str,
) -> CustomResult<storage::BlocklistLookup, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::BlocklistLookup::find_by_merchant_id_fingerprint(&conn, merchant_id, fingerprint)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint(
&self,
merchant_id: &common_utils::id_type::MerchantId,
fingerprint: &str,
) -> CustomResult<storage::BlocklistLookup, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::BlocklistLookup::delete_by_merchant_id_fingerprint(&conn, merchant_id, fingerprint)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
#[async_trait::async_trait]
impl BlocklistLookupInterface for MockDb {
#[instrument(skip_all)]
async fn insert_blocklist_lookup_entry(
&self,
_blocklist_lookup_entry: storage::BlocklistLookupNew,
) -> CustomResult<storage::BlocklistLookup, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_fingerprint: &str,
) -> CustomResult<storage::BlocklistLookup, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_fingerprint: &str,
) -> CustomResult<storage::BlocklistLookup, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
}
#[async_trait::async_trait]
impl BlocklistLookupInterface for KafkaStore {
#[instrument(skip_all)]
async fn insert_blocklist_lookup_entry(
&self,
blocklist_lookup_entry: storage::BlocklistLookupNew,
) -> CustomResult<storage::BlocklistLookup, errors::StorageError> {
self.diesel_store
.insert_blocklist_lookup_entry(blocklist_lookup_entry)
.await
}
#[instrument(skip_all)]
async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint(
&self,
merchant_id: &common_utils::id_type::MerchantId,
fingerprint: &str,
) -> CustomResult<storage::BlocklistLookup, errors::StorageError> {
self.diesel_store
.find_blocklist_lookup_entry_by_merchant_id_fingerprint(merchant_id, fingerprint)
.await
}
#[instrument(skip_all)]
async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint(
&self,
merchant_id: &common_utils::id_type::MerchantId,
fingerprint: &str,
) -> CustomResult<storage::BlocklistLookup, errors::StorageError> {
self.diesel_store
.delete_blocklist_lookup_entry_by_merchant_id_fingerprint(merchant_id, fingerprint)
.await
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/health_check.rs | crates/router/src/db/health_check.rs | use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl};
use diesel_models::ConfigNew;
use error_stack::ResultExt;
use router_env::{instrument, logger, tracing};
use super::{MockDb, Store};
use crate::{
connection,
core::errors::{self, CustomResult},
types::storage,
};
#[async_trait::async_trait]
pub trait HealthCheckDbInterface {
async fn health_check_db(&self) -> CustomResult<(), errors::HealthCheckDBError>;
}
#[async_trait::async_trait]
impl HealthCheckDbInterface for Store {
#[instrument(skip_all)]
async fn health_check_db(&self) -> CustomResult<(), errors::HealthCheckDBError> {
let conn = connection::pg_connection_write(self)
.await
.change_context(errors::HealthCheckDBError::DBError)?;
conn.transaction_async(|conn| async move {
let query = diesel::select(diesel::dsl::sql::<diesel::sql_types::Integer>("1 + 1"));
let _x: i32 = query.get_result_async(&conn).await.map_err(|err| {
logger::error!(read_err=?err,"Error while reading element in the database");
errors::HealthCheckDBError::DBReadError
})?;
logger::debug!("Database read was successful");
let config = ConfigNew {
key: "test_key".to_string(),
config: "test_value".to_string(),
};
config.insert(&conn).await.map_err(|err| {
logger::error!(write_err=?err,"Error while writing to database");
errors::HealthCheckDBError::DBWriteError
})?;
logger::debug!("Database write was successful");
storage::Config::delete_by_key(&conn, "test_key")
.await
.map_err(|err| {
logger::error!(delete_err=?err,"Error while deleting element in the database");
errors::HealthCheckDBError::DBDeleteError
})?;
logger::debug!("Database delete was successful");
Ok::<_, errors::HealthCheckDBError>(())
})
.await?;
Ok(())
}
}
#[async_trait::async_trait]
impl HealthCheckDbInterface for MockDb {
async fn health_check_db(&self) -> CustomResult<(), errors::HealthCheckDBError> {
Ok(())
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/unified_translations.rs | crates/router/src/db/unified_translations.rs | use diesel_models::unified_translations as storage;
use error_stack::report;
use super::MockDb;
use crate::{
connection,
core::errors::{self, CustomResult},
services::Store,
};
#[async_trait::async_trait]
pub trait UnifiedTranslationsInterface {
async fn add_unfied_translation(
&self,
translation: storage::UnifiedTranslationsNew,
) -> CustomResult<storage::UnifiedTranslations, errors::StorageError>;
async fn update_translation(
&self,
unified_code: String,
unified_message: String,
locale: String,
data: storage::UnifiedTranslationsUpdate,
) -> CustomResult<storage::UnifiedTranslations, errors::StorageError>;
async fn find_translation(
&self,
unified_code: String,
unified_message: String,
locale: String,
) -> CustomResult<String, errors::StorageError>;
async fn delete_translation(
&self,
unified_code: String,
unified_message: String,
locale: String,
) -> CustomResult<bool, errors::StorageError>;
}
#[async_trait::async_trait]
impl UnifiedTranslationsInterface for Store {
async fn add_unfied_translation(
&self,
translation: storage::UnifiedTranslationsNew,
) -> CustomResult<storage::UnifiedTranslations, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
translation
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
async fn update_translation(
&self,
unified_code: String,
unified_message: String,
locale: String,
data: storage::UnifiedTranslationsUpdate,
) -> CustomResult<storage::UnifiedTranslations, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::UnifiedTranslations::update_by_unified_code_unified_message_locale(
&conn,
unified_code,
unified_message,
locale,
data,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
async fn find_translation(
&self,
unified_code: String,
unified_message: String,
locale: String,
) -> CustomResult<String, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
let translations =
storage::UnifiedTranslations::find_by_unified_code_unified_message_locale(
&conn,
unified_code,
unified_message,
locale,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))?;
Ok(translations.translation)
}
async fn delete_translation(
&self,
unified_code: String,
unified_message: String,
locale: String,
) -> CustomResult<bool, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::UnifiedTranslations::delete_by_unified_code_unified_message_locale(
&conn,
unified_code,
unified_message,
locale,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
#[async_trait::async_trait]
impl UnifiedTranslationsInterface for MockDb {
async fn add_unfied_translation(
&self,
_translation: storage::UnifiedTranslationsNew,
) -> CustomResult<storage::UnifiedTranslations, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
async fn find_translation(
&self,
_unified_code: String,
_unified_message: String,
_locale: String,
) -> CustomResult<String, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
async fn update_translation(
&self,
_unified_code: String,
_unified_message: String,
_locale: String,
_data: storage::UnifiedTranslationsUpdate,
) -> CustomResult<storage::UnifiedTranslations, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
async fn delete_translation(
&self,
_unified_code: String,
_unified_message: String,
_locale: String,
) -> CustomResult<bool, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/kafka_store.rs | crates/router/src/db/kafka_store.rs | use std::{collections::HashSet, sync::Arc};
use ::payment_methods::state::PaymentMethodsStorageInterface;
use common_enums::enums::MerchantStorageScheme;
use common_utils::{
errors::CustomResult,
id_type,
types::{keymanager::KeyManagerState, user::ThemeLineage, TenantConfig},
};
#[cfg(feature = "v2")]
use diesel_models::ephemeral_key::{ClientSecretType, ClientSecretTypeNew};
use diesel_models::{
enums::{self, ProcessTrackerStatus},
ephemeral_key::{EphemeralKey, EphemeralKeyNew},
refund as diesel_refund,
reverse_lookup::{ReverseLookup, ReverseLookupNew},
user_role as user_storage,
};
use error_stack::ResultExt;
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::payouts::{
payout_attempt::PayoutAttemptInterface, payouts::PayoutsInterface,
};
use hyperswitch_domain_models::{
cards_info::CardsInfoInterface,
disputes,
invoice::{Invoice as DomainInvoice, InvoiceInterface, InvoiceUpdate as DomainInvoiceUpdate},
payment_methods::PaymentMethodInterface,
payments::{payment_attempt::PaymentAttemptInterface, payment_intent::PaymentIntentInterface},
refunds,
subscription::{
Subscription as DomainSubscription, SubscriptionInterface,
SubscriptionUpdate as DomainSubscriptionUpdate,
},
};
#[cfg(not(feature = "payouts"))]
use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface};
use masking::Secret;
use redis_interface::{errors::RedisError, RedisConnectionPool, RedisEntryId};
use router_env::{instrument, logger, tracing};
use scheduler::{
db::{process_tracker::ProcessTrackerInterface, queue::QueueInterface},
SchedulerInterface,
};
use serde::Serialize;
use storage_impl::redis::kv_store::RedisConnInterface;
use time::PrimitiveDateTime;
use super::{
dashboard_metadata::DashboardMetadataInterface,
ephemeral_key::ClientSecretInterface,
hyperswitch_ai_interaction::HyperswitchAiInteractionInterface,
role::RoleInterface,
user::{sample_data::BatchSampleDataInterface, theme::ThemeInterface, UserInterface},
user_authentication_method::UserAuthenticationMethodInterface,
user_key_store::UserKeyStoreInterface,
user_role::{ListUserRolesByOrgIdPayload, ListUserRolesByUserIdPayload, UserRoleInterface},
};
#[cfg(feature = "payouts")]
use crate::services::kafka::payout::KafkaPayout;
use crate::{
core::errors::{self, ProcessTrackerError},
db::{
self,
address::AddressInterface,
api_keys::ApiKeyInterface,
authentication::AuthenticationInterface,
authorization::AuthorizationInterface,
business_profile::ProfileInterface,
callback_mapper::CallbackMapperInterface,
capture::CaptureInterface,
configs::ConfigInterface,
customers::CustomerInterface,
dispute::DisputeInterface,
ephemeral_key::EphemeralKeyInterface,
events::EventInterface,
file::FileMetadataInterface,
generic_link::GenericLinkInterface,
gsm::GsmInterface,
health_check::HealthCheckDbInterface,
locker_mock_up::LockerMockUpInterface,
mandate::MandateInterface,
merchant_account::MerchantAccountInterface,
merchant_connector_account::{ConnectorAccessToken, MerchantConnectorAccountInterface},
merchant_key_store::MerchantKeyStoreInterface,
payment_link::PaymentLinkInterface,
refund::RefundInterface,
reverse_lookup::ReverseLookupInterface,
routing_algorithm::RoutingAlgorithmInterface,
tokenization::TokenizationInterface,
unified_translations::UnifiedTranslationsInterface,
AccountsStorageInterface, CommonStorageInterface, GlobalStorageInterface,
MasterKeyInterface, StorageInterface,
},
services::{kafka::KafkaProducer, Store},
types::{domain, storage, AccessToken},
};
#[derive(Debug, Clone, Serialize)]
pub struct TenantID(pub String);
#[derive(Clone)]
pub struct KafkaStore {
pub kafka_producer: KafkaProducer,
pub diesel_store: Store,
pub tenant_id: TenantID,
}
impl KafkaStore {
pub async fn new(
store: Store,
mut kafka_producer: KafkaProducer,
tenant_id: TenantID,
tenant_config: &dyn TenantConfig,
) -> Self {
kafka_producer.set_tenancy(tenant_config);
Self {
kafka_producer,
diesel_store: store,
tenant_id,
}
}
}
#[async_trait::async_trait]
impl AddressInterface for KafkaStore {
async fn find_address_by_address_id(
&self,
address_id: &str,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Address, errors::StorageError> {
self.diesel_store
.find_address_by_address_id(address_id, key_store)
.await
}
async fn update_address(
&self,
address_id: String,
address: storage::AddressUpdate,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Address, errors::StorageError> {
self.diesel_store
.update_address(address_id, address, key_store)
.await
}
async fn update_address_for_payments(
&self,
this: domain::PaymentAddress,
address: domain::AddressUpdate,
payment_id: id_type::PaymentId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::PaymentAddress, errors::StorageError> {
self.diesel_store
.update_address_for_payments(this, address, payment_id, key_store, storage_scheme)
.await
}
async fn insert_address_for_payments(
&self,
payment_id: &id_type::PaymentId,
address: domain::PaymentAddress,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::PaymentAddress, errors::StorageError> {
self.diesel_store
.insert_address_for_payments(payment_id, address, key_store, storage_scheme)
.await
}
async fn find_address_by_merchant_id_payment_id_address_id(
&self,
merchant_id: &id_type::MerchantId,
payment_id: &id_type::PaymentId,
address_id: &str,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::PaymentAddress, errors::StorageError> {
self.diesel_store
.find_address_by_merchant_id_payment_id_address_id(
merchant_id,
payment_id,
address_id,
key_store,
storage_scheme,
)
.await
}
async fn insert_address_for_customers(
&self,
address: domain::CustomerAddress,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Address, errors::StorageError> {
self.diesel_store
.insert_address_for_customers(address, key_store)
.await
}
async fn update_address_by_merchant_id_customer_id(
&self,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
address: storage::AddressUpdate,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Address>, errors::StorageError> {
self.diesel_store
.update_address_by_merchant_id_customer_id(customer_id, merchant_id, address, key_store)
.await
}
}
#[async_trait::async_trait]
impl ApiKeyInterface for KafkaStore {
async fn insert_api_key(
&self,
api_key: storage::ApiKeyNew,
) -> CustomResult<storage::ApiKey, errors::StorageError> {
self.diesel_store.insert_api_key(api_key).await
}
async fn update_api_key(
&self,
merchant_id: id_type::MerchantId,
key_id: id_type::ApiKeyId,
api_key: storage::ApiKeyUpdate,
) -> CustomResult<storage::ApiKey, errors::StorageError> {
self.diesel_store
.update_api_key(merchant_id, key_id, api_key)
.await
}
async fn revoke_api_key(
&self,
merchant_id: &id_type::MerchantId,
key_id: &id_type::ApiKeyId,
) -> CustomResult<bool, errors::StorageError> {
self.diesel_store.revoke_api_key(merchant_id, key_id).await
}
async fn find_api_key_by_merchant_id_key_id_optional(
&self,
merchant_id: &id_type::MerchantId,
key_id: &id_type::ApiKeyId,
) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> {
self.diesel_store
.find_api_key_by_merchant_id_key_id_optional(merchant_id, key_id)
.await
}
async fn find_api_key_by_hash_optional(
&self,
hashed_api_key: storage::HashedApiKey,
) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> {
self.diesel_store
.find_api_key_by_hash_optional(hashed_api_key)
.await
}
async fn list_api_keys_by_merchant_id(
&self,
merchant_id: &id_type::MerchantId,
limit: Option<i64>,
offset: Option<i64>,
) -> CustomResult<Vec<storage::ApiKey>, errors::StorageError> {
self.diesel_store
.list_api_keys_by_merchant_id(merchant_id, limit, offset)
.await
}
}
#[async_trait::async_trait]
impl CardsInfoInterface for KafkaStore {
type Error = errors::StorageError;
async fn get_card_info(
&self,
card_iin: &str,
) -> CustomResult<Option<storage::CardInfo>, errors::StorageError> {
self.diesel_store.get_card_info(card_iin).await
}
async fn add_card_info(
&self,
data: storage::CardInfo,
) -> CustomResult<storage::CardInfo, errors::StorageError> {
self.diesel_store.add_card_info(data).await
}
async fn update_card_info(
&self,
card_iin: String,
data: storage::UpdateCardInfo,
) -> CustomResult<storage::CardInfo, errors::StorageError> {
self.diesel_store.update_card_info(card_iin, data).await
}
}
#[async_trait::async_trait]
impl ConfigInterface for KafkaStore {
type Error = errors::StorageError;
async fn insert_config(
&self,
config: storage::ConfigNew,
) -> CustomResult<storage::Config, errors::StorageError> {
self.diesel_store.insert_config(config).await
}
async fn find_config_by_key(
&self,
key: &str,
) -> CustomResult<storage::Config, errors::StorageError> {
self.diesel_store.find_config_by_key(key).await
}
async fn find_config_by_key_from_db(
&self,
key: &str,
) -> CustomResult<storage::Config, errors::StorageError> {
self.diesel_store.find_config_by_key_from_db(key).await
}
async fn update_config_in_database(
&self,
key: &str,
config_update: storage::ConfigUpdate,
) -> CustomResult<storage::Config, errors::StorageError> {
self.diesel_store
.update_config_in_database(key, config_update)
.await
}
async fn update_config_by_key(
&self,
key: &str,
config_update: storage::ConfigUpdate,
) -> CustomResult<storage::Config, errors::StorageError> {
self.diesel_store
.update_config_by_key(key, config_update)
.await
}
async fn delete_config_by_key(
&self,
key: &str,
) -> CustomResult<storage::Config, errors::StorageError> {
self.diesel_store.delete_config_by_key(key).await
}
async fn find_config_by_key_unwrap_or(
&self,
key: &str,
default_config: Option<String>,
) -> CustomResult<storage::Config, errors::StorageError> {
self.diesel_store
.find_config_by_key_unwrap_or(key, default_config)
.await
}
}
#[async_trait::async_trait]
impl CustomerInterface for KafkaStore {
type Error = errors::StorageError;
#[cfg(feature = "v1")]
async fn delete_customer_by_customer_id_merchant_id(
&self,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> CustomResult<bool, errors::StorageError> {
self.diesel_store
.delete_customer_by_customer_id_merchant_id(customer_id, merchant_id)
.await
}
#[cfg(feature = "v1")]
async fn find_customer_optional_by_customer_id_merchant_id(
&self,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Option<domain::Customer>, errors::StorageError> {
self.diesel_store
.find_customer_optional_by_customer_id_merchant_id(
customer_id,
merchant_id,
key_store,
storage_scheme,
)
.await
}
#[cfg(feature = "v1")]
async fn find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id(
&self,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Option<domain::Customer>, errors::StorageError> {
self.diesel_store
.find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id(
customer_id,
merchant_id,
key_store,
storage_scheme,
)
.await
}
#[cfg(feature = "v2")]
async fn find_optional_by_merchant_id_merchant_reference_id(
&self,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Option<domain::Customer>, errors::StorageError> {
self.diesel_store
.find_optional_by_merchant_id_merchant_reference_id(
customer_id,
merchant_id,
key_store,
storage_scheme,
)
.await
}
#[cfg(feature = "v1")]
async fn update_customer_by_customer_id_merchant_id(
&self,
customer_id: id_type::CustomerId,
merchant_id: id_type::MerchantId,
customer: domain::Customer,
customer_update: storage::CustomerUpdate,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, errors::StorageError> {
self.diesel_store
.update_customer_by_customer_id_merchant_id(
customer_id,
merchant_id,
customer,
customer_update,
key_store,
storage_scheme,
)
.await
}
#[cfg(feature = "v2")]
async fn update_customer_by_global_id(
&self,
id: &id_type::GlobalCustomerId,
customer: domain::Customer,
customer_update: storage::CustomerUpdate,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, errors::StorageError> {
self.diesel_store
.update_customer_by_global_id(id, customer, customer_update, key_store, storage_scheme)
.await
}
async fn list_customers_by_merchant_id(
&self,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
constraints: super::customers::CustomerListConstraints,
) -> CustomResult<Vec<domain::Customer>, errors::StorageError> {
self.diesel_store
.list_customers_by_merchant_id(merchant_id, key_store, constraints)
.await
}
async fn list_customers_by_merchant_id_with_count(
&self,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
constraints: super::customers::CustomerListConstraints,
) -> CustomResult<(Vec<domain::Customer>, usize), errors::StorageError> {
self.diesel_store
.list_customers_by_merchant_id_with_count(merchant_id, key_store, constraints)
.await
}
#[cfg(feature = "v1")]
async fn find_customer_by_customer_id_merchant_id(
&self,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, errors::StorageError> {
self.diesel_store
.find_customer_by_customer_id_merchant_id(
customer_id,
merchant_id,
key_store,
storage_scheme,
)
.await
}
#[cfg(feature = "v2")]
async fn find_customer_by_merchant_reference_id_merchant_id(
&self,
merchant_reference_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, errors::StorageError> {
self.diesel_store
.find_customer_by_merchant_reference_id_merchant_id(
merchant_reference_id,
merchant_id,
key_store,
storage_scheme,
)
.await
}
#[cfg(feature = "v2")]
async fn find_customer_by_global_id(
&self,
id: &id_type::GlobalCustomerId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, errors::StorageError> {
self.diesel_store
.find_customer_by_global_id(id, key_store, storage_scheme)
.await
}
async fn insert_customer(
&self,
customer_data: domain::Customer,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, errors::StorageError> {
self.diesel_store
.insert_customer(customer_data, key_store, storage_scheme)
.await
}
}
#[async_trait::async_trait]
impl DisputeInterface for KafkaStore {
async fn insert_dispute(
&self,
dispute_new: storage::DisputeNew,
) -> CustomResult<storage::Dispute, errors::StorageError> {
let dispute = self.diesel_store.insert_dispute(dispute_new).await?;
if let Err(er) = self
.kafka_producer
.log_dispute(&dispute, None, self.tenant_id.clone())
.await
{
logger::error!(message="Failed to add analytics entry for Dispute {dispute:?}", error_message=?er);
};
Ok(dispute)
}
async fn find_by_merchant_id_payment_id_connector_dispute_id(
&self,
merchant_id: &id_type::MerchantId,
payment_id: &id_type::PaymentId,
connector_dispute_id: &str,
) -> CustomResult<Option<storage::Dispute>, errors::StorageError> {
self.diesel_store
.find_by_merchant_id_payment_id_connector_dispute_id(
merchant_id,
payment_id,
connector_dispute_id,
)
.await
}
async fn find_dispute_by_merchant_id_dispute_id(
&self,
merchant_id: &id_type::MerchantId,
dispute_id: &str,
) -> CustomResult<storage::Dispute, errors::StorageError> {
self.diesel_store
.find_dispute_by_merchant_id_dispute_id(merchant_id, dispute_id)
.await
}
async fn find_disputes_by_constraints(
&self,
merchant_id: &id_type::MerchantId,
dispute_constraints: &disputes::DisputeListConstraints,
) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> {
self.diesel_store
.find_disputes_by_constraints(merchant_id, dispute_constraints)
.await
}
async fn update_dispute(
&self,
this: storage::Dispute,
dispute: storage::DisputeUpdate,
) -> CustomResult<storage::Dispute, errors::StorageError> {
let dispute_new = self
.diesel_store
.update_dispute(this.clone(), dispute)
.await?;
if let Err(er) = self
.kafka_producer
.log_dispute(&dispute_new, Some(this), self.tenant_id.clone())
.await
{
logger::error!(message="Failed to add analytics entry for Dispute {dispute_new:?}", error_message=?er);
};
Ok(dispute_new)
}
async fn find_disputes_by_merchant_id_payment_id(
&self,
merchant_id: &id_type::MerchantId,
payment_id: &id_type::PaymentId,
) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> {
self.diesel_store
.find_disputes_by_merchant_id_payment_id(merchant_id, payment_id)
.await
}
async fn get_dispute_status_with_count(
&self,
merchant_id: &id_type::MerchantId,
profile_id_list: Option<Vec<id_type::ProfileId>>,
time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::StorageError> {
self.diesel_store
.get_dispute_status_with_count(merchant_id, profile_id_list, time_range)
.await
}
}
#[async_trait::async_trait]
impl EphemeralKeyInterface for KafkaStore {
#[cfg(feature = "v1")]
async fn create_ephemeral_key(
&self,
ek: EphemeralKeyNew,
validity: i64,
) -> CustomResult<EphemeralKey, errors::StorageError> {
self.diesel_store.create_ephemeral_key(ek, validity).await
}
#[cfg(feature = "v1")]
async fn get_ephemeral_key(
&self,
key: &str,
) -> CustomResult<EphemeralKey, errors::StorageError> {
self.diesel_store.get_ephemeral_key(key).await
}
#[cfg(feature = "v1")]
async fn delete_ephemeral_key(
&self,
id: &str,
) -> CustomResult<EphemeralKey, errors::StorageError> {
self.diesel_store.delete_ephemeral_key(id).await
}
}
#[async_trait::async_trait]
impl ClientSecretInterface for KafkaStore {
#[cfg(feature = "v2")]
async fn create_client_secret(
&self,
ek: ClientSecretTypeNew,
validity: i64,
) -> CustomResult<ClientSecretType, errors::StorageError> {
self.diesel_store.create_client_secret(ek, validity).await
}
#[cfg(feature = "v2")]
async fn get_client_secret(
&self,
key: &str,
) -> CustomResult<ClientSecretType, errors::StorageError> {
self.diesel_store.get_client_secret(key).await
}
#[cfg(feature = "v2")]
async fn delete_client_secret(
&self,
id: &str,
) -> CustomResult<ClientSecretType, errors::StorageError> {
self.diesel_store.delete_client_secret(id).await
}
}
#[async_trait::async_trait]
impl EventInterface for KafkaStore {
async fn insert_event(
&self,
event: domain::Event,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError> {
self.diesel_store
.insert_event(event, merchant_key_store)
.await
}
async fn find_event_by_merchant_id_event_id(
&self,
merchant_id: &id_type::MerchantId,
event_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError> {
self.diesel_store
.find_event_by_merchant_id_event_id(merchant_id, event_id, merchant_key_store)
.await
}
async fn find_event_by_merchant_id_idempotent_event_id(
&self,
merchant_id: &id_type::MerchantId,
idempotent_event_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError> {
self.diesel_store
.find_event_by_merchant_id_idempotent_event_id(
merchant_id,
idempotent_event_id,
merchant_key_store,
)
.await
}
async fn list_initial_events_by_merchant_id_constraints(
&self,
merchant_id: &id_type::MerchantId,
created_after: PrimitiveDateTime,
created_before: PrimitiveDateTime,
limit: Option<i64>,
offset: Option<i64>,
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
self.diesel_store
.list_initial_events_by_merchant_id_constraints(
merchant_id,
created_after,
created_before,
limit,
offset,
event_types,
is_delivered,
merchant_key_store,
)
.await
}
async fn list_events_by_merchant_id_initial_attempt_id(
&self,
merchant_id: &id_type::MerchantId,
initial_attempt_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
self.diesel_store
.list_events_by_merchant_id_initial_attempt_id(
merchant_id,
initial_attempt_id,
merchant_key_store,
)
.await
}
async fn list_initial_events_by_merchant_id_primary_object_id(
&self,
merchant_id: &id_type::MerchantId,
primary_object_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
self.diesel_store
.list_initial_events_by_merchant_id_primary_object_id(
merchant_id,
primary_object_id,
merchant_key_store,
)
.await
}
async fn find_initial_event_by_merchant_id_initial_attempt_id(
&self,
merchant_id: &id_type::MerchantId,
initial_attempt_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Option<domain::Event>, errors::StorageError> {
self.diesel_store
.find_initial_event_by_merchant_id_initial_attempt_id(
merchant_id,
initial_attempt_id,
merchant_key_store,
)
.await
}
async fn list_initial_events_by_profile_id_constraints(
&self,
profile_id: &id_type::ProfileId,
created_after: PrimitiveDateTime,
created_before: PrimitiveDateTime,
limit: Option<i64>,
offset: Option<i64>,
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
self.diesel_store
.list_initial_events_by_profile_id_constraints(
profile_id,
created_after,
created_before,
limit,
offset,
event_types,
is_delivered,
merchant_key_store,
)
.await
}
async fn list_initial_events_by_profile_id_primary_object_id(
&self,
profile_id: &id_type::ProfileId,
primary_object_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
self.diesel_store
.list_initial_events_by_profile_id_primary_object_id(
profile_id,
primary_object_id,
merchant_key_store,
)
.await
}
async fn find_initial_event_by_profile_id_initial_attempt_id(
&self,
profile_id: &id_type::ProfileId,
initial_attempt_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Option<domain::Event>, errors::StorageError> {
self.diesel_store
.find_initial_event_by_profile_id_initial_attempt_id(
profile_id,
initial_attempt_id,
merchant_key_store,
)
.await
}
async fn update_event_by_merchant_id_event_id(
&self,
merchant_id: &id_type::MerchantId,
event_id: &str,
event: domain::EventUpdate,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError> {
self.diesel_store
.update_event_by_merchant_id_event_id(merchant_id, event_id, event, merchant_key_store)
.await
}
async fn count_initial_events_by_constraints(
&self,
merchant_id: &id_type::MerchantId,
profile_id: Option<id_type::ProfileId>,
created_after: PrimitiveDateTime,
created_before: PrimitiveDateTime,
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
) -> CustomResult<i64, errors::StorageError> {
self.diesel_store
.count_initial_events_by_constraints(
merchant_id,
profile_id,
created_after,
created_before,
event_types,
is_delivered,
)
.await
}
}
#[async_trait::async_trait]
impl LockerMockUpInterface for KafkaStore {
async fn find_locker_by_card_id(
&self,
card_id: &str,
) -> CustomResult<storage::LockerMockUp, errors::StorageError> {
self.diesel_store.find_locker_by_card_id(card_id).await
}
async fn insert_locker_mock_up(
&self,
new: storage::LockerMockUpNew,
) -> CustomResult<storage::LockerMockUp, errors::StorageError> {
self.diesel_store.insert_locker_mock_up(new).await
}
async fn delete_locker_mock_up(
&self,
card_id: &str,
) -> CustomResult<storage::LockerMockUp, errors::StorageError> {
self.diesel_store.delete_locker_mock_up(card_id).await
}
}
#[async_trait::async_trait]
impl MandateInterface for KafkaStore {
async fn find_mandate_by_merchant_id_mandate_id(
&self,
merchant_id: &id_type::MerchantId,
mandate_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::Mandate, errors::StorageError> {
self.diesel_store
.find_mandate_by_merchant_id_mandate_id(merchant_id, mandate_id, storage_scheme)
.await
}
async fn find_mandate_by_merchant_id_connector_mandate_id(
&self,
merchant_id: &id_type::MerchantId,
connector_mandate_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::Mandate, errors::StorageError> {
self.diesel_store
.find_mandate_by_merchant_id_connector_mandate_id(
merchant_id,
connector_mandate_id,
storage_scheme,
)
.await
}
#[cfg(feature = "v2")]
async fn find_mandate_by_global_customer_id(
&self,
id: &id_type::GlobalCustomerId,
) -> CustomResult<Vec<storage::Mandate>, errors::StorageError> {
self.diesel_store
.find_mandate_by_global_customer_id(id)
.await
}
async fn find_mandate_by_merchant_id_customer_id(
&self,
merchant_id: &id_type::MerchantId,
customer_id: &id_type::CustomerId,
) -> CustomResult<Vec<storage::Mandate>, errors::StorageError> {
self.diesel_store
.find_mandate_by_merchant_id_customer_id(merchant_id, customer_id)
.await
}
async fn update_mandate_by_merchant_id_mandate_id(
&self,
merchant_id: &id_type::MerchantId,
mandate_id: &str,
mandate_update: storage::MandateUpdate,
mandate: storage::Mandate,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::Mandate, errors::StorageError> {
self.diesel_store
.update_mandate_by_merchant_id_mandate_id(
merchant_id,
mandate_id,
mandate_update,
mandate,
storage_scheme,
)
.await
}
async fn find_mandates_by_merchant_id(
&self,
merchant_id: &id_type::MerchantId,
mandate_constraints: api_models::mandates::MandateListConstraints,
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/payment_method_session.rs | crates/router/src/db/payment_method_session.rs | #[cfg(feature = "v2")]
use crate::core::errors::{self, CustomResult};
use crate::db::MockDb;
#[cfg(feature = "v2")]
#[async_trait::async_trait]
pub trait PaymentMethodsSessionInterface {
async fn insert_payment_methods_session(
&self,
key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
payment_methods_session: hyperswitch_domain_models::payment_methods::PaymentMethodSession,
validity: i64,
) -> CustomResult<(), errors::StorageError>;
async fn update_payment_method_session(
&self,
key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
id: &common_utils::id_type::GlobalPaymentMethodSessionId,
payment_methods_session: hyperswitch_domain_models::payment_methods::PaymentMethodsSessionUpdateEnum,
current_session: hyperswitch_domain_models::payment_methods::PaymentMethodSession,
) -> CustomResult<
hyperswitch_domain_models::payment_methods::PaymentMethodSession,
errors::StorageError,
>;
async fn get_payment_methods_session(
&self,
key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
id: &common_utils::id_type::GlobalPaymentMethodSessionId,
) -> CustomResult<
hyperswitch_domain_models::payment_methods::PaymentMethodSession,
errors::StorageError,
>;
}
#[cfg(feature = "v1")]
pub trait PaymentMethodsSessionInterface {}
#[cfg(feature = "v1")]
impl PaymentMethodsSessionInterface for crate::services::Store {}
#[cfg(feature = "v2")]
mod storage {
use error_stack::ResultExt;
use hyperswitch_domain_models::behaviour::{Conversion, ReverseConversion};
use router_env::{instrument, tracing};
use storage_impl::redis::kv_store::RedisConnInterface;
use super::PaymentMethodsSessionInterface;
use crate::{
core::errors::{self, CustomResult},
services::Store,
};
#[async_trait::async_trait]
impl PaymentMethodsSessionInterface for Store {
#[instrument(skip_all)]
async fn insert_payment_methods_session(
&self,
_key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
payment_methods_session: hyperswitch_domain_models::payment_methods::PaymentMethodSession,
validity_in_seconds: i64,
) -> CustomResult<(), errors::StorageError> {
let redis_key = payment_methods_session.id.get_redis_key();
let db_model = payment_methods_session
.construct_new()
.await
.change_context(errors::StorageError::EncryptionError)?;
let redis_connection = self
.get_redis_conn()
.map_err(Into::<errors::StorageError>::into)?;
redis_connection
.serialize_and_set_key_with_expiry(&redis_key.into(), db_model, validity_in_seconds)
.await
.change_context(errors::StorageError::KVError)
.attach_printable("Failed to insert payment methods session to redis")
}
#[instrument(skip_all)]
async fn get_payment_methods_session(
&self,
key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
id: &common_utils::id_type::GlobalPaymentMethodSessionId,
) -> CustomResult<
hyperswitch_domain_models::payment_methods::PaymentMethodSession,
errors::StorageError,
> {
let redis_key = id.get_redis_key();
let redis_connection = self
.get_redis_conn()
.map_err(Into::<errors::StorageError>::into)?;
let db_model = redis_connection
.get_and_deserialize_key::<diesel_models::payment_methods_session::PaymentMethodSession>(&redis_key.into(), "PaymentMethodSession")
.await
.change_context(errors::StorageError::KVError)?;
let key_manager_identifier = common_utils::types::keymanager::Identifier::Merchant(
key_store.merchant_id.clone(),
);
db_model
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
&key_store.key,
key_manager_identifier,
)
.await
.change_context(errors::StorageError::DecryptionError)
.attach_printable("Failed to decrypt payment methods session")
}
#[instrument(skip_all)]
async fn update_payment_method_session(
&self,
key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
session_id: &common_utils::id_type::GlobalPaymentMethodSessionId,
update_request: hyperswitch_domain_models::payment_methods::PaymentMethodsSessionUpdateEnum,
current_session: hyperswitch_domain_models::payment_methods::PaymentMethodSession,
) -> CustomResult<
hyperswitch_domain_models::payment_methods::PaymentMethodSession,
errors::StorageError,
> {
let redis_key = session_id.get_redis_key();
let internal_obj = hyperswitch_domain_models::payment_methods::PaymentMethodsSessionUpdateInternal::from(update_request);
let update_state = current_session.apply_changeset(internal_obj);
let db_model = update_state
.construct_new()
.await
.change_context(errors::StorageError::EncryptionError)?;
let redis_connection = self
.get_redis_conn()
.map_err(Into::<errors::StorageError>::into)?;
redis_connection
.serialize_and_set_key_without_modifying_ttl(&redis_key.into(), db_model.clone())
.await
.change_context(errors::StorageError::KVError)
.attach_printable("Failed to insert payment methods session to redis");
let key_manager_identifier = common_utils::types::keymanager::Identifier::Merchant(
key_store.merchant_id.clone(),
);
db_model
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
&key_store.key,
key_manager_identifier,
)
.await
.change_context(errors::StorageError::DecryptionError)
.attach_printable("Failed to decrypt payment methods session")
}
}
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl PaymentMethodsSessionInterface for MockDb {
async fn insert_payment_methods_session(
&self,
key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
payment_methods_session: hyperswitch_domain_models::payment_methods::PaymentMethodSession,
validity_in_seconds: i64,
) -> CustomResult<(), errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
async fn update_payment_method_session(
&self,
key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
id: &common_utils::id_type::GlobalPaymentMethodSessionId,
payment_methods_session: hyperswitch_domain_models::payment_methods::PaymentMethodsSessionUpdateEnum,
current_session: hyperswitch_domain_models::payment_methods::PaymentMethodSession,
) -> CustomResult<
hyperswitch_domain_models::payment_methods::PaymentMethodSession,
errors::StorageError,
> {
Err(errors::StorageError::MockDbError)?
}
#[cfg(feature = "v2")]
async fn get_payment_methods_session(
&self,
key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
id: &common_utils::id_type::GlobalPaymentMethodSessionId,
) -> CustomResult<
hyperswitch_domain_models::payment_methods::PaymentMethodSession,
errors::StorageError,
> {
Err(errors::StorageError::MockDbError)?
}
}
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl PaymentMethodsSessionInterface for MockDb {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/gsm.rs | crates/router/src/db/gsm.rs | use diesel_models::gsm as storage;
use error_stack::{report, ResultExt};
use router_env::{instrument, tracing};
use super::MockDb;
use crate::{
connection,
core::errors::{self, CustomResult},
services::Store,
};
#[async_trait::async_trait]
pub trait GsmInterface {
async fn add_gsm_rule(
&self,
rule: hyperswitch_domain_models::gsm::GatewayStatusMap,
) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError>;
async fn find_gsm_decision(
&self,
connector: String,
flow: String,
sub_flow: String,
code: String,
message: String,
) -> CustomResult<String, errors::StorageError>;
async fn find_gsm_rule(
&self,
connector: String,
flow: String,
sub_flow: String,
code: String,
message: String,
) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError>;
async fn update_gsm_rule(
&self,
connector: String,
flow: String,
sub_flow: String,
code: String,
message: String,
data: hyperswitch_domain_models::gsm::GatewayStatusMappingUpdate,
) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError>;
async fn delete_gsm_rule(
&self,
connector: String,
flow: String,
sub_flow: String,
code: String,
message: String,
) -> CustomResult<bool, errors::StorageError>;
}
#[async_trait::async_trait]
impl GsmInterface for Store {
#[instrument(skip_all)]
async fn add_gsm_rule(
&self,
rule: hyperswitch_domain_models::gsm::GatewayStatusMap,
) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
let gsm_db_record = diesel_models::gsm::GatewayStatusMappingNew::try_from(rule)
.change_context(errors::StorageError::SerializationFailed)
.attach_printable("Failed to convert gsm domain models to diesel models")?
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))?;
hyperswitch_domain_models::gsm::GatewayStatusMap::try_from(gsm_db_record)
.change_context(errors::StorageError::DeserializationFailed)
.attach_printable("Failed to convert gsm diesel models to domain models")
}
#[instrument(skip_all)]
async fn find_gsm_decision(
&self,
connector: String,
flow: String,
sub_flow: String,
code: String,
message: String,
) -> CustomResult<String, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::GatewayStatusMap::retrieve_decision(
&conn, connector, flow, sub_flow, code, message,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_gsm_rule(
&self,
connector: String,
flow: String,
sub_flow: String,
code: String,
message: String,
) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
let gsm_db_record =
storage::GatewayStatusMap::find(&conn, connector, flow, sub_flow, code, message)
.await
.map_err(|error| report!(errors::StorageError::from(error)))?;
hyperswitch_domain_models::gsm::GatewayStatusMap::try_from(gsm_db_record)
.change_context(errors::StorageError::DeserializationFailed)
.attach_printable("Failed to convert gsm diesel models to domain models")
}
#[instrument(skip_all)]
async fn update_gsm_rule(
&self,
connector: String,
flow: String,
sub_flow: String,
code: String,
message: String,
data: hyperswitch_domain_models::gsm::GatewayStatusMappingUpdate,
) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
let gsm_update_data = diesel_models::gsm::GatewayStatusMappingUpdate::try_from(data)
.change_context(errors::StorageError::SerializationFailed)?;
let gsm_db_record = storage::GatewayStatusMap::update(
&conn,
connector,
flow,
sub_flow,
code,
message,
gsm_update_data,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))?;
hyperswitch_domain_models::gsm::GatewayStatusMap::try_from(gsm_db_record)
.change_context(errors::StorageError::DeserializationFailed)
.attach_printable("Failed to convert gsm diesel models to domain models")
}
#[instrument(skip_all)]
async fn delete_gsm_rule(
&self,
connector: String,
flow: String,
sub_flow: String,
code: String,
message: String,
) -> CustomResult<bool, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::GatewayStatusMap::delete(&conn, connector, flow, sub_flow, code, message)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
#[async_trait::async_trait]
impl GsmInterface for MockDb {
async fn add_gsm_rule(
&self,
_rule: hyperswitch_domain_models::gsm::GatewayStatusMap,
) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
async fn find_gsm_decision(
&self,
_connector: String,
_flow: String,
_sub_flow: String,
_code: String,
_message: String,
) -> CustomResult<String, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
async fn find_gsm_rule(
&self,
_connector: String,
_flow: String,
_sub_flow: String,
_code: String,
_message: String,
) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
async fn update_gsm_rule(
&self,
_connector: String,
_flow: String,
_sub_flow: String,
_code: String,
_message: String,
_data: hyperswitch_domain_models::gsm::GatewayStatusMappingUpdate,
) -> CustomResult<hyperswitch_domain_models::gsm::GatewayStatusMap, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
async fn delete_gsm_rule(
&self,
_connector: String,
_flow: String,
_sub_flow: String,
_code: String,
_message: String,
) -> CustomResult<bool, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/authentication.rs | crates/router/src/db/authentication.rs | use common_utils::{ext_traits::AsyncExt, types::keymanager::KeyManagerState};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
behaviour::{Conversion, ReverseConversion},
merchant_key_store::MerchantKeyStore,
};
use router_env::{instrument, tracing};
use storage_impl::StorageError;
use super::{MockDb, Store};
use crate::{connection, core::errors::CustomResult, types::storage};
#[async_trait::async_trait]
pub trait AuthenticationInterface {
async fn insert_authentication(
&self,
state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
authentication: hyperswitch_domain_models::authentication::Authentication,
) -> CustomResult<hyperswitch_domain_models::authentication::Authentication, StorageError>;
async fn find_authentication_by_merchant_id_authentication_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
authentication_id: &common_utils::id_type::AuthenticationId,
merchant_key_store: &MerchantKeyStore,
state: &KeyManagerState,
) -> CustomResult<hyperswitch_domain_models::authentication::Authentication, StorageError>;
async fn find_authentication_by_merchant_id_connector_authentication_id(
&self,
merchant_id: common_utils::id_type::MerchantId,
connector_authentication_id: String,
merchant_key_store: &MerchantKeyStore,
state: &KeyManagerState,
) -> CustomResult<hyperswitch_domain_models::authentication::Authentication, StorageError>;
async fn update_authentication_by_merchant_id_authentication_id(
&self,
previous_state: hyperswitch_domain_models::authentication::Authentication,
authentication_update: hyperswitch_domain_models::authentication::AuthenticationUpdate,
merchant_key_store: &MerchantKeyStore,
state: &KeyManagerState,
) -> CustomResult<hyperswitch_domain_models::authentication::Authentication, StorageError>;
}
#[async_trait::async_trait]
impl AuthenticationInterface for Store {
#[instrument(skip_all)]
async fn insert_authentication(
&self,
state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
authentication: hyperswitch_domain_models::authentication::Authentication,
) -> CustomResult<hyperswitch_domain_models::authentication::Authentication, StorageError> {
let conn = connection::pg_connection_write(self).await?;
authentication
.construct_new()
.await
.change_context(StorageError::EncryptionError)?
.insert(&conn)
.await
.map_err(|error| report!(StorageError::from(error)))?
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
}
#[instrument(skip_all)]
async fn find_authentication_by_merchant_id_authentication_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
authentication_id: &common_utils::id_type::AuthenticationId,
merchant_key_store: &MerchantKeyStore,
state: &KeyManagerState,
) -> CustomResult<hyperswitch_domain_models::authentication::Authentication, StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Authentication::find_by_merchant_id_authentication_id(
&conn,
merchant_id,
authentication_id,
)
.await
.map_err(|error| report!(StorageError::from(error)))
.async_and_then(|authn| async {
authn
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
})
.await
}
#[instrument(skip_all)]
async fn find_authentication_by_merchant_id_connector_authentication_id(
&self,
merchant_id: common_utils::id_type::MerchantId,
connector_authentication_id: String,
merchant_key_store: &MerchantKeyStore,
state: &KeyManagerState,
) -> CustomResult<hyperswitch_domain_models::authentication::Authentication, StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Authentication::find_authentication_by_merchant_id_connector_authentication_id(
&conn,
&merchant_id,
&connector_authentication_id,
)
.await
.map_err(|error| report!(StorageError::from(error)))
.async_and_then(|authn| async {
authn
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
})
.await
}
#[instrument(skip_all)]
async fn update_authentication_by_merchant_id_authentication_id(
&self,
previous_state: hyperswitch_domain_models::authentication::Authentication,
authentication_update: hyperswitch_domain_models::authentication::AuthenticationUpdate,
merchant_key_store: &MerchantKeyStore,
state: &KeyManagerState,
) -> CustomResult<hyperswitch_domain_models::authentication::Authentication, StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::Authentication::update_by_merchant_id_authentication_id(
&conn,
previous_state.merchant_id,
previous_state.authentication_id,
authentication_update.into(),
)
.await
.map_err(|error| report!(StorageError::from(error)))
.async_and_then(|authn| async {
authn
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
})
.await
}
}
#[async_trait::async_trait]
impl AuthenticationInterface for MockDb {
async fn insert_authentication(
&self,
state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
authentication: hyperswitch_domain_models::authentication::Authentication,
) -> CustomResult<hyperswitch_domain_models::authentication::Authentication, StorageError> {
let mut authentications = self.authentications.lock().await;
if authentications.iter().any(|authentication_inner| {
authentication_inner.authentication_id == authentication.authentication_id
}) {
Err(StorageError::DuplicateValue {
entity: "authentication_id",
key: Some(
authentication
.authentication_id
.get_string_repr()
.to_string(),
),
})?
}
let authentication_new = storage::Authentication {
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
authentication_id: authentication.authentication_id,
merchant_id: authentication.merchant_id,
authentication_status: authentication.authentication_status,
authentication_connector: authentication.authentication_connector,
connector_authentication_id: authentication.connector_authentication_id,
authentication_data: None,
payment_method_id: authentication.payment_method_id,
authentication_type: authentication.authentication_type,
authentication_lifecycle_status: authentication.authentication_lifecycle_status,
error_code: authentication.error_code,
error_message: authentication.error_message,
connector_metadata: authentication.connector_metadata,
maximum_supported_version: authentication.maximum_supported_version,
threeds_server_transaction_id: authentication.threeds_server_transaction_id,
cavv: authentication.cavv,
authentication_flow_type: authentication.authentication_flow_type,
message_version: authentication.message_version,
eci: authentication.eci,
trans_status: authentication.trans_status,
acquirer_bin: authentication.acquirer_bin,
acquirer_merchant_id: authentication.acquirer_merchant_id,
three_ds_method_data: authentication.three_ds_method_data,
three_ds_method_url: authentication.three_ds_method_url,
acs_url: authentication.acs_url,
challenge_request: authentication.challenge_request,
challenge_request_key: authentication.challenge_request_key,
acs_reference_number: authentication.acs_reference_number,
acs_trans_id: authentication.acs_trans_id,
acs_signed_content: authentication.acs_signed_content,
profile_id: authentication.profile_id,
payment_id: authentication.payment_id,
merchant_connector_id: authentication.merchant_connector_id,
ds_trans_id: authentication.ds_trans_id,
directory_server_id: authentication.directory_server_id,
acquirer_country_code: authentication.acquirer_country_code,
service_details: authentication.service_details,
organization_id: authentication.organization_id,
authentication_client_secret: authentication.authentication_client_secret,
force_3ds_challenge: authentication.force_3ds_challenge,
psd2_sca_exemption_type: authentication.psd2_sca_exemption_type,
return_url: authentication.return_url,
amount: authentication.amount,
currency: authentication.currency,
billing_address: None,
shipping_address: None,
browser_info: authentication.browser_info,
email: None,
profile_acquirer_id: authentication.profile_acquirer_id,
challenge_code: authentication.challenge_code,
challenge_cancel: authentication.challenge_cancel,
challenge_code_reason: authentication.challenge_code_reason,
message_extension: authentication.message_extension,
customer_details: authentication.customer_details,
earliest_supported_version: authentication.earliest_supported_version,
latest_supported_version: authentication.latest_supported_version,
mcc: authentication.mcc,
platform: authentication.platform.map(|platform| platform.to_string()),
device_type: authentication.device_type,
device_brand: authentication.device_brand,
device_os: authentication.device_os,
device_display: authentication.device_display,
browser_name: authentication.browser_name,
browser_version: authentication.browser_version,
scheme_name: authentication.scheme_name,
exemption_requested: authentication.exemption_requested,
exemption_accepted: authentication.exemption_accepted,
issuer_id: authentication.issuer_id,
issuer_country: authentication.issuer_country,
merchant_country_code: authentication.merchant_country_code,
billing_country: authentication.billing_country,
shipping_country: authentication.shipping_country,
};
let authentication: hyperswitch_domain_models::authentication::Authentication =
authentication_new
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::EncryptionError)?;
authentications.push(authentication.clone());
Ok(authentication)
}
async fn find_authentication_by_merchant_id_authentication_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
authentication_id: &common_utils::id_type::AuthenticationId,
_merchant_key_store: &MerchantKeyStore,
_state: &KeyManagerState,
) -> CustomResult<hyperswitch_domain_models::authentication::Authentication, StorageError> {
let authentications = self.authentications.lock().await;
authentications
.iter()
.find(|auth| {
auth.merchant_id == *merchant_id && auth.authentication_id == *authentication_id
})
.cloned()
.ok_or(
StorageError::ValueNotFound(format!(
"Authentication not found for merchant_id: {} and authentication_id: {}",
merchant_id.get_string_repr(),
authentication_id.get_string_repr()
))
.into(),
)
}
async fn find_authentication_by_merchant_id_connector_authentication_id(
&self,
merchant_id: common_utils::id_type::MerchantId,
connector_authentication_id: String,
_merchant_key_store: &MerchantKeyStore,
_state: &KeyManagerState,
) -> CustomResult<hyperswitch_domain_models::authentication::Authentication, StorageError> {
let authentications = self.authentications.lock().await;
authentications
.iter()
.find(|auth| {
auth.merchant_id == merchant_id
&& auth.connector_authentication_id.as_ref()
== Some(&connector_authentication_id)
})
.cloned()
.ok_or(
StorageError::ValueNotFound(format!(
"Authentication not found for merchant_id: {} and connector_authentication_id: {}",
merchant_id.get_string_repr(),
connector_authentication_id
))
.into(),
)
}
async fn update_authentication_by_merchant_id_authentication_id(
&self,
previous_state: hyperswitch_domain_models::authentication::Authentication,
authentication_update: hyperswitch_domain_models::authentication::AuthenticationUpdate,
_merchant_key_store: &MerchantKeyStore,
_state: &KeyManagerState,
) -> CustomResult<hyperswitch_domain_models::authentication::Authentication, StorageError> {
let mut authentications = self.authentications.lock().await;
let auth_to_update = authentications
.iter_mut()
.find(|auth| {
auth.merchant_id == previous_state.merchant_id
&& auth.authentication_id == previous_state.authentication_id
})
.ok_or(StorageError::ValueNotFound(format!(
"Authentication not found for merchant_id: {} and authentication_id: {}",
previous_state.merchant_id.get_string_repr(),
previous_state.authentication_id.get_string_repr()
)))?;
// Apply the update based on the variant
match authentication_update {
hyperswitch_domain_models::authentication::AuthenticationUpdate::PreAuthenticationVersionCallUpdate {
maximum_supported_3ds_version,
message_version,
} => {
auth_to_update.maximum_supported_version = Some(maximum_supported_3ds_version);
auth_to_update.message_version = Some(message_version);
}
hyperswitch_domain_models::authentication::AuthenticationUpdate::PreAuthenticationThreeDsMethodCall {
threeds_server_transaction_id,
three_ds_method_data,
three_ds_method_url,
acquirer_bin,
acquirer_merchant_id,
connector_metadata,
} => {
auth_to_update.threeds_server_transaction_id = Some(threeds_server_transaction_id);
auth_to_update.three_ds_method_data = three_ds_method_data;
auth_to_update.three_ds_method_url = three_ds_method_url;
auth_to_update.acquirer_bin = acquirer_bin;
auth_to_update.acquirer_merchant_id = acquirer_merchant_id;
auth_to_update.connector_metadata = connector_metadata;
}
hyperswitch_domain_models::authentication::AuthenticationUpdate::PreAuthenticationUpdate {
threeds_server_transaction_id,
maximum_supported_3ds_version,
connector_authentication_id,
three_ds_method_data,
three_ds_method_url,
message_version,
connector_metadata,
authentication_status,
acquirer_bin,
acquirer_merchant_id,
directory_server_id,
acquirer_country_code,
billing_address,
shipping_address,
browser_info,
email,
scheme_id,
merchant_category_code,
merchant_country_code,
billing_country,
shipping_country,
earliest_supported_version,
latest_supported_version,
} => {
auth_to_update.threeds_server_transaction_id = Some(threeds_server_transaction_id);
auth_to_update.maximum_supported_version = Some(maximum_supported_3ds_version);
auth_to_update.connector_authentication_id = Some(connector_authentication_id);
auth_to_update.three_ds_method_data = three_ds_method_data;
auth_to_update.three_ds_method_url = three_ds_method_url;
auth_to_update.message_version = Some(message_version);
auth_to_update.connector_metadata = connector_metadata;
auth_to_update.authentication_status = authentication_status;
auth_to_update.acquirer_bin = acquirer_bin;
auth_to_update.acquirer_merchant_id = acquirer_merchant_id;
auth_to_update.directory_server_id = directory_server_id;
auth_to_update.acquirer_country_code = acquirer_country_code;
auth_to_update.billing_address = *billing_address;
auth_to_update.shipping_address = *shipping_address;
auth_to_update.browser_info = *browser_info;
auth_to_update.email = email;
auth_to_update.scheme_name = scheme_id;
auth_to_update.mcc = merchant_category_code;
auth_to_update.merchant_country_code = merchant_country_code;
auth_to_update.billing_country = billing_country;
auth_to_update.shipping_country = shipping_country;
auth_to_update.earliest_supported_version = earliest_supported_version;
auth_to_update.latest_supported_version = latest_supported_version;
}
hyperswitch_domain_models::authentication::AuthenticationUpdate::AuthenticationUpdate {
trans_status,
authentication_type,
acs_url,
challenge_request,
acs_reference_number,
acs_trans_id,
acs_signed_content,
connector_metadata,
authentication_status,
ds_trans_id,
eci,
challenge_code,
challenge_cancel,
challenge_code_reason,
message_extension,
challenge_request_key,
device_type,
device_brand,
device_os,
device_display,
} => {
auth_to_update.trans_status = Some(trans_status);
auth_to_update.authentication_type = Some(authentication_type);
auth_to_update.acs_url = acs_url;
auth_to_update.challenge_request = challenge_request;
auth_to_update.acs_reference_number = acs_reference_number;
auth_to_update.acs_trans_id = acs_trans_id;
auth_to_update.acs_signed_content = acs_signed_content;
auth_to_update.connector_metadata = connector_metadata;
auth_to_update.authentication_status = authentication_status;
auth_to_update.ds_trans_id = ds_trans_id;
auth_to_update.eci = eci;
auth_to_update.challenge_code = challenge_code;
auth_to_update.challenge_cancel = challenge_cancel;
auth_to_update.challenge_code_reason = challenge_code_reason;
auth_to_update.message_extension = message_extension;
auth_to_update.challenge_request_key = challenge_request_key;
auth_to_update.device_type = device_type;
auth_to_update.device_brand = device_brand;
auth_to_update.device_os = device_os;
auth_to_update.device_display = device_display;
}
hyperswitch_domain_models::authentication::AuthenticationUpdate::PostAuthenticationUpdate {
trans_status,
eci,
authentication_status,
challenge_cancel,
challenge_code_reason,
} => {
auth_to_update.trans_status = Some(trans_status);
auth_to_update.eci = eci;
auth_to_update.authentication_status = authentication_status;
auth_to_update.challenge_cancel = challenge_cancel;
auth_to_update.challenge_code_reason = challenge_code_reason;
}
hyperswitch_domain_models::authentication::AuthenticationUpdate::ErrorUpdate {
error_message,
error_code,
authentication_status,
connector_authentication_id,
} => {
auth_to_update.error_message = error_message;
auth_to_update.error_code = error_code;
auth_to_update.authentication_status = authentication_status;
auth_to_update.connector_authentication_id = connector_authentication_id;
}
hyperswitch_domain_models::authentication::AuthenticationUpdate::PostAuthorizationUpdate {
authentication_lifecycle_status,
} => {
auth_to_update.authentication_lifecycle_status = authentication_lifecycle_status;
}
hyperswitch_domain_models::authentication::AuthenticationUpdate::AuthenticationStatusUpdate {
trans_status,
authentication_status,
} => {
auth_to_update.trans_status = Some(trans_status);
auth_to_update.authentication_status = authentication_status;
}
}
auth_to_update.modified_at = common_utils::date_time::now();
Ok(auth_to_update.clone())
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/business_profile.rs | crates/router/src/db/business_profile.rs | pub use hyperswitch_domain_models::{
business_profile::{self, ProfileInterface},
errors::api_error_response,
};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/mandate.rs | crates/router/src/db/mandate.rs | use common_utils::id_type;
use super::MockDb;
use crate::{
core::errors::{self, CustomResult},
types::storage::{self as storage_types, enums::MerchantStorageScheme},
};
#[async_trait::async_trait]
pub trait MandateInterface {
async fn find_mandate_by_merchant_id_mandate_id(
&self,
merchant_id: &id_type::MerchantId,
mandate_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage_types::Mandate, errors::StorageError>;
async fn find_mandate_by_merchant_id_connector_mandate_id(
&self,
merchant_id: &id_type::MerchantId,
connector_mandate_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage_types::Mandate, errors::StorageError>;
async fn find_mandate_by_merchant_id_customer_id(
&self,
merchant_id: &id_type::MerchantId,
customer_id: &id_type::CustomerId,
) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError>;
// Fix this function once we move to mandate v2
#[cfg(feature = "v2")]
async fn find_mandate_by_global_customer_id(
&self,
id: &id_type::GlobalCustomerId,
) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError>;
async fn update_mandate_by_merchant_id_mandate_id(
&self,
merchant_id: &id_type::MerchantId,
mandate_id: &str,
mandate_update: storage_types::MandateUpdate,
mandate: storage_types::Mandate,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage_types::Mandate, errors::StorageError>;
async fn find_mandates_by_merchant_id(
&self,
merchant_id: &id_type::MerchantId,
mandate_constraints: api_models::mandates::MandateListConstraints,
) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError>;
async fn insert_mandate(
&self,
mandate: storage_types::MandateNew,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage_types::Mandate, errors::StorageError>;
}
#[cfg(feature = "kv_store")]
mod storage {
use common_utils::{fallback_reverse_lookup_not_found, id_type};
use diesel_models::kv;
use error_stack::{report, ResultExt};
use redis_interface::HsetnxReply;
use router_env::{instrument, tracing};
use storage_impl::redis::kv_store::{
decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey,
};
use super::MandateInterface;
use crate::{
connection,
core::errors::{self, utils::RedisErrorExt, CustomResult},
db::reverse_lookup::ReverseLookupInterface,
services::Store,
types::storage::{self as storage_types, enums::MerchantStorageScheme, MandateDbExt},
utils::db_utils,
};
#[async_trait::async_trait]
impl MandateInterface for Store {
#[instrument(skip_all)]
async fn find_mandate_by_merchant_id_mandate_id(
&self,
merchant_id: &id_type::MerchantId,
mandate_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage_types::Mandate, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
let database_call = || async {
storage_types::Mandate::find_by_merchant_id_mandate_id(
&conn,
merchant_id,
mandate_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
};
let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Mandate>(
self,
storage_scheme,
Op::Find,
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
MerchantStorageScheme::RedisKv => {
let key = PartitionKey::MerchantIdMandateId {
merchant_id,
mandate_id,
};
let field = format!("mandate_{mandate_id}");
Box::pin(db_utils::try_redis_get_else_try_database_get(
async {
Box::pin(kv_wrapper(
self,
KvOperation::<diesel_models::Mandate>::HGet(&field),
key,
))
.await?
.try_into_hget()
},
database_call,
))
.await
}
}
}
#[instrument(skip_all)]
async fn find_mandate_by_merchant_id_connector_mandate_id(
&self,
merchant_id: &id_type::MerchantId,
connector_mandate_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage_types::Mandate, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
let database_call = || async {
storage_types::Mandate::find_by_merchant_id_connector_mandate_id(
&conn,
merchant_id,
connector_mandate_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
};
let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Mandate>(
self,
storage_scheme,
Op::Find,
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
MerchantStorageScheme::RedisKv => {
let lookup_id = format!(
"mid_{}_conn_mandate_{}",
merchant_id.get_string_repr(),
connector_mandate_id
);
let lookup = fallback_reverse_lookup_not_found!(
self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)
.await,
database_call().await
);
let key = PartitionKey::CombinationKey {
combination: &lookup.pk_id,
};
Box::pin(db_utils::try_redis_get_else_try_database_get(
async {
Box::pin(kv_wrapper(
self,
KvOperation::<diesel_models::Mandate>::HGet(&lookup.sk_id),
key,
))
.await?
.try_into_hget()
},
database_call,
))
.await
}
}
}
#[instrument(skip_all)]
async fn find_mandate_by_merchant_id_customer_id(
&self,
merchant_id: &id_type::MerchantId,
customer_id: &id_type::CustomerId,
) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage_types::Mandate::find_by_merchant_id_customer_id(&conn, merchant_id, customer_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn find_mandate_by_global_customer_id(
&self,
id: &id_type::GlobalCustomerId,
) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage_types::Mandate::find_by_global_customer_id(&conn, id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn update_mandate_by_merchant_id_mandate_id(
&self,
merchant_id: &id_type::MerchantId,
mandate_id: &str,
mandate_update: storage_types::MandateUpdate,
mandate: storage_types::Mandate,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage_types::Mandate, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
let key = PartitionKey::MerchantIdMandateId {
merchant_id,
mandate_id,
};
let field = format!("mandate_{mandate_id}");
let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Mandate>(
self,
storage_scheme,
Op::Update(key.clone(), &field, mandate.updated_by.as_deref()),
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
storage_types::Mandate::update_by_merchant_id_mandate_id(
&conn,
merchant_id,
mandate_id,
mandate_update.convert_to_mandate_update(storage_scheme),
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
MerchantStorageScheme::RedisKv => {
let key_str = key.to_string();
if let diesel_models::MandateUpdate::ConnectorMandateIdUpdate {
connector_mandate_id: Some(val),
..
} = &mandate_update
{
let rev_lookup = diesel_models::ReverseLookupNew {
sk_id: field.clone(),
pk_id: key_str.clone(),
lookup_id: format!(
"mid_{}_conn_mandate_{}",
merchant_id.get_string_repr(),
val
),
source: "mandate".to_string(),
updated_by: storage_scheme.to_string(),
};
self.insert_reverse_lookup(rev_lookup, storage_scheme)
.await?;
}
let m_update = mandate_update.convert_to_mandate_update(storage_scheme);
let updated_mandate = m_update.clone().apply_changeset(mandate.clone());
let redis_value = serde_json::to_string(&updated_mandate)
.change_context(errors::StorageError::SerializationFailed)?;
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Update {
updatable: Box::new(kv::Updateable::MandateUpdate(
kv::MandateUpdateMems {
orig: mandate,
update_data: m_update,
},
)),
},
};
Box::pin(kv_wrapper::<(), _, _>(
self,
KvOperation::<diesel_models::Mandate>::Hset(
(&field, redis_value),
redis_entry,
),
key,
))
.await
.map_err(|err| err.to_redis_failed_response(&key_str))?
.try_into_hset()
.change_context(errors::StorageError::KVError)?;
Ok(updated_mandate)
}
}
}
#[instrument(skip_all)]
async fn find_mandates_by_merchant_id(
&self,
merchant_id: &id_type::MerchantId,
mandate_constraints: api_models::mandates::MandateListConstraints,
) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage_types::Mandate::filter_by_constraints(&conn, merchant_id, mandate_constraints)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn insert_mandate(
&self,
mut mandate: storage_types::MandateNew,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage_types::Mandate, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Mandate>(
self,
storage_scheme,
Op::Insert,
))
.await;
mandate.update_storage_scheme(storage_scheme);
match storage_scheme {
MerchantStorageScheme::PostgresOnly => mandate
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error))),
MerchantStorageScheme::RedisKv => {
let mandate_id = mandate.mandate_id.clone();
let merchant_id = &mandate.merchant_id.to_owned();
let connector_mandate_id = mandate.connector_mandate_id.clone();
let key = PartitionKey::MerchantIdMandateId {
merchant_id,
mandate_id: mandate_id.as_str(),
};
let key_str = key.to_string();
let field = format!("mandate_{mandate_id}");
let storage_mandate = storage_types::Mandate::from(&mandate);
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
insertable: Box::new(kv::Insertable::Mandate(mandate)),
},
};
if let Some(connector_val) = connector_mandate_id {
let lookup_id = format!(
"mid_{}_conn_mandate_{}",
merchant_id.get_string_repr(),
connector_val
);
let reverse_lookup_entry = diesel_models::ReverseLookupNew {
sk_id: field.clone(),
pk_id: key_str.clone(),
lookup_id,
source: "mandate".to_string(),
updated_by: storage_scheme.to_string(),
};
self.insert_reverse_lookup(reverse_lookup_entry, storage_scheme)
.await?;
}
match Box::pin(kv_wrapper::<diesel_models::Mandate, _, _>(
self,
KvOperation::<diesel_models::Mandate>::HSetNx(
&field,
&storage_mandate,
redis_entry,
),
key,
))
.await
.map_err(|err| err.to_redis_failed_response(&key_str))?
.try_into_hsetnx()
{
Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue {
entity: "mandate",
key: Some(storage_mandate.mandate_id),
}
.into()),
Ok(HsetnxReply::KeySet) => Ok(storage_mandate),
Err(er) => Err(er).change_context(errors::StorageError::KVError),
}
}
}
}
}
}
#[cfg(not(feature = "kv_store"))]
mod storage {
use common_utils::id_type;
use error_stack::report;
use router_env::{instrument, tracing};
use super::MandateInterface;
use crate::{
connection,
core::errors::{self, CustomResult},
services::Store,
types::storage::{self as storage_types, enums::MerchantStorageScheme, MandateDbExt},
};
#[async_trait::async_trait]
impl MandateInterface for Store {
#[instrument(skip_all)]
async fn find_mandate_by_merchant_id_mandate_id(
&self,
merchant_id: &id_type::MerchantId,
mandate_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage_types::Mandate, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage_types::Mandate::find_by_merchant_id_mandate_id(&conn, merchant_id, mandate_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_mandate_by_merchant_id_connector_mandate_id(
&self,
merchant_id: &id_type::MerchantId,
connector_mandate_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage_types::Mandate, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage_types::Mandate::find_by_merchant_id_connector_mandate_id(
&conn,
merchant_id,
connector_mandate_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_mandate_by_merchant_id_customer_id(
&self,
merchant_id: &id_type::MerchantId,
customer_id: &id_type::CustomerId,
) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage_types::Mandate::find_by_merchant_id_customer_id(&conn, merchant_id, customer_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
// Need to fix this once we start moving to mandate v2
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn find_mandate_by_global_customer_id(
&self,
customer_id: &id_type::GlobalCustomerId,
) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage_types::Mandate::find_by_global_id(&conn, customer_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn update_mandate_by_merchant_id_mandate_id(
&self,
merchant_id: &id_type::MerchantId,
mandate_id: &str,
mandate_update: storage_types::MandateUpdate,
_mandate: storage_types::Mandate,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage_types::Mandate, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage_types::Mandate::update_by_merchant_id_mandate_id(
&conn,
merchant_id,
mandate_id,
storage_types::MandateUpdateInternal::from(mandate_update),
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_mandates_by_merchant_id(
&self,
merchant_id: &id_type::MerchantId,
mandate_constraints: api_models::mandates::MandateListConstraints,
) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage_types::Mandate::filter_by_constraints(&conn, merchant_id, mandate_constraints)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn insert_mandate(
&self,
mandate: storage_types::MandateNew,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage_types::Mandate, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
mandate
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
}
#[async_trait::async_trait]
impl MandateInterface for MockDb {
async fn find_mandate_by_merchant_id_mandate_id(
&self,
merchant_id: &id_type::MerchantId,
mandate_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage_types::Mandate, errors::StorageError> {
self.mandates
.lock()
.await
.iter()
.find(|mandate| mandate.merchant_id == *merchant_id && mandate.mandate_id == mandate_id)
.cloned()
.ok_or_else(|| errors::StorageError::ValueNotFound("mandate not found".to_string()))
.map_err(|err| err.into())
}
async fn find_mandate_by_merchant_id_connector_mandate_id(
&self,
merchant_id: &id_type::MerchantId,
connector_mandate_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage_types::Mandate, errors::StorageError> {
self.mandates
.lock()
.await
.iter()
.find(|mandate| {
mandate.merchant_id == *merchant_id
&& mandate.connector_mandate_id == Some(connector_mandate_id.to_string())
})
.cloned()
.ok_or_else(|| errors::StorageError::ValueNotFound("mandate not found".to_string()))
.map_err(|err| err.into())
}
async fn find_mandate_by_merchant_id_customer_id(
&self,
merchant_id: &id_type::MerchantId,
customer_id: &id_type::CustomerId,
) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> {
return Ok(self
.mandates
.lock()
.await
.iter()
.filter(|mandate| {
mandate.merchant_id == *merchant_id && &mandate.customer_id == customer_id
})
.cloned()
.collect());
}
// Need to fix this once we move to v2 mandate
#[cfg(feature = "v2")]
async fn find_mandate_by_global_customer_id(
&self,
id: &id_type::GlobalCustomerId,
) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> {
todo!()
}
async fn update_mandate_by_merchant_id_mandate_id(
&self,
merchant_id: &id_type::MerchantId,
mandate_id: &str,
mandate_update: storage_types::MandateUpdate,
_mandate: storage_types::Mandate,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage_types::Mandate, errors::StorageError> {
let mut mandates = self.mandates.lock().await;
match mandates
.iter_mut()
.find(|mandate| mandate.merchant_id == *merchant_id && mandate.mandate_id == mandate_id)
{
Some(mandate) => {
let m_update = diesel_models::MandateUpdateInternal::from(mandate_update);
let updated_mandate = m_update.clone().apply_changeset(mandate.clone());
Ok(updated_mandate)
}
None => {
Err(errors::StorageError::ValueNotFound("mandate not found".to_string()).into())
}
}
}
async fn find_mandates_by_merchant_id(
&self,
merchant_id: &id_type::MerchantId,
mandate_constraints: api_models::mandates::MandateListConstraints,
) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> {
let mandates = self.mandates.lock().await;
let mandates_iter = mandates.iter().filter(|mandate| {
let mut checker = mandate.merchant_id == *merchant_id;
if let Some(created_time) = mandate_constraints.created_time {
checker &= mandate.created_at == created_time;
}
if let Some(created_time_lt) = mandate_constraints.created_time_lt {
checker &= mandate.created_at < created_time_lt;
}
if let Some(created_time_gt) = mandate_constraints.created_time_gt {
checker &= mandate.created_at > created_time_gt;
}
if let Some(created_time_lte) = mandate_constraints.created_time_lte {
checker &= mandate.created_at <= created_time_lte;
}
if let Some(created_time_gte) = mandate_constraints.created_time_gte {
checker &= mandate.created_at >= created_time_gte;
}
if let Some(connector) = &mandate_constraints.connector {
checker &= mandate.connector == *connector;
}
if let Some(mandate_status) = mandate_constraints.mandate_status {
checker &= mandate.mandate_status == mandate_status;
}
checker
});
#[allow(clippy::as_conversions)]
let offset = (if mandate_constraints.offset.unwrap_or(0) < 0 {
0
} else {
mandate_constraints.offset.unwrap_or(0)
}) as usize;
let mandates: Vec<storage_types::Mandate> = if let Some(limit) = mandate_constraints.limit {
#[allow(clippy::as_conversions)]
mandates_iter
.skip(offset)
.take((if limit < 0 { 0 } else { limit }) as usize)
.cloned()
.collect()
} else {
mandates_iter.skip(offset).cloned().collect()
};
Ok(mandates)
}
async fn insert_mandate(
&self,
mandate_new: storage_types::MandateNew,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage_types::Mandate, errors::StorageError> {
let mut mandates = self.mandates.lock().await;
let customer_user_agent_extended = mandate_new.get_customer_user_agent_extended();
let mandate = storage_types::Mandate {
mandate_id: mandate_new.mandate_id.clone(),
customer_id: mandate_new.customer_id,
merchant_id: mandate_new.merchant_id,
original_payment_id: mandate_new.original_payment_id,
payment_method_id: mandate_new.payment_method_id,
mandate_status: mandate_new.mandate_status,
mandate_type: mandate_new.mandate_type,
customer_accepted_at: mandate_new.customer_accepted_at,
customer_ip_address: mandate_new.customer_ip_address,
customer_user_agent: None,
network_transaction_id: mandate_new.network_transaction_id,
previous_attempt_id: mandate_new.previous_attempt_id,
created_at: mandate_new
.created_at
.unwrap_or_else(common_utils::date_time::now),
mandate_amount: mandate_new.mandate_amount,
mandate_currency: mandate_new.mandate_currency,
amount_captured: mandate_new.amount_captured,
connector: mandate_new.connector,
connector_mandate_id: mandate_new.connector_mandate_id,
start_date: mandate_new.start_date,
end_date: mandate_new.end_date,
metadata: mandate_new.metadata,
connector_mandate_ids: mandate_new.connector_mandate_ids,
merchant_connector_id: mandate_new.merchant_connector_id,
updated_by: mandate_new.updated_by,
customer_user_agent_extended,
};
mandates.push(mandate.clone());
Ok(mandate)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/role.rs | crates/router/src/db/role.rs | use common_utils::id_type;
use diesel_models::{
enums::{EntityType, RoleScope},
role as storage,
};
use error_stack::report;
use router_env::{instrument, tracing};
use super::MockDb;
use crate::{
connection,
core::errors::{self, CustomResult},
services::Store,
};
#[async_trait::async_trait]
pub trait RoleInterface {
async fn insert_role(
&self,
role: storage::RoleNew,
) -> CustomResult<storage::Role, errors::StorageError>;
async fn find_role_by_role_id(
&self,
role_id: &str,
) -> CustomResult<storage::Role, errors::StorageError>;
async fn find_role_by_role_id_in_lineage(
&self,
role_id: &str,
merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
profile_id: &id_type::ProfileId,
tenant_id: &id_type::TenantId,
) -> CustomResult<storage::Role, errors::StorageError>;
async fn find_by_role_id_org_id_tenant_id(
&self,
role_id: &str,
org_id: &id_type::OrganizationId,
tenant_id: &id_type::TenantId,
) -> CustomResult<storage::Role, errors::StorageError>;
async fn update_role_by_role_id(
&self,
role_id: &str,
role_update: storage::RoleUpdate,
) -> CustomResult<storage::Role, errors::StorageError>;
async fn delete_role_by_role_id(
&self,
role_id: &str,
) -> CustomResult<storage::Role, errors::StorageError>;
//TODO: Remove once generic_list_roles_by_entity_type is stable
async fn list_roles_for_org_by_parameters(
&self,
tenant_id: &id_type::TenantId,
org_id: &id_type::OrganizationId,
merchant_id: Option<&id_type::MerchantId>,
entity_type: Option<EntityType>,
limit: Option<u32>,
) -> CustomResult<Vec<storage::Role>, errors::StorageError>;
async fn generic_list_roles_by_entity_type(
&self,
payload: storage::ListRolesByEntityPayload,
is_lineage_data_required: bool,
tenant_id: id_type::TenantId,
org_id: id_type::OrganizationId,
) -> CustomResult<Vec<storage::Role>, errors::StorageError>;
}
#[async_trait::async_trait]
impl RoleInterface for Store {
#[instrument(skip_all)]
async fn insert_role(
&self,
role: storage::RoleNew,
) -> CustomResult<storage::Role, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
role.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_role_by_role_id(
&self,
role_id: &str,
) -> CustomResult<storage::Role, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Role::find_by_role_id(&conn, role_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_role_by_role_id_in_lineage(
&self,
role_id: &str,
merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
profile_id: &id_type::ProfileId,
tenant_id: &id_type::TenantId,
) -> CustomResult<storage::Role, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Role::find_by_role_id_in_lineage(
&conn,
role_id,
merchant_id,
org_id,
profile_id,
tenant_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_by_role_id_org_id_tenant_id(
&self,
role_id: &str,
org_id: &id_type::OrganizationId,
tenant_id: &id_type::TenantId,
) -> CustomResult<storage::Role, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Role::find_by_role_id_org_id_tenant_id(&conn, role_id, org_id, tenant_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn update_role_by_role_id(
&self,
role_id: &str,
role_update: storage::RoleUpdate,
) -> CustomResult<storage::Role, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::Role::update_by_role_id(&conn, role_id, role_update)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn delete_role_by_role_id(
&self,
role_id: &str,
) -> CustomResult<storage::Role, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::Role::delete_by_role_id(&conn, role_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
//TODO: Remove once generic_list_roles_by_entity_type is stable
#[instrument(skip_all)]
async fn list_roles_for_org_by_parameters(
&self,
tenant_id: &id_type::TenantId,
org_id: &id_type::OrganizationId,
merchant_id: Option<&id_type::MerchantId>,
entity_type: Option<EntityType>,
limit: Option<u32>,
) -> CustomResult<Vec<storage::Role>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Role::generic_roles_list_for_org(
&conn,
tenant_id.to_owned(),
org_id.to_owned(),
merchant_id.cloned(),
entity_type,
limit,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn generic_list_roles_by_entity_type(
&self,
payload: storage::ListRolesByEntityPayload,
is_lineage_data_required: bool,
tenant_id: id_type::TenantId,
org_id: id_type::OrganizationId,
) -> CustomResult<Vec<storage::Role>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Role::generic_list_roles_by_entity_type(
&conn,
payload,
is_lineage_data_required,
tenant_id,
org_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
#[async_trait::async_trait]
impl RoleInterface for MockDb {
async fn insert_role(
&self,
role: storage::RoleNew,
) -> CustomResult<storage::Role, errors::StorageError> {
let mut roles = self.roles.lock().await;
if roles
.iter()
.any(|role_inner| role_inner.role_id == role.role_id)
{
Err(errors::StorageError::DuplicateValue {
entity: "role_id",
key: None,
})?
}
let role = storage::Role {
role_name: role.role_name,
role_id: role.role_id,
merchant_id: role.merchant_id,
org_id: role.org_id,
groups: role.groups,
scope: role.scope,
entity_type: role.entity_type,
created_by: role.created_by,
created_at: role.created_at,
last_modified_at: role.last_modified_at,
last_modified_by: role.last_modified_by,
profile_id: role.profile_id,
tenant_id: role.tenant_id,
};
roles.push(role.clone());
Ok(role)
}
async fn find_role_by_role_id(
&self,
role_id: &str,
) -> CustomResult<storage::Role, errors::StorageError> {
let roles = self.roles.lock().await;
roles
.iter()
.find(|role| role.role_id == role_id)
.cloned()
.ok_or(
errors::StorageError::ValueNotFound(format!(
"No role available role_id = {role_id}"
))
.into(),
)
}
async fn find_role_by_role_id_in_lineage(
&self,
role_id: &str,
merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
profile_id: &id_type::ProfileId,
tenant_id: &id_type::TenantId,
) -> CustomResult<storage::Role, errors::StorageError> {
let roles = self.roles.lock().await;
roles
.iter()
.find(|role| {
role.role_id == role_id
&& (role.tenant_id == *tenant_id)
&& role.org_id == *org_id
&& ((role.scope == RoleScope::Organization)
|| (role
.merchant_id
.as_ref()
.is_some_and(|merchant_id_from_role| {
merchant_id_from_role == merchant_id
&& role.scope == RoleScope::Merchant
}))
|| (role
.profile_id
.as_ref()
.is_some_and(|profile_id_from_role| {
profile_id_from_role == profile_id
&& role.scope == RoleScope::Profile
})))
})
.cloned()
.ok_or(
errors::StorageError::ValueNotFound(format!(
"No role available in merchant scope for role_id = {role_id}, \
merchant_id = {merchant_id:?} and org_id = {org_id:?}"
))
.into(),
)
}
async fn find_by_role_id_org_id_tenant_id(
&self,
role_id: &str,
org_id: &id_type::OrganizationId,
tenant_id: &id_type::TenantId,
) -> CustomResult<storage::Role, errors::StorageError> {
let roles = self.roles.lock().await;
roles
.iter()
.find(|role| {
role.role_id == role_id && role.org_id == *org_id && role.tenant_id == *tenant_id
})
.cloned()
.ok_or(
errors::StorageError::ValueNotFound(format!(
"No role available in org scope for role_id = {role_id} and org_id = {org_id:?}"
))
.into(),
)
}
async fn update_role_by_role_id(
&self,
role_id: &str,
role_update: storage::RoleUpdate,
) -> CustomResult<storage::Role, errors::StorageError> {
let mut roles = self.roles.lock().await;
roles
.iter_mut()
.find(|role| role.role_id == role_id)
.map(|role| {
*role = match role_update {
storage::RoleUpdate::UpdateDetails {
groups,
role_name,
last_modified_at,
last_modified_by,
} => storage::Role {
groups: groups.unwrap_or(role.groups.to_owned()),
role_name: role_name.unwrap_or(role.role_name.to_owned()),
last_modified_by,
last_modified_at,
..role.to_owned()
},
};
role.to_owned()
})
.ok_or(
errors::StorageError::ValueNotFound(format!(
"No role available for role_id = {role_id}"
))
.into(),
)
}
async fn delete_role_by_role_id(
&self,
role_id: &str,
) -> CustomResult<storage::Role, errors::StorageError> {
let mut roles = self.roles.lock().await;
let role_index = roles
.iter()
.position(|role| role.role_id == role_id)
.ok_or(errors::StorageError::ValueNotFound(format!(
"No role available for role_id = {role_id}"
)))?;
Ok(roles.remove(role_index))
}
//TODO: Remove once generic_list_roles_by_entity_type is stable
#[instrument(skip_all)]
async fn list_roles_for_org_by_parameters(
&self,
tenant_id: &id_type::TenantId,
org_id: &id_type::OrganizationId,
merchant_id: Option<&id_type::MerchantId>,
entity_type: Option<EntityType>,
limit: Option<u32>,
) -> CustomResult<Vec<storage::Role>, errors::StorageError> {
let roles = self.roles.lock().await;
let limit_usize = limit.unwrap_or(u32::MAX).try_into().unwrap_or(usize::MAX);
let roles_list: Vec<_> = roles
.iter()
.filter(|role| {
let matches_merchant = merchant_id
.zip(role.merchant_id.as_ref())
.map(|(merchant_id, role_merchant_id)| merchant_id == role_merchant_id)
.unwrap_or(true);
matches_merchant
&& role.org_id == *org_id
&& role.tenant_id == *tenant_id
&& Some(role.entity_type) == entity_type
})
.take(limit_usize)
.cloned()
.collect();
Ok(roles_list)
}
#[instrument(skip_all)]
async fn generic_list_roles_by_entity_type(
&self,
payload: storage::ListRolesByEntityPayload,
is_lineage_data_required: bool,
tenant_id: id_type::TenantId,
org_id: id_type::OrganizationId,
) -> CustomResult<Vec<storage::Role>, errors::StorageError> {
let roles = self.roles.lock().await;
let roles_list: Vec<_> = roles
.iter()
.filter(|role| match &payload {
storage::ListRolesByEntityPayload::Organization => {
let entity_in_vec = if is_lineage_data_required {
vec![
EntityType::Organization,
EntityType::Merchant,
EntityType::Profile,
]
} else {
vec![EntityType::Organization]
};
role.tenant_id == tenant_id
&& role.org_id == org_id
&& entity_in_vec.contains(&role.entity_type)
}
storage::ListRolesByEntityPayload::Merchant(merchant_id) => {
let entity_in_vec = if is_lineage_data_required {
vec![EntityType::Merchant, EntityType::Profile]
} else {
vec![EntityType::Merchant]
};
let matches_merchant = role
.merchant_id
.as_ref()
.is_some_and(|merchant_id_from_role| merchant_id_from_role == merchant_id);
role.tenant_id == tenant_id
&& role.org_id == org_id
&& (role.scope == RoleScope::Organization || matches_merchant)
&& entity_in_vec.contains(&role.entity_type)
}
storage::ListRolesByEntityPayload::Profile(merchant_id, profile_id) => {
let entity_in_vec = [EntityType::Profile];
let matches_merchant =
role.merchant_id
.as_ref()
.is_some_and(|merchant_id_from_role| {
merchant_id_from_role == merchant_id
&& role.scope == RoleScope::Merchant
});
let matches_profile =
role.profile_id
.as_ref()
.is_some_and(|profile_id_from_role| {
profile_id_from_role == profile_id
&& role.scope == RoleScope::Profile
});
role.tenant_id == tenant_id
&& role.org_id == org_id
&& (role.scope == RoleScope::Organization
|| matches_merchant
|| matches_profile)
&& entity_in_vec.contains(&role.entity_type)
}
})
.cloned()
.collect();
Ok(roles_list)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/events.rs | crates/router/src/db/events.rs | use std::collections::HashSet;
use common_utils::ext_traits::AsyncExt;
use error_stack::{report, ResultExt};
use futures::future::try_join_all;
use router_env::{instrument, tracing};
use super::{MockDb, Store};
use crate::{
connection,
core::errors::{self, CustomResult},
types::{
domain::{
self,
behaviour::{Conversion, ReverseConversion},
},
storage,
},
};
#[async_trait::async_trait]
pub trait EventInterface
where
domain::Event:
Conversion<DstType = storage::events::Event, NewDstType = storage::events::EventNew>,
{
async fn insert_event(
&self,
event: domain::Event,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError>;
async fn find_event_by_merchant_id_event_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError>;
async fn find_event_by_merchant_id_idempotent_event_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
idempotent_event_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError>;
#[allow(clippy::too_many_arguments)]
async fn list_initial_events_by_merchant_id_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
created_after: time::PrimitiveDateTime,
created_before: time::PrimitiveDateTime,
limit: Option<i64>,
offset: Option<i64>,
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError>;
async fn list_events_by_merchant_id_initial_attempt_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
initial_attempt_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError>;
async fn list_initial_events_by_merchant_id_primary_object_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
primary_object_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError>;
async fn find_initial_event_by_merchant_id_initial_attempt_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
initial_attempt_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Option<domain::Event>, errors::StorageError>;
#[allow(clippy::too_many_arguments)]
async fn list_initial_events_by_profile_id_constraints(
&self,
profile_id: &common_utils::id_type::ProfileId,
created_after: time::PrimitiveDateTime,
created_before: time::PrimitiveDateTime,
limit: Option<i64>,
offset: Option<i64>,
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError>;
async fn list_initial_events_by_profile_id_primary_object_id(
&self,
profile_id: &common_utils::id_type::ProfileId,
primary_object_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError>;
async fn find_initial_event_by_profile_id_initial_attempt_id(
&self,
profile_id: &common_utils::id_type::ProfileId,
initial_attempt_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Option<domain::Event>, errors::StorageError>;
async fn update_event_by_merchant_id_event_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
event: domain::EventUpdate,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError>;
async fn count_initial_events_by_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
profile_id: Option<common_utils::id_type::ProfileId>,
created_after: time::PrimitiveDateTime,
created_before: time::PrimitiveDateTime,
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
) -> CustomResult<i64, errors::StorageError>;
}
#[async_trait::async_trait]
impl EventInterface for Store {
#[instrument(skip_all)]
async fn insert_event(
&self,
event: domain::Event,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
event
.construct_new()
.await
.change_context(errors::StorageError::EncryptionError)?
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))?
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
}
#[instrument(skip_all)]
async fn find_event_by_merchant_id_event_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Event::find_by_merchant_id_event_id(&conn, merchant_id, event_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))?
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
}
#[instrument(skip_all)]
async fn find_event_by_merchant_id_idempotent_event_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
idempotent_event_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Event::find_by_merchant_id_idempotent_event_id(
&conn,
merchant_id,
idempotent_event_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))?
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
}
#[instrument(skip_all)]
async fn list_initial_events_by_merchant_id_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
created_after: time::PrimitiveDateTime,
created_before: time::PrimitiveDateTime,
limit: Option<i64>,
offset: Option<i64>,
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Event::list_initial_attempts_by_merchant_id_constraints(
&conn,
merchant_id,
created_after,
created_before,
limit,
offset,
event_types,
is_delivered,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
.async_and_then(|events| {
try_join_all(events.into_iter().map(|event| async move {
event
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
}))
})
.await
}
#[instrument(skip_all)]
async fn list_events_by_merchant_id_initial_attempt_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
initial_attempt_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Event::list_by_merchant_id_initial_attempt_id(
&conn,
merchant_id,
initial_attempt_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
.async_and_then(|events| {
try_join_all(events.into_iter().map(|event| async move {
event
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
}))
})
.await
}
#[instrument(skip_all)]
async fn list_initial_events_by_merchant_id_primary_object_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
primary_object_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Event::list_initial_attempts_by_merchant_id_primary_object_id(
&conn,
merchant_id,
primary_object_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
.async_and_then(|events| {
try_join_all(events.into_iter().map(|event| async move {
event
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
}))
})
.await
}
#[instrument(skip_all)]
async fn find_initial_event_by_merchant_id_initial_attempt_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
initial_attempt_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Option<domain::Event>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Event::find_initial_attempt_by_merchant_id_initial_attempt_id(
&conn,
merchant_id,
initial_attempt_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
.async_and_then(|event_opt| async {
match event_opt {
Some(event) => Ok(Some(
event
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?,
)),
None => Ok(None),
}
})
.await
}
#[instrument(skip_all)]
async fn list_initial_events_by_profile_id_constraints(
&self,
profile_id: &common_utils::id_type::ProfileId,
created_after: time::PrimitiveDateTime,
created_before: time::PrimitiveDateTime,
limit: Option<i64>,
offset: Option<i64>,
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Event::list_initial_attempts_by_profile_id_constraints(
&conn,
profile_id,
created_after,
created_before,
limit,
offset,
event_types,
is_delivered,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
.async_and_then(|events| {
try_join_all(events.into_iter().map(|event| async move {
event
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
merchant_key_store.key.get_inner(),
common_utils::types::keymanager::Identifier::Merchant(
merchant_key_store.merchant_id.clone(),
),
)
.await
.change_context(errors::StorageError::DecryptionError)
}))
})
.await
}
#[instrument(skip_all)]
async fn list_initial_events_by_profile_id_primary_object_id(
&self,
profile_id: &common_utils::id_type::ProfileId,
primary_object_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Event::list_initial_attempts_by_profile_id_primary_object_id(
&conn,
profile_id,
primary_object_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
.async_and_then(|events| {
try_join_all(events.into_iter().map(|event| async {
event
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
}))
})
.await
}
#[instrument(skip_all)]
async fn find_initial_event_by_profile_id_initial_attempt_id(
&self,
profile_id: &common_utils::id_type::ProfileId,
initial_attempt_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Option<domain::Event>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Event::find_initial_attempt_by_profile_id_initial_attempt_id(
&conn,
profile_id,
initial_attempt_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
.async_and_then(|event_opt| async {
match event_opt {
Some(event) => Ok(Some(
event
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
merchant_key_store.key.get_inner(),
common_utils::types::keymanager::Identifier::Merchant(
merchant_key_store.merchant_id.clone(),
),
)
.await
.change_context(errors::StorageError::DecryptionError)?,
)),
None => Ok(None),
}
})
.await
}
#[instrument(skip_all)]
async fn update_event_by_merchant_id_event_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
event: domain::EventUpdate,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::Event::update_by_merchant_id_event_id(&conn, merchant_id, event_id, event.into())
.await
.map_err(|error| report!(errors::StorageError::from(error)))?
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
}
async fn count_initial_events_by_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
profile_id: Option<common_utils::id_type::ProfileId>,
created_after: time::PrimitiveDateTime,
created_before: time::PrimitiveDateTime,
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
) -> CustomResult<i64, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Event::count_initial_attempts_by_constraints(
&conn,
merchant_id,
profile_id,
created_after,
created_before,
event_types,
is_delivered,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
#[async_trait::async_trait]
impl EventInterface for MockDb {
async fn insert_event(
&self,
event: domain::Event,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError> {
let mut locked_events = self.events.lock().await;
let stored_event = Conversion::convert(event)
.await
.change_context(errors::StorageError::EncryptionError)?;
locked_events.push(stored_event.clone());
stored_event
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
}
async fn find_event_by_merchant_id_event_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError> {
let locked_events = self.events.lock().await;
locked_events
.iter()
.find(|event| {
event.merchant_id == Some(merchant_id.to_owned()) && event.event_id == event_id
})
.cloned()
.async_map(|event| async {
event
.convert(self.get_keymanager_state().attach_printable("Missing KeyManagerState")?,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
})
.await
.transpose()?
.ok_or(
errors::StorageError::ValueNotFound(format!(
"No event available with merchant_id = {merchant_id:?} and event_id = {event_id}"
))
.into(),
)
}
async fn find_event_by_merchant_id_idempotent_event_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
idempotent_event_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError> {
let locked_events = self.events.lock().await;
locked_events
.iter()
.find(|event| {
event.merchant_id == Some(merchant_id.to_owned()) && event.idempotent_event_id == Some(idempotent_event_id.to_string())
})
.cloned()
.async_map(|event| async {
event
.convert(self.get_keymanager_state().attach_printable("Missing KeyManagerState")?,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
})
.await
.transpose()?
.ok_or(
errors::StorageError::ValueNotFound(format!(
"No event available with merchant_id = {merchant_id:?} and idempotent_event_id = {idempotent_event_id}"
))
.into(),
)
}
async fn list_initial_events_by_merchant_id_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
created_after: time::PrimitiveDateTime,
created_before: time::PrimitiveDateTime,
limit: Option<i64>,
offset: Option<i64>,
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
let locked_events = self.events.lock().await;
let events_iter = locked_events.iter().filter(|event| {
let check = event.merchant_id == Some(merchant_id.to_owned())
&& event.initial_attempt_id.as_ref() == Some(&event.event_id)
&& (event.created_at >= created_after)
&& (event.created_at <= created_before)
&& (event_types.is_empty() || event_types.contains(&event.event_type))
&& (event.is_overall_delivery_successful == is_delivered);
check
});
let offset: usize = if let Some(offset) = offset {
if offset < 0 {
Err(errors::StorageError::MockDbError)?;
}
offset
.try_into()
.map_err(|_| errors::StorageError::MockDbError)?
} else {
0
};
let limit: usize = if let Some(limit) = limit {
if limit < 0 {
Err(errors::StorageError::MockDbError)?;
}
limit
.try_into()
.map_err(|_| errors::StorageError::MockDbError)?
} else {
usize::MAX
};
let events = events_iter
.skip(offset)
.take(limit)
.cloned()
.collect::<Vec<_>>();
let mut domain_events = Vec::with_capacity(events.len());
for event in events {
let domain_event = event
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?;
domain_events.push(domain_event);
}
Ok(domain_events)
}
async fn list_events_by_merchant_id_initial_attempt_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
initial_attempt_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
let locked_events = self.events.lock().await;
let events = locked_events
.iter()
.filter(|event| {
event.merchant_id == Some(merchant_id.to_owned())
&& event.initial_attempt_id == Some(initial_attempt_id.to_owned())
})
.cloned()
.collect::<Vec<_>>();
let mut domain_events = Vec::with_capacity(events.len());
for event in events {
let domain_event = event
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?;
domain_events.push(domain_event);
}
Ok(domain_events)
}
async fn list_initial_events_by_merchant_id_primary_object_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
primary_object_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
let locked_events = self.events.lock().await;
let events = locked_events
.iter()
.filter(|event| {
event.merchant_id == Some(merchant_id.to_owned())
&& event.initial_attempt_id.as_deref() == Some(&event.event_id)
&& event.primary_object_id.as_str() == primary_object_id
})
.cloned()
.collect::<Vec<_>>();
let mut domain_events = Vec::with_capacity(events.len());
for event in events {
let domain_event = event
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?;
domain_events.push(domain_event);
}
Ok(domain_events)
}
async fn find_initial_event_by_merchant_id_initial_attempt_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
initial_attempt_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Option<domain::Event>, errors::StorageError> {
let locked_events = self.events.lock().await;
let event_opt = locked_events.iter().find(|event| {
event.merchant_id == Some(merchant_id.to_owned())
&& event.event_id == initial_attempt_id
});
match event_opt {
Some(event) => {
let domain_event = event
.clone()
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?;
Ok(Some(domain_event))
}
None => Ok(None),
}
}
async fn list_initial_events_by_profile_id_constraints(
&self,
profile_id: &common_utils::id_type::ProfileId,
created_after: time::PrimitiveDateTime,
created_before: time::PrimitiveDateTime,
limit: Option<i64>,
offset: Option<i64>,
event_types: HashSet<common_enums::EventType>,
is_delivered: Option<bool>,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
let locked_events = self.events.lock().await;
let events_iter = locked_events.iter().filter(|event| {
let check = event.business_profile_id == Some(profile_id.to_owned())
&& event.initial_attempt_id.as_ref() == Some(&event.event_id)
&& (event.created_at >= created_after)
&& (event.created_at <= created_before)
&& (event_types.is_empty() || event_types.contains(&event.event_type))
&& (event.is_overall_delivery_successful == is_delivered);
check
});
let offset: usize = if let Some(offset) = offset {
if offset < 0 {
Err(errors::StorageError::MockDbError)?;
}
offset
.try_into()
.map_err(|_| errors::StorageError::MockDbError)?
} else {
0
};
let limit: usize = if let Some(limit) = limit {
if limit < 0 {
Err(errors::StorageError::MockDbError)?;
}
limit
.try_into()
.map_err(|_| errors::StorageError::MockDbError)?
} else {
usize::MAX
};
let events = events_iter
.skip(offset)
.take(limit)
.cloned()
.collect::<Vec<_>>();
let mut domain_events = Vec::with_capacity(events.len());
for event in events {
let domain_event = event
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?;
domain_events.push(domain_event);
}
Ok(domain_events)
}
async fn list_initial_events_by_profile_id_primary_object_id(
&self,
profile_id: &common_utils::id_type::ProfileId,
primary_object_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
let locked_events = self.events.lock().await;
let events = locked_events
.iter()
.filter(|event| {
event.business_profile_id == Some(profile_id.to_owned())
&& event.initial_attempt_id.as_deref() == Some(&event.event_id)
&& event.primary_object_id.as_str() == primary_object_id
})
.cloned()
.collect::<Vec<_>>();
let mut domain_events = Vec::with_capacity(events.len());
for event in events {
let domain_event = event
.convert(
self.get_keymanager_state()
.attach_printable("Missing KeyManagerState")?,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?;
domain_events.push(domain_event);
}
Ok(domain_events)
}
async fn find_initial_event_by_profile_id_initial_attempt_id(
&self,
profile_id: &common_utils::id_type::ProfileId,
initial_attempt_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Option<domain::Event>, errors::StorageError> {
let locked_events = self.events.lock().await;
let event_opt = locked_events.iter().find(|event| {
event.business_profile_id == Some(profile_id.to_owned())
&& event.event_id == initial_attempt_id
});
match event_opt {
Some(event) => {
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/authorization.rs | crates/router/src/db/authorization.rs | use diesel_models::authorization::AuthorizationUpdateInternal;
use error_stack::report;
use router_env::{instrument, tracing};
use super::{MockDb, Store};
use crate::{
connection,
core::errors::{self, CustomResult},
types::storage,
};
#[async_trait::async_trait]
pub trait AuthorizationInterface {
async fn insert_authorization(
&self,
authorization: storage::AuthorizationNew,
) -> CustomResult<storage::Authorization, errors::StorageError>;
async fn find_all_authorizations_by_merchant_id_payment_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
) -> CustomResult<Vec<storage::Authorization>, errors::StorageError>;
async fn update_authorization_by_merchant_id_authorization_id(
&self,
merchant_id: common_utils::id_type::MerchantId,
authorization_id: String,
authorization: storage::AuthorizationUpdate,
) -> CustomResult<storage::Authorization, errors::StorageError>;
}
#[async_trait::async_trait]
impl AuthorizationInterface for Store {
#[instrument(skip_all)]
async fn insert_authorization(
&self,
authorization: storage::AuthorizationNew,
) -> CustomResult<storage::Authorization, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
authorization
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_all_authorizations_by_merchant_id_payment_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
) -> CustomResult<Vec<storage::Authorization>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Authorization::find_by_merchant_id_payment_id(&conn, merchant_id, payment_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn update_authorization_by_merchant_id_authorization_id(
&self,
merchant_id: common_utils::id_type::MerchantId,
authorization_id: String,
authorization: storage::AuthorizationUpdate,
) -> CustomResult<storage::Authorization, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::Authorization::update_by_merchant_id_authorization_id(
&conn,
merchant_id,
authorization_id,
authorization,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
#[async_trait::async_trait]
impl AuthorizationInterface for MockDb {
async fn insert_authorization(
&self,
authorization: storage::AuthorizationNew,
) -> CustomResult<storage::Authorization, errors::StorageError> {
let mut authorizations = self.authorizations.lock().await;
if authorizations.iter().any(|authorization_inner| {
authorization_inner.authorization_id == authorization.authorization_id
}) {
Err(errors::StorageError::DuplicateValue {
entity: "authorization_id",
key: None,
})?
}
let authorization = storage::Authorization {
authorization_id: authorization.authorization_id,
merchant_id: authorization.merchant_id,
payment_id: authorization.payment_id,
amount: authorization.amount,
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
status: authorization.status,
error_code: authorization.error_code,
error_message: authorization.error_message,
connector_authorization_id: authorization.connector_authorization_id,
previously_authorized_amount: authorization.previously_authorized_amount,
};
authorizations.push(authorization.clone());
Ok(authorization)
}
async fn find_all_authorizations_by_merchant_id_payment_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
) -> CustomResult<Vec<storage::Authorization>, errors::StorageError> {
let authorizations = self.authorizations.lock().await;
let authorizations_found: Vec<storage::Authorization> = authorizations
.iter()
.filter(|a| a.merchant_id == *merchant_id && a.payment_id == *payment_id)
.cloned()
.collect();
Ok(authorizations_found)
}
async fn update_authorization_by_merchant_id_authorization_id(
&self,
merchant_id: common_utils::id_type::MerchantId,
authorization_id: String,
authorization_update: storage::AuthorizationUpdate,
) -> CustomResult<storage::Authorization, errors::StorageError> {
let mut authorizations = self.authorizations.lock().await;
authorizations
.iter_mut()
.find(|authorization| authorization.authorization_id == authorization_id && authorization.merchant_id == merchant_id)
.map(|authorization| {
let authorization_updated =
AuthorizationUpdateInternal::from(authorization_update)
.create_authorization(authorization.clone());
*authorization = authorization_updated.clone();
authorization_updated
})
.ok_or(
errors::StorageError::ValueNotFound(format!(
"cannot find authorization for authorization_id = {authorization_id} and merchant_id = {merchant_id:?}"
))
.into(),
)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/dashboard_metadata.rs | crates/router/src/db/dashboard_metadata.rs | use common_utils::id_type;
use diesel_models::{enums, user::dashboard_metadata as storage};
use error_stack::{report, ResultExt};
use router_env::{instrument, tracing};
use storage_impl::MockDb;
use crate::{
connection,
core::errors::{self, CustomResult},
services::Store,
};
#[async_trait::async_trait]
pub trait DashboardMetadataInterface {
async fn insert_metadata(
&self,
metadata: storage::DashboardMetadataNew,
) -> CustomResult<storage::DashboardMetadata, errors::StorageError>;
async fn update_metadata(
&self,
user_id: Option<String>,
merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
data_key: enums::DashboardMetadata,
dashboard_metadata_update: storage::DashboardMetadataUpdate,
) -> CustomResult<storage::DashboardMetadata, errors::StorageError>;
async fn find_user_scoped_dashboard_metadata(
&self,
user_id: &str,
merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
data_keys: Vec<enums::DashboardMetadata>,
) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError>;
async fn find_merchant_scoped_dashboard_metadata(
&self,
merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
data_keys: Vec<enums::DashboardMetadata>,
) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError>;
async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id(
&self,
user_id: &str,
merchant_id: &id_type::MerchantId,
) -> CustomResult<bool, errors::StorageError>;
async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key(
&self,
user_id: &str,
merchant_id: &id_type::MerchantId,
data_key: enums::DashboardMetadata,
) -> CustomResult<storage::DashboardMetadata, errors::StorageError>;
}
#[async_trait::async_trait]
impl DashboardMetadataInterface for Store {
#[instrument(skip_all)]
async fn insert_metadata(
&self,
metadata: storage::DashboardMetadataNew,
) -> CustomResult<storage::DashboardMetadata, errors::StorageError> {
let conn = connection::pg_accounts_connection_write(self).await?;
metadata
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn update_metadata(
&self,
user_id: Option<String>,
merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
data_key: enums::DashboardMetadata,
dashboard_metadata_update: storage::DashboardMetadataUpdate,
) -> CustomResult<storage::DashboardMetadata, errors::StorageError> {
let conn = connection::pg_accounts_connection_write(self).await?;
storage::DashboardMetadata::update(
&conn,
user_id,
merchant_id,
org_id,
data_key,
dashboard_metadata_update,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_user_scoped_dashboard_metadata(
&self,
user_id: &str,
merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
data_keys: Vec<enums::DashboardMetadata>,
) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> {
let conn = connection::pg_accounts_connection_read(self).await?;
storage::DashboardMetadata::find_user_scoped_dashboard_metadata(
&conn,
user_id.to_owned(),
merchant_id.to_owned(),
org_id.to_owned(),
data_keys,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_merchant_scoped_dashboard_metadata(
&self,
merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
data_keys: Vec<enums::DashboardMetadata>,
) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> {
let conn = connection::pg_accounts_connection_read(self).await?;
storage::DashboardMetadata::find_merchant_scoped_dashboard_metadata(
&conn,
merchant_id.to_owned(),
org_id.to_owned(),
data_keys,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id(
&self,
user_id: &str,
merchant_id: &id_type::MerchantId,
) -> CustomResult<bool, errors::StorageError> {
let conn = connection::pg_accounts_connection_write(self).await?;
storage::DashboardMetadata::delete_all_user_scoped_dashboard_metadata_by_merchant_id(
&conn,
user_id.to_owned(),
merchant_id.to_owned(),
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key(
&self,
user_id: &str,
merchant_id: &id_type::MerchantId,
data_key: enums::DashboardMetadata,
) -> CustomResult<storage::DashboardMetadata, errors::StorageError> {
let conn = connection::pg_accounts_connection_write(self).await?;
storage::DashboardMetadata::delete_user_scoped_dashboard_metadata_by_merchant_id_data_key(
&conn,
user_id.to_owned(),
merchant_id.to_owned(),
data_key,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
#[async_trait::async_trait]
impl DashboardMetadataInterface for MockDb {
async fn insert_metadata(
&self,
metadata: storage::DashboardMetadataNew,
) -> CustomResult<storage::DashboardMetadata, errors::StorageError> {
let mut dashboard_metadata = self.dashboard_metadata.lock().await;
if dashboard_metadata.iter().any(|metadata_inner| {
metadata_inner.user_id == metadata.user_id
&& metadata_inner.merchant_id == metadata.merchant_id
&& metadata_inner.org_id == metadata.org_id
&& metadata_inner.data_key == metadata.data_key
}) {
Err(errors::StorageError::DuplicateValue {
entity: "user_id, merchant_id, org_id and data_key",
key: None,
})?
}
let metadata_new = storage::DashboardMetadata {
id: i32::try_from(dashboard_metadata.len())
.change_context(errors::StorageError::MockDbError)?,
user_id: metadata.user_id,
merchant_id: metadata.merchant_id,
org_id: metadata.org_id,
data_key: metadata.data_key,
data_value: metadata.data_value,
created_by: metadata.created_by,
created_at: metadata.created_at,
last_modified_by: metadata.last_modified_by,
last_modified_at: metadata.last_modified_at,
};
dashboard_metadata.push(metadata_new.clone());
Ok(metadata_new)
}
async fn update_metadata(
&self,
user_id: Option<String>,
merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
data_key: enums::DashboardMetadata,
dashboard_metadata_update: storage::DashboardMetadataUpdate,
) -> CustomResult<storage::DashboardMetadata, errors::StorageError> {
let mut dashboard_metadata = self.dashboard_metadata.lock().await;
let dashboard_metadata_to_update = dashboard_metadata
.iter_mut()
.find(|metadata| {
metadata.user_id == user_id
&& metadata.merchant_id == merchant_id
&& metadata.org_id == org_id
&& metadata.data_key == data_key
})
.ok_or(errors::StorageError::MockDbError)?;
match dashboard_metadata_update {
storage::DashboardMetadataUpdate::UpdateData {
data_key,
data_value,
last_modified_by,
} => {
dashboard_metadata_to_update.data_key = data_key;
dashboard_metadata_to_update.data_value = data_value;
dashboard_metadata_to_update.last_modified_by = last_modified_by;
dashboard_metadata_to_update.last_modified_at = common_utils::date_time::now();
}
}
Ok(dashboard_metadata_to_update.clone())
}
async fn find_user_scoped_dashboard_metadata(
&self,
user_id: &str,
merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
data_keys: Vec<enums::DashboardMetadata>,
) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> {
let dashboard_metadata = self.dashboard_metadata.lock().await;
let query_result = dashboard_metadata
.iter()
.filter(|metadata_inner| {
metadata_inner
.user_id
.clone()
.map(|user_id_inner| user_id_inner == user_id)
.unwrap_or(false)
&& metadata_inner.merchant_id == *merchant_id
&& metadata_inner.org_id == *org_id
&& data_keys.contains(&metadata_inner.data_key)
})
.cloned()
.collect::<Vec<storage::DashboardMetadata>>();
if query_result.is_empty() {
return Err(errors::StorageError::ValueNotFound(format!(
"No dashboard_metadata available for user_id = {user_id},\
merchant_id = {merchant_id:?}, org_id = {org_id:?} and data_keys = {data_keys:?}",
))
.into());
}
Ok(query_result)
}
async fn find_merchant_scoped_dashboard_metadata(
&self,
merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
data_keys: Vec<enums::DashboardMetadata>,
) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> {
let dashboard_metadata = self.dashboard_metadata.lock().await;
let query_result = dashboard_metadata
.iter()
.filter(|metadata_inner| {
metadata_inner.merchant_id == *merchant_id
&& metadata_inner.org_id == *org_id
&& data_keys.contains(&metadata_inner.data_key)
})
.cloned()
.collect::<Vec<storage::DashboardMetadata>>();
if query_result.is_empty() {
return Err(errors::StorageError::ValueNotFound(format!(
"No dashboard_metadata available for merchant_id = {merchant_id:?},\
org_id = {org_id:?} and data_keyss = {data_keys:?}",
))
.into());
}
Ok(query_result)
}
async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id(
&self,
user_id: &str,
merchant_id: &id_type::MerchantId,
) -> CustomResult<bool, errors::StorageError> {
let mut dashboard_metadata = self.dashboard_metadata.lock().await;
let initial_len = dashboard_metadata.len();
dashboard_metadata.retain(|metadata_inner| {
!(metadata_inner
.user_id
.clone()
.map(|user_id_inner| user_id_inner == user_id)
.unwrap_or(false)
&& metadata_inner.merchant_id == *merchant_id)
});
if dashboard_metadata.len() == initial_len {
return Err(errors::StorageError::ValueNotFound(format!(
"No user available for user_id = {user_id} and merchant id = {merchant_id:?}"
))
.into());
}
Ok(true)
}
async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key(
&self,
user_id: &str,
merchant_id: &id_type::MerchantId,
data_key: enums::DashboardMetadata,
) -> CustomResult<storage::DashboardMetadata, errors::StorageError> {
let mut dashboard_metadata = self.dashboard_metadata.lock().await;
let index_to_remove = dashboard_metadata
.iter()
.position(|metadata_inner| {
metadata_inner.user_id.as_deref() == Some(user_id)
&& metadata_inner.merchant_id == *merchant_id
&& metadata_inner.data_key == data_key
})
.ok_or(errors::StorageError::ValueNotFound(
"No data found".to_string(),
))?;
let deleted_value = dashboard_metadata.swap_remove(index_to_remove);
Ok(deleted_value)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/refund.rs | crates/router/src/db/refund.rs | #[cfg(feature = "olap")]
use std::collections::{HashMap, HashSet};
#[cfg(feature = "olap")]
use common_utils::types::{ConnectorTransactionIdTrait, MinorUnit};
use diesel_models::{errors::DatabaseError, refund as diesel_refund};
use hyperswitch_domain_models::refunds;
use super::MockDb;
use crate::{
core::errors::{self, CustomResult},
types::storage::enums,
};
#[cfg(feature = "olap")]
const MAX_LIMIT: usize = 100;
#[async_trait::async_trait]
pub trait RefundInterface {
#[cfg(feature = "v1")]
async fn find_refund_by_internal_reference_id_merchant_id(
&self,
internal_reference_id: &str,
merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<diesel_refund::Refund, errors::StorageError>;
#[cfg(feature = "v1")]
async fn find_refund_by_payment_id_merchant_id(
&self,
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError>;
#[cfg(feature = "v1")]
async fn find_refund_by_merchant_id_refund_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
refund_id: &str,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<diesel_refund::Refund, errors::StorageError>;
#[cfg(feature = "v1")]
async fn find_refund_by_merchant_id_connector_refund_id_connector(
&self,
merchant_id: &common_utils::id_type::MerchantId,
connector_refund_id: &str,
connector: &str,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<diesel_refund::Refund, errors::StorageError>;
async fn update_refund(
&self,
this: diesel_refund::Refund,
refund: diesel_refund::RefundUpdate,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<diesel_refund::Refund, errors::StorageError>;
async fn find_refund_by_merchant_id_connector_transaction_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
connector_transaction_id: &str,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError>;
#[cfg(feature = "v2")]
async fn find_refund_by_id(
&self,
id: &common_utils::id_type::GlobalRefundId,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<diesel_refund::Refund, errors::StorageError>;
async fn insert_refund(
&self,
new: diesel_refund::RefundNew,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<diesel_refund::Refund, errors::StorageError>;
#[cfg(all(feature = "v1", feature = "olap"))]
async fn filter_refund_by_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
refund_details: &refunds::RefundListConstraints,
storage_scheme: enums::MerchantStorageScheme,
limit: i64,
offset: i64,
) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError>;
#[cfg(all(feature = "v2", feature = "olap"))]
async fn filter_refund_by_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
refund_details: refunds::RefundListConstraints,
storage_scheme: enums::MerchantStorageScheme,
limit: i64,
offset: i64,
) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError>;
#[cfg(all(feature = "v1", feature = "olap"))]
async fn filter_refund_by_meta_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
refund_details: &common_utils::types::TimeRange,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError>;
#[cfg(all(feature = "v1", feature = "olap"))]
async fn get_refund_status_with_count(
&self,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
constraints: &common_utils::types::TimeRange,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError>;
#[cfg(all(feature = "v1", feature = "olap"))]
async fn get_total_count_of_refunds(
&self,
merchant_id: &common_utils::id_type::MerchantId,
refund_details: &refunds::RefundListConstraints,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError>;
#[cfg(all(feature = "v2", feature = "olap"))]
async fn get_total_count_of_refunds(
&self,
merchant_id: &common_utils::id_type::MerchantId,
refund_details: refunds::RefundListConstraints,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError>;
}
#[cfg(not(feature = "kv_store"))]
mod storage {
use error_stack::report;
use hyperswitch_domain_models::refunds;
use router_env::{instrument, tracing};
use super::RefundInterface;
use crate::{
connection,
core::errors::{self, CustomResult},
services::Store,
types::storage::{self as storage_types, enums},
};
#[async_trait::async_trait]
impl RefundInterface for Store {
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_refund_by_internal_reference_id_merchant_id(
&self,
internal_reference_id: &str,
merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<diesel_refund::Refund, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
diesel_refund::Refund::find_by_internal_reference_id_merchant_id(
&conn,
internal_reference_id,
merchant_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn insert_refund(
&self,
new: diesel_refund::RefundNew,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<diesel_refund::Refund, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
new.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_refund_by_merchant_id_connector_transaction_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
connector_transaction_id: &str,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
diesel_refund::Refund::find_by_merchant_id_connector_transaction_id(
&conn,
merchant_id,
connector_transaction_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[cfg(feature = "v2")]
async fn find_refund_by_id(
&self,
id: &common_utils::id_type::GlobalRefundId,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<diesel_refund::Refund, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
diesel_refund::Refund::find_by_global_id(&conn, id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn update_refund(
&self,
this: diesel_refund::Refund,
refund: diesel_refund::RefundUpdate,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<diesel_refund::Refund, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
this.update(&conn, refund)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn update_refund(
&self,
this: diesel_refund::Refund,
refund: diesel_refund::RefundUpdate,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<diesel_refund::Refund, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
this.update_with_id(&conn, refund)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_refund_by_merchant_id_refund_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
refund_id: &str,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<diesel_refund::Refund, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
diesel_refund::Refund::find_by_merchant_id_refund_id(&conn, merchant_id, refund_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_refund_by_merchant_id_connector_refund_id_connector(
&self,
merchant_id: &common_utils::id_type::MerchantId,
connector_refund_id: &str,
connector: &str,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<diesel_refund::Refund, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
diesel_refund::Refund::find_by_merchant_id_connector_refund_id_connector(
&conn,
merchant_id,
connector_refund_id,
connector,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_refund_by_payment_id_merchant_id(
&self,
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
diesel_refund::Refund::find_by_payment_id_merchant_id(&conn, payment_id, merchant_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[cfg(all(feature = "v1", feature = "olap"))]
#[instrument(skip_all)]
async fn filter_refund_by_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
refund_details: &refunds::RefundListConstraints,
_storage_scheme: enums::MerchantStorageScheme,
limit: i64,
offset: i64,
) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
<diesel_models::refund::Refund as storage_types::RefundDbExt>::filter_by_constraints(
&conn,
merchant_id,
refund_details,
limit,
offset,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[cfg(all(feature = "v2", feature = "olap"))]
#[instrument(skip_all)]
async fn filter_refund_by_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
refund_details: refunds::RefundListConstraints,
_storage_scheme: enums::MerchantStorageScheme,
limit: i64,
offset: i64,
) -> CustomResult<Vec<diesel_models::refund::Refund>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
<diesel_models::refund::Refund as storage_types::RefundDbExt>::filter_by_constraints(
&conn,
merchant_id,
refund_details,
limit,
offset,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[cfg(all(feature = "v1", feature = "olap"))]
#[instrument(skip_all)]
async fn filter_refund_by_meta_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
refund_details: &api_models::payments::TimeRange,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
<diesel_models::refund::Refund as storage_types::RefundDbExt>::filter_by_meta_constraints(
&conn,
merchant_id,
refund_details,
)
.await
.map_err(|error|report!(errors::StorageError::from(error)))
}
#[cfg(all(feature = "v1", feature = "olap"))]
#[instrument(skip_all)]
async fn get_refund_status_with_count(
&self,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: &api_models::payments::TimeRange,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
<diesel_models::refund::Refund as storage_types::RefundDbExt>::get_refund_status_with_count(&conn, merchant_id,profile_id_list, time_range)
.await
.map_err(|error|report!(errors::StorageError::from(error)))
}
#[cfg(all(feature = "v1", feature = "olap"))]
#[instrument(skip_all)]
async fn get_total_count_of_refunds(
&self,
merchant_id: &common_utils::id_type::MerchantId,
refund_details: &refunds::RefundListConstraints,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
<diesel_models::refund::Refund as storage_types::RefundDbExt>::get_refunds_count(
&conn,
merchant_id,
refund_details,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[cfg(all(feature = "v2", feature = "olap"))]
#[instrument(skip_all)]
async fn get_total_count_of_refunds(
&self,
merchant_id: &common_utils::id_type::MerchantId,
refund_details: refunds::RefundListConstraints,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
<diesel_models::refund::Refund as storage_types::RefundDbExt>::get_refunds_count(
&conn,
merchant_id,
refund_details,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
}
#[cfg(feature = "kv_store")]
mod storage {
use common_utils::{
ext_traits::Encode, fallback_reverse_lookup_not_found, types::ConnectorTransactionIdTrait,
};
use diesel_models::refund as diesel_refund;
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::refunds;
use redis_interface::HsetnxReply;
use router_env::{instrument, tracing};
use storage_impl::redis::kv_store::{
decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey,
};
use super::RefundInterface;
use crate::{
connection,
core::errors::{self, utils::RedisErrorExt, CustomResult},
db::reverse_lookup::ReverseLookupInterface,
services::Store,
types::storage::{self as storage_types, enums, kv},
utils::db_utils,
};
#[async_trait::async_trait]
impl RefundInterface for Store {
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_refund_by_internal_reference_id_merchant_id(
&self,
internal_reference_id: &str,
merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<diesel_refund::Refund, errors::StorageError> {
let database_call = || async {
let conn = connection::pg_connection_read(self).await?;
diesel_refund::Refund::find_by_internal_reference_id_merchant_id(
&conn,
internal_reference_id,
merchant_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
};
let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_refund::Refund>(
self,
storage_scheme,
Op::Find,
))
.await;
match storage_scheme {
enums::MerchantStorageScheme::PostgresOnly => database_call().await,
enums::MerchantStorageScheme::RedisKv => {
let lookup_id = format!(
"ref_inter_ref_{}_{internal_reference_id}",
merchant_id.get_string_repr()
);
let lookup = fallback_reverse_lookup_not_found!(
self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)
.await,
database_call().await
);
let key = PartitionKey::CombinationKey {
combination: &lookup.pk_id,
};
Box::pin(db_utils::try_redis_get_else_try_database_get(
async {
Box::pin(kv_wrapper(
self,
KvOperation::<diesel_refund::Refund>::HGet(&lookup.sk_id),
key,
))
.await?
.try_into_hget()
},
database_call,
))
.await
}
}
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn insert_refund(
&self,
new: diesel_refund::RefundNew,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<diesel_refund::Refund, errors::StorageError> {
let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_refund::Refund>(
self,
storage_scheme,
Op::Insert,
))
.await;
match storage_scheme {
enums::MerchantStorageScheme::PostgresOnly => {
let conn = connection::pg_connection_write(self).await?;
new.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
enums::MerchantStorageScheme::RedisKv => {
let merchant_id = new.merchant_id.clone();
let payment_id = new.payment_id.clone();
let key = PartitionKey::MerchantIdPaymentId {
merchant_id: &merchant_id,
payment_id: &payment_id,
};
let key_str = key.to_string();
// TODO: need to add an application generated payment attempt id to distinguish between multiple attempts for the same payment id
// Check for database presence as well Maybe use a read replica here ?
let created_refund = diesel_refund::Refund {
refund_id: new.refund_id.clone(),
merchant_id: new.merchant_id.clone(),
attempt_id: new.attempt_id.clone(),
internal_reference_id: new.internal_reference_id.clone(),
payment_id: new.payment_id.clone(),
connector_transaction_id: new.connector_transaction_id.clone(),
connector: new.connector.clone(),
connector_refund_id: new.connector_refund_id.clone(),
external_reference_id: new.external_reference_id.clone(),
refund_type: new.refund_type,
total_amount: new.total_amount,
currency: new.currency,
refund_amount: new.refund_amount,
refund_status: new.refund_status,
sent_to_gateway: new.sent_to_gateway,
refund_error_message: None,
refund_error_code: None,
metadata: new.metadata.clone(),
refund_arn: new.refund_arn.clone(),
created_at: new.created_at,
modified_at: new.created_at,
description: new.description.clone(),
refund_reason: new.refund_reason.clone(),
profile_id: new.profile_id.clone(),
updated_by: new.updated_by.clone(),
merchant_connector_id: new.merchant_connector_id.clone(),
charges: new.charges.clone(),
split_refunds: new.split_refunds.clone(),
organization_id: new.organization_id.clone(),
unified_code: None,
unified_message: None,
processor_refund_data: new.processor_refund_data.clone(),
processor_transaction_data: new.processor_transaction_data.clone(),
issuer_error_code: None,
issuer_error_message: None,
// Below fields are deprecated. Please add any new fields above this line.
connector_refund_data: None,
connector_transaction_data: None,
};
let field = format!(
"pa_{}_ref_{}",
&created_refund.attempt_id, &created_refund.refund_id
);
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
insertable: Box::new(kv::Insertable::Refund(new)),
},
};
let mut reverse_lookups = vec![
storage_types::ReverseLookupNew {
sk_id: field.clone(),
lookup_id: format!(
"ref_ref_id_{}_{}",
created_refund.merchant_id.get_string_repr(),
created_refund.refund_id
),
pk_id: key_str.clone(),
source: "refund".to_string(),
updated_by: storage_scheme.to_string(),
},
// [#492]: A discussion is required on whether this is required?
storage_types::ReverseLookupNew {
sk_id: field.clone(),
lookup_id: format!(
"ref_inter_ref_{}_{}",
created_refund.merchant_id.get_string_repr(),
created_refund.internal_reference_id
),
pk_id: key_str.clone(),
source: "refund".to_string(),
updated_by: storage_scheme.to_string(),
},
];
if let Some(connector_refund_id) =
created_refund.to_owned().get_optional_connector_refund_id()
{
reverse_lookups.push(storage_types::ReverseLookupNew {
sk_id: field.clone(),
lookup_id: format!(
"ref_connector_{}_{}_{}",
created_refund.merchant_id.get_string_repr(),
connector_refund_id,
created_refund.connector
),
pk_id: key_str.clone(),
source: "refund".to_string(),
updated_by: storage_scheme.to_string(),
})
};
let rev_look = reverse_lookups
.into_iter()
.map(|rev| self.insert_reverse_lookup(rev, storage_scheme));
futures::future::try_join_all(rev_look).await?;
match Box::pin(kv_wrapper::<diesel_refund::Refund, _, _>(
self,
KvOperation::<diesel_refund::Refund>::HSetNx(
&field,
&created_refund,
redis_entry,
),
key,
))
.await
.map_err(|err| err.to_redis_failed_response(&key_str))?
.try_into_hsetnx()
{
Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue {
entity: "refund",
key: Some(created_refund.refund_id),
}
.into()),
Ok(HsetnxReply::KeySet) => Ok(created_refund),
Err(er) => Err(er).change_context(errors::StorageError::KVError),
}
}
}
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn insert_refund(
&self,
new: diesel_refund::RefundNew,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<diesel_refund::Refund, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
new.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_refund_by_merchant_id_connector_transaction_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
connector_transaction_id: &str,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError> {
let database_call = || async {
let conn = connection::pg_connection_read(self).await?;
diesel_refund::Refund::find_by_merchant_id_connector_transaction_id(
&conn,
merchant_id,
connector_transaction_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
};
let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_refund::Refund>(
self,
storage_scheme,
Op::Find,
))
.await;
match storage_scheme {
enums::MerchantStorageScheme::PostgresOnly => database_call().await,
enums::MerchantStorageScheme::RedisKv => {
let lookup_id = format!(
"pa_conn_trans_{}_{connector_transaction_id}",
merchant_id.get_string_repr()
);
let lookup = fallback_reverse_lookup_not_found!(
self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)
.await,
database_call().await
);
let key = PartitionKey::CombinationKey {
combination: &lookup.pk_id,
};
let pattern = db_utils::generate_hscan_pattern_for_refund(&lookup.sk_id);
Box::pin(db_utils::try_redis_get_else_try_database_get(
async {
Box::pin(kv_wrapper(
self,
KvOperation::<diesel_refund::Refund>::Scan(&pattern),
key,
))
.await?
.try_into_scan()
},
database_call,
))
.await
}
}
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn find_refund_by_merchant_id_connector_transaction_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
connector_transaction_id: &str,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<diesel_refund::Refund>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
diesel_refund::Refund::find_by_merchant_id_connector_transaction_id(
&conn,
merchant_id,
connector_transaction_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn update_refund(
&self,
this: diesel_refund::Refund,
refund: diesel_refund::RefundUpdate,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<diesel_refund::Refund, errors::StorageError> {
let merchant_id = this.merchant_id.clone();
let payment_id = this.payment_id.clone();
let key = PartitionKey::MerchantIdPaymentId {
merchant_id: &merchant_id,
payment_id: &payment_id,
};
let field = format!("pa_{}_ref_{}", &this.attempt_id, &this.refund_id);
let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_refund::Refund>(
self,
storage_scheme,
Op::Update(key.clone(), &field, Some(&this.updated_by)),
))
.await;
match storage_scheme {
enums::MerchantStorageScheme::PostgresOnly => {
let conn = connection::pg_connection_write(self).await?;
this.update(&conn, refund)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
enums::MerchantStorageScheme::RedisKv => {
let key_str = key.to_string();
let updated_refund = refund.clone().apply_changeset(this.clone());
let redis_value = updated_refund
.encode_to_string_of_json()
.change_context(errors::StorageError::SerializationFailed)?;
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Update {
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/routing_algorithm.rs | crates/router/src/db/routing_algorithm.rs | use diesel_models::routing_algorithm as routing_storage;
use error_stack::report;
use router_env::{instrument, tracing};
use storage_impl::mock_db::MockDb;
use crate::{
connection,
core::errors::{self, CustomResult},
services::Store,
};
type StorageResult<T> = CustomResult<T, errors::StorageError>;
#[async_trait::async_trait]
pub trait RoutingAlgorithmInterface {
async fn insert_routing_algorithm(
&self,
routing_algorithm: routing_storage::RoutingAlgorithm,
) -> StorageResult<routing_storage::RoutingAlgorithm>;
async fn find_routing_algorithm_by_profile_id_algorithm_id(
&self,
profile_id: &common_utils::id_type::ProfileId,
algorithm_id: &common_utils::id_type::RoutingId,
) -> StorageResult<routing_storage::RoutingAlgorithm>;
async fn find_routing_algorithm_by_algorithm_id_merchant_id(
&self,
algorithm_id: &common_utils::id_type::RoutingId,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<routing_storage::RoutingAlgorithm>;
async fn find_routing_algorithm_metadata_by_algorithm_id_profile_id(
&self,
algorithm_id: &common_utils::id_type::RoutingId,
profile_id: &common_utils::id_type::ProfileId,
) -> StorageResult<routing_storage::RoutingProfileMetadata>;
async fn list_routing_algorithm_metadata_by_profile_id(
&self,
profile_id: &common_utils::id_type::ProfileId,
limit: i64,
offset: i64,
) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>>;
async fn list_routing_algorithm_metadata_by_merchant_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
limit: i64,
offset: i64,
) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>>;
async fn list_routing_algorithm_metadata_by_merchant_id_transaction_type(
&self,
merchant_id: &common_utils::id_type::MerchantId,
transaction_type: &common_enums::TransactionType,
limit: i64,
offset: i64,
) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>>;
}
#[async_trait::async_trait]
impl RoutingAlgorithmInterface for Store {
#[instrument(skip_all)]
async fn insert_routing_algorithm(
&self,
routing_algorithm: routing_storage::RoutingAlgorithm,
) -> StorageResult<routing_storage::RoutingAlgorithm> {
let conn = connection::pg_connection_write(self).await?;
routing_algorithm
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_routing_algorithm_by_profile_id_algorithm_id(
&self,
profile_id: &common_utils::id_type::ProfileId,
algorithm_id: &common_utils::id_type::RoutingId,
) -> StorageResult<routing_storage::RoutingAlgorithm> {
let conn = connection::pg_connection_write(self).await?;
routing_storage::RoutingAlgorithm::find_by_algorithm_id_profile_id(
&conn,
algorithm_id,
profile_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_routing_algorithm_by_algorithm_id_merchant_id(
&self,
algorithm_id: &common_utils::id_type::RoutingId,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<routing_storage::RoutingAlgorithm> {
let conn = connection::pg_connection_write(self).await?;
routing_storage::RoutingAlgorithm::find_by_algorithm_id_merchant_id(
&conn,
algorithm_id,
merchant_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_routing_algorithm_metadata_by_algorithm_id_profile_id(
&self,
algorithm_id: &common_utils::id_type::RoutingId,
profile_id: &common_utils::id_type::ProfileId,
) -> StorageResult<routing_storage::RoutingProfileMetadata> {
let conn = connection::pg_connection_write(self).await?;
routing_storage::RoutingAlgorithm::find_metadata_by_algorithm_id_profile_id(
&conn,
algorithm_id,
profile_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn list_routing_algorithm_metadata_by_profile_id(
&self,
profile_id: &common_utils::id_type::ProfileId,
limit: i64,
offset: i64,
) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>> {
let conn = connection::pg_connection_write(self).await?;
routing_storage::RoutingAlgorithm::list_metadata_by_profile_id(
&conn, profile_id, limit, offset,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn list_routing_algorithm_metadata_by_merchant_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
limit: i64,
offset: i64,
) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>> {
let conn = connection::pg_connection_write(self).await?;
routing_storage::RoutingAlgorithm::list_metadata_by_merchant_id(
&conn,
merchant_id,
limit,
offset,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
async fn list_routing_algorithm_metadata_by_merchant_id_transaction_type(
&self,
merchant_id: &common_utils::id_type::MerchantId,
transaction_type: &common_enums::TransactionType,
limit: i64,
offset: i64,
) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>> {
let conn = connection::pg_connection_write(self).await?;
routing_storage::RoutingAlgorithm::list_metadata_by_merchant_id_transaction_type(
&conn,
merchant_id,
transaction_type,
limit,
offset,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
#[async_trait::async_trait]
impl RoutingAlgorithmInterface for MockDb {
async fn insert_routing_algorithm(
&self,
_routing_algorithm: routing_storage::RoutingAlgorithm,
) -> StorageResult<routing_storage::RoutingAlgorithm> {
Err(errors::StorageError::MockDbError)?
}
async fn find_routing_algorithm_by_profile_id_algorithm_id(
&self,
_profile_id: &common_utils::id_type::ProfileId,
_algorithm_id: &common_utils::id_type::RoutingId,
) -> StorageResult<routing_storage::RoutingAlgorithm> {
Err(errors::StorageError::MockDbError)?
}
async fn find_routing_algorithm_by_algorithm_id_merchant_id(
&self,
_algorithm_id: &common_utils::id_type::RoutingId,
_merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<routing_storage::RoutingAlgorithm> {
Err(errors::StorageError::MockDbError)?
}
async fn find_routing_algorithm_metadata_by_algorithm_id_profile_id(
&self,
_algorithm_id: &common_utils::id_type::RoutingId,
_profile_id: &common_utils::id_type::ProfileId,
) -> StorageResult<routing_storage::RoutingProfileMetadata> {
Err(errors::StorageError::MockDbError)?
}
async fn list_routing_algorithm_metadata_by_profile_id(
&self,
_profile_id: &common_utils::id_type::ProfileId,
_limit: i64,
_offset: i64,
) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>> {
Err(errors::StorageError::MockDbError)?
}
async fn list_routing_algorithm_metadata_by_merchant_id(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_limit: i64,
_offset: i64,
) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>> {
Err(errors::StorageError::MockDbError)?
}
async fn list_routing_algorithm_metadata_by_merchant_id_transaction_type(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_transaction_type: &common_enums::TransactionType,
_limit: i64,
_offset: i64,
) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>> {
Err(errors::StorageError::MockDbError)?
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/configs.rs | crates/router/src/db/configs.rs | pub use hyperswitch_domain_models::{
configs::{self, ConfigInterface},
errors::api_error_response,
};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router/src/db/hyperswitch_ai_interaction.rs | crates/router/src/db/hyperswitch_ai_interaction.rs | use diesel_models::hyperswitch_ai_interaction as storage;
use error_stack::report;
use router_env::{instrument, tracing};
use super::MockDb;
use crate::{
connection,
core::errors::{self, CustomResult},
services::Store,
};
#[async_trait::async_trait]
pub trait HyperswitchAiInteractionInterface {
async fn insert_hyperswitch_ai_interaction(
&self,
hyperswitch_ai_interaction: storage::HyperswitchAiInteractionNew,
) -> CustomResult<storage::HyperswitchAiInteraction, errors::StorageError>;
async fn list_hyperswitch_ai_interactions(
&self,
merchant_id: Option<common_utils::id_type::MerchantId>,
limit: i64,
offset: i64,
) -> CustomResult<Vec<storage::HyperswitchAiInteraction>, errors::StorageError>;
}
#[async_trait::async_trait]
impl HyperswitchAiInteractionInterface for Store {
#[instrument(skip_all)]
async fn insert_hyperswitch_ai_interaction(
&self,
hyperswitch_ai_interaction: storage::HyperswitchAiInteractionNew,
) -> CustomResult<storage::HyperswitchAiInteraction, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
hyperswitch_ai_interaction
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn list_hyperswitch_ai_interactions(
&self,
merchant_id: Option<common_utils::id_type::MerchantId>,
limit: i64,
offset: i64,
) -> CustomResult<Vec<storage::HyperswitchAiInteraction>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::HyperswitchAiInteraction::filter_by_optional_merchant_id(
&conn,
merchant_id.as_ref(),
limit,
offset,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
#[async_trait::async_trait]
impl HyperswitchAiInteractionInterface for MockDb {
async fn insert_hyperswitch_ai_interaction(
&self,
hyperswitch_ai_interaction: storage::HyperswitchAiInteractionNew,
) -> CustomResult<storage::HyperswitchAiInteraction, errors::StorageError> {
let mut hyperswitch_ai_interactions = self.hyperswitch_ai_interactions.lock().await;
let hyperswitch_ai_interaction = storage::HyperswitchAiInteraction {
id: hyperswitch_ai_interaction.id,
session_id: hyperswitch_ai_interaction.session_id,
user_id: hyperswitch_ai_interaction.user_id,
merchant_id: hyperswitch_ai_interaction.merchant_id,
profile_id: hyperswitch_ai_interaction.profile_id,
org_id: hyperswitch_ai_interaction.org_id,
role_id: hyperswitch_ai_interaction.role_id,
user_query: hyperswitch_ai_interaction.user_query,
response: hyperswitch_ai_interaction.response,
database_query: hyperswitch_ai_interaction.database_query,
interaction_status: hyperswitch_ai_interaction.interaction_status,
created_at: hyperswitch_ai_interaction.created_at,
};
hyperswitch_ai_interactions.push(hyperswitch_ai_interaction.clone());
Ok(hyperswitch_ai_interaction)
}
async fn list_hyperswitch_ai_interactions(
&self,
merchant_id: Option<common_utils::id_type::MerchantId>,
limit: i64,
offset: i64,
) -> CustomResult<Vec<storage::HyperswitchAiInteraction>, errors::StorageError> {
let hyperswitch_ai_interactions = self.hyperswitch_ai_interactions.lock().await;
let offset_usize = offset.try_into().unwrap_or_else(|_| {
common_utils::consts::DEFAULT_LIST_OFFSET
.try_into()
.unwrap_or(usize::MIN)
});
let limit_usize = limit.try_into().unwrap_or_else(|_| {
common_utils::consts::DEFAULT_LIST_LIMIT
.try_into()
.unwrap_or(usize::MAX)
});
let filtered_interactions: Vec<storage::HyperswitchAiInteraction> =
hyperswitch_ai_interactions
.iter()
.filter(
|interaction| match (merchant_id.as_ref(), &interaction.merchant_id) {
(Some(merchant_id), Some(interaction_merchant_id)) => {
interaction_merchant_id == &merchant_id.get_string_repr().to_owned()
}
(None, _) => true,
_ => false,
},
)
.skip(offset_usize)
.take(limit_usize)
.cloned()
.collect();
Ok(filtered_interactions)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.