id stringlengths 11 116 | type stringclasses 1 value | granularity stringclasses 4 values | content stringlengths 16 477k | metadata dict |
|---|---|---|---|---|
fn_clm_router_ephemeral_key_delete_8169358679620158936 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/ephemeral_key
pub async fn ephemeral_key_delete(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::EphemeralKeyDelete;
let payload = path.into_inner();
api::server_wrap(
flow,
state,
&req,
payload,
|state, _: auth::AuthenticationData, req, _| helpers::delete_ephemeral_key(state, req),
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
)
.await
}
| {
"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_client_secret_delete_8169358679620158936 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/ephemeral_key
pub async fn client_secret_delete(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::EphemeralKeyDelete;
let payload = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _: auth::AuthenticationData, req, _| helpers::delete_client_secret(state, req),
&auth::V2ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
},
api_locking::LockAction::NotApplicable,
))
.await
}
| {
"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_retrieve_mandates_list_-5865303832944726651 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/mandates
pub async fn retrieve_mandates_list(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Query<api_models::mandates::MandateListConstraints>,
) -> HttpResponse {
let flow = Flow::MandatesList;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
mandate::retrieve_mandates_list(state, merchant_context, req)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantMandateRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 33,
"total_crates": null
} |
fn_clm_router_get_mandate_-5865303832944726651 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/mandates
pub async fn get_mandate(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::MandatesRetrieve;
let mandate_id = mandates::MandateId {
mandate_id: path.into_inner(),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
mandate_id,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
mandate::get_mandate(state, merchant_context, req)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
| {
"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_revoke_mandate_-5865303832944726651 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/mandates
pub async fn revoke_mandate(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::MandatesRevoke;
let mandate_id = mandates::MandateId {
mandate_id: path.into_inner(),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
mandate_id,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
mandate::revoke_mandate(state, merchant_context, req)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
| {
"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_generate_feature_matrix_3984648059326459007 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/feature_matrix
pub async fn generate_feature_matrix(
state: app::SessionState,
req: payment_types::FeatureMatrixRequest,
) -> RouterResponse<feature_matrix::FeatureMatrixListResponse> {
let connector_list = req
.connectors
.unwrap_or_else(|| Connector::iter().collect());
let feature_matrix_response: Vec<payment_types::ConnectorFeatureMatrixResponse> =
connector_list
.into_iter()
.filter_map(|connector_name| {
api_types::feature_matrix::FeatureMatrixConnectorData::convert_connector(
&connector_name.to_string(),
)
.inspect_err(|_| {
router_env::logger::warn!("Failed to fetch {:?} details", connector_name)
})
.ok()
.and_then(|connector| {
build_connector_feature_details(&state, connector, connector_name.to_string())
})
})
.collect();
Ok(ApplicationResponse::Json(
payment_types::FeatureMatrixListResponse {
connector_count: feature_matrix_response.len(),
connectors: feature_matrix_response,
},
))
}
| {
"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_build_payment_method_wise_feature_details_3984648059326459007 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/feature_matrix
fn build_payment_method_wise_feature_details(
state: &app::SessionState,
connector_name: &str,
payment_method: enums::PaymentMethod,
supported_payment_method_types: &PaymentMethodTypeMetadata,
) -> Vec<feature_matrix::SupportedPaymentMethod> {
supported_payment_method_types
.iter()
.map(|(payment_method_type, feature_metadata)| {
let payment_method_type_config =
state
.conf
.pm_filters
.0
.get(connector_name)
.and_then(|selected_connector| {
selected_connector.0.get(
&settings::PaymentMethodFilterKey::PaymentMethodType(
*payment_method_type,
),
)
});
let supported_countries = payment_method_type_config.and_then(|config| {
config.country.clone().map(|set| {
set.into_iter()
.map(common_enums::CountryAlpha2::from_alpha2_to_alpha3)
.collect::<std::collections::HashSet<_>>()
})
});
let supported_currencies =
payment_method_type_config.and_then(|config| config.currency.clone());
feature_matrix::SupportedPaymentMethod {
payment_method,
payment_method_type: *payment_method_type,
payment_method_type_display_name: payment_method_type.to_display_name(),
mandates: feature_metadata.mandates,
refunds: feature_metadata.refunds,
supported_capture_methods: feature_metadata.supported_capture_methods.clone(),
payment_method_specific_features: feature_metadata.specific_features.clone(),
supported_countries,
supported_currencies,
}
})
.collect()
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 37,
"total_crates": null
} |
fn_clm_router_build_connector_feature_details_3984648059326459007 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/feature_matrix
fn build_connector_feature_details(
state: &app::SessionState,
connector: ConnectorEnum,
connector_name: String,
) -> Option<feature_matrix::ConnectorFeatureMatrixResponse> {
let connector_integration_features = connector.get_supported_payment_methods();
let supported_payment_methods =
connector_integration_features.map(|connector_integration_feature_data| {
connector_integration_feature_data
.iter()
.flat_map(|(payment_method, supported_payment_method_types)| {
build_payment_method_wise_feature_details(
state,
&connector_name,
*payment_method,
supported_payment_method_types,
)
})
.collect::<Vec<feature_matrix::SupportedPaymentMethod>>()
});
let supported_webhook_flows = connector
.get_supported_webhook_flows()
.map(|webhook_flows| webhook_flows.to_vec());
let connector_about = connector.get_connector_about();
connector_about.map(
|connector_about| feature_matrix::ConnectorFeatureMatrixResponse {
name: connector_name.to_uppercase(),
display_name: connector_about.display_name.to_string(),
description: connector_about.description.to_string(),
integration_status: connector_about.integration_status,
category: connector_about.connector_type,
supported_webhook_flows,
supported_payment_methods,
},
)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 29,
"total_crates": null
} |
fn_clm_router_fetch_feature_matrix_3984648059326459007 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/feature_matrix
pub async fn fetch_feature_matrix(
state: web::Data<app::AppState>,
req: HttpRequest,
json_payload: Option<web::Json<payment_types::FeatureMatrixRequest>>,
) -> impl Responder {
let flow: Flow = Flow::FeatureMatrix;
let payload = json_payload
.map(|json_request| json_request.into_inner())
.unwrap_or_else(|| payment_types::FeatureMatrixRequest { connectors: None });
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, (), req, _| generate_feature_matrix(state, req),
&auth::NoAuth,
LockAction::NotApplicable,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 22,
"total_crates": null
} |
fn_clm_router_new_8425067536982359475 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/app
// Inherent implementation for AppState
pub async fn new(
conf: settings::Settings<SecuredSecret>,
shut_down_signal: oneshot::Sender<()>,
api_client: Box<dyn crate::services::ApiClient>,
) -> Self {
Box::pin(Self::with_storage(
conf,
StorageImpl::Postgresql,
shut_down_signal,
api_client,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14467,
"total_crates": null
} |
fn_clm_router_as_ref_8425067536982359475 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/app
// Implementation of AppState for AsRef<Self>
fn as_ref(&self) -> &Self {
self
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 7553,
"total_crates": null
} |
fn_clm_router_server_8425067536982359475 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/app
// Inherent implementation for RecoveryDataBackfill
pub fn server(state: AppState) -> Scope {
web::scope("/v2/recovery/data-backfill")
.app_data(web::Data::new(state))
.service(
web::resource("").route(
web::post()
.to(super::revenue_recovery_data_backfill::revenue_recovery_data_backfill),
),
)
.service(web::resource("/status/{token_id}").route(
web::post().to(
super::revenue_recovery_data_backfill::revenue_recovery_data_backfill_status,
),
))
.service(web::resource("/redis-data/{token_id}").route(
web::get().to(
super::revenue_recovery_redis::get_revenue_recovery_redis_data,
),
))
.service(web::resource("/update-token").route(
web::put().to(
super::revenue_recovery_data_backfill::update_revenue_recovery_additional_redis_data,
),
))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 250,
"total_crates": null
} |
fn_clm_router_with_storage_8425067536982359475 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/app
// Inherent implementation for AppState
/// # Panics
///
/// Panics if Store can't be created or JWE decryption fails
pub async fn with_storage(
conf: settings::Settings<SecuredSecret>,
storage_impl: StorageImpl,
shut_down_signal: oneshot::Sender<()>,
api_client: Box<dyn crate::services::ApiClient>,
) -> Self {
#[allow(clippy::expect_used)]
let secret_management_client = conf
.secrets_management
.get_secret_management_client()
.await
.expect("Failed to create secret management client");
let conf = Box::pin(secrets_transformers::fetch_raw_secrets(
conf,
&*secret_management_client,
))
.await;
#[allow(clippy::expect_used)]
let encryption_client = conf
.encryption_management
.get_encryption_management_client()
.await
.expect("Failed to create encryption client");
Box::pin(async move {
let testable = storage_impl == StorageImpl::PostgresqlTest;
#[allow(clippy::expect_used)]
let event_handler = conf
.events
.get_event_handler()
.await
.expect("Failed to create event handler");
#[allow(clippy::expect_used)]
#[cfg(feature = "olap")]
let opensearch_client = conf
.opensearch
.get_opensearch_client()
.await
.expect("Failed to initialize OpenSearch client.")
.map(Arc::new);
#[allow(clippy::expect_used)]
let cache_store = get_cache_store(&conf.clone(), shut_down_signal, testable)
.await
.expect("Failed to create store");
let global_store: Box<dyn GlobalStorageInterface> = Self::get_store_interface(
&storage_impl,
&event_handler,
&conf,
&conf.multitenancy.global_tenant,
Arc::clone(&cache_store),
testable,
)
.await
.get_global_storage_interface();
#[cfg(feature = "olap")]
let pools = conf
.multitenancy
.tenants
.get_pools_map(conf.analytics.get_inner())
.await;
let stores = conf
.multitenancy
.tenants
.get_store_interface_map(&storage_impl, &conf, Arc::clone(&cache_store), testable)
.await;
let accounts_store = conf
.multitenancy
.tenants
.get_accounts_store_interface_map(
&storage_impl,
&conf,
Arc::clone(&cache_store),
testable,
)
.await;
#[cfg(feature = "email")]
let email_client = Arc::new(create_email_client(&conf).await);
let file_storage_client = conf.file_storage.get_file_storage_client().await;
let theme_storage_client = conf.theme.storage.get_file_storage_client().await;
let crm_client = conf.crm.get_crm_client().await;
let grpc_client = conf.grpc_client.get_grpc_client_interface().await;
let infra_component_values = Self::process_env_mappings(conf.infra_values.clone());
let enhancement = conf.enhancement.clone();
let superposition_service = if conf.superposition.get_inner().enabled {
match SuperpositionClient::new(conf.superposition.get_inner().clone()).await {
Ok(client) => {
router_env::logger::info!("Superposition client initialized successfully");
Some(Arc::new(client))
}
Err(err) => {
router_env::logger::warn!(
"Failed to initialize superposition client: {:?}. Continuing without superposition support.",
err
);
None
}
}
} else {
None
};
Self {
flow_name: String::from("default"),
stores,
global_store,
accounts_store,
conf: Arc::new(conf),
#[cfg(feature = "email")]
email_client,
api_client,
event_handler,
#[cfg(feature = "olap")]
pools,
#[cfg(feature = "olap")]
opensearch_client,
request_id: None,
file_storage_client,
encryption_client,
grpc_client,
theme_storage_client,
crm_client,
infra_components: infra_component_values,
enhancement,
superposition_service,
}
})
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 139,
"total_crates": null
} |
fn_clm_router_get_session_state_8425067536982359475 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/app
// Inherent implementation for AppState
pub fn get_session_state<E, F>(
self: Arc<Self>,
tenant: &id_type::TenantId,
locale: Option<String>,
err: F,
) -> Result<SessionState, E>
where
F: FnOnce() -> E + Copy,
{
let tenant_conf = self.conf.multitenancy.get_tenant(tenant).ok_or_else(err)?;
let mut event_handler = self.event_handler.clone();
event_handler.add_tenant(tenant_conf);
let store = self.stores.get(tenant).ok_or_else(err)?.clone();
Ok(SessionState {
store,
global_store: self.global_store.clone(),
accounts_store: self.accounts_store.get(tenant).ok_or_else(err)?.clone(),
conf: Arc::clone(&self.conf),
api_client: self.api_client.clone(),
event_handler,
#[cfg(feature = "olap")]
pool: self.pools.get(tenant).ok_or_else(err)?.clone(),
file_storage_client: self.file_storage_client.clone(),
request_id: self.request_id,
base_url: tenant_conf.base_url.clone(),
tenant: tenant_conf.clone(),
#[cfg(feature = "email")]
email_client: Arc::clone(&self.email_client),
#[cfg(feature = "olap")]
opensearch_client: self.opensearch_client.clone(),
grpc_client: Arc::clone(&self.grpc_client),
theme_storage_client: self.theme_storage_client.clone(),
locale: locale.unwrap_or(common_utils::consts::DEFAULT_LOCALE.to_string()),
crm_client: self.crm_client.clone(),
infra_components: self.infra_components.clone(),
enhancement: self.enhancement.clone(),
superposition_service: self.superposition_service.clone(),
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 136,
"total_crates": null
} |
fn_clm_router_apple_pay_certificates_migration_-199382706710106615 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/apple_pay_certificates_migration
pub async fn apple_pay_certificates_migration(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<
api_models::apple_pay_certificates_migration::ApplePayCertificatesMigrationRequest,
>,
) -> HttpResponse {
let flow = Flow::ApplePayCertificatesMigration;
Box::pin(api::server_wrap(
flow,
state,
&req,
&json_payload.into_inner(),
|state, _, req, _| {
apple_pay_certificates_migration::apple_pay_certificates_migration(state, req)
},
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
| {
"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_execute_decision_rule_7581694049468948435 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/three_ds_decision_rule
pub async fn execute_decision_rule(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
payload: web::Json<api_models::three_ds_decision_rule::ThreeDsDecisionRuleExecuteRequest>,
) -> impl Responder {
let flow = Flow::ThreeDsDecisionRuleExecute;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = MerchantContext::NormalMerchant(Box::new(Context(
auth.merchant_account,
auth.key_store,
)));
three_ds_decision_rule_core::execute_three_ds_decision_rule(
state,
merchant_context,
req,
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.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_list_initial_webhook_delivery_attempts_-3003016120798163854 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/webhook_events
pub async fn list_initial_webhook_delivery_attempts(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::MerchantId>,
json_payload: web::Json<EventListConstraints>,
) -> impl Responder {
let flow = Flow::WebhookEventInitialDeliveryAttemptList;
let merchant_id = path.into_inner();
let constraints = json_payload.into_inner();
let request_internal = EventListRequestInternal {
merchant_id: merchant_id.clone(),
constraints,
};
Box::pin(api::server_wrap(
flow,
state,
&req,
request_internal,
|state, _, request_internal, _| {
webhook_events::list_initial_delivery_attempts(
state,
request_internal.merchant_id,
request_internal.constraints,
)
},
auth::auth_type(
&auth::AdminApiAuth,
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: Permission::MerchantWebhookEventRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.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_list_webhook_delivery_attempts_-3003016120798163854 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/webhook_events
pub async fn list_webhook_delivery_attempts(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<(common_utils::id_type::MerchantId, String)>,
) -> impl Responder {
let flow = Flow::WebhookEventDeliveryAttemptList;
let (merchant_id, initial_attempt_id) = path.into_inner();
let request_internal = WebhookDeliveryAttemptListRequestInternal {
merchant_id: merchant_id.clone(),
initial_attempt_id,
};
Box::pin(api::server_wrap(
flow,
state,
&req,
request_internal,
|state, _, request_internal, _| {
webhook_events::list_delivery_attempts(
state,
request_internal.merchant_id,
request_internal.initial_attempt_id,
)
},
auth::auth_type(
&auth::AdminApiAuth,
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: Permission::MerchantWebhookEventRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 24,
"total_crates": null
} |
fn_clm_router_retry_webhook_delivery_attempt_-3003016120798163854 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/webhook_events
pub async fn retry_webhook_delivery_attempt(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<(common_utils::id_type::MerchantId, String)>,
) -> impl Responder {
let flow = Flow::WebhookEventDeliveryRetry;
let (merchant_id, event_id) = path.into_inner();
let request_internal = WebhookDeliveryRetryRequestInternal {
merchant_id: merchant_id.clone(),
event_id,
};
Box::pin(api::server_wrap(
flow,
state,
&req,
request_internal,
|state, _, request_internal, _| {
webhook_events::retry_delivery_attempt(
state,
request_internal.merchant_id,
request_internal.event_id,
)
},
auth::auth_type(
&auth::AdminApiAuth,
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: Permission::MerchantWebhookEventWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 24,
"total_crates": null
} |
fn_clm_router_list_initial_webhook_delivery_attempts_with_jwtauth_-3003016120798163854 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/webhook_events
pub async fn list_initial_webhook_delivery_attempts_with_jwtauth(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<EventListConstraints>,
) -> impl Responder {
let flow = Flow::WebhookEventInitialDeliveryAttemptList;
let constraints = json_payload.into_inner();
let request_internal = EventListRequestInternal {
merchant_id: common_utils::id_type::MerchantId::default(),
constraints,
};
Box::pin(api::server_wrap(
flow,
state,
&req,
request_internal,
|state, auth: UserFromToken, mut request_internal, _| {
let merchant_id = auth.merchant_id;
let profile_id = auth.profile_id;
request_internal.merchant_id = merchant_id;
request_internal.constraints.profile_id = Some(profile_id);
webhook_events::list_initial_delivery_attempts(
state,
request_internal.merchant_id,
request_internal.constraints,
)
},
&auth::JWTAuth {
permission: Permission::ProfileWebhookEventRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 20,
"total_crates": null
} |
fn_clm_router_relay_retrieve_8365372361712256239 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/relay
pub async fn relay_retrieve(
state: web::Data<app::AppState>,
path: web::Path<common_utils::id_type::RelayId>,
req: actix_web::HttpRequest,
query_params: web::Query<api_models::relay::RelayRetrieveBody>,
) -> impl Responder {
let flow = Flow::RelayRetrieve;
let relay_retrieve_request = api_models::relay::RelayRetrieveRequest {
force_sync: query_params.force_sync,
id: path.into_inner(),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
relay_retrieve_request,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = crate::types::domain::MerchantContext::NormalMerchant(Box::new(
crate::types::domain::Context(auth.merchant_account, auth.key_store),
));
relay::relay_retrieve(
state,
merchant_context,
#[cfg(feature = "v1")]
auth.profile_id,
#[cfg(feature = "v2")]
Some(auth.profile.get_id().clone()),
req,
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 36,
"total_crates": null
} |
fn_clm_router_relay_8365372361712256239 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/relay
pub async fn relay(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
payload: web::Json<api_models::relay::RelayRequest>,
) -> impl Responder {
let flow = Flow::Relay;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, _| {
let merchant_context = crate::types::domain::MerchantContext::NormalMerchant(Box::new(
crate::types::domain::Context(auth.merchant_account, auth.key_store),
));
relay::relay_flow_decider(
state,
merchant_context,
#[cfg(feature = "v1")]
auth.profile_id,
#[cfg(feature = "v2")]
Some(auth.profile.get_id().clone()),
req,
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 33,
"total_crates": null
} |
fn_clm_router_connector_retrieve_-1406071958368249829 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/admin
pub async fn connector_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::MerchantConnectorAccountId>,
) -> HttpResponse {
let flow = Flow::MerchantConnectorsRetrieve;
let id = path.into_inner();
let payload = web::Json(admin::MerchantConnectorId { id: id.clone() }).into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state,
auth::AuthenticationData {
merchant_account,
key_store,
..
},
req,
_| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(merchant_account, key_store),
));
retrieve_connector(state, merchant_context, req.id.clone())
},
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
required_permission: Permission::MerchantConnectorRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 36,
"total_crates": null
} |
fn_clm_router_connector_delete_-1406071958368249829 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/admin
pub async fn connector_delete(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::MerchantConnectorAccountId>,
) -> HttpResponse {
let flow = Flow::MerchantConnectorsDelete;
let id = path.into_inner();
let payload = web::Json(admin::MerchantConnectorId { id: id.clone() }).into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state,
auth::AuthenticationData {
merchant_account,
key_store,
..
},
req,
_| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(merchant_account, key_store),
));
delete_connector(state, merchant_context, req.id)
},
auth::auth_type(
&auth::AdminApiAuthWithMerchantIdFromHeader,
&auth::JWTAuthMerchantFromHeader {
required_permission: Permission::MerchantConnectorWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
| {
"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_connector_list_profile_-1406071958368249829 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/admin
pub async fn connector_list_profile(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::MerchantId>,
) -> HttpResponse {
let flow = Flow::MerchantConnectorsList;
let merchant_id = path.into_inner();
api::server_wrap(
flow,
state,
&req,
merchant_id.to_owned(),
|state, auth, merchant_id, _| {
list_payment_connectors(
state,
merchant_id,
auth.profile_id.map(|profile_id| vec![profile_id]),
)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuthWithMerchantIdFromRoute(merchant_id.clone())),
&auth::JWTAuthMerchantFromRoute {
merchant_id,
required_permission: Permission::ProfileConnectorRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
)
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 30,
"total_crates": null
} |
fn_clm_router_organization_update_-1406071958368249829 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/admin
pub async fn organization_update(
state: web::Data<AppState>,
req: HttpRequest,
org_id: web::Path<common_utils::id_type::OrganizationId>,
json_payload: web::Json<admin::OrganizationUpdateRequest>,
) -> HttpResponse {
let flow = Flow::OrganizationUpdate;
let organization_id = org_id.into_inner();
let org_id = admin::OrganizationId {
organization_id: organization_id.clone(),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, _, req, _| update_organization(state, org_id.clone(), req),
auth::auth_type(
&auth::V2AdminApiAuth,
&auth::JWTAuthOrganizationFromRoute {
organization_id,
required_permission: Permission::OrganizationAccountWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
| {
"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_update_merchant_account_-1406071958368249829 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/admin
pub async fn update_merchant_account(
state: web::Data<AppState>,
req: HttpRequest,
mid: web::Path<common_utils::id_type::MerchantId>,
json_payload: web::Json<admin::MerchantAccountUpdate>,
) -> HttpResponse {
let flow = Flow::MerchantsAccountUpdate;
let merchant_id = mid.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, _, req, _| merchant_account_update(state, &merchant_id, None, req),
auth::auth_type(
&auth::PlatformOrgAdminAuthWithMerchantIdFromRoute {
merchant_id_from_route: merchant_id.clone(),
is_admin_auth_allowed: true,
},
&auth::JWTAuthMerchantFromRoute {
merchant_id: merchant_id.clone(),
required_permission: Permission::MerchantAccountWrite,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
| {
"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_action_url_6910472145658899808 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/connector_onboarding
pub async fn get_action_url(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<api_types::ActionUrlRequest>,
) -> HttpResponse {
let flow = Flow::GetActionUrl;
let req_payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow.clone(),
state,
&http_req,
req_payload.clone(),
core::get_action_url,
&auth::JWTAuth {
permission: Permission::MerchantAccountWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 20,
"total_crates": null
} |
fn_clm_router_sync_onboarding_status_6910472145658899808 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/connector_onboarding
pub async fn sync_onboarding_status(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<api_types::OnboardingSyncRequest>,
) -> HttpResponse {
let flow = Flow::SyncOnboardingStatus;
let req_payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow.clone(),
state,
&http_req,
req_payload.clone(),
core::sync_onboarding_status,
&auth::JWTAuth {
permission: Permission::MerchantAccountWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 20,
"total_crates": null
} |
fn_clm_router_reset_tracking_id_6910472145658899808 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/connector_onboarding
pub async fn reset_tracking_id(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<api_types::ResetTrackingIdRequest>,
) -> HttpResponse {
let flow = Flow::ResetTrackingId;
let req_payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow.clone(),
state,
&http_req,
req_payload.clone(),
core::reset_tracking_id,
&auth::JWTAuth {
permission: Permission::MerchantAccountWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 20,
"total_crates": null
} |
fn_clm_router_get_data_from_hyperswitch_ai_workflow_6127123741722097575 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/chat
pub async fn get_data_from_hyperswitch_ai_workflow(
state: web::Data<AppState>,
http_req: HttpRequest,
payload: web::Json<chat_api::ChatRequest>,
) -> HttpResponse {
let flow = Flow::GetDataFromHyperswitchAiFlow;
let session_id = http_req
.headers()
.get(common_utils::consts::X_CHAT_SESSION_ID)
.and_then(|header_value| header_value.to_str().ok());
Box::pin(api::server_wrap(
flow.clone(),
state,
&http_req,
payload.into_inner(),
|state, user: auth::UserFromToken, payload, _| {
metrics::CHAT_REQUEST_COUNT.add(
1,
router_env::metric_attributes!(("merchant_id", user.merchant_id.clone())),
);
chat_core::get_data_from_hyperswitch_ai_workflow(state, user, payload, session_id)
},
// At present, the AI service retrieves data scoped to the merchant level
&auth::JWTAuth {
permission: Permission::MerchantPaymentRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
| {
"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_get_all_conversations_6127123741722097575 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/chat
pub async fn get_all_conversations(
state: web::Data<AppState>,
http_req: HttpRequest,
payload: web::Query<chat_api::ChatListRequest>,
) -> HttpResponse {
let flow = Flow::ListAllChatInteractions;
Box::pin(api::server_wrap(
flow.clone(),
state,
&http_req,
payload.into_inner(),
|state, user: auth::UserFromToken, payload, _| {
chat_core::list_chat_conversations(state, user, payload)
},
&auth::DashboardNoPermissionAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 20,
"total_crates": null
} |
fn_clm_router_link_token_create_5264745766956374301 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/pm_auth
pub async fn link_token_create(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<api_types::pm_auth::LinkTokenCreateRequest>,
) -> impl Responder {
let payload = json_payload.into_inner();
let flow = Flow::PmAuthLinkTokenCreate;
let api_auth = auth::ApiKeyAuth::default();
let (auth, _) = match crate::services::authentication::check_client_secret_and_get_auth(
req.headers(),
&payload,
api_auth,
) {
Ok((auth, _auth_flow)) => (auth, _auth_flow),
Err(e) => return api::log_and_return_error_response(e),
};
let header_payload =
match hyperswitch_domain_models::payments::HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth, payload, _| {
let merchant_context = crate::types::domain::MerchantContext::NormalMerchant(Box::new(
crate::types::domain::Context(auth.merchant_account, auth.key_store),
));
crate::core::pm_auth::create_link_token(
state,
merchant_context,
payload,
Some(header_payload.clone()),
)
},
&*auth,
api_locking::LockAction::NotApplicable,
))
.await
}
| {
"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_exchange_token_5264745766956374301 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/pm_auth
pub async fn exchange_token(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<api_types::pm_auth::ExchangeTokenCreateRequest>,
) -> impl Responder {
let payload = json_payload.into_inner();
let flow = Flow::PmAuthExchangeToken;
let api_auth = auth::ApiKeyAuth::default();
let (auth, _) = match crate::services::authentication::check_client_secret_and_get_auth(
req.headers(),
&payload,
api_auth,
) {
Ok((auth, _auth_flow)) => (auth, _auth_flow),
Err(e) => return api::log_and_return_error_response(e),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth, payload, _| {
let merchant_context = crate::types::domain::MerchantContext::NormalMerchant(Box::new(
crate::types::domain::Context(auth.merchant_account, auth.key_store),
));
crate::core::pm_auth::exchange_token_core(state, merchant_context, payload)
},
&*auth,
api_locking::LockAction::NotApplicable,
))
.await
}
| {
"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_track_response_status_code_3571073166479603442 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/metrics/request
pub fn track_response_status_code<Q>(response: &ApplicationResponse<Q>) -> i64 {
match response {
ApplicationResponse::Json(_)
| ApplicationResponse::StatusOk
| ApplicationResponse::TextPlain(_)
| ApplicationResponse::Form(_)
| ApplicationResponse::GenericLinkForm(_)
| ApplicationResponse::PaymentLinkForm(_)
| ApplicationResponse::FileData(_)
| ApplicationResponse::JsonWithHeaders(_) => 200,
ApplicationResponse::JsonForRedirection(_) => 302,
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 13,
"total_crates": null
} |
fn_clm_router_spawn_metrics_collector_949698661510812687 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/metrics/bg_metrics_collector
pub fn spawn_metrics_collector(metrics_collection_interval_in_secs: Option<u16>) {
let metrics_collection_interval = metrics_collection_interval_in_secs
.unwrap_or(DEFAULT_BG_METRICS_COLLECTION_INTERVAL_IN_SECS);
let cache_instances = [
&cache::CONFIG_CACHE,
&cache::ACCOUNTS_CACHE,
&cache::ROUTING_CACHE,
&cache::CGRAPH_CACHE,
&cache::PM_FILTERS_CGRAPH_CACHE,
&cache::DECISION_MANAGER_CACHE,
&cache::SURCHARGE_CACHE,
&cache::SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE,
&cache::CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE,
&cache::ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE,
];
tokio::spawn(async move {
loop {
for instance in cache_instances {
instance.record_entry_count_metric().await
}
tokio::time::sleep(std::time::Duration::from_secs(
metrics_collection_interval.into(),
))
.await
}
});
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 25,
"total_crates": null
} |
fn_clm_router_populate_browser_info_-4743356594011637820 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/payments/helpers
pub fn populate_browser_info(
req: &actix_web::HttpRequest,
payload: &mut api::PaymentsRequest,
header_payload: &hyperswitch_domain_models::payments::HeaderPayload,
) -> RouterResult<()> {
let mut browser_info: types::BrowserInformation = payload
.browser_info
.clone()
.map(|v| v.parse_value("BrowserInformation"))
.transpose()
.change_context_lazy(|| errors::ApiErrorResponse::InvalidRequestData {
message: "invalid format for 'browser_info' provided".to_string(),
})?
.unwrap_or(types::BrowserInformation {
color_depth: None,
java_enabled: None,
java_script_enabled: None,
language: None,
screen_height: None,
screen_width: None,
time_zone: None,
accept_header: None,
user_agent: None,
ip_address: None,
os_type: None,
os_version: None,
device_model: None,
accept_language: None,
referer: None,
});
let ip_address = req
.connection_info()
.realip_remote_addr()
.map(ToOwned::to_owned);
if ip_address.is_some() {
logger::debug!("Extracted ip address from request");
}
browser_info.ip_address = browser_info.ip_address.or_else(|| {
ip_address
.as_ref()
.map(|ip| ip.parse())
.transpose()
.unwrap_or_else(|error| {
logger::error!(
?error,
"failed to parse ip address which is extracted from the request"
);
None
})
});
// If the locale is present in the header payload, we will use it as the accept language
if header_payload.locale.is_some() {
browser_info.accept_language = browser_info
.accept_language
.or(header_payload.locale.clone());
}
if let Some(api::MandateData {
customer_acceptance:
Some(api::CustomerAcceptance {
online:
Some(api::OnlineMandate {
ip_address: req_ip, ..
}),
..
}),
..
}) = &mut payload.mandate_data
{
*req_ip = req_ip
.clone()
.or_else(|| ip_address.map(|ip| masking::Secret::new(ip.to_string())));
}
let encoded = browser_info
.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"failed to re-encode browser information to json after setting ip address",
)?;
payload.browser_info = Some(encoded);
Ok(())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 69,
"total_crates": null
} |
fn_clm_router_revenue_recovery_resume_api_6743532116886385693 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/process_tracker/revenue_recovery
pub async fn revenue_recovery_resume_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::GlobalPaymentId>,
json_payload: web::Json<revenue_recovery_api::RevenueRecoveryRetriggerRequest>,
) -> HttpResponse {
let flow = Flow::RevenueRecoveryResume;
let id = path.into_inner();
let payload = json_payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _, payload, _| {
revenue_recovery::resume_revenue_recovery_process_tracker(state, id.clone(), payload)
},
&auth::V2AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 22,
"total_crates": null
} |
fn_clm_router_revenue_recovery_pt_retrieve_api_6743532116886385693 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/process_tracker/revenue_recovery
pub async fn revenue_recovery_pt_retrieve_api(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::GlobalPaymentId>,
) -> HttpResponse {
let flow = Flow::RevenueRecoveryRetrieve;
let id = path.into_inner();
let payload = revenue_recovery_api::RevenueRecoveryId {
revenue_recovery_id: id,
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _: (), id, _| {
revenue_recovery::retrieve_revenue_recovery_process_tracker(
state,
id.revenue_recovery_id,
)
},
&auth::JWTAuth {
permission: Permission::ProfileRevenueRecoveryRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
| {
"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_refund_payment_-7604715307643159147 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/dummy_connector/core
pub async fn refund_payment(
state: SessionState,
req: types::DummyConnectorRefundRequest,
) -> types::DummyConnectorResponse<types::DummyConnectorRefundResponse> {
utils::tokio_mock_sleep(
state.conf.dummy_connector.refund_duration,
state.conf.dummy_connector.refund_tolerance,
)
.await;
let payment_id = req
.payment_id
.get_required_value("payment_id")
.change_context(errors::DummyConnectorErrors::MissingRequiredField {
field_name: "payment_id",
})?;
let mut payment_data =
utils::get_payment_data_from_payment_id(&state, payment_id.get_string_repr().to_owned())
.await?;
payment_data.is_eligible_for_refund(req.amount)?;
let refund_id = generate_id_with_default_len(consts::REFUND_ID_PREFIX);
payment_data.eligible_amount -= req.amount;
utils::store_data_in_redis(
&state,
payment_id.get_string_repr().to_owned(),
payment_data.to_owned(),
state.conf.dummy_connector.payment_ttl,
)
.await?;
let refund_data = types::DummyConnectorRefundResponse::new(
types::DummyConnectorStatus::Succeeded,
refund_id.to_owned(),
payment_data.currency,
common_utils::date_time::now(),
payment_data.amount,
req.amount,
);
utils::store_data_in_redis(
&state,
refund_id,
refund_data.to_owned(),
state.conf.dummy_connector.refund_ttl,
)
.await?;
Ok(api::ApplicationResponse::Json(refund_data))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 205,
"total_crates": null
} |
fn_clm_router_payment_complete_-7604715307643159147 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/dummy_connector/core
pub async fn payment_complete(
state: SessionState,
req: types::DummyConnectorPaymentCompleteRequest,
) -> types::DummyConnectorResponse<()> {
utils::tokio_mock_sleep(
state.conf.dummy_connector.payment_duration,
state.conf.dummy_connector.payment_tolerance,
)
.await;
let payment_data = utils::get_payment_data_by_attempt_id(&state, req.attempt_id.clone()).await;
let payment_status = if req.confirm {
types::DummyConnectorStatus::Succeeded
} else {
types::DummyConnectorStatus::Failed
};
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::DummyConnectorErrors::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let _ = redis_conn.delete_key(&req.attempt_id.as_str().into()).await;
if let Ok(payment_data) = payment_data {
let updated_payment_data = types::DummyConnectorPaymentData {
status: payment_status,
next_action: None,
..payment_data
};
utils::store_data_in_redis(
&state,
updated_payment_data.payment_id.get_string_repr().to_owned(),
updated_payment_data.clone(),
state.conf.dummy_connector.payment_ttl,
)
.await?;
return Ok(api::ApplicationResponse::JsonForRedirection(
api_models::payments::RedirectionResponse {
return_url: String::new(),
params: vec![],
return_url_with_query_params: updated_payment_data
.return_url
.unwrap_or(state.conf.dummy_connector.default_return_url.clone()),
http_method: "GET".to_string(),
headers: vec![],
},
));
}
Ok(api::ApplicationResponse::JsonForRedirection(
api_models::payments::RedirectionResponse {
return_url: String::new(),
params: vec![],
return_url_with_query_params: state.conf.dummy_connector.default_return_url.clone(),
http_method: "GET".to_string(),
headers: vec![],
},
))
}
| {
"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_payment_authorize_-7604715307643159147 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/dummy_connector/core
pub async fn payment_authorize(
state: SessionState,
req: types::DummyConnectorPaymentConfirmRequest,
) -> types::DummyConnectorResponse<String> {
let payment_data = utils::get_payment_data_by_attempt_id(&state, req.attempt_id.clone()).await;
let dummy_connector_conf = &state.conf.dummy_connector;
if let Ok(payment_data_inner) = payment_data {
let return_url = format!(
"{}/dummy-connector/complete/{}",
state.base_url, req.attempt_id
);
Ok(api::ApplicationResponse::FileData((
utils::get_authorize_page(payment_data_inner, return_url, dummy_connector_conf)
.as_bytes()
.to_vec(),
mime::TEXT_HTML,
)))
} else {
Ok(api::ApplicationResponse::FileData((
utils::get_expired_page(dummy_connector_conf)
.as_bytes()
.to_vec(),
mime::TEXT_HTML,
)))
}
}
| {
"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_payment_-7604715307643159147 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/dummy_connector/core
pub async fn payment(
state: SessionState,
req: types::DummyConnectorPaymentRequest,
) -> types::DummyConnectorResponse<types::DummyConnectorPaymentResponse> {
utils::tokio_mock_sleep(
state.conf.dummy_connector.payment_duration,
state.conf.dummy_connector.payment_tolerance,
)
.await;
let payment_attempt: types::DummyConnectorPaymentAttempt = req.into();
let payment_data =
types::DummyConnectorPaymentData::process_payment_attempt(&state, payment_attempt)?;
utils::store_data_in_redis(
&state,
payment_data.attempt_id.clone(),
payment_data.payment_id.clone(),
state.conf.dummy_connector.authorize_ttl,
)
.await?;
utils::store_data_in_redis(
&state,
payment_data.payment_id.get_string_repr().to_owned(),
payment_data.clone(),
state.conf.dummy_connector.payment_ttl,
)
.await?;
Ok(api::ApplicationResponse::Json(payment_data.into()))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 37,
"total_crates": null
} |
fn_clm_router_refund_data_-7604715307643159147 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/dummy_connector/core
pub async fn refund_data(
state: SessionState,
req: types::DummyConnectorRefundRetrieveRequest,
) -> types::DummyConnectorResponse<types::DummyConnectorRefundResponse> {
let refund_id = req.refund_id;
utils::tokio_mock_sleep(
state.conf.dummy_connector.refund_retrieve_duration,
state.conf.dummy_connector.refund_retrieve_tolerance,
)
.await;
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::DummyConnectorErrors::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let refund_data = redis_conn
.get_and_deserialize_key::<types::DummyConnectorRefundResponse>(
&refund_id.as_str().into(),
"DummyConnectorRefundResponse",
)
.await
.change_context(errors::DummyConnectorErrors::RefundNotFound)?;
Ok(api::ApplicationResponse::Json(refund_data))
}
| {
"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_new_-2152130589636201877 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/dummy_connector/types
// Inherent implementation for DummyConnectorRefundResponse
pub fn new(
status: DummyConnectorStatus,
id: String,
currency: Currency,
created: PrimitiveDateTime,
payment_amount: i64,
refund_amount: i64,
) -> Self {
Self {
status,
id,
currency,
created,
payment_amount,
refund_amount,
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14463,
"total_crates": null
} |
fn_clm_router_from_-2152130589636201877 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/dummy_connector/types
// Implementation of DummyConnectorPaymentResponse for From<DummyConnectorPaymentData>
fn from(value: DummyConnectorPaymentData) -> Self {
Self {
status: value.status,
id: value.payment_id,
amount: value.amount,
currency: value.currency,
created: value.created,
payment_method_type: value.payment_method_type,
next_action: value.next_action,
}
}
| {
"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_name_-2152130589636201877 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/dummy_connector/types
// Implementation of DummyConnectorPayLater for GetPaymentMethodDetails
fn get_name(&self) -> &'static str {
match self {
Self::Klarna => "Klarna",
Self::Affirm => "Affirm",
Self::AfterPayClearPay => "Afterpay Clearpay",
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 44,
"total_crates": null
} |
fn_clm_router_is_eligible_for_refund_-2152130589636201877 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/dummy_connector/types
// Inherent implementation for DummyConnectorPaymentData
pub fn is_eligible_for_refund(&self, refund_amount: i64) -> DummyConnectorResult<()> {
if self.eligible_amount < refund_amount {
return Err(
report!(DummyConnectorErrors::RefundAmountExceedsPaymentAmount)
.attach_printable("Eligible amount is lesser than refund amount"),
);
}
if self.status != DummyConnectorStatus::Succeeded {
return Err(report!(DummyConnectorErrors::PaymentNotSuccessful)
.attach_printable("Payment is not successful to process the refund"));
}
Ok(())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 25,
"total_crates": null
} |
fn_clm_router_get_connector_image_link_-2152130589636201877 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/dummy_connector/types
// Inherent implementation for DummyConnectors
pub fn get_connector_image_link(self, base_url: &str) -> String {
let image_name = match self {
Self::PhonyPay => "PHONYPAY.svg",
Self::FauxPay => "FAUXPAY.svg",
Self::PretendPay => "PRETENDPAY.svg",
Self::StripeTest => "STRIPE_TEST.svg",
Self::PaypalTest => "PAYPAL_TEST.svg",
_ => "PHONYPAY.svg",
};
format!("{base_url}{image_name}")
}
| {
"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_switch_5549196171679306101 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/dummy_connector/errors
// Implementation of DummyConnectorErrors for common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse>
fn switch(&self) -> api_models::errors::types::ApiErrorResponse {
use api_models::errors::types::{ApiError, ApiErrorResponse as AER};
match self {
Self::InternalServerError => {
AER::InternalServerError(ApiError::new("DC", 0, self.error_message(), None))
}
Self::PaymentNotFound => {
AER::NotFound(ApiError::new("DC", 1, self.error_message(), None))
}
Self::MissingRequiredField { field_name: _ } => {
AER::BadRequest(ApiError::new("DC", 2, self.error_message(), None))
}
Self::RefundAmountExceedsPaymentAmount => {
AER::InternalServerError(ApiError::new("DC", 3, self.error_message(), None))
}
Self::CardNotSupported => {
AER::BadRequest(ApiError::new("DC", 4, self.error_message(), None))
}
Self::RefundNotFound => {
AER::NotFound(ApiError::new("DC", 5, self.error_message(), None))
}
Self::PaymentNotSuccessful => {
AER::BadRequest(ApiError::new("DC", 6, self.error_message(), None))
}
Self::PaymentStoringError => {
AER::InternalServerError(ApiError::new("DC", 7, self.error_message(), None))
}
Self::PaymentDeclined { message: _ } => {
AER::BadRequest(ApiError::new("DC", 8, self.error_message(), None))
}
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 3134,
"total_crates": null
} |
fn_clm_router_fmt_5549196171679306101 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/dummy_connector/errors
// Implementation of DummyConnectorErrors for core::fmt::Display
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
r#"{{"error":{}}}"#,
serde_json::to_string(self)
.unwrap_or_else(|_| "Dummy connector error response".to_string())
)
}
| {
"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_store_data_in_redis_-8994140929393458666 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/dummy_connector/utils
pub async fn store_data_in_redis(
state: &SessionState,
key: String,
data: impl serde::Serialize + Debug,
ttl: i64,
) -> types::DummyConnectorResult<()> {
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::DummyConnectorErrors::InternalServerError)
.attach_printable("Failed to get redis connection")?;
redis_conn
.serialize_and_set_key_with_expiry(&key.into(), data, ttl)
.await
.change_context(errors::DummyConnectorErrors::PaymentStoringError)
.attach_printable("Failed to add data in redis")?;
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_flow_from_card_number_-8994140929393458666 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/dummy_connector/utils
// Inherent implementation for types::DummyConnectorCard
pub fn get_flow_from_card_number(
self,
connector: DummyConnectors,
) -> types::DummyConnectorResult<types::DummyConnectorCardFlow> {
let card_number = self.number.peek();
match card_number.as_str() {
"4111111111111111" | "4242424242424242" | "5555555555554444" | "38000000000006"
| "378282246310005" | "6011111111111117" => {
Ok(types::DummyConnectorCardFlow::NoThreeDS(
types::DummyConnectorStatus::Succeeded,
None,
))
}
"5105105105105100" | "4000000000000002" => {
Ok(types::DummyConnectorCardFlow::NoThreeDS(
types::DummyConnectorStatus::Failed,
Some(errors::DummyConnectorErrors::PaymentDeclined {
message: "Card declined",
}),
))
}
"4000000000009995" => {
if connector == DummyConnectors::StripeTest {
Ok(types::DummyConnectorCardFlow::NoThreeDS(
types::DummyConnectorStatus::Succeeded,
None,
))
} else {
Ok(types::DummyConnectorCardFlow::NoThreeDS(
types::DummyConnectorStatus::Failed,
Some(errors::DummyConnectorErrors::PaymentDeclined {
message: "Internal Server Error from Connector, Please try again later",
}),
))
}
}
"4000000000009987" => Ok(types::DummyConnectorCardFlow::NoThreeDS(
types::DummyConnectorStatus::Failed,
Some(errors::DummyConnectorErrors::PaymentDeclined {
message: "Lost card",
}),
)),
"4000000000009979" => Ok(types::DummyConnectorCardFlow::NoThreeDS(
types::DummyConnectorStatus::Failed,
Some(errors::DummyConnectorErrors::PaymentDeclined {
message: "Stolen card",
}),
)),
"4000003800000446" => Ok(types::DummyConnectorCardFlow::ThreeDS(
types::DummyConnectorStatus::Succeeded,
None,
)),
_ => Err(report!(errors::DummyConnectorErrors::CardNotSupported)
.attach_printable("The card is not supported")),
}
}
| {
"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_tokio_mock_sleep_-8994140929393458666 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/dummy_connector/utils
pub async fn tokio_mock_sleep(delay: u64, tolerance: u64) {
let mut rng = rand::thread_rng();
// TODO: change this to `Uniform::try_from`
// this would require changing the fn signature
// to return a Result
let effective_delay = Uniform::from((delay - tolerance)..(delay + tolerance));
tokio::sleep(tokio::Duration::from_millis(
effective_delay.sample(&mut rng),
))
.await
}
| {
"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_get_payment_data_by_attempt_id_-8994140929393458666 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/dummy_connector/utils
pub async fn get_payment_data_by_attempt_id(
state: &SessionState,
attempt_id: String,
) -> types::DummyConnectorResult<types::DummyConnectorPaymentData> {
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::DummyConnectorErrors::InternalServerError)
.attach_printable("Failed to get redis connection")?;
redis_conn
.get_and_deserialize_key::<String>(&attempt_id.as_str().into(), "String")
.await
.async_and_then(|payment_id| async move {
redis_conn
.get_and_deserialize_key::<types::DummyConnectorPaymentData>(
&payment_id.as_str().into(),
"DummyConnectorPaymentData",
)
.await
})
.await
.change_context(errors::DummyConnectorErrors::PaymentNotFound)
}
| {
"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_build_payment_data_from_payment_attempt_-8994140929393458666 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/dummy_connector/utils
// Implementation of types::DummyConnectorPaymentMethodData for ProcessPaymentAttempt
fn build_payment_data_from_payment_attempt(
self,
payment_attempt: types::DummyConnectorPaymentAttempt,
redirect_url: String,
) -> types::DummyConnectorResult<types::DummyConnectorPaymentData> {
match self {
Self::Card(card) => {
card.build_payment_data_from_payment_attempt(payment_attempt, redirect_url)
}
Self::Upi(upi_data) => match upi_data {
types::DummyConnectorUpi::UpiCollect(upi_collect) => upi_collect
.build_payment_data_from_payment_attempt(payment_attempt, redirect_url),
},
Self::Wallet(wallet) => {
wallet.build_payment_data_from_payment_attempt(payment_attempt, redirect_url)
}
Self::PayLater(pay_later) => {
pay_later.build_payment_data_from_payment_attempt(payment_attempt, redirect_url)
}
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 31,
"total_crates": null
} |
fn_clm_router_get_attach_evidence_request_6136203550492766804 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/disputes/utils
pub async fn get_attach_evidence_request(
mut payload: Multipart,
) -> CustomResult<disputes::AttachEvidenceRequest, errors::ApiErrorResponse> {
let mut option_evidence_type: Option<disputes::EvidenceType> = None;
let mut dispute_id: Option<String> = None;
let mut file_name: Option<String> = None;
let mut file_content: Option<Vec<Bytes>> = None;
while let Ok(Some(mut field)) = payload.try_next().await {
let content_disposition = field.content_disposition();
let field_name = content_disposition.get_name();
// Parse the different parameters expected in the multipart request
match field_name {
Some("file") => {
file_name = content_disposition.get_filename().map(String::from);
//Collect the file content and throw error if something fails
let mut file_data = Vec::new();
let mut stream = field.into_stream();
while let Some(chunk) = stream.next().await {
match chunk {
Ok(bytes) => file_data.push(bytes),
Err(err) => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| format!("File parsing error: {err}"))?,
}
}
file_content = Some(file_data)
}
Some("dispute_id") => {
dispute_id = helpers::read_string(&mut field).await;
}
Some("evidence_type") => {
option_evidence_type = parse_evidence_type(&mut field).await?;
}
// Can ignore other params
_ => (),
}
}
let evidence_type = option_evidence_type.get_required_value("evidence_type")?;
let file = file_content.get_required_value("file")?.concat().to_vec();
//Get and validate file size
let file_size = i32::try_from(file.len())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("File size error")?;
// Check if empty file and throw error
fp_utils::when(file_size <= 0, || {
Err(errors::ApiErrorResponse::MissingFile)
.attach_printable("Missing / Invalid file in the request")
})?;
// Get file mime type using 'infer'
let kind = infer::get(&file).ok_or(errors::ApiErrorResponse::MissingFileContentType)?;
let file_type = kind
.mime_type()
.parse::<mime::Mime>()
.change_context(errors::ApiErrorResponse::MissingFileContentType)
.attach_printable("File content type error")?;
let create_file_request = files::CreateFileRequest {
file,
file_name,
file_size,
file_type,
purpose: files::FilePurpose::DisputeEvidence,
dispute_id,
};
Ok(disputes::AttachEvidenceRequest {
evidence_type,
create_file_request,
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 67,
"total_crates": null
} |
fn_clm_router_parse_evidence_type_6136203550492766804 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/disputes/utils
pub async fn parse_evidence_type(
field: &mut Field,
) -> CustomResult<Option<disputes::EvidenceType>, errors::ApiErrorResponse> {
let purpose = helpers::read_string(field).await;
match purpose {
Some(evidence_type) => Ok(Some(
evidence_type
.parse_enum("Evidence Type")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error parsing evidence type")?,
)),
_ => 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": 21,
"total_crates": null
} |
fn_clm_router_upload_file_to_theme_storage_-7163726149432712565 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/user/theme
pub async fn upload_file_to_theme_storage(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
MultipartForm(payload): MultipartForm<theme_api::UploadFileAssetData>,
) -> HttpResponse {
let flow = Flow::UploadFileToThemeStorage;
let theme_id = path.into_inner();
let payload = theme_api::UploadFileRequest {
asset_name: payload.asset_name.into_inner(),
asset_data: Secret::new(payload.asset_data.data.to_vec()),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _, payload, _| {
theme_core::upload_file_to_theme_storage(state, theme_id.clone(), payload)
},
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
| {
"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_upload_file_to_user_theme_storage_-7163726149432712565 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/user/theme
pub async fn upload_file_to_user_theme_storage(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
MultipartForm(payload): MultipartForm<theme_api::UploadFileAssetData>,
) -> HttpResponse {
let flow = Flow::UploadFileToUserThemeStorage;
let theme_id = path.into_inner();
let payload = theme_api::UploadFileRequest {
asset_name: payload.asset_name.into_inner(),
asset_data: Secret::new(payload.asset_data.data.to_vec()),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, user: auth::UserFromToken, payload, _| {
theme_core::upload_file_to_user_theme_storage(state, theme_id.clone(), user, payload)
},
&auth::JWTAuth {
permission: Permission::OrganizationThemeWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
| {
"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_update_theme_-7163726149432712565 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/user/theme
pub async fn update_theme(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
payload: web::Json<theme_api::UpdateThemeRequest>,
) -> HttpResponse {
let flow = Flow::UpdateTheme;
let theme_id = path.into_inner();
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _, payload, _| theme_core::update_theme(state, theme_id.clone(), payload),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 25,
"total_crates": null
} |
fn_clm_router_update_user_theme_-7163726149432712565 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/user/theme
pub async fn update_user_theme(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
payload: web::Json<theme_api::UpdateThemeRequest>,
) -> HttpResponse {
let flow = Flow::UpdateUserTheme;
let theme_id = path.into_inner();
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, user: auth::UserFromToken, payload, _| {
theme_core::update_user_theme(state, theme_id.clone(), user, payload)
},
&auth::JWTAuth {
permission: Permission::OrganizationThemeWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 25,
"total_crates": null
} |
fn_clm_router_get_theme_using_lineage_-7163726149432712565 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/user/theme
pub async fn get_theme_using_lineage(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<ThemeLineage>,
) -> HttpResponse {
let flow = Flow::GetThemeUsingLineage;
let lineage = query.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
lineage,
|state, _, lineage, _| theme_core::get_theme_using_lineage(state, lineage),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
| {
"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_get_create_file_request_8766147818887261062 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/routes/files/transformers
pub async fn get_create_file_request(
mut payload: Multipart,
) -> CustomResult<CreateFileRequest, errors::ApiErrorResponse> {
let mut option_purpose: Option<files::FilePurpose> = None;
let mut dispute_id: Option<String> = None;
let mut file_name: Option<String> = None;
let mut file_content: Option<Vec<Bytes>> = None;
while let Ok(Some(mut field)) = payload.try_next().await {
let content_disposition = field.content_disposition();
let field_name = content_disposition.get_name();
// Parse the different parameters expected in the multipart request
match field_name {
Some("purpose") => {
option_purpose = helpers::get_file_purpose(&mut field).await;
}
Some("file") => {
file_name = content_disposition.get_filename().map(String::from);
//Collect the file content and throw error if something fails
let mut file_data = Vec::new();
let mut stream = field.into_stream();
while let Some(chunk) = stream.next().await {
match chunk {
Ok(bytes) => file_data.push(bytes),
Err(err) => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!("{}{}", "File parsing error: ", err))?,
}
}
file_content = Some(file_data)
}
Some("dispute_id") => {
dispute_id = helpers::read_string(&mut field).await;
}
// Can ignore other params
_ => (),
}
}
let purpose = option_purpose.get_required_value("purpose")?;
let file = match file_content {
Some(valid_file_content) => valid_file_content.concat().to_vec(),
None => Err(errors::ApiErrorResponse::MissingFile)
.attach_printable("Missing / Invalid file in the request")?,
};
//Get and validate file size
let file_size = i32::try_from(file.len())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("File size error")?;
// Check if empty file and throw error
if file_size <= 0 {
Err(errors::ApiErrorResponse::MissingFile)
.attach_printable("Missing / Invalid file in the request")?
}
// Get file mime type using 'infer'
let kind = infer::get(&file).ok_or(errors::ApiErrorResponse::MissingFileContentType)?;
let file_type = kind
.mime_type()
.parse::<mime::Mime>()
.change_context(errors::ApiErrorResponse::MissingFileContentType)
.attach_printable("File content type error")?;
Ok(CreateFileRequest {
file,
file_name,
file_size,
file_type,
purpose,
dispute_id,
})
}
| {
"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_search_indexes_7146606674361677307 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/consts/opensearch
pub const fn get_search_indexes() -> [SearchIndex; 8] {
[
SearchIndex::PaymentAttempts,
SearchIndex::PaymentIntents,
SearchIndex::Refunds,
SearchIndex::Disputes,
SearchIndex::SessionizerPaymentAttempts,
SearchIndex::SessionizerPaymentIntents,
SearchIndex::SessionizerRefunds,
SearchIndex::SessionizerDisputes,
]
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 10,
"total_crates": null
} |
fn_clm_router_get_redis_connection_for_global_tenant_-4560646222057195532 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/openidconnect
fn get_redis_connection_for_global_tenant(
state: &SessionState,
) -> UserResult<std::sync::Arc<RedisConnectionPool>> {
state
.global_store
.get_redis_conn()
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to get redis connection")
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 90,
"total_crates": null
} |
fn_clm_router_get_user_email_from_oidc_provider_-4560646222057195532 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/openidconnect
pub async fn get_user_email_from_oidc_provider(
state: &SessionState,
redirect_url: String,
redirect_state: Secret<String>,
base_url: Secret<String>,
client_id: Secret<String>,
authorization_code: Secret<String>,
client_secret: Secret<String>,
) -> UserResult<UserEmail> {
let nonce = get_nonce_from_redis(state, &redirect_state).await?;
let discovery_document = get_discovery_document(base_url, state).await?;
let client = get_oidc_core_client(
discovery_document,
client_id,
Some(client_secret),
redirect_url,
)?;
let nonce_clone = nonce.clone();
client
.authorize_url(
oidc_core::CoreAuthenticationFlow::AuthorizationCode,
|| oidc::CsrfToken::new(redirect_state.expose()),
|| nonce_clone,
)
.add_scope(oidc::Scope::new("email".to_string()));
// Send request to OpenId provider with authorization code
let token_response = client
.exchange_code(oidc::AuthorizationCode::new(authorization_code.expose()))
.request_async(|req| get_oidc_reqwest_client(state, req))
.await
.map_err(|e| match e {
oidc::RequestTokenError::ServerResponse(resp)
if resp.error() == &oidc_core::CoreErrorResponseType::InvalidGrant =>
{
UserErrors::SSOFailed
}
_ => UserErrors::InternalServerError,
})
.attach_printable("Failed to exchange code and fetch oidc token")?;
// Fetch id token from response
let id_token = token_response
.id_token()
.ok_or(UserErrors::InternalServerError)
.attach_printable("Id Token not provided in token response")?;
// Verify id token
let id_token_claims = id_token
.claims(&client.id_token_verifier(), &nonce)
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to verify id token")?;
// Get email from token
let email_from_token = id_token_claims
.email()
.map(|email| email.to_string())
.ok_or(UserErrors::InternalServerError)
.attach_printable("OpenID Provider Didnt provide email")?;
UserEmail::new(Secret::new(email_from_token))
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to create email type")
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 81,
"total_crates": null
} |
fn_clm_router_get_oidc_reqwest_client_-4560646222057195532 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/openidconnect
async fn get_oidc_reqwest_client(
state: &SessionState,
request: oidc::HttpRequest,
) -> Result<oidc::HttpResponse, ApiClientError> {
let client = client::create_client(&state.conf.proxy, None, None, None)
.map_err(|e| e.current_context().switch())?;
let mut request_builder = client
.request(request.method, request.url)
.body(request.body);
for (name, value) in &request.headers {
request_builder = request_builder.header(name.as_str(), value.as_bytes());
}
let request = request_builder
.build()
.map_err(|_| ApiClientError::ClientConstructionFailed)?;
let response = client
.execute(request)
.await
.map_err(|_| ApiClientError::RequestNotSent("OpenIDConnect".to_string()))?;
Ok(oidc::HttpResponse {
status_code: response.status(),
headers: response.headers().to_owned(),
body: response
.bytes()
.await
.map_err(|_| ApiClientError::ResponseDecodingFailed)?
.to_vec(),
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 48,
"total_crates": null
} |
fn_clm_router_get_authorization_url_-4560646222057195532 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/openidconnect
pub async fn get_authorization_url(
state: SessionState,
redirect_url: String,
redirect_state: Secret<String>,
base_url: Secret<String>,
client_id: Secret<String>,
) -> UserResult<url::Url> {
let discovery_document = get_discovery_document(base_url, &state).await?;
let (auth_url, csrf_token, nonce) =
get_oidc_core_client(discovery_document, client_id, None, redirect_url)?
.authorize_url(
oidc_core::CoreAuthenticationFlow::AuthorizationCode,
|| oidc::CsrfToken::new(redirect_state.expose()),
oidc::Nonce::new_random,
)
.add_scope(oidc::Scope::new("email".to_string()))
.url();
// Save csrf & nonce as key value respectively
let key = get_oidc_redis_key(csrf_token.secret());
get_redis_connection_for_global_tenant(&state)?
.set_key_with_expiry(&key.into(), nonce.secret(), consts::user::REDIS_SSO_TTL)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("Failed to save csrf-nonce in redis")?;
Ok(auth_url)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 47,
"total_crates": null
} |
fn_clm_router_get_oidc_core_client_-4560646222057195532 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/openidconnect
fn get_oidc_core_client(
discovery_document: oidc_core::CoreProviderMetadata,
client_id: Secret<String>,
client_secret: Option<Secret<String>>,
redirect_url: String,
) -> UserResult<oidc_core::CoreClient> {
let client_id = oidc::ClientId::new(client_id.expose());
let client_secret = client_secret.map(|secret| oidc::ClientSecret::new(secret.expose()));
let redirect_url = oidc::RedirectUrl::new(redirect_url)
.change_context(UserErrors::InternalServerError)
.attach_printable("Error creating redirect URL type")?;
Ok(
oidc_core::CoreClient::from_provider_metadata(discovery_document, client_id, client_secret)
.set_redirect_uri(redirect_url),
)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 26,
"total_crates": null
} |
fn_clm_router_decrypt_jwe_-8639071140824141905 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/encryption
pub async fn decrypt_jwe(
jwt: &str,
key_ids: KeyIdCheck<'_>,
private_key: impl AsRef<[u8]>,
alg: jwe::alg::rsaes::RsaesJweAlgorithm,
) -> CustomResult<String, errors::EncryptionError> {
if let KeyIdCheck::RequestResponseKeyId((req_key_id, resp_key_id)) = key_ids {
utils::when(req_key_id.ne(resp_key_id), || {
Err(report!(errors::EncryptionError)
.attach_printable("key_id mismatch, Error authenticating response"))
})?;
}
let decrypter = alg
.decrypter_from_pem(private_key)
.change_context(errors::EncryptionError)
.attach_printable("Error getting JweDecryptor")?;
let (dst_payload, _dst_header) = jwe::deserialize_compact(jwt, &decrypter)
.change_context(errors::EncryptionError)
.attach_printable("Error getting Decrypted jwe")?;
String::from_utf8(dst_payload)
.change_context(errors::EncryptionError)
.attach_printable("Could not decode JWE payload from UTF-8")
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 55,
"total_crates": null
} |
fn_clm_router_encrypt_jwe_-8639071140824141905 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/encryption
pub async fn encrypt_jwe(
payload: &[u8],
public_key: impl AsRef<[u8]>,
algorithm: EncryptionAlgorithm,
key_id: Option<&str>,
) -> CustomResult<String, errors::EncryptionError> {
let alg = jwe::RSA_OAEP_256;
let mut src_header = jwe::JweHeader::new();
let enc_str = algorithm.as_ref();
src_header.set_content_encryption(enc_str);
src_header.set_token_type("JWT");
if let Some(key_id) = key_id {
src_header.set_key_id(key_id);
}
let encrypter = alg
.encrypter_from_pem(public_key)
.change_context(errors::EncryptionError)
.attach_printable("Error getting JweEncryptor")?;
jwe::serialize_compact(payload, &src_header, &encrypter)
.change_context(errors::EncryptionError)
.attach_printable("Error getting jwt string")
}
| {
"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_jws_sign_payload_-8639071140824141905 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/encryption
pub async fn jws_sign_payload(
payload: &[u8],
kid: &str,
private_key: impl AsRef<[u8]>,
) -> CustomResult<String, errors::EncryptionError> {
let alg = jws::RS256;
let mut src_header = jws::JwsHeader::new();
src_header.set_key_id(kid);
let signer = alg
.signer_from_pem(private_key)
.change_context(errors::EncryptionError)
.attach_printable("Error getting signer")?;
let jwt = jws::serialize_compact(payload, &src_header, &signer)
.change_context(errors::EncryptionError)
.attach_printable("Error getting signed jwt string")?;
Ok(jwt)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 47,
"total_crates": null
} |
fn_clm_router_verify_sign_-8639071140824141905 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/encryption
pub fn verify_sign(
jws_body: String,
key: impl AsRef<[u8]>,
) -> CustomResult<String, errors::EncryptionError> {
let alg = jws::RS256;
let input = jws_body.as_bytes();
let verifier = alg
.verifier_from_pem(key)
.change_context(errors::EncryptionError)
.attach_printable("Error getting verifier")?;
let (dst_payload, _dst_header) = jws::deserialize_compact(input, &verifier)
.change_context(errors::EncryptionError)
.attach_printable("Error getting Decrypted jws")?;
let resp = String::from_utf8(dst_payload)
.change_context(errors::EncryptionError)
.attach_printable("Could not convert to UTF-8")?;
Ok(resp)
}
| {
"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_test_jwe_-8639071140824141905 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/encryption
async fn test_jwe() {
let jwt = encrypt_jwe(
"request_payload".as_bytes(),
ENCRYPTION_KEY,
EncryptionAlgorithm::A256GCM,
None,
)
.await
.unwrap();
let alg = jwe::RSA_OAEP_256;
let payload = decrypt_jwe(&jwt, KeyIdCheck::SkipKeyIdCheck, DECRYPTION_KEY, alg)
.await
.unwrap();
assert_eq!("request_payload".to_string(), payload)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 6,
"total_crates": null
} |
fn_clm_router_generate_jwt_6120336654301695858 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/jwt
pub async fn generate_jwt<T>(
claims_data: &T,
settings: &Settings,
) -> CustomResult<String, UserErrors>
where
T: serde::ser::Serialize,
{
let jwt_secret = &settings.secrets.get_inner().jwt_secret;
encode(
&Header::default(),
claims_data,
&EncodingKey::from_secret(jwt_secret.peek().as_bytes()),
)
.change_context(UserErrors::InternalServerError)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 36,
"total_crates": null
} |
fn_clm_router_generate_exp_6120336654301695858 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/jwt
pub fn generate_exp(
exp_duration: std::time::Duration,
) -> CustomResult<std::time::Duration, UserErrors> {
std::time::SystemTime::now()
.checked_add(exp_duration)
.ok_or(UserErrors::InternalServerError)?
.duration_since(std::time::UNIX_EPOCH)
.change_context(UserErrors::InternalServerError)
}
| {
"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_increment_blocked_count_in_cache_529830715782412237 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/card_testing_guard
pub async fn increment_blocked_count_in_cache<A>(
state: &A,
cache_key: &str,
expiry: i64,
) -> RouterResult<()>
where
A: SessionStateInfo + Sync,
{
let redis_conn = get_redis_connection(state)?;
let value: Option<i32> = redis_conn
.get_key(&cache_key.into())
.await
.change_context(ApiErrorResponse::InternalServerError)?;
let mut incremented_blocked_count: i32 = 1;
if let Some(actual_value) = value {
incremented_blocked_count = actual_value + 1;
}
redis_conn
.set_key_with_expiry(&cache_key.into(), incremented_blocked_count, expiry)
.await
.change_context(ApiErrorResponse::InternalServerError)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 36,
"total_crates": null
} |
fn_clm_router_get_blocked_count_from_cache_529830715782412237 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/card_testing_guard
pub async fn get_blocked_count_from_cache<A>(
state: &A,
cache_key: &str,
) -> RouterResult<Option<i32>>
where
A: SessionStateInfo + Sync,
{
let redis_conn = get_redis_connection(state)?;
let value: Option<i32> = redis_conn
.get_key(&cache_key.into())
.await
.change_context(ApiErrorResponse::InternalServerError)?;
Ok(value)
}
| {
"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_set_blocked_count_in_cache_529830715782412237 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/card_testing_guard
pub async fn set_blocked_count_in_cache<A>(
state: &A,
cache_key: &str,
value: i32,
expiry: i64,
) -> RouterResult<()>
where
A: SessionStateInfo + Sync,
{
let redis_conn = get_redis_connection(state)?;
redis_conn
.set_key_with_expiry(&cache_key.into(), value, expiry)
.await
.change_context(ApiErrorResponse::InternalServerError)
}
| {
"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_get_redis_connection_529830715782412237 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/card_testing_guard
fn get_redis_connection<A: SessionStateInfo>(state: &A) -> RouterResult<Arc<RedisConnectionPool>> {
state
.store()
.get_redis_conn()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 17,
"total_crates": null
} |
fn_clm_router_new_-1600941121536599388 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/kafka
// Inherent implementation for KafkaConsolidatedEvent<'a, T>
fn new(event: &'a T, tenant_id: TenantID) -> Self {
Self {
log: KafkaConsolidatedLog { event, tenant_id },
log_type: event.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": 14455,
"total_crates": null
} |
fn_clm_router_validate_-1600941121536599388 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/kafka
// Inherent implementation for KafkaSettings
pub fn validate(&self) -> Result<(), crate::core::errors::ApplicationError> {
use common_utils::ext_traits::ConfigExt;
use crate::core::errors::ApplicationError;
common_utils::fp_utils::when(self.brokers.is_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka brokers must not be empty".into(),
))
})?;
common_utils::fp_utils::when(self.intent_analytics_topic.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka Intent Analytics topic must not be empty".into(),
))
})?;
common_utils::fp_utils::when(self.attempt_analytics_topic.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka Attempt Analytics topic must not be empty".into(),
))
})?;
common_utils::fp_utils::when(self.refund_analytics_topic.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka Refund Analytics topic must not be empty".into(),
))
})?;
common_utils::fp_utils::when(self.api_logs_topic.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka API event Analytics topic must not be empty".into(),
))
})?;
common_utils::fp_utils::when(self.connector_logs_topic.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka Connector Logs topic must not be empty".into(),
))
})?;
common_utils::fp_utils::when(
self.outgoing_webhook_logs_topic.is_default_or_empty(),
|| {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka Outgoing Webhook Logs topic must not be empty".into(),
))
},
)?;
common_utils::fp_utils::when(self.dispute_analytics_topic.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka Dispute Logs topic must not be empty".into(),
))
})?;
common_utils::fp_utils::when(self.audit_events_topic.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka Audit Events topic must not be empty".into(),
))
})?;
#[cfg(feature = "payouts")]
common_utils::fp_utils::when(self.payout_analytics_topic.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka Payout Analytics topic must not be empty".into(),
))
})?;
common_utils::fp_utils::when(self.consolidated_events_topic.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Consolidated Events topic must not be empty".into(),
))
})?;
common_utils::fp_utils::when(
self.authentication_analytics_topic.is_default_or_empty(),
|| {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka Authentication Analytics topic must not be empty".into(),
))
},
)?;
common_utils::fp_utils::when(self.routing_logs_topic.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"Kafka Routing Logs topic must not be empty".into(),
))
})?;
Ok(())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 323,
"total_crates": null
} |
fn_clm_router_log_event_-1600941121536599388 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/kafka
// Inherent implementation for KafkaProducer
pub fn log_event<T: KafkaMessage>(&self, event: &T) -> MQResult<()> {
router_env::logger::debug!("Logging Kafka Event {event:?}");
let topic = self.get_topic(event.event_type());
self.producer
.0
.send(
BaseRecord::to(topic)
.key(&event.key())
.payload(&event.value()?)
.timestamp(event.creation_timestamp().unwrap_or_else(|| {
(OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000)
.try_into()
.unwrap_or_else(|_| {
// kafka producer accepts milliseconds
// try converting nanos to millis if that fails convert seconds to millis
OffsetDateTime::now_utc().unix_timestamp() * 1_000
})
})),
)
.map_err(|(error, record)| report!(error).attach_printable(format!("{record:?}")))
.change_context(KafkaError::GenericError)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 199,
"total_crates": null
} |
fn_clm_router_value_-1600941121536599388 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/kafka
fn value(&self) -> MQResult<Vec<u8>> {
// Add better error logging here
serde_json::to_vec(&self).change_context(KafkaError::GenericError)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 109,
"total_crates": null
} |
fn_clm_router_create_-1600941121536599388 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/kafka
// Inherent implementation for KafkaProducer
pub async fn create(conf: &KafkaSettings) -> MQResult<Self> {
Ok(Self {
producer: Arc::new(RdKafkaProducer(
ThreadedProducer::from_config(
rdkafka::ClientConfig::new().set("bootstrap.servers", conf.brokers.join(",")),
)
.change_context(KafkaError::InitializationError)?,
)),
fraud_check_analytics_topic: conf.fraud_check_analytics_topic.clone(),
intent_analytics_topic: conf.intent_analytics_topic.clone(),
attempt_analytics_topic: conf.attempt_analytics_topic.clone(),
refund_analytics_topic: conf.refund_analytics_topic.clone(),
api_logs_topic: conf.api_logs_topic.clone(),
connector_logs_topic: conf.connector_logs_topic.clone(),
outgoing_webhook_logs_topic: conf.outgoing_webhook_logs_topic.clone(),
dispute_analytics_topic: conf.dispute_analytics_topic.clone(),
audit_events_topic: conf.audit_events_topic.clone(),
#[cfg(feature = "payouts")]
payout_analytics_topic: conf.payout_analytics_topic.clone(),
consolidated_events_topic: conf.consolidated_events_topic.clone(),
authentication_analytics_topic: conf.authentication_analytics_topic.clone(),
ckh_database_name: None,
routing_logs_topic: conf.routing_logs_topic.clone(),
revenue_recovery_topic: conf.revenue_recovery_topic.clone(),
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 108,
"total_crates": null
} |
fn_clm_router_new_2400127679428170735 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/authentication
// Implementation of None for HeaderMapStruct<'a>
pub fn new(headers: &'a HeaderMap) -> Self {
HeaderMapStruct { headers }
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14463,
"total_crates": null
} |
fn_clm_router_auth_type_2400127679428170735 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/authentication
pub fn auth_type<'a, T, A>(
default_auth: &'a dyn AuthenticateAndFetch<T, A>,
jwt_auth_type: &'a dyn AuthenticateAndFetch<T, A>,
headers: &HeaderMap,
) -> &'a dyn AuthenticateAndFetch<T, A>
where
{
if is_jwt_auth(headers) {
return jwt_auth_type;
}
default_auth
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 432,
"total_crates": null
} |
fn_clm_router_check_client_secret_and_get_auth_2400127679428170735 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/authentication
pub fn check_client_secret_and_get_auth<T>(
headers: &HeaderMap,
payload: &impl ClientSecretFetch,
api_auth: ApiKeyAuth,
) -> RouterResult<(
Box<dyn AuthenticateAndFetch<AuthenticationData, T>>,
api::AuthFlow,
)>
where
T: SessionStateInfo + Sync + Send,
ApiKeyAuth: AuthenticateAndFetch<AuthenticationData, T>,
PublishableKeyAuth: AuthenticateAndFetch<AuthenticationData, T>,
{
let api_key = get_api_key(headers)?;
if api_key.starts_with("pk_") {
payload
.get_client_secret()
.check_value_present("client_secret")
.map_err(|_| errors::ApiErrorResponse::MissingRequiredField {
field_name: "client_secret",
})?;
return Ok((
Box::new(HeaderAuth(PublishableKeyAuth)),
api::AuthFlow::Client,
));
}
if payload.get_client_secret().is_some() {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "client_secret is not a valid parameter".to_owned(),
}
.into());
}
Ok((Box::new(HeaderAuth(api_auth)), api::AuthFlow::Merchant))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 105,
"total_crates": null
} |
fn_clm_router_construct_authentication_data_2400127679428170735 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/authentication
async fn construct_authentication_data<A>(
state: &A,
merchant_id: &id_type::MerchantId,
request_headers: &HeaderMap,
profile_id: Option<id_type::ProfileId>,
) -> RouterResult<AuthenticationData>
where
A: SessionStateInfo + Sync,
{
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
&(&state.session_state()).into(),
merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(
&(&state.session_state()).into(),
merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
// Get connected merchant account if API call is done by Platform merchant account on behalf of connected merchant account
let (merchant, platform_merchant_account) = if state.conf().platform.enabled {
get_platform_merchant_account(state, request_headers, merchant).await?
} else {
(merchant, None)
};
let key_store = if platform_merchant_account.is_some() {
state
.store()
.get_merchant_key_store_by_merchant_id(
&(&state.session_state()).into(),
merchant.get_id(),
&state.store().get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Failed to fetch merchant key store for the merchant id")?
} else {
key_store
};
let auth = AuthenticationData {
merchant_account: merchant,
platform_merchant_account,
key_store,
profile_id,
};
Ok(auth)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 58,
"total_crates": null
} |
fn_clm_router_get_id_type_from_header_if_present_2400127679428170735 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/authentication
// Implementation of None for HeaderMapStruct<'a>
pub fn get_id_type_from_header_if_present<T>(&self, key: &str) -> RouterResult<Option<T>>
where
T: TryFrom<
std::borrow::Cow<'static, str>,
Error = error_stack::Report<errors::ValidationError>,
>,
{
self.headers
.get(key)
.map(|value| value.to_str())
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "`{key}` in headers",
})
.attach_printable(format!(
"Failed to convert header value to string for header key: {key}",
))?
.map(|value| {
T::try_from(std::borrow::Cow::Owned(value.to_owned())).change_context(
errors::ApiErrorResponse::InvalidRequestData {
message: format!("`{key}` header is invalid"),
},
)
})
.transpose()
}
| {
"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_server_wrap_-1596591786337376396 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/api
pub async fn server_wrap<'a, T, U, Q, F, Fut, E>(
flow: impl router_env::types::FlowMetric,
state: web::Data<AppState>,
request: &'a HttpRequest,
payload: T,
func: F,
api_auth: &dyn AuthenticateAndFetch<U, SessionState>,
lock_action: api_locking::LockAction,
) -> HttpResponse
where
F: Fn(SessionState, U, T, ReqState) -> Fut,
Fut: Future<Output = CustomResult<ApplicationResponse<Q>, E>>,
Q: Serialize + Debug + ApiEventMetric + 'a,
T: Debug + Serialize + ApiEventMetric,
ApplicationResponse<Q>: Debug,
E: ErrorSwitch<api_models::errors::types::ApiErrorResponse> + error_stack::Context,
{
let request_method = request.method().as_str();
let url_path = request.path();
let unmasked_incoming_header_keys = state.conf().unmasked_headers.keys;
let incoming_request_header = request.headers();
let incoming_header_to_log: HashMap<String, HeaderValue> =
incoming_request_header
.iter()
.fold(HashMap::new(), |mut acc, (key, value)| {
let key = key.to_string();
if unmasked_incoming_header_keys.contains(&key.as_str().to_lowercase()) {
acc.insert(key.clone(), value.clone());
} else {
acc.insert(key.clone(), HeaderValue::from_static("**MASKED**"));
}
acc
});
tracing::Span::current().record("request_method", request_method);
tracing::Span::current().record("request_url_path", url_path);
let start_instant = Instant::now();
logger::info!(
tag = ?Tag::BeginRequest, payload = ?payload,
headers = ?incoming_header_to_log);
let server_wrap_util_res = server_wrap_util(
&flow,
state.clone(),
incoming_request_header,
request,
payload,
func,
api_auth,
lock_action,
)
.await
.map(|response| {
logger::info!(api_response =? response);
response
});
let res = match server_wrap_util_res {
Ok(ApplicationResponse::Json(response)) => match serde_json::to_string(&response) {
Ok(res) => http_response_json(res),
Err(_) => http_response_err(
r#"{
"error": {
"message": "Error serializing response from connector"
}
}"#,
),
},
Ok(ApplicationResponse::StatusOk) => http_response_ok(),
Ok(ApplicationResponse::TextPlain(text)) => http_response_plaintext(text),
Ok(ApplicationResponse::FileData((file_data, content_type))) => {
http_response_file_data(file_data, content_type)
}
Ok(ApplicationResponse::JsonForRedirection(response)) => {
match serde_json::to_string(&response) {
Ok(res) => http_redirect_response(res, response),
Err(_) => http_response_err(
r#"{
"error": {
"message": "Error serializing response from connector"
}
}"#,
),
}
}
Ok(ApplicationResponse::Form(redirection_data)) => {
let config = state.conf();
build_redirection_form(
&redirection_data.redirect_form,
redirection_data.payment_method_data,
redirection_data.amount,
redirection_data.currency,
config,
)
.respond_to(request)
.map_into_boxed_body()
}
Ok(ApplicationResponse::GenericLinkForm(boxed_generic_link_data)) => {
let link_type = boxed_generic_link_data.data.to_string();
match build_generic_link_html(
boxed_generic_link_data.data,
boxed_generic_link_data.locale,
) {
Ok(rendered_html) => {
let headers = if !boxed_generic_link_data.allowed_domains.is_empty() {
let domains_str = boxed_generic_link_data
.allowed_domains
.into_iter()
.collect::<Vec<String>>()
.join(" ");
let csp_header = format!("frame-ancestors 'self' {domains_str};");
Some(HashSet::from([("content-security-policy", csp_header)]))
} else {
None
};
http_response_html_data(rendered_html, headers)
}
Err(_) => http_response_err(format!("Error while rendering {link_type} HTML page")),
}
}
Ok(ApplicationResponse::PaymentLinkForm(boxed_payment_link_data)) => {
match *boxed_payment_link_data {
PaymentLinkAction::PaymentLinkFormData(payment_link_data) => {
match build_payment_link_html(payment_link_data) {
Ok(rendered_html) => http_response_html_data(rendered_html, None),
Err(_) => http_response_err(
r#"{
"error": {
"message": "Error while rendering payment link html page"
}
}"#,
),
}
}
PaymentLinkAction::PaymentLinkStatus(payment_link_data) => {
match get_payment_link_status(payment_link_data) {
Ok(rendered_html) => http_response_html_data(rendered_html, None),
Err(_) => http_response_err(
r#"{
"error": {
"message": "Error while rendering payment link status page"
}
}"#,
),
}
}
}
}
Ok(ApplicationResponse::JsonWithHeaders((response, headers))) => {
let request_elapsed_time = request.headers().get(X_HS_LATENCY).and_then(|value| {
if value == "true" {
Some(start_instant.elapsed())
} else {
None
}
});
let proxy_connector_http_status_code = if state
.conf
.proxy_status_mapping
.proxy_connector_http_status_code
{
headers
.iter()
.find(|(key, _)| key == headers::X_CONNECTOR_HTTP_STATUS_CODE)
.and_then(|(_, value)| {
match value.clone().into_inner().parse::<u16>() {
Ok(code) => match http::StatusCode::from_u16(code) {
Ok(status_code) => Some(status_code),
Err(err) => {
logger::error!(
"Invalid HTTP status code parsed from connector_http_status_code: {:?}",
err
);
None
}
},
Err(err) => {
logger::error!(
"Failed to parse connector_http_status_code from header: {:?}",
err
);
None
}
}
})
} else {
None
};
match serde_json::to_string(&response) {
Ok(res) => http_response_json_with_headers(
res,
headers,
request_elapsed_time,
proxy_connector_http_status_code,
),
Err(_) => http_response_err(
r#"{
"error": {
"message": "Error serializing response from connector"
}
}"#,
),
}
}
Err(error) => log_and_return_error_response(error),
};
let response_code = res.status().as_u16();
tracing::Span::current().record("status_code", response_code);
let end_instant = Instant::now();
let request_duration = end_instant.saturating_duration_since(start_instant);
logger::info!(
tag = ?Tag::EndRequest,
time_taken_ms = request_duration.as_millis(),
);
res
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 1455,
"total_crates": null
} |
fn_clm_router_log_and_return_error_response_-1596591786337376396 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/api
pub fn log_and_return_error_response<T>(error: Report<T>) -> HttpResponse
where
T: error_stack::Context + Clone + ResponseError,
Report<T>: EmbedError,
{
logger::error!(?error);
HttpResponse::from_error(error.embed().current_context().clone())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 306,
"total_crates": null
} |
fn_clm_router_server_wrap_util_-1596591786337376396 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/api
pub async fn server_wrap_util<'a, 'b, U, T, Q, F, Fut, E, OErr>(
flow: &'a impl router_env::types::FlowMetric,
state: web::Data<AppState>,
incoming_request_header: &HeaderMap,
request: &'a HttpRequest,
payload: T,
func: F,
api_auth: &dyn AuthenticateAndFetch<U, SessionState>,
lock_action: api_locking::LockAction,
) -> CustomResult<ApplicationResponse<Q>, OErr>
where
F: Fn(SessionState, U, T, ReqState) -> Fut,
'b: 'a,
Fut: Future<Output = CustomResult<ApplicationResponse<Q>, E>>,
Q: Serialize + Debug + 'a + ApiEventMetric,
T: Debug + Serialize + ApiEventMetric,
E: ErrorSwitch<OErr> + error_stack::Context,
OErr: ResponseError + error_stack::Context + Serialize,
errors::ApiErrorResponse: ErrorSwitch<OErr>,
{
let request_id = RequestId::extract(request)
.await
.attach_printable("Unable to extract request id from request")
.change_context(errors::ApiErrorResponse::InternalServerError.switch())?;
let mut app_state = state.get_ref().clone();
let start_instant = Instant::now();
let serialized_request = masking::masked_serialize(&payload)
.attach_printable("Failed to serialize json request")
.change_context(errors::ApiErrorResponse::InternalServerError.switch())?;
let mut event_type = payload.get_api_event_type();
let tenant_id = if !state.conf.multitenancy.enabled {
common_utils::id_type::TenantId::try_from_string(DEFAULT_TENANT.to_owned())
.attach_printable("Unable to get default tenant id")
.change_context(errors::ApiErrorResponse::InternalServerError.switch())?
} else {
let request_tenant_id = incoming_request_header
.get(TENANT_HEADER)
.and_then(|value| value.to_str().ok())
.ok_or_else(|| errors::ApiErrorResponse::MissingTenantId.switch())
.and_then(|header_value| {
common_utils::id_type::TenantId::try_from_string(header_value.to_string()).map_err(
|_| {
errors::ApiErrorResponse::InvalidRequestData {
message: format!("`{}` header is invalid", headers::X_TENANT_ID),
}
.switch()
},
)
})?;
state
.conf
.multitenancy
.get_tenant(&request_tenant_id)
.map(|tenant| tenant.tenant_id.clone())
.ok_or(
errors::ApiErrorResponse::InvalidTenant {
tenant_id: request_tenant_id.get_string_repr().to_string(),
}
.switch(),
)?
};
let locale = utils::get_locale_from_header(&incoming_request_header.clone());
let mut session_state =
Arc::new(app_state.clone()).get_session_state(&tenant_id, Some(locale), || {
errors::ApiErrorResponse::InvalidTenant {
tenant_id: tenant_id.get_string_repr().to_string(),
}
.switch()
})?;
session_state.add_request_id(request_id);
let mut request_state = session_state.get_req_state();
request_state.event_context.record_info(request_id);
request_state
.event_context
.record_info(("flow".to_string(), flow.to_string()));
request_state.event_context.record_info((
"tenant_id".to_string(),
tenant_id.get_string_repr().to_string(),
));
// Currently auth failures are not recorded as API events
let (auth_out, auth_type) = api_auth
.authenticate_and_fetch(request.headers(), &session_state)
.await
.switch()?;
request_state.event_context.record_info(auth_type.clone());
let merchant_id = auth_type
.get_merchant_id()
.cloned()
.unwrap_or(common_utils::id_type::MerchantId::get_merchant_id_not_found());
app_state.add_flow_name(flow.to_string());
tracing::Span::current().record("merchant_id", merchant_id.get_string_repr().to_owned());
let output = {
lock_action
.clone()
.perform_locking_action(&session_state, merchant_id.to_owned())
.await
.switch()?;
let res = func(session_state.clone(), auth_out, payload, request_state)
.await
.switch();
lock_action
.free_lock_action(&session_state, merchant_id.to_owned())
.await
.switch()?;
res
};
let request_duration = Instant::now()
.saturating_duration_since(start_instant)
.as_millis();
let mut serialized_response = None;
let mut error = None;
let mut overhead_latency = None;
let status_code = match output.as_ref() {
Ok(res) => {
if let ApplicationResponse::Json(data) = res {
serialized_response.replace(
masking::masked_serialize(&data)
.attach_printable("Failed to serialize json response")
.change_context(errors::ApiErrorResponse::InternalServerError.switch())?,
);
} else if let ApplicationResponse::JsonWithHeaders((data, headers)) = res {
serialized_response.replace(
masking::masked_serialize(&data)
.attach_printable("Failed to serialize json response")
.change_context(errors::ApiErrorResponse::InternalServerError.switch())?,
);
if let Some((_, value)) = headers.iter().find(|(key, _)| key == X_HS_LATENCY) {
if let Ok(external_latency) = value.clone().into_inner().parse::<u128>() {
overhead_latency.replace(external_latency);
}
}
}
event_type = res.get_api_event_type().or(event_type);
metrics::request::track_response_status_code(res)
}
Err(err) => {
error.replace(
serde_json::to_value(err.current_context())
.attach_printable("Failed to serialize json response")
.change_context(errors::ApiErrorResponse::InternalServerError.switch())
.ok()
.into(),
);
err.current_context().status_code().as_u16().into()
}
};
let infra = extract_mapped_fields(
&serialized_request,
state.enhancement.as_ref(),
state.infra_components.as_ref(),
);
let api_event = ApiEvent::new(
tenant_id,
Some(merchant_id.clone()),
flow,
&request_id,
request_duration,
status_code,
serialized_request,
serialized_response,
overhead_latency,
auth_type,
error,
event_type.unwrap_or(ApiEventsType::Miscellaneous),
request,
request.method(),
infra.clone(),
);
state.event_handler().log_event(&api_event);
output
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 260,
"total_crates": null
} |
fn_clm_router_build_payment_link_template_-1596591786337376396 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/api
fn build_payment_link_template(
payment_link_data: PaymentLinkFormData,
) -> CustomResult<(Tera, Context), errors::ApiErrorResponse> {
let mut tera = Tera::default();
// Add modification to css template with dynamic data
let css_template =
include_str!("../core/payment_link/payment_link_initiate/payment_link.css").to_string();
let _ = tera.add_raw_template("payment_link_css", &css_template);
let mut context = Context::new();
context.insert("css_color_scheme", &payment_link_data.css_script);
let rendered_css = match tera.render("payment_link_css", &context) {
Ok(rendered_css) => rendered_css,
Err(tera_error) => {
crate::logger::warn!("{tera_error}");
Err(errors::ApiErrorResponse::InternalServerError)?
}
};
// Add modification to js template with dynamic data
let js_template =
include_str!("../core/payment_link/payment_link_initiate/payment_link.js").to_string();
let _ = tera.add_raw_template("payment_link_js", &js_template);
context.insert("payment_details_js_script", &payment_link_data.js_script);
let sdk_origin = payment_link_data
.sdk_url
.host_str()
.ok_or_else(|| {
logger::error!("Host missing for payment link SDK URL");
report!(errors::ApiErrorResponse::InternalServerError)
})
.and_then(|host| {
if host == "localhost" {
let port = payment_link_data.sdk_url.port().ok_or_else(|| {
logger::error!("Port missing for localhost in SDK URL");
report!(errors::ApiErrorResponse::InternalServerError)
})?;
Ok(format!(
"{}://{}:{}",
payment_link_data.sdk_url.scheme(),
host,
port
))
} else {
Ok(format!("{}://{}", payment_link_data.sdk_url.scheme(), host))
}
})?;
context.insert("sdk_origin", &sdk_origin);
let rendered_js = match tera.render("payment_link_js", &context) {
Ok(rendered_js) => rendered_js,
Err(tera_error) => {
crate::logger::warn!("{tera_error}");
Err(errors::ApiErrorResponse::InternalServerError)?
}
};
// Logging template
let logging_template =
include_str!("redirection/assets/redirect_error_logs_push.js").to_string();
//Locale template
let locale_template = include_str!("../core/payment_link/locale.js").to_string();
// Modify Html template with rendered js and rendered css files
let html_template =
include_str!("../core/payment_link/payment_link_initiate/payment_link.html").to_string();
let _ = tera.add_raw_template("payment_link", &html_template);
context.insert("rendered_meta_tag_html", &payment_link_data.html_meta_tags);
context.insert(
"preload_link_tags",
&get_preload_link_html_template(&payment_link_data.sdk_url),
);
context.insert(
"hyperloader_sdk_link",
&get_hyper_loader_sdk(&payment_link_data.sdk_url),
);
context.insert("locale_template", &locale_template);
context.insert("rendered_css", &rendered_css);
context.insert("rendered_js", &rendered_js);
context.insert("logging_template", &logging_template);
Ok((tera, context))
}
| {
"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
} |
fn_clm_router_http_response_err_-1596591786337376396 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/api
pub fn http_response_err<T: body::MessageBody + 'static>(response: T) -> HttpResponse {
HttpResponse::BadRequest()
.content_type(mime::APPLICATION_JSON)
.body(response)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 58,
"total_crates": null
} |
fn_clm_router_get_redis_connection_for_global_tenant_-3606878052487424315 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/authorization
fn get_redis_connection_for_global_tenant<A: SessionStateInfo>(
state: &A,
) -> RouterResult<Arc<RedisConnectionPool>> {
state
.global_store()
.get_redis_conn()
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 92,
"total_crates": null
} |
fn_clm_router_get_role_info_from_db_-3606878052487424315 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/authorization
async fn get_role_info_from_db<A>(
state: &A,
role_id: &str,
org_id: &id_type::OrganizationId,
tenant_id: &id_type::TenantId,
) -> RouterResult<roles::RoleInfo>
where
A: SessionStateInfo + Sync,
{
state
.session_state()
.global_store
.find_by_role_id_org_id_tenant_id(role_id, org_id, tenant_id)
.await
.map(roles::RoleInfo::from)
.to_not_found_response(ApiErrorResponse::InvalidJwtToken)
}
| {
"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_get_role_info_-3606878052487424315 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/authorization
pub async fn get_role_info<A>(state: &A, token: &AuthToken) -> RouterResult<roles::RoleInfo>
where
A: SessionStateInfo + Sync,
{
if let Some(role_info) = roles::predefined_roles::PREDEFINED_ROLES.get(token.role_id.as_str()) {
return Ok(role_info.clone());
}
if let Ok(role_info) = get_role_info_from_cache(state, &token.role_id)
.await
.map_err(|e| logger::error!("Failed to get permissions from cache {e:?}"))
{
return Ok(role_info.clone());
}
let role_info = get_role_info_from_db(
state,
&token.role_id,
&token.org_id,
token
.tenant_id
.as_ref()
.unwrap_or(&state.session_state().tenant.tenant_id),
)
.await?;
let token_expiry =
i64::try_from(token.exp).change_context(ApiErrorResponse::InternalServerError)?;
let cache_ttl = token_expiry - common_utils::date_time::now_unix_timestamp();
if cache_ttl > 0 {
set_role_info_in_cache(state, &token.role_id, &role_info, cache_ttl)
.await
.map_err(|e| logger::error!("Failed to set role info in cache {e:?}"))
.ok();
}
Ok(role_info)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 45,
"total_crates": null
} |
fn_clm_router_set_role_info_in_cache_-3606878052487424315 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/services/authorization
pub async fn set_role_info_in_cache<A>(
state: &A,
role_id: &str,
role_info: &roles::RoleInfo,
expiry: i64,
) -> RouterResult<()>
where
A: SessionStateInfo + Sync,
{
let redis_conn = get_redis_connection_for_global_tenant(state)?;
redis_conn
.serialize_and_set_key_with_expiry(
&get_cache_key_from_role_id(role_id).into(),
role_info,
expiry,
)
.await
.change_context(ApiErrorResponse::InternalServerError)
}
| {
"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
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.