text
stringlengths
70
351k
source
stringclasses
4 values
<|fim_prefix|> // file: hyperswitch/crates/analytics/src/api_event/metrics.rs | crate: analytics use api_models::analytics::{ api_event::{ ApiEventDimensions, ApiEventFilters, ApiEventMetrics, ApiEventMetricsBucketIdentifier, }, Granularity, TimeRange, }; use crate::{ query::{Aggregate, GroupByClause, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, LoadRow, MetricsResult}, }; use std::collections::HashSet; use api_count::ApiCount; use latency::MaxLatency; use status_code_count::StatusCodeCount; use self::latency::LatencyAvg; 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)>> { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
// file: hyperswitch/crates/analytics/src/api_event/metrics/status_code_count.rs | crate: analytics 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}, }; 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) }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/analytics/src/payment_intents/metrics.rs | crate: analytics use std::collections::HashSet; use api_models::analytics::{ payment_intents::{ PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetrics, PaymentIntentMetricsBucketIdentifier, }, Granularity, TimeRange, }; use crate::{ enums::AuthInfo, query::{Aggregate, GroupByClause, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, LoadRow, MetricsResult}, }; use payment_intent_count::PaymentIntentCount; use payment_processed_amount::PaymentProcessedAmount; use payments_success_rate::PaymentsSuccessRate; use smart_retried_amount::SmartRetriedAmount; use successful_smart_retries::SuccessfulSmartRetries; use total_smart_retries::TotalSmartRetries; async fn load_metrics( &self, dimensions: &[PaymentIntentDimensions], auth: &AuthInfo, filters: &PaymentIntentFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/analytics/src/payment_intents/filters.rs | crate: analytics use api_models::analytics::{payment_intents::PaymentIntentDimensions, Granularity, TimeRange}; use common_utils::errors::ReportSwitchExt; use time::PrimitiveDateTime; use crate::{ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, types::{ AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, FiltersError, FiltersResult, LoadRow, }, }; pub async fn get_payment_intent_filter_for_dimension<T>( dimension: PaymentIntentDimensions, merchant_id: &common_utils::id_type::MerchantId, time_range: &TimeRange, pool: &T, ) -> FiltersResult<Vec<PaymentIntentFilterRow>> where T: AnalyticsDataSource + PaymentIntentFilterAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/analytics/src/active_payments/core.rs | crate: analytics use std::collections::HashMap; use api_models::analytics::{ active_payments::{ ActivePaymentsMetrics, ActivePaymentsMetricsBucketIdentifier, MetricsBucketResponse, }, AnalyticsMetadata, GetActivePaymentsMetricRequest, MetricsResponse, }; use router_env::{instrument, logger, tracing}; use super::ActivePaymentsMetricsAccumulator; use crate::{ active_payments::ActivePaymentsMetricAccumulator, errors::{AnalyticsError, AnalyticsResult}, AnalyticsProvider, }; pub async fn get_metrics( pool: &AnalyticsProvider, publishable_key: &String, merchant_id: &common_utils::id_type::MerchantId, req: GetActivePaymentsMetricRequest, ) -> AnalyticsResult<MetricsResponse<MetricsBucketResponse>> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/analytics/src/active_payments/metrics/active_payments.rs | crate: analytics 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}, }; async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, publishable_key: &str, time_range: &TimeRange, pool: &T, ) -> MetricsResult< HashSet<( ActivePaymentsMetricsBucketIdentifier, ActivePaymentsMetricRow, )>, > { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/analytics/src/sdk_events/events.rs | crate: analytics use api_models::analytics::{ sdk_events::{SdkEventNames, SdkEventsRequest}, Granularity, }; use common_utils::errors::ReportSwitchExt; use time::PrimitiveDateTime; use crate::{ query::{Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, FiltersError, FiltersResult, LoadRow}, }; pub async fn get_sdk_event<T>( publishable_key: &String, request: SdkEventsRequest, pool: &T, ) -> FiltersResult<Vec<SdkEventsResult>> where T: AnalyticsDataSource + SdkEventsFilterAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/analytics/src/sdk_events/filters.rs | crate: analytics use api_models::analytics::{sdk_events::SdkEventDimensions, Granularity, TimeRange}; use time::PrimitiveDateTime; use crate::{ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, FiltersError, FiltersResult, LoadRow}, }; pub async fn get_sdk_event_filter_for_dimension<T>( dimension: SdkEventDimensions, publishable_key: &String, time_range: &TimeRange, pool: &T, ) -> FiltersResult<Vec<SdkEventFilter>> where T: AnalyticsDataSource + SdkEventFilterAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/analytics/src/disputes/core.rs | crate: analytics use api_models::analytics::{ disputes::{ DisputeDimensions, DisputeMetrics, DisputeMetricsBucketIdentifier, DisputeMetricsBucketResponse, }, DisputeFilterValue, DisputeFiltersResponse, DisputesAnalyticsMetadata, DisputesMetricsResponse, GetDisputeFilterRequest, GetDisputeMetricRequest, }; 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_filters( pool: &AnalyticsProvider, req: GetDisputeFilterRequest, auth: &AuthInfo, ) -> AnalyticsResult<DisputeFiltersResponse> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/analytics/src/disputes/core.rs | crate: analytics use std::collections::HashMap; use api_models::analytics::{ disputes::{ DisputeDimensions, DisputeMetrics, DisputeMetricsBucketIdentifier, DisputeMetricsBucketResponse, }, DisputeFilterValue, DisputeFiltersResponse, DisputesAnalyticsMetadata, DisputesMetricsResponse, GetDisputeFilterRequest, GetDisputeMetricRequest, }; 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>> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/analytics/src/disputes/filters.rs | crate: analytics use api_models::analytics::{disputes::DisputeDimensions, Granularity, TimeRange}; use time::PrimitiveDateTime; use crate::{ enums::AuthInfo, query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, types::{ AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, FiltersError, FiltersResult, LoadRow, }, }; 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>, { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/analytics/src/auth_events/filters.rs | crate: analytics use api_models::analytics::{auth_events::AuthEventDimensions, Granularity, TimeRange}; use common_utils::errors::ReportSwitchExt; use time::PrimitiveDateTime; use crate::{ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, types::{ AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, FiltersError, FiltersResult, LoadRow, }, }; pub async fn get_auth_events_filter_for_dimension<T>( dimension: AuthEventDimensions, merchant_id: &common_utils::id_type::MerchantId, time_range: &TimeRange, pool: &T, ) -> FiltersResult<Vec<AuthEventFilterRow>> where T: AnalyticsDataSource + AuthEventFilterAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/analytics/src/refunds/distribution.rs | crate: analytics use api_models::analytics::{ refunds::{ RefundDimensions, RefundDistributions, RefundFilters, RefundMetricsBucketIdentifier, RefundType, }, Granularity, RefundDistributionBody, TimeRange, }; use crate::{ enums::AuthInfo, query::{Aggregate, GroupByClause, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, LoadRow, MetricsResult}, }; async fn load_distribution( &self, distribution: &RefundDistributionBody, dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<Vec<(RefundMetricsBucketIdentifier, RefundDistributionRow)>> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/analytics/src/refunds/filters.rs | crate: analytics use api_models::analytics::{ refunds::{RefundDimensions, RefundType}, Granularity, TimeRange, }; use time::PrimitiveDateTime; use crate::{ enums::AuthInfo, query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, types::{ AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, FiltersError, FiltersResult, LoadRow, }, }; pub async fn get_refund_filter_for_dimension<T>( dimension: RefundDimensions, auth: &AuthInfo, time_range: &TimeRange, pool: &T, ) -> FiltersResult<Vec<RefundFilterRow>> where T: AnalyticsDataSource + RefundFilterAnalytics, PrimitiveDateTime: ToSql<T>, AnalyticsCollection: ToSql<T>, Granularity: GroupByClause<T>, Aggregate<&'static str>: ToSql<T>, Window<&'static str>: ToSql<T>, { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/tests/payouts.rs | crate: router async fn payouts_todo() { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/compatibility/stripe/customers.rs | crate: router use actix_web::{web, HttpRequest, HttpResponse}; use common_utils::id_type; use router_env::{instrument, tracing, Flow}; use crate::{ compatibility::{stripe::errors, wrap}, core::{api_locking, customers, payment_methods::cards}, routes, services::{api, authentication as auth}, types::api::{customers as customer_types, payment_methods}, }; pub async fn list_customer_payment_method_api( state: web::Data<routes::AppState>, req: HttpRequest, path: web::Path<id_type::CustomerId>, json_payload: web::Query<payment_methods::PaymentMethodListRequest>, ) -> HttpResponse { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/compatibility/stripe/customers.rs | crate: router use actix_web::{web, HttpRequest, HttpResponse}; use common_utils::id_type; use router_env::{instrument, tracing, Flow}; use crate::{ compatibility::{stripe::errors, wrap}, core::{api_locking, customers, payment_methods::cards}, routes, services::{api, authentication as auth}, types::api::{customers as customer_types, payment_methods}, }; pub async fn customer_delete( state: web::Data<routes::AppState>, req: HttpRequest, path: web::Path<id_type::CustomerId>, ) -> HttpResponse { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/compatibility/stripe/customers.rs | crate: router use actix_web::{web, HttpRequest, HttpResponse}; use common_utils::id_type; use error_stack::report; use router_env::{instrument, tracing, Flow}; use crate::{ compatibility::{stripe::errors, wrap}, core::{api_locking, customers, payment_methods::cards}, routes, services::{api, authentication as auth}, types::api::{customers as customer_types, payment_methods}, }; pub async fn customer_update( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, path: web::Path<id_type::CustomerId>, form_payload: web::Bytes, ) -> HttpResponse { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/compatibility/stripe/customers.rs | crate: router use actix_web::{web, HttpRequest, HttpResponse}; use common_utils::id_type; use router_env::{instrument, tracing, Flow}; use crate::{ compatibility::{stripe::errors, wrap}, core::{api_locking, customers, payment_methods::cards}, routes, services::{api, authentication as auth}, types::api::{customers as customer_types, payment_methods}, }; pub async fn customer_retrieve( state: web::Data<routes::AppState>, req: HttpRequest, path: web::Path<id_type::CustomerId>, ) -> HttpResponse { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/compatibility/stripe/customers.rs | crate: router use actix_web::{web, HttpRequest, HttpResponse}; use error_stack::report; use router_env::{instrument, tracing, Flow}; use crate::{ compatibility::{stripe::errors, wrap}, core::{api_locking, customers, payment_methods::cards}, routes, services::{api, authentication as auth}, types::api::{customers as customer_types, payment_methods}, }; pub async fn customer_create( state: web::Data<routes::AppState>, qs_config: web::Data<serde_qs::Config>, req: HttpRequest, form_payload: web::Bytes, ) -> HttpResponse { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/types/storage/payment_link.rs | crate: router use diesel::{associations::HasTable, ExpressionMethods, QueryDsl}; pub use diesel_models::{ payment_link::{PaymentLink, PaymentLinkNew}, schema::payment_link::dsl, }; use crate::{ connection::PgPooledConn, core::errors::{self, CustomResult}, logger, }; async fn filter_by_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payment_link_list_constraints: api_models::payments::PaymentLinkListConstraints, ) -> CustomResult<Vec<Self>, errors::DatabaseError> { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/types/storage/mandate.rs | crate: router use common_utils::errors::CustomResult; use diesel::{associations::HasTable, ExpressionMethods, QueryDsl}; use diesel_models::{errors, schema::mandate::dsl}; use crate::{connection::PgPooledConn, logger}; async fn filter_by_constraints( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, mandate_list_constraints: api_models::mandates::MandateListConstraints, ) -> CustomResult<Vec<Self>, errors::DatabaseError> { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/types/domain/user_key_store.rs | crate: router use common_utils::{ crypto::Encryptable, date_time, type_name, types::keymanager::{Identifier, KeyManagerState}, }; use hyperswitch_domain_models::type_encryption::{crypto_operation, CryptoOperation}; use masking::{PeekInterface, Secret}; use crate::errors::{CustomResult, ValidationError}; async fn convert_back( state: &KeyManagerState, item: Self::DstType, key: &Secret<Vec<u8>>, _key_manager_identifier: Identifier, ) -> CustomResult<Self, ValidationError> where Self: Sized, { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/workflows/revenue_recovery.rs | crate: router use api_models::payments::PaymentsGetIntentRequest; use common_utils::{ ext_traits::{StringExt, ValueExt}, id_type, }; use hyperswitch_domain_models::payments::PaymentIntentData; use router_env::logger; use scheduler::{types::process_data, utils as scheduler_utils}; use crate::{ core::{ admin, payments, revenue_recovery::{self as pcr, types}, }, db::StorageInterface, errors::StorageError, types::{ api::{self as api_types}, storage::revenue_recovery as pcr_storage_types, }, }; use crate::{routes::SessionState, types::storage}; pub(crate) async fn get_schedule_time_to_retry_mit_payments( db: &dyn StorageInterface, merchant_id: &id_type::MerchantId, retry_count: i32, ) -> Option<time::PrimitiveDateTime> { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/workflows/revenue_recovery.rs | crate: router use scheduler::{consumer::workflows::ProcessTrackerWorkflow, errors}; use storage_impl::errors as storage_errors; use crate::{ core::{ admin, payments, revenue_recovery::{self as pcr, types}, }, db::StorageInterface, errors::StorageError, types::{ api::{self as api_types}, storage::revenue_recovery as pcr_storage_types, }, }; use crate::{routes::SessionState, types::storage}; pub(crate) async fn extract_data_and_perform_action( state: &SessionState, tracking_data: &pcr_storage_types::PcrWorkflowTrackingData, ) -> Result<pcr_storage_types::PcrPaymentData, errors::ProcessTrackerError> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/workflows/revenue_recovery.rs | crate: router use api_models::payments::PaymentsGetIntentRequest; use common_utils::{ ext_traits::{StringExt, ValueExt}, id_type, }; use hyperswitch_domain_models::payments::PaymentIntentData; use scheduler::{consumer::workflows::ProcessTrackerWorkflow, errors}; use storage_impl::errors as storage_errors; use crate::{ core::{ admin, payments, revenue_recovery::{self as pcr, types}, }, db::StorageInterface, errors::StorageError, types::{ api::{self as api_types}, storage::revenue_recovery as pcr_storage_types, }, }; use crate::{routes::SessionState, types::storage}; async fn execute_workflow<'a>( &'a self, state: &'a SessionState, process: storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/configs/secrets_transformers.rs | crate: router use common_utils::{errors::CustomResult, ext_traits::AsyncExt}; use hyperswitch_interfaces::secrets_interface::{ secret_handler::SecretsHandler, secret_state::{RawSecret, SecretStateContainer, SecuredSecret}, SecretManagementInterface, SecretsManagementError, }; async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, _secret_management_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/configs/secrets_transformers.rs | crate: router use hyperswitch_interfaces::secrets_interface::{ secret_handler::SecretsHandler, secret_state::{RawSecret, SecretStateContainer, SecuredSecret}, SecretManagementInterface, SecretsManagementError, }; use crate::settings::{self, Settings}; /// # Panics /// /// Will panic even if kms decryption fails for at least one field pub(crate) async fn fetch_raw_secrets( conf: Settings<SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, ) -> Settings<RawSecret> { {#[allow(clippy::expect_used)]let master_database = settings::Database::convert_to_raw_secret(conf.master_database, secret_management_client) .await .expect("Failed to decrypt master database configuration");<|fim_suffix|> <|fim_middle|> let network_tokenization_service = conf .network_tokenization_service .async_map(|network_tokenization_service| async { settings::NetworkTokenizationService::convert_to_raw_secret( network_tokenization_service, secret_management_client, ) .await .expect("Failed to decrypt network tokenization service configs") }) .await;Settings { server: conf.server, master_database, redis: conf.redis, log: conf.log, #[cfg(feature = "kv_store")] drainer: conf.drainer, encryption_management: conf.encryption_management, secrets_management: conf.secrets_management, proxy: conf.proxy, env: conf.env, key_manager, #[cfg(feature = "olap")] replica_database, secrets, fallback_merchant_ids_api_key_auth: conf.fallback_merchant_ids_api_key_auth, locker: conf.locker, connectors: conf.connectors, forex_api, refund: conf.refund, eph_key: conf.eph_key, scheduler: conf.scheduler, jwekey, webhooks: conf.webhooks, pm_filters: conf.pm_filters, payout_method_filters: conf.payout_method_filters, bank_config: conf.bank_config, api_keys, file_storage: conf.file_storage, tokenization: conf.tokenization, connector_customer: conf.connector_customer, #[cfg(feature = "dummy_connector")] dummy_connector: conf.dummy_connector, #[cfg(feature = "email")] email: conf.email, user: conf.user, mandates: conf.mandates, network_transaction_id_supported_connectors: conf .network_transaction_id_supported_connectors, required_fields: conf.required_fields, delayed_session_response: conf.delayed_session_response, webhook_source_verification_call: conf.webhook_source_verification_call, billing_connectors_payment_sync: conf.billing_connectors_payment_sync, payment_method_auth, connector_request_reference_id_config: conf.connector_request_reference_id_config, #[cfg(feature = "payouts")] payouts: conf.payouts, applepay_decrypt_keys, paze_decrypt_keys, google_pay_decrypt_keys: conf.google_pay_decrypt_keys, multiple_api_version_supported_connectors: conf.multiple_api_version_supported_connectors, applepay_merchant_configs, lock_settings: conf.lock_settings, temp_locker_enable_config: conf.temp_locker_enable_config, generic_link: conf.generic_link, payment_link: conf.payment_link, #[cfg(feature = "olap")] analytics, #[cfg(feature = "olap")] opensearch: conf.opensearch, #[cfg(feature = "kv_store")] kv_config: conf.kv_config, #[cfg(feature = "frm")] frm: conf.frm, #[cfg(feature = "olap")] report_download_config: conf.report_download_config, events: conf.events, #[cfg(feature = "olap")] connector_onboarding, cors: conf.cors, unmasked_headers: conf.unmasked_headers, saved_payment_methods: conf.saved_payment_methods, multitenancy: conf.multitenancy, user_auth_methods, decision: conf.decision, locker_based_open_banking_connectors: conf.locker_based_open_banking_connectors, grpc_client: conf.grpc_client, #[cfg(feature = "v2")] cell_information: conf.cell_information, network_tokenization_supported_card_networks: conf .network_tokenization_supported_card_networks, network_tokenization_service, network_tokenization_supported_connectors: conf.network_tokenization_supported_connectors, theme: conf.theme, platform: conf.platform, }}}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/db/health_check.rs | crate: router use diesel_models::ConfigNew; use router_env::{instrument, logger, tracing}; use crate::{ connection, core::errors::{self, CustomResult}, types::storage, }; async fn health_check_db(&self) -> CustomResult<(), errors::HealthCheckDBError> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/routes/verification.rs | crate: router use actix_web::{web, HttpRequest, Responder}; use api_models::verifications; use router_env::{instrument, tracing, Flow}; use super::app::AppState; use crate::{ core::{api_locking, verification}, services::{api, authentication as auth, authorization::permissions::Permission}, }; pub async fn retrieve_apple_pay_verified_domains( state: web::Data<AppState>, req: HttpRequest, params: web::Query<verifications::ApplepayGetVerifiedDomainsParam>, ) -> impl Responder { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/routes/verification.rs | crate: router use actix_web::{web, HttpRequest, Responder}; use api_models::verifications; use router_env::{instrument, tracing, Flow}; use super::app::AppState; use crate::{ core::{api_locking, verification}, services::{api, authentication as auth, authorization::permissions::Permission}, }; pub async fn apple_pay_merchant_registration( state: web::Data<AppState>, req: HttpRequest, json_payload: web::Json<verifications::ApplepayMerchantVerificationRequest>, path: web::Path<common_utils::id_type::MerchantId>, ) -> impl Responder { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/routes/files.rs | crate: router use actix_web::{web, HttpRequest, HttpResponse}; use router_env::{instrument, tracing, Flow}; use crate::core::api_locking; use super::app::AppState; use crate::{ core::files::*, services::{api, authentication as auth}, types::api::files, }; pub async fn files_retrieve( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, ) -> HttpResponse { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/routes/files.rs | crate: router use actix_web::{web, HttpRequest, HttpResponse}; use router_env::{instrument, tracing, Flow}; use crate::core::api_locking; use super::app::AppState; use crate::{ core::files::*, services::{api, authentication as auth}, types::api::files, }; pub async fn files_delete( state: web::Data<AppState>, req: HttpRequest, path: web::Path<String>, ) -> HttpResponse { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/routes/files.rs | crate: router use actix_multipart::Multipart; use actix_web::{web, HttpRequest, HttpResponse}; use router_env::{instrument, tracing, Flow}; use crate::core::api_locking; use super::app::AppState; use crate::{ core::files::*, services::{api, authentication as auth}, types::api::files, }; pub async fn files_create( state: web::Data<AppState>, req: HttpRequest, payload: Multipart, ) -> HttpResponse { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/routes/webhooks.rs | crate: router use actix_web::{web, HttpRequest, Responder}; use router_env::{instrument, tracing, Flow}; use super::app::AppState; use crate::{ core::{ api_locking, webhooks::{self, types}, }, services::{api, authentication as auth}, }; pub async fn receive_incoming_webhook<W: types::OutgoingWebhookType>( state: web::Data<AppState>, req: HttpRequest, body: web::Bytes, path: web::Path<( common_utils::id_type::MerchantId, common_utils::id_type::ProfileId, common_utils::id_type::MerchantConnectorAccountId, )>, ) -> impl Responder { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/routes/webhooks.rs | crate: router use actix_web::{web, HttpRequest, Responder}; use router_env::{instrument, tracing, Flow}; use super::app::AppState; use crate::{ core::{ api_locking, webhooks::{self, types}, }, services::{api, authentication as auth}, }; pub async fn receive_incoming_relay_webhook<W: types::OutgoingWebhookType>( state: web::Data<AppState>, req: HttpRequest, body: web::Bytes, path: web::Path<( common_utils::id_type::MerchantId, common_utils::id_type::ProfileId, common_utils::id_type::MerchantConnectorAccountId, )>, ) -> impl Responder { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/routes/webhooks.rs | crate: router use actix_web::{web, HttpRequest, Responder}; use router_env::{instrument, tracing, Flow}; use super::app::AppState; use crate::{ core::{ api_locking, webhooks::{self, types}, }, services::{api, authentication as auth}, }; pub async fn receive_incoming_relay_webhook<W: types::OutgoingWebhookType>( state: web::Data<AppState>, req: HttpRequest, body: web::Bytes, path: web::Path<( common_utils::id_type::MerchantId, common_utils::id_type::MerchantConnectorAccountId, )>, ) -> impl Responder { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/routes/webhooks.rs | crate: router use actix_web::{web, HttpRequest, Responder}; use router_env::{instrument, tracing, Flow}; use super::app::AppState; use crate::{ core::{ api_locking, webhooks::{self, types}, }, services::{api, authentication as auth}, }; pub async fn receive_incoming_webhook<W: types::OutgoingWebhookType>( state: web::Data<AppState>, req: HttpRequest, body: web::Bytes, path: web::Path<(common_utils::id_type::MerchantId, String)>, ) -> impl Responder { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/routes/webhook_events.rs | crate: router use actix_web::{web, HttpRequest, Responder}; use router_env::{instrument, tracing, Flow}; use crate::{ core::{api_locking, webhooks::webhook_events}, routes::AppState, services::{ api, authentication::{self as auth, UserFromToken}, authorization::permissions::Permission, }, types::api::webhook_events::{ EventListConstraints, EventListRequestInternal, WebhookDeliveryAttemptListRequestInternal, WebhookDeliveryRetryRequestInternal, }, }; pub async fn retry_webhook_delivery_attempt( state: web::Data<AppState>, req: HttpRequest, path: web::Path<(common_utils::id_type::MerchantId, String)>, ) -> impl Responder { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/routes/webhook_events.rs | crate: router use actix_web::{web, HttpRequest, Responder}; use router_env::{instrument, tracing, Flow}; use crate::{ core::{api_locking, webhooks::webhook_events}, routes::AppState, services::{ api, authentication::{self as auth, UserFromToken}, authorization::permissions::Permission, }, types::api::webhook_events::{ EventListConstraints, EventListRequestInternal, WebhookDeliveryAttemptListRequestInternal, WebhookDeliveryRetryRequestInternal, }, }; pub async fn list_webhook_delivery_attempts( state: web::Data<AppState>, req: HttpRequest, path: web::Path<(common_utils::id_type::MerchantId, String)>, ) -> impl Responder { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/routes/webhook_events.rs | crate: router use actix_web::{web, HttpRequest, Responder}; use router_env::{instrument, tracing, Flow}; use crate::{ core::{api_locking, webhooks::webhook_events}, routes::AppState, services::{ api, authentication::{self as auth, UserFromToken}, authorization::permissions::Permission, }, types::api::webhook_events::{ EventListConstraints, EventListRequestInternal, WebhookDeliveryAttemptListRequestInternal, WebhookDeliveryRetryRequestInternal, }, }; pub async fn list_initial_webhook_delivery_attempts_with_jwtauth( state: web::Data<AppState>, req: HttpRequest, query: web::Query<EventListConstraints>, ) -> impl Responder { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/routes/webhook_events.rs | crate: router use actix_web::{web, HttpRequest, Responder}; use router_env::{instrument, tracing, Flow}; use crate::{ core::{api_locking, webhooks::webhook_events}, routes::AppState, services::{ api, authentication::{self as auth, UserFromToken}, authorization::permissions::Permission, }, types::api::webhook_events::{ EventListConstraints, EventListRequestInternal, WebhookDeliveryAttemptListRequestInternal, WebhookDeliveryRetryRequestInternal, }, }; pub async fn list_initial_webhook_delivery_attempts( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::MerchantId>, query: web::Query<EventListConstraints>, ) -> impl Responder { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/routes/relay.rs | crate: router use actix_web::{web, Responder}; use router_env::{instrument, tracing, Flow}; use crate::{ self as app, core::{api_locking, relay}, services::{api, authentication as auth}, }; pub async fn relay_retrieve( state: web::Data<app::AppState>, path: web::Path<common_utils::id_type::RelayId>, req: actix_web::HttpRequest, query_params: web::Query<api_models::relay::RelayRetrieveBody>, ) -> impl Responder { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/routes/relay.rs | crate: router use actix_web::{web, Responder}; use router_env::{instrument, tracing, Flow}; use crate::{ self as app, core::{api_locking, relay}, services::{api, authentication as auth}, }; pub async fn relay( state: web::Data<app::AppState>, req: actix_web::HttpRequest, payload: web::Json<api_models::relay::RelayRequest>, ) -> impl Responder { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/routes/metrics/bg_metrics_collector.rs | crate: router use storage_impl::redis::cache; pub fn spawn_metrics_collector(metrics_collection_interval_in_secs: Option<u16>) { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/routes/process_tracker/revenue_recovery.rs | crate: router use actix_web::{web, HttpRequest, HttpResponse}; use api_models::process_tracker::revenue_recovery as revenue_recovery_api; use router_env::Flow; use crate::{ core::{api_locking, revenue_recovery}, routes::AppState, services::{api, authentication as auth, authorization::permissions::Permission}, }; pub async fn revenue_recovery_pt_retrieve_api( state: web::Data<AppState>, req: HttpRequest, path: web::Path<common_utils::id_type::GlobalPaymentId>, ) -> HttpResponse { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/services/kafka/dispute_event.rs | crate: router use crate::types::storage::dispute::Dispute; pub fn from_storage(dispute: &'a Dispute) -> Self { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/services/kafka/authentication_event.rs | crate: router use diesel_models::{authentication::Authentication, enums as storage_enums}; pub fn from_storage(authentication: &'a Authentication) -> Self { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch-card-vault/benches/encryption.rs | crate: benches use criterion::{black_box, criterion_group, criterion_main, Criterion}; use josekit::jwe; use rand::rngs::OsRng; use rsa::{pkcs8::EncodePrivateKey, pkcs8::EncodePublicKey, RsaPrivateKey, RsaPublicKey}; use tartarus::crypto::encryption_manager::{ encryption_interface::Encryption, managers::{aes, jw}, }; pub fn criterion_jwe_jws(c: &mut Criterion) { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch-card-vault/benches/encryption.rs | crate: benches use criterion::{black_box, criterion_group, criterion_main, Criterion}; use rand::rngs::OsRng; use tartarus::crypto::encryption_manager::{ encryption_interface::Encryption, managers::{aes, jw}, }; pub fn criterion_aes(c: &mut Criterion) { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch-card-vault/benches/hashing.rs | crate: benches use criterion::{black_box, criterion_group, criterion_main, Criterion}; use tartarus::crypto::hash_manager::{hash_interface::Encode, managers::sha::HmacSha512}; pub fn criterion_hmac_sha512(c: &mut Criterion) { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch-card-vault/src/middleware.rs | crate: src use crate::{ crypto::encryption_manager::{ encryption_interface::Encryption, managers::jw::{self, JWEncryption}, }, error::{self, ContainerError, ResultContainerExt}, }; use crate::custom_extractors::TenantStateResolver; use axum::body::Body; use axum::http::{request, response}; use axum::{http::Request, middleware::Next}; use josekit::jwe; /// Middleware providing implementation to perform JWE + JWS encryption and decryption around the /// card APIs pub async fn middleware( TenantStateResolver(state): TenantStateResolver, parts: request::Parts, axum::Json(jwe_body): axum::Json<jw::JweBody>, next: Next, ) -> Result<(response::Parts, axum::Json<jw::JweBody>), ContainerError<error::ApiError>> { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/analytics/src/payments/metrics/retries_count.rs | crate: analytics use std::collections::HashSet; use api_models::{ analytics::{ payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier}, Granularity, TimeRange, }, enums::IntentStatus, }; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::PaymentMetricRow; use crate::{ enums::AuthInfo, query::{ Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window, }, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; async fn load_metrics( &self, _dimensions: &[PaymentDimensions], auth: &AuthInfo, _filters: &PaymentFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
// file: hyperswitch/crates/analytics/src/payments/metrics/avg_ticket_size.rs | crate: analytics use std::collections::HashSet; use api_models::analytics::{ payments::{PaymentDimensions, PaymentFilters, PaymentMetricsBucketIdentifier}, Granularity, TimeRange, }; use diesel_models::enums as storage_enums; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::{PaymentMetric, PaymentMetricRow}; use crate::{ enums::AuthInfo, query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; async fn load_metrics( &self, dimensions: &[PaymentDimensions], auth: &AuthInfo, filters: &PaymentFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Payment); 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(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) .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 .add_filter_clause( PaymentDimensions::PaymentStatus, storage_enums::AttemptStatus::Charged, ) .switch()?; query_builder .execute_query::<PaymentMetricRow, _>(pool) .await .change_context(MetricsError::QueryBuildingError)? .change_context(MetricsError::QueryExecutionFailure)? .into_iter() .map(|i| { Ok(( PaymentMetricsBucketIdentifier::new( i.currency.as_ref().map(|i| i.0), i.status.as_ref().map(|i| i.0), i.connector.clone(), i.authentication_type.as_ref().map(|i| i.0), i.payment_method.clone(), i.payment_method_type.clone(), i.client_source.clone(), i.client_version.clone(), i.profile_id.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<(PaymentMetricsBucketIdentifier, PaymentMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/analytics/src/api_event/events.rs | crate: analytics use api_models::analytics::{ api_event::{ApiLogsRequest, QueryType}, Granularity, }; use common_utils::errors::ReportSwitchExt; use router_env::Flow; use time::PrimitiveDateTime; use crate::{ query::{Aggregate, GroupByClause, QueryBuilder, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, FiltersError, FiltersResult, LoadRow}, }; 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>, { <|fim_suffix|> <|fim_middle|> }
ast_fragments
// file: hyperswitch/crates/analytics/src/api_event/metrics/latency.rs | crate: analytics 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}, }; 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) }
ast_fragments
// file: hyperswitch/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_intent_count.rs | crate: analytics use std::collections::HashSet; use api_models::analytics::{ payment_intents::{ PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetricsBucketIdentifier, }, Granularity, TimeRange, }; 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}, }; 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::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) .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::<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) }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/analytics/src/payment_intents/metrics/sessionized_metrics/payment_processed_amount.rs | crate: analytics use std::collections::HashSet; use api_models::analytics::{ payment_intents::{ PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetricsBucketIdentifier, }, Granularity, TimeRange, }; 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}, }; 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);<|fim_suffix|> <|fim_middle|> 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)}}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/analytics/src/sdk_events/metrics/payment_method_selected_count.rs | crate: analytics use std::collections::HashSet; use api_models::analytics::{ sdk_events::{ SdkEventDimensions, SdkEventFilters, SdkEventMetricsBucketIdentifier, SdkEventNames, }, Granularity, TimeRange, }; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::SdkEventMetricRow; use crate::{ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; async fn load_metrics( &self, dimensions: &[SdkEventDimensions], publishable_key: &str, filters: &SdkEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/analytics/src/frm/metrics/frm_blocked_rate.rs | crate: analytics use api_models::analytics::{ frm::{FrmDimensions, FrmFilters, FrmMetricsBucketIdentifier}, Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use super::FrmMetricRow; use crate::{ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; 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, { <|fim_suffix|> <|fim_middle|> }
ast_fragments
// file: hyperswitch/crates/analytics/src/auth_events/metrics.rs | crate: analytics use std::collections::HashSet; use api_models::analytics::{ auth_events::{ AuthEventDimensions, AuthEventFilters, AuthEventMetrics, AuthEventMetricsBucketIdentifier, }, Granularity, TimeRange, }; use crate::{ query::{Aggregate, GroupByClause, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, DBEnumWrapper, LoadRow, MetricsResult}, }; use authentication_attempt_count::AuthenticationAttemptCount; use authentication_count::AuthenticationCount; use authentication_error_message::AuthenticationErrorMessage; use authentication_funnel::AuthenticationFunnel; use authentication_success_count::AuthenticationSuccessCount; use challenge_attempt_count::ChallengeAttemptCount; use challenge_flow_count::ChallengeFlowCount; use challenge_success_count::ChallengeSuccessCount; use frictionless_flow_count::FrictionlessFlowCount; use frictionless_success_count::FrictionlessSuccessCount; async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, dimensions: &[AuthEventDimensions], filters: &AuthEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { match self { Self::AuthenticationCount => { AuthenticationCount .load_metrics( merchant_id, dimensions, filters, granularity, time_range, pool, ) .await } Self::AuthenticationAttemptCount => { AuthenticationAttemptCount .load_metrics( merchant_id, dimensions, filters, granularity, time_range, pool, ) .await } Self::AuthenticationSuccessCount => { AuthenticationSuccessCount .load_metrics( merchant_id, dimensions, filters, granularity, time_range, pool, ) .await } Self::ChallengeFlowCount => { ChallengeFlowCount .load_metrics( merchant_id, dimensions, filters, granularity, time_range, pool, ) .await } Self::ChallengeAttemptCount => { ChallengeAttemptCount .load_metrics( merchant_id, dimensions, filters, granularity, time_range, pool, ) .await } Self::ChallengeSuccessCount => { ChallengeSuccessCount .load_metrics( merchant_id, dimensions, filters, granularity, time_range, pool, ) .await } Self::FrictionlessFlowCount => { FrictionlessFlowCount .load_metrics( merchant_id, dimensions, filters, granularity, time_range, pool, ) .await } Self::FrictionlessSuccessCount => { FrictionlessSuccessCount .load_metrics( merchant_id, dimensions, filters, granularity, time_range, pool, ) .await } Self::AuthenticationErrorMessage => { AuthenticationErrorMessage .load_metrics( merchant_id, dimensions, filters, granularity, time_range, pool, ) .await } Self::AuthenticationFunnel => { AuthenticationFunnel .load_metrics( merchant_id, dimensions, filters, granularity, time_range, pool, ) .await } } }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs | crate: analytics use std::collections::HashSet; use api_models::analytics::{ auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, Granularity, TimeRange, }; use common_enums::{AuthenticationStatus, DecoupledAuthenticationType}; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::AuthEventMetricRow; use crate::{ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, dimensions: &[AuthEventDimensions], filters: &AuthEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs | crate: analytics use std::collections::HashSet; use api_models::analytics::{ auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetricsBucketIdentifier}, Granularity, TimeRange, }; use common_enums::{AuthenticationStatus, DecoupledAuthenticationType}; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::AuthEventMetricRow; use crate::{ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; async fn load_metrics( &self, merchant_id: &common_utils::id_type::MerchantId, dimensions: &[AuthEventDimensions], filters: &AuthEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(AuthEventMetricsBucketIdentifier, AuthEventMetricRow)>> { { (Some(g), Some(st)) => g.clip_to_start(st)?,<|fim_suffix|> <|fim_middle|> _ => time_range.start_time, } }
ast_fragments
// file: hyperswitch/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_success_rate.rs | crate: analytics use std::collections::HashSet; use api_models::analytics::{ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier}, Granularity, TimeRange, }; use error_stack::ResultExt; use super::RefundMetricRow; use crate::{ enums::AuthInfo, query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; async fn load_metrics( &self, dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> where T: AnalyticsDataSource + super::RefundMetricAnalytics, { let mut query_builder = QueryBuilder::new(AnalyticsCollection::RefundSessionized); let mut dimensions = dimensions.to_vec(); dimensions.push(RefundDimensions::RefundStatus); 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()?; auth.set_filter_clause(&mut query_builder).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::<RefundMetricRow, _>(pool) .await .change_context(MetricsError::QueryBuildingError)? .change_context(MetricsError::QueryExecutionFailure)? .into_iter() .map(|i| { Ok(( RefundMetricsBucketIdentifier::new( i.currency.as_ref().map(|i| i.0), None, i.connector.clone(), i.refund_type.as_ref().map(|i| i.0.to_string()), i.profile_id.clone(), i.refund_reason.clone(), i.refund_error_message.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<(RefundMetricsBucketIdentifier, RefundMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/analytics/src/refunds/metrics/sessionized_metrics/refund_reason.rs | crate: analytics use std::collections::HashSet; use api_models::analytics::{ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier}, Granularity, TimeRange, }; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::RefundMetricRow; use crate::{ enums::AuthInfo, query::{ Aggregate, FilterTypes, GroupByClause, Order, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window, }, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; async fn load_metrics( &self, dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(RefundMetricsBucketIdentifier, RefundMetricRow)>> { {let mut inner_query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::RefundSessionized);<|fim_suffix|> <|fim_middle|> outer_query_builder .execute_query::<RefundMetricRow, _>(pool) .await .change_context(MetricsError::QueryBuildingError)? .change_context(MetricsError::QueryExecutionFailure)? .into_iter() .map(|i| { Ok(( RefundMetricsBucketIdentifier::new( i.currency.as_ref().map(|i| i.0), None, i.connector.clone(), i.refund_type.as_ref().map(|i| i.0.to_string()), i.profile_id.clone(), i.refund_reason.clone(), i.refund_error_message.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<(RefundMetricsBucketIdentifier, RefundMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure)}}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/analytics/src/refunds/distribution/sessionized_distribution/refund_reason.rs | crate: analytics use api_models::analytics::{ refunds::{RefundDimensions, RefundFilters, RefundMetricsBucketIdentifier}, Granularity, RefundDistributionBody, TimeRange, }; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::{RefundDistribution, RefundDistributionRow}; use crate::{ enums::AuthInfo, query::{ Aggregate, GroupByClause, Order, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window, }, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; async fn load_distribution( &self, distribution: &RefundDistributionBody, dimensions: &[RefundDimensions], auth: &AuthInfo, filters: &RefundFilters, granularity: &Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<Vec<(RefundMetricsBucketIdentifier, RefundDistributionRow)>> { {let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::RefundSessionized);<|fim_suffix|> <|fim_middle|> query_builder .execute_query::<RefundDistributionRow, _>(pool) .await .change_context(MetricsError::QueryBuildingError)? .change_context(MetricsError::QueryExecutionFailure)? .into_iter() .map(|i| { Ok(( RefundMetricsBucketIdentifier::new( i.currency.as_ref().map(|i| i.0), i.refund_status.as_ref().map(|i| i.0.to_string()), i.connector.clone(), i.refund_type.as_ref().map(|i| i.0.to_string()), i.profile_id.clone(), i.refund_reason.clone(), i.refund_error_message.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< Vec<(RefundMetricsBucketIdentifier, RefundDistributionRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure)}}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/routes/payments/helpers.rs | crate: router use error_stack::ResultExt; use crate::{ core::errors::{self, RouterResult}, logger, types::{self, api}, utils::{Encode, ValueExt}, }; pub fn populate_browser_info( req: &actix_web::HttpRequest, payload: &mut api::PaymentsRequest, header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<()> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/services/pm_auth.rs | crate: router use pm_auth::{ consts, core::errors::ConnectorError, types::{self as pm_auth_types, api::BoxedConnectorIntegration, PaymentAuthRouterData}, }; use crate::{ core::errors::{self}, logger, routes::SessionState, services::{self}, }; pub async fn execute_connector_processing_step<'b, T, Req, Resp>( state: &'b SessionState, connector_integration: BoxedConnectorIntegration<'_, T, Req, Resp>, req: &'b PaymentAuthRouterData<T, Req, Resp>, connector: &pm_auth_types::PaymentMethodAuthConnectors, ) -> errors::CustomResult<PaymentAuthRouterData<T, Req, Resp>, ConnectorError> where T: Clone + 'static, Req: Clone + 'static, Resp: Clone + 'static, { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/euclid/src/frontend/dir/transformers.rs | crate: euclid use crate::{dirval, dssa::types::AnalysisErrorType, enums as global_enums, frontend::dir}; fn into_dir_value(self) -> Result<dir::DirValue, AnalysisErrorType> { <|fim_suffix|> <|fim_middle|> }
ast_fragments
<|fim_prefix|> // file: hyperswitch/crates/router/src/compatibility/wrap.rs | crate: router use std::{future::Future, sync::Arc, time::Instant}; use actix_web::{HttpRequest, HttpResponse, Responder}; use common_utils::errors::{CustomResult, ErrorSwitch}; use router_env::{instrument, tracing, Tag}; use serde::Serialize; use crate::{ core::{api_locking, errors}, events::api_logs::ApiEventMetric, routes::{ app::{AppStateInfo, ReqState}, metrics, AppState, SessionState, }, services::{self, api, authentication as auth, logger}, }; pub async fn compatibility_api_wrap<'a, 'b, U, T, Q, F, Fut, S, E, E2>( flow: impl router_env::types::FlowMetric, state: Arc<AppState>, request: &'a HttpRequest, payload: T, func: F, api_authentication: &dyn auth::AuthenticateAndFetch<U, SessionState>, lock_action: api_locking::LockAction, ) -> HttpResponse where F: Fn(SessionState, U, T, ReqState) -> Fut, Fut: Future<Output = CustomResult<api::ApplicationResponse<Q>, E2>>, E2: ErrorSwitch<E> + std::error::Error + Send + Sync + 'static, Q: Serialize + std::fmt::Debug + 'a + ApiEventMetric, S: TryFrom<Q> + Serialize, E: Serialize + error_stack::Context + actix_web::ResponseError + Clone, error_stack::Report<E>: services::EmbedError, errors::ApiErrorResponse: ErrorSwitch<E>, T: std::fmt::Debug + Serialize + ApiEventMetric, { {<|fim_suffix|> <|fim_middle|> }}
ast_fragments
# file: hyperswitch-encryption-service/Cargo.toml | crate: Cargo.toml [dependencies] cargo_metadata = "0.18.1" error-stack = "0.4.1" thiserror = "1.0.58" aws-config = { version = "1.5.0" } aws-sdk-kms = { version = "1.29.0" } axum = { version = "0.7.5", features = ["macros"] } axum-server = {git = "https://github.com/dracarys18/axum-server.git",rev ="5430efefd14b43cbbc8e4faa50ff9274b8b8b7aa"} base64 = "0.22.1" tokio = { version = "1.37.0", features = ["macros", "rt-multi-thread"] } tower-http = {version = "0.5.2", features = ["trace","request-id","util"] } ulid = "1.1.2" tower = "0.4.13" trace = "0.1.7" tracing = "0.1.40" tracing-subscriber = {version = "0.3.18", default-features = true, features = ["env-filter", "json", "registry"] } tracing-appender = "0.2.3" opentelemetry = { version = "0.23.0", features = ["metrics"] } opentelemetry_sdk = { version = "0.23.0", features = ["metrics"] } opentelemetry-prometheus = "0.16.0" prometheus = "0.13.4" serde = { version = "1.0.202", features = ["derive"] } serde_json = "1.0.117" tokio-postgres = { version = "0.7.10", optional = true } tokio-postgres-rustls = { version = "0.13.0", optional = true } masking = { git = "https://github.com/juspay/hyperswitch.git",tag = "2024.12.17.0",features = ["cassandra"] } async-trait = "0.1.80" hex = "0.4.3" charybdis = { git = "https://github.com/dracarys18/charybdis.git", rev = "1637c263f512adf7840705e3ab405a113437a6e3" } scylla = { git = "https://github.com/juspay/scylla-rust-driver.git",rev = "5700aa2847b25437cdd4fcf34d707aa90dca8b89", features = ["time-03"]} ring = { version = "0.17.8", features = ["std"] } strum = { version = "0.26", features = ["derive"] } futures = "0.3.30" time = { version = "0.3.36", features = ["parsing"]} diesel = { version = "2.2.4", features = ["postgres", "serde_json", "time"] } diesel-async = { version = "0.5.2", features = ["postgres", "bb8"] } config = { version = "0.14.0", features = ["toml"] } serde_path_to_error = "0.1.16" moka = { version = "0.12", default-features = false, features = ["future"]} rustls-native-certs = { version="0.8.1", optional = true } rustls = { version = "0.23.10", default-features = false,features = ["std"], optional = true} rustls-pemfile = { version = "2.1.2", default-features = false, features = ["std"], optional=true } rustc-hash = "1.1.0" rayon = "1.10.0" once_cell = "1.19.0" hyper = "1.3.1" blake3 = "1.5.4" vaultrs = { version = "0.7.2" }
ast_fragments
# file: hyperswitch-encryption-service/Cargo.toml | crate: Cargo.toml [package] name = "cripta" version = "0.1.0" edition = "2021" rust-version = "1.78"
ast_fragments
# file: hyperswitch-encryption-service/Cargo.toml | crate: Cargo.toml [patch.crates-io] tokio-rustls = { git = "https://github.com/rustls/tokio-rustls", rev = "3a153acec6c4d189eb5de501b2155b4484b8651b" } # main # All the AES,AWS,Vault features will be used as a runtime feature flag rather than compiletime
ast_fragments
# file: hyperswitch-encryption-service/Cargo.toml | crate: Cargo.toml [features] aes = [] mtls = ["dep:rustls", "dep:rustls-pemfile", "axum-server/tls-rustls"] aws = [] release = ["aws", "mtls", "postgres_ssl"] vault = [] postgres_ssl = ["dep:rustls", "dep:rustls-native-certs", "dep:rustls-pemfile", "dep:tokio-postgres", "dep:tokio-postgres-rustls"] cassandra = []
ast_fragments
# file: hyperswitch-encryption-service/Cargo.toml | crate: Cargo.toml [dev-dependencies] criterion = "0.5.1" rand = "0.8.5"
ast_fragments
# file: hyperswitch-encryption-service/Cargo.toml | crate: Cargo.toml [build-dependencies] cargo_metadata = "0.18.1"
ast_fragments
# file: hyperswitch-encryption-service/Cargo.toml | crate: Cargo.toml [lints.rust] unsafe_code = "forbid" rust_2018_idioms = { level = "warn", priority = -1 }
ast_fragments
# file: hyperswitch-encryption-service/diesel.toml | crate: diesel.toml [print_schema] file = "src/schema.rs" import_types = ["diesel::sql_types::*"] generate_missing_sql_type_definitions = false
ast_fragments
# file: hyperswitch-encryption-service/config/development.toml | crate: config [metrics_server] host = "127.0.0.1" port = 6128
ast_fragments
# file: hyperswitch-encryption-service/config/development.toml | crate: config [server] host = "127.0.0.1" port = 5000
ast_fragments
# file: hyperswitch-encryption-service/config/development.toml | crate: config [database] user = "db_user" password = "db_pass" host = "localhost" port = 5432 dbname = "encryption_db" pool_size = 5 min_idle = 2 enable_ssl = false
ast_fragments
# file: hyperswitch-encryption-service/config/development.toml | crate: config [multitenancy.tenants.public] cache_prefix = "public" schema = "public"
ast_fragments
# file: hyperswitch-encryption-service/config/development.toml | crate: config [multitenancy.tenants.global] cache_prefix = "global" schema = "global"
ast_fragments
# file: hyperswitch-encryption-service/config/development.toml | crate: config [log] log_level = "debug" log_format = "console"
ast_fragments
# file: hyperswitch-encryption-service/config/development.toml | crate: config [secrets] master_key = "6d761d32f1b14ef34cf016d726b29b02b5cfce92a8959f1bfb65995c8100925e" access_token = "secret123" hash_context = "keymanager:hyperswitch"
ast_fragments
# file: hyperswitch/Cargo.toml [workspace.lints.clippy] as_conversions = "warn" cloned_instead_of_copied = "warn" dbg_macro = "warn" expect_used = "warn" fn_params_excessive_bools = "warn" index_refutable_slice = "warn" indexing_slicing = "warn" large_futures = "warn" match_on_vec_items = "warn" missing_panics_doc = "warn" mod_module_files = "warn" out_of_bounds_indexing = "warn" panic = "warn" panic_in_result_fn = "warn" panicking_unwrap = "warn" print_stderr = "warn" print_stdout = "warn" todo = "warn" trivially_copy_pass_by_ref = "warn" unimplemented = "warn" unnecessary_self_imports = "warn" unreachable = "warn" unwrap_in_result = "warn" unwrap_used = "warn" use_self = "warn" wildcard_dependencies = "warn" # Lints to allow option_map_unit_fn = "allow"
ast_fragments
# file: hyperswitch/Cargo.toml [workspace] resolver = "2" members = ["crates/*"] exclude = ["crates/openapi"] package.edition = "2021" package.rust-version = "1.80.0" package.license = "Apache-2.0"
ast_fragments
# file: hyperswitch/Cargo.toml [workspace.dependencies] tracing = { version = "0.1.40" } # Most of the lint configuration is based on https://github.com/EmbarkStudios/rust-ecosystem/blob/main/lints.toml
ast_fragments
# file: hyperswitch/Cargo.toml [workspace.lints.rust] unsafe_code = "forbid" rust_2018_idioms = { level = "warn", priority = -1 } # Remove priority once https://github.com/rust-lang/rust-clippy/pull/12827 is available in stable clippy unused_qualifications = "warn" # missing_debug_implementations = "warn" # missing_docs = "warn"
ast_fragments
# file: hyperswitch/Cargo.toml [profile.release] strip = true lto = true codegen-units = 1
ast_fragments
# file: hyperswitch/diesel_v2.toml [print_schema] file = "crates/diesel_models/src/schema_v2.rs" import_types = ["diesel::sql_types::*", "crate::enums::diesel_exports::*"] generate_missing_sql_type_definitions = false
ast_fragments
# file: hyperswitch/cog.toml [commit_types] feat = { changelog_title = "<!-- 0 -->Features" } fix = { changelog_title = "<!-- 1 -->Bug Fixes" } perf = { changelog_title = "<!-- 2 -->Performance" } refactor = { changelog_title = "<!-- 3 -->Refactors" } test = { changelog_title = "<!-- 4 -->Testing" } docs = { changelog_title = "<!-- 5 -->Documentation" } chore = { changelog_title = "<!-- 6 -->Miscellaneous Tasks" } build = { changelog_title = "<!-- 7 -->Build System / Dependencies" } ci = { changelog_title = "Continuous Integration", omit_from_changelog = true }
ast_fragments
# file: hyperswitch/cog.toml [changelog] path = "CHANGELOG.md" template = ".github/cocogitto-changelog-template" remote = "github.com" owner = "juspay" repository = "hyperswitch"
ast_fragments
# file: hyperswitch/.deepsource.toml [analyzers.meta] msrv = "1.80.0"
ast_fragments
<|meta_start|><|file|> hyperswitch/package.json<|meta_end|> { "name": "hyperswitch", "version": "0.0.0", "private": true, "description": "This is just to run automated newman tests for this service", "devDependencies": { "newman": "git+ssh://git@github.com:knutties/newman.git#7106e194c15d49d066fa09d9a2f18b2238f3dba8" } }
ast_fragments
# file: hyperswitch/diesel.toml [print_schema] file = "crates/diesel_models/src/schema.rs" import_types = ["diesel::sql_types::*", "crate::enums::diesel_exports::*"] generate_missing_sql_type_definitions = false patch_file="crates/diesel_models/drop_id.patch"
ast_fragments
# file: hyperswitch/.typos.toml [default.extend-identifiers] ABD = "ABD" # Aberdeenshire, UK ISO 3166-2 code ACTIVITE = "ACTIVITE" # French translation of activity AER = "AER" # An alias to Api Error Response ANG = "ANG" # Netherlands Antillean guilder currency code BA = "BA" # Bosnia and Herzegovina country code bottm = "bottm" # name of a css class for nexinets ui test CAF = "CAF" # Central African Republic country code FO = "FO" # Faroe Islands (the) country code flate2 = "flate2" hd = "hd" # animation data parameter HypoNoeLbFurNiederosterreichUWien = "HypoNoeLbFurNiederosterreichUWien" hypo_noe_lb_fur_niederosterreich_u_wien = "hypo_noe_lb_fur_niederosterreich_u_wien" IOT = "IOT" # British Indian Ocean Territory country code klick = "klick" # Swedish word for clicks FPR = "FPR" # Fraud Prevention Rules LSO = "LSO" # Lesotho country code NAM = "NAM" # Namibia country code ND = "ND" # North Dakota state code optin = "optin" # Boku preflow name optin_id = "optin_id" # Boku's id for optin flow passord = "passord" # name of a css class for adyen ui test payment_vas = "payment_vas" PaymentVas = "PaymentVas" PN = "PN" # Pitcairn country code RegioBank = "RegioBank" RO = "RO" # Romania country code skip_ws = "skip_ws" # skip white space SOM = "SOM" # Somalia country code SUR = "SUR" # Single South American currency code THA = "THA" # Thailand country code TTO = "TTO" # Trinidad and Tobago country code WS = "WS" # Samoa country code ws = "ws" # Web socket ws2ipdef = "ws2ipdef" # WinSock Extension ws2tcpip = "ws2tcpip" # WinSock Extension ZAR = "ZAR" # South African Rand currency code JOD = "JOD" # Jordan currency code Payed = "Payed" # Paid status for digital virgo SessionConnectorDatas = "SessionConnectorDatas" # Wrapper for List of SessionConnectorData Alo = "Alo" # Is iso representation of a state in France alo = "alo" # Is iso representation of a state in France BRE = "BRE" # Is iso representation of Brittany VasCounty = "VasCounty" # Is a state in Hungary StipMunicipality = "StipMunicipality" # Is a municipality in North Macedonia HAV = "HAV" # Is iso representation of a state in UK LEW = "LEW" # Is iso representation of a state in UK THR = "THR" # Is iso representation of a state in UK WLL = "WLL" # Is iso representation of a state in UK WIL = "WIL" # Is iso representation of a state in UK YOR = "YOR" # Is iso representation of a state in UK OT = "OT" # Is iso representation of a state in Romania OltCounty = "OltCounty" # Is a state in Romania Olt = "Olt" # Is iso representation of a state in Romania Vas = "Vas" # Is iso representation of a state in Hungary vas = "vas" # Is iso representation of a state in Hungary WHT = "WHT" # Is iso representation of a state in Belgium CantonOfEschSurAlzette = "CantonOfEschSurAlzette" # Is a state in Luxembourg GorenjaVasPoljane = "GorenjaVasPoljane" # Is a state in Slovenia sur = "sur" # Is iso representation of a state in Luxembourg Corse = "Corse" # Is a state in France CorseDuSud = "CorseDuSud" # Is a state in France Gard = "Gard" # Is a state in France HauteCorse = "HauteCorse" # Is a state in France Somme = "Somme" # Is a state in France RaceFram = "RaceFram" # Is a state in France TrnovskaVas = "TrnovskaVas" # Is a state in Slovenia Corse-du-Sud = "Corse-du-Sud" # Is a state in France Haute-Corse = "Haute-Corse" # Is a state in France Fram = "Fram" # Is a state in Slovenia
ast_fragments
# file: hyperswitch/.typos.toml [default] check-filename = true extend-ignore-identifiers-re = [ "UE_[0-9]{3,4}", # Unified error codes ]
ast_fragments
# file: hyperswitch/.typos.toml [default.extend-words] aci = "aci" # Name of a connector afe = "afe" # Commit id ba = "ba" # ignore minor commit conversions daa = "daa" # Commit id deriver = "deriver" ede = "ede" # ignore minor commit conversions encrypter = "encrypter" # Used by the `ring` crate guid = "guid" # globally unique identifier Hashi = "Hashi" # HashiCorp iin = "iin" # Card iin kms = "kms" # Key management service nin = "nin" # National identification number, a field used by PayU connector requestor = "requestor" #Used in external 3ds flows substituters = "substituters" # Present in `flake.nix` unsuccess = "unsuccess" # Used in cryptopay request
ast_fragments
# file: hyperswitch/.typos.toml [files] extend-exclude = [ "config/redis.conf", # `typos` also checked "AKE" in the file, which is present as a quoted string "openapi/open_api_spec.yaml", # no longer updated "crates/router/src/utils/user/blocker_emails.txt", # this file contains various email domains "CHANGELOG.md", # This file contains all the commits "crates/router/locales/*.yml", # locales "crates/router/src/core/payment_link/locale.js", # this file contains conversion of static strings in various languages ]
ast_fragments