id stringlengths 11 116 | type stringclasses 1 value | granularity stringclasses 4 values | content stringlengths 16 477k | metadata dict |
|---|---|---|---|---|
fn_clm_router_get_pre_authentication_request_data_-8397267065422295570 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/unified_authentication_service/types
fn get_pre_authentication_request_data(
_payment_method_data: Option<&domain::PaymentMethodData>,
_service_details: Option<payments::CtpServiceDetails>,
_amount: common_utils::types::MinorUnit,
_currency: Option<common_enums::Currency>,
_merchant_details: Option<&hyperswitch_domain_models::router_request_types::unified_authentication_service::MerchantDetails>,
_billing_address: Option<&hyperswitch_domain_models::address::Address>,
_acquirer_bin: Option<String>,
_acquirer_merchant_id: Option<String>,
_payment_method_type: Option<common_enums::PaymentMethodType>,
) -> RouterResult<UasPreAuthenticationRequestData> {
Err(errors::ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason(
"get_pre_authentication_request_data".to_string(),
),
}
.into())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 9,
"total_crates": null
} |
fn_clm_router_get_authentication_request_data_-8397267065422295570 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/unified_authentication_service/types
fn get_authentication_request_data(
_browser_details: Option<BrowserInformation>,
_amount: Option<common_utils::types::MinorUnit>,
_currency: Option<common_enums::Currency>,
_message_category: MessageCategory,
_device_channel: payments::DeviceChannel,
_authentication: diesel_models::authentication::Authentication,
_return_url: Option<String>,
_sdk_information: Option<payments::SdkInformation>,
_threeds_method_comp_ind: payments::ThreeDsCompletionIndicator,
_email: Option<common_utils::pii::Email>,
_webhook_url: String,
) -> RouterResult<UasAuthenticationRequestData> {
Err(errors::ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason(
"get_pre_authentication_request_data".to_string(),
),
}
.into())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 9,
"total_crates": null
} |
fn_clm_router_authentication_-8397267065422295570 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/unified_authentication_service/types
async fn authentication(
_state: &SessionState,
_business_profile: &domain::Profile,
_payment_method: &common_enums::PaymentMethod,
_browser_details: Option<BrowserInformation>,
_amount: Option<common_utils::types::MinorUnit>,
_currency: Option<common_enums::Currency>,
_message_category: MessageCategory,
_device_channel: payments::DeviceChannel,
_authentication_data: diesel_models::authentication::Authentication,
_return_url: Option<String>,
_sdk_information: Option<payments::SdkInformation>,
_threeds_method_comp_ind: payments::ThreeDsCompletionIndicator,
_email: Option<common_utils::pii::Email>,
_webhook_url: String,
_merchant_connector_account: &MerchantConnectorAccountType,
_connector_name: &str,
_payment_id: Option<common_utils::id_type::PaymentId>,
) -> RouterResult<hyperswitch_domain_models::types::UasAuthenticationRouterData> {
Err(errors::ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason("authentication".to_string()),
}
.into())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 9,
"total_crates": null
} |
fn_clm_router_external_authentication_update_trackers_-3055722393480730623 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/unified_authentication_service/utils
pub async fn external_authentication_update_trackers<F: Clone, Req>(
state: &SessionState,
router_data: RouterData<F, Req, UasAuthenticationResponseData>,
authentication: diesel_models::authentication::Authentication,
acquirer_details: Option<
hyperswitch_domain_models::router_request_types::authentication::AcquirerDetails,
>,
merchant_key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
billing_address: Option<common_utils::encryption::Encryption>,
shipping_address: Option<common_utils::encryption::Encryption>,
email: Option<common_utils::encryption::Encryption>,
browser_info: Option<serde_json::Value>,
) -> RouterResult<diesel_models::authentication::Authentication> {
let authentication_update = match router_data.response {
Ok(response) => match response {
UasAuthenticationResponseData::PreAuthentication {
authentication_details,
} => Ok(
diesel_models::authentication::AuthenticationUpdate::PreAuthenticationUpdate {
threeds_server_transaction_id: authentication_details
.threeds_server_transaction_id
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable(
"missing threeds_server_transaction_id in PreAuthentication Details",
)?,
maximum_supported_3ds_version: authentication_details
.maximum_supported_3ds_version
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable(
"missing maximum_supported_3ds_version in PreAuthentication Details",
)?,
connector_authentication_id: authentication_details
.connector_authentication_id
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable(
"missing connector_authentication_id in PreAuthentication Details",
)?,
three_ds_method_data: authentication_details.three_ds_method_data,
three_ds_method_url: authentication_details.three_ds_method_url,
message_version: authentication_details
.message_version
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("missing message_version in PreAuthentication Details")?,
connector_metadata: authentication_details.connector_metadata,
authentication_status: common_enums::AuthenticationStatus::Pending,
acquirer_bin: acquirer_details
.as_ref()
.map(|acquirer_details| acquirer_details.acquirer_bin.clone()),
acquirer_merchant_id: acquirer_details
.as_ref()
.map(|acquirer_details| acquirer_details.acquirer_merchant_id.clone()),
acquirer_country_code: acquirer_details
.and_then(|acquirer_details| acquirer_details.acquirer_country_code),
directory_server_id: authentication_details.directory_server_id,
browser_info: Box::new(browser_info),
email,
billing_address,
shipping_address,
},
),
UasAuthenticationResponseData::Authentication {
authentication_details,
} => {
let authentication_status = common_enums::AuthenticationStatus::foreign_from(
authentication_details.trans_status.clone(),
);
authentication_details
.authentication_value
.async_map(|auth_val| {
crate::core::payment_methods::vault::create_tokenize(
state,
auth_val.expose(),
None,
authentication
.authentication_id
.get_string_repr()
.to_string(),
merchant_key_store.key.get_inner(),
)
})
.await
.transpose()?;
Ok(
diesel_models::authentication::AuthenticationUpdate::AuthenticationUpdate {
trans_status: authentication_details.trans_status,
acs_url: authentication_details.authn_flow_type.get_acs_url(),
challenge_request: authentication_details
.authn_flow_type
.get_challenge_request(),
challenge_request_key: authentication_details
.authn_flow_type
.get_challenge_request_key(),
acs_reference_number: authentication_details
.authn_flow_type
.get_acs_reference_number(),
acs_trans_id: authentication_details.authn_flow_type.get_acs_trans_id(),
acs_signed_content: authentication_details
.authn_flow_type
.get_acs_signed_content(),
authentication_type: authentication_details
.authn_flow_type
.get_decoupled_authentication_type(),
authentication_status,
connector_metadata: authentication_details.connector_metadata,
ds_trans_id: authentication_details.ds_trans_id,
eci: authentication_details.eci,
challenge_code: authentication_details.challenge_code,
challenge_cancel: authentication_details.challenge_cancel,
challenge_code_reason: authentication_details.challenge_code_reason,
message_extension: authentication_details.message_extension,
},
)
}
UasAuthenticationResponseData::PostAuthentication {
authentication_details,
} => {
let trans_status = authentication_details
.trans_status
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("missing trans_status in PostAuthentication Details")?;
authentication_details
.dynamic_data_details
.and_then(|details| details.dynamic_data_value)
.map(ExposeInterface::expose)
.async_map(|auth_val| {
crate::core::payment_methods::vault::create_tokenize(
state,
auth_val,
None,
authentication
.authentication_id
.get_string_repr()
.to_string(),
merchant_key_store.key.get_inner(),
)
})
.await
.transpose()?;
Ok(
diesel_models::authentication::AuthenticationUpdate::PostAuthenticationUpdate {
authentication_status: common_enums::AuthenticationStatus::foreign_from(
trans_status.clone(),
),
trans_status,
eci: authentication_details.eci,
challenge_cancel: authentication_details.challenge_cancel,
challenge_code_reason: authentication_details.challenge_code_reason,
},
)
}
UasAuthenticationResponseData::Confirmation { .. } => Err(
ApiErrorResponse::InternalServerError,
)
.attach_printable("unexpected api confirmation in external authentication flow."),
},
Err(error) => Ok(
diesel_models::authentication::AuthenticationUpdate::ErrorUpdate {
connector_authentication_id: error.connector_transaction_id,
authentication_status: common_enums::AuthenticationStatus::Failed,
error_message: error
.reason
.map(|reason| format!("message: {}, reason: {}", error.message, reason))
.or(Some(error.message)),
error_code: Some(error.code),
},
),
}?;
state
.store
.update_authentication_by_merchant_id_authentication_id(
authentication,
authentication_update,
)
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Error while updating authentication")
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 128,
"total_crates": null
} |
fn_clm_router_construct_uas_router_data_-3055722393480730623 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/unified_authentication_service/utils
pub fn construct_uas_router_data<F: Clone, Req, Res>(
state: &SessionState,
authentication_connector_name: String,
payment_method: PaymentMethod,
merchant_id: common_utils::id_type::MerchantId,
address: Option<PaymentAddress>,
request_data: Req,
merchant_connector_account: &payments::helpers::MerchantConnectorAccountType,
authentication_id: Option<common_utils::id_type::AuthenticationId>,
payment_id: Option<common_utils::id_type::PaymentId>,
) -> RouterResult<RouterData<F, Req, Res>> {
let auth_type: ConnectorAuthType = merchant_connector_account
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Error while parsing ConnectorAuthType")?;
Ok(RouterData {
flow: PhantomData,
merchant_id,
customer_id: None,
connector_customer: None,
connector: authentication_connector_name,
payment_id: payment_id
.map(|id| id.get_string_repr().to_owned())
.unwrap_or_default(),
tenant_id: state.tenant.tenant_id.clone(),
attempt_id: IRRELEVANT_ATTEMPT_ID_IN_AUTHENTICATION_FLOW.to_owned(),
status: common_enums::AttemptStatus::default(),
payment_method,
payment_method_type: None,
connector_auth_type: auth_type,
description: None,
address: address.unwrap_or_default(),
auth_type: common_enums::AuthenticationType::default(),
connector_meta_data: merchant_connector_account.get_metadata().clone(),
connector_wallets_details: merchant_connector_account.get_connector_wallets_details(),
amount_captured: None,
minor_amount_captured: None,
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
recurring_mandate_payment_data: None,
preprocessing_id: None,
payment_method_balance: None,
connector_api_version: None,
request: request_data,
response: Err(ErrorResponse::default()),
connector_request_reference_id:
IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_AUTHENTICATION_FLOW.to_owned(),
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
test_mode: None,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
dispute_id: None,
refund_id: None,
payment_method_status: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload: None,
connector_mandate_request_reference_id: None,
authentication_id,
psd2_sca_exemption_type: None,
raw_connector_response: None,
is_payment_id_from_merchant: None,
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
})
}
| {
"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_do_auth_connector_call_-3055722393480730623 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/unified_authentication_service/utils
pub async fn do_auth_connector_call<F, Req, Res>(
state: &SessionState,
authentication_connector_name: String,
router_data: RouterData<F, Req, Res>,
) -> RouterResult<RouterData<F, Req, Res>>
where
Req: std::fmt::Debug + Clone + 'static,
Res: std::fmt::Debug + Clone + 'static,
F: std::fmt::Debug + Clone + 'static,
dyn api::Connector + Sync: services::api::ConnectorIntegration<F, Req, Res>,
dyn api::ConnectorV2 + Sync: services::api::ConnectorIntegrationV2<F, UasFlowData, Req, Res>,
{
let connector_data =
api::AuthenticationConnectorData::get_connector_by_name(&authentication_connector_name)?;
let connector_integration: services::BoxedUnifiedAuthenticationServiceInterface<F, Req, Res> =
connector_data.connector.get_connector_integration();
let router_data = execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payment_failed_response()?;
Ok(router_data)
}
| {
"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_authenticate_authentication_client_secret_and_check_expiry_-3055722393480730623 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/unified_authentication_service/utils
pub fn authenticate_authentication_client_secret_and_check_expiry(
req_client_secret: &String,
authentication: &diesel_models::authentication::Authentication,
) -> RouterResult<()> {
let stored_client_secret = authentication
.authentication_client_secret
.clone()
.get_required_value("authentication_client_secret")
.change_context(ApiErrorResponse::MissingRequiredField {
field_name: "client_secret",
})
.attach_printable("client secret not found in db")?;
if req_client_secret != &stored_client_secret {
Err(report!(ApiErrorResponse::ClientSecretInvalid))
} else {
let current_timestamp = common_utils::date_time::now();
let session_expiry = authentication
.created_at
.saturating_add(time::Duration::seconds(DEFAULT_SESSION_EXPIRY));
if current_timestamp > session_expiry {
Err(report!(ApiErrorResponse::ClientSecretExpired))
} else {
Ok(())
}
}
}
| {
"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_checkout_event_status_and_reason_-3055722393480730623 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/unified_authentication_service/utils
pub fn get_checkout_event_status_and_reason(
attempt_status: common_enums::AttemptStatus,
) -> (Option<String>, Option<String>) {
match attempt_status {
common_enums::AttemptStatus::Charged | common_enums::AttemptStatus::Authorized => (
Some("01".to_string()),
Some("The payment was successful".to_string()),
),
_ => (
Some("03".to_string()),
Some("The payment was not successful".to_string()),
),
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 21,
"total_crates": null
} |
fn_clm_router_foreign_try_from_-2061703342061414921 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/unified_connector_service/transformers
// Implementation of payments_grpc::RequestDetails for transformers::ForeignTryFrom<
&hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,
>
fn foreign_try_from(
request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,
) -> Result<Self, Self::Error> {
let headers_map = request_details
.headers
.iter()
.map(|(key, value)| {
let value_string = value.to_str().unwrap_or_default().to_string();
(key.as_str().to_string(), value_string)
})
.collect();
Ok(Self {
method: 1, // POST method for webhooks
uri: Some({
let uri_result = request_details
.headers
.get("x-forwarded-path")
.and_then(|h| h.to_str().map_err(|e| {
tracing::warn!(
header_conversion_error=?e,
header_value=?h,
"Failed to convert x-forwarded-path header to string for webhook processing"
);
e
}).ok());
uri_result.unwrap_or_else(|| {
tracing::debug!("x-forwarded-path header not found or invalid, using default '/Unknown'");
"/Unknown"
}).to_string()
}),
body: request_details.body.to_vec(),
headers: headers_map,
query_params: Some(request_details.query_params.clone()),
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 462,
"total_crates": null
} |
fn_clm_router_build_webhook_transform_request_-2061703342061414921 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/unified_connector_service/transformers
/// Build UCS webhook transform request from webhook components
pub fn build_webhook_transform_request(
_webhook_body: &[u8],
request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,
webhook_secrets: Option<payments_grpc::WebhookSecrets>,
merchant_id: &str,
connector_id: &str,
) -> Result<PaymentServiceTransformRequest, error_stack::Report<errors::ApiErrorResponse>> {
let request_details_grpc =
<payments_grpc::RequestDetails as transformers::ForeignTryFrom<_>>::foreign_try_from(
request_details,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to transform webhook request details to gRPC format")?;
Ok(PaymentServiceTransformRequest {
request_ref_id: Some(Identifier {
id_type: Some(payments_grpc::identifier::IdType::Id(format!(
"{}_{}_{}",
merchant_id,
connector_id,
time::OffsetDateTime::now_utc().unix_timestamp()
))),
}),
request_details: Some(request_details_grpc),
webhook_secrets,
access_token: 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_transform_ucs_webhook_response_-2061703342061414921 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/unified_connector_service/transformers
/// Transform UCS webhook response into webhook event data
pub fn transform_ucs_webhook_response(
response: PaymentServiceTransformResponse,
) -> Result<WebhookTransformData, error_stack::Report<errors::ApiErrorResponse>> {
let event_type =
api_models::webhooks::IncomingWebhookEvent::from_ucs_event_type(response.event_type);
Ok(WebhookTransformData {
event_type,
source_verified: response.source_verified,
webhook_content: response.content,
response_ref_id: response.response_ref_id.and_then(|identifier| {
identifier.id_type.and_then(|id_type| match id_type {
payments_grpc::identifier::IdType::Id(id) => Some(id),
payments_grpc::identifier::IdType::EncodedData(encoded_data) => Some(encoded_data),
payments_grpc::identifier::IdType::NoResponseIdMarker(_) => None,
})
}),
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 19,
"total_crates": null
} |
fn_clm_router_check_existence_and_add_domain_to_db_8353358495600920008 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/verification/utils
pub async fn check_existence_and_add_domain_to_db(
state: &SessionState,
merchant_id: common_utils::id_type::MerchantId,
profile_id_from_auth_layer: Option<common_utils::id_type::ProfileId>,
merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId,
domain_from_req: Vec<String>,
) -> CustomResult<Vec<String>, errors::ApiErrorResponse> {
let key_manager_state = &state.into();
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;
#[cfg(feature = "v1")]
let merchant_connector_account = state
.store
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
&merchant_id,
&merchant_connector_id,
&key_store,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
#[cfg(feature = "v2")]
let merchant_connector_account = state
.store
.find_merchant_connector_account_by_id(
key_manager_state,
&merchant_connector_id,
&key_store,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
utils::validate_profile_id_from_auth_layer(
profile_id_from_auth_layer,
&merchant_connector_account,
)?;
let mut already_verified_domains = merchant_connector_account
.applepay_verified_domains
.clone()
.unwrap_or_default();
let mut new_verified_domains: Vec<String> = domain_from_req
.into_iter()
.filter(|req_domain| !already_verified_domains.contains(req_domain))
.collect();
already_verified_domains.append(&mut new_verified_domains);
#[cfg(feature = "v1")]
let updated_mca = storage::MerchantConnectorAccountUpdate::Update {
connector_type: None,
connector_name: None,
connector_account_details: Box::new(None),
test_mode: None,
disabled: None,
merchant_connector_id: None,
payment_methods_enabled: None,
metadata: None,
frm_configs: None,
connector_webhook_details: Box::new(None),
applepay_verified_domains: Some(already_verified_domains.clone()),
pm_auth_config: Box::new(None),
connector_label: None,
status: None,
connector_wallets_details: Box::new(None),
additional_merchant_data: Box::new(None),
};
#[cfg(feature = "v2")]
let updated_mca = storage::MerchantConnectorAccountUpdate::Update {
connector_type: None,
connector_account_details: Box::new(None),
disabled: None,
payment_methods_enabled: None,
metadata: None,
frm_configs: None,
connector_webhook_details: Box::new(None),
applepay_verified_domains: Some(already_verified_domains.clone()),
pm_auth_config: Box::new(None),
connector_label: None,
status: None,
connector_wallets_details: Box::new(None),
additional_merchant_data: Box::new(None),
feature_metadata: Box::new(None),
};
state
.store
.update_merchant_connector_account(
key_manager_state,
merchant_connector_account,
updated_mca.into(),
&key_store,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed while updating MerchantConnectorAccount: id: {merchant_connector_id:?}",
)
})?;
Ok(already_verified_domains.clone())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 85,
"total_crates": null
} |
fn_clm_router_check_if_profile_id_is_present_in_payment_intent_8353358495600920008 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/verification/utils
pub async fn check_if_profile_id_is_present_in_payment_intent(
payment_id: PaymentId,
state: &SessionState,
auth_data: &AuthenticationData,
) -> CustomResult<(), errors::ApiErrorResponse> {
let db = &*state.store;
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
&state.into(),
&payment_id,
auth_data.merchant_account.get_id(),
&auth_data.key_store,
auth_data.merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)?;
utils::validate_profile_id_from_auth_layer(auth_data.profile_id.clone(), &payment_intent)
}
| {
"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_log_applepay_verification_response_if_error_8353358495600920008 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/verification/utils
pub fn log_applepay_verification_response_if_error(
response: &Result<Result<types::Response, types::Response>, Report<errors::ApiClientError>>,
) {
if let Err(error) = response.as_ref() {
logger::error!(applepay_domain_verification_error= ?error);
};
response.as_ref().ok().map(|res| {
res.as_ref()
.map_err(|error| logger::error!(applepay_domain_verification_error= ?error))
});
}
| {
"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_execute_payment_8256400709692590680 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/revenue_recovery/types
// Implementation of None for Action
pub async fn execute_payment(
state: &SessionState,
_merchant_id: &id_type::MerchantId,
payment_intent: &PaymentIntent,
process: &storage::ProcessTracker,
profile: &domain::Profile,
merchant_context: domain::MerchantContext,
revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,
revenue_recovery_metadata: &PaymentRevenueRecoveryMetadata,
latest_attempt_id: &id_type::GlobalAttemptId,
) -> RecoveryResult<Self> {
let connector_customer_id = payment_intent
.extract_connector_customer_id_from_payment_intent()
.change_context(errors::RecoveryError::ValueNotFound)
.attach_printable("Failed to extract customer ID from payment intent")?;
let tracking_data: pcr::RevenueRecoveryWorkflowTrackingData =
serde_json::from_value(process.tracking_data.clone())
.change_context(errors::RecoveryError::ValueNotFound)
.attach_printable("Failed to deserialize the tracking data from process tracker")?;
let last_token_used = payment_intent
.feature_metadata
.as_ref()
.and_then(|fm| fm.payment_revenue_recovery_metadata.as_ref())
.map(|rr| {
rr.billing_connector_payment_details
.payment_processor_token
.clone()
});
let recovery_algorithm = tracking_data.revenue_recovery_retry;
let scheduled_token = match storage::revenue_recovery_redis_operation::RedisTokenManager::get_token_based_on_retry_type(
state,
&connector_customer_id,
recovery_algorithm,
last_token_used.as_deref(),
)
.await {
Ok(scheduled_token_opt) => scheduled_token_opt,
Err(e) => {
logger::error!(
error = ?e,
connector_customer_id = %connector_customer_id,
"Failed to get PSP token status"
);
None
}
};
match scheduled_token {
Some(scheduled_token) => {
let response = revenue_recovery_core::api::call_proxy_api(
state,
payment_intent,
revenue_recovery_payment_data,
revenue_recovery_metadata,
&scheduled_token
.payment_processor_token_details
.payment_processor_token,
)
.await;
let recovery_payment_intent =
hyperswitch_domain_models::revenue_recovery::RecoveryPaymentIntent::from(
payment_intent,
);
// handle proxy api's response
match response {
Ok(payment_data) => match payment_data.payment_attempt.status.foreign_into() {
RevenueRecoveryPaymentsAttemptStatus::Succeeded => {
let recovery_payment_attempt =
hyperswitch_domain_models::revenue_recovery::RecoveryPaymentAttempt::from(
&payment_data.payment_attempt,
);
let recovery_payment_tuple =
recovery_incoming_flow::RecoveryPaymentTuple::new(
&recovery_payment_intent,
&recovery_payment_attempt,
);
// publish events to kafka
if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka(
state,
&recovery_payment_tuple,
Some(process.retry_count+1)
)
.await{
router_env::logger::error!(
"Failed to publish revenue recovery event to kafka: {:?}",
e
);
};
let is_hard_decline = revenue_recovery::check_hard_decline(
state,
&payment_data.payment_attempt,
)
.await
.ok();
// update the status of token in redis
let _update_error_code = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker(
state,
&connector_customer_id,
&None,
&is_hard_decline,
Some(&scheduled_token.payment_processor_token_details.payment_processor_token),
)
.await;
// unlocking the token
let _unlock_the_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(
state,
&connector_customer_id,
)
.await;
let event_status = common_enums::EventType::PaymentSucceeded;
let payments_response = payment_data
.clone()
.generate_response(
state,
None,
None,
None,
&merchant_context,
profile,
None,
)
.change_context(
errors::RecoveryError::PaymentsResponseGenerationFailed,
)
.attach_printable("Failed while generating response for payment")?;
RevenueRecoveryOutgoingWebhook::send_outgoing_webhook_based_on_revenue_recovery_status(
state,
common_enums::EventClass::Payments,
event_status,
payment_intent,
&merchant_context,
profile,
payment_data.payment_attempt.id.get_string_repr().to_string(),
payments_response
)
.await?;
Ok(Self::SuccessfulPayment(
payment_data.payment_attempt.clone(),
))
}
RevenueRecoveryPaymentsAttemptStatus::Failed => {
let recovery_payment_attempt =
hyperswitch_domain_models::revenue_recovery::RecoveryPaymentAttempt::from(
&payment_data.payment_attempt,
);
let recovery_payment_tuple =
recovery_incoming_flow::RecoveryPaymentTuple::new(
&recovery_payment_intent,
&recovery_payment_attempt,
);
// publish events to kafka
if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka(
state,
&recovery_payment_tuple,
Some(process.retry_count+1)
)
.await{
router_env::logger::error!(
"Failed to publish revenue recovery event to kafka: {:?}",
e
);
};
let error_code = payment_data
.payment_attempt
.clone()
.error
.map(|error| error.code);
let is_hard_decline = revenue_recovery::check_hard_decline(
state,
&payment_data.payment_attempt,
)
.await
.ok();
let _update_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker(
state,
&connector_customer_id,
&error_code,
&is_hard_decline,
Some(&scheduled_token
.payment_processor_token_details
.payment_processor_token)
,
)
.await;
// unlocking the token
let _unlock_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(
state,
&connector_customer_id,
)
.await;
// Reopen calculate workflow on payment failure
Box::pin(reopen_calculate_workflow_on_payment_failure(
state,
process,
profile,
merchant_context,
payment_intent,
revenue_recovery_payment_data,
latest_attempt_id,
))
.await?;
// Return terminal failure to finish the current execute workflow
Ok(Self::TerminalFailure(payment_data.payment_attempt.clone()))
}
RevenueRecoveryPaymentsAttemptStatus::Processing => {
Ok(Self::SyncPayment(payment_data.payment_attempt.clone()))
}
RevenueRecoveryPaymentsAttemptStatus::InvalidStatus(action) => {
logger::info!(?action, "Invalid Payment Status For PCR Payment");
Ok(Self::ManualReviewAction)
}
},
Err(err) =>
// check for an active attempt being constructed or not
{
logger::error!(execute_payment_res=?err);
Ok(Self::ReviewPayment)
}
}
}
None => {
let response = revenue_recovery_core::api::call_psync_api(
state,
payment_intent.get_id(),
revenue_recovery_payment_data,
true,
true,
)
.await;
let payment_status_data = response
.change_context(errors::RecoveryError::PaymentCallFailed)
.attach_printable("Error while executing the Psync call")?;
let payment_attempt = payment_status_data.payment_attempt;
logger::info!(
process_id = %process.id,
connector_customer_id = %connector_customer_id,
"No token available, finishing CALCULATE_WORKFLOW"
);
state
.store
.as_scheduler()
.finish_process_with_business_status(
process.clone(),
business_status::CALCULATE_WORKFLOW_FINISH,
)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to finish CALCULATE_WORKFLOW")?;
logger::info!(
process_id = %process.id,
connector_customer_id = %connector_customer_id,
"CALCULATE_WORKFLOW finished successfully"
);
Ok(Self::TerminalFailure(payment_attempt.clone()))
}
}
}
| {
"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_execute_payment_task_response_handler_8256400709692590680 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/revenue_recovery/types
// Implementation of None for Action
pub async fn execute_payment_task_response_handler(
&self,
state: &SessionState,
payment_intent: &PaymentIntent,
execute_task_process: &storage::ProcessTracker,
revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,
revenue_recovery_metadata: &mut PaymentRevenueRecoveryMetadata,
) -> Result<(), errors::ProcessTrackerError> {
logger::info!("Entering execute_payment_task_response_handler");
let db = &*state.store;
match self {
Self::SyncPayment(payment_attempt) => {
revenue_recovery_core::insert_psync_pcr_task_to_pt(
revenue_recovery_payment_data.billing_mca.get_id().clone(),
db,
revenue_recovery_payment_data
.merchant_account
.get_id()
.to_owned(),
payment_intent.id.clone(),
revenue_recovery_payment_data.profile.get_id().to_owned(),
payment_attempt.id.clone(),
storage::ProcessTrackerRunner::PassiveRecoveryWorkflow,
revenue_recovery_payment_data.retry_algorithm,
)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to create a psync workflow in the process tracker")?;
db.as_scheduler()
.finish_process_with_business_status(
execute_task_process.clone(),
business_status::EXECUTE_WORKFLOW_COMPLETE_FOR_PSYNC,
)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to update the process tracker")?;
Ok(())
}
Self::RetryPayment(schedule_time) => {
db.as_scheduler()
.retry_process(execute_task_process.clone(), *schedule_time)
.await?;
// update the connector payment transmission field to Unsuccessful and unset active attempt id
revenue_recovery_metadata.set_payment_transmission_field_for_api_request(
enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful,
);
let payment_update_req =
PaymentsUpdateIntentRequest::update_feature_metadata_and_active_attempt_with_api(
payment_intent
.feature_metadata
.clone()
.unwrap_or_default()
.convert_back()
.set_payment_revenue_recovery_metadata_using_api(
revenue_recovery_metadata.clone(),
),
api_enums::UpdateActiveAttempt::Unset,
);
logger::info!(
"Call made to payments update intent api , with the request body {:?}",
payment_update_req
);
revenue_recovery_core::api::update_payment_intent_api(
state,
payment_intent.id.clone(),
revenue_recovery_payment_data,
payment_update_req,
)
.await
.change_context(errors::RecoveryError::PaymentCallFailed)?;
Ok(())
}
Self::TerminalFailure(payment_attempt) => {
db.as_scheduler()
.finish_process_with_business_status(
execute_task_process.clone(),
business_status::EXECUTE_WORKFLOW_FAILURE,
)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to update the process tracker")?;
// TODO: Add support for retrying failed outgoing recordback webhooks
Ok(())
}
Self::SuccessfulPayment(payment_attempt) => {
db.as_scheduler()
.finish_process_with_business_status(
execute_task_process.clone(),
business_status::EXECUTE_WORKFLOW_COMPLETE,
)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to update the process tracker")?;
// Record back to billing connector for terminal status
// TODO: Add support for retrying failed outgoing recordback webhooks
record_back_to_billing_connector(
state,
payment_attempt,
payment_intent,
&revenue_recovery_payment_data.billing_mca,
)
.await
.change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed)
.attach_printable("Failed to update the process tracker")?;
Ok(())
}
Self::ReviewPayment => {
// requeue the process tracker in case of error response
let pt_update = storage::ProcessTrackerUpdate::StatusUpdate {
status: enums::ProcessTrackerStatus::Pending,
business_status: Some(String::from(business_status::EXECUTE_WORKFLOW_REQUEUE)),
};
db.as_scheduler()
.update_process(execute_task_process.clone(), pt_update)
.await?;
Ok(())
}
Self::ManualReviewAction => {
logger::debug!("Invalid Payment Status For PCR Payment");
let pt_update = storage::ProcessTrackerUpdate::StatusUpdate {
status: enums::ProcessTrackerStatus::Review,
business_status: Some(String::from(business_status::EXECUTE_WORKFLOW_COMPLETE)),
};
// update the process tracker status as Review
db.as_scheduler()
.update_process(execute_task_process.clone(), pt_update)
.await?;
Ok(())
}
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 121,
"total_crates": null
} |
fn_clm_router_psync_response_handler_8256400709692590680 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/revenue_recovery/types
// Implementation of None for Action
pub async fn psync_response_handler(
&self,
state: &SessionState,
payment_intent: &PaymentIntent,
psync_task_process: &storage::ProcessTracker,
revenue_recovery_metadata: &mut PaymentRevenueRecoveryMetadata,
revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,
) -> Result<(), errors::ProcessTrackerError> {
logger::info!("Entering psync_response_handler");
let db = &*state.store;
let connector_customer_id = payment_intent
.feature_metadata
.as_ref()
.and_then(|fm| fm.payment_revenue_recovery_metadata.as_ref())
.map(|rr| {
rr.billing_connector_payment_details
.connector_customer_id
.clone()
});
match self {
Self::SyncPayment(payment_attempt) => {
// get a schedule time for psync
// and retry the process if there is a schedule time
// if None mark the pt status as Retries Exceeded and finish the task
payment_sync::recovery_retry_sync_task(
state,
connector_customer_id,
revenue_recovery_metadata.connector.to_string(),
revenue_recovery_payment_data
.merchant_account
.get_id()
.clone(),
psync_task_process.clone(),
)
.await?;
Ok(())
}
Self::RetryPayment(schedule_time) => {
// finish the psync task
db.as_scheduler()
.finish_process_with_business_status(
psync_task_process.clone(),
business_status::PSYNC_WORKFLOW_COMPLETE,
)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to update the process tracker")?;
// fetch the execute task
let task = revenue_recovery_core::EXECUTE_WORKFLOW;
let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow;
let process_tracker_id = payment_intent
.get_id()
.get_execute_revenue_recovery_id(task, runner);
let execute_task_process = db
.as_scheduler()
.find_process_by_id(&process_tracker_id)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)?
.get_required_value("Process Tracker")?;
// retry the execute tasks
db.as_scheduler()
.retry_process(execute_task_process, *schedule_time)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to update the process tracker")?;
Ok(())
}
Self::TerminalFailure(payment_attempt) => {
// TODO: Add support for retrying failed outgoing recordback webhooks
// finish the current psync task
db.as_scheduler()
.finish_process_with_business_status(
psync_task_process.clone(),
business_status::PSYNC_WORKFLOW_COMPLETE,
)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to update the process tracker")?;
Ok(())
}
Self::SuccessfulPayment(payment_attempt) => {
// finish the current psync task
db.as_scheduler()
.finish_process_with_business_status(
psync_task_process.clone(),
business_status::PSYNC_WORKFLOW_COMPLETE,
)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to update the process tracker")?;
// Record a successful transaction back to Billing Connector
// TODO: Add support for retrying failed outgoing recordback webhooks
record_back_to_billing_connector(
state,
payment_attempt,
payment_intent,
&revenue_recovery_payment_data.billing_mca,
)
.await
.change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed)
.attach_printable("Failed to update the process tracker")?;
Ok(())
}
Self::ReviewPayment => {
// requeue the process tracker task in case of psync api error
let pt_update = storage::ProcessTrackerUpdate::StatusUpdate {
status: enums::ProcessTrackerStatus::Pending,
business_status: Some(String::from(business_status::PSYNC_WORKFLOW_REQUEUE)),
};
db.as_scheduler()
.update_process(psync_task_process.clone(), pt_update)
.await?;
Ok(())
}
Self::ManualReviewAction => {
logger::debug!("Invalid Payment Status For PCR Payment");
let pt_update = storage::ProcessTrackerUpdate::StatusUpdate {
status: enums::ProcessTrackerStatus::Review,
business_status: Some(String::from(business_status::PSYNC_WORKFLOW_COMPLETE)),
};
// update the process tracker status as Review
db.as_scheduler()
.update_process(psync_task_process.clone(), pt_update)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to update the process tracker")?;
Ok(())
}
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 117,
"total_crates": null
} |
fn_clm_router_update_pt_status_based_on_attempt_status_for_payments_sync_8256400709692590680 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/revenue_recovery/types
// Implementation of None for RevenueRecoveryPaymentsAttemptStatus
pub(crate) async fn update_pt_status_based_on_attempt_status_for_payments_sync(
&self,
state: &SessionState,
payment_intent: &PaymentIntent,
process_tracker: storage::ProcessTracker,
profile: &domain::Profile,
merchant_context: domain::MerchantContext,
revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,
payment_attempt: PaymentAttempt,
revenue_recovery_metadata: &mut PaymentRevenueRecoveryMetadata,
) -> Result<(), errors::ProcessTrackerError> {
let connector_customer_id = payment_intent
.extract_connector_customer_id_from_payment_intent()
.change_context(errors::RecoveryError::ValueNotFound)
.attach_printable("Failed to extract customer ID from payment intent")?;
let db = &*state.store;
let recovery_payment_intent =
hyperswitch_domain_models::revenue_recovery::RecoveryPaymentIntent::from(
payment_intent,
);
let recovery_payment_attempt =
hyperswitch_domain_models::revenue_recovery::RecoveryPaymentAttempt::from(
&payment_attempt,
);
let recovery_payment_tuple = recovery_incoming_flow::RecoveryPaymentTuple::new(
&recovery_payment_intent,
&recovery_payment_attempt,
);
let used_token = get_payment_processor_token_id_from_payment_attempt(&payment_attempt);
let retry_count = process_tracker.retry_count;
let psync_response = revenue_recovery_payment_data
.psync_data
.as_ref()
.ok_or(errors::RecoveryError::ValueNotFound)
.attach_printable("Psync data not found in revenue recovery payment data")?;
match self {
Self::Succeeded => {
// finish psync task as the payment was a success
db.as_scheduler()
.finish_process_with_business_status(
process_tracker,
business_status::PSYNC_WORKFLOW_COMPLETE,
)
.await?;
let event_status = common_enums::EventType::PaymentSucceeded;
// publish events to kafka
if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka(
state,
&recovery_payment_tuple,
Some(retry_count+1)
)
.await{
router_env::logger::error!(
"Failed to publish revenue recovery event to kafka: {:?}",
e
);
};
// update the status of token in redis
let _update_error_code = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker(
state,
&connector_customer_id,
&None,
// Since this is succeeded payment attempt, 'is_hard_decine' will be false.
&Some(false),
used_token.as_deref(),
)
.await;
// unlocking the token
let _unlock_the_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(
state,
&connector_customer_id,
)
.await;
let payments_response = psync_response
.clone()
.generate_response(state, None, None, None, &merchant_context, profile, None)
.change_context(errors::RecoveryError::PaymentsResponseGenerationFailed)
.attach_printable("Failed while generating response for payment")?;
RevenueRecoveryOutgoingWebhook::send_outgoing_webhook_based_on_revenue_recovery_status(
state,
common_enums::EventClass::Payments,
event_status,
payment_intent,
&merchant_context,
profile,
recovery_payment_attempt
.attempt_id
.get_string_repr()
.to_string(),
payments_response
)
.await?;
// Record a successful transaction back to Billing Connector
// TODO: Add support for retrying failed outgoing recordback webhooks
record_back_to_billing_connector(
state,
&payment_attempt,
payment_intent,
&revenue_recovery_payment_data.billing_mca,
)
.await
.change_context(errors::RecoveryError::RecordBackToBillingConnectorFailed)
.attach_printable("Failed to update the process tracker")?;
}
Self::Failed => {
// finish psync task
db.as_scheduler()
.finish_process_with_business_status(
process_tracker.clone(),
business_status::PSYNC_WORKFLOW_COMPLETE,
)
.await?;
// publish events to kafka
if let Err(e) = recovery_incoming_flow::RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka(
state,
&recovery_payment_tuple,
Some(retry_count+1)
)
.await{
router_env::logger::error!(
"Failed to publish revenue recovery event to kafka : {:?}", e
);
};
let error_code = recovery_payment_attempt.error_code;
let is_hard_decline = revenue_recovery::check_hard_decline(state, &payment_attempt)
.await
.ok();
// update the status of token in redis
let _update_error_code = storage::revenue_recovery_redis_operation::RedisTokenManager::update_payment_processor_token_error_code_from_process_tracker(
state,
&connector_customer_id,
&error_code,
&is_hard_decline,
used_token.as_deref(),
)
.await;
// unlocking the token
let _unlock_the_connector_customer_id = storage::revenue_recovery_redis_operation::RedisTokenManager::unlock_connector_customer_status(
state,
&connector_customer_id,
)
.await;
// Reopen calculate workflow on payment failure
Box::pin(reopen_calculate_workflow_on_payment_failure(
state,
&process_tracker,
profile,
merchant_context,
payment_intent,
revenue_recovery_payment_data,
psync_response.payment_attempt.get_id(),
))
.await?;
}
Self::Processing => {
// do a psync payment
let action = Box::pin(Action::payment_sync_call(
state,
revenue_recovery_payment_data,
payment_intent,
&process_tracker,
profile,
merchant_context,
payment_attempt,
))
.await?;
//handle the response
Box::pin(action.psync_response_handler(
state,
payment_intent,
&process_tracker,
revenue_recovery_metadata,
revenue_recovery_payment_data,
))
.await?;
}
Self::InvalidStatus(status) => logger::debug!(
"Invalid Attempt Status for the Recovery Payment : {}",
status
),
}
Ok(())
}
| {
"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_reopen_calculate_workflow_on_payment_failure_8256400709692590680 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/revenue_recovery/types
/// Reopen calculate workflow when payment fails
pub async fn reopen_calculate_workflow_on_payment_failure(
state: &SessionState,
process: &storage::ProcessTracker,
profile: &domain::Profile,
merchant_context: domain::MerchantContext,
payment_intent: &PaymentIntent,
revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,
latest_attempt_id: &id_type::GlobalAttemptId,
) -> RecoveryResult<()> {
let db = &*state.store;
let id = payment_intent.id.clone();
let task = revenue_recovery_core::CALCULATE_WORKFLOW;
let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow;
let old_tracking_data: pcr::RevenueRecoveryWorkflowTrackingData =
serde_json::from_value(process.tracking_data.clone())
.change_context(errors::RecoveryError::ValueNotFound)
.attach_printable("Failed to deserialize the tracking data from process tracker")?;
let new_tracking_data = pcr::RevenueRecoveryWorkflowTrackingData {
payment_attempt_id: latest_attempt_id.clone(),
..old_tracking_data
};
let tracking_data = serde_json::to_value(new_tracking_data)
.change_context(errors::RecoveryError::ValueNotFound)
.attach_printable("Failed to serialize the tracking data for process tracker")?;
// Construct the process tracker ID for CALCULATE_WORKFLOW
let process_tracker_id = format!("{}_{}_{}", runner, task, id.get_string_repr());
logger::info!(
payment_id = %id.get_string_repr(),
process_tracker_id = %process_tracker_id,
"Attempting to reopen CALCULATE_WORKFLOW on payment failure"
);
// Find the existing CALCULATE_WORKFLOW process tracker
let calculate_process = db
.find_process_by_id(&process_tracker_id)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to find CALCULATE_WORKFLOW process tracker")?;
match calculate_process {
Some(process) => {
logger::info!(
payment_id = %id.get_string_repr(),
process_tracker_id = %process_tracker_id,
current_status = %process.business_status,
current_retry_count = process.retry_count,
"Found existing CALCULATE_WORKFLOW, updating status and retry count"
);
// Update the process tracker to reopen the calculate workflow
// 1. Change status from "finish" to "pending"
// 2. Increase retry count by 1
// 3. Set business status to QUEUED
// 4. Schedule for immediate execution
let new_retry_count = process.retry_count + 1;
let new_schedule_time = common_utils::date_time::now()
+ time::Duration::seconds(
state
.conf
.revenue_recovery
.recovery_timestamp
.reopen_workflow_buffer_time_in_seconds,
);
let pt_update = storage::ProcessTrackerUpdate::Update {
name: Some(task.to_string()),
retry_count: Some(new_retry_count),
schedule_time: Some(new_schedule_time),
tracking_data: Some(tracking_data),
business_status: Some(String::from(business_status::PENDING)),
status: Some(common_enums::ProcessTrackerStatus::Pending),
updated_at: Some(common_utils::date_time::now()),
};
db.update_process(process.clone(), pt_update)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to update CALCULATE_WORKFLOW process tracker")?;
logger::info!(
payment_id = %id.get_string_repr(),
process_tracker_id = %process_tracker_id,
new_retry_count = new_retry_count,
new_schedule_time = %new_schedule_time,
"Successfully reopened CALCULATE_WORKFLOW with increased retry count"
);
}
None => {
logger::info!(
payment_id = %id.get_string_repr(),
process_tracker_id = %process_tracker_id,
"CALCULATE_WORKFLOW process tracker not found, creating new entry"
);
let task = "CALCULATE_WORKFLOW";
let db = &*state.store;
// Create process tracker ID in the format: CALCULATE_WORKFLOW_{payment_intent_id}
let process_tracker_id = format!("{runner}_{task}_{}", id.get_string_repr());
// Set scheduled time to current time + buffer time set in configuration
let schedule_time = common_utils::date_time::now()
+ time::Duration::seconds(
state
.conf
.revenue_recovery
.recovery_timestamp
.reopen_workflow_buffer_time_in_seconds,
);
let new_retry_count = process.retry_count + 1;
// Check if a process tracker entry already exists for this payment intent
let existing_entry = db
.as_scheduler()
.find_process_by_id(&process_tracker_id)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable(
"Failed to check for existing calculate workflow process tracker entry",
)?;
// No entry exists - create a new one
router_env::logger::info!(
"No existing CALCULATE_WORKFLOW task found for payment_intent_id: {}, creating new entry... ",
id.get_string_repr()
);
let tag = ["PCR"];
let runner = storage::ProcessTrackerRunner::PassiveRecoveryWorkflow;
let process_tracker_entry = storage::ProcessTrackerNew::new(
&process_tracker_id,
task,
runner,
tag,
process.tracking_data.clone(),
Some(new_retry_count),
schedule_time,
common_types::consts::API_VERSION,
)
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable("Failed to construct calculate workflow process tracker entry")?;
// Insert into process tracker with status New
db.as_scheduler()
.insert_process(process_tracker_entry)
.await
.change_context(errors::RecoveryError::ProcessTrackerFailure)
.attach_printable(
"Failed to enter calculate workflow process_tracker_entry in DB",
)?;
router_env::logger::info!(
"Successfully created new CALCULATE_WORKFLOW task for payment_intent_id: {}",
id.get_string_repr()
);
logger::info!(
payment_id = %id.get_string_repr(),
process_tracker_id = %process_tracker_id,
"Successfully created new CALCULATE_WORKFLOW entry using perform_calculate_workflow"
);
}
}
Ok(())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 89,
"total_crates": null
} |
fn_clm_router_foreign_from_4077746020382667360 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/revenue_recovery/transformers
// Implementation of hyperswitch_domain_models::revenue_recovery::RevenueRecoveryAttemptData for ForeignFrom<&api_models::payments::RecoveryPaymentsCreate>
fn foreign_from(data: &api_models::payments::RecoveryPaymentsCreate) -> Self {
Self {
amount: data.amount_details.order_amount().into(),
currency: data.amount_details.currency(),
merchant_reference_id: data.merchant_reference_id.to_owned(),
connector_transaction_id: data.connector_transaction_id.as_ref().map(|txn_id| {
common_utils::types::ConnectorTransactionId::TxnId(txn_id.peek().to_string())
}),
error_code: data.error.as_ref().map(|error| error.code.clone()),
error_message: data.error.as_ref().map(|error| error.message.clone()),
processor_payment_method_token: data
.payment_method_data
.primary_processor_payment_method_token
.peek()
.to_string(),
connector_customer_id: data.connector_customer_id.peek().to_string(),
connector_account_reference_id: data
.payment_merchant_connector_id
.get_string_repr()
.to_string(),
transaction_created_at: data.transaction_created_at.to_owned(),
status: data.attempt_status,
payment_method_type: data.payment_method_type,
payment_method_sub_type: data.payment_method_sub_type,
network_advice_code: data
.error
.as_ref()
.and_then(|error| error.network_advice_code.clone()),
network_decline_code: data
.error
.as_ref()
.and_then(|error| error.network_decline_code.clone()),
network_error_message: data
.error
.as_ref()
.and_then(|error| error.network_error_message.clone()),
// retry count will be updated whenever there is new attempt is created.
retry_count: None,
invoice_next_billing_time: None,
invoice_billing_started_at_time: data.billing_started_at,
card_info: data
.payment_method_data
.additional_payment_method_info
.clone(),
charge_id: None,
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 276,
"total_crates": null
} |
fn_clm_router_custom_revenue_recovery_core_-8461250148467501815 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/revenue_recovery/api
pub async fn custom_revenue_recovery_core(
state: SessionState,
req_state: ReqState,
merchant_context: MerchantContext,
profile: domain::Profile,
request: api_models::payments::RecoveryPaymentsCreate,
) -> RouterResponse<payments_api::RecoveryPaymentsResponse> {
let store = state.store.as_ref();
let key_manager_state = &(&state).into();
let payment_merchant_connector_account_id = request.payment_merchant_connector_id.to_owned();
// Find the payment & billing merchant connector id at the top level to avoid multiple DB calls.
let payment_merchant_connector_account = store
.find_merchant_connector_account_by_id(
key_manager_state,
&payment_merchant_connector_account_id,
merchant_context.get_merchant_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: payment_merchant_connector_account_id
.clone()
.get_string_repr()
.to_string(),
})?;
let billing_connector_account = store
.find_merchant_connector_account_by_id(
key_manager_state,
&request.billing_merchant_connector_id.clone(),
merchant_context.get_merchant_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: request
.billing_merchant_connector_id
.clone()
.get_string_repr()
.to_string(),
})?;
let recovery_intent =
recovery_incoming::RevenueRecoveryInvoice::get_or_create_custom_recovery_intent(
request.clone(),
&state,
&req_state,
&merchant_context,
&profile,
)
.await
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: format!(
"Failed to load recovery intent for merchant reference id : {:?}",
request.merchant_reference_id.to_owned()
)
.to_string(),
})?;
let (revenue_recovery_attempt_data, updated_recovery_intent) =
recovery_incoming::RevenueRecoveryAttempt::load_recovery_attempt_from_api(
request.clone(),
&state,
&req_state,
&merchant_context,
&profile,
recovery_intent.clone(),
payment_merchant_connector_account,
)
.await
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: format!(
"Failed to load recovery attempt for merchant reference id : {:?}",
request.merchant_reference_id.to_owned()
)
.to_string(),
})?;
let intent_retry_count = updated_recovery_intent
.feature_metadata
.as_ref()
.and_then(|metadata| metadata.get_retry_count())
.ok_or(report!(errors::ApiErrorResponse::GenericNotFoundError {
message: "Failed to fetch retry count from intent feature metadata".to_string(),
}))?;
router_env::logger::info!("Intent retry count: {:?}", intent_retry_count);
let recovery_action = recovery_incoming::RecoveryAction {
action: request.action.to_owned(),
};
let mca_retry_threshold = billing_connector_account
.get_retry_threshold()
.ok_or(report!(errors::ApiErrorResponse::GenericNotFoundError {
message: "Failed to fetch retry threshold from billing merchant connector account"
.to_string(),
}))?;
recovery_action
.handle_action(
&state,
&profile,
&merchant_context,
&billing_connector_account,
mca_retry_threshold,
intent_retry_count,
&(
Some(revenue_recovery_attempt_data),
updated_recovery_intent.clone(),
),
)
.await
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "Unexpected response from recovery core".to_string(),
})?;
let response = api_models::payments::RecoveryPaymentsResponse {
id: updated_recovery_intent.payment_id.to_owned(),
intent_status: updated_recovery_intent.status.to_owned(),
merchant_reference_id: updated_recovery_intent.merchant_reference_id.to_owned(),
};
Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
response,
))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 93,
"total_crates": null
} |
fn_clm_router_record_internal_attempt_api_-8461250148467501815 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/revenue_recovery/api
pub async fn record_internal_attempt_api(
state: &SessionState,
payment_intent: &payments_domain::PaymentIntent,
revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,
revenue_recovery_metadata: &payments_api::PaymentRevenueRecoveryMetadata,
card_info: payments_api::AdditionalCardInfo,
payment_processor_token: &str,
) -> RouterResult<payments_api::PaymentAttemptRecordResponse> {
let revenue_recovery_attempt_data =
recovery_incoming::RevenueRecoveryAttempt::get_revenue_recovery_attempt(
payment_intent,
revenue_recovery_metadata,
&revenue_recovery_payment_data.billing_mca,
card_info,
payment_processor_token,
)
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "get_revenue_recovery_attempt was not constructed".to_string(),
})?;
let request_payload = revenue_recovery_attempt_data
.create_payment_record_request(
state,
&revenue_recovery_payment_data.billing_mca.id,
Some(
revenue_recovery_metadata
.active_attempt_payment_connector_id
.clone(),
),
Some(revenue_recovery_metadata.connector),
common_enums::TriggeredBy::Internal,
)
.await
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "Cannot Create the payment record Request".to_string(),
})?;
let merchant_context_from_revenue_recovery_payment_data =
MerchantContext::NormalMerchant(Box::new(Context(
revenue_recovery_payment_data.merchant_account.clone(),
revenue_recovery_payment_data.key_store.clone(),
)));
let attempt_response = Box::pin(payments::record_attempt_core(
state.clone(),
state.get_req_state(),
merchant_context_from_revenue_recovery_payment_data,
revenue_recovery_payment_data.profile.clone(),
request_payload,
payment_intent.id.clone(),
hyperswitch_domain_models::payments::HeaderPayload::default(),
))
.await;
match attempt_response {
Ok(services::ApplicationResponse::JsonWithHeaders((attempt_response, _))) => {
Ok(attempt_response)
}
Ok(_) => Err(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable("Unexpected response from record attempt core"),
error @ Err(_) => {
router_env::logger::error!(?error);
Err(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable("failed to record attempt for revenue recovery workflow")
}
}
}
| {
"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_call_proxy_api_-8461250148467501815 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/revenue_recovery/api
pub async fn call_proxy_api(
state: &SessionState,
payment_intent: &payments_domain::PaymentIntent,
revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,
revenue_recovery: &payments_api::PaymentRevenueRecoveryMetadata,
payment_processor_token: &str,
) -> RouterResult<payments_domain::PaymentConfirmData<api_types::Authorize>> {
let operation = payments::operations::proxy_payments_intent::PaymentProxyIntent;
let recurring_details = api_models::mandates::ProcessorPaymentToken {
processor_payment_token: payment_processor_token.to_string(),
merchant_connector_id: Some(revenue_recovery.get_merchant_connector_id_for_api_request()),
};
let req = payments_api::ProxyPaymentsRequest {
return_url: None,
amount: payments_api::AmountDetails::new(payment_intent.amount_details.clone().into()),
recurring_details,
shipping: None,
browser_info: None,
connector: revenue_recovery.connector.to_string(),
merchant_connector_id: revenue_recovery.get_merchant_connector_id_for_api_request(),
};
logger::info!(
"Call made to payments proxy api , with the request body {:?}",
req
);
let merchant_context_from_revenue_recovery_payment_data =
MerchantContext::NormalMerchant(Box::new(Context(
revenue_recovery_payment_data.merchant_account.clone(),
revenue_recovery_payment_data.key_store.clone(),
)));
// TODO : Use api handler instead of calling get_tracker and payments_operation_core
// Get the tracker related information. This includes payment intent and payment attempt
let get_tracker_response = operation
.to_get_tracker()?
.get_trackers(
state,
payment_intent.get_id(),
&req,
&merchant_context_from_revenue_recovery_payment_data,
&revenue_recovery_payment_data.profile,
&payments_domain::HeaderPayload::default(),
)
.await?;
let (payment_data, _req, _, _) = Box::pin(payments::proxy_for_payments_operation_core::<
api_types::Authorize,
_,
_,
_,
payments_domain::PaymentConfirmData<api_types::Authorize>,
>(
state,
state.get_req_state(),
merchant_context_from_revenue_recovery_payment_data,
revenue_recovery_payment_data.profile.clone(),
operation,
req,
get_tracker_response,
payments::CallConnectorAction::Trigger,
payments_domain::HeaderPayload::default(),
None,
))
.await?;
Ok(payment_data)
}
| {
"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_call_psync_api_-8461250148467501815 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/revenue_recovery/api
pub async fn call_psync_api(
state: &SessionState,
global_payment_id: &id_type::GlobalPaymentId,
revenue_recovery_data: &revenue_recovery_types::RevenueRecoveryPaymentData,
force_sync_bool: bool,
expand_attempts_bool: bool,
) -> RouterResult<payments_domain::PaymentStatusData<api_types::PSync>> {
let operation = payments::operations::PaymentGet;
let req = payments_api::PaymentsRetrieveRequest {
force_sync: force_sync_bool,
param: None,
expand_attempts: expand_attempts_bool,
return_raw_connector_response: None,
merchant_connector_details: None,
};
let merchant_context_from_revenue_recovery_data =
MerchantContext::NormalMerchant(Box::new(Context(
revenue_recovery_data.merchant_account.clone(),
revenue_recovery_data.key_store.clone(),
)));
// TODO : Use api handler instead of calling get_tracker and payments_operation_core
// Get the tracker related information. This includes payment intent and payment attempt
let get_tracker_response = operation
.to_get_tracker()?
.get_trackers(
state,
global_payment_id,
&req,
&merchant_context_from_revenue_recovery_data,
&revenue_recovery_data.profile,
&payments_domain::HeaderPayload::default(),
)
.await?;
let (payment_data, _req, _, _, _, _) = Box::pin(payments::payments_operation_core::<
api_types::PSync,
_,
_,
_,
payments_domain::PaymentStatusData<api_types::PSync>,
>(
state,
state.get_req_state(),
merchant_context_from_revenue_recovery_data,
&revenue_recovery_data.profile,
operation,
req,
get_tracker_response,
payments::CallConnectorAction::Trigger,
payments_domain::HeaderPayload::default(),
))
.await?;
Ok(payment_data)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 50,
"total_crates": null
} |
fn_clm_router_update_payment_intent_api_-8461250148467501815 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/revenue_recovery/api
pub async fn update_payment_intent_api(
state: &SessionState,
global_payment_id: id_type::GlobalPaymentId,
revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,
update_req: payments_api::PaymentsUpdateIntentRequest,
) -> RouterResult<payments_domain::PaymentIntentData<api_types::PaymentUpdateIntent>> {
// TODO : Use api handler instead of calling payments_intent_operation_core
let operation = payments::operations::PaymentUpdateIntent;
let merchant_context_from_revenue_recovery_payment_data =
MerchantContext::NormalMerchant(Box::new(Context(
revenue_recovery_payment_data.merchant_account.clone(),
revenue_recovery_payment_data.key_store.clone(),
)));
let (payment_data, _req, _) = payments::payments_intent_operation_core::<
api_types::PaymentUpdateIntent,
_,
_,
payments_domain::PaymentIntentData<api_types::PaymentUpdateIntent>,
>(
state,
state.get_req_state(),
merchant_context_from_revenue_recovery_payment_data,
revenue_recovery_payment_data.profile.clone(),
operation,
update_req,
global_payment_id,
payments_domain::HeaderPayload::default(),
)
.await?;
Ok(payment_data)
}
| {
"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_upload_and_get_provider_provider_file_id_profile_id_2145319124900094127 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/files/helpers
pub async fn upload_and_get_provider_provider_file_id_profile_id(
state: &SessionState,
merchant_context: &domain::MerchantContext,
create_file_request: &api::CreateFileRequest,
file_key: String,
) -> CustomResult<
(
String,
api_models::enums::FileUploadProvider,
Option<common_utils::id_type::ProfileId>,
Option<common_utils::id_type::MerchantConnectorAccountId>,
),
errors::ApiErrorResponse,
> {
match create_file_request.purpose {
api::FilePurpose::DisputeEvidence => {
let dispute_id = create_file_request
.dispute_id
.clone()
.ok_or(errors::ApiErrorResponse::MissingDisputeId)?;
let dispute = state
.store
.find_dispute_by_merchant_id_dispute_id(
merchant_context.get_merchant_account().get_id(),
&dispute_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::DisputeNotFound { dispute_id })?;
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&dispute.connector,
api::GetToken::Connector,
dispute.merchant_connector_id.clone(),
)?;
if connector_data.connector_name.supports_file_storage_module() {
let payment_intent = state
.store
.find_payment_intent_by_payment_id_merchant_id(
&state.into(),
&dispute.payment_id,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_attempt = state
.store
.find_payment_attempt_by_attempt_id_merchant_id(
&dispute.attempt_id,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let connector_integration: services::BoxedFilesConnectorIntegrationInterface<
api::Upload,
types::UploadFileRequestData,
types::UploadFileResponse,
> = connector_data.connector.get_connector_integration();
let router_data = utils::construct_upload_file_router_data(
state,
&payment_intent,
&payment_attempt,
merchant_context,
create_file_request,
dispute,
&connector_data.connector_name.to_string(),
file_key,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed constructing the upload file router data")?;
let response = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while calling upload file connector api")?;
let upload_file_response = response.response.map_err(|err| {
errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: connector_data.connector_name.to_string(),
status_code: err.status_code,
reason: err.reason,
}
})?;
Ok((
upload_file_response.provider_file_id,
api_models::enums::FileUploadProvider::foreign_try_from(
&connector_data.connector_name,
)?,
payment_intent.profile_id,
payment_attempt.merchant_connector_id,
))
} else {
state
.file_storage_client
.upload_file(&file_key, create_file_request.file.clone())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
Ok((
file_key,
api_models::enums::FileUploadProvider::Router,
None,
None,
))
}
}
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 83,
"total_crates": null
} |
fn_clm_router_retrieve_file_and_provider_file_id_from_file_id_2145319124900094127 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/files/helpers
pub async fn retrieve_file_and_provider_file_id_from_file_id(
state: &SessionState,
file_id: Option<String>,
dispute_id: Option<String>,
merchant_context: &domain::MerchantContext,
is_connector_file_data_required: api::FileDataRequired,
) -> CustomResult<FileInfo, errors::ApiErrorResponse> {
match file_id {
None => Ok(FileInfo {
file_data: None,
provider_file_id: None,
file_type: None,
}),
Some(file_key) => {
let file_metadata_object = state
.store
.find_file_metadata_by_merchant_id_file_id(
merchant_context.get_merchant_account().get_id(),
&file_key,
)
.await
.change_context(errors::ApiErrorResponse::FileNotFound)?;
let (provider, provider_file_id) = match (
file_metadata_object.file_upload_provider,
file_metadata_object.provider_file_id.clone(),
file_metadata_object.available,
) {
(Some(provider), Some(provider_file_id), true) => (provider, provider_file_id),
_ => Err(errors::ApiErrorResponse::FileNotAvailable)
.attach_printable("File not available")?,
};
match provider {
diesel_models::enums::FileUploadProvider::Router => Ok(FileInfo {
file_data: Some(
state
.file_storage_client
.retrieve_file(&provider_file_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?,
),
provider_file_id: Some(provider_file_id),
file_type: Some(file_metadata_object.file_type),
}),
_ => {
let connector_file_data = match is_connector_file_data_required {
api::FileDataRequired::Required => Some(
retrieve_file_from_connector(
state,
file_metadata_object.clone(),
dispute_id,
merchant_context,
)
.await?,
),
api::FileDataRequired::NotRequired => None,
};
Ok(FileInfo {
file_data: connector_file_data,
provider_file_id: Some(provider_file_id),
file_type: Some(file_metadata_object.file_type),
})
}
}
}
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 63,
"total_crates": null
} |
fn_clm_router_retrieve_file_from_connector_2145319124900094127 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/files/helpers
pub async fn retrieve_file_from_connector(
state: &SessionState,
file_metadata: diesel_models::file::FileMetadata,
dispute_id: Option<String>,
merchant_context: &domain::MerchantContext,
) -> CustomResult<Vec<u8>, errors::ApiErrorResponse> {
let connector = &types::Connector::foreign_try_from(
file_metadata
.file_upload_provider
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Missing file upload provider")?,
)?
.to_string();
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
connector,
api::GetToken::Connector,
file_metadata.merchant_connector_id.clone(),
)?;
let dispute = match dispute_id {
Some(dispute) => Some(
state
.store
.find_dispute_by_merchant_id_dispute_id(
merchant_context.get_merchant_account().get_id(),
&dispute,
)
.await
.to_not_found_response(errors::ApiErrorResponse::DisputeNotFound {
dispute_id: dispute,
})?,
),
None => None,
};
let connector_integration: services::BoxedFilesConnectorIntegrationInterface<
api::Retrieve,
types::RetrieveFileRequestData,
types::RetrieveFileResponse,
> = connector_data.connector.get_connector_integration();
let router_data = utils::construct_retrieve_file_router_data(
state,
merchant_context,
&file_metadata,
dispute,
connector,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed constructing the retrieve file router data")?;
let response = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_files_failed_response()
.attach_printable("Failed while calling retrieve file connector api")?;
let retrieve_file_response =
response
.response
.map_err(|err| errors::ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: connector.to_string(),
status_code: err.status_code,
reason: err.reason,
})?;
Ok(retrieve_file_response.file_data)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 51,
"total_crates": null
} |
fn_clm_router_validate_file_upload_2145319124900094127 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/files/helpers
pub async fn validate_file_upload(
state: &SessionState,
merchant_context: domain::MerchantContext,
create_file_request: api::CreateFileRequest,
) -> CustomResult<(), errors::ApiErrorResponse> {
//File Validation based on the purpose of file upload
match create_file_request.purpose {
api::FilePurpose::DisputeEvidence => {
let dispute_id = &create_file_request
.dispute_id
.ok_or(errors::ApiErrorResponse::MissingDisputeId)?;
let dispute = state
.store
.find_dispute_by_merchant_id_dispute_id(
merchant_context.get_merchant_account().get_id(),
dispute_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::DisputeNotFound {
dispute_id: dispute_id.to_string(),
})?;
// Connector is not called for validating the file, connector_id can be passed as None safely
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&dispute.connector,
api::GetToken::Connector,
None,
)?;
let validation = connector_data.connector.validate_file_upload(
create_file_request.purpose,
create_file_request.file_size,
create_file_request.file_type.clone(),
);
match validation {
Ok(()) => Ok(()),
Err(err) => match err.current_context() {
errors::ConnectorError::FileValidationFailed { reason } => {
Err(errors::ApiErrorResponse::FileValidationFailed {
reason: reason.to_string(),
}
.into())
}
//We are using parent error and ignoring this
_error => Err(err
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("File validation failed"))?,
},
}
}
}
}
| {
"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_delete_file_using_file_id_2145319124900094127 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/files/helpers
pub async fn delete_file_using_file_id(
state: &SessionState,
file_key: String,
merchant_context: &domain::MerchantContext,
) -> CustomResult<(), errors::ApiErrorResponse> {
let file_metadata_object = state
.store
.find_file_metadata_by_merchant_id_file_id(
merchant_context.get_merchant_account().get_id(),
&file_key,
)
.await
.change_context(errors::ApiErrorResponse::FileNotFound)?;
let (provider, provider_file_id) = match (
file_metadata_object.file_upload_provider,
file_metadata_object.provider_file_id,
file_metadata_object.available,
) {
(Some(provider), Some(provider_file_id), true) => (provider, provider_file_id),
_ => Err(errors::ApiErrorResponse::FileNotAvailable)
.attach_printable("File not available")?,
};
match provider {
diesel_models::enums::FileUploadProvider::Router => state
.file_storage_client
.delete_file(&provider_file_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError),
_ => Err(errors::ApiErrorResponse::FileProviderNotSupported {
message: "Not Supported because provider is not Router".to_string(),
}
.into()),
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 31,
"total_crates": null
} |
fn_clm_router_validate_secure_payment_link_render_request_3146046220273944053 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/payment_link/validator
pub fn validate_secure_payment_link_render_request(
request_headers: &header::HeaderMap,
payment_link: &PaymentLink,
payment_link_config: &PaymentLinkConfig,
) -> RouterResult<()> {
let link_id = payment_link.payment_link_id.clone();
let allowed_domains = payment_link_config
.allowed_domains
.clone()
.ok_or(report!(errors::ApiErrorResponse::InvalidRequestUrl))
.attach_printable_lazy(|| {
format!("Secure payment link was not generated for {link_id}\nmissing allowed_domains")
})?;
// Validate secure_link was generated
if payment_link.secure_link.clone().is_none() {
return Err(report!(errors::ApiErrorResponse::InvalidRequestUrl)).attach_printable_lazy(
|| format!("Secure payment link was not generated for {link_id}\nmissing secure_link"),
);
}
// Fetch destination is "iframe"
match request_headers.get("sec-fetch-dest").and_then(|v| v.to_str().ok()) {
Some("iframe") => Ok(()),
Some(requestor) => Err(report!(errors::ApiErrorResponse::AccessForbidden {
resource: "payment_link".to_string(),
}))
.attach_printable_lazy(|| {
format!(
"Access to payment_link [{link_id}] is forbidden when requested through {requestor}",
)
}),
None => Err(report!(errors::ApiErrorResponse::AccessForbidden {
resource: "payment_link".to_string(),
}))
.attach_printable_lazy(|| {
format!(
"Access to payment_link [{link_id}] is forbidden when sec-fetch-dest is not present in request headers",
)
}),
}?;
// Validate origin / referer
let domain_in_req = {
let origin_or_referer = request_headers
.get("origin")
.or_else(|| request_headers.get("referer"))
.and_then(|v| v.to_str().ok())
.ok_or_else(|| {
report!(errors::ApiErrorResponse::AccessForbidden {
resource: "payment_link".to_string(),
})
})
.attach_printable_lazy(|| {
format!(
"Access to payment_link [{link_id}] is forbidden when origin or referer is not present in request headers",
)
})?;
let url = Url::parse(origin_or_referer)
.map_err(|_| {
report!(errors::ApiErrorResponse::AccessForbidden {
resource: "payment_link".to_string(),
})
})
.attach_printable_lazy(|| {
format!("Invalid URL found in request headers {origin_or_referer}")
})?;
url.host_str()
.and_then(|host| url.port().map(|port| format!("{host}:{port}")))
.or_else(|| url.host_str().map(String::from))
.ok_or_else(|| {
report!(errors::ApiErrorResponse::AccessForbidden {
resource: "payment_link".to_string(),
})
})
.attach_printable_lazy(|| {
format!("host or port not found in request headers {url:?}")
})?
};
if validate_domain_against_allowed_domains(&domain_in_req, allowed_domains) {
Ok(())
} else {
Err(report!(errors::ApiErrorResponse::AccessForbidden {
resource: "payment_link".to_string(),
}))
.attach_printable_lazy(|| {
format!(
"Access to payment_link [{link_id}] is forbidden from requestor - {domain_in_req}",
)
})
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 83,
"total_crates": null
} |
fn_clm_router_from_6336102903953161980 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/routing/transformers
// Implementation of storage_enums::TransactionType for From<&routing::TransactionData<'_>>
fn from(value: &routing::TransactionData<'_>) -> Self {
match value {
routing::TransactionData::Payment(_) => Self::Payment,
#[cfg(feature = "payouts")]
routing::TransactionData::Payout(_) => Self::Payout,
}
}
| {
"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_foreign_try_from_6336102903953161980 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/routing/transformers
// Implementation of MerchantRoutingAlgorithm for ForeignTryFrom<RoutingAlgorithm>
fn foreign_try_from(value: RoutingAlgorithm) -> Result<Self, Self::Error> {
let algorithm: RoutingAlgorithmWrapper = match value.kind {
diesel_models::enums::RoutingAlgorithmKind::Dynamic => value
.algorithm_data
.parse_value::<DynamicRoutingAlgorithm>("RoutingAlgorithmDynamic")
.map(RoutingAlgorithmWrapper::Dynamic)?,
_ => value
.algorithm_data
.parse_value::<api_models::routing::StaticRoutingAlgorithm>("RoutingAlgorithm")
.map(RoutingAlgorithmWrapper::Static)?,
};
Ok(Self {
id: value.algorithm_id,
name: value.name,
profile_id: value.profile_id,
description: value.description.unwrap_or_default(),
algorithm,
created_at: value.created_at.assume_utc().unix_timestamp(),
modified_at: value.modified_at.assume_utc().unix_timestamp(),
algorithm_for: value.algorithm_for,
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 442,
"total_crates": null
} |
fn_clm_router_foreign_from_6336102903953161980 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/routing/transformers
// Implementation of storage_enums::RoutingAlgorithmKind for ForeignFrom<RoutingAlgorithmKind>
fn foreign_from(value: RoutingAlgorithmKind) -> Self {
match value {
RoutingAlgorithmKind::Single => Self::Single,
RoutingAlgorithmKind::Priority => Self::Priority,
RoutingAlgorithmKind::VolumeSplit => Self::VolumeSplit,
RoutingAlgorithmKind::Advanced => Self::Advanced,
RoutingAlgorithmKind::Dynamic => Self::Dynamic,
RoutingAlgorithmKind::ThreeDsDecisionRule => Self::ThreeDsDecisionRule,
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 212,
"total_crates": null
} |
fn_clm_router_construct_sr_request_6336102903953161980 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/routing/transformers
// Implementation of OpenRouterDecideGatewayRequest for OpenRouterDecideGatewayRequestExt
fn construct_sr_request(
attempt: &PaymentAttempt,
eligible_gateway_list: Vec<RoutableConnectorChoice>,
ranking_algorithm: Option<RankingAlgorithm>,
is_elimination_enabled: bool,
) -> Self {
Self {
payment_info: PaymentInfo {
payment_id: attempt.payment_id.clone(),
amount: attempt.net_amount.get_order_amount(),
currency: attempt.currency.unwrap_or(storage_enums::Currency::USD),
payment_type: "ORDER_PAYMENT".to_string(),
payment_method_type: "UPI".into(), // TODO: once open-router makes this field string, we can send from attempt
payment_method: attempt.payment_method.unwrap_or_default(),
metadata: None,
card_isin: None,
},
merchant_id: attempt.profile_id.clone(),
eligible_gateway_list: Some(
eligible_gateway_list
.into_iter()
.map(|connector| connector.to_string())
.collect(),
),
ranking_algorithm,
elimination_enabled: Some(is_elimination_enabled),
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 33,
"total_crates": null
} |
fn_clm_router_construct_debit_request_6336102903953161980 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/routing/transformers
// Implementation of OpenRouterDecideGatewayRequest for OpenRouterDecideGatewayRequestExt
fn construct_debit_request(
attempt: &PaymentAttempt,
metadata: Option<String>,
card_isin: Option<Secret<String>>,
ranking_algorithm: Option<RankingAlgorithm>,
) -> Self {
Self {
payment_info: PaymentInfo {
payment_id: attempt.payment_id.clone(),
amount: attempt.net_amount.get_total_amount(),
currency: attempt.currency.unwrap_or(storage_enums::Currency::USD),
payment_type: "ORDER_PAYMENT".to_string(),
card_isin: card_isin.map(|value| value.peek().clone()),
metadata,
payment_method_type: "UPI".into(), // TODO: once open-router makes this field string, we can send from attempt
payment_method: attempt.payment_method.unwrap_or_default(),
},
merchant_id: attempt.profile_id.clone(),
// eligible gateway list is not used in debit routing
eligible_gateway_list: None,
ranking_algorithm,
elimination_enabled: None,
}
}
| {
"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_new_5169409339312738427 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/routing/helpers
// Implementation of None for DynamicRoutingConfigParamsInterpolator
pub fn new(
payment_method: Option<common_enums::PaymentMethod>,
payment_method_type: Option<common_enums::PaymentMethodType>,
authentication_type: Option<common_enums::AuthenticationType>,
currency: Option<common_enums::Currency>,
country: Option<common_enums::CountryAlpha2>,
card_network: Option<String>,
card_bin: Option<String>,
) -> Self {
Self {
payment_method,
payment_method_type,
authentication_type,
currency,
country,
card_network,
card_bin,
}
}
| {
"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_push_metrics_with_update_window_for_success_based_routing_5169409339312738427 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/routing/helpers
pub async fn push_metrics_with_update_window_for_success_based_routing(
state: &SessionState,
payment_attempt: &storage::PaymentAttempt,
routable_connectors: Vec<routing_types::RoutableConnectorChoice>,
profile_id: &id_type::ProfileId,
dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
dynamic_routing_config_params_interpolator: DynamicRoutingConfigParamsInterpolator,
) -> RouterResult<()> {
if let Some(success_based_algo_ref) = dynamic_routing_algo_ref.success_based_algorithm {
if success_based_algo_ref.enabled_feature != routing_types::DynamicRoutingFeatures::None {
let client = &state
.grpc_client
.dynamic_routing
.as_ref()
.ok_or(errors::ApiErrorResponse::GenericNotFoundError {
message: "dynamic routing gRPC client not found".to_string(),
})?
.success_rate_client;
let payment_connector = &payment_attempt.connector.clone().ok_or(
errors::ApiErrorResponse::GenericNotFoundError {
message: "unable to derive payment connector from payment attempt".to_string(),
},
)?;
let routable_connector = routing_types::RoutableConnectorChoice {
choice_kind: api_models::routing::RoutableChoiceKind::FullStruct,
connector: common_enums::RoutableConnectors::from_str(payment_connector.as_str())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to infer routable_connector from connector")?,
merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
};
let payment_status_attribute =
get_desired_payment_status_for_dynamic_routing_metrics(payment_attempt.status);
let success_based_routing_configs = fetch_dynamic_routing_configs::<
routing_types::SuccessBasedRoutingConfig,
>(
state,
profile_id,
success_based_algo_ref
.algorithm_id_with_timestamp
.algorithm_id
.ok_or(errors::ApiErrorResponse::GenericNotFoundError {
message: "success_rate algorithm_id not found".to_string(),
})
.attach_printable(
"success_based_routing_algorithm_id not found in business_profile",
)?,
)
.await
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "success_rate based dynamic routing configs not found".to_string(),
})
.attach_printable("unable to retrieve success_rate based dynamic routing configs")?;
let success_based_routing_config_params = dynamic_routing_config_params_interpolator
.get_string_val(
success_based_routing_configs
.params
.as_ref()
.ok_or(errors::RoutingError::SuccessBasedRoutingParamsNotFoundError)
.change_context(errors::ApiErrorResponse::InternalServerError)?,
);
let success_based_connectors = client
.calculate_entity_and_global_success_rate(
profile_id.get_string_repr().into(),
success_based_routing_configs.clone(),
success_based_routing_config_params.clone(),
routable_connectors.clone(),
state.get_grpc_headers(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to calculate/fetch success rate from dynamic routing service",
)?;
let first_merchant_success_based_connector = &success_based_connectors
.entity_scores_with_labels
.first()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to fetch the first connector from list of connectors obtained from dynamic routing service",
)?;
let (first_merchant_success_based_connector_label, _) = first_merchant_success_based_connector.label
.split_once(':')
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!(
"unable to split connector_name and mca_id from the first connector {:?} obtained from dynamic routing service",
first_merchant_success_based_connector.label
))?;
let first_global_success_based_connector = &success_based_connectors
.global_scores_with_labels
.first()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to fetch the first global connector from list of connectors obtained from dynamic routing service",
)?;
let outcome = get_dynamic_routing_based_metrics_outcome_for_payment(
payment_status_attribute,
payment_connector.to_string(),
first_merchant_success_based_connector_label.to_string(),
);
core_metrics::DYNAMIC_SUCCESS_BASED_ROUTING.add(
1,
router_env::metric_attributes!(
(
"tenant",
state.tenant.tenant_id.get_string_repr().to_owned(),
),
(
"merchant_profile_id",
format!(
"{}:{}",
payment_attempt.merchant_id.get_string_repr(),
payment_attempt.profile_id.get_string_repr()
),
),
(
"merchant_specific_success_based_routing_connector",
first_merchant_success_based_connector_label.to_string(),
),
(
"merchant_specific_success_based_routing_connector_score",
first_merchant_success_based_connector.score.to_string(),
),
(
"global_success_based_routing_connector",
first_global_success_based_connector.label.to_string(),
),
(
"global_success_based_routing_connector_score",
first_global_success_based_connector.score.to_string(),
),
("payment_connector", payment_connector.to_string()),
(
"currency",
payment_attempt
.currency
.map_or_else(|| "None".to_string(), |currency| currency.to_string()),
),
(
"payment_method",
payment_attempt.payment_method.map_or_else(
|| "None".to_string(),
|payment_method| payment_method.to_string(),
),
),
(
"payment_method_type",
payment_attempt.payment_method_type.map_or_else(
|| "None".to_string(),
|payment_method_type| payment_method_type.to_string(),
),
),
(
"capture_method",
payment_attempt.capture_method.map_or_else(
|| "None".to_string(),
|capture_method| capture_method.to_string(),
),
),
(
"authentication_type",
payment_attempt.authentication_type.map_or_else(
|| "None".to_string(),
|authentication_type| authentication_type.to_string(),
),
),
("payment_status", payment_attempt.status.to_string()),
("conclusive_classification", outcome.to_string()),
),
);
logger::debug!("successfully pushed success_based_routing metrics");
let duplicate_stats = state
.store
.find_dynamic_routing_stats_optional_by_attempt_id_merchant_id(
payment_attempt.attempt_id.clone(),
&payment_attempt.merchant_id.to_owned(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch dynamic_routing_stats entry")?;
if duplicate_stats.is_some() {
let dynamic_routing_update = DynamicRoutingStatsUpdate {
amount: payment_attempt.get_total_amount(),
success_based_routing_connector: first_merchant_success_based_connector_label
.to_string(),
payment_connector: payment_connector.to_string(),
payment_method_type: payment_attempt.payment_method_type,
currency: payment_attempt.currency,
payment_method: payment_attempt.payment_method,
capture_method: payment_attempt.capture_method,
authentication_type: payment_attempt.authentication_type,
payment_status: payment_attempt.status,
conclusive_classification: outcome,
global_success_based_connector: Some(
first_global_success_based_connector.label.to_string(),
),
};
state
.store
.update_dynamic_routing_stats(
payment_attempt.attempt_id.clone(),
&payment_attempt.merchant_id.to_owned(),
dynamic_routing_update,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to update dynamic routing stats to db")?;
} else {
let dynamic_routing_stats = DynamicRoutingStatsNew {
payment_id: payment_attempt.payment_id.to_owned(),
attempt_id: payment_attempt.attempt_id.clone(),
merchant_id: payment_attempt.merchant_id.to_owned(),
profile_id: payment_attempt.profile_id.to_owned(),
amount: payment_attempt.get_total_amount(),
success_based_routing_connector: first_merchant_success_based_connector_label
.to_string(),
payment_connector: payment_connector.to_string(),
payment_method_type: payment_attempt.payment_method_type,
currency: payment_attempt.currency,
payment_method: payment_attempt.payment_method,
capture_method: payment_attempt.capture_method,
authentication_type: payment_attempt.authentication_type,
payment_status: payment_attempt.status,
conclusive_classification: outcome,
created_at: common_utils::date_time::now(),
global_success_based_connector: Some(
first_global_success_based_connector.label.to_string(),
),
};
state
.store
.insert_dynamic_routing_stat_entry(dynamic_routing_stats)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to push dynamic routing stats to db")?;
};
let label_with_status = routing_utils::UpdateLabelWithStatusEventRequest {
label: routable_connector.clone().to_string(),
status: payment_status_attribute == common_enums::AttemptStatus::Charged,
};
let event_request = routing_utils::UpdateSuccessRateWindowEventRequest {
id: payment_attempt.profile_id.get_string_repr().to_string(),
params: success_based_routing_config_params.clone(),
labels_with_status: vec![label_with_status.clone()],
global_labels_with_status: vec![label_with_status],
config: success_based_routing_configs
.config
.as_ref()
.map(routing_utils::UpdateSuccessRateWindowConfig::from),
};
let routing_events_wrapper = routing_utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
state.request_id,
payment_attempt.payment_id.get_string_repr().to_string(),
profile_id.to_owned(),
payment_attempt.merchant_id.to_owned(),
"IntelligentRouter: UpdateSuccessRateWindow".to_string(),
Some(event_request.clone()),
true,
false,
);
let closure = || async {
let update_response_result = client
.update_success_rate(
profile_id.get_string_repr().into(),
success_based_routing_configs,
success_based_routing_config_params,
vec![routing_types::RoutableConnectorChoiceWithStatus::new(
routable_connector.clone(),
payment_status_attribute == common_enums::AttemptStatus::Charged,
)],
state.get_grpc_headers(),
)
.await
.change_context(errors::RoutingError::SuccessRateCalculationError)
.attach_printable(
"unable to update success based routing window in dynamic routing service",
);
match update_response_result {
Ok(update_response) => {
let updated_resp =
routing_utils::UpdateSuccessRateWindowEventResponse::try_from(
&update_response,
)
.change_context(errors::RoutingError::RoutingEventsError { message: "Unable to convert to UpdateSuccessRateWindowEventResponse from UpdateSuccessRateWindowResponse".to_string(), status_code: 500 })?;
Ok(Some(updated_resp))
}
Err(err) => {
logger::error!(
"unable to update connector score in dynamic routing service: {:?}",
err.current_context()
);
Err(err)
}
}
};
let events_response = routing_events_wrapper
.construct_event_builder(
"SuccessRateCalculator.UpdateSuccessRateWindow".to_string(),
routing_events::RoutingEngine::IntelligentRouter,
routing_events::ApiMethod::Grpc,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"SR-Intelligent-Router: Failed to update success rate in Intelligent-Router",
)?
.trigger_event(state, closure)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"SR-Intelligent-Router: Failed to update success rate in Intelligent-Router",
)?;
let _response: routing_utils::UpdateSuccessRateWindowEventResponse = events_response
.response
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"UpdateSuccessRateWindowEventResponse not found in RoutingEventResponse",
)?;
let mut routing_event = events_response
.event
.ok_or(errors::RoutingError::RoutingEventsError {
message:
"SR-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse"
.to_string(),
status_code: 500,
})
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"SR-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse",
)?;
routing_event.set_status_code(200);
routing_event.set_payment_connector(routable_connector); // we can do this inside the event wrap by implementing an interface on the req type
state.event_handler().log_event(&routing_event);
Ok(())
} else {
Ok(())
}
} else {
Ok(())
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 237,
"total_crates": null
} |
fn_clm_router_foreign_from_5169409339312738427 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/routing/helpers
// Implementation of open_router::TxnStatus for ForeignFrom<common_enums::AttemptStatus>
fn foreign_from(attempt_status: common_enums::AttemptStatus) -> Self {
match attempt_status {
common_enums::AttemptStatus::Started => Self::Started,
common_enums::AttemptStatus::AuthenticationFailed => Self::AuthenticationFailed,
common_enums::AttemptStatus::RouterDeclined => Self::JuspayDeclined,
common_enums::AttemptStatus::AuthenticationPending => Self::PendingVbv,
common_enums::AttemptStatus::AuthenticationSuccessful => Self::VBVSuccessful,
common_enums::AttemptStatus::Authorized
| common_enums::AttemptStatus::PartiallyAuthorized => Self::Authorized,
common_enums::AttemptStatus::AuthorizationFailed => Self::AuthorizationFailed,
common_enums::AttemptStatus::Charged => Self::Charged,
common_enums::AttemptStatus::Authorizing => Self::Authorizing,
common_enums::AttemptStatus::CodInitiated => Self::CODInitiated,
common_enums::AttemptStatus::Voided | common_enums::AttemptStatus::Expired => {
Self::Voided
}
common_enums::AttemptStatus::VoidedPostCharge => Self::VoidedPostCharge,
common_enums::AttemptStatus::VoidInitiated => Self::VoidInitiated,
common_enums::AttemptStatus::CaptureInitiated => Self::CaptureInitiated,
common_enums::AttemptStatus::CaptureFailed => Self::CaptureFailed,
common_enums::AttemptStatus::VoidFailed => Self::VoidFailed,
common_enums::AttemptStatus::AutoRefunded => Self::AutoRefunded,
common_enums::AttemptStatus::PartialCharged => Self::PartialCharged,
common_enums::AttemptStatus::PartialChargedAndChargeable => Self::ToBeCharged,
common_enums::AttemptStatus::Unresolved => Self::Pending,
common_enums::AttemptStatus::Pending
| common_enums::AttemptStatus::IntegrityFailure => Self::Pending,
common_enums::AttemptStatus::Failure => Self::Failure,
common_enums::AttemptStatus::PaymentMethodAwaited => Self::Pending,
common_enums::AttemptStatus::ConfirmationAwaited => Self::Pending,
common_enums::AttemptStatus::DeviceDataCollectionPending => Self::Pending,
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 212,
"total_crates": null
} |
fn_clm_router_push_metrics_with_update_window_for_contract_based_routing_5169409339312738427 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/routing/helpers
pub async fn push_metrics_with_update_window_for_contract_based_routing(
state: &SessionState,
payment_attempt: &storage::PaymentAttempt,
routable_connectors: Vec<routing_types::RoutableConnectorChoice>,
profile_id: &id_type::ProfileId,
dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
_dynamic_routing_config_params_interpolator: DynamicRoutingConfigParamsInterpolator,
) -> RouterResult<()> {
if let Some(contract_routing_algo_ref) = dynamic_routing_algo_ref.contract_based_routing {
if contract_routing_algo_ref.enabled_feature != routing_types::DynamicRoutingFeatures::None
{
let client = &state
.grpc_client
.dynamic_routing
.as_ref()
.ok_or(errors::ApiErrorResponse::GenericNotFoundError {
message: "dynamic routing gRPC client not found".to_string(),
})?
.contract_based_client;
let payment_connector = &payment_attempt.connector.clone().ok_or(
errors::ApiErrorResponse::GenericNotFoundError {
message: "unable to derive payment connector from payment attempt".to_string(),
},
)?;
let contract_based_routing_config =
fetch_dynamic_routing_configs::<routing_types::ContractBasedRoutingConfig>(
state,
profile_id,
contract_routing_algo_ref
.algorithm_id_with_timestamp
.algorithm_id
.ok_or(errors::ApiErrorResponse::GenericNotFoundError {
message: "contract_routing algorithm_id not found".to_string(),
})
.attach_printable(
"contract_based_routing_algorithm_id not found in business_profile",
)?,
)
.await
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "contract based dynamic routing configs not found".to_string(),
})
.attach_printable("unable to retrieve contract based dynamic routing configs")?;
let mut existing_label_info = None;
contract_based_routing_config
.label_info
.as_ref()
.map(|label_info_vec| {
for label_info in label_info_vec {
if Some(&label_info.mca_id)
== payment_attempt.merchant_connector_id.as_ref()
{
existing_label_info = Some(label_info.clone());
}
}
});
let final_label_info = existing_label_info
.ok_or(errors::ApiErrorResponse::GenericNotFoundError {
message: "LabelInformation from ContractBasedRoutingConfig not found"
.to_string(),
})
.attach_printable(
"unable to get LabelInformation from ContractBasedRoutingConfig",
)?;
logger::debug!(
"contract based routing: matched LabelInformation - {:?}",
final_label_info
);
let request_label_info = routing_types::LabelInformation {
label: final_label_info.label.clone(),
target_count: final_label_info.target_count,
target_time: final_label_info.target_time,
mca_id: final_label_info.mca_id.to_owned(),
};
let payment_status_attribute =
get_desired_payment_status_for_dynamic_routing_metrics(payment_attempt.status);
if payment_status_attribute == common_enums::AttemptStatus::Charged {
let event_request = routing_utils::UpdateContractRequestEventRequest {
id: profile_id.get_string_repr().to_string(),
params: "".to_string(),
labels_information: vec![
routing_utils::ContractLabelInformationEventRequest::from(
&request_label_info,
),
],
};
let routing_events_wrapper = routing_utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
state.request_id,
payment_attempt.payment_id.get_string_repr().to_string(),
profile_id.to_owned(),
payment_attempt.merchant_id.to_owned(),
"IntelligentRouter: UpdateContractScore".to_string(),
Some(event_request.clone()),
true,
false,
);
let closure = || async {
let update_response_result = client
.update_contracts(
profile_id.get_string_repr().into(),
vec![request_label_info],
"".to_string(),
vec![],
1,
state.get_grpc_headers(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to update contract based routing window in dynamic routing service",
);
match update_response_result {
Ok(resp) => {
let updated_resp =
routing_utils::UpdateContractEventResponse::try_from(&resp)
.change_context(errors::RoutingError::RoutingEventsError { message: "Unable to convert to UpdateContractEventResponse from UpdateContractResponse".to_string(), status_code: 500 })?;
Ok(Some(updated_resp))
}
Err(err) => {
logger::error!(
"unable to update elimination score in dynamic routing service: {:?}",
err.current_context()
);
// have to refactor errors
Err(error_stack::report!(
errors::RoutingError::ContractScoreUpdationError
))
}
}
};
let events_response = routing_events_wrapper.construct_event_builder( "ContractScoreCalculator.UpdateContract".to_string(),
routing_events::RoutingEngine::IntelligentRouter,
routing_events::ApiMethod::Grpc)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("ContractRouting-Intelligent-Router: Failed to construct RoutingEventsBuilder")?
.trigger_event(state, closure)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("ContractRouting-Intelligent-Router: Failed to update contract scores in Intelligent-Router")?;
let _response: routing_utils::UpdateContractEventResponse = events_response
.response
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"UpdateContractEventResponse not found in RoutingEventResponse",
)?;
let mut routing_event = events_response
.event
.ok_or(errors::RoutingError::RoutingEventsError {
message:
"ContractRouting-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse"
.to_string(),
status_code: 500,
})
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("ContractRouting-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse")?;
routing_event.set_payment_connector(routing_types::RoutableConnectorChoice {
choice_kind: api_models::routing::RoutableChoiceKind::FullStruct,
connector: common_enums::RoutableConnectors::from_str(
final_label_info.label.as_str(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to infer routable_connector from connector")?,
merchant_connector_id: Some(final_label_info.mca_id.clone()),
});
routing_event.set_status_code(200);
state.event_handler().log_event(&routing_event);
}
let contract_based_connectors = routable_connectors
.into_iter()
.filter(|conn| {
conn.merchant_connector_id.clone() == Some(final_label_info.mca_id.clone())
})
.collect::<Vec<_>>();
let contract_scores = client
.calculate_contract_score(
profile_id.get_string_repr().into(),
contract_based_routing_config.clone(),
"".to_string(),
contract_based_connectors,
state.get_grpc_headers(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to calculate/fetch contract scores from dynamic routing service",
)?;
let first_contract_based_connector = &contract_scores
.labels_with_score
.first()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to fetch the first connector from list of connectors obtained from dynamic routing service",
)?;
let (first_contract_based_connector, connector_score, current_payment_cnt) = (first_contract_based_connector.label
.split_once(':')
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!(
"unable to split connector_name and mca_id from the first connector {first_contract_based_connector:?} obtained from dynamic routing service",
))?
.0, first_contract_based_connector.score, first_contract_based_connector.current_count );
core_metrics::DYNAMIC_CONTRACT_BASED_ROUTING.add(
1,
router_env::metric_attributes!(
(
"tenant",
state.tenant.tenant_id.get_string_repr().to_owned(),
),
(
"merchant_profile_id",
format!(
"{}:{}",
payment_attempt.merchant_id.get_string_repr(),
payment_attempt.profile_id.get_string_repr()
),
),
(
"contract_based_routing_connector",
first_contract_based_connector.to_string(),
),
(
"contract_based_routing_connector_score",
connector_score.to_string(),
),
(
"current_payment_count_contract_based_routing_connector",
current_payment_cnt.to_string(),
),
("payment_connector", payment_connector.to_string()),
(
"currency",
payment_attempt
.currency
.map_or_else(|| "None".to_string(), |currency| currency.to_string()),
),
(
"payment_method",
payment_attempt.payment_method.map_or_else(
|| "None".to_string(),
|payment_method| payment_method.to_string(),
),
),
(
"payment_method_type",
payment_attempt.payment_method_type.map_or_else(
|| "None".to_string(),
|payment_method_type| payment_method_type.to_string(),
),
),
(
"capture_method",
payment_attempt.capture_method.map_or_else(
|| "None".to_string(),
|capture_method| capture_method.to_string(),
),
),
(
"authentication_type",
payment_attempt.authentication_type.map_or_else(
|| "None".to_string(),
|authentication_type| authentication_type.to_string(),
),
),
("payment_status", payment_attempt.status.to_string()),
),
);
logger::debug!("successfully pushed contract_based_routing metrics");
Ok(())
} else {
Ok(())
}
} else {
Ok(())
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 181,
"total_crates": null
} |
fn_clm_router_update_window_for_elimination_routing_5169409339312738427 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/routing/helpers
pub async fn update_window_for_elimination_routing(
state: &SessionState,
payment_attempt: &storage::PaymentAttempt,
profile_id: &id_type::ProfileId,
dynamic_algo_ref: routing_types::DynamicRoutingAlgorithmRef,
elimination_routing_configs_params_interpolator: DynamicRoutingConfigParamsInterpolator,
gsm_error_category: common_enums::ErrorCategory,
) -> RouterResult<()> {
if let Some(elimination_algo_ref) = dynamic_algo_ref.elimination_routing_algorithm {
if elimination_algo_ref.enabled_feature != routing_types::DynamicRoutingFeatures::None {
let client = &state
.grpc_client
.dynamic_routing
.as_ref()
.ok_or(errors::ApiErrorResponse::GenericNotFoundError {
message: "dynamic routing gRPC client not found".to_string(),
})?
.elimination_based_client;
let elimination_routing_config = fetch_dynamic_routing_configs::<
routing_types::EliminationRoutingConfig,
>(
state,
profile_id,
elimination_algo_ref
.algorithm_id_with_timestamp
.algorithm_id
.ok_or(errors::ApiErrorResponse::GenericNotFoundError {
message: "elimination routing algorithm_id not found".to_string(),
})
.attach_printable(
"elimination_routing_algorithm_id not found in business_profile",
)?,
)
.await
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "elimination based dynamic routing configs not found".to_string(),
})
.attach_printable("unable to retrieve success_rate based dynamic routing configs")?;
let payment_connector = &payment_attempt.connector.clone().ok_or(
errors::ApiErrorResponse::GenericNotFoundError {
message: "unable to derive payment connector from payment attempt".to_string(),
},
)?;
let elimination_routing_config_params = elimination_routing_configs_params_interpolator
.get_string_val(
elimination_routing_config
.params
.as_ref()
.ok_or(errors::RoutingError::EliminationBasedRoutingParamsNotFoundError)
.change_context(errors::ApiErrorResponse::InternalServerError)?,
);
let labels_with_bucket_name =
vec![routing_types::RoutableConnectorChoiceWithBucketName::new(
routing_types::RoutableConnectorChoice {
choice_kind: api_models::routing::RoutableChoiceKind::FullStruct,
connector: common_enums::RoutableConnectors::from_str(
payment_connector.as_str(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to infer routable_connector from connector")?,
merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
},
gsm_error_category.to_string(),
)];
let event_request = routing_utils::UpdateEliminationBucketEventRequest {
id: profile_id.get_string_repr().to_string(),
params: elimination_routing_config_params.clone(),
labels_with_bucket_name: labels_with_bucket_name
.iter()
.map(|conn_choice| {
routing_utils::LabelWithBucketNameEventRequest::from(conn_choice)
})
.collect(),
config: elimination_routing_config
.elimination_analyser_config
.as_ref()
.map(routing_utils::EliminationRoutingEventBucketConfig::from),
};
let routing_events_wrapper = routing_utils::RoutingEventsWrapper::new(
state.tenant.tenant_id.clone(),
state.request_id,
payment_attempt.payment_id.get_string_repr().to_string(),
profile_id.to_owned(),
payment_attempt.merchant_id.to_owned(),
"IntelligentRouter: UpdateEliminationBucket".to_string(),
Some(event_request.clone()),
true,
false,
);
let closure = || async {
let update_response_result = client
.update_elimination_bucket_config(
profile_id.get_string_repr().to_string(),
elimination_routing_config_params,
labels_with_bucket_name,
elimination_routing_config.elimination_analyser_config,
state.get_grpc_headers(),
)
.await
.change_context(errors::RoutingError::EliminationRoutingCalculationError)
.attach_printable(
"unable to update elimination based routing buckets in dynamic routing service",
);
match update_response_result {
Ok(resp) => {
let updated_resp =
routing_utils::UpdateEliminationBucketEventResponse::try_from(&resp)
.change_context(errors::RoutingError::RoutingEventsError { message: "Unable to convert to UpdateEliminationBucketEventResponse from UpdateEliminationBucketResponse".to_string(), status_code: 500 })?;
Ok(Some(updated_resp))
}
Err(err) => {
logger::error!(
"unable to update elimination score in dynamic routing service: {:?}",
err.current_context()
);
Err(err)
}
}
};
let events_response = routing_events_wrapper.construct_event_builder( "EliminationAnalyser.UpdateEliminationBucket".to_string(),
routing_events::RoutingEngine::IntelligentRouter,
routing_events::ApiMethod::Grpc)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Elimination-Intelligent-Router: Failed to update elimination bucket in Intelligent-Router")?
.trigger_event(state, closure)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Elimination-Intelligent-Router: Failed to update elimination bucket in Intelligent-Router")?;
let _response: routing_utils::UpdateEliminationBucketEventResponse = events_response
.response
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"UpdateEliminationBucketEventResponse not found in RoutingEventResponse",
)?;
let mut routing_event = events_response
.event
.ok_or(errors::RoutingError::RoutingEventsError {
message:
"Elimination-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse"
.to_string(),
status_code: 500,
})
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Elimination-Intelligent-Router: RoutingEvent not found in RoutingEventsResponse")?;
routing_event.set_status_code(200);
routing_event.set_payment_connector(routing_types::RoutableConnectorChoice {
choice_kind: api_models::routing::RoutableChoiceKind::FullStruct,
connector: common_enums::RoutableConnectors::from_str(payment_connector.as_str())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to infer routable_connector from connector")?,
merchant_connector_id: payment_attempt.merchant_connector_id.clone(),
});
state.event_handler().log_event(&routing_event);
Ok(())
} else {
Ok(())
}
} else {
Ok(())
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 141,
"total_crates": null
} |
fn_clm_router_status_code_-6381979949226052871 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/errors/customers_error_response
// Implementation of CustomersErrorResponse for actix_web::ResponseError
fn status_code(&self) -> StatusCode {
common_utils::errors::ErrorSwitch::<api_models::errors::types::ApiErrorResponse>::switch(
self,
)
.status_code()
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 30,
"total_crates": null
} |
fn_clm_router_error_response_-6381979949226052871 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/errors/customers_error_response
// Implementation of CustomersErrorResponse for actix_web::ResponseError
fn error_response(&self) -> actix_web::HttpResponse {
common_utils::errors::ErrorSwitch::<api_models::errors::types::ApiErrorResponse>::switch(
self,
)
.error_response()
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 24,
"total_crates": null
} |
fn_clm_router_switch_-6037560470740856114 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/errors/transformers
// Implementation of ApiErrorResponse for ErrorSwitch<CustomersErrorResponse>
fn switch(&self) -> CustomersErrorResponse {
use CustomersErrorResponse as CER;
match self {
Self::InternalServerError => CER::InternalServerError,
Self::MandateActive => CER::MandateActive,
Self::CustomerNotFound => CER::CustomerNotFound,
_ => CER::InternalServerError,
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 3080,
"total_crates": null
} |
fn_clm_router_switch_4191881459564649410 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/errors/user
// Implementation of UserErrors 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};
let sub_code = "UR";
match self {
Self::InternalServerError => {
AER::InternalServerError(ApiError::new("HE", 0, self.get_error_message(), None))
}
Self::InvalidCredentials => {
AER::Unauthorized(ApiError::new(sub_code, 1, self.get_error_message(), None))
}
Self::UserNotFound => {
AER::Unauthorized(ApiError::new(sub_code, 2, self.get_error_message(), None))
}
Self::UserExists => {
AER::BadRequest(ApiError::new(sub_code, 3, self.get_error_message(), None))
}
Self::LinkInvalid => {
AER::Unauthorized(ApiError::new(sub_code, 4, self.get_error_message(), None))
}
Self::UnverifiedUser => {
AER::Unauthorized(ApiError::new(sub_code, 5, self.get_error_message(), None))
}
Self::InvalidOldPassword => {
AER::BadRequest(ApiError::new(sub_code, 6, self.get_error_message(), None))
}
Self::EmailParsingError => {
AER::BadRequest(ApiError::new(sub_code, 7, self.get_error_message(), None))
}
Self::NameParsingError => {
AER::BadRequest(ApiError::new(sub_code, 8, self.get_error_message(), None))
}
Self::PasswordParsingError => {
AER::BadRequest(ApiError::new(sub_code, 9, self.get_error_message(), None))
}
Self::UserAlreadyVerified => {
AER::Unauthorized(ApiError::new(sub_code, 11, self.get_error_message(), None))
}
Self::CompanyNameParsingError => {
AER::BadRequest(ApiError::new(sub_code, 14, self.get_error_message(), None))
}
Self::MerchantAccountCreationError(_) => AER::InternalServerError(ApiError::new(
sub_code,
15,
self.get_error_message(),
None,
)),
Self::InvalidEmailError => {
AER::BadRequest(ApiError::new(sub_code, 16, self.get_error_message(), None))
}
Self::MerchantIdNotFound => {
AER::BadRequest(ApiError::new(sub_code, 18, self.get_error_message(), None))
}
Self::MetadataAlreadySet => {
AER::BadRequest(ApiError::new(sub_code, 19, self.get_error_message(), None))
}
Self::DuplicateOrganizationId => AER::InternalServerError(ApiError::new(
sub_code,
21,
self.get_error_message(),
None,
)),
Self::InvalidRoleId => {
AER::BadRequest(ApiError::new(sub_code, 22, self.get_error_message(), None))
}
Self::InvalidRoleOperation => {
AER::BadRequest(ApiError::new(sub_code, 23, self.get_error_message(), None))
}
Self::IpAddressParsingFailed => AER::InternalServerError(ApiError::new(
sub_code,
24,
self.get_error_message(),
None,
)),
Self::InvalidMetadataRequest => {
AER::BadRequest(ApiError::new(sub_code, 26, self.get_error_message(), None))
}
Self::MerchantIdParsingError => {
AER::BadRequest(ApiError::new(sub_code, 28, self.get_error_message(), None))
}
Self::ChangePasswordError => {
AER::BadRequest(ApiError::new(sub_code, 29, self.get_error_message(), None))
}
Self::InvalidDeleteOperation => {
AER::BadRequest(ApiError::new(sub_code, 30, self.get_error_message(), None))
}
Self::MaxInvitationsError => {
AER::BadRequest(ApiError::new(sub_code, 31, self.get_error_message(), None))
}
Self::RoleNotFound => {
AER::BadRequest(ApiError::new(sub_code, 32, self.get_error_message(), None))
}
Self::InvalidRoleOperationWithMessage(_) => {
AER::BadRequest(ApiError::new(sub_code, 33, self.get_error_message(), None))
}
Self::RoleNameParsingError => {
AER::BadRequest(ApiError::new(sub_code, 34, self.get_error_message(), None))
}
Self::RoleNameAlreadyExists => {
AER::BadRequest(ApiError::new(sub_code, 35, self.get_error_message(), None))
}
Self::TotpNotSetup => {
AER::BadRequest(ApiError::new(sub_code, 36, self.get_error_message(), None))
}
Self::InvalidTotp => {
AER::BadRequest(ApiError::new(sub_code, 37, self.get_error_message(), None))
}
Self::TotpRequired => {
AER::BadRequest(ApiError::new(sub_code, 38, self.get_error_message(), None))
}
Self::InvalidRecoveryCode => {
AER::BadRequest(ApiError::new(sub_code, 39, self.get_error_message(), None))
}
Self::TwoFactorAuthRequired => {
AER::BadRequest(ApiError::new(sub_code, 40, self.get_error_message(), None))
}
Self::TwoFactorAuthNotSetup => {
AER::BadRequest(ApiError::new(sub_code, 41, self.get_error_message(), None))
}
Self::TotpSecretNotFound => {
AER::BadRequest(ApiError::new(sub_code, 42, self.get_error_message(), None))
}
Self::UserAuthMethodAlreadyExists => {
AER::BadRequest(ApiError::new(sub_code, 43, self.get_error_message(), None))
}
Self::InvalidUserAuthMethodOperation => {
AER::BadRequest(ApiError::new(sub_code, 44, self.get_error_message(), None))
}
Self::AuthConfigParsingError => {
AER::BadRequest(ApiError::new(sub_code, 45, self.get_error_message(), None))
}
Self::SSOFailed => {
AER::BadRequest(ApiError::new(sub_code, 46, self.get_error_message(), None))
}
Self::JwtProfileIdMissing => {
AER::Unauthorized(ApiError::new(sub_code, 47, self.get_error_message(), None))
}
Self::MaxTotpAttemptsReached => {
AER::BadRequest(ApiError::new(sub_code, 48, self.get_error_message(), None))
}
Self::MaxRecoveryCodeAttemptsReached => {
AER::BadRequest(ApiError::new(sub_code, 49, self.get_error_message(), None))
}
Self::ForbiddenTenantId => {
AER::BadRequest(ApiError::new(sub_code, 50, self.get_error_message(), None))
}
Self::ErrorUploadingFile => AER::InternalServerError(ApiError::new(
sub_code,
51,
self.get_error_message(),
None,
)),
Self::ErrorRetrievingFile => AER::InternalServerError(ApiError::new(
sub_code,
52,
self.get_error_message(),
None,
)),
Self::ThemeNotFound => {
AER::NotFound(ApiError::new(sub_code, 53, self.get_error_message(), None))
}
Self::ThemeAlreadyExists => {
AER::BadRequest(ApiError::new(sub_code, 54, self.get_error_message(), None))
}
Self::InvalidThemeLineage(_) => {
AER::BadRequest(ApiError::new(sub_code, 55, self.get_error_message(), None))
}
Self::MissingEmailConfig => {
AER::BadRequest(ApiError::new(sub_code, 56, self.get_error_message(), None))
}
Self::InvalidAuthMethodOperationWithMessage(_) => {
AER::BadRequest(ApiError::new(sub_code, 57, self.get_error_message(), None))
}
Self::InvalidCloneConnectorOperation(_) => {
AER::BadRequest(ApiError::new(sub_code, 58, self.get_error_message(), None))
}
Self::ErrorCloningConnector(_) => AER::InternalServerError(ApiError::new(
sub_code,
59,
self.get_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": 3398,
"total_crates": null
} |
fn_clm_router_get_error_message_4191881459564649410 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/errors/user
// Implementation of None for UserErrors
pub fn get_error_message(&self) -> String {
match self {
Self::InternalServerError => "Something went wrong".to_string(),
Self::InvalidCredentials => "Incorrect email or password".to_string(),
Self::UserNotFound => "Email doesn’t exist. Register".to_string(),
Self::UserExists => "An account already exists with this email".to_string(),
Self::LinkInvalid => "Invalid or expired link".to_string(),
Self::UnverifiedUser => "Kindly verify your account".to_string(),
Self::InvalidOldPassword => {
"Old password incorrect. Please enter the correct password".to_string()
}
Self::EmailParsingError => "Invalid Email".to_string(),
Self::NameParsingError => "Invalid Name".to_string(),
Self::PasswordParsingError => "Invalid Password".to_string(),
Self::UserAlreadyVerified => "User already verified".to_string(),
Self::CompanyNameParsingError => "Invalid Company Name".to_string(),
Self::MerchantAccountCreationError(error_message) => error_message.to_string(),
Self::InvalidEmailError => "Invalid Email".to_string(),
Self::MerchantIdNotFound => "Invalid Merchant ID".to_string(),
Self::MetadataAlreadySet => "Metadata already set".to_string(),
Self::DuplicateOrganizationId => {
"An Organization with the id already exists".to_string()
}
Self::InvalidRoleId => "Invalid Role ID".to_string(),
Self::InvalidRoleOperation => "User Role Operation Not Supported".to_string(),
Self::IpAddressParsingFailed => "Something went wrong".to_string(),
Self::InvalidMetadataRequest => "Invalid Metadata Request".to_string(),
Self::MerchantIdParsingError => "Invalid Merchant Id".to_string(),
Self::ChangePasswordError => "Old and new password cannot be same".to_string(),
Self::InvalidDeleteOperation => "Delete Operation Not Supported".to_string(),
Self::MaxInvitationsError => "Maximum invite count per request exceeded".to_string(),
Self::RoleNotFound => "Role Not Found".to_string(),
Self::InvalidRoleOperationWithMessage(error_message) => error_message.to_string(),
Self::RoleNameParsingError => "Invalid Role Name".to_string(),
Self::RoleNameAlreadyExists => "Role name already exists".to_string(),
Self::TotpNotSetup => "TOTP not setup".to_string(),
Self::InvalidTotp => "Invalid TOTP".to_string(),
Self::TotpRequired => "TOTP required".to_string(),
Self::InvalidRecoveryCode => "Invalid Recovery Code".to_string(),
Self::MaxTotpAttemptsReached => "Maximum attempts reached for TOTP".to_string(),
Self::MaxRecoveryCodeAttemptsReached => {
"Maximum attempts reached for Recovery Code".to_string()
}
Self::TwoFactorAuthRequired => "Two factor auth required".to_string(),
Self::TwoFactorAuthNotSetup => "Two factor auth not setup".to_string(),
Self::TotpSecretNotFound => "TOTP secret not found".to_string(),
Self::UserAuthMethodAlreadyExists => "User auth method already exists".to_string(),
Self::InvalidUserAuthMethodOperation => {
"Invalid user auth method operation".to_string()
}
Self::AuthConfigParsingError => "Auth config parsing error".to_string(),
Self::SSOFailed => "Invalid SSO request".to_string(),
Self::JwtProfileIdMissing => "profile_id missing in JWT".to_string(),
Self::ForbiddenTenantId => "Forbidden tenant id".to_string(),
Self::ErrorUploadingFile => "Error Uploading file to Theme Storage".to_string(),
Self::ErrorRetrievingFile => "Error Retrieving file from Theme Storage".to_string(),
Self::ThemeNotFound => "Theme not found".to_string(),
Self::ThemeAlreadyExists => "Theme with lineage already exists".to_string(),
Self::InvalidThemeLineage(field_name) => {
format!("Invalid field: {field_name} in lineage")
}
Self::MissingEmailConfig => "Missing required field: email_config".to_string(),
Self::InvalidAuthMethodOperationWithMessage(operation) => {
format!("Invalid Auth Method Operation: {operation}")
}
Self::InvalidCloneConnectorOperation(operation) => {
format!("Invalid Clone Connector Operation: {operation}")
}
Self::ErrorCloningConnector(error_message) => {
format!("Error cloning connector: {error_message}")
}
}
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 302,
"total_crates": null
} |
fn_clm_router_custom_error_handlers_-6577430622084457898 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/errors/error_handlers
pub fn custom_error_handlers<B: body::MessageBody + 'static>(
res: ServiceResponse<B>,
) -> actix_web::Result<ErrorHandlerResponse<B>> {
let error_response = match res.status() {
StatusCode::NOT_FOUND => ApiErrorResponse::InvalidRequestUrl,
StatusCode::METHOD_NOT_ALLOWED => ApiErrorResponse::InvalidHttpMethod,
_ => ApiErrorResponse::InternalServerError,
};
let (req, res) = res.into_parts();
logger::warn!(error_response=?res);
let res = match res.error() {
Some(_) => res.map_into_boxed_body(),
None => error_response.error_response(),
};
let res = ServiceResponse::new(req, res)
.map_into_boxed_body()
.map_into_right_body();
Ok(ErrorHandlerResponse::Response(res))
}
| {
"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_to_not_found_response_-6122081867085758514 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/errors/utils
// Implementation of error_stack::Result<T, errors::StorageError> for StorageErrorExt<T, errors::UserErrors>
fn to_not_found_response(
self,
not_found_response: errors::UserErrors,
) -> error_stack::Result<T, errors::UserErrors> {
self.map_err(|e| {
if e.current_context().is_db_not_found() {
e.change_context(not_found_response)
} else {
e.change_context(errors::UserErrors::InternalServerError)
}
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 1470,
"total_crates": null
} |
fn_clm_router_to_payment_failed_response_-6122081867085758514 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/errors/utils
// Implementation of error_stack::Result<T, errors::ConnectorError> for ConnectorErrorExt<T>
fn to_payment_failed_response(self) -> error_stack::Result<T, errors::ApiErrorResponse> {
self.map_err(|err| {
let error = match err.current_context() {
errors::ConnectorError::ProcessingStepFailed(Some(bytes)) => {
let response_str = std::str::from_utf8(bytes);
let data = match response_str {
Ok(s) => serde_json::from_str(s)
.map_err(
|error| logger::error!(%error,"Failed to convert response to JSON"),
)
.ok(),
Err(error) => {
logger::error!(%error,"Failed to convert response to UTF8 string");
None
}
};
errors::ApiErrorResponse::PaymentAuthorizationFailed { data }
}
errors::ConnectorError::MissingRequiredField { field_name } => {
errors::ApiErrorResponse::MissingRequiredField { field_name }
}
errors::ConnectorError::MissingRequiredFields { field_names } => {
errors::ApiErrorResponse::MissingRequiredFields { field_names: field_names.to_vec() }
}
errors::ConnectorError::NotImplemented(reason) => {
errors::ApiErrorResponse::NotImplemented {
message: errors::NotImplementedMessage::Reason(
reason.to_string(),
),
}
}
errors::ConnectorError::MismatchedPaymentData => {
errors::ApiErrorResponse::InvalidDataValue {
field_name:
"payment_method_data, payment_method_type and payment_experience does not match",
}
},
errors::ConnectorError::MandatePaymentDataMismatch {fields}=> {
errors::ApiErrorResponse::MandatePaymentDataMismatch {
fields: fields.to_owned(),
}
},
errors::ConnectorError::NotSupported { message, connector } => {
errors::ApiErrorResponse::NotSupported { message: format!("{message} is not supported by {connector}") }
},
errors::ConnectorError::FlowNotSupported{ flow, connector } => {
errors::ApiErrorResponse::FlowNotSupported { flow: flow.to_owned(), connector: connector.to_owned() }
},
errors::ConnectorError::MaxFieldLengthViolated{ connector, field_name, max_length, received_length} => {
errors::ApiErrorResponse::MaxFieldLengthViolated { connector: connector.to_string(), field_name: field_name.to_string(), max_length: *max_length, received_length: *received_length }
},
errors::ConnectorError::InvalidDataFormat { field_name } => {
errors::ApiErrorResponse::InvalidDataValue { field_name }
},
errors::ConnectorError::CaptureMethodNotSupported => {
errors::ApiErrorResponse::NotSupported {
message: "Capture Method Not Supported".to_owned(),
}
}
errors::ConnectorError::InvalidWalletToken {wallet_name} => errors::ApiErrorResponse::InvalidWalletToken {wallet_name: wallet_name.to_string()},
errors::ConnectorError::CurrencyNotSupported { message, connector} => errors::ApiErrorResponse::CurrencyNotSupported { message: format!("Credentials for the currency {message} are not configured with the connector {connector}/hyperswitch") },
errors::ConnectorError::FailedToObtainAuthType => errors::ApiErrorResponse::InvalidConnectorConfiguration {config: "connector_account_details".to_string()},
errors::ConnectorError::InvalidConnectorConfig { config } => errors::ApiErrorResponse::InvalidConnectorConfiguration { config: config.to_string() },
errors::ConnectorError::FailedToObtainIntegrationUrl |
errors::ConnectorError::RequestEncodingFailed |
errors::ConnectorError::RequestEncodingFailedWithReason(_) |
errors::ConnectorError::ParsingFailed |
errors::ConnectorError::ResponseDeserializationFailed |
errors::ConnectorError::UnexpectedResponseError(_) |
errors::ConnectorError::RoutingRulesParsingError |
errors::ConnectorError::FailedToObtainPreferredConnector |
errors::ConnectorError::InvalidConnectorName |
errors::ConnectorError::InvalidWallet |
errors::ConnectorError::ResponseHandlingFailed |
errors::ConnectorError::FailedToObtainCertificate |
errors::ConnectorError::NoConnectorMetaData | errors::ConnectorError::NoConnectorWalletDetails |
errors::ConnectorError::FailedToObtainCertificateKey |
errors::ConnectorError::MissingConnectorMandateID |
errors::ConnectorError::MissingConnectorMandateMetadata |
errors::ConnectorError::MissingConnectorTransactionID |
errors::ConnectorError::MissingConnectorRefundID |
errors::ConnectorError::MissingApplePayTokenData |
errors::ConnectorError::WebhooksNotImplemented |
errors::ConnectorError::WebhookBodyDecodingFailed |
errors::ConnectorError::WebhookSignatureNotFound |
errors::ConnectorError::WebhookSourceVerificationFailed |
errors::ConnectorError::WebhookVerificationSecretNotFound |
errors::ConnectorError::WebhookVerificationSecretInvalid |
errors::ConnectorError::WebhookReferenceIdNotFound |
errors::ConnectorError::WebhookEventTypeNotFound |
errors::ConnectorError::WebhookResourceObjectNotFound |
errors::ConnectorError::WebhookResponseEncodingFailed |
errors::ConnectorError::InvalidDateFormat |
errors::ConnectorError::DateFormattingFailed |
errors::ConnectorError::MissingConnectorRelatedTransactionID { .. } |
errors::ConnectorError::FileValidationFailed { .. } |
errors::ConnectorError::MissingConnectorRedirectionPayload { .. } |
errors::ConnectorError::FailedAtConnector { .. } |
errors::ConnectorError::MissingPaymentMethodType |
errors::ConnectorError::InSufficientBalanceInPaymentMethod |
errors::ConnectorError::RequestTimeoutReceived |
errors::ConnectorError::ProcessingStepFailed(None)|
errors::ConnectorError::GenericError {..} |
errors::ConnectorError::AmountConversionFailed => errors::ApiErrorResponse::InternalServerError
};
err.change_context(error)
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 202,
"total_crates": null
} |
fn_clm_router_to_duplicate_response_-6122081867085758514 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/errors/utils
// Implementation of error_stack::Result<T, errors::StorageError> for StorageErrorExt<T, errors::UserErrors>
fn to_duplicate_response(
self,
duplicate_response: errors::UserErrors,
) -> error_stack::Result<T, errors::UserErrors> {
self.map_err(|e| {
if e.current_context().is_db_unique_violation() {
e.change_context(duplicate_response)
} else {
e.change_context(errors::UserErrors::InternalServerError)
}
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 135,
"total_crates": null
} |
fn_clm_router_to_refund_failed_response_-6122081867085758514 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/errors/utils
// Implementation of error_stack::Result<T, errors::ConnectorError> for ConnectorErrorExt<T>
fn to_refund_failed_response(self) -> error_stack::Result<T, errors::ApiErrorResponse> {
self.map_err(|err| match err.current_context() {
errors::ConnectorError::ProcessingStepFailed(Some(bytes)) => {
let response_str = std::str::from_utf8(bytes);
let data = match response_str {
Ok(s) => serde_json::from_str(s)
.map_err(
|error| logger::error!(%error,"Failed to convert response to JSON"),
)
.ok(),
Err(error) => {
logger::error!(%error,"Failed to convert response to UTF8 string");
None
}
};
err.change_context(errors::ApiErrorResponse::RefundFailed { data })
}
errors::ConnectorError::NotImplemented(reason) => {
errors::ApiErrorResponse::NotImplemented {
message: errors::NotImplementedMessage::Reason(reason.to_string()),
}
.into()
}
errors::ConnectorError::NotSupported { message, connector } => {
errors::ApiErrorResponse::NotSupported {
message: format!("{message} is not supported by {connector}"),
}
.into()
}
errors::ConnectorError::CaptureMethodNotSupported => {
errors::ApiErrorResponse::NotSupported {
message: "Capture Method Not Supported".to_owned(),
}
.into()
}
errors::ConnectorError::FailedToObtainIntegrationUrl
| errors::ConnectorError::RequestEncodingFailed
| errors::ConnectorError::RequestEncodingFailedWithReason(_)
| errors::ConnectorError::ParsingFailed
| errors::ConnectorError::ResponseDeserializationFailed
| errors::ConnectorError::UnexpectedResponseError(_)
| errors::ConnectorError::RoutingRulesParsingError
| errors::ConnectorError::FailedToObtainPreferredConnector
| errors::ConnectorError::ProcessingStepFailed(_)
| errors::ConnectorError::InvalidConnectorName
| errors::ConnectorError::InvalidWallet
| errors::ConnectorError::ResponseHandlingFailed
| errors::ConnectorError::MissingRequiredField { .. }
| errors::ConnectorError::MissingRequiredFields { .. }
| errors::ConnectorError::FailedToObtainAuthType
| errors::ConnectorError::FailedToObtainCertificate
| errors::ConnectorError::NoConnectorMetaData
| errors::ConnectorError::NoConnectorWalletDetails
| errors::ConnectorError::FailedToObtainCertificateKey
| errors::ConnectorError::MaxFieldLengthViolated { .. }
| errors::ConnectorError::FlowNotSupported { .. }
| errors::ConnectorError::MissingConnectorMandateID
| errors::ConnectorError::MissingConnectorMandateMetadata
| errors::ConnectorError::MissingConnectorTransactionID
| errors::ConnectorError::MissingConnectorRefundID
| errors::ConnectorError::MissingApplePayTokenData
| errors::ConnectorError::WebhooksNotImplemented
| errors::ConnectorError::WebhookBodyDecodingFailed
| errors::ConnectorError::WebhookSignatureNotFound
| errors::ConnectorError::WebhookSourceVerificationFailed
| errors::ConnectorError::WebhookVerificationSecretNotFound
| errors::ConnectorError::WebhookVerificationSecretInvalid
| errors::ConnectorError::WebhookReferenceIdNotFound
| errors::ConnectorError::WebhookEventTypeNotFound
| errors::ConnectorError::WebhookResourceObjectNotFound
| errors::ConnectorError::WebhookResponseEncodingFailed
| errors::ConnectorError::InvalidDateFormat
| errors::ConnectorError::DateFormattingFailed
| errors::ConnectorError::InvalidDataFormat { .. }
| errors::ConnectorError::MismatchedPaymentData
| errors::ConnectorError::MandatePaymentDataMismatch { .. }
| errors::ConnectorError::InvalidWalletToken { .. }
| errors::ConnectorError::MissingConnectorRelatedTransactionID { .. }
| errors::ConnectorError::FileValidationFailed { .. }
| errors::ConnectorError::MissingConnectorRedirectionPayload { .. }
| errors::ConnectorError::FailedAtConnector { .. }
| errors::ConnectorError::MissingPaymentMethodType
| errors::ConnectorError::InSufficientBalanceInPaymentMethod
| errors::ConnectorError::RequestTimeoutReceived
| errors::ConnectorError::CurrencyNotSupported { .. }
| errors::ConnectorError::InvalidConnectorConfig { .. }
| errors::ConnectorError::AmountConversionFailed
| errors::ConnectorError::GenericError { .. } => {
err.change_context(errors::ApiErrorResponse::RefundFailed { data: None })
}
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 60,
"total_crates": null
} |
fn_clm_router_to_payout_failed_response_-6122081867085758514 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/errors/utils
// Implementation of error_stack::Result<T, errors::ConnectorError> for ConnectorErrorExt<T>
fn to_payout_failed_response(self) -> error_stack::Result<T, errors::ApiErrorResponse> {
self.map_err(|err| {
let error = match err.current_context() {
errors::ConnectorError::ProcessingStepFailed(Some(bytes)) => {
let response_str = std::str::from_utf8(bytes);
let data = match response_str {
Ok(s) => serde_json::from_str(s)
.map_err(
|error| logger::error!(%error,"Failed to convert response to JSON"),
)
.ok(),
Err(error) => {
logger::error!(%error,"Failed to convert response to UTF8 string");
None
}
};
errors::ApiErrorResponse::PayoutFailed { data }
}
errors::ConnectorError::MissingRequiredField { field_name } => {
errors::ApiErrorResponse::MissingRequiredField { field_name }
}
errors::ConnectorError::MissingRequiredFields { field_names } => {
errors::ApiErrorResponse::MissingRequiredFields {
field_names: field_names.to_vec(),
}
}
errors::ConnectorError::NotSupported { message, connector } => {
errors::ApiErrorResponse::NotSupported {
message: format!("{message} by {connector}"),
}
}
errors::ConnectorError::NotImplemented(reason) => {
errors::ApiErrorResponse::NotImplemented {
message: errors::NotImplementedMessage::Reason(reason.to_string()),
}
}
errors::ConnectorError::InvalidConnectorConfig { config } => {
errors::ApiErrorResponse::InvalidConnectorConfiguration {
config: config.to_string(),
}
}
_ => errors::ApiErrorResponse::InternalServerError,
};
err.change_context(error)
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 51,
"total_crates": null
} |
fn_clm_router_switch_6395490519417150562 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/errors/chat
// Implementation of ChatErrors 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};
let sub_code = "AI";
match self {
Self::InternalServerError => {
AER::InternalServerError(ApiError::new("HE", 0, self.get_error_message(), None))
}
Self::MissingConfigError => {
AER::InternalServerError(ApiError::new(sub_code, 1, self.get_error_message(), None))
}
Self::ChatResponseDeserializationFailed => {
AER::BadRequest(ApiError::new(sub_code, 2, self.get_error_message(), None))
}
Self::UnauthorizedAccess => {
AER::Unauthorized(ApiError::new(sub_code, 3, self.get_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": 3104,
"total_crates": null
} |
fn_clm_router_get_error_message_6395490519417150562 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/errors/chat
// Inherent implementation for ChatErrors
pub fn get_error_message(&self) -> String {
match self {
Self::InternalServerError => "Something went wrong".to_string(),
Self::MissingConfigError => "Missing webhook url".to_string(),
Self::ChatResponseDeserializationFailed => "Failed to parse chat response".to_string(),
Self::UnauthorizedAccess => "Not authorized to access the resource".to_string(),
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 212,
"total_crates": null
} |
fn_clm_router_switch_3747860481632465845 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/errors/user/sample_data
// Implementation of SampleDataError for ErrorSwitch<ApiErrorResponse>
fn switch(&self) -> ApiErrorResponse {
match self {
Self::InternalServerError => ApiErrorResponse::InternalServerError(ApiError::new(
"SD",
0,
"Something went wrong",
None,
)),
Self::DataDoesNotExist => ApiErrorResponse::NotFound(ApiError::new(
"SD",
1,
"Sample Data not present for given request",
None,
)),
Self::InvalidParameters => ApiErrorResponse::BadRequest(ApiError::new(
"SD",
2,
"Invalid parameters to generate Sample Data",
None,
)),
Self::InvalidRange => ApiErrorResponse::BadRequest(ApiError::new(
"SD",
3,
"Records to be generated should be between range 10 and 100",
None,
)),
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 3096,
"total_crates": null
} |
fn_clm_router_switch_from_3747860481632465845 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/errors/user/sample_data
// Implementation of SampleDataError for ErrorSwitchFrom<StorageError>
fn switch_from(error: &StorageError) -> Self {
match matches!(error, StorageError::ValueNotFound(_)) {
true => Self::DataDoesNotExist,
false => Self::InternalServerError,
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 11,
"total_crates": null
} |
fn_clm_router_construct_relay_refund_router_data_-9121742063140104205 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/relay/utils
pub async fn construct_relay_refund_router_data<F>(
state: &SessionState,
merchant_id: &id_type::MerchantId,
connector_account: &domain::MerchantConnectorAccount,
relay_record: &hyperswitch_domain_models::relay::Relay,
) -> RouterResult<types::RefundsRouterData<F>> {
let connector_auth_type = connector_account
.get_connector_account_details()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while parsing value for ConnectorAuthType")?;
#[cfg(feature = "v2")]
let connector_name = &connector_account.connector_name.to_string();
#[cfg(feature = "v1")]
let connector_name = &connector_account.connector_name;
let webhook_url = Some(payments::helpers::create_webhook_url(
&state.base_url.clone(),
merchant_id,
connector_account.get_id().get_string_repr(),
));
let supported_connector = &state
.conf
.multiple_api_version_supported_connectors
.supported_connectors;
let connector_enum = api_models::enums::Connector::from_str(connector_name)
.change_context(errors::ConnectorError::InvalidConnectorName)
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "connector",
})
.attach_printable_lazy(|| format!("unable to parse connector name {connector_name:?}"))?;
let connector_api_version = if supported_connector.contains(&connector_enum) {
state
.store
.find_config_by_key(&format!("connector_api_version_{connector_name}"))
.await
.map(|value| value.config)
.ok()
} else {
None
};
let hyperswitch_domain_models::relay::RelayData::Refund(relay_refund_data) = relay_record
.request_data
.clone()
.get_required_value("refund relay data")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to obtain relay data to construct relay refund data")?;
let relay_id_string = relay_record.id.get_string_repr().to_string();
let router_data = hyperswitch_domain_models::router_data::RouterData {
flow: std::marker::PhantomData,
merchant_id: merchant_id.clone(),
customer_id: None,
tenant_id: state.tenant.tenant_id.clone(),
connector: connector_name.to_string(),
payment_id: IRRELEVANT_PAYMENT_INTENT_ID.to_string(),
attempt_id: IRRELEVANT_PAYMENT_ATTEMPT_ID.to_string(),
status: common_enums::AttemptStatus::Charged,
payment_method: common_enums::PaymentMethod::default(),
payment_method_type: None,
connector_auth_type,
description: None,
address: hyperswitch_domain_models::payment_address::PaymentAddress::default(),
auth_type: common_enums::AuthenticationType::default(),
connector_meta_data: connector_account.metadata.clone(),
connector_wallets_details: None,
amount_captured: None,
payment_method_status: None,
minor_amount_captured: None,
request: hyperswitch_domain_models::router_request_types::RefundsData {
refund_id: relay_id_string.clone(),
connector_transaction_id: relay_record.connector_resource_id.clone(),
refund_amount: relay_refund_data.amount.get_amount_as_i64(),
minor_refund_amount: relay_refund_data.amount,
currency: relay_refund_data.currency,
payment_amount: relay_refund_data.amount.get_amount_as_i64(),
minor_payment_amount: relay_refund_data.amount,
webhook_url,
connector_metadata: None,
refund_connector_metadata: None,
reason: relay_refund_data.reason,
connector_refund_id: relay_record.connector_reference_id.clone(),
browser_info: None,
split_refunds: None,
integrity_object: None,
refund_status: common_enums::RefundStatus::from(relay_record.status),
merchant_account_id: None,
merchant_config_currency: None,
capture_method: None,
additional_payment_method_data: None,
},
response: Err(ErrorResponse::default()),
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
connector_customer: None,
recurring_mandate_payment_data: None,
preprocessing_id: None,
connector_request_reference_id: relay_id_string.clone(),
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
test_mode: connector_account.get_connector_test_mode(),
payment_method_balance: None,
connector_api_version,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
refund_id: Some(relay_id_string),
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload: None,
connector_mandate_request_reference_id: None,
authentication_id: None,
psd2_sca_exemption_type: None,
raw_connector_response: None,
is_payment_id_from_merchant: None,
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
};
Ok(router_data)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 96,
"total_crates": null
} |
fn_clm_router_foreign_from_7132040897424201564 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/outgoing_v2
// Implementation of outgoing_webhook_logs::OutgoingWebhookEventContent for ForeignFrom<storage::EventMetadata>
fn foreign_from(event_metadata: storage::EventMetadata) -> Self {
match event_metadata {
diesel_models::EventMetadata::Payment { payment_id } => Self::Payment {
payment_id,
content: serde_json::Value::Null,
},
diesel_models::EventMetadata::Payout { payout_id } => Self::Payout {
payout_id,
content: serde_json::Value::Null,
},
diesel_models::EventMetadata::Refund {
payment_id,
refund_id,
} => Self::Refund {
payment_id,
refund_id,
content: serde_json::Value::Null,
},
diesel_models::EventMetadata::Dispute {
payment_id,
attempt_id,
dispute_id,
} => Self::Dispute {
payment_id,
attempt_id,
dispute_id,
content: serde_json::Value::Null,
},
diesel_models::EventMetadata::Mandate {
payment_method_id,
mandate_id,
} => Self::Mandate {
payment_method_id,
mandate_id,
content: serde_json::Value::Null,
},
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 212,
"total_crates": null
} |
fn_clm_router_create_event_and_trigger_outgoing_webhook_7132040897424201564 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/outgoing_v2
pub(crate) async fn create_event_and_trigger_outgoing_webhook(
state: SessionState,
business_profile: domain::Profile,
merchant_key_store: &domain::MerchantKeyStore,
event_type: enums::EventType,
event_class: enums::EventClass,
primary_object_id: String,
primary_object_type: enums::EventObjectType,
content: api::OutgoingWebhookContent,
primary_object_created_at: time::PrimitiveDateTime,
) -> CustomResult<(), errors::ApiErrorResponse> {
let delivery_attempt = enums::WebhookDeliveryAttempt::InitialAttempt;
let idempotent_event_id =
utils::get_idempotent_event_id(&primary_object_id, event_type, delivery_attempt)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to generate idempotent event ID")?;
let webhook_url_result = business_profile
.get_webhook_url_from_profile()
.change_context(errors::WebhooksFlowError::MerchantWebhookUrlNotConfigured);
if utils::is_outgoing_webhook_disabled(
&state,
&webhook_url_result,
&business_profile,
&idempotent_event_id,
) {
return Ok(());
}
let event_id = utils::generate_event_id();
let merchant_id = business_profile.merchant_id.clone();
let now = common_utils::date_time::now();
let outgoing_webhook = api::OutgoingWebhook {
merchant_id: merchant_id.clone(),
event_id: event_id.clone(),
event_type,
content: content.clone(),
timestamp: now,
};
let request_content = get_outgoing_webhook_request(outgoing_webhook, &business_profile)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to construct outgoing webhook request content")?;
let event_metadata = storage::EventMetadata::foreign_from(&content);
let key_manager_state = &(&state).into();
let new_event = domain::Event {
event_id: event_id.clone(),
event_type,
event_class,
is_webhook_notified: false,
primary_object_id,
primary_object_type,
created_at: now,
merchant_id: Some(business_profile.merchant_id.clone()),
business_profile_id: Some(business_profile.get_id().to_owned()),
primary_object_created_at: Some(primary_object_created_at),
idempotent_event_id: Some(idempotent_event_id.clone()),
initial_attempt_id: Some(event_id.clone()),
request: Some(
crypto_operation(
key_manager_state,
type_name!(domain::Event),
CryptoOperation::Encrypt(
ext_traits::Encode::encode_to_string_of_json(&request_content)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to encode outgoing webhook request content")
.map(masking::Secret::new)?,
),
keymanager::Identifier::Merchant(merchant_key_store.merchant_id.clone()),
masking::PeekInterface::peek(merchant_key_store.key.get_inner()),
)
.await
.and_then(|val| val.try_into_operation())
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to encrypt outgoing webhook request content")?,
),
response: None,
delivery_attempt: Some(delivery_attempt),
metadata: Some(event_metadata),
is_overall_delivery_successful: Some(false),
};
let event_insert_result = state
.store
.insert_event(key_manager_state, new_event, merchant_key_store)
.await;
let event = match event_insert_result {
Ok(event) => Ok(event),
Err(error) => {
if error.current_context().is_db_unique_violation() {
// If the event_id already exists in the database, it indicates that the event for the resource has already been sent, so we skip the flow
logger::debug!("Event with idempotent ID `{idempotent_event_id}` already exists in the database");
return Ok(());
} else {
logger::error!(event_insertion_failure=?error);
Err(error
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to insert event in events table"))
}
}
}?;
let cloned_key_store = merchant_key_store.clone();
// Using a tokio spawn here and not arbiter because not all caller of this function
// may have an actix arbiter
tokio::spawn(
async move {
Box::pin(trigger_webhook_and_raise_event(
state,
business_profile,
&cloned_key_store,
event,
request_content,
delivery_attempt,
Some(content),
))
.await;
}
.in_current_span(),
);
Ok(())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 143,
"total_crates": null
} |
fn_clm_router_get_outgoing_webhook_request_7132040897424201564 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/outgoing_v2
pub(crate) fn get_outgoing_webhook_request(
outgoing_webhook: api::OutgoingWebhook,
business_profile: &domain::Profile,
) -> CustomResult<webhook_events::OutgoingWebhookRequestContent, errors::WebhooksFlowError> {
#[inline]
fn get_outgoing_webhook_request_inner<WebhookType: types::OutgoingWebhookType>(
outgoing_webhook: api::OutgoingWebhook,
business_profile: &domain::Profile,
) -> CustomResult<webhook_events::OutgoingWebhookRequestContent, errors::WebhooksFlowError>
{
let mut headers = vec![
(
reqwest::header::CONTENT_TYPE.to_string(),
mime::APPLICATION_JSON.essence_str().into(),
),
(
reqwest::header::USER_AGENT.to_string(),
consts::USER_AGENT.to_string().into(),
),
];
let transformed_outgoing_webhook = WebhookType::from(outgoing_webhook);
let payment_response_hash_key = business_profile.payment_response_hash_key.clone();
let custom_headers = business_profile
.outgoing_webhook_custom_http_headers
.clone()
.map(|headers| {
ext_traits::ValueExt::parse_value::<HashMap<String, String>>(
masking::ExposeInterface::expose(headers.into_inner()),
"HashMap<String,String>",
)
.change_context(errors::WebhooksFlowError::OutgoingWebhookEncodingFailed)
.attach_printable("Failed to deserialize outgoing webhook custom HTTP headers")
})
.transpose()?;
if let Some(ref map) = custom_headers {
headers.extend(
map.iter()
.map(|(key, value)| (key.clone(), masking::Mask::into_masked(value.clone()))),
);
};
let outgoing_webhooks_signature = transformed_outgoing_webhook
.get_outgoing_webhooks_signature(payment_response_hash_key)?;
if let Some(signature) = outgoing_webhooks_signature.signature {
WebhookType::add_webhook_header(&mut headers, signature)
}
Ok(webhook_events::OutgoingWebhookRequestContent {
body: outgoing_webhooks_signature.payload,
headers: headers
.into_iter()
.map(|(name, value)| (name, masking::Secret::new(value.into_inner())))
.collect(),
})
}
get_outgoing_webhook_request_inner::<webhooks::OutgoingWebhook>(
outgoing_webhook,
business_profile,
)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 60,
"total_crates": null
} |
fn_clm_router_raise_webhooks_analytics_event_7132040897424201564 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/outgoing_v2
async fn raise_webhooks_analytics_event(
state: SessionState,
trigger_webhook_result: CustomResult<
(domain::Event, Option<Report<errors::WebhooksFlowError>>),
errors::WebhooksFlowError,
>,
content: Option<api::OutgoingWebhookContent>,
merchant_id: common_utils::id_type::MerchantId,
fallback_event: domain::Event,
) {
let (updated_event, optional_error) = match trigger_webhook_result {
Ok((updated_event, error)) => (updated_event, error),
Err(error) => (fallback_event, Some(error)),
};
let error = optional_error.and_then(|error| {
logger::error!(?error, "Failed to send webhook to merchant");
serde_json::to_value(error.current_context())
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.inspect_err(|error| {
logger::error!(?error, "Failed to serialize outgoing webhook error as JSON");
})
.ok()
});
let outgoing_webhook_event_content = content
.as_ref()
.and_then(
outgoing_webhook_logs::OutgoingWebhookEventMetric::get_outgoing_webhook_event_content,
)
.or_else(|| {
updated_event
.metadata
.map(outgoing_webhook_logs::OutgoingWebhookEventContent::foreign_from)
});
// Get status_code from webhook response
let status_code = {
let webhook_response: Option<webhook_events::OutgoingWebhookResponseContent> =
updated_event.response.and_then(|res| {
ext_traits::StringExt::parse_struct(
masking::PeekInterface::peek(res.get_inner()),
"OutgoingWebhookResponseContent",
)
.map_err(|error| {
logger::error!(?error, "Error deserializing webhook response");
error
})
.ok()
});
webhook_response.and_then(|res| res.status_code)
};
let webhook_event = outgoing_webhook_logs::OutgoingWebhookEvent::new(
state.tenant.tenant_id.clone(),
merchant_id,
updated_event.event_id,
updated_event.event_type,
outgoing_webhook_event_content,
error,
updated_event.initial_attempt_id,
status_code,
updated_event.delivery_attempt,
);
state.event_handler().log_event(&webhook_event);
}
| {
"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_update_event_in_storage_7132040897424201564 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/outgoing_v2
async fn update_event_in_storage(
state: SessionState,
is_webhook_notified: bool,
outgoing_webhook_response: webhook_events::OutgoingWebhookResponseContent,
merchant_key_store: domain::MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
) -> CustomResult<domain::Event, errors::WebhooksFlowError> {
let key_manager_state = &(&state).into();
let event_update = domain::EventUpdate::UpdateResponse {
is_webhook_notified,
response: Some(
crypto_operation(
key_manager_state,
type_name!(domain::Event),
CryptoOperation::Encrypt(
ext_traits::Encode::encode_to_string_of_json(&outgoing_webhook_response)
.change_context(
errors::WebhooksFlowError::OutgoingWebhookResponseEncodingFailed,
)
.map(masking::Secret::new)?,
),
keymanager::Identifier::Merchant(merchant_key_store.merchant_id.clone()),
masking::PeekInterface::peek(merchant_key_store.key.get_inner()),
)
.await
.and_then(|val| val.try_into_operation())
.change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)
.attach_printable("Failed to encrypt outgoing webhook response content")?,
),
};
state
.store
.update_event_by_merchant_id_event_id(
key_manager_state,
merchant_id,
event_id,
event_update,
&merchant_key_store,
)
.await
.change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)
}
| {
"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_outgoing_webhook_response_content_6523092487668576888 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/types
// Inherent implementation for WebhookResponse
pub async fn get_outgoing_webhook_response_content(
self,
) -> webhook_events::OutgoingWebhookResponseContent {
let status_code = self.response.status();
let response_headers = self
.response
.headers()
.iter()
.map(|(name, value)| {
(
name.as_str().to_owned(),
value
.to_str()
.map(|s| Secret::from(String::from(s)))
.unwrap_or_else(|error| {
logger::warn!(
"Response header {} contains non-UTF-8 characters: {error:?}",
name.as_str()
);
Secret::from(String::from("Non-UTF-8 header value"))
}),
)
})
.collect::<Vec<_>>();
let response_body = self
.response
.text()
.await
.map(Secret::from)
.unwrap_or_else(|error| {
logger::warn!("Response contains non-UTF-8 characters: {error:?}");
Secret::from(String::from("Non-UTF-8 response body"))
});
webhook_events::OutgoingWebhookResponseContent {
body: Some(response_body),
headers: Some(response_headers),
status_code: Some(status_code.as_u16()),
error_message: None,
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 59,
"total_crates": null
} |
fn_clm_router_get_outgoing_webhooks_signature_6523092487668576888 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/types
// Implementation of webhooks::OutgoingWebhook for OutgoingWebhookType
fn get_outgoing_webhooks_signature(
&self,
payment_response_hash_key: Option<impl AsRef<[u8]>>,
) -> errors::CustomResult<OutgoingWebhookPayloadWithSignature, errors::WebhooksFlowError> {
let webhook_signature_payload = self
.encode_to_string_of_json()
.change_context(errors::WebhooksFlowError::OutgoingWebhookEncodingFailed)
.attach_printable("failed encoding outgoing webhook payload")?;
let signature = payment_response_hash_key
.map(|key| {
common_utils::crypto::HmacSha512::sign_message(
&common_utils::crypto::HmacSha512,
key.as_ref(),
webhook_signature_payload.as_bytes(),
)
})
.transpose()
.change_context(errors::WebhooksFlowError::OutgoingWebhookSigningFailed)
.attach_printable("Failed to sign the message")?
.map(hex::encode);
Ok(OutgoingWebhookPayloadWithSignature {
payload: webhook_signature_payload.into(),
signature,
})
}
| {
"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_add_webhook_header_6523092487668576888 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/types
// Implementation of webhooks::OutgoingWebhook for OutgoingWebhookType
fn add_webhook_header(header: &mut Vec<(String, Maskable<String>)>, signature: String) {
header.push((headers::X_WEBHOOK_SIGNATURE.to_string(), signature.into()))
}
| {
"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_new_8059259674955479913 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/network_tokenization_incoming
// Inherent implementation for Authorization
pub fn new(header: Option<&HeaderValue>) -> Self {
Self {
header: header.cloned(),
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14465,
"total_crates": null
} |
fn_clm_router_from_8059259674955479913 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/network_tokenization_incoming
// Implementation of PaymentMethodCreateWrapper for From<(&api::payment_methods::CardDetail, &domain::PaymentMethod)>
fn from(
(data, payment_method): (&api::payment_methods::CardDetail, &domain::PaymentMethod),
) -> Self {
Self(api::payment_methods::PaymentMethodCreate {
customer_id: Some(payment_method.customer_id.clone()),
payment_method: payment_method.payment_method,
payment_method_type: payment_method.payment_method_type,
payment_method_issuer: payment_method.payment_method_issuer.clone(),
payment_method_issuer_code: payment_method.payment_method_issuer_code,
metadata: payment_method.metadata.clone(),
payment_method_data: None,
connector_mandate_details: None,
client_secret: None,
billing: None,
card: Some(data.clone()),
card_network: data
.card_network
.clone()
.map(|card_network| card_network.to_string()),
bank_transfer: None,
wallet: None,
network_transaction_id: payment_method.network_transaction_id.clone(),
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 2618,
"total_crates": null
} |
fn_clm_router_get_inner_8059259674955479913 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/network_tokenization_incoming
// Inherent implementation for PaymentMethodCreateWrapper
fn get_inner(self) -> api::payment_methods::PaymentMethodCreate {
self.0
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 584,
"total_crates": null
} |
fn_clm_router_handle_metadata_update_8059259674955479913 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/network_tokenization_incoming
pub async fn handle_metadata_update(
state: &SessionState,
metadata: &pm_types::NetworkTokenRequestorData,
locker_id: String,
payment_method: &domain::PaymentMethod,
merchant_context: &domain::MerchantContext,
decrypted_data: api::payment_methods::CardDetailFromLocker,
is_pan_update: bool,
) -> RouterResult<WebhookResponseTracker> {
let merchant_id = merchant_context.get_merchant_account().get_id();
let customer_id = &payment_method.customer_id;
let payment_method_id = payment_method.get_id().clone();
let status = payment_method.status;
match metadata.is_update_required(decrypted_data) {
false => {
logger::info!(
"No update required for payment method {} for locker_id {}",
payment_method.get_id(),
locker_id
);
Ok(WebhookResponseTracker::PaymentMethod {
payment_method_id,
status,
})
}
true => {
let mut card = cards::get_card_from_locker(state, customer_id, merchant_id, &locker_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch token information from the locker")?;
card.card_exp_year = metadata.expiry_year.clone();
card.card_exp_month = metadata.expiry_month.clone();
let card_network = card
.card_brand
.clone()
.map(|card_brand| enums::CardNetwork::from_str(&card_brand))
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "card network",
})
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid Card Network stored in vault")?;
let card_data = api::payment_methods::CardDetail::from((card, card_network));
let payment_method_request: api::payment_methods::PaymentMethodCreate =
PaymentMethodCreateWrapper::from((&card_data, payment_method)).get_inner();
let pm_cards = cards::PmCards {
state,
merchant_context,
};
pm_cards
.delete_card_from_locker(customer_id, merchant_id, &locker_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to delete network token")?;
let (res, _) = pm_cards
.add_card_to_locker(payment_method_request, &card_data, customer_id, None)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add network token")?;
let pm_details = res.card.as_ref().map(|card| {
api::payment_methods::PaymentMethodsData::Card(
api::payment_methods::CardDetailsPaymentMethod::from((card.clone(), None)),
)
});
let key_manager_state = state.into();
let pm_data_encrypted: Option<Encryptable<Secret<serde_json::Value>>> = pm_details
.async_map(|pm_card| {
cards::create_encrypted_data(
&key_manager_state,
merchant_context.get_merchant_key_store(),
pm_card,
)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt payment method data")?;
let pm_update = if is_pan_update {
storage::PaymentMethodUpdate::AdditionalDataUpdate {
locker_id: Some(res.payment_method_id),
payment_method_data: pm_data_encrypted.map(Into::into),
status: None,
payment_method: None,
payment_method_type: None,
payment_method_issuer: None,
network_token_requestor_reference_id: None,
network_token_locker_id: None,
network_token_payment_method_data: None,
}
} else {
storage::PaymentMethodUpdate::AdditionalDataUpdate {
locker_id: None,
payment_method_data: None,
status: None,
payment_method: None,
payment_method_type: None,
payment_method_issuer: None,
network_token_requestor_reference_id: None,
network_token_locker_id: Some(res.payment_method_id),
network_token_payment_method_data: pm_data_encrypted.map(Into::into),
}
};
let db = &*state.store;
db.update_payment_method(
&key_manager_state,
merchant_context.get_merchant_key_store(),
payment_method.clone(),
pm_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update the payment method")?;
Ok(WebhookResponseTracker::PaymentMethod {
payment_method_id,
status,
})
}
}
}
| {
"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_update_payment_method_8059259674955479913 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/network_tokenization_incoming
// Implementation of pm_types::NetworkTokenMetaDataUpdateBody for NetworkTokenWebhookResponseExt
async fn update_payment_method(
&self,
state: &SessionState,
payment_method: &domain::PaymentMethod,
merchant_context: &domain::MerchantContext,
) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
let decrypted_data = self.decrypt_payment_method_data(payment_method)?;
handle_metadata_update(
state,
&self.token,
payment_method
.network_token_locker_id
.clone()
.get_required_value("locker_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Locker id is not found for the payment method")?,
payment_method,
merchant_context,
decrypted_data,
true,
)
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 98,
"total_crates": null
} |
fn_clm_router_foreign_from_2902385510201336307 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/outgoing
// Implementation of storage::EventMetadata for ForeignFrom<&api::OutgoingWebhookContent>
fn foreign_from(content: &api::OutgoingWebhookContent) -> Self {
match content {
webhooks::OutgoingWebhookContent::PaymentDetails(payments_response) => Self::Payment {
payment_id: payments_response.payment_id.clone(),
},
webhooks::OutgoingWebhookContent::RefundDetails(refund_response) => Self::Refund {
payment_id: refund_response.payment_id.clone(),
refund_id: refund_response.refund_id.clone(),
},
webhooks::OutgoingWebhookContent::DisputeDetails(dispute_response) => Self::Dispute {
payment_id: dispute_response.payment_id.clone(),
attempt_id: dispute_response.attempt_id.clone(),
dispute_id: dispute_response.dispute_id.clone(),
},
webhooks::OutgoingWebhookContent::MandateDetails(mandate_response) => Self::Mandate {
payment_method_id: mandate_response.payment_method_id.clone(),
mandate_id: mandate_response.mandate_id.clone(),
},
#[cfg(feature = "payouts")]
webhooks::OutgoingWebhookContent::PayoutDetails(payout_response) => Self::Payout {
payout_id: payout_response.payout_id.clone(),
},
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 230,
"total_crates": null
} |
fn_clm_router_create_event_and_trigger_outgoing_webhook_2902385510201336307 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/outgoing
pub(crate) async fn create_event_and_trigger_outgoing_webhook(
state: SessionState,
merchant_context: domain::MerchantContext,
business_profile: domain::Profile,
event_type: enums::EventType,
event_class: enums::EventClass,
primary_object_id: String,
primary_object_type: enums::EventObjectType,
content: api::OutgoingWebhookContent,
primary_object_created_at: Option<time::PrimitiveDateTime>,
) -> CustomResult<(), errors::ApiErrorResponse> {
let delivery_attempt = enums::WebhookDeliveryAttempt::InitialAttempt;
let idempotent_event_id =
utils::get_idempotent_event_id(&primary_object_id, event_type, delivery_attempt)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to generate idempotent event ID")?;
let webhook_url_result = get_webhook_url_from_business_profile(&business_profile);
if !state.conf.webhooks.outgoing_enabled
|| webhook_url_result.is_err()
|| webhook_url_result.as_ref().is_ok_and(String::is_empty)
{
logger::debug!(
business_profile_id=?business_profile.get_id(),
%idempotent_event_id,
"Outgoing webhooks are disabled in application configuration, or merchant webhook URL \
could not be obtained; skipping outgoing webhooks for event"
);
return Ok(());
}
let event_id = utils::generate_event_id();
let merchant_id = business_profile.merchant_id.clone();
let now = common_utils::date_time::now();
let outgoing_webhook = api::OutgoingWebhook {
merchant_id: merchant_id.clone(),
event_id: event_id.clone(),
event_type,
content: content.clone(),
timestamp: now,
};
let request_content =
get_outgoing_webhook_request(&merchant_context, outgoing_webhook, &business_profile)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to construct outgoing webhook request content")?;
let event_metadata = storage::EventMetadata::foreign_from(&content);
let key_manager_state = &(&state).into();
let new_event = domain::Event {
event_id: event_id.clone(),
event_type,
event_class,
is_webhook_notified: false,
primary_object_id,
primary_object_type,
created_at: now,
merchant_id: Some(business_profile.merchant_id.clone()),
business_profile_id: Some(business_profile.get_id().to_owned()),
primary_object_created_at,
idempotent_event_id: Some(idempotent_event_id.clone()),
initial_attempt_id: Some(event_id.clone()),
request: Some(
crypto_operation(
key_manager_state,
type_name!(domain::Event),
CryptoOperation::Encrypt(
request_content
.encode_to_string_of_json()
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to encode outgoing webhook request content")
.map(Secret::new)?,
),
Identifier::Merchant(
merchant_context
.get_merchant_key_store()
.merchant_id
.clone(),
),
merchant_context
.get_merchant_key_store()
.key
.get_inner()
.peek(),
)
.await
.and_then(|val| val.try_into_operation())
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to encrypt outgoing webhook request content")?,
),
response: None,
delivery_attempt: Some(delivery_attempt),
metadata: Some(event_metadata),
is_overall_delivery_successful: Some(false),
};
let lock_value = utils::perform_redis_lock(
&state,
&idempotent_event_id,
merchant_context.get_merchant_account().get_id().to_owned(),
)
.await?;
if lock_value.is_none() {
return Ok(());
}
if (state
.store
.find_event_by_merchant_id_idempotent_event_id(
key_manager_state,
&merchant_id,
&idempotent_event_id,
merchant_context.get_merchant_key_store(),
)
.await)
.is_ok()
{
logger::debug!(
"Event with idempotent ID `{idempotent_event_id}` already exists in the database"
);
utils::free_redis_lock(
&state,
&idempotent_event_id,
merchant_context.get_merchant_account().get_id().to_owned(),
lock_value,
)
.await?;
return Ok(());
}
let event_insert_result = state
.store
.insert_event(
key_manager_state,
new_event,
merchant_context.get_merchant_key_store(),
)
.await;
let event = match event_insert_result {
Ok(event) => Ok(event),
Err(error) => {
logger::error!(event_insertion_failure=?error);
Err(error
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to insert event in events table"))
}
}?;
utils::free_redis_lock(
&state,
&idempotent_event_id,
merchant_context.get_merchant_account().get_id().to_owned(),
lock_value,
)
.await?;
let process_tracker = add_outgoing_webhook_retry_task_to_process_tracker(
&*state.store,
&business_profile,
&event,
)
.await
.inspect_err(|error| {
logger::error!(
?error,
"Failed to add outgoing webhook retry task to process tracker"
);
})
.ok();
let cloned_key_store = merchant_context.get_merchant_key_store().clone();
// Using a tokio spawn here and not arbiter because not all caller of this function
// may have an actix arbiter
tokio::spawn(
async move {
Box::pin(trigger_webhook_and_raise_event(
state,
business_profile,
&cloned_key_store,
event,
request_content,
delivery_attempt,
Some(content),
process_tracker,
))
.await;
}
.in_current_span(),
);
Ok(())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 187,
"total_crates": null
} |
fn_clm_router_trigger_webhook_to_merchant_2902385510201336307 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/outgoing
async fn trigger_webhook_to_merchant(
state: SessionState,
business_profile: domain::Profile,
merchant_key_store: &domain::MerchantKeyStore,
event: domain::Event,
request_content: OutgoingWebhookRequestContent,
delivery_attempt: enums::WebhookDeliveryAttempt,
process_tracker: Option<storage::ProcessTracker>,
) -> CustomResult<(), errors::WebhooksFlowError> {
let webhook_url = match (
get_webhook_url_from_business_profile(&business_profile),
process_tracker.clone(),
) {
(Ok(webhook_url), _) => Ok(webhook_url),
(Err(error), Some(process_tracker)) => {
if !error
.current_context()
.is_webhook_delivery_retryable_error()
{
logger::debug!("Failed to obtain merchant webhook URL, aborting retries");
state
.store
.as_scheduler()
.finish_process_with_business_status(process_tracker, business_status::FAILURE)
.await
.change_context(
errors::WebhooksFlowError::OutgoingWebhookProcessTrackerTaskUpdateFailed,
)?;
}
Err(error)
}
(Err(error), None) => Err(error),
}?;
let event_id = event.event_id;
let headers = request_content
.headers
.into_iter()
.map(|(name, value)| (name, value.into_masked()))
.collect();
let request = services::RequestBuilder::new()
.method(services::Method::Post)
.url(&webhook_url)
.attach_default_headers()
.headers(headers)
.set_body(RequestContent::RawBytes(
request_content.body.expose().into_bytes(),
))
.build();
let response = state
.api_client
.send_request(&state, request, None, false)
.await;
metrics::WEBHOOK_OUTGOING_COUNT.add(
1,
router_env::metric_attributes!((MERCHANT_ID, business_profile.merchant_id.clone())),
);
logger::debug!(outgoing_webhook_response=?response);
match delivery_attempt {
enums::WebhookDeliveryAttempt::InitialAttempt => match response {
Err(client_error) => {
api_client_error_handler(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
client_error,
delivery_attempt,
ScheduleWebhookRetry::NoSchedule,
)
.await?
}
Ok(response) => {
let status_code = response.status();
let updated_event = update_event_in_storage(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
response,
)
.await?;
if status_code.is_success() {
update_overall_delivery_status_in_storage(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
updated_event,
)
.await?;
success_response_handler(
state.clone(),
&business_profile.merchant_id,
process_tracker,
business_status::INITIAL_DELIVERY_ATTEMPT_SUCCESSFUL,
)
.await?;
} else {
error_response_handler(
state.clone(),
&business_profile.merchant_id,
delivery_attempt,
status_code.as_u16(),
"Ignoring error when sending webhook to merchant",
ScheduleWebhookRetry::NoSchedule,
)
.await?;
}
}
},
enums::WebhookDeliveryAttempt::AutomaticRetry => {
let process_tracker = process_tracker
.get_required_value("process_tracker")
.change_context(errors::WebhooksFlowError::OutgoingWebhookRetrySchedulingFailed)
.attach_printable("`process_tracker` is unavailable in automatic retry flow")?;
match response {
Err(client_error) => {
api_client_error_handler(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
client_error,
delivery_attempt,
ScheduleWebhookRetry::WithProcessTracker(Box::new(process_tracker)),
)
.await?;
}
Ok(response) => {
let status_code = response.status();
let updated_event = update_event_in_storage(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
response,
)
.await?;
if status_code.is_success() {
update_overall_delivery_status_in_storage(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
updated_event,
)
.await?;
success_response_handler(
state.clone(),
&business_profile.merchant_id,
Some(process_tracker),
"COMPLETED_BY_PT",
)
.await?;
} else {
error_response_handler(
state.clone(),
&business_profile.merchant_id,
delivery_attempt,
status_code.as_u16(),
"An error occurred when sending webhook to merchant",
ScheduleWebhookRetry::WithProcessTracker(Box::new(process_tracker)),
)
.await?;
}
}
}
}
enums::WebhookDeliveryAttempt::ManualRetry => match response {
Err(client_error) => {
api_client_error_handler(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
client_error,
delivery_attempt,
ScheduleWebhookRetry::NoSchedule,
)
.await?
}
Ok(response) => {
let status_code = response.status();
let _updated_event = update_event_in_storage(
state.clone(),
merchant_key_store.clone(),
&business_profile.merchant_id,
&event_id,
response,
)
.await?;
if status_code.is_success() {
increment_webhook_outgoing_received_count(&business_profile.merchant_id);
} else {
error_response_handler(
state,
&business_profile.merchant_id,
delivery_attempt,
status_code.as_u16(),
"Ignoring error when sending webhook to merchant",
ScheduleWebhookRetry::NoSchedule,
)
.await?;
}
}
},
}
Ok(())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 152,
"total_crates": null
} |
fn_clm_router_update_event_in_storage_2902385510201336307 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/outgoing
async fn update_event_in_storage(
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
response: reqwest::Response,
) -> CustomResult<domain::Event, errors::WebhooksFlowError> {
let status_code = response.status();
let is_webhook_notified = status_code.is_success();
let key_manager_state = &(&state).into();
let response_headers = response
.headers()
.iter()
.map(|(name, value)| {
(
name.as_str().to_owned(),
value
.to_str()
.map(|s| Secret::from(String::from(s)))
.unwrap_or_else(|error| {
logger::warn!(
"Response header {} contains non-UTF-8 characters: {error:?}",
name.as_str()
);
Secret::from(String::from("Non-UTF-8 header value"))
}),
)
})
.collect::<Vec<_>>();
let response_body = response
.text()
.await
.map(Secret::from)
.unwrap_or_else(|error| {
logger::warn!("Response contains non-UTF-8 characters: {error:?}");
Secret::from(String::from("Non-UTF-8 response body"))
});
let response_to_store = OutgoingWebhookResponseContent {
body: Some(response_body),
headers: Some(response_headers),
status_code: Some(status_code.as_u16()),
error_message: None,
};
let event_update = domain::EventUpdate::UpdateResponse {
is_webhook_notified,
response: Some(
crypto_operation(
key_manager_state,
type_name!(domain::Event),
CryptoOperation::Encrypt(
response_to_store
.encode_to_string_of_json()
.change_context(
errors::WebhooksFlowError::OutgoingWebhookResponseEncodingFailed,
)
.map(Secret::new)?,
),
Identifier::Merchant(merchant_key_store.merchant_id.clone()),
merchant_key_store.key.get_inner().peek(),
)
.await
.and_then(|val| val.try_into_operation())
.change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)
.attach_printable("Failed to encrypt outgoing webhook response content")?,
),
};
state
.store
.update_event_by_merchant_id_event_id(
key_manager_state,
merchant_id,
event_id,
event_update,
&merchant_key_store,
)
.await
.change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 87,
"total_crates": null
} |
fn_clm_router_get_outgoing_webhook_request_2902385510201336307 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/outgoing
pub(crate) fn get_outgoing_webhook_request(
merchant_context: &domain::MerchantContext,
outgoing_webhook: api::OutgoingWebhook,
business_profile: &domain::Profile,
) -> CustomResult<OutgoingWebhookRequestContent, errors::WebhooksFlowError> {
#[inline]
fn get_outgoing_webhook_request_inner<WebhookType: types::OutgoingWebhookType>(
outgoing_webhook: api::OutgoingWebhook,
business_profile: &domain::Profile,
) -> CustomResult<OutgoingWebhookRequestContent, errors::WebhooksFlowError> {
let mut headers = vec![
(
reqwest::header::CONTENT_TYPE.to_string(),
mime::APPLICATION_JSON.essence_str().into(),
),
(
reqwest::header::USER_AGENT.to_string(),
consts::USER_AGENT.to_string().into(),
),
];
let transformed_outgoing_webhook = WebhookType::from(outgoing_webhook);
let payment_response_hash_key = business_profile.payment_response_hash_key.clone();
let custom_headers = business_profile
.outgoing_webhook_custom_http_headers
.clone()
.map(|headers| {
headers
.into_inner()
.expose()
.parse_value::<HashMap<String, String>>("HashMap<String,String>")
.change_context(errors::WebhooksFlowError::OutgoingWebhookEncodingFailed)
.attach_printable("Failed to deserialize outgoing webhook custom HTTP headers")
})
.transpose()?;
if let Some(ref map) = custom_headers {
headers.extend(
map.iter()
.map(|(key, value)| (key.clone(), value.clone().into_masked())),
);
};
let outgoing_webhooks_signature = transformed_outgoing_webhook
.get_outgoing_webhooks_signature(payment_response_hash_key)?;
if let Some(signature) = outgoing_webhooks_signature.signature {
WebhookType::add_webhook_header(&mut headers, signature)
}
Ok(OutgoingWebhookRequestContent {
body: outgoing_webhooks_signature.payload,
headers: headers
.into_iter()
.map(|(name, value)| (name, Secret::new(value.into_inner())))
.collect(),
})
}
match merchant_context
.get_merchant_account()
.get_compatible_connector()
{
#[cfg(feature = "stripe")]
Some(api_models::enums::Connector::Stripe) => get_outgoing_webhook_request_inner::<
stripe_webhooks::StripeOutgoingWebhook,
>(outgoing_webhook, business_profile),
_ => get_outgoing_webhook_request_inner::<webhooks::OutgoingWebhook>(
outgoing_webhook,
business_profile,
),
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 64,
"total_crates": null
} |
fn_clm_router_new_-3107278269255533877 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/recovery_incoming
// Inherent implementation for RecoveryPaymentTuple
pub fn new(
payment_intent: &revenue_recovery::RecoveryPaymentIntent,
payment_attempt: &revenue_recovery::RecoveryPaymentAttempt,
) -> Self {
Self(payment_intent.clone(), payment_attempt.clone())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14469,
"total_crates": null
} |
fn_clm_router_get_payment_attempt_-3107278269255533877 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/recovery_incoming
// Implementation of None for RevenueRecoveryAttempt
async fn get_payment_attempt(
&self,
state: &SessionState,
req_state: &ReqState,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
payment_intent: &revenue_recovery::RecoveryPaymentIntent,
) -> CustomResult<
Option<(
revenue_recovery::RecoveryPaymentAttempt,
revenue_recovery::RecoveryPaymentIntent,
)>,
errors::RevenueRecoveryError,
> {
let attempt_response =
Box::pin(payments::payments_list_attempts_using_payment_intent_id::<
payments::operations::PaymentGetListAttempts,
api_payments::PaymentAttemptListResponse,
_,
payments::operations::payment_attempt_list::PaymentGetListAttempts,
hyperswitch_domain_models::payments::PaymentAttemptListData<
payments::operations::PaymentGetListAttempts,
>,
>(
state.clone(),
req_state.clone(),
merchant_context.clone(),
profile.clone(),
payments::operations::PaymentGetListAttempts,
api_payments::PaymentAttemptListRequest {
payment_intent_id: payment_intent.payment_id.clone(),
},
payment_intent.payment_id.clone(),
hyperswitch_domain_models::payments::HeaderPayload::default(),
))
.await;
let response = match attempt_response {
Ok(services::ApplicationResponse::JsonWithHeaders((payments_response, _))) => {
let final_attempt = self
.0
.charge_id
.as_ref()
.map(|charge_id| {
payments_response
.find_attempt_in_attempts_list_using_charge_id(charge_id.clone())
})
.unwrap_or_else(|| {
self.0
.connector_transaction_id
.as_ref()
.and_then(|transaction_id| {
payments_response
.find_attempt_in_attempts_list_using_connector_transaction_id(
transaction_id,
)
})
});
let payment_attempt =
final_attempt.map(|res| revenue_recovery::RecoveryPaymentAttempt {
attempt_id: res.id.to_owned(),
attempt_status: res.status.to_owned(),
feature_metadata: res.feature_metadata.to_owned(),
amount: res.amount.net_amount,
network_advice_code: res.error.clone().and_then(|e| e.network_advice_code), // Placeholder, to be populated if available
network_decline_code: res
.error
.clone()
.and_then(|e| e.network_decline_code), // Placeholder, to be populated if available
error_code: res.error.clone().map(|error| error.code),
created_at: res.created_at,
});
// If we have an attempt, combine it with payment_intent in a tuple.
let res_with_payment_intent_and_attempt =
payment_attempt.map(|attempt| (attempt, (*payment_intent).clone()));
Ok(res_with_payment_intent_and_attempt)
}
Ok(_) => Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed)
.attach_printable("Unexpected response from payment intent core"),
error @ Err(_) => {
logger::error!(?error);
Err(errors::RevenueRecoveryError::PaymentAttemptFetchFailed)
.attach_printable("failed to fetch payment attempt in recovery webhook flow")
}
}?;
Ok(response)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 245,
"total_crates": null
} |
fn_clm_router_get_payment_intent_-3107278269255533877 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/recovery_incoming
// Inherent implementation for RevenueRecoveryInvoice
async fn get_payment_intent(
&self,
state: &SessionState,
req_state: &ReqState,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
) -> CustomResult<Option<revenue_recovery::RecoveryPaymentIntent>, errors::RevenueRecoveryError>
{
let payment_response = Box::pin(payments::payments_get_intent_using_merchant_reference(
state.clone(),
merchant_context.clone(),
profile.clone(),
req_state.clone(),
&self.0.merchant_reference_id,
hyperswitch_domain_models::payments::HeaderPayload::default(),
))
.await;
let response = match payment_response {
Ok(services::ApplicationResponse::JsonWithHeaders((payments_response, _))) => {
let payment_id = payments_response.id.clone();
let status = payments_response.status;
let feature_metadata = payments_response.feature_metadata;
let merchant_id = merchant_context.get_merchant_account().get_id().clone();
let revenue_recovery_invoice_data = &self.0;
Ok(Some(revenue_recovery::RecoveryPaymentIntent {
payment_id,
status,
feature_metadata,
merchant_id,
merchant_reference_id: Some(
revenue_recovery_invoice_data.merchant_reference_id.clone(),
),
invoice_amount: revenue_recovery_invoice_data.amount,
invoice_currency: revenue_recovery_invoice_data.currency,
created_at: revenue_recovery_invoice_data.billing_started_at,
billing_address: revenue_recovery_invoice_data.billing_address.clone(),
}))
}
Err(err)
if matches!(
err.current_context(),
&errors::ApiErrorResponse::PaymentNotFound
) =>
{
Ok(None)
}
Ok(_) => Err(errors::RevenueRecoveryError::PaymentIntentFetchFailed)
.attach_printable("Unexpected response from payment intent core"),
error @ Err(_) => {
logger::error!(?error);
Err(errors::RevenueRecoveryError::PaymentIntentFetchFailed)
.attach_printable("failed to fetch payment intent recovery webhook flow")
}
}?;
Ok(response)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 155,
"total_crates": null
} |
fn_clm_router_publish_revenue_recovery_event_to_kafka_-3107278269255533877 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/recovery_incoming
// Inherent implementation for RecoveryPaymentTuple
pub async fn publish_revenue_recovery_event_to_kafka(
state: &SessionState,
recovery_payment_tuple: &Self,
retry_count: Option<i32>,
) -> CustomResult<(), errors::RevenueRecoveryError> {
let recovery_payment_intent = &recovery_payment_tuple.0;
let recovery_payment_attempt = &recovery_payment_tuple.1;
let revenue_recovery_feature_metadata = recovery_payment_intent
.feature_metadata
.as_ref()
.and_then(|metadata| metadata.revenue_recovery.as_ref());
let billing_city = recovery_payment_intent
.billing_address
.as_ref()
.and_then(|billing_address| billing_address.address.as_ref())
.and_then(|address| address.city.clone())
.map(Secret::new);
let billing_state = recovery_payment_intent
.billing_address
.as_ref()
.and_then(|billing_address| billing_address.address.as_ref())
.and_then(|address| address.state.clone());
let billing_country = recovery_payment_intent
.billing_address
.as_ref()
.and_then(|billing_address| billing_address.address.as_ref())
.and_then(|address| address.country);
let card_info = revenue_recovery_feature_metadata.and_then(|metadata| {
metadata
.billing_connector_payment_method_details
.as_ref()
.and_then(|details| details.get_billing_connector_card_info())
});
#[allow(clippy::as_conversions)]
let retry_count = Some(retry_count.unwrap_or_else(|| {
revenue_recovery_feature_metadata
.map(|data| data.total_retry_count as i32)
.unwrap_or(0)
}));
let event = kafka::revenue_recovery::RevenueRecovery {
merchant_id: &recovery_payment_intent.merchant_id,
invoice_amount: recovery_payment_intent.invoice_amount,
invoice_currency: &recovery_payment_intent.invoice_currency,
invoice_date: revenue_recovery_feature_metadata.and_then(|data| {
data.invoice_billing_started_at_time
.map(|time| time.assume_utc())
}),
invoice_due_date: revenue_recovery_feature_metadata
.and_then(|data| data.invoice_next_billing_time.map(|time| time.assume_utc())),
billing_city,
billing_country: billing_country.as_ref(),
billing_state,
attempt_amount: recovery_payment_attempt.amount,
attempt_currency: &recovery_payment_intent.invoice_currency.clone(),
attempt_status: &recovery_payment_attempt.attempt_status.clone(),
pg_error_code: recovery_payment_attempt.error_code.clone(),
network_advice_code: recovery_payment_attempt.network_advice_code.clone(),
network_error_code: recovery_payment_attempt.network_decline_code.clone(),
first_pg_error_code: revenue_recovery_feature_metadata
.and_then(|data| data.first_payment_attempt_pg_error_code.clone()),
first_network_advice_code: revenue_recovery_feature_metadata
.and_then(|data| data.first_payment_attempt_network_advice_code.clone()),
first_network_error_code: revenue_recovery_feature_metadata
.and_then(|data| data.first_payment_attempt_network_decline_code.clone()),
attempt_created_at: recovery_payment_attempt.created_at.assume_utc(),
payment_method_type: revenue_recovery_feature_metadata
.map(|data| &data.payment_method_type),
payment_method_subtype: revenue_recovery_feature_metadata
.map(|data| &data.payment_method_subtype),
card_network: card_info
.as_ref()
.and_then(|info| info.card_network.as_ref()),
card_issuer: card_info.and_then(|data| data.card_issuer.clone()),
retry_count,
payment_gateway: revenue_recovery_feature_metadata.map(|data| data.connector),
};
state.event_handler.log_event(&event);
Ok(())
}
| {
"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_recovery_incoming_webhook_flow_-3107278269255533877 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/recovery_incoming
pub async fn recovery_incoming_webhook_flow(
state: SessionState,
merchant_context: domain::MerchantContext,
business_profile: domain::Profile,
source_verified: bool,
connector_enum: &connector_integration_interface::ConnectorEnum,
billing_connector_account: hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
connector_name: &str,
request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,
event_type: webhooks::IncomingWebhookEvent,
req_state: ReqState,
object_ref_id: &webhooks::ObjectReferenceId,
) -> CustomResult<webhooks::WebhookResponseTracker, errors::RevenueRecoveryError> {
// Source verification is necessary for revenue recovery webhooks flow since We don't have payment intent/attempt object created before in our system.
common_utils::fp_utils::when(!source_verified, || {
Err(report!(
errors::RevenueRecoveryError::WebhookAuthenticationFailed
))
})?;
let connector = api_enums::Connector::from_str(connector_name)
.change_context(errors::RevenueRecoveryError::InvoiceWebhookProcessingFailed)
.attach_printable_lazy(|| format!("unable to parse connector name {connector_name:?}"))?;
let billing_connectors_with_invoice_sync_call = &state.conf.billing_connectors_invoice_sync;
let should_billing_connector_invoice_api_called = billing_connectors_with_invoice_sync_call
.billing_connectors_which_requires_invoice_sync_call
.contains(&connector);
let billing_connectors_with_payment_sync_call = &state.conf.billing_connectors_payment_sync;
let should_billing_connector_payment_api_called = billing_connectors_with_payment_sync_call
.billing_connectors_which_require_payment_sync
.contains(&connector);
let billing_connector_payment_details =
BillingConnectorPaymentsSyncResponseData::get_billing_connector_payment_details(
should_billing_connector_payment_api_called,
&state,
&merchant_context,
&billing_connector_account,
connector_name,
object_ref_id,
)
.await?;
let invoice_id = billing_connector_payment_details
.clone()
.map(|data| data.merchant_reference_id);
let billing_connector_invoice_details =
BillingConnectorInvoiceSyncResponseData::get_billing_connector_invoice_details(
should_billing_connector_invoice_api_called,
&state,
&merchant_context,
&billing_connector_account,
connector_name,
invoice_id,
)
.await?;
// Checks whether we have data in billing_connector_invoice_details , if it is there then we construct revenue recovery invoice from it else it takes from webhook
let invoice_details = RevenueRecoveryInvoice::get_recovery_invoice_details(
connector_enum,
request_details,
billing_connector_invoice_details.as_ref(),
)?;
// Fetch the intent using merchant reference id, if not found create new intent.
let payment_intent = invoice_details
.get_payment_intent(&state, &req_state, &merchant_context, &business_profile)
.await
.transpose()
.async_unwrap_or_else(|| async {
invoice_details
.create_payment_intent(&state, &req_state, &merchant_context, &business_profile)
.await
})
.await?;
let is_event_recovery_transaction_event = event_type.is_recovery_transaction_event();
let (recovery_attempt_from_payment_attempt, recovery_intent_from_payment_attempt) =
RevenueRecoveryAttempt::get_recovery_payment_attempt(
is_event_recovery_transaction_event,
&billing_connector_account,
&state,
connector_enum,
&req_state,
billing_connector_payment_details.as_ref(),
request_details,
&merchant_context,
&business_profile,
&payment_intent,
&invoice_details.0,
)
.await?;
// Publish event to Kafka
if let Some(ref attempt) = recovery_attempt_from_payment_attempt {
// Passing `merchant_context` here
let recovery_payment_tuple =
&RecoveryPaymentTuple::new(&recovery_intent_from_payment_attempt, attempt);
if let Err(e) = RecoveryPaymentTuple::publish_revenue_recovery_event_to_kafka(
&state,
recovery_payment_tuple,
None,
)
.await
{
logger::error!(
"Failed to publish revenue recovery event to kafka : {:?}",
e
);
};
}
let attempt_triggered_by = recovery_attempt_from_payment_attempt
.as_ref()
.and_then(|attempt| attempt.get_attempt_triggered_by());
let recovery_action = RecoveryAction {
action: RecoveryAction::get_action(event_type, attempt_triggered_by),
};
let mca_retry_threshold = billing_connector_account
.get_retry_threshold()
.ok_or(report!(
errors::RevenueRecoveryError::BillingThresholdRetryCountFetchFailed
))?;
let intent_retry_count = recovery_intent_from_payment_attempt
.feature_metadata
.as_ref()
.and_then(|metadata| metadata.get_retry_count())
.ok_or(report!(errors::RevenueRecoveryError::RetryCountFetchFailed))?;
logger::info!("Intent retry count: {:?}", intent_retry_count);
recovery_action
.handle_action(
&state,
&business_profile,
&merchant_context,
&billing_connector_account,
mca_retry_threshold,
intent_retry_count,
&(
recovery_attempt_from_payment_attempt,
recovery_intent_from_payment_attempt,
),
)
.await
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 77,
"total_crates": null
} |
fn_clm_router_incoming_webhooks_core_4763811398955835165 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/incoming_v2
async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(
state: SessionState,
req_state: ReqState,
req: &actix_web::HttpRequest,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
connector_id: &common_utils::id_type::MerchantConnectorAccountId,
body: actix_web::web::Bytes,
_is_relay_webhook: bool,
) -> errors::RouterResult<(
services::ApplicationResponse<serde_json::Value>,
WebhookResponseTracker,
serde_json::Value,
)> {
metrics::WEBHOOK_INCOMING_COUNT.add(
1,
router_env::metric_attributes!((
MERCHANT_ID,
merchant_context.get_merchant_account().get_id().clone()
)),
);
let mut request_details = IncomingWebhookRequestDetails {
method: req.method().clone(),
uri: req.uri().clone(),
headers: req.headers(),
query_params: req.query_string().to_string(),
body: &body,
};
// Fetch the merchant connector account to get the webhooks source secret
// `webhooks source secret` is a secret shared between the merchant and connector
// This is used for source verification and webhooks integrity
let (merchant_connector_account, connector, connector_name) = fetch_mca_and_connector(
&state,
connector_id,
merchant_context.get_merchant_key_store(),
)
.await?;
let decoded_body = connector
.decode_webhook_body(
&request_details,
merchant_context.get_merchant_account().get_id(),
merchant_connector_account.connector_webhook_details.clone(),
connector_name.as_str(),
)
.await
.switch()
.attach_printable("There was an error in incoming webhook body decoding")?;
request_details.body = &decoded_body;
let event_type = match connector
.get_webhook_event_type(&request_details)
.allow_webhook_event_type_not_found(
state
.clone()
.conf
.webhooks
.ignore_error
.event_type
.unwrap_or(true),
)
.switch()
.attach_printable("Could not find event type in incoming webhook body")?
{
Some(event_type) => event_type,
// Early return allows us to acknowledge the webhooks that we do not support
None => {
logger::error!(
webhook_payload =? request_details.body,
"Failed while identifying the event type",
);
metrics::WEBHOOK_EVENT_TYPE_IDENTIFICATION_FAILURE_COUNT.add(
1,
router_env::metric_attributes!(
(
MERCHANT_ID,
merchant_context.get_merchant_account().get_id().clone()
),
("connector", connector_name)
),
);
let response = connector
.get_webhook_api_response(&request_details, None)
.switch()
.attach_printable("Failed while early return in case of event type parsing")?;
return Ok((
response,
WebhookResponseTracker::NoEffect,
serde_json::Value::Null,
));
}
};
logger::info!(event_type=?event_type);
// if it is a setup webhook event, return ok status
if event_type == webhooks::IncomingWebhookEvent::SetupWebhook {
return Ok((
services::ApplicationResponse::StatusOk,
WebhookResponseTracker::NoEffect,
serde_json::Value::default(),
));
}
let is_webhook_event_supported = !matches!(
event_type,
webhooks::IncomingWebhookEvent::EventNotSupported
);
let is_webhook_event_enabled = !utils::is_webhook_event_disabled(
&*state.clone().store,
connector_name.as_str(),
merchant_context.get_merchant_account().get_id(),
&event_type,
)
.await;
//process webhook further only if webhook event is enabled and is not event_not_supported
let process_webhook_further = is_webhook_event_enabled && is_webhook_event_supported;
logger::info!(process_webhook=?process_webhook_further);
let flow_type: api::WebhookFlow = event_type.into();
let mut event_object: Box<dyn masking::ErasedMaskSerialize> = Box::new(serde_json::Value::Null);
let webhook_effect = if process_webhook_further
&& !matches!(flow_type, api::WebhookFlow::ReturnResponse)
{
let object_ref_id = connector
.get_webhook_object_reference_id(&request_details)
.switch()
.attach_printable("Could not find object reference id in incoming webhook body")?;
let connector_enum = api_models::enums::Connector::from_str(&connector_name)
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "connector",
})
.attach_printable_lazy(|| {
format!("unable to parse connector name {connector_name:?}")
})?;
let connectors_with_source_verification_call = &state.conf.webhook_source_verification_call;
let source_verified = if connectors_with_source_verification_call
.connectors_with_webhook_source_verification_call
.contains(&connector_enum)
{
verify_webhook_source_verification_call(
connector.clone(),
&state,
&merchant_context,
merchant_connector_account.clone(),
&connector_name,
&request_details,
)
.await
.or_else(|error| match error.current_context() {
errors::ConnectorError::WebhookSourceVerificationFailed => {
logger::error!(?error, "Source Verification Failed");
Ok(false)
}
_ => Err(error),
})
.switch()
.attach_printable("There was an issue in incoming webhook source verification")?
} else {
connector
.clone()
.verify_webhook_source(
&request_details,
merchant_context.get_merchant_account().get_id(),
merchant_connector_account.connector_webhook_details.clone(),
merchant_connector_account.connector_account_details.clone(),
connector_name.as_str(),
)
.await
.or_else(|error| match error.current_context() {
errors::ConnectorError::WebhookSourceVerificationFailed => {
logger::error!(?error, "Source Verification Failed");
Ok(false)
}
_ => Err(error),
})
.switch()
.attach_printable("There was an issue in incoming webhook source verification")?
};
logger::info!(source_verified=?source_verified);
if source_verified {
metrics::WEBHOOK_SOURCE_VERIFIED_COUNT.add(
1,
router_env::metric_attributes!((
MERCHANT_ID,
merchant_context.get_merchant_account().get_id().clone()
)),
);
}
// If source verification is mandatory and source is not verified, fail with webhook authentication error
// else continue the flow
match (
connector.is_webhook_source_verification_mandatory(),
source_verified,
) {
(true, false) => Err(errors::ApiErrorResponse::WebhookAuthenticationFailed)?,
_ => {
event_object = connector
.get_webhook_resource_object(&request_details)
.switch()
.attach_printable("Could not find resource object in incoming webhook body")?;
let webhook_details = api::IncomingWebhookDetails {
object_reference_id: object_ref_id.clone(),
resource_object: serde_json::to_vec(&event_object)
.change_context(errors::ParsingError::EncodeError("byte-vec"))
.attach_printable("Unable to convert webhook payload to a value")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"There was an issue when encoding the incoming webhook body to bytes",
)?,
};
match flow_type {
api::WebhookFlow::Payment => Box::pin(payments_incoming_webhook_flow(
state.clone(),
req_state,
merchant_context,
profile,
webhook_details,
source_verified,
))
.await
.attach_printable("Incoming webhook flow for payments failed")?,
api::WebhookFlow::Refund => todo!(),
api::WebhookFlow::Dispute => todo!(),
api::WebhookFlow::BankTransfer => todo!(),
api::WebhookFlow::ReturnResponse => WebhookResponseTracker::NoEffect,
api::WebhookFlow::Mandate => todo!(),
api::WebhookFlow::ExternalAuthentication => todo!(),
api::WebhookFlow::FraudCheck => todo!(),
api::WebhookFlow::Setup => WebhookResponseTracker::NoEffect,
#[cfg(feature = "payouts")]
api::WebhookFlow::Payout => todo!(),
api::WebhookFlow::Subscription => todo!(),
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
api::WebhookFlow::Recovery => {
Box::pin(recovery_incoming::recovery_incoming_webhook_flow(
state.clone(),
merchant_context,
profile,
source_verified,
&connector,
merchant_connector_account,
&connector_name,
&request_details,
event_type,
req_state,
&object_ref_id,
))
.await
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to process recovery incoming webhook")?
}
}
}
}
} else {
metrics::WEBHOOK_INCOMING_FILTERED_COUNT.add(
1,
router_env::metric_attributes!((
MERCHANT_ID,
merchant_context.get_merchant_account().get_id().clone()
)),
);
WebhookResponseTracker::NoEffect
};
let response = connector
.get_webhook_api_response(&request_details, None)
.switch()
.attach_printable("Could not get incoming webhook api response from connector")?;
let serialized_request = event_object
.masked_serialize()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not convert webhook effect to string")?;
Ok((response, webhook_effect, serialized_request))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 176,
"total_crates": null
} |
fn_clm_router_payments_incoming_webhook_flow_4763811398955835165 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/incoming_v2
async fn payments_incoming_webhook_flow(
state: SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
webhook_details: api::IncomingWebhookDetails,
source_verified: bool,
) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
let consume_or_trigger_flow = if source_verified {
payments::CallConnectorAction::HandleResponse(webhook_details.resource_object)
} else {
payments::CallConnectorAction::Trigger
};
let key_manager_state = &(&state).into();
let payments_response = match webhook_details.object_reference_id {
webhooks::ObjectReferenceId::PaymentId(id) => {
let get_trackers_response = get_trackers_response_for_payment_get_operation(
state.store.as_ref(),
&id,
profile.get_id(),
key_manager_state,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let payment_id = get_trackers_response.payment_data.get_payment_id();
let lock_action = api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::Payments,
override_lock_retries: None,
},
};
lock_action
.clone()
.perform_locking_action(
&state,
merchant_context.get_merchant_account().get_id().to_owned(),
)
.await?;
let (
payment_data,
_req,
customer,
connector_http_status_code,
external_latency,
connector_response_data,
) = Box::pin(payments::payments_operation_core::<
api::PSync,
_,
_,
_,
PaymentStatusData<api::PSync>,
>(
&state,
req_state,
merchant_context.clone(),
&profile,
payments::operations::PaymentGet,
api::PaymentsRetrieveRequest {
force_sync: true,
expand_attempts: false,
param: None,
return_raw_connector_response: None,
merchant_connector_details: None,
},
get_trackers_response,
consume_or_trigger_flow,
HeaderPayload::default(),
))
.await?;
let response = payment_data.generate_response(
&state,
connector_http_status_code,
external_latency,
None,
&merchant_context,
&profile,
Some(connector_response_data),
);
lock_action
.free_lock_action(
&state,
merchant_context.get_merchant_account().get_id().to_owned(),
)
.await?;
match response {
Ok(value) => value,
Err(err)
if matches!(
err.current_context(),
&errors::ApiErrorResponse::PaymentNotFound
) && state
.clone()
.conf
.webhooks
.ignore_error
.payment_not_found
.unwrap_or(true) =>
{
metrics::WEBHOOK_PAYMENT_NOT_FOUND.add(
1,
router_env::metric_attributes!((
"merchant_id",
merchant_context.get_merchant_account().get_id().clone()
)),
);
return Ok(WebhookResponseTracker::NoEffect);
}
error @ Err(_) => error?,
}
}
_ => Err(errors::ApiErrorResponse::WebhookProcessingFailure).attach_printable(
"Did not get payment id as object reference id in webhook payments flow",
)?,
};
match payments_response {
services::ApplicationResponse::JsonWithHeaders((payments_response, _)) => {
let payment_id = payments_response.id.clone();
let status = payments_response.status;
let event_type: Option<enums::EventType> = payments_response.status.into();
// If event is NOT an UnsupportedEvent, trigger Outgoing Webhook
if let Some(outgoing_event_type) = event_type {
let primary_object_created_at = payments_response.created;
// TODO: trigger an outgoing webhook to merchant
Box::pin(create_event_and_trigger_outgoing_webhook(
state,
profile,
merchant_context.get_merchant_key_store(),
outgoing_event_type,
enums::EventClass::Payments,
payment_id.get_string_repr().to_owned(),
enums::EventObjectType::PaymentDetails,
api::OutgoingWebhookContent::PaymentDetails(Box::new(payments_response)),
primary_object_created_at,
))
.await?;
};
let response = WebhookResponseTracker::Payment { payment_id, status };
Ok(response)
}
_ => Err(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("received non-json response from payments core")?,
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 80,
"total_crates": null
} |
fn_clm_router_incoming_webhooks_wrapper_4763811398955835165 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/incoming_v2
pub async fn incoming_webhooks_wrapper<W: types::OutgoingWebhookType>(
flow: &impl router_env::types::FlowMetric,
state: SessionState,
req_state: ReqState,
req: &actix_web::HttpRequest,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
connector_id: &common_utils::id_type::MerchantConnectorAccountId,
body: actix_web::web::Bytes,
is_relay_webhook: bool,
) -> RouterResponse<serde_json::Value> {
let start_instant = Instant::now();
let (application_response, webhooks_response_tracker, serialized_req) =
Box::pin(incoming_webhooks_core::<W>(
state.clone(),
req_state,
req,
merchant_context.clone(),
profile,
connector_id,
body.clone(),
is_relay_webhook,
))
.await?;
logger::info!(incoming_webhook_payload = ?serialized_req);
let request_duration = Instant::now()
.saturating_duration_since(start_instant)
.as_millis();
let request_id = RequestId::extract(req)
.await
.attach_printable("Unable to extract request id from request")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let auth_type = auth::AuthenticationType::WebhookAuth {
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
};
let status_code = 200;
let api_event = ApiEventsType::Webhooks {
connector: connector_id.clone(),
payment_id: webhooks_response_tracker.get_payment_id(),
};
let response_value = serde_json::to_value(&webhooks_response_tracker)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not convert webhook effect to string")?;
let infra = state.infra_components.clone();
let api_event = ApiEvent::new(
state.tenant.tenant_id.clone(),
Some(merchant_context.get_merchant_account().get_id().clone()),
flow,
&request_id,
request_duration,
status_code,
serialized_req,
Some(response_value),
None,
auth_type,
None,
api_event,
req,
req.method(),
infra,
);
state.event_handler().log_event(&api_event);
Ok(application_response)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 66,
"total_crates": null
} |
fn_clm_router_get_trackers_response_for_payment_get_operation_4763811398955835165 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/incoming_v2
async fn get_trackers_response_for_payment_get_operation<F>(
db: &dyn StorageInterface,
payment_id: &api::PaymentIdType,
profile_id: &common_utils::id_type::ProfileId,
key_manager_state: &KeyManagerState,
merchant_key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> errors::RouterResult<payments::operations::GetTrackerResponse<PaymentStatusData<F>>>
where
F: Clone,
{
let (payment_intent, payment_attempt) = match payment_id {
api_models::payments::PaymentIdType::PaymentIntentId(ref id) => {
let payment_intent = db
.find_payment_intent_by_id(
key_manager_state,
id,
merchant_key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_attempt = db
.find_payment_attempt_by_id(
key_manager_state,
merchant_key_store,
&payment_intent
.active_attempt_id
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("active_attempt_id not present in payment_attempt")?,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
(payment_intent, payment_attempt)
}
api_models::payments::PaymentIdType::ConnectorTransactionId(ref id) => {
let payment_attempt = db
.find_payment_attempt_by_profile_id_connector_transaction_id(
key_manager_state,
merchant_key_store,
profile_id,
id,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_intent = db
.find_payment_intent_by_id(
key_manager_state,
&payment_attempt.payment_id,
merchant_key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
(payment_intent, payment_attempt)
}
api_models::payments::PaymentIdType::PaymentAttemptId(ref id) => {
let global_attempt_id = common_utils::id_type::GlobalAttemptId::try_from(
std::borrow::Cow::Owned(id.to_owned()),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while getting GlobalAttemptId")?;
let payment_attempt = db
.find_payment_attempt_by_id(
key_manager_state,
merchant_key_store,
&global_attempt_id,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_intent = db
.find_payment_intent_by_id(
key_manager_state,
&payment_attempt.payment_id,
merchant_key_store,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
(payment_intent, payment_attempt)
}
api_models::payments::PaymentIdType::PreprocessingId(ref _id) => todo!(),
};
// We need the address here to send it in the response
// In case we need to send an outgoing webhook, we might have to send the billing address and shipping address
let payment_address = hyperswitch_domain_models::payment_address::PaymentAddress::new(
payment_intent
.shipping_address
.clone()
.map(|address| address.into_inner()),
payment_intent
.billing_address
.clone()
.map(|address| address.into_inner()),
payment_attempt
.payment_method_billing_address
.clone()
.map(|address| address.into_inner()),
Some(true),
);
Ok(payments::operations::GetTrackerResponse {
payment_data: PaymentStatusData {
flow: PhantomData,
payment_intent,
payment_attempt,
attempts: None,
should_sync_with_connector: true,
payment_address,
merchant_connector_details: None,
},
})
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 63,
"total_crates": null
} |
fn_clm_router_get_connector_by_connector_name_4763811398955835165 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/incoming_v2
fn get_connector_by_connector_name(
state: &SessionState,
connector_name: &str,
merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
) -> CustomResult<(ConnectorEnum, String), errors::ApiErrorResponse> {
let authentication_connector =
api_models::enums::convert_authentication_connector(connector_name);
#[cfg(feature = "frm")]
{
let frm_connector = api_models::enums::convert_frm_connector(connector_name);
if frm_connector.is_some() {
let frm_connector_data =
api::FraudCheckConnectorData::get_connector_by_name(connector_name)?;
return Ok((
frm_connector_data.connector,
frm_connector_data.connector_name.to_string(),
));
}
}
let (connector, connector_name) = if authentication_connector.is_some() {
let authentication_connector_data =
api::AuthenticationConnectorData::get_connector_by_name(connector_name)?;
(
authentication_connector_data.connector,
authentication_connector_data.connector_name.to_string(),
)
} else {
let connector_data = ConnectorData::get_connector_by_name(
&state.conf.connectors,
connector_name,
GetToken::Connector,
merchant_connector_id,
)
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "invalid connector name received".to_string(),
})
.attach_printable("Failed construction of ConnectorData")?;
(
connector_data.connector,
connector_data.connector_name.to_string(),
)
};
Ok((connector, connector_name))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 35,
"total_crates": null
} |
fn_clm_router_process_webhook_business_logic_-1697265579327188042 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/incoming
async fn process_webhook_business_logic(
state: &SessionState,
req_state: ReqState,
merchant_context: &domain::MerchantContext,
connector: &ConnectorEnum,
connector_name: &str,
event_type: webhooks::IncomingWebhookEvent,
source_verified_via_ucs: bool,
webhook_transform_data: &Option<Box<unified_connector_service::WebhookTransformData>>,
request_details: &IncomingWebhookRequestDetails<'_>,
is_relay_webhook: bool,
) -> errors::RouterResult<WebhookResponseTracker> {
let object_ref_id = connector
.get_webhook_object_reference_id(request_details)
.switch()
.attach_printable("Could not find object reference id in incoming webhook body")?;
let connector_enum = Connector::from_str(connector_name)
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "connector",
})
.attach_printable_lazy(|| format!("unable to parse connector name {connector_name:?}"))?;
let connectors_with_source_verification_call = &state.conf.webhook_source_verification_call;
let merchant_connector_account = match Box::pin(helper_utils::get_mca_from_object_reference_id(
state,
object_ref_id.clone(),
merchant_context,
connector_name,
))
.await
{
Ok(mca) => mca,
Err(error) => {
let result = handle_incoming_webhook_error(
error,
connector,
connector_name,
request_details,
merchant_context.get_merchant_account().get_id(),
);
match result {
Ok((_, webhook_tracker, _)) => return Ok(webhook_tracker),
Err(e) => return Err(e),
}
}
};
let source_verified = if source_verified_via_ucs {
// If UCS handled verification, use that result
source_verified_via_ucs
} else {
// Fall back to traditional source verification
if connectors_with_source_verification_call
.connectors_with_webhook_source_verification_call
.contains(&connector_enum)
{
verify_webhook_source_verification_call(
connector.clone(),
state,
merchant_context,
merchant_connector_account.clone(),
connector_name,
request_details,
)
.await
.or_else(|error| match error.current_context() {
errors::ConnectorError::WebhookSourceVerificationFailed => {
logger::error!(?error, "Source Verification Failed");
Ok(false)
}
_ => Err(error),
})
.switch()
.attach_printable("There was an issue in incoming webhook source verification")?
} else {
connector
.clone()
.verify_webhook_source(
request_details,
merchant_context.get_merchant_account().get_id(),
merchant_connector_account.connector_webhook_details.clone(),
merchant_connector_account.connector_account_details.clone(),
connector_name,
)
.await
.or_else(|error| match error.current_context() {
errors::ConnectorError::WebhookSourceVerificationFailed => {
logger::error!(?error, "Source Verification Failed");
Ok(false)
}
_ => Err(error),
})
.switch()
.attach_printable("There was an issue in incoming webhook source verification")?
}
};
if source_verified {
metrics::WEBHOOK_SOURCE_VERIFIED_COUNT.add(
1,
router_env::metric_attributes!((
MERCHANT_ID,
merchant_context.get_merchant_account().get_id().clone()
)),
);
} else if connector.is_webhook_source_verification_mandatory() {
// if webhook consumption is mandatory for connector, fail webhook
// so that merchant can retrigger it after updating merchant_secret
return Err(errors::ApiErrorResponse::WebhookAuthenticationFailed.into());
}
logger::info!(source_verified=?source_verified);
let event_object: Box<dyn masking::ErasedMaskSerialize> =
if let Some(transform_data) = webhook_transform_data {
// Use UCS transform data if available
if let Some(webhook_content) = &transform_data.webhook_content {
// Convert UCS webhook content to appropriate format
Box::new(
serde_json::to_value(webhook_content)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize UCS webhook content")?,
)
} else {
// Fall back to connector extraction
connector
.get_webhook_resource_object(request_details)
.switch()
.attach_printable("Could not find resource object in incoming webhook body")?
}
} else {
// Use traditional connector extraction
connector
.get_webhook_resource_object(request_details)
.switch()
.attach_printable("Could not find resource object in incoming webhook body")?
};
let webhook_details = api::IncomingWebhookDetails {
object_reference_id: object_ref_id.clone(),
resource_object: serde_json::to_vec(&event_object)
.change_context(errors::ParsingError::EncodeError("byte-vec"))
.attach_printable("Unable to convert webhook payload to a value")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"There was an issue when encoding the incoming webhook body to bytes",
)?,
};
let profile_id = &merchant_connector_account.profile_id;
let key_manager_state = &(state).into();
let business_profile = state
.store
.find_business_profile_by_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
// If the incoming webhook is a relay webhook, then we need to trigger the relay webhook flow
let result_response = if is_relay_webhook {
let relay_webhook_response = Box::pin(relay_incoming_webhook_flow(
state.clone(),
merchant_context.clone(),
business_profile,
webhook_details,
event_type,
source_verified,
))
.await
.attach_printable("Incoming webhook flow for relay failed");
// Using early return ensures unsupported webhooks are acknowledged to the connector
if let Some(errors::ApiErrorResponse::NotSupported { .. }) = relay_webhook_response
.as_ref()
.err()
.map(|a| a.current_context())
{
logger::error!(
webhook_payload =? request_details.body,
"Failed while identifying the event type",
);
let _response = connector
.get_webhook_api_response(request_details, None)
.switch()
.attach_printable(
"Failed while early return in case of not supported event type in relay webhooks",
)?;
return Ok(WebhookResponseTracker::NoEffect);
};
relay_webhook_response
} else {
let flow_type: api::WebhookFlow = event_type.into();
match flow_type {
api::WebhookFlow::Payment => Box::pin(payments_incoming_webhook_flow(
state.clone(),
req_state,
merchant_context.clone(),
business_profile,
webhook_details,
source_verified,
connector,
request_details,
event_type,
webhook_transform_data,
))
.await
.attach_printable("Incoming webhook flow for payments failed"),
api::WebhookFlow::Refund => Box::pin(refunds_incoming_webhook_flow(
state.clone(),
merchant_context.clone(),
business_profile,
webhook_details,
connector_name,
source_verified,
event_type,
))
.await
.attach_printable("Incoming webhook flow for refunds failed"),
api::WebhookFlow::Dispute => Box::pin(disputes_incoming_webhook_flow(
state.clone(),
merchant_context.clone(),
business_profile,
webhook_details,
source_verified,
connector,
request_details,
event_type,
))
.await
.attach_printable("Incoming webhook flow for disputes failed"),
api::WebhookFlow::BankTransfer => Box::pin(bank_transfer_webhook_flow(
state.clone(),
req_state,
merchant_context.clone(),
business_profile,
webhook_details,
source_verified,
))
.await
.attach_printable("Incoming bank-transfer webhook flow failed"),
api::WebhookFlow::ReturnResponse => Ok(WebhookResponseTracker::NoEffect),
api::WebhookFlow::Mandate => Box::pin(mandates_incoming_webhook_flow(
state.clone(),
merchant_context.clone(),
business_profile,
webhook_details,
source_verified,
event_type,
))
.await
.attach_printable("Incoming webhook flow for mandates failed"),
api::WebhookFlow::ExternalAuthentication => {
Box::pin(external_authentication_incoming_webhook_flow(
state.clone(),
req_state,
merchant_context.clone(),
source_verified,
event_type,
request_details,
connector,
object_ref_id,
business_profile,
merchant_connector_account,
))
.await
.attach_printable("Incoming webhook flow for external authentication failed")
}
api::WebhookFlow::FraudCheck => Box::pin(frm_incoming_webhook_flow(
state.clone(),
req_state,
merchant_context.clone(),
source_verified,
event_type,
object_ref_id,
business_profile,
))
.await
.attach_printable("Incoming webhook flow for fraud check failed"),
#[cfg(feature = "payouts")]
api::WebhookFlow::Payout => Box::pin(payouts_incoming_webhook_flow(
state.clone(),
merchant_context.clone(),
business_profile,
webhook_details,
event_type,
source_verified,
))
.await
.attach_printable("Incoming webhook flow for payouts failed"),
api::WebhookFlow::Subscription => {
Box::pin(subscriptions::webhooks::incoming_webhook_flow(
state.clone().into(),
merchant_context.clone(),
business_profile,
webhook_details,
source_verified,
connector,
request_details,
event_type,
merchant_connector_account,
))
.await
.attach_printable("Incoming webhook flow for subscription failed")
}
_ => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unsupported Flow Type received in incoming webhooks"),
}
};
match result_response {
Ok(response) => Ok(response),
Err(error) => {
let result = handle_incoming_webhook_error(
error,
connector,
connector_name,
request_details,
merchant_context.get_merchant_account().get_id(),
);
match result {
Ok((_, webhook_tracker, _)) => Ok(webhook_tracker),
Err(e) => Err(e),
}
}
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 241,
"total_crates": null
} |
fn_clm_router_external_authentication_incoming_webhook_flow_-1697265579327188042 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/incoming
async fn external_authentication_incoming_webhook_flow(
state: SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
source_verified: bool,
event_type: webhooks::IncomingWebhookEvent,
request_details: &IncomingWebhookRequestDetails<'_>,
connector: &ConnectorEnum,
object_ref_id: api::ObjectReferenceId,
business_profile: domain::Profile,
merchant_connector_account: domain::MerchantConnectorAccount,
) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
if source_verified {
let authentication_details = connector
.get_external_authentication_details(request_details)
.switch()?;
let trans_status = authentication_details.trans_status;
let authentication_update = storage::AuthenticationUpdate::PostAuthenticationUpdate {
authentication_status: common_enums::AuthenticationStatus::foreign_from(
trans_status.clone(),
),
trans_status,
eci: authentication_details.eci,
challenge_cancel: authentication_details.challenge_cancel,
challenge_code_reason: authentication_details.challenge_code_reason,
};
let authentication =
if let webhooks::ObjectReferenceId::ExternalAuthenticationID(authentication_id_type) =
object_ref_id
{
match authentication_id_type {
webhooks::AuthenticationIdType::AuthenticationId(authentication_id) => state
.store
.find_authentication_by_merchant_id_authentication_id(
merchant_context.get_merchant_account().get_id(),
&authentication_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::AuthenticationNotFound {
id: authentication_id.get_string_repr().to_string(),
})
.attach_printable("Error while fetching authentication record"),
webhooks::AuthenticationIdType::ConnectorAuthenticationId(
connector_authentication_id,
) => state
.store
.find_authentication_by_merchant_id_connector_authentication_id(
merchant_context.get_merchant_account().get_id().clone(),
connector_authentication_id.clone(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::AuthenticationNotFound {
id: connector_authentication_id,
})
.attach_printable("Error while fetching authentication record"),
}
} else {
Err(errors::ApiErrorResponse::WebhookProcessingFailure).attach_printable(
"received a non-external-authentication id for retrieving authentication",
)
}?;
let updated_authentication = state
.store
.update_authentication_by_merchant_id_authentication_id(
authentication,
authentication_update,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while updating authentication")?;
authentication_details
.authentication_value
.async_map(|auth_val| {
payment_methods::vault::create_tokenize(
&state,
auth_val.expose(),
None,
updated_authentication
.authentication_id
.clone()
.get_string_repr()
.to_string(),
merchant_context.get_merchant_key_store().key.get_inner(),
)
})
.await
.transpose()?;
// Check if it's a payment authentication flow, payment_id would be there only for payment authentication flows
if let Some(payment_id) = updated_authentication.payment_id {
let is_pull_mechanism_enabled = helper_utils::check_if_pull_mechanism_for_external_3ds_enabled_from_connector_metadata(merchant_connector_account.metadata.map(|metadata| metadata.expose()));
// Merchant doesn't have pull mechanism enabled and if it's challenge flow, we have to authorize whenever we receive a ARes webhook
if !is_pull_mechanism_enabled
&& updated_authentication.authentication_type
== Some(common_enums::DecoupledAuthenticationType::Challenge)
&& event_type == webhooks::IncomingWebhookEvent::ExternalAuthenticationARes
{
let payment_confirm_req = api::PaymentsRequest {
payment_id: Some(api_models::payments::PaymentIdType::PaymentIntentId(
payment_id,
)),
merchant_id: Some(merchant_context.get_merchant_account().get_id().clone()),
..Default::default()
};
let payments_response = Box::pin(payments::payments_core::<
api::Authorize,
api::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api::Authorize>,
>(
state.clone(),
req_state,
merchant_context.clone(),
None,
payments::PaymentConfirm,
payment_confirm_req,
services::api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
HeaderPayload::with_source(enums::PaymentSource::ExternalAuthenticator),
))
.await?;
match payments_response {
services::ApplicationResponse::JsonWithHeaders((payments_response, _)) => {
let payment_id = payments_response.payment_id.clone();
let status = payments_response.status;
let event_type: Option<enums::EventType> = payments_response.status.into();
// Set poll_id as completed in redis to allow the fetch status of poll through retrieve_poll_status api from client
let poll_id = core_utils::get_poll_id(
merchant_context.get_merchant_account().get_id(),
core_utils::get_external_authentication_request_poll_id(&payment_id),
);
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
redis_conn
.set_key_without_modifying_ttl(
&poll_id.into(),
api_models::poll::PollStatus::Completed.to_string(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add poll_id in redis")?;
// If event is NOT an UnsupportedEvent, trigger Outgoing Webhook
if let Some(outgoing_event_type) = event_type {
let primary_object_created_at = payments_response.created;
Box::pin(super::create_event_and_trigger_outgoing_webhook(
state,
merchant_context,
business_profile,
outgoing_event_type,
enums::EventClass::Payments,
payment_id.get_string_repr().to_owned(),
enums::EventObjectType::PaymentDetails,
api::OutgoingWebhookContent::PaymentDetails(Box::new(
payments_response,
)),
primary_object_created_at,
))
.await?;
};
let response = WebhookResponseTracker::Payment { payment_id, status };
Ok(response)
}
_ => Err(errors::ApiErrorResponse::WebhookProcessingFailure).attach_printable(
"Did not get payment id as object reference id in webhook payments flow",
)?,
}
} else {
Ok(WebhookResponseTracker::NoEffect)
}
} else {
Ok(WebhookResponseTracker::NoEffect)
}
} else {
logger::error!(
"Webhook source verification failed for external authentication webhook flow"
);
Err(report!(
errors::ApiErrorResponse::WebhookAuthenticationFailed
))
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 131,
"total_crates": null
} |
fn_clm_router_update_connector_mandate_details_-1697265579327188042 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/incoming
async fn update_connector_mandate_details(
state: &SessionState,
merchant_context: &domain::MerchantContext,
object_ref_id: api::ObjectReferenceId,
connector: &ConnectorEnum,
request_details: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<(), errors::ApiErrorResponse> {
let webhook_connector_mandate_details = connector
.get_mandate_details(request_details)
.switch()
.attach_printable("Could not find connector mandate details in incoming webhook body")?;
let webhook_connector_network_transaction_id = connector
.get_network_txn_id(request_details)
.switch()
.attach_printable(
"Could not find connector network transaction id in incoming webhook body",
)?;
// Either one OR both of the fields are present
if webhook_connector_mandate_details.is_some()
|| webhook_connector_network_transaction_id.is_some()
{
let payment_attempt =
get_payment_attempt_from_object_reference_id(state, object_ref_id, merchant_context)
.await?;
if let Some(ref payment_method_id) = payment_attempt.payment_method_id {
let key_manager_state = &state.into();
let payment_method_info = state
.store
.find_payment_method(
key_manager_state,
merchant_context.get_merchant_key_store(),
payment_method_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
// Update connector's mandate details
let updated_connector_mandate_details =
if let Some(webhook_mandate_details) = webhook_connector_mandate_details {
let mandate_details = payment_method_info
.get_common_mandate_reference()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize to Payment Mandate Reference")?;
let merchant_connector_account_id = payment_attempt
.merchant_connector_id
.clone()
.get_required_value("merchant_connector_id")?;
if mandate_details.payments.as_ref().is_none_or(|payments| {
!payments.0.contains_key(&merchant_connector_account_id)
}) {
// Update the payment attempt to maintain consistency across tables.
let (mandate_metadata, connector_mandate_request_reference_id) =
payment_attempt
.connector_mandate_detail
.as_ref()
.map(|details| {
(
details.mandate_metadata.clone(),
details.connector_mandate_request_reference_id.clone(),
)
})
.unwrap_or((None, None));
let connector_mandate_reference_id = ConnectorMandateReferenceId {
connector_mandate_id: Some(
webhook_mandate_details
.connector_mandate_id
.peek()
.to_string(),
),
payment_method_id: Some(payment_method_id.to_string()),
mandate_metadata,
connector_mandate_request_reference_id,
};
let attempt_update =
storage::PaymentAttemptUpdate::ConnectorMandateDetailUpdate {
connector_mandate_detail: Some(connector_mandate_reference_id),
updated_by: merchant_context
.get_merchant_account()
.storage_scheme
.to_string(),
};
state
.store
.update_payment_attempt_with_attempt_id(
payment_attempt.clone(),
attempt_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
insert_mandate_details(
&payment_attempt,
&webhook_mandate_details,
Some(mandate_details),
)?
} else {
logger::info!(
"Skipping connector mandate details update since they are already present."
);
None
}
} else {
None
};
let connector_mandate_details_value = updated_connector_mandate_details
.map(|common_mandate| {
common_mandate.get_mandate_details_value().map_err(|err| {
router_env::logger::error!(
"Failed to get get_mandate_details_value : {:?}",
err
);
errors::ApiErrorResponse::MandateUpdateFailed
})
})
.transpose()?;
let pm_update = diesel_models::PaymentMethodUpdate::ConnectorNetworkTransactionIdAndMandateDetailsUpdate {
connector_mandate_details: connector_mandate_details_value.map(masking::Secret::new),
network_transaction_id: webhook_connector_network_transaction_id
.map(|webhook_network_transaction_id| webhook_network_transaction_id.get_id().clone()),
};
state
.store
.update_payment_method(
key_manager_state,
merchant_context.get_merchant_key_store(),
payment_method_info,
pm_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update payment method in db")?;
}
}
Ok(())
}
| {
"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_incoming_webhooks_core_-1697265579327188042 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/incoming
async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(
state: SessionState,
req_state: ReqState,
req: &actix_web::HttpRequest,
merchant_context: domain::MerchantContext,
connector_name_or_mca_id: &str,
body: actix_web::web::Bytes,
is_relay_webhook: bool,
) -> errors::RouterResult<(
services::ApplicationResponse<serde_json::Value>,
WebhookResponseTracker,
serde_json::Value,
)> {
// Initial setup and metrics
metrics::WEBHOOK_INCOMING_COUNT.add(
1,
router_env::metric_attributes!((
MERCHANT_ID,
merchant_context.get_merchant_account().get_id().clone()
)),
);
let request_details = IncomingWebhookRequestDetails {
method: req.method().clone(),
uri: req.uri().clone(),
headers: req.headers(),
query_params: req.query_string().to_string(),
body: &body,
};
// Fetch the merchant connector account to get the webhooks source secret
let (merchant_connector_account, connector, connector_name) =
fetch_optional_mca_and_connector(&state, &merchant_context, connector_name_or_mca_id)
.await?;
// Determine webhook processing path (UCS vs non-UCS) and handle event type extraction
let webhook_processing_result =
match if unified_connector_service::should_call_unified_connector_service_for_webhooks(
&state,
&merchant_context,
&connector_name,
)
.await?
{
logger::info!(
connector = connector_name,
"Using Unified Connector Service for webhook processing",
);
process_ucs_webhook_transform(
&state,
&merchant_context,
&connector_name,
&body,
&request_details,
merchant_connector_account.as_ref(),
)
.await
} else {
// NON-UCS PATH: Need to decode body first
let decoded_body = connector
.decode_webhook_body(
&request_details,
merchant_context.get_merchant_account().get_id(),
merchant_connector_account
.clone()
.and_then(|mca| mca.connector_webhook_details.clone()),
&connector_name,
)
.await
.switch()
.attach_printable("There was an error in incoming webhook body decoding")?;
process_non_ucs_webhook(
&state,
&merchant_context,
&connector,
&connector_name,
decoded_body.into(),
&request_details,
)
.await
} {
Ok(result) => result,
Err(error) => {
let error_result = handle_incoming_webhook_error(
error,
&connector,
connector_name.as_str(),
&request_details,
merchant_context.get_merchant_account().get_id(),
);
match error_result {
Ok((response, webhook_tracker, serialized_request)) => {
return Ok((response, webhook_tracker, serialized_request));
}
Err(e) => return Err(e),
}
}
};
// if it is a setup webhook event, return ok status
if webhook_processing_result.event_type == webhooks::IncomingWebhookEvent::SetupWebhook {
return Ok((
services::ApplicationResponse::StatusOk,
WebhookResponseTracker::NoEffect,
serde_json::Value::default(),
));
}
// Update request_details with the appropriate body (decoded for non-UCS, raw for UCS)
let final_request_details = match &webhook_processing_result.decoded_body {
Some(decoded_body) => IncomingWebhookRequestDetails {
method: request_details.method.clone(),
uri: request_details.uri.clone(),
headers: request_details.headers,
query_params: request_details.query_params.clone(),
body: decoded_body,
},
None => request_details, // Use original request details for UCS
};
logger::info!(event_type=?webhook_processing_result.event_type);
// Check if webhook should be processed further
let is_webhook_event_supported = !matches!(
webhook_processing_result.event_type,
webhooks::IncomingWebhookEvent::EventNotSupported
);
let is_webhook_event_enabled = !utils::is_webhook_event_disabled(
&*state.clone().store,
connector_name.as_str(),
merchant_context.get_merchant_account().get_id(),
&webhook_processing_result.event_type,
)
.await;
let flow_type: api::WebhookFlow = webhook_processing_result.event_type.into();
let process_webhook_further = is_webhook_event_enabled
&& is_webhook_event_supported
&& !matches!(flow_type, api::WebhookFlow::ReturnResponse);
logger::info!(process_webhook=?process_webhook_further);
let mut event_object: Box<dyn masking::ErasedMaskSerialize> = Box::new(serde_json::Value::Null);
let webhook_effect = match process_webhook_further {
true => {
let business_logic_result = process_webhook_business_logic(
&state,
req_state,
&merchant_context,
&connector,
&connector_name,
webhook_processing_result.event_type,
webhook_processing_result.source_verified,
&webhook_processing_result.transform_data,
&final_request_details,
is_relay_webhook,
)
.await;
match business_logic_result {
Ok(response) => {
// Extract event object for serialization
event_object = extract_webhook_event_object(
&webhook_processing_result.transform_data,
&connector,
&final_request_details,
)?;
response
}
Err(error) => {
let error_result = handle_incoming_webhook_error(
error,
&connector,
connector_name.as_str(),
&final_request_details,
merchant_context.get_merchant_account().get_id(),
);
match error_result {
Ok((_, webhook_tracker, _)) => webhook_tracker,
Err(e) => return Err(e),
}
}
}
}
false => {
metrics::WEBHOOK_INCOMING_FILTERED_COUNT.add(
1,
router_env::metric_attributes!((
MERCHANT_ID,
merchant_context.get_merchant_account().get_id().clone()
)),
);
WebhookResponseTracker::NoEffect
}
};
// Generate response
let response = connector
.get_webhook_api_response(&final_request_details, None)
.switch()
.attach_printable("Could not get incoming webhook api response from connector")?;
let serialized_request = event_object
.masked_serialize()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Could not convert webhook effect to string")?;
Ok((response, webhook_effect, serialized_request))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 100,
"total_crates": null
} |
fn_clm_router_payments_incoming_webhook_flow_-1697265579327188042 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/incoming
async fn payments_incoming_webhook_flow(
state: SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
business_profile: domain::Profile,
webhook_details: api::IncomingWebhookDetails,
source_verified: bool,
connector: &ConnectorEnum,
request_details: &IncomingWebhookRequestDetails<'_>,
event_type: webhooks::IncomingWebhookEvent,
webhook_transform_data: &Option<Box<unified_connector_service::WebhookTransformData>>,
) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
let consume_or_trigger_flow = if source_verified {
// Determine the appropriate action based on UCS availability
let resource_object = webhook_details.resource_object;
match webhook_transform_data.as_ref() {
Some(transform_data) => {
// Serialize the transform data to pass to UCS handler
let transform_data_bytes = serde_json::to_vec(transform_data.as_ref())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to serialize UCS webhook transform data")?;
payments::CallConnectorAction::UCSHandleResponse(transform_data_bytes)
}
None => payments::CallConnectorAction::HandleResponse(resource_object),
}
} else {
payments::CallConnectorAction::Trigger
};
let payments_response = match webhook_details.object_reference_id {
webhooks::ObjectReferenceId::PaymentId(ref id) => {
let payment_id = get_payment_id(
state.store.as_ref(),
id,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let lock_action = api_locking::LockAction::Hold {
input: api_locking::LockingInput {
unique_locking_key: payment_id.get_string_repr().to_owned(),
api_identifier: lock_utils::ApiIdentifier::Payments,
override_lock_retries: None,
},
};
lock_action
.clone()
.perform_locking_action(
&state,
merchant_context.get_merchant_account().get_id().to_owned(),
)
.await?;
let response = Box::pin(payments::payments_core::<
api::PSync,
api::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api::PSync>,
>(
state.clone(),
req_state,
merchant_context.clone(),
None,
payments::operations::PaymentStatus,
api::PaymentsRetrieveRequest {
resource_id: id.clone(),
merchant_id: Some(merchant_context.get_merchant_account().get_id().clone()),
force_sync: true,
connector: None,
param: None,
merchant_connector_details: None,
client_secret: None,
expand_attempts: None,
expand_captures: None,
all_keys_required: None,
},
services::AuthFlow::Merchant,
consume_or_trigger_flow.clone(),
None,
HeaderPayload::default(),
))
.await;
// When mandate details are present in successful webhooks, and consuming webhooks are skipped during payment sync if the payment status is already updated to charged, this function is used to update the connector mandate details.
if should_update_connector_mandate_details(source_verified, event_type) {
update_connector_mandate_details(
&state,
&merchant_context,
webhook_details.object_reference_id.clone(),
connector,
request_details,
)
.await?
};
lock_action
.free_lock_action(
&state,
merchant_context.get_merchant_account().get_id().to_owned(),
)
.await?;
match response {
Ok(value) => value,
Err(err)
if matches!(
err.current_context(),
&errors::ApiErrorResponse::PaymentNotFound
) && state
.conf
.webhooks
.ignore_error
.payment_not_found
.unwrap_or(true) =>
{
metrics::WEBHOOK_PAYMENT_NOT_FOUND.add(
1,
router_env::metric_attributes!((
"merchant_id",
merchant_context.get_merchant_account().get_id().clone()
)),
);
return Ok(WebhookResponseTracker::NoEffect);
}
error @ Err(_) => error?,
}
}
_ => Err(errors::ApiErrorResponse::WebhookProcessingFailure).attach_printable(
"Did not get payment id as object reference id in webhook payments flow",
)?,
};
match payments_response {
services::ApplicationResponse::JsonWithHeaders((payments_response, _)) => {
let payment_id = payments_response.payment_id.clone();
let status = payments_response.status;
let event_type: Option<enums::EventType> = payments_response.status.into();
// If event is NOT an UnsupportedEvent, trigger Outgoing Webhook
if let Some(outgoing_event_type) = event_type {
let primary_object_created_at = payments_response.created;
Box::pin(super::create_event_and_trigger_outgoing_webhook(
state,
merchant_context,
business_profile,
outgoing_event_type,
enums::EventClass::Payments,
payment_id.get_string_repr().to_owned(),
enums::EventObjectType::PaymentDetails,
api::OutgoingWebhookContent::PaymentDetails(Box::new(payments_response)),
primary_object_created_at,
))
.await?;
};
let response = WebhookResponseTracker::Payment { payment_id, status };
Ok(response)
}
_ => Err(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("received non-json response from payments core")?,
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 100,
"total_crates": null
} |
fn_clm_router_list_initial_delivery_attempts_5948976530536712184 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/webhook_events
pub async fn list_initial_delivery_attempts(
state: SessionState,
merchant_id: common_utils::id_type::MerchantId,
api_constraints: api::webhook_events::EventListConstraints,
) -> RouterResponse<api::webhook_events::TotalEventsResponse> {
let profile_id = api_constraints.profile_id.clone();
let constraints = api::webhook_events::EventListConstraintsInternal::foreign_try_from(
api_constraints.clone(),
)?;
let store = state.store.as_ref();
let key_manager_state = &(&state).into();
let (account, key_store) =
get_account_and_key_store(state.clone(), merchant_id.clone(), profile_id.clone()).await?;
let now = common_utils::date_time::now();
let events_list_begin_time =
(now.date() - time::Duration::days(INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_DAYS)).midnight();
let (events, total_count) = match constraints {
api_models::webhook_events::EventListConstraintsInternal::ObjectIdFilter { object_id } => {
let events = match account {
MerchantAccountOrProfile::MerchantAccount(merchant_account) => {
store
.list_initial_events_by_merchant_id_primary_object_id(
key_manager_state,
merchant_account.get_id(),
&object_id,
&key_store,
)
.await
}
MerchantAccountOrProfile::Profile(business_profile) => {
store
.list_initial_events_by_profile_id_primary_object_id(
key_manager_state,
business_profile.get_id(),
&object_id,
&key_store,
)
.await
}
}
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to list events with specified constraints")?;
let total_count = i64::try_from(events.len())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while converting from usize to i64")?;
(events, total_count)
}
api_models::webhook_events::EventListConstraintsInternal::GenericFilter {
created_after,
created_before,
limit,
offset,
event_classes,
event_types,
is_delivered,
} => {
let limit = match limit {
Some(limit) if limit <= INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_LIMIT => Ok(Some(limit)),
Some(limit) if limit > INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_LIMIT => Err(
errors::ApiErrorResponse::InvalidRequestData{
message: format!("`limit` must be a number less than {INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_LIMIT}")
}
),
_ => Ok(Some(INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_LIMIT)),
}?;
let offset = match offset {
Some(offset) if offset > 0 => Some(offset),
_ => None,
};
let event_classes = event_classes.unwrap_or(HashSet::new());
let mut event_types = event_types.unwrap_or(HashSet::new());
if !event_classes.is_empty() {
event_types = finalize_event_types(event_classes, event_types).await?;
}
fp_utils::when(
!created_after
.zip(created_before)
.map(|(created_after, created_before)| created_after <= created_before)
.unwrap_or(true),
|| {
Err(errors::ApiErrorResponse::InvalidRequestData { message: "The `created_after` timestamp must be an earlier timestamp compared to the `created_before` timestamp".to_string() })
},
)?;
let created_after = match created_after {
Some(created_after) => {
if created_after < events_list_begin_time {
Err(errors::ApiErrorResponse::InvalidRequestData { message: format!("`created_after` must be a timestamp within the past {INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_DAYS} days.") })
} else {
Ok(created_after)
}
}
None => Ok(events_list_begin_time),
}?;
let created_before = match created_before {
Some(created_before) => {
if created_before < events_list_begin_time {
Err(errors::ApiErrorResponse::InvalidRequestData { message: format!("`created_before` must be a timestamp within the past {INITIAL_DELIVERY_ATTEMPTS_LIST_MAX_DAYS} days.") })
} else {
Ok(created_before)
}
}
None => Ok(now),
}?;
let events = match account {
MerchantAccountOrProfile::MerchantAccount(merchant_account) => {
store
.list_initial_events_by_merchant_id_constraints(
key_manager_state,
merchant_account.get_id(),
created_after,
created_before,
limit,
offset,
event_types.clone(),
is_delivered,
&key_store,
)
.await
}
MerchantAccountOrProfile::Profile(business_profile) => {
store
.list_initial_events_by_profile_id_constraints(
key_manager_state,
business_profile.get_id(),
created_after,
created_before,
limit,
offset,
event_types.clone(),
is_delivered,
&key_store,
)
.await
}
}
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to list events with specified constraints")?;
let total_count = store
.count_initial_events_by_constraints(
&merchant_id,
profile_id,
created_after,
created_before,
event_types,
is_delivered,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get total events count")?;
(events, total_count)
}
};
let events = events
.into_iter()
.map(api::webhook_events::EventListItemResponse::try_from)
.collect::<Result<Vec<_>, _>>()?;
Ok(ApplicationResponse::Json(
api::webhook_events::TotalEventsResponse::new(total_count, events),
))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 114,
"total_crates": null
} |
fn_clm_router_retry_delivery_attempt_5948976530536712184 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/webhook_events
pub async fn retry_delivery_attempt(
state: SessionState,
merchant_id: common_utils::id_type::MerchantId,
event_id: String,
) -> RouterResponse<api::webhook_events::EventRetrieveResponse> {
let store = state.store.as_ref();
let key_manager_state = &(&state).into();
let key_store = store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&store.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let event_to_retry = store
.find_event_by_merchant_id_event_id(
key_manager_state,
&key_store.merchant_id,
&event_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::EventNotFound)?;
let business_profile_id = event_to_retry
.business_profile_id
.get_required_value("business_profile_id")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to read business profile ID from event to retry")?;
let business_profile = store
.find_business_profile_by_profile_id(key_manager_state, &key_store, &business_profile_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to find business profile")?;
let delivery_attempt = storage::enums::WebhookDeliveryAttempt::ManualRetry;
let new_event_id = super::utils::generate_event_id();
let idempotent_event_id = super::utils::get_idempotent_event_id(
&event_to_retry.primary_object_id,
event_to_retry.event_type,
delivery_attempt,
)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to generate idempotent event ID")?;
let now = common_utils::date_time::now();
let new_event = domain::Event {
event_id: new_event_id.clone(),
event_type: event_to_retry.event_type,
event_class: event_to_retry.event_class,
is_webhook_notified: false,
primary_object_id: event_to_retry.primary_object_id,
primary_object_type: event_to_retry.primary_object_type,
created_at: now,
merchant_id: Some(business_profile.merchant_id.clone()),
business_profile_id: Some(business_profile.get_id().to_owned()),
primary_object_created_at: event_to_retry.primary_object_created_at,
idempotent_event_id: Some(idempotent_event_id),
initial_attempt_id: event_to_retry.initial_attempt_id,
request: event_to_retry.request,
response: None,
delivery_attempt: Some(delivery_attempt),
metadata: event_to_retry.metadata,
is_overall_delivery_successful: Some(false),
};
let event = store
.insert_event(key_manager_state, new_event, &key_store)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to insert event")?;
// We only allow retrying deliveries for events with `request` populated.
let request_content = event
.request
.as_ref()
.get_required_value("request")
.change_context(errors::ApiErrorResponse::InternalServerError)?
.peek()
.parse_struct("OutgoingWebhookRequestContent")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse webhook event request information")?;
Box::pin(super::outgoing::trigger_webhook_and_raise_event(
state.clone(),
business_profile,
&key_store,
event,
request_content,
delivery_attempt,
None,
None,
))
.await;
let updated_event = store
.find_event_by_merchant_id_event_id(
key_manager_state,
&key_store.merchant_id,
&new_event_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::EventNotFound)?;
Ok(ApplicationResponse::Json(
api::webhook_events::EventRetrieveResponse::try_from(updated_event)?,
))
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 95,
"total_crates": null
} |
fn_clm_router_list_delivery_attempts_5948976530536712184 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/webhook_events
pub async fn list_delivery_attempts(
state: SessionState,
merchant_id: common_utils::id_type::MerchantId,
initial_attempt_id: String,
) -> RouterResponse<Vec<api::webhook_events::EventRetrieveResponse>> {
let store = state.store.as_ref();
let key_manager_state = &(&state).into();
let key_store = store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&store.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let events = store
.list_events_by_merchant_id_initial_attempt_id(
key_manager_state,
&merchant_id,
&initial_attempt_id,
&key_store,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to list delivery attempts for initial event")?;
if events.is_empty() {
Err(error_stack::report!(
errors::ApiErrorResponse::EventNotFound
))
.attach_printable("No delivery attempts found with the specified `initial_attempt_id`")
} else {
Ok(ApplicationResponse::Json(
events
.into_iter()
.map(api::webhook_events::EventRetrieveResponse::try_from)
.collect::<Result<Vec<_>, _>>()?,
))
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 43,
"total_crates": null
} |
fn_clm_router_get_account_and_key_store_5948976530536712184 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/webhook_events
async fn get_account_and_key_store(
state: SessionState,
merchant_id: common_utils::id_type::MerchantId,
profile_id: Option<common_utils::id_type::ProfileId>,
) -> errors::RouterResult<(MerchantAccountOrProfile, domain::MerchantKeyStore)> {
let store = state.store.as_ref();
let key_manager_state = &(&state).into();
let merchant_key_store = store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&store.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
match profile_id {
// If profile ID is specified, return business profile, since a business profile is more
// specific than a merchant account.
Some(profile_id) => {
let business_profile = store
.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
&merchant_key_store,
&merchant_id,
&profile_id,
)
.await
.attach_printable_lazy(|| {
format!(
"Failed to find business profile by merchant_id `{merchant_id:?}` and profile_id `{profile_id:?}`. \
The merchant_id associated with the business profile `{profile_id:?}` may be \
different than the merchant_id specified (`{merchant_id:?}`)."
)
})
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
Ok((
MerchantAccountOrProfile::Profile(Box::new(business_profile)),
merchant_key_store,
))
}
None => {
let merchant_account = store
.find_merchant_account_by_merchant_id(
key_manager_state,
&merchant_id,
&merchant_key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
Ok((
MerchantAccountOrProfile::MerchantAccount(Box::new(merchant_account)),
merchant_key_store,
))
}
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 39,
"total_crates": null
} |
fn_clm_router_finalize_event_types_5948976530536712184 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/webhook_events
async fn finalize_event_types(
event_classes: HashSet<common_enums::EventClass>,
mut event_types: HashSet<common_enums::EventType>,
) -> CustomResult<HashSet<common_enums::EventType>, errors::ApiErrorResponse> {
// Examples:
// 1. event_classes = ["payments", "refunds"], event_types = ["payment_succeeded"]
// 2. event_classes = ["refunds"], event_types = ["payment_succeeded"]
// Create possible_event_types based on event_classes
// Example 1: possible_event_types = ["payment_*", "refund_*"]
// Example 2: possible_event_types = ["refund_*"]
let possible_event_types = event_classes
.clone()
.into_iter()
.flat_map(common_enums::EventClass::event_types)
.collect::<HashSet<_>>();
if event_types.is_empty() {
return Ok(possible_event_types);
}
// Extend event_types if disjoint with event_classes
// Example 1: event_types = ["payment_succeeded", "refund_*"], is_disjoint is used to extend "refund_*" and ignore "payment_*".
// Example 2: event_types = ["payment_succeeded", "refund_*"], is_disjoint is only used to extend "refund_*".
event_classes.into_iter().for_each(|class| {
let valid_event_types = class.event_types();
if event_types.is_disjoint(&valid_event_types) {
event_types.extend(valid_event_types);
}
});
// Validate event_types is a subset of possible_event_types
// Example 1: event_types is a subset of possible_event_types (valid)
// Example 2: event_types is not a subset of possible_event_types (error due to "payment_succeeded")
if !event_types.is_subset(&possible_event_types) {
return Err(error_stack::report!(
errors::ApiErrorResponse::InvalidRequestData {
message: "`event_types` must be a subset of `event_classes`".to_string(),
}
));
}
Ok(event_types.clone())
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 25,
"total_crates": null
} |
fn_clm_router_construct_webhook_router_data_1595426940056822842 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/utils
pub async fn construct_webhook_router_data(
state: &SessionState,
connector_name: &str,
merchant_connector_account: domain::MerchantConnectorAccount,
merchant_context: &domain::MerchantContext,
connector_wh_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
request_details: &api::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<types::VerifyWebhookSourceRouterData, errors::ApiErrorResponse> {
let auth_type: types::ConnectorAuthType =
helpers::MerchantConnectorAccountType::DbVal(Box::new(merchant_connector_account.clone()))
.get_connector_account_details()
.parse_value("ConnectorAuthType")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let router_data = types::RouterData {
flow: PhantomData,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
connector: connector_name.to_string(),
customer_id: None,
tenant_id: state.tenant.tenant_id.clone(),
payment_id: common_utils::id_type::PaymentId::get_irrelevant_id("source_verification_flow")
.get_string_repr()
.to_owned(),
attempt_id: IRRELEVANT_ATTEMPT_ID_IN_SOURCE_VERIFICATION_FLOW.to_string(),
status: diesel_models::enums::AttemptStatus::default(),
payment_method: diesel_models::enums::PaymentMethod::default(),
payment_method_type: None,
connector_auth_type: auth_type,
description: None,
address: PaymentAddress::default(),
auth_type: diesel_models::enums::AuthenticationType::default(),
connector_meta_data: None,
connector_wallets_details: None,
amount_captured: None,
minor_amount_captured: None,
request: types::VerifyWebhookSourceRequestData {
webhook_headers: request_details.headers.clone(),
webhook_body: request_details.body.to_vec().clone(),
merchant_secret: connector_wh_secrets.to_owned(),
},
response: Err(types::ErrorResponse::default()),
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
connector_customer: None,
recurring_mandate_payment_data: None,
preprocessing_id: None,
connector_request_reference_id:
IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_SOURCE_VERIFICATION_FLOW.to_string(),
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
test_mode: None,
payment_method_balance: None,
payment_method_status: None,
connector_api_version: None,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
refund_id: None,
dispute_id: None,
connector_response: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload: None,
connector_mandate_request_reference_id: None,
authentication_id: None,
psd2_sca_exemption_type: None,
raw_connector_response: None,
is_payment_id_from_merchant: None,
l2_l3_data: None,
minor_amount_capturable: None,
authorized_amount: None,
};
Ok(router_data)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 66,
"total_crates": null
} |
fn_clm_router_free_redis_lock_1595426940056822842 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/utils
pub(super) async fn free_redis_lock<A>(
state: &A,
unique_locking_key: &str,
merchant_id: common_utils::id_type::MerchantId,
lock_value: Option<String>,
) -> RouterResult<()>
where
A: SessionStateInfo,
{
let redis_conn = state
.store()
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error connecting to redis")?;
let redis_locking_key = format!(
"{}_{}_{}",
WEBHOOK_LOCK_PREFIX,
merchant_id.get_string_repr(),
unique_locking_key
);
match redis_conn
.get_key::<Option<String>>(&redis_locking_key.as_str().into())
.await
{
Ok(val) => {
if val == lock_value {
match redis_conn
.delete_key(&redis_locking_key.as_str().into())
.await
{
Ok(redis::types::DelReply::KeyDeleted) => {
logger::info!("Lock freed {redis_locking_key}");
tracing::Span::current().record("redis_lock_released", redis_locking_key);
Ok(())
}
Ok(redis::types::DelReply::KeyNotDeleted) => Err(
errors::ApiErrorResponse::InternalServerError,
)
.attach_printable("Status release lock called but key is not found in redis"),
Err(error) => Err(error)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while deleting redis key"),
}
} else {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("The redis value which acquired the lock is not equal to the redis value requesting for releasing the lock")
}
}
Err(error) => Err(error)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while deleting redis key"),
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 50,
"total_crates": null
} |
fn_clm_router_perform_redis_lock_1595426940056822842 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/utils
pub(super) async fn perform_redis_lock<A>(
state: &A,
unique_locking_key: &str,
merchant_id: common_utils::id_type::MerchantId,
) -> RouterResult<Option<String>>
where
A: SessionStateInfo,
{
let lock_value: String = uuid::Uuid::new_v4().to_string();
let redis_conn = state
.store()
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error connecting to redis")?;
let redis_locking_key = format!(
"{}_{}_{}",
WEBHOOK_LOCK_PREFIX,
merchant_id.get_string_repr(),
unique_locking_key
);
let redis_lock_expiry_seconds = state.conf().webhooks.redis_lock_expiry_seconds;
let redis_lock_result = redis_conn
.set_key_if_not_exists_with_expiry(
&redis_locking_key.as_str().into(),
lock_value.clone(),
Some(i64::from(redis_lock_expiry_seconds)),
)
.await;
match redis_lock_result {
Ok(redis::SetnxReply::KeySet) => {
logger::info!("Lock acquired for for {redis_locking_key}");
Ok(Some(lock_value))
}
Ok(redis::SetnxReply::KeyNotSet) => {
logger::info!("Lock already held for {redis_locking_key}");
Ok(None)
}
Err(err) => Err(err
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error acquiring redis lock")),
}
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 41,
"total_crates": null
} |
fn_clm_router_get_idempotent_event_id_1595426940056822842 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/utils
pub(crate) fn get_idempotent_event_id(
primary_object_id: &str,
event_type: types::storage::enums::EventType,
delivery_attempt: types::storage::enums::WebhookDeliveryAttempt,
) -> Result<String, Report<errors::WebhooksFlowError>> {
use crate::types::storage::enums::WebhookDeliveryAttempt;
const EVENT_ID_SUFFIX_LENGTH: usize = 8;
let common_prefix = format!("{primary_object_id}_{event_type}");
// Hash the common prefix with SHA256 and encode with URL-safe base64 without padding
let digest = crypto::Sha256
.generate_digest(common_prefix.as_bytes())
.change_context(errors::WebhooksFlowError::IdGenerationFailed)
.attach_printable("Failed to generate idempotent event ID")?;
let base_encoded = consts::BASE64_ENGINE_URL_SAFE_NO_PAD.encode(digest);
let result = match delivery_attempt {
WebhookDeliveryAttempt::InitialAttempt => base_encoded,
WebhookDeliveryAttempt::AutomaticRetry | WebhookDeliveryAttempt::ManualRetry => {
common_utils::generate_id(EVENT_ID_SUFFIX_LENGTH, &base_encoded)
}
};
Ok(result)
}
| {
"crate": "router",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 31,
"total_crates": null
} |
fn_clm_router_is_webhook_event_disabled_1595426940056822842 | clm | function | // Repository: hyperswitch
// Crate: router
// Purpose: Main application server handling HTTP requests, authentication, and business logic orchestration
// Module: crates/router/src/core/webhooks/utils
/// Check whether the merchant has configured to disable the webhook `event` for the `connector`
/// First check for the key "whconf_{merchant_id}_{connector_id}" in redis,
/// if not found, fetch from configs table in database
pub async fn is_webhook_event_disabled(
db: &dyn StorageInterface,
connector_id: &str,
merchant_id: &common_utils::id_type::MerchantId,
event: &api::IncomingWebhookEvent,
) -> bool {
let redis_key = merchant_id.get_webhook_config_disabled_events_key(connector_id);
let merchant_webhook_disable_config_result: CustomResult<
api::MerchantWebhookConfig,
redis_interface::errors::RedisError,
> = get_and_deserialize_key(db, &redis_key, "MerchantWebhookConfig").await;
match merchant_webhook_disable_config_result {
Ok(merchant_webhook_config) => merchant_webhook_config.contains(event),
Err(..) => {
//if failed to fetch from redis. fetch from db and populate redis
db.find_config_by_key(&redis_key)
.await
.map(|config| {
match serde_json::from_str::<api::MerchantWebhookConfig>(&config.config) {
Ok(set) => set.contains(event),
Err(err) => {
logger::warn!(?err, "error while parsing merchant webhook config");
false
}
}
})
.unwrap_or_else(|err| {
logger::warn!(?err, "error while fetching merchant webhook config");
false
})
}
}
}
| {
"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
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.