id
stringlengths
11
116
type
stringclasses
1 value
granularity
stringclasses
4 values
content
stringlengths
16
477k
metadata
dict
fn_clm_router_get_outgoing_webhook_content_and_event_type_4090695360850491449
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/outgoing_webhook_retry async fn get_outgoing_webhook_content_and_event_type( state: SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, key_store: domain::MerchantKeyStore, tracking_data: &OutgoingWebhookTrackingData, ) -> Result<(OutgoingWebhookContent, Option<EventType>), errors::ProcessTrackerError> { use api_models::{ disputes::DisputeRetrieveRequest, mandates::MandateId, payments::{PaymentIdType, PaymentsResponse, PaymentsRetrieveRequest}, refunds::{RefundResponse, RefundsRetrieveRequest}, }; use crate::{ core::{ disputes::retrieve_dispute, mandate::get_mandate, payments::{payments_core, CallConnectorAction, PaymentStatus}, refunds::refund_retrieve_core_with_refund_id, }, services::{ApplicationResponse, AuthFlow}, types::{api::PSync, transformers::ForeignFrom}, }; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context( merchant_account.clone(), key_store.clone(), ))); match tracking_data.event_class { diesel_models::enums::EventClass::Payments => { let payment_id = tracking_data.primary_object_id.clone(); let payment_id = id_type::PaymentId::try_from(std::borrow::Cow::Owned(payment_id)) .map_err(|payment_id_parsing_error| { logger::error!( ?payment_id_parsing_error, "Failed to parse payment ID from tracking data" ); errors::ProcessTrackerError::DeserializationFailed })?; let request = PaymentsRetrieveRequest { resource_id: PaymentIdType::PaymentIntentId(payment_id), merchant_id: Some(tracking_data.merchant_id.clone()), force_sync: false, ..Default::default() }; let payments_response = match Box::pin(payments_core::< PSync, PaymentsResponse, _, _, _, payments::PaymentData<PSync>, >( state, req_state, merchant_context.clone(), None, PaymentStatus, request, AuthFlow::Client, CallConnectorAction::Avoid, None, hyperswitch_domain_models::payments::HeaderPayload::default(), )) .await? { ApplicationResponse::Json(payments_response) | ApplicationResponse::JsonWithHeaders((payments_response, _)) => { Ok(payments_response) } ApplicationResponse::StatusOk | ApplicationResponse::TextPlain(_) | ApplicationResponse::JsonForRedirection(_) | ApplicationResponse::Form(_) | ApplicationResponse::GenericLinkForm(_) | ApplicationResponse::PaymentLinkForm(_) | ApplicationResponse::FileData(_) => { Err(errors::ProcessTrackerError::ResourceFetchingFailed { resource_name: tracking_data.primary_object_id.clone(), }) } }?; let event_type: Option<EventType> = payments_response.status.into(); logger::debug!(current_resource_status=%payments_response.status); Ok(( OutgoingWebhookContent::PaymentDetails(Box::new(payments_response)), event_type, )) } diesel_models::enums::EventClass::Refunds => { let refund_id = tracking_data.primary_object_id.clone(); let request = RefundsRetrieveRequest { refund_id, force_sync: Some(false), merchant_connector_details: None, }; let refund = Box::pin(refund_retrieve_core_with_refund_id( state, merchant_context.clone(), None, request, )) .await?; let event_type: Option<EventType> = refund.refund_status.into(); logger::debug!(current_resource_status=%refund.refund_status); let refund_response = RefundResponse::foreign_from(refund); Ok(( OutgoingWebhookContent::RefundDetails(Box::new(refund_response)), event_type, )) } diesel_models::enums::EventClass::Disputes => { let dispute_id = tracking_data.primary_object_id.clone(); let request = DisputeRetrieveRequest { dispute_id, force_sync: None, }; let dispute_response = match Box::pin(retrieve_dispute( state, merchant_context.clone(), None, request, )) .await? { ApplicationResponse::Json(dispute_response) | ApplicationResponse::JsonWithHeaders((dispute_response, _)) => { Ok(dispute_response) } ApplicationResponse::StatusOk | ApplicationResponse::TextPlain(_) | ApplicationResponse::JsonForRedirection(_) | ApplicationResponse::Form(_) | ApplicationResponse::GenericLinkForm(_) | ApplicationResponse::PaymentLinkForm(_) | ApplicationResponse::FileData(_) => { Err(errors::ProcessTrackerError::ResourceFetchingFailed { resource_name: tracking_data.primary_object_id.clone(), }) } } .map(Box::new)?; let event_type = Some(EventType::from(dispute_response.dispute_status)); logger::debug!(current_resource_status=%dispute_response.dispute_status); Ok(( OutgoingWebhookContent::DisputeDetails(dispute_response), event_type, )) } diesel_models::enums::EventClass::Mandates => { let mandate_id = tracking_data.primary_object_id.clone(); let request = MandateId { mandate_id }; let mandate_response = match get_mandate(state, merchant_context.clone(), request).await? { ApplicationResponse::Json(mandate_response) | ApplicationResponse::JsonWithHeaders((mandate_response, _)) => { Ok(mandate_response) } ApplicationResponse::StatusOk | ApplicationResponse::TextPlain(_) | ApplicationResponse::JsonForRedirection(_) | ApplicationResponse::Form(_) | ApplicationResponse::GenericLinkForm(_) | ApplicationResponse::PaymentLinkForm(_) | ApplicationResponse::FileData(_) => { Err(errors::ProcessTrackerError::ResourceFetchingFailed { resource_name: tracking_data.primary_object_id.clone(), }) } } .map(Box::new)?; let event_type: Option<EventType> = mandate_response.status.into(); logger::debug!(current_resource_status=%mandate_response.status); Ok(( OutgoingWebhookContent::MandateDetails(mandate_response), event_type, )) } #[cfg(feature = "payouts")] diesel_models::enums::EventClass::Payouts => { let payout_id = tracking_data.primary_object_id.clone(); let request = payout_models::PayoutRequest::PayoutActionRequest( payout_models::PayoutActionRequest { payout_id: id_type::PayoutId::try_from(std::borrow::Cow::Owned(payout_id))?, }, ); let payout_data = Box::pin(payouts::make_payout_data( &state, &merchant_context, None, &request, DEFAULT_LOCALE, )) .await?; let payout_create_response = payouts::response_handler(&state, &merchant_context, &payout_data).await?; let event_type: Option<EventType> = payout_data.payout_attempt.status.into(); logger::debug!(current_resource_status=%payout_data.payout_attempt.status); Ok(( OutgoingWebhookContent::PayoutDetails(Box::new(payout_create_response)), event_type, )) } } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 104, "total_crates": null }
fn_clm_router_get_webhook_delivery_retry_schedule_time_4090695360850491449
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/outgoing_webhook_retry pub(crate) async fn get_webhook_delivery_retry_schedule_time( db: &dyn StorageInterface, merchant_id: &id_type::MerchantId, retry_count: i32, ) -> Option<time::PrimitiveDateTime> { let key = "pt_mapping_outgoing_webhooks"; let result = db .find_config_by_key(key) .await .map(|value| value.config) .and_then(|config| { config .parse_struct("OutgoingWebhookRetryProcessTrackerMapping") .change_context(errors::StorageError::DeserializationFailed) }); let mapping = result.map_or_else( |error| { if error.current_context().is_db_not_found() { logger::debug!("Outgoing webhooks retry config `{key}` not found, ignoring"); } else { logger::error!( ?error, "Failed to read outgoing webhooks retry config `{key}`" ); } process_data::OutgoingWebhookRetryProcessTrackerMapping::default() }, |mapping| { logger::debug!(?mapping, "Using custom outgoing webhooks retry config"); mapping }, ); let time_delta = scheduler_utils::get_outgoing_webhook_retry_schedule_time( mapping, merchant_id, retry_count, ); scheduler_utils::get_time_from_delta(time_delta) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 38, "total_crates": null }
fn_clm_router_retry_webhook_delivery_task_4090695360850491449
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/outgoing_webhook_retry pub(crate) async fn retry_webhook_delivery_task( db: &dyn StorageInterface, merchant_id: &id_type::MerchantId, process: storage::ProcessTracker, ) -> errors::CustomResult<(), errors::StorageError> { let schedule_time = get_webhook_delivery_retry_schedule_time(db, merchant_id, process.retry_count + 1).await; match schedule_time { Some(schedule_time) => { db.as_scheduler() .retry_process(process, schedule_time) .await } None => { db.as_scheduler() .finish_process_with_business_status(process, business_status::RETRIES_EXCEEDED) .await } } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 26, "total_crates": null }
fn_clm_router_error_handler_4090695360850491449
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/outgoing_webhook_retry // Implementation of OutgoingWebhookRetryWorkflow for ProcessTrackerWorkflow<SessionState> async fn error_handler<'a>( &'a self, state: &'a SessionState, process: storage::ProcessTracker, error: errors::ProcessTrackerError, ) -> errors::CustomResult<(), errors::ProcessTrackerError> { consumer::consumer_error_handler(state.store.as_scheduler(), process, error).await }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 18, "total_crates": null }
fn_clm_router_execute_workflow_4090695360850491449
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/outgoing_webhook_retry // Implementation of OutgoingWebhookRetryWorkflow for ProcessTrackerWorkflow<SessionState> async fn execute_workflow<'a>( &'a self, _state: &'a SessionState, _process: storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { todo!() }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 11, "total_crates": null }
fn_clm_router_execute_workflow_2701381176912474938
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/dispute_list // Implementation of DisputeListWorkflow for ProcessTrackerWorkflow<SessionState> async fn execute_workflow<'a>( &'a self, state: &'a SessionState, process: storage::ProcessTracker, ) -> Result<(), sch_errors::ProcessTrackerError> { let db = &*state.store; let tracking_data: api::DisputeListPTData = process .tracking_data .clone() .parse_value("ProcessDisputePTData")?; let key_manager_state = &state.into(); let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, &tracking_data.merchant_id, &db.get_master_key().to_vec().into(), ) .await?; let merchant_account = db .find_merchant_account_by_merchant_id( key_manager_state, &tracking_data.merchant_id.clone(), &key_store, ) .await?; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context( merchant_account.clone(), key_store.clone(), ))); let business_profile = state .store .find_business_profile_by_profile_id( &(state).into(), merchant_context.get_merchant_key_store(), &tracking_data.profile_id, ) .await?; if process.retry_count == 0 { let m_db = state.clone().store; let m_tracking_data = tracking_data.clone(); let dispute_polling_interval = *business_profile .dispute_polling_interval .unwrap_or_default() .deref(); tokio::spawn( async move { schedule_next_dispute_list_task( &*m_db, &m_tracking_data, dispute_polling_interval, ) .await .map_err(|error| { logger::error!( "Failed to add dispute list task to process tracker: {error}" ) }) } .in_current_span(), ); }; let response = Box::pin(disputes::fetch_disputes_from_connector( state.clone(), merchant_context, tracking_data.merchant_connector_id, hyperswitch_domain_models::router_request_types::FetchDisputesRequestData { created_from: tracking_data.created_from, created_till: tracking_data.created_till, }, )) .await .attach_printable("Dispute update failed"); if response.is_err() { retry_sync_task( db, tracking_data.connector_name, tracking_data.merchant_id, process, ) .await?; } else { state .store .as_scheduler() .finish_process_with_business_status(process, business_status::COMPLETED_BY_PT) .await? } Ok(()) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 77, "total_crates": null }
fn_clm_router_get_sync_process_schedule_time_2701381176912474938
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/dispute_list pub async fn get_sync_process_schedule_time( db: &dyn StorageInterface, connector: &str, merchant_id: &common_utils::id_type::MerchantId, retry_count: i32, ) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> { let mapping: common_utils::errors::CustomResult< process_data::ConnectorPTMapping, errors::StorageError, > = db .find_config_by_key(&format!("pt_mapping_{connector}")) .await .map(|value| value.config) .and_then(|config| { config .parse_struct("ConnectorPTMapping") .change_context(errors::StorageError::DeserializationFailed) }); let mapping = match mapping { Ok(x) => x, Err(error) => { logger::info!(?error, "Redis Mapping Error"); process_data::ConnectorPTMapping::default() } }; let time_delta = scheduler_utils::get_schedule_time(mapping, merchant_id, retry_count); Ok(scheduler_utils::get_time_from_delta(time_delta)) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 44, "total_crates": null }
fn_clm_router_schedule_next_dispute_list_task_2701381176912474938
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/dispute_list pub async fn schedule_next_dispute_list_task( db: &dyn StorageInterface, tracking_data: &api::DisputeListPTData, dispute_polling_interval: i32, ) -> Result<(), errors::ProcessTrackerError> { let new_created_till = tracking_data .created_till .checked_add(time::Duration::hours(i64::from(dispute_polling_interval))) .ok_or(sch_errors::ProcessTrackerError::TypeConversionError)?; let fetch_request = hyperswitch_domain_models::router_request_types::FetchDisputesRequestData { created_from: tracking_data.created_till, created_till: new_created_till, }; disputes::add_dispute_list_task_to_pt( db, &tracking_data.connector_name, tracking_data.merchant_id.clone(), tracking_data.merchant_connector_id.clone(), tracking_data.profile_id.clone(), fetch_request, ) .await?; Ok(()) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 29, "total_crates": null }
fn_clm_router_retry_sync_task_2701381176912474938
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/dispute_list /// Schedule the task for retry /// /// Returns bool which indicates whether this was the last retry or not pub async fn retry_sync_task( db: &dyn StorageInterface, connector: String, merchant_id: common_utils::id_type::MerchantId, pt: storage::ProcessTracker, ) -> Result<bool, sch_errors::ProcessTrackerError> { let schedule_time: Option<time::PrimitiveDateTime> = get_sync_process_schedule_time(db, &connector, &merchant_id, pt.retry_count + 1).await?; match schedule_time { Some(s_time) => { db.as_scheduler().retry_process(pt, s_time).await?; Ok(false) } None => { db.as_scheduler() .finish_process_with_business_status(pt, business_status::RETRIES_EXCEEDED) .await?; Ok(true) } } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 26, "total_crates": null }
fn_clm_router_error_handler_2701381176912474938
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/dispute_list // Implementation of DisputeListWorkflow for ProcessTrackerWorkflow<SessionState> async fn error_handler<'a>( &'a self, state: &'a SessionState, process: storage::ProcessTracker, error: sch_errors::ProcessTrackerError, ) -> errors::CustomResult<(), sch_errors::ProcessTrackerError> { consumer::consumer_error_handler(state.store.as_scheduler(), process, error).await }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 18, "total_crates": null }
fn_clm_router_execute_workflow_-6005522412918103892
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/payment_sync // Implementation of PaymentsSyncWorkflow for ProcessTrackerWorkflow<SessionState> async fn execute_workflow<'a>( &'a self, state: &'a SessionState, process: storage::ProcessTracker, ) -> Result<(), sch_errors::ProcessTrackerError> { let db: &dyn StorageInterface = &*state.store; let tracking_data: api::PaymentsRetrieveRequest = process .tracking_data .clone() .parse_value("PaymentsRetrieveRequest")?; let key_manager_state = &state.into(); let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, tracking_data .merchant_id .as_ref() .get_required_value("merchant_id")?, &db.get_master_key().to_vec().into(), ) .await?; let merchant_account = db .find_merchant_account_by_merchant_id( key_manager_state, tracking_data .merchant_id .as_ref() .get_required_value("merchant_id")?, &key_store, ) .await?; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context( merchant_account.clone(), key_store.clone(), ))); // TODO: Add support for ReqState in PT flows let (mut payment_data, _, customer, _, _) = Box::pin(payment_flows::payments_operation_core::< api::PSync, _, _, _, payment_flows::PaymentData<api::PSync>, >( state, state.get_req_state(), &merchant_context, None, operations::PaymentStatus, tracking_data.clone(), payment_flows::CallConnectorAction::Trigger, services::AuthFlow::Client, None, hyperswitch_domain_models::payments::HeaderPayload::default(), )) .await?; let terminal_status = [ enums::AttemptStatus::RouterDeclined, enums::AttemptStatus::Charged, enums::AttemptStatus::AutoRefunded, enums::AttemptStatus::Voided, enums::AttemptStatus::VoidFailed, enums::AttemptStatus::CaptureFailed, enums::AttemptStatus::Failure, ]; match &payment_data.payment_attempt.status { status if terminal_status.contains(status) => { state .store .as_scheduler() .finish_process_with_business_status(process, business_status::COMPLETED_BY_PT) .await? } _ => { let connector = payment_data .payment_attempt .connector .clone() .ok_or(sch_errors::ProcessTrackerError::MissingRequiredField)?; let is_last_retry = retry_sync_task( db, connector, payment_data.payment_attempt.merchant_id.clone(), process, ) .await?; // If the payment status is still processing and there is no connector transaction_id // then change the payment status to failed if all retries exceeded if is_last_retry && payment_data.payment_attempt.status == enums::AttemptStatus::Pending && payment_data .payment_attempt .connector_transaction_id .as_ref() .is_none() { let payment_intent_update = hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::PGStatusUpdate { status: api_models::enums::IntentStatus::Failed,updated_by: merchant_account.storage_scheme.to_string(), incremental_authorization_allowed: Some(false), feature_metadata: payment_data.payment_intent.feature_metadata.clone().map(masking::Secret::new), }; let payment_attempt_update = hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptUpdate::ErrorUpdate { connector: None, status: api_models::enums::AttemptStatus::Failure, error_code: None, error_message: None, error_reason: Some(Some( consts::REQUEST_TIMEOUT_ERROR_MESSAGE_FROM_PSYNC.to_string(), )), amount_capturable: Some(common_utils::types::MinorUnit::new(0)), updated_by: merchant_account.storage_scheme.to_string(), unified_code: None, unified_message: None, connector_transaction_id: None, payment_method_data: None, authentication_type: None, issuer_error_code: None, issuer_error_message: None, network_details:None }; payment_data.payment_attempt = db .update_payment_attempt_with_attempt_id( payment_data.payment_attempt, payment_attempt_update, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; payment_data.payment_intent = db .update_payment_intent( &state.into(), payment_data.payment_intent, payment_intent_update, &key_store, merchant_account.storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let profile_id = payment_data .payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Could not find profile_id in payment intent")?; let business_profile = db .find_business_profile_by_profile_id( key_manager_state, &key_store, profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; // Trigger the outgoing webhook to notify the merchant about failed payment let operation = operations::PaymentStatus; Box::pin(utils::trigger_payments_webhook( merchant_context, business_profile, payment_data, customer, state, operation, )) .await .map_err(|error| logger::warn!(payments_outgoing_webhook_error=?error)) .ok(); } } }; Ok(()) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 117, "total_crates": null }
fn_clm_router_get_sync_process_schedule_time_-6005522412918103892
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/payment_sync /// Get the next schedule time /// /// The schedule time can be configured in configs by this key `pt_mapping_trustpay` /// ```json /// { /// "default_mapping": { /// "start_after": 60, /// "frequency": [300], /// "count": [5] /// }, /// "max_retries_count": 5 /// } /// ``` /// /// This config represents /// /// `start_after`: The first psync should happen after 60 seconds /// /// `frequency` and `count`: The next 5 retries should have an interval of 300 seconds between them pub async fn get_sync_process_schedule_time( db: &dyn StorageInterface, connector: &str, merchant_id: &common_utils::id_type::MerchantId, retry_count: i32, ) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> { let mapping: common_utils::errors::CustomResult< process_data::ConnectorPTMapping, errors::StorageError, > = db .find_config_by_key(&format!("pt_mapping_{connector}")) .await .map(|value| value.config) .and_then(|config| { config .parse_struct("ConnectorPTMapping") .change_context(errors::StorageError::DeserializationFailed) }); let mapping = match mapping { Ok(x) => x, Err(error) => { logger::info!(?error, "Redis Mapping Error"); process_data::ConnectorPTMapping::default() } }; let time_delta = scheduler_utils::get_schedule_time(mapping, merchant_id, retry_count); Ok(scheduler_utils::get_time_from_delta(time_delta)) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 44, "total_crates": null }
fn_clm_router_recovery_retry_sync_task_-6005522412918103892
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/payment_sync pub async fn recovery_retry_sync_task( state: &SessionState, connector_customer_id: Option<String>, connector: String, merchant_id: common_utils::id_type::MerchantId, pt: storage::ProcessTracker, ) -> Result<bool, sch_errors::ProcessTrackerError> { let db = &*state.store; let schedule_time = get_sync_process_schedule_time(db, &connector, &merchant_id, pt.retry_count + 1).await?; match schedule_time { Some(s_time) => { db.as_scheduler().retry_process(pt, s_time).await?; connector_customer_id .async_map(|id| async move { let _ = update_token_expiry_based_on_schedule_time(state, &id, Some(s_time)) .await .map_err(|e| { logger::error!( error = ?e, connector_customer_id = %id, "Failed to update the token expiry time in redis" ); e }); }) .await; Ok(false) } None => { db.as_scheduler() .finish_process_with_business_status(pt, business_status::RETRIES_EXCEEDED) .await?; Ok(true) } } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 29, "total_crates": null }
fn_clm_router_retry_sync_task_-6005522412918103892
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/payment_sync /// Schedule the task for retry /// /// Returns bool which indicates whether this was the last retry or not pub async fn retry_sync_task( db: &dyn StorageInterface, connector: String, merchant_id: common_utils::id_type::MerchantId, pt: storage::ProcessTracker, ) -> Result<bool, sch_errors::ProcessTrackerError> { let schedule_time = get_sync_process_schedule_time(db, &connector, &merchant_id, pt.retry_count + 1).await?; match schedule_time { Some(s_time) => { db.as_scheduler().retry_process(pt, s_time).await?; Ok(false) } None => { db.as_scheduler() .finish_process_with_business_status(pt, business_status::RETRIES_EXCEEDED) .await?; Ok(true) } } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 26, "total_crates": null }
fn_clm_router_error_handler_-6005522412918103892
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/payment_sync // Implementation of PaymentsSyncWorkflow for ProcessTrackerWorkflow<SessionState> async fn error_handler<'a>( &'a self, state: &'a SessionState, process: storage::ProcessTracker, error: sch_errors::ProcessTrackerError, ) -> errors::CustomResult<(), sch_errors::ProcessTrackerError> { consumer::consumer_error_handler(state.store.as_scheduler(), process, error).await }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 18, "total_crates": null }
fn_clm_router_from_-8047297520985161689
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/revenue_recovery // Implementation of external_grpc_client::DeciderRequest for From<InternalDeciderRequest> fn from(internal_request: InternalDeciderRequest) -> Self { Self { first_error_message: internal_request.first_error_message, billing_state: internal_request.billing_state.map(|s| s.peek().to_string()), card_funding: internal_request.card_funding, card_network: internal_request.card_network, card_issuer: internal_request.card_issuer, invoice_start_time: internal_request.invoice_start_time, retry_count: internal_request.retry_count, merchant_id: internal_request.merchant_id, invoice_amount: internal_request.invoice_amount, invoice_currency: internal_request.invoice_currency, invoice_due_date: internal_request.invoice_due_date, billing_country: internal_request.billing_country, billing_city: internal_request.billing_city, attempt_currency: internal_request.attempt_currency, attempt_status: internal_request.attempt_status, attempt_amount: internal_request.attempt_amount, pg_error_code: internal_request.pg_error_code, network_advice_code: internal_request.network_advice_code, network_error_code: internal_request.network_error_code, first_pg_error_code: internal_request.first_pg_error_code, first_network_advice_code: internal_request.first_network_advice_code, first_network_error_code: internal_request.first_network_error_code, attempt_response_time: internal_request.attempt_response_time, payment_method_type: internal_request.payment_method_type, payment_gateway: internal_request.payment_gateway, retry_count_left: internal_request.retry_count_left, total_retry_count_within_network: internal_request.total_retry_count_within_network, first_error_msg_time: internal_request.first_error_msg_time, wait_time: internal_request.wait_time, } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 2606, "total_crates": null }
fn_clm_router_get_schedule_time_for_smart_retry_-8047297520985161689
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/revenue_recovery pub(crate) async fn get_schedule_time_for_smart_retry( state: &SessionState, payment_intent: &PaymentIntent, retry_after_time: Option<prost_types::Timestamp>, token_with_retry_info: &PaymentProcessorTokenWithRetryInfo, ) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> { let card_config = &state.conf.revenue_recovery.card_config; // Not populating it right now let first_error_message = "None".to_string(); let retry_count_left = token_with_retry_info.monthly_retry_remaining; let pg_error_code = token_with_retry_info.token_status.error_code.clone(); let card_info = token_with_retry_info .token_status .payment_processor_token_details .clone(); let billing_state = payment_intent .billing_address .as_ref() .and_then(|addr_enc| addr_enc.get_inner().address.as_ref()) .and_then(|details| details.state.as_ref()) .cloned(); let revenue_recovery_metadata = payment_intent .feature_metadata .as_ref() .and_then(|metadata| metadata.payment_revenue_recovery_metadata.as_ref()); let card_network = card_info.card_network.clone(); let total_retry_count_within_network = card_config.get_network_config(card_network.clone()); let card_network_str = card_network.map(|network| network.to_string()); let card_issuer_str = card_info.card_issuer.clone(); let card_funding_str = match card_info.card_type.as_deref() { Some("card") => None, Some(s) => Some(s.to_string()), None => None, }; let start_time_primitive = payment_intent.created_at; let recovery_timestamp_config = &state.conf.revenue_recovery.recovery_timestamp; let modified_start_time_primitive = start_time_primitive.saturating_add( time::Duration::seconds(recovery_timestamp_config.initial_timestamp_in_seconds), ); let start_time_proto = date_time::convert_to_prost_timestamp(modified_start_time_primitive); let merchant_id = Some(payment_intent.merchant_id.get_string_repr().to_string()); let invoice_amount = Some( payment_intent .amount_details .order_amount .get_amount_as_i64(), ); let invoice_currency = Some(payment_intent.amount_details.currency.to_string()); let billing_country = payment_intent .billing_address .as_ref() .and_then(|addr_enc| addr_enc.get_inner().address.as_ref()) .and_then(|details| details.country.as_ref()) .map(|country| country.to_string()); let billing_city = payment_intent .billing_address .as_ref() .and_then(|addr_enc| addr_enc.get_inner().address.as_ref()) .and_then(|details| details.city.as_ref()) .cloned(); let first_pg_error_code = revenue_recovery_metadata .and_then(|metadata| metadata.first_payment_attempt_pg_error_code.clone()); let first_network_advice_code = revenue_recovery_metadata .and_then(|metadata| metadata.first_payment_attempt_network_advice_code.clone()); let first_network_error_code = revenue_recovery_metadata .and_then(|metadata| metadata.first_payment_attempt_network_decline_code.clone()); let invoice_due_date = revenue_recovery_metadata .and_then(|metadata| metadata.invoice_next_billing_time) .map(date_time::convert_to_prost_timestamp); let decider_request = InternalDeciderRequest { first_error_message, billing_state, card_funding: card_funding_str, card_network: card_network_str, card_issuer: card_issuer_str, invoice_start_time: Some(start_time_proto), retry_count: Some(token_with_retry_info.total_30_day_retries.into()), merchant_id, invoice_amount, invoice_currency, invoice_due_date, billing_country, billing_city, attempt_currency: None, attempt_status: None, attempt_amount: None, pg_error_code, network_advice_code: None, network_error_code: None, first_pg_error_code, first_network_advice_code, first_network_error_code, attempt_response_time: None, payment_method_type: None, payment_gateway: None, retry_count_left: Some(retry_count_left.into()), total_retry_count_within_network: Some( total_retry_count_within_network .max_retry_count_for_thirty_day .into(), ), first_error_msg_time: None, wait_time: retry_after_time, }; if let Some(mut client) = state.grpc_client.recovery_decider_client.clone() { match client .decide_on_retry(decider_request.into(), state.get_recovery_grpc_headers()) .await { Ok(grpc_response) => Ok(grpc_response .retry_flag .then_some(()) .and(grpc_response.retry_time) .and_then(|prost_ts| { match date_time::convert_from_prost_timestamp(&prost_ts) { Ok(pdt) => Some(pdt), Err(e) => { logger::error!( "Failed to convert retry_time from prost::Timestamp: {e:?}" ); None // If conversion fails, treat as no valid retry time } } })), Err(e) => { logger::error!("Recovery decider gRPC call failed: {e:?}"); Ok(None) } } } else { logger::debug!("Recovery decider client is not configured"); Ok(None) } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 137, "total_crates": null }
fn_clm_router_execute_workflow_-8047297520985161689
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/revenue_recovery // Implementation of ExecutePcrWorkflow for ProcessTrackerWorkflow<SessionState> async fn execute_workflow<'a>( &'a self, state: &'a SessionState, process: storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { let tracking_data = process .tracking_data .clone() .parse_value::<pcr_storage_types::RevenueRecoveryWorkflowTrackingData>( "PCRWorkflowTrackingData", )?; let request = PaymentsGetIntentRequest { id: tracking_data.global_payment_id.clone(), }; let revenue_recovery_payment_data = extract_data_and_perform_action(state, &tracking_data).await?; let merchant_context_from_revenue_recovery_payment_data = domain::MerchantContext::NormalMerchant(Box::new(domain::Context( revenue_recovery_payment_data.merchant_account.clone(), revenue_recovery_payment_data.key_store.clone(), ))); let (payment_data, _, _) = payments::payments_intent_operation_core::< api_types::PaymentGetIntent, _, _, PaymentIntentData<api_types::PaymentGetIntent>, >( state, state.get_req_state(), merchant_context_from_revenue_recovery_payment_data.clone(), revenue_recovery_payment_data.profile.clone(), payments::operations::PaymentGetIntent, request, tracking_data.global_payment_id.clone(), hyperswitch_domain_models::payments::HeaderPayload::default(), ) .await?; match process.name.as_deref() { Some("EXECUTE_WORKFLOW") => { Box::pin(pcr::perform_execute_payment( state, &process, &revenue_recovery_payment_data.profile.clone(), merchant_context_from_revenue_recovery_payment_data.clone(), &tracking_data, &revenue_recovery_payment_data, &payment_data.payment_intent, )) .await } Some("PSYNC_WORKFLOW") => { Box::pin(pcr::perform_payments_sync( state, &process, &revenue_recovery_payment_data.profile.clone(), merchant_context_from_revenue_recovery_payment_data.clone(), &tracking_data, &revenue_recovery_payment_data, &payment_data.payment_intent, )) .await?; Ok(()) } Some("CALCULATE_WORKFLOW") => { Box::pin(pcr::perform_calculate_workflow( state, &process, &revenue_recovery_payment_data.profile.clone(), merchant_context_from_revenue_recovery_payment_data, &tracking_data, &revenue_recovery_payment_data, &payment_data.payment_intent, )) .await } _ => Err(errors::ProcessTrackerError::JobNotFound), } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 61, "total_crates": null }
fn_clm_router_check_hard_decline_-8047297520985161689
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/revenue_recovery pub async fn check_hard_decline( state: &SessionState, payment_attempt: &payment_attempt::PaymentAttempt, ) -> Result<bool, error_stack::Report<storage_impl::errors::RecoveryError>> { let error_message = payment_attempt .error .as_ref() .map(|details| details.message.clone()); let error_code = payment_attempt .error .as_ref() .map(|details| details.code.clone()); let connector_name = payment_attempt .connector .clone() .ok_or(storage_impl::errors::RecoveryError::ValueNotFound) .attach_printable("unable to derive payment connector from payment attempt")?; let gsm_record = payments::helpers::get_gsm_record( state, error_code, error_message, connector_name, REVENUE_RECOVERY.to_string(), ) .await; let is_hard_decline = gsm_record .and_then(|record| record.error_category) .map(|category| category == common_enums::ErrorCategory::HardDecline) .unwrap_or(false); Ok(is_hard_decline) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 50, "total_crates": null }
fn_clm_router_call_decider_for_payment_processor_tokens_select_closet_time_-8047297520985161689
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/revenue_recovery pub async fn call_decider_for_payment_processor_tokens_select_closet_time( state: &SessionState, processor_tokens: &HashMap<String, PaymentProcessorTokenWithRetryInfo>, payment_intent: &PaymentIntent, connector_customer_id: &str, ) -> CustomResult<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> { tracing::debug!("Filtered payment attempts based on payment tokens",); let mut tokens_with_schedule_time: Vec<ScheduledToken> = Vec::new(); for token_with_retry_info in processor_tokens.values() { let token_details = &token_with_retry_info .token_status .payment_processor_token_details; let error_code = token_with_retry_info.token_status.error_code.clone(); match error_code { None => { let utc_schedule_time = time::OffsetDateTime::now_utc() + time::Duration::minutes(1); let schedule_time = time::PrimitiveDateTime::new( utc_schedule_time.date(), utc_schedule_time.time(), ); tokens_with_schedule_time = vec![ScheduledToken { token_details: token_details.clone(), schedule_time, }]; tracing::debug!( "Found payment processor token with no error code scheduling it for {schedule_time}", ); break; } Some(_) => { process_token_for_retry(state, token_with_retry_info, payment_intent) .await? .map(|token_with_schedule_time| { tokens_with_schedule_time.push(token_with_schedule_time) }); } } } let best_token = tokens_with_schedule_time .iter() .min_by_key(|token| token.schedule_time) .cloned(); match best_token { None => { RedisTokenManager::unlock_connector_customer_status(state, connector_customer_id) .await .change_context(errors::ProcessTrackerError::EApiErrorResponse)?; tracing::debug!("No payment processor tokens available for scheduling"); Ok(None) } Some(token) => { tracing::debug!("Found payment processor token with least schedule time"); RedisTokenManager::update_payment_processor_token_schedule_time( state, connector_customer_id, &token.token_details.payment_processor_token, Some(token.schedule_time), ) .await .change_context(errors::ProcessTrackerError::EApiErrorResponse)?; Ok(Some(token.schedule_time)) } } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 49, "total_crates": null }
fn_clm_router_execute_workflow_7878677870689871098
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/attach_payout_account_workflow // Implementation of AttachPayoutAccountWorkflow for ProcessTrackerWorkflow<SessionState> async fn execute_workflow<'a>( &'a self, state: &'a SessionState, process: storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { // Gather context let db = &*state.store; let tracking_data: api::PayoutRetrieveRequest = process .tracking_data .clone() .parse_value("PayoutRetrieveRequest")?; let merchant_id = tracking_data .merchant_id .clone() .get_required_value("merchant_id")?; let key_manager_state = &state.into(); let key_store = db .get_merchant_key_store_by_merchant_id( key_manager_state, &merchant_id, &db.get_master_key().to_vec().into(), ) .await?; let merchant_account = db .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store) .await?; let request = api::payouts::PayoutRequest::PayoutRetrieveRequest(tracking_data); let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context( merchant_account.clone(), key_store.clone(), ))); let mut payout_data = Box::pin(payouts::make_payout_data( state, &merchant_context, None, &request, DEFAULT_LOCALE, )) .await?; payouts::payouts_core(state, &merchant_context, &mut payout_data, None, None).await?; Ok(()) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 49, "total_crates": null }
fn_clm_router_error_handler_7878677870689871098
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/attach_payout_account_workflow // Implementation of AttachPayoutAccountWorkflow for ProcessTrackerWorkflow<SessionState> async fn error_handler<'a>( &'a self, state: &'a SessionState, process: storage::ProcessTracker, error: errors::ProcessTrackerError, ) -> core_errors::CustomResult<(), errors::ProcessTrackerError> { consumer::consumer_error_handler(state.store.as_scheduler(), process, error).await }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 18, "total_crates": null }
fn_clm_router_error_handler_1671806514531970715
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/payment_method_status_update // Implementation of PaymentMethodStatusUpdateWorkflow for ProcessTrackerWorkflow<SessionState> async fn error_handler<'a>( &'a self, _state: &'a SessionState, process: storage::ProcessTracker, _error: errors::ProcessTrackerError, ) -> errors::CustomResult<(), errors::ProcessTrackerError> { error!(%process.id, "Failed while executing workflow"); Ok(()) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 14, "total_crates": null }
fn_clm_router_execute_workflow_1671806514531970715
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/payment_method_status_update // Implementation of PaymentMethodStatusUpdateWorkflow for ProcessTrackerWorkflow<SessionState> async fn execute_workflow<'a>( &'a self, _state: &'a SessionState, _process: storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { todo!() }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 11, "total_crates": null }
fn_clm_router_error_handler_8326547083539140358
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/refund_router // Implementation of RefundWorkflowRouter for ProcessTrackerWorkflow<SessionState> async fn error_handler<'a>( &'a self, _state: &'a SessionState, process: storage::ProcessTracker, _error: errors::ProcessTrackerError, ) -> errors::CustomResult<(), errors::ProcessTrackerError> { error!(%process.id, "Failed while executing workflow"); Ok(()) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 14, "total_crates": null }
fn_clm_router_execute_workflow_8326547083539140358
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/workflows/refund_router // Implementation of RefundWorkflowRouter for ProcessTrackerWorkflow<SessionState> async fn execute_workflow<'a>( &'a self, _state: &'a SessionState, _process: storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { todo!() }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 11, "total_crates": null }
fn_clm_router_validate_opt_-4244796765487357500
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/ext_traits // Implementation of Option<&T> for ValidateCall<T, F> fn validate_opt(self, func: F) -> CustomResult<(), errors::ValidationError> { match self { Some(val) => func(val), None => Ok(()), } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 10, "total_crates": null }
fn_clm_router_parse_value_3992458386329099305
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/user pub fn parse_value<T>(value: serde_json::Value, type_name: &str) -> UserResult<T> where T: serde::de::DeserializeOwned, { serde_json::from_value::<T>(value) .change_context(UserErrors::InternalServerError) .attach_printable(format!("Unable to parse {type_name}")) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 479, "total_crates": null }
fn_clm_router_foreign_from_3992458386329099305
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/user // Implementation of UserAuthType for ForeignFrom<&user_api::AuthConfig> fn foreign_from(from: &user_api::AuthConfig) -> Self { match *from { user_api::AuthConfig::OpenIdConnect { .. } => Self::OpenIdConnect, user_api::AuthConfig::Password => Self::Password, user_api::AuthConfig::MagicLink => Self::MagicLink, } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 212, "total_crates": null }
fn_clm_router_build_cloned_connector_create_request_3992458386329099305
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/user pub async fn build_cloned_connector_create_request( source_mca: DomainMerchantConnectorAccount, destination_profile_id: Option<id_type::ProfileId>, destination_connector_label: Option<String>, ) -> UserResult<admin_api::MerchantConnectorCreate> { let source_mca_name = source_mca .connector_name .parse::<connector_enums::Connector>() .change_context(UserErrors::InternalServerError) .attach_printable("Invalid connector name received")?; let payment_methods_enabled = source_mca .payment_methods_enabled .clone() .map(|data| { let val = data.into_iter().map(|secret| secret.expose()).collect(); serde_json::Value::Array(val) .parse_value("PaymentMethods") .change_context(UserErrors::InternalServerError) .attach_printable("Unable to deserialize PaymentMethods") }) .transpose()?; let frm_configs = source_mca .frm_configs .as_ref() .map(|configs_vec| { configs_vec .iter() .map(|config_secret| { config_secret .peek() .clone() .parse_value("FrmConfigs") .change_context(UserErrors::InternalServerError) .attach_printable("Unable to deserialize FrmConfigs") }) .collect::<Result<Vec<_>, _>>() }) .transpose()?; let connector_webhook_details = source_mca .connector_webhook_details .map(|webhook_details| { serde_json::Value::parse_value( webhook_details.expose(), "MerchantConnectorWebhookDetails", ) .change_context(UserErrors::InternalServerError) .attach_printable("Unable to deserialize connector_webhook_details") }) .transpose()?; let connector_wallets_details = source_mca .connector_wallets_details .map(|secret_value| { secret_value .into_inner() .expose() .parse_value::<admin_api::ConnectorWalletDetails>("ConnectorWalletDetails") .change_context(UserErrors::InternalServerError) .attach_printable("Unable to parse ConnectorWalletDetails from Value") }) .transpose()?; let additional_merchant_data = source_mca .additional_merchant_data .map(|secret_value| { secret_value .into_inner() .expose() .parse_value::<AdditionalMerchantData>("AdditionalMerchantData") .change_context(UserErrors::InternalServerError) .attach_printable("Unable to parse AdditionalMerchantData from Value") }) .transpose()? .map(admin_api::AdditionalMerchantData::foreign_from); Ok(admin_api::MerchantConnectorCreate { connector_type: source_mca.connector_type, connector_name: source_mca_name, connector_label: destination_connector_label.or(source_mca.connector_label.clone()), merchant_connector_id: None, connector_account_details: Some(source_mca.connector_account_details.clone().into_inner()), test_mode: source_mca.test_mode, disabled: source_mca.disabled, payment_methods_enabled, metadata: source_mca.metadata, business_country: source_mca.business_country, business_label: source_mca.business_label.clone(), business_sub_label: source_mca.business_sub_label.clone(), frm_configs, connector_webhook_details, profile_id: destination_profile_id, pm_auth_config: source_mca.pm_auth_config.clone(), connector_wallets_details, status: Some(source_mca.status), additional_merchant_data, }) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 111, "total_crates": null }
fn_clm_router_get_redis_connection_for_global_tenant_3992458386329099305
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/user pub fn get_redis_connection_for_global_tenant( state: &SessionState, ) -> UserResult<Arc<RedisConnectionPool>> { state .global_store .get_redis_conn() .change_context(UserErrors::InternalServerError) .attach_printable("Failed to get redis connection") }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 100, "total_crates": null }
fn_clm_router_get_role_info_from_db_3992458386329099305
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/user // Inherent implementation for UserFromToken pub async fn get_role_info_from_db(&self, state: &SessionState) -> UserResult<RoleInfo> { RoleInfo::from_role_id_org_id_tenant_id( state, &self.role_id, &self.org_id, self.tenant_id.as_ref().unwrap_or(&state.tenant.tenant_id), ) .await .change_context(UserErrors::InternalServerError) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 65, "total_crates": null }
fn_clm_router_get_lineage_for_user_id_and_entity_for_accepting_invite_4035543333154386519
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/user_role pub async fn get_lineage_for_user_id_and_entity_for_accepting_invite( state: &SessionState, user_id: &str, tenant_id: &id_type::TenantId, entity_id: String, entity_type: EntityType, ) -> UserResult< Option<( id_type::OrganizationId, Option<id_type::MerchantId>, Option<id_type::ProfileId>, )>, > { match entity_type { EntityType::Tenant => Err(UserErrors::InvalidRoleOperationWithMessage( "Tenant roles are not allowed for this operation".to_string(), ) .into()), EntityType::Organization => { let Ok(org_id) = id_type::OrganizationId::try_from(std::borrow::Cow::from(entity_id.clone())) else { return Ok(None); }; let user_roles = state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id, tenant_id, org_id: Some(&org_id), merchant_id: None, profile_id: None, entity_id: None, version: None, status: Some(UserStatus::InvitationSent), limit: None, }) .await .change_context(UserErrors::InternalServerError)? .into_iter() .collect::<HashSet<_>>(); if user_roles.len() > 1 { return Ok(None); } if let Some(user_role) = user_roles.into_iter().next() { let (_entity_id, entity_type) = user_role .get_entity_id_and_type() .ok_or(UserErrors::InternalServerError)?; if entity_type != EntityType::Organization { return Ok(None); } return Ok(Some(( user_role.org_id.ok_or(UserErrors::InternalServerError)?, None, None, ))); } Ok(None) } EntityType::Merchant => { let Ok(merchant_id) = id_type::MerchantId::wrap(entity_id) else { return Ok(None); }; let user_roles = state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id, tenant_id, org_id: None, merchant_id: Some(&merchant_id), profile_id: None, entity_id: None, version: None, status: Some(UserStatus::InvitationSent), limit: None, }) .await .change_context(UserErrors::InternalServerError)? .into_iter() .collect::<HashSet<_>>(); if user_roles.len() > 1 { return Ok(None); } if let Some(user_role) = user_roles.into_iter().next() { let (_entity_id, entity_type) = user_role .get_entity_id_and_type() .ok_or(UserErrors::InternalServerError)?; if entity_type != EntityType::Merchant { return Ok(None); } return Ok(Some(( user_role.org_id.ok_or(UserErrors::InternalServerError)?, Some(merchant_id), None, ))); } Ok(None) } EntityType::Profile => { let Ok(profile_id) = id_type::ProfileId::try_from(std::borrow::Cow::from(entity_id)) else { return Ok(None); }; let user_roles = state .global_store .list_user_roles_by_user_id(ListUserRolesByUserIdPayload { user_id, tenant_id: &state.tenant.tenant_id, org_id: None, merchant_id: None, profile_id: Some(&profile_id), entity_id: None, version: None, status: Some(UserStatus::InvitationSent), limit: None, }) .await .change_context(UserErrors::InternalServerError)? .into_iter() .collect::<HashSet<_>>(); if user_roles.len() > 1 { return Ok(None); } if let Some(user_role) = user_roles.into_iter().next() { let (_entity_id, entity_type) = user_role .get_entity_id_and_type() .ok_or(UserErrors::InternalServerError)?; if entity_type != EntityType::Profile { return Ok(None); } return Ok(Some(( user_role.org_id.ok_or(UserErrors::InternalServerError)?, Some( user_role .merchant_id .ok_or(UserErrors::InternalServerError)?, ), Some(profile_id), ))); } Ok(None) } } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 93, "total_crates": null }
fn_clm_router_validate_role_name_4035543333154386519
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/user_role pub async fn validate_role_name( state: &SessionState, role_name: &domain::RoleName, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, tenant_id: &id_type::TenantId, profile_id: &id_type::ProfileId, entity_type: &EntityType, ) -> UserResult<()> { let role_name_str = role_name.clone().get_role_name(); let is_present_in_predefined_roles = roles::predefined_roles::PREDEFINED_ROLES .iter() .any(|(_, role_info)| role_info.get_role_name() == role_name_str); let entity_type_for_role = match entity_type { EntityType::Tenant | EntityType::Organization => ListRolesByEntityPayload::Organization, EntityType::Merchant => ListRolesByEntityPayload::Merchant(merchant_id.to_owned()), EntityType::Profile => { ListRolesByEntityPayload::Profile(merchant_id.to_owned(), profile_id.to_owned()) } }; let is_present_in_custom_role = match state .global_store .generic_list_roles_by_entity_type( entity_type_for_role, false, tenant_id.to_owned(), org_id.to_owned(), ) .await { Ok(roles_list) => roles_list .iter() .any(|role| role.role_name == role_name_str), Err(e) => { if e.current_context().is_db_not_found() { false } else { return Err(UserErrors::InternalServerError.into()); } } }; if is_present_in_predefined_roles || is_present_in_custom_role { return Err(UserErrors::RoleNameAlreadyExists.into()); } Ok(()) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 57, "total_crates": null }
fn_clm_router_get_single_profile_id_4035543333154386519
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/user_role pub async fn get_single_profile_id( state: &SessionState, user_role: &UserRole, merchant_id: &id_type::MerchantId, ) -> UserResult<id_type::ProfileId> { let (_, entity_type) = user_role .get_entity_id_and_type() .ok_or(UserErrors::InternalServerError)?; match entity_type { EntityType::Tenant | EntityType::Organization | EntityType::Merchant => { let key_store = state .store .get_merchant_key_store_by_merchant_id( &state.into(), merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .change_context(UserErrors::InternalServerError)?; Ok(state .store .list_profile_by_merchant_id(&state.into(), &key_store, merchant_id) .await .change_context(UserErrors::InternalServerError)? .pop() .ok_or(UserErrors::InternalServerError)? .get_id() .to_owned()) } EntityType::Profile => user_role .profile_id .clone() .ok_or(UserErrors::InternalServerError) .attach_printable("profile_id not found"), } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 52, "total_crates": null }
fn_clm_router_permission_groups_to_parent_group_info_4035543333154386519
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/user_role pub fn permission_groups_to_parent_group_info( permission_groups: &[PermissionGroup], entity_type: EntityType, ) -> Vec<role_api::ParentGroupInfo> { let parent_groups_map: HashMap<ParentGroup, Vec<common_enums::PermissionScope>> = permission_groups .iter() .fold(HashMap::new(), |mut acc, group| { let parent = group.parent(); let scope = group.scope(); acc.entry(parent).or_default().push(scope); acc }); parent_groups_map .into_iter() .filter_map(|(name, scopes)| { let unique_scopes = scopes .into_iter() .collect::<HashSet<_>>() .into_iter() .collect(); let filtered_resources = permissions::filter_resources_by_entity_type(name.resources(), entity_type)?; Some(role_api::ParentGroupInfo { name, resources: filtered_resources, scopes: unique_scopes, }) }) .collect() }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 51, "total_crates": null }
fn_clm_router_get_single_merchant_id_4035543333154386519
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/user_role pub async fn get_single_merchant_id( state: &SessionState, user_role: &UserRole, org_id: &id_type::OrganizationId, ) -> UserResult<id_type::MerchantId> { let (_, entity_type) = user_role .get_entity_id_and_type() .ok_or(UserErrors::InternalServerError)?; match entity_type { EntityType::Tenant | EntityType::Organization => Ok(state .store .list_merchant_accounts_by_organization_id(&state.into(), org_id) .await .to_not_found_response(UserErrors::InvalidRoleOperationWithMessage( "Invalid Org Id".to_string(), ))? .first() .ok_or(UserErrors::InternalServerError) .attach_printable("No merchants found for org_id")? .get_id() .clone()), EntityType::Merchant | EntityType::Profile => user_role .merchant_id .clone() .ok_or(UserErrors::InternalServerError) .attach_printable("merchant_id not found"), } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 46, "total_crates": null }
fn_clm_router_get_test_card_details_3725669809540095604
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/verify_connector pub fn get_test_card_details( connector_name: Connector, ) -> errors::RouterResult<Option<domain::Card>> { match connector_name { Connector::Stripe => Some(generate_card_from_details( "4242424242424242".to_string(), "2025".to_string(), "12".to_string(), "100".to_string(), )) .transpose(), Connector::Paypal => Some(generate_card_from_details( "4111111111111111".to_string(), "2025".to_string(), "02".to_string(), "123".to_string(), )) .transpose(), _ => Ok(None), } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 40, "total_crates": null }
fn_clm_router_generate_card_from_details_3725669809540095604
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/verify_connector pub fn generate_card_from_details( card_number: String, card_exp_year: String, card_exp_month: String, card_cvv: String, ) -> errors::RouterResult<domain::Card> { Ok(domain::Card { card_number: card_number .parse::<cards::CardNumber>() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error while parsing card number")?, card_issuer: None, card_cvc: masking::Secret::new(card_cvv), card_network: None, card_exp_year: masking::Secret::new(card_exp_year), card_exp_month: masking::Secret::new(card_exp_month), nick_name: None, card_type: None, card_issuing_country: None, bank_code: None, card_holder_name: None, co_badged_card_data: None, }) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 26, "total_crates": null }
fn_clm_router_new_-3726939189834630647
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/currency // Inherent implementation for FxExchangeRatesCacheEntry fn new(exchange_rate: ExchangeRates) -> Self { Self { data: Arc::new(exchange_rate), timestamp: date_time::now_unix_timestamp(), } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 14457, "total_crates": null }
fn_clm_router_try_from_-3726939189834630647
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/currency // Implementation of ExchangeRates for TryFrom<DefaultExchangeRates> fn try_from(value: DefaultExchangeRates) -> Result<Self, Self::Error> { let mut conversion_usable: HashMap<enums::Currency, CurrencyFactors> = HashMap::new(); for (curr, conversion) in value.conversion { let enum_curr = enums::Currency::from_str(curr.as_str()) .change_context(ForexError::ConversionError) .attach_printable("Unable to Convert currency received")?; conversion_usable.insert(enum_curr, CurrencyFactors::from(conversion)); } let base_curr = enums::Currency::from_str(value.base_currency.as_str()) .change_context(ForexError::ConversionError) .attach_printable("Unable to convert base currency")?; Ok(Self { base_currency: base_curr, conversion: conversion_usable, }) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 2679, "total_crates": null }
fn_clm_router_from_-3726939189834630647
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/currency // Implementation of CurrencyFactors for From<Conversion> fn from(value: Conversion) -> Self { Self { to_factor: value.to_factor, from_factor: value.from_factor, } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 2600, "total_crates": null }
fn_clm_router_fetch_forex_rates_from_fallback_api_-3726939189834630647
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/currency pub async fn fetch_forex_rates_from_fallback_api( state: &SessionState, ) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> { let fallback_forex_api_key = state.conf.forex_api.get_inner().fallback_api_key.peek(); let fallback_forex_url: String = format!("{FALLBACK_FOREX_BASE_URL}{fallback_forex_api_key}"); let fallback_forex_request = services::RequestBuilder::new() .method(services::Method::Get) .url(&fallback_forex_url) .build(); logger::info!(fallback_forex_request=?fallback_forex_request,"forex_log: Fallback api call for forex fetch"); let response = state .api_client .send_request( &state.clone(), fallback_forex_request, Some(FOREX_API_TIMEOUT), false, ) .await .change_context(ForexError::ApiUnresponsive) .attach_printable("Fallback forex fetch api unresponsive")?; let fallback_forex_response = response .json::<FallbackForexResponse>() .await .change_context(ForexError::ParsingError) .attach_printable( "Unable to parse response received from fallback api into ForexResponse", )?; logger::info!(fallback_forex_response=?fallback_forex_response,"forex_log"); let mut conversions: HashMap<enums::Currency, CurrencyFactors> = HashMap::new(); for enum_curr in enums::Currency::iter() { match fallback_forex_response.quotes.get( format!( "{}{}", FALLBACK_FOREX_API_CURRENCY_PREFIX, &enum_curr.to_string() ) .as_str(), ) { Some(rate) => { let from_factor = match Decimal::new(1, 0).checked_div(**rate) { Some(rate) => rate, None => { logger::error!( "forex_error: Rates for {} not received from API", &enum_curr ); continue; } }; let currency_factors = CurrencyFactors::new(**rate, from_factor); conversions.insert(enum_curr, currency_factors); } None => { if enum_curr == enums::Currency::USD { let currency_factors = CurrencyFactors::new(Decimal::new(1, 0), Decimal::new(1, 0)); conversions.insert(enum_curr, currency_factors); } else { logger::error!( "forex_error: Rates for {} not received from API", &enum_curr ); } } }; } let rates = FxExchangeRatesCacheEntry::new(ExchangeRates::new(enums::Currency::USD, conversions)); match acquire_redis_lock(state).await { Ok(_) => { save_forex_data_to_cache_and_redis(state, rates.clone()).await?; Ok(rates) } Err(e) => Err(e), } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 71, "total_crates": null }
fn_clm_router_convert_currency_-3726939189834630647
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/currency pub async fn convert_currency( state: SessionState, amount: i64, to_currency: String, from_currency: String, ) -> CustomResult<api_models::currency::CurrencyConversionResponse, ForexError> { let forex_api = state.conf.forex_api.get_inner(); let rates = get_forex_rates(&state, forex_api.data_expiration_delay_in_seconds) .await .change_context(ForexError::ApiError)?; let to_currency = enums::Currency::from_str(to_currency.as_str()) .change_context(ForexError::CurrencyNotAcceptable) .attach_printable("The provided currency is not acceptable")?; let from_currency = enums::Currency::from_str(from_currency.as_str()) .change_context(ForexError::CurrencyNotAcceptable) .attach_printable("The provided currency is not acceptable")?; let converted_amount = currency_conversion::conversion::convert(&rates.data, from_currency, to_currency, amount) .change_context(ForexError::ConversionError) .attach_printable("Unable to perform currency conversion")?; Ok(api_models::currency::CurrencyConversionResponse { converted_amount: converted_amount.to_string(), currency: to_currency.to_string(), }) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 48, "total_crates": null }
fn_clm_router_try_redis_get_else_try_database_get_6830105063282392602
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/db_utils pub async fn try_redis_get_else_try_database_get<F, RFut, DFut, T>( redis_fut: RFut, database_call_closure: F, ) -> error_stack::Result<T, errors::StorageError> where F: FnOnce() -> DFut, RFut: futures::Future<Output = error_stack::Result<T, redis_interface::errors::RedisError>>, DFut: futures::Future<Output = error_stack::Result<T, errors::StorageError>>, { let redis_output = redis_fut.await; match redis_output { Ok(output) => Ok(output), Err(redis_error) => match redis_error.current_context() { redis_interface::errors::RedisError::NotFound => { metrics::KV_MISS.add(1, &[]); database_call_closure().await } // Keeping the key empty here since the error would never go here. _ => Err(redis_error.to_redis_failed_response("")), }, } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 54, "total_crates": null }
fn_clm_router_generate_hscan_pattern_for_refund_6830105063282392602
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/db_utils /// Generates hscan field pattern. Suppose the field is pa_1234_ref_1211 it will generate /// pa_1234_ref_* pub fn generate_hscan_pattern_for_refund(sk: &str) -> String { sk.split('_') .take(3) .chain(["*"]) .collect::<Vec<&str>>() .join("_") }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 18, "total_crates": null }
fn_clm_router_set_tracking_id_in_configs_1291649215695185696
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/connector_onboarding pub async fn set_tracking_id_in_configs( state: &SessionState, connector_id: &common_utils::id_type::MerchantConnectorAccountId, connector: enums::Connector, ) -> RouterResult<()> { let timestamp = common_utils::date_time::now_unix_timestamp().to_string(); let find_config = state .store .find_config_by_key(&build_key(connector_id, connector)) .await; if find_config.is_ok() { state .store .update_config_by_key( &build_key(connector_id, connector), ConfigUpdate::Update { config: Some(timestamp), }, ) .await .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Error updating data in configs table")?; } else if find_config .as_ref() .map_err(|e| e.current_context().is_db_not_found()) .err() .unwrap_or(false) { state .store .insert_config(ConfigNew { key: build_key(connector_id, connector), config: timestamp, }) .await .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Error inserting data in configs table")?; } else { find_config.change_context(ApiErrorResponse::InternalServerError)?; } Ok(()) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 53, "total_crates": null }
fn_clm_router_check_if_connector_exists_1291649215695185696
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/connector_onboarding pub async fn check_if_connector_exists( state: &SessionState, connector_id: &common_utils::id_type::MerchantConnectorAccountId, merchant_id: &common_utils::id_type::MerchantId, ) -> RouterResult<()> { let key_manager_state = &state.into(); let key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .to_not_found_response(ApiErrorResponse::MerchantAccountNotFound)?; #[cfg(feature = "v1")] let _connector = state .store .find_by_merchant_connector_account_merchant_id_merchant_connector_id( key_manager_state, merchant_id, connector_id, &key_store, ) .await .to_not_found_response(ApiErrorResponse::MerchantConnectorAccountNotFound { id: connector_id.get_string_repr().to_string(), })?; #[cfg(feature = "v2")] { let _ = connector_id; let _ = key_store; todo!() }; Ok(()) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 39, "total_crates": null }
fn_clm_router_get_tracking_id_from_configs_1291649215695185696
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/connector_onboarding pub async fn get_tracking_id_from_configs( state: &SessionState, connector_id: &common_utils::id_type::MerchantConnectorAccountId, connector: enums::Connector, ) -> RouterResult<String> { let timestamp = state .store .find_config_by_key_unwrap_or( &build_key(connector_id, connector), Some(common_utils::date_time::now_unix_timestamp().to_string()), ) .await .change_context(ApiErrorResponse::InternalServerError) .attach_printable("Error getting data from configs table")? .config; Ok(format!("{}_{}", connector_id.get_string_repr(), timestamp)) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 28, "total_crates": null }
fn_clm_router_get_connector_auth_1291649215695185696
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/connector_onboarding pub fn get_connector_auth( connector: enums::Connector, connector_data: &settings::ConnectorOnboarding, ) -> RouterResult<types::ConnectorAuthType> { match connector { enums::Connector::Paypal => Ok(types::ConnectorAuthType::BodyKey { api_key: connector_data.paypal.client_secret.clone(), key1: connector_data.paypal.client_id.clone(), }), _ => Err(ApiErrorResponse::NotImplemented { message: NotImplementedMessage::Reason(format!( "Onboarding is not implemented for {connector}", )), } .into()), } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 21, "total_crates": null }
fn_clm_router_is_enabled_1291649215695185696
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/connector_onboarding pub fn is_enabled( connector: types::Connector, conf: &settings::ConnectorOnboarding, ) -> Option<bool> { match connector { enums::Connector::Paypal => Some(conf.paypal.enabled), _ => None, } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 16, "total_crates": null }
fn_clm_router_construct_hyperswitch_ai_interaction_7924688606395330764
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/chat pub async fn construct_hyperswitch_ai_interaction( state: &SessionState, user_from_token: &auth::UserFromToken, req: &chat_api::ChatRequest, response: &chat_api::ChatResponse, request_id: &str, ) -> CustomResult<HyperswitchAiInteractionNew, errors::ApiErrorResponse> { let encryption_key = state.conf.chat.get_inner().encryption_key.clone().expose(); let key = match hex::decode(&encryption_key) { Ok(key) => key, Err(e) => { router_env::logger::error!("Failed to decode encryption key: {}", e); // Fallback to using the string as bytes, which was the previous behavior encryption_key.as_bytes().to_vec() } }; let encrypted_user_query_bytes = GcmAes256 .encode_message(&key, &req.message.clone().expose().into_bytes()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to encrypt user query")?; let encrypted_response_bytes = serde_json::to_vec(&response.response.clone()) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to serialize response for encryption") .and_then(|bytes| { GcmAes256 .encode_message(&key, &bytes) .change_context(errors::ApiErrorResponse::InternalServerError) }) .attach_printable("Failed to encrypt response")?; Ok(HyperswitchAiInteractionNew { id: request_id.to_owned(), session_id: Some(request_id.to_string()), user_id: Some(user_from_token.user_id.clone()), merchant_id: Some(user_from_token.merchant_id.get_string_repr().to_string()), profile_id: Some(user_from_token.profile_id.get_string_repr().to_string()), org_id: Some(user_from_token.org_id.get_string_repr().to_string()), role_id: Some(user_from_token.role_id.clone()), user_query: Some(Encryption::new(encrypted_user_query_bytes.into())), response: Some(Encryption::new(encrypted_response_bytes.into())), database_query: response.query_executed.clone().map(|q| q.expose()), interaction_status: Some(response.status.clone()), created_at: common_utils::date_time::now(), }) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 91, "total_crates": null }
fn_clm_router_build_paypal_post_request_2184835883678995278
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/connector_onboarding/paypal pub fn build_paypal_post_request<T>( url: String, body: T, access_token: String, ) -> RouterResult<Request> where T: serde::Serialize + Send + 'static, { Ok(RequestBuilder::new() .method(Method::Post) .url(&url) .attach_default_headers() .header( header::AUTHORIZATION.to_string().as_str(), format!("Bearer {access_token}").as_str(), ) .header( header::CONTENT_TYPE.to_string().as_str(), "application/json", ) .set_body(RequestContent::Json(Box::new(body))) .build()) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 43, "total_crates": null }
fn_clm_router_generate_access_token_2184835883678995278
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/connector_onboarding/paypal pub async fn generate_access_token(state: SessionState) -> RouterResult<types::AccessToken> { let connector = enums::Connector::Paypal; let boxed_connector = types::api::ConnectorData::convert_connector(connector.to_string().as_str())?; let connector_auth = super::get_connector_auth(connector, state.conf.connector_onboarding.get_inner())?; connector::Paypal::get_access_token( &state, verify_connector_types::VerifyConnectorData { connector: boxed_connector, connector_auth, card_details: verify_connector_utils::get_test_card_details(connector)?.ok_or( ApiErrorResponse::FlowNotSupported { flow: "Connector onboarding".to_string(), connector: connector.to_string(), }, )?, }, ) .await? .ok_or(ApiErrorResponse::InternalServerError) .attach_printable("Error occurred while retrieving access token") }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 40, "total_crates": null }
fn_clm_router_build_paypal_get_request_2184835883678995278
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/connector_onboarding/paypal pub fn build_paypal_get_request(url: String, access_token: String) -> RouterResult<Request> { Ok(RequestBuilder::new() .method(Method::Get) .url(&url) .attach_default_headers() .header( header::AUTHORIZATION.to_string().as_str(), format!("Bearer {access_token}").as_str(), ) .build()) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 34, "total_crates": null }
fn_clm_router_can_user_access_theme_-5688102172796782355
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/user/theme pub async fn can_user_access_theme( user: &UserFromToken, user_entity_type: &EntityType, theme: &Theme, ) -> UserResult<()> { if user_entity_type < &theme.entity_type { return Err(UserErrors::ThemeNotFound.into()); } match theme.entity_type { EntityType::Tenant => { if user.tenant_id.as_ref() == Some(&theme.tenant_id) && theme.org_id.is_none() && theme.merchant_id.is_none() && theme.profile_id.is_none() { Ok(()) } else { Err(UserErrors::ThemeNotFound.into()) } } EntityType::Organization => { if user.tenant_id.as_ref() == Some(&theme.tenant_id) && theme.org_id.as_ref() == Some(&user.org_id) && theme.merchant_id.is_none() && theme.profile_id.is_none() { Ok(()) } else { Err(UserErrors::ThemeNotFound.into()) } } EntityType::Merchant => { if user.tenant_id.as_ref() == Some(&theme.tenant_id) && theme.org_id.as_ref() == Some(&user.org_id) && theme.merchant_id.as_ref() == Some(&user.merchant_id) && theme.profile_id.is_none() { Ok(()) } else { Err(UserErrors::ThemeNotFound.into()) } } EntityType::Profile => { if user.tenant_id.as_ref() == Some(&theme.tenant_id) && theme.org_id.as_ref() == Some(&user.org_id) && theme.merchant_id.as_ref() == Some(&user.merchant_id) && theme.profile_id.as_ref() == Some(&user.profile_id) { Ok(()) } else { Err(UserErrors::ThemeNotFound.into()) } } } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 64, "total_crates": null }
fn_clm_router_get_theme_file_key_-5688102172796782355
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/user/theme pub fn get_theme_file_key(theme_id: &str) -> PathBuf { get_specific_file_key(theme_id, "theme.json") }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 51, "total_crates": null }
fn_clm_router_retrieve_file_from_theme_bucket_-5688102172796782355
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/user/theme pub async fn retrieve_file_from_theme_bucket( state: &SessionState, path: &PathBuf, ) -> UserResult<Vec<u8>> { state .theme_storage_client .retrieve_file(path_buf_to_str(path)?) .await .change_context(UserErrors::ErrorRetrievingFile) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 43, "total_crates": null }
fn_clm_router_get_most_specific_theme_using_token_and_min_entity_-5688102172796782355
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/user/theme pub async fn get_most_specific_theme_using_token_and_min_entity( state: &SessionState, user_from_token: &UserFromToken, min_entity: EntityType, ) -> UserResult<Option<Theme>> { get_most_specific_theme_using_lineage( state, ThemeLineage::new( min_entity, user_from_token .tenant_id .clone() .unwrap_or(state.tenant.tenant_id.clone()), user_from_token.org_id.clone(), user_from_token.merchant_id.clone(), user_from_token.profile_id.clone(), ), ) .await }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 41, "total_crates": null }
fn_clm_router_validate_merchant_and_get_key_store_-5688102172796782355
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/user/theme async fn validate_merchant_and_get_key_store( state: &SessionState, org_id: &id_type::OrganizationId, merchant_id: &id_type::MerchantId, ) -> UserResult<MerchantKeyStore> { let key_store = state .store .get_merchant_key_store_by_merchant_id( &state.into(), merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .to_not_found_response(UserErrors::InvalidThemeLineage("merchant_id".to_string()))?; let merchant_account = state .store .find_merchant_account_by_merchant_id(&state.into(), merchant_id, &key_store) .await .to_not_found_response(UserErrors::InvalidThemeLineage("merchant_id".to_string()))?; if &merchant_account.organization_id != org_id { return Err(UserErrors::InvalidThemeLineage("merchant_id".to_string()).into()); } Ok(key_store) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 38, "total_crates": null }
fn_clm_router_insert_merchant_scoped_metadata_to_db_5832464454137081428
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/user/dashboard_metadata pub async fn insert_merchant_scoped_metadata_to_db( state: &SessionState, user_id: String, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, metadata_key: DBEnum, metadata_value: impl serde::Serialize, ) -> UserResult<DashboardMetadata> { let now = common_utils::date_time::now(); let data_value = serde_json::to_value(metadata_value) .change_context(UserErrors::InternalServerError) .attach_printable("Error Converting Struct To Serde Value")?; state .store .insert_metadata(DashboardMetadataNew { user_id: None, merchant_id, org_id, data_key: metadata_key, data_value: Secret::from(data_value), created_by: user_id.clone(), created_at: now, last_modified_by: user_id, last_modified_at: now, }) .await .map_err(|e| { if e.current_context().is_db_unique_violation() { return e.change_context(UserErrors::MetadataAlreadySet); } e.change_context(UserErrors::InternalServerError) }) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 100, "total_crates": null }
fn_clm_router_deserialize_to_response_5832464454137081428
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/user/dashboard_metadata pub fn deserialize_to_response<T>(data: Option<&DashboardMetadata>) -> UserResult<Option<T>> where T: serde::de::DeserializeOwned, { data.map(|metadata| serde_json::from_value(metadata.data_value.clone().expose())) .transpose() .change_context(UserErrors::InternalServerError) .attach_printable("Error Serializing Metadata from DB") }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 66, "total_crates": null }
fn_clm_router_set_ip_address_if_required_5832464454137081428
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/user/dashboard_metadata pub fn set_ip_address_if_required( request: &mut SetMetaDataRequest, headers: &HeaderMap, ) -> UserResult<()> { if let SetMetaDataRequest::ProductionAgreement(req) = request { let ip_address_from_request: Secret<String, common_utils::pii::IpAddress> = headers .get(headers::X_FORWARDED_FOR) .ok_or(report!(UserErrors::IpAddressParsingFailed)) .attach_printable("X-Forwarded-For header not found")? .to_str() .change_context(UserErrors::IpAddressParsingFailed) .attach_printable("Error converting Header Value to Str")? .split(',') .next() .and_then(|ip| { let ip_addr: Result<IpAddr, _> = ip.parse(); ip_addr.ok() }) .ok_or(report!(UserErrors::IpAddressParsingFailed)) .attach_printable("Error Parsing header value to ip")? .to_string() .into(); req.ip_address = Some(ip_address_from_request) } Ok(()) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 43, "total_crates": null }
fn_clm_router_is_prod_email_required_5832464454137081428
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/user/dashboard_metadata pub fn is_prod_email_required(data: &ProdIntent, user_email: String) -> bool { let poc_email_check = not_contains_string( data.poc_email.as_ref().map(|email| email.peek().as_str()), "juspay", ); let business_website_check = not_contains_string(data.business_website.as_ref().map(|s| s.as_str()), "juspay") && not_contains_string( data.business_website.as_ref().map(|s| s.as_str()), "hyperswitch", ); let user_email_check = not_contains_string(Some(&user_email), "juspay"); if (poc_email_check && business_website_check && user_email_check).not() { logger::info!(prod_intent_email = poc_email_check); logger::info!(prod_intent_email = business_website_check); logger::info!(prod_intent_email = user_email_check); } poc_email_check && business_website_check && user_email_check }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 43, "total_crates": null }
fn_clm_router_insert_user_scoped_metadata_to_db_5832464454137081428
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/user/dashboard_metadata pub async fn insert_user_scoped_metadata_to_db( state: &SessionState, user_id: String, merchant_id: id_type::MerchantId, org_id: id_type::OrganizationId, metadata_key: DBEnum, metadata_value: impl serde::Serialize, ) -> UserResult<DashboardMetadata> { let now = common_utils::date_time::now(); let data_value = serde_json::to_value(metadata_value) .change_context(UserErrors::InternalServerError) .attach_printable("Error Converting Struct To Serde Value")?; state .store .insert_metadata(DashboardMetadataNew { user_id: Some(user_id.clone()), merchant_id, org_id, data_key: metadata_key, data_value: Secret::from(data_value), created_by: user_id.clone(), created_at: now, last_modified_by: user_id, last_modified_at: now, }) .await .map_err(|e| { if e.current_context().is_db_unique_violation() { return e.change_context(UserErrors::MetadataAlreadySet); } e.change_context(UserErrors::InternalServerError) }) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 42, "total_crates": null }
fn_clm_router_generate_password_hash_-5431158025595930369
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/user/password pub fn generate_password_hash( password: Secret<String>, ) -> CustomResult<Secret<String>, UserErrors> { let salt = SaltString::generate(&mut OsRng); let argon2 = Argon2::default(); let password_hash = argon2 .hash_password(password.expose().as_bytes(), &salt) .change_context(UserErrors::InternalServerError)?; Ok(Secret::new(password_hash.to_string())) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 35, "total_crates": null }
fn_clm_router_is_correct_password_-5431158025595930369
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/user/password pub fn is_correct_password( candidate: &Secret<String>, password: &Secret<String>, ) -> CustomResult<bool, UserErrors> { let password = password.peek(); let parsed_hash = PasswordHash::new(password).change_context(UserErrors::InternalServerError)?; let result = Argon2::default().verify_password(candidate.peek().as_bytes(), &parsed_hash); match result { Ok(_) => Ok(true), Err(argon2Err::Password) => Ok(false), Err(e) => Err(e), } .change_context(UserErrors::InternalServerError) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 32, "total_crates": null }
fn_clm_router_get_temp_password_-5431158025595930369
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/user/password pub fn get_temp_password() -> Secret<String> { let uuid_pass = uuid::Uuid::new_v4().to_string(); let mut rng = rand::thread_rng(); let special_chars: Vec<char> = "!@#$%^&*()-_=+[]{}|;:,.<>?".chars().collect(); let special_char = special_chars.choose(&mut rng).unwrap_or(&'@'); Secret::new(format!( "{}{}{}{}{}", uuid_pass, rng.gen_range('A'..='Z'), special_char, rng.gen_range('a'..='z'), rng.gen_range('0'..='9'), )) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 26, "total_crates": null }
fn_clm_router_get_index_for_correct_recovery_code_-5431158025595930369
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/user/password pub fn get_index_for_correct_recovery_code( candidate: &Secret<String>, recovery_codes: &[Secret<String>], ) -> CustomResult<Option<usize>, UserErrors> { for (index, recovery_code) in recovery_codes.iter().enumerate() { let is_match = is_correct_password(candidate, recovery_code)?; if is_match { return Ok(Some(index)); } } Ok(None) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 19, "total_crates": null }
fn_clm_router_generate_default_totp_-2955692600061598279
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/user/two_factor_auth pub fn generate_default_totp( email: pii::Email, secret: Option<masking::Secret<String>>, issuer: String, ) -> UserResult<TOTP> { let secret = secret .map(|sec| totp_rs::Secret::Encoded(sec.expose())) .unwrap_or_else(totp_rs::Secret::generate_secret) .to_bytes() .change_context(UserErrors::InternalServerError)?; TOTP::new( Algorithm::SHA1, consts::user::TOTP_DIGITS, consts::user::TOTP_TOLERANCE, consts::user::TOTP_VALIDITY_DURATION_IN_SECONDS, secret, Some(issuer), email.expose().expose(), ) .change_context(UserErrors::InternalServerError) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 42, "total_crates": null }
fn_clm_router_check_totp_in_redis_-2955692600061598279
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/user/two_factor_auth pub async fn check_totp_in_redis(state: &SessionState, user_id: &str) -> UserResult<bool> { let redis_conn = super::get_redis_connection_for_global_tenant(state)?; let key = format!("{}{}", consts::user::REDIS_TOTP_PREFIX, user_id); redis_conn .exists::<()>(&key.into()) .await .change_context(UserErrors::InternalServerError) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 31, "total_crates": null }
fn_clm_router_check_recovery_code_in_redis_-2955692600061598279
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/user/two_factor_auth pub async fn check_recovery_code_in_redis(state: &SessionState, user_id: &str) -> UserResult<bool> { let redis_conn = super::get_redis_connection_for_global_tenant(state)?; let key = format!("{}{}", consts::user::REDIS_RECOVERY_CODE_PREFIX, user_id); redis_conn .exists::<()>(&key.into()) .await .change_context(UserErrors::InternalServerError) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 28, "total_crates": null }
fn_clm_router_insert_totp_in_redis_-2955692600061598279
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/user/two_factor_auth pub async fn insert_totp_in_redis(state: &SessionState, user_id: &str) -> UserResult<()> { let redis_conn = super::get_redis_connection_for_global_tenant(state)?; let key = format!("{}{}", consts::user::REDIS_TOTP_PREFIX, user_id); redis_conn .set_key_with_expiry( &key.as_str().into(), common_utils::date_time::now_unix_timestamp(), state.conf.user.two_factor_auth_expiry_in_secs, ) .await .change_context(UserErrors::InternalServerError) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 28, "total_crates": null }
fn_clm_router_insert_totp_secret_in_redis_-2955692600061598279
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/user/two_factor_auth pub async fn insert_totp_secret_in_redis( state: &SessionState, user_id: &str, secret: &masking::Secret<String>, ) -> UserResult<()> { let redis_conn = super::get_redis_connection_for_global_tenant(state)?; redis_conn .set_key_with_expiry( &get_totp_secret_key(user_id).into(), secret.peek(), consts::user::REDIS_TOTP_SECRET_TTL_IN_SECS, ) .await .change_context(UserErrors::InternalServerError) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 28, "total_crates": null }
fn_clm_router_generate_sample_data_-5489816440962390563
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/user/sample_data pub async fn generate_sample_data( state: &SessionState, req: SampleDataRequest, merchant_id: &id_type::MerchantId, org_id: &id_type::OrganizationId, ) -> SampleDataResult< Vec<( PaymentIntent, PaymentAttemptBatchNew, Option<RefundNew>, Option<DisputeNew>, )>, > { let sample_data_size: usize = req.record.unwrap_or(100); let key_manager_state = &state.into(); if !(10..=100).contains(&sample_data_size) { return Err(SampleDataError::InvalidRange.into()); } let key_store = state .store .get_merchant_key_store_by_merchant_id( key_manager_state, merchant_id, &state.store.get_master_key().to_vec().into(), ) .await .change_context(SampleDataError::InternalServerError)?; let merchant_from_db = state .store .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store) .await .change_context::<SampleDataError>(SampleDataError::DataDoesNotExist)?; let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(domain::Context( merchant_from_db.clone(), key_store, ))); #[cfg(feature = "v1")] let (profile_id_result, business_country_default, business_label_default) = { let merchant_parsed_details: Vec<api_models::admin::PrimaryBusinessDetails> = serde_json::from_value(merchant_from_db.primary_business_details.clone()) .change_context(SampleDataError::InternalServerError) .attach_printable("Error while parsing primary business details")?; let business_country_default = merchant_parsed_details.first().map(|x| x.country); let business_label_default = merchant_parsed_details.first().map(|x| x.business.clone()); let profile_id = crate::core::utils::get_profile_id_from_business_details( key_manager_state, business_country_default, business_label_default.as_ref(), &merchant_context, req.profile_id.as_ref(), &*state.store, false, ) .await; (profile_id, business_country_default, business_label_default) }; #[cfg(feature = "v2")] let (profile_id_result, business_country_default, business_label_default) = { let profile_id = req .profile_id.clone() .ok_or(hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse::MissingRequiredField { field_name: "profile_id", }); (profile_id, None, None) }; let profile_id = match profile_id_result { Ok(id) => id.clone(), Err(error) => { router_env::logger::error!( "Profile ID not found in business details. Attempting to fetch from the database {error:?}" ); state .store .list_profile_by_merchant_id( key_manager_state, merchant_context.get_merchant_key_store(), merchant_id, ) .await .change_context(SampleDataError::InternalServerError) .attach_printable("Failed to get business profile")? .first() .ok_or(SampleDataError::InternalServerError)? .get_id() .to_owned() } }; // 10 percent payments should be failed #[allow(clippy::as_conversions)] let failure_attempts = usize::try_from((sample_data_size as f32 / 10.0).round() as i64) .change_context(SampleDataError::InvalidParameters)?; let failure_after_attempts = sample_data_size / failure_attempts; // 20 percent refunds for payments #[allow(clippy::as_conversions)] let number_of_refunds = usize::try_from((sample_data_size as f32 / 5.0).round() as i64) .change_context(SampleDataError::InvalidParameters)?; let mut refunds_count = 0; // 2 disputes if generated data size is between 50 and 100, 1 dispute if it is less than 50. let number_of_disputes: usize = if sample_data_size >= 50 { 2 } else { 1 }; let mut disputes_count = 0; let mut random_array: Vec<usize> = (1..=sample_data_size).collect(); // Shuffle the array let mut rng = thread_rng(); random_array.shuffle(&mut rng); let mut res: Vec<( PaymentIntent, PaymentAttemptBatchNew, Option<RefundNew>, Option<DisputeNew>, )> = Vec::new(); let start_time = req .start_time .unwrap_or(common_utils::date_time::now() - time::Duration::days(7)) .assume_utc() .unix_timestamp(); let end_time = req .end_time .unwrap_or_else(common_utils::date_time::now) .assume_utc() .unix_timestamp(); let current_time = common_utils::date_time::now().assume_utc().unix_timestamp(); let min_amount = req.min_amount.unwrap_or(100); let max_amount = req.max_amount.unwrap_or(min_amount + 100); if min_amount > max_amount || start_time > end_time || start_time > current_time || end_time > current_time { return Err(SampleDataError::InvalidParameters.into()); }; let currency_vec = req.currency.unwrap_or(vec![common_enums::Currency::USD]); let currency_vec_len = currency_vec.len(); let connector_vec = req .connector .unwrap_or(vec![DummyConnector4, DummyConnector7]); let connector_vec_len = connector_vec.len(); let auth_type = req.auth_type.unwrap_or(vec![ common_enums::AuthenticationType::ThreeDs, common_enums::AuthenticationType::NoThreeDs, ]); let auth_type_len = auth_type.len(); if currency_vec_len == 0 || connector_vec_len == 0 || auth_type_len == 0 { return Err(SampleDataError::InvalidParameters.into()); } // This has to be an internal server error because, this function failing means that the intended functionality is not working as expected let dashboard_customer_id = id_type::CustomerId::try_from(std::borrow::Cow::from("hs-dashboard-user")) .change_context(SampleDataError::InternalServerError)?; for num in 1..=sample_data_size { let payment_id = id_type::PaymentId::generate_test_payment_id_for_sample_data(); let attempt_id = payment_id.get_attempt_id(1); let client_secret = payment_id.generate_client_secret(); let amount = thread_rng().gen_range(min_amount..=max_amount); let created_at @ modified_at @ last_synced = OffsetDateTime::from_unix_timestamp(thread_rng().gen_range(start_time..=end_time)) .map(common_utils::date_time::convert_to_pdt) .unwrap_or( req.start_time.unwrap_or_else(|| { common_utils::date_time::now() - time::Duration::days(7) }), ); let session_expiry = created_at.saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)); // After some set of payments sample data will have a failed attempt let is_failed_payment = (random_array.get(num - 1).unwrap_or(&0) % failure_after_attempts) == 0; let payment_intent = PaymentIntent { payment_id: payment_id.clone(), merchant_id: merchant_id.clone(), status: match is_failed_payment { true => common_enums::IntentStatus::Failed, _ => common_enums::IntentStatus::Succeeded, }, amount: MinorUnit::new(amount * 100), currency: Some( *currency_vec .get((num - 1) % currency_vec_len) .unwrap_or(&common_enums::Currency::USD), ), description: Some("This is a sample payment".to_string()), created_at, modified_at, last_synced: Some(last_synced), client_secret: Some(client_secret), business_country: business_country_default, business_label: business_label_default.clone(), active_attempt: hyperswitch_domain_models::RemoteStorageObject::ForeignID( attempt_id.clone(), ), attempt_count: 1, customer_id: Some(dashboard_customer_id.clone()), amount_captured: Some(MinorUnit::new(amount * 100)), profile_id: Some(profile_id.clone()), return_url: Default::default(), metadata: Default::default(), connector_id: Default::default(), shipping_address_id: Default::default(), billing_address_id: Default::default(), statement_descriptor_name: Default::default(), statement_descriptor_suffix: Default::default(), setup_future_usage: Default::default(), off_session: Default::default(), order_details: Default::default(), allowed_payment_method_types: Default::default(), connector_metadata: Default::default(), feature_metadata: Default::default(), merchant_decision: Default::default(), payment_link_id: Default::default(), payment_confirm_source: Default::default(), updated_by: merchant_from_db.storage_scheme.to_string(), surcharge_applicable: Default::default(), request_incremental_authorization: Default::default(), incremental_authorization_allowed: Default::default(), authorization_count: Default::default(), fingerprint_id: None, session_expiry: Some(session_expiry), request_external_three_ds_authentication: None, split_payments: None, frm_metadata: Default::default(), customer_details: None, billing_details: None, merchant_order_reference_id: Default::default(), shipping_details: None, is_payment_processor_token_flow: None, organization_id: org_id.clone(), shipping_cost: None, tax_details: None, skip_external_tax_calculation: None, request_extended_authorization: None, psd2_sca_exemption_type: None, processor_merchant_id: merchant_id.clone(), created_by: None, force_3ds_challenge: None, force_3ds_challenge_trigger: None, is_iframe_redirection_enabled: None, is_payment_id_from_merchant: None, payment_channel: None, order_date: None, discount_amount: None, duty_amount: None, tax_status: None, shipping_amount_tax: None, enable_partial_authorization: None, enable_overcapture: None, mit_category: None, }; let (connector_transaction_id, processor_transaction_data) = ConnectorTransactionId::form_id_and_data(attempt_id.clone()); let payment_attempt = PaymentAttemptBatchNew { attempt_id: attempt_id.clone(), payment_id: payment_id.clone(), connector_transaction_id: Some(connector_transaction_id), merchant_id: merchant_id.clone(), status: match is_failed_payment { true => common_enums::AttemptStatus::Failure, _ => common_enums::AttemptStatus::Charged, }, amount: MinorUnit::new(amount * 100), currency: payment_intent.currency, connector: Some( (*connector_vec .get((num - 1) % connector_vec_len) .unwrap_or(&DummyConnector4)) .to_string(), ), payment_method: Some(common_enums::PaymentMethod::Card), payment_method_type: Some(get_payment_method_type(thread_rng().gen_range(1..=2))), authentication_type: Some( *auth_type .get((num - 1) % auth_type_len) .unwrap_or(&common_enums::AuthenticationType::NoThreeDs), ), error_message: match is_failed_payment { true => Some("This is a test payment which has a failed status".to_string()), _ => None, }, error_code: match is_failed_payment { true => Some("HS001".to_string()), _ => None, }, confirm: true, created_at, modified_at, last_synced: Some(last_synced), amount_to_capture: Some(MinorUnit::new(amount * 100)), connector_response_reference_id: Some(attempt_id.clone()), updated_by: merchant_from_db.storage_scheme.to_string(), save_to_locker: None, offer_amount: None, surcharge_amount: None, tax_amount: None, payment_method_id: None, capture_method: None, capture_on: None, cancellation_reason: None, mandate_id: None, browser_info: None, payment_token: None, connector_metadata: None, payment_experience: None, payment_method_data: None, business_sub_label: None, straight_through_algorithm: None, preprocessing_step_id: None, mandate_details: None, error_reason: None, multiple_capture_count: None, amount_capturable: MinorUnit::new(i64::default()), merchant_connector_id: None, authentication_data: None, encoded_data: None, unified_code: None, unified_message: None, net_amount: None, external_three_ds_authentication_attempted: None, authentication_connector: None, authentication_id: None, mandate_data: None, payment_method_billing_address_id: None, fingerprint_id: None, charge_id: None, client_source: None, client_version: None, customer_acceptance: None, profile_id: profile_id.clone(), organization_id: org_id.clone(), shipping_cost: None, order_tax_amount: None, processor_transaction_data, connector_mandate_detail: None, request_extended_authorization: None, extended_authorization_applied: None, capture_before: None, card_discovery: None, processor_merchant_id: Some(merchant_id.clone()), created_by: None, setup_future_usage_applied: None, routing_approach: None, connector_request_reference_id: None, network_transaction_id: None, network_details: None, is_stored_credential: None, authorized_amount: None, }; let refund = if refunds_count < number_of_refunds && !is_failed_payment { refunds_count += 1; let (connector_transaction_id, processor_transaction_data) = ConnectorTransactionId::form_id_and_data(attempt_id.clone()); Some(RefundNew { refund_id: common_utils::generate_id_with_default_len("test"), internal_reference_id: common_utils::generate_id_with_default_len("test"), external_reference_id: None, payment_id: payment_id.clone(), attempt_id: attempt_id.clone(), merchant_id: merchant_id.clone(), connector_transaction_id, connector_refund_id: None, description: Some("This is a sample refund".to_string()), created_at, modified_at, refund_reason: Some("Sample Refund".to_string()), connector: payment_attempt .connector .clone() .unwrap_or(DummyConnector4.to_string()), currency: *currency_vec .get((num - 1) % currency_vec_len) .unwrap_or(&common_enums::Currency::USD), total_amount: MinorUnit::new(amount * 100), refund_amount: MinorUnit::new(amount * 100), refund_status: common_enums::RefundStatus::Success, sent_to_gateway: true, refund_type: diesel_models::enums::RefundType::InstantRefund, metadata: None, refund_arn: None, profile_id: payment_intent.profile_id.clone(), updated_by: merchant_from_db.storage_scheme.to_string(), merchant_connector_id: payment_attempt.merchant_connector_id.clone(), charges: None, split_refunds: None, organization_id: org_id.clone(), processor_refund_data: None, processor_transaction_data, }) } else { None }; let dispute = if disputes_count < number_of_disputes && !is_failed_payment && refund.is_none() { disputes_count += 1; let currency = payment_intent .currency .unwrap_or(common_enums::Currency::USD); Some(DisputeNew { dispute_id: common_utils::generate_id_with_default_len("test"), amount: StringMinorUnitForConnector::convert( &StringMinorUnitForConnector, MinorUnit::new(amount * 100), currency, ) .change_context(SampleDataError::InternalServerError)?, currency: currency.to_string(), dispute_stage: storage_enums::DisputeStage::Dispute, dispute_status: storage_enums::DisputeStatus::DisputeOpened, payment_id: payment_id.clone(), attempt_id: attempt_id.clone(), merchant_id: merchant_id.clone(), connector_status: "Sample connector status".into(), connector_dispute_id: common_utils::generate_id_with_default_len("test"), connector_reason: Some("Sample Dispute".into()), connector_reason_code: Some("123".into()), challenge_required_by: None, connector_created_at: None, connector_updated_at: None, connector: payment_attempt .connector .clone() .unwrap_or(DummyConnector4.to_string()), evidence: None, profile_id: payment_intent.profile_id.clone(), merchant_connector_id: payment_attempt.merchant_connector_id.clone(), dispute_amount: MinorUnit::new(amount * 100), organization_id: org_id.clone(), dispute_currency: Some(payment_intent.currency.unwrap_or_default()), }) } else { None }; res.push((payment_intent, payment_attempt, refund, dispute)); } Ok(res) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 397, "total_crates": null }
fn_clm_router_get_payment_method_type_-5489816440962390563
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/utils/user/sample_data fn get_payment_method_type(num: u8) -> common_enums::PaymentMethodType { let rem: u8 = (num) % 2; match rem { 0 => common_enums::PaymentMethodType::Debit, _ => common_enums::PaymentMethodType::Credit, } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 111, "total_crates": null }
fn_clm_router_default_-662431829661104316
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/configs/defaults // Implementation of super::settings::ApiKeys for Default fn default() -> Self { Self { // Hex-encoded 32-byte long (64 characters long when hex-encoded) key used for calculating // hashes of API keys hash_key: String::new().into(), // Specifies the number of days before API key expiry when email reminders should be sent #[cfg(feature = "email")] expiry_reminder_days: vec![7, 3, 1], // Hex-encoded key used for calculating checksum for partial auth #[cfg(feature = "partial-auth")] checksum_auth_key: String::new().into(), // context used for blake3 #[cfg(feature = "partial-auth")] checksum_auth_context: String::new().into(), #[cfg(feature = "partial-auth")] enable_partial_auth: false, } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 7715, "total_crates": null }
fn_clm_router_convert_to_raw_secret_8795890677314072763
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/configs/secrets_transformers // Implementation of settings::NetworkTokenizationService for SecretsHandler async fn convert_to_raw_secret( value: SecretStateContainer<Self, SecuredSecret>, secret_management_client: &dyn SecretManagementInterface, ) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> { let network_tokenization = value.get_inner(); let token_service_api_key = secret_management_client .get_secret(network_tokenization.token_service_api_key.clone()) .await?; let public_key = secret_management_client .get_secret(network_tokenization.public_key.clone()) .await?; let private_key = secret_management_client .get_secret(network_tokenization.private_key.clone()) .await?; let webhook_source_verification_key = secret_management_client .get_secret(network_tokenization.webhook_source_verification_key.clone()) .await?; Ok(value.transition_state(|network_tokenization| Self { public_key, private_key, token_service_api_key, webhook_source_verification_key, ..network_tokenization })) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 82, "total_crates": null }
fn_clm_router_fetch_raw_secrets_8795890677314072763
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/configs/secrets_transformers /// # 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"); #[cfg(feature = "olap")] #[allow(clippy::expect_used)] let analytics = analytics::AnalyticsConfig::convert_to_raw_secret(conf.analytics, secret_management_client) .await .expect("Failed to decrypt analytics configuration"); #[cfg(feature = "olap")] #[allow(clippy::expect_used)] let replica_database = settings::Database::convert_to_raw_secret(conf.replica_database, secret_management_client) .await .expect("Failed to decrypt replica database configuration"); #[allow(clippy::expect_used)] let secrets = settings::Secrets::convert_to_raw_secret(conf.secrets, secret_management_client) .await .expect("Failed to decrypt secrets"); #[allow(clippy::expect_used)] let forex_api = settings::ForexApi::convert_to_raw_secret(conf.forex_api, secret_management_client) .await .expect("Failed to decrypt forex api configs"); #[allow(clippy::expect_used)] let jwekey = settings::Jwekey::convert_to_raw_secret(conf.jwekey, secret_management_client) .await .expect("Failed to decrypt jwekey configs"); #[allow(clippy::expect_used)] let api_keys = settings::ApiKeys::convert_to_raw_secret(conf.api_keys, secret_management_client) .await .expect("Failed to decrypt api_keys configs"); #[cfg(feature = "olap")] #[allow(clippy::expect_used)] let connector_onboarding = settings::ConnectorOnboarding::convert_to_raw_secret( conf.connector_onboarding, secret_management_client, ) .await .expect("Failed to decrypt connector_onboarding configs"); #[allow(clippy::expect_used)] let applepay_decrypt_keys = settings::ApplePayDecryptConfig::convert_to_raw_secret( conf.applepay_decrypt_keys, secret_management_client, ) .await .expect("Failed to decrypt applepay decrypt configs"); #[allow(clippy::expect_used)] let paze_decrypt_keys = if let Some(paze_keys) = conf.paze_decrypt_keys { Some( settings::PazeDecryptConfig::convert_to_raw_secret(paze_keys, secret_management_client) .await .expect("Failed to decrypt paze decrypt configs"), ) } else { None }; #[allow(clippy::expect_used)] let applepay_merchant_configs = settings::ApplepayMerchantConfigs::convert_to_raw_secret( conf.applepay_merchant_configs, secret_management_client, ) .await .expect("Failed to decrypt applepay merchant configs"); #[allow(clippy::expect_used)] let payment_method_auth = settings::PaymentMethodAuth::convert_to_raw_secret( conf.payment_method_auth, secret_management_client, ) .await .expect("Failed to decrypt payment method auth configs"); #[allow(clippy::expect_used)] let key_manager = settings::KeyManagerConfig::convert_to_raw_secret( conf.key_manager, secret_management_client, ) .await .expect("Failed to decrypt keymanager configs"); #[allow(clippy::expect_used)] let user_auth_methods = settings::UserAuthMethodSettings::convert_to_raw_secret( conf.user_auth_methods, secret_management_client, ) .await .expect("Failed to decrypt user_auth_methods configs"); #[allow(clippy::expect_used)] 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; #[allow(clippy::expect_used)] let chat = settings::ChatSettings::convert_to_raw_secret(conf.chat, secret_management_client) .await .expect("Failed to decrypt chat configs"); #[allow(clippy::expect_used)] let superposition = external_services::superposition::SuperpositionClientConfig::convert_to_raw_secret( conf.superposition, secret_management_client, ) .await .expect("Failed to decrypt superposition config"); Settings { server: conf.server, chat, 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, zero_mandates: conf.zero_mandates, network_transaction_id_supported_connectors: conf .network_transaction_id_supported_connectors, list_dispute_supported_connectors: conf.list_dispute_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, billing_connectors_invoice_sync: conf.billing_connectors_invoice_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, crm: conf.crm, #[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, l2_l3_data_config: conf.l2_l3_data_config, authentication_providers: conf.authentication_providers, open_router: conf.open_router, #[cfg(feature = "v2")] revenue_recovery: conf.revenue_recovery, debit_routing_config: conf.debit_routing_config, clone_connector_allowlist: conf.clone_connector_allowlist, merchant_id_auth: conf.merchant_id_auth, internal_merchant_id_profile_id_auth: conf.internal_merchant_id_profile_id_auth, infra_values: conf.infra_values, enhancement: conf.enhancement, proxy_status_mapping: conf.proxy_status_mapping, internal_services: conf.internal_services, superposition, comparison_service: conf.comparison_service, } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 49, "total_crates": null }
fn_clm_router_new_-2170337367866431088
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/configs/settings // Implementation of None for Settings<SecuredSecret> pub fn new() -> ApplicationResult<Self> { Self::with_config_path(None) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 14465, "total_crates": null }
fn_clm_router_default_-2170337367866431088
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/configs/settings // Implementation of CellInformation for Default fn default() -> Self { // We provide a static default cell id for constructing application settings. // This will only panic at application startup if we're unable to construct the default, // around the time of deserializing application settings. // And a panic at application startup is considered acceptable. #[allow(clippy::expect_used)] let cell_id = id_type::CellId::from_string("defid").expect("Failed to create a default for Cell Id"); Self { id: cell_id } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 7705, "total_crates": null }
fn_clm_router_from_-2170337367866431088
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/configs/settings // Implementation of storage_impl::config::Database for From<Database> fn from(val: Database) -> Self { Self { username: val.username, password: val.password, host: val.host, port: val.port, dbname: val.dbname, pool_size: val.pool_size, connection_timeout: val.connection_timeout, queue_strategy: val.queue_strategy, min_idle: val.min_idle, max_lifetime: val.max_lifetime, } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 2600, "total_crates": null }
fn_clm_router_validate_-2170337367866431088
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/configs/settings // Implementation of None for Settings<SecuredSecret> pub fn validate(&self) -> ApplicationResult<()> { self.server.validate()?; self.master_database.get_inner().validate()?; #[cfg(feature = "olap")] self.replica_database.get_inner().validate()?; // The logger may not yet be initialized when validating the application configuration #[allow(clippy::print_stderr)] self.redis.validate().map_err(|error| { eprintln!("{error}"); ApplicationError::InvalidConfigurationValueError("Redis configuration".into()) })?; if self.log.file.enabled { if self.log.file.file_name.is_default_or_empty() { return Err(error_stack::Report::from( ApplicationError::InvalidConfigurationValueError( "log file name must not be empty".into(), ), )); } if self.log.file.path.is_default_or_empty() { return Err(error_stack::Report::from( ApplicationError::InvalidConfigurationValueError( "log directory path must not be empty".into(), ), )); } } self.secrets.get_inner().validate()?; self.locker.validate()?; self.connectors.validate("connectors")?; self.chat.get_inner().validate()?; self.cors.validate()?; self.scheduler .as_ref() .map(|scheduler_settings| scheduler_settings.validate()) .transpose()?; #[cfg(feature = "kv_store")] self.drainer.validate()?; self.api_keys.get_inner().validate()?; self.file_storage .validate() .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?; self.crm .validate() .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?; self.lock_settings.validate()?; self.events.validate()?; #[cfg(feature = "olap")] self.opensearch.validate()?; self.encryption_management .validate() .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.into()))?; self.secrets_management .validate() .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.into()))?; self.generic_link.payment_method_collect.validate()?; self.generic_link.payout_link.validate()?; #[cfg(feature = "v2")] self.cell_information.validate()?; self.network_tokenization_service .as_ref() .map(|x| x.get_inner().validate()) .transpose()?; self.paze_decrypt_keys .as_ref() .map(|x| x.get_inner().validate()) .transpose()?; self.google_pay_decrypt_keys .as_ref() .map(|x| x.validate()) .transpose()?; self.key_manager.get_inner().validate()?; #[cfg(feature = "email")] self.email .validate() .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.into()))?; self.theme .storage .validate() .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?; self.platform.validate()?; self.open_router.validate()?; // Validate gRPC client settings #[cfg(feature = "revenue_recovery")] self.grpc_client .recovery_decider_client .as_ref() .map(|config| config.validate()) .transpose() .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?; self.superposition .get_inner() .validate() .map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?; Ok(()) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 401, "total_crates": null }
fn_clm_router_deserialize_-2170337367866431088
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/configs/settings // Implementation of TenantConfig for Deserialize<'de> fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> { #[derive(Deserialize)] struct Inner { base_url: String, schema: String, accounts_schema: String, redis_key_prefix: String, clickhouse_database: String, user: TenantUserConfig, } let hashmap = <HashMap<id_type::TenantId, Inner>>::deserialize(deserializer)?; Ok(Self( hashmap .into_iter() .map(|(key, value)| { ( key.clone(), Tenant { tenant_id: key, base_url: value.base_url, schema: value.schema, accounts_schema: value.accounts_schema, redis_key_prefix: value.redis_key_prefix, clickhouse_database: value.clickhouse_database, user: value.user, }, ) }) .collect(), )) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 146, "total_crates": null }
fn_clm_router_validate_-8393998494310486621
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/configs/validations // Inherent implementation for super::settings::ChatSettings pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; when(self.enabled && self.hyperswitch_ai_host.is_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "hyperswitch ai host must be set if chat is enabled".into(), )) }) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 227, "total_crates": null }
fn_clm_router_default_496459316428462322
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/configs/defaults/payout_required_fields // Implementation of PayoutRequiredFields for Default fn default() -> Self { Self(HashMap::from([ ( Card, PaymentMethodTypeInfo(HashMap::from([ // Adyen get_connector_payment_method_type_fields( PayoutConnectors::Adyenplatform, PaymentMethodType::Debit, ), get_connector_payment_method_type_fields( PayoutConnectors::Adyenplatform, PaymentMethodType::Credit, ), ])), ), ( BankTransfer, PaymentMethodTypeInfo(HashMap::from([ // Adyen get_connector_payment_method_type_fields( PayoutConnectors::Adyenplatform, PaymentMethodType::SepaBankTransfer, ), // Ebanx get_connector_payment_method_type_fields( PayoutConnectors::Ebanx, PaymentMethodType::Pix, ), // Wise get_connector_payment_method_type_fields( PayoutConnectors::Wise, PaymentMethodType::Bacs, ), ])), ), ( Wallet, PaymentMethodTypeInfo(HashMap::from([ // Adyen get_connector_payment_method_type_fields( PayoutConnectors::Adyenplatform, PaymentMethodType::Paypal, ), ])), ), ])) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 7731, "total_crates": null }
fn_clm_router_get_connector_payment_method_type_fields_496459316428462322
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/configs/defaults/payout_required_fields fn get_connector_payment_method_type_fields( connector: PayoutConnectors, payment_method_type: PaymentMethodType, ) -> (PaymentMethodType, ConnectorFields) { let mut common_fields = get_billing_details_for_payment_method(connector, payment_method_type); match payment_method_type { // Card PaymentMethodType::Debit => { common_fields.extend(get_card_fields()); ( payment_method_type, ConnectorFields { fields: HashMap::from([( connector.into(), RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: common_fields, }, )]), }, ) } PaymentMethodType::Credit => { common_fields.extend(get_card_fields()); ( payment_method_type, ConnectorFields { fields: HashMap::from([( connector.into(), RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: common_fields, }, )]), }, ) } // Banks PaymentMethodType::Bacs => { common_fields.extend(get_bacs_fields()); ( payment_method_type, ConnectorFields { fields: HashMap::from([( connector.into(), RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: common_fields, }, )]), }, ) } PaymentMethodType::Pix => { common_fields.extend(get_pix_bank_transfer_fields()); ( payment_method_type, ConnectorFields { fields: HashMap::from([( connector.into(), RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: common_fields, }, )]), }, ) } PaymentMethodType::SepaBankTransfer => { common_fields.extend(get_sepa_fields()); ( payment_method_type, ConnectorFields { fields: HashMap::from([( connector.into(), RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: common_fields, }, )]), }, ) } // Wallets PaymentMethodType::Paypal => { common_fields.extend(get_paypal_fields()); ( payment_method_type, ConnectorFields { fields: HashMap::from([( connector.into(), RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: common_fields, }, )]), }, ) } // Bank Redirect PaymentMethodType::Interac => { common_fields.extend(get_interac_fields(connector)); ( payment_method_type, ConnectorFields { fields: HashMap::from([( connector.into(), RequiredFieldFinal { mandate: HashMap::new(), non_mandate: HashMap::new(), common: common_fields, }, )]), }, ) } _ => ( payment_method_type, ConnectorFields { fields: HashMap::new(), }, ), } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 106, "total_crates": null }
fn_clm_router_get_billing_details_496459316428462322
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/configs/defaults/payout_required_fields fn get_billing_details(connector: PayoutConnectors) -> HashMap<String, RequiredFieldInfo> { match connector { PayoutConnectors::Adyen => HashMap::from([ ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "billing.address.line1".to_string(), display_name: "billing_address_line1".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.line2".to_string(), RequiredFieldInfo { required_field: "billing.address.line2".to_string(), display_name: "billing_address_line2".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "billing.address.city".to_string(), display_name: "billing_address_city".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "billing.address.zip".to_string(), display_name: "billing_address_zip".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "billing.address.country".to_string(), display_name: "billing_address_country".to_string(), field_type: FieldType::UserAddressCountry { options: get_countries_for_connector(connector) .iter() .map(|country| country.to_string()) .collect::<Vec<String>>(), }, value: None, }, ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "billing.address.first_name".to_string(), display_name: "billing_address_first_name".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "billing.address.last_name".to_string(), display_name: "billing_address_last_name".to_string(), field_type: FieldType::Text, value: None, }, ), ]), PayoutConnectors::Wise => HashMap::from([ ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "billing.address.line1".to_string(), display_name: "billing_address_line1".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "billing.address.city".to_string(), display_name: "billing_address_city".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.state".to_string(), RequiredFieldInfo { required_field: "billing.address.state".to_string(), display_name: "billing_address_state".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.zip".to_string(), RequiredFieldInfo { required_field: "billing.address.zip".to_string(), display_name: "billing_address_zip".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "billing.address.country".to_string(), display_name: "billing_address_country".to_string(), field_type: FieldType::UserAddressCountry { options: get_countries_for_connector(connector) .iter() .map(|country| country.to_string()) .collect::<Vec<String>>(), }, value: None, }, ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "billing.address.first_name".to_string(), display_name: "billing_address_first_name".to_string(), field_type: FieldType::Text, value: None, }, ), ]), _ => HashMap::from([]), } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 106, "total_crates": null }
fn_clm_router_get_interac_fields_496459316428462322
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/configs/defaults/payout_required_fields fn get_interac_fields(connector: PayoutConnectors) -> HashMap<String, RequiredFieldInfo> { match connector { PayoutConnectors::Loonio => HashMap::from([ ( "payout_method_data.bank_redirect.interac.email".to_string(), RequiredFieldInfo { required_field: "payout_method_data.bank_redirect.interac.email".to_string(), display_name: "email".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "billing.address.first_name".to_string(), display_name: "billing_address_first_name".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "billing.address.last_name".to_string(), display_name: "billing_address_last_name".to_string(), field_type: FieldType::Text, value: None, }, ), ]), PayoutConnectors::Gigadat => HashMap::from([ ( "payout_method_data.bank_redirect.interac.email".to_string(), RequiredFieldInfo { required_field: "payout_method_data.bank_redirect.interac.email".to_string(), display_name: "email".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "billing.address.first_name".to_string(), display_name: "billing_address_first_name".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.last_name".to_string(), RequiredFieldInfo { required_field: "billing.address.last_name".to_string(), display_name: "billing_address_last_name".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.phone.number".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.number".to_string(), display_name: "phone".to_string(), field_type: FieldType::UserPhoneNumber, value: None, }, ), ( "billing.phone.country_code".to_string(), RequiredFieldInfo { required_field: "payment_method_data.billing.phone.country_code".to_string(), display_name: "dialing_code".to_string(), field_type: FieldType::UserPhoneNumberCountryCode, value: None, }, ), ]), _ => HashMap::from([]), } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 57, "total_crates": null }
fn_clm_router_get_billing_details_for_payment_method_496459316428462322
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/configs/defaults/payout_required_fields fn get_billing_details_for_payment_method( connector: PayoutConnectors, payment_method_type: PaymentMethodType, ) -> HashMap<String, RequiredFieldInfo> { match connector { PayoutConnectors::Adyenplatform => { let mut fields = HashMap::from([ ( "billing.address.line1".to_string(), RequiredFieldInfo { required_field: "billing.address.line1".to_string(), display_name: "billing_address_line1".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.line2".to_string(), RequiredFieldInfo { required_field: "billing.address.line2".to_string(), display_name: "billing_address_line2".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.city".to_string(), RequiredFieldInfo { required_field: "billing.address.city".to_string(), display_name: "billing_address_city".to_string(), field_type: FieldType::Text, value: None, }, ), ( "billing.address.country".to_string(), RequiredFieldInfo { required_field: "billing.address.country".to_string(), display_name: "billing_address_country".to_string(), field_type: FieldType::UserAddressCountry { options: get_countries_for_connector(connector) .iter() .map(|country| country.to_string()) .collect::<Vec<String>>(), }, value: None, }, ), ]); // Add first_name for bank payouts only if payment_method_type == PaymentMethodType::SepaBankTransfer { fields.insert( "billing.address.first_name".to_string(), RequiredFieldInfo { required_field: "billing.address.first_name".to_string(), display_name: "billing_address_first_name".to_string(), field_type: FieldType::Text, value: None, }, ); } fields } _ => get_billing_details(connector), } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 47, "total_crates": null }
fn_clm_router_from_-5435653393204249105
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/connector/utils // Implementation of PaymentMethodDataType for From<domain::payments::PaymentMethodData> fn from(pm_data: domain::payments::PaymentMethodData) -> Self { match pm_data { domain::payments::PaymentMethodData::Card(_) => Self::Card, domain::payments::PaymentMethodData::NetworkToken(_) => Self::NetworkToken, domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => Self::Card, domain::payments::PaymentMethodData::CardRedirect(card_redirect_data) => { match card_redirect_data { domain::CardRedirectData::Knet {} => Self::Knet, domain::payments::CardRedirectData::Benefit {} => Self::Benefit, domain::payments::CardRedirectData::MomoAtm {} => Self::MomoAtm, domain::payments::CardRedirectData::CardRedirect {} => Self::CardRedirect, } } domain::payments::PaymentMethodData::Wallet(wallet_data) => match wallet_data { domain::payments::WalletData::AliPayQr(_) => Self::AliPayQr, domain::payments::WalletData::AliPayRedirect(_) => Self::AliPayRedirect, domain::payments::WalletData::AliPayHkRedirect(_) => Self::AliPayHkRedirect, domain::payments::WalletData::AmazonPay(_) => Self::AmazonPay, domain::payments::WalletData::AmazonPayRedirect(_) => Self::AmazonPayRedirect, domain::payments::WalletData::Paysera(_) => Self::Paysera, domain::payments::WalletData::Skrill(_) => Self::Skrill, domain::payments::WalletData::MomoRedirect(_) => Self::MomoRedirect, domain::payments::WalletData::KakaoPayRedirect(_) => Self::KakaoPayRedirect, domain::payments::WalletData::GoPayRedirect(_) => Self::GoPayRedirect, domain::payments::WalletData::GcashRedirect(_) => Self::GcashRedirect, domain::payments::WalletData::ApplePay(_) => Self::ApplePay, domain::payments::WalletData::ApplePayRedirect(_) => Self::ApplePayRedirect, domain::payments::WalletData::ApplePayThirdPartySdk(_) => { Self::ApplePayThirdPartySdk } domain::payments::WalletData::DanaRedirect {} => Self::DanaRedirect, domain::payments::WalletData::GooglePay(_) => Self::GooglePay, domain::payments::WalletData::BluecodeRedirect {} => Self::Bluecode, domain::payments::WalletData::GooglePayRedirect(_) => Self::GooglePayRedirect, domain::payments::WalletData::GooglePayThirdPartySdk(_) => { Self::GooglePayThirdPartySdk } domain::payments::WalletData::MbWayRedirect(_) => Self::MbWayRedirect, domain::payments::WalletData::MobilePayRedirect(_) => Self::MobilePayRedirect, domain::payments::WalletData::PaypalRedirect(_) => Self::PaypalRedirect, domain::payments::WalletData::PaypalSdk(_) => Self::PaypalSdk, domain::payments::WalletData::Paze(_) => Self::Paze, domain::payments::WalletData::SamsungPay(_) => Self::SamsungPay, domain::payments::WalletData::TwintRedirect {} => Self::TwintRedirect, domain::payments::WalletData::VippsRedirect {} => Self::VippsRedirect, domain::payments::WalletData::TouchNGoRedirect(_) => Self::TouchNGoRedirect, domain::payments::WalletData::WeChatPayRedirect(_) => Self::WeChatPayRedirect, domain::payments::WalletData::WeChatPayQr(_) => Self::WeChatPayQr, domain::payments::WalletData::CashappQr(_) => Self::CashappQr, domain::payments::WalletData::SwishQr(_) => Self::SwishQr, domain::payments::WalletData::Mifinity(_) => Self::Mifinity, domain::payments::WalletData::RevolutPay(_) => Self::RevolutPay, }, domain::payments::PaymentMethodData::PayLater(pay_later_data) => match pay_later_data { domain::payments::PayLaterData::KlarnaRedirect { .. } => Self::KlarnaRedirect, domain::payments::PayLaterData::KlarnaSdk { .. } => Self::KlarnaSdk, domain::payments::PayLaterData::AffirmRedirect {} => Self::AffirmRedirect, domain::payments::PayLaterData::AfterpayClearpayRedirect { .. } => { Self::AfterpayClearpayRedirect } domain::payments::PayLaterData::PayBrightRedirect {} => Self::PayBrightRedirect, domain::payments::PayLaterData::WalleyRedirect {} => Self::WalleyRedirect, domain::payments::PayLaterData::AlmaRedirect {} => Self::AlmaRedirect, domain::payments::PayLaterData::FlexitiRedirect {} => Self::FlexitiRedirect, domain::payments::PayLaterData::AtomeRedirect {} => Self::AtomeRedirect, domain::payments::PayLaterData::BreadpayRedirect {} => Self::BreadpayRedirect, }, domain::payments::PaymentMethodData::BankRedirect(bank_redirect_data) => { match bank_redirect_data { domain::payments::BankRedirectData::BancontactCard { .. } => { Self::BancontactCard } domain::payments::BankRedirectData::Bizum {} => Self::Bizum, domain::payments::BankRedirectData::Blik { .. } => Self::Blik, domain::payments::BankRedirectData::Eft { .. } => Self::Eft, domain::payments::BankRedirectData::Eps { .. } => Self::Eps, domain::payments::BankRedirectData::Giropay { .. } => Self::Giropay, domain::payments::BankRedirectData::Ideal { .. } => Self::Ideal, domain::payments::BankRedirectData::Interac { .. } => Self::Interac, domain::payments::BankRedirectData::OnlineBankingCzechRepublic { .. } => { Self::OnlineBankingCzechRepublic } domain::payments::BankRedirectData::OnlineBankingFinland { .. } => { Self::OnlineBankingFinland } domain::payments::BankRedirectData::OnlineBankingPoland { .. } => { Self::OnlineBankingPoland } domain::payments::BankRedirectData::OnlineBankingSlovakia { .. } => { Self::OnlineBankingSlovakia } domain::payments::BankRedirectData::OpenBankingUk { .. } => Self::OpenBankingUk, domain::payments::BankRedirectData::Przelewy24 { .. } => Self::Przelewy24, domain::payments::BankRedirectData::Sofort { .. } => Self::Sofort, domain::payments::BankRedirectData::Trustly { .. } => Self::Trustly, domain::payments::BankRedirectData::OnlineBankingFpx { .. } => { Self::OnlineBankingFpx } domain::payments::BankRedirectData::OnlineBankingThailand { .. } => { Self::OnlineBankingThailand } domain::payments::BankRedirectData::LocalBankRedirect { } => { Self::LocalBankRedirect } } } domain::payments::PaymentMethodData::BankDebit(bank_debit_data) => { match bank_debit_data { domain::payments::BankDebitData::AchBankDebit { .. } => Self::AchBankDebit, domain::payments::BankDebitData::SepaBankDebit { .. } => Self::SepaBankDebit, domain::payments::BankDebitData::SepaGuarenteedBankDebit { .. } => Self::SepaGuarenteedDebit, domain::payments::BankDebitData::BecsBankDebit { .. } => Self::BecsBankDebit, domain::payments::BankDebitData::BacsBankDebit { .. } => Self::BacsBankDebit, } } domain::payments::PaymentMethodData::BankTransfer(bank_transfer_data) => { match *bank_transfer_data { domain::payments::BankTransferData::AchBankTransfer { .. } => { Self::AchBankTransfer } domain::payments::BankTransferData::SepaBankTransfer { .. } => { Self::SepaBankTransfer } domain::payments::BankTransferData::BacsBankTransfer { .. } => { Self::BacsBankTransfer } domain::payments::BankTransferData::MultibancoBankTransfer { .. } => { Self::MultibancoBankTransfer } domain::payments::BankTransferData::PermataBankTransfer { .. } => { Self::PermataBankTransfer } domain::payments::BankTransferData::BcaBankTransfer { .. } => { Self::BcaBankTransfer } domain::payments::BankTransferData::BniVaBankTransfer { .. } => { Self::BniVaBankTransfer } domain::payments::BankTransferData::BriVaBankTransfer { .. } => { Self::BriVaBankTransfer } domain::payments::BankTransferData::CimbVaBankTransfer { .. } => { Self::CimbVaBankTransfer } domain::payments::BankTransferData::DanamonVaBankTransfer { .. } => { Self::DanamonVaBankTransfer } domain::payments::BankTransferData::MandiriVaBankTransfer { .. } => { Self::MandiriVaBankTransfer } domain::payments::BankTransferData::Pix { .. } => Self::Pix, domain::payments::BankTransferData::Pse {} => Self::Pse, domain::payments::BankTransferData::LocalBankTransfer { .. } => { Self::LocalBankTransfer } domain::payments::BankTransferData::InstantBankTransfer {} => { Self::InstantBankTransfer } domain::payments::BankTransferData::InstantBankTransferFinland {} => { Self::InstantBankTransferFinland } domain::payments::BankTransferData::InstantBankTransferPoland {} => { Self::InstantBankTransferPoland } domain::payments::BankTransferData::IndonesianBankTransfer { .. } => { Self::IndonesianBankTransfer } } } domain::payments::PaymentMethodData::Crypto(_) => Self::Crypto, domain::payments::PaymentMethodData::MandatePayment => Self::MandatePayment, domain::payments::PaymentMethodData::Reward => Self::Reward, domain::payments::PaymentMethodData::Upi(_) => Self::Upi, domain::payments::PaymentMethodData::Voucher(voucher_data) => match voucher_data { domain::payments::VoucherData::Boleto(_) => Self::Boleto, domain::payments::VoucherData::Efecty => Self::Efecty, domain::payments::VoucherData::PagoEfectivo => Self::PagoEfectivo, domain::payments::VoucherData::RedCompra => Self::RedCompra, domain::payments::VoucherData::RedPagos => Self::RedPagos, domain::payments::VoucherData::Alfamart(_) => Self::Alfamart, domain::payments::VoucherData::Indomaret(_) => Self::Indomaret, domain::payments::VoucherData::Oxxo => Self::Oxxo, domain::payments::VoucherData::SevenEleven(_) => Self::SevenEleven, domain::payments::VoucherData::Lawson(_) => Self::Lawson, domain::payments::VoucherData::MiniStop(_) => Self::MiniStop, domain::payments::VoucherData::FamilyMart(_) => Self::FamilyMart, domain::payments::VoucherData::Seicomart(_) => Self::Seicomart, domain::payments::VoucherData::PayEasy(_) => Self::PayEasy, }, domain::PaymentMethodData::RealTimePayment(real_time_payment_data) => match *real_time_payment_data{ hyperswitch_domain_models::payment_method_data::RealTimePaymentData::DuitNow { } => Self::DuitNow, hyperswitch_domain_models::payment_method_data::RealTimePaymentData::Fps { } => Self::Fps, hyperswitch_domain_models::payment_method_data::RealTimePaymentData::PromptPay { } => Self::PromptPay, hyperswitch_domain_models::payment_method_data::RealTimePaymentData::VietQr { } => Self::VietQr, }, domain::payments::PaymentMethodData::GiftCard(gift_card_data) => { match *gift_card_data { domain::payments::GiftCardData::Givex(_) => Self::Givex, domain::payments::GiftCardData::BhnCardNetwork(_)=>Self::BhnCardNetwork, domain::payments::GiftCardData::PaySafeCard {} => Self::PaySafeCar, } } domain::payments::PaymentMethodData::CardToken(_) => Self::CardToken, domain::payments::PaymentMethodData::OpenBanking(data) => match data { hyperswitch_domain_models::payment_method_data::OpenBankingData::OpenBankingPIS { } => Self::OpenBanking }, domain::payments::PaymentMethodData::MobilePayment(mobile_payment_data) => match mobile_payment_data { hyperswitch_domain_models::payment_method_data::MobilePaymentData::DirectCarrierBilling { .. } => Self::DirectCarrierBilling, }, } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 2600, "total_crates": null }
fn_clm_router_get_connector_transaction_id_-5435653393204249105
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/connector/utils // Implementation of types::PaymentsSyncData for PaymentsSyncRequestData fn get_connector_transaction_id(&self) -> CustomResult<String, errors::ConnectorError> { match self.connector_transaction_id.clone() { ResponseId::ConnectorTransactionId(txn_id) => Ok(txn_id), _ => Err(errors::ValidationError::IncorrectValueProvided { field_name: "connector_transaction_id", }) .attach_printable("Expected connector transaction ID not found") .change_context(errors::ConnectorError::MissingConnectorTransactionID)?, } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 1265, "total_crates": null }
fn_clm_router_missing_field_err_-5435653393204249105
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/connector/utils pub fn missing_field_err( message: &'static str, ) -> Box<dyn Fn() -> error_stack::Report<errors::ConnectorError> + 'static> { Box::new(move || { errors::ConnectorError::MissingRequiredField { field_name: message, } .into() }) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 491, "total_crates": null }
fn_clm_router_foreign_try_from_-5435653393204249105
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/connector/utils // Implementation of CanadaStatesAbbreviation for ForeignTryFrom<String> fn foreign_try_from(value: String) -> Result<Self, Self::Error> { let state_abbreviation_check = StringExt::<Self>::parse_enum(value.to_uppercase().clone(), "CanadaStatesAbbreviation"); match state_abbreviation_check { Ok(state_abbreviation) => Ok(state_abbreviation), Err(_) => { let binding = value.as_str().to_lowercase(); let state = binding.as_str(); match state { "alberta" => Ok(Self::AB), "british columbia" => Ok(Self::BC), "manitoba" => Ok(Self::MB), "new brunswick" => Ok(Self::NB), "newfoundland and labrador" | "newfoundland & labrador" => Ok(Self::NL), "northwest territories" => Ok(Self::NT), "nova scotia" => Ok(Self::NS), "nunavut" => Ok(Self::NU), "ontario" => Ok(Self::ON), "prince edward island" => Ok(Self::PE), "quebec" => Ok(Self::QC), "saskatchewan" => Ok(Self::SK), "yukon" => Ok(Self::YT), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", } .into()), } } } }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 442, "total_crates": null }
fn_clm_router_convert_amount_-5435653393204249105
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/connector/utils pub fn convert_amount<T>( amount_convertor: &dyn AmountConvertor<Output = T>, amount: MinorUnit, currency: enums::Currency, ) -> Result<T, error_stack::Report<errors::ConnectorError>> { amount_convertor .convert(amount, currency) .change_context(errors::ConnectorError::AmountConversionFailed) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": true, "num_enums": null, "num_structs": null, "num_tables": null, "score": 317, "total_crates": null }
fn_clm_router_insert_dynamic_routing_stat_entry_3583205148843641059
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/db/dynamic_routing_stats // Implementation of KafkaStore for DynamicRoutingStatsInterface async fn insert_dynamic_routing_stat_entry( &self, dynamic_routing_stat: storage::DynamicRoutingStatsNew, ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> { self.diesel_store .insert_dynamic_routing_stat_entry(dynamic_routing_stat) .await }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 16, "total_crates": null }
fn_clm_router_find_dynamic_routing_stats_optional_by_attempt_id_merchant_id_3583205148843641059
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/db/dynamic_routing_stats // Implementation of KafkaStore for DynamicRoutingStatsInterface async fn find_dynamic_routing_stats_optional_by_attempt_id_merchant_id( &self, attempt_id: String, merchant_id: &common_utils::id_type::MerchantId, ) -> CustomResult<Option<storage::DynamicRoutingStats>, errors::StorageError> { self.diesel_store .find_dynamic_routing_stats_optional_by_attempt_id_merchant_id(attempt_id, merchant_id) .await }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 16, "total_crates": null }
fn_clm_router_update_dynamic_routing_stats_3583205148843641059
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/db/dynamic_routing_stats // Implementation of KafkaStore for DynamicRoutingStatsInterface async fn update_dynamic_routing_stats( &self, attempt_id: String, merchant_id: &common_utils::id_type::MerchantId, data: storage::DynamicRoutingStatsUpdate, ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> { self.diesel_store .update_dynamic_routing_stats(attempt_id, merchant_id, data) .await }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 16, "total_crates": null }
fn_clm_router_find_disputes_by_constraints_-931197206101911210
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/db/dispute // Implementation of MockDb for DisputeInterface async fn find_disputes_by_constraints( &self, merchant_id: &common_utils::id_type::MerchantId, dispute_constraints: &disputes::DisputeListConstraints, ) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> { let locked_disputes = self.disputes.lock().await; let limit_usize = dispute_constraints .limit .unwrap_or(u32::MAX) .try_into() .unwrap_or(usize::MAX); let offset_usize = dispute_constraints .offset .unwrap_or(0) .try_into() .unwrap_or(usize::MIN); let filtered_disputes: Vec<storage::Dispute> = locked_disputes .iter() .filter(|dispute| { dispute.merchant_id == *merchant_id && dispute_constraints .dispute_id .as_ref() .is_none_or(|id| &dispute.dispute_id == id) && dispute_constraints .payment_id .as_ref() .is_none_or(|id| &dispute.payment_id == id) && dispute_constraints .profile_id .as_ref() .is_none_or(|profile_ids| { dispute .profile_id .as_ref() .is_none_or(|id| profile_ids.contains(id)) }) && dispute_constraints .dispute_status .as_ref() .is_none_or(|statuses| statuses.contains(&dispute.dispute_status)) && dispute_constraints .dispute_stage .as_ref() .is_none_or(|stages| stages.contains(&dispute.dispute_stage)) && dispute_constraints.reason.as_ref().is_none_or(|reason| { dispute .connector_reason .as_ref() .is_none_or(|d_reason| d_reason == reason) }) && dispute_constraints .connector .as_ref() .is_none_or(|connectors| { connectors .iter() .any(|connector| dispute.connector.as_str() == *connector) }) && dispute_constraints .merchant_connector_id .as_ref() .is_none_or(|id| dispute.merchant_connector_id.as_ref() == Some(id)) && dispute_constraints .currency .as_ref() .is_none_or(|currencies| { currencies.iter().any(|currency| { dispute .dispute_currency .map(|dispute_currency| &dispute_currency == currency) .unwrap_or(dispute.currency.as_str() == currency.to_string()) }) }) && dispute_constraints.time_range.as_ref().is_none_or(|range| { let dispute_time = dispute.created_at; dispute_time >= range.start_time && range .end_time .is_none_or(|end_time| dispute_time <= end_time) }) }) .skip(offset_usize) .take(limit_usize) .cloned() .collect(); Ok(filtered_disputes) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 119, "total_crates": null }
fn_clm_router_insert_dispute_-931197206101911210
clm
function
// Repository: hyperswitch // Crate: router // Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration // Module: crates/router/src/db/dispute // Implementation of MockDb for DisputeInterface async fn insert_dispute( &self, dispute: storage::DisputeNew, ) -> CustomResult<storage::Dispute, errors::StorageError> { let evidence = dispute.evidence.ok_or(errors::StorageError::MockDbError)?; let mut locked_disputes = self.disputes.lock().await; if locked_disputes .iter() .any(|d| d.dispute_id == dispute.dispute_id) { Err(errors::StorageError::MockDbError)?; } let now = common_utils::date_time::now(); let new_dispute = storage::Dispute { dispute_id: dispute.dispute_id, amount: dispute.amount, currency: dispute.currency, dispute_stage: dispute.dispute_stage, dispute_status: dispute.dispute_status, payment_id: dispute.payment_id, attempt_id: dispute.attempt_id, merchant_id: dispute.merchant_id, connector_status: dispute.connector_status, connector_dispute_id: dispute.connector_dispute_id, connector_reason: dispute.connector_reason, connector_reason_code: dispute.connector_reason_code, challenge_required_by: dispute.challenge_required_by, connector_created_at: dispute.connector_created_at, connector_updated_at: dispute.connector_updated_at, created_at: now, modified_at: now, connector: dispute.connector, profile_id: dispute.profile_id, evidence, merchant_connector_id: dispute.merchant_connector_id, dispute_amount: dispute.dispute_amount, organization_id: dispute.organization_id, dispute_currency: dispute.dispute_currency, }; locked_disputes.push(new_dispute.clone()); Ok(new_dispute) }
{ "crate": "router", "file": null, "file_size": null, "is_async": false, "is_pub": false, "num_enums": null, "num_structs": null, "num_tables": null, "score": 64, "total_crates": null }