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/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs | crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs | use std::collections::HashSet;
use api_models::analytics::{
payment_intents::{
PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetricsBucketIdentifier,
},
Granularity, TimeRange,
};
use common_utils::errors::ReportSwitchExt;
use diesel_models::enums as storage_enums;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
use super::PaymentIntentMetricRow;
use crate::{
enums::AuthInfo,
query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
};
#[derive(Default)]
pub(crate) struct PaymentProcessedAmount;
#[async_trait::async_trait]
impl<T> super::PaymentIntentMetric<T> for PaymentProcessedAmount
where
T: AnalyticsDataSource + super::PaymentIntentMetricAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
async fn load_metrics(
&self,
dimensions: &[PaymentIntentDimensions],
auth: &AuthInfo,
filters: &PaymentIntentFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>>
{
let mut query_builder: QueryBuilder<T> =
QueryBuilder::new(AnalyticsCollection::PaymentIntentSessionized);
let mut dimensions = dimensions.to_vec();
dimensions.push(PaymentIntentDimensions::PaymentIntentStatus);
for dim in dimensions.iter() {
query_builder.add_select_column(dim).switch()?;
}
query_builder
.add_select_column(Aggregate::Count {
field: None,
alias: Some("count"),
})
.switch()?;
query_builder
.add_select_column("(attempt_count = 1) as first_attempt")
.switch()?;
query_builder.add_select_column("currency").switch()?;
query_builder
.add_select_column(Aggregate::Sum {
field: "amount",
alias: Some("total"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Min {
field: "created_at",
alias: Some("start_bucket"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Max {
field: "created_at",
alias: Some("end_bucket"),
})
.switch()?;
filters.set_filter_clause(&mut query_builder).switch()?;
auth.set_filter_clause(&mut query_builder).switch()?;
time_range
.set_filter_clause(&mut query_builder)
.attach_printable("Error filtering time range")
.switch()?;
for dim in dimensions.iter() {
query_builder
.add_group_by_clause(dim)
.attach_printable("Error grouping by dimensions")
.switch()?;
}
query_builder
.add_group_by_clause("first_attempt")
.attach_printable("Error grouping by first_attempt")
.switch()?;
query_builder
.add_group_by_clause("currency")
.attach_printable("Error grouping by currency")
.switch()?;
if let Some(granularity) = granularity {
granularity
.set_group_by_clause(&mut query_builder)
.attach_printable("Error adding granularity")
.switch()?;
}
query_builder
.add_filter_clause(
PaymentIntentDimensions::PaymentIntentStatus,
storage_enums::IntentStatus::Succeeded,
)
.switch()?;
query_builder
.execute_query::<PaymentIntentMetricRow, _>(pool)
.await
.change_context(MetricsError::QueryBuildingError)?
.change_context(MetricsError::QueryExecutionFailure)?
.into_iter()
.map(|i| {
Ok((
PaymentIntentMetricsBucketIdentifier::new(
None,
i.currency.as_ref().map(|i| i.0),
i.profile_id.clone(),
i.connector.clone(),
i.authentication_type.as_ref().map(|i| i.0),
i.payment_method.clone(),
i.payment_method_type.clone(),
i.card_network.clone(),
i.merchant_id.clone(),
i.card_last_4.clone(),
i.card_issuer.clone(),
i.error_reason.clone(),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
_ => time_range.start_time,
},
end_time: granularity.as_ref().map_or_else(
|| Ok(time_range.end_time),
|g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
)?,
},
),
i,
))
})
.collect::<error_stack::Result<
HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>,
crate::query::PostProcessingError,
>>()
.change_context(MetricsError::PostProcessingFailure)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/payment_intents/metrics/sessionized_metrics/smart_retried_amount.rs | crates/analytics/src/payment_intents/metrics/sessionized_metrics/smart_retried_amount.rs | use std::collections::HashSet;
use api_models::{
analytics::{
payment_intents::{
PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetricsBucketIdentifier,
},
Granularity, TimeRange,
},
enums::IntentStatus,
};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
use super::PaymentIntentMetricRow;
use crate::{
enums::AuthInfo,
query::{
Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql,
Window,
},
types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
};
#[derive(Default)]
pub(crate) struct SmartRetriedAmount;
#[async_trait::async_trait]
impl<T> super::PaymentIntentMetric<T> for SmartRetriedAmount
where
T: AnalyticsDataSource + super::PaymentIntentMetricAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
async fn load_metrics(
&self,
dimensions: &[PaymentIntentDimensions],
auth: &AuthInfo,
filters: &PaymentIntentFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>>
{
let mut query_builder: QueryBuilder<T> =
QueryBuilder::new(AnalyticsCollection::PaymentIntentSessionized);
for dim in dimensions.iter() {
query_builder.add_select_column(dim).switch()?;
}
query_builder
.add_select_column(Aggregate::Sum {
field: "amount",
alias: Some("total"),
})
.switch()?;
query_builder
.add_select_column("(attempt_count = 1) as first_attempt")
.switch()?;
query_builder.add_select_column("currency").switch()?;
query_builder
.add_select_column(Aggregate::Min {
field: "created_at",
alias: Some("start_bucket"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Max {
field: "created_at",
alias: Some("end_bucket"),
})
.switch()?;
filters.set_filter_clause(&mut query_builder).switch()?;
auth.set_filter_clause(&mut query_builder).switch()?;
query_builder
.add_custom_filter_clause("attempt_count", "1", FilterTypes::Gt)
.switch()?;
query_builder
.add_custom_filter_clause("status", IntentStatus::Succeeded, FilterTypes::Equal)
.switch()?;
time_range
.set_filter_clause(&mut query_builder)
.attach_printable("Error filtering time range")
.switch()?;
for dim in dimensions.iter() {
query_builder
.add_group_by_clause(dim)
.attach_printable("Error grouping by dimensions")
.switch()?;
}
query_builder
.add_group_by_clause("first_attempt")
.attach_printable("Error grouping by first_attempt")
.switch()?;
query_builder
.add_group_by_clause("currency")
.attach_printable("Error grouping by currency")
.switch()?;
if let Some(granularity) = granularity {
granularity
.set_group_by_clause(&mut query_builder)
.attach_printable("Error adding granularity")
.switch()?;
}
query_builder
.execute_query::<PaymentIntentMetricRow, _>(pool)
.await
.change_context(MetricsError::QueryBuildingError)?
.change_context(MetricsError::QueryExecutionFailure)?
.into_iter()
.map(|i| {
Ok((
PaymentIntentMetricsBucketIdentifier::new(
i.status.as_ref().map(|i| i.0),
i.currency.as_ref().map(|i| i.0),
i.profile_id.clone(),
i.connector.clone(),
i.authentication_type.as_ref().map(|i| i.0),
i.payment_method.clone(),
i.payment_method_type.clone(),
i.card_network.clone(),
i.merchant_id.clone(),
i.card_last_4.clone(),
i.card_issuer.clone(),
i.error_reason.clone(),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
_ => time_range.start_time,
},
end_time: granularity.as_ref().map_or_else(
|| Ok(time_range.end_time),
|g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
)?,
},
),
i,
))
})
.collect::<error_stack::Result<
HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>,
crate::query::PostProcessingError,
>>()
.change_context(MetricsError::PostProcessingFailure)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_success_rate.rs | crates/analytics/src/payment_intents/metrics/sessionized_metrics/payments_success_rate.rs | use std::collections::HashSet;
use api_models::analytics::{
payment_intents::{
PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetricsBucketIdentifier,
},
Granularity, TimeRange,
};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
use super::PaymentIntentMetricRow;
use crate::{
enums::AuthInfo,
query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
};
#[derive(Default)]
pub(crate) struct PaymentsSuccessRate;
#[async_trait::async_trait]
impl<T> super::PaymentIntentMetric<T> for PaymentsSuccessRate
where
T: AnalyticsDataSource + super::PaymentIntentMetricAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
async fn load_metrics(
&self,
dimensions: &[PaymentIntentDimensions],
auth: &AuthInfo,
filters: &PaymentIntentFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>>
{
let mut query_builder: QueryBuilder<T> =
QueryBuilder::new(AnalyticsCollection::PaymentIntentSessionized);
let mut dimensions = dimensions.to_vec();
dimensions.push(PaymentIntentDimensions::PaymentIntentStatus);
for dim in dimensions.iter() {
query_builder.add_select_column(dim).switch()?;
}
query_builder
.add_select_column(Aggregate::Count {
field: None,
alias: Some("count"),
})
.switch()?;
query_builder
.add_select_column("(attempt_count = 1) as first_attempt".to_string())
.switch()?;
query_builder
.add_select_column(Aggregate::Min {
field: "created_at",
alias: Some("start_bucket"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Max {
field: "created_at",
alias: Some("end_bucket"),
})
.switch()?;
filters.set_filter_clause(&mut query_builder).switch()?;
auth.set_filter_clause(&mut query_builder).switch()?;
time_range
.set_filter_clause(&mut query_builder)
.attach_printable("Error filtering time range")
.switch()?;
for dim in dimensions.iter() {
query_builder
.add_group_by_clause(dim)
.attach_printable("Error grouping by dimensions")
.switch()?;
}
query_builder
.add_group_by_clause("first_attempt")
.attach_printable("Error grouping by first_attempt")
.switch()?;
if let Some(granularity) = granularity {
granularity
.set_group_by_clause(&mut query_builder)
.attach_printable("Error adding granularity")
.switch()?;
}
query_builder
.execute_query::<PaymentIntentMetricRow, _>(pool)
.await
.change_context(MetricsError::QueryBuildingError)?
.change_context(MetricsError::QueryExecutionFailure)?
.into_iter()
.map(|i| {
Ok((
PaymentIntentMetricsBucketIdentifier::new(
None,
i.currency.as_ref().map(|i| i.0),
i.profile_id.clone(),
i.connector.clone(),
i.authentication_type.as_ref().map(|i| i.0),
i.payment_method.clone(),
i.payment_method_type.clone(),
i.card_network.clone(),
i.merchant_id.clone(),
i.card_last_4.clone(),
i.card_issuer.clone(),
i.error_reason.clone(),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
_ => time_range.start_time,
},
end_time: granularity.as_ref().map_or_else(
|| Ok(time_range.end_time),
|g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
)?,
},
),
i,
))
})
.collect::<error_stack::Result<
HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>,
crate::query::PostProcessingError,
>>()
.change_context(MetricsError::PostProcessingFailure)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/api_event/filters.rs | crates/analytics/src/api_event/filters.rs | use api_models::analytics::{api_event::ApiEventDimensions, Granularity, TimeRange};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
use crate::{
query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window},
types::{AnalyticsCollection, AnalyticsDataSource, FiltersError, FiltersResult, LoadRow},
};
pub trait ApiEventFilterAnalytics: LoadRow<ApiEventFilter> {}
pub async fn get_api_event_filter_for_dimension<T>(
dimension: ApiEventDimensions,
merchant_id: &common_utils::id_type::MerchantId,
time_range: &TimeRange,
pool: &T,
) -> FiltersResult<Vec<ApiEventFilter>>
where
T: AnalyticsDataSource + ApiEventFilterAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::ApiEvents);
query_builder.add_select_column(dimension).switch()?;
time_range
.set_filter_clause(&mut query_builder)
.attach_printable("Error filtering time range")
.switch()?;
query_builder
.add_filter_clause("merchant_id", merchant_id)
.switch()?;
query_builder.set_distinct();
query_builder
.execute_query::<ApiEventFilter, _>(pool)
.await
.change_context(FiltersError::QueryBuildingError)?
.change_context(FiltersError::QueryExecutionFailure)
}
#[derive(Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)]
pub struct ApiEventFilter {
pub status_code: Option<i32>,
pub flow_type: Option<String>,
pub api_flow: Option<String>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/api_event/core.rs | crates/analytics/src/api_event/core.rs | use std::collections::HashMap;
use api_models::analytics::{
api_event::{
ApiEventMetricsBucketIdentifier, ApiEventMetricsBucketValue, ApiLogsRequest,
ApiMetricsBucketResponse,
},
AnalyticsMetadata, ApiEventFiltersResponse, GetApiEventFiltersRequest,
GetApiEventMetricRequest, MetricsResponse,
};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use router_env::{
instrument, logger,
tracing::{self, Instrument},
};
use super::{
events::{get_api_event, ApiLogsResult},
metrics::ApiEventMetricRow,
};
use crate::{
errors::{AnalyticsError, AnalyticsResult},
metrics,
types::FiltersError,
AnalyticsProvider,
};
#[instrument(skip_all)]
pub async fn api_events_core(
pool: &AnalyticsProvider,
req: ApiLogsRequest,
merchant_id: &common_utils::id_type::MerchantId,
) -> AnalyticsResult<Vec<ApiLogsResult>> {
let data = match pool {
AnalyticsProvider::Sqlx(_) => Err(FiltersError::NotImplemented(
"API Events not implemented for SQLX",
))
.attach_printable("SQL Analytics is not implemented for API Events"),
AnalyticsProvider::Clickhouse(pool) => get_api_event(merchant_id, req, pool).await,
AnalyticsProvider::CombinedSqlx(_sqlx_pool, ckh_pool)
| AnalyticsProvider::CombinedCkh(_sqlx_pool, ckh_pool) => {
get_api_event(merchant_id, req, ckh_pool).await
}
}
.switch()?;
Ok(data)
}
pub async fn get_filters(
pool: &AnalyticsProvider,
req: GetApiEventFiltersRequest,
merchant_id: &common_utils::id_type::MerchantId,
) -> AnalyticsResult<ApiEventFiltersResponse> {
use api_models::analytics::{api_event::ApiEventDimensions, ApiEventFilterValue};
use super::filters::get_api_event_filter_for_dimension;
use crate::api_event::filters::ApiEventFilter;
let mut res = ApiEventFiltersResponse::default();
for dim in req.group_by_names {
let values = match pool {
AnalyticsProvider::Sqlx(_pool) => Err(FiltersError::NotImplemented(
"API Events not implemented for SQLX",
))
.attach_printable("SQL Analytics is not implemented for API Events"),
AnalyticsProvider::Clickhouse(ckh_pool)
| AnalyticsProvider::CombinedSqlx(_, ckh_pool)
| AnalyticsProvider::CombinedCkh(_, ckh_pool) => {
get_api_event_filter_for_dimension(dim, merchant_id, &req.time_range, ckh_pool)
.await
}
}
.switch()?
.into_iter()
.filter_map(|fil: ApiEventFilter| match dim {
ApiEventDimensions::StatusCode => fil.status_code.map(|i| i.to_string()),
ApiEventDimensions::FlowType => fil.flow_type,
ApiEventDimensions::ApiFlow => fil.api_flow,
})
.collect::<Vec<String>>();
res.query_data.push(ApiEventFilterValue {
dimension: dim,
values,
})
}
Ok(res)
}
#[instrument(skip_all)]
pub async fn get_api_event_metrics(
pool: &AnalyticsProvider,
merchant_id: &common_utils::id_type::MerchantId,
req: GetApiEventMetricRequest,
) -> AnalyticsResult<MetricsResponse<ApiMetricsBucketResponse>> {
let mut metrics_accumulator: HashMap<ApiEventMetricsBucketIdentifier, ApiEventMetricRow> =
HashMap::new();
let mut set = tokio::task::JoinSet::new();
for metric_type in req.metrics.iter().cloned() {
let req = req.clone();
let pool = pool.clone();
let task_span = tracing::debug_span!(
"analytics_api_metrics_query",
api_event_metric = metric_type.as_ref()
);
// TODO: lifetime issues with joinset,
// can be optimized away if joinset lifetime requirements are relaxed
let merchant_id_scoped = merchant_id.to_owned();
set.spawn(
async move {
let data = pool
.get_api_event_metrics(
&metric_type,
&req.group_by_names.clone(),
&merchant_id_scoped,
&req.filters,
req.time_series.map(|t| t.granularity),
&req.time_range,
)
.await
.change_context(AnalyticsError::UnknownError);
(metric_type, data)
}
.instrument(task_span),
);
}
while let Some((metric, data)) = set
.join_next()
.await
.transpose()
.change_context(AnalyticsError::UnknownError)?
{
let data = data?;
let attributes = router_env::metric_attributes!(
("metric_type", metric.to_string()),
("source", pool.to_string()),
);
let value = u64::try_from(data.len());
if let Ok(val) = value {
metrics::BUCKETS_FETCHED.record(val, attributes);
logger::debug!("Attributes: {:?}, Buckets fetched: {}", attributes, val);
}
for (id, value) in data {
metrics_accumulator
.entry(id)
.and_modify(|data| {
data.api_count = data.api_count.or(value.api_count);
data.status_code_count = data.status_code_count.or(value.status_code_count);
data.latency = data.latency.or(value.latency);
})
.or_insert(value);
}
}
let query_data: Vec<ApiMetricsBucketResponse> = metrics_accumulator
.into_iter()
.map(|(id, val)| ApiMetricsBucketResponse {
values: ApiEventMetricsBucketValue {
latency: val.latency,
api_count: val.api_count,
status_code_count: val.status_code_count,
},
dimensions: id,
})
.collect();
Ok(MetricsResponse {
query_data,
meta_data: [AnalyticsMetadata {
current_time_range: req.time_range,
}],
})
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/api_event/types.rs | crates/analytics/src/api_event/types.rs | use api_models::analytics::api_event::{ApiEventDimensions, ApiEventFilters};
use error_stack::ResultExt;
use crate::{
query::{QueryBuilder, QueryFilter, QueryResult, ToSql},
types::{AnalyticsCollection, AnalyticsDataSource},
};
impl<T> QueryFilter<T> for ApiEventFilters
where
T: AnalyticsDataSource,
AnalyticsCollection: ToSql<T>,
{
fn set_filter_clause(&self, builder: &mut QueryBuilder<T>) -> QueryResult<()> {
if !self.status_code.is_empty() {
builder
.add_filter_in_range_clause(ApiEventDimensions::StatusCode, &self.status_code)
.attach_printable("Error adding status_code filter")?;
}
if !self.flow_type.is_empty() {
builder
.add_filter_in_range_clause(ApiEventDimensions::FlowType, &self.flow_type)
.attach_printable("Error adding flow_type filter")?;
}
if !self.api_flow.is_empty() {
builder
.add_filter_in_range_clause(ApiEventDimensions::ApiFlow, &self.api_flow)
.attach_printable("Error adding api_name filter")?;
}
Ok(())
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/api_event/events.rs | crates/analytics/src/api_event/events.rs | use api_models::analytics::{
api_event::{ApiLogsRequest, QueryType},
Granularity,
};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use router_env::Flow;
use time::PrimitiveDateTime;
use crate::{
query::{Aggregate, GroupByClause, QueryBuilder, ToSql, Window},
types::{AnalyticsCollection, AnalyticsDataSource, FiltersError, FiltersResult, LoadRow},
};
pub trait ApiLogsFilterAnalytics: LoadRow<ApiLogsResult> {}
pub async fn get_api_event<T>(
merchant_id: &common_utils::id_type::MerchantId,
query_param: ApiLogsRequest,
pool: &T,
) -> FiltersResult<Vec<ApiLogsResult>>
where
T: AnalyticsDataSource + ApiLogsFilterAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::ApiEvents);
query_builder.add_select_column("*").switch()?;
query_builder
.add_filter_clause("merchant_id", merchant_id)
.switch()?;
match query_param.query_param {
QueryType::Payment { payment_id } => {
query_builder
.add_filter_clause("payment_id", &payment_id)
.switch()?;
query_builder
.add_filter_in_range_clause(
"api_flow",
&[
Flow::PaymentsCancel,
Flow::PaymentsCapture,
Flow::PaymentsConfirm,
Flow::PaymentsCreate,
Flow::PaymentsStart,
Flow::PaymentsUpdate,
Flow::RefundsCreate,
Flow::RefundsUpdate,
Flow::DisputesEvidenceSubmit,
Flow::AttachDisputeEvidence,
Flow::RetrieveDisputeEvidence,
Flow::IncomingWebhookReceive,
Flow::PaymentMethodsList,
Flow::CustomerPaymentMethodsList,
Flow::PaymentsSessionToken,
],
)
.switch()?;
}
QueryType::Refund {
payment_id,
refund_id,
} => {
query_builder
.add_filter_clause("payment_id", &payment_id)
.switch()?;
query_builder
.add_filter_clause("refund_id", refund_id)
.switch()?;
query_builder
.add_filter_in_range_clause(
"api_flow",
&[
Flow::RefundsCreate,
Flow::RefundsUpdate,
Flow::IncomingWebhookReceive,
],
)
.switch()?;
}
QueryType::Dispute {
payment_id,
dispute_id,
} => {
query_builder
.add_filter_clause("payment_id", &payment_id)
.switch()?;
query_builder
.add_filter_clause("dispute_id", dispute_id)
.switch()?;
query_builder
.add_filter_in_range_clause(
"api_flow",
&[
Flow::DisputesEvidenceSubmit,
Flow::AttachDisputeEvidence,
Flow::RetrieveDisputeEvidence,
],
)
.switch()?;
}
}
//TODO!: update the execute_query function to return reports instead of plain errors...
query_builder
.execute_query::<ApiLogsResult, _>(pool)
.await
.change_context(FiltersError::QueryBuildingError)?
.change_context(FiltersError::QueryExecutionFailure)
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct ApiLogsResult {
pub merchant_id: common_utils::id_type::MerchantId,
pub payment_id: Option<common_utils::id_type::PaymentId>,
pub refund_id: Option<String>,
pub payment_method_id: Option<String>,
pub payment_method: Option<String>,
pub payment_method_type: Option<String>,
pub customer_id: Option<String>,
pub user_id: Option<String>,
pub connector: Option<String>,
pub request_id: Option<String>,
pub flow_type: String,
pub api_flow: String,
pub api_auth_type: Option<String>,
pub request: String,
pub response: Option<String>,
pub error: Option<String>,
pub authentication_data: Option<String>,
pub status_code: u16,
pub latency: Option<u128>,
pub user_agent: Option<String>,
pub hs_latency: Option<u128>,
pub ip_addr: Option<String>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
pub http_method: Option<String>,
pub url_path: Option<String>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/api_event/metrics.rs | crates/analytics/src/api_event/metrics.rs | use api_models::analytics::{
api_event::{
ApiEventDimensions, ApiEventFilters, ApiEventMetrics, ApiEventMetricsBucketIdentifier,
},
Granularity, TimeRange,
};
use time::PrimitiveDateTime;
use crate::{
query::{Aggregate, GroupByClause, ToSql, Window},
types::{AnalyticsCollection, AnalyticsDataSource, LoadRow, MetricsResult},
};
mod api_count;
pub mod latency;
mod status_code_count;
use std::collections::HashSet;
use api_count::ApiCount;
use latency::MaxLatency;
use status_code_count::StatusCodeCount;
use self::latency::LatencyAvg;
#[derive(Debug, PartialEq, Eq, serde::Deserialize, Hash)]
pub struct ApiEventMetricRow {
pub latency: Option<u64>,
pub api_count: Option<u64>,
pub status_code_count: Option<u64>,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub start_bucket: Option<PrimitiveDateTime>,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub end_bucket: Option<PrimitiveDateTime>,
}
pub trait ApiEventMetricAnalytics: LoadRow<ApiEventMetricRow> + LoadRow<LatencyAvg> {}
#[async_trait::async_trait]
pub trait ApiEventMetric<T>
where
T: AnalyticsDataSource + ApiEventMetricAnalytics,
{
async fn load_metrics(
&self,
dimensions: &[ApiEventDimensions],
merchant_id: &common_utils::id_type::MerchantId,
filters: &ApiEventFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<HashSet<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>>;
}
#[async_trait::async_trait]
impl<T> ApiEventMetric<T> for ApiEventMetrics
where
T: AnalyticsDataSource + ApiEventMetricAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
async fn load_metrics(
&self,
dimensions: &[ApiEventDimensions],
merchant_id: &common_utils::id_type::MerchantId,
filters: &ApiEventFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<HashSet<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>> {
match self {
Self::Latency => {
MaxLatency
.load_metrics(
dimensions,
merchant_id,
filters,
granularity,
time_range,
pool,
)
.await
}
Self::ApiCount => {
ApiCount
.load_metrics(
dimensions,
merchant_id,
filters,
granularity,
time_range,
pool,
)
.await
}
Self::StatusCodeCount => {
StatusCodeCount
.load_metrics(
dimensions,
merchant_id,
filters,
granularity,
time_range,
pool,
)
.await
}
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/api_event/metrics/latency.rs | crates/analytics/src/api_event/metrics/latency.rs | use std::collections::HashSet;
use api_models::analytics::{
api_event::{ApiEventDimensions, ApiEventFilters, ApiEventMetricsBucketIdentifier},
Granularity, TimeRange,
};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
use super::ApiEventMetricRow;
use crate::{
query::{
Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql,
Window,
},
types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
};
#[derive(Default)]
pub(super) struct MaxLatency;
#[async_trait::async_trait]
impl<T> super::ApiEventMetric<T> for MaxLatency
where
T: AnalyticsDataSource + super::ApiEventMetricAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
async fn load_metrics(
&self,
_dimensions: &[ApiEventDimensions],
merchant_id: &common_utils::id_type::MerchantId,
filters: &ApiEventFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<HashSet<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>> {
let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::ApiEvents);
query_builder
.add_select_column(Aggregate::Sum {
field: "latency",
alias: Some("latency_sum"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Count {
field: Some("latency"),
alias: Some("latency_count"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Min {
field: "created_at",
alias: Some("start_bucket"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Max {
field: "created_at",
alias: Some("end_bucket"),
})
.switch()?;
if let Some(granularity) = granularity {
granularity
.set_group_by_clause(&mut query_builder)
.attach_printable("Error adding granularity")
.switch()?;
}
filters.set_filter_clause(&mut query_builder).switch()?;
query_builder
.add_filter_clause("merchant_id", merchant_id)
.switch()?;
time_range
.set_filter_clause(&mut query_builder)
.attach_printable("Error filtering time range")
.switch()?;
query_builder
.add_custom_filter_clause("request", "10.63.134.6", FilterTypes::NotLike)
.attach_printable("Error filtering out locker IP")
.switch()?;
query_builder
.execute_query::<LatencyAvg, _>(pool)
.await
.change_context(MetricsError::QueryBuildingError)?
.change_context(MetricsError::QueryExecutionFailure)?
.into_iter()
.map(|i| {
Ok((
ApiEventMetricsBucketIdentifier::new(TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
_ => time_range.start_time,
},
end_time: granularity.as_ref().map_or_else(
|| Ok(time_range.end_time),
|g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
)?,
}),
ApiEventMetricRow {
latency: if i.latency_count != 0 {
Some(i.latency_sum.unwrap_or(0) / i.latency_count)
} else {
None
},
api_count: None,
status_code_count: None,
start_bucket: i.start_bucket,
end_bucket: i.end_bucket,
},
))
})
.collect::<error_stack::Result<
HashSet<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>,
crate::query::PostProcessingError,
>>()
.change_context(MetricsError::PostProcessingFailure)
}
}
#[derive(Debug, PartialEq, Eq, serde::Deserialize)]
pub struct LatencyAvg {
latency_sum: Option<u64>,
latency_count: u64,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub start_bucket: Option<PrimitiveDateTime>,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub end_bucket: Option<PrimitiveDateTime>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/api_event/metrics/status_code_count.rs | crates/analytics/src/api_event/metrics/status_code_count.rs | use std::collections::HashSet;
use api_models::analytics::{
api_event::{ApiEventDimensions, ApiEventFilters, ApiEventMetricsBucketIdentifier},
Granularity, TimeRange,
};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
use super::ApiEventMetricRow;
use crate::{
query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
};
#[derive(Default)]
pub(super) struct StatusCodeCount;
#[async_trait::async_trait]
impl<T> super::ApiEventMetric<T> for StatusCodeCount
where
T: AnalyticsDataSource + super::ApiEventMetricAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
async fn load_metrics(
&self,
_dimensions: &[ApiEventDimensions],
merchant_id: &common_utils::id_type::MerchantId,
filters: &ApiEventFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<HashSet<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>> {
let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::ApiEvents);
query_builder
.add_select_column(Aggregate::Count {
field: Some("status_code"),
alias: Some("status_code_count"),
})
.switch()?;
filters.set_filter_clause(&mut query_builder).switch()?;
query_builder
.add_filter_clause("merchant_id", merchant_id)
.switch()?;
time_range
.set_filter_clause(&mut query_builder)
.attach_printable("Error filtering time range")
.switch()?;
query_builder
.add_select_column(Aggregate::Min {
field: "created_at",
alias: Some("start_bucket"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Max {
field: "created_at",
alias: Some("end_bucket"),
})
.switch()?;
if let Some(granularity) = granularity {
granularity
.set_group_by_clause(&mut query_builder)
.attach_printable("Error adding granularity")
.switch()?;
}
query_builder
.execute_query::<ApiEventMetricRow, _>(pool)
.await
.change_context(MetricsError::QueryBuildingError)?
.change_context(MetricsError::QueryExecutionFailure)?
.into_iter()
.map(|i| {
Ok((
ApiEventMetricsBucketIdentifier::new(TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
_ => time_range.start_time,
},
end_time: granularity.as_ref().map_or_else(
|| Ok(time_range.end_time),
|g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
)?,
}),
i,
))
})
.collect::<error_stack::Result<
HashSet<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>,
crate::query::PostProcessingError,
>>()
.change_context(MetricsError::PostProcessingFailure)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/api_event/metrics/api_count.rs | crates/analytics/src/api_event/metrics/api_count.rs | use std::collections::HashSet;
use api_models::analytics::{
api_event::{ApiEventDimensions, ApiEventFilters, ApiEventMetricsBucketIdentifier},
Granularity, TimeRange,
};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
use super::ApiEventMetricRow;
use crate::{
query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
};
#[derive(Default)]
pub(super) struct ApiCount;
#[async_trait::async_trait]
impl<T> super::ApiEventMetric<T> for ApiCount
where
T: AnalyticsDataSource + super::ApiEventMetricAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
async fn load_metrics(
&self,
_dimensions: &[ApiEventDimensions],
merchant_id: &common_utils::id_type::MerchantId,
filters: &ApiEventFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<HashSet<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>> {
let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::ApiEvents);
query_builder
.add_select_column(Aggregate::Count {
field: None,
alias: Some("api_count"),
})
.switch()?;
if !filters.flow_type.is_empty() {
query_builder
.add_filter_in_range_clause(ApiEventDimensions::FlowType, &filters.flow_type)
.attach_printable("Error adding flow_type filter")
.switch()?;
}
query_builder
.add_select_column(Aggregate::Min {
field: "created_at",
alias: Some("start_bucket"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Max {
field: "created_at",
alias: Some("end_bucket"),
})
.switch()?;
if let Some(granularity) = granularity {
granularity
.set_group_by_clause(&mut query_builder)
.attach_printable("Error adding granularity")
.switch()?;
}
query_builder
.add_filter_clause("merchant_id", merchant_id)
.switch()?;
time_range
.set_filter_clause(&mut query_builder)
.attach_printable("Error filtering time range")
.switch()?;
query_builder
.execute_query::<ApiEventMetricRow, _>(pool)
.await
.change_context(MetricsError::QueryBuildingError)?
.change_context(MetricsError::QueryExecutionFailure)?
.into_iter()
.map(|i| {
Ok((
ApiEventMetricsBucketIdentifier::new(TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
_ => time_range.start_time,
},
end_time: granularity.as_ref().map_or_else(
|| Ok(time_range.end_time),
|g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
)?,
}),
i,
))
})
.collect::<error_stack::Result<
HashSet<(ApiEventMetricsBucketIdentifier, ApiEventMetricRow)>,
crate::query::PostProcessingError,
>>()
.change_context(MetricsError::PostProcessingFailure)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/active_payments/core.rs | crates/analytics/src/active_payments/core.rs | use std::collections::HashMap;
use api_models::analytics::{
active_payments::{
ActivePaymentsMetrics, ActivePaymentsMetricsBucketIdentifier, MetricsBucketResponse,
},
AnalyticsMetadata, GetActivePaymentsMetricRequest, MetricsResponse,
};
use error_stack::ResultExt;
use router_env::{instrument, logger, tracing};
use super::ActivePaymentsMetricsAccumulator;
use crate::{
active_payments::ActivePaymentsMetricAccumulator,
errors::{AnalyticsError, AnalyticsResult},
AnalyticsProvider,
};
#[instrument(skip_all)]
pub async fn get_metrics(
pool: &AnalyticsProvider,
publishable_key: &String,
merchant_id: &common_utils::id_type::MerchantId,
req: GetActivePaymentsMetricRequest,
) -> AnalyticsResult<MetricsResponse<MetricsBucketResponse>> {
let mut metrics_accumulator: HashMap<
ActivePaymentsMetricsBucketIdentifier,
ActivePaymentsMetricsAccumulator,
> = HashMap::new();
let mut set = tokio::task::JoinSet::new();
for metric_type in req.metrics.iter().cloned() {
let publishable_key_scoped = publishable_key.to_owned();
let merchant_id_scoped = merchant_id.to_owned();
let pool = pool.clone();
set.spawn(async move {
let data = pool
.get_active_payments_metrics(
&metric_type,
&merchant_id_scoped,
&publishable_key_scoped,
&req.time_range,
)
.await
.change_context(AnalyticsError::UnknownError);
(metric_type, data)
});
}
while let Some((metric, data)) = set
.join_next()
.await
.transpose()
.change_context(AnalyticsError::UnknownError)?
{
logger::info!("Logging metric: {metric} Result: {:?}", data);
for (id, value) in data? {
let metrics_builder = metrics_accumulator.entry(id).or_default();
match metric {
ActivePaymentsMetrics::ActivePayments => {
metrics_builder.active_payments.add_metrics_bucket(&value)
}
}
}
logger::debug!(
"Analytics Accumulated Results: metric: {}, results: {:#?}",
metric,
metrics_accumulator
);
}
let query_data: Vec<MetricsBucketResponse> = metrics_accumulator
.into_iter()
.map(|(id, val)| MetricsBucketResponse {
values: val.collect(),
dimensions: id,
})
.collect();
Ok(MetricsResponse {
query_data,
meta_data: [AnalyticsMetadata {
current_time_range: req.time_range,
}],
})
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/active_payments/accumulator.rs | crates/analytics/src/active_payments/accumulator.rs | use api_models::analytics::active_payments::ActivePaymentsMetricsBucketValue;
use super::metrics::ActivePaymentsMetricRow;
#[derive(Debug, Default)]
pub struct ActivePaymentsMetricsAccumulator {
pub active_payments: CountAccumulator,
}
#[derive(Debug, Default)]
#[repr(transparent)]
pub struct CountAccumulator {
pub count: Option<i64>,
}
pub trait ActivePaymentsMetricAccumulator {
type MetricOutput;
fn add_metrics_bucket(&mut self, metrics: &ActivePaymentsMetricRow);
fn collect(self) -> Self::MetricOutput;
}
impl ActivePaymentsMetricAccumulator for CountAccumulator {
type MetricOutput = Option<u64>;
#[inline]
fn add_metrics_bucket(&mut self, metrics: &ActivePaymentsMetricRow) {
self.count = match (self.count, metrics.count) {
(None, None) => None,
(None, i @ Some(_)) | (i @ Some(_), None) => i,
(Some(a), Some(b)) => Some(a + b),
}
}
#[inline]
fn collect(self) -> Self::MetricOutput {
self.count.and_then(|i| u64::try_from(i).ok())
}
}
impl ActivePaymentsMetricsAccumulator {
#[allow(dead_code)]
pub fn collect(self) -> ActivePaymentsMetricsBucketValue {
ActivePaymentsMetricsBucketValue {
active_payments: self.active_payments.collect(),
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/active_payments/metrics.rs | crates/analytics/src/active_payments/metrics.rs | use std::collections::HashSet;
use api_models::analytics::{
active_payments::{ActivePaymentsMetrics, ActivePaymentsMetricsBucketIdentifier},
Granularity, TimeRange,
};
use time::PrimitiveDateTime;
use crate::{
query::{Aggregate, GroupByClause, ToSql, Window},
types::{AnalyticsCollection, AnalyticsDataSource, LoadRow, MetricsResult},
};
mod active_payments;
use active_payments::ActivePayments;
#[derive(Debug, PartialEq, Eq, serde::Deserialize, Hash)]
pub struct ActivePaymentsMetricRow {
pub count: Option<i64>,
}
pub trait ActivePaymentsMetricAnalytics: LoadRow<ActivePaymentsMetricRow> {}
#[async_trait::async_trait]
pub trait ActivePaymentsMetric<T>
where
T: AnalyticsDataSource + ActivePaymentsMetricAnalytics,
{
async fn load_metrics(
&self,
merchant_id: &common_utils::id_type::MerchantId,
publishable_key: &str,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<
HashSet<(
ActivePaymentsMetricsBucketIdentifier,
ActivePaymentsMetricRow,
)>,
>;
}
#[async_trait::async_trait]
impl<T> ActivePaymentsMetric<T> for ActivePaymentsMetrics
where
T: AnalyticsDataSource + ActivePaymentsMetricAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
async fn load_metrics(
&self,
merchant_id: &common_utils::id_type::MerchantId,
publishable_key: &str,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<
HashSet<(
ActivePaymentsMetricsBucketIdentifier,
ActivePaymentsMetricRow,
)>,
> {
match self {
Self::ActivePayments => {
ActivePayments
.load_metrics(merchant_id, publishable_key, time_range, pool)
.await
}
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/active_payments/metrics/active_payments.rs | crates/analytics/src/active_payments/metrics/active_payments.rs | use std::collections::HashSet;
use api_models::analytics::{
active_payments::ActivePaymentsMetricsBucketIdentifier, Granularity, TimeRange,
};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
use super::ActivePaymentsMetricRow;
use crate::{
query::{Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window},
types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
};
#[derive(Default)]
pub(super) struct ActivePayments;
#[async_trait::async_trait]
impl<T> super::ActivePaymentsMetric<T> for ActivePayments
where
T: AnalyticsDataSource + super::ActivePaymentsMetricAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
async fn load_metrics(
&self,
merchant_id: &common_utils::id_type::MerchantId,
publishable_key: &str,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<
HashSet<(
ActivePaymentsMetricsBucketIdentifier,
ActivePaymentsMetricRow,
)>,
> {
let mut query_builder: QueryBuilder<T> =
QueryBuilder::new(AnalyticsCollection::ActivePaymentsAnalytics);
query_builder
.add_select_column(Aggregate::DistinctCount {
field: "payment_id",
alias: Some("count"),
})
.switch()?;
query_builder
.add_custom_filter_clause(
"merchant_id",
format!("'{}','{}'", merchant_id.get_string_repr(), publishable_key),
FilterTypes::In,
)
.switch()?;
query_builder
.add_negative_filter_clause("payment_id", "")
.switch()?;
query_builder
.add_custom_filter_clause(
"flow_type",
"'sdk', 'payment', 'payment_redirection_response'",
FilterTypes::In,
)
.switch()?;
time_range
.set_filter_clause(&mut query_builder)
.attach_printable("Error filtering time range")
.switch()?;
query_builder
.execute_query::<ActivePaymentsMetricRow, _>(pool)
.await
.change_context(MetricsError::QueryBuildingError)?
.change_context(MetricsError::QueryExecutionFailure)?
.into_iter()
.map(|i| Ok((ActivePaymentsMetricsBucketIdentifier::new(None), i)))
.collect::<error_stack::Result<
HashSet<(
ActivePaymentsMetricsBucketIdentifier,
ActivePaymentsMetricRow,
)>,
crate::query::PostProcessingError,
>>()
.change_context(MetricsError::PostProcessingFailure)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/routing_events/core.rs | crates/analytics/src/routing_events/core.rs | use api_models::analytics::routing_events::RoutingEventsRequest;
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use super::events::{get_routing_events, RoutingEventsResult};
use crate::{errors::AnalyticsResult, types::FiltersError, AnalyticsProvider};
pub async fn routing_events_core(
pool: &AnalyticsProvider,
req: RoutingEventsRequest,
merchant_id: &common_utils::id_type::MerchantId,
) -> AnalyticsResult<Vec<RoutingEventsResult>> {
let data = match pool {
AnalyticsProvider::Sqlx(_) => Err(FiltersError::NotImplemented(
"Connector Events not implemented for SQLX",
))
.attach_printable("SQL Analytics is not implemented for Connector Events"),
AnalyticsProvider::Clickhouse(ckh_pool)
| AnalyticsProvider::CombinedSqlx(_, ckh_pool)
| AnalyticsProvider::CombinedCkh(_, ckh_pool) => {
get_routing_events(merchant_id, req, ckh_pool).await
}
}
.switch()?;
Ok(data)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/routing_events/events.rs | crates/analytics/src/routing_events/events.rs | use api_models::analytics::{routing_events::RoutingEventsRequest, Granularity};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
use crate::{
query::{Aggregate, GroupByClause, QueryBuilder, ToSql, Window},
types::{AnalyticsCollection, AnalyticsDataSource, FiltersError, FiltersResult, LoadRow},
};
pub trait RoutingEventLogAnalytics: LoadRow<RoutingEventsResult> {}
pub async fn get_routing_events<T>(
merchant_id: &common_utils::id_type::MerchantId,
query_param: RoutingEventsRequest,
pool: &T,
) -> FiltersResult<Vec<RoutingEventsResult>>
where
T: AnalyticsDataSource + RoutingEventLogAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::RoutingEvents);
query_builder.add_select_column("*").switch()?;
query_builder
.add_filter_clause("merchant_id", merchant_id)
.switch()?;
query_builder
.add_filter_clause("payment_id", &query_param.payment_id)
.switch()?;
if let Some(refund_id) = query_param.refund_id {
query_builder
.add_filter_clause("refund_id", &refund_id)
.switch()?;
}
if let Some(dispute_id) = query_param.dispute_id {
query_builder
.add_filter_clause("dispute_id", &dispute_id)
.switch()?;
}
query_builder
.execute_query::<RoutingEventsResult, _>(pool)
.await
.change_context(FiltersError::QueryBuildingError)?
.change_context(FiltersError::QueryExecutionFailure)
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct RoutingEventsResult {
pub merchant_id: common_utils::id_type::MerchantId,
pub profile_id: common_utils::id_type::ProfileId,
pub payment_id: String,
pub routable_connectors: String,
pub payment_connector: Option<String>,
pub request_id: Option<String>,
pub flow: String,
pub url: Option<String>,
pub request: String,
pub response: Option<String>,
pub error: Option<String>,
pub status_code: Option<u16>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
pub method: String,
pub routing_engine: String,
pub routing_approach: Option<String>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/frm/filters.rs | crates/analytics/src/frm/filters.rs | use api_models::analytics::{
frm::{FrmDimensions, FrmTransactionType},
Granularity, TimeRange,
};
use common_utils::errors::ReportSwitchExt;
use diesel_models::enums::FraudCheckStatus;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
use crate::{
query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window},
types::{
AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, FiltersError, FiltersResult,
LoadRow,
},
};
pub trait FrmFilterAnalytics: LoadRow<FrmFilterRow> {}
pub async fn get_frm_filter_for_dimension<T>(
dimension: FrmDimensions,
merchant_id: &common_utils::id_type::MerchantId,
time_range: &TimeRange,
pool: &T,
) -> FiltersResult<Vec<FrmFilterRow>>
where
T: AnalyticsDataSource + FrmFilterAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::FraudCheck);
query_builder.add_select_column(dimension).switch()?;
time_range
.set_filter_clause(&mut query_builder)
.attach_printable("Error filtering time range")
.switch()?;
query_builder
.add_filter_clause("merchant_id", merchant_id)
.switch()?;
query_builder.set_distinct();
query_builder
.execute_query::<FrmFilterRow, _>(pool)
.await
.change_context(FiltersError::QueryBuildingError)?
.change_context(FiltersError::QueryExecutionFailure)
}
#[derive(Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)]
pub struct FrmFilterRow {
pub frm_status: Option<DBEnumWrapper<FraudCheckStatus>>,
pub frm_transaction_type: Option<DBEnumWrapper<FrmTransactionType>>,
pub frm_name: Option<String>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/frm/core.rs | crates/analytics/src/frm/core.rs | #![allow(dead_code)]
use std::collections::HashMap;
use api_models::analytics::{
frm::{FrmDimensions, FrmMetrics, FrmMetricsBucketIdentifier, FrmMetricsBucketResponse},
AnalyticsMetadata, FrmFilterValue, FrmFiltersResponse, GetFrmFilterRequest,
GetFrmMetricRequest, MetricsResponse,
};
use error_stack::ResultExt;
use router_env::{
logger,
tracing::{self, Instrument},
};
use super::{
filters::{get_frm_filter_for_dimension, FrmFilterRow},
FrmMetricsAccumulator,
};
use crate::{
errors::{AnalyticsError, AnalyticsResult},
frm::FrmMetricAccumulator,
metrics, AnalyticsProvider,
};
pub async fn get_metrics(
pool: &AnalyticsProvider,
merchant_id: &common_utils::id_type::MerchantId,
req: GetFrmMetricRequest,
) -> AnalyticsResult<MetricsResponse<FrmMetricsBucketResponse>> {
let mut metrics_accumulator: HashMap<FrmMetricsBucketIdentifier, FrmMetricsAccumulator> =
HashMap::new();
let mut set = tokio::task::JoinSet::new();
for metric_type in req.metrics.iter().cloned() {
let req = req.clone();
let pool = pool.clone();
let task_span =
tracing::debug_span!("analytics_frm_query", frm_metric = metric_type.as_ref());
// Currently JoinSet works with only static lifetime references even if the task pool does not outlive the given reference
// We can optimize away this clone once that is fixed
let merchant_id_scoped = merchant_id.to_owned();
set.spawn(
async move {
let data = pool
.get_frm_metrics(
&metric_type,
&req.group_by_names.clone(),
&merchant_id_scoped,
&req.filters,
req.time_series.map(|t| t.granularity),
&req.time_range,
)
.await
.change_context(AnalyticsError::UnknownError);
(metric_type, data)
}
.instrument(task_span),
);
}
while let Some((metric, data)) = set
.join_next()
.await
.transpose()
.change_context(AnalyticsError::UnknownError)?
{
let data = data?;
let attributes = router_env::metric_attributes!(
("metric_type", metric.to_string()),
("source", pool.to_string()),
);
let value = u64::try_from(data.len());
if let Ok(val) = value {
metrics::BUCKETS_FETCHED.record(val, attributes);
logger::debug!("Attributes: {:?}, Buckets fetched: {}", attributes, val);
}
for (id, value) in data {
logger::debug!(bucket_id=?id, bucket_value=?value, "Bucket row for metric {metric}");
let metrics_builder = metrics_accumulator.entry(id).or_default();
match metric {
FrmMetrics::FrmBlockedRate => {
metrics_builder.frm_blocked_rate.add_metrics_bucket(&value)
}
FrmMetrics::FrmTriggeredAttempts => metrics_builder
.frm_triggered_attempts
.add_metrics_bucket(&value),
}
}
logger::debug!(
"Analytics Accumulated Results: metric: {}, results: {:#?}",
metric,
metrics_accumulator
);
}
let query_data: Vec<FrmMetricsBucketResponse> = metrics_accumulator
.into_iter()
.map(|(id, val)| FrmMetricsBucketResponse {
values: val.collect(),
dimensions: id,
})
.collect();
Ok(MetricsResponse {
query_data,
meta_data: [AnalyticsMetadata {
current_time_range: req.time_range,
}],
})
}
pub async fn get_filters(
pool: &AnalyticsProvider,
req: GetFrmFilterRequest,
merchant_id: &common_utils::id_type::MerchantId,
) -> AnalyticsResult<FrmFiltersResponse> {
let mut res = FrmFiltersResponse::default();
for dim in req.group_by_names {
let values = match pool {
AnalyticsProvider::Sqlx(pool) => {
get_frm_filter_for_dimension(dim, merchant_id, &req.time_range, pool)
.await
}
AnalyticsProvider::Clickhouse(pool) => {
get_frm_filter_for_dimension(dim, merchant_id, &req.time_range, pool)
.await
}
AnalyticsProvider::CombinedCkh(sqlx_pool, ckh_pool) => {
let ckh_result = get_frm_filter_for_dimension(
dim,
merchant_id,
&req.time_range,
ckh_pool,
)
.await;
let sqlx_result = get_frm_filter_for_dimension(
dim,
merchant_id,
&req.time_range,
sqlx_pool,
)
.await;
match (&sqlx_result, &ckh_result) {
(Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => {
logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres frm analytics filters")
},
_ => {}
};
ckh_result
}
AnalyticsProvider::CombinedSqlx(sqlx_pool, ckh_pool) => {
let ckh_result = get_frm_filter_for_dimension(
dim,
merchant_id,
&req.time_range,
ckh_pool,
)
.await;
let sqlx_result = get_frm_filter_for_dimension(
dim,
merchant_id,
&req.time_range,
sqlx_pool,
)
.await;
match (&sqlx_result, &ckh_result) {
(Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => {
logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres frm analytics filters")
},
_ => {}
};
sqlx_result
}
}
.change_context(AnalyticsError::UnknownError)?
.into_iter()
.filter_map(|fil: FrmFilterRow| match dim {
FrmDimensions::FrmStatus => fil.frm_status.map(|i| i.as_ref().to_string()),
FrmDimensions::FrmName => fil.frm_name,
FrmDimensions::FrmTransactionType => {
fil.frm_transaction_type.map(|i| i.as_ref().to_string())
}
})
.collect::<Vec<String>>();
res.query_data.push(FrmFilterValue {
dimension: dim,
values,
})
}
Ok(res)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/frm/types.rs | crates/analytics/src/frm/types.rs | use api_models::analytics::frm::{FrmDimensions, FrmFilters};
use error_stack::ResultExt;
use crate::{
query::{QueryBuilder, QueryFilter, QueryResult, ToSql},
types::{AnalyticsCollection, AnalyticsDataSource},
};
impl<T> QueryFilter<T> for FrmFilters
where
T: AnalyticsDataSource,
AnalyticsCollection: ToSql<T>,
{
fn set_filter_clause(&self, builder: &mut QueryBuilder<T>) -> QueryResult<()> {
if !self.frm_status.is_empty() {
builder
.add_filter_in_range_clause(FrmDimensions::FrmStatus, &self.frm_status)
.attach_printable("Error adding frm status filter")?;
}
if !self.frm_name.is_empty() {
builder
.add_filter_in_range_clause(FrmDimensions::FrmName, &self.frm_name)
.attach_printable("Error adding frm name filter")?;
}
if !self.frm_transaction_type.is_empty() {
builder
.add_filter_in_range_clause(
FrmDimensions::FrmTransactionType,
&self.frm_transaction_type,
)
.attach_printable("Error adding frm transaction type filter")?;
}
Ok(())
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/frm/accumulator.rs | crates/analytics/src/frm/accumulator.rs | use api_models::analytics::frm::FrmMetricsBucketValue;
use common_enums::enums as storage_enums;
use super::metrics::FrmMetricRow;
#[derive(Debug, Default)]
pub struct FrmMetricsAccumulator {
pub frm_triggered_attempts: TriggeredAttemptsAccumulator,
pub frm_blocked_rate: BlockedRateAccumulator,
}
#[derive(Debug, Default)]
#[repr(transparent)]
pub struct TriggeredAttemptsAccumulator {
pub count: Option<i64>,
}
#[derive(Debug, Default)]
pub struct BlockedRateAccumulator {
pub fraud: i64,
pub total: i64,
}
pub trait FrmMetricAccumulator {
type MetricOutput;
fn add_metrics_bucket(&mut self, metrics: &FrmMetricRow);
fn collect(self) -> Self::MetricOutput;
}
impl FrmMetricAccumulator for TriggeredAttemptsAccumulator {
type MetricOutput = Option<u64>;
#[inline]
fn add_metrics_bucket(&mut self, metrics: &FrmMetricRow) {
self.count = match (self.count, metrics.count) {
(None, None) => None,
(None, i @ Some(_)) | (i @ Some(_), None) => i,
(Some(a), Some(b)) => Some(a + b),
}
}
#[inline]
fn collect(self) -> Self::MetricOutput {
self.count.and_then(|i| u64::try_from(i).ok())
}
}
impl FrmMetricAccumulator for BlockedRateAccumulator {
type MetricOutput = Option<f64>;
fn add_metrics_bucket(&mut self, metrics: &FrmMetricRow) {
if let Some(ref frm_status) = metrics.frm_status {
if frm_status.as_ref() == &storage_enums::FraudCheckStatus::Fraud {
self.fraud += metrics.count.unwrap_or_default();
}
};
self.total += metrics.count.unwrap_or_default();
}
fn collect(self) -> Self::MetricOutput {
if self.total <= 0 {
None
} else {
Some(
f64::from(u32::try_from(self.fraud).ok()?) * 100.0
/ f64::from(u32::try_from(self.total).ok()?),
)
}
}
}
impl FrmMetricsAccumulator {
pub fn collect(self) -> FrmMetricsBucketValue {
FrmMetricsBucketValue {
frm_blocked_rate: self.frm_blocked_rate.collect(),
frm_triggered_attempts: self.frm_triggered_attempts.collect(),
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/frm/metrics.rs | crates/analytics/src/frm/metrics.rs | use api_models::analytics::{
frm::{FrmDimensions, FrmFilters, FrmMetrics, FrmMetricsBucketIdentifier, FrmTransactionType},
Granularity, TimeRange,
};
use diesel_models::enums as storage_enums;
use time::PrimitiveDateTime;
mod frm_blocked_rate;
mod frm_triggered_attempts;
use frm_blocked_rate::FrmBlockedRate;
use frm_triggered_attempts::FrmTriggeredAttempts;
use crate::{
query::{Aggregate, GroupByClause, ToSql, Window},
types::{AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, LoadRow, MetricsResult},
};
#[derive(Debug, Eq, PartialEq, serde::Deserialize)]
pub struct FrmMetricRow {
pub frm_name: Option<String>,
pub frm_status: Option<DBEnumWrapper<storage_enums::FraudCheckStatus>>,
pub frm_transaction_type: Option<DBEnumWrapper<FrmTransactionType>>,
pub total: Option<bigdecimal::BigDecimal>,
pub count: Option<i64>,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub start_bucket: Option<PrimitiveDateTime>,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub end_bucket: Option<PrimitiveDateTime>,
}
pub trait FrmMetricAnalytics: LoadRow<FrmMetricRow> {}
#[async_trait::async_trait]
pub trait FrmMetric<T>
where
T: AnalyticsDataSource + FrmMetricAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
async fn load_metrics(
&self,
dimensions: &[FrmDimensions],
merchant_id: &common_utils::id_type::MerchantId,
filters: &FrmFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<Vec<(FrmMetricsBucketIdentifier, FrmMetricRow)>>;
}
#[async_trait::async_trait]
impl<T> FrmMetric<T> for FrmMetrics
where
T: AnalyticsDataSource + FrmMetricAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
async fn load_metrics(
&self,
dimensions: &[FrmDimensions],
merchant_id: &common_utils::id_type::MerchantId,
filters: &FrmFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<Vec<(FrmMetricsBucketIdentifier, FrmMetricRow)>> {
match self {
Self::FrmTriggeredAttempts => {
FrmTriggeredAttempts::default()
.load_metrics(
dimensions,
merchant_id,
filters,
granularity,
time_range,
pool,
)
.await
}
Self::FrmBlockedRate => {
FrmBlockedRate::default()
.load_metrics(
dimensions,
merchant_id,
filters,
granularity,
time_range,
pool,
)
.await
}
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/frm/metrics/frm_blocked_rate.rs | crates/analytics/src/frm/metrics/frm_blocked_rate.rs | use api_models::analytics::{
frm::{FrmDimensions, FrmFilters, FrmMetricsBucketIdentifier},
Granularity, TimeRange,
};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
use super::FrmMetricRow;
use crate::{
query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
};
#[derive(Default)]
pub(super) struct FrmBlockedRate {}
#[async_trait::async_trait]
impl<T> super::FrmMetric<T> for FrmBlockedRate
where
T: AnalyticsDataSource + super::FrmMetricAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
async fn load_metrics(
&self,
dimensions: &[FrmDimensions],
merchant_id: &common_utils::id_type::MerchantId,
filters: &FrmFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<Vec<(FrmMetricsBucketIdentifier, FrmMetricRow)>>
where
T: AnalyticsDataSource + super::FrmMetricAnalytics,
{
let mut query_builder = QueryBuilder::new(AnalyticsCollection::FraudCheck);
let mut dimensions = dimensions.to_vec();
dimensions.push(FrmDimensions::FrmStatus);
for dim in dimensions.iter() {
query_builder.add_select_column(dim).switch()?;
}
query_builder
.add_select_column(Aggregate::Count {
field: None,
alias: Some("count"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Min {
field: "created_at",
alias: Some("start_bucket"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Max {
field: "created_at",
alias: Some("end_bucket"),
})
.switch()?;
filters.set_filter_clause(&mut query_builder).switch()?;
query_builder
.add_filter_clause("merchant_id", merchant_id)
.switch()?;
time_range.set_filter_clause(&mut query_builder).switch()?;
for dim in dimensions.iter() {
query_builder.add_group_by_clause(dim).switch()?;
}
if let Some(granularity) = granularity {
granularity
.set_group_by_clause(&mut query_builder)
.switch()?;
}
query_builder
.execute_query::<FrmMetricRow, _>(pool)
.await
.change_context(MetricsError::QueryBuildingError)?
.change_context(MetricsError::QueryExecutionFailure)?
.into_iter()
.map(|i| {
Ok((
FrmMetricsBucketIdentifier::new(
i.frm_name.as_ref().map(|i| i.to_string()),
None,
i.frm_transaction_type.as_ref().map(|i| i.0.to_string()),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
_ => time_range.start_time,
},
end_time: granularity.as_ref().map_or_else(
|| Ok(time_range.end_time),
|g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
)?,
},
),
i,
))
})
.collect::<error_stack::Result<
Vec<(FrmMetricsBucketIdentifier, FrmMetricRow)>,
crate::query::PostProcessingError,
>>()
.change_context(MetricsError::PostProcessingFailure)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/frm/metrics/frm_triggered_attempts.rs | crates/analytics/src/frm/metrics/frm_triggered_attempts.rs | use api_models::analytics::{
frm::{FrmDimensions, FrmFilters, FrmMetricsBucketIdentifier},
Granularity, TimeRange,
};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
use super::FrmMetricRow;
use crate::{
query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
};
#[derive(Default)]
pub(super) struct FrmTriggeredAttempts {}
#[async_trait::async_trait]
impl<T> super::FrmMetric<T> for FrmTriggeredAttempts
where
T: AnalyticsDataSource + super::FrmMetricAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
async fn load_metrics(
&self,
dimensions: &[FrmDimensions],
merchant_id: &common_utils::id_type::MerchantId,
filters: &FrmFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<Vec<(FrmMetricsBucketIdentifier, FrmMetricRow)>> {
let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::FraudCheck);
for dim in dimensions.iter() {
query_builder.add_select_column(dim).switch()?;
}
query_builder
.add_select_column(Aggregate::Count {
field: None,
alias: Some("count"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Min {
field: "created_at",
alias: Some("start_bucket"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Max {
field: "created_at",
alias: Some("end_bucket"),
})
.switch()?;
filters.set_filter_clause(&mut query_builder).switch()?;
query_builder
.add_filter_clause("merchant_id", merchant_id)
.switch()?;
time_range
.set_filter_clause(&mut query_builder)
.attach_printable("Error filtering time range")
.switch()?;
for dim in dimensions.iter() {
query_builder
.add_group_by_clause(dim)
.attach_printable("Error grouping by dimensions")
.switch()?;
}
if let Some(granularity) = granularity {
granularity
.set_group_by_clause(&mut query_builder)
.attach_printable("Error adding granularity")
.switch()?;
}
query_builder
.execute_query::<FrmMetricRow, _>(pool)
.await
.change_context(MetricsError::QueryBuildingError)?
.change_context(MetricsError::QueryExecutionFailure)?
.into_iter()
.map(|i| {
Ok((
FrmMetricsBucketIdentifier::new(
i.frm_name.as_ref().map(|i| i.to_string()),
i.frm_status.as_ref().map(|i| i.0.to_string()),
i.frm_transaction_type.as_ref().map(|i| i.0.to_string()),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
_ => time_range.start_time,
},
end_time: granularity.as_ref().map_or_else(
|| Ok(time_range.end_time),
|g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
)?,
},
),
i,
))
})
.collect::<error_stack::Result<Vec<_>, crate::query::PostProcessingError>>()
.change_context(MetricsError::PostProcessingFailure)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/disputes/filters.rs | crates/analytics/src/disputes/filters.rs | use api_models::analytics::{disputes::DisputeDimensions, Granularity, TimeRange};
use common_utils::errors::ReportSwitchExt;
use diesel_models::enums::Currency;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
use crate::{
enums::AuthInfo,
query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window},
types::{
AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, FiltersError, FiltersResult,
LoadRow,
},
};
pub trait DisputeFilterAnalytics: LoadRow<DisputeFilterRow> {}
pub async fn get_dispute_filter_for_dimension<T>(
dimension: DisputeDimensions,
auth: &AuthInfo,
time_range: &TimeRange,
pool: &T,
) -> FiltersResult<Vec<DisputeFilterRow>>
where
T: AnalyticsDataSource + DisputeFilterAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Dispute);
query_builder.add_select_column(dimension).switch()?;
time_range
.set_filter_clause(&mut query_builder)
.attach_printable("Error filtering time range")
.switch()?;
auth.set_filter_clause(&mut query_builder).switch()?;
query_builder.set_distinct();
query_builder
.execute_query::<DisputeFilterRow, _>(pool)
.await
.change_context(FiltersError::QueryBuildingError)?
.change_context(FiltersError::QueryExecutionFailure)
}
#[derive(Debug, serde::Serialize, Eq, PartialEq, serde::Deserialize)]
pub struct DisputeFilterRow {
pub connector: Option<String>,
pub dispute_status: Option<String>,
pub connector_status: Option<String>,
pub dispute_stage: Option<String>,
pub currency: Option<DBEnumWrapper<Currency>>,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/disputes/core.rs | crates/analytics/src/disputes/core.rs | use std::collections::HashMap;
use api_models::analytics::{
disputes::{
DisputeDimensions, DisputeMetrics, DisputeMetricsBucketIdentifier,
DisputeMetricsBucketResponse,
},
DisputeFilterValue, DisputeFiltersResponse, DisputesAnalyticsMetadata, DisputesMetricsResponse,
GetDisputeFilterRequest, GetDisputeMetricRequest,
};
use error_stack::ResultExt;
use router_env::{
logger,
tracing::{self, Instrument},
};
use super::{
filters::{get_dispute_filter_for_dimension, DisputeFilterRow},
DisputeMetricsAccumulator,
};
use crate::{
disputes::DisputeMetricAccumulator,
enums::AuthInfo,
errors::{AnalyticsError, AnalyticsResult},
metrics, AnalyticsProvider,
};
pub async fn get_metrics(
pool: &AnalyticsProvider,
auth: &AuthInfo,
req: GetDisputeMetricRequest,
) -> AnalyticsResult<DisputesMetricsResponse<DisputeMetricsBucketResponse>> {
let mut metrics_accumulator: HashMap<
DisputeMetricsBucketIdentifier,
DisputeMetricsAccumulator,
> = HashMap::new();
let mut set = tokio::task::JoinSet::new();
for metric_type in req.metrics.iter().cloned() {
let req = req.clone();
let pool = pool.clone();
let task_span = tracing::debug_span!(
"analytics_dispute_query",
refund_metric = metric_type.as_ref()
);
// Currently JoinSet works with only static lifetime references even if the task pool does not outlive the given reference
// We can optimize away this clone once that is fixed
let auth_scoped = auth.to_owned();
set.spawn(
async move {
let data = pool
.get_dispute_metrics(
&metric_type,
&req.group_by_names.clone(),
&auth_scoped,
&req.filters,
req.time_series.map(|t| t.granularity),
&req.time_range,
)
.await
.change_context(AnalyticsError::UnknownError);
(metric_type, data)
}
.instrument(task_span),
);
}
while let Some((metric, data)) = set
.join_next()
.await
.transpose()
.change_context(AnalyticsError::UnknownError)?
{
let data = data?;
let attributes = router_env::metric_attributes!(
("metric_type", metric.to_string()),
("source", pool.to_string()),
);
let value = u64::try_from(data.len());
if let Ok(val) = value {
metrics::BUCKETS_FETCHED.record(val, attributes);
logger::debug!("Attributes: {:?}, Buckets fetched: {}", attributes, val);
}
for (id, value) in data {
logger::debug!(bucket_id=?id, bucket_value=?value, "Bucket row for metric {metric}");
let metrics_builder = metrics_accumulator.entry(id).or_default();
match metric {
DisputeMetrics::DisputeStatusMetric
| DisputeMetrics::SessionizedDisputeStatusMetric => metrics_builder
.disputes_status_rate
.add_metrics_bucket(&value),
DisputeMetrics::TotalAmountDisputed
| DisputeMetrics::SessionizedTotalAmountDisputed => {
metrics_builder.disputed_amount.add_metrics_bucket(&value)
}
DisputeMetrics::TotalDisputeLostAmount
| DisputeMetrics::SessionizedTotalDisputeLostAmount => metrics_builder
.dispute_lost_amount
.add_metrics_bucket(&value),
}
}
logger::debug!(
"Analytics Accumulated Results: metric: {}, results: {:#?}",
metric,
metrics_accumulator
);
}
let mut total_disputed_amount = 0;
let mut total_dispute_lost_amount = 0;
let query_data: Vec<DisputeMetricsBucketResponse> = metrics_accumulator
.into_iter()
.map(|(id, val)| {
let collected_values = val.collect();
if let Some(amount) = collected_values.disputed_amount {
total_disputed_amount += amount;
}
if let Some(amount) = collected_values.dispute_lost_amount {
total_dispute_lost_amount += amount;
}
DisputeMetricsBucketResponse {
values: collected_values,
dimensions: id,
}
})
.collect();
Ok(DisputesMetricsResponse {
query_data,
meta_data: [DisputesAnalyticsMetadata {
total_disputed_amount: Some(total_disputed_amount),
total_dispute_lost_amount: Some(total_dispute_lost_amount),
}],
})
}
pub async fn get_filters(
pool: &AnalyticsProvider,
req: GetDisputeFilterRequest,
auth: &AuthInfo,
) -> AnalyticsResult<DisputeFiltersResponse> {
let mut res = DisputeFiltersResponse::default();
for dim in req.group_by_names {
let values = match pool {
AnalyticsProvider::Sqlx(pool) => {
get_dispute_filter_for_dimension(dim, auth, &req.time_range, pool)
.await
}
AnalyticsProvider::Clickhouse(pool) => {
get_dispute_filter_for_dimension(dim, auth, &req.time_range, pool)
.await
}
AnalyticsProvider::CombinedCkh(sqlx_pool, ckh_pool) => {
let ckh_result = get_dispute_filter_for_dimension(
dim,
auth,
&req.time_range,
ckh_pool,
)
.await;
let sqlx_result = get_dispute_filter_for_dimension(
dim,
auth,
&req.time_range,
sqlx_pool,
)
.await;
match (&sqlx_result, &ckh_result) {
(Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => {
router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres disputes analytics filters")
},
_ => {}
};
ckh_result
}
AnalyticsProvider::CombinedSqlx(sqlx_pool, ckh_pool) => {
let ckh_result = get_dispute_filter_for_dimension(
dim,
auth,
&req.time_range,
ckh_pool,
)
.await;
let sqlx_result = get_dispute_filter_for_dimension(
dim,
auth,
&req.time_range,
sqlx_pool,
)
.await;
match (&sqlx_result, &ckh_result) {
(Ok(ref sqlx_res), Ok(ref ckh_res)) if sqlx_res != ckh_res => {
router_env::logger::error!(clickhouse_result=?ckh_res, postgres_result=?sqlx_res, "Mismatch between clickhouse & postgres disputes analytics filters")
},
_ => {}
};
sqlx_result
}
}
.change_context(AnalyticsError::UnknownError)?
.into_iter()
.filter_map(|fil: DisputeFilterRow| match dim {
DisputeDimensions::DisputeStage => fil.dispute_stage,
DisputeDimensions::Connector => fil.connector,
DisputeDimensions::Currency => fil.currency.map(|i| i.as_ref().to_string()),
})
.collect::<Vec<String>>();
res.query_data.push(DisputeFilterValue {
dimension: dim,
values,
})
}
Ok(res)
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/disputes/types.rs | crates/analytics/src/disputes/types.rs | use api_models::analytics::disputes::{DisputeDimensions, DisputeFilters};
use error_stack::ResultExt;
use crate::{
query::{QueryBuilder, QueryFilter, QueryResult, ToSql},
types::{AnalyticsCollection, AnalyticsDataSource},
};
impl<T> QueryFilter<T> for DisputeFilters
where
T: AnalyticsDataSource,
AnalyticsCollection: ToSql<T>,
{
fn set_filter_clause(&self, builder: &mut QueryBuilder<T>) -> QueryResult<()> {
if !self.connector.is_empty() {
builder
.add_filter_in_range_clause(DisputeDimensions::Connector, &self.connector)
.attach_printable("Error adding connector filter")?;
}
if !self.dispute_stage.is_empty() {
builder
.add_filter_in_range_clause(DisputeDimensions::DisputeStage, &self.dispute_stage)
.attach_printable("Error adding dispute stage filter")?;
}
if !self.currency.is_empty() {
builder
.add_filter_in_range_clause(DisputeDimensions::Currency, &self.currency)
.attach_printable("Error adding currency filter")?;
}
Ok(())
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/disputes/accumulators.rs | crates/analytics/src/disputes/accumulators.rs | use api_models::analytics::disputes::DisputeMetricsBucketValue;
use diesel_models::enums as storage_enums;
use super::metrics::DisputeMetricRow;
#[derive(Debug, Default)]
pub struct DisputeMetricsAccumulator {
pub disputes_status_rate: RateAccumulator,
pub disputed_amount: DisputedAmountAccumulator,
pub dispute_lost_amount: DisputedAmountAccumulator,
}
#[derive(Debug, Default)]
pub struct RateAccumulator {
pub won_count: i64,
pub challenged_count: i64,
pub lost_count: i64,
pub total: i64,
}
#[derive(Debug, Default)]
#[repr(transparent)]
pub struct DisputedAmountAccumulator {
pub total: Option<i64>,
}
pub trait DisputeMetricAccumulator {
type MetricOutput;
fn add_metrics_bucket(&mut self, metrics: &DisputeMetricRow);
fn collect(self) -> Self::MetricOutput;
}
impl DisputeMetricAccumulator for DisputedAmountAccumulator {
type MetricOutput = Option<u64>;
#[inline]
fn add_metrics_bucket(&mut self, metrics: &DisputeMetricRow) {
self.total = match (
self.total,
metrics
.total
.as_ref()
.and_then(bigdecimal::ToPrimitive::to_i64),
) {
(None, None) => None,
(None, i @ Some(_)) | (i @ Some(_), None) => i,
(Some(a), Some(b)) => Some(a + b),
}
}
#[inline]
fn collect(self) -> Self::MetricOutput {
self.total.and_then(|i| u64::try_from(i).ok())
}
}
impl DisputeMetricAccumulator for RateAccumulator {
type MetricOutput = Option<(Option<u64>, Option<u64>, Option<u64>, Option<u64>)>;
fn add_metrics_bucket(&mut self, metrics: &DisputeMetricRow) {
if let Some(ref dispute_status) = metrics.dispute_status {
if dispute_status.as_ref() == &storage_enums::DisputeStatus::DisputeChallenged {
self.challenged_count += metrics.count.unwrap_or_default();
}
if dispute_status.as_ref() == &storage_enums::DisputeStatus::DisputeWon {
self.won_count += metrics.count.unwrap_or_default();
}
if dispute_status.as_ref() == &storage_enums::DisputeStatus::DisputeLost {
self.lost_count += metrics.count.unwrap_or_default();
}
};
self.total += metrics.count.unwrap_or_default();
}
fn collect(self) -> Self::MetricOutput {
if self.total <= 0 {
Some((None, None, None, None))
} else {
Some((
u64::try_from(self.challenged_count).ok(),
u64::try_from(self.won_count).ok(),
u64::try_from(self.lost_count).ok(),
u64::try_from(self.total).ok(),
))
}
}
}
impl DisputeMetricsAccumulator {
pub fn collect(self) -> DisputeMetricsBucketValue {
let (challenge_rate, won_rate, lost_rate, total_dispute) =
self.disputes_status_rate.collect().unwrap_or_default();
DisputeMetricsBucketValue {
disputes_challenged: challenge_rate,
disputes_won: won_rate,
disputes_lost: lost_rate,
disputed_amount: self.disputed_amount.collect(),
dispute_lost_amount: self.dispute_lost_amount.collect(),
total_dispute,
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/disputes/metrics.rs | crates/analytics/src/disputes/metrics.rs | mod dispute_status_metric;
mod sessionized_metrics;
mod total_amount_disputed;
mod total_dispute_lost_amount;
use std::collections::HashSet;
use api_models::analytics::{
disputes::{DisputeDimensions, DisputeFilters, DisputeMetrics, DisputeMetricsBucketIdentifier},
Granularity,
};
use common_utils::types::TimeRange;
use diesel_models::enums as storage_enums;
use time::PrimitiveDateTime;
use self::{
dispute_status_metric::DisputeStatusMetric, total_amount_disputed::TotalAmountDisputed,
total_dispute_lost_amount::TotalDisputeLostAmount,
};
use crate::{
enums::AuthInfo,
query::{Aggregate, GroupByClause, ToSql, Window},
types::{AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, LoadRow, MetricsResult},
};
#[derive(Debug, Eq, PartialEq, serde::Deserialize, Hash)]
pub struct DisputeMetricRow {
pub dispute_stage: Option<DBEnumWrapper<storage_enums::DisputeStage>>,
pub dispute_status: Option<DBEnumWrapper<storage_enums::DisputeStatus>>,
pub connector: Option<String>,
pub currency: Option<DBEnumWrapper<storage_enums::Currency>>,
pub total: Option<bigdecimal::BigDecimal>,
pub count: Option<i64>,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub start_bucket: Option<PrimitiveDateTime>,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub end_bucket: Option<PrimitiveDateTime>,
}
pub trait DisputeMetricAnalytics: LoadRow<DisputeMetricRow> {}
#[async_trait::async_trait]
pub trait DisputeMetric<T>
where
T: AnalyticsDataSource + DisputeMetricAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
async fn load_metrics(
&self,
dimensions: &[DisputeDimensions],
auth: &AuthInfo,
filters: &DisputeFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>>;
}
#[async_trait::async_trait]
impl<T> DisputeMetric<T> for DisputeMetrics
where
T: AnalyticsDataSource + DisputeMetricAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
async fn load_metrics(
&self,
dimensions: &[DisputeDimensions],
auth: &AuthInfo,
filters: &DisputeFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>> {
match self {
Self::TotalAmountDisputed => {
TotalAmountDisputed::default()
.load_metrics(dimensions, auth, filters, granularity, time_range, pool)
.await
}
Self::DisputeStatusMetric => {
DisputeStatusMetric::default()
.load_metrics(dimensions, auth, filters, granularity, time_range, pool)
.await
}
Self::TotalDisputeLostAmount => {
TotalDisputeLostAmount::default()
.load_metrics(dimensions, auth, filters, granularity, time_range, pool)
.await
}
Self::SessionizedTotalAmountDisputed => {
sessionized_metrics::TotalAmountDisputed::default()
.load_metrics(dimensions, auth, filters, granularity, time_range, pool)
.await
}
Self::SessionizedDisputeStatusMetric => {
sessionized_metrics::DisputeStatusMetric::default()
.load_metrics(dimensions, auth, filters, granularity, time_range, pool)
.await
}
Self::SessionizedTotalDisputeLostAmount => {
sessionized_metrics::TotalDisputeLostAmount::default()
.load_metrics(dimensions, auth, filters, granularity, time_range, pool)
.await
}
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/disputes/metrics/total_dispute_lost_amount.rs | crates/analytics/src/disputes/metrics/total_dispute_lost_amount.rs | use std::collections::HashSet;
use api_models::analytics::{
disputes::{DisputeDimensions, DisputeFilters, DisputeMetricsBucketIdentifier},
Granularity, TimeRange,
};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
use super::DisputeMetricRow;
use crate::{
enums::AuthInfo,
query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
};
#[derive(Default)]
pub(super) struct TotalDisputeLostAmount {}
#[async_trait::async_trait]
impl<T> super::DisputeMetric<T> for TotalDisputeLostAmount
where
T: AnalyticsDataSource + super::DisputeMetricAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
async fn load_metrics(
&self,
dimensions: &[DisputeDimensions],
auth: &AuthInfo,
filters: &DisputeFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>>
where
T: AnalyticsDataSource + super::DisputeMetricAnalytics,
{
let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Dispute);
for dim in dimensions.iter() {
query_builder.add_select_column(dim).switch()?;
}
query_builder
.add_select_column(Aggregate::Sum {
field: "dispute_amount",
alias: Some("total"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Min {
field: "created_at",
alias: Some("start_bucket"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Max {
field: "created_at",
alias: Some("end_bucket"),
})
.switch()?;
filters.set_filter_clause(&mut query_builder).switch()?;
auth.set_filter_clause(&mut query_builder).switch()?;
time_range
.set_filter_clause(&mut query_builder)
.attach_printable("Error filtering time range")
.switch()?;
for dim in dimensions.iter() {
query_builder.add_group_by_clause(dim).switch()?;
}
if let Some(granularity) = granularity {
granularity
.set_group_by_clause(&mut query_builder)
.switch()?;
}
query_builder
.add_filter_clause("dispute_status", "dispute_lost")
.switch()?;
query_builder
.execute_query::<DisputeMetricRow, _>(pool)
.await
.change_context(MetricsError::QueryBuildingError)?
.change_context(MetricsError::QueryExecutionFailure)?
.into_iter()
.map(|i| {
Ok((
DisputeMetricsBucketIdentifier::new(
i.dispute_stage.as_ref().map(|i| i.0),
i.connector.clone(),
i.currency.as_ref().map(|i| i.0),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
_ => time_range.start_time,
},
end_time: granularity.as_ref().map_or_else(
|| Ok(time_range.end_time),
|g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
)?,
},
),
i,
))
})
.collect::<error_stack::Result<HashSet<_>, crate::query::PostProcessingError>>()
.change_context(MetricsError::PostProcessingFailure)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/disputes/metrics/sessionized_metrics.rs | crates/analytics/src/disputes/metrics/sessionized_metrics.rs | mod dispute_status_metric;
mod total_amount_disputed;
mod total_dispute_lost_amount;
pub(super) use dispute_status_metric::DisputeStatusMetric;
pub(super) use total_amount_disputed::TotalAmountDisputed;
pub(super) use total_dispute_lost_amount::TotalDisputeLostAmount;
pub use super::{DisputeMetric, DisputeMetricAnalytics, DisputeMetricRow};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/disputes/metrics/total_amount_disputed.rs | crates/analytics/src/disputes/metrics/total_amount_disputed.rs | use std::collections::HashSet;
use api_models::analytics::{
disputes::{DisputeDimensions, DisputeFilters, DisputeMetricsBucketIdentifier},
Granularity, TimeRange,
};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
use super::DisputeMetricRow;
use crate::{
enums::AuthInfo,
query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
};
#[derive(Default)]
pub(super) struct TotalAmountDisputed {}
#[async_trait::async_trait]
impl<T> super::DisputeMetric<T> for TotalAmountDisputed
where
T: AnalyticsDataSource + super::DisputeMetricAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
async fn load_metrics(
&self,
dimensions: &[DisputeDimensions],
auth: &AuthInfo,
filters: &DisputeFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>>
where
T: AnalyticsDataSource + super::DisputeMetricAnalytics,
{
let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Dispute);
for dim in dimensions {
query_builder.add_select_column(dim).switch()?;
}
query_builder
.add_select_column(Aggregate::Sum {
field: "dispute_amount",
alias: Some("total"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Min {
field: "created_at",
alias: Some("start_bucket"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Max {
field: "created_at",
alias: Some("end_bucket"),
})
.switch()?;
filters.set_filter_clause(&mut query_builder).switch()?;
auth.set_filter_clause(&mut query_builder).switch()?;
time_range
.set_filter_clause(&mut query_builder)
.attach_printable("Error filtering time range")
.switch()?;
for dim in dimensions.iter() {
query_builder.add_group_by_clause(dim).switch()?;
}
if let Some(granularity) = granularity {
granularity
.set_group_by_clause(&mut query_builder)
.switch()?;
}
query_builder
.add_filter_clause("dispute_status", "dispute_won")
.switch()?;
query_builder
.execute_query::<DisputeMetricRow, _>(pool)
.await
.change_context(MetricsError::QueryBuildingError)?
.change_context(MetricsError::QueryExecutionFailure)?
.into_iter()
.map(|i| {
Ok((
DisputeMetricsBucketIdentifier::new(
i.dispute_stage.as_ref().map(|i| i.0),
i.connector.clone(),
i.currency.as_ref().map(|i| i.0),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
_ => time_range.start_time,
},
end_time: granularity.as_ref().map_or_else(
|| Ok(time_range.end_time),
|g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
)?,
},
),
i,
))
})
.collect::<error_stack::Result<HashSet<_>, crate::query::PostProcessingError>>()
.change_context(MetricsError::PostProcessingFailure)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/disputes/metrics/dispute_status_metric.rs | crates/analytics/src/disputes/metrics/dispute_status_metric.rs | use std::collections::HashSet;
use api_models::analytics::{
disputes::{DisputeDimensions, DisputeFilters, DisputeMetricsBucketIdentifier},
Granularity, TimeRange,
};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
use super::DisputeMetricRow;
use crate::{
enums::AuthInfo,
query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
};
#[derive(Default)]
pub(super) struct DisputeStatusMetric {}
#[async_trait::async_trait]
impl<T> super::DisputeMetric<T> for DisputeStatusMetric
where
T: AnalyticsDataSource + super::DisputeMetricAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
async fn load_metrics(
&self,
dimensions: &[DisputeDimensions],
auth: &AuthInfo,
filters: &DisputeFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>>
where
T: AnalyticsDataSource + super::DisputeMetricAnalytics,
{
let mut query_builder = QueryBuilder::new(AnalyticsCollection::Dispute);
for dim in dimensions {
query_builder.add_select_column(dim).switch()?;
}
query_builder.add_select_column("dispute_status").switch()?;
query_builder
.add_select_column(Aggregate::Count {
field: None,
alias: Some("count"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Min {
field: "created_at",
alias: Some("start_bucket"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Max {
field: "created_at",
alias: Some("end_bucket"),
})
.switch()?;
filters.set_filter_clause(&mut query_builder).switch()?;
auth.set_filter_clause(&mut query_builder).switch()?;
time_range.set_filter_clause(&mut query_builder).switch()?;
for dim in dimensions {
query_builder.add_group_by_clause(dim).switch()?;
}
query_builder
.add_group_by_clause("dispute_status")
.switch()?;
if let Some(granularity) = granularity {
granularity
.set_group_by_clause(&mut query_builder)
.switch()?;
}
query_builder
.execute_query::<DisputeMetricRow, _>(pool)
.await
.change_context(MetricsError::QueryBuildingError)?
.change_context(MetricsError::QueryExecutionFailure)?
.into_iter()
.map(|i| {
Ok((
DisputeMetricsBucketIdentifier::new(
i.dispute_stage.as_ref().map(|i| i.0),
i.connector.clone(),
i.currency.as_ref().map(|i| i.0),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
_ => time_range.start_time,
},
end_time: granularity.as_ref().map_or_else(
|| Ok(time_range.end_time),
|g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
)?,
},
),
i,
))
})
.collect::<error_stack::Result<
HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>,
crate::query::PostProcessingError,
>>()
.change_context(MetricsError::PostProcessingFailure)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/disputes/metrics/sessionized_metrics/total_dispute_lost_amount.rs | crates/analytics/src/disputes/metrics/sessionized_metrics/total_dispute_lost_amount.rs | use std::collections::HashSet;
use api_models::analytics::{
disputes::{DisputeDimensions, DisputeFilters, DisputeMetricsBucketIdentifier},
Granularity, TimeRange,
};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
use super::DisputeMetricRow;
use crate::{
enums::AuthInfo,
query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
};
#[derive(Default)]
pub(crate) struct TotalDisputeLostAmount {}
#[async_trait::async_trait]
impl<T> super::DisputeMetric<T> for TotalDisputeLostAmount
where
T: AnalyticsDataSource + super::DisputeMetricAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
async fn load_metrics(
&self,
dimensions: &[DisputeDimensions],
auth: &AuthInfo,
filters: &DisputeFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>>
where
T: AnalyticsDataSource + super::DisputeMetricAnalytics,
{
let mut query_builder: QueryBuilder<T> =
QueryBuilder::new(AnalyticsCollection::DisputeSessionized);
for dim in dimensions.iter() {
query_builder.add_select_column(dim).switch()?;
}
query_builder
.add_select_column(Aggregate::Sum {
field: "dispute_amount",
alias: Some("total"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Min {
field: "created_at",
alias: Some("start_bucket"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Max {
field: "created_at",
alias: Some("end_bucket"),
})
.switch()?;
filters.set_filter_clause(&mut query_builder).switch()?;
auth.set_filter_clause(&mut query_builder).switch()?;
time_range
.set_filter_clause(&mut query_builder)
.attach_printable("Error filtering time range")
.switch()?;
for dim in dimensions.iter() {
query_builder.add_group_by_clause(dim).switch()?;
}
if let Some(granularity) = granularity {
granularity
.set_group_by_clause(&mut query_builder)
.switch()?;
}
query_builder
.add_filter_clause("dispute_status", "dispute_lost")
.switch()?;
query_builder
.execute_query::<DisputeMetricRow, _>(pool)
.await
.change_context(MetricsError::QueryBuildingError)?
.change_context(MetricsError::QueryExecutionFailure)?
.into_iter()
.map(|i| {
Ok((
DisputeMetricsBucketIdentifier::new(
i.dispute_stage.as_ref().map(|i| i.0),
i.connector.clone(),
i.currency.as_ref().map(|i| i.0),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
_ => time_range.start_time,
},
end_time: granularity.as_ref().map_or_else(
|| Ok(time_range.end_time),
|g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
)?,
},
),
i,
))
})
.collect::<error_stack::Result<HashSet<_>, crate::query::PostProcessingError>>()
.change_context(MetricsError::PostProcessingFailure)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/disputes/metrics/sessionized_metrics/total_amount_disputed.rs | crates/analytics/src/disputes/metrics/sessionized_metrics/total_amount_disputed.rs | use std::collections::HashSet;
use api_models::analytics::{
disputes::{DisputeDimensions, DisputeFilters, DisputeMetricsBucketIdentifier},
Granularity, TimeRange,
};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
use super::DisputeMetricRow;
use crate::{
enums::AuthInfo,
query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
};
#[derive(Default)]
pub(crate) struct TotalAmountDisputed {}
#[async_trait::async_trait]
impl<T> super::DisputeMetric<T> for TotalAmountDisputed
where
T: AnalyticsDataSource + super::DisputeMetricAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
async fn load_metrics(
&self,
dimensions: &[DisputeDimensions],
auth: &AuthInfo,
filters: &DisputeFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>>
where
T: AnalyticsDataSource + super::DisputeMetricAnalytics,
{
let mut query_builder: QueryBuilder<T> =
QueryBuilder::new(AnalyticsCollection::DisputeSessionized);
for dim in dimensions {
query_builder.add_select_column(dim).switch()?;
}
query_builder
.add_select_column(Aggregate::Sum {
field: "dispute_amount",
alias: Some("total"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Min {
field: "created_at",
alias: Some("start_bucket"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Max {
field: "created_at",
alias: Some("end_bucket"),
})
.switch()?;
filters.set_filter_clause(&mut query_builder).switch()?;
auth.set_filter_clause(&mut query_builder).switch()?;
time_range
.set_filter_clause(&mut query_builder)
.attach_printable("Error filtering time range")
.switch()?;
for dim in dimensions.iter() {
query_builder.add_group_by_clause(dim).switch()?;
}
if let Some(granularity) = granularity {
granularity
.set_group_by_clause(&mut query_builder)
.switch()?;
}
query_builder
.add_filter_clause("dispute_status", "dispute_won")
.switch()?;
query_builder
.execute_query::<DisputeMetricRow, _>(pool)
.await
.change_context(MetricsError::QueryBuildingError)?
.change_context(MetricsError::QueryExecutionFailure)?
.into_iter()
.map(|i| {
Ok((
DisputeMetricsBucketIdentifier::new(
i.dispute_stage.as_ref().map(|i| i.0),
i.connector.clone(),
i.currency.as_ref().map(|i| i.0),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
_ => time_range.start_time,
},
end_time: granularity.as_ref().map_or_else(
|| Ok(time_range.end_time),
|g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
)?,
},
),
i,
))
})
.collect::<error_stack::Result<HashSet<_>, crate::query::PostProcessingError>>()
.change_context(MetricsError::PostProcessingFailure)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/analytics/src/disputes/metrics/sessionized_metrics/dispute_status_metric.rs | crates/analytics/src/disputes/metrics/sessionized_metrics/dispute_status_metric.rs | use std::collections::HashSet;
use api_models::analytics::{
disputes::{DisputeDimensions, DisputeFilters, DisputeMetricsBucketIdentifier},
Granularity, TimeRange,
};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
use super::DisputeMetricRow;
use crate::{
enums::AuthInfo,
query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
};
#[derive(Default)]
pub(crate) struct DisputeStatusMetric {}
#[async_trait::async_trait]
impl<T> super::DisputeMetric<T> for DisputeStatusMetric
where
T: AnalyticsDataSource + super::DisputeMetricAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
async fn load_metrics(
&self,
dimensions: &[DisputeDimensions],
auth: &AuthInfo,
filters: &DisputeFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>>
where
T: AnalyticsDataSource + super::DisputeMetricAnalytics,
{
let mut query_builder = QueryBuilder::new(AnalyticsCollection::DisputeSessionized);
for dim in dimensions {
query_builder.add_select_column(dim).switch()?;
}
query_builder.add_select_column("dispute_status").switch()?;
query_builder
.add_select_column(Aggregate::Count {
field: None,
alias: Some("count"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Min {
field: "created_at",
alias: Some("start_bucket"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Max {
field: "created_at",
alias: Some("end_bucket"),
})
.switch()?;
filters.set_filter_clause(&mut query_builder).switch()?;
auth.set_filter_clause(&mut query_builder).switch()?;
time_range.set_filter_clause(&mut query_builder).switch()?;
for dim in dimensions {
query_builder.add_group_by_clause(dim).switch()?;
}
query_builder
.add_group_by_clause("dispute_status")
.switch()?;
if let Some(granularity) = granularity {
granularity
.set_group_by_clause(&mut query_builder)
.switch()?;
}
query_builder
.execute_query::<DisputeMetricRow, _>(pool)
.await
.change_context(MetricsError::QueryBuildingError)?
.change_context(MetricsError::QueryExecutionFailure)?
.into_iter()
.map(|i| {
Ok((
DisputeMetricsBucketIdentifier::new(
i.dispute_stage.as_ref().map(|i| i.0),
i.connector.clone(),
i.currency.as_ref().map(|i| i.0),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
_ => time_range.start_time,
},
end_time: granularity.as_ref().map_or_else(
|| Ok(time_range.end_time),
|g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
)?,
},
),
i,
))
})
.collect::<error_stack::Result<
HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>,
crate::query::PostProcessingError,
>>()
.change_context(MetricsError::PostProcessingFailure)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/smithy-generator/build.rs | crates/smithy-generator/build.rs | // crates/smithy-generator/build.rs
use std::{collections::HashSet, fs, path::Path};
use regex::Regex;
fn main() -> Result<(), Box<dyn std::error::Error>> {
run_build()
}
fn run_build() -> Result<(), Box<dyn std::error::Error>> {
let workspace_root = get_workspace_root()?;
// Detect enabled features for this build
let enabled_features = detect_enabled_features();
// Create feature resolver to map smithy-generator features to dependency features
let feature_resolver = FeatureResolver::new(&enabled_features);
let mut smithy_models = Vec::new();
// Scan all crates in the workspace for SmithyModel derives
let crates_dir = workspace_root.join("crates");
if let Ok(entries) = fs::read_dir(&crates_dir) {
for entry in entries.flatten() {
if entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false) {
let crate_path = entry.path();
let crate_name = match crate_path.file_name() {
Some(name) => name.to_string_lossy(),
None => {
continue;
}
};
// Skip the smithy crate itself to avoid self-dependency
if crate_name == "smithy"
|| crate_name == "smithy-core"
|| crate_name == "smithy-generator"
{
continue;
}
// Check if this crate should be scanned based on enabled features
if feature_resolver.should_scan_crate(&crate_name) {
let _ = scan_crate_for_smithy_models(
&crate_path,
&crate_name,
&mut smithy_models,
&feature_resolver,
);
}
}
}
}
// Generate the registry file
generate_model_registry(&smithy_models)?;
Ok(())
}
/// Detects which features are enabled for the current build
fn detect_enabled_features() -> HashSet<String> {
let mut features = HashSet::new();
// Check all CARGO_FEATURE_* environment variables
for (key, value) in std::env::vars() {
if key.starts_with("CARGO_FEATURE_") && value == "1" {
if let Some(feature_suffix) = key.strip_prefix("CARGO_FEATURE_") {
let feature_name = feature_suffix.to_lowercase().replace('_', "-");
features.insert(feature_name);
}
}
}
// Always include default features if none are explicitly enabled
// Note: We should be more careful about default feature assumptions
if features.is_empty() {
features.insert("v1".to_string());
}
features
}
/// Resolves feature dependencies between smithy-generator and its dependencies
struct FeatureResolver {
enabled_features: HashSet<String>,
crate_feature_cache: std::collections::HashMap<String, HashSet<String>>,
}
impl FeatureResolver {
fn new(enabled_features: &HashSet<String>) -> Self {
let mut resolver = Self {
enabled_features: enabled_features.clone(),
crate_feature_cache: std::collections::HashMap::new(),
};
// Pre-compute feature mappings for known crates
resolver.initialize_feature_mappings();
resolver
}
fn initialize_feature_mappings(&mut self) {
// Initialize feature mappings for each known crate
for crate_name in &["api_models", "common_utils", "common_types", "common_enums"] {
let features = self.compute_crate_features(crate_name);
self.crate_feature_cache
.insert(crate_name.to_string(), features);
}
}
/// Determines if a crate should be scanned based on enabled features
fn should_scan_crate(&self, crate_name: &str) -> bool {
match crate_name {
"api_models" => {
// api_models is a core crate that should always be scanned
// The feature gates within the crate will determine what's available
true
}
"common_utils" => {
// common_utils is a core utility crate, always scan it
true
}
"common_types" => {
// common_types should be scanned if any version features are enabled
self.enabled_features.contains("v1") || self.enabled_features.contains("v2")
}
"common_enums" => {
// common_enums is used by most other crates, always scan it
true
}
"router_derive" => {
// Proc macro crate, not relevant for SmithyModel scanning
false
}
"external_services" | "storage_impl" | "router" => {
// These are application crates, may contain models but less likely
// Include them but with lower priority
true
}
_ => {
// For unknown crates, include them by default to be safe
true
}
}
}
/// Determines which features are enabled for a dependency crate
fn get_enabled_crate_features(&self, crate_name: &str) -> HashSet<String> {
// Use cached result if available
if let Some(cached_features) = self.crate_feature_cache.get(crate_name) {
return cached_features.clone();
}
// Compute features for unknown crates
self.compute_crate_features(crate_name)
}
fn compute_crate_features(&self, crate_name: &str) -> HashSet<String> {
let mut crate_features = HashSet::new();
match crate_name {
"api_models" => {
// api_models has v1 and v2 features that directly map to smithy-generator features
if self.enabled_features.contains("v1") {
crate_features.insert("v1".to_string());
}
if self.enabled_features.contains("v2") {
crate_features.insert("v2".to_string());
}
// api_models also has some derived features
for feature in &self.enabled_features {
match feature.as_str() {
"frm" | "payouts" | "disputes" | "routing" => {
crate_features.insert(feature.clone());
}
_ => {}
}
}
}
"common_utils" => {
// common_utils features typically map directly
if self.enabled_features.contains("v1") {
crate_features.insert("v1".to_string());
}
if self.enabled_features.contains("v2") {
crate_features.insert("v2".to_string());
}
}
"common_types" => {
// common_types has payment-related features
if self.enabled_features.contains("v2") {
crate_features.insert("v2".to_string());
}
// Some features are version-independent
for feature in &self.enabled_features {
match feature.as_str() {
"frm" | "payouts" | "disputes" => {
crate_features.insert(feature.clone());
}
_ => {}
}
}
}
"common_enums" => {
// common_enums typically doesn't have version-specific features
// but may have functional features
for feature in &self.enabled_features {
match feature.as_str() {
"frm" | "payouts" | "disputes" | "routing" => {
crate_features.insert(feature.clone());
}
_ => {}
}
}
}
_ => {
// For unknown crates, be conservative and only pass through
// features that are commonly used
for feature in &self.enabled_features {
match feature.as_str() {
"v1" | "v2" => {
crate_features.insert(feature.clone());
}
_ => {}
}
}
}
}
crate_features
}
}
fn get_workspace_root() -> Result<std::path::PathBuf, Box<dyn std::error::Error>> {
let manifest_dir = std::env::var("CARGO_MANIFEST_DIR")
.map_err(|_| "CARGO_MANIFEST_DIR environment variable not set")?;
let manifest_path = Path::new(&manifest_dir);
let parent1 = manifest_path
.parent()
.ok_or("Cannot get parent directory of CARGO_MANIFEST_DIR")?;
let workspace_root = parent1
.parent()
.ok_or("Cannot get workspace root directory")?;
Ok(workspace_root.to_path_buf())
}
fn scan_crate_for_smithy_models(
crate_path: &Path,
crate_name: &str,
models: &mut Vec<SmithyModelInfo>,
feature_resolver: &FeatureResolver,
) -> Result<(), Box<dyn std::error::Error>> {
let src_path = crate_path.join("src");
if !src_path.exists() {
return Ok(());
}
let _enabled_features = feature_resolver.get_enabled_crate_features(crate_name);
scan_directory(&src_path, crate_name, "", models, feature_resolver)?;
Ok(())
}
fn scan_directory(
dir: &Path,
crate_name: &str,
module_path: &str,
models: &mut Vec<SmithyModelInfo>,
feature_resolver: &FeatureResolver,
) -> Result<(), Box<dyn std::error::Error>> {
if let Ok(entries) = fs::read_dir(dir) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
let dir_name = match path.file_name() {
Some(name) => name.to_string_lossy(),
None => {
continue;
}
};
let new_module_path = if module_path.is_empty() {
dir_name.to_string()
} else {
format!("{}::{}", module_path, dir_name)
};
scan_directory(
&path,
crate_name,
&new_module_path,
models,
feature_resolver,
)?;
} else if path.extension().map(|ext| ext == "rs").unwrap_or(false) {
let _ = scan_rust_file(&path, crate_name, module_path, models, feature_resolver);
}
}
}
Ok(())
}
fn scan_rust_file(
file_path: &Path,
crate_name: &str,
module_path: &str,
models: &mut Vec<SmithyModelInfo>,
feature_resolver: &FeatureResolver,
) -> Result<(), Box<dyn std::error::Error>> {
if let Ok(content) = fs::read_to_string(file_path) {
// More precise regex that captures cfg attributes, derive, and struct/enum declarations
// This captures cfg attributes that may be separated from derive by comments/other attributes
let re = Regex::new(r"(?ms)((?:#\[cfg\([^\]]*\)\]\s*)*)((?:///[^\r\n]*\s*|#\[[^\]]*\]\s*)*)(#\[derive\([^)]*\bSmithyModel\b[^)]*\)\])\s*(?:(?:#\[[^\]]*\]\s*)|(?://[^\r\n]*\s*)|(?:///[^\r\n]*\s*)|(?:/\*.*?\*/\s*))*(?:pub\s+)?(?:struct|enum)\s+([A-Z][A-Za-z0-9_]*)\s*[<\{\(]")
.map_err(|e| format!("Failed to compile regex: {}", e))?;
for captures in re.captures_iter(&content) {
let cfg_attrs = captures.get(1).map(|m| m.as_str()).unwrap_or("");
let derive_attr = captures.get(3).map(|m| m.as_str()).unwrap_or("");
let item_name = match captures.get(4) {
Some(capture) => capture.as_str(),
None => {
continue;
}
};
// Verify this is actually a SmithyModel derive by checking the derive attribute more precisely
if !derive_attr.contains("SmithyModel") {
continue;
}
// For items with the same name but different feature gates (like FeatureMetadata),
// we need to ensure we only include the version that actually has SmithyModel
// under the current feature configuration
let enabled_features = feature_resolver.get_enabled_crate_features(crate_name);
// Special handling for items that have multiple definitions with different derives
if item_name == "FeatureMetadata"
|| item_name == "CustomerRequest"
|| item_name == "CustomerUpdateRequest"
{
// FeatureMetadata only has SmithyModel in v1 version
if !enabled_features.contains("v1") {
continue;
}
}
// Check if this item is available under current feature gates
if is_item_available_for_features(cfg_attrs, crate_name, feature_resolver) {
// Validate that the item name is a valid Rust identifier
if is_valid_rust_identifier(item_name) {
let full_module_path = create_module_path(file_path, crate_name, module_path)?;
models.push(SmithyModelInfo {
struct_name: item_name.to_string(),
module_path: full_module_path,
cfg_attrs: cfg_attrs.to_string(),
});
}
}
}
}
Ok(())
}
/// Checks if an item is available under the current feature configuration
fn is_item_available_for_features(
cfg_attrs: &str,
crate_name: &str,
feature_resolver: &FeatureResolver,
) -> bool {
if cfg_attrs.trim().is_empty() {
// No feature gates, item is always available
return true;
}
let enabled_features = feature_resolver.get_enabled_crate_features(crate_name);
// Parse each cfg attribute line
let cfg_lines: Vec<&str> = cfg_attrs
.lines()
.map(|line| line.trim())
.filter(|line| !line.is_empty() && line.starts_with("#[cfg("))
.collect();
// If no cfg attributes found, item is available
if cfg_lines.is_empty() {
return true;
}
// All cfg attributes must be satisfied (AND logic between different cfg attributes)
for cfg_line in cfg_lines {
if !evaluate_cfg_condition(cfg_line, &enabled_features) {
return false;
}
}
true
}
/// Evaluates a single cfg condition
fn evaluate_cfg_condition(cfg_line: &str, enabled_features: &HashSet<String>) -> bool {
// Simple feature check: #[cfg(feature = "v1")]
if let Some(captures) = Regex::new(r#"#\[cfg\(feature\s*=\s*"([^"]+)"\)\]"#)
.ok()
.and_then(|re| re.captures(cfg_line))
{
if let Some(feature_match) = captures.get(1) {
let feature_name = feature_match.as_str();
return enabled_features.contains(feature_name);
}
}
// any() function: #[cfg(any(feature = "v1", feature = "v2"))]
if let Some(captures) = Regex::new(r#"#\[cfg\(any\(([^)]+)\)\)\]"#)
.ok()
.and_then(|re| re.captures(cfg_line))
{
if let Some(any_content) = captures.get(1) {
return evaluate_any_condition(any_content.as_str(), enabled_features);
}
}
// all() function: #[cfg(all(feature = "v1", not(feature = "v2")))]
if let Some(captures) = Regex::new(r#"#\[cfg\(all\(([^)]+)\)\)\]"#)
.ok()
.and_then(|re| re.captures(cfg_line))
{
if let Some(all_content) = captures.get(1) {
return evaluate_all_condition(all_content.as_str(), enabled_features);
}
}
// not() function: #[cfg(not(feature = "v1"))]
if let Some(captures) = Regex::new(r#"#\[cfg\(not\(([^)]+)\)\)\]"#)
.ok()
.and_then(|re| re.captures(cfg_line))
{
if let Some(not_content) = captures.get(1) {
return !evaluate_simple_feature_condition(not_content.as_str(), enabled_features);
}
}
// If we can't parse the cfg condition, assume it's available to avoid false negatives
true
}
/// Evaluates any() condition - returns true if any condition is met
fn evaluate_any_condition(condition: &str, enabled_features: &HashSet<String>) -> bool {
let parts: Vec<&str> = condition.split(',').map(|s| s.trim()).collect();
for part in parts {
if evaluate_simple_feature_condition(part, enabled_features) {
return true;
}
}
false
}
/// Evaluates all() condition - returns true if all conditions are met
fn evaluate_all_condition(condition: &str, enabled_features: &HashSet<String>) -> bool {
let parts: Vec<&str> = condition.split(',').map(|s| s.trim()).collect();
for part in parts {
if part.starts_with("not(") && part.ends_with(')') {
let inner = &part[4..part.len() - 1];
if evaluate_simple_feature_condition(inner, enabled_features) {
return false; // not() condition failed
}
} else if !evaluate_simple_feature_condition(part, enabled_features) {
return false;
}
}
true
}
/// Evaluates a simple feature condition like 'feature = "v1"'
fn evaluate_simple_feature_condition(condition: &str, enabled_features: &HashSet<String>) -> bool {
if let Some(captures) = Regex::new(r#"feature\s*=\s*"([^"]+)""#)
.ok()
.and_then(|re| re.captures(condition))
{
if let Some(feature_match) = captures.get(1) {
let feature_name = feature_match.as_str();
return enabled_features.contains(feature_name);
}
}
// If we can't parse it, assume it's false for safety
false
}
fn is_valid_rust_identifier(name: &str) -> bool {
if name.is_empty() {
return false;
}
// Rust identifiers must start with a letter or underscore
let first_char = match name.chars().next() {
Some(ch) => ch,
None => return false, // This shouldn't happen since we checked is_empty above, but being safe
};
if !first_char.is_ascii_alphabetic() && first_char != '_' {
return false;
}
// Must not be a Rust keyword
let keywords = [
"as", "break", "const", "continue", "crate", "else", "enum", "extern", "false", "fn",
"for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref",
"return", "self", "Self", "static", "struct", "super", "trait", "true", "type", "unsafe",
"use", "where", "while", "async", "await", "dyn", "is", "abstract", "become", "box", "do",
"final", "macro", "override", "priv", "typeof", "unsized", "virtual", "yield", "try",
];
if keywords.contains(&name) {
return false;
}
// All other characters must be alphanumeric or underscore
name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
}
fn create_module_path(
file_path: &Path,
crate_name: &str,
module_path: &str,
) -> Result<String, Box<dyn std::error::Error>> {
let file_name = file_path
.file_stem()
.and_then(|s| s.to_str())
.ok_or_else(|| {
format!(
"Cannot extract file name from path: {}",
file_path.display()
)
})?;
let crate_name_normalized = crate_name.replace('-', "_");
let result = if file_name == "lib" || file_name == "mod" {
if module_path.is_empty() {
crate_name_normalized
} else {
format!("{}::{}", crate_name_normalized, module_path)
}
} else if module_path.is_empty() {
format!("{}::{}", crate_name_normalized, file_name)
} else {
format!("{}::{}::{}", crate_name_normalized, module_path, file_name)
};
Ok(result)
}
#[derive(Debug)]
struct SmithyModelInfo {
struct_name: String,
module_path: String,
cfg_attrs: String,
}
fn generate_model_registry(models: &[SmithyModelInfo]) -> Result<(), Box<dyn std::error::Error>> {
let out_dir = std::env::var("OUT_DIR").map_err(|_| "OUT_DIR environment variable not set")?;
let registry_path = Path::new(&out_dir).join("model_registry.rs");
let mut content = String::new();
content.push_str("// Auto-generated model registry\n");
content.push_str("// DO NOT EDIT - This file is generated by build.rs\n\n");
if !models.is_empty() {
content.push_str("use smithy_core::{SmithyModel, SmithyModelGenerator};\n\n");
// Generate feature-gated imports
for model in models {
if !model.cfg_attrs.trim().is_empty() {
// Add cfg attributes for conditional compilation
content.push_str(&format!("{}\n", model.cfg_attrs.trim()));
}
content.push_str(&format!(
"use {}::{};\n",
model.module_path, model.struct_name
));
}
content.push_str("\npub fn discover_smithy_models() -> Vec<SmithyModel> {\n");
content.push_str(" vec![\n");
// Generate feature-gated model collection calls
for model in models.iter() {
if !model.cfg_attrs.trim().is_empty() {
// Add cfg attributes for conditional compilation
content.push_str(&format!(" {}\n", model.cfg_attrs.trim()));
}
content.push_str(&format!(
" {}::generate_smithy_model(),\n",
model.struct_name
));
}
content.push_str(" ]\n");
content.push_str("}\n");
} else {
// Generate empty function if no models found
content.push_str("use smithy_core::SmithyModel;\n\n");
content.push_str("pub fn discover_smithy_models() -> Vec<SmithyModel> {\n");
content.push_str(" Vec::new()\n");
content.push_str("}\n");
}
fs::write(®istry_path, content).map_err(|e| {
format!(
"Failed to write model registry to {}: {}",
registry_path.display(),
e
)
})?;
Ok(())
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/smithy-generator/src/main.rs | crates/smithy-generator/src/main.rs | // crates/smithy-generator/main.rs
use std::path::Path;
use router_env::logger;
use smithy_core::SmithyGenerator;
// Include the auto-generated model registry
include!(concat!(env!("OUT_DIR"), "/model_registry.rs"));
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut generator = SmithyGenerator::new();
logger::info!("Discovering Smithy models from workspace...");
// Automatically discover and add all models
let models = discover_smithy_models();
logger::info!("Found {} Smithy models", models.len());
if models.is_empty() {
logger::info!("No SmithyModel structs found. Make sure your structs:");
logger::info!(" 1. Derive SmithyModel: #[derive(SmithyModel)]");
logger::info!(" 2. Are in a crate that smithy can access");
logger::info!(" 3. Have the correct smithy attributes");
return Ok(());
}
for model in models {
logger::info!(" Processing namespace: {}", model.namespace);
let shape_names: Vec<_> = model.shapes.keys().collect();
logger::info!(" Shapes: {:?}", shape_names);
generator.add_model(model);
}
logger::info!("Generating Smithy IDL files...");
// Generate IDL files
let output_dir = Path::new("smithy/models");
let absolute_output_dir = std::env::current_dir()?.join(output_dir);
logger::info!("Output directory: {}", absolute_output_dir.display());
generator.generate_idl(output_dir)?;
logger::info!("✅ Smithy models generated successfully!");
logger::info!("Files written to: {}", absolute_output_dir.display());
// List generated files
if let Ok(entries) = std::fs::read_dir(output_dir) {
logger::info!("Generated files:");
for entry in entries.flatten() {
if entry.file_type().map(|ft| ft.is_file()).unwrap_or(false) {
logger::info!(" - {}", entry.file_name().to_string_lossy());
}
}
}
Ok(())
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/currency_conversion/src/lib.rs | crates/currency_conversion/src/lib.rs | pub mod conversion;
pub mod error;
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/currency_conversion/src/error.rs | crates/currency_conversion/src/error.rs | #[derive(Debug, thiserror::Error, serde::Serialize)]
#[serde(tag = "type", content = "info", rename_all = "snake_case")]
pub enum CurrencyConversionError {
#[error("Currency Conversion isn't possible")]
DecimalMultiplicationFailed,
#[error("Currency not supported: '{0}'")]
ConversionNotSupported(String),
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/currency_conversion/src/conversion.rs | crates/currency_conversion/src/conversion.rs | use common_enums::Currency;
use rust_decimal::Decimal;
use rusty_money::Money;
use crate::{
error::CurrencyConversionError,
types::{currency_match, ExchangeRates},
};
pub fn convert(
ex_rates: &ExchangeRates,
from_currency: Currency,
to_currency: Currency,
amount: i64,
) -> Result<Decimal, CurrencyConversionError> {
let money_minor = Money::from_minor(amount, currency_match(from_currency));
let base_currency = ex_rates.base_currency;
if to_currency == base_currency {
ex_rates.forward_conversion(*money_minor.amount(), from_currency)
} else if from_currency == base_currency {
ex_rates.backward_conversion(*money_minor.amount(), to_currency)
} else {
let base_conversion_amt =
ex_rates.forward_conversion(*money_minor.amount(), from_currency)?;
ex_rates.backward_conversion(base_conversion_amt, to_currency)
}
}
#[cfg(test)]
mod tests {
use std::collections::HashMap;
use crate::types::CurrencyFactors;
#[test]
fn currency_to_currency_conversion() {
use super::*;
let mut conversion: HashMap<Currency, CurrencyFactors> = HashMap::new();
let inr_conversion_rates =
CurrencyFactors::new(Decimal::new(823173, 4), Decimal::new(1214, 5));
let szl_conversion_rates =
CurrencyFactors::new(Decimal::new(194423, 4), Decimal::new(514, 4));
let convert_from = Currency::SZL;
let convert_to = Currency::INR;
let amount = 2000;
let base_currency = Currency::USD;
conversion.insert(convert_from, inr_conversion_rates);
conversion.insert(convert_to, szl_conversion_rates);
let sample_rate = ExchangeRates::new(base_currency, conversion);
let res =
convert(&sample_rate, convert_from, convert_to, amount).expect("converted_currency");
println!("The conversion from {amount} {convert_from} to {convert_to} is {res:?}");
}
#[test]
fn currency_to_base_conversion() {
use super::*;
let mut conversion: HashMap<Currency, CurrencyFactors> = HashMap::new();
let inr_conversion_rates =
CurrencyFactors::new(Decimal::new(823173, 4), Decimal::new(1214, 5));
let usd_conversion_rates = CurrencyFactors::new(Decimal::new(1, 0), Decimal::new(1, 0));
let convert_from = Currency::INR;
let convert_to = Currency::USD;
let amount = 2000;
let base_currency = Currency::USD;
conversion.insert(convert_from, inr_conversion_rates);
conversion.insert(convert_to, usd_conversion_rates);
let sample_rate = ExchangeRates::new(base_currency, conversion);
let res =
convert(&sample_rate, convert_from, convert_to, amount).expect("converted_currency");
println!("The conversion from {amount} {convert_from} to {convert_to} is {res:?}");
}
#[test]
fn base_to_currency_conversion() {
use super::*;
let mut conversion: HashMap<Currency, CurrencyFactors> = HashMap::new();
let inr_conversion_rates =
CurrencyFactors::new(Decimal::new(823173, 4), Decimal::new(1214, 5));
let usd_conversion_rates = CurrencyFactors::new(Decimal::new(1, 0), Decimal::new(1, 0));
let convert_from = Currency::USD;
let convert_to = Currency::INR;
let amount = 2000;
let base_currency = Currency::USD;
conversion.insert(convert_from, usd_conversion_rates);
conversion.insert(convert_to, inr_conversion_rates);
let sample_rate = ExchangeRates::new(base_currency, conversion);
let res =
convert(&sample_rate, convert_from, convert_to, amount).expect("converted_currency");
println!("The conversion from {amount} {convert_from} to {convert_to} is {res:?}");
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/currency_conversion/src/types.rs | crates/currency_conversion/src/types.rs | use std::collections::HashMap;
use common_enums::Currency;
use rust_decimal::Decimal;
use rusty_money::iso;
use crate::error::CurrencyConversionError;
/// Cached currency store of base currency
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ExchangeRates {
pub base_currency: Currency,
pub conversion: HashMap<Currency, CurrencyFactors>,
}
/// Stores the multiplicative factor for conversion between currency to base and vice versa
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CurrencyFactors {
/// The factor that will be multiplied to provide Currency output
pub to_factor: Decimal,
/// The factor that will be multiplied to provide for the base output
pub from_factor: Decimal,
}
impl CurrencyFactors {
pub fn new(to_factor: Decimal, from_factor: Decimal) -> Self {
Self {
to_factor,
from_factor,
}
}
}
impl ExchangeRates {
pub fn new(base_currency: Currency, conversion: HashMap<Currency, CurrencyFactors>) -> Self {
Self {
base_currency,
conversion,
}
}
/// The flow here is from_currency -> base_currency -> to_currency
/// from to_currency -> base currency
pub fn forward_conversion(
&self,
amt: Decimal,
from_currency: Currency,
) -> Result<Decimal, CurrencyConversionError> {
let from_factor = self
.conversion
.get(&from_currency)
.ok_or_else(|| {
CurrencyConversionError::ConversionNotSupported(from_currency.to_string())
})?
.from_factor;
amt.checked_mul(from_factor)
.ok_or(CurrencyConversionError::DecimalMultiplicationFailed)
}
/// from base_currency -> to_currency
pub fn backward_conversion(
&self,
amt: Decimal,
to_currency: Currency,
) -> Result<Decimal, CurrencyConversionError> {
let to_factor = self
.conversion
.get(&to_currency)
.ok_or_else(|| {
CurrencyConversionError::ConversionNotSupported(to_currency.to_string())
})?
.to_factor;
amt.checked_mul(to_factor)
.ok_or(CurrencyConversionError::DecimalMultiplicationFailed)
}
}
pub fn currency_match(currency: Currency) -> &'static iso::Currency {
match currency {
Currency::AED => iso::AED,
Currency::AFN => iso::AFN,
Currency::ALL => iso::ALL,
Currency::AMD => iso::AMD,
Currency::ANG => iso::ANG,
Currency::AOA => iso::AOA,
Currency::ARS => iso::ARS,
Currency::AUD => iso::AUD,
Currency::AWG => iso::AWG,
Currency::AZN => iso::AZN,
Currency::BAM => iso::BAM,
Currency::BBD => iso::BBD,
Currency::BDT => iso::BDT,
Currency::BGN => iso::BGN,
Currency::BHD => iso::BHD,
Currency::BIF => iso::BIF,
Currency::BMD => iso::BMD,
Currency::BND => iso::BND,
Currency::BOB => iso::BOB,
Currency::BRL => iso::BRL,
Currency::BSD => iso::BSD,
Currency::BTN => iso::BTN,
Currency::BWP => iso::BWP,
Currency::BYN => iso::BYN,
Currency::BZD => iso::BZD,
Currency::CAD => iso::CAD,
Currency::CDF => iso::CDF,
Currency::CHF => iso::CHF,
Currency::CLF => iso::CLF,
Currency::CLP => iso::CLP,
Currency::CNY => iso::CNY,
Currency::COP => iso::COP,
Currency::CRC => iso::CRC,
Currency::CUC => iso::CUC,
Currency::CUP => iso::CUP,
Currency::CVE => iso::CVE,
Currency::CZK => iso::CZK,
Currency::DJF => iso::DJF,
Currency::DKK => iso::DKK,
Currency::DOP => iso::DOP,
Currency::DZD => iso::DZD,
Currency::EGP => iso::EGP,
Currency::ERN => iso::ERN,
Currency::ETB => iso::ETB,
Currency::EUR => iso::EUR,
Currency::FJD => iso::FJD,
Currency::FKP => iso::FKP,
Currency::GBP => iso::GBP,
Currency::GEL => iso::GEL,
Currency::GHS => iso::GHS,
Currency::GIP => iso::GIP,
Currency::GMD => iso::GMD,
Currency::GNF => iso::GNF,
Currency::GTQ => iso::GTQ,
Currency::GYD => iso::GYD,
Currency::HKD => iso::HKD,
Currency::HNL => iso::HNL,
Currency::HRK => iso::HRK,
Currency::HTG => iso::HTG,
Currency::HUF => iso::HUF,
Currency::IDR => iso::IDR,
Currency::ILS => iso::ILS,
Currency::INR => iso::INR,
Currency::IQD => iso::IQD,
Currency::IRR => iso::IRR,
Currency::ISK => iso::ISK,
Currency::JMD => iso::JMD,
Currency::JOD => iso::JOD,
Currency::JPY => iso::JPY,
Currency::KES => iso::KES,
Currency::KGS => iso::KGS,
Currency::KHR => iso::KHR,
Currency::KMF => iso::KMF,
Currency::KPW => iso::KPW,
Currency::KRW => iso::KRW,
Currency::KWD => iso::KWD,
Currency::KYD => iso::KYD,
Currency::KZT => iso::KZT,
Currency::LAK => iso::LAK,
Currency::LBP => iso::LBP,
Currency::LKR => iso::LKR,
Currency::LRD => iso::LRD,
Currency::LSL => iso::LSL,
Currency::LYD => iso::LYD,
Currency::MAD => iso::MAD,
Currency::MDL => iso::MDL,
Currency::MGA => iso::MGA,
Currency::MKD => iso::MKD,
Currency::MMK => iso::MMK,
Currency::MNT => iso::MNT,
Currency::MOP => iso::MOP,
Currency::MRU => iso::MRU,
Currency::MUR => iso::MUR,
Currency::MVR => iso::MVR,
Currency::MWK => iso::MWK,
Currency::MXN => iso::MXN,
Currency::MYR => iso::MYR,
Currency::MZN => iso::MZN,
Currency::NAD => iso::NAD,
Currency::NGN => iso::NGN,
Currency::NIO => iso::NIO,
Currency::NOK => iso::NOK,
Currency::NPR => iso::NPR,
Currency::NZD => iso::NZD,
Currency::OMR => iso::OMR,
Currency::PAB => iso::PAB,
Currency::PEN => iso::PEN,
Currency::PGK => iso::PGK,
Currency::PHP => iso::PHP,
Currency::PKR => iso::PKR,
Currency::PLN => iso::PLN,
Currency::PYG => iso::PYG,
Currency::QAR => iso::QAR,
Currency::RON => iso::RON,
Currency::RSD => iso::RSD,
Currency::RUB => iso::RUB,
Currency::RWF => iso::RWF,
Currency::SAR => iso::SAR,
Currency::SBD => iso::SBD,
Currency::SCR => iso::SCR,
Currency::SDG => iso::SDG,
Currency::SEK => iso::SEK,
Currency::SGD => iso::SGD,
Currency::SHP => iso::SHP,
Currency::SLE => iso::SLE,
Currency::SLL => iso::SLL,
Currency::SOS => iso::SOS,
Currency::SRD => iso::SRD,
Currency::SSP => iso::SSP,
Currency::STD => iso::STD,
Currency::STN => iso::STN,
Currency::SVC => iso::SVC,
Currency::SYP => iso::SYP,
Currency::SZL => iso::SZL,
Currency::THB => iso::THB,
Currency::TJS => iso::TJS,
Currency::TND => iso::TND,
Currency::TMT => iso::TMT,
Currency::TOP => iso::TOP,
Currency::TTD => iso::TTD,
Currency::TRY => iso::TRY,
Currency::TWD => iso::TWD,
Currency::TZS => iso::TZS,
Currency::UAH => iso::UAH,
Currency::UGX => iso::UGX,
Currency::USD => iso::USD,
Currency::UYU => iso::UYU,
Currency::UZS => iso::UZS,
Currency::VES => iso::VES,
Currency::VND => iso::VND,
Currency::VUV => iso::VUV,
Currency::WST => iso::WST,
Currency::XAF => iso::XAF,
Currency::XCD => iso::XCD,
Currency::XOF => iso::XOF,
Currency::XPF => iso::XPF,
Currency::YER => iso::YER,
Currency::ZAR => iso::ZAR,
Currency::ZMW => iso::ZMW,
Currency::ZWL => iso::ZWL,
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router_env/build.rs | crates/router_env/build.rs | mod vergen {
include!("src/vergen.rs");
}
mod cargo_workspace {
include!("src/cargo_workspace.rs");
}
fn main() {
vergen::generate_cargo_instructions();
cargo_workspace::verify_cargo_metadata_format();
cargo_workspace::set_cargo_workspace_members_env();
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router_env/src/lib.rs | crates/router_env/src/lib.rs | #![warn(missing_debug_implementations)]
//! Environment of payment router: logger, basic config, its environment awareness.
#![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR" ), "/", "README.md"))]
/// Utilities to identify members of the current cargo workspace.
pub mod cargo_workspace;
pub mod env;
pub mod logger;
pub mod metrics;
#[cfg(feature = "actix_web")]
pub mod request_id;
#[cfg(feature = "actix_web")]
pub mod root_span;
/// `cargo` build instructions generation for obtaining information about the application
/// environment.
#[cfg(feature = "vergen")]
pub mod vergen;
// pub use literally;
#[doc(inline)]
pub use logger::*;
pub use opentelemetry;
// Re-export our internal request_id module for easier migration
#[cfg(feature = "actix_web")]
pub use request_id::{IdReuse, RequestId, RequestIdentifier};
#[cfg(feature = "actix_web")]
pub use root_span::CustomRootSpanBuilder;
pub use tracing;
#[cfg(feature = "actix_web")]
pub use tracing_actix_web;
pub use tracing_appender;
#[doc(inline)]
pub use self::env::*;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router_env/src/logger.rs | crates/router_env/src/logger.rs | //! Logger of the system.
pub use tracing::{debug, error, event as log, info, warn};
pub use tracing_attributes::instrument;
pub mod config;
mod defaults;
pub use crate::config::Config;
// mod macros;
pub mod types;
pub use types::{Category, Flow, Level, Tag};
mod setup;
pub use setup::{setup, TelemetryGuard};
pub mod formatter;
pub use formatter::FormattingLayer;
pub mod storage;
pub use storage::{Storage, StorageSubscription};
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router_env/src/request_id.rs | crates/router_env/src/request_id.rs | #![warn(unused, missing_docs)]
//! Request ID middleware for Actix Web applications.
//!
//! This module provides middleware to associate every HTTP request with a unique identifier.
//! The request ID can be used for distributed tracing, error tracking, and request correlation
//! across microservices.
//!
//! # Features
//!
//! - **Automatic UUID v7 generation**: Uses time-ordered UUIDs for better performance
//! - **Header reuse**: Respects incoming request ID headers for request correlation
//! - **Configurable headers**: Custom header names supported for any request ID header
//! - **Request extraction**: RequestId can be extracted in route handlers
//! - **Response headers**: Automatically adds request ID to response headers
//! - **Upstream logging**: Logs incoming request IDs for debugging
//!
//! # Examples
//!
//! ```rust
//! use router_env::{RequestIdentifier, IdReuse};
//! use actix_web::{web, App, HttpServer};
//!
//! let app = App::new()
//! .wrap(
//! RequestIdentifier::new("x-request-id")
//! .use_incoming_id(IdReuse::UseIncoming)
//! );
//! ```
use std::{
fmt::{self, Display, Formatter},
future::{ready, Future, Ready},
pin::Pin,
str::FromStr,
sync::Arc,
task::{Context, Poll},
};
use actix_web::{
dev::{Payload, Service, ServiceRequest, ServiceResponse, Transform},
error::ResponseError,
http::header::{HeaderName, HeaderValue},
Error as ActixError, FromRequest, HttpMessage, HttpRequest,
};
use error_stack::{report, ResultExt};
use uuid::Uuid;
/// Custom result type for request ID operations.
pub type RequestIdResult<T> = Result<T, error_stack::Report<RequestIdError>>;
/// Errors that can occur when working with request IDs.
#[derive(Debug, Clone)]
pub enum RequestIdError {
/// No request ID is associated with the current request.
NoAssociatedId,
/// Failed to convert header value to request ID.
InvalidHeaderValue {
/// The invalid header value that caused the error.
value: String,
},
}
impl error_stack::Context for RequestIdError {}
impl ResponseError for RequestIdError {}
impl Display for RequestIdError {
fn fmt(&self, fmt: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::NoAssociatedId => write!(fmt, "No request ID associated with this request"),
Self::InvalidHeaderValue { value } => write!(fmt, "Invalid header value: {}", value),
}
}
}
/// Configuration for handling incoming request ID headers.
#[derive(Clone, Copy, PartialEq, Eq, Default, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum IdReuse {
/// Reuse the incoming request ID if present, otherwise generate a new one.
UseIncoming,
/// Always generate a new request ID, ignoring any incoming headers.
#[default]
IgnoreIncoming,
}
/// Generate a new UUID v7 request ID.
fn generate_uuid_v7() -> String {
Uuid::now_v7().to_string()
}
/// Request ID middleware that takes a configurable header name
/// and determines how to handle incoming request IDs.
#[derive(Clone, Debug)]
pub struct RequestIdentifier {
header_name: String,
use_incoming_id: IdReuse,
}
/// Request ID value that can be extracted in route handlers.
///
/// Wraps an `Arc<str>` for optimal performance in web middleware.
#[derive(Clone, PartialEq, Eq, Debug, Hash)]
pub struct RequestId(Arc<str>);
/// The middleware implementation that processes requests.
#[derive(Debug)]
pub struct RequestIdMiddleware<S> {
service: S,
header_name: HeaderName,
use_incoming_id: IdReuse,
}
impl Display for RequestId {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.as_str())
}
}
impl FromStr for RequestId {
type Err = error_stack::Report<RequestIdError>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
if s.is_empty() {
Err(report!(RequestIdError::InvalidHeaderValue {
value: s.to_string(),
}))
} else {
Ok(Self(s.into()))
}
}
}
impl TryFrom<HeaderValue> for RequestId {
type Error = error_stack::Report<RequestIdError>;
fn try_from(value: HeaderValue) -> Result<Self, Self::Error> {
let s = value
.to_str()
.change_context(RequestIdError::InvalidHeaderValue {
value: format!("{:?}", value),
})?;
Self::from_str(s)
}
}
impl From<RequestId> for String {
fn from(request_id: RequestId) -> Self {
request_id.0.to_string()
}
}
impl TryFrom<String> for RequestId {
type Error = error_stack::Report<RequestIdError>;
fn try_from(s: String) -> Result<Self, Self::Error> {
Self::from_str(s.as_str())
}
}
impl TryFrom<&str> for RequestId {
type Error = error_stack::Report<RequestIdError>;
fn try_from(s: &str) -> Result<Self, Self::Error> {
Self::from_str(s)
}
}
impl RequestId {
/// Extract request ID from ServiceRequest header or generate UUID v7.
///
/// This is the core logic: try to extract from the specified header,
/// if not possible or not desired, generate a new UUID v7.
pub fn extract_or_generate(
request: &ServiceRequest,
header_name: &HeaderName,
use_incoming_id: IdReuse,
) -> Self {
let request_id_string = match use_incoming_id {
IdReuse::UseIncoming => {
// Try to extract from incoming header
if let Some(existing_header) = request.headers().get(header_name) {
Self::try_from(existing_header.clone())
.map(|id| id.0.to_string())
.unwrap_or_else(|e| {
tracing::warn!(
error = %e,
"Invalid request ID header, generating new UUID v7"
);
generate_uuid_v7()
})
} else {
// No header found, generate new UUID v7
generate_uuid_v7()
}
}
IdReuse::IgnoreIncoming => {
// Always generate new UUID v7
generate_uuid_v7()
}
};
Self(request_id_string.into())
}
/// Convert this request ID to a `HeaderValue`.
pub fn to_header_value(&self) -> RequestIdResult<HeaderValue> {
HeaderValue::from_str(&self.0).change_context(RequestIdError::InvalidHeaderValue {
value: self.0.to_string(),
})
}
/// Get a string representation of this request ID.
pub fn as_str(&self) -> &str {
&self.0
}
}
impl RequestIdentifier {
/// Create a request ID middleware with a custom header name.
///
/// # Examples
///
/// ```rust
/// use router_env::RequestIdentifier;
///
/// // Use any custom header name for request ID extraction
/// let middleware = RequestIdentifier::new("x-request-id");
/// ```
#[must_use]
pub fn new(header_name: &str) -> Self {
Self {
header_name: header_name.to_string(),
use_incoming_id: IdReuse::default(),
}
}
/// Configure how incoming request ID headers should be handled.
///
/// # Examples
///
/// ```rust
/// use router_env::{RequestIdentifier, IdReuse};
///
/// let middleware = RequestIdentifier::new("x-request-id")
/// .use_incoming_id(IdReuse::IgnoreIncoming);
/// ```
#[must_use]
pub fn use_incoming_id(self, use_incoming_id: IdReuse) -> Self {
Self {
use_incoming_id,
..self
}
}
}
impl<S, B> Transform<S, ServiceRequest> for RequestIdentifier
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError>,
S::Future: 'static,
B: 'static,
{
type Response = S::Response;
type Error = S::Error;
type Transform = RequestIdMiddleware<S>;
type InitError = ();
type Future = Ready<Result<Self::Transform, Self::InitError>>;
fn new_transform(&self, service: S) -> Self::Future {
let header_name = HeaderName::from_str(&self.header_name).unwrap_or_else(|_| {
tracing::error!(
"Invalid header name '{}', using fallback 'x-request-id'",
self.header_name
);
HeaderName::from_static("x-request-id")
});
ready(Ok(RequestIdMiddleware {
service,
header_name,
use_incoming_id: self.use_incoming_id,
}))
}
}
#[allow(clippy::type_complexity)]
impl<S, B> Service<ServiceRequest> for RequestIdMiddleware<S>
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = ActixError>,
S::Future: 'static,
B: 'static,
{
type Response = S::Response;
type Error = S::Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;
fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.service.poll_ready(ctx)
}
fn call(&self, request: ServiceRequest) -> Self::Future {
let header_name = self.header_name.clone();
// Capture incoming request ID for logging
let incoming_request_id = request.headers().get(&header_name).cloned();
// Extract request ID from header or generate new UUID v7
let request_id =
RequestId::extract_or_generate(&request, &header_name, self.use_incoming_id);
// Create header value for response
let header_value = request_id.to_header_value().unwrap_or_else(|e| {
tracing::error!(
error = %e,
request_id = %request_id,
"Failed to convert request ID to header value"
);
HeaderValue::from_static("invalid-request-id")
});
// Store request ID for extraction in handlers
request.extensions_mut().insert(request_id.clone());
let fut = self.service.call(request);
Box::pin(async move {
// Log incoming request IDs for correlation
if let Some(upstream_request_id) = incoming_request_id {
tracing::debug!(
?upstream_request_id,
generated_request_id = %request_id,
"Received upstream request ID for correlation"
);
}
let mut response = fut.await?;
// Add request ID to response headers
response.headers_mut().insert(header_name, header_value);
Ok(response)
})
}
}
impl FromRequest for RequestId {
type Error = RequestIdError;
type Future = Ready<Result<Self, Self::Error>>;
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
ready(
req.extensions()
.get::<Self>()
.cloned()
.ok_or(RequestIdError::NoAssociatedId),
)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router_env/src/env.rs | crates/router_env/src/env.rs | //! Information about the current environment.
use std::path::PathBuf;
use serde::{Deserialize, Serialize};
/// Environment variables accessed by the application. This module aims to be the source of truth
/// containing all environment variable that the application accesses.
pub mod vars {
/// Parent directory where `Cargo.toml` is stored.
pub const CARGO_MANIFEST_DIR: &str = "CARGO_MANIFEST_DIR";
/// Environment variable that sets development/sandbox/production environment.
pub const RUN_ENV: &str = "RUN_ENV";
/// Directory of config TOML files. Default is `config`.
pub const CONFIG_DIR: &str = "CONFIG_DIR";
}
/// Current environment.
#[derive(
Debug,
Default,
Deserialize,
Serialize,
Clone,
Copy,
PartialEq,
Eq,
Hash,
strum::Display,
strum::EnumString,
)]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum Env {
/// Development environment.
#[default]
Development,
/// Integration environment.
Integ,
/// Sandbox environment.
Sandbox,
/// Production environment.
Production,
}
/// Name of current environment. Either "development", "sandbox" or "production".
pub fn which() -> Env {
#[cfg(debug_assertions)]
let default_env = Env::Development;
#[cfg(not(debug_assertions))]
let default_env = Env::Production;
std::env::var(vars::RUN_ENV).map_or_else(|_| default_env, |v| v.parse().unwrap_or(default_env))
}
/// Three letter (lowercase) prefix corresponding to the current environment.
/// Either `dev`, `integ`, `snd` or `prd`.
pub fn prefix_for_env() -> &'static str {
match which() {
Env::Development => "dev",
Env::Integ => "integ",
Env::Sandbox => "snd",
Env::Production => "prd",
}
}
/// Path to the root directory of the cargo workspace.
/// It is recommended that this be used by the application as the base path to build other paths
/// such as configuration and logs directories.
pub fn workspace_path() -> PathBuf {
if let Ok(manifest_dir) = std::env::var(vars::CARGO_MANIFEST_DIR) {
let mut path = PathBuf::from(manifest_dir);
path.pop();
path.pop();
path
} else {
PathBuf::from(".")
}
}
/// Version of the crate containing the following information:
///
/// - The latest git tag. If tags are not present in the repository, the short commit hash is used
/// instead.
/// - Short hash of the latest git commit.
/// - Timestamp of the latest git commit.
///
/// Example: `0.1.0-abcd012-2038-01-19T03:14:08Z`.
#[cfg(feature = "vergen")]
#[macro_export]
macro_rules! version {
() => {
concat!(
env!("VERGEN_GIT_DESCRIBE"),
"-",
env!("VERGEN_GIT_SHA"),
"-",
env!("VERGEN_GIT_COMMIT_TIMESTAMP"),
)
};
}
/// A string uniquely identifying the application build.
///
/// Consists of a combination of:
/// - Version defined in the crate file
/// - Timestamp of commit
/// - Hash of the commit
/// - Version of rust compiler
/// - Target triple
///
/// Example: `0.1.0-f5f383e-2022-09-04T11:39:37Z-1.63.0-x86_64-unknown-linux-gnu`
#[cfg(feature = "vergen")]
#[macro_export]
macro_rules! build {
() => {
concat!(
env!("CARGO_PKG_VERSION"),
"-",
env!("VERGEN_GIT_SHA"),
"-",
env!("VERGEN_GIT_COMMIT_TIMESTAMP"),
"-",
env!("VERGEN_RUSTC_SEMVER"),
"-",
$crate::profile!(),
"-",
env!("VERGEN_CARGO_TARGET_TRIPLE"),
)
};
}
/// Short hash of the current commit.
///
/// Example: `f5f383e`.
#[cfg(feature = "vergen")]
#[macro_export]
macro_rules! commit {
() => {
env!("VERGEN_GIT_SHA")
};
}
// /// Information about the platform on which service was built, including:
// /// - Information about OS
// /// - Information about CPU
// ///
// /// Example: ``.
// #[macro_export]
// macro_rules! platform {
// (
// ) => {
// concat!(
// env!("VERGEN_SYSINFO_OS_VERSION"),
// " - ",
// env!("VERGEN_SYSINFO_CPU_BRAND"),
// )
// };
// }
/// Service name deduced from name of the binary.
/// This macro must be called within binaries only.
///
/// Example: `router`.
#[macro_export]
macro_rules! service_name {
() => {
env!("CARGO_BIN_NAME")
};
}
/// Build profile, either debug or release.
///
/// Example: `release`.
#[macro_export]
macro_rules! profile {
() => {
env!("CARGO_PROFILE")
};
}
/// The latest git tag. If tags are not present in the repository, the short commit hash is used
/// instead. Refer to the [`git describe`](https://git-scm.com/docs/git-describe) documentation for
/// more details.
#[macro_export]
macro_rules! git_tag {
() => {
env!("VERGEN_GIT_DESCRIBE")
};
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router_env/src/root_span.rs | crates/router_env/src/root_span.rs | //! Custom RootSpanBuilder tracing-actix-web
use actix_web::{
body::MessageBody,
dev::{ServiceRequest, ServiceResponse},
http::StatusCode,
Error, HttpMessage, ResponseError,
};
use tracing::Span;
use tracing_actix_web::{root_span, RootSpanBuilder};
use crate::request_id::RequestId;
/// Custom RootSpanBuilder that captures x-request-id header in spans
#[derive(Debug)]
pub struct CustomRootSpanBuilder;
impl RootSpanBuilder for CustomRootSpanBuilder {
fn on_request_start(request: &ServiceRequest) -> Span {
// Extract the RequestId from extensions (set by RequestIdentifier middleware)
// We clone the string to avoid lifetime issues with the temporary Ref guard
let request_id = request
.extensions()
.get::<RequestId>()
.map(|id| id.to_string())
.unwrap_or_default();
root_span!(
level = crate::Level::INFO,
request,
request_id = request_id.as_str()
)
}
fn on_request_end<B: MessageBody>(span: Span, outcome: &Result<ServiceResponse<B>, Error>) {
match &outcome {
Ok(response) => {
if let Some(error) = response.response().error() {
// use the status code already constructed for the outgoing HTTP response
handle_error(span, response.status(), error.as_response_error());
} else {
let code: i32 = response.response().status().as_u16().into();
span.record("http.status_code", code);
span.record("otel.status_code", "OK");
}
}
Err(error) => {
let response_error = error.as_response_error();
handle_error(span, response_error.status_code(), response_error);
}
};
}
}
fn handle_error(span: Span, status_code: StatusCode, response_error: &dyn ResponseError) {
// pre-formatting errors is a workaround for https://github.com/tokio-rs/tracing/issues/1565
let display = format!("{response_error}");
let debug = format!("{response_error:?}");
span.record("exception.message", tracing::field::display(display));
span.record("exception.details", tracing::field::display(debug));
let code: i32 = status_code.as_u16().into();
span.record("http.status_code", code);
if status_code.is_client_error() {
span.record("otel.status_code", "OK");
} else {
span.record("otel.status_code", "ERROR");
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router_env/src/cargo_workspace.rs | crates/router_env/src/cargo_workspace.rs | /// Sets the `CARGO_WORKSPACE_MEMBERS` environment variable to include a comma-separated list of
/// names of all crates in the current cargo workspace.
///
/// This function should be typically called within build scripts, so that the environment variable
/// is available to the corresponding crate at compile time.
///
/// # Panics
///
/// Panics if running the `cargo metadata` command fails.
#[allow(clippy::expect_used)]
pub fn set_cargo_workspace_members_env() {
use std::io::Write;
let metadata = cargo_metadata::MetadataCommand::new()
.exec()
.expect("Failed to obtain cargo metadata");
let workspace_members = metadata
.workspace_packages()
.iter()
.map(|package| package.name.as_str())
.collect::<Vec<_>>()
.join(",");
writeln!(
&mut std::io::stdout(),
"cargo:rustc-env=CARGO_WORKSPACE_MEMBERS={workspace_members}"
)
.expect("Failed to set `CARGO_WORKSPACE_MEMBERS` environment variable");
}
/// Verify that the cargo metadata workspace packages format matches that expected by
/// [`set_cargo_workspace_members_env`] to set the `CARGO_WORKSPACE_MEMBERS` environment variable.
///
/// This function should be typically called within build scripts, before the
/// [`set_cargo_workspace_members_env`] function is called.
///
/// # Panics
///
/// Panics if running the `cargo metadata` command fails, or if the workspace member package names
/// cannot be determined.
pub fn verify_cargo_metadata_format() {
#[allow(clippy::expect_used)]
let metadata = cargo_metadata::MetadataCommand::new()
.exec()
.expect("Failed to obtain cargo metadata");
assert!(
metadata
.workspace_packages()
.iter()
.any(|package| package.name == env!("CARGO_PKG_NAME")),
"Unable to determine workspace member package names from `cargo metadata`"
);
}
/// Obtain the crates in the current cargo workspace as a `HashSet`.
///
/// This macro requires that [`set_cargo_workspace_members_env()`] function be called in the
/// build script of the crate where this macro is being called.
///
/// # Errors
///
/// Causes a compilation error if the `CARGO_WORKSPACE_MEMBERS` environment variable is unset.
#[macro_export]
macro_rules! cargo_workspace_members {
() => {
std::env!("CARGO_WORKSPACE_MEMBERS")
.split(',')
.collect::<std::collections::HashSet<&'static str>>()
};
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router_env/src/metrics.rs | crates/router_env/src/metrics.rs | //! Utilities to easily create opentelemetry contexts, meters and metrics.
/// Create a global [`Meter`][Meter] with the specified name and an optional description.
///
/// [Meter]: opentelemetry::metrics::Meter
#[macro_export]
macro_rules! global_meter {
($name:ident) => {
static $name: ::std::sync::LazyLock<$crate::opentelemetry::metrics::Meter> =
::std::sync::LazyLock::new(|| $crate::opentelemetry::global::meter(stringify!($name)));
};
($meter:ident, $name:literal) => {
static $meter: ::std::sync::LazyLock<$crate::opentelemetry::metrics::Meter> =
::std::sync::LazyLock::new(|| $crate::opentelemetry::global::meter(stringify!($name)));
};
}
/// Create a [`Counter`][Counter] metric with the specified name and an optional description,
/// associated with the specified meter. Note that the meter must be a valid [`Meter`][Meter].
///
/// [Counter]: opentelemetry::metrics::Counter
/// [Meter]: opentelemetry::metrics::Meter
#[macro_export]
macro_rules! counter_metric {
($name:ident, $meter:ident) => {
pub(crate) static $name: ::std::sync::LazyLock<
$crate::opentelemetry::metrics::Counter<u64>,
> = ::std::sync::LazyLock::new(|| $meter.u64_counter(stringify!($name)).build());
};
($name:ident, $meter:ident, description:literal) => {
#[doc = $description]
pub(crate) static $name: ::std::sync::LazyLock<
$crate::opentelemetry::metrics::Counter<u64>,
> = ::std::sync::LazyLock::new(|| {
$meter
.u64_counter(stringify!($name))
.with_description($description)
.build()
});
};
}
/// Create a [`Histogram`][Histogram] f64 metric with the specified name and an optional description,
/// associated with the specified meter. Note that the meter must be a valid [`Meter`][Meter].
///
/// [Histogram]: opentelemetry::metrics::Histogram
/// [Meter]: opentelemetry::metrics::Meter
#[macro_export]
macro_rules! histogram_metric_f64 {
($name:ident, $meter:ident) => {
pub(crate) static $name: ::std::sync::LazyLock<
$crate::opentelemetry::metrics::Histogram<f64>,
> = ::std::sync::LazyLock::new(|| {
$meter
.f64_histogram(stringify!($name))
.with_boundaries($crate::metrics::f64_histogram_buckets())
.build()
});
};
($name:ident, $meter:ident, $description:literal) => {
#[doc = $description]
pub(crate) static $name: ::std::sync::LazyLock<
$crate::opentelemetry::metrics::Histogram<f64>,
> = ::std::sync::LazyLock::new(|| {
$meter
.f64_histogram(stringify!($name))
.with_description($description)
.with_boundaries($crate::metrics::f64_histogram_buckets())
.build()
});
};
}
/// Create a [`Histogram`][Histogram] u64 metric with the specified name and an optional description,
/// associated with the specified meter. Note that the meter must be a valid [`Meter`][Meter].
///
/// [Histogram]: opentelemetry::metrics::Histogram
/// [Meter]: opentelemetry::metrics::Meter
#[macro_export]
macro_rules! histogram_metric_u64 {
($name:ident, $meter:ident) => {
pub(crate) static $name: ::std::sync::LazyLock<
$crate::opentelemetry::metrics::Histogram<u64>,
> = ::std::sync::LazyLock::new(|| {
$meter
.u64_histogram(stringify!($name))
.with_boundaries($crate::metrics::f64_histogram_buckets())
.build()
});
};
($name:ident, $meter:ident, $description:literal) => {
#[doc = $description]
pub(crate) static $name: ::std::sync::LazyLock<
$crate::opentelemetry::metrics::Histogram<u64>,
> = ::std::sync::LazyLock::new(|| {
$meter
.u64_histogram(stringify!($name))
.with_description($description)
.with_boundaries($crate::metrics::f64_histogram_buckets())
.build()
});
};
}
/// Create a [`Gauge`][Gauge] metric with the specified name and an optional description,
/// associated with the specified meter. Note that the meter must be a valid [`Meter`][Meter].
///
/// [Gauge]: opentelemetry::metrics::Gauge
/// [Meter]: opentelemetry::metrics::Meter
#[macro_export]
macro_rules! gauge_metric {
($name:ident, $meter:ident) => {
pub(crate) static $name: ::std::sync::LazyLock<$crate::opentelemetry::metrics::Gauge<u64>> =
::std::sync::LazyLock::new(|| $meter.u64_gauge(stringify!($name)).build());
};
($name:ident, $meter:ident, description:literal) => {
#[doc = $description]
pub(crate) static $name: ::std::sync::LazyLock<$crate::opentelemetry::metrics::Gauge<u64>> =
::std::sync::LazyLock::new(|| {
$meter
.u64_gauge(stringify!($name))
.with_description($description)
.build()
});
};
}
/// Create attributes to associate with a metric from key-value pairs.
#[macro_export]
macro_rules! metric_attributes {
($(($key:expr, $value:expr $(,)?)),+ $(,)?) => {
&[$($crate::opentelemetry::KeyValue::new($key, $value)),+]
};
}
pub use helpers::f64_histogram_buckets;
mod helpers {
/// Returns the buckets to be used for a f64 histogram
#[inline(always)]
pub fn f64_histogram_buckets() -> Vec<f64> {
let mut init = 0.01;
let mut buckets: [f64; 15] = [0.0; 15];
for bucket in &mut buckets {
init *= 2.0;
*bucket = init;
}
Vec::from(buckets)
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router_env/src/vergen.rs | crates/router_env/src/vergen.rs | /// Configures the [`vergen`][::vergen] crate to generate the `cargo` build instructions.
///
/// This function should be typically called within build scripts to generate `cargo` build
/// instructions for the corresponding crate.
///
/// # Panics
///
/// Panics if `vergen` fails to generate `cargo` build instructions.
#[cfg(feature = "vergen")]
#[allow(clippy::expect_used)]
pub fn generate_cargo_instructions() {
use std::io::Write;
use vergen::EmitBuilder;
EmitBuilder::builder()
.cargo_debug()
.cargo_opt_level()
.cargo_target_triple()
.git_commit_timestamp()
.git_describe(true, true, None)
.git_sha(true)
.rustc_semver()
.rustc_commit_hash()
.emit()
.expect("Failed to generate `cargo` build instructions");
writeln!(
&mut std::io::stdout(),
"cargo:rustc-env=CARGO_PROFILE={}",
std::env::var("PROFILE").expect("Failed to obtain `cargo` profile")
)
.expect("Failed to set `CARGO_PROFILE` environment variable");
}
#[cfg(not(feature = "vergen"))]
pub fn generate_cargo_instructions() {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router_env/src/logger/setup.rs | crates/router_env/src/logger/setup.rs | //! Setup logging subsystem.
use std::time::Duration;
use ::config::ConfigError;
use serde_json::ser::{CompactFormatter, PrettyFormatter};
use tracing_appender::non_blocking::WorkerGuard;
use tracing_subscriber::{fmt, prelude::*, util::SubscriberInitExt, EnvFilter, Layer};
use crate::{config, FormattingLayer, StorageSubscription};
/// Contains guards necessary for logging and metrics collection.
#[derive(Debug)]
pub struct TelemetryGuard {
_log_guards: Vec<WorkerGuard>,
}
/// Setup logging sub-system specifying the logging configuration, service (binary) name, and a
/// list of external crates for which a more verbose logging must be enabled. All crates within the
/// current cargo workspace are automatically considered for verbose logging.
#[allow(clippy::print_stdout)] // The logger hasn't been initialized yet
pub fn setup(
config: &config::Log,
service_name: &str,
crates_to_filter: impl AsRef<[&'static str]>,
) -> error_stack::Result<TelemetryGuard, ConfigError> {
let mut guards = Vec::new();
// Setup OpenTelemetry traces and metrics
let traces_layer = if config.telemetry.traces_enabled {
setup_tracing_pipeline(&config.telemetry, service_name)
} else {
None
};
if config.telemetry.metrics_enabled {
setup_metrics_pipeline(&config.telemetry)
};
// Setup file logging
let file_writer = if config.file.enabled {
let mut path = crate::env::workspace_path();
// Using an absolute path for file log path would replace workspace path with absolute path,
// which is the intended behavior for us.
path.push(&config.file.path);
let file_appender = tracing_appender::rolling::hourly(&path, &config.file.file_name);
let (file_writer, guard) = tracing_appender::non_blocking(file_appender);
guards.push(guard);
let file_filter = get_envfilter(
config.file.filtering_directive.as_ref(),
config::Level(tracing::Level::WARN),
config.file.level,
&crates_to_filter,
);
println!("Using file logging filter: {file_filter}");
let layer = FormattingLayer::new(service_name, file_writer, CompactFormatter)?
.with_filter(file_filter);
Some(layer)
} else {
None
};
let subscriber = tracing_subscriber::registry()
.with(traces_layer)
.with(StorageSubscription)
.with(file_writer);
// Setup console logging
if config.console.enabled {
let (console_writer, guard) = tracing_appender::non_blocking(std::io::stdout());
guards.push(guard);
let console_filter = get_envfilter(
config.console.filtering_directive.as_ref(),
config::Level(tracing::Level::WARN),
config.console.level,
&crates_to_filter,
);
println!("Using console logging filter: {console_filter}");
match config.console.log_format {
config::LogFormat::Default => {
let logging_layer = fmt::layer()
.with_timer(fmt::time::time())
.pretty()
.with_writer(console_writer)
.with_filter(console_filter);
subscriber.with(logging_layer).init();
}
config::LogFormat::Json => {
error_stack::Report::set_color_mode(error_stack::fmt::ColorMode::None);
subscriber
.with(
FormattingLayer::new(service_name, console_writer, CompactFormatter)?
.with_filter(console_filter),
)
.init();
}
config::LogFormat::PrettyJson => {
error_stack::Report::set_color_mode(error_stack::fmt::ColorMode::None);
subscriber
.with(
FormattingLayer::new(service_name, console_writer, PrettyFormatter::new())?
.with_filter(console_filter),
)
.init();
}
}
} else {
subscriber.init();
};
// Returning the TelemetryGuard for logs to be printed and metrics to be collected until it is
// dropped
Ok(TelemetryGuard {
_log_guards: guards,
})
}
fn get_opentelemetry_exporter_config(
config: &config::LogTelemetry,
) -> opentelemetry_otlp::ExportConfig {
let mut exporter_config = opentelemetry_otlp::ExportConfig {
protocol: opentelemetry_otlp::Protocol::Grpc,
endpoint: config.otel_exporter_otlp_endpoint.clone(),
..Default::default()
};
if let Some(timeout) = config.otel_exporter_otlp_timeout {
exporter_config.timeout = Duration::from_millis(timeout);
}
exporter_config
}
#[derive(Debug, Clone)]
enum TraceUrlAssert {
Match(String),
EndsWith(String),
}
impl TraceUrlAssert {
fn compare_url(&self, url: &str) -> bool {
match self {
Self::Match(value) => url == value,
Self::EndsWith(end) => url.ends_with(end),
}
}
}
impl From<String> for TraceUrlAssert {
fn from(value: String) -> Self {
match value {
url if url.starts_with('*') => Self::EndsWith(url.trim_start_matches('*').to_string()),
url => Self::Match(url),
}
}
}
#[derive(Debug, Clone)]
struct TraceAssertion {
clauses: Option<Vec<TraceUrlAssert>>,
/// default behaviour for tracing if no condition is provided
default: bool,
}
impl TraceAssertion {
/// Should the provided url be traced
fn should_trace_url(&self, url: &str) -> bool {
match &self.clauses {
Some(clauses) => clauses.iter().all(|cur| cur.compare_url(url)),
None => self.default,
}
}
}
/// Conditional Sampler for providing control on url based tracing
#[derive(Clone, Debug)]
struct ConditionalSampler<T: opentelemetry_sdk::trace::ShouldSample + Clone + 'static>(
TraceAssertion,
T,
);
impl<T: opentelemetry_sdk::trace::ShouldSample + Clone + 'static>
opentelemetry_sdk::trace::ShouldSample for ConditionalSampler<T>
{
fn should_sample(
&self,
parent_context: Option<&opentelemetry::Context>,
trace_id: opentelemetry::trace::TraceId,
name: &str,
span_kind: &opentelemetry::trace::SpanKind,
attributes: &[opentelemetry::KeyValue],
links: &[opentelemetry::trace::Link],
) -> opentelemetry::trace::SamplingResult {
use opentelemetry::trace::TraceContextExt;
match attributes
.iter()
.find(|&kv| kv.key == opentelemetry::Key::new("http.route"))
.map_or(self.0.default, |inner| {
self.0.should_trace_url(&inner.value.as_str())
}) {
true => {
self.1
.should_sample(parent_context, trace_id, name, span_kind, attributes, links)
}
false => opentelemetry::trace::SamplingResult {
decision: opentelemetry::trace::SamplingDecision::Drop,
attributes: Vec::new(),
trace_state: match parent_context {
Some(ctx) => ctx.span().span_context().trace_state().clone(),
None => opentelemetry::trace::TraceState::default(),
},
},
}
}
}
fn setup_tracing_pipeline(
config: &config::LogTelemetry,
service_name: &str,
) -> Option<
tracing_opentelemetry::OpenTelemetryLayer<
tracing_subscriber::Registry,
opentelemetry_sdk::trace::Tracer,
>,
> {
use opentelemetry::trace::TracerProvider;
use opentelemetry_otlp::WithExportConfig;
use opentelemetry_sdk::trace;
opentelemetry::global::set_text_map_propagator(
opentelemetry_sdk::propagation::TraceContextPropagator::new(),
);
// Set the export interval to 1 second
let batch_config = trace::BatchConfigBuilder::default()
.with_scheduled_delay(Duration::from_millis(1000))
.build();
let exporter_result = opentelemetry_otlp::SpanExporter::builder()
.with_tonic()
.with_export_config(get_opentelemetry_exporter_config(config))
.build();
let exporter = if config.ignore_errors {
#[allow(clippy::print_stderr)] // The logger hasn't been initialized yet
exporter_result
.inspect_err(|error| eprintln!("Failed to build traces exporter: {error:?}"))
.ok()?
} else {
// Safety: This is conditional, there is an option to avoid this behavior at runtime.
#[allow(clippy::expect_used)]
exporter_result.expect("Failed to build traces exporter")
};
let mut provider_builder = trace::TracerProvider::builder()
.with_span_processor(
trace::BatchSpanProcessor::builder(
exporter,
// The runtime would have to be updated if a different web framework is used
opentelemetry_sdk::runtime::TokioCurrentThread,
)
.with_batch_config(batch_config)
.build(),
)
.with_sampler(trace::Sampler::ParentBased(Box::new(ConditionalSampler(
TraceAssertion {
clauses: config
.route_to_trace
.clone()
.map(|inner| inner.into_iter().map(TraceUrlAssert::from).collect()),
default: false,
},
trace::Sampler::TraceIdRatioBased(config.sampling_rate.unwrap_or(1.0)),
))))
.with_resource(opentelemetry_sdk::Resource::new(vec![
opentelemetry::KeyValue::new("service.name", service_name.to_owned()),
]));
if config.use_xray_generator {
provider_builder = provider_builder
.with_id_generator(opentelemetry_aws::trace::XrayIdGenerator::default());
}
Some(
tracing_opentelemetry::layer()
.with_tracer(provider_builder.build().tracer(service_name.to_owned())),
)
}
fn setup_metrics_pipeline(config: &config::LogTelemetry) {
use opentelemetry_otlp::WithExportConfig;
let exporter_result = opentelemetry_otlp::MetricExporter::builder()
.with_tonic()
.with_temporality(opentelemetry_sdk::metrics::Temporality::Cumulative)
.with_export_config(get_opentelemetry_exporter_config(config))
.build();
let exporter = if config.ignore_errors {
#[allow(clippy::print_stderr)] // The logger hasn't been initialized yet
exporter_result
.inspect_err(|error| eprintln!("Failed to build metrics exporter: {error:?}"))
.ok();
return;
} else {
// Safety: This is conditional, there is an option to avoid this behavior at runtime.
#[allow(clippy::expect_used)]
exporter_result.expect("Failed to build metrics exporter")
};
let reader = opentelemetry_sdk::metrics::PeriodicReader::builder(
exporter,
// The runtime would have to be updated if a different web framework is used
opentelemetry_sdk::runtime::TokioCurrentThread,
)
.with_interval(Duration::from_secs(3))
.with_timeout(Duration::from_secs(10))
.build();
let provider = opentelemetry_sdk::metrics::SdkMeterProvider::builder()
.with_reader(reader)
.with_resource(opentelemetry_sdk::Resource::new([
opentelemetry::KeyValue::new(
"pod",
std::env::var("POD_NAME").unwrap_or(String::from("hyperswitch-server-default")),
),
]))
.build();
opentelemetry::global::set_meter_provider(provider);
}
fn get_envfilter(
filtering_directive: Option<&String>,
default_log_level: config::Level,
filter_log_level: config::Level,
crates_to_filter: impl AsRef<[&'static str]>,
) -> EnvFilter {
filtering_directive
.map(|filter| {
// Try to create target filter from specified filtering directive, if set
// Safety: If user is overriding the default filtering directive, then we need to panic
// for invalid directives.
#[allow(clippy::expect_used)]
EnvFilter::builder()
.with_default_directive(default_log_level.into_level().into())
.parse(filter)
.expect("Invalid EnvFilter filtering directive")
})
.unwrap_or_else(|| {
// Construct a default target filter otherwise
let mut workspace_members = crate::cargo_workspace_members!();
workspace_members.extend(crates_to_filter.as_ref());
workspace_members
.drain()
.zip(std::iter::repeat(filter_log_level.into_level()))
.fold(
EnvFilter::default().add_directive(default_log_level.into_level().into()),
|env_filter, (target, level)| {
// Safety: This is a hardcoded basic filtering directive. If even the basic
// filter is wrong, it's better to panic.
#[allow(clippy::expect_used)]
env_filter.add_directive(
format!("{target}={level}")
.parse()
.expect("Invalid EnvFilter directive format"),
)
},
)
})
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router_env/src/logger/config.rs | crates/router_env/src/logger/config.rs | //! Logger-specific config.
use std::path::PathBuf;
use serde::Deserialize;
/// Config settings.
#[derive(Debug, Deserialize, Clone)]
pub struct Config {
/// Logging to a file.
pub log: Log,
}
/// Log config settings.
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(default)]
pub struct Log {
/// Logging to a file.
pub file: LogFile,
/// Logging to a console.
pub console: LogConsole,
/// Telemetry / tracing.
pub telemetry: LogTelemetry,
}
/// Logging to a file.
#[derive(Debug, Deserialize, Clone)]
#[serde(default)]
pub struct LogFile {
/// Whether you want to store log in log files.
pub enabled: bool,
/// Where to store log files.
pub path: String,
/// Name of log file without suffix.
pub file_name: String,
/// What gets into log files.
pub level: Level,
/// Directive which sets the log level for one or more crates/modules.
pub filtering_directive: Option<String>,
// pub do_async: bool, // is not used
// pub rotation: u16,
}
/// Describes the level of verbosity of a span or event.
#[derive(Debug, Clone, Copy)]
pub struct Level(pub(super) tracing::Level);
impl Level {
/// Returns the most verbose [`tracing::Level`]
pub fn into_level(self) -> tracing::Level {
self.0
}
}
impl<'de> Deserialize<'de> for Level {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
use std::str::FromStr as _;
let s = String::deserialize(deserializer)?;
tracing::Level::from_str(&s)
.map(Level)
.map_err(serde::de::Error::custom)
}
}
/// Logging to a console.
#[derive(Debug, Deserialize, Clone)]
#[serde(default)]
pub struct LogConsole {
/// Whether you want to see log in your terminal.
pub enabled: bool,
/// What you see in your terminal.
pub level: Level,
/// Log format
#[serde(default)]
pub log_format: LogFormat,
/// Directive which sets the log level for one or more crates/modules.
pub filtering_directive: Option<String>,
}
/// Telemetry / tracing.
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(default)]
pub struct LogTelemetry {
/// Whether the traces pipeline is enabled.
pub traces_enabled: bool,
/// Whether the metrics pipeline is enabled.
pub metrics_enabled: bool,
/// Whether errors in setting up traces or metrics pipelines must be ignored.
pub ignore_errors: bool,
/// Sampling rate for traces
pub sampling_rate: Option<f64>,
/// Base endpoint URL to send metrics and traces to. Can optionally include the port number.
pub otel_exporter_otlp_endpoint: Option<String>,
/// Timeout (in milliseconds) for sending metrics and traces.
pub otel_exporter_otlp_timeout: Option<u64>,
/// Whether to use xray ID generator, (enable this if you plan to use AWS-XRAY)
pub use_xray_generator: bool,
/// Route Based Tracing
pub route_to_trace: Option<Vec<String>>,
/// Interval for collecting the metrics (such as gauge) in background thread
pub bg_metrics_collection_interval_in_secs: Option<u16>,
}
/// Telemetry / tracing.
#[derive(Default, Debug, Deserialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum LogFormat {
/// Default pretty log format
Default,
/// JSON based structured logging
#[default]
Json,
/// JSON based structured logging with pretty print
PrettyJson,
}
impl Config {
/// Default constructor.
pub fn new() -> Result<Self, config::ConfigError> {
Self::new_with_config_path(None)
}
/// Constructor expecting config path set explicitly.
pub fn new_with_config_path(
explicit_config_path: Option<PathBuf>,
) -> Result<Self, config::ConfigError> {
// Configuration values are picked up in the following priority order (1 being least
// priority):
// 1. Defaults from the implementation of the `Default` trait.
// 2. Values from config file. The config file accessed depends on the environment
// specified by the `RUN_ENV` environment variable. `RUN_ENV` can be one of
// `development`, `sandbox` or `production`. If nothing is specified for `RUN_ENV`,
// `/config/development.toml` file is read.
// 3. Environment variables prefixed with `ROUTER` and each level separated by double
// underscores.
//
// Values in config file override the defaults in `Default` trait, and the values set using
// environment variables override both the defaults and the config file values.
let environment = crate::env::which();
let config_path = Self::config_path(&environment.to_string(), explicit_config_path);
let config = Self::builder(&environment.to_string())?
.add_source(config::File::from(config_path).required(false))
.add_source(config::Environment::with_prefix("ROUTER").separator("__"))
.build()?;
// The logger may not yet be initialized when constructing the application configuration
#[allow(clippy::print_stderr)]
serde_path_to_error::deserialize(config).map_err(|error| {
crate::error!(%error, "Unable to deserialize configuration");
eprintln!("Unable to deserialize application configuration: {error}");
error.into_inner()
})
}
/// Construct config builder extending it by fall-back defaults and setting config file to load.
pub fn builder(
environment: &str,
) -> Result<config::ConfigBuilder<config::builder::DefaultState>, config::ConfigError> {
config::Config::builder()
// Here, it should be `set_override()` not `set_default()`.
// "env" can't be altered by config field.
// Should be single source of truth.
.set_override("env", environment)
}
/// Config path.
pub fn config_path(environment: &str, explicit_config_path: Option<PathBuf>) -> PathBuf {
let mut config_path = PathBuf::new();
if let Some(explicit_config_path_val) = explicit_config_path {
config_path.push(explicit_config_path_val);
} else {
let config_file_name = match environment {
"production" => "production.toml",
"sandbox" => "sandbox.toml",
_ => "development.toml",
};
let config_directory = Self::get_config_directory();
config_path.push(config_directory);
config_path.push(config_file_name);
}
config_path
}
/// Get the Directory for the config file
/// Read the env variable `CONFIG_DIR` or fallback to `config`
pub fn get_config_directory() -> PathBuf {
let mut config_path = PathBuf::new();
let config_directory =
std::env::var(crate::env::vars::CONFIG_DIR).unwrap_or_else(|_| "config".into());
config_path.push(crate::env::workspace_path());
config_path.push(config_directory);
config_path
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router_env/src/logger/storage.rs | crates/router_env/src/logger/storage.rs | //! Storing [layer](https://docs.rs/tracing-subscriber/0.3.15/tracing_subscriber/layer/trait.Layer.html) for Router.
use std::{collections::HashMap, fmt, time::Instant};
use tracing::{
field::{Field, Visit},
span::{Attributes, Record},
Id, Subscriber,
};
use tracing_subscriber::{layer::Context, Layer};
/// Storage to store key value pairs of spans.
#[derive(Clone, Debug)]
pub struct StorageSubscription;
/// Storage to store key value pairs of spans.
/// When new entry is crated it stores it in [HashMap] which is owned by `extensions`.
#[derive(Clone, Debug)]
pub struct Storage<'a> {
/// Hash map to store values.
pub values: HashMap<&'a str, serde_json::Value>,
}
impl<'a> Storage<'a> {
/// Default constructor.
pub fn new() -> Self {
Self::default()
}
pub fn record_value(&mut self, key: &'a str, value: serde_json::Value) {
if super::formatter::IMPLICIT_KEYS.contains(key) {
tracing::warn!(value =? value, "{} is a reserved entry. Skipping it.", key);
} else {
self.values.insert(key, value);
}
}
}
/// Default constructor.
impl Default for Storage<'_> {
fn default() -> Self {
Self {
values: HashMap::new(),
}
}
}
/// Visitor to store entry.
impl Visit for Storage<'_> {
/// A i64.
fn record_i64(&mut self, field: &Field, value: i64) {
self.record_value(field.name(), serde_json::Value::from(value));
}
/// A u64.
fn record_u64(&mut self, field: &Field, value: u64) {
self.record_value(field.name(), serde_json::Value::from(value));
}
/// A 64-bit floating point.
fn record_f64(&mut self, field: &Field, value: f64) {
self.record_value(field.name(), serde_json::Value::from(value));
}
/// A boolean.
fn record_bool(&mut self, field: &Field, value: bool) {
self.record_value(field.name(), serde_json::Value::from(value));
}
/// A string.
fn record_str(&mut self, field: &Field, value: &str) {
self.record_value(field.name(), serde_json::Value::from(value));
}
/// Otherwise.
fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
match field.name() {
// Skip fields which are already handled
name if name.starts_with("log.") => (),
name if name.starts_with("r#") => {
self.record_value(
#[allow(clippy::expect_used)]
name.get(2..)
.expect("field name must have a minimum of two characters"),
serde_json::Value::from(format!("{value:?}")),
);
}
name => {
self.record_value(name, serde_json::Value::from(format!("{value:?}")));
}
};
}
}
const PERSISTENT_KEYS: [&str; 6] = [
"payment_id",
"connector_name",
"merchant_id",
"flow",
"payment_method",
"status_code",
];
impl<S: Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>> Layer<S>
for StorageSubscription
{
/// On new span.
fn on_new_span(&self, attrs: &Attributes<'_>, id: &Id, ctx: Context<'_, S>) {
#[allow(clippy::expect_used)]
let span = ctx.span(id).expect("No span");
let mut extensions = span.extensions_mut();
let mut visitor = if let Some(parent_span) = span.parent() {
let mut extensions = parent_span.extensions_mut();
extensions
.get_mut::<Storage<'_>>()
.map(|v| v.to_owned())
.unwrap_or_default()
} else {
Storage::default()
};
attrs.record(&mut visitor);
extensions.insert(visitor);
}
/// On additional key value pairs store it.
fn on_record(&self, span: &Id, values: &Record<'_>, ctx: Context<'_, S>) {
#[allow(clippy::expect_used)]
let span = ctx.span(span).expect("No span");
let mut extensions = span.extensions_mut();
#[allow(clippy::expect_used)]
let visitor = extensions
.get_mut::<Storage<'_>>()
.expect("The span does not have storage");
values.record(visitor);
}
/// On enter store time.
fn on_enter(&self, span: &Id, ctx: Context<'_, S>) {
#[allow(clippy::expect_used)]
let span = ctx.span(span).expect("No span");
let mut extensions = span.extensions_mut();
if extensions.get_mut::<Instant>().is_none() {
extensions.insert(Instant::now());
}
}
/// On close create an entry about how long did it take.
fn on_close(&self, span: Id, ctx: Context<'_, S>) {
#[allow(clippy::expect_used)]
let span = ctx.span(&span).expect("No span");
let elapsed_milliseconds = {
let extensions = span.extensions();
extensions
.get::<Instant>()
.map(|i| i.elapsed().as_millis())
.unwrap_or(0)
};
if let Some(s) = span.extensions().get::<Storage<'_>>() {
s.values.iter().for_each(|(k, v)| {
if PERSISTENT_KEYS.contains(k) {
span.parent().and_then(|p| {
p.extensions_mut()
.get_mut::<Storage<'_>>()
.map(|s| s.record_value(k, v.to_owned()))
});
}
})
};
let mut extensions_mut = span.extensions_mut();
#[allow(clippy::expect_used)]
let visitor = extensions_mut
.get_mut::<Storage<'_>>()
.expect("No visitor in extensions");
if let Ok(elapsed) = serde_json::to_value(elapsed_milliseconds) {
visitor.record_value("elapsed_milliseconds", elapsed);
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router_env/src/logger/types.rs | crates/router_env/src/logger/types.rs | //! Types.
use serde::Deserialize;
use strum::{Display, EnumString};
pub use tracing::{
field::{Field, Visit},
Level, Value,
};
/// Category and tag of log event.
///
/// Don't hesitate to add your variant if it is missing here.
#[derive(Debug, Default, Deserialize, Clone, Display, EnumString)]
pub enum Tag {
/// General.
#[default]
General,
/// Redis: get.
RedisGet,
/// Redis: set.
RedisSet,
/// API: incoming web request.
ApiIncomingRequest,
/// API: outgoing web request.
ApiOutgoingRequest,
/// Data base: create.
DbCreate,
/// Data base: read.
DbRead,
/// Data base: updare.
DbUpdate,
/// Data base: delete.
DbDelete,
/// Begin Request
BeginRequest,
/// End Request
EndRequest,
/// Call initiated to connector.
InitiatedToConnector,
/// Event: general.
Event,
/// Compatibility Layer Request
CompatibilityLayerRequest,
}
/// API Flow
#[derive(Debug, Display, Clone, PartialEq, Eq)]
pub enum Flow {
/// Health check
HealthCheck,
/// Deep health Check
DeepHealthCheck,
/// OIDC Discovery endpoint
OidcDiscovery,
/// OIDC JWKS endpoint
OidcJwks,
/// OIDC Authorize endpoint
OidcAuthorize,
/// OIDC Token endpoint
OidcToken,
/// Organization create flow
OrganizationCreate,
/// Organization retrieve flow
OrganizationRetrieve,
/// Organization update flow
OrganizationUpdate,
/// Merchants account create flow.
MerchantsAccountCreate,
/// Merchants account retrieve flow.
MerchantsAccountRetrieve,
/// Merchants account update flow.
MerchantsAccountUpdate,
/// Merchants account delete flow.
MerchantsAccountDelete,
/// Merchant Connectors create flow.
MerchantConnectorsCreate,
/// Merchant Connectors retrieve flow.
MerchantConnectorsRetrieve,
/// Merchant account list
MerchantAccountList,
/// Merchant Connectors update flow.
MerchantConnectorsUpdate,
/// Merchant Connectors delete flow.
MerchantConnectorsDelete,
/// Merchant Connectors list flow.
MerchantConnectorsList,
/// Merchant Transfer Keys
MerchantTransferKey,
/// ConfigKey create flow.
ConfigKeyCreate,
/// ConfigKey fetch flow.
ConfigKeyFetch,
/// Enable platform account flow.
EnablePlatformAccount,
/// ConfigKey Update flow.
ConfigKeyUpdate,
/// ConfigKey Delete flow.
ConfigKeyDelete,
/// Customers create flow.
CustomersCreate,
/// Customers retrieve flow.
CustomersRetrieve,
/// Customers update flow.
CustomersUpdate,
/// Customers delete flow.
CustomersDelete,
/// Customers get mandates flow.
CustomersGetMandates,
/// Create an Ephemeral Key.
EphemeralKeyCreate,
/// Delete an Ephemeral Key.
EphemeralKeyDelete,
/// Mandates retrieve flow.
MandatesRetrieve,
/// Mandates revoke flow.
MandatesRevoke,
/// Mandates list flow.
MandatesList,
/// Payment methods create flow.
PaymentMethodsCreate,
/// Payment methods migrate flow.
PaymentMethodsMigrate,
/// Payment methods batch update flow.
PaymentMethodsBatchUpdate,
/// Payment methods batch retrieve flow.
PaymentMethodsBatchRetrieve,
/// Payment methods list flow.
PaymentMethodsList,
/// Payment method save flow
PaymentMethodSave,
/// Customer payment methods list flow.
CustomerPaymentMethodsList,
/// Payment methods token data get flow.
GetPaymentMethodTokenData,
/// List Customers for a merchant
CustomersList,
///List Customers for a merchant with constraints.
CustomersListWithConstraints,
/// Retrieve countries and currencies for connector and payment method
ListCountriesCurrencies,
/// Payment method create collect link flow.
PaymentMethodCollectLink,
/// Payment methods retrieve flow.
PaymentMethodsRetrieve,
/// Payment methods update flow.
PaymentMethodsUpdate,
/// Payment methods delete flow.
PaymentMethodsDelete,
/// Network token status check flow.
NetworkTokenStatusCheck,
/// Default Payment method flow.
DefaultPaymentMethodsSet,
/// Payments create flow.
PaymentsCreate,
/// Payments Retrieve flow.
PaymentsRetrieve,
/// Payments Retrieve force sync flow.
PaymentsRetrieveForceSync,
/// Payments Retrieve using merchant reference id
PaymentsRetrieveUsingMerchantReferenceId,
/// Payments update flow.
PaymentsUpdate,
/// Payments confirm flow.
PaymentsConfirm,
/// Payments capture flow.
PaymentsCapture,
/// Payments cancel flow.
PaymentsCancel,
/// Payments cancel post capture flow.
PaymentsCancelPostCapture,
/// Payments approve flow.
PaymentsApprove,
/// Payments reject flow.
PaymentsReject,
/// Payments Session Token flow
PaymentsSessionToken,
/// Payments start flow.
PaymentsStart,
/// Payments list flow.
PaymentsList,
/// Payments filters flow
PaymentsFilters,
/// Payments aggregates flow
PaymentsAggregate,
/// Payments Create Intent flow
PaymentsCreateIntent,
/// Payments Get Intent flow
PaymentsGetIntent,
/// Payments Update Intent flow
PaymentsUpdateIntent,
/// Payments confirm intent flow
PaymentsConfirmIntent,
/// Payments create and confirm intent flow
PaymentsCreateAndConfirmIntent,
/// Payment attempt list flow
PaymentAttemptsList,
#[cfg(feature = "payouts")]
/// Payouts create flow
PayoutsCreate,
#[cfg(feature = "payouts")]
/// Payouts retrieve flow.
PayoutsRetrieve,
#[cfg(feature = "payouts")]
/// Payouts update flow.
PayoutsUpdate,
/// Payouts confirm flow.
PayoutsConfirm,
#[cfg(feature = "payouts")]
/// Payouts cancel flow.
PayoutsCancel,
#[cfg(feature = "payouts")]
/// Payouts fulfill flow.
PayoutsFulfill,
#[cfg(feature = "payouts")]
/// Payouts list flow.
PayoutsList,
#[cfg(feature = "payouts")]
/// Payouts filter flow.
PayoutsFilter,
/// Payouts accounts flow.
PayoutsAccounts,
/// Payout link initiate flow
PayoutLinkInitiate,
/// Payments Redirect flow
PaymentsRedirect,
/// Payemnts Complete Authorize Flow
PaymentsCompleteAuthorize,
/// Refunds create flow.
RefundsCreate,
/// Refunds retrieve flow.
RefundsRetrieve,
/// Refunds retrieve force sync flow.
RefundsRetrieveForceSync,
/// Refunds update flow.
RefundsUpdate,
/// Refunds list flow.
RefundsList,
/// Refunds filters flow
RefundsFilters,
/// Refunds aggregates flow
RefundsAggregate,
// Retrieve forex flow.
RetrieveForexFlow,
/// Toggles recon service for a merchant.
ReconMerchantUpdate,
/// Recon token request flow.
ReconTokenRequest,
/// Initial request for recon service.
ReconServiceRequest,
/// Recon token verification flow
ReconVerifyToken,
/// Routing create flow,
RoutingCreateConfig,
/// Routing link config
RoutingLinkConfig,
/// Routing link config
RoutingUnlinkConfig,
/// Routing retrieve config
RoutingRetrieveConfig,
/// Routing retrieve active config
RoutingRetrieveActiveConfig,
/// Routing retrieve default config
RoutingRetrieveDefaultConfig,
/// Routing retrieve dictionary
RoutingRetrieveDictionary,
/// Rule migration for decision-engine
DecisionEngineRuleMigration,
/// Routing update config
RoutingUpdateConfig,
/// Routing update default config
RoutingUpdateDefaultConfig,
/// Routing delete config
RoutingDeleteConfig,
/// Subscription create flow,
CreateSubscription,
/// Subscription get items flow,
GetSubscriptionItemsForSubscription,
/// Subscription confirm flow,
ConfirmSubscription,
/// Subscription create and confirm flow,
CreateAndConfirmSubscription,
/// Get Subscription flow
GetSubscription,
/// Update Subscription flow
UpdateSubscription,
/// Get Subscription estimate flow
GetSubscriptionEstimate,
/// Pause Subscription flow
PauseSubscription,
/// Resume Subscription flow
ResumeSubscription,
/// Cancel Subscription flow
CancelSubscription,
/// Create dynamic routing
CreateDynamicRoutingConfig,
/// Toggle dynamic routing
ToggleDynamicRouting,
/// Update dynamic routing config
UpdateDynamicRoutingConfigs,
/// Add record to blocklist
AddToBlocklist,
/// Delete record from blocklist
DeleteFromBlocklist,
/// List entries from blocklist
ListBlocklist,
/// Toggle blocklist for merchant
ToggleBlocklistGuard,
/// Incoming Webhook Receive
IncomingWebhookReceive,
/// Recovery incoming webhook receive
RecoveryIncomingWebhookReceive,
/// Validate payment method flow
ValidatePaymentMethod,
/// API Key create flow
ApiKeyCreate,
/// API Key retrieve flow
ApiKeyRetrieve,
/// API Key update flow
ApiKeyUpdate,
/// API Key revoke flow
ApiKeyRevoke,
/// API Key list flow
ApiKeyList,
/// Dispute Retrieve flow
DisputesRetrieve,
/// Dispute List flow
DisputesList,
/// Dispute Filters flow
DisputesFilters,
/// Cards Info flow
CardsInfo,
/// Create File flow
CreateFile,
/// Delete File flow
DeleteFile,
/// Retrieve File flow
RetrieveFile,
/// Dispute Evidence submission flow
DisputesEvidenceSubmit,
/// Create Config Key flow
CreateConfigKey,
/// Attach Dispute Evidence flow
AttachDisputeEvidence,
/// Delete Dispute Evidence flow
DeleteDisputeEvidence,
/// Disputes aggregate flow
DisputesAggregate,
/// Retrieve Dispute Evidence flow
RetrieveDisputeEvidence,
/// Invalidate cache flow
CacheInvalidate,
/// Payment Link Retrieve flow
PaymentLinkRetrieve,
/// payment Link Initiate flow
PaymentLinkInitiate,
/// payment Link Initiate flow
PaymentSecureLinkInitiate,
/// Payment Link List flow
PaymentLinkList,
/// Payment Link Status
PaymentLinkStatus,
/// Create a profile
ProfileCreate,
/// Update a profile
ProfileUpdate,
/// Retrieve a profile
ProfileRetrieve,
/// Delete a profile
ProfileDelete,
/// List all the profiles for a merchant
ProfileList,
/// Different verification flows
Verification,
/// Rust locker migration
RustLockerMigration,
/// Gsm Rule Creation flow
GsmRuleCreate,
/// Gsm Rule Retrieve flow
GsmRuleRetrieve,
/// Gsm Rule Update flow
GsmRuleUpdate,
/// Apple pay certificates migration
ApplePayCertificatesMigration,
/// Gsm Rule Delete flow
GsmRuleDelete,
/// Get data from embedded flow
GetDataFromHyperswitchAiFlow,
// List all chat interactions
ListAllChatInteractions,
/// User Sign Up
UserSignUp,
/// User Sign Up
UserSignUpWithMerchantId,
/// User Sign In
UserSignIn,
/// User transfer key
UserTransferKey,
/// User connect account
UserConnectAccount,
/// Upsert Decision Manager Config
DecisionManagerUpsertConfig,
/// Delete Decision Manager Config
DecisionManagerDeleteConfig,
/// Retrieve Decision Manager Config
DecisionManagerRetrieveConfig,
/// Manual payment fulfillment acknowledgement
FrmFulfillment,
/// Get connectors feature matrix
FeatureMatrix,
/// Change password flow
ChangePassword,
/// Signout flow
Signout,
/// Set Dashboard Metadata flow
SetDashboardMetadata,
/// Get Multiple Dashboard Metadata flow
GetMultipleDashboardMetadata,
/// Payment Connector Verify
VerifyPaymentConnector,
/// Internal user signup
InternalUserSignup,
/// Create tenant level user
TenantUserCreate,
/// Switch org
SwitchOrg,
/// Switch merchant v2
SwitchMerchantV2,
/// Switch profile
SwitchProfile,
/// Get permission info
GetAuthorizationInfo,
/// Get Roles info
GetRolesInfo,
/// Get Parent Group Info
GetParentGroupInfo,
/// List roles v2
ListRolesV2,
/// List invitable roles at entity level
ListInvitableRolesAtEntityLevel,
/// List updatable roles at entity level
ListUpdatableRolesAtEntityLevel,
/// Get role
GetRole,
/// Get parent info for role
GetRoleV2,
/// Get role from token
GetRoleFromToken,
/// Get resources and groups for role from token
GetRoleFromTokenV2,
/// Get parent groups info for role from token
GetParentGroupsInfoForRoleFromToken,
/// Update user role
UpdateUserRole,
/// Create merchant account for user in a org
UserMerchantAccountCreate,
/// Create Platform
CreatePlatformAccount,
/// Create Org in a given tenancy
UserOrgMerchantCreate,
/// Generate Sample Data
GenerateSampleData,
/// Delete Sample Data
DeleteSampleData,
/// Get details of a user
GetUserDetails,
/// Get details of a user role in a merchant account
GetUserRoleDetails,
/// PaymentMethodAuth Link token create
PmAuthLinkTokenCreate,
/// PaymentMethodAuth Exchange token create
PmAuthExchangeToken,
/// Get reset password link
ForgotPassword,
/// Reset password using link
ResetPassword,
/// Force set or force change password
RotatePassword,
/// Invite multiple users
InviteMultipleUser,
/// Reinvite user
ReInviteUser,
/// Accept invite from email
AcceptInviteFromEmail,
/// Delete user role
DeleteUserRole,
/// Incremental Authorization flow
PaymentsIncrementalAuthorization,
/// Extend Authorization flow
PaymentsExtendAuthorization,
/// Get action URL for connector onboarding
GetActionUrl,
/// Sync connector onboarding status
SyncOnboardingStatus,
/// Reset tracking id
ResetTrackingId,
/// Verify email Token
VerifyEmail,
/// Send verify email
VerifyEmailRequest,
/// Update user account details
UpdateUserAccountDetails,
/// Accept user invitation using entities
AcceptInvitationsV2,
/// Accept user invitation using entities before user login
AcceptInvitationsPreAuth,
/// Initiate external authentication for a payment
PaymentsExternalAuthentication,
/// Authorize the payment after external 3ds authentication
PaymentsAuthorize,
/// Create Role
CreateRole,
/// Create Role V2
CreateRoleV2,
/// Update Role
UpdateRole,
/// User email flow start
UserFromEmail,
/// Begin TOTP
TotpBegin,
/// Reset TOTP
TotpReset,
/// Verify TOTP
TotpVerify,
/// Update TOTP secret
TotpUpdate,
/// Verify Access Code
RecoveryCodeVerify,
/// Generate or Regenerate recovery codes
RecoveryCodesGenerate,
/// Terminate two factor authentication
TerminateTwoFactorAuth,
/// Check 2FA status
TwoFactorAuthStatus,
/// Create user authentication method
CreateUserAuthenticationMethod,
/// Update user authentication method
UpdateUserAuthenticationMethod,
/// List user authentication methods
ListUserAuthenticationMethods,
/// Get sso auth url
GetSsoAuthUrl,
/// Signin with SSO
SignInWithSso,
/// Auth Select
AuthSelect,
/// List Orgs for user
ListOrgForUser,
/// List Merchants for user in org
ListMerchantsForUserInOrg,
/// List Profile for user in org and merchant
ListProfileForUserInOrgAndMerchant,
/// List Users in Org
ListUsersInLineage,
/// List invitations for user
ListInvitationsForUser,
/// Get theme using lineage
GetThemeUsingLineage,
/// Get theme using theme id
GetThemeUsingThemeId,
/// Upload file to theme storage
UploadFileToThemeStorage,
/// Create theme
CreateTheme,
/// Update theme
UpdateTheme,
/// Delete theme
DeleteTheme,
/// Create user theme
CreateUserTheme,
/// Update user theme
UpdateUserTheme,
/// Delete user theme
DeleteUserTheme,
/// Upload file to user theme storage
UploadFileToUserThemeStorage,
/// Get user theme using theme id
GetUserThemeUsingThemeId,
///List All Themes In Lineage
ListAllThemesInLineage,
/// Get user theme using lineage
GetUserThemeUsingLineage,
/// List initial webhook delivery attempts
WebhookEventInitialDeliveryAttemptList,
/// List delivery attempts for a webhook event
WebhookEventDeliveryAttemptList,
/// Manually retry the delivery for a webhook event
WebhookEventDeliveryRetry,
/// Retrieve status of the Poll
RetrievePollStatus,
/// Toggles the extended card info feature in profile level
ToggleExtendedCardInfo,
/// Toggles the extended card info feature in profile level
ToggleConnectorAgnosticMit,
/// Get the extended card info associated to a payment_id
GetExtendedCardInfo,
/// Manually update the refund details like status, error code, error message etc.
RefundsManualUpdate,
/// Manually update the payment details like status, error code, error message etc.
PaymentsManualUpdate,
#[cfg(feature = "payouts")]
/// Manually update the payout details like status, error code, error message etc.
PayoutsManualUpdate,
/// Dynamic Tax Calcultion
SessionUpdateTaxCalculation,
ProxyConfirmIntent,
/// Payments post session tokens flow
PaymentsPostSessionTokens,
/// Payments Update Metadata
PaymentsUpdateMetadata,
/// Payments start redirection flow
PaymentStartRedirection,
/// Volume split on the routing type
VolumeSplitOnRoutingType,
/// Routing evaluate rule flow
RoutingEvaluateRule,
/// Relay flow
Relay,
/// Relay retrieve flow
RelayRetrieve,
/// Card tokenization flow
TokenizeCard,
/// Card tokenization using payment method flow
TokenizeCardUsingPaymentMethodId,
/// Cards batch tokenization flow
TokenizeCardBatch,
/// Incoming Relay Webhook Receive
IncomingRelayWebhookReceive,
/// Generate Hypersense Token
HypersenseTokenRequest,
/// Verify Hypersense Token
HypersenseVerifyToken,
/// Signout Hypersense Token
HypersenseSignoutToken,
/// Payment Method Session Create
PaymentMethodSessionCreate,
/// Payment Method Session Retrieve
PaymentMethodSessionRetrieve,
// Payment Method Session Update
PaymentMethodSessionUpdate,
/// Update a saved payment method using the payment methods session
PaymentMethodSessionUpdateSavedPaymentMethod,
/// Delete a saved payment method using the payment methods session
PaymentMethodSessionDeleteSavedPaymentMethod,
/// Confirm a payment method session with payment method data
PaymentMethodSessionConfirm,
/// Create Cards Info flow
CardsInfoCreate,
/// Update Cards Info flow
CardsInfoUpdate,
/// Cards Info migrate flow
CardsInfoMigrate,
///Total payment method count for merchant
TotalPaymentMethodCount,
/// Process Tracker Revenue Recovery Workflow Retrieve
RevenueRecoveryRetrieve,
/// Process Tracker Revenue Recovery Workflow Resume
RevenueRecoveryResume,
/// Tokenization flow
TokenizationCreate,
/// Tokenization retrieve flow
TokenizationRetrieve,
/// Clone Connector flow
CloneConnector,
/// Authentication Create flow
AuthenticationCreate,
/// Authentication Eligibility flow
AuthenticationEligibility,
/// Authentication Sync flow
AuthenticationSync,
/// Authentication Sync Post Update flow
AuthenticationSyncPostUpdate,
/// Authentication Authenticate flow
AuthenticationAuthenticate,
/// Authentication Session Token flow
AuthenticationSessionToken,
/// Authentication Eligibility Check flow
AuthenticationEligibilityCheck,
/// Authentication Retrieve Eligibility Check flow
AuthenticationRetrieveEligibilityCheck,
///Proxy Flow
Proxy,
/// Profile Acquirer Create flow
ProfileAcquirerCreate,
/// Profile Acquirer Update flow
ProfileAcquirerUpdate,
/// ThreeDs Decision Rule Execute flow
ThreeDsDecisionRuleExecute,
/// Incoming Network Token Webhook Receive
IncomingNetworkTokenWebhookReceive,
/// Decision Engine Decide Gateway Call
DecisionEngineDecideGatewayCall,
/// Decision Engine Gateway Feedback Call
DecisionEngineGatewayFeedbackCall,
/// Recovery payments create flow.
RecoveryPaymentsCreate,
/// Tokenization delete flow
TokenizationDelete,
/// Payment method data backfill flow
RecoveryDataBackfill,
/// Revenue recovery Redis operations flow
RevenueRecoveryRedis,
/// Payment Method balance check flow
PaymentMethodBalanceCheck,
/// Payments Submit Eligibility flow
PaymentsSubmitEligibility,
/// Apply payment method data flow
ApplyPaymentMethodData,
/// Payouts aggregates flow
PayoutsAggregate,
}
/// Trait for providing generic behaviour to flow metric
pub trait FlowMetric: ToString + std::fmt::Debug + Clone {}
impl FlowMetric for Flow {}
/// Category of log event.
#[derive(Debug)]
pub enum Category {
/// Redis: general.
Redis,
/// API: general.
Api,
/// Database: general.
Store,
/// Event: general.
Event,
/// General: general.
General,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router_env/src/logger/formatter.rs | crates/router_env/src/logger/formatter.rs | //! Formatting [layer](https://docs.rs/tracing-subscriber/0.3.15/tracing_subscriber/layer/trait.Layer.html) for Router.
use std::{
collections::{HashMap, HashSet},
fmt,
io::Write,
sync::LazyLock,
};
use config::ConfigError;
use serde::ser::{SerializeMap, Serializer};
use serde_json::{ser::Formatter, Value};
// use time::format_description::well_known::Rfc3339;
use time::format_description::well_known::Iso8601;
use tracing::{Event, Metadata, Subscriber};
use tracing_subscriber::{
fmt::MakeWriter,
layer::Context,
registry::{LookupSpan, SpanRef},
Layer,
};
use crate::Storage;
// TODO: Documentation coverage for this crate
// Implicit keys
const MESSAGE: &str = "message";
const HOSTNAME: &str = "hostname";
const PID: &str = "pid";
const ENV: &str = "env";
const VERSION: &str = "version";
const BUILD: &str = "build";
const LEVEL: &str = "level";
const TARGET: &str = "target";
const SERVICE: &str = "service";
const LINE: &str = "line";
const FILE: &str = "file";
const FN: &str = "fn";
const FULL_NAME: &str = "full_name";
const TIME: &str = "time";
// Extra implicit keys. Keys that are provided during runtime but should be treated as
// implicit in the logs
const FLOW: &str = "flow";
const MERCHANT_AUTH: &str = "merchant_authentication";
const MERCHANT_ID: &str = "merchant_id";
const REQUEST_METHOD: &str = "request_method";
const REQUEST_URL_PATH: &str = "request_url_path";
const REQUEST_ID: &str = "request_id";
const WORKFLOW_ID: &str = "workflow_id";
const GLOBAL_ID: &str = "global_id";
const SESSION_ID: &str = "session_id";
/// Set of predefined implicit keys.
pub static IMPLICIT_KEYS: LazyLock<rustc_hash::FxHashSet<&str>> = LazyLock::new(|| {
let mut set = rustc_hash::FxHashSet::default();
set.insert(HOSTNAME);
set.insert(PID);
set.insert(ENV);
set.insert(VERSION);
set.insert(BUILD);
set.insert(LEVEL);
set.insert(TARGET);
set.insert(SERVICE);
set.insert(LINE);
set.insert(FILE);
set.insert(FN);
set.insert(FULL_NAME);
set.insert(TIME);
set
});
/// Extra implicit keys. Keys that are not purely implicit but need to be logged alongside
/// other implicit keys in the log json.
pub static EXTRA_IMPLICIT_KEYS: LazyLock<rustc_hash::FxHashSet<&str>> = LazyLock::new(|| {
let mut set = rustc_hash::FxHashSet::default();
set.insert(MESSAGE);
set.insert(FLOW);
set.insert(MERCHANT_AUTH);
set.insert(MERCHANT_ID);
set.insert(REQUEST_METHOD);
set.insert(REQUEST_URL_PATH);
set.insert(REQUEST_ID);
set.insert(GLOBAL_ID);
set.insert(SESSION_ID);
set.insert(WORKFLOW_ID);
set
});
/// Describe type of record: entering a span, exiting a span, an event.
#[derive(Clone, Debug)]
pub enum RecordType {
/// Entering a span.
EnterSpan,
/// Exiting a span.
ExitSpan,
/// Event.
Event,
}
impl fmt::Display for RecordType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let repr = match self {
Self::EnterSpan => "START",
Self::ExitSpan => "END",
Self::Event => "EVENT",
};
write!(f, "{repr}")
}
}
/// Format log records.
/// `FormattingLayer` relies on the `tracing_bunyan_formatter::JsonStorageLayer` which is storage of entries.
#[derive(Debug)]
pub struct FormattingLayer<W, F>
where
W: for<'a> MakeWriter<'a> + 'static,
F: Formatter + Clone,
{
dst_writer: W,
pid: u32,
hostname: String,
env: String,
service: String,
#[cfg(feature = "vergen")]
version: String,
#[cfg(feature = "vergen")]
build: String,
default_fields: HashMap<String, Value>,
formatter: F,
}
impl<W, F> FormattingLayer<W, F>
where
W: for<'a> MakeWriter<'a> + 'static,
F: Formatter + Clone,
{
/// Constructor of `FormattingLayer`.
///
/// A `name` will be attached to all records during formatting.
/// A `dst_writer` to forward all records.
///
/// ## Example
/// ```rust
/// let formatting_layer = router_env::FormattingLayer::new("my_service", std::io::stdout, serde_json::ser::CompactFormatter);
/// ```
pub fn new(
service: &str,
dst_writer: W,
formatter: F,
) -> error_stack::Result<Self, ConfigError> {
Self::new_with_implicit_entries(service, dst_writer, HashMap::new(), formatter)
}
/// Construct of `FormattingLayer with implicit default entries.
pub fn new_with_implicit_entries(
service: &str,
dst_writer: W,
default_fields: HashMap<String, Value>,
formatter: F,
) -> error_stack::Result<Self, ConfigError> {
let pid = std::process::id();
let hostname = gethostname::gethostname().to_string_lossy().into_owned();
let service = service.to_string();
#[cfg(feature = "vergen")]
let version = crate::version!().to_string();
#[cfg(feature = "vergen")]
let build = crate::build!().to_string();
let env = crate::env::which().to_string();
for key in default_fields.keys() {
if IMPLICIT_KEYS.contains(key.as_str()) {
return Err(ConfigError::Message(format!(
"A reserved key `{key}` was included in `default_fields` in the log formatting layer"
))
.into());
}
}
Ok(Self {
dst_writer,
pid,
hostname,
env,
service,
#[cfg(feature = "vergen")]
version,
#[cfg(feature = "vergen")]
build,
default_fields,
formatter,
})
}
/// Serialize common for both span and event entries.
fn common_serialize<S>(
&self,
map_serializer: &mut impl SerializeMap<Error = serde_json::Error>,
metadata: &Metadata<'_>,
span: Option<&SpanRef<'_, S>>,
storage: &Storage<'_>,
name: &str,
) -> Result<(), std::io::Error>
where
S: Subscriber + for<'a> LookupSpan<'a>,
{
let is_extra = |s: &str| !IMPLICIT_KEYS.contains(s);
let is_extra_implicit = |s: &str| is_extra(s) && EXTRA_IMPLICIT_KEYS.contains(s);
map_serializer.serialize_entry(HOSTNAME, &self.hostname)?;
map_serializer.serialize_entry(PID, &self.pid)?;
map_serializer.serialize_entry(ENV, &self.env)?;
#[cfg(feature = "vergen")]
map_serializer.serialize_entry(VERSION, &self.version)?;
#[cfg(feature = "vergen")]
map_serializer.serialize_entry(BUILD, &self.build)?;
map_serializer.serialize_entry(LEVEL, &format_args!("{}", metadata.level()))?;
map_serializer.serialize_entry(TARGET, metadata.target())?;
map_serializer.serialize_entry(SERVICE, &self.service)?;
map_serializer.serialize_entry(LINE, &metadata.line())?;
map_serializer.serialize_entry(FILE, &metadata.file())?;
map_serializer.serialize_entry(FN, name)?;
map_serializer
.serialize_entry(FULL_NAME, &format_args!("{}::{}", metadata.target(), name))?;
if let Ok(time) = &time::OffsetDateTime::now_utc().format(&Iso8601::DEFAULT) {
map_serializer.serialize_entry(TIME, time)?;
}
// Write down implicit default entries.
for (key, value) in self.default_fields.iter() {
map_serializer.serialize_entry(key, value)?;
}
#[cfg(feature = "log_custom_entries_to_extra")]
let mut extra = serde_json::Map::default();
let mut explicit_entries_set: HashSet<&str> = HashSet::default();
// Write down explicit event's entries.
for (key, value) in storage.values.iter() {
if is_extra_implicit(key) {
#[cfg(feature = "log_extra_implicit_fields")]
map_serializer.serialize_entry(key, value)?;
explicit_entries_set.insert(key);
} else if is_extra(key) {
#[cfg(feature = "log_custom_entries_to_extra")]
extra.insert(key.to_string(), value.clone());
#[cfg(not(feature = "log_custom_entries_to_extra"))]
map_serializer.serialize_entry(key, value)?;
explicit_entries_set.insert(key);
} else {
tracing::warn!(
?key,
?value,
"Attempting to log a reserved entry. It won't be added to the logs"
);
}
}
// Write down entries from the span, if it exists.
if let Some(span) = &span {
let extensions = span.extensions();
if let Some(visitor) = extensions.get::<Storage<'_>>() {
for (key, value) in &visitor.values {
if is_extra_implicit(key) && !explicit_entries_set.contains(key) {
#[cfg(feature = "log_extra_implicit_fields")]
map_serializer.serialize_entry(key, value)?;
} else if is_extra(key) && !explicit_entries_set.contains(key) {
#[cfg(feature = "log_custom_entries_to_extra")]
extra.insert(key.to_string(), value.clone());
#[cfg(not(feature = "log_custom_entries_to_extra"))]
map_serializer.serialize_entry(key, value)?;
} else {
tracing::warn!(
?key,
?value,
"Attempting to log a reserved entry. It won't be added to the logs"
);
}
}
}
}
#[cfg(feature = "log_custom_entries_to_extra")]
map_serializer.serialize_entry("extra", &extra)?;
Ok(())
}
/// Flush memory buffer into an output stream trailing it with next line.
///
/// Should be done by single `write_all` call to avoid fragmentation of log because of mutlithreading.
fn flush(&self, mut buffer: Vec<u8>) -> Result<(), std::io::Error> {
buffer.write_all(b"\n")?;
self.dst_writer.make_writer().write_all(&buffer)
}
/// Serialize entries of span.
fn span_serialize<S>(
&self,
span: &SpanRef<'_, S>,
ty: RecordType,
) -> Result<Vec<u8>, std::io::Error>
where
S: Subscriber + for<'a> LookupSpan<'a>,
{
let mut buffer = Vec::new();
let mut serializer =
serde_json::Serializer::with_formatter(&mut buffer, self.formatter.clone());
let mut map_serializer = serializer.serialize_map(None)?;
let message = Self::span_message(span, ty);
let mut storage = Storage::default();
storage.record_value("message", message.into());
self.common_serialize(
&mut map_serializer,
span.metadata(),
Some(span),
&storage,
span.name(),
)?;
map_serializer.end()?;
Ok(buffer)
}
/// Serialize event into a buffer of bytes using parent span.
pub fn event_serialize<S>(
&self,
span: Option<&SpanRef<'_, S>>,
event: &Event<'_>,
) -> std::io::Result<Vec<u8>>
where
S: Subscriber + for<'a> LookupSpan<'a>,
{
let mut buffer = Vec::new();
let mut serializer =
serde_json::Serializer::with_formatter(&mut buffer, self.formatter.clone());
let mut map_serializer = serializer.serialize_map(None)?;
let mut storage = Storage::default();
event.record(&mut storage);
let name = span.map_or("?", SpanRef::name);
Self::event_message(span, event, &mut storage);
self.common_serialize(&mut map_serializer, event.metadata(), span, &storage, name)?;
map_serializer.end()?;
Ok(buffer)
}
/// Format message of a span.
///
/// Example: "[FN_WITHOUT_COLON - START]"
fn span_message<S>(span: &SpanRef<'_, S>, ty: RecordType) -> String
where
S: Subscriber + for<'a> LookupSpan<'a>,
{
format!("[{} - {}]", span.metadata().name().to_uppercase(), ty)
}
/// Format message of an event.
///
/// Examples: "[FN_WITHOUT_COLON - EVENT] Message"
fn event_message<S>(span: Option<&SpanRef<'_, S>>, event: &Event<'_>, storage: &mut Storage<'_>)
where
S: Subscriber + for<'a> LookupSpan<'a>,
{
// Get value of kept "message" or "target" if does not exist.
let message = storage
.values
.entry("message")
.or_insert_with(|| event.metadata().target().into());
// Prepend the span name to the message if span exists.
if let (Some(span), Value::String(a)) = (span, message) {
*a = format!("{} {}", Self::span_message(span, RecordType::Event), a,);
}
}
}
#[allow(clippy::expect_used)]
impl<S, W, F> Layer<S> for FormattingLayer<W, F>
where
S: Subscriber + for<'a> LookupSpan<'a>,
W: for<'a> MakeWriter<'a> + 'static,
F: Formatter + Clone + 'static,
{
fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
// Event could have no span.
let span = ctx.lookup_current();
let result: std::io::Result<Vec<u8>> = self.event_serialize(span.as_ref(), event);
if let Ok(formatted) = result {
let _ = self.flush(formatted);
}
}
#[cfg(feature = "log_active_span_json")]
fn on_enter(&self, id: &tracing::Id, ctx: Context<'_, S>) {
let span = ctx.span(id).expect("No span");
if let Ok(serialized) = self.span_serialize(&span, RecordType::EnterSpan) {
let _ = self.flush(serialized);
}
}
#[cfg(not(feature = "log_active_span_json"))]
fn on_close(&self, id: tracing::Id, ctx: Context<'_, S>) {
let span = ctx.span(&id).expect("No span");
if span.parent().is_none() {
if let Ok(serialized) = self.span_serialize(&span, RecordType::ExitSpan) {
let _ = self.flush(serialized);
}
}
}
#[cfg(feature = "log_active_span_json")]
fn on_close(&self, id: tracing::Id, ctx: Context<'_, S>) {
let span = ctx.span(&id).expect("No span");
if let Ok(serialized) = self.span_serialize(&span, RecordType::ExitSpan) {
let _ = self.flush(serialized);
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router_env/src/logger/defaults.rs | crates/router_env/src/logger/defaults.rs | impl Default for super::config::LogFile {
fn default() -> Self {
Self {
enabled: true,
path: "logs".into(),
file_name: "debug.log".into(),
level: super::config::Level(tracing::Level::DEBUG),
filtering_directive: None,
}
}
}
impl Default for super::config::LogConsole {
fn default() -> Self {
Self {
enabled: false,
level: super::config::Level(tracing::Level::INFO),
log_format: super::config::LogFormat::Json,
filtering_directive: None,
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router_env/tests/logger.rs | crates/router_env/tests/logger.rs | mod test_module;
use ::config::ConfigError;
use router_env::TelemetryGuard;
use self::test_module::fn_with_colon;
fn logger() -> error_stack::Result<&'static TelemetryGuard, ConfigError> {
use std::sync::OnceLock;
static INSTANCE: OnceLock<TelemetryGuard> = OnceLock::new();
#[allow(clippy::unwrap_used)]
Ok(INSTANCE.get_or_init(|| {
let config = router_env::Config::new().unwrap();
router_env::setup(&config.log, "router_env_test", []).unwrap()
}))
}
#[tokio::test]
async fn basic() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
logger()?;
fn_with_colon(13).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_env/tests/test_module.rs | crates/router_env/tests/test_module.rs | use router_env as logger;
#[tracing::instrument(skip_all)]
pub async fn fn_with_colon(val: i32) {
let a = 13;
let b = 31;
logger::log!(
logger::Level::WARN,
?a,
?b,
tag = ?logger::Tag::ApiIncomingRequest,
category = ?logger::Category::Api,
flow = "some_flow",
session_id = "some_session",
answer = 13,
message2 = "yyy",
message = "Experiment",
val,
);
fn_without_colon(131).await;
}
#[tracing::instrument(fields(val3 = "abc"), skip_all)]
pub async fn fn_without_colon(val: i32) {
let a = 13;
let b = 31;
// trace_macros!(true);
logger::log!(
logger::Level::INFO,
?a,
?b,
tag = ?logger::Tag::ApiIncomingRequest,
category = ?logger::Category::Api,
flow = "some_flow",
session_id = "some_session",
answer = 13,
message2 = "yyy",
message = "Experiment",
val,
);
// trace_macros!(false);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/router_env/tests/env.rs | crates/router_env/tests/env.rs | #[cfg(feature = "vergen")]
use router_env as env;
#[cfg(feature = "vergen")]
#[tokio::test]
async fn basic() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
println!("CARGO_PKG_VERSION : {:?}", env!("CARGO_PKG_VERSION"));
println!("CARGO_PROFILE : {:?}", env!("CARGO_PROFILE"));
println!(
"GIT_COMMIT_TIMESTAMP : {:?}",
env!("VERGEN_GIT_COMMIT_TIMESTAMP")
);
println!("GIT_SHA : {:?}", env!("VERGEN_GIT_SHA"));
println!("RUSTC_SEMVER : {:?}", env!("VERGEN_RUSTC_SEMVER"));
println!(
"CARGO_TARGET_TRIPLE : {:?}",
env!("VERGEN_CARGO_TARGET_TRIPLE")
);
Ok(())
}
#[cfg(feature = "vergen")]
#[tokio::test]
async fn env_macro() {
println!("version : {:?}", env::version!());
println!("build : {:?}", env::build!());
println!("commit : {:?}", env::commit!());
// println!("platform : {:?}", env::platform!());
assert!(!env::version!().is_empty());
assert!(!env::build!().is_empty());
assert!(!env::commit!().is_empty());
// assert!(env::platform!().len() > 0);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/test_utils/src/lib.rs | crates/test_utils/src/lib.rs | #![allow(clippy::print_stdout, clippy::print_stderr)]
pub mod connector_auth;
pub mod newman_runner;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/test_utils/src/connector_auth.rs | crates/test_utils/src/connector_auth.rs | use std::{collections::HashMap, env};
use masking::Secret;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ConnectorAuthentication {
pub aci: Option<BodyKey>,
#[cfg(not(feature = "payouts"))]
pub adyen: Option<BodyKey>,
#[cfg(feature = "payouts")]
pub adyenplatform: Option<HeaderKey>,
pub affirm: Option<HeaderKey>,
#[cfg(feature = "payouts")]
pub adyen: Option<SignatureKey>,
#[cfg(not(feature = "payouts"))]
pub adyen_uk: Option<BodyKey>,
#[cfg(feature = "payouts")]
pub adyen_uk: Option<SignatureKey>,
pub airwallex: Option<BodyKey>,
pub amazonpay: Option<BodyKey>,
pub archipel: Option<NoKey>,
pub authipay: Option<SignatureKey>,
pub authorizedotnet: Option<BodyKey>,
pub bambora: Option<BodyKey>,
pub bamboraapac: Option<HeaderKey>,
pub bankofamerica: Option<SignatureKey>,
pub barclaycard: Option<SignatureKey>,
pub billwerk: Option<HeaderKey>,
pub bitpay: Option<HeaderKey>,
pub blackhawknetwork: Option<HeaderKey>,
pub calida: Option<HeaderKey>,
pub bluesnap: Option<BodyKey>,
pub boku: Option<BodyKey>,
pub breadpay: Option<BodyKey>,
pub cardinal: Option<SignatureKey>,
pub cashtocode: Option<BodyKey>,
pub celero: Option<HeaderKey>,
pub chargebee: Option<HeaderKey>,
pub checkbook: Option<BodyKey>,
pub checkout: Option<SignatureKey>,
pub coinbase: Option<HeaderKey>,
pub coingate: Option<HeaderKey>,
pub cryptopay: Option<BodyKey>,
pub cybersource: Option<SignatureKey>,
pub datatrans: Option<HeaderKey>,
pub deutschebank: Option<SignatureKey>,
pub digitalvirgo: Option<HeaderKey>,
pub dlocal: Option<SignatureKey>,
#[cfg(feature = "dummy_connector")]
pub dummyconnector: Option<HeaderKey>,
pub dwolla: Option<HeaderKey>,
pub ebanx: Option<HeaderKey>,
pub elavon: Option<HeaderKey>,
pub envoy: Option<HeaderKey>,
pub facilitapay: Option<BodyKey>,
pub finix: Option<HeaderKey>,
pub fiserv: Option<SignatureKey>,
pub fiservemea: Option<HeaderKey>,
pub fiuu: Option<HeaderKey>,
pub flexiti: Option<HeaderKey>,
pub forte: Option<MultiAuthKey>,
pub getnet: Option<HeaderKey>,
pub gigadat: Option<SignatureKey>,
pub globalpay: Option<BodyKey>,
pub globepay: Option<BodyKey>,
pub gocardless: Option<HeaderKey>,
pub gpayments: Option<HeaderKey>,
pub helcim: Option<HeaderKey>,
pub hipay: Option<HeaderKey>,
pub hyperswitch_vault: Option<SignatureKey>,
pub hyperwallet: Option<BodyKey>,
pub iatapay: Option<SignatureKey>,
pub inespay: Option<HeaderKey>,
pub itaubank: Option<MultiAuthKey>,
pub jpmorgan: Option<BodyKey>,
pub juspaythreedsserver: Option<HeaderKey>,
pub katapult: Option<HeaderKey>,
pub loonio: Option<HeaderKey>,
pub mifinity: Option<HeaderKey>,
pub mollie: Option<BodyKey>,
pub moneris: Option<SignatureKey>,
pub mpgs: Option<HeaderKey>,
pub multisafepay: Option<HeaderKey>,
pub netcetera: Option<HeaderKey>,
pub nexinets: Option<BodyKey>,
pub nexixpay: Option<HeaderKey>,
pub nomupay: Option<BodyKey>,
pub noon: Option<SignatureKey>,
pub nordea: Option<SignatureKey>,
pub novalnet: Option<HeaderKey>,
pub nmi: Option<HeaderKey>,
pub nuvei: Option<SignatureKey>,
pub opayo: Option<HeaderKey>,
pub opennode: Option<HeaderKey>,
pub paybox: Option<HeaderKey>,
pub payeezy: Option<SignatureKey>,
pub payjustnow: Option<HeaderKey>,
pub payjustnowinstore: Option<BodyKey>,
pub payload: Option<CurrencyAuthKey>,
pub payme: Option<BodyKey>,
pub payone: Option<HeaderKey>,
pub paypal: Option<BodyKey>,
pub paysafe: Option<BodyKey>,
pub paystack: Option<HeaderKey>,
pub paytm: Option<HeaderKey>,
pub payu: Option<BodyKey>,
pub peachpayments: Option<HeaderKey>,
pub phonepe: Option<HeaderKey>,
pub placetopay: Option<BodyKey>,
pub plaid: Option<BodyKey>,
pub powertranz: Option<BodyKey>,
pub prophetpay: Option<HeaderKey>,
pub rapyd: Option<BodyKey>,
pub razorpay: Option<BodyKey>,
pub recurly: Option<HeaderKey>,
pub redsys: Option<HeaderKey>,
pub santander: Option<BodyKey>,
pub shift4: Option<HeaderKey>,
pub sift: Option<HeaderKey>,
pub silverflow: Option<SignatureKey>,
pub square: Option<BodyKey>,
pub stax: Option<HeaderKey>,
pub stripe: Option<HeaderKey>,
pub stripebilling: Option<HeaderKey>,
pub taxjar: Option<HeaderKey>,
pub tesouro: Option<HeaderKey>,
pub threedsecureio: Option<HeaderKey>,
pub thunes: Option<HeaderKey>,
pub tokenex: Option<BodyKey>,
pub tokenio: Option<HeaderKey>,
pub stripe_au: Option<HeaderKey>,
pub stripe_uk: Option<HeaderKey>,
pub trustpay: Option<SignatureKey>,
pub trustpayments: Option<HeaderKey>,
pub tsys: Option<SignatureKey>,
pub unified_authentication_service: Option<HeaderKey>,
pub vgs: Option<SignatureKey>,
pub volt: Option<HeaderKey>,
pub wellsfargo: Option<HeaderKey>,
// pub wellsfargopayout: Option<HeaderKey>,
pub wise: Option<BodyKey>,
pub worldpay: Option<BodyKey>,
pub worldpayvantiv: Option<HeaderKey>,
pub worldpayxml: Option<HeaderKey>,
pub xendit: Option<HeaderKey>,
pub zift: Option<HeaderKey>,
pub worldline: Option<SignatureKey>,
pub zen: Option<HeaderKey>,
pub zsl: Option<BodyKey>,
pub automation_configs: Option<AutomationConfigs>,
pub users: Option<UsersConfigs>,
}
impl Default for ConnectorAuthentication {
fn default() -> Self {
Self::new()
}
}
#[allow(dead_code)]
impl ConnectorAuthentication {
/// # Panics
///
/// Will panic if `CONNECTOR_AUTH_FILE_PATH` env is not set
#[allow(clippy::expect_used)]
pub fn new() -> Self {
// Do `export CONNECTOR_AUTH_FILE_PATH="/hyperswitch/crates/router/tests/connectors/sample_auth.toml"`
// before running tests in shell
let path = env::var("CONNECTOR_AUTH_FILE_PATH")
.expect("Connector authentication file path not set");
toml::from_str(
&std::fs::read_to_string(path).expect("connector authentication config file not found"),
)
.expect("Failed to read connector authentication config file")
}
}
#[derive(Clone, Debug, Deserialize)]
pub struct ConnectorAuthenticationMap(HashMap<String, ConnectorAuthType>);
impl Default for ConnectorAuthenticationMap {
fn default() -> Self {
Self::new()
}
}
// This is a temporary solution to avoid rust compiler from complaining about unused function
#[allow(dead_code)]
impl ConnectorAuthenticationMap {
pub fn inner(&self) -> &HashMap<String, ConnectorAuthType> {
&self.0
}
/// # Panics
///
/// Will panic if `CONNECTOR_AUTH_FILE_PATH` env is not set
#[allow(clippy::expect_used)]
pub fn new() -> Self {
// Do `export CONNECTOR_AUTH_FILE_PATH="/hyperswitch/crates/router/tests/connectors/sample_auth.toml"`
// before running tests in shell
let path = env::var("CONNECTOR_AUTH_FILE_PATH")
.expect("connector authentication file path not set");
// Read the file contents to a JsonString
let contents =
&std::fs::read_to_string(path).expect("Failed to read connector authentication file");
// Deserialize the JsonString to a HashMap
let auth_config: HashMap<String, toml::Value> =
toml::from_str(contents).expect("Failed to deserialize TOML file");
// auth_config contains the data in below given format:
// {
// "connector_name": Table(
// {
// "api_key": String(
// "API_Key",
// ),
// "api_secret": String(
// "Secret key",
// ),
// "key1": String(
// "key1",
// ),
// "key2": String(
// "key2",
// ),
// },
// ),
// "connector_name": Table(
// ...
// }
// auth_map refines and extracts required information
let auth_map = auth_config
.into_iter()
.map(|(connector_name, config)| {
let auth_type = match config {
toml::Value::Table(mut table) => {
if let Some(auth_key_map_value) = table.remove("auth_key_map") {
// This is a CurrencyAuthKey
if let toml::Value::Table(auth_key_map_table) = auth_key_map_value {
let mut parsed_auth_map = HashMap::new();
for (currency, val) in auth_key_map_table {
if let Ok(currency_enum) =
currency.parse::<common_enums::Currency>()
{
parsed_auth_map
.insert(currency_enum, Secret::new(val.to_string()));
}
}
ConnectorAuthType::CurrencyAuthKey {
auth_key_map: parsed_auth_map,
}
} else {
ConnectorAuthType::NoKey
}
} else {
match (
table.get("api_key"),
table.get("key1"),
table.get("api_secret"),
table.get("key2"),
) {
(Some(api_key), None, None, None) => ConnectorAuthType::HeaderKey {
api_key: Secret::new(
api_key.as_str().unwrap_or_default().to_string(),
),
},
(Some(api_key), Some(key1), None, None) => {
ConnectorAuthType::BodyKey {
api_key: Secret::new(
api_key.as_str().unwrap_or_default().to_string(),
),
key1: Secret::new(
key1.as_str().unwrap_or_default().to_string(),
),
}
}
(Some(api_key), Some(key1), Some(api_secret), None) => {
ConnectorAuthType::SignatureKey {
api_key: Secret::new(
api_key.as_str().unwrap_or_default().to_string(),
),
key1: Secret::new(
key1.as_str().unwrap_or_default().to_string(),
),
api_secret: Secret::new(
api_secret.as_str().unwrap_or_default().to_string(),
),
}
}
(Some(api_key), Some(key1), Some(api_secret), Some(key2)) => {
ConnectorAuthType::MultiAuthKey {
api_key: Secret::new(
api_key.as_str().unwrap_or_default().to_string(),
),
key1: Secret::new(
key1.as_str().unwrap_or_default().to_string(),
),
api_secret: Secret::new(
api_secret.as_str().unwrap_or_default().to_string(),
),
key2: Secret::new(
key2.as_str().unwrap_or_default().to_string(),
),
}
}
_ => ConnectorAuthType::NoKey,
}
}
}
_ => ConnectorAuthType::NoKey,
};
(connector_name, auth_type)
})
.collect();
Self(auth_map)
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct HeaderKey {
pub api_key: Secret<String>,
}
impl From<HeaderKey> for ConnectorAuthType {
fn from(key: HeaderKey) -> Self {
Self::HeaderKey {
api_key: key.api_key,
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct BodyKey {
pub api_key: Secret<String>,
pub key1: Secret<String>,
}
impl From<BodyKey> for ConnectorAuthType {
fn from(key: BodyKey) -> Self {
Self::BodyKey {
api_key: key.api_key,
key1: key.key1,
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct SignatureKey {
pub api_key: Secret<String>,
pub key1: Secret<String>,
pub api_secret: Secret<String>,
}
impl From<SignatureKey> for ConnectorAuthType {
fn from(key: SignatureKey) -> Self {
Self::SignatureKey {
api_key: key.api_key,
key1: key.key1,
api_secret: key.api_secret,
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct MultiAuthKey {
pub api_key: Secret<String>,
pub key1: Secret<String>,
pub api_secret: Secret<String>,
pub key2: Secret<String>,
}
impl From<MultiAuthKey> for ConnectorAuthType {
fn from(key: MultiAuthKey) -> Self {
Self::MultiAuthKey {
api_key: key.api_key,
key1: key.key1,
api_secret: key.api_secret,
key2: key.key2,
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct CurrencyAuthKey {
pub auth_key_map: HashMap<String, toml::Value>,
}
impl From<CurrencyAuthKey> for ConnectorAuthType {
fn from(key: CurrencyAuthKey) -> Self {
let mut auth_map = HashMap::new();
for (currency, auth_data) in key.auth_key_map {
if let Ok(currency_enum) = currency.parse::<common_enums::Currency>() {
auth_map.insert(currency_enum, Secret::new(auth_data.to_string()));
}
}
Self::CurrencyAuthKey {
auth_key_map: auth_map,
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct NoKey {}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct AutomationConfigs {
pub hs_base_url: Option<String>,
pub hs_api_key: Option<String>,
pub hs_api_keys: Option<String>,
pub hs_webhook_url: Option<String>,
pub hs_test_env: Option<String>,
pub hs_test_browser: Option<String>,
pub chrome_profile_path: Option<String>,
pub firefox_profile_path: Option<String>,
pub pypl_email: Option<String>,
pub pypl_pass: Option<String>,
pub gmail_email: Option<String>,
pub gmail_pass: Option<String>,
pub clearpay_email: Option<String>,
pub clearpay_pass: Option<String>,
pub configs_url: Option<String>,
pub stripe_pub_key: Option<String>,
pub testcases_path: Option<String>,
pub bluesnap_gateway_merchant_id: Option<String>,
pub globalpay_gateway_merchant_id: Option<String>,
pub authorizedotnet_gateway_merchant_id: Option<String>,
pub run_minimum_steps: Option<bool>,
pub airwallex_merchant_name: Option<String>,
pub adyen_bancontact_username: Option<String>,
pub adyen_bancontact_pass: Option<String>,
}
#[derive(Default, Debug, Clone, serde::Deserialize)]
#[serde(tag = "auth_type")]
pub enum ConnectorAuthType {
HeaderKey {
api_key: Secret<String>,
},
BodyKey {
api_key: Secret<String>,
key1: Secret<String>,
},
SignatureKey {
api_key: Secret<String>,
key1: Secret<String>,
api_secret: Secret<String>,
},
MultiAuthKey {
api_key: Secret<String>,
key1: Secret<String>,
api_secret: Secret<String>,
key2: Secret<String>,
},
CurrencyAuthKey {
auth_key_map: HashMap<common_enums::Currency, Secret<String>>,
},
#[default]
NoKey,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct UsersConfigs {
pub user_email: String,
pub user_password: String,
pub wrong_password: String,
pub user_base_email_for_signup: String,
pub user_domain_for_signup: String,
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/test_utils/src/newman_runner.rs | crates/test_utils/src/newman_runner.rs | use std::{
env,
fs::{self, OpenOptions},
io::{self, Write},
path::Path,
process::{exit, Command},
};
use anyhow::{Context, Result};
use clap::{Parser, ValueEnum};
use masking::PeekInterface;
use regex::Regex;
use crate::connector_auth::{
ConnectorAuthType, ConnectorAuthentication, ConnectorAuthenticationMap,
};
#[derive(ValueEnum, Clone, Copy)]
pub enum Module {
Connector,
Users,
}
#[derive(Parser)]
#[command(version, about = "Postman collection runner using newman!", long_about = None)]
pub struct Args {
/// Admin API Key of the environment
#[arg(short, long)]
admin_api_key: String,
/// Base URL of the Hyperswitch environment
#[arg(short, long)]
base_url: String,
/// Name of the connector
#[arg(short, long)]
connector_name: Option<String>,
/// Name of the module
#[arg(short, long)]
module_name: Option<Module>,
/// Custom headers
#[arg(short = 'H', long = "header")]
custom_headers: Option<Vec<String>>,
/// Minimum delay in milliseconds to be added before sending a request
/// By default, 7 milliseconds will be the delay
#[arg(short, long, default_value_t = 7)]
delay_request: u32,
/// Folder name of specific tests
#[arg(short, long = "folder")]
folders: Option<String>,
/// Optional Verbose logs
#[arg(short, long)]
verbose: bool,
}
impl Args {
/// Getter for the `module_name` field
pub fn get_module_name(&self) -> Option<Module> {
self.module_name
}
}
pub struct ReturnArgs {
pub newman_command: Command,
pub modified_file_paths: Vec<Option<String>>,
pub collection_path: String,
}
// Generates the name of the collection JSON file for the specified connector.
// Example: CONNECTOR_NAME="stripe" -> OUTPUT: postman/collection-json/stripe.postman_collection.json
#[inline]
fn get_collection_path(name: impl AsRef<str>) -> String {
format!(
"postman/collection-json/{}.postman_collection.json",
name.as_ref()
)
}
// Generates the name of the collection directory for the specified connector.
// Example: CONNECTOR_NAME="stripe" -> OUTPUT: postman/collection-dir/stripe
#[inline]
fn get_dir_path(name: impl AsRef<str>) -> String {
format!("postman/collection-dir/{}", name.as_ref())
}
// This function currently allows you to add only custom headers.
// In future, as we scale, this can be modified based on the need
fn insert_content<T, U>(dir: T, content_to_insert: U) -> io::Result<()>
where
T: AsRef<Path>,
U: AsRef<str>,
{
let file_name = "event.prerequest.js";
let file_path = dir.as_ref().join(file_name);
// Open the file in write mode or create it if it doesn't exist
let mut file = OpenOptions::new()
.append(true)
.create(true)
.open(file_path)?;
write!(file, "{}", content_to_insert.as_ref())?;
Ok(())
}
// This function gives runner for connector or a module
pub fn generate_runner() -> Result<ReturnArgs> {
let args = Args::parse();
match args.get_module_name() {
Some(Module::Users) => generate_newman_command_for_users(),
Some(Module::Connector) => generate_newman_command_for_connector(),
// Running connector tests when no module is passed to keep the previous test behavior same
None => generate_newman_command_for_connector(),
}
}
pub fn generate_newman_command_for_users() -> Result<ReturnArgs> {
let args = Args::parse();
let base_url = args.base_url;
let admin_api_key = args.admin_api_key;
let path = env::var("CONNECTOR_AUTH_FILE_PATH")
.with_context(|| "connector authentication file path not set")?;
let authentication: ConnectorAuthentication = toml::from_str(
&fs::read_to_string(path)
.with_context(|| "connector authentication config file not found")?,
)
.with_context(|| "connector authentication file path not set")?;
let users_configs = authentication
.users
.with_context(|| "user configs not found in authentication file")?;
let collection_path = get_collection_path("users");
let mut newman_command = Command::new("newman");
newman_command.args(["run", &collection_path]);
newman_command.args(["--env-var", &format!("admin_api_key={admin_api_key}")]);
newman_command.args(["--env-var", &format!("baseUrl={base_url}")]);
newman_command.args([
"--env-var",
&format!("user_email={}", users_configs.user_email),
]);
newman_command.args([
"--env-var",
&format!(
"user_base_email_for_signup={}",
users_configs.user_base_email_for_signup
),
]);
newman_command.args([
"--env-var",
&format!(
"user_domain_for_signup={}",
users_configs.user_domain_for_signup
),
]);
newman_command.args([
"--env-var",
&format!("user_password={}", users_configs.user_password),
]);
newman_command.args([
"--env-var",
&format!("wrong_password={}", users_configs.wrong_password),
]);
newman_command.args([
"--delay-request",
format!("{}", &args.delay_request).as_str(),
]);
newman_command.arg("--color").arg("on");
if args.verbose {
newman_command.arg("--verbose");
}
Ok(ReturnArgs {
newman_command,
modified_file_paths: vec![],
collection_path,
})
}
pub fn generate_newman_command_for_connector() -> Result<ReturnArgs> {
let args = Args::parse();
let connector_name = args
.connector_name
.with_context(|| "invalid parameters: connector/module name not found in arguments")?;
let base_url = args.base_url;
let admin_api_key = args.admin_api_key;
let collection_path = get_collection_path(&connector_name);
let collection_dir_path = get_dir_path(&connector_name);
let auth_map = ConnectorAuthenticationMap::new();
let inner_map = auth_map.inner();
/*
Newman runner
Certificate keys are added through secrets in CI, so there's no need to explicitly pass it as arguments.
It can be overridden by explicitly passing certificates as arguments.
If the collection requires certificates (Stripe collection for example) during the merchant connector account create step,
then Stripe's certificates will be passed implicitly (for now).
If any other connector requires certificates to be passed, that has to be passed explicitly for now.
*/
let mut newman_command = Command::new("newman");
newman_command.args(["run", &collection_path]);
newman_command.args(["--env-var", &format!("admin_api_key={admin_api_key}")]);
newman_command.args(["--env-var", &format!("baseUrl={base_url}")]);
let custom_header_exist = check_for_custom_headers(args.custom_headers, &collection_dir_path);
// validation of connector is needed here as a work around to the limitation of the fork of newman that Hyperswitch uses
let (connector_name, modified_collection_file_paths) =
check_connector_for_dynamic_amount(&connector_name);
if let Some(auth_type) = inner_map.get(connector_name) {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => {
newman_command.args([
"--env-var",
&format!("connector_api_key={}", api_key.peek()),
]);
}
ConnectorAuthType::BodyKey { api_key, key1 } => {
newman_command.args([
"--env-var",
&format!("connector_api_key={}", api_key.peek()),
"--env-var",
&format!("connector_key1={}", key1.peek()),
]);
}
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => {
newman_command.args([
"--env-var",
&format!("connector_api_key={}", api_key.peek()),
"--env-var",
&format!("connector_key1={}", key1.peek()),
"--env-var",
&format!("connector_api_secret={}", api_secret.peek()),
]);
}
ConnectorAuthType::MultiAuthKey {
api_key,
key1,
key2,
api_secret,
} => {
newman_command.args([
"--env-var",
&format!("connector_api_key={}", api_key.peek()),
"--env-var",
&format!("connector_key1={}", key1.peek()),
"--env-var",
&format!("connector_key2={}", key2.peek()),
"--env-var",
&format!("connector_api_secret={}", api_secret.peek()),
]);
}
// Handle other ConnectorAuthType variants
_ => {
eprintln!("Invalid authentication type.");
}
}
} else {
eprintln!("Connector not found.");
}
// Add additional environment variables if present
if let Ok(gateway_merchant_id) = env::var("GATEWAY_MERCHANT_ID") {
newman_command.args([
"--env-var",
&format!("gateway_merchant_id={gateway_merchant_id}"),
]);
}
if let Ok(gpay_certificate) = env::var("GPAY_CERTIFICATE") {
newman_command.args(["--env-var", &format!("certificate={gpay_certificate}")]);
}
if let Ok(gpay_certificate_keys) = env::var("GPAY_CERTIFICATE_KEYS") {
newman_command.args([
"--env-var",
&format!("certificate_keys={gpay_certificate_keys}"),
]);
}
if let Ok(merchant_api_key) = env::var("MERCHANT_API_KEY") {
newman_command.args(["--env-var", &format!("merchant_api_key={merchant_api_key}")]);
}
newman_command.args([
"--delay-request",
format!("{}", &args.delay_request).as_str(),
]);
newman_command.arg("--color").arg("on");
// Add flags for running specific folders
if let Some(folders) = &args.folders {
let folder_names: Vec<String> = folders.split(',').map(|s| s.trim().to_string()).collect();
for folder_name in folder_names {
if !folder_name.contains("QuickStart") {
// This is a quick fix, "QuickStart" is intentional to have merchant account and API keys set up
// This will be replaced by a more robust and efficient account creation or reuse existing old account
newman_command.args(["--folder", "QuickStart"]);
}
newman_command.args(["--folder", &folder_name]);
}
}
if args.verbose {
newman_command.arg("--verbose");
}
Ok(ReturnArgs {
newman_command,
modified_file_paths: vec![modified_collection_file_paths, custom_header_exist],
collection_path,
})
}
pub fn check_for_custom_headers(headers: Option<Vec<String>>, path: &str) -> Option<String> {
if let Some(headers) = &headers {
for header in headers {
if let Some((key, value)) = header.split_once(':') {
let content_to_insert =
format!(r#"pm.request.headers.add({{key: "{key}", value: "{value}"}});"#);
if let Err(err) = insert_content(path, &content_to_insert) {
eprintln!("An error occurred while inserting the custom header: {err}");
}
} else {
eprintln!("Invalid header format: {header}");
}
}
return Some(format!("{path}/event.prerequest.js"));
}
None
}
// If the connector name exists in dynamic_amount_connectors,
// the corresponding collection is modified at runtime to remove double quotes
pub fn check_connector_for_dynamic_amount(connector_name: &str) -> (&str, Option<String>) {
let collection_dir_path = get_dir_path(connector_name);
let dynamic_amount_connectors = ["nmi", "powertranz"];
if dynamic_amount_connectors.contains(&connector_name) {
return remove_quotes_for_integer_values(connector_name).unwrap_or((connector_name, None));
}
/*
If connector name does not exist in dynamic_amount_connectors but we want to run it with custom headers,
since we're running from collections directly, we'll have to export the collection again and it is much simpler.
We could directly inject the custom-headers using regex, but it is not encouraged as it is hard
to determine the place of edit.
*/
export_collection(connector_name, collection_dir_path);
(connector_name, None)
}
/*
Existing issue with the fork of newman is that, it requires you to pass variables like `{{value}}` within
double quotes without which it fails to execute.
For integer values like `amount`, this is a bummer as it flags the value stating it is of type
string and not integer.
Refactoring is done in 2 steps:
- Export the collection to json (although the json will be up-to-date, we export it again for safety)
- Use regex to replace the values which removes double quotes from integer values
Ex: \"{{amount}}\" -> {{amount}}
*/
pub fn remove_quotes_for_integer_values(
connector_name: &str,
) -> Result<(&str, Option<String>), io::Error> {
let collection_path = get_collection_path(connector_name);
let collection_dir_path = get_dir_path(connector_name);
let values_to_replace = [
"amount",
"another_random_number",
"capture_amount",
"random_number",
"refund_amount",
];
export_collection(connector_name, collection_dir_path);
let mut contents = fs::read_to_string(&collection_path)?;
for value_to_replace in values_to_replace {
if let Ok(re) = Regex::new(&format!(
r#"\\"(?P<field>\{{\{{{value_to_replace}\}}\}})\\""#,
)) {
contents = re.replace_all(&contents, "$field").to_string();
} else {
eprintln!("Regex validation failed.");
}
let mut file = OpenOptions::new()
.write(true)
.truncate(true)
.open(&collection_path)?;
file.write_all(contents.as_bytes())?;
}
Ok((connector_name, Some(collection_path)))
}
pub fn export_collection(connector_name: &str, collection_dir_path: String) {
let collection_path = get_collection_path(connector_name);
let mut newman_command = Command::new("newman");
newman_command.args([
"dir-import".to_owned(),
collection_dir_path,
"-o".to_owned(),
collection_path.clone(),
]);
match newman_command.spawn().and_then(|mut child| child.wait()) {
Ok(exit_status) => {
if exit_status.success() {
println!("Conversion of collection from directory structure to json successful!");
} else {
eprintln!("Conversion of collection from directory structure to json failed!");
exit(exit_status.code().unwrap_or(1));
}
}
Err(err) => {
eprintln!("Failed to execute dir-import: {err:?}");
exit(1);
}
}
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/test_utils/src/main.rs | crates/test_utils/src/main.rs | #![allow(clippy::print_stdout, clippy::print_stderr)]
use std::process::{exit, Command};
use anyhow::Result;
use test_utils::newman_runner;
fn main() -> Result<()> {
let mut runner = newman_runner::generate_runner()?;
// Execute the newman command
let output = runner.newman_command.spawn();
let mut child = match output {
Ok(child) => child,
Err(err) => {
eprintln!("Failed to execute command: {err}");
exit(1);
}
};
let status = child.wait();
// Filter out None values leaving behind Some(Path)
let paths: Vec<String> = runner.modified_file_paths.into_iter().flatten().collect();
if !paths.is_empty() {
let git_status = Command::new("git").arg("restore").args(&paths).output();
match git_status {
Ok(output) if !output.status.success() => {
let stderr_str = String::from_utf8_lossy(&output.stderr);
eprintln!("Git command failed with error: {stderr_str}");
}
Ok(_) => {
println!("Git restore successful!");
}
Err(e) => {
eprintln!("Error running Git: {e}");
}
}
}
let exit_code = match status {
Ok(exit_status) => {
if exit_status.success() {
println!("Command executed successfully!");
exit_status.code().unwrap_or(0)
} else {
eprintln!("Command failed with exit code: {:?}", exit_status.code());
exit_status.code().unwrap_or(1)
}
}
Err(err) => {
eprintln!("Failed to wait for command execution: {err}");
exit(1);
}
};
exit(exit_code);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/test_utils/tests/connectors/checkout_wh_ui.rs | crates/test_utils/tests/connectors/checkout_wh_ui.rs | use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct CheckoutSeleniumTest;
impl SeleniumTest for CheckoutSeleniumTest {
fn get_connector_name(&self) -> String {
"checkout".to_string()
}
}
async fn should_make_webhook(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = CheckoutSeleniumTest {};
conn.make_webhook_test(
web_driver,
&format!("{CHECKOUT_BASE_URL}/saved/18"),
vec![
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Sleep(8)),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded", "status=processing"],
)),
],
10,
"succeeded",
)
.await?;
Ok(())
}
#[test]
fn should_make_webhook_test() {
tester!(should_make_webhook);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/test_utils/tests/connectors/stripe_ui.rs | crates/test_utils/tests/connectors/stripe_ui.rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct StripeSeleniumTest;
impl SeleniumTest for StripeSeleniumTest {
fn get_connector_name(&self) -> String {
"stripe".to_string()
}
}
async fn should_make_3ds_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000000000003063&expmonth=10&expyear=25&cvv=123&amount=100&country=US¤cy=USD"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Id("test-source-authorize-3ds"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(Selector::QueryParamStr, "status=succeeded")),
]).await?;
Ok(())
}
async fn should_make_3ds_mandate_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000002500003155&expmonth=10&expyear=25&cvv=123&amount=10&country=US¤cy=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD&return_url={CHECKOUT_BASE_URL}/payments"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Id("test-source-authorize-3ds"))),
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
async fn should_fail_recurring_payment_due_to_authentication(
c: WebDriver,
) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000002760003184&expmonth=10&expyear=25&cvv=123&amount=10&country=US¤cy=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD&return_url={CHECKOUT_BASE_URL}/payments"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Id("test-source-authorize-3ds"))),
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Your card was declined. This transaction requires authentication.")),
]).await?;
Ok(())
}
async fn should_make_3ds_mandate_with_zero_dollar_payment(
c: WebDriver,
) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000002500003155&expmonth=10&expyear=25&cvv=123&amount=0&country=US¤cy=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD&return_url={CHECKOUT_BASE_URL}/payments"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Id("test-source-authorize-3ds"))),
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
// Need to be handled as mentioned in https://stripe.com/docs/payments/save-and-reuse?platform=web#charge-saved-payment-method
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
async fn should_make_gpay_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
let pub_key = conn
.get_configs()
.automation_configs
.unwrap()
.stripe_pub_key
.unwrap();
conn.make_gpay_payment(c,
&format!("{CHECKOUT_BASE_URL}/gpay?gatewayname=stripe&gpaycustomfields[stripe:version]=2018-10-31&gpaycustomfields[stripe:publishableKey]={pub_key}&amount=70.00&country=US¤cy=USD"),
vec![
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
async fn should_make_gpay_mandate_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
let pub_key = conn
.get_configs()
.automation_configs
.unwrap()
.stripe_pub_key
.unwrap();
conn.make_gpay_payment(c,
&format!("{CHECKOUT_BASE_URL}/gpay?gatewayname=stripe&gpaycustomfields[stripe:version]=2018-10-31&gpaycustomfields[stripe:publishableKey]={pub_key}&amount=70.00&country=US¤cy=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD"),
vec![
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
#[ignore = "Different flows"]
//https://stripe.com/docs/testing#regulatory-cards
async fn should_make_stripe_klarna_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/19"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SwitchFrame(By::Id("klarna-apf-iframe"))),
Event::RunIf(
Assert::IsPresent("Let’s verify your phone"),
vec![
Event::Trigger(Trigger::SendKeys(By::Id("phone"), "9123456789")),
Event::Trigger(Trigger::Click(By::Id("onContinue"))),
Event::Trigger(Trigger::SendKeys(By::Id("otp_field"), "123456")),
],
),
Event::RunIf(
Assert::IsPresent("We've updated our Shopping terms"),
vec![Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='kaf-button']",
)))],
),
Event::RunIf(
Assert::IsPresent("Pick a plan"),
vec![Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='pick-plan']",
)))],
),
Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='confirm-and-pay']",
))),
Event::RunIf(
Assert::IsPresent("Fewer clicks"),
vec![Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='SmoothCheckoutPopUp:skip']",
)))],
),
Event::Trigger(Trigger::SwitchTab(Position::Prev)),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_afterpay_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/22"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"a[class='common-Button common-Button--default']",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_stripe_alipay_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/35"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"button[class='common-Button common-Button--default']",
))),
Event::Trigger(Trigger::Sleep(5)),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_stripe_ideal_bank_redirect_payment(
c: WebDriver,
) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/2"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"a[class='common-Button common-Button--default']",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_stripe_giropay_bank_redirect_payment(
c: WebDriver,
) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/1"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"a[class='common-Button common-Button--default']",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_stripe_eps_bank_redirect_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/26"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"a[class='common-Button common-Button--default']",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_stripe_bancontact_card_redirect_payment(
c: WebDriver,
) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/28"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"a[class='common-Button common-Button--default']",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_stripe_p24_redirect_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/31"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"a[class='common-Button common-Button--default']",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_stripe_sofort_redirect_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/34"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"a[class='common-Button common-Button--default']",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=processing", "status=succeeded"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_stripe_ach_bank_debit_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/56"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SendKeys(
By::Css("input[class='p-CodePuncher-controllingInput']"),
"11AA",
)),
Event::Trigger(Trigger::Click(By::Css(
"div[class='SubmitButton-IconContainer']",
))),
Event::Assert(Assert::IsPresent("Thanks for your payment")),
Event::Assert(Assert::IsPresent("You completed a payment")),
],
)
.await?;
Ok(())
}
async fn should_make_stripe_sepa_bank_debit_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/67"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Status")),
Event::Assert(Assert::IsPresent("processing")),
],
)
.await?;
Ok(())
}
async fn should_make_stripe_affirm_paylater_payment(
driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_affirm_payment(
driver,
&format!("{CHECKOUT_BASE_URL}/saved/110"),
vec![Event::Assert(Assert::IsPresent("succeeded"))],
)
.await?;
Ok(())
}
#[test]
#[serial]
fn should_make_3ds_payment_test() {
tester!(should_make_3ds_payment);
}
#[test]
#[serial]
fn should_make_3ds_mandate_payment_test() {
tester!(should_make_3ds_mandate_payment);
}
#[test]
#[serial]
fn should_fail_recurring_payment_due_to_authentication_test() {
tester!(should_fail_recurring_payment_due_to_authentication);
}
#[test]
#[serial]
fn should_make_3ds_mandate_with_zero_dollar_payment_test() {
tester!(should_make_3ds_mandate_with_zero_dollar_payment);
}
#[test]
#[serial]
fn should_make_gpay_payment_test() {
tester!(should_make_gpay_payment);
}
#[test]
#[serial]
#[ignore]
fn should_make_gpay_mandate_payment_test() {
tester!(should_make_gpay_mandate_payment);
}
#[test]
#[serial]
fn should_make_stripe_klarna_payment_test() {
tester!(should_make_stripe_klarna_payment);
}
#[test]
#[serial]
fn should_make_afterpay_payment_test() {
tester!(should_make_afterpay_payment);
}
#[test]
#[serial]
fn should_make_stripe_alipay_payment_test() {
tester!(should_make_stripe_alipay_payment);
}
#[test]
#[serial]
fn should_make_stripe_ideal_bank_redirect_payment_test() {
tester!(should_make_stripe_ideal_bank_redirect_payment);
}
#[test]
#[serial]
fn should_make_stripe_giropay_bank_redirect_payment_test() {
tester!(should_make_stripe_giropay_bank_redirect_payment);
}
#[test]
#[serial]
fn should_make_stripe_eps_bank_redirect_payment_test() {
tester!(should_make_stripe_eps_bank_redirect_payment);
}
#[test]
#[serial]
fn should_make_stripe_bancontact_card_redirect_payment_test() {
tester!(should_make_stripe_bancontact_card_redirect_payment);
}
#[test]
#[serial]
fn should_make_stripe_p24_redirect_payment_test() {
tester!(should_make_stripe_p24_redirect_payment);
}
#[test]
#[serial]
fn should_make_stripe_sofort_redirect_payment_test() {
tester!(should_make_stripe_sofort_redirect_payment);
}
#[test]
#[serial]
fn should_make_stripe_ach_bank_debit_payment_test() {
tester!(should_make_stripe_ach_bank_debit_payment);
}
#[test]
#[serial]
fn should_make_stripe_sepa_bank_debit_payment_test() {
tester!(should_make_stripe_sepa_bank_debit_payment);
}
#[test]
#[serial]
fn should_make_stripe_affirm_paylater_payment_test() {
tester!(should_make_stripe_affirm_paylater_payment);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/test_utils/tests/connectors/zen_ui.rs | crates/test_utils/tests/connectors/zen_ui.rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct ZenSeleniumTest;
impl SeleniumTest for ZenSeleniumTest {
fn get_connector_name(&self) -> String {
"zen".to_string()
}
}
async fn should_make_zen_3ds_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let mycon = ZenSeleniumTest {};
mycon
.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/201"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Sleep(10)), //url gets updated only after some time, so need this timeout to solve the issue
Event::Trigger(Trigger::SwitchFrame(By::Name("cko-3ds2-iframe"))),
Event::Trigger(Trigger::SendKeys(By::Id("password"), "Checkout1!")),
Event::Trigger(Trigger::Click(By::Id("txtButton"))),
Event::Trigger(Trigger::Sleep(3)),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
#[test]
#[serial]
fn should_make_zen_3ds_payment_test() {
tester!(should_make_zen_3ds_payment);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/test_utils/tests/connectors/worldline_ui.rs | crates/test_utils/tests/connectors/worldline_ui.rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct WorldlineSeleniumTest;
impl SeleniumTest for WorldlineSeleniumTest {
fn get_connector_name(&self) -> String {
"worldline".to_string()
}
}
async fn should_make_card_non_3ds_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = WorldlineSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/71"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("status")),
Event::Assert(Assert::IsPresent("processing")),
],
)
.await?;
Ok(())
}
async fn should_make_worldline_ideal_redirect_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = WorldlineSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/49"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=requires_customer_action", "status=succeeded"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_worldline_giropay_redirect_payment(
c: WebDriver,
) -> Result<(), WebDriverError> {
let conn = WorldlineSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/48"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=requires_customer_action", "status=succeeded"],
)),
],
)
.await?;
Ok(())
}
#[test]
#[serial]
#[ignore]
fn should_make_worldline_giropay_redirect_payment_test() {
tester!(should_make_worldline_giropay_redirect_payment);
}
#[test]
#[serial]
fn should_make_worldline_ideal_redirect_payment_test() {
tester!(should_make_worldline_ideal_redirect_payment);
}
#[test]
#[serial]
fn should_make_card_non_3ds_payment_test() {
tester!(should_make_card_non_3ds_payment);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/test_utils/tests/connectors/multisafepay_ui.rs | crates/test_utils/tests/connectors/multisafepay_ui.rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct MultisafepaySeleniumTest;
impl SeleniumTest for MultisafepaySeleniumTest {
fn get_connector_name(&self) -> String {
"multisafepay".to_string()
}
}
async fn should_make_multisafepay_3ds_payment_success(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = MultisafepaySeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/207"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_multisafepay_3ds_payment_failed(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = MultisafepaySeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/93"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("failed")),
],
)
.await?;
Ok(())
}
async fn should_make_gpay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = MultisafepaySeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/153"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("button[class='btn btn-default']"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_paypal_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = MultisafepaySeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/154"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"button[class='btn btn-msp-success btn-block']",
))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
#[test]
#[serial]
fn should_make_multisafepay_3ds_payment_success_test() {
tester!(should_make_multisafepay_3ds_payment_success);
}
#[test]
#[serial]
fn should_make_multisafepay_3ds_payment_failed_test() {
tester!(should_make_multisafepay_3ds_payment_failed);
}
#[test]
#[serial]
#[ignore]
fn should_make_gpay_payment_test() {
tester!(should_make_gpay_payment);
}
#[test]
#[serial]
fn should_make_paypal_payment_test() {
tester!(should_make_paypal_payment);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/test_utils/tests/connectors/selenium.rs | crates/test_utils/tests/connectors/selenium.rs | #![allow(clippy::expect_used, clippy::unwrap_in_result, clippy::unwrap_used)]
use std::{
collections::{HashMap, HashSet},
env,
io::Read,
path::{MAIN_SEPARATOR, MAIN_SEPARATOR_STR},
time::Duration,
};
use async_trait::async_trait;
use base64::Engine;
use serde::{Deserialize, Serialize};
use serde_json::json;
use test_utils::connector_auth;
use thirtyfour::{components::SelectElement, prelude::*, WebDriver};
#[derive(Clone)]
pub enum Event<'a> {
RunIf(Assert<'a>, Vec<Self>),
EitherOr(Assert<'a>, Vec<Self>, Vec<Self>),
Assert(Assert<'a>),
Trigger(Trigger<'a>),
}
#[derive(Clone)]
#[allow(dead_code)]
pub enum Trigger<'a> {
Goto(&'a str),
Click(By),
ClickNth(By, usize),
SelectOption(By, &'a str),
ChangeQueryParam(&'a str, &'a str),
SwitchTab(Position),
SwitchFrame(By),
Find(By),
Query(By),
SendKeys(By, &'a str),
Sleep(u64),
}
#[derive(Clone)]
pub enum Position {
Prev,
Next,
}
#[derive(Clone)]
pub enum Selector {
Title,
QueryParamStr,
}
#[derive(Clone)]
pub enum Assert<'a> {
Eq(Selector, &'a str),
Contains(Selector, &'a str),
ContainsAny(Selector, Vec<&'a str>),
EitherOfThemExist(&'a str, &'a str),
IsPresent(&'a str),
IsElePresent(By),
IsPresentNow(&'a str),
}
pub static CHECKOUT_BASE_URL: &str = "https://hs-payments-test.netlify.app";
#[async_trait]
pub trait SeleniumTest {
fn get_saved_testcases(&self) -> serde_json::Value {
get_saved_testcases()
}
fn get_configs(&self) -> connector_auth::ConnectorAuthentication {
get_configs()
}
async fn retry_click(
&self,
times: i32,
interval: u64,
driver: &WebDriver,
by: By,
) -> Result<(), WebDriverError> {
let mut res = Ok(());
for _i in 0..times {
res = self.click_element(driver, by.clone()).await;
if res.is_err() {
tokio::time::sleep(Duration::from_secs(interval)).await;
} else {
break;
}
}
return res;
}
fn get_connector_name(&self) -> String;
async fn complete_actions(
&self,
driver: &WebDriver,
actions: Vec<Event<'_>>,
) -> Result<(), WebDriverError> {
for action in actions {
match action {
Event::Assert(assert) => match assert {
Assert::Contains(selector, text) => match selector {
Selector::QueryParamStr => {
let url = driver.current_url().await?;
assert!(url.query().unwrap().contains(text))
}
_ => assert!(driver.title().await?.contains(text)),
},
Assert::ContainsAny(selector, search_keys) => match selector {
Selector::QueryParamStr => {
let url = driver.current_url().await?;
assert!(search_keys
.iter()
.any(|key| url.query().unwrap().contains(key)))
}
_ => assert!(driver.title().await?.contains(search_keys.first().unwrap())),
},
Assert::EitherOfThemExist(text_1, text_2) => assert!(
is_text_present_now(driver, text_1).await?
|| is_text_present_now(driver, text_2).await?
),
Assert::Eq(_selector, text) => assert_eq!(driver.title().await?, text),
Assert::IsPresent(text) => {
assert!(is_text_present(driver, text).await?)
}
Assert::IsElePresent(selector) => {
assert!(is_element_present(driver, selector).await?)
}
Assert::IsPresentNow(text) => {
assert!(is_text_present_now(driver, text).await?)
}
},
Event::RunIf(con_event, events) => match con_event {
Assert::Contains(selector, text) => match selector {
Selector::QueryParamStr => {
let url = driver.current_url().await?;
if url.query().unwrap().contains(text) {
self.complete_actions(driver, events).await?;
}
}
_ => assert!(driver.title().await?.contains(text)),
},
Assert::ContainsAny(selector, keys) => match selector {
Selector::QueryParamStr => {
let url = driver.current_url().await?;
if keys.iter().any(|key| url.query().unwrap().contains(key)) {
self.complete_actions(driver, events).await?;
}
}
_ => assert!(driver.title().await?.contains(keys.first().unwrap())),
},
Assert::Eq(_selector, text) => {
if text == driver.title().await? {
self.complete_actions(driver, events).await?;
}
}
Assert::EitherOfThemExist(text_1, text_2) => {
if is_text_present_now(driver, text_1).await.is_ok()
|| is_text_present_now(driver, text_2).await.is_ok()
{
self.complete_actions(driver, events).await?;
}
}
Assert::IsPresent(text) => {
if is_text_present(driver, text).await.is_ok() {
self.complete_actions(driver, events).await?;
}
}
Assert::IsElePresent(text) => {
if is_element_present(driver, text).await.is_ok() {
self.complete_actions(driver, events).await?;
}
}
Assert::IsPresentNow(text) => {
if is_text_present_now(driver, text).await.is_ok() {
self.complete_actions(driver, events).await?;
}
}
},
Event::EitherOr(con_event, success, failure) => match con_event {
Assert::Contains(selector, text) => match selector {
Selector::QueryParamStr => {
let url = driver.current_url().await?;
self.complete_actions(
driver,
if url.query().unwrap().contains(text) {
success
} else {
failure
},
)
.await?;
}
_ => assert!(driver.title().await?.contains(text)),
},
Assert::ContainsAny(selector, keys) => match selector {
Selector::QueryParamStr => {
let url = driver.current_url().await?;
self.complete_actions(
driver,
if keys.iter().any(|key| url.query().unwrap().contains(key)) {
success
} else {
failure
},
)
.await?;
}
_ => assert!(driver.title().await?.contains(keys.first().unwrap())),
},
Assert::Eq(_selector, text) => {
self.complete_actions(
driver,
if text == driver.title().await? {
success
} else {
failure
},
)
.await?;
}
Assert::EitherOfThemExist(text_1, text_2) => {
self.complete_actions(
driver,
if is_text_present_now(driver, text_1).await.is_ok()
|| is_text_present_now(driver, text_2).await.is_ok()
{
success
} else {
failure
},
)
.await?;
}
Assert::IsPresent(text) => {
self.complete_actions(
driver,
if is_text_present(driver, text).await.is_ok() {
success
} else {
failure
},
)
.await?;
}
Assert::IsElePresent(by) => {
self.complete_actions(
driver,
if is_element_present(driver, by).await.is_ok() {
success
} else {
failure
},
)
.await?;
}
Assert::IsPresentNow(text) => {
self.complete_actions(
driver,
if is_text_present_now(driver, text).await.is_ok() {
success
} else {
failure
},
)
.await?;
}
},
Event::Trigger(trigger) => match trigger {
Trigger::Goto(url) => {
let saved_tests =
serde_json::to_string(&self.get_saved_testcases()).unwrap();
let conf = serde_json::to_string(&self.get_configs()).unwrap();
let configs = self.get_configs().automation_configs.unwrap();
let hs_base_url = configs
.hs_base_url
.unwrap_or_else(|| "http://localhost:8080".to_string());
let configs_url = configs.configs_url.unwrap();
let hs_api_keys = configs.hs_api_keys.unwrap();
let test_env = configs.hs_test_env.unwrap();
let script = &[
format!("localStorage.configs='{configs_url}'").as_str(),
format!("localStorage.current_env='{test_env}'").as_str(),
"localStorage.hs_api_key=''",
format!("localStorage.hs_api_keys='{hs_api_keys}'").as_str(),
format!("localStorage.base_url='{hs_base_url}'").as_str(),
format!("localStorage.hs_api_configs='{conf}'").as_str(),
format!("localStorage.saved_payments=JSON.stringify({saved_tests})")
.as_str(),
"localStorage.force_sync='true'",
format!(
"localStorage.current_connector=\"{}\";",
self.get_connector_name().clone()
)
.as_str(),
]
.join(";");
driver.goto(url).await?;
driver.execute(script, Vec::new()).await?;
}
Trigger::Click(by) => {
self.retry_click(3, 5, driver, by.clone()).await?;
}
Trigger::ClickNth(by, n) => {
let ele = driver.query(by).all().await?.into_iter().nth(n).unwrap();
ele.wait_until().enabled().await?;
ele.wait_until().displayed().await?;
ele.wait_until().clickable().await?;
ele.scroll_into_view().await?;
ele.click().await?;
}
Trigger::Find(by) => {
driver.find(by).await?;
}
Trigger::Query(by) => {
driver.query(by).first().await?;
}
Trigger::SendKeys(by, input) => {
let ele = driver.query(by).first().await?;
ele.wait_until().displayed().await?;
ele.send_keys(&input).await?;
}
Trigger::SelectOption(by, input) => {
let ele = driver.query(by).first().await?;
let select_element = SelectElement::new(&ele).await?;
select_element.select_by_partial_text(input).await?;
}
Trigger::ChangeQueryParam(param, value) => {
let mut url = driver.current_url().await?;
let mut hash_query: HashMap<String, String> =
url.query_pairs().into_owned().collect();
hash_query.insert(param.to_string(), value.to_string());
let url_str = serde_urlencoded::to_string(hash_query)
.expect("Query Param update failed");
url.set_query(Some(&url_str));
driver.goto(url.as_str()).await?;
}
Trigger::Sleep(seconds) => {
tokio::time::sleep(Duration::from_secs(seconds)).await;
}
Trigger::SwitchTab(position) => match position {
Position::Next => {
let windows = driver.windows().await?;
if let Some(window) = windows.iter().next_back() {
driver.switch_to_window(window.to_owned()).await?;
}
}
Position::Prev => {
let windows = driver.windows().await?;
if let Some(window) = windows.into_iter().next() {
driver.switch_to_window(window.to_owned()).await?;
}
}
},
Trigger::SwitchFrame(by) => {
let iframe = driver.query(by).first().await?;
iframe.wait_until().displayed().await?;
iframe.clone().enter_frame().await?;
}
},
}
}
Ok(())
}
async fn click_element(&self, driver: &WebDriver, by: By) -> Result<(), WebDriverError> {
let ele = driver.query(by).first().await?;
ele.wait_until().enabled().await?;
ele.wait_until().displayed().await?;
ele.wait_until().clickable().await?;
ele.scroll_into_view().await?;
ele.click().await
}
async fn make_redirection_payment(
&self,
web_driver: WebDriver,
actions: Vec<Event<'_>>,
) -> Result<(), WebDriverError> {
// To support failure retries
let result = self
.execute_steps(web_driver.clone(), actions.clone())
.await;
if result.is_err() {
self.execute_steps(web_driver, actions).await
} else {
result
}
}
async fn execute_steps(
&self,
web_driver: WebDriver,
actions: Vec<Event<'_>>,
) -> Result<(), WebDriverError> {
let config = self.get_configs().automation_configs.unwrap();
if config.run_minimum_steps.unwrap() {
self.complete_actions(&web_driver, actions.get(..3).unwrap().to_vec())
.await
} else {
self.complete_actions(&web_driver, actions).await
}
}
async fn make_gpay_payment(
&self,
web_driver: WebDriver,
url: &str,
actions: Vec<Event<'_>>,
) -> Result<(), WebDriverError> {
self.execute_gpay_steps(web_driver, url, actions).await
}
async fn execute_gpay_steps(
&self,
web_driver: WebDriver,
url: &str,
actions: Vec<Event<'_>>,
) -> Result<(), WebDriverError> {
let config = self.get_configs().automation_configs.unwrap();
let (email, pass) = (&config.gmail_email.unwrap(), &config.gmail_pass.unwrap());
let default_actions = vec![
Event::Trigger(Trigger::Goto(url)),
Event::Trigger(Trigger::Click(By::Css(".gpay-button"))),
Event::Trigger(Trigger::SwitchTab(Position::Next)),
Event::Trigger(Trigger::Sleep(5)),
Event::RunIf(
Assert::EitherOfThemExist("Use your Google Account", "Sign in"),
vec![
Event::Trigger(Trigger::SendKeys(By::Id("identifierId"), email)),
Event::Trigger(Trigger::ClickNth(By::Tag("button"), 2)),
Event::EitherOr(
Assert::IsPresent("Welcome"),
vec![
Event::Trigger(Trigger::SendKeys(By::Name("Passwd"), pass)),
Event::Trigger(Trigger::Sleep(2)),
Event::Trigger(Trigger::Click(By::Id("passwordNext"))),
Event::Trigger(Trigger::Sleep(10)),
],
vec![
Event::Trigger(Trigger::SendKeys(By::Id("identifierId"), email)),
Event::Trigger(Trigger::ClickNth(By::Tag("button"), 2)),
Event::Trigger(Trigger::SendKeys(By::Name("Passwd"), pass)),
Event::Trigger(Trigger::Sleep(2)),
Event::Trigger(Trigger::Click(By::Id("passwordNext"))),
Event::Trigger(Trigger::Sleep(10)),
],
),
],
),
Event::Trigger(Trigger::SwitchFrame(By::Css(
".bootstrapperIframeContainerElement iframe",
))),
Event::Assert(Assert::IsPresent("Gpay Tester")),
Event::Trigger(Trigger::Click(By::ClassName("jfk-button-action"))),
Event::Trigger(Trigger::SwitchTab(Position::Prev)),
];
self.complete_actions(&web_driver, default_actions).await?;
self.complete_actions(&web_driver, actions).await
}
async fn make_affirm_payment(
&self,
driver: WebDriver,
url: &str,
actions: Vec<Event<'_>>,
) -> Result<(), WebDriverError> {
self.complete_actions(
&driver,
vec![
Event::Trigger(Trigger::Goto(url)),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
],
)
.await?;
let mut affirm_actions = vec![
Event::RunIf(
Assert::IsPresent("Big purchase? No problem."),
vec![
Event::Trigger(Trigger::SendKeys(
By::Css("input[data-testid='phone-number-field']"),
"(833) 549-5574", // any test phone number accepted by affirm
)),
Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='submit-button']",
))),
Event::Trigger(Trigger::SendKeys(
By::Css("input[data-testid='phone-pin-field']"),
"1234",
)),
],
),
Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='skip-payment-button']",
))),
Event::Trigger(Trigger::Click(By::Css("div[data-testid='indicator']"))),
Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='submit-button']",
))),
Event::Trigger(Trigger::Click(By::Css("div[data-testid='indicator']"))),
Event::Trigger(Trigger::Click(By::Css(
"div[data-testid='disclosure-checkbox-indicator']",
))),
Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='submit-button']",
))),
];
affirm_actions.extend(actions);
self.complete_actions(&driver, affirm_actions).await
}
async fn make_webhook_test(
&self,
web_driver: WebDriver,
payment_url: &str,
actions: Vec<Event<'_>>,
webhook_retry_time: u64,
webhook_status: &str,
) -> Result<(), WebDriverError> {
self.complete_actions(
&web_driver,
vec![Event::Trigger(Trigger::Goto(payment_url))],
)
.await?;
self.complete_actions(&web_driver, actions).await?; //additional actions needs to make a payment
self.complete_actions(
&web_driver,
vec![Event::Trigger(Trigger::Goto(&format!(
"{CHECKOUT_BASE_URL}/events"
)))],
)
.await?;
let element = web_driver.query(By::Css("h2.last-payment")).first().await?;
let payment_id = element.text().await?;
let retries = 3; // no of retry times
for _i in 0..retries {
let configs = self.get_configs().automation_configs.unwrap();
let outgoing_webhook_url = configs.hs_webhook_url.unwrap().to_string();
let client = reqwest::Client::new();
let response = client.get(outgoing_webhook_url).send().await.unwrap(); // get events from outgoing webhook endpoint
let body_text = response.text().await.unwrap();
let data: WebhookResponse = serde_json::from_str(&body_text).unwrap();
let last_three_events = data.data.get(data.data.len().saturating_sub(3)..).unwrap(); // Get the last three elements if available
for last_event in last_three_events {
let last_event_body = &last_event.step.request.body;
let decoded_bytes = base64::engine::general_purpose::STANDARD //decode the encoded outgoing webhook event
.decode(last_event_body)
.unwrap();
let decoded_str = String::from_utf8(decoded_bytes).unwrap();
let webhook_response: HsWebhookResponse =
serde_json::from_str(&decoded_str).unwrap();
if payment_id == webhook_response.content.object.payment_id
&& webhook_status == webhook_response.content.object.status
{
return Ok(());
}
}
self.complete_actions(
&web_driver,
vec![Event::Trigger(Trigger::Sleep(webhook_retry_time))],
)
.await?;
}
Err(WebDriverError::CustomError("Webhook Not Found".to_string()))
}
async fn make_paypal_payment(
&self,
web_driver: WebDriver,
url: &str,
actions: Vec<Event<'_>>,
) -> Result<(), WebDriverError> {
let pypl_url = url.to_string();
// To support failure retries
let result = self
.execute_paypal_steps(web_driver.clone(), &pypl_url, actions.clone())
.await;
if result.is_err() {
self.execute_paypal_steps(web_driver.clone(), &pypl_url, actions.clone())
.await
} else {
result
}
}
async fn execute_paypal_steps(
&self,
web_driver: WebDriver,
url: &str,
actions: Vec<Event<'_>>,
) -> Result<(), WebDriverError> {
self.complete_actions(
&web_driver,
vec![
Event::Trigger(Trigger::Goto(url)),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
],
)
.await?;
let (email, pass) = (
&self
.get_configs()
.automation_configs
.unwrap()
.pypl_email
.unwrap(),
&self
.get_configs()
.automation_configs
.unwrap()
.pypl_pass
.unwrap(),
);
let mut pypl_actions = vec![
Event::Trigger(Trigger::Sleep(8)),
Event::RunIf(
Assert::IsPresentNow("Enter your email address to get started"),
vec![
Event::Trigger(Trigger::SendKeys(By::Id("email"), email)),
Event::Trigger(Trigger::Click(By::Id("btnNext"))),
],
),
Event::RunIf(
Assert::IsPresentNow("Password"),
vec![
Event::Trigger(Trigger::SendKeys(By::Id("password"), pass)),
Event::Trigger(Trigger::Click(By::Id("btnLogin"))),
],
),
];
pypl_actions.extend(actions);
self.complete_actions(&web_driver, pypl_actions).await
}
async fn make_clearpay_payment(
&self,
driver: WebDriver,
url: &str,
actions: Vec<Event<'_>>,
) -> Result<(), WebDriverError> {
self.complete_actions(
&driver,
vec![
Event::Trigger(Trigger::Goto(url)),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Sleep(5)),
Event::RunIf(
Assert::IsPresentNow("Manage Cookies"),
vec![
Event::Trigger(Trigger::Click(By::Css("button.cookie-setting-link"))),
Event::Trigger(Trigger::Click(By::Id("accept-recommended-btn-handler"))),
],
),
],
)
.await?;
let (email, pass) = (
&self
.get_configs()
.automation_configs
.unwrap()
.clearpay_email
.unwrap(),
&self
.get_configs()
.automation_configs
.unwrap()
.clearpay_pass
.unwrap(),
);
let mut clearpay_actions = vec![
Event::Trigger(Trigger::Sleep(3)),
Event::EitherOr(
Assert::IsPresent("Please enter your password"),
vec![
Event::Trigger(Trigger::SendKeys(By::Css("input[name='password']"), pass)),
Event::Trigger(Trigger::Click(By::Css("button[type='submit']"))),
],
vec![
Event::Trigger(Trigger::SendKeys(
By::Css("input[name='identifier']"),
email,
)),
Event::Trigger(Trigger::Click(By::Css("button[type='submit']"))),
Event::Trigger(Trigger::Sleep(3)),
Event::Trigger(Trigger::SendKeys(By::Css("input[name='password']"), pass)),
Event::Trigger(Trigger::Click(By::Css("button[type='submit']"))),
],
),
Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='summary-button']",
))),
];
clearpay_actions.extend(actions);
self.complete_actions(&driver, clearpay_actions).await
}
}
async fn is_text_present_now(driver: &WebDriver, key: &str) -> WebDriverResult<bool> {
let mut xpath = "//*[contains(text(),'".to_owned();
xpath.push_str(key);
xpath.push_str("')]");
let result = driver.find(By::XPath(&xpath)).await?;
let display: &str = &result.css_value("display").await?;
if display.is_empty() || display == "none" {
return Err(WebDriverError::CustomError("Element is hidden".to_string()));
}
result.is_present().await
}
async fn is_text_present(driver: &WebDriver, key: &str) -> WebDriverResult<bool> {
let mut xpath = "//*[contains(text(),'".to_owned();
xpath.push_str(key);
xpath.push_str("')]");
let result = driver.query(By::XPath(&xpath)).first().await?;
result.is_present().await
}
async fn is_element_present(driver: &WebDriver, by: By) -> WebDriverResult<bool> {
let element = driver.query(by).first().await?;
element.is_present().await
}
#[macro_export]
macro_rules! tester_inner {
($execute:ident, $webdriver:expr) => {{
use std::{
sync::{Arc, Mutex},
thread,
};
let driver = $webdriver;
// we'll need the session_id from the thread
// NOTE: even if it panics, so can't just return it
let session_id = Arc::new(Mutex::new(None));
// run test in its own thread to catch panics
let sid = session_id.clone();
let res = thread::spawn(move || {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
let driver = runtime
.block_on(driver)
.expect("failed to construct test WebDriver");
*sid.lock().unwrap() = runtime.block_on(driver.session_id()).ok();
// make sure we close, even if an assertion fails
let client = driver.clone();
let x = runtime.block_on(async move {
let run = tokio::spawn($execute(driver)).await;
let _ = client.quit().await;
run
});
drop(runtime);
x.expect("test panicked")
})
.join();
let success = handle_test_error(res);
assert!(success);
}};
}
#[macro_export]
macro_rules! function {
() => {{
fn f() {}
fn type_name_of<T>(_: T) -> &'static str {
std::any::type_name::<T>()
}
let name = type_name_of(f);
&name.get(..name.len() - 3).unwrap()
}};
}
#[macro_export]
macro_rules! tester {
($f:ident) => {{
use $crate::{function, tester_inner};
let test_name = format!("{:?}", function!());
if (should_ignore_test(&test_name)) {
return;
}
let browser = get_browser();
let url = make_url(&browser);
let caps = make_capabilities(&browser);
tester_inner!($f, WebDriver::new(url, caps));
}};
}
fn get_saved_testcases() -> serde_json::Value {
let env_value = env::var("CONNECTOR_TESTS_FILE_PATH").ok();
if env_value.is_none() {
return serde_json::json!("");
}
let path = env_value.unwrap();
let mut file = &std::fs::File::open(path).expect("Failed to open file");
let mut contents = String::new();
file.read_to_string(&mut contents)
.expect("Failed to read file");
// Parse the JSON data
serde_json::from_str(&contents).expect("Failed to parse JSON")
}
fn get_configs() -> connector_auth::ConnectorAuthentication {
let path =
env::var("CONNECTOR_AUTH_FILE_PATH").expect("connector authentication file path not set");
toml::from_str(
&std::fs::read_to_string(path).expect("connector authentication config file not found"),
)
.expect("Failed to read connector authentication config file")
}
pub fn should_ignore_test(name: &str) -> bool {
let conf = get_saved_testcases()
.get("tests_to_ignore")
.unwrap_or(&json!([]))
.clone();
let tests_to_ignore: HashSet<String> =
serde_json::from_value(conf).unwrap_or_else(|_| HashSet::new());
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/test_utils/tests/connectors/shift4_ui.rs | crates/test_utils/tests/connectors/shift4_ui.rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct Shift4SeleniumTest;
impl SeleniumTest for Shift4SeleniumTest {
fn get_connector_name(&self) -> String {
"shift4".to_string()
}
}
async fn should_make_3ds_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = Shift4SeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/37"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::ClassName("btn-success"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_giropay_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = Shift4SeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/39"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::ClassName("btn-success"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_ideal_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = Shift4SeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/42"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::ClassName("btn-success"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_sofort_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = Shift4SeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/43"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::ClassName("btn-success"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_eps_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = Shift4SeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/157"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::ClassName("btn-success"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
#[test]
#[serial]
fn should_make_3ds_payment_test() {
tester!(should_make_3ds_payment);
}
#[test]
#[serial]
fn should_make_giropay_payment_test() {
tester!(should_make_giropay_payment);
}
#[test]
#[serial]
fn should_make_ideal_payment_test() {
tester!(should_make_ideal_payment);
}
#[test]
#[serial]
fn should_make_sofort_payment_test() {
tester!(should_make_sofort_payment);
}
#[test]
#[serial]
fn should_make_eps_payment_test() {
tester!(should_make_eps_payment);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/test_utils/tests/connectors/adyen_uk_ui.rs | crates/test_utils/tests/connectors/adyen_uk_ui.rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct AdyenSeleniumTest;
impl SeleniumTest for AdyenSeleniumTest {
fn get_connector_name(&self) -> String {
"adyen_uk".to_string()
}
}
async fn should_make_adyen_3ds_payment_failed(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/177"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SwitchFrame(By::Name("threeDSIframe"))),
Event::Assert(Assert::IsPresent("AUTHENTICATION DETAILS")),
Event::Trigger(Trigger::SendKeys(By::ClassName("input-field"), "password")),
Event::Trigger(Trigger::Click(By::Id("buttonSubmit"))),
Event::Trigger(Trigger::Sleep(5)),
Event::Assert(Assert::IsPresent("failed")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_3ds_payment_success(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/62"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SwitchFrame(By::Name("threeDSIframe"))),
Event::Assert(Assert::IsPresent("AUTHENTICATION DETAILS")),
Event::Trigger(Trigger::SendKeys(By::ClassName("input-field"), "password")),
Event::Trigger(Trigger::Click(By::Id("buttonSubmit"))),
Event::Trigger(Trigger::Sleep(5)),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_3ds_mandate_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/203"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")), // mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("a.btn"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_3ds_mandate_with_zero_dollar_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/204"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")), // mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("a.btn"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_gpay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_gpay_payment(web_driver,
&format!("{CHECKOUT_BASE_URL}/gpay?gatewayname=adyen&gatewaymerchantid=JuspayDEECOM&amount=70.00&country=US¤cy=USD"),
vec![
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
async fn should_make_adyen_gpay_mandate_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_gpay_payment(web_driver,
&format!("{CHECKOUT_BASE_URL}/gpay?gatewayname=adyen&gatewaymerchantid=JuspayDEECOM&amount=70.00&country=US¤cy=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=7000&mandate_data[mandate_type][multi_use][currency]=USD"),
vec![
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
async fn should_make_adyen_gpay_zero_dollar_mandate_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_gpay_payment(web_driver,
&format!("{CHECKOUT_BASE_URL}/gpay?gatewayname=adyen&gatewaymerchantid=JuspayDEECOM&amount=0.00&country=US¤cy=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD"),
vec![
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
async fn should_make_adyen_klarna_mandate_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/195"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SwitchFrame(By::Id("klarna-apf-iframe"))),
Event::Trigger(Trigger::Sleep(5)),
Event::Trigger(Trigger::Click(By::Id("signInWithBankId"))),
Event::Assert(Assert::IsPresent("Klart att betala")),
Event::EitherOr(
Assert::IsPresent("Klart att betala"),
vec![Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='confirm-and-pay']",
)))],
vec![
Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='SmoothCheckoutPopUp:skip']",
))),
Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='confirm-and-pay']",
))),
],
),
Event::RunIf(
Assert::IsPresent("Färre klick, snabbare betalning"),
vec![Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='SmoothCheckoutPopUp:enable']",
)))],
),
Event::Trigger(Trigger::SwitchTab(Position::Prev)),
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")), // mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_alipay_hk_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/162"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::EitherOr(
Assert::IsPresent("Payment Method Not Available"),
vec![Event::Assert(Assert::IsPresent(
"Please try again or select a different payment method",
))],
vec![
Event::Trigger(Trigger::Click(By::Css("button[value='authorised']"))),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_bizum_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/186"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SendKeys(By::Id("iPhBizInit"), "700000000")),
Event::Trigger(Trigger::Click(By::Id("bBizInit"))),
Event::Trigger(Trigger::Click(By::Css("input.btn.btn-lg.btn-continue"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_clearpay_payment(driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_clearpay_payment(
driver,
&format!("{CHECKOUT_BASE_URL}/saved/163"),
vec![Event::Assert(Assert::IsPresent("succeeded"))],
)
.await?;
Ok(())
}
async fn should_make_adyen_paypal_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_paypal_payment(
web_driver,
&format!("{CHECKOUT_BASE_URL}/saved/202"),
vec![
Event::Trigger(Trigger::Click(By::Id("payment-submit-btn"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=processing"], //final status of this payment method will remain in processing state
)),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_ach_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/58"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_sepa_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/51"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_bacs_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/54"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Status")),
Event::Assert(Assert::IsPresent("processing")), //final status of this payment method will remain in processing state
],
)
.await?;
Ok(())
}
async fn should_make_adyen_ideal_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/52"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::ClassName("btnLink"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_eps_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/61"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("button[value='authorised']"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_bancontact_card_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
let user = &conn
.get_configs()
.automation_configs
.unwrap()
.adyen_bancontact_username
.unwrap();
let pass = &conn
.get_configs()
.automation_configs
.unwrap()
.adyen_bancontact_pass
.unwrap();
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/68"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SendKeys(By::Id("username"), user)),
Event::Trigger(Trigger::SendKeys(By::Id("password"), pass)),
Event::Trigger(Trigger::Click(By::ClassName("button"))),
Event::Trigger(Trigger::Sleep(2)),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_wechatpay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/75"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("button[value='authorised']"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_mbway_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/196"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Status")),
Event::Assert(Assert::IsPresent("processing")), //final status of this payment method will remain in processing state
],
)
.await?;
Ok(())
}
async fn should_make_adyen_ebanking_fi_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/78"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::ClassName("css-ns0tbt"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_onlinebanking_pl_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/197"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Id("user_account_pbl_correct"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded", "status=processing"],
)),
],
)
.await?;
Ok(())
}
#[ignore]
async fn should_make_adyen_giropay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/70"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SendKeys(
By::Css("input[id='tags']"),
"Testbank Fiducia 44448888 GENODETT488",
)),
Event::Trigger(Trigger::Click(By::Css("input[id='tags']"))),
Event::Trigger(Trigger::Sleep(3)),
Event::Trigger(Trigger::Click(By::Id("ui-id-3"))),
Event::Trigger(Trigger::Click(By::ClassName("blueButton"))),
Event::Trigger(Trigger::SendKeys(By::Name("sc"), "10")),
Event::Trigger(Trigger::SendKeys(By::Name("extensionSc"), "4000")),
Event::Trigger(Trigger::SendKeys(By::Name("customerName1"), "Hopper")),
Event::Trigger(Trigger::SendKeys(
By::Name("customerIBAN"),
"DE36444488881234567890",
)),
Event::Trigger(Trigger::Click(By::Css("input[value='Absenden']"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=processing"], //final status of this payment method will remain in processing state
)),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_twint_payment(driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/170"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("button[value='authorised']"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_walley_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/198"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Teknikmössor AB")),
Event::Trigger(Trigger::SwitchFrame(By::ClassName(
"collector-checkout-iframe",
))),
Event::Trigger(Trigger::Click(By::Id("purchase"))),
Event::Trigger(Trigger::Sleep(10)),
Event::Trigger(Trigger::SwitchFrame(By::Css(
"iframe[title='Walley Modal - idp-choices']",
))),
Event::Assert(Assert::IsPresent("Identifisering")),
Event::Trigger(Trigger::Click(By::Id("optionLoggInnMedBankId"))),
Event::Trigger(Trigger::SwitchFrame(By::Css("iframe[title='BankID']"))),
Event::Assert(Assert::IsPresent("Engangskode")),
Event::Trigger(Trigger::SendKeys(By::Css("input[type='password']"), "otp")),
Event::Trigger(Trigger::Sleep(4)),
Event::Trigger(Trigger::Click(By::Css("button[title='Neste']"))),
Event::Assert(Assert::IsPresent("Ditt BankID-passord")),
Event::Trigger(Trigger::Sleep(4)),
Event::Trigger(Trigger::SendKeys(
By::Css("input[type='password']"),
"qwer1234",
)),
Event::Trigger(Trigger::Click(By::Css("button[title='Neste']"))),
Event::Trigger(Trigger::SwitchTab(Position::Prev)),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_dana_payment(driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/175"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SendKeys(
By::Css("input[type='number']"),
"12345678901",
)), // Mobile Number can be any random 11 digit number
Event::Trigger(Trigger::Click(By::Css("button"))),
Event::Trigger(Trigger::SendKeys(By::Css("input[type='number']"), "111111")), // PIN can be any random 11 digit number
Event::Trigger(Trigger::Click(By::ClassName("btn-next"))),
Event::Trigger(Trigger::Sleep(3)),
Event::Trigger(Trigger::Click(By::ClassName("btn-next"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_online_banking_fpx_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/172"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("button[value='authorised']"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_online_banking_thailand_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/184"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("button[value='authorised']"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_touch_n_go_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/185"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("button[value='authorised']"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_swish_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/210"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("status")),
Event::Assert(Assert::IsPresent("processing")),
Event::Assert(Assert::IsPresent("Next Action Type")),
Event::Assert(Assert::IsPresent("qr_code_information")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_blik_payment(driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/64"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Next Action Type")),
Event::Assert(Assert::IsPresent("wait_screen_information")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_momo_atm_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/238"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Sleep(5)), // Delay for provider to not reject payment for botting
Event::Trigger(Trigger::SendKeys(
By::Id("card-number"),
"9704 0000 0000 0018",
)),
Event::Trigger(Trigger::SendKeys(By::Id("card-expire"), "03/07")),
Event::Trigger(Trigger::SendKeys(By::Id("card-name"), "NGUYEN VAN A")),
Event::Trigger(Trigger::SendKeys(By::Id("number-phone"), "987656666")),
Event::Trigger(Trigger::Click(By::Id("btn-pay-card"))),
Event::Trigger(Trigger::SendKeys(By::Id("napasOtpCode"), "otp")),
Event::Trigger(Trigger::Click(By::Id("napasProcessBtn1"))),
Event::Trigger(Trigger::Sleep(5)), // Delay to get to status page
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
#[test]
#[serial]
fn should_make_adyen_gpay_payment_test() {
tester!(should_make_adyen_gpay_payment);
}
#[test]
#[serial]
fn should_make_adyen_gpay_mandate_payment_test() {
tester!(should_make_adyen_gpay_mandate_payment);
}
#[test]
#[serial]
fn should_make_adyen_gpay_zero_dollar_mandate_payment_test() {
tester!(should_make_adyen_gpay_zero_dollar_mandate_payment);
}
#[test]
#[serial]
fn should_make_adyen_klarna_mandate_payment_test() {
tester!(should_make_adyen_klarna_mandate_payment);
}
#[test]
#[serial]
fn should_make_adyen_3ds_payment_failed_test() {
tester!(should_make_adyen_3ds_payment_failed);
}
#[test]
#[serial]
fn should_make_adyen_3ds_mandate_payment_test() {
tester!(should_make_adyen_3ds_mandate_payment);
}
#[test]
#[serial]
fn should_make_adyen_3ds_mandate_with_zero_dollar_payment_test() {
tester!(should_make_adyen_3ds_mandate_with_zero_dollar_payment);
}
#[test]
#[serial]
fn should_make_adyen_3ds_payment_success_test() {
tester!(should_make_adyen_3ds_payment_success);
}
#[test]
#[serial]
fn should_make_adyen_alipay_hk_payment_test() {
tester!(should_make_adyen_alipay_hk_payment);
}
#[test]
#[serial]
fn should_make_adyen_swish_payment_test() {
tester!(should_make_adyen_swish_payment);
}
#[test]
#[serial]
#[ignore = "Failing from connector side"]
fn should_make_adyen_bizum_payment_test() {
tester!(should_make_adyen_bizum_payment);
}
#[test]
#[serial]
fn should_make_adyen_clearpay_payment_test() {
tester!(should_make_adyen_clearpay_payment);
}
#[test]
#[serial]
fn should_make_adyen_twint_payment_test() {
tester!(should_make_adyen_twint_payment);
}
#[test]
#[serial]
fn should_make_adyen_paypal_payment_test() {
tester!(should_make_adyen_paypal_payment);
}
#[test]
#[serial]
fn should_make_adyen_ach_payment_test() {
tester!(should_make_adyen_ach_payment);
}
#[test]
#[serial]
fn should_make_adyen_sepa_payment_test() {
tester!(should_make_adyen_sepa_payment);
}
#[test]
#[serial]
fn should_make_adyen_bacs_payment_test() {
tester!(should_make_adyen_bacs_payment);
}
#[test]
#[serial]
fn should_make_adyen_ideal_payment_test() {
tester!(should_make_adyen_ideal_payment);
}
#[test]
#[serial]
fn should_make_adyen_eps_payment_test() {
tester!(should_make_adyen_eps_payment);
}
#[test]
#[serial]
fn should_make_adyen_bancontact_card_payment_test() {
tester!(should_make_adyen_bancontact_card_payment);
}
#[test]
#[serial]
fn should_make_adyen_wechatpay_payment_test() {
tester!(should_make_adyen_wechatpay_payment);
}
#[test]
#[serial]
fn should_make_adyen_mbway_payment_test() {
tester!(should_make_adyen_mbway_payment);
}
#[test]
#[serial]
fn should_make_adyen_ebanking_fi_payment_test() {
tester!(should_make_adyen_ebanking_fi_payment);
}
#[test]
#[serial]
fn should_make_adyen_onlinebanking_pl_payment_test() {
tester!(should_make_adyen_onlinebanking_pl_payment);
}
#[ignore]
#[test]
#[serial]
fn should_make_adyen_giropay_payment_test() {
tester!(should_make_adyen_giropay_payment);
}
#[ignore]
#[test]
#[serial]
fn should_make_adyen_walley_payment_test() {
tester!(should_make_adyen_walley_payment);
}
#[test]
#[serial]
fn should_make_adyen_dana_payment_test() {
tester!(should_make_adyen_dana_payment);
}
#[test]
#[serial]
fn should_make_adyen_blik_payment_test() {
tester!(should_make_adyen_blik_payment);
}
#[test]
#[serial]
fn should_make_adyen_online_banking_fpx_payment_test() {
tester!(should_make_adyen_online_banking_fpx_payment);
}
#[test]
#[serial]
fn should_make_adyen_online_banking_thailand_payment_test() {
tester!(should_make_adyen_online_banking_thailand_payment);
}
#[test]
#[serial]
fn should_make_adyen_touch_n_go_payment_test() {
tester!(should_make_adyen_touch_n_go_payment);
}
#[ignore]
#[test]
#[serial]
fn should_make_adyen_momo_atm_payment_test() {
tester!(should_make_adyen_momo_atm_payment);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/test_utils/tests/connectors/authorizedotnet_wh_ui.rs | crates/test_utils/tests/connectors/authorizedotnet_wh_ui.rs | use rand::Rng;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct AuthorizedotnetSeleniumTest;
impl SeleniumTest for AuthorizedotnetSeleniumTest {
fn get_connector_name(&self) -> String {
"authorizedotnet".to_string()
}
}
async fn should_make_webhook(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AuthorizedotnetSeleniumTest {};
let amount = rand::thread_rng().gen_range(50..1000); //This connector detects it as fraudulent payment if the same amount is used for multiple payments so random amount is passed for testing(
conn.make_webhook_test(
web_driver,
&format!("{CHECKOUT_BASE_URL}/saved/227?amount={amount}"),
vec![
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("status")),
Event::Assert(Assert::IsPresent("processing")),
],
10,
"processing",
)
.await?;
Ok(())
}
#[test]
fn should_make_webhook_test() {
tester!(should_make_webhook);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/test_utils/tests/connectors/trustpay_3ds_ui.rs | crates/test_utils/tests/connectors/trustpay_3ds_ui.rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct TrustpaySeleniumTest;
impl SeleniumTest for TrustpaySeleniumTest {
fn get_connector_name(&self) -> String {
"trustpay_3ds".to_string()
}
}
async fn should_make_trustpay_3ds_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = TrustpaySeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/206"))),
Event::Trigger(Trigger::Sleep(1)),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"button.btn.btn-lg.btn-primary.btn-block",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
#[test]
#[serial]
#[ignore]
fn should_make_trustpay_3ds_payment_test() {
tester!(should_make_trustpay_3ds_payment);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/test_utils/tests/connectors/stripe_wh_ui.rs | crates/test_utils/tests/connectors/stripe_wh_ui.rs | use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct StripeSeleniumTest;
impl SeleniumTest for StripeSeleniumTest {
fn get_connector_name(&self) -> String {
"stripe".to_string()
}
}
async fn should_make_webhook(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_webhook_test(
web_driver,
&format!("{CHECKOUT_BASE_URL}/saved/16"),
vec![
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("status")),
Event::Assert(Assert::IsPresent("succeeded")),
],
10,
"succeeded",
)
.await?;
Ok(())
}
#[test]
fn should_make_webhook_test() {
tester!(should_make_webhook);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/test_utils/tests/connectors/checkout_ui.rs | crates/test_utils/tests/connectors/checkout_ui.rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct CheckoutSeleniumTest;
impl SeleniumTest for CheckoutSeleniumTest {
fn get_connector_name(&self) -> String {
"checkout".to_string()
}
}
async fn should_make_frictionless_3ds_payment(c: WebDriver) -> Result<(), WebDriverError> {
let mycon = CheckoutSeleniumTest {};
mycon
.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/18"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Google Search")),
Event::Trigger(Trigger::Sleep(5)), //url gets updated only after some time, so need this timeout to solve the issue
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded", "status=processing"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_3ds_payment(c: WebDriver) -> Result<(), WebDriverError> {
let mycon = CheckoutSeleniumTest {};
mycon
.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/20"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Sleep(5)), //url gets updated only after some time, so need this timeout to solve the issue
Event::Trigger(Trigger::SwitchFrame(By::Name("cko-3ds2-iframe"))),
Event::Trigger(Trigger::SendKeys(By::Id("password"), "Checkout1!")),
Event::Trigger(Trigger::Click(By::Id("txtButton"))),
Event::Trigger(Trigger::Sleep(2)),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded", "status=processing"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_gpay_payment(c: WebDriver) -> Result<(), WebDriverError> {
let mycon = CheckoutSeleniumTest {};
mycon
.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/73"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Sleep(10)), //url gets updated only after some time, so need this timeout to solve the issue
Event::Trigger(Trigger::SwitchFrame(By::Name("cko-3ds2-iframe"))),
Event::Trigger(Trigger::SendKeys(By::Id("password"), "Checkout1!")),
Event::Trigger(Trigger::Click(By::Id("txtButton"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded", "status=processing"],
)),
],
)
.await?;
Ok(())
}
#[test]
#[serial]
fn should_make_frictionless_3ds_payment_test() {
tester!(should_make_frictionless_3ds_payment);
}
#[test]
#[serial]
fn should_make_3ds_payment_test() {
tester!(should_make_3ds_payment);
}
#[test]
#[serial]
#[ignore]
fn should_make_gpay_payment_test() {
tester!(should_make_gpay_payment);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/test_utils/tests/connectors/nexinets_ui.rs | crates/test_utils/tests/connectors/nexinets_ui.rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct NexinetsSeleniumTest;
impl SeleniumTest for NexinetsSeleniumTest {
fn get_connector_name(&self) -> String {
"nexinets".to_string()
}
}
async fn should_make_paypal_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = NexinetsSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/220"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"a.btn.btn-primary.btn-block.margin-bottm-15",
))),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded", "status=processing"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_3ds_card_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = NexinetsSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/221"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SwitchFrame(By::Id("threeDSCReqIframe"))),
Event::Trigger(Trigger::SendKeys(By::Id("otp"), "1234")),
Event::Trigger(Trigger::Click(By::Css("button#sendOtp"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded", "status=processing"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_ideal_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = NexinetsSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/222"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"a.btn.btn-primary.btn-block.margin-bottm-15",
))),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded", "status=processing"],
)),
],
)
.await?;
Ok(())
}
#[test]
#[serial]
fn should_make_paypal_payment_test() {
tester!(should_make_paypal_payment);
}
#[test]
#[serial]
fn should_make_3ds_card_payment_test() {
tester!(should_make_3ds_card_payment);
}
#[test]
#[serial]
fn should_make_ideal_payment_test() {
tester!(should_make_ideal_payment);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/test_utils/tests/connectors/adyen_uk_wh_ui.rs | crates/test_utils/tests/connectors/adyen_uk_wh_ui.rs | use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct AdyenSeleniumTest;
impl SeleniumTest for AdyenSeleniumTest {
fn get_connector_name(&self) -> String {
"adyen_uk".to_string()
}
}
async fn should_make_webhook(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_webhook_test(
web_driver,
&format!("{CHECKOUT_BASE_URL}/saved/104"),
vec![
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
10,
"succeeded",
)
.await?;
Ok(())
}
#[test]
fn should_make_webhook_test() {
tester!(should_make_webhook);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/test_utils/tests/connectors/bluesnap_wh_ui.rs | crates/test_utils/tests/connectors/bluesnap_wh_ui.rs | use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct BluesnapSeleniumTest;
impl SeleniumTest for BluesnapSeleniumTest {
fn get_connector_name(&self) -> String {
"bluesnap".to_string()
}
}
async fn should_make_webhook(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = BluesnapSeleniumTest {};
conn.make_webhook_test(
web_driver,
&format!("{CHECKOUT_BASE_URL}/saved/199"),
vec![
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
10,
"succeeded",
)
.await?;
Ok(())
}
#[test]
fn should_make_webhook_test() {
tester!(should_make_webhook);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/test_utils/tests/connectors/payu_ui.rs | crates/test_utils/tests/connectors/payu_ui.rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct PayUSeleniumTest;
impl SeleniumTest for PayUSeleniumTest {
fn get_connector_name(&self) -> String {
"payu".to_string()
}
}
async fn should_make_no_3ds_card_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = PayUSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/72"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Sleep(1)),
Event::Assert(Assert::IsPresent("status")),
Event::Assert(Assert::IsPresent("processing")),
],
)
.await?;
Ok(())
}
async fn should_make_gpay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = PayUSeleniumTest {};
conn.make_gpay_payment(web_driver,
&format!("{CHECKOUT_BASE_URL}/gpay?gatewayname=payu&gatewaymerchantid=459551&amount=70.00&country=US¤cy=PLN"),
vec![
Event::Assert(Assert::IsPresent("Status")),
Event::Assert(Assert::IsPresent("processing")),
]).await?;
Ok(())
}
#[test]
#[serial]
fn should_make_no_3ds_card_payment_test() {
tester!(should_make_no_3ds_card_payment);
}
#[test]
#[serial]
#[ignore]
fn should_make_gpay_payment_test() {
tester!(should_make_gpay_payment);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/test_utils/tests/connectors/main.rs | crates/test_utils/tests/connectors/main.rs | #![allow(
clippy::expect_used,
clippy::panic,
clippy::unwrap_in_result,
clippy::unwrap_used,
clippy::print_stderr
)]
mod aci_ui;
mod adyen_uk_ui;
mod adyen_uk_wh_ui;
mod airwallex_ui;
mod authorizedotnet_ui;
mod authorizedotnet_wh_ui;
mod bambora_ui;
mod bluesnap_ui;
mod bluesnap_wh_ui;
mod checkout_ui;
mod checkout_wh_ui;
mod globalpay_ui;
mod mollie_ui;
mod multisafepay_ui;
mod nexinets_ui;
mod noon_ui;
mod nuvei_ui;
mod paypal_ui;
mod payu_ui;
mod selenium;
mod shift4_ui;
mod stripe_ui;
mod stripe_wh_ui;
mod trustpay_3ds_ui;
mod worldline_ui;
mod zen_ui;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/test_utils/tests/connectors/airwallex_ui.rs | crates/test_utils/tests/connectors/airwallex_ui.rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct AirwallexSeleniumTest;
impl SeleniumTest for AirwallexSeleniumTest {
fn get_connector_name(&self) -> String {
"airwallex".to_string()
}
}
async fn should_make_airwallex_3ds_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AirwallexSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/85"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Query(By::ClassName("title"))),
Event::Assert(Assert::Eq(
Selector::Title,
"Airwallex - Create 3D Secure Payment",
)),
Event::Trigger(Trigger::SendKeys(By::Id("challengeDataEntry"), "1234")),
Event::Trigger(Trigger::Click(By::Id("submit"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_airwallex_gpay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AirwallexSeleniumTest {};
let merchant_name = conn
.get_configs()
.automation_configs
.unwrap()
.airwallex_merchant_name
.unwrap();
conn.make_gpay_payment(web_driver,
&format!("{CHECKOUT_BASE_URL}/gpay?gatewayname=airwallex&gatewaymerchantid={merchant_name}&amount=70.00&country=US¤cy=USD"),
vec![
Event::Trigger(Trigger::Query(By::ClassName("title"))),
Event::Assert(Assert::Eq(Selector::Title, "Airwallex - Create 3D Secure Payment")),
Event::Trigger(Trigger::SendKeys(By::Id("challengeDataEntry"), "1234")),
Event::Trigger(Trigger::Click(By::Id("submit"))),
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
#[test]
#[serial]
fn should_make_airwallex_3ds_payment_test() {
tester!(should_make_airwallex_3ds_payment);
}
#[test]
#[serial]
#[ignore]
fn should_make_airwallex_gpay_payment_test() {
tester!(should_make_airwallex_gpay_payment);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/test_utils/tests/connectors/noon_ui.rs | crates/test_utils/tests/connectors/noon_ui.rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct NoonSeleniumTest;
impl SeleniumTest for NoonSeleniumTest {
fn get_connector_name(&self) -> String {
"noon".to_string()
}
}
async fn should_make_noon_3ds_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = NoonSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/176"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SwitchFrame(By::Id("redirectTo3ds1Frame"))),
Event::Trigger(Trigger::SwitchFrame(By::Css("iframe[frameborder='0']"))),
Event::Trigger(Trigger::SendKeys(By::Css("input.input-field"), "1234")),
Event::Trigger(Trigger::Click(By::Css("input.button.primary"))),
Event::Trigger(Trigger::Sleep(5)),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_noon_3ds_mandate_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = NoonSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/214"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SwitchFrame(By::Id("redirectTo3ds1Frame"))),
Event::Trigger(Trigger::SwitchFrame(By::Css("iframe[frameborder='0']"))),
Event::Trigger(Trigger::SendKeys(By::Css("input.input-field"), "1234")),
Event::Trigger(Trigger::Click(By::Css("input.button.primary"))),
Event::Trigger(Trigger::Sleep(5)),
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")), // mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("a.btn"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_noon_non_3ds_mandate_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = NoonSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/215"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")), // mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("a.btn"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
#[test]
#[serial]
fn should_make_noon_3ds_payment_test() {
tester!(should_make_noon_3ds_payment);
}
#[test]
#[serial]
fn should_make_noon_3ds_mandate_payment_test() {
tester!(should_make_noon_3ds_mandate_payment);
}
#[test]
#[serial]
fn should_make_noon_non_3ds_mandate_payment_test() {
tester!(should_make_noon_non_3ds_mandate_payment);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/test_utils/tests/connectors/nuvei_ui.rs | crates/test_utils/tests/connectors/nuvei_ui.rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct NuveiSeleniumTest;
impl SeleniumTest for NuveiSeleniumTest {
fn get_connector_name(&self) -> String {
"nuvei".to_string()
}
}
async fn should_make_nuvei_3ds_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = NuveiSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000027891380961&expmonth=10&expyear=25&cvv=123&amount=200&country=US¤cy=USD"))),
Event::Assert(Assert::IsPresent("Expiry Year")),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Query(By::ClassName("title"))),
Event::Assert(Assert::Eq(Selector::Title, "ThreeDS ACS Emulator - Challenge Page")),
Event::Trigger(Trigger::Click(By::Id("btn1"))),
Event::Trigger(Trigger::Click(By::Id("btn5"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(Selector::QueryParamStr, "status=succeeded")),
]).await?;
Ok(())
}
async fn should_make_nuvei_3ds_mandate_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = NuveiSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000027891380961&expmonth=10&expyear=25&cvv=123&amount=200&country=US¤cy=USD&setup_future_usage=off_session&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=in%20sit&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=7000&mandate_data[mandate_type][multi_use][currency]=USD&mandate_data[mandate_type][multi_use][start_date]=2022-09-10T00:00:00Z&mandate_data[mandate_type][multi_use][end_date]=2023-09-10T00:00:00Z&mandate_data[mandate_type][multi_use][metadata][frequency]=13&return_url={CHECKOUT_BASE_URL}/payments"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Query(By::ClassName("title"))),
Event::Assert(Assert::Eq(Selector::Title, "ThreeDS ACS Emulator - Challenge Page")),
Event::Trigger(Trigger::Click(By::Id("btn1"))),
Event::Trigger(Trigger::Click(By::Id("btn5"))),
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("man_")),//mandate id prefix is present
]).await?;
Ok(())
}
async fn should_make_nuvei_gpay_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = NuveiSeleniumTest {};
conn.make_gpay_payment(c,
&format!("{CHECKOUT_BASE_URL}/gpay?gatewayname=nuveidigital&gatewaymerchantid=googletest&amount=10.00&country=IN¤cy=USD"),
vec![
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
async fn should_make_nuvei_pypl_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = NuveiSeleniumTest {};
conn.make_paypal_payment(
c,
&format!("{CHECKOUT_BASE_URL}/saved/5"),
vec![
Event::Trigger(Trigger::Click(By::Id("payment-submit-btn"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_nuvei_giropay_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = NuveiSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/bank-redirect?amount=1.00&country=DE¤cy=EUR&paymentmethod=giropay"))),
Event::Trigger(Trigger::Click(By::Id("bank-redirect-btn"))),
Event::Assert(Assert::IsPresent("You are about to make a payment using the Giropay service.")),
Event::Trigger(Trigger::Click(By::Id("ctl00_ctl00_mainContent_btnConfirm"))),
Event::RunIf(Assert::IsPresent("Bank suchen"), vec![
Event::Trigger(Trigger::SendKeys(By::Id("bankSearch"), "GIROPAY Testbank 1")),
Event::Trigger(Trigger::Click(By::Id("GIROPAY Testbank 1"))),
]),
Event::Assert(Assert::IsPresent("GIROPAY Testbank 1")),
Event::Trigger(Trigger::Click(By::Css("button[name='claimCheckoutButton']"))),
Event::Assert(Assert::IsPresent("sandbox.paydirekt")),
Event::Trigger(Trigger::Click(By::Id("submitButton"))),
Event::Trigger(Trigger::Sleep(5)),
Event::Trigger(Trigger::SwitchTab(Position::Next)),
Event::Assert(Assert::IsPresent("Sicher bezahlt!")),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(Selector::QueryParamStr, vec!["status=succeeded", "status=processing"]))
]).await?;
Ok(())
}
async fn should_make_nuvei_ideal_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = NuveiSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/bank-redirect?amount=10.00&country=NL¤cy=EUR&paymentmethod=ideal&processingbank=ing"))),
Event::Trigger(Trigger::Click(By::Id("bank-redirect-btn"))),
Event::Assert(Assert::IsPresent("Your account will be debited:")),
Event::Trigger(Trigger::SelectOption(By::Id("ctl00_ctl00_mainContent_ServiceContent_ddlBanks"), "ING Simulator")),
Event::Trigger(Trigger::Click(By::Id("ctl00_ctl00_mainContent_btnConfirm"))),
Event::Assert(Assert::IsPresent("IDEALFORTIS")),
Event::Trigger(Trigger::Sleep(5)),
Event::Trigger(Trigger::Click(By::Id("ctl00_mainContent_btnGo"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(Selector::QueryParamStr, vec!["status=succeeded", "status=processing"]))
]).await?;
Ok(())
}
async fn should_make_nuvei_sofort_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = NuveiSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/bank-redirect?amount=10.00&country=DE¤cy=EUR&paymentmethod=sofort"))),
Event::Trigger(Trigger::Click(By::Id("bank-redirect-btn"))),
Event::Assert(Assert::IsPresent("SOFORT")),
Event::Trigger(Trigger::ChangeQueryParam("sender_holder", "John Doe")),
Event::Trigger(Trigger::Click(By::Id("ctl00_mainContent_btnGo"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(Selector::QueryParamStr, vec!["status=succeeded", "status=processing"]))
]).await?;
Ok(())
}
async fn should_make_nuvei_eps_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = NuveiSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/bank-redirect?amount=10.00&country=AT¤cy=EUR&paymentmethod=eps&processingbank=ing"))),
Event::Trigger(Trigger::Click(By::Id("bank-redirect-btn"))),
Event::Assert(Assert::IsPresent("You are about to make a payment using the EPS service.")),
Event::Trigger(Trigger::SendKeys(By::Id("ctl00_ctl00_mainContent_ServiceContent_txtCustomerName"), "John Doe")),
Event::Trigger(Trigger::Click(By::Id("ctl00_ctl00_mainContent_btnConfirm"))),
Event::Assert(Assert::IsPresent("Simulator")),
Event::Trigger(Trigger::SelectOption(By::Css("select[name='result']"), "Succeeded")),
Event::Trigger(Trigger::Click(By::Id("submitbutton"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(Selector::QueryParamStr, vec!["status=succeeded", "status=processing"]))
]).await?;
Ok(())
}
#[test]
#[serial]
fn should_make_nuvei_3ds_payment_test() {
tester!(should_make_nuvei_3ds_payment);
}
#[test]
#[serial]
fn should_make_nuvei_3ds_mandate_payment_test() {
tester!(should_make_nuvei_3ds_mandate_payment);
}
#[test]
#[serial]
fn should_make_nuvei_gpay_payment_test() {
tester!(should_make_nuvei_gpay_payment);
}
#[test]
#[serial]
fn should_make_nuvei_pypl_payment_test() {
tester!(should_make_nuvei_pypl_payment);
}
#[test]
#[serial]
fn should_make_nuvei_giropay_payment_test() {
tester!(should_make_nuvei_giropay_payment);
}
#[test]
#[serial]
fn should_make_nuvei_ideal_payment_test() {
tester!(should_make_nuvei_ideal_payment);
}
#[test]
#[serial]
fn should_make_nuvei_sofort_payment_test() {
tester!(should_make_nuvei_sofort_payment);
}
#[test]
#[serial]
fn should_make_nuvei_eps_payment_test() {
tester!(should_make_nuvei_eps_payment);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/test_utils/tests/connectors/bambora_ui.rs | crates/test_utils/tests/connectors/bambora_ui.rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct BamboraSeleniumTest;
impl SeleniumTest for BamboraSeleniumTest {
fn get_connector_name(&self) -> String {
"bambora".to_string()
}
}
async fn should_make_3ds_payment(c: WebDriver) -> Result<(), WebDriverError> {
let mycon = BamboraSeleniumTest {};
mycon
.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/33"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Id("continue-transaction"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
#[test]
#[serial]
fn should_make_3ds_payment_test() {
tester!(should_make_3ds_payment);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/test_utils/tests/connectors/bluesnap_ui.rs | crates/test_utils/tests/connectors/bluesnap_ui.rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct BluesnapSeleniumTest;
impl SeleniumTest for BluesnapSeleniumTest {
fn get_connector_name(&self) -> String {
"bluesnap".to_string()
}
}
async fn should_make_3ds_payment(driver: WebDriver) -> Result<(), WebDriverError> {
let conn = BluesnapSeleniumTest {};
conn.make_redirection_payment(
driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/200"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::RunIf(
Assert::IsElePresent(By::Id("Cardinal-CCA-IFrame")),
vec![
Event::Trigger(Trigger::SwitchFrame(By::Id("Cardinal-CCA-IFrame"))),
Event::Assert(Assert::IsPresent("Enter your code below")),
Event::Trigger(Trigger::SendKeys(By::Name("challengeDataEntry"), "1234")),
Event::Trigger(Trigger::Click(By::ClassName("button.primary"))),
],
),
Event::Trigger(Trigger::Sleep(10)),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_gpay_payment(driver: WebDriver) -> Result<(), WebDriverError> {
let conn = BluesnapSeleniumTest {};
let pub_key = conn
.get_configs()
.automation_configs
.unwrap()
.bluesnap_gateway_merchant_id
.unwrap();
conn.make_gpay_payment(driver,
&format!("{CHECKOUT_BASE_URL}/gpay?gatewayname=bluesnap&gatewaymerchantid={pub_key}&amount=11.00&country=US¤cy=USD"),
vec![
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
#[test]
#[serial]
fn should_make_3ds_payment_test() {
tester!(should_make_3ds_payment);
}
#[test]
#[serial]
fn should_make_gpay_payment_test() {
tester!(should_make_gpay_payment);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/test_utils/tests/connectors/paypal_ui.rs | crates/test_utils/tests/connectors/paypal_ui.rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct PaypalSeleniumTest;
impl SeleniumTest for PaypalSeleniumTest {
fn get_connector_name(&self) -> String {
"paypal".to_string()
}
}
async fn should_make_paypal_paypal_wallet_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = PaypalSeleniumTest {};
conn.make_paypal_payment(
web_driver,
&format!("{CHECKOUT_BASE_URL}/saved/21"),
vec![
Event::Trigger(Trigger::Click(By::Css("#payment-submit-btn"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=processing"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_paypal_ideal_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = PaypalSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/181"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Name("Successful"))),
Event::Assert(Assert::IsPresent("processing")),
],
)
.await?;
Ok(())
}
async fn should_make_paypal_giropay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = PaypalSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/233"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Name("Successful"))),
Event::Assert(Assert::IsPresent("processing")),
],
)
.await?;
Ok(())
}
async fn should_make_paypal_eps_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = PaypalSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/234"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Name("Successful"))),
Event::Assert(Assert::IsPresent("processing")),
],
)
.await?;
Ok(())
}
async fn should_make_paypal_sofort_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = PaypalSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/235"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Name("Successful"))),
Event::Assert(Assert::IsPresent("processing")),
],
)
.await?;
Ok(())
}
#[test]
#[serial]
fn should_make_paypal_paypal_wallet_payment_test() {
tester!(should_make_paypal_paypal_wallet_payment);
}
#[test]
#[serial]
fn should_make_paypal_ideal_payment_test() {
tester!(should_make_paypal_ideal_payment);
}
#[test]
#[serial]
fn should_make_paypal_giropay_payment_test() {
tester!(should_make_paypal_giropay_payment);
}
#[test]
#[serial]
fn should_make_paypal_eps_payment_test() {
tester!(should_make_paypal_eps_payment);
}
#[test]
#[serial]
fn should_make_paypal_sofort_payment_test() {
tester!(should_make_paypal_sofort_payment);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/test_utils/tests/connectors/mollie_ui.rs | crates/test_utils/tests/connectors/mollie_ui.rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct MollieSeleniumTest;
impl SeleniumTest for MollieSeleniumTest {
fn get_connector_name(&self) -> String {
"mollie".to_string()
}
}
async fn should_make_mollie_paypal_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = MollieSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/32"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Test profile")),
Event::Trigger(Trigger::Click(By::Css("input[value='paid']"))),
Event::Trigger(Trigger::Click(By::Css(
"button[class='button form__button']",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_mollie_sofort_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = MollieSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/29"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Test profile")),
Event::Trigger(Trigger::Click(By::Css("input[value='paid']"))),
Event::Trigger(Trigger::Click(By::Css(
"button[class='button form__button']",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_mollie_ideal_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn: MollieSeleniumTest = MollieSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/36"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Test profile")),
Event::Trigger(Trigger::Click(By::ClassName(
"payment-method-list--bordered",
))),
Event::Assert(Assert::IsPresent("Test profile")),
Event::Trigger(Trigger::Click(By::Css("input[value='paid']"))),
Event::Trigger(Trigger::Click(By::Css(
"button[class='button form__button']",
))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_mollie_eps_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = MollieSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/38"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Test profile")),
Event::Trigger(Trigger::Click(By::Css("input[value='paid']"))),
Event::Trigger(Trigger::Click(By::Css(
"button[class='button form__button']",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_mollie_giropay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = MollieSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/41"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Test profile")),
Event::Trigger(Trigger::Click(By::Css("input[value='paid']"))),
Event::Trigger(Trigger::Click(By::Css(
"button[class='button form__button']",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_mollie_bancontact_card_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = MollieSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/86"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Test profile")),
Event::Trigger(Trigger::Click(By::Css("input[value='paid']"))),
Event::Trigger(Trigger::Click(By::Css(
"button[class='button form__button']",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_mollie_przelewy24_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = MollieSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/87"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Test profile")),
Event::Trigger(Trigger::Click(By::Css("input[value='paid']"))),
Event::Trigger(Trigger::Click(By::Css(
"button[class='button form__button']",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_mollie_3ds_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = MollieSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/148"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Test profile")),
Event::Trigger(Trigger::Click(By::Css("input[value='paid']"))),
Event::Trigger(Trigger::Click(By::Css(
"button[class='button form__button']",
))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
#[test]
#[serial]
fn should_make_mollie_paypal_payment_test() {
tester!(should_make_mollie_paypal_payment);
}
#[test]
#[serial]
fn should_make_mollie_sofort_payment_test() {
tester!(should_make_mollie_sofort_payment);
}
#[test]
#[serial]
fn should_make_mollie_ideal_payment_test() {
tester!(should_make_mollie_ideal_payment);
}
#[test]
#[serial]
fn should_make_mollie_eps_payment_test() {
tester!(should_make_mollie_eps_payment);
}
#[test]
#[serial]
fn should_make_mollie_giropay_payment_test() {
tester!(should_make_mollie_giropay_payment);
}
#[test]
#[serial]
fn should_make_mollie_bancontact_card_payment_test() {
tester!(should_make_mollie_bancontact_card_payment);
}
#[test]
#[serial]
fn should_make_mollie_przelewy24_payment_test() {
tester!(should_make_mollie_przelewy24_payment);
}
#[test]
#[serial]
fn should_make_mollie_3ds_payment_test() {
tester!(should_make_mollie_3ds_payment);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/test_utils/tests/connectors/aci_ui.rs | crates/test_utils/tests/connectors/aci_ui.rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct AciSeleniumTest;
impl SeleniumTest for AciSeleniumTest {
fn get_connector_name(&self) -> String {
"aci".to_string()
}
}
async fn should_make_aci_card_mandate_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/180"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")), // mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("a.btn"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_aci_alipay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/213"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Id("submit-success"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_aci_interac_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/14"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("input[value='Continue payment']"))),
Event::Trigger(Trigger::Click(By::Css("input[value='Confirm']"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_aci_eps_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/208"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("input.button-body.button-short"))),
Event::Trigger(Trigger::Click(By::Css("input.button-body.button-short"))),
Event::Trigger(Trigger::Click(By::Css("input.button-body.button-short"))),
Event::Trigger(Trigger::Click(By::Css("input.button-body.button-middle"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_aci_ideal_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/211"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("input.pps-button"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_aci_sofort_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/212"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"button.large.button.primary.expand.form-submitter",
))),
Event::Trigger(Trigger::Click(By::Css(
"button.large.button.primary.expand.form-submitter",
))),
Event::Trigger(Trigger::Click(By::Css(
"button.large.button.primary.expand.form-submitter",
))),
Event::Trigger(Trigger::Click(By::Css(
"button.large.button.primary.expand.form-submitter",
))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_aci_giropay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/209"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SendKeys(By::Name("sc"), "10")),
Event::Trigger(Trigger::SendKeys(By::Name("extensionSc"), "4000")),
Event::Trigger(Trigger::SendKeys(By::Name("customerName1"), "Hopper")),
Event::Trigger(Trigger::Click(By::Css("input[value='Absenden']"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_aci_trustly_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/13"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Sleep(2)),
Event::Trigger(Trigger::Click(By::XPath(
r#"//*[@id="app"]/div[1]/div/div[2]/div/ul/div[4]/div/div[1]/div[2]/div[1]/span"#,
))),
Event::Trigger(Trigger::Click(By::Css(
"button.sc-eJocfa.sc-oeezt.cDgdS.bptgBT",
))),
Event::Trigger(Trigger::SendKeys(
By::Css("input.sc-fXgAZx.hkChHq"),
"123456789",
)),
Event::Trigger(Trigger::Click(By::Css(
"button.sc-eJocfa.sc-oeezt.cDgdS.bptgBT",
))),
Event::Trigger(Trigger::SendKeys(
By::Css("input.sc-fXgAZx.hkChHq"),
"783213",
)),
Event::Trigger(Trigger::Click(By::Css(
"button.sc-eJocfa.sc-oeezt.cDgdS.bptgBT",
))),
Event::Trigger(Trigger::Click(By::Css("div.sc-jJMGnK.laKGqb"))),
Event::Trigger(Trigger::Click(By::Css(
"button.sc-eJocfa.sc-oeezt.cDgdS.bptgBT",
))),
Event::Trigger(Trigger::SendKeys(
By::Css("input.sc-fXgAZx.hkChHq"),
"355508",
)),
Event::Trigger(Trigger::Click(By::Css(
"button.sc-eJocfa.sc-oeezt.cDgdS.bptgBT",
))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_aci_przelewy24_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/12"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Id("pf31"))),
Event::Trigger(Trigger::Click(By::Css(
"button.btn.btn-lg.btn-info.btn-block",
))),
Event::Trigger(Trigger::Click(By::Css(
"button.btn.btn-success.btn-lg.accept-button",
))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
#[test]
#[serial]
fn should_make_aci_card_mandate_payment_test() {
tester!(should_make_aci_card_mandate_payment);
}
#[test]
#[serial]
fn should_make_aci_alipay_payment_test() {
tester!(should_make_aci_alipay_payment);
}
#[test]
#[serial]
fn should_make_aci_interac_payment_test() {
tester!(should_make_aci_interac_payment);
}
#[test]
#[serial]
fn should_make_aci_eps_payment_test() {
tester!(should_make_aci_eps_payment);
}
#[test]
#[serial]
fn should_make_aci_ideal_payment_test() {
tester!(should_make_aci_ideal_payment);
}
#[test]
#[serial]
fn should_make_aci_sofort_payment_test() {
tester!(should_make_aci_sofort_payment);
}
#[test]
#[serial]
fn should_make_aci_giropay_payment_test() {
tester!(should_make_aci_giropay_payment);
}
#[test]
#[serial]
fn should_make_aci_trustly_payment_test() {
tester!(should_make_aci_trustly_payment);
}
#[test]
#[serial]
fn should_make_aci_przelewy24_payment_test() {
tester!(should_make_aci_przelewy24_payment);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/test_utils/tests/connectors/globalpay_ui.rs | crates/test_utils/tests/connectors/globalpay_ui.rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct GlobalpaySeleniumTest;
impl SeleniumTest for GlobalpaySeleniumTest {
fn get_connector_name(&self) -> String {
"globalpay".to_string()
}
}
async fn should_make_gpay_payment(driver: WebDriver) -> Result<(), WebDriverError> {
let conn = GlobalpaySeleniumTest {};
let pub_key = conn
.get_configs()
.automation_configs
.unwrap()
.globalpay_gateway_merchant_id
.unwrap();
conn.make_gpay_payment(driver,
&format!("{CHECKOUT_BASE_URL}/gpay?amount=10.00&country=US¤cy=USD&gatewayname=globalpayments&gatewaymerchantid={pub_key}"),
vec![
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
async fn should_make_globalpay_paypal_payment(driver: WebDriver) -> Result<(), WebDriverError> {
let conn = GlobalpaySeleniumTest {};
conn.make_paypal_payment(
driver,
&format!("{CHECKOUT_BASE_URL}/saved/46"),
vec![
Event::Trigger(Trigger::Click(By::Id("payment-submit-btn"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_globalpay_ideal_payment(driver: WebDriver) -> Result<(), WebDriverError> {
let conn = GlobalpaySeleniumTest {};
conn.make_redirection_payment(
driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/53"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Choose your Bank")),
Event::Trigger(Trigger::Click(By::Css("button.btn.btn-primary"))),
Event::Assert(Assert::IsPresent("Login to your Online Banking Account")),
Event::Trigger(Trigger::Click(By::Css("button.btn.btn-primary"))),
Event::Assert(Assert::IsPresent("Transaction Authentication")),
Event::Trigger(Trigger::Click(By::Css("button.btn.btn-primary"))),
Event::Assert(Assert::IsPresent("Payment Successful")),
Event::Trigger(Trigger::Click(By::Css("button.btn.btn-primary"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded", "status=processing"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_globalpay_giropay_payment(driver: WebDriver) -> Result<(), WebDriverError> {
let conn = GlobalpaySeleniumTest {};
conn.make_redirection_payment(
driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/59"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Choose your Bank")),
Event::Trigger(Trigger::Click(By::Css("button.btn.btn-primary"))),
Event::Assert(Assert::IsPresent("Login to your Online Banking Account")),
Event::Trigger(Trigger::Click(By::Css("button.btn.btn-primary"))),
Event::Assert(Assert::IsPresent("Transaction Authentication")),
Event::Trigger(Trigger::Click(By::Css("button.btn.btn-primary"))),
Event::Assert(Assert::IsPresent("Payment Successful")),
Event::Trigger(Trigger::Click(By::Css("button.btn.btn-primary"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded", "status=processing"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_globalpay_eps_payment(driver: WebDriver) -> Result<(), WebDriverError> {
let conn = GlobalpaySeleniumTest {};
conn.make_redirection_payment(
driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/50"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Choose your Bank")),
Event::Trigger(Trigger::Click(By::Css("button.btn.btn-primary"))),
Event::Assert(Assert::IsPresent("Login to your Online Banking Account")),
Event::Trigger(Trigger::Click(By::Css("button.btn.btn-primary"))),
Event::Assert(Assert::IsPresent("Transaction Authentication")),
Event::Trigger(Trigger::Click(By::Css("button.btn.btn-primary"))),
Event::Assert(Assert::IsPresent("Payment Successful")),
Event::Trigger(Trigger::Click(By::Css("button.btn.btn-primary"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded", "status=processing"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_globalpay_sofort_payment(driver: WebDriver) -> Result<(), WebDriverError> {
let conn = GlobalpaySeleniumTest {};
conn.make_redirection_payment(
driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/63"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::RunIf(
Assert::IsPresent("Wählen"),
vec![Event::Trigger(Trigger::Click(By::Css("p.description")))],
),
Event::Assert(Assert::IsPresent("Demo Bank")),
Event::Trigger(Trigger::SendKeys(
By::Id("BackendFormLOGINNAMEUSERID"),
"12345",
)),
Event::Trigger(Trigger::SendKeys(By::Id("BackendFormUSERPIN"), "1234")),
Event::Trigger(Trigger::Click(By::Css(
"button.button-right.primary.has-indicator",
))),
Event::RunIf(
Assert::IsPresent("Kontoauswahl"),
vec![Event::Trigger(Trigger::Click(By::Css(
"button.button-right.primary.has-indicator",
)))],
),
Event::Assert(Assert::IsPresent("PPRO Payment Services Ltd.")),
Event::Trigger(Trigger::SendKeys(By::Id("BackendFormTan"), "12345")),
Event::Trigger(Trigger::Click(By::Css(
"button.button-right.primary.has-indicator",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded", "status=processing"],
)),
],
)
.await?;
Ok(())
}
#[test]
#[serial]
fn should_make_gpay_payment_test() {
tester!(should_make_gpay_payment);
}
#[test]
#[serial]
fn should_make_globalpay_paypal_payment_test() {
tester!(should_make_globalpay_paypal_payment);
}
#[test]
#[serial]
fn should_make_globalpay_ideal_payment_test() {
tester!(should_make_globalpay_ideal_payment);
}
#[test]
#[serial]
fn should_make_globalpay_giropay_payment_test() {
tester!(should_make_globalpay_giropay_payment);
}
#[test]
#[serial]
fn should_make_globalpay_eps_payment_test() {
tester!(should_make_globalpay_eps_payment);
}
#[test]
#[serial]
fn should_make_globalpay_sofort_payment_test() {
tester!(should_make_globalpay_sofort_payment);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/test_utils/tests/connectors/authorizedotnet_ui.rs | crates/test_utils/tests/connectors/authorizedotnet_ui.rs | use rand::Rng;
use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct AuthorizedotnetSeleniumTest;
impl SeleniumTest for AuthorizedotnetSeleniumTest {
fn get_connector_name(&self) -> String {
"authorizedotnet".to_string()
}
}
async fn should_make_gpay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AuthorizedotnetSeleniumTest {};
let amount = rand::thread_rng().gen_range(1..1000); //This connector detects it as fraudulent payment if the same amount is used for multiple payments so random amount is passed for testing
let pub_key = conn
.get_configs()
.automation_configs
.unwrap()
.authorizedotnet_gateway_merchant_id
.unwrap();
conn.make_gpay_payment(web_driver,
&format!("{CHECKOUT_BASE_URL}/gpay?gatewayname=authorizenet&gatewaymerchantid={pub_key}&amount={amount}&country=US¤cy=USD"),
vec![
Event::Assert(Assert::IsPresent("status")),
Event::Assert(Assert::IsPresent("processing")), // This connector status will be processing for one day
]).await?;
Ok(())
}
async fn should_make_paypal_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AuthorizedotnetSeleniumTest {};
conn.make_paypal_payment(
web_driver,
&format!("{CHECKOUT_BASE_URL}/saved/156"),
vec![
Event::EitherOr(
Assert::IsElePresent(By::Css(".reviewButton")),
vec![Event::Trigger(Trigger::Click(By::Css(".reviewButton")))],
vec![Event::Trigger(Trigger::Click(By::Id("payment-submit-btn")))],
),
Event::Assert(Assert::IsPresent("status")),
Event::Assert(Assert::IsPresent("processing")), // This connector status will be processing for one day
],
)
.await?;
Ok(())
}
#[test]
#[serial]
#[ignore]
fn should_make_gpay_payment_test() {
tester!(should_make_gpay_payment);
}
#[test]
#[serial]
fn should_make_paypal_payment_test() {
tester!(should_make_paypal_payment);
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/openapi/src/openapi_v2.rs | crates/openapi/src/openapi_v2.rs | use crate::routes;
#[derive(utoipa::OpenApi)]
#[openapi(
info(
title = "Hyperswitch - API Documentation",
contact(
name = "Hyperswitch Support",
url = "https://hyperswitch.io",
email = "hyperswitch@juspay.in"
),
// terms_of_service = "https://www.juspay.io/terms",
description = r#"
## Get started
Hyperswitch provides a collection of APIs that enable you to process and manage payments.
Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes.
You can consume the APIs directly using your favorite HTTP/REST library.
We have a testing environment referred to "sandbox", which you can setup to test API calls without
affecting production data.
Currently, our sandbox environment is live while our production environment is under development
and will be available soon.
You can sign up on our Dashboard to get API keys to access Hyperswitch API.
### Environment
Use the following base URLs when making requests to the APIs:
| Environment | Base URL |
|---------------|------------------------------------|
| Sandbox | <https://sandbox.hyperswitch.io> |
| Production | <https://api.hyperswitch.io> |
## Authentication
When you sign up on our [dashboard](https://app.hyperswitch.io) and create a merchant
account, you are given a secret key (also referred as api-key) and a publishable key.
You may authenticate all API requests with Hyperswitch server by providing the appropriate key in
the request Authorization header.
| Key | Description |
|-----------------|-----------------------------------------------------------------------------------------------|
| api-key | Private key. Used to authenticate all API requests from your merchant server |
| publishable key | Unique identifier for your account. Used to authenticate API requests from your app's client |
Never share your secret api keys. Keep them guarded and secure.
"#,
),
servers(
(url = "https://sandbox.hyperswitch.io", description = "Sandbox Environment")
),
tags(
(name = "Merchant Account", description = "Create and manage merchant accounts"),
(name = "Profile", description = "Create and manage profiles"),
(name = "Merchant Connector Account", description = "Create and manage merchant connector accounts"),
(name = "Payments", description = "Create and manage one-time payments, recurring payments and mandates"),
(name = "Refunds", description = "Create and manage refunds for successful payments"),
(name = "Mandates", description = "Manage mandates"),
(name = "Customers", description = "Create and manage customers"),
(name = "Payment Methods", description = "Create and manage payment methods of customers"),
(name = "Disputes", description = "Manage disputes"),
(name = "API Key", description = "Create and manage API Keys"),
(name = "Payouts", description = "Create and manage payouts"),
(name = "payment link", description = "Create payment link"),
(name = "Routing", description = "Create and manage routing configurations"),
(name = "Event", description = "Manage events"),
),
// The paths will be displayed in the same order as they are registered here
paths(
// Routes for Organization
routes::organization::organization_create,
routes::organization::organization_retrieve,
routes::organization::organization_update,
routes::organization::merchant_account_list,
// Routes for merchant connector account
routes::merchant_connector_account::connector_create,
routes::merchant_connector_account::connector_retrieve,
routes::merchant_connector_account::connector_update,
routes::merchant_connector_account::connector_delete,
// Routes for merchant account
routes::merchant_account::merchant_account_create,
routes::merchant_account::merchant_account_retrieve,
routes::merchant_account::merchant_account_update,
routes::merchant_account::profiles_list,
// Routes for profile
routes::profile::profile_create,
routes::profile::profile_retrieve,
routes::profile::profile_update,
routes::profile::connector_list,
// Routes for routing under profile
routes::profile::routing_link_config,
routes::profile::routing_unlink_config,
routes::profile::routing_update_default_config,
routes::profile::routing_retrieve_default_config,
routes::profile::routing_retrieve_linked_config,
// Routes for routing
routes::routing::routing_create_config,
routes::routing::routing_retrieve_config,
// Routes for api keys
routes::api_keys::api_key_create,
routes::api_keys::api_key_retrieve,
routes::api_keys::api_key_update,
routes::api_keys::api_key_revoke,
routes::api_keys::api_key_list,
//Routes for customers
routes::customers::customers_create,
routes::customers::customers_retrieve,
routes::customers::customers_update,
routes::customers::customers_delete,
routes::customers::customers_list,
//Routes for payments
routes::payments::payments_create_intent,
routes::payments::payments_get_intent,
routes::payments::payments_update_intent,
routes::payments::payments_confirm_intent,
routes::payments::payment_status,
routes::payments::payments_create_and_confirm_intent,
routes::payments::payments_connector_session,
routes::payments::list_payment_methods,
routes::payments::payments_list,
routes::payments::payments_apply_pm_data,
//Routes for payment methods
routes::payment_method::create_payment_method_api,
routes::payment_method::create_payment_method_intent_api,
routes::payment_method::confirm_payment_method_intent_api,
routes::payment_method::payment_method_update_api,
routes::payment_method::payment_method_retrieve_api,
routes::payment_method::payment_method_delete_api,
routes::payment_method::network_token_status_check_api,
routes::payment_method::list_customer_payment_method_api,
//Routes for payment method session
routes::payment_method::payment_method_session_create,
routes::payment_method::payment_method_session_retrieve,
routes::payment_method::payment_method_session_list_payment_methods,
routes::payment_method::payment_method_session_update_saved_payment_method,
routes::payment_method::payment_method_session_delete_saved_payment_method,
routes::payment_method::payment_method_session_confirm,
//Routes for refunds
routes::refunds::refunds_create,
routes::refunds::refunds_metadata_update,
routes::refunds::refunds_retrieve,
routes::refunds::refunds_list,
// Routes for Revenue Recovery flow under Process Tracker
routes::revenue_recovery::revenue_recovery_pt_retrieve_api,
// Routes for proxy
routes::proxy::proxy_core,
// Route for tokenization
routes::tokenization::create_token_vault_api,
routes::tokenization::delete_tokenized_data_api,
),
components(schemas(
common_utils::types::MinorUnit,
common_utils::types::StringMinorUnit,
common_utils::types::TimeRange,
common_utils::types::BrowserInformation,
common_utils::link_utils::GenericLinkUiConfig,
common_utils::link_utils::EnabledPaymentMethod,
common_utils::payout_method_utils::AdditionalPayoutMethodData,
common_utils::payout_method_utils::CardAdditionalData,
common_utils::payout_method_utils::BankAdditionalData,
common_utils::payout_method_utils::WalletAdditionalData,
common_utils::payout_method_utils::BankRedirectAdditionalData,
common_utils::payout_method_utils::AchBankTransferAdditionalData,
common_utils::payout_method_utils::BacsBankTransferAdditionalData,
common_utils::payout_method_utils::SepaBankTransferAdditionalData,
common_utils::payout_method_utils::PixBankTransferAdditionalData,
common_utils::payout_method_utils::PaypalAdditionalData,
common_utils::payout_method_utils::InteracAdditionalData,
common_utils::payout_method_utils::VenmoAdditionalData,
common_utils::payout_method_utils::ApplePayDecryptAdditionalData,
common_utils::payout_method_utils::PassthroughAddtionalData,
common_types::payments::SplitPaymentsRequest,
common_types::payments::GpayTokenizationData,
common_types::payments::GPayPredecryptData,
common_types::payments::GpayEcryptedTokenizationData,
common_types::payments::ApplePayPaymentData,
common_types::payments::ApplePayPredecryptData,
common_types::payments::ApplePayCryptogramData,
common_types::payments::ApplePayPaymentData,
common_types::payments::StripeSplitPaymentRequest,
common_types::domain::AdyenSplitData,
common_types::payments::AcceptanceType,
common_types::payments::CustomerAcceptance,
common_types::payments::OnlineMandate,
common_types::payments::XenditSplitRequest,
common_types::payments::XenditSplitRoute,
common_types::payments::XenditChargeResponseData,
common_types::payments::XenditMultipleSplitResponse,
common_types::payments::XenditMultipleSplitRequest,
common_types::domain::XenditSplitSubMerchantData,
common_types::domain::AdyenSplitItem,
common_types::domain::MerchantConnectorAuthDetails,
common_types::refunds::StripeSplitRefundRequest,
common_utils::types::ChargeRefunds,
common_types::payment_methods::PaymentMethodsEnabled,
common_types::payment_methods::PspTokenization,
common_types::payment_methods::NetworkTokenization,
common_types::refunds::SplitRefund,
common_types::payments::ConnectorChargeResponseData,
common_types::payments::StripeChargeResponseData,
common_types::three_ds_decision_rule_engine::ThreeDSDecisionRule,
common_types::three_ds_decision_rule_engine::ThreeDSDecision,
api_models::payments::CartesBancairesParams,
api_models::payments::NetworkParams,
api_models::payments::Cryptogram,
api_models::payments::ExternalThreeDsData,
common_types::payments::MerchantCountryCode,
common_utils::request::Method,
api_models::errors::types::GenericErrorResponseOpenApi,
api_models::refunds::RefundsCreateRequest,
api_models::refunds::RefundErrorDetails,
api_models::refunds::RefundType,
api_models::refunds::RefundResponse,
api_models::refunds::RefundStatus,
api_models::refunds::RefundMetadataUpdateRequest,
api_models::organization::OrganizationCreateRequest,
api_models::organization::OrganizationUpdateRequest,
api_models::organization::OrganizationResponse,
api_models::admin::MerchantAccountCreateWithoutOrgId,
api_models::admin::MerchantAccountUpdate,
api_models::admin::MerchantAccountDeleteResponse,
api_models::admin::MerchantConnectorDeleteResponse,
api_models::admin::MerchantConnectorResponse,
api_models::admin::MerchantConnectorListResponse,
api_models::admin::AuthenticationConnectorDetails,
api_models::admin::ExternalVaultConnectorDetails,
api_models::admin::VaultTokenField,
api_models::admin::ExtendedCardInfoConfig,
api_models::admin::BusinessGenericLinkConfig,
api_models::admin::BusinessCollectLinkConfig,
api_models::admin::BusinessPayoutLinkConfig,
api_models::admin::MerchantConnectorAccountFeatureMetadata,
api_models::admin::RevenueRecoveryMetadata,
api_models::customers::CustomerRequest,
api_models::customers::CustomerUpdateRequest,
api_models::customers::CustomerDeleteResponse,
api_models::ephemeral_key::ResourceId,
api_models::payment_methods::PaymentMethodCreate,
api_models::payment_methods::PaymentMethodIntentCreate,
api_models::payment_methods::PaymentMethodIntentConfirm,
api_models::payment_methods::AuthenticationDetails,
api_models::payment_methods::PaymentMethodResponse,
api_models::payment_methods::PaymentMethodResponseData,
api_models::payment_methods::CustomerPaymentMethodResponseItem,
api_models::payment_methods::PaymentMethodResponseItem,
api_models::payment_methods::ListMethodsForPaymentMethodsRequest,
api_models::payment_methods::PaymentMethodListResponseForSession,
api_models::payment_methods::CustomerPaymentMethodsListResponse,
api_models::payment_methods::ResponsePaymentMethodsEnabled,
api_models::payment_methods::PaymentMethodSubtypeSpecificData,
api_models::payment_methods::ResponsePaymentMethodTypes,
api_models::payment_methods::PaymentExperienceTypes,
api_models::payment_methods::CardNetworkTypes,
api_models::payment_methods::BankDebitTypes,
api_models::payment_methods::BankTransferTypes,
api_models::payment_methods::PaymentMethodDeleteResponse,
api_models::payment_methods::PaymentMethodUpdate,
api_models::payment_methods::PaymentMethodUpdateData,
api_models::payment_methods::CardDetailFromLocker,
api_models::payment_methods::PaymentMethodCreateData,
api_models::payment_methods::ProxyCardDetails,
api_models::payment_methods::CardDetail,
api_models::payment_methods::CardDetailUpdate,
api_models::payment_methods::CardType,
api_models::payment_methods::RequestPaymentMethodTypes,
api_models::payment_methods::CardType,
api_models::payment_methods::PaymentMethodListData,
api_models::payment_methods::NetworkTokenStatusCheckResponse,
api_models::payment_methods::NetworkTokenStatusCheckSuccessResponse,
api_models::payment_methods::NetworkTokenStatusCheckFailureResponse,
api_models::enums::TokenStatus,
api_models::poll::PollResponse,
api_models::poll::PollStatus,
api_models::customers::CustomerResponse,
api_models::admin::AcceptedCountries,
api_models::admin::AcceptedCurrencies,
api_models::enums::AdyenSplitType,
api_models::enums::ProductType,
api_models::enums::PaymentType,
api_models::enums::ScaExemptionType,
api_models::enums::PaymentMethod,
api_models::enums::PaymentMethodType,
api_models::enums::ConnectorType,
api_models::enums::PayoutConnectors,
api_models::enums::AuthenticationConnectors,
api_models::enums::VaultSdk,
api_models::enums::Currency,
api_models::enums::CavvAlgorithm,
api_models::enums::ExemptionIndicator,
api_models::enums::DocumentKind,
api_models::enums::IntentStatus,
api_models::enums::CaptureMethod,
api_models::enums::FutureUsage,
api_models::enums::AuthenticationType,
api_models::enums::Connector,
api_models::enums::PaymentMethod,
api_models::enums::PaymentMethodIssuerCode,
api_models::enums::MandateStatus,
api_models::enums::MerchantProductType,
api_models::enums::PaymentExperience,
api_models::enums::BankNames,
api_models::enums::BankType,
api_models::enums::BankHolderType,
api_models::enums::CardNetwork,
api_models::enums::MerchantCategoryCode,
api_models::enums::TokenDataType,
api_models::enums::DisputeStage,
api_models::enums::DisputeStatus,
api_models::enums::CountryAlpha2,
api_models::enums::CountryAlpha3,
api_models::enums::FieldType,
api_models::enums::FrmAction,
api_models::enums::FrmPreferredFlowTypes,
api_models::enums::RetryAction,
api_models::enums::AttemptStatus,
api_models::enums::CaptureStatus,
api_models::enums::ReconStatus,
api_models::enums::ConnectorStatus,
api_models::enums::AuthorizationStatus,
api_models::enums::ElementPosition,
api_models::enums::ElementSize,
api_models::enums::TaxStatus,
api_models::enums::SizeVariants,
api_models::enums::MerchantProductType,
api_models::enums::PaymentLinkDetailsLayout,
api_models::enums::PaymentMethodStatus,
api_models::enums::HyperswitchConnectorCategory,
api_models::enums::ConnectorIntegrationStatus,
api_models::enums::FeatureStatus,
api_models::enums::OrderFulfillmentTimeOrigin,
api_models::enums::UIWidgetFormLayout,
api_models::enums::MerchantProductType,
api_models::enums::CtpServiceProvider,
api_models::enums::PaymentLinkSdkLabelType,
api_models::enums::PaymentLinkShowSdkTerms,
api_models::enums::OrganizationType,
api_models::enums::GooglePayCardFundingSource,
api_models::enums::VaultTokenType,
api_models::enums::StorageType,
api_models::admin::MerchantConnectorCreate,
api_models::admin::AdditionalMerchantData,
api_models::admin::CardTestingGuardConfig,
api_models::admin::CardTestingGuardStatus,
api_models::admin::ConnectorWalletDetails,
api_models::admin::MerchantRecipientData,
api_models::admin::MerchantAccountData,
api_models::admin::MerchantConnectorUpdate,
api_models::admin::PrimaryBusinessDetails,
api_models::admin::FrmConfigs,
api_models::admin::FrmPaymentMethod,
api_models::admin::FrmPaymentMethodType,
api_models::admin::MerchantConnectorDetailsWrap,
api_models::admin::MerchantConnectorDetails,
api_models::admin::MerchantConnectorWebhookDetails,
api_models::admin::ProfileCreate,
api_models::admin::ProfileResponse,
api_models::admin::BusinessPaymentLinkConfig,
api_models::admin::PaymentLinkBackgroundImageConfig,
api_models::admin::PaymentLinkConfigRequest,
api_models::admin::PaymentLinkConfig,
api_models::admin::PaymentLinkTransactionDetails,
api_models::admin::TransactionDetailsUiConfiguration,
api_models::disputes::DisputeResponse,
api_models::disputes::DisputeResponsePaymentsRetrieve,
api_models::gsm::GsmCreateRequest,
api_models::gsm::GsmRetrieveRequest,
api_models::gsm::GsmUpdateRequest,
api_models::gsm::GsmDeleteRequest,
api_models::gsm::GsmDeleteResponse,
api_models::gsm::GsmResponse,
api_models::enums::GsmDecision,
api_models::enums::GsmFeature,
api_models::enums::StandardisedCode,
common_types::domain::GsmFeatureData,
common_types::domain::RetryFeatureData,
api_models::payments::NullObject,
api_models::payments::AddressDetails,
api_models::payments::EligibilityBalanceCheckResponseItem,
api_models::payments::PMBalanceCheckEligibilityResponse,
api_models::payments::PMBalanceCheckSuccessResponse,
api_models::payments::PMBalanceCheckFailureResponse,
api_models::payments::BankDebitData,
api_models::payments::AliPayQr,
api_models::payments::PaymentAttemptFeatureMetadata,
api_models::payments::PaymentAttemptRevenueRecoveryData,
api_models::payments::BillingConnectorPaymentMethodDetails,
api_models::payments::RecordAttemptErrorDetails,
api_models::payments::BillingConnectorAdditionalCardInfo,
api_models::payments::AliPayRedirection,
api_models::payments::MomoRedirection,
api_models::payments::TouchNGoRedirection,
api_models::payments::GcashRedirection,
api_models::payments::KakaoPayRedirection,
api_models::payments::AliPayHkRedirection,
api_models::payments::GoPayRedirection,
api_models::payments::MbWayRedirection,
api_models::payments::MobilePayRedirection,
api_models::payments::WeChatPayRedirection,
api_models::payments::WeChatPayQr,
api_models::payments::BankDebitBilling,
api_models::payments::CryptoData,
api_models::payments::RewardData,
api_models::payments::UpiData,
api_models::payments::UpiCollectData,
api_models::payments::UpiIntentData,
api_models::payments::UpiQrData,
api_models::payments::VoucherData,
api_models::payments::BoletoVoucherData,
api_models::payments::AlfamartVoucherData,
api_models::payments::IndomaretVoucherData,
api_models::payments::Address,
api_models::payments::VoucherData,
api_models::payments::JCSVoucherData,
api_models::payments::AlfamartVoucherData,
api_models::payments::IndomaretVoucherData,
api_models::payments::BankRedirectData,
api_models::payments::RealTimePaymentData,
api_models::payments::BankRedirectBilling,
api_models::payments::BankRedirectBilling,
api_models::payments::ConnectorMetadata,
api_models::payments::FeatureMetadata,
api_models::payments::SdkType,
api_models::payments::ApplepayConnectorMetadataRequest,
api_models::payments::SessionTokenInfo,
api_models::payments::PaymentProcessingDetailsAt,
api_models::payments::ApplepayInitiative,
api_models::payments::PaymentProcessingDetails,
api_models::payments::PaymentMethodDataResponseWithBilling,
api_models::payments::PaymentMethodDataResponse,
api_models::payments::CardResponse,
api_models::payments::PaylaterResponse,
api_models::payments::KlarnaSdkPaymentMethodResponse,
api_models::payments::SwishQrData,
api_models::payments::RevolutPayData,
api_models::payments::AirwallexData,
api_models::payments::BraintreeData,
api_models::payments::NoonData,
api_models::payments::OrderDetailsWithAmount,
api_models::payments::NextActionType,
api_models::payments::WalletData,
api_models::payments::NextActionData,
api_models::payments::PayLaterData,
api_models::payments::MandateData,
api_models::payments::PhoneDetails,
api_models::payments::PaymentMethodData,
api_models::payments::PaymentMethodDataRequest,
api_models::payments::SplitPaymentMethodDataRequest,
api_models::payments::MandateType,
api_models::payments::MandateAmountData,
api_models::payments::Card,
api_models::payments::CardRedirectData,
api_models::payments::CardToken,
api_models::payments::ConnectorTokenDetails,
api_models::payments::PaymentsRequest,
api_models::payments::PaymentsResponse,
api_models::payments::PaymentsListResponseItem,
api_models::payments::PaymentsRetrieveRequest,
api_models::payments::PaymentsStatusRequest,
api_models::payments::PaymentsCaptureRequest,
api_models::payments::PaymentsSessionRequest,
api_models::payments::PaymentsSessionResponse,
api_models::payments::PaymentsCreateIntentRequest,
api_models::payments::PaymentsUpdateIntentRequest,
api_models::payments::PaymentsIntentResponse,
api_models::payments::PaymentAttemptListRequest,
api_models::payments::PaymentAttemptListResponse,
api_models::payments::PazeWalletData,
api_models::payments::AmountDetails,
api_models::payments::AmountDetailsUpdate,
api_models::payments::SessionToken,
api_models::payments::VaultSessionDetails,
api_models::payments::VgsSessionDetails,
api_models::payments::HyperswitchVaultSessionDetails,
api_models::payments::ApplePaySessionResponse,
api_models::payments::ThirdPartySdkSessionResponse,
api_models::payments::NoThirdPartySdkSessionResponse,
api_models::payments::SecretInfoToInitiateSdk,
api_models::payments::ApplePayPaymentRequest,
api_models::payments::ApplePayBillingContactFields,
api_models::payments::ApplePayShippingContactFields,
api_models::payments::ApplePayAddressParameters,
api_models::payments::ApplePayRecurringPaymentRequest,
api_models::payments::ApplePayRegularBillingRequest,
api_models::payments::ApplePayPaymentTiming,
api_models::payments::RecurringPaymentIntervalUnit,
api_models::payments::ApplePayRecurringDetails,
api_models::payments::ApplePayRegularBillingDetails,
api_models::payments::AmountInfo,
api_models::payments::GooglePayWalletData,
api_models::payments::PayPalWalletData,
api_models::payments::PaypalRedirection,
api_models::payments::GpayMerchantInfo,
api_models::payments::GpayAllowedPaymentMethods,
api_models::payments::GpayAllowedMethodsParameters,
api_models::payments::GpayTokenizationSpecification,
api_models::payments::GpayTokenParameters,
api_models::payments::GpayTransactionInfo,
api_models::payments::GpaySessionTokenResponse,
api_models::payments::GooglePayThirdPartySdkData,
api_models::payments::KlarnaSessionTokenResponse,
api_models::payments::PaypalSessionTokenResponse,
api_models::payments::PaypalFlow,
api_models::payments::PaypalTransactionInfo,
api_models::payments::ApplepaySessionTokenResponse,
api_models::payments::SdkNextAction,
api_models::payments::NextActionCall,
api_models::payments::SdkNextActionData,
api_models::payments::SamsungPayWalletData,
api_models::payments::WeChatPay,
api_models::payments::GooglePayPaymentMethodInfo,
api_models::payments::ApplePayWalletData,
api_models::payments::ApplepayPaymentMethod,
api_models::payments::PazeSessionTokenResponse,
api_models::payments::SamsungPaySessionTokenResponse,
api_models::payments::SamsungPayMerchantPaymentInformation,
api_models::payments::SamsungPayAmountDetails,
api_models::payments::SamsungPayAmountFormat,
api_models::payments::SamsungPayProtocolType,
api_models::payments::SamsungPayWalletCredentials,
api_models::payments::SamsungPayWebWalletData,
api_models::payments::SamsungPayAppWalletData,
api_models::payments::SamsungPayCardBrand,
api_models::payments::SamsungPayTokenData,
api_models::payments::PaymentsCancelRequest,
api_models::payments::PaymentListResponse,
api_models::payments::CashappQr,
api_models::payments::BankTransferData,
api_models::payments::BankTransferNextStepsData,
api_models::payments::SepaAndBacsBillingDetails,
api_models::payments::AchBillingDetails,
api_models::payments::MultibancoBillingDetails,
api_models::payments::DokuBillingDetails,
api_models::payments::BankTransferInstructions,
api_models::payments::MobilePaymentNextStepData,
api_models::payments::MobilePaymentConsent,
api_models::payments::IframeData,
api_models::payments::ReceiverDetails,
api_models::payments::AchTransfer,
api_models::payments::MultibancoTransferInstructions,
api_models::payments::DokuBankTransferInstructions,
api_models::payments::AmazonPayRedirectData,
api_models::payments::SkrillData,
api_models::payments::PayseraData,
api_models::payments::ApplePayRedirectData,
api_models::payments::ApplePayThirdPartySdkData,
api_models::payments::GooglePayRedirectData,
api_models::payments::GooglePayThirdPartySdk,
api_models::mandates::NetworkTransactionIdAndCardDetails,
api_models::mandates::NetworkTransactionIdAndNetworkTokenDetails,
api_models::payments::GooglePaySessionResponse,
api_models::payments::GpayShippingAddressParameters,
api_models::payments::GpayBillingAddressParameters,
api_models::payments::GpayBillingAddressFormat,
api_models::payments::SepaBankTransferInstructions,
api_models::payments::BacsBankTransferInstructions,
api_models::payments::RedirectResponse,
api_models::payments::RequestSurchargeDetails,
api_models::payments::PaymentRevenueRecoveryMetadata,
api_models::payments::BillingConnectorPaymentDetails,
api_models::payments::ApplyPaymentMethodDataRequest,
api_models::payments::CheckAndApplyPaymentMethodDataResponse,
api_models::payments::ApplyPaymentMethodDataSurchargeResponseItem,
api_models::enums::PaymentConnectorTransmission,
api_models::enums::TriggeredBy,
api_models::payments::PaymentAttemptResponse,
api_models::payments::PaymentAttemptRecordResponse,
api_models::payments::PaymentAttemptAmountDetails,
api_models::payments::CaptureResponse,
api_models::payments::PaymentsIncrementalAuthorizationRequest,
api_models::payments::IncrementalAuthorizationResponse,
api_models::payments::PaymentsCompleteAuthorizeRequest,
api_models::payments::PaymentsExternalAuthenticationRequest,
api_models::payments::PaymentsExternalAuthenticationResponse,
api_models::payments::SdkInformation,
api_models::payments::DeviceChannel,
api_models::payments::ThreeDsCompletionIndicator,
api_models::payments::MifinityData,
api_models::payments::ClickToPaySessionResponse,
api_models::enums::TransactionStatus,
api_models::payments::PaymentCreatePaymentLinkConfig,
api_models::payments::ThreeDsData,
api_models::payments::ThreeDsMethodData,
api_models::payments::ThreeDsMethodKey,
api_models::payments::PollConfigResponse,
api_models::payments::PollConfig,
api_models::payments::ExternalAuthenticationDetailsResponse,
api_models::payments::ExtendedCardInfo,
api_models::payments::PaymentsConfirmIntentRequest,
api_models::payments::AmountDetailsResponse,
api_models::payments::BankCodeResponse,
api_models::payments::Order,
api_models::payments::SortOn,
api_models::payments::SortBy,
api_models::payments::PaymentMethodListResponseForPayments,
api_models::payments::ResponsePaymentMethodTypesForPayments,
api_models::payment_methods::CardNetworkTokenizeRequest,
api_models::payment_methods::CardNetworkTokenizeResponse,
api_models::payment_methods::CardType,
api_models::payments::AmazonPaySessionTokenData,
api_models::payments::AmazonPayMerchantCredentials,
api_models::payments::AmazonPayWalletData,
api_models::payments::AmazonPaySessionTokenResponse,
api_models::payments::AmazonPayPaymentIntent,
api_models::payments::AmazonPayDeliveryOptions,
api_models::payments::AmazonPayDeliveryPrice,
api_models::payments::AmazonPayShippingMethod,
api_models::payment_methods::RequiredFieldInfo,
api_models::payment_methods::MaskedBankDetails,
api_models::payment_methods::SurchargeDetailsResponse,
api_models::payment_methods::SurchargeResponse,
api_models::payment_methods::SurchargePercentage,
api_models::payment_methods::PaymentMethodCollectLinkRequest,
api_models::payment_methods::PaymentMethodCollectLinkResponse,
api_models::payment_methods::PaymentMethodSubtypeSpecificData,
api_models::payment_methods::PaymentMethodSessionRequest,
api_models::payment_methods::PaymentMethodSessionResponse,
api_models::payment_methods::PaymentMethodsSessionUpdateRequest,
api_models::payment_methods::NetworkTokenResponse,
api_models::payment_methods::NetworkTokenDetailsPaymentMethod,
api_models::payment_methods::NetworkTokenDetailsResponse,
api_models::payment_methods::TokenDataResponse,
api_models::payment_methods::TokenDetailsResponse,
api_models::payment_methods::TokenizeCardRequest,
api_models::payment_methods::TokenizeDataRequest,
api_models::payment_methods::TokenizePaymentMethodRequest,
api_models::refunds::RefundListRequest,
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/openapi/src/lib.rs | crates/openapi/src/lib.rs | pub mod routes;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/openapi/src/main.rs | crates/openapi/src/main.rs | #[cfg(feature = "v1")]
mod openapi;
#[cfg(feature = "v2")]
mod openapi_v2;
mod routes;
#[allow(clippy::print_stdout)] // Using a logger is not necessary here
fn main() {
#[cfg(all(feature = "v1", feature = "v2"))]
compile_error!("features v1 and v2 are mutually exclusive, please enable only one of them");
#[cfg(feature = "v1")]
let relative_file_path = "api-reference/v1/openapi_spec_v1.json";
#[cfg(feature = "v2")]
let relative_file_path = "api-reference/v2/openapi_spec_v2.json";
#[cfg(any(feature = "v1", feature = "v2"))]
let mut file_path = router_env::workspace_path();
#[cfg(any(feature = "v1", feature = "v2"))]
file_path.push(relative_file_path);
#[cfg(feature = "v1")]
let openapi = <openapi::ApiDoc as utoipa::OpenApi>::openapi();
#[cfg(feature = "v2")]
let openapi = <openapi_v2::ApiDoc as utoipa::OpenApi>::openapi();
#[allow(clippy::expect_used)]
#[cfg(any(feature = "v1", feature = "v2"))]
std::fs::write(
&file_path,
openapi
.to_pretty_json()
.expect("Failed to serialize OpenAPI specification as JSON"),
)
.expect("Failed to write OpenAPI specification to file");
#[allow(clippy::expect_used)]
#[cfg(feature = "v1")]
{
// TODO: Do this using utoipa::extensions after we have upgraded to 5.x
let file_content =
std::fs::read_to_string(&file_path).expect("Failed to read OpenAPI specification file");
let mut lines: Vec<&str> = file_content.lines().collect();
// Insert the new text at line 3 (index 2)
if lines.len() > 2 {
let new_line = " \"x-mcp\": {\n \"enabled\": true\n },";
lines.insert(2, new_line);
}
let modified_content = lines.join("\n");
std::fs::write(&file_path, modified_content)
.expect("Failed to write modified OpenAPI specification to file");
}
#[cfg(any(feature = "v1", feature = "v2"))]
println!("Successfully saved OpenAPI specification file at '{relative_file_path}'");
#[cfg(not(any(feature = "v1", feature = "v2")))]
println!("No feature enabled to generate OpenAPI specification, please enable either 'v1' or 'v2' feature");
}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/openapi/src/openapi.rs | crates/openapi/src/openapi.rs | use crate::routes;
#[derive(utoipa::OpenApi)]
#[openapi(
info(
title = "Hyperswitch - API Documentation",
contact(
name = "Hyperswitch Support",
url = "https://hyperswitch.io",
email = "hyperswitch@juspay.in"
),
// terms_of_service = "https://www.juspay.io/terms",
description = r#"
## Get started
Hyperswitch provides a collection of APIs that enable you to process and manage payments.
Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes.
You can consume the APIs directly using your favorite HTTP/REST library.
We have a testing environment referred to "sandbox", which you can setup to test API calls without
affecting production data.
Currently, our sandbox environment is live while our production environment is under development
and will be available soon.
You can sign up on our Dashboard to get API keys to access Hyperswitch API.
### Environment
Use the following base URLs when making requests to the APIs:
| Environment | Base URL |
|---------------|------------------------------------|
| Sandbox | <https://sandbox.hyperswitch.io> |
| Production | <https://api.hyperswitch.io> |
## Authentication
When you sign up on our [dashboard](https://app.hyperswitch.io) and create a merchant
account, you are given a secret key (also referred as api-key) and a publishable key.
You may authenticate all API requests with Hyperswitch server by providing the appropriate key in
the request Authorization header.
| Key | Description |
|-----------------|-----------------------------------------------------------------------------------------------|
| api-key | Private key. Used to authenticate all API requests from your merchant server |
| publishable key | Unique identifier for your account. Used to authenticate API requests from your app's client |
Never share your secret api keys. Keep them guarded and secure.
"#,
),
servers(
(url = "https://sandbox.hyperswitch.io", description = "Sandbox Environment")
),
tags(
(name = "Merchant Account", description = "Create and manage merchant accounts"),
(name = "Profile", description = "Create and manage profiles"),
(name = "Merchant Connector Account", description = "Create and manage merchant connector accounts"),
(name = "Payments", description = "Create and manage one-time payments, recurring payments and mandates"),
(name = "Refunds", description = "Create and manage refunds for successful payments"),
(name = "Mandates", description = "Manage mandates"),
(name = "Customers", description = "Create and manage customers"),
(name = "Payment Methods", description = "Create and manage payment methods of customers"),
(name = "Disputes", description = "Manage disputes"),
(name = "API Key", description = "Create and manage API Keys"),
(name = "Payouts", description = "Create and manage payouts"),
(name = "payment link", description = "Create payment link"),
(name = "Routing", description = "Create and manage routing configurations"),
(name = "Event", description = "Manage events"),
(name = "Authentication", description = "Create and manage authentication"),
(name = "Subscriptions", description = "Subscription management and billing endpoints")
),
// The paths will be displayed in the same order as they are registered here
paths(
// Routes for payments
routes::payments::payments_create,
routes::payments::payments_update,
routes::payments::payments_confirm,
routes::payments::payments_retrieve,
routes::payments::payments_capture,
routes::payments::payments_connector_session,
routes::payments::payments_cancel,
routes::payments::payments_cancel_post_capture,
routes::payments::payments_extend_authorization,
routes::payments::payments_list,
routes::payments::payments_incremental_authorization,
routes::payment_link::payment_link_retrieve,
routes::payments::payments_external_authentication,
routes::payments::payments_complete_authorize,
routes::payments::payments_post_session_tokens,
routes::payments::payments_update_metadata,
routes::payments::payments_submit_eligibility,
// Routes for relay
routes::relay::relay,
routes::relay::relay_retrieve,
// Routes for refunds
routes::refunds::refunds_create,
routes::refunds::refunds_retrieve,
routes::refunds::refunds_update,
routes::refunds::refunds_list,
// Routes for Organization
routes::organization::organization_create,
routes::organization::organization_retrieve,
routes::organization::organization_update,
// Routes for merchant account
routes::merchant_account::merchant_account_create,
routes::merchant_account::retrieve_merchant_account,
routes::merchant_account::update_merchant_account,
routes::merchant_account::delete_merchant_account,
routes::merchant_account::merchant_account_kv_status,
// Routes for merchant connector account
routes::merchant_connector_account::connector_create,
routes::merchant_connector_account::connector_retrieve,
routes::merchant_connector_account::connector_list,
routes::merchant_connector_account::connector_update,
routes::merchant_connector_account::connector_delete,
//Routes for gsm
routes::gsm::create_gsm_rule,
routes::gsm::get_gsm_rule,
routes::gsm::update_gsm_rule,
routes::gsm::delete_gsm_rule,
// Routes for mandates
routes::mandates::get_mandate,
routes::mandates::revoke_mandate,
routes::mandates::customers_mandates_list,
//Routes for customers
routes::customers::customers_create,
routes::customers::customers_retrieve,
routes::customers::customers_list,
routes::customers::customers_update,
routes::customers::customers_delete,
//Routes for payment methods
routes::payment_method::create_payment_method_api,
routes::payment_method::list_payment_method_api,
routes::payment_method::list_customer_payment_method_api,
routes::payment_method::list_customer_payment_method_api_client,
routes::payment_method::default_payment_method_set_api,
routes::payment_method::payment_method_retrieve_api,
routes::payment_method::payment_method_update_api,
routes::payment_method::payment_method_delete_api,
// Routes for Profile
routes::profile::profile_create,
routes::profile::profile_list,
routes::profile::profile_retrieve,
routes::profile::profile_update,
routes::profile::profile_delete,
// Routes for disputes
routes::disputes::retrieve_dispute,
routes::disputes::retrieve_disputes_list,
// Routes for routing
routes::routing::routing_create_config,
routes::routing::routing_link_config,
routes::routing::routing_retrieve_config,
routes::routing::list_routing_configs,
routes::routing::routing_unlink_config,
routes::routing::routing_update_default_config,
routes::routing::routing_retrieve_default_config,
routes::routing::routing_retrieve_linked_config,
routes::routing::routing_retrieve_default_config_for_profiles,
routes::routing::routing_update_default_config_for_profile,
routes::routing::success_based_routing_update_configs,
routes::routing::toggle_success_based_routing,
routes::routing::toggle_elimination_routing,
routes::routing::create_success_based_routing,
routes::routing::create_elimination_routing,
routes::routing::contract_based_routing_setup_config,
routes::routing::contract_based_routing_update_configs,
routes::routing::call_decide_gateway_open_router,
routes::routing::call_update_gateway_score_open_router,
routes::routing::evaluate_routing_rule,
// Routes for blocklist
routes::blocklist::remove_entry_from_blocklist,
routes::blocklist::list_blocked_payment_methods,
routes::blocklist::add_entry_to_blocklist,
routes::blocklist::toggle_blocklist_guard,
// Routes for payouts
routes::payouts::payouts_create,
routes::payouts::payouts_retrieve,
routes::payouts::payouts_update,
routes::payouts::payouts_cancel,
routes::payouts::payouts_fulfill,
routes::payouts::payouts_list,
routes::payouts::payouts_confirm,
routes::payouts::payouts_list_filters,
routes::payouts::payouts_list_by_filter,
// Routes for api keys
routes::api_keys::api_key_create,
routes::api_keys::api_key_retrieve,
routes::api_keys::api_key_update,
routes::api_keys::api_key_revoke,
routes::api_keys::api_key_list,
// Routes for events
routes::webhook_events::list_initial_webhook_delivery_attempts,
routes::webhook_events::list_initial_webhook_delivery_attempts_with_jwtauth,
routes::webhook_events::list_webhook_delivery_attempts,
routes::webhook_events::retry_webhook_delivery_attempt,
// Routes for poll apis
routes::poll::retrieve_poll_status,
// Routes for profile acquirer account
routes::profile_acquirer::profile_acquirer_create,
routes::profile_acquirer::profile_acquirer_update,
// Routes for 3DS Decision Rule
routes::three_ds_decision_rule::three_ds_decision_rule_execute,
// Routes for authentication
routes::authentication::authentication_create,
routes::authentication::authentication_eligibility,
routes::authentication::authentication_authenticate,
routes::authentication::authentication_redirect,
routes::authentication::authentication_sync,
routes::authentication::authentication_enabled_authn_methods_token,
routes::authentication::authentication_eligibility_check,
routes::authentication::authentication_retrieve_eligibility_check,
// Routes for platform account
routes::platform::create_platform_account,
//Routes for subscriptions
routes::subscriptions::create_and_confirm_subscription,
routes::subscriptions::create_subscription,
routes::subscriptions::confirm_subscription,
routes::subscriptions::get_subscription,
routes::subscriptions::update_subscription,
routes::subscriptions::get_subscription_items,
routes::subscriptions::get_estimate,
routes::subscriptions::pause_subscription,
routes::subscriptions::resume_subscription,
routes::subscriptions::cancel_subscription,
),
components(schemas(
common_utils::types::MinorUnit,
common_utils::types::StringMinorUnit,
common_utils::types::TimeRange,
common_utils::link_utils::GenericLinkUiConfig,
common_utils::link_utils::EnabledPaymentMethod,
common_utils::payout_method_utils::AdditionalPayoutMethodData,
common_utils::payout_method_utils::CardAdditionalData,
common_utils::payout_method_utils::BankAdditionalData,
common_utils::payout_method_utils::WalletAdditionalData,
common_utils::payout_method_utils::BankRedirectAdditionalData,
common_utils::payout_method_utils::AchBankTransferAdditionalData,
common_utils::payout_method_utils::BacsBankTransferAdditionalData,
common_utils::payout_method_utils::SepaBankTransferAdditionalData,
common_utils::payout_method_utils::PixBankTransferAdditionalData,
common_utils::payout_method_utils::PaypalAdditionalData,
common_utils::payout_method_utils::InteracAdditionalData,
common_utils::payout_method_utils::VenmoAdditionalData,
common_utils::payout_method_utils::ApplePayDecryptAdditionalData,
common_utils::payout_method_utils::PassthroughAddtionalData,
common_types::payments::SplitPaymentsRequest,
common_types::payments::GpayTokenizationData,
common_types::payments::GPayPredecryptData,
common_types::payments::GpayEcryptedTokenizationData,
common_types::payments::ApplePayPaymentData,
common_types::payments::ApplePayPredecryptData,
common_types::payments::ApplePayCryptogramData,
common_types::payments::StripeSplitPaymentRequest,
common_types::domain::AdyenSplitData,
common_types::domain::AdyenSplitItem,
common_types::payments::AcceptanceType,
common_types::payments::CustomerAcceptance,
common_types::payments::OnlineMandate,
common_types::payments::XenditSplitRequest,
common_types::payments::XenditSplitRoute,
common_types::payments::XenditChargeResponseData,
common_types::payments::XenditMultipleSplitResponse,
common_types::payments::XenditMultipleSplitRequest,
common_types::domain::XenditSplitSubMerchantData,
common_utils::types::ChargeRefunds,
common_types::refunds::SplitRefund,
common_types::refunds::StripeSplitRefundRequest,
common_types::payments::ConnectorChargeResponseData,
common_types::payments::StripeChargeResponseData,
common_types::three_ds_decision_rule_engine::ThreeDSDecisionRule,
common_types::three_ds_decision_rule_engine::ThreeDSDecision,
common_types::payments::MerchantCountryCode,
common_types::payments::BillingDescriptor,
common_types::payments::PartnerMerchantIdentifierDetails,
common_types::payments::PartnerApplicationDetails,
common_types::payments::MerchantApplicationDetails,
api_models::enums::PaymentChannel,
api_models::three_ds_decision_rule::ThreeDsDecisionRuleExecuteRequest,
api_models::three_ds_decision_rule::ThreeDsDecisionRuleExecuteResponse,
api_models::three_ds_decision_rule::PaymentData,
api_models::three_ds_decision_rule::PaymentMethodMetaData,
api_models::three_ds_decision_rule::CustomerDeviceData,
api_models::three_ds_decision_rule::IssuerData,
api_models::three_ds_decision_rule::AcquirerData,
api_models::payments::CartesBancairesParams,
api_models::payments::NetworkParams,
api_models::payments::Cryptogram,
api_models::payments::ExternalThreeDsData,
api_models::payments::PaymentMethodTokenizationDetails,
api_models::refunds::RefundRequest,
api_models::refunds::RefundType,
api_models::refunds::RefundResponse,
api_models::refunds::RefundStatus,
api_models::refunds::RefundUpdateRequest,
api_models::organization::OrganizationCreateRequest,
api_models::organization::OrganizationUpdateRequest,
api_models::organization::OrganizationResponse,
api_models::admin::MerchantAccountCreate,
api_models::admin::MerchantAccountUpdate,
api_models::admin::MerchantAccountDeleteResponse,
api_models::admin::MerchantConnectorDeleteResponse,
api_models::admin::MerchantConnectorResponse,
api_models::admin::MerchantConnectorListResponse,
api_models::admin::AuthenticationConnectorDetails,
api_models::admin::ExtendedCardInfoConfig,
api_models::admin::BusinessGenericLinkConfig,
api_models::admin::BusinessCollectLinkConfig,
api_models::admin::BusinessPayoutLinkConfig,
api_models::admin::CardTestingGuardConfig,
api_models::admin::CardTestingGuardStatus,
api_models::customers::CustomerRequest,
api_models::customers::CustomerUpdateRequest,
api_models::customers::CustomerDeleteResponse,
api_models::payment_methods::PaymentMethodCreate,
api_models::payment_methods::PaymentMethodResponse,
api_models::payment_methods::CustomerPaymentMethodUpdateResponse,
api_models::payment_methods::CustomerPaymentMethod,
common_types::three_ds_decision_rule_engine::ThreeDSDecisionRule,
common_types::domain::AcquirerConfigMap,
common_types::domain::AcquirerConfig,
api_models::payment_methods::PaymentMethodListResponse,
api_models::payment_methods::PaymentMethodDataWalletInfo,
api_models::payment_methods::ResponsePaymentMethodsEnabled,
api_models::payment_methods::ResponsePaymentMethodTypes,
api_models::payment_methods::PaymentExperienceTypes,
api_models::payment_methods::CardNetworkTypes,
api_models::payment_methods::BankDebitTypes,
api_models::payment_methods::BankTransferTypes,
api_models::payment_methods::CustomerPaymentMethodsListResponse,
api_models::payment_methods::PaymentMethodDeleteResponse,
api_models::payment_methods::PaymentMethodUpdate,
api_models::payment_methods::CustomerDefaultPaymentMethodResponse,
api_models::payment_methods::CardDetailFromLocker,
api_models::payment_methods::PaymentMethodCreateData,
api_models::payment_methods::CardDetail,
api_models::payment_methods::CardDetailUpdate,
api_models::payment_methods::RequestPaymentMethodTypes,
api_models::poll::PollResponse,
api_models::poll::PollStatus,
api_models::customers::CustomerResponse,
api_models::admin::AcceptedCountries,
api_models::admin::AcceptedCurrencies,
api_models::enums::AdyenSplitType,
api_models::enums::PaymentType,
api_models::enums::MitCategory,
api_models::enums::ScaExemptionType,
api_models::enums::PaymentMethod,
api_models::enums::TriggeredBy,
api_models::enums::TokenDataType,
api_models::enums::PaymentMethodType,
api_models::enums::ConnectorType,
api_models::enums::PayoutConnectors,
api_models::enums::AuthenticationConnectors,
api_models::enums::Currency,
api_models::enums::CavvAlgorithm,
api_models::enums::ExemptionIndicator,
api_models::enums::DocumentKind,
api_models::enums::IntentStatus,
api_models::enums::CaptureMethod,
api_models::enums::FutureUsage,
api_models::enums::AuthenticationType,
api_models::enums::Connector,
api_models::enums::PaymentMethod,
api_models::enums::PaymentMethodIssuerCode,
api_models::enums::TaxStatus,
api_models::enums::MandateStatus,
api_models::enums::PaymentExperience,
api_models::enums::BankNames,
api_models::enums::BankType,
api_models::enums::BankHolderType,
api_models::enums::CardNetwork,
api_models::enums::MerchantCategoryCode,
api_models::enums::DisputeStage,
api_models::enums::DisputeStatus,
api_models::enums::CountryAlpha2,
api_models::enums::Country,
api_models::enums::CountryAlpha3,
api_models::enums::FieldType,
api_models::enums::FrmAction,
api_models::enums::FrmPreferredFlowTypes,
api_models::enums::RetryAction,
api_models::enums::AttemptStatus,
api_models::enums::CaptureStatus,
api_models::enums::ReconStatus,
api_models::enums::ConnectorStatus,
api_models::enums::AuthorizationStatus,
api_models::enums::ElementPosition,
api_models::enums::ElementSize,
api_models::enums::SizeVariants,
api_models::enums::MerchantProductType,
api_models::enums::PaymentLinkDetailsLayout,
api_models::enums::PaymentMethodStatus,
api_models::enums::UIWidgetFormLayout,
api_models::enums::MerchantProductType,
api_models::enums::HyperswitchConnectorCategory,
api_models::enums::ConnectorIntegrationStatus,
api_models::enums::CardDiscovery,
api_models::enums::FeatureStatus,
api_models::enums::MerchantProductType,
api_models::enums::CtpServiceProvider,
api_models::enums::PaymentLinkSdkLabelType,
api_models::enums::OrganizationType,
api_models::enums::PaymentLinkShowSdkTerms,
api_models::enums::ExternalVaultEnabled,
api_models::enums::GooglePayCardFundingSource,
api_models::enums::VaultSdk,
api_models::enums::VaultTokenType,
api_models::admin::ExternalVaultConnectorDetails,
api_models::admin::VaultTokenField,
api_models::admin::MerchantConnectorCreate,
api_models::admin::AdditionalMerchantData,
api_models::admin::ConnectorWalletDetails,
api_models::admin::MerchantRecipientData,
api_models::admin::MerchantAccountData,
api_models::admin::MerchantConnectorUpdate,
api_models::admin::PrimaryBusinessDetails,
api_models::admin::FrmConfigs,
api_models::admin::FrmPaymentMethod,
api_models::admin::FrmPaymentMethodType,
api_models::admin::PaymentMethodsEnabled,
api_models::admin::MerchantConnectorDetailsWrap,
api_models::admin::MerchantConnectorDetails,
api_models::admin::MerchantConnectorWebhookDetails,
api_models::admin::ProfileCreate,
api_models::admin::ProfileResponse,
api_models::admin::BusinessPaymentLinkConfig,
api_models::admin::PaymentLinkBackgroundImageConfig,
api_models::admin::PaymentLinkConfigRequest,
api_models::admin::PaymentLinkConfig,
api_models::admin::PaymentLinkTransactionDetails,
api_models::admin::TransactionDetailsUiConfiguration,
api_models::disputes::DisputeResponse,
api_models::disputes::DisputeResponsePaymentsRetrieve,
api_models::gsm::GsmCreateRequest,
api_models::gsm::GsmRetrieveRequest,
api_models::gsm::GsmUpdateRequest,
api_models::gsm::GsmDeleteRequest,
api_models::gsm::GsmDeleteResponse,
api_models::gsm::GsmResponse,
api_models::enums::GsmDecision,
api_models::enums::GsmFeature,
api_models::enums::StandardisedCode,
common_types::domain::GsmFeatureData,
common_types::domain::RetryFeatureData,
api_models::payments::AddressDetails,
api_models::payments::BankDebitData,
api_models::payments::AliPayQr,
api_models::payments::AliPayRedirection,
api_models::payments::MomoRedirection,
api_models::payments::TouchNGoRedirection,
api_models::payments::GcashRedirection,
api_models::payments::KakaoPayRedirection,
api_models::payments::AliPayHkRedirection,
api_models::payments::GoPayRedirection,
api_models::payments::MbWayRedirection,
api_models::payments::MobilePayRedirection,
api_models::payments::WeChatPayRedirection,
api_models::payments::WeChatPayQr,
api_models::payments::BankDebitBilling,
api_models::payments::CryptoData,
api_models::payments::RewardData,
api_models::payments::UpiData,
api_models::payments::UpiCollectData,
api_models::payments::UpiIntentData,
api_models::payments::UpiQrData,
api_models::payments::VoucherData,
api_models::payments::BoletoVoucherData,
api_models::payments::AlfamartVoucherData,
api_models::payments::IndomaretVoucherData,
api_models::payments::Address,
api_models::payments::VoucherData,
api_models::payments::JCSVoucherData,
api_models::payments::AlfamartVoucherData,
api_models::payments::IndomaretVoucherData,
api_models::payments::BankRedirectData,
api_models::payments::RealTimePaymentData,
api_models::payments::BankRedirectBilling,
api_models::payments::BankRedirectBilling,
api_models::payments::ConnectorMetadata,
api_models::payments::FeatureMetadata,
api_models::payments::ApplepayConnectorMetadataRequest,
api_models::payments::SessionTokenInfo,
api_models::payments::PaymentProcessingDetailsAt,
api_models::payments::ApplepayInitiative,
api_models::payments::PaymentProcessingDetails,
api_models::payments::PaymentMethodDataResponseWithBilling,
api_models::payments::PaymentMethodDataResponse,
api_models::payments::CardResponse,
api_models::payments::PaylaterResponse,
api_models::payments::KlarnaSdkPaymentMethodResponse,
api_models::payments::SwishQrData,
api_models::payments::RevolutPayData,
api_models::payments::AirwallexData,
api_models::payments::BraintreeData,
api_models::payments::NoonData,
api_models::payments::OrderDetailsWithAmount,
api_models::payments::NextActionType,
api_models::payments::WalletData,
api_models::payments::NextActionData,
api_models::payments::PayLaterData,
api_models::payments::MandateData,
api_models::payments::PhoneDetails,
api_models::payments::PaymentMethodData,
api_models::payments::PaymentMethodDataRequest,
api_models::payments::MandateType,
api_models::payments::MandateAmountData,
api_models::payments::Card,
api_models::payments::CardRedirectData,
api_models::payments::CardToken,
api_models::payments::PaymentsRequest,
api_models::payments::PaymentsCreateRequest,
api_models::payments::PaymentsUpdateRequest,
api_models::payments::PaymentsConfirmRequest,
api_models::payments::PaymentsResponse,
api_models::payments::PaymentsCreateResponseOpenApi,
api_models::payments::PaymentsEligibilityRequest,
api_models::payments::PaymentsEligibilityResponse,
api_models::payments::PaymentsCreateResponseOpenApi,
api_models::errors::types::GenericErrorResponseOpenApi,
api_models::payments::PaymentRetrieveBody,
api_models::payments::PaymentsRetrieveRequest,
api_models::payments::PaymentsCaptureRequest,
api_models::payments::PaymentsSessionRequest,
api_models::payments::PaymentsSessionResponse,
api_models::payments::PazeWalletData,
api_models::payments::SessionToken,
api_models::payments::ApplePaySessionResponse,
api_models::payments::NullObject,
api_models::payments::ThirdPartySdkSessionResponse,
api_models::payments::NoThirdPartySdkSessionResponse,
api_models::payments::SecretInfoToInitiateSdk,
api_models::payments::ApplePayPaymentRequest,
api_models::payments::ApplePayBillingContactFields,
api_models::payments::ApplePayShippingContactFields,
api_models::payments::ApplePayRecurringPaymentRequest,
api_models::payments::ApplePayRegularBillingRequest,
api_models::payments::ApplePayPaymentTiming,
api_models::payments::RecurringPaymentIntervalUnit,
api_models::payments::ApplePayRecurringDetails,
api_models::payments::ApplePayRegularBillingDetails,
api_models::payments::ApplePayAddressParameters,
api_models::payments::AmountInfo,
api_models::payments::ClickToPaySessionResponse,
api_models::enums::ProductType,
api_models::enums::MerchantAccountType,
api_models::enums::MerchantAccountRequestType,
api_models::payments::GooglePayWalletData,
api_models::payments::PayPalWalletData,
api_models::payments::PaypalRedirection,
api_models::payments::GpayMerchantInfo,
api_models::payments::GpayAllowedPaymentMethods,
api_models::payments::GpayAllowedMethodsParameters,
api_models::payments::GpayTokenizationSpecification,
api_models::payments::GpayTokenParameters,
api_models::payments::GpayTransactionInfo,
api_models::payments::GpaySessionTokenResponse,
api_models::payments::GooglePayThirdPartySdkData,
api_models::payments::KlarnaSessionTokenResponse,
api_models::payments::PaypalSessionTokenResponse,
api_models::payments::PaypalFlow,
api_models::payments::PaypalTransactionInfo,
api_models::payments::ApplepaySessionTokenResponse,
api_models::payments::SdkNextAction,
api_models::payments::NextActionCall,
api_models::payments::SdkNextActionData,
api_models::payments::SamsungPayWalletData,
api_models::payments::WeChatPay,
api_models::payments::GooglePayPaymentMethodInfo,
api_models::payments::ApplePayWalletData,
api_models::payments::SamsungPayWalletCredentials,
api_models::payments::SamsungPayWebWalletData,
api_models::payments::SamsungPayAppWalletData,
api_models::payments::SamsungPayCardBrand,
api_models::payments::SamsungPayTokenData,
api_models::payments::ApplepayPaymentMethod,
api_models::payments::PaymentsCancelRequest,
api_models::payments::PaymentsCancelPostCaptureRequest,
api_models::payments::PaymentListConstraints,
api_models::payments::PaymentListResponse,
api_models::payments::CashappQr,
api_models::payments::BankTransferData,
api_models::payments::BankTransferNextStepsData,
api_models::payments::SepaAndBacsBillingDetails,
api_models::payments::AchBillingDetails,
api_models::payments::MultibancoBillingDetails,
api_models::payments::DokuBillingDetails,
api_models::payments::BankTransferInstructions,
api_models::payments::MobilePaymentNextStepData,
api_models::payments::MobilePaymentConsent,
api_models::payments::IframeData,
api_models::payments::ReceiverDetails,
api_models::payments::AchTransfer,
api_models::payments::MultibancoTransferInstructions,
api_models::payments::DokuBankTransferInstructions,
api_models::payments::AmazonPayRedirectData,
api_models::payments::SkrillData,
api_models::payments::PayseraData,
api_models::payments::ApplePayRedirectData,
api_models::payments::ApplePayThirdPartySdkData,
api_models::payments::GooglePayRedirectData,
api_models::payments::GooglePayThirdPartySdk,
api_models::payments::GooglePaySessionResponse,
api_models::payments::PazeSessionTokenResponse,
api_models::payments::SamsungPaySessionTokenResponse,
api_models::payments::SamsungPayMerchantPaymentInformation,
api_models::payments::SamsungPayAmountDetails,
api_models::payments::SamsungPayAmountFormat,
api_models::payments::SamsungPayProtocolType,
api_models::payments::GpayShippingAddressParameters,
api_models::payments::GpayBillingAddressParameters,
api_models::payments::GpayBillingAddressFormat,
api_models::payments::NetworkDetails,
api_models::payments::SepaBankTransferInstructions,
api_models::payments::BacsBankTransferInstructions,
api_models::payments::RedirectResponse,
api_models::payments::RequestSurchargeDetails,
api_models::payments::PaymentAttemptResponse,
api_models::payments::CaptureResponse,
api_models::payments::PaymentsIncrementalAuthorizationRequest,
api_models::payments::IncrementalAuthorizationResponse,
api_models::payments::PaymentsCompleteAuthorizeRequest,
api_models::payments::PaymentsExternalAuthenticationRequest,
api_models::payments::PaymentsExternalAuthenticationResponse,
api_models::payments::SdkInformation,
api_models::payments::DeviceChannel,
api_models::payments::ThreeDsCompletionIndicator,
api_models::payments::MifinityData,
api_models::enums::TransactionStatus,
api_models::payments::BrowserInformation,
api_models::payments::PaymentCreatePaymentLinkConfig,
api_models::payments::ThreeDsData,
api_models::payments::ThreeDsMethodData,
api_models::payments::ThreeDsMethodKey,
api_models::payments::PollConfigResponse,
api_models::payments::PollConfig,
api_models::payments::ExternalAuthenticationDetailsResponse,
api_models::payments::ExtendedCardInfo,
api_models::payments::AmazonPaySessionTokenData,
api_models::payments::AmazonPayMerchantCredentials,
api_models::payments::AmazonPayWalletData,
api_models::payments::AmazonPaySessionTokenResponse,
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | true |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/openapi/src/routes.rs | crates/openapi/src/routes.rs | #![allow(unused)]
pub mod api_keys;
pub mod authentication;
pub mod blocklist;
pub mod customers;
pub mod disputes;
pub mod gsm;
pub mod mandates;
pub mod merchant_account;
pub mod merchant_connector_account;
pub mod organization;
pub mod payment_link;
pub mod payment_method;
pub mod payments;
pub mod payouts;
pub mod platform;
pub mod poll;
pub mod profile;
pub mod profile_acquirer;
pub mod proxy;
pub mod refunds;
pub mod relay;
pub mod revenue_recovery;
pub mod routing;
pub mod subscriptions;
pub mod three_ds_decision_rule;
pub mod tokenization;
pub mod webhook_events;
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/openapi/src/routes/api_keys.rs | crates/openapi/src/routes/api_keys.rs | #[cfg(feature = "v1")]
/// API Key - Create
///
/// Create a new API Key for accessing our APIs from your servers. The plaintext API Key will be
/// displayed only once on creation, so ensure you store it securely.
#[utoipa::path(
post,
path = "/api_keys/{merchant_id}",
params(("merchant_id" = String, Path, description = "The unique identifier for the merchant account")),
request_body= CreateApiKeyRequest,
responses(
(status = 200, description = "API Key created", body = CreateApiKeyResponse),
(status = 400, description = "Invalid data")
),
tag = "API Key",
operation_id = "Create an API Key",
security(("admin_api_key" = []))
)]
pub async fn api_key_create() {}
#[cfg(feature = "v2")]
/// API Key - Create
///
/// Create a new API Key for accessing our APIs from your servers. The plaintext API Key will be
/// displayed only once on creation, so ensure you store it securely.
#[utoipa::path(
post,
path = "/v2/api-keys",
request_body= CreateApiKeyRequest,
responses(
(status = 200, description = "API Key created", body = CreateApiKeyResponse),
(status = 400, description = "Invalid data")
),
tag = "API Key",
operation_id = "Create an API Key",
security(("admin_api_key" = []))
)]
pub async fn api_key_create() {}
#[cfg(feature = "v1")]
/// API Key - Retrieve
///
/// Retrieve information about the specified API Key.
#[utoipa::path(
get,
path = "/api_keys/{merchant_id}/{key_id}",
params (
("merchant_id" = String, Path, description = "The unique identifier for the merchant account"),
("key_id" = String, Path, description = "The unique identifier for the API Key")
),
responses(
(status = 200, description = "API Key retrieved", body = RetrieveApiKeyResponse),
(status = 404, description = "API Key not found")
),
tag = "API Key",
operation_id = "Retrieve an API Key",
security(("admin_api_key" = []))
)]
pub async fn api_key_retrieve() {}
#[cfg(feature = "v2")]
/// API Key - Retrieve
///
/// Retrieve information about the specified API Key.
#[utoipa::path(
get,
path = "/v2/api-keys/{id}",
params (
("id" = String, Path, description = "The unique identifier for the API Key")
),
responses(
(status = 200, description = "API Key retrieved", body = RetrieveApiKeyResponse),
(status = 404, description = "API Key not found")
),
tag = "API Key",
operation_id = "Retrieve an API Key",
security(("admin_api_key" = []))
)]
pub async fn api_key_retrieve() {}
#[cfg(feature = "v1")]
/// API Key - Update
///
/// Update information for the specified API Key.
#[utoipa::path(
post,
path = "/api_keys/{merchant_id}/{key_id}",
request_body = UpdateApiKeyRequest,
params (
("merchant_id" = String, Path, description = "The unique identifier for the merchant account"),
("key_id" = String, Path, description = "The unique identifier for the API Key")
),
responses(
(status = 200, description = "API Key updated", body = RetrieveApiKeyResponse),
(status = 404, description = "API Key not found")
),
tag = "API Key",
operation_id = "Update an API Key",
security(("admin_api_key" = []))
)]
pub async fn api_key_update() {}
#[cfg(feature = "v2")]
/// API Key - Update
///
/// Update information for the specified API Key.
#[utoipa::path(
put,
path = "/v2/api-keys/{id}",
request_body = UpdateApiKeyRequest,
params (
("id" = String, Path, description = "The unique identifier for the API Key")
),
responses(
(status = 200, description = "API Key updated", body = RetrieveApiKeyResponse),
(status = 404, description = "API Key not found")
),
tag = "API Key",
operation_id = "Update an API Key",
security(("admin_api_key" = []))
)]
pub async fn api_key_update() {}
#[cfg(feature = "v1")]
/// API Key - Revoke
///
/// Revoke the specified API Key. Once revoked, the API Key can no longer be used for
/// authenticating with our APIs.
#[utoipa::path(
delete,
path = "/api_keys/{merchant_id}/{key_id}",
params (
("merchant_id" = String, Path, description = "The unique identifier for the merchant account"),
("key_id" = String, Path, description = "The unique identifier for the API Key")
),
responses(
(status = 200, description = "API Key revoked", body = RevokeApiKeyResponse),
(status = 404, description = "API Key not found")
),
tag = "API Key",
operation_id = "Revoke an API Key",
security(("admin_api_key" = []))
)]
pub async fn api_key_revoke() {}
#[cfg(feature = "v2")]
/// API Key - Revoke
///
/// Revoke the specified API Key. Once revoked, the API Key can no longer be used for
/// authenticating with our APIs.
#[utoipa::path(
delete,
path = "/v2/api-keys/{id}",
params (
("id" = String, Path, description = "The unique identifier for the API Key")
),
responses(
(status = 200, description = "API Key revoked", body = RevokeApiKeyResponse),
(status = 404, description = "API Key not found")
),
tag = "API Key",
operation_id = "Revoke an API Key",
security(("admin_api_key" = []))
)]
pub async fn api_key_revoke() {}
#[cfg(feature = "v1")]
/// API Key - List
///
/// List all the API Keys associated to a merchant account.
#[utoipa::path(
get,
path = "/api_keys/{merchant_id}/list",
params(
("merchant_id" = String, Path, description = "The unique identifier for the merchant account"),
("limit" = Option<i64>, Query, description = "The maximum number of API Keys to include in the response"),
("skip" = Option<i64>, Query, description = "The number of API Keys to skip when retrieving the list of API keys."),
),
responses(
(status = 200, description = "List of API Keys retrieved successfully", body = Vec<RetrieveApiKeyResponse>),
),
tag = "API Key",
operation_id = "List all API Keys associated with a merchant account",
security(("admin_api_key" = []))
)]
pub async fn api_key_list() {}
#[cfg(feature = "v2")]
/// API Key - List
///
/// List all the API Keys associated to a merchant account.
#[utoipa::path(
get,
path = "/v2/api-keys/list",
params(
("limit" = Option<i64>, Query, description = "The maximum number of API Keys to include in the response"),
("skip" = Option<i64>, Query, description = "The number of API Keys to skip when retrieving the list of API keys."),
),
responses(
(status = 200, description = "List of API Keys retrieved successfully", body = Vec<RetrieveApiKeyResponse>),
),
tag = "API Key",
operation_id = "List all API Keys associated with a merchant account",
security(("admin_api_key" = []))
)]
pub async fn api_key_list() {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/openapi/src/routes/mandates.rs | crates/openapi/src/routes/mandates.rs | /// Mandates - Retrieve Mandate
///
/// Retrieves a mandate created using the Payments/Create API
#[utoipa::path(
get,
path = "/mandates/{mandate_id}",
params(
("mandate_id" = String, Path, description = "The identifier for mandate")
),
responses(
(status = 200, description = "The mandate was retrieved successfully", body = MandateResponse),
(status = 404, description = "Mandate does not exist in our records")
),
tag = "Mandates",
operation_id = "Retrieve a Mandate",
security(("api_key" = []))
)]
pub async fn get_mandate() {}
/// Mandates - Revoke Mandate
///
/// Revokes a mandate created using the Payments/Create API
#[utoipa::path(
post,
path = "/mandates/revoke/{mandate_id}",
params(
("mandate_id" = String, Path, description = "The identifier for a mandate")
),
responses(
(status = 200, description = "The mandate was revoked successfully", body = MandateRevokedResponse),
(status = 400, description = "Mandate does not exist in our records")
),
tag = "Mandates",
operation_id = "Revoke a Mandate",
security(("api_key" = []))
)]
pub async fn revoke_mandate() {}
/// Mandates - List Mandates
#[utoipa::path(
get,
path = "/mandates/list",
params(
("limit" = Option<i64>, Query, description = "The maximum number of Mandate Objects to include in the response"),
("mandate_status" = Option<MandateStatus>, Query, description = "The status of mandate"),
("connector" = Option<String>, Query, description = "The connector linked to mandate"),
("created_time" = Option<PrimitiveDateTime>, Query, description = "The time at which mandate is created"),
("created_time.lt" = Option<PrimitiveDateTime>, Query, description = "Time less than the mandate created time"),
("created_time.gt" = Option<PrimitiveDateTime>, Query, description = "Time greater than the mandate created time"),
("created_time.lte" = Option<PrimitiveDateTime>, Query, description = "Time less than or equals to the mandate created time"),
("created_time.gte" = Option<PrimitiveDateTime>, Query, description = "Time greater than or equals to the mandate created time"),
),
responses(
(status = 200, description = "The mandate list was retrieved successfully", body = Vec<MandateResponse>),
(status = 401, description = "Unauthorized request")
),
tag = "Mandates",
operation_id = "List Mandates",
security(("api_key" = []))
)]
pub async fn retrieve_mandates_list() {}
/// Mandates - Customer Mandates List
///
/// Lists all the mandates for a particular customer id.
#[utoipa::path(
get,
path = "/customers/{customer_id}/mandates",
params(
("customer_id" = String, Path, description = "The unique identifier for the customer")
),
responses(
(status = 200, description = "List of retrieved mandates for a customer", body = Vec<MandateResponse>),
(status = 400, description = "Invalid Data"),
),
tag = "Mandates",
operation_id = "List Mandates for a Customer",
security(("api_key" = []))
)]
pub async fn customers_mandates_list() {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/openapi/src/routes/blocklist.rs | crates/openapi/src/routes/blocklist.rs | #[utoipa::path(
post,
path = "/blocklist/toggle",
params (
("status" = bool, Query, description = "Boolean value to enable/disable blocklist"),
),
responses(
(status = 200, description = "Blocklist guard enabled/disabled", body = ToggleBlocklistResponse),
(status = 400, description = "Invalid Data")
),
tag = "Blocklist",
operation_id = "Toggle blocklist guard for a particular merchant",
security(("api_key" = []))
)]
pub async fn toggle_blocklist_guard() {}
#[utoipa::path(
post,
path = "/blocklist",
request_body = BlocklistRequest,
responses(
(status = 200, description = "Fingerprint Blocked", body = BlocklistResponse),
(status = 400, description = "Invalid Data")
),
tag = "Blocklist",
operation_id = "Block a Fingerprint",
security(("api_key" = []))
)]
pub async fn add_entry_to_blocklist() {}
#[utoipa::path(
delete,
path = "/blocklist",
request_body = BlocklistRequest,
responses(
(status = 200, description = "Fingerprint Unblocked", body = BlocklistResponse),
(status = 400, description = "Invalid Data")
),
tag = "Blocklist",
operation_id = "Unblock a Fingerprint",
security(("api_key" = []))
)]
pub async fn remove_entry_from_blocklist() {}
#[utoipa::path(
get,
path = "/blocklist",
params (
("data_kind" = BlocklistDataKind, Query, description = "Kind of the fingerprint list requested"),
),
responses(
(status = 200, description = "Blocked Fingerprints", body = BlocklistResponse),
(status = 400, description = "Invalid Data")
),
tag = "Blocklist",
operation_id = "List Blocked fingerprints of a particular kind",
security(("api_key" = []))
)]
pub async fn list_blocked_payment_methods() {}
| rust | Apache-2.0 | 4201e04a8f0f1d46b57f24868f4f943a9be50bda | 2026-01-04T15:31:59.475325Z | false |
juspay/hyperswitch | https://github.com/juspay/hyperswitch/blob/4201e04a8f0f1d46b57f24868f4f943a9be50bda/crates/openapi/src/routes/refunds.rs | crates/openapi/src/routes/refunds.rs | /// Refunds - Create
///
/// Creates a refund against an already processed payment. In case of some processors, you can even opt to refund only a partial amount multiple times until the original charge amount has been refunded
#[utoipa::path(
post,
path = "/refunds",
request_body(
content = RefundRequest,
examples(
(
"Create an instant refund to refund the whole amount" = (
value = json!({
"payment_id": "{{payment_id}}",
"refund_type": "instant"
})
)
),
(
"Create an instant refund to refund partial amount" = (
value = json!({
"payment_id": "{{payment_id}}",
"refund_type": "instant",
"amount": 654
})
)
),
(
"Create an instant refund with reason" = (
value = json!({
"payment_id": "{{payment_id}}",
"refund_type": "instant",
"amount": 6540,
"reason": "Customer returned product"
})
)
),
)
),
responses(
(status = 200, description = "Refund created", body = RefundResponse),
(status = 400, description = "Missing Mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Refunds",
operation_id = "Create a Refund",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn refunds_create() {}
/// Refunds - Retrieve
///
/// Retrieves a Refund. This may be used to get the status of a previously initiated refund
#[utoipa::path(
get,
path = "/refunds/{refund_id}",
params(
("refund_id" = String, Path, description = "The identifier for refund")
),
responses(
(status = 200, description = "Refund retrieved", body = RefundResponse),
(status = 404, description = "Refund does not exist in our records")
),
tag = "Refunds",
operation_id = "Retrieve a Refund",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn refunds_retrieve() {}
/// Refunds - Retrieve (POST)
///
/// To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment
#[utoipa::path(
get,
path = "/refunds/sync",
responses(
(status = 200, description = "Refund retrieved", body = RefundResponse),
(status = 404, description = "Refund does not exist in our records")
),
tag = "Refunds",
operation_id = "Retrieve a Refund",
security(("api_key" = []))
)]
pub async fn refunds_retrieve_with_body() {}
/// Refunds - Update
///
/// Updates the properties of a Refund object. This API can be used to attach a reason for the refund or metadata fields
#[utoipa::path(
post,
path = "/refunds/{refund_id}",
params(
("refund_id" = String, Path, description = "The identifier for refund")
),
request_body(
content = RefundUpdateRequest,
examples(
(
"Update refund reason" = (
value = json!({
"reason": "Paid by mistake"
})
)
),
)
),
responses(
(status = 200, description = "Refund updated", body = RefundResponse),
(status = 400, description = "Missing Mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Refunds",
operation_id = "Update a Refund",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn refunds_update() {}
/// Refunds - List
///
/// Lists all the refunds associated with the merchant, or for a specific payment if payment_id is provided
#[utoipa::path(
post,
path = "/refunds/list",
request_body=RefundListRequest,
responses(
(status = 200, description = "List of refunds", body = RefundListResponse),
),
tag = "Refunds",
operation_id = "List all Refunds",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub fn refunds_list() {}
/// Refunds - List For the Given profiles
///
/// Lists all the refunds associated with the merchant or a payment_id if payment_id is not provided
#[utoipa::path(
post,
path = "/refunds/profile/list",
request_body=RefundListRequest,
responses(
(status = 200, description = "List of refunds", body = RefundListResponse),
),
tag = "Refunds",
operation_id = "List all Refunds for the given Profiles",
security(("api_key" = []))
)]
pub fn refunds_list_profile() {}
/// Refunds - Filter
///
/// To list the refunds filters associated with list of connectors, currencies and payment statuses
#[utoipa::path(
post,
path = "/refunds/filter",
request_body=TimeRange,
responses(
(status = 200, description = "List of filters", body = RefundListMetaData),
),
tag = "Refunds",
operation_id = "List all filters for Refunds",
security(("api_key" = []))
)]
pub async fn refunds_filter_list() {}
/// Refunds - Create
///
/// Creates a refund against an already processed payment. In case of some processors, you can even opt to refund only a partial amount multiple times until the original charge amount has been refunded
#[utoipa::path(
post,
path = "/v2/refunds",
request_body(
content = RefundsCreateRequest,
examples(
(
"Create an instant refund to refund the whole amount" = (
value = json!({
"payment_id": "{{payment_id}}",
"merchant_reference_id": "ref_123",
"refund_type": "instant"
})
)
),
(
"Create an instant refund to refund partial amount" = (
value = json!({
"payment_id": "{{payment_id}}",
"merchant_reference_id": "ref_123",
"refund_type": "instant",
"amount": 654
})
)
),
(
"Create an instant refund with reason" = (
value = json!({
"payment_id": "{{payment_id}}",
"merchant_reference_id": "ref_123",
"refund_type": "instant",
"amount": 6540,
"reason": "Customer returned product"
})
)
),
)
),
responses(
(status = 200, description = "Refund created", body = RefundResponse),
(status = 400, description = "Missing Mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Refunds",
operation_id = "Create a Refund",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn refunds_create() {}
/// Refunds - Metadata Update
///
/// Updates the properties of a Refund object. This API can be used to attach a reason for the refund or metadata fields
#[utoipa::path(
put,
path = "/v2/refunds/{id}/update-metadata",
params(
("id" = String, Path, description = "The identifier for refund")
),
request_body(
content = RefundMetadataUpdateRequest,
examples(
(
"Update refund reason" = (
value = json!({
"reason": "Paid by mistake"
})
)
)
)
),
responses(
(status = 200, description = "Refund updated", body = RefundResponse),
(status = 400, description = "Missing Mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Refunds",
operation_id = "Update Refund Metadata and Reason",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn refunds_metadata_update() {}
/// Refunds - Retrieve
///
/// Retrieves a Refund. This may be used to get the status of a previously initiated refund
#[utoipa::path(
get,
path = "/v2/refunds/{id}",
params(
("id" = String, Path, description = "The identifier for refund")
),
responses(
(status = 200, description = "Refund retrieved", body = RefundResponse),
(status = 404, description = "Refund does not exist in our records")
),
tag = "Refunds",
operation_id = "Retrieve a Refund",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn refunds_retrieve() {}
/// Refunds - List
///
/// To list the refunds associated with a payment_id or with the merchant, if payment_id is not provided
#[utoipa::path(
post,
path = "/v2/refunds/list",
request_body=RefundListRequest,
responses(
(status = 200, description = "List of refunds", body = RefundListResponse),
),
tag = "Refunds",
operation_id = "List all Refunds",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub fn refunds_list() {}
| 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.