id
stringlengths 20
153
| type
stringclasses 1
value | granularity
stringclasses 14
values | content
stringlengths 16
84.3k
| metadata
dict |
|---|---|---|---|---|
connector-service_small_file_connector-integration_-6830782010146565307
|
clm
|
small_file
|
// connector-service/backend/connector-integration/src/connectors/aci/aci_result_codes.rs
pub(super) const FAILURE_CODES: [&str; 502] = [
"100.370.100",
"100.370.110",
"100.370.111",
"100.380.100",
"100.380.101",
"100.380.110",
"100.380.201",
"100.380.305",
"100.380.306",
"100.380.401",
"100.380.501",
"100.395.502",
"100.396.101",
"100.400.000",
"100.400.001",
"100.400.002",
"100.400.005",
"100.400.007",
"100.400.020",
"100.400.021",
"100.400.030",
"100.400.039",
"100.400.040",
"100.400.041",
"100.400.042",
"100.400.043",
"100.400.044",
"100.400.045",
"100.400.051",
"100.400.060",
"100.400.061",
"100.400.063",
"100.400.064",
"100.400.065",
"100.400.071",
"100.400.080",
"100.400.081",
"100.400.083",
"100.400.084",
"100.400.085",
"100.400.086",
"100.400.087",
"100.400.091",
"100.400.100",
"100.400.120",
"100.400.121",
"100.400.122",
"100.400.123",
"100.400.130",
"100.400.139",
"100.400.140",
"100.400.141",
"100.400.142",
"100.400.143",
"100.400.144",
"100.400.145",
"100.400.146",
"100.400.147",
"100.400.148",
"100.400.149",
"100.400.150",
"100.400.151",
"100.400.152",
"100.400.241",
"100.400.242",
"100.400.243",
"100.400.260",
"100.400.300",
"100.400.301",
"100.400.302",
"100.400.303",
"100.400.304",
"100.400.305",
"100.400.306",
"100.400.307",
"100.400.308",
"100.400.309",
"100.400.310",
"100.400.311",
"100.400.312",
"100.400.313",
"100.400.314",
"100.400.315",
"100.400.316",
"100.400.317",
"100.400.318",
"100.400.319",
"100.400.320",
"100.400.321",
"100.400.322",
"100.400.323",
"100.400.324",
"100.400.325",
"100.400.326",
"100.400.327",
"100.400.328",
"800.400.100",
"800.400.101",
"800.400.102",
"800.400.103",
"800.400.104",
"800.400.105",
"800.400.110",
"800.400.150",
"800.400.151",
"100.380.401",
"100.390.101",
"100.390.102",
"100.390.103",
"100.390.104",
"100.390.105",
"100.390.106",
"100.390.107",
"100.390.108",
"100.390.109",
"100.390.110",
"100.390.111",
"100.390.112",
"100.390.113",
"100.390.114",
"100.390.115",
"100.390.116",
"100.390.117",
"100.390.118",
"800.400.200",
"100.100.701",
"800.200.159",
"800.200.160",
"800.200.165",
"800.200.202",
"800.200.208",
"800.200.220",
"800.300.101",
"800.300.102",
"800.300.200",
"800.300.301",
"800.300.302",
"800.300.401",
"800.300.500",
"800.300.501",
"800.310.200",
"800.310.210",
"800.310.211",
"800.110.100",
"800.120.100",
"800.120.101",
"800.120.102",
"800.120.103",
"800.120.200",
"800.120.201",
"800.120.202",
"800.120.203",
"800.120.300",
"800.120.401",
"800.130.100",
"800.140.100",
"800.140.101",
"800.140.110",
"800.140.111",
"800.140.112",
"800.140.113",
"800.150.100",
"800.160.100",
"800.160.110",
"800.160.120",
"800.160.130",
"500.100.201",
"500.100.202",
"500.100.203",
"500.100.301",
"500.100.302",
"500.100.303",
"500.100.304",
"500.100.401",
"500.100.402",
"500.100.403",
"500.200.101",
"600.200.100",
"600.200.200",
"600.200.201",
"600.200.202",
"600.200.300",
"600.200.310",
"600.200.400",
"600.200.500",
"600.200.501",
"600.200.600",
"600.200.700",
"600.200.800",
"600.200.810",
"600.300.101",
"600.300.200",
"600.300.210",
"600.300.211",
"800.121.100",
"800.121.200",
"100.150.100",
"100.150.101",
"100.150.200",
"100.150.201",
"100.150.202",
"100.150.203",
"100.150.204",
"100.150.205",
"100.150.300",
"100.350.100",
"100.350.101",
"100.350.200",
"100.350.201",
"100.350.301",
"100.350.302",
"100.350.303",
"100.350.310",
"100.350.311",
"100.350.312",
"100.350.313",
"100.350.314",
"100.350.315",
"100.350.316",
"100.350.400",
"100.350.500",
"100.350.601",
"100.350.602",
"100.250.100",
"100.250.105",
"100.250.106",
"100.250.107",
"100.250.110",
"100.250.111",
"100.250.120",
"100.250.121",
"100.250.122",
"100.250.123",
"100.250.124",
"100.250.125",
"100.250.250",
"100.360.201",
"100.360.300",
"100.360.303",
"100.360.400",
"700.100.100",
"700.100.200",
"700.100.300",
"700.100.400",
"700.100.500",
"700.100.600",
"700.100.700",
"700.100.701",
"700.100.710",
"700.300.100",
"700.300.200",
"700.300.300",
"700.300.400",
"700.300.500",
"700.300.600",
"700.300.700",
"700.300.800",
"700.400.000",
"700.400.100",
"700.400.101",
"700.400.200",
"700.400.300",
"700.400.400",
"700.400.402",
"700.400.410",
"700.400.411",
"700.400.420",
"700.400.510",
"700.400.520",
"700.400.530",
"700.400.540",
"700.400.550",
"700.400.560",
"700.400.561",
"700.400.562",
"700.400.565",
"700.400.570",
"700.400.580",
"700.400.590",
"700.400.600",
"700.400.700",
"700.450.001",
"700.500.001",
"700.500.002",
"700.500.003",
"700.500.004",
"100.300.101",
"100.300.200",
"100.300.300",
"100.300.400",
"100.300.401",
"100.300.402",
"100.300.501",
"100.300.600",
"100.300.601",
"100.300.700",
"100.300.701",
"100.370.100",
"100.370.101",
"100.370.102",
"100.370.110",
"100.370.111",
"100.370.121",
"100.370.122",
"100.370.123",
"100.370.124",
"100.370.125",
"100.370.131",
"100.370.132",
"100.500.101",
"100.500.201",
"100.500.301",
"100.500.302",
"100.500.303",
"100.500.304",
"100.600.500",
"100.900.500",
"200.100.101",
"200.100.102",
"200.100.103",
"200.100.150",
"200.100.151",
"200.100.199",
"200.100.201",
"200.100.300",
"200.100.301",
"200.100.302",
"200.100.401",
"200.100.402",
"200.100.403",
"200.100.404",
"200.100.501",
"200.100.502",
"200.100.503",
"200.100.504",
"200.100.601",
"200.100.602",
"200.100.603",
"200.200.106",
"200.300.403",
"200.300.404",
"200.300.405",
"200.300.406",
"200.300.407",
"800.900.100",
"800.900.101",
"800.900.200",
"800.900.201",
"800.900.300",
"800.900.301",
"800.900.302",
"800.900.303",
"800.900.399",
"800.900.401",
"800.900.450",
"100.800.100",
"100.800.101",
"100.800.102",
"100.800.200",
"100.800.201",
"100.800.202",
"100.800.300",
"100.800.301",
"100.800.302",
"100.800.400",
"100.800.401",
"100.800.500",
"100.800.501",
"100.700.100",
"100.700.101",
"100.700.200",
"100.700.201",
"100.700.300",
"100.700.400",
"100.700.500",
"100.700.800",
"100.700.801",
"100.700.802",
"100.700.810",
"100.900.100",
"100.900.101",
"100.900.105",
"100.900.200",
"100.900.300",
"100.900.301",
"100.900.400",
"100.900.401",
"100.900.450",
"100.900.500",
"100.100.100",
"100.100.101",
"100.100.104",
"100.100.200",
"100.100.201",
"100.100.300",
"100.100.301",
"100.100.303",
"100.100.304",
"100.100.305",
"100.100.400",
"100.100.401",
"100.100.402",
"100.100.500",
"100.100.501",
"100.100.600",
"100.100.601",
"100.100.650",
"100.100.651",
"100.100.700",
"100.100.701",
"100.200.100",
"100.200.103",
"100.200.104",
"100.200.200",
"100.210.101",
"100.210.102",
"100.211.101",
"100.211.102",
"100.211.103",
"100.211.104",
"100.211.105",
"100.211.106",
"100.212.101",
"100.212.102",
"100.212.103",
"100.550.300",
"100.550.301",
"100.550.303",
"100.550.310",
"100.550.311",
"100.550.312",
"100.550.400",
"100.550.401",
"100.550.601",
"100.550.603",
"100.550.605",
"100.550.701",
"100.550.702",
"100.380.101",
"100.380.201",
"100.380.305",
"100.380.306",
"800.100.100",
"800.100.150",
"800.100.151",
"800.100.152",
"800.100.153",
"800.100.154",
"800.100.155",
"800.100.156",
"800.100.157",
"800.100.158",
"800.100.159",
"800.100.160",
"800.100.161",
"800.100.162",
"800.100.163",
"800.100.164",
"800.100.165",
"800.100.166",
"800.100.167",
"800.100.168",
"800.100.169",
"800.100.170",
"800.100.171",
"800.100.172",
"800.100.173",
"800.100.174",
"800.100.175",
"800.100.176",
"800.100.177",
"800.100.178",
"800.100.179",
"800.100.190",
"800.100.191",
"800.100.192",
"800.100.195",
"800.100.196",
"800.100.197",
"800.100.198",
"800.100.199",
"800.100.200",
"800.100.201",
"800.100.202",
"800.100.203",
"800.100.204",
"800.100.205",
"800.100.206",
"800.100.207",
"800.100.208",
"800.100.402",
"800.100.403",
"800.100.500",
"800.100.501",
"800.700.100",
"800.700.101",
"800.700.201",
"800.700.500",
"800.800.102",
"800.800.202",
"800.800.302",
"100.390.100",
];
pub(super) const SUCCESSFUL_CODES: [&str; 16] = [
"000.000.000",
"000.000.100",
"000.100.105",
"000.100.106",
"000.100.110",
"000.100.111",
"000.100.112",
"000.300.000",
"000.300.100",
"000.300.101",
"000.300.102",
"000.300.103",
"000.310.100",
"000.310.101",
"000.310.110",
"000.600.000",
];
pub(super) const PENDING_CODES: [&str; 26] = [
"000.400.000",
"000.400.010",
"000.400.020",
"000.400.040",
"000.400.050",
"000.400.060",
"000.400.070",
"000.400.080",
"000.400.081",
"000.400.082",
"000.400.090",
"000.400.091",
"000.400.100",
"000.400.110",
"000.200.000",
"000.200.001",
"000.200.100",
"000.200.101",
"000.200.102",
"000.200.103",
"000.200.200",
"000.200.201",
"100.400.500",
"800.400.500",
"800.400.501",
"800.400.502",
];
|
{
"chunk": null,
"crate": "connector-integration",
"enum_name": null,
"file_size": 10492,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_connector-integration_4269101882135321764
|
clm
|
small_file
|
// connector-service/backend/connector-integration/src/connectors/cashtocode/transformers.rs
use std::collections::HashMap;
use common_utils::{
errors::CustomResult, ext_traits::ValueExt, id_type, request::Method, types::FloatMajorUnit,
Email,
};
use domain_types::{
connector_flow::Authorize,
connector_types::{PaymentFlowData, PaymentsAuthorizeData, PaymentsResponseData, ResponseId},
errors::{self, ConnectorError},
payment_method_data::PaymentMethodDataTypes,
router_data::{ConnectorAuthType, ErrorResponse},
router_data_v2::RouterDataV2,
router_response_types::RedirectForm,
utils,
};
use error_stack::ResultExt;
use hyperswitch_masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{connectors::cashtocode::CashtocodeRouterData, types::ResponseRouterData};
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CashtocodePaymentsRequest {
amount: FloatMajorUnit,
transaction_id: String,
user_id: Secret<id_type::CustomerId>,
currency: common_enums::Currency,
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
user_alias: Secret<id_type::CustomerId>,
requested_url: String,
cancel_url: String,
email: Option<Email>,
mid: Secret<String>,
}
fn get_mid(
connector_auth_type: &ConnectorAuthType,
payment_method_type: Option<common_enums::PaymentMethodType>,
currency: common_enums::Currency,
) -> Result<Secret<String>, errors::ConnectorError> {
match CashtocodeAuth::try_from((connector_auth_type, ¤cy)) {
Ok(cashtocode_auth) => match payment_method_type {
Some(common_enums::PaymentMethodType::ClassicReward) => Ok(cashtocode_auth
.merchant_id_classic
.ok_or(errors::ConnectorError::FailedToObtainAuthType)?),
Some(common_enums::PaymentMethodType::Evoucher) => Ok(cashtocode_auth
.merchant_id_evoucher
.ok_or(errors::ConnectorError::FailedToObtainAuthType)?),
_ => Err(errors::ConnectorError::FailedToObtainAuthType),
},
Err(_) => Err(errors::ConnectorError::FailedToObtainAuthType)?,
}
}
impl<
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize,
>
TryFrom<
CashtocodeRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
> for CashtocodePaymentsRequest
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: CashtocodeRouterData<
RouterDataV2<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>,
T,
>,
) -> Result<Self, Self::Error> {
let customer_id = item.router_data.resource_common_data.get_customer_id()?;
let url = item.router_data.request.get_router_return_url()?;
let mid = get_mid(
&item.router_data.connector_auth_type,
item.router_data.request.payment_method_type,
item.router_data.request.currency,
)?;
let amount = item
.connector
.amount_converter
.convert(
item.router_data.request.minor_amount,
item.router_data.request.currency,
)
.change_context(ConnectorError::RequestEncodingFailed)?;
match item.router_data.resource_common_data.payment_method {
common_enums::PaymentMethod::Reward => Ok(Self {
amount,
transaction_id: item
.router_data
.resource_common_data
.connector_request_reference_id,
currency: item.router_data.request.currency,
user_id: Secret::new(customer_id.to_owned()),
first_name: None,
last_name: None,
user_alias: Secret::new(customer_id),
requested_url: url.to_owned(),
cancel_url: url,
email: item.router_data.request.email.clone(),
mid,
}),
_ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
}
}
}
#[derive(Default, Debug, Deserialize)]
pub struct CashtocodeAuthType {
pub auths: HashMap<common_enums::Currency, CashtocodeAuth>,
}
#[derive(Default, Debug, Deserialize)]
pub struct CashtocodeAuth {
pub password_classic: Option<Secret<String>>,
pub password_evoucher: Option<Secret<String>>,
pub username_classic: Option<Secret<String>>,
pub username_evoucher: Option<Secret<String>>,
pub merchant_id_classic: Option<Secret<String>>,
pub merchant_id_evoucher: Option<Secret<String>>,
}
impl TryFrom<&ConnectorAuthType> for CashtocodeAuthType {
type Error = error_stack::Report<errors::ConnectorError>; // Assuming ErrorStack is the appropriate error type
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::CurrencyAuthKey { auth_key_map } => {
let transformed_auths = auth_key_map
.iter()
.map(|(currency, identity_auth_key)| {
let cashtocode_auth = identity_auth_key
.to_owned()
.parse_value::<CashtocodeAuth>("CashtocodeAuth")
.change_context(errors::ConnectorError::InvalidDataFormat {
field_name: "auth_key_map",
})?;
Ok((currency.to_owned(), cashtocode_auth))
})
.collect::<Result<_, Self::Error>>()?;
Ok(Self {
auths: transformed_auths,
})
}
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
impl TryFrom<(&ConnectorAuthType, &common_enums::Currency)> for CashtocodeAuth {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: (&ConnectorAuthType, &common_enums::Currency)) -> Result<Self, Self::Error> {
let (auth_type, currency) = value;
if let ConnectorAuthType::CurrencyAuthKey { auth_key_map } = auth_type {
if let Some(identity_auth_key) = auth_key_map.get(currency) {
let cashtocode_auth: Self = identity_auth_key
.to_owned()
.parse_value("CashtocodeAuth")
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(cashtocode_auth)
} else {
Err(errors::ConnectorError::CurrencyNotSupported {
message: currency.to_string(),
connector: "CashToCode",
}
.into())
}
} else {
Err(errors::ConnectorError::FailedToObtainAuthType.into())
}
}
}
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum CashtocodePaymentStatus {
Succeeded,
#[default]
Processing,
}
impl From<CashtocodePaymentStatus> for common_enums::AttemptStatus {
fn from(item: CashtocodePaymentStatus) -> Self {
match item {
CashtocodePaymentStatus::Succeeded => Self::Charged,
CashtocodePaymentStatus::Processing => Self::AuthenticationPending,
}
}
}
#[derive(Debug, Deserialize, Clone, Serialize)]
pub struct CashtocodeErrors {
pub message: String,
pub path: String,
#[serde(rename = "type")]
pub event_type: String,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(untagged)]
pub enum CashtocodePaymentsResponse {
CashtoCodeError(CashtocodeErrorResponse),
CashtoCodeData(CashtocodePaymentsResponseData),
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CashtocodePaymentsResponseData {
pub pay_url: url::Url,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CashtocodePaymentsSyncResponse {
pub transaction_id: String,
pub amount: FloatMajorUnit,
}
fn get_redirect_form_data(
payment_method_type: common_enums::PaymentMethodType,
response_data: CashtocodePaymentsResponseData,
) -> CustomResult<RedirectForm, errors::ConnectorError> {
match payment_method_type {
common_enums::PaymentMethodType::ClassicReward => Ok(RedirectForm::Form {
//redirect form is manually constructed because the connector for this pm type expects query params in the url
endpoint: response_data.pay_url.to_string(),
method: Method::Post,
form_fields: Default::default(),
}),
common_enums::PaymentMethodType::Evoucher => Ok(RedirectForm::Form {
//here the pay url gets parsed, and query params are sent as formfields as the connector expects
endpoint: response_data.pay_url.to_string(),
method: Method::Get,
form_fields: Default::default(),
}),
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("CashToCode"),
))?,
}
}
impl<
F,
T: PaymentMethodDataTypes
+ std::fmt::Debug
+ std::marker::Sync
+ std::marker::Send
+ 'static
+ Serialize
+ Serialize,
> TryFrom<ResponseRouterData<CashtocodePaymentsResponse, Self>>
for RouterDataV2<F, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData>
{
type Error = error_stack::Report<ConnectorError>;
fn try_from(
item: ResponseRouterData<CashtocodePaymentsResponse, Self>,
) -> Result<Self, Self::Error> {
let ResponseRouterData {
response,
router_data,
http_code,
} = item;
let (status, response) = match response {
CashtocodePaymentsResponse::CashtoCodeError(error_data) => (
common_enums::AttemptStatus::Failure,
Err(ErrorResponse {
code: error_data.error.to_string(),
status_code: item.http_code,
message: error_data.error_description.clone(),
reason: Some(error_data.error_description),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
}),
),
CashtocodePaymentsResponse::CashtoCodeData(response_data) => {
let payment_method_type = router_data
.request
.payment_method_type
.ok_or(errors::ConnectorError::MissingPaymentMethodType)?;
let redirection_data = get_redirect_form_data(payment_method_type, response_data)?;
(
common_enums::AttemptStatus::AuthenticationPending,
Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
router_data
.resource_common_data
.connector_request_reference_id
.clone(),
),
redirection_data: Some(Box::new(redirection_data)),
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
status_code: http_code,
}),
)
}
};
Ok(Self {
resource_common_data: PaymentFlowData {
status,
..router_data.resource_common_data
},
response,
..router_data
})
}
}
#[derive(Debug, Deserialize, Serialize)]
pub struct CashtocodeErrorResponse {
pub error: serde_json::Value,
pub error_description: String,
pub errors: Option<Vec<CashtocodeErrors>>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CashtocodeIncomingWebhook {
pub amount: FloatMajorUnit,
pub currency: String,
pub foreign_transaction_id: String,
#[serde(rename = "type")]
pub event_type: String,
pub transaction_id: String,
}
|
{
"chunk": null,
"crate": "connector-integration",
"enum_name": null,
"file_size": 12910,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_connector-integration_-87029215718539496
|
clm
|
small_file
|
// connector-service/backend/connector-integration/src/connectors/razorpayv2/test.rs
//! Tests for RazorpayV2 connector
#[cfg(test)]
mod tests {
// use super::super::transformers::*;
#[test]
fn test_upi_flow_determination() {
// Add tests for UPI flow determination logic
// TODO: Implement comprehensive tests
}
#[test]
fn test_create_order_request_building() {
// Add tests for create order request building
// TODO: Implement comprehensive tests
}
#[test]
fn test_payments_request_building() {
// Add tests for payments request building
// TODO: Implement comprehensive tests
}
}
|
{
"chunk": null,
"crate": "connector-integration",
"enum_name": null,
"file_size": 590,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_connector-integration_7699459339071947392
|
clm
|
small_file
|
// connector-service/backend/connector-integration/src/connectors/cashfree/test.rs
// Test file placeholder for Cashfree connector
// Tests will be implemented once the basic connector is working
#[cfg(test)]
mod tests {
use domain_types::payment_method_data::DefaultPCIHolder;
use interfaces::api::ConnectorCommon;
use crate::connectors;
#[test]
fn test_cashfree_connector_creation() {
// Basic test to ensure connector can be created
let connector: &connectors::cashfree::Cashfree<DefaultPCIHolder> =
super::super::Cashfree::new();
assert_eq!(connector.id(), "cashfree");
}
}
|
{
"chunk": null,
"crate": "connector-integration",
"enum_name": null,
"file_size": 558,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_connector-integration_-8421620542795988629
|
clm
|
small_file
|
// connector-service/backend/connector-integration/src/utils/xml_utils.rs
use bytes::Bytes;
use domain_types::errors;
use serde_json::{Map, Value};
/// Processes XML response bytes by converting to properly structured JSON.
///
/// This function:
/// 1. Takes XML data as `Bytes` input
/// 2. Converts it to a UTF-8 string and trims whitespace
/// 3. Checks for XML declarations and removes them if present
/// 4. Parses the XML into a JSON structure
/// 5. Flattens nested "$text" fields to create a clean key-value structure
/// 6. Returns the processed JSON data as `Bytes`
pub fn preprocess_xml_response_bytes(xml_data: Bytes) -> Result<Bytes, errors::ConnectorError> {
// Log raw bytes for debugging
tracing::info!(bytes=?xml_data, "Raw XML bytes received for preprocessing");
// Convert to UTF-8 string
let response_str = std::str::from_utf8(&xml_data)
.map_err(|_| errors::ConnectorError::ResponseDeserializationFailed)?
.trim();
// Handle XML declarations by removing them if present
let cleaned_response = if response_str.starts_with("<?xml") {
// Find the end of the XML declaration and skip it
match response_str.find("?>") {
Some(pos) => {
let substring = &response_str[pos + 2..];
let cleaned = substring.trim();
tracing::info!("Removed XML declaration: {}", cleaned);
cleaned
}
None => {
tracing::warn!("XML declaration start found but no closing '?>' tag");
response_str
}
}
} else {
tracing::info!("No XML declaration found, using as-is");
response_str
};
// Ensure the XML has a txn wrapper if needed
let final_xml = if !cleaned_response.starts_with("<txn>")
&& (cleaned_response.contains("<ssl_") || cleaned_response.contains("<error"))
{
format!("<txn>{cleaned_response}</txn>")
} else {
cleaned_response.to_string()
};
// Parse XML to a generic JSON Value
let json_value: Value = match quick_xml::de::from_str(&final_xml) {
Ok(val) => {
tracing::info!("Successfully converted XML to JSON structure");
val
}
Err(err) => {
tracing::error!(error=?err, "Failed to parse XML to JSON structure");
// Create a basic JSON structure with error information
return Err(errors::ConnectorError::ResponseDeserializationFailed);
}
};
// Extract and flatten the JSON structure
let flattened_json = flatten_json_structure(json_value);
// Convert JSON Value to string and then to bytes
let json_string = serde_json::to_string(&flattened_json).map_err(|e| {
tracing::error!(error=?e, "Failed to convert to JSON string");
errors::ConnectorError::ResponseDeserializationFailed
})?;
tracing::info!(json=?json_string, "Flattened JSON structure");
// Return JSON as bytes
Ok(Bytes::from(json_string.into_bytes()))
}
/// Flattens a nested JSON structure, extracting values from "$text" fields
pub fn flatten_json_structure(json_value: Value) -> Value {
let mut flattened = Map::new();
// Extract txn object if present
let txn_obj = if let Some(obj) = json_value.as_object() {
if let Some(txn) = obj.get("txn") {
txn.as_object()
} else {
Some(obj)
}
} else {
None
};
// Process the fields
if let Some(obj) = txn_obj {
for (key, value) in obj {
// Handle nested "$text" fields
if let Some(value_obj) = value.as_object() {
if let Some(text_value) = value_obj.get("$text") {
// Extract the value from "$text" field
flattened.insert(key.clone(), text_value.clone());
} else if value_obj.is_empty() {
// Empty object, insert empty string
flattened.insert(key.clone(), Value::String("".to_string()));
} else {
// Use the value as is
flattened.insert(key.clone(), value.clone());
}
} else {
// Use the value as is
flattened.insert(key.clone(), value.clone());
}
}
}
Value::Object(flattened)
}
|
{
"chunk": null,
"crate": "connector-integration",
"enum_name": null,
"file_size": 4320,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_tracing-kafka_5501410502799828961
|
clm
|
small_file
|
// connector-service/backend/tracing-kafka/src/lib.rs
//! A Kafka tracing layer that integrates with the tracing ecosystem.
//!
//! This crate provides a simple way to send tracing logs to Kafka while maintaining
//! consistent JSON formatting through the log_utils infrastructure.
//!
//! # Examples
//! ```no_run
//! use tracing_kafka::KafkaLayer;
//! use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
//!
//! let kafka_layer = KafkaLayer::builder()
//! .brokers(&["localhost:9092"])
//! .topic("application-logs")
//! .build()
//! .expect("Failed to create Kafka layer");
//!
//! tracing_subscriber::registry()
//! .with(kafka_layer)
//! .init();
//! ```
//!
//! # Publishing Custom Events
//!
//! In addition to logging, the `KafkaWriter` can be used to publish custom events to Kafka.
//! The `publish_event` method allows you to send a payload to a specific topic with an optional key and headers.
//!
//! ```no_run
//! use tracing_kafka::KafkaWriter;
//! use rdkafka::message::OwnedHeaders;
//!
//! let writer = KafkaWriter::new(
//! vec!["localhost:9092".to_string()],
//! "default-topic".to_string(),
//! None, None, None, None, None, None
//! ).expect("Failed to create KafkaWriter");
//!
//! let headers = OwnedHeaders::new().add("my-header", "my-value");
//!
//! let result = writer.publish_event(
//! "custom-events",
//! Some("event-key"),
//! b"event-payload",
//! Some(headers),
//! );
//!
//! if let Err(e) = result {
//! eprintln!("Failed to publish event: {}", e);
//! }
//! ```
pub mod builder;
mod layer;
mod writer;
pub use layer::{KafkaLayer, KafkaLayerError};
pub use writer::{KafkaWriter, KafkaWriterError};
#[cfg(feature = "kafka-metrics")]
mod metrics;
/// Initializes the metrics for the tracing kafka.
/// This function should be called once at application startup.
#[cfg(feature = "kafka-metrics")]
pub fn init() {
metrics::initialize_all_metrics();
}
#[cfg(not(feature = "kafka-metrics"))]
pub fn init() {
tracing::warn!("Kafka metrics feature is not enabled. Metrics will not be collected.");
}
|
{
"chunk": null,
"crate": "tracing-kafka",
"enum_name": null,
"file_size": 2065,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_tracing-kafka_863436229918585844
|
clm
|
small_file
|
// connector-service/backend/tracing-kafka/src/metrics.rs
//! Prometheus metrics for Kafka writer
use std::sync::LazyLock;
use prometheus::{register_int_counter, register_int_gauge, IntCounter, IntGauge};
/// Total number of logs successfully sent to Kafka
#[allow(clippy::expect_used)]
pub static KAFKA_LOGS_SENT: LazyLock<IntCounter> = LazyLock::new(|| {
register_int_counter!(
"kafka_logs_sent_total",
"Total number of logs successfully sent to Kafka"
)
.expect("Failed to register kafka_logs_sent_total metric")
});
/// Total number of logs dropped due to Kafka queue full or errors
#[allow(clippy::expect_used)]
pub static KAFKA_LOGS_DROPPED: LazyLock<IntCounter> = LazyLock::new(|| {
register_int_counter!(
"kafka_logs_dropped_total",
"Total number of logs dropped due to Kafka queue full or errors"
)
.expect("Failed to register kafka_logs_dropped_total metric")
});
/// Current size of Kafka producer queue
#[allow(clippy::expect_used)]
pub static KAFKA_QUEUE_SIZE: LazyLock<IntGauge> = LazyLock::new(|| {
register_int_gauge!(
"kafka_producer_queue_size",
"Current size of Kafka producer queue"
)
.expect("Failed to register kafka_producer_queue_size metric")
});
/// Logs dropped due to queue full
#[allow(clippy::expect_used)]
pub static KAFKA_DROPS_QUEUE_FULL: LazyLock<IntCounter> = LazyLock::new(|| {
register_int_counter!(
"kafka_drops_queue_full_total",
"Total number of logs dropped due to Kafka queue being full"
)
.expect("Failed to register kafka_drops_queue_full_total metric")
});
/// Logs dropped due to message too large
#[allow(clippy::expect_used)]
pub static KAFKA_DROPS_MSG_TOO_LARGE: LazyLock<IntCounter> = LazyLock::new(|| {
register_int_counter!(
"kafka_drops_msg_too_large_total",
"Total number of logs dropped due to message size exceeding limit"
)
.expect("Failed to register kafka_drops_msg_too_large_total metric")
});
/// Logs dropped due to timeout
#[allow(clippy::expect_used)]
pub static KAFKA_DROPS_TIMEOUT: LazyLock<IntCounter> = LazyLock::new(|| {
register_int_counter!(
"kafka_drops_timeout_total",
"Total number of logs dropped due to timeout"
)
.expect("Failed to register kafka_drops_timeout_total metric")
});
/// Logs dropped due to other errors
#[allow(clippy::expect_used)]
pub static KAFKA_DROPS_OTHER: LazyLock<IntCounter> = LazyLock::new(|| {
register_int_counter!(
"kafka_drops_other_total",
"Total number of logs dropped due to other errors"
)
.expect("Failed to register kafka_drops_other_total metric")
});
/// Total number of audit events successfully sent to Kafka
#[allow(clippy::expect_used)]
pub static KAFKA_AUDIT_EVENTS_SENT: LazyLock<IntCounter> = LazyLock::new(|| {
register_int_counter!(
"kafka_audit_events_sent_total",
"Total number of audit events successfully sent to Kafka"
)
.expect("Failed to register kafka_audit_events_sent_total metric")
});
/// Total number of audit events dropped due to Kafka queue full or errors
#[allow(clippy::expect_used)]
pub static KAFKA_AUDIT_EVENTS_DROPPED: LazyLock<IntCounter> = LazyLock::new(|| {
register_int_counter!(
"kafka_audit_events_dropped_total",
"Total number of audit events dropped due to Kafka queue full or errors"
)
.expect("Failed to register kafka_audit_events_dropped_total metric")
});
/// Current size of Kafka audit event producer queue
#[allow(clippy::expect_used)]
pub static KAFKA_AUDIT_EVENT_QUEUE_SIZE: LazyLock<IntGauge> = LazyLock::new(|| {
register_int_gauge!(
"kafka_audit_event_queue_size",
"Current size of Kafka audit event producer queue"
)
.expect("Failed to register kafka_audit_event_queue_size metric")
});
/// Audit events dropped due to queue full
#[allow(clippy::expect_used)]
pub static KAFKA_AUDIT_DROPS_QUEUE_FULL: LazyLock<IntCounter> = LazyLock::new(|| {
register_int_counter!(
"kafka_audit_drops_queue_full_total",
"Total number of audit events dropped due to Kafka queue being full"
)
.expect("Failed to register kafka_audit_drops_queue_full_total metric")
});
/// Audit events dropped due to message too large
#[allow(clippy::expect_used)]
pub static KAFKA_AUDIT_DROPS_MSG_TOO_LARGE: LazyLock<IntCounter> = LazyLock::new(|| {
register_int_counter!(
"kafka_audit_drops_msg_too_large_total",
"Total number of audit events dropped due to message size exceeding limit"
)
.expect("Failed to register kafka_audit_drops_msg_too_large_total metric")
});
/// Audit events dropped due to timeout
#[allow(clippy::expect_used)]
pub static KAFKA_AUDIT_DROPS_TIMEOUT: LazyLock<IntCounter> = LazyLock::new(|| {
register_int_counter!(
"kafka_audit_drops_timeout_total",
"Total number of audit events dropped due to timeout"
)
.expect("Failed to register kafka_audit_drops_timeout_total metric")
});
/// Audit events dropped due to other errors
#[allow(clippy::expect_used)]
pub static KAFKA_AUDIT_DROPS_OTHER: LazyLock<IntCounter> = LazyLock::new(|| {
register_int_counter!(
"kafka_audit_drops_other_total",
"Total number of audit events dropped due to other errors"
)
.expect("Failed to register kafka_audit_drops_other_total metric")
});
/// Forces the initialization of all metrics in this module.
///
/// This function should be called once at application startup to ensure that all metrics
/// are registered upfront. If any metric registration fails (e.g., due to a duplicate
/// metric name), the application will panic immediately.
#[cfg(feature = "kafka-metrics")]
pub fn initialize_all_metrics() {
// Force evaluation of all lazy metrics to fail fast if registration fails.
let _ = &*KAFKA_LOGS_SENT;
let _ = &*KAFKA_LOGS_DROPPED;
let _ = &*KAFKA_QUEUE_SIZE;
let _ = &*KAFKA_DROPS_QUEUE_FULL;
let _ = &*KAFKA_DROPS_MSG_TOO_LARGE;
let _ = &*KAFKA_DROPS_TIMEOUT;
let _ = &*KAFKA_DROPS_OTHER;
let _ = &*KAFKA_AUDIT_EVENTS_SENT;
let _ = &*KAFKA_AUDIT_EVENTS_DROPPED;
let _ = &*KAFKA_AUDIT_EVENT_QUEUE_SIZE;
let _ = &*KAFKA_AUDIT_DROPS_QUEUE_FULL;
let _ = &*KAFKA_AUDIT_DROPS_MSG_TOO_LARGE;
let _ = &*KAFKA_AUDIT_DROPS_TIMEOUT;
let _ = &*KAFKA_AUDIT_DROPS_OTHER;
}
|
{
"chunk": null,
"crate": "tracing-kafka",
"enum_name": null,
"file_size": 6322,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_tracing-kafka_-8840925468162898005
|
clm
|
small_file
|
// connector-service/backend/tracing-kafka/src/writer.rs
//! Kafka writer implementation for sending formatted log messages to Kafka.
use std::{
io::{self, Write},
sync::Arc,
time::Duration,
};
use rdkafka::{
config::ClientConfig,
error::{KafkaError, RDKafkaErrorCode},
message::OwnedHeaders,
producer::{BaseRecord, DeliveryResult, Producer, ProducerContext, ThreadedProducer},
ClientContext,
};
#[cfg(feature = "kafka-metrics")]
use super::metrics::{
KAFKA_AUDIT_DROPS_MSG_TOO_LARGE, KAFKA_AUDIT_DROPS_OTHER, KAFKA_AUDIT_DROPS_QUEUE_FULL,
KAFKA_AUDIT_DROPS_TIMEOUT, KAFKA_AUDIT_EVENTS_DROPPED, KAFKA_AUDIT_EVENTS_SENT,
KAFKA_AUDIT_EVENT_QUEUE_SIZE, KAFKA_DROPS_MSG_TOO_LARGE, KAFKA_DROPS_OTHER,
KAFKA_DROPS_QUEUE_FULL, KAFKA_DROPS_TIMEOUT, KAFKA_LOGS_DROPPED, KAFKA_LOGS_SENT,
KAFKA_QUEUE_SIZE,
};
/// A `ProducerContext` that handles delivery callbacks to increment metrics.
#[derive(Clone)]
struct MetricsProducerContext;
impl ClientContext for MetricsProducerContext {}
impl ProducerContext for MetricsProducerContext {
type DeliveryOpaque = Box<KafkaMessageType>;
fn delivery(&self, delivery_result: &DeliveryResult<'_>, opaque: Self::DeliveryOpaque) {
let message_type = *opaque;
let is_success = delivery_result.is_ok();
#[cfg(feature = "kafka-metrics")]
{
match (message_type, is_success) {
(KafkaMessageType::Event, true) => KAFKA_AUDIT_EVENTS_SENT.inc(),
(KafkaMessageType::Event, false) => KAFKA_AUDIT_EVENTS_DROPPED.inc(),
(KafkaMessageType::Log, true) => KAFKA_LOGS_SENT.inc(),
(KafkaMessageType::Log, false) => KAFKA_LOGS_DROPPED.inc(),
}
}
if let Err((kafka_error, _)) = delivery_result {
#[cfg(feature = "kafka-metrics")]
match (message_type, &kafka_error) {
(
KafkaMessageType::Event,
KafkaError::MessageProduction(RDKafkaErrorCode::QueueFull),
) => {
KAFKA_AUDIT_DROPS_QUEUE_FULL.inc();
}
(
KafkaMessageType::Event,
KafkaError::MessageProduction(RDKafkaErrorCode::MessageSizeTooLarge),
) => {
KAFKA_AUDIT_DROPS_MSG_TOO_LARGE.inc();
}
(
KafkaMessageType::Event,
KafkaError::MessageProduction(RDKafkaErrorCode::MessageTimedOut),
) => {
KAFKA_AUDIT_DROPS_TIMEOUT.inc();
}
(KafkaMessageType::Event, _) => {
KAFKA_AUDIT_DROPS_OTHER.inc();
}
(
KafkaMessageType::Log,
KafkaError::MessageProduction(RDKafkaErrorCode::QueueFull),
) => {
KAFKA_DROPS_QUEUE_FULL.inc();
}
(
KafkaMessageType::Log,
KafkaError::MessageProduction(RDKafkaErrorCode::MessageSizeTooLarge),
) => {
KAFKA_DROPS_MSG_TOO_LARGE.inc();
}
(
KafkaMessageType::Log,
KafkaError::MessageProduction(RDKafkaErrorCode::MessageTimedOut),
) => {
KAFKA_DROPS_TIMEOUT.inc();
}
(KafkaMessageType::Log, _) => {
KAFKA_DROPS_OTHER.inc();
}
}
}
}
}
/// This enum helps the callback distinguish between logs and events.
#[derive(Clone, Copy, Debug)]
enum KafkaMessageType {
Event,
Log,
}
/// Kafka writer that implements std::io::Write for seamless integration with tracing
#[derive(Clone)]
pub struct KafkaWriter {
producer: Arc<ThreadedProducer<MetricsProducerContext>>,
topic: String,
}
impl std::fmt::Debug for KafkaWriter {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("KafkaWriter")
.field("topic", &self.topic)
.finish()
}
}
impl KafkaWriter {
/// Creates a new KafkaWriter with the specified brokers and topic.
#[allow(clippy::too_many_arguments)]
pub fn new(
brokers: Vec<String>,
topic: String,
batch_size: Option<usize>,
linger_ms: Option<u64>,
queue_buffering_max_messages: Option<usize>,
queue_buffering_max_kbytes: Option<usize>,
reconnect_backoff_min_ms: Option<u64>,
reconnect_backoff_max_ms: Option<u64>,
) -> Result<Self, KafkaWriterError> {
let mut config = ClientConfig::new();
config.set("bootstrap.servers", brokers.join(","));
if let Some(min_backoff) = reconnect_backoff_min_ms {
config.set("reconnect.backoff.ms", min_backoff.to_string());
}
if let Some(max_backoff) = reconnect_backoff_max_ms {
config.set("reconnect.backoff.max.ms", max_backoff.to_string());
}
if let Some(max_messages) = queue_buffering_max_messages {
config.set("queue.buffering.max.messages", max_messages.to_string());
}
if let Some(max_kbytes) = queue_buffering_max_kbytes {
config.set("queue.buffering.max.kbytes", max_kbytes.to_string());
}
if let Some(size) = batch_size {
config.set("batch.size", size.to_string());
}
if let Some(ms) = linger_ms {
config.set("linger.ms", ms.to_string());
}
let producer: ThreadedProducer<MetricsProducerContext> = config
.create_with_context(MetricsProducerContext)
.map_err(KafkaWriterError::ProducerCreation)?;
producer
.client()
.fetch_metadata(Some(&topic), Duration::from_secs(5))
.map_err(KafkaWriterError::MetadataFetch)?;
Ok(Self {
producer: Arc::new(producer),
topic,
})
}
/// Publishes a single event to Kafka. This method is non-blocking.
/// Returns an error if the message cannot be enqueued to the producer's buffer.
pub fn publish_event(
&self,
topic: &str,
key: Option<&str>,
payload: &[u8],
headers: Option<OwnedHeaders>,
) -> Result<(), KafkaError> {
#[cfg(feature = "kafka-metrics")]
{
let queue_size = self.producer.in_flight_count();
KAFKA_AUDIT_EVENT_QUEUE_SIZE.set(queue_size.into());
}
let mut record = BaseRecord::with_opaque_to(topic, Box::new(KafkaMessageType::Event))
.payload(payload)
.timestamp(
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis().try_into().unwrap_or(0))
.unwrap_or(0),
);
if let Some(k) = key {
record = record.key(k);
}
if let Some(h) = headers {
record = record.headers(h);
}
match self.producer.send(record) {
Ok(_) => Ok(()),
Err((kafka_error, _)) => {
#[cfg(feature = "kafka-metrics")]
{
KAFKA_AUDIT_EVENTS_DROPPED.inc();
// Only QUEUE_FULL can happen during send() - others happen during delivery
match &kafka_error {
KafkaError::MessageProduction(RDKafkaErrorCode::QueueFull) => {
KAFKA_AUDIT_DROPS_QUEUE_FULL.inc();
}
_ => {
KAFKA_AUDIT_DROPS_OTHER.inc();
}
}
}
Err(kafka_error)
}
}
}
/// Creates a new builder for constructing a KafkaWriter
pub fn builder() -> crate::builder::KafkaWriterBuilder {
crate::builder::KafkaWriterBuilder::new()
}
}
impl Write for KafkaWriter {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
#[cfg(feature = "kafka-metrics")]
{
let queue_size = self.producer.in_flight_count();
KAFKA_QUEUE_SIZE.set(queue_size.into());
}
let record = BaseRecord::with_opaque_to(&self.topic, Box::new(KafkaMessageType::Log))
.payload(buf)
.timestamp(
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_millis().try_into().unwrap_or(0))
.unwrap_or(0),
);
if let Err((kafka_error, _)) = self.producer.send::<(), [u8]>(record) {
#[cfg(feature = "kafka-metrics")]
{
KAFKA_LOGS_DROPPED.inc();
match &kafka_error {
KafkaError::MessageProduction(RDKafkaErrorCode::QueueFull) => {
KAFKA_DROPS_QUEUE_FULL.inc();
}
_ => {
KAFKA_DROPS_OTHER.inc();
}
}
}
}
// Return Ok to not block the application. The actual delivery result
// is handled by the callback in the background.
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
self.producer
.flush(rdkafka::util::Timeout::After(Duration::from_secs(5)))
.map_err(|e: KafkaError| io::Error::other(format!("Kafka flush failed: {e}")))
}
}
/// Errors that can occur when creating or using a KafkaWriter.
#[derive(Debug, thiserror::Error)]
pub enum KafkaWriterError {
#[error("Failed to create Kafka producer: {0}")]
ProducerCreation(KafkaError),
#[error("Failed to fetch Kafka metadata: {0}")]
MetadataFetch(KafkaError),
}
/// Make KafkaWriter compatible with tracing_appender's MakeWriter trait.
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for KafkaWriter {
type Writer = Self;
fn make_writer(&'a self) -> Self::Writer {
self.clone()
}
}
/// Graceful shutdown - flush pending messages when dropping
impl Drop for KafkaWriter {
fn drop(&mut self) {
// Only flush if this is the last reference to the producer
if Arc::strong_count(&self.producer) == 1 {
// Try to flush pending messages with a 5 second timeout
let _ = self
.producer
.flush(rdkafka::util::Timeout::After(Duration::from_secs(5)));
}
}
}
|
{
"chunk": null,
"crate": "tracing-kafka",
"enum_name": null,
"file_size": 10584,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_tracing-kafka_-6998519293309712771
|
clm
|
small_file
|
// connector-service/backend/tracing-kafka/src/layer.rs
//! Kafka layer implementation that reuses log_utils formatting.
use std::{
collections::{HashMap, HashSet},
time::Duration,
};
use log_utils::{
AdditionalFieldsPlacement, JsonFormattingLayer, JsonFormattingLayerConfig, LoggerError,
};
use tracing::Subscriber;
use tracing_subscriber::Layer;
use crate::{
builder::KafkaWriterBuilder,
writer::{KafkaWriter, KafkaWriterError},
};
/// Tracing layer that sends JSON-formatted logs to Kafka
///
/// Wraps log_utils' JsonFormattingLayer
pub struct KafkaLayer {
inner: JsonFormattingLayer<KafkaWriter, serde_json::ser::CompactFormatter>,
}
impl KafkaLayer {
/// Creates a new builder for configuring a KafkaLayer.
pub fn builder() -> KafkaLayerBuilder {
KafkaLayerBuilder::new()
}
/// Creates a new KafkaLayer from a pre-configured KafkaWriter.
/// This is primarily used internally by the builder.
pub(crate) fn from_writer(
kafka_writer: KafkaWriter,
static_fields: HashMap<String, serde_json::Value>,
) -> Result<Self, KafkaLayerError> {
let config = JsonFormattingLayerConfig {
static_top_level_fields: static_fields,
top_level_keys: HashSet::new(),
log_span_lifecycles: true,
additional_fields_placement: AdditionalFieldsPlacement::TopLevel,
};
let inner: JsonFormattingLayer<KafkaWriter, serde_json::ser::CompactFormatter> =
JsonFormattingLayer::new(config, kafka_writer, serde_json::ser::CompactFormatter)?;
Ok(Self { inner })
}
}
impl<S> Layer<S> for KafkaLayer
where
S: Subscriber + for<'lookup> tracing_subscriber::registry::LookupSpan<'lookup>,
{
fn on_event(&self, event: &tracing::Event<'_>, ctx: tracing_subscriber::layer::Context<'_, S>) {
self.inner.on_event(event, ctx);
}
fn on_new_span(
&self,
attrs: &tracing::span::Attributes<'_>,
id: &tracing::span::Id,
ctx: tracing_subscriber::layer::Context<'_, S>,
) {
self.inner.on_new_span(attrs, id, ctx);
}
fn on_enter(&self, id: &tracing::span::Id, ctx: tracing_subscriber::layer::Context<'_, S>) {
self.inner.on_enter(id, ctx);
}
fn on_exit(&self, id: &tracing::span::Id, ctx: tracing_subscriber::layer::Context<'_, S>) {
self.inner.on_exit(id, ctx);
}
fn on_close(&self, id: tracing::span::Id, ctx: tracing_subscriber::layer::Context<'_, S>) {
self.inner.on_close(id, ctx);
}
}
impl KafkaLayer {
/// Boxes the layer, making it easier to compose with other layers.
pub fn boxed<S>(self) -> Box<dyn Layer<S> + Send + Sync + 'static>
where
Self: Layer<S> + Sized + Send + Sync + 'static,
S: Subscriber + for<'span> tracing_subscriber::registry::LookupSpan<'span>,
{
Box::new(self)
}
}
/// Errors that can occur when creating a KafkaLayer.
#[derive(Debug, thiserror::Error)]
pub enum KafkaLayerError {
#[error("Kafka writer error: {0}")]
Writer(#[from] KafkaWriterError),
#[error("Logger configuration error: {0}")]
Logger(#[from] LoggerError),
#[error("Missing brokers configuration")]
MissingBrokers,
#[error("Missing topic configuration")]
MissingTopic,
}
/// Builder for creating a KafkaLayer with custom configuration.
#[derive(Debug, Clone, Default)]
pub struct KafkaLayerBuilder {
writer_builder: KafkaWriterBuilder,
static_fields: HashMap<String, serde_json::Value>,
}
impl KafkaLayerBuilder {
/// Creates a new builder with default settings.
pub fn new() -> Self {
Self::default()
}
/// Sets the Kafka brokers to connect to.
pub fn brokers(mut self, brokers: &[&str]) -> Self {
self.writer_builder = self
.writer_builder
.brokers(brokers.iter().map(|s| s.to_string()).collect());
self
}
/// Sets the Kafka topic to send logs to.
pub fn topic(mut self, topic: impl Into<String>) -> Self {
self.writer_builder = self.writer_builder.topic(topic);
self
}
/// Sets the batch size for buffering messages before sending.
pub fn batch_size(mut self, size: usize) -> Self {
self.writer_builder = self.writer_builder.batch_size(size);
self
}
/// Sets the linger time in milliseconds.
pub fn linger_ms(mut self, ms: u64) -> Self {
self.writer_builder = self.writer_builder.linger_ms(ms);
self
}
/// Sets the linger time as a Duration.
pub fn linger(mut self, duration: Duration) -> Self {
self.writer_builder = self.writer_builder.linger(duration);
self
}
/// Sets the maximum number of messages to buffer in the producer's queue.
pub fn queue_buffering_max_messages(mut self, size: usize) -> Self {
self.writer_builder = self.writer_builder.queue_buffering_max_messages(size);
self
}
/// Sets the maximum size of the producer's queue in kilobytes.
pub fn queue_buffering_max_kbytes(mut self, size: usize) -> Self {
self.writer_builder = self.writer_builder.queue_buffering_max_kbytes(size);
self
}
/// Sets the reconnect backoff times.
pub fn reconnect_backoff(mut self, min: Duration, max: Duration) -> Self {
self.writer_builder = self.writer_builder.reconnect_backoff(min, max);
self
}
/// Adds static fields that will be included in every log entry.
/// These fields are added at the top level of the JSON output.
pub fn static_fields(mut self, fields: HashMap<String, serde_json::Value>) -> Self {
self.static_fields = fields;
self
}
/// Adds a single static field that will be included in every log entry.
pub fn add_static_field(mut self, key: String, value: serde_json::Value) -> Self {
self.static_fields.insert(key, value);
self
}
/// Builds the KafkaLayer with the configured settings.
pub fn build(self) -> Result<KafkaLayer, KafkaLayerError> {
let kafka_writer = self.writer_builder.build()?;
KafkaLayer::from_writer(kafka_writer, self.static_fields)
}
}
|
{
"chunk": null,
"crate": "tracing-kafka",
"enum_name": null,
"file_size": 6135,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_tracing-kafka_-7694171944301536872
|
clm
|
small_file
|
// connector-service/backend/tracing-kafka/src/builder.rs
//! Builder pattern implementation for KafkaWriter
use std::time::Duration;
use super::writer::{KafkaWriter, KafkaWriterError};
/// Builder for creating a KafkaWriter with custom configuration
#[derive(Debug, Clone, Default)]
pub struct KafkaWriterBuilder {
brokers: Option<Vec<String>>,
topic: Option<String>,
batch_size: Option<usize>,
linger_ms: Option<u64>,
queue_buffering_max_messages: Option<usize>,
queue_buffering_max_kbytes: Option<usize>,
reconnect_backoff_min_ms: Option<u64>,
reconnect_backoff_max_ms: Option<u64>,
}
impl KafkaWriterBuilder {
/// Creates a new builder with default settings
pub fn new() -> Self {
Self::default()
}
/// Sets the Kafka brokers to connect to
pub fn brokers(mut self, brokers: Vec<String>) -> Self {
self.brokers = Some(brokers);
self
}
/// Sets the Kafka topic to send logs to
pub fn topic(mut self, topic: impl Into<String>) -> Self {
self.topic = Some(topic.into());
self
}
/// Sets the batch size for buffering messages before sending
pub fn batch_size(mut self, size: usize) -> Self {
self.batch_size = Some(size);
self
}
/// Sets the linger time in milliseconds
pub fn linger_ms(mut self, ms: u64) -> Self {
self.linger_ms = Some(ms);
self
}
/// Sets the linger time as a Duration
pub fn linger(mut self, duration: Duration) -> Self {
self.linger_ms = duration.as_millis().try_into().ok();
self
}
/// Sets the maximum number of messages to buffer in the producer's queue
pub fn queue_buffering_max_messages(mut self, size: usize) -> Self {
self.queue_buffering_max_messages = Some(size);
self
}
/// Sets the maximum size of the producer's queue in kilobytes
pub fn queue_buffering_max_kbytes(mut self, size: usize) -> Self {
self.queue_buffering_max_kbytes = Some(size);
self
}
/// Sets the reconnect backoff times
pub fn reconnect_backoff(mut self, min: Duration, max: Duration) -> Self {
self.reconnect_backoff_min_ms = min.as_millis().try_into().ok();
self.reconnect_backoff_max_ms = max.as_millis().try_into().ok();
self
}
/// Builds the KafkaWriter with the configured settings
pub fn build(self) -> Result<KafkaWriter, KafkaWriterError> {
let brokers = self.brokers.ok_or_else(|| {
KafkaWriterError::ProducerCreation(rdkafka::error::KafkaError::ClientCreation(
"No brokers specified. Use .brokers()".to_string(),
))
})?;
let topic = self.topic.ok_or_else(|| {
KafkaWriterError::ProducerCreation(rdkafka::error::KafkaError::ClientCreation(
"No topic specified. Use .topic()".to_string(),
))
})?;
KafkaWriter::new(
brokers,
topic,
self.batch_size,
self.linger_ms,
self.queue_buffering_max_messages,
self.queue_buffering_max_kbytes,
self.reconnect_backoff_min_ms,
self.reconnect_backoff_max_ms,
)
}
}
|
{
"chunk": null,
"crate": "tracing-kafka",
"enum_name": null,
"file_size": 3188,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_ucs_common_enums_4511884537961120054
|
clm
|
small_file
|
// connector-service/backend/common_enums/src/lib.rs
pub mod enums;
pub use enums::*;
|
{
"chunk": null,
"crate": "ucs_common_enums",
"enum_name": null,
"file_size": 34,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_ucs_cards_2421374958024815720
|
clm
|
small_file
|
// connector-service/backend/cards/src/lib.rs
pub mod validate;
pub use crate::validate::{CardNumber, CardNumberStrategy, CardNumberValidationErr, NetworkToken};
|
{
"chunk": null,
"crate": "ucs_cards",
"enum_name": null,
"file_size": 117,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_external-services_6066888807983657858
|
clm
|
small_file
|
// connector-service/backend/external-services/src/shared_metrics.rs
#![allow(clippy::unwrap_used)]
use std::{
future::Future,
pin::Pin,
task::{Context, Poll},
time::Instant,
};
use error_stack::ResultExt;
use http_body::Body as HttpBody;
use lazy_static::lazy_static;
use prometheus::{
self, register_histogram_vec, register_int_counter_vec, Encoder, HistogramVec, IntCounterVec,
TextEncoder,
};
use tower::{Layer, Service};
// Define latency buckets for histograms
const LATENCY_BUCKETS: &[f64] = &[
0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0,
];
lazy_static! {
pub static ref GRPC_SERVER_REQUESTS_TOTAL: IntCounterVec = register_int_counter_vec!(
"GRPC_SERVER_REQUESTS_TOTAL",
"Total number of gRPC requests received",
&["method", "service", "connector"]
)
.unwrap();
pub static ref GRPC_SERVER_REQUESTS_SUCCESSFUL: IntCounterVec = register_int_counter_vec!(
"GRPC_SERVER_REQUESTS_SUCCESSFUL",
"Total number of gRPC requests successful",
&["method", "service", "connector"]
)
.unwrap();
pub static ref GRPC_SERVER_REQUEST_LATENCY: HistogramVec = register_histogram_vec!(
"GRPC_SERVER_REQUEST_LATENCY",
"Request latency in seconds",
&["method", "service", "connector"],
LATENCY_BUCKETS.to_vec()
)
.unwrap();
pub static ref EXTERNAL_SERVICE_API_CALLS_LATENCY: HistogramVec = register_histogram_vec!(
"EXTERNAL_SERVICE_API_CALLS_LATENCY_SECONDS",
"Latency of external service API calls",
&["method", "service", "connector"],
LATENCY_BUCKETS.to_vec()
)
.unwrap();
pub static ref EXTERNAL_SERVICE_TOTAL_API_CALLS: IntCounterVec = register_int_counter_vec!(
"EXTERNAL_SERVICE_TOTAL_API_CALLS",
"Total number of external service API calls",
&["method", "service", "connector"]
)
.unwrap();
pub static ref EXTERNAL_SERVICE_API_CALLS_ERRORS: IntCounterVec = register_int_counter_vec!(
"EXTERNAL_SERVICE_API_CALLS_ERRORS",
"Total number of errors in external service API calls",
&["method", "service", "connector", "error"]
)
.unwrap();
}
// Middleware Layer that automatically handles all gRPC methods
#[derive(Clone)]
pub struct GrpcMetricsLayer;
#[allow(clippy::new_without_default)]
impl GrpcMetricsLayer {
pub fn new() -> Self {
Self
}
}
impl<S> Layer<S> for GrpcMetricsLayer {
type Service = GrpcMetricsService<S>;
fn layer(&self, service: S) -> Self::Service {
GrpcMetricsService::new(service)
}
}
// Middleware Service that intercepts all gRPC calls
#[derive(Clone)]
pub struct GrpcMetricsService<S> {
inner: S,
}
impl<S> GrpcMetricsService<S> {
pub fn new(inner: S) -> Self {
Self { inner }
}
}
impl<S, B> Service<hyper::Request<B>> for GrpcMetricsService<S>
where
S: Service<hyper::Request<B>, Response = hyper::Response<B>> + Clone + Send + 'static,
S::Future: Send + 'static,
S::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
B: HttpBody + Send + 'static,
{
type Response = hyper::Response<B>;
type Error = S::Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, mut req: hyper::Request<B>) -> Self::Future {
let clone = self.inner.clone();
let mut inner = std::mem::replace(&mut self.inner, clone);
let start_time = Instant::now();
// Extract method name from gRPC path
let method_name = extract_grpc_method_name(&req);
let service_name = extract_grpc_service_name(&req);
// Extract connector from request headers/metadata
let connector = extract_connector_from_request(&req);
// Increment total requests counter
GRPC_SERVER_REQUESTS_TOTAL
.with_label_values(&[&method_name, &service_name, &connector])
.inc();
req.extensions_mut().insert(service_name.clone());
Box::pin(async move {
let result = inner.call(req).await;
// Record metrics based on response
match &result {
Ok(response) => {
// Check gRPC status from response
if is_grpc_success(response) {
GRPC_SERVER_REQUESTS_SUCCESSFUL
.with_label_values(&[&method_name, &service_name, &connector])
.inc();
}
}
Err(_) => {
// Network/transport level error
}
}
// Record latency
let duration = start_time.elapsed().as_secs_f64();
GRPC_SERVER_REQUEST_LATENCY
.with_label_values(&[&method_name, &service_name, &connector])
.observe(duration);
result
})
}
}
// Extract gRPC method name from HTTP request
fn extract_grpc_method_name<B>(req: &hyper::Request<B>) -> String {
let path = req.uri().path();
if let Some(method) = path.rfind('/') {
let method_name = &path[method + 1..];
if !method_name.is_empty() {
return method_name.to_string();
}
}
"unknown_method".to_string()
}
fn extract_grpc_service_name<B>(req: &hyper::Request<B>) -> String {
let path = req.uri().path();
if let Some(pos) = path.rfind('/') {
let full_service = &path[1..pos];
if let Some(service_name) = full_service.rsplit('.').next() {
return service_name.to_string();
}
}
"unknown_service".to_string()
}
// Extract connector information from request
fn extract_connector_from_request<B>(req: &hyper::Request<B>) -> String {
if let Some(connector) = req.headers().get("x-connector") {
if let Ok(connector_str) = connector.to_str() {
return connector_str.to_string();
}
}
"unknown".to_string()
}
// Check if gRPC response indicates success
fn is_grpc_success<B>(response: &hyper::Response<B>) -> bool {
// gRPC success is based on grpc-status header, not HTTP status
if let Some(grpc_status) = response.headers().get("grpc-status") {
if let Ok(status_str) = grpc_status.to_str() {
if let Ok(status_code) = status_str.parse::<i32>() {
if status_code == 0 {
return true; // gRPC OK
} else {
return false;
}
} else {
return false;
}
} else {
return false;
}
}
true
}
// Metrics handler
pub async fn metrics_handler() -> error_stack::Result<String, MetricsError> {
let mut buffer = Vec::new();
let encoder = TextEncoder::new();
let metric_families = prometheus::gather();
encoder
.encode(&metric_families, &mut buffer)
.change_context(MetricsError::EncodingError)?;
String::from_utf8(buffer).change_context(MetricsError::Utf8Error)
}
#[derive(Debug, thiserror::Error)]
pub enum MetricsError {
#[error("Error encoding metrics")]
EncodingError,
#[error("Error converting metrics to utf8")]
Utf8Error,
}
|
{
"chunk": null,
"crate": "external-services",
"enum_name": null,
"file_size": 7315,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_external-services_-791301926000199053
|
clm
|
small_file
|
// connector-service/backend/external-services/src/lib.rs
pub mod service;
pub mod shared_metrics;
pub use service::*;
|
{
"chunk": null,
"crate": "external-services",
"enum_name": null,
"file_size": 61,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_domain_types_3648700667243119668
|
clm
|
small_file
|
// connector-service/backend/domain_types/src/router_request_types.rs
use std::str::FromStr;
use common_enums::{self, CaptureMethod, Currency};
use common_utils::{
pii::{self, IpAddress},
types::SemanticVersion,
Email, MinorUnit,
};
use error_stack::ResultExt;
use hyperswitch_masking::Secret;
use serde::Serialize;
use crate::utils::ForeignFrom;
use grpc_api_types::payments;
use crate::{
errors,
payment_method_data::{PaymentMethodData, PaymentMethodDataTypes},
utils,
};
pub type Error = error_stack::Report<crate::errors::ConnectorError>;
#[derive(Clone, Debug, Default, serde::Serialize, serde::Deserialize)]
pub struct BrowserInformation {
pub color_depth: Option<u8>,
pub java_enabled: Option<bool>,
pub java_script_enabled: Option<bool>,
pub language: Option<String>,
pub screen_height: Option<u32>,
pub screen_width: Option<u32>,
pub time_zone: Option<i32>,
pub ip_address: Option<std::net::IpAddr>,
pub accept_header: Option<String>,
pub user_agent: Option<String>,
pub os_type: Option<String>,
pub os_version: Option<String>,
pub device_model: Option<String>,
pub accept_language: Option<String>,
pub referer: Option<String>,
}
impl BrowserInformation {
pub fn get_ip_address(&self) -> Result<Secret<String, IpAddress>, Error> {
let ip_address = self
.ip_address
.ok_or_else(utils::missing_field_err("browser_info.ip_address"))?;
Ok(Secret::new(ip_address.to_string()))
}
pub fn get_accept_header(&self) -> Result<String, Error> {
self.accept_header
.clone()
.ok_or_else(utils::missing_field_err("browser_info.accept_header"))
}
pub fn get_language(&self) -> Result<String, Error> {
self.language
.clone()
.ok_or_else(utils::missing_field_err("browser_info.language"))
}
pub fn get_screen_height(&self) -> Result<u32, Error> {
self.screen_height
.ok_or_else(utils::missing_field_err("browser_info.screen_height"))
}
pub fn get_screen_width(&self) -> Result<u32, Error> {
self.screen_width
.ok_or_else(utils::missing_field_err("browser_info.screen_width"))
}
pub fn get_color_depth(&self) -> Result<u8, Error> {
self.color_depth
.ok_or_else(utils::missing_field_err("browser_info.color_depth"))
}
pub fn get_user_agent(&self) -> Result<String, Error> {
self.user_agent
.clone()
.ok_or_else(utils::missing_field_err("browser_info.user_agent"))
}
pub fn get_time_zone(&self) -> Result<i32, Error> {
self.time_zone
.ok_or_else(utils::missing_field_err("browser_info.time_zone"))
}
pub fn get_java_enabled(&self) -> Result<bool, Error> {
self.java_enabled
.ok_or_else(utils::missing_field_err("browser_info.java_enabled"))
}
pub fn get_java_script_enabled(&self) -> Result<bool, Error> {
self.java_script_enabled
.ok_or_else(utils::missing_field_err("browser_info.java_script_enabled"))
}
pub fn get_referer(&self) -> Result<String, Error> {
self.referer
.clone()
.ok_or_else(utils::missing_field_err("browser_info.referer"))
}
}
#[derive(Debug, Default, Clone)]
pub enum SyncRequestType {
MultipleCaptureSync(Vec<String>),
#[default]
SinglePaymentSync,
}
#[derive(Debug, Default, Clone)]
pub struct PaymentsCancelData {
pub amount: Option<i64>,
pub currency: Option<Currency>,
pub connector_transaction_id: String,
pub cancellation_reason: Option<String>,
pub connector_meta: Option<serde_json::Value>,
pub browser_info: Option<BrowserInformation>,
pub metadata: Option<serde_json::Value>,
// This metadata is used to store the metadata shared during the payment intent request.
// minor amount data for amount framework
pub minor_amount: Option<MinorUnit>,
pub webhook_url: Option<String>,
pub capture_method: Option<CaptureMethod>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct AuthenticationData {
pub trans_status: Option<common_enums::TransactionStatus>,
pub eci: Option<String>,
pub cavv: Option<Secret<String>>,
// This is mastercard specific field
pub ucaf_collection_indicator: Option<String>,
pub threeds_server_transaction_id: Option<String>,
pub message_version: Option<SemanticVersion>,
pub ds_trans_id: Option<String>,
pub acs_transaction_id: Option<String>,
pub transaction_id: Option<String>,
}
impl TryFrom<payments::AuthenticationData> for AuthenticationData {
type Error = error_stack::Report<errors::ApplicationErrorResponse>;
fn try_from(value: payments::AuthenticationData) -> Result<Self, Self::Error> {
let payments::AuthenticationData {
eci,
cavv,
threeds_server_transaction_id,
message_version,
ds_transaction_id,
trans_status,
acs_transaction_id,
transaction_id,
ucaf_collection_indicator,
} = value;
let threeds_server_transaction_id =
utils::extract_optional_connector_request_reference_id(&threeds_server_transaction_id);
let message_version = message_version.map(|message_version|{
SemanticVersion::from_str(&message_version).change_context(errors::ApplicationErrorResponse::BadRequest(errors::ApiError{
sub_code: "INVALID_SEMANTIC_VERSION_DATA".to_owned(),
error_identifier: 400,
error_message: "Invalid semantic version format. Expected format: 'major.minor.patch' (e.g., '2.1.0')".to_string(),
error_object: Some(serde_json::json!({
"field": "message_version",
"provided_value": message_version,
"expected_format": "major.minor.patch",
"examples": ["1.0.0", "2.1.0", "2.2.0"],
"validation_rule": "Must be in format X.Y.Z where X, Y, Z are non-negative integers"
})),
}))
}).transpose()?;
let trans_status = trans_status.map(|trans_status|{
grpc_api_types::payments::TransactionStatus::try_from(trans_status).change_context(errors::ApplicationErrorResponse::BadRequest(errors::ApiError{
sub_code: "INVALID_TRANSACTION_STATUS".to_owned(),
error_identifier: 400,
error_message: "Invalid transaction status format. Expected one of the valid 3DS transaction status values".to_string(),
error_object: Some(serde_json::json!({
"field": "transaction_status",
"provided_value": trans_status,
"expected_values": [
"Y (Success)",
"N (Failure)",
"U (Verification Not Performed)",
"A (Not Verified)",
"R (Rejected)",
"C (Challenge Required)",
"D (Challenge Required - Decoupled Authentication)",
"I (Information Only)"
],
"validation_rule": "Must be one of the valid 3DS transaction status codes (Y, N, U, A, R, C, D, I)",
"description": "Transaction status represents the result of 3D Secure authentication/verification process"
})),
}))}).transpose()?.map(common_enums::TransactionStatus::foreign_from);
Ok(Self {
ucaf_collection_indicator,
trans_status,
eci,
cavv: cavv.map(Secret::new),
threeds_server_transaction_id,
message_version,
ds_trans_id: ds_transaction_id,
acs_transaction_id,
transaction_id,
})
}
}
impl utils::ForeignFrom<AuthenticationData> for payments::AuthenticationData {
fn foreign_from(value: AuthenticationData) -> Self {
use hyperswitch_masking::ExposeInterface;
Self {
ucaf_collection_indicator: value.ucaf_collection_indicator,
eci: value.eci,
cavv: value.cavv.map(|cavv| cavv.expose()),
threeds_server_transaction_id: value.threeds_server_transaction_id.map(|id| {
payments::Identifier {
id_type: Some(payments::identifier::IdType::Id(id)),
}
}),
message_version: value.message_version.map(|v| v.to_string()),
ds_transaction_id: value.ds_trans_id,
trans_status: value
.trans_status
.map(payments::TransactionStatus::foreign_from)
.map(i32::from),
acs_transaction_id: value.acs_transaction_id,
transaction_id: value.transaction_id,
}
}
}
#[derive(Debug, Clone)]
pub struct ConnectorCustomerData<T: PaymentMethodDataTypes> {
pub description: Option<String>,
pub email: Option<pii::Email>,
pub phone: Option<Secret<String>>,
pub name: Option<Secret<String>>,
pub preprocessing_id: Option<String>,
pub payment_method_data: Option<PaymentMethodData<T>>,
// pub split_payments: Option<SplitPaymentsRequest>,
}
impl<T: PaymentMethodDataTypes> ConnectorCustomerData<T> {
pub fn get_email(&self) -> Result<Email, Error> {
self.email
.clone()
.ok_or_else(utils::missing_field_err("email"))
}
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct AuthoriseIntegrityObject {
/// Authorise amount
pub amount: MinorUnit,
/// Authorise currency
pub currency: Currency,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct CreateOrderIntegrityObject {
/// Authorise amount
pub amount: MinorUnit,
/// Authorise currency
pub currency: Currency,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct SetupMandateIntegrityObject {
/// Authorise amount
pub amount: Option<MinorUnit>,
/// Authorise currency
pub currency: Currency,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct RepeatPaymentIntegrityObject {
/// Payment amount
pub amount: i64,
/// Payment currency
pub currency: Currency,
/// Mandate reference
pub mandate_reference: String,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct PaymentSynIntegrityObject {
/// Authorise amount
pub amount: MinorUnit,
/// Authorise currency
pub currency: Currency,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct PaymentVoidIntegrityObject {
pub connector_transaction_id: String,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct PaymentVoidPostCaptureIntegrityObject {
pub connector_transaction_id: String,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct RefundIntegrityObject {
pub refund_amount: MinorUnit,
pub currency: Currency,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct CaptureIntegrityObject {
pub amount_to_capture: MinorUnit,
pub currency: Currency,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct AcceptDisputeIntegrityObject {
pub connector_dispute_id: String,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct DefendDisputeIntegrityObject {
pub connector_dispute_id: String,
pub defense_reason_code: String,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct RefundSyncIntegrityObject {
pub connector_transaction_id: String,
pub connector_refund_id: String,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct SubmitEvidenceIntegrityObject {
pub connector_dispute_id: String,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct SessionTokenIntegrityObject {
pub amount: MinorUnit,
pub currency: Currency,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct AccessTokenIntegrityObject {
pub grant_type: String,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct CreateConnectorCustomerIntegrityObject {
pub customer_id: Option<Secret<String>>,
pub email: Option<Secret<String>>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct PaymentMethodTokenIntegrityObject {
pub amount: MinorUnit,
pub currency: Currency,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct PreAuthenticateIntegrityObject {
pub amount: MinorUnit,
pub currency: Currency,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct AuthenticateIntegrityObject {
pub amount: MinorUnit,
pub currency: Currency,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct PostAuthenticateIntegrityObject {
pub amount: MinorUnit,
pub currency: Currency,
}
|
{
"chunk": null,
"crate": "domain_types",
"enum_name": null,
"file_size": 12758,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_domain_types_4794849861800683444
|
clm
|
small_file
|
// connector-service/backend/domain_types/src/payment_address.rs
use common_enums::ProductType;
use common_utils::{ext_traits::ConfigExt, Email, MinorUnit};
use hyperswitch_masking::{PeekInterface, Secret, SerializableSecret};
use crate::utils::{convert_us_state_to_code, missing_field_err, Error};
#[derive(Clone, Default, Debug)]
pub struct PaymentAddress {
shipping: Option<Address>,
billing: Option<Address>,
unified_payment_method_billing: Option<Address>,
payment_method_billing: Option<Address>,
}
impl PaymentAddress {
pub fn new(
shipping: Option<Address>,
billing: Option<Address>,
payment_method_billing: Option<Address>,
should_unify_address: Option<bool>,
) -> Self {
// billing -> .billing, this is the billing details passed in the root of payments request
// payment_method_billing -> .payment_method_data.billing
let unified_payment_method_billing = if should_unify_address.unwrap_or(true) {
// Merge the billing details field from both `payment.billing` and `payment.payment_method_data.billing`
// The unified payment_method_billing will be used as billing address and passed to the connector module
// This unification is required in order to provide backwards compatibility
// so that if `payment.billing` is passed it should be sent to the connector module
// Unify the billing details with `payment_method_data.billing`
payment_method_billing
.as_ref()
.map(|payment_method_billing| {
payment_method_billing
.clone()
.unify_address(billing.as_ref())
})
.or(billing.clone())
} else {
payment_method_billing.clone()
};
Self {
shipping,
billing,
unified_payment_method_billing,
payment_method_billing,
}
}
pub fn get_shipping(&self) -> Option<&Address> {
self.shipping.as_ref()
}
pub fn get_payment_method_billing(&self) -> Option<&Address> {
self.unified_payment_method_billing.as_ref()
}
/// Unify the billing details from `payment_method_data.[payment_method_data].billing details`.
pub fn unify_with_payment_method_data_billing(
self,
payment_method_data_billing: Option<Address>,
) -> Self {
// Unify the billing details with `payment_method_data.billing_details`
let unified_payment_method_billing = payment_method_data_billing
.map(|payment_method_data_billing| {
payment_method_data_billing.unify_address(self.get_payment_method_billing())
})
.or(self.get_payment_method_billing().cloned());
Self {
shipping: self.shipping,
billing: self.billing,
unified_payment_method_billing,
payment_method_billing: self.payment_method_billing,
}
}
pub fn get_request_payment_method_billing(&self) -> Option<&Address> {
self.payment_method_billing.as_ref()
}
pub fn get_payment_billing(&self) -> Option<&Address> {
self.billing.as_ref()
}
}
#[derive(Default, Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(deny_unknown_fields)]
pub struct Address {
/// Provide the address details
pub address: Option<AddressDetails>,
pub phone: Option<PhoneDetails>,
pub email: Option<Email>,
}
impl SerializableSecret for Address {}
impl Address {
/// Unify the address, giving priority to `self` when details are present in both
pub fn unify_address(self, other: Option<&Self>) -> Self {
let other_address_details = other.and_then(|address| address.address.as_ref());
Self {
address: self
.address
.map(|address| address.unify_address_details(other_address_details))
.or(other_address_details.cloned()),
email: self.email.or(other.and_then(|other| other.email.clone())),
phone: self.phone.or(other.and_then(|other| other.phone.clone())),
}
}
}
impl Address {
pub fn get_email(&self) -> Result<Email, Error> {
self.email.clone().ok_or_else(missing_field_err("email"))
}
pub fn get_phone_with_country_code(
&self,
) -> Result<Secret<String>, error_stack::Report<crate::errors::ConnectorError>> {
self.phone
.clone()
.map(|phone_details| phone_details.get_number_with_country_code())
.transpose()?
.ok_or_else(missing_field_err("phone"))
}
pub fn get_optional_country(&self) -> Option<common_enums::CountryAlpha2> {
self.address
.as_ref()
.and_then(|billing_details| billing_details.country)
}
pub fn get_optional_full_name(&self) -> Option<Secret<String>> {
self.address
.as_ref()
.and_then(|billing_address| billing_address.get_optional_full_name())
}
pub fn get_optional_first_name(&self) -> Option<Secret<String>> {
self.address
.as_ref()
.and_then(|billing_address| billing_address.get_optional_first_name())
}
pub fn get_optional_last_name(&self) -> Option<Secret<String>> {
self.address
.as_ref()
.and_then(|billing_address| billing_address.get_optional_last_name())
}
}
// used by customers also, could be moved outside
/// Address details
#[derive(Clone, Default, Debug, Eq, serde::Deserialize, serde::Serialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct AddressDetails {
/// The city, district, suburb, town, or village of the address.
pub city: Option<String>,
/// The two-letter ISO 3166-1 alpha-2 country code (e.g., US, GB).
pub country: Option<common_enums::CountryAlpha2>,
/// The first line of the street address or P.O. Box.
pub line1: Option<Secret<String>>,
/// The second line of the street address or P.O. Box (e.g., apartment, suite, unit, or building).
pub line2: Option<Secret<String>>,
/// The third line of the street address, if applicable.
pub line3: Option<Secret<String>>,
/// The zip/postal code for the address
pub zip: Option<Secret<String>>,
/// The address state
pub state: Option<Secret<String>>,
/// The first name for the address
pub first_name: Option<Secret<String>>,
/// The last name for the address
pub last_name: Option<Secret<String>>,
}
impl AddressDetails {
pub fn get_optional_full_name(&self) -> Option<Secret<String>> {
match (self.first_name.as_ref(), self.last_name.as_ref()) {
(Some(first_name), Some(last_name)) => Some(Secret::new(format!(
"{} {}",
first_name.peek(),
last_name.peek()
))),
(Some(name), None) | (None, Some(name)) => Some(name.to_owned()),
_ => None,
}
}
pub fn get_optional_first_name(&self) -> Option<Secret<String>> {
self.first_name.clone()
}
pub fn get_optional_last_name(&self) -> Option<Secret<String>> {
self.last_name.clone()
}
pub fn unify_address_details(self, other: Option<&Self>) -> Self {
if let Some(other) = other {
let (first_name, last_name) = if self
.first_name
.as_ref()
.is_some_and(|first_name| !first_name.is_empty_after_trim())
{
(self.first_name, self.last_name)
} else {
(other.first_name.clone(), other.last_name.clone())
};
Self {
first_name,
last_name,
city: self.city.or(other.city.clone()),
country: self.country.or(other.country),
line1: self.line1.or(other.line1.clone()),
line2: self.line2.or(other.line2.clone()),
line3: self.line3.or(other.line3.clone()),
zip: self.zip.or(other.zip.clone()),
state: self.state.or(other.state.clone()),
}
} else {
self
}
}
}
impl AddressDetails {
pub fn get_first_name(&self) -> Result<&Secret<String>, Error> {
self.first_name
.as_ref()
.ok_or_else(missing_field_err("address.first_name"))
}
pub fn get_last_name(&self) -> Result<&Secret<String>, Error> {
self.last_name
.as_ref()
.ok_or_else(missing_field_err("address.last_name"))
}
pub fn get_full_name(&self) -> Result<Secret<String>, Error> {
let first_name = self.get_first_name()?.peek().to_owned();
let last_name = self
.get_last_name()
.ok()
.cloned()
.unwrap_or(Secret::new("".to_string()));
let last_name = last_name.peek();
let full_name = format!("{first_name} {last_name}").trim().to_string();
Ok(Secret::new(full_name))
}
pub fn get_line1(&self) -> Result<&Secret<String>, Error> {
self.line1
.as_ref()
.ok_or_else(missing_field_err("address.line1"))
}
pub fn get_city(&self) -> Result<&String, Error> {
self.city
.as_ref()
.ok_or_else(missing_field_err("address.city"))
}
pub fn get_state(&self) -> Result<&Secret<String>, Error> {
self.state
.as_ref()
.ok_or_else(missing_field_err("address.state"))
}
pub fn get_line2(&self) -> Result<&Secret<String>, Error> {
self.line2
.as_ref()
.ok_or_else(missing_field_err("address.line2"))
}
pub fn get_zip(&self) -> Result<&Secret<String>, Error> {
self.zip
.as_ref()
.ok_or_else(missing_field_err("address.zip"))
}
pub fn get_country(&self) -> Result<&common_enums::CountryAlpha2, Error> {
self.country
.as_ref()
.ok_or_else(missing_field_err("address.country"))
}
pub fn get_combined_address_line(&self) -> Result<Secret<String>, Error> {
Ok(Secret::new(format!(
"{},{}",
self.get_line1()?.peek(),
self.get_line2()?.peek()
)))
}
pub fn get_optional_line2(&self) -> Option<Secret<String>> {
self.line2.clone()
}
pub fn get_optional_country(&self) -> Option<common_enums::CountryAlpha2> {
self.country
}
pub fn to_state_code(&self) -> Result<Secret<String>, Error> {
let country = self.get_country()?;
let state = self.get_state()?;
match country {
common_enums::CountryAlpha2::US => Ok(Secret::new(
convert_us_state_to_code(&state.peek().to_string()).to_string(),
)),
_ => Ok(state.clone()),
}
}
pub fn to_state_code_as_optional(&self) -> Result<Option<Secret<String>>, Error> {
self.state
.as_ref()
.map(|state| {
if state.peek().len() == 2 {
Ok(state.to_owned())
} else {
self.to_state_code()
}
})
.transpose()
}
}
#[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct PhoneDetails {
/// The contact number
pub number: Option<Secret<String>>,
/// The country code attached to the number
pub country_code: Option<String>,
}
impl PhoneDetails {
pub fn get_country_code(&self) -> Result<String, Error> {
self.country_code
.clone()
.ok_or_else(missing_field_err("billing.phone.country_code"))
}
pub fn extract_country_code(&self) -> Result<String, Error> {
self.get_country_code()
.map(|cc| cc.trim_start_matches('+').to_string())
}
pub fn get_number(&self) -> Result<Secret<String>, Error> {
self.number
.clone()
.ok_or_else(missing_field_err("billing.phone.number"))
}
pub fn get_number_with_country_code(&self) -> Result<Secret<String>, Error> {
let number = self.get_number()?;
let country_code = self.get_country_code()?;
Ok(Secret::new(format!("{}{}", country_code, number.peek())))
}
pub fn get_number_with_hash_country_code(&self) -> Result<Secret<String>, Error> {
let number = self.get_number()?;
let country_code = self.get_country_code()?;
let number_without_plus = country_code.trim_start_matches('+');
Ok(Secret::new(format!(
"{}#{}",
number_without_plus,
number.peek()
)))
}
}
#[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)]
pub struct RedirectionResponse {
pub return_url_with_query_params: String,
}
#[derive(Debug, Default, PartialEq, serde::Deserialize, serde::Serialize, Clone)]
pub struct OrderDetailsWithAmount {
/// Name of the product that is being purchased
pub product_name: String,
/// The quantity of the product to be purchased
pub quantity: u16,
/// the amount per quantity of product
pub amount: MinorUnit,
/// tax rate applicable to the product
pub tax_rate: Option<f64>,
/// total tax amount applicable to the product
pub total_tax_amount: Option<MinorUnit>,
// Does the order includes shipping
pub requires_shipping: Option<bool>,
/// The image URL of the product
pub product_img_link: Option<String>,
/// ID of the product that is being purchased
pub product_id: Option<String>,
/// Category of the product that is being purchased
pub category: Option<String>,
/// Sub category of the product that is being purchased
pub sub_category: Option<String>,
/// Brand of the product that is being purchased
pub brand: Option<String>,
/// Type of the product that is being purchased
pub product_type: Option<ProductType>,
/// The tax code for the product
pub product_tax_code: Option<String>,
}
impl hyperswitch_masking::SerializableSecret for OrderDetailsWithAmount {}
|
{
"chunk": null,
"crate": "domain_types",
"enum_name": null,
"file_size": 14201,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_domain_types_-8778740194381731474
|
clm
|
small_file
|
// connector-service/backend/domain_types/src/router_data_v2.rs
use std::marker::PhantomData;
use crate::router_data::{ConnectorAuthType, ErrorResponse};
#[derive(Debug, Clone)]
pub struct RouterDataV2<Flow, ResourceCommonData, FlowSpecificRequest, FlowSpecificResponse> {
pub flow: PhantomData<Flow>,
// pub tenant_id: id_type::TenantId, // TODO: Should we add this
pub resource_common_data: ResourceCommonData,
pub connector_auth_type: ConnectorAuthType,
/// Contains flow-specific data required to construct a request and send it to the connector.
pub request: FlowSpecificRequest,
/// Contains flow-specific data that the connector responds with.
pub response: Result<FlowSpecificResponse, ErrorResponse>,
}
|
{
"chunk": null,
"crate": "domain_types",
"enum_name": null,
"file_size": 682,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_domain_types_2301475437378205030
|
clm
|
small_file
|
// connector-service/backend/domain_types/src/lib.rs
pub mod api;
pub mod connector_flow;
pub mod connector_types;
pub mod errors;
pub mod mandates;
pub mod payment_address;
pub mod payment_method_data;
pub mod router_data;
pub mod router_data_v2;
pub mod router_flow_types;
pub mod router_request_types;
pub mod router_response_types;
pub mod types;
pub mod utils;
|
{
"chunk": null,
"crate": "domain_types",
"enum_name": null,
"file_size": 313,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_domain_types_-764259173922624356
|
clm
|
small_file
|
// connector-service/backend/domain_types/src/router_flow_types.rs
use serde::Serialize;
#[derive(Clone, Debug)]
pub struct VerifyWebhookSource;
#[derive(Debug, Clone, Serialize)]
pub struct ConnectorMandateDetails {
pub connector_mandate_id: hyperswitch_masking::Secret<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct ConnectorNetworkTxnId(hyperswitch_masking::Secret<String>);
impl ConnectorNetworkTxnId {
pub fn new(txn_id: hyperswitch_masking::Secret<String>) -> Self {
Self(txn_id)
}
pub fn get_id(&self) -> &hyperswitch_masking::Secret<String> {
&self.0
}
}
|
{
"chunk": null,
"crate": "domain_types",
"enum_name": null,
"file_size": 546,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_domain_types_7969894047322031300
|
clm
|
small_file
|
// connector-service/backend/domain_types/src/router_data.rs
use std::collections::HashMap;
use cards::{
validate::{CardExpirationMonth, CardExpirationYear},
NetworkToken,
};
use common_utils::ext_traits::{OptionExt, ValueExt};
use error_stack::ResultExt;
use hyperswitch_masking::{ExposeInterface, Secret};
use crate::utils::missing_field_err;
pub type Error = error_stack::Report<crate::errors::ConnectorError>;
#[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize)]
#[serde(tag = "auth_type")]
pub enum ConnectorAuthType {
TemporaryAuth,
HeaderKey {
api_key: Secret<String>,
},
BodyKey {
api_key: Secret<String>,
key1: Secret<String>,
},
SignatureKey {
api_key: Secret<String>,
key1: Secret<String>,
api_secret: Secret<String>,
},
MultiAuthKey {
api_key: Secret<String>,
key1: Secret<String>,
api_secret: Secret<String>,
key2: Secret<String>,
},
CurrencyAuthKey {
auth_key_map: HashMap<common_enums::enums::Currency, common_utils::pii::SecretSerdeValue>,
},
CertificateAuth {
certificate: Secret<String>,
private_key: Secret<String>,
},
#[default]
NoKey,
}
impl ConnectorAuthType {
pub fn from_option_secret_value(
value: Option<common_utils::pii::SecretSerdeValue>,
) -> common_utils::errors::CustomResult<Self, common_utils::errors::ParsingError> {
value
.parse_value::<Self>("ConnectorAuthType")
.change_context(common_utils::errors::ParsingError::StructParseFailure(
"ConnectorAuthType",
))
}
pub fn from_secret_value(
value: common_utils::pii::SecretSerdeValue,
) -> common_utils::errors::CustomResult<Self, common_utils::errors::ParsingError> {
value
.parse_value::<Self>("ConnectorAuthType")
.change_context(common_utils::errors::ParsingError::StructParseFailure(
"ConnectorAuthType",
))
}
// show only first and last two digits of the key and mask others with *
// mask the entire key if it's length is less than or equal to 4
fn mask_key(&self, key: String) -> Secret<String> {
let key_len = key.len();
let masked_key = if key_len <= 4 {
"*".repeat(key_len)
} else {
// Show the first two and last two characters, mask the rest with '*'
let mut masked_key = String::new();
let key_len = key.len();
// Iterate through characters by their index
for (index, character) in key.chars().enumerate() {
if index < 2 || index >= key_len - 2 {
masked_key.push(character); // Keep the first two and last two characters
} else {
masked_key.push('*'); // Mask the middle characters
}
}
masked_key
};
Secret::new(masked_key)
}
// Mask the keys in the auth_type
pub fn get_masked_keys(&self) -> Self {
match self {
Self::TemporaryAuth => Self::TemporaryAuth,
Self::NoKey => Self::NoKey,
Self::HeaderKey { api_key } => Self::HeaderKey {
api_key: self.mask_key(api_key.clone().expose()),
},
Self::BodyKey { api_key, key1 } => Self::BodyKey {
api_key: self.mask_key(api_key.clone().expose()),
key1: self.mask_key(key1.clone().expose()),
},
Self::SignatureKey {
api_key,
key1,
api_secret,
} => Self::SignatureKey {
api_key: self.mask_key(api_key.clone().expose()),
key1: self.mask_key(key1.clone().expose()),
api_secret: self.mask_key(api_secret.clone().expose()),
},
Self::MultiAuthKey {
api_key,
key1,
api_secret,
key2,
} => Self::MultiAuthKey {
api_key: self.mask_key(api_key.clone().expose()),
key1: self.mask_key(key1.clone().expose()),
api_secret: self.mask_key(api_secret.clone().expose()),
key2: self.mask_key(key2.clone().expose()),
},
Self::CurrencyAuthKey { auth_key_map } => Self::CurrencyAuthKey {
auth_key_map: auth_key_map.clone(),
},
Self::CertificateAuth {
certificate,
private_key,
} => Self::CertificateAuth {
certificate: self.mask_key(certificate.clone().expose()),
private_key: self.mask_key(private_key.clone().expose()),
},
}
}
}
#[derive(Clone, Debug, serde::Serialize)]
pub struct ErrorResponse {
pub code: String,
pub message: String,
pub reason: Option<String>,
pub status_code: u16,
pub attempt_status: Option<common_enums::enums::AttemptStatus>,
pub connector_transaction_id: Option<String>,
pub network_decline_code: Option<String>,
pub network_advice_code: Option<String>,
pub network_error_message: Option<String>,
}
impl Default for ErrorResponse {
fn default() -> Self {
Self {
code: "HE_00".to_string(),
message: "Something went wrong".to_string(),
reason: None,
status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(),
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
}
}
}
impl ErrorResponse {
pub fn get_not_implemented() -> Self {
Self {
code: "IR_00".to_string(),
message: "This API is under development and will be made available soon.".to_string(),
reason: None,
status_code: http::StatusCode::INTERNAL_SERVER_ERROR.as_u16(),
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
}
}
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayCryptogramData {
pub online_payment_cryptogram: Secret<String>,
pub eci_indicator: Option<String>,
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ApplePayPredecryptData {
pub application_primary_account_number: Secret<String>,
pub application_expiration_date: String,
pub currency_code: String,
pub transaction_amount: i64,
pub device_manufacturer_identifier: Secret<String>,
pub payment_data_type: Secret<String>,
pub payment_data: ApplePayCryptogramData,
}
impl ApplePayPredecryptData {
pub fn get_four_digit_expiry_year(&self) -> Result<Secret<String>, Error> {
Ok(Secret::new(format!(
"20{}",
self.application_expiration_date
.get(0..2)
.ok_or(crate::errors::ConnectorError::RequestEncodingFailed)?
)))
}
pub fn get_expiry_month(&self) -> Result<Secret<String>, Error> {
Ok(Secret::new(
self.application_expiration_date
.get(2..4)
.ok_or(crate::errors::ConnectorError::RequestEncodingFailed)?
.to_owned(),
))
}
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayDecryptedData {
pub message_expiration: String,
pub message_id: String,
#[serde(rename = "paymentMethod")]
pub payment_method_type: String,
pub payment_method_details: GooglePayPaymentMethodDetails,
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayPaymentMethodDetails {
pub auth_method: common_enums::enums::GooglePayAuthMethod,
pub expiration_month: CardExpirationMonth,
pub expiration_year: CardExpirationYear,
pub pan: cards::CardNumber,
pub cryptogram: Option<Secret<String>>,
pub eci_indicator: Option<String>,
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PazeDecryptedData {
pub client_id: Secret<String>,
pub profile_id: String,
pub token: PazeToken,
pub payment_card_network: common_enums::enums::CardNetwork,
pub dynamic_data: Vec<PazeDynamicData>,
pub billing_address: PazeAddress,
pub consumer: PazeConsumer,
pub eci: Option<String>,
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PazeToken {
pub payment_token: NetworkTokenNumber,
pub token_expiration_month: Secret<String>,
pub token_expiration_year: Secret<String>,
pub payment_account_reference: Secret<String>,
}
pub type NetworkTokenNumber = NetworkToken;
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PazeConsumer {
// This is consumer data not customer data.
pub first_name: Option<Secret<String>>,
pub last_name: Option<Secret<String>>,
pub full_name: Secret<String>,
pub email_address: common_utils::pii::Email,
pub mobile_number: Option<PazePhoneNumber>,
pub country_code: Option<common_enums::enums::CountryAlpha2>,
pub language_code: Option<String>,
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PazePhoneNumber {
pub country_code: Secret<String>,
pub phone_number: Secret<String>,
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PazeAddress {
pub name: Option<Secret<String>>,
pub line1: Option<Secret<String>>,
pub line2: Option<Secret<String>>,
pub line3: Option<Secret<String>>,
pub city: Option<Secret<String>>,
pub state: Option<Secret<String>>,
pub zip: Option<Secret<String>>,
pub country_code: Option<common_enums::enums::CountryAlpha2>,
}
#[derive(Debug, Clone, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PazeDynamicData {
pub dynamic_data_value: Option<Secret<String>>,
pub dynamic_data_type: Option<String>,
pub dynamic_data_expiration: Option<String>,
}
#[derive(Debug, Clone, serde::Deserialize)]
pub enum PaymentMethodToken {
Token(Secret<String>),
ApplePayDecrypt(Box<ApplePayPredecryptData>),
GooglePayDecrypt(Box<GooglePayDecryptedData>),
PazeDecrypt(Box<PazeDecryptedData>),
}
#[derive(Debug, Default, Clone)]
pub struct RecurringMandatePaymentData {
pub payment_method_type: Option<common_enums::enums::PaymentMethodType>, //required for making recurring payment using saved payment method through stripe
pub original_payment_authorized_amount: Option<i64>,
pub original_payment_authorized_currency: Option<common_enums::enums::Currency>,
pub mandate_metadata: Option<common_utils::pii::SecretSerdeValue>,
}
impl RecurringMandatePaymentData {
pub fn get_original_payment_amount(&self) -> Result<i64, Error> {
self.original_payment_authorized_amount
.ok_or_else(missing_field_err("original_payment_authorized_amount"))
}
pub fn get_original_payment_currency(&self) -> Result<common_enums::Currency, Error> {
self.original_payment_authorized_currency
.ok_or_else(missing_field_err("original_payment_authorized_currency"))
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ConnectorResponseData {
pub additional_payment_method_data: Option<AdditionalPaymentMethodConnectorResponse>,
extended_authorization_response_data: Option<ExtendedAuthorizationResponseData>,
is_overcapture_enabled: Option<bool>,
}
impl ConnectorResponseData {
pub fn with_additional_payment_method_data(
additional_payment_method_data: AdditionalPaymentMethodConnectorResponse,
) -> Self {
Self {
additional_payment_method_data: Some(additional_payment_method_data),
extended_authorization_response_data: None,
is_overcapture_enabled: None,
}
}
pub fn new(
additional_payment_method_data: Option<AdditionalPaymentMethodConnectorResponse>,
is_overcapture_enabled: Option<bool>,
extended_authorization_response_data: Option<ExtendedAuthorizationResponseData>,
) -> Self {
Self {
additional_payment_method_data,
extended_authorization_response_data,
is_overcapture_enabled,
}
}
pub fn get_extended_authorization_response_data(
&self,
) -> Option<&ExtendedAuthorizationResponseData> {
self.extended_authorization_response_data.as_ref()
}
pub fn is_overcapture_enabled(&self) -> Option<bool> {
self.is_overcapture_enabled
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum AdditionalPaymentMethodConnectorResponse {
Card {
/// Details regarding the authentication details of the connector, if this is a 3ds payment.
authentication_data: Option<serde_json::Value>,
/// Various payment checks that are done for a payment
payment_checks: Option<serde_json::Value>,
/// Card Network returned by the processor
card_network: Option<String>,
/// Domestic(Co-Branded) Card network returned by the processor
domestic_network: Option<String>,
},
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ExtendedAuthorizationResponseData {
pub extended_authentication_applied: Option<bool>,
pub capture_before: Option<time::PrimitiveDateTime>,
}
|
{
"chunk": null,
"crate": "domain_types",
"enum_name": null,
"file_size": 13730,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_domain_types_6123773352099696515
|
clm
|
small_file
|
// connector-service/backend/domain_types/src/router_response_types.rs
use std::collections::HashMap;
use common_utils::Method;
#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
pub enum RedirectForm {
Form {
endpoint: String,
method: Method,
form_fields: HashMap<String, String>,
},
Html {
html_data: String,
},
BlueSnap {
payment_fields_token: String, // payment-field-token
},
CybersourceAuthSetup {
access_token: String,
ddc_url: String,
reference_id: String,
},
CybersourceConsumerAuth {
access_token: String,
step_up_url: String,
},
DeutschebankThreeDSChallengeFlow {
acs_url: String,
creq: String,
},
Payme,
Braintree {
client_token: String,
card_token: String,
bin: String,
acs_url: String,
},
Nmi {
amount: String,
currency: common_enums::Currency,
public_key: hyperswitch_masking::Secret<String>,
customer_vault_id: String,
order_id: String,
},
Mifinity {
initialization_token: String,
},
WorldpayDDCForm {
endpoint: url::Url,
method: Method,
form_fields: HashMap<String, String>,
collection_id: Option<String>,
},
Uri {
uri: String,
},
}
impl From<(url::Url, Method)> for RedirectForm {
fn from((mut redirect_url, method): (url::Url, Method)) -> Self {
let form_fields = HashMap::from_iter(
redirect_url
.query_pairs()
.map(|(key, value)| (key.to_string(), value.to_string())),
);
// Do not include query params in the endpoint
redirect_url.set_query(None);
Self::Form {
endpoint: redirect_url.to_string(),
method,
form_fields,
}
}
}
#[derive(Clone, Debug)]
pub struct Response {
/// headers
pub headers: Option<http::HeaderMap>,
/// response
pub response: bytes::Bytes,
/// status code
pub status_code: u16,
}
|
{
"chunk": null,
"crate": "domain_types",
"enum_name": null,
"file_size": 2052,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_domain_types_-9203487555415585328
|
clm
|
small_file
|
// connector-service/backend/domain_types/src/mandates.rs
use common_enums::Currency;
use common_utils::{date_time, pii::IpAddress, SecretSerdeValue};
use error_stack::ResultExt;
use hyperswitch_masking::Secret;
use time::PrimitiveDateTime;
use crate::utils::{missing_field_err, Error};
#[derive(Default, Eq, PartialEq, Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct CustomerAcceptance {
/// Type of acceptance provided by the
pub acceptance_type: AcceptanceType,
/// Specifying when the customer acceptance was provided
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub accepted_at: Option<PrimitiveDateTime>,
/// Information required for online mandate generation
pub online: Option<OnlineMandate>,
}
#[derive(Default, Eq, PartialEq, Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct OnlineMandate {
/// Ip address of the customer machine from which the mandate was created
#[serde(skip_deserializing)]
pub ip_address: Option<Secret<String, IpAddress>>,
/// The user-agent of the customer's browser
pub user_agent: String,
}
#[derive(Default, Eq, PartialEq, Debug, Clone, serde::Serialize)]
pub struct MandateData {
/// A way to update the mandate's payment method details
pub update_mandate_id: Option<String>,
/// A consent from the customer to store the payment method
pub customer_acceptance: Option<CustomerAcceptance>,
/// A way to select the type of mandate used
pub mandate_type: Option<MandateDataType>,
}
#[derive(Default, Debug, PartialEq, Eq, Clone, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "lowercase")]
pub enum AcceptanceType {
Online,
#[default]
Offline,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum MandateDataType {
SingleUse(MandateAmountData),
MultiUse(Option<MandateAmountData>),
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
pub struct MandateAmountData {
pub amount: common_utils::types::MinorUnit,
pub currency: Currency,
pub start_date: Option<PrimitiveDateTime>,
pub end_date: Option<PrimitiveDateTime>,
pub metadata: Option<SecretSerdeValue>,
}
impl MandateAmountData {
pub fn get_end_date(&self, format: date_time::DateFormat) -> Result<String, Error> {
let date = self.end_date.ok_or_else(missing_field_err(
"mandate_data.mandate_type.{multi_use|single_use}.end_date",
))?;
date_time::format_date(date, format)
.change_context(crate::errors::ConnectorError::DateFormattingFailed)
}
pub fn get_metadata(&self) -> Result<SecretSerdeValue, Error> {
self.metadata.clone().ok_or_else(missing_field_err(
"mandate_data.mandate_type.{multi_use|single_use}.metadata",
))
}
}
|
{
"chunk": null,
"crate": "domain_types",
"enum_name": null,
"file_size": 2830,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_domain_types_-8256841136792189831
|
clm
|
small_file
|
// connector-service/backend/domain_types/src/api.rs
use std::collections::HashSet;
use crate::{
payment_method_data::{DefaultPCIHolder, PaymentMethodData},
router_response_types::RedirectForm,
};
#[derive(Debug, Eq, PartialEq)]
pub struct RedirectionFormData {
pub redirect_form: RedirectForm,
pub payment_method_data: Option<PaymentMethodData<DefaultPCIHolder>>,
pub amount: String,
pub currency: String,
}
#[derive(Debug, Eq, PartialEq)]
pub enum PaymentLinkAction {
PaymentLinkFormData(PaymentLinkFormData),
PaymentLinkStatus(PaymentLinkStatusData),
}
#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentLinkFormData {
pub js_script: String,
pub css_script: String,
pub sdk_url: url::Url,
pub html_meta_tags: String,
}
#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentLinkStatusData {
pub js_script: String,
pub css_script: String,
}
#[derive(Debug, Eq, PartialEq)]
pub struct GenericLinks {
pub allowed_domains: HashSet<String>,
pub data: GenericLinksData,
pub locale: String,
}
#[derive(Debug, Eq, PartialEq)]
pub enum GenericLinksData {
ExpiredLink(GenericExpiredLinkData),
PaymentMethodCollect(GenericLinkFormData),
PayoutLink(GenericLinkFormData),
PayoutLinkStatus(GenericLinkStatusData),
PaymentMethodCollectStatus(GenericLinkStatusData),
SecurePaymentLink(PaymentLinkFormData),
}
#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
pub struct GenericExpiredLinkData {
pub title: String,
pub message: String,
pub theme: String,
}
#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
pub struct GenericLinkFormData {
pub js_data: String,
pub css_data: String,
pub sdk_url: url::Url,
pub html_meta_tags: String,
}
#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
pub struct GenericLinkStatusData {
pub js_data: String,
pub css_data: String,
}
|
{
"chunk": null,
"crate": "domain_types",
"enum_name": null,
"file_size": 2002,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_domain_types_-4703749612792602811
|
clm
|
small_file
|
// connector-service/backend/domain_types/src/connector_flow.rs
#[derive(Debug, Clone)]
pub struct CreateOrder;
#[derive(Debug, Clone)]
pub struct Authorize;
#[derive(Debug, Clone)]
pub struct PSync;
#[derive(Debug, Clone)]
pub struct Void;
#[derive(Debug, Clone)]
pub struct RSync;
#[derive(Debug, Clone)]
pub struct Refund;
#[derive(Debug, Clone)]
pub struct Capture;
#[derive(Debug, Clone)]
pub struct SetupMandate;
#[derive(Debug, Clone)]
pub struct RepeatPayment;
#[derive(Debug, Clone)]
pub struct Accept;
#[derive(Debug, Clone)]
pub struct SubmitEvidence;
#[derive(Debug, Clone)]
pub struct DefendDispute;
#[derive(Debug, Clone)]
pub struct CreateSessionToken;
#[derive(Debug, Clone)]
pub struct CreateAccessToken;
#[derive(Debug, Clone)]
pub struct CreateConnectorCustomer;
#[derive(Debug, Clone)]
pub struct PaymentMethodToken;
#[derive(Debug, Clone)]
pub struct PreAuthenticate;
#[derive(Debug, Clone)]
pub struct Authenticate;
#[derive(Debug, Clone)]
pub struct PostAuthenticate;
#[derive(Debug, Clone)]
pub struct VoidPC;
#[derive(strum::Display)]
#[strum(serialize_all = "snake_case")]
pub enum FlowName {
Authorize,
Refund,
Rsync,
Psync,
Void,
VoidPc,
SetupMandate,
RepeatPayment,
Capture,
AcceptDispute,
SubmitEvidence,
DefendDispute,
CreateOrder,
IncomingWebhook,
Dsync,
CreateSessionToken,
CreateAccessToken,
CreateConnectorCustomer,
PaymentMethodToken,
PreAuthenticate,
Authenticate,
PostAuthenticate,
}
|
{
"chunk": null,
"crate": "domain_types",
"enum_name": null,
"file_size": 1466,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_grpc-api-types_-3244079078714223733
|
clm
|
small_file
|
// connector-service/backend/grpc-api-types/build.rs
use std::{env, path::PathBuf};
fn main() -> Result<(), Box<dyn std::error::Error>> {
let out_dir = PathBuf::from(env::var("OUT_DIR")?);
// Create the bridge generator with string enums
let bridge_generator = g2h::BridgeGenerator::with_tonic_build()
.with_string_enums()
.file_descriptor_set_path(out_dir.join("connector_service_descriptor.bin"));
// Create a basic prost config and add your extern_path configuration
let mut config = prost_build::Config::new();
config.extern_path(".ucs.v2.CardNumberType", "::cards::CardNumber");
config.extern_path(
".ucs.v2.SecretString",
"::hyperswitch_masking::Secret<String>",
);
// Use compile_protos_with_config which handles everything internally
// including string enum support, serde derives, and descriptor set writing
bridge_generator.compile_protos_with_config(
config,
&[
"proto/services.proto",
"proto/health_check.proto",
"proto/payment.proto",
"proto/payment_methods.proto",
],
&["proto"],
)?;
// prost_build::Config::new()
// .service_generator(Box::new(web_generator))
// .file_descriptor_set_path(out_dir.join("connector_service_descriptor.bin"))
// .type_attribute(".", "#[derive(serde::Serialize, serde::Deserialize)]")
// .type_attribute(".", "#[allow(clippy::large_enum_variant)]")
// .compile_protos(
// &[
// "proto/services.proto",
// "proto/health_check.proto",
// "proto/payment.proto",
// "proto/payment_methods.proto",
// ],
// &["proto"],
// )?;
Ok(())
}
|
{
"chunk": null,
"crate": "grpc-api-types",
"enum_name": null,
"file_size": 1744,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_grpc-api-types_3661992858984206027
|
clm
|
small_file
|
// connector-service/backend/grpc-api-types/src/lib.rs
#![allow(clippy::large_enum_variant)]
#![allow(clippy::uninlined_format_args)]
pub const FILE_DESCRIPTOR_SET: &[u8] =
tonic::include_file_descriptor_set!("connector_service_descriptor");
pub mod payments {
tonic::include_proto!("ucs.v2");
}
pub mod health_check {
tonic::include_proto!("grpc.health.v1");
}
|
{
"chunk": null,
"crate": "grpc-api-types",
"enum_name": null,
"file_size": 322,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_grpc-server_6998574658475352091
|
clm
|
small_file
|
// connector-service/backend/grpc-server/build.rs
fn main() -> Result<(), Box<dyn std::error::Error>> {
build_info::set_cargo_workspace_members_env();
build_info::generate_vergen_cargo_instructions();
Ok(())
}
|
{
"chunk": null,
"crate": "grpc-server",
"enum_name": null,
"file_size": 173,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_grpc-server_-4343738646407124784
|
clm
|
small_file
|
// connector-service/backend/grpc-server/tests/novalnet_payment_flows_test.rs
#![allow(clippy::expect_used)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::panic)]
use grpc_server::{app, configs};
mod common;
mod utils;
use std::{
str::FromStr,
time::{SystemTime, UNIX_EPOCH},
};
use cards::CardNumber;
use grpc_api_types::{
health_check::{health_client::HealthClient, HealthCheckRequest},
payments::{
card_payment_method_type, identifier::IdType, payment_method,
payment_service_client::PaymentServiceClient, Address, AuthenticationType, CaptureMethod,
CardDetails, CardPaymentMethodType, Currency, Identifier, PaymentAddress, PaymentMethod,
PaymentServiceAuthorizeRequest, PaymentStatus,
},
};
use hyperswitch_masking::{ExposeInterface, Secret};
use tonic::{transport::Channel, Request};
use uuid::Uuid;
// Helper function to get current timestamp
fn get_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
// Helper function to generate a unique ID using UUID
fn generate_unique_id(prefix: &str) -> String {
format!("{}_{}", prefix, Uuid::new_v4())
}
// Constants for Novalnet connector
const CONNECTOR_NAME: &str = "novalnet";
const AUTH_TYPE: &str = "signature-key";
const MERCHANT_ID: &str = "merchant_1234";
// Test card data
const TEST_AMOUNT: i64 = 1000;
const TEST_CARD_NUMBER: &str = "4111111111111111"; // Valid test card for Novalnet
const TEST_CARD_EXP_MONTH: &str = "12";
const TEST_CARD_EXP_YEAR: &str = "2025";
const TEST_CARD_CVC: &str = "123";
const TEST_CARD_HOLDER: &str = "Test User";
const TEST_EMAIL: &str = "customer@example.com";
fn add_novalnet_metadata<T>(request: &mut Request<T>) {
let auth = utils::credential_utils::load_connector_auth(CONNECTOR_NAME)
.expect("Failed to load novalnet credentials");
let (api_key, key1, api_secret) = match auth {
domain_types::router_data::ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => (api_key.expose(), key1.expose(), api_secret.expose()),
_ => panic!("Expected SignatureKey auth type for novalnet"),
};
request.metadata_mut().append(
"x-connector",
CONNECTOR_NAME.parse().expect("Failed to parse x-connector"),
);
request
.metadata_mut()
.append("x-auth", AUTH_TYPE.parse().expect("Failed to parse x-auth"));
request.metadata_mut().append(
"x-api-key",
api_key.parse().expect("Failed to parse x-api-key"),
);
request
.metadata_mut()
.append("x-key1", key1.parse().expect("Failed to parse x-key1"));
request.metadata_mut().append(
"x-api-secret",
api_secret.parse().expect("Failed to parse x-api-secret"),
);
request.metadata_mut().append(
"x-merchant-id",
MERCHANT_ID.parse().expect("Failed to parse x-merchant-id"),
);
request.metadata_mut().append(
"x-request-id",
format!("test_request_{}", get_timestamp())
.parse()
.expect("Failed to parse x-request-id"),
);
}
// Helper function to create a payment authorize request
fn create_authorize_request(capture_method: CaptureMethod) -> PaymentServiceAuthorizeRequest {
let card_details = card_payment_method_type::CardType::Credit(CardDetails {
card_number: Some(CardNumber::from_str(TEST_CARD_NUMBER).unwrap()),
card_exp_month: Some(Secret::new(TEST_CARD_EXP_MONTH.to_string())),
card_exp_year: Some(Secret::new(TEST_CARD_EXP_YEAR.to_string())),
card_cvc: Some(Secret::new(TEST_CARD_CVC.to_string())),
card_holder_name: Some(Secret::new(TEST_CARD_HOLDER.to_string())),
card_issuer: None,
card_network: Some(1),
card_type: None,
card_issuing_country_alpha2: None,
bank_code: None,
nick_name: None,
});
let address = PaymentAddress {
billing_address: Some(Address {
first_name: Some("John".to_string().into()),
last_name: Some("Doe".to_string().into()),
email: Some("test@test.com".to_string().into()),
..Default::default()
}),
shipping_address: None,
};
PaymentServiceAuthorizeRequest {
amount: TEST_AMOUNT,
minor_amount: TEST_AMOUNT,
currency: i32::from(Currency::Usd),
payment_method: Some(PaymentMethod {
payment_method: Some(payment_method::PaymentMethod::Card(CardPaymentMethodType {
card_type: Some(card_details),
})),
}),
return_url: Some("https://hyperswitch.io/".to_string()),
webhook_url: Some("https://hyperswitch.io/".to_string()),
email: Some(TEST_EMAIL.to_string().into()),
address: Some(address),
auth_type: i32::from(AuthenticationType::NoThreeDs),
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(generate_unique_id("novalnet_test"))),
}),
enrolled_for_3ds: false,
request_incremental_authorization: false,
capture_method: Some(i32::from(capture_method)),
// payment_method_type: Some(i32::from(PaymentMethodType::Credit)),
..Default::default()
}
}
// Test for basic health check
#[tokio::test]
async fn test_health() {
grpc_test!(client, HealthClient<Channel>, {
let response = client
.check(Request::new(HealthCheckRequest {
service: "connector_service".to_string(),
}))
.await
.expect("Failed to call health check")
.into_inner();
assert_eq!(
response.status(),
grpc_api_types::health_check::health_check_response::ServingStatus::Serving
);
});
}
// Test payment authorization with auto capture
#[tokio::test]
async fn test_payment_authorization_auto_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request
let request = create_authorize_request(CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_novalnet_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC authorize call failed")
.into_inner();
assert!(
response.status == i32::from(PaymentStatus::AuthenticationPending),
"Payment should be in AuthenticationPending state"
);
});
}
|
{
"chunk": null,
"crate": "grpc-server",
"enum_name": null,
"file_size": 6551,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_grpc-server_-9211585717375662373
|
clm
|
small_file
|
// connector-service/backend/grpc-server/tests/test_amount_conversion.rs
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use common_enums::Currency;
use common_utils::{
types::{MinorUnit, StringMajorUnitForConnector},
AmountConvertor,
};
#[test]
fn test_amount_conversion_with_currency_validation() {
let converter = StringMajorUnitForConnector;
let amount = MinorUnit::new(12345);
// Test zero decimal currency (JPY)
let result = converter.convert(amount, Currency::JPY);
assert!(result.is_ok(), "JPY conversion should succeed");
let converted = result.unwrap();
assert_eq!(converted.get_amount_as_string(), "12345");
// Test two decimal currency (USD)
let result = converter.convert(amount, Currency::USD);
assert!(result.is_ok(), "USD conversion should succeed");
let converted = result.unwrap();
assert_eq!(converted.get_amount_as_string(), "123.45");
// Test three decimal currency (BHD)
let result = converter.convert(amount, Currency::BHD);
assert!(result.is_ok(), "BHD conversion should succeed");
let converted = result.unwrap();
assert_eq!(converted.get_amount_as_string(), "12.345");
// Test four decimal currency (CLF)
let result = converter.convert(amount, Currency::CLF);
assert!(result.is_ok(), "CLF conversion should succeed");
let converted = result.unwrap();
assert_eq!(converted.get_amount_as_string(), "1.2345");
}
#[test]
fn test_currency_validation_errors_propagate() {
// This test verifies that if we had an unsupported currency,
// the error would propagate through the amount conversion system.
// Since all current currencies are supported, we'll test by verifying
// that the currency validation is being called.
let converter = StringMajorUnitForConnector;
let amount = MinorUnit::new(1000);
// Test that various currencies work
let currencies = vec![
Currency::USD,
Currency::EUR,
Currency::GBP,
Currency::JPY,
Currency::BHD,
Currency::CLF,
Currency::KRW,
Currency::VND,
];
let mut failed_currencies = Vec::new();
for currency in currencies {
let result = converter.convert(amount, currency);
if result.is_err() {
failed_currencies.push(currency);
}
}
assert!(
failed_currencies.is_empty(),
"The following currencies failed conversion: {failed_currencies:?}"
);
}
#[test]
fn test_amount_conversion_precision() {
let converter = StringMajorUnitForConnector;
// Test with different amounts to verify precision
let test_cases = vec![
(MinorUnit::new(1), Currency::USD, "0.01"),
(MinorUnit::new(100), Currency::USD, "1.00"),
(MinorUnit::new(12345), Currency::USD, "123.45"),
(MinorUnit::new(1), Currency::JPY, "1"),
(MinorUnit::new(1000), Currency::JPY, "1000"),
(MinorUnit::new(1234), Currency::BHD, "1.234"),
(MinorUnit::new(12345), Currency::BHD, "12.345"),
(MinorUnit::new(1234), Currency::CLF, "0.1234"),
(MinorUnit::new(12345), Currency::CLF, "1.2345"),
];
let mut failed_test_cases = Vec::new();
for (amount, currency, expected) in test_cases {
let result = converter.convert(amount, currency);
match result {
Ok(converted) => {
let actual = converted.get_amount_as_string();
if actual != expected {
failed_test_cases.push((amount, currency, expected, actual));
}
}
Err(_) => {
failed_test_cases.push((amount, currency, expected, "ERROR".to_string()));
}
}
}
assert!(
failed_test_cases.is_empty(),
"The following test cases failed: {failed_test_cases:?}"
);
}
}
|
{
"chunk": null,
"crate": "grpc-server",
"enum_name": null,
"file_size": 4177,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_grpc-server_-7945249832950166259
|
clm
|
small_file
|
// connector-service/backend/grpc-server/tests/mifinity_payment_flows_test.rs
#![allow(clippy::expect_used)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::panic)]
use grpc_server::{app, configs};
use hyperswitch_masking::{ExposeInterface, Secret};
mod common;
mod utils;
use std::time::{SystemTime, UNIX_EPOCH};
use grpc_api_types::{
health_check::{health_client::HealthClient, HealthCheckRequest},
payments::{
identifier::IdType, payment_method, payment_service_client::PaymentServiceClient,
wallet_payment_method_type, AuthenticationType, CaptureMethod, Currency, Identifier,
MifinityWallet, PaymentMethod, PaymentServiceAuthorizeRequest,
PaymentServiceAuthorizeResponse, PaymentServiceGetRequest, PaymentStatus,
WalletPaymentMethodType,
},
};
use tonic::{transport::Channel, Request};
// Helper function to get current timestamp
fn get_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
// Constants for Mifinity connector
const CONNECTOR_NAME: &str = "mifinity";
// Test card data
const TEST_AMOUNT: i64 = 1000;
const TEST_DESTINATION_ACCOUNT_NUMBER: &str = "5001000001223369"; // Valid test destination account number for Mifinity
const TEST_BRAND_ID: &str = "001";
const TEST_DATE_OF_BIRTH: &str = "2001-10-16";
const TEST_EMAIL: &str = "customer@example.com";
fn add_mifinity_metadata<T>(request: &mut Request<T>) {
let auth = utils::credential_utils::load_connector_auth(CONNECTOR_NAME)
.expect("Failed to load mifinity credentials");
let api_key = match auth {
domain_types::router_data::ConnectorAuthType::HeaderKey { api_key } => api_key.expose(),
_ => panic!("Expected HeaderKey auth type for mifinity"),
};
request.metadata_mut().append(
"x-connector",
CONNECTOR_NAME.parse().expect("Failed to parse x-connector"),
);
request.metadata_mut().append(
"x-auth",
"header-key".parse().expect("Failed to parse x-auth"),
);
request.metadata_mut().append(
"x-api-key",
api_key.parse().expect("Failed to parse x-api-key"),
);
// Add merchant ID which is required by the server
request.metadata_mut().append(
"x-merchant-id",
"12abc123-f8a3-99b8-9ef8-b31180358hh4"
.parse()
.expect("Failed to parse x-merchant-id"),
);
// Add tenant ID which is required by the server
request.metadata_mut().append(
"x-tenant-id",
"default".parse().expect("Failed to parse x-tenant-id"),
);
// Add request ID which is required by the server
request.metadata_mut().append(
"x-request-id",
format!("mifinity_req_{}", get_timestamp())
.parse()
.expect("Failed to parse x-request-id"),
);
}
// Helper function to extract connector transaction ID from response
fn extract_transaction_id(response: &PaymentServiceAuthorizeResponse) -> String {
match &response.transaction_id {
Some(id) => match id.id_type.as_ref().unwrap() {
IdType::Id(id) => id.clone(),
_ => panic!("Expected connector transaction ID"),
},
None => panic!("Resource ID is None"),
}
}
// Helper function to create a payment authorize request
fn create_authorize_request(capture_method: CaptureMethod) -> PaymentServiceAuthorizeRequest {
let wallet_details = wallet_payment_method_type::WalletType::Mifinity(MifinityWallet {
date_of_birth: Some(Secret::new(TEST_DATE_OF_BIRTH.to_string())),
language_preference: Some("en-US".to_string()),
});
// Create connector metadata JSON string
let connector_meta_data = format!(
"{{\"brand_id\":\"{TEST_BRAND_ID}\",\"destination_account_number\":\"{TEST_DESTINATION_ACCOUNT_NUMBER}\"}}"
);
PaymentServiceAuthorizeRequest {
amount: TEST_AMOUNT,
minor_amount: TEST_AMOUNT,
currency: i32::from(Currency::Eur),
payment_method: Some(PaymentMethod {
payment_method: Some(payment_method::PaymentMethod::Wallet(
WalletPaymentMethodType {
wallet_type: Some(wallet_details),
},
)),
}),
return_url: Some(
"https://hyperswitch.io/connector-service/authnet_webhook_grpcurl".to_string(),
),
email: Some(TEST_EMAIL.to_string().into()),
address: Some(grpc_api_types::payments::PaymentAddress {
shipping_address: Some(grpc_api_types::payments::Address::default()),
billing_address: Some(grpc_api_types::payments::Address {
first_name: Some("joseph".to_string().into()),
last_name: Some("Doe".to_string().into()),
phone_number: Some("8056594427".to_string().into()),
phone_country_code: Some("+91".to_string()),
email: Some("swangi@gmail.com".to_string().into()),
line1: Some("1467".to_string().into()),
line2: Some("Harrison Street".to_string().into()),
line3: Some("Harrison Street".to_string().into()),
city: Some("San Fransico".to_string().into()),
state: Some("California".to_string().into()),
zip_code: Some("94122".to_string().into()),
country_alpha2_code: Some(grpc_api_types::payments::CountryAlpha2::De.into()),
}),
}),
auth_type: i32::from(AuthenticationType::NoThreeDs),
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(format!("mifinity_test_{}", get_timestamp()))),
}),
customer_id: Some("Test_customer".to_string()),
enrolled_for_3ds: false,
request_incremental_authorization: false,
capture_method: Some(i32::from(capture_method)),
metadata: {
let mut metadata = std::collections::HashMap::new();
metadata.insert("connector_meta_data".to_string(), connector_meta_data);
metadata
},
// payment_method_type: Some(i32::from(PaymentMethodType::Credit)),
..Default::default()
}
}
// Helper function to create a payment sync request
fn create_payment_sync_request(transaction_id: &str) -> PaymentServiceGetRequest {
PaymentServiceGetRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
capture_method: None,
handle_response: None,
amount: TEST_AMOUNT,
currency: i32::from(Currency::Eur),
state: None,
}
}
// Test for basic health check
#[tokio::test]
async fn test_health() {
grpc_test!(client, HealthClient<Channel>, {
let response = client
.check(Request::new(HealthCheckRequest {
service: "connector_service".to_string(),
}))
.await
.expect("Failed to call health check")
.into_inner();
assert_eq!(
response.status(),
grpc_api_types::health_check::health_check_response::ServingStatus::Serving
);
});
}
// Test payment authorization with auto capture
#[tokio::test]
async fn test_payment_authorization_auto_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request
let request = create_authorize_request(CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_mifinity_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC authorize call failed")
.into_inner();
assert!(
response.status == i32::from(PaymentStatus::AuthenticationPending)
|| response.status == i32::from(PaymentStatus::Pending),
"Payment should be in AuthenticationPending or Pending state"
);
});
}
// Test payment sync with auto capture
#[tokio::test]
async fn test_payment_sync_auto_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Add delay of 2 seconds
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
// Create the payment authorization request
let request = create_authorize_request(CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_mifinity_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC authorize call failed")
.into_inner();
// Extract the transaction ID
let transaction_id = extract_transaction_id(&response);
// Create sync request
let sync_request = create_payment_sync_request(&transaction_id);
// Add metadata headers for sync request
let mut sync_grpc_request = Request::new(sync_request);
add_mifinity_metadata(&mut sync_grpc_request);
// Send the sync request
let sync_response = client
.get(sync_grpc_request)
.await
.expect("gRPC payment_sync call failed")
.into_inner();
// Verify the sync response
assert!(
sync_response.status == i32::from(PaymentStatus::AuthenticationPending)
|| sync_response.status == i32::from(PaymentStatus::Charged),
"Payment should be in AuthenticationPending or Charged state"
);
});
}
|
{
"chunk": null,
"crate": "grpc-server",
"enum_name": null,
"file_size": 9710,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_grpc-server_-7542628931815647432
|
clm
|
small_file
|
// connector-service/backend/grpc-server/tests/test_health.rs
#![allow(clippy::expect_used)]
use grpc_server::{app, configs};
mod common;
use grpc_api_types::health_check::{health_client::HealthClient, HealthCheckRequest};
use tonic::{transport::Channel, Request};
#[tokio::test]
async fn test_health() {
grpc_test!(client, HealthClient<Channel>, {
let response = client
.check(Request::new(HealthCheckRequest {
service: "connector_service".to_string(),
}))
.await
.expect("Failed to call health check")
.into_inner();
assert_eq!(
response.status(),
grpc_api_types::health_check::health_check_response::ServingStatus::Serving
);
});
}
|
{
"chunk": null,
"crate": "grpc-server",
"enum_name": null,
"file_size": 708,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_grpc-server_3949670969701485582
|
clm
|
small_file
|
// connector-service/backend/grpc-server/tests/cashtocode_payment_flows_test.rs
#![allow(clippy::expect_used)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::panic)]
use grpc_server::{app, configs};
mod common;
mod utils;
use std::time::{SystemTime, UNIX_EPOCH};
use grpc_api_types::{
health_check::{health_client::HealthClient, HealthCheckRequest},
payments::{
identifier::IdType, payment_method, payment_service_client::PaymentServiceClient,
AuthenticationType, CaptureMethod, Currency, Identifier, PaymentMethod,
PaymentServiceAuthorizeRequest, PaymentStatus, RewardPaymentMethodType, RewardType,
},
};
use tonic::{transport::Channel, Request};
// Helper function to get current timestamp
fn get_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
// Constants for Cashtocode connector
const CONNECTOR_NAME: &str = "cashtocode";
const AUTH_TYPE: &str = "currency-auth-key";
const MERCHANT_ID: &str = "merchant_1234";
const TEST_EMAIL: &str = "customer@example.com";
// Test data
const TEST_AMOUNT: i64 = 1000;
fn add_cashtocode_metadata<T>(request: &mut Request<T>) {
let auth = utils::credential_utils::load_connector_auth(CONNECTOR_NAME)
.expect("Failed to load cashtocode credentials");
let auth_key_map = match auth {
domain_types::router_data::ConnectorAuthType::CurrencyAuthKey { auth_key_map } => {
auth_key_map
}
_ => panic!("Expected CurrencyAuthKey auth type for cashtocode"),
};
// Serialize the auth_key_map to JSON for metadata
let auth_key_map_json =
serde_json::to_string(&auth_key_map).expect("Failed to serialize auth_key_map");
request.metadata_mut().append(
"x-connector",
CONNECTOR_NAME.parse().expect("Failed to parse x-connector"),
);
request
.metadata_mut()
.append("x-auth", AUTH_TYPE.parse().expect("Failed to parse x-auth"));
request.metadata_mut().append(
"x-auth-key-map",
auth_key_map_json
.parse()
.expect("Failed to parse x-auth-key-map"),
);
request.metadata_mut().append(
"x-merchant-id",
MERCHANT_ID.parse().expect("Failed to parse x-merchant-id"),
);
request.metadata_mut().append(
"x-request-id",
format!("test_request_{}", get_timestamp())
.parse()
.expect("Failed to parse x-request-id"),
);
}
// Helper function to create a payment authorize request
fn create_authorize_request(capture_method: CaptureMethod) -> PaymentServiceAuthorizeRequest {
PaymentServiceAuthorizeRequest {
amount: TEST_AMOUNT,
minor_amount: TEST_AMOUNT,
currency: i32::from(Currency::Eur),
payment_method: Some(PaymentMethod {
payment_method: Some(payment_method::PaymentMethod::Reward(
RewardPaymentMethodType {
reward_type: i32::from(RewardType::Classicreward),
},
)),
}),
customer_id: Some("cust_1233".to_string()),
return_url: Some("https://hyperswitch.io/connector-service".to_string()),
webhook_url: Some("https://hyperswitch.io/connector-service".to_string()),
email: Some(TEST_EMAIL.to_string().into()),
address: Some(grpc_api_types::payments::PaymentAddress::default()),
auth_type: i32::from(AuthenticationType::NoThreeDs),
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(format!("cashtocode_test_{}", get_timestamp()))),
}),
enrolled_for_3ds: false,
request_incremental_authorization: false,
capture_method: Some(i32::from(capture_method)),
..Default::default()
}
}
// Test for basic health check
#[tokio::test]
async fn test_health() {
grpc_test!(client, HealthClient<Channel>, {
let response = client
.check(Request::new(HealthCheckRequest {
service: "connector_service".to_string(),
}))
.await
.expect("Failed to call health check")
.into_inner();
assert_eq!(
response.status(),
grpc_api_types::health_check::health_check_response::ServingStatus::Serving
);
});
}
// Test payment authorization with auto capture
#[tokio::test]
async fn test_payment_authorization() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request
let request = create_authorize_request(CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_cashtocode_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC authorize call failed")
.into_inner();
assert!(
response.status == i32::from(PaymentStatus::AuthenticationPending),
"Payment should be in AuthenticationPending state"
);
});
}
|
{
"chunk": null,
"crate": "grpc-server",
"enum_name": null,
"file_size": 5038,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_grpc-server_1061119781833247450
|
clm
|
small_file
|
// connector-service/backend/grpc-server/tests/test_currency.rs
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::panic, clippy::print_stdout)]
mod tests {
use common_enums::{Currency, CurrencyError};
#[test]
fn test_zero_decimal_currencies() {
// Test currencies that should have 0 decimal places
assert_eq!(
Currency::JPY
.number_of_digits_after_decimal_point()
.unwrap(),
0
);
assert_eq!(
Currency::KRW
.number_of_digits_after_decimal_point()
.unwrap(),
0
);
assert_eq!(
Currency::VND
.number_of_digits_after_decimal_point()
.unwrap(),
0
);
assert_eq!(
Currency::BIF
.number_of_digits_after_decimal_point()
.unwrap(),
0
);
assert_eq!(
Currency::CLP
.number_of_digits_after_decimal_point()
.unwrap(),
0
);
}
#[test]
fn test_two_decimal_currencies() {
// Test currencies that should have 2 decimal places
assert_eq!(
Currency::USD
.number_of_digits_after_decimal_point()
.unwrap(),
2
);
assert_eq!(
Currency::EUR
.number_of_digits_after_decimal_point()
.unwrap(),
2
);
assert_eq!(
Currency::GBP
.number_of_digits_after_decimal_point()
.unwrap(),
2
);
assert_eq!(
Currency::CAD
.number_of_digits_after_decimal_point()
.unwrap(),
2
);
assert_eq!(
Currency::AUD
.number_of_digits_after_decimal_point()
.unwrap(),
2
);
}
#[test]
fn test_three_decimal_currencies() {
// Test currencies that should have 3 decimal places
assert_eq!(
Currency::BHD
.number_of_digits_after_decimal_point()
.unwrap(),
3
);
assert_eq!(
Currency::JOD
.number_of_digits_after_decimal_point()
.unwrap(),
3
);
assert_eq!(
Currency::KWD
.number_of_digits_after_decimal_point()
.unwrap(),
3
);
assert_eq!(
Currency::OMR
.number_of_digits_after_decimal_point()
.unwrap(),
3
);
assert_eq!(
Currency::TND
.number_of_digits_after_decimal_point()
.unwrap(),
3
);
}
#[test]
fn test_four_decimal_currencies() {
// Test currencies that should have 4 decimal places
assert_eq!(
Currency::CLF
.number_of_digits_after_decimal_point()
.unwrap(),
4
);
}
#[test]
fn test_currency_classification_completeness() {
// Test that all currencies in the enum are properly classified
let mut tested_currencies = 0;
let mut successful_classifications = 0;
// We'll iterate through some key currencies to verify they're all classified
let test_currencies = vec![
Currency::USD,
Currency::EUR,
Currency::GBP,
Currency::JPY,
Currency::KRW,
Currency::BHD,
Currency::JOD,
Currency::CLF,
Currency::CNY,
Currency::INR,
Currency::CAD,
Currency::AUD,
Currency::CHF,
Currency::SEK,
Currency::NOK,
Currency::DKK,
Currency::PLN,
Currency::CZK,
Currency::HUF,
Currency::RUB,
];
let mut failed_currencies = Vec::new();
for currency in test_currencies {
tested_currencies += 1;
match currency.number_of_digits_after_decimal_point() {
Ok(_) => successful_classifications += 1,
Err(_) => {
failed_currencies.push(currency);
println!("❌ Currency {currency:?} not properly classified");
}
}
}
// Fail the test if any currencies failed
assert!(
failed_currencies.is_empty(),
"The following currencies are not properly classified: {failed_currencies:?}"
);
println!("✅ Tested {tested_currencies} currencies, {successful_classifications} successful classifications");
assert_eq!(
tested_currencies, successful_classifications,
"All tested currencies should be properly classified"
);
}
#[test]
fn test_currency_error_message() {
// Since all current currencies should be classified, we can't easily test
// the error case without adding a fake currency. Instead, let's verify
// the error type exists and can be created
let error = CurrencyError::UnsupportedCurrency {
currency: "TEST".to_string(),
};
let error_string = format!("{error}");
assert!(error_string.contains("Unsupported currency: TEST"));
assert!(error_string.contains("Please add this currency to the supported currency list"));
}
#[test]
fn test_comprehensive_currency_coverage() {
// Test a representative sample from each classification
let currencies_to_test = vec![
// Zero decimal currencies
(Currency::BIF, 0),
(Currency::CLP, 0),
(Currency::DJF, 0),
(Currency::GNF, 0),
(Currency::JPY, 0),
(Currency::KMF, 0),
(Currency::KRW, 0),
(Currency::MGA, 0),
(Currency::PYG, 0),
(Currency::RWF, 0),
(Currency::UGX, 0),
(Currency::VND, 0),
(Currency::VUV, 0),
(Currency::XAF, 0),
(Currency::XOF, 0),
(Currency::XPF, 0),
// Three decimal currencies
(Currency::BHD, 3),
(Currency::JOD, 3),
(Currency::KWD, 3),
(Currency::OMR, 3),
(Currency::TND, 3),
// Four decimal currencies
(Currency::CLF, 4),
// Two decimal currencies (sample)
(Currency::USD, 2),
(Currency::EUR, 2),
(Currency::GBP, 2),
(Currency::AED, 2),
(Currency::AFN, 2),
(Currency::ALL, 2),
(Currency::AMD, 2),
(Currency::ANG, 2),
(Currency::AOA, 2),
];
for (currency, expected_decimals) in currencies_to_test {
match currency.number_of_digits_after_decimal_point() {
Ok(decimals) => {
assert_eq!(decimals, expected_decimals,
"Currency {currency:?} should have {expected_decimals} decimals, got {decimals}");
}
Err(e) => {
panic!("Currency {currency:?} should be classified but got error: {e}");
}
}
}
}
}
|
{
"chunk": null,
"crate": "grpc-server",
"enum_name": null,
"file_size": 7398,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_grpc-server_-4265129285553488760
|
clm
|
small_file
|
// connector-service/backend/grpc-server/tests/common.rs
use std::{future::Future, sync::Arc};
use grpc_api_types::{
health_check::health_client::HealthClient,
payments::{
payment_service_client::PaymentServiceClient, refund_service_client::RefundServiceClient,
},
};
use http::Uri;
use hyper_util::rt::TokioIo; // Add this import
use tempfile::NamedTempFile;
use tokio::net::UnixListener;
use tokio_stream::wrappers::UnixListenerStream;
use tonic::transport::{Channel, Endpoint, Server};
use tower::service_fn;
pub trait AutoClient {
fn new(channel: Channel) -> Self;
}
impl AutoClient for PaymentServiceClient<Channel> {
fn new(channel: Channel) -> Self {
Self::new(channel)
}
}
impl AutoClient for HealthClient<Channel> {
fn new(channel: Channel) -> Self {
Self::new(channel)
}
}
impl AutoClient for RefundServiceClient<Channel> {
fn new(channel: Channel) -> Self {
Self::new(channel)
}
}
/// # Panics
///
/// Will panic if the socket file cannot be created or removed
pub async fn server_and_client_stub<T>(
service: grpc_server::app::Service,
) -> Result<(impl Future<Output = ()>, T), Box<dyn std::error::Error>>
where
T: AutoClient,
{
let socket = NamedTempFile::new()?;
let socket = Arc::new(socket.into_temp_path());
std::fs::remove_file(&*socket)?;
let uds = UnixListener::bind(&*socket)?;
let stream = UnixListenerStream::new(uds);
let serve_future = async {
let result = Server::builder()
.add_service(
grpc_api_types::health_check::health_server::HealthServer::new(
service.health_check_service,
),
)
.add_service(
grpc_api_types::payments::payment_service_server::PaymentServiceServer::new(
service.payments_service,
),
)
.add_service(
grpc_api_types::payments::refund_service_server::RefundServiceServer::new(
service.refunds_service,
),
)
.serve_with_incoming(stream)
.await;
// Server must be running fine...
assert!(result.is_ok());
};
let socket = Arc::clone(&socket);
// Connect to the server over a Unix socket
// The URL will be ignored.
let channel = Endpoint::try_from("http://any.url")?
.connect_with_connector(service_fn(move |_: Uri| {
let socket = Arc::clone(&socket);
async move {
// Wrap the UnixStream with TokioIo to make it compatible with hyper
let unix_stream = tokio::net::UnixStream::connect(&*socket).await?;
Ok::<_, std::io::Error>(TokioIo::new(unix_stream))
}
}))
.await?;
let client = T::new(channel);
Ok((serve_future, client))
}
#[macro_export]
macro_rules! grpc_test {
($client:ident, $c_type:ty, $body:block) => {
let config = configs::Config::new().expect("Failed while parsing config");
let server = app::Service::new(std::sync::Arc::new(config)).await;
let (server_fut, mut $client) = common::server_and_client_stub::<$c_type>(server)
.await
.expect("Failed to create the server client pair");
let response = async { $body };
tokio::select! {
_ = server_fut => panic!("Server failed"),
_ = response => {}
}
};
}
|
{
"chunk": null,
"crate": "grpc-server",
"enum_name": null,
"file_size": 3434,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_grpc-server_-8391166333106684163
|
clm
|
small_file
|
// connector-service/backend/grpc-server/tests/utils/credential_utils.rs
//! Common credential loading utilities for test files
//!
//! This module provides a generic way to load connector credentials from
//! the JSON configuration file (.github/test/creds.json)
#![allow(dead_code)]
use common_enums::enums::Currency;
use common_utils::pii::SecretSerdeValue;
use domain_types::router_data::ConnectorAuthType;
use hyperswitch_masking::Secret;
use std::{collections::HashMap, fs};
// Path to the credentials file - use environment variable if set (for CI), otherwise use relative path (for local)
fn get_creds_file_path() -> String {
std::env::var("CONNECTOR_AUTH_FILE_PATH")
.unwrap_or_else(|_| "../../.github/test/creds.json".to_string())
}
/// Generic credential structure that can deserialize any connector's credentials
#[derive(serde::Deserialize, Debug, Clone)]
pub struct ConnectorAccountDetails {
pub auth_type: String,
#[serde(default)]
pub api_key: Option<String>,
#[serde(default)]
pub key1: Option<String>,
#[serde(default)]
pub api_secret: Option<String>,
#[serde(default)]
pub key2: Option<String>,
#[serde(default)]
pub certificate: Option<String>,
#[serde(default)]
pub private_key: Option<String>,
#[serde(default)]
pub auth_key_map: Option<HashMap<Currency, SecretSerdeValue>>,
}
#[derive(serde::Deserialize, Debug, Clone)]
pub struct ConnectorCredentials {
pub connector_account_details: ConnectorAccountDetails,
#[serde(default)]
pub metadata: Option<serde_json::Value>,
}
/// All connector credentials stored in the JSON file
pub type AllCredentials = HashMap<String, ConnectorCredentials>;
/// Error type for credential loading operations
#[derive(Debug, thiserror::Error)]
pub enum CredentialError {
#[error("Failed to read credentials file: {0}")]
FileReadError(#[from] std::io::Error),
#[error("Failed to parse credentials JSON: {0}")]
ParseError(#[from] serde_json::Error),
#[error("Connector '{0}' not found in credentials")]
ConnectorNotFound(String),
#[error("Invalid auth type '{0}' for connector '{1}'")]
InvalidAuthType(String, String),
#[error("Missing required field '{0}' for auth type '{1}'")]
MissingField(String, String),
#[error("Invalid structure for connector '{0}': {1}")]
InvalidStructure(String, String),
}
/// Load credentials for a specific connector from the JSON configuration file
///
/// # Arguments
/// * `connector_name` - Name of the connector (e.g., "aci", "authorizedotnet")
///
/// # Returns
/// * `ConnectorAuthType` - The loaded and converted credentials
///
/// # Examples
/// ```
/// // Load Authorize.Net credentials
/// let auth = load_connector_auth("authorizedotnet").unwrap();
/// ```
pub fn load_connector_auth(connector_name: &str) -> Result<ConnectorAuthType, CredentialError> {
load_from_json(connector_name)
}
/// Load metadata for a specific connector from the JSON configuration file
///
/// # Arguments
/// * `connector_name` - Name of the connector (e.g., "nexinets", "fiserv")
///
/// # Returns
/// * `HashMap<String, String>` - The metadata key-value pairs, or empty map if no metadata
///
/// # Examples
/// ```
/// // Load connector metadata (e.g., terminal_id, shop_name)
/// let metadata = load_connector_metadata("fiserv").unwrap();
/// let terminal_id = metadata.get("terminal_id");
/// ```
pub fn load_connector_metadata(
connector_name: &str,
) -> Result<HashMap<String, String>, CredentialError> {
let creds_file_path = get_creds_file_path();
let creds_content = fs::read_to_string(&creds_file_path)?;
let json_value: serde_json::Value = serde_json::from_str(&creds_content)?;
let all_credentials = match load_credentials_individually(&json_value) {
Ok(creds) => creds,
Err(_e) => {
// Try standard parsing as fallback
serde_json::from_value(json_value)?
}
};
let connector_creds = all_credentials
.get(connector_name)
.ok_or_else(|| CredentialError::ConnectorNotFound(connector_name.to_string()))?;
match &connector_creds.metadata {
Some(serde_json::Value::Object(map)) => {
let mut result = HashMap::new();
for (key, value) in map {
if let Some(string_val) = value.as_str() {
result.insert(key.clone(), string_val.to_string());
}
}
Ok(result)
}
_ => Ok(HashMap::new()),
}
}
/// Load credentials from JSON file
fn load_from_json(connector_name: &str) -> Result<ConnectorAuthType, CredentialError> {
let creds_file_path = get_creds_file_path();
let creds_content = fs::read_to_string(&creds_file_path)?;
let json_value: serde_json::Value = serde_json::from_str(&creds_content)?;
let all_credentials = match load_credentials_individually(&json_value) {
Ok(creds) => creds,
Err(_e) => {
// Try standard parsing as fallback
serde_json::from_value(json_value)?
}
};
let connector_creds = all_credentials
.get(connector_name)
.ok_or_else(|| CredentialError::ConnectorNotFound(connector_name.to_string()))?;
convert_to_auth_type(&connector_creds.connector_account_details, connector_name)
}
/// Load credentials by parsing each connector individually
fn load_credentials_individually(
json_value: &serde_json::Value,
) -> Result<AllCredentials, CredentialError> {
let mut all_credentials = HashMap::new();
let root_object = json_value.as_object().ok_or_else(|| {
CredentialError::InvalidStructure(
"root".to_string(),
"Expected JSON object at root".to_string(),
)
})?;
for (connector_name, connector_value) in root_object {
match parse_single_connector(connector_name, connector_value) {
Ok(creds) => {
all_credentials.insert(connector_name.clone(), creds);
}
Err(_e) => {
// Continue loading other connectors instead of failing completely
}
}
}
if all_credentials.is_empty() {
return Err(CredentialError::InvalidStructure(
"root".to_string(),
"No valid connectors found".to_string(),
));
}
Ok(all_credentials)
}
/// Parse a single connector's credentials
fn parse_single_connector(
connector_name: &str,
connector_value: &serde_json::Value,
) -> Result<ConnectorCredentials, CredentialError> {
let connector_obj = connector_value.as_object().ok_or_else(|| {
CredentialError::InvalidStructure(
connector_name.to_string(),
"Expected JSON object".to_string(),
)
})?;
// Check if this is a flat structure (has connector_account_details directly)
if connector_obj.contains_key("connector_account_details") {
// Flat structure: connector_name -> { connector_account_details: {...} }
return parse_connector_credentials(connector_name, connector_value);
}
// Nested structure: connector_name -> { connector_1: {...}, connector_2: {...} } eg. stripe
for (_sub_name, sub_value) in connector_obj.iter() {
if let Some(sub_obj) = sub_value.as_object() {
if sub_obj.contains_key("connector_account_details") {
return parse_connector_credentials(connector_name, sub_value);
}
}
}
// If we get here, no valid connector_account_details was found
Err(CredentialError::InvalidStructure(
connector_name.to_string(),
"No connector_account_details found in flat or nested structure".to_string(),
))
}
/// Parse connector credentials from JSON value
fn parse_connector_credentials(
connector_name: &str,
connector_value: &serde_json::Value,
) -> Result<ConnectorCredentials, CredentialError> {
let connector_obj = connector_value.as_object().ok_or_else(|| {
CredentialError::InvalidStructure(
connector_name.to_string(),
"Expected JSON object".to_string(),
)
})?;
let account_details_value =
connector_obj
.get("connector_account_details")
.ok_or_else(|| {
CredentialError::InvalidStructure(
connector_name.to_string(),
"Missing connector_account_details".to_string(),
)
})?;
let account_details = parse_connector_account_details(connector_name, account_details_value)?;
// Parse metadata if present
let metadata = connector_obj
.get("metadata")
.map(|v| serde_json::from_value(v.clone()))
.transpose()?;
Ok(ConnectorCredentials {
connector_account_details: account_details,
metadata,
})
}
/// Parse connector account details
fn parse_connector_account_details(
connector_name: &str,
value: &serde_json::Value,
) -> Result<ConnectorAccountDetails, CredentialError> {
let obj = value.as_object().ok_or_else(|| {
CredentialError::InvalidStructure(
connector_name.to_string(),
"connector_account_details must be an object".to_string(),
)
})?;
// Extract auth_type first
let auth_type = obj
.get("auth_type")
.and_then(|v| v.as_str())
.ok_or_else(|| {
CredentialError::InvalidStructure(
connector_name.to_string(),
"Missing or invalid auth_type".to_string(),
)
})?
.to_string();
// Handle different auth types with specific parsing logic
match auth_type.as_str() {
"CurrencyAuthKey" => {
// Special handling for CurrencyAuthKey which has complex nested structure
parse_currency_auth_key_details(connector_name, obj)
}
_ => {
// For other auth types, use standard serde parsing
serde_json::from_value(value.clone()).map_err(CredentialError::ParseError)
}
}
}
/// Special parsing logic for CurrencyAuthKey auth type
fn parse_currency_auth_key_details(
connector_name: &str,
obj: &serde_json::Map<String, serde_json::Value>,
) -> Result<ConnectorAccountDetails, CredentialError> {
let auth_key_map_value = obj.get("auth_key_map").ok_or_else(|| {
CredentialError::InvalidStructure(
connector_name.to_string(),
"Missing auth_key_map for CurrencyAuthKey".to_string(),
)
})?;
let auth_key_map_obj = auth_key_map_value.as_object().ok_or_else(|| {
CredentialError::InvalidStructure(
connector_name.to_string(),
"auth_key_map must be an object".to_string(),
)
})?;
let mut auth_key_map = HashMap::new();
for (currency_str, secret_value) in auth_key_map_obj {
let currency = currency_str.parse::<Currency>().map_err(|_| {
CredentialError::InvalidStructure(
connector_name.to_string(),
format!("Invalid currency: {}", currency_str),
)
})?;
let secret_serde_value = SecretSerdeValue::new(secret_value.clone());
auth_key_map.insert(currency, secret_serde_value);
}
Ok(ConnectorAccountDetails {
auth_type: "CurrencyAuthKey".to_string(),
api_key: None,
key1: None,
api_secret: None,
key2: None,
certificate: None,
private_key: None,
auth_key_map: Some(auth_key_map),
})
}
/// Convert generic credential details to specific ConnectorAuthType
fn convert_to_auth_type(
details: &ConnectorAccountDetails,
connector_name: &str,
) -> Result<ConnectorAuthType, CredentialError> {
match details.auth_type.as_str() {
"HeaderKey" => {
let api_key = details.api_key.as_ref().ok_or_else(|| {
CredentialError::MissingField("api_key".to_string(), "HeaderKey".to_string())
})?;
Ok(ConnectorAuthType::HeaderKey {
api_key: Secret::new(api_key.clone()),
})
}
"BodyKey" => {
let api_key = details.api_key.as_ref().ok_or_else(|| {
CredentialError::MissingField("api_key".to_string(), "BodyKey".to_string())
})?;
let key1 = details.key1.as_ref().ok_or_else(|| {
CredentialError::MissingField("key1".to_string(), "BodyKey".to_string())
})?;
Ok(ConnectorAuthType::BodyKey {
api_key: Secret::new(api_key.clone()),
key1: Secret::new(key1.clone()),
})
}
"SignatureKey" => {
let api_key = details.api_key.as_ref().ok_or_else(|| {
CredentialError::MissingField("api_key".to_string(), "SignatureKey".to_string())
})?;
let key1 = details.key1.as_ref().ok_or_else(|| {
CredentialError::MissingField("key1".to_string(), "SignatureKey".to_string())
})?;
let api_secret = details.api_secret.as_ref().ok_or_else(|| {
CredentialError::MissingField("api_secret".to_string(), "SignatureKey".to_string())
})?;
Ok(ConnectorAuthType::SignatureKey {
api_key: Secret::new(api_key.clone()),
key1: Secret::new(key1.clone()),
api_secret: Secret::new(api_secret.clone()),
})
}
"MultiAuthKey" => {
let api_key = details.api_key.as_ref().ok_or_else(|| {
CredentialError::MissingField("api_key".to_string(), "MultiAuthKey".to_string())
})?;
let key1 = details.key1.as_ref().ok_or_else(|| {
CredentialError::MissingField("key1".to_string(), "MultiAuthKey".to_string())
})?;
let api_secret = details.api_secret.as_ref().ok_or_else(|| {
CredentialError::MissingField("api_secret".to_string(), "MultiAuthKey".to_string())
})?;
let key2 = details.key2.as_ref().ok_or_else(|| {
CredentialError::MissingField("key2".to_string(), "MultiAuthKey".to_string())
})?;
Ok(ConnectorAuthType::MultiAuthKey {
api_key: Secret::new(api_key.clone()),
key1: Secret::new(key1.clone()),
api_secret: Secret::new(api_secret.clone()),
key2: Secret::new(key2.clone()),
})
}
"CurrencyAuthKey" => {
// For CurrencyAuthKey, we expect the auth_key_map field to contain the mapping
let auth_key_map = details.auth_key_map.as_ref().ok_or_else(|| {
CredentialError::MissingField(
"auth_key_map".to_string(),
"CurrencyAuthKey".to_string(),
)
})?;
Ok(ConnectorAuthType::CurrencyAuthKey {
auth_key_map: auth_key_map.clone(),
})
}
"CertificateAuth" => {
let certificate = details.certificate.as_ref().ok_or_else(|| {
CredentialError::MissingField(
"certificate".to_string(),
"CertificateAuth".to_string(),
)
})?;
let private_key = details.private_key.as_ref().ok_or_else(|| {
CredentialError::MissingField(
"private_key".to_string(),
"CertificateAuth".to_string(),
)
})?;
Ok(ConnectorAuthType::CertificateAuth {
certificate: Secret::new(certificate.clone()),
private_key: Secret::new(private_key.clone()),
})
}
"NoKey" => Ok(ConnectorAuthType::NoKey),
"TemporaryAuth" => Ok(ConnectorAuthType::TemporaryAuth),
_ => Err(CredentialError::InvalidAuthType(
details.auth_type.clone(),
connector_name.to_string(),
)),
}
}
|
{
"chunk": null,
"crate": "grpc-server",
"enum_name": null,
"file_size": 15968,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_grpc-server_93212607919302039
|
clm
|
small_file
|
// connector-service/backend/grpc-server/tests/utils/mod.rs
pub mod credential_utils;
|
{
"chunk": null,
"crate": "grpc-server",
"enum_name": null,
"file_size": 26,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_grpc-server_3819165835490215078
|
clm
|
small_file
|
// connector-service/backend/grpc-server/tests/beta_tests/cryptopay_payment_flows_test.rs
#![allow(clippy::expect_used)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::panic)]
use grpc_server::{app, configs};
mod common;
mod utils;
use grpc_api_types::{
health_check::{health_client::HealthClient, HealthCheckRequest},
payments::{
identifier::IdType, payment_method, payment_service_client::PaymentServiceClient,
AuthenticationType, CaptureMethod, CryptoCurrency, CryptoCurrencyPaymentMethodType,
Currency, Identifier, PaymentMethod, PaymentServiceAuthorizeRequest,
PaymentServiceAuthorizeResponse, PaymentServiceGetRequest, PaymentStatus,
},
};
use hyperswitch_masking::ExposeInterface;
use std::time::{SystemTime, UNIX_EPOCH};
use tonic::{transport::Channel, Request};
// Helper function to get current timestamp
fn get_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
// Constants for Cryptopay connector
const CONNECTOR_NAME: &str = "cryptopay";
const AUTH_TYPE: &str = "body-key";
const MERCHANT_ID: &str = "merchant_1234";
const TEST_EMAIL: &str = "customer@example.com";
// Test card data
const TEST_AMOUNT: i64 = 1000;
const TEST_PAY_CURRENCY: &str = "LTC";
const TEST_NETWORK: &str = "litecoin";
fn add_cryptopay_metadata<T>(request: &mut Request<T>) {
let auth = utils::credential_utils::load_connector_auth(CONNECTOR_NAME)
.expect("Failed to load cryptopay credentials");
let (api_key, key1) = match auth {
domain_types::router_data::ConnectorAuthType::BodyKey { api_key, key1 } => {
(api_key.expose(), key1.expose())
}
_ => panic!("Expected BodyKey auth type for cryptopay"),
};
request.metadata_mut().append(
"x-connector",
CONNECTOR_NAME.parse().expect("Failed to parse x-connector"),
);
request
.metadata_mut()
.append("x-auth", AUTH_TYPE.parse().expect("Failed to parse x-auth"));
request.metadata_mut().append(
"x-api-key",
api_key.parse().expect("Failed to parse x-api-key"),
);
request
.metadata_mut()
.append("x-key1", key1.parse().expect("Failed to parse x-key1"));
request.metadata_mut().append(
"x-merchant-id",
MERCHANT_ID.parse().expect("Failed to parse x-merchant-id"),
);
request.metadata_mut().append(
"x-request-id",
format!("test_request_{}", get_timestamp())
.parse()
.expect("Failed to parse x-request-id"),
);
}
// Helper function to extract connector transaction ID from response
fn extract_request_ref_id(response: &PaymentServiceAuthorizeResponse) -> String {
match &response.response_ref_id {
Some(id) => match id.id_type.as_ref().unwrap() {
IdType::Id(id) => id.clone(),
_ => panic!("Expected connector response_ref_id"),
},
None => panic!("Resource ID is None"),
}
}
// Helper function to create a payment authorize request
fn create_authorize_request(capture_method: CaptureMethod) -> PaymentServiceAuthorizeRequest {
PaymentServiceAuthorizeRequest {
amount: TEST_AMOUNT,
minor_amount: TEST_AMOUNT,
currency: i32::from(Currency::Usd),
payment_method: Some(PaymentMethod {
payment_method: Some(payment_method::PaymentMethod::Crypto(
CryptoCurrencyPaymentMethodType {
crypto_currency: Some(CryptoCurrency {
pay_currency: Some(TEST_PAY_CURRENCY.to_string()),
network: Some(TEST_NETWORK.to_string()),
}),
},
)),
}),
return_url: Some(
"https://hyperswitch.io/connector-service/authnet_webhook_grpcurl".to_string(),
),
webhook_url: Some(
"https://hyperswitch.io/connector-service/authnet_webhook_grpcurl".to_string(),
),
email: Some(TEST_EMAIL.to_string().into()),
address: Some(grpc_api_types::payments::PaymentAddress::default()),
auth_type: i32::from(AuthenticationType::NoThreeDs),
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(format!("cryptopay_test_{}", get_timestamp()))),
}),
enrolled_for_3ds: false,
request_incremental_authorization: false,
capture_method: Some(i32::from(capture_method)),
// payment_method_type: Some(i32::from(PaymentMethodType::Credit)),
..Default::default()
}
}
// Helper function to create a payment sync request
fn create_payment_sync_request(request_ref_id: &str) -> PaymentServiceGetRequest {
PaymentServiceGetRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id("not_required".to_string())),
}),
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(request_ref_id.to_string())),
}),
capture_method: None,
handle_response: None,
amount: TEST_AMOUNT,
currency: i32::from(Currency::Usd),
state: None,
}
}
// Test for basic health check
#[tokio::test]
async fn test_health() {
grpc_test!(client, HealthClient<Channel>, {
let response = client
.check(Request::new(HealthCheckRequest {
service: "connector_service".to_string(),
}))
.await
.expect("Failed to call health check")
.into_inner();
assert_eq!(
response.status(),
grpc_api_types::health_check::health_check_response::ServingStatus::Serving
);
});
}
// Test payment authorization with auto capture
#[tokio::test]
async fn test_payment_authorization_and_psync() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request
let request = create_authorize_request(CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_cryptopay_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC authorize call failed")
.into_inner();
// Add comprehensive logging for debugging
println!("=== CRYPTOPAY PAYMENT RESPONSE DEBUG ===");
println!("Response: {:#?}", response);
println!("Status: {}", response.status);
println!("Error code: {:?}", response.error_code);
println!("Error message: {:?}", response.error_message);
println!("Status code: {:?}", response.status_code);
println!("=== END DEBUG ===");
// Check for different possible statuses that Cryptopay might return
// Status 21 = Failure, which indicates auth/credential issues
if response.status == 21 {
// This is a failure status - likely auth/credential issues
assert_eq!(response.status, 21, "Expected failure status due to auth issues");
println!("Cryptopay authentication/credential issue detected - test expecting failure");
return; // Exit early since we can't proceed with sync test
}
let acceptable_statuses = [
i32::from(PaymentStatus::AuthenticationPending),
i32::from(PaymentStatus::Pending),
i32::from(PaymentStatus::Charged),
];
assert!(
acceptable_statuses.contains(&response.status),
"Payment should be in AuthenticationPending, Pending, or Charged state, but was: {}",
response.status
);
let request_ref_id = extract_request_ref_id(&response);
// Create sync request
let sync_request = create_payment_sync_request(&request_ref_id);
// Add metadata headers for sync request
let mut sync_grpc_request = Request::new(sync_request);
add_cryptopay_metadata(&mut sync_grpc_request);
// Send the sync request
let sync_response = client
.get(sync_grpc_request)
.await
.expect("gRPC payment_sync call failed")
.into_inner();
// Verify the sync response
assert!(
sync_response.status == i32::from(PaymentStatus::AuthenticationPending),
"Payment should be in AuthenticationPending state"
);
});
}
|
{
"chunk": null,
"crate": "grpc-server",
"enum_name": null,
"file_size": 8378,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_grpc-server_559727822511286263
|
clm
|
small_file
|
// connector-service/backend/grpc-server/tests/beta_tests/bluecode_payment_flows_test.rs
#![allow(clippy::expect_used)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::panic)]
use grpc_server::{app, configs};
mod common;
mod utils;
use std::{
collections::HashMap,
time::{SystemTime, UNIX_EPOCH},
};
use grpc_api_types::{
health_check::{health_client::HealthClient, HealthCheckRequest},
payments::{
identifier::IdType, payment_method, payment_service_client::PaymentServiceClient,
wallet_payment_method_type, Address, AuthenticationType, Bluecode, BrowserInformation,
CaptureMethod, CountryAlpha2, Identifier, PaymentAddress, PaymentMethod,
PaymentServiceAuthorizeRequest, PaymentServiceAuthorizeResponse, PaymentServiceGetRequest,
PaymentStatus, WalletPaymentMethodType,
},
};
use hyperswitch_masking::{ExposeInterface, Secret};
use rand::{distributions::Alphanumeric, Rng};
use tonic::{transport::Channel, Request};
// Constants for Bluecode connector
const CONNECTOR_NAME: &str = "bluecode";
// Test card data
const TEST_AMOUNT: i64 = 1000;
// Helper function to get current timestamp
fn get_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
// Helper function to add Bluecode metadata headers to a request
fn add_bluecode_metadata<T>(request: &mut Request<T>) {
let auth = utils::credential_utils::load_connector_auth(CONNECTOR_NAME)
.expect("Failed to load bluecode credentials");
let api_key = match auth {
domain_types::router_data::ConnectorAuthType::HeaderKey { api_key } => api_key.expose(),
_ => panic!("Expected HeaderKey auth type for bluecode"),
};
// Get the shop_name from metadata
let metadata = utils::credential_utils::load_connector_metadata(CONNECTOR_NAME)
.expect("Failed to load bluecode metadata");
let shop_name = metadata
.get("shop_name")
.expect("shop_name not found in bluecode metadata")
.clone();
request.metadata_mut().append(
"x-connector",
CONNECTOR_NAME.parse().expect("Failed to parse x-connector"),
);
request.metadata_mut().append(
"x-auth",
"header-key".parse().expect("Failed to parse x-auth"),
);
request.metadata_mut().append(
"x-api-key",
api_key.parse().expect("Failed to parse x-api-key"),
);
// Add the terminal_id in the metadata JSON
// This metadata must be in the proper format that the connector expects
let metadata_json = format!(r#"{{"shop_name":"{shop_name}"}}"#);
request.metadata_mut().append(
"x-metadata",
metadata_json.parse().expect("Failed to parse x-metadata"),
);
request.metadata_mut().append(
"x-tenant-id",
"default".parse().expect("Failed to parse x-tenant-id"),
);
// Add request ID which is required by the server
request.metadata_mut().append(
"x-request-id",
format!("mifinity_req_{}", get_timestamp())
.parse()
.expect("Failed to parse x-request-id"),
);
request.metadata_mut().append(
"x-merchant-id",
"12abc123-f8a3-99b8-9ef8-b31180358hh4"
.parse()
.expect("Failed to parse x-merchant-id"),
);
}
// Helper function to extract connector transaction ID from response
fn extract_transaction_id(response: &PaymentServiceAuthorizeResponse) -> String {
match &response.transaction_id {
Some(id) => match id.id_type.as_ref().unwrap() {
IdType::Id(id) => id.clone(),
_ => panic!("Expected connector transaction ID"),
},
None => panic!("Resource ID is None"),
}
}
// Helper function to generate unique request reference ID
fn generate_unique_request_ref_id(prefix: &str) -> String {
format!(
"{}_{}",
prefix,
&uuid::Uuid::new_v4().simple().to_string()[..8]
)
}
// Helper function to generate unique email
fn generate_unique_email() -> String {
format!("testcustomer{}@gmail.com", get_timestamp())
}
// Function to generate random name
fn random_name() -> String {
rand::thread_rng()
.sample_iter(&Alphanumeric)
.take(8)
.map(char::from)
.collect()
}
// Helper function to create a payment authorization request
#[allow(clippy::field_reassign_with_default)]
fn create_payment_authorize_request(
capture_method: common_enums::CaptureMethod,
) -> PaymentServiceAuthorizeRequest {
// Initialize with all required fields
let mut request = PaymentServiceAuthorizeRequest {
payment_method: Some(PaymentMethod {
payment_method: Some(payment_method::PaymentMethod::Wallet(
WalletPaymentMethodType {
wallet_type: Some(wallet_payment_method_type::WalletType::Bluecode(
Bluecode {},
)),
},
)),
}),
..Default::default()
};
if let common_enums::CaptureMethod::Manual = capture_method {
request.capture_method = Some(i32::from(CaptureMethod::Manual));
// request.request_incremental_authorization = true;
} else {
request.capture_method = Some(i32::from(CaptureMethod::Automatic));
}
let mut request_ref_id = Identifier::default();
request_ref_id.id_type = Some(IdType::Id(
generate_unique_request_ref_id("req_"), // Using timestamp to make unique
));
request.request_ref_id = Some(request_ref_id);
// Set the basic payment details matching working grpcurl
request.amount = TEST_AMOUNT;
request.minor_amount = TEST_AMOUNT;
request.currency = 146; // Currency value from working grpcurl
request.email = Some(Secret::new(generate_unique_email()));
// Generate random names for billing to prevent duplicate transaction errors
let billing_first_name = random_name();
let billing_last_name = random_name();
// Minimal address structure matching working grpcurl
request.address = Some(PaymentAddress {
billing_address: Some(Address {
first_name: Some(Secret::new(billing_first_name)),
last_name: Some(Secret::new(billing_last_name)),
line1: Some(Secret::new("14 Main Street".to_string())),
line2: None,
line3: None,
city: Some(Secret::new("Pecan Springs".to_string())),
state: Some(Secret::new("TX".to_string())),
zip_code: Some(Secret::new("44628".to_string())),
country_alpha2_code: Some(i32::from(CountryAlpha2::Us)),
phone_number: None,
phone_country_code: None,
email: None,
}),
shipping_address: None, // Minimal address - no shipping for working grpcurl
});
let browser_info = BrowserInformation {
color_depth: None,
java_enabled: Some(false),
screen_height: Some(1080),
screen_width: Some(1920),
user_agent: Some("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)".to_string()),
accept_header: Some(
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8".to_string(),
),
java_script_enabled: Some(false),
language: Some("en-US".to_string()),
ip_address: None,
os_type: None,
os_version: None,
device_model: None,
accept_language: None,
time_zone_offset_minutes: None,
referer: None,
};
request.browser_info = Some(browser_info);
request.return_url = Some("www.google.com".to_string());
// Set the transaction details
request.auth_type = i32::from(AuthenticationType::NoThreeDs);
request.request_incremental_authorization = true;
request.enrolled_for_3ds = true;
// Set capture method
// request.capture_method = Some(i32::from(CaptureMethod::from(capture_method)));
// Get shop_name for metadata
let metadata = utils::credential_utils::load_connector_metadata(CONNECTOR_NAME)
.expect("Failed to load bluecode metadata");
let shop_name = metadata
.get("shop_name")
.expect("shop_name not found in bluecode metadata")
.clone();
// Create connector metadata as a proper JSON object
let mut connector_metadata = HashMap::new();
connector_metadata.insert("shop_name".to_string(), shop_name);
let connector_metadata_json =
serde_json::to_string(&connector_metadata).expect("Failed to serialize connector metadata");
let mut metadata = HashMap::new();
metadata.insert("connector_meta_data".to_string(), connector_metadata_json);
request.metadata = metadata;
request
}
// Helper function to create a payment sync request
fn create_payment_sync_request(transaction_id: &str) -> PaymentServiceGetRequest {
PaymentServiceGetRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(format!("fiserv_sync_{}", get_timestamp()))),
}),
capture_method: None,
handle_response: None,
// all_keys_required: None,
amount: TEST_AMOUNT,
currency: 146, // Currency value from working grpcurl
state: None,
}
}
// Test for basic health check
#[tokio::test]
async fn test_health() {
grpc_test!(client, HealthClient<Channel>, {
let response = client
.check(Request::new(HealthCheckRequest {
service: "connector_service".to_string(),
}))
.await
.expect("Failed to call health check")
.into_inner();
assert_eq!(
response.status(),
grpc_api_types::health_check::health_check_response::ServingStatus::Serving
);
});
}
// Test payment authorization with auto capture
#[tokio::test]
async fn test_payment_authorization_auto_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request
let request = create_payment_authorize_request(common_enums::CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_bluecode_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
// Debug print has been removed
// Verify the response
assert!(
response.transaction_id.is_some(),
"Resource ID should be present"
);
// Extract the transaction ID
let _transaction_id = extract_transaction_id(&response);
// Verify payment status
assert!(
response.status == i32::from(PaymentStatus::AuthenticationPending),
"Payment should be in AuthenticationPending state"
);
});
}
// Test payment sync
#[tokio::test]
async fn test_payment_sync() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// First create a payment to sync
let auth_request = create_payment_authorize_request(common_enums::CaptureMethod::Manual);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_bluecode_metadata(&mut auth_grpc_request);
// Send the auth request
let auth_response = client
.authorize(auth_grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
// Extract the transaction ID
let transaction_id = extract_transaction_id(&auth_response);
// Create sync request
let sync_request = create_payment_sync_request(&transaction_id);
// Add metadata headers for sync request
let mut sync_grpc_request = Request::new(sync_request);
add_bluecode_metadata(&mut sync_grpc_request);
// Send the sync request
let sync_response = client
.get(sync_grpc_request)
.await
.expect("gRPC payment_sync call failed")
.into_inner();
// Verify the sync response
assert!(
sync_response.status == i32::from(PaymentStatus::AuthenticationPending),
"Payment should be in AuthenticationPending state"
);
});
}
|
{
"chunk": null,
"crate": "grpc-server",
"enum_name": null,
"file_size": 12437,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_grpc-server_5381403527828220498
|
clm
|
small_file
|
// connector-service/backend/grpc-server/src/request.rs
use std::sync::Arc;
use common_utils::metadata::MaskedMetadata;
use crate::{
configs,
error::ResultExtGrpc,
utils::{get_metadata_payload, MetadataPayload},
};
/// Structured request data with secure metadata access.
#[derive(Debug)]
pub struct RequestData<T> {
pub payload: T,
pub extracted_metadata: MetadataPayload,
pub masked_metadata: MaskedMetadata, // all metadata with masking config
pub extensions: tonic::Extensions,
}
impl<T> RequestData<T> {
#[allow(clippy::result_large_err)]
pub fn from_grpc_request(
request: tonic::Request<T>,
config: Arc<configs::Config>,
) -> Result<Self, tonic::Status> {
let (metadata, extensions, payload) = request.into_parts();
// Construct MetadataPayload from raw metadata (existing functions need it)
let metadata_payload =
get_metadata_payload(&metadata, config.clone()).into_grpc_status()?;
// Pass tonic metadata and config to MaskedMetadata
let masked_metadata = MaskedMetadata::new(metadata, config.unmasked_headers.clone());
Ok(Self {
payload,
extracted_metadata: metadata_payload,
masked_metadata,
extensions,
})
}
}
|
{
"chunk": null,
"crate": "grpc-server",
"enum_name": null,
"file_size": 1249,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_grpc-server_1253602369638970611
|
clm
|
small_file
|
// connector-service/backend/grpc-server/src/logger.rs
pub mod config;
pub mod setup;
pub use setup::setup;
pub mod env;
pub use tracing::{debug, error, event as log, info, warn};
pub use tracing_attributes::instrument;
|
{
"chunk": null,
"crate": "grpc-server",
"enum_name": null,
"file_size": 168,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_grpc-server_-2425448326891067086
|
clm
|
small_file
|
// connector-service/backend/grpc-server/src/error.rs
use domain_types::errors::{ApiClientError, ApiError, ApplicationErrorResponse, ConnectorError};
use grpc_api_types::payments::PaymentServiceAuthorizeResponse;
use tonic::Status;
use crate::logger;
/// Allows [error_stack::Report] to change between error contexts
/// using the dependent [ErrorSwitch] trait to define relations & mappings between traits
pub trait ReportSwitchExt<T, U> {
/// Switch to the intended report by calling switch
/// requires error switch to be already implemented on the error type
fn switch(self) -> Result<T, error_stack::Report<U>>;
}
impl<T, U, V> ReportSwitchExt<T, U> for Result<T, error_stack::Report<V>>
where
V: ErrorSwitch<U> + error_stack::Context,
U: error_stack::Context,
{
#[track_caller]
fn switch(self) -> Result<T, error_stack::Report<U>> {
match self {
Ok(i) => Ok(i),
Err(er) => {
let new_c = er.current_context().switch();
Err(er.change_context(new_c))
}
}
}
}
/// Allow [error_stack::Report] to convert between error types
/// This auto-implements [ReportSwitchExt] for the corresponding errors
pub trait ErrorSwitch<T> {
/// Get the next error type that the source error can be escalated into
/// This does not consume the source error since we need to keep it in context
fn switch(&self) -> T;
}
/// Allow [error_stack::Report] to convert between error types
/// This serves as an alternative to [ErrorSwitch]
pub trait ErrorSwitchFrom<T> {
/// Convert to an error type that the source can be escalated into
/// This does not consume the source error since we need to keep it in context
fn switch_from(error: &T) -> Self;
}
impl<T, S> ErrorSwitch<T> for S
where
T: ErrorSwitchFrom<Self>,
{
fn switch(&self) -> T {
T::switch_from(self)
}
}
pub trait IntoGrpcStatus {
fn into_grpc_status(self) -> Status;
}
pub trait ResultExtGrpc<T> {
#[allow(clippy::result_large_err)]
fn into_grpc_status(self) -> Result<T, Status>;
}
impl<T, E> ResultExtGrpc<T> for error_stack::Result<T, E>
where
error_stack::Report<E>: IntoGrpcStatus,
{
fn into_grpc_status(self) -> Result<T, Status> {
match self {
Ok(x) => Ok(x),
Err(err) => Err(err.into_grpc_status()),
}
}
}
#[derive(Debug, thiserror::Error)]
pub enum ConfigurationError {
#[error("Invalid host for socket: {0}")]
AddressError(#[from] std::net::AddrParseError),
#[error("Failed while building grpc reflection service: {0}")]
GrpcReflectionServiceError(#[from] tonic_reflection::server::Error),
#[error("Error while creating metrics server")]
MetricsServerError,
#[error("Error while creating the server: {0}")]
ServerError(#[from] tonic::transport::Error),
#[error("IO error: {0}")]
IoError(#[from] std::io::Error),
}
impl ErrorSwitch<ApplicationErrorResponse> for ConnectorError {
fn switch(&self) -> ApplicationErrorResponse {
match self {
Self::FailedToObtainIntegrationUrl
| Self::FailedToObtainPreferredConnector
| Self::FailedToObtainAuthType
| Self::FailedToObtainCertificate
| Self::FailedToObtainCertificateKey
| Self::RequestEncodingFailed
| Self::RequestEncodingFailedWithReason(_)
| Self::ParsingFailed
| Self::ResponseDeserializationFailed
| Self::ResponseHandlingFailed
| Self::WebhookResponseEncodingFailed
| Self::ProcessingStepFailed(_)
| Self::UnexpectedResponseError(_)
| Self::RoutingRulesParsingError
| Self::FailedAtConnector { .. }
| Self::AmountConversionFailed
| Self::GenericError { .. }
| Self::MandatePaymentDataMismatch { .. } => {
ApplicationErrorResponse::InternalServerError(ApiError {
sub_code: "INTERNAL_SERVER_ERROR".to_string(),
error_identifier: 500,
error_message: self.to_string(),
error_object: None,
})
}
Self::InvalidConnectorName
| Self::InvalidWallet
| Self::MissingRequiredField { .. }
| Self::MissingRequiredFields { .. }
| Self::InvalidDateFormat
| Self::NotSupported { .. }
| Self::FlowNotSupported { .. }
| Self::DateFormattingFailed
| Self::InvalidDataFormat { .. }
| Self::MismatchedPaymentData
| Self::InvalidWalletToken { .. }
| Self::FileValidationFailed { .. }
| Self::MissingConnectorRedirectionPayload { .. }
| Self::MissingPaymentMethodType
| Self::CurrencyNotSupported { .. }
| Self::NoConnectorWalletDetails
| Self::MissingConnectorMandateMetadata
| Self::IntegrityCheckFailed { .. }
| Self::SourceVerificationFailed
| Self::InvalidConnectorConfig { .. } => {
ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "BAD_REQUEST".to_string(),
error_identifier: 400,
error_message: self.to_string(),
error_object: None,
})
}
Self::NoConnectorMetaData
| Self::MissingConnectorMandateID
| Self::MissingConnectorTransactionID
| Self::MissingConnectorRefundID
| Self::MissingConnectorRelatedTransactionID { .. }
| Self::InSufficientBalanceInPaymentMethod => {
ApplicationErrorResponse::Unprocessable(ApiError {
sub_code: "UNPROCESSABLE_ENTITY".to_string(),
error_identifier: 422,
error_message: self.to_string(),
error_object: None,
})
}
Self::NotImplemented(_)
| Self::CaptureMethodNotSupported
| Self::WebhooksNotImplemented => ApplicationErrorResponse::NotImplemented(ApiError {
sub_code: "NOT_IMPLEMENTED".to_string(),
error_identifier: 501,
error_message: self.to_string(),
error_object: None,
}),
Self::MissingApplePayTokenData
| Self::WebhookBodyDecodingFailed
| Self::WebhookSourceVerificationFailed
| Self::WebhookVerificationSecretInvalid => {
ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "INVALID_WEBHOOK_DATA".to_string(),
error_identifier: 400,
error_message: self.to_string(),
error_object: None,
})
}
Self::RequestTimeoutReceived => {
ApplicationErrorResponse::InternalServerError(ApiError {
sub_code: "REQUEST_TIMEOUT".to_string(),
error_identifier: 504,
error_message: self.to_string(),
error_object: None,
})
}
Self::WebhookEventTypeNotFound
| Self::WebhookSignatureNotFound
| Self::WebhookReferenceIdNotFound
| Self::WebhookResourceObjectNotFound
| Self::WebhookVerificationSecretNotFound => {
ApplicationErrorResponse::NotFound(ApiError {
sub_code: "WEBHOOK_DETAILS_NOT_FOUND".to_string(),
error_identifier: 404,
error_message: self.to_string(),
error_object: None,
})
}
}
}
}
impl ErrorSwitch<ApplicationErrorResponse> for ApiClientError {
fn switch(&self) -> ApplicationErrorResponse {
match self {
Self::HeaderMapConstructionFailed
| Self::InvalidProxyConfiguration
| Self::ClientConstructionFailed
| Self::CertificateDecodeFailed
| Self::BodySerializationFailed
| Self::UnexpectedState
| Self::UrlEncodingFailed
| Self::RequestNotSent(_)
| Self::ResponseDecodingFailed
| Self::InternalServerErrorReceived
| Self::BadGatewayReceived
| Self::ServiceUnavailableReceived
| Self::UrlParsingFailed
| Self::UnexpectedServerResponse => {
ApplicationErrorResponse::InternalServerError(ApiError {
sub_code: "INTERNAL_SERVER_ERROR".to_string(),
error_identifier: 500,
error_message: self.to_string(),
error_object: None,
})
}
Self::RequestTimeoutReceived | Self::GatewayTimeoutReceived => {
ApplicationErrorResponse::InternalServerError(ApiError {
sub_code: "REQUEST_TIMEOUT".to_string(),
error_identifier: 504,
error_message: self.to_string(),
error_object: None,
})
}
Self::ConnectionClosedIncompleteMessage => {
ApplicationErrorResponse::InternalServerError(ApiError {
sub_code: "INTERNAL_SERVER_ERROR".to_string(),
error_identifier: 500,
error_message: self.to_string(),
error_object: None,
})
}
}
}
}
impl IntoGrpcStatus for error_stack::Report<ApplicationErrorResponse> {
fn into_grpc_status(self) -> Status {
logger::error!(error=?self);
match self.current_context() {
ApplicationErrorResponse::Unauthorized(api_error) => {
Status::unauthenticated(&api_error.error_message)
}
ApplicationErrorResponse::ForbiddenCommonResource(api_error)
| ApplicationErrorResponse::ForbiddenPrivateResource(api_error) => {
Status::permission_denied(&api_error.error_message)
}
ApplicationErrorResponse::Conflict(api_error)
| ApplicationErrorResponse::Gone(api_error)
| ApplicationErrorResponse::Unprocessable(api_error)
| ApplicationErrorResponse::InternalServerError(api_error)
| ApplicationErrorResponse::MethodNotAllowed(api_error)
| ApplicationErrorResponse::DomainError(api_error) => {
Status::internal(&api_error.error_message)
}
ApplicationErrorResponse::NotImplemented(api_error) => {
Status::unimplemented(&api_error.error_message)
}
ApplicationErrorResponse::NotFound(api_error) => {
Status::not_found(&api_error.error_message)
}
ApplicationErrorResponse::BadRequest(api_error) => {
Status::invalid_argument(&api_error.error_message)
}
}
}
}
#[derive(Debug, Clone)]
pub struct PaymentAuthorizationError {
pub status: grpc_api_types::payments::PaymentStatus,
pub error_message: Option<String>,
pub error_code: Option<String>,
pub status_code: Option<u32>,
}
impl PaymentAuthorizationError {
pub fn new(
status: grpc_api_types::payments::PaymentStatus,
error_message: Option<String>,
error_code: Option<String>,
status_code: Option<u32>,
) -> Self {
Self {
status,
error_message,
error_code,
status_code,
}
}
}
impl From<PaymentAuthorizationError> for PaymentServiceAuthorizeResponse {
fn from(error: PaymentAuthorizationError) -> Self {
Self {
transaction_id: None,
redirection_data: None,
network_txn_id: None,
response_ref_id: None,
incremental_authorization_allowed: None,
status: error.status.into(),
error_message: error.error_message,
error_code: error.error_code,
status_code: error.status_code.unwrap_or(500),
response_headers: std::collections::HashMap::new(),
connector_metadata: std::collections::HashMap::new(),
raw_connector_response: None,
raw_connector_request: None,
state: None,
mandate_reference: None,
minor_amount_capturable: None,
minor_captured_amount: None,
captured_amount: None,
connector_response: None,
}
}
}
|
{
"chunk": null,
"crate": "grpc-server",
"enum_name": null,
"file_size": 12625,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_grpc-server_8674746398584233230
|
clm
|
small_file
|
// connector-service/backend/grpc-server/src/configs.rs
use std::path::PathBuf;
use common_utils::{consts, events::EventConfig, metadata::HeaderMaskingConfig};
use domain_types::types::{Connectors, Proxy};
use crate::{error::ConfigurationError, logger::config::Log};
#[derive(Clone, serde::Deserialize, Debug)]
pub struct Config {
pub common: Common,
pub server: Server,
pub metrics: MetricsServer,
pub log: Log,
pub proxy: Proxy,
pub connectors: Connectors,
#[serde(default)]
pub events: EventConfig,
#[serde(default)]
pub lineage: LineageConfig,
#[serde(default)]
pub unmasked_headers: HeaderMaskingConfig,
}
#[derive(Clone, serde::Deserialize, Debug, Default)]
pub struct LineageConfig {
/// Enable processing of x-lineage-ids header
pub enabled: bool,
/// Custom header name (default: x-lineage-ids)
#[serde(default = "default_lineage_header")]
pub header_name: String,
/// Prefix for lineage fields in events
#[serde(default = "default_lineage_prefix")]
pub field_prefix: String,
}
fn default_lineage_header() -> String {
consts::X_LINEAGE_IDS.to_string()
}
fn default_lineage_prefix() -> String {
consts::LINEAGE_FIELD_PREFIX.to_string()
}
#[derive(Clone, serde::Deserialize, Debug)]
pub struct Common {
pub environment: consts::Env,
}
impl Common {
pub fn validate(&self) -> Result<(), config::ConfigError> {
let Self { environment } = self;
match environment {
consts::Env::Development | consts::Env::Production | consts::Env::Sandbox => Ok(()),
}
}
}
#[derive(Clone, serde::Deserialize, Debug)]
pub struct Server {
pub host: String,
pub port: u16,
#[serde(rename = "type", default)]
pub type_: ServiceType,
}
#[derive(Clone, serde::Deserialize, Debug)]
pub struct MetricsServer {
pub host: String,
pub port: u16,
}
#[derive(Clone, serde::Deserialize, Debug, Default)]
#[serde(rename_all = "snake_case")]
pub enum ServiceType {
#[default]
Grpc,
Http,
}
impl Config {
/// Function to build the configuration by picking it from default locations
pub fn new() -> Result<Self, config::ConfigError> {
Self::new_with_config_path(None)
}
/// Function to build the configuration by picking it from default locations
pub fn new_with_config_path(
explicit_config_path: Option<PathBuf>,
) -> Result<Self, config::ConfigError> {
let env = consts::Env::current_env();
let config_path = Self::config_path(&env, explicit_config_path);
let config = Self::builder(&env)?
.add_source(config::File::from(config_path).required(false))
.add_source(
config::Environment::with_prefix(consts::ENV_PREFIX)
.try_parsing(true)
.separator("__")
.list_separator(",")
.with_list_parse_key("proxy.bypass_proxy_urls")
.with_list_parse_key("redis.cluster_urls")
.with_list_parse_key("database.tenants")
.with_list_parse_key("log.kafka.brokers")
.with_list_parse_key("events.brokers")
.with_list_parse_key("unmasked_headers.keys"),
)
.build()?;
#[allow(clippy::print_stderr)]
let config: Self = serde_path_to_error::deserialize(config).map_err(|error| {
eprintln!("Unable to deserialize application configuration: {error}");
error.into_inner()
})?;
// Validate the environment field
config.common.validate()?;
Ok(config)
}
pub fn builder(
environment: &consts::Env,
) -> Result<config::ConfigBuilder<config::builder::DefaultState>, config::ConfigError> {
config::Config::builder()
// Here, it should be `set_override()` not `set_default()`.
// "env" can't be altered by config field.
// Should be single source of truth.
.set_override("env", environment.to_string())
}
/// Config path.
pub fn config_path(
environment: &consts::Env,
explicit_config_path: Option<PathBuf>,
) -> PathBuf {
let mut config_path = PathBuf::new();
if let Some(explicit_config_path_val) = explicit_config_path {
config_path.push(explicit_config_path_val);
} else {
let config_directory: String = "config".into();
let config_file_name = environment.config_path();
config_path.push(workspace_path());
config_path.push(config_directory);
config_path.push(config_file_name);
}
config_path
}
}
impl Server {
pub async fn tcp_listener(&self) -> Result<tokio::net::TcpListener, ConfigurationError> {
let loc = format!("{}:{}", self.host, self.port);
tracing::info!(loc = %loc, "binding the server");
Ok(tokio::net::TcpListener::bind(loc).await?)
}
}
impl MetricsServer {
pub async fn tcp_listener(&self) -> Result<tokio::net::TcpListener, ConfigurationError> {
let loc = format!("{}:{}", self.host, self.port);
tracing::info!(loc = %loc, "binding the server");
Ok(tokio::net::TcpListener::bind(loc).await?)
}
}
pub fn workspace_path() -> PathBuf {
if let Ok(manifest_dir) = std::env::var("CARGO_MANIFEST_DIR") {
let mut path = PathBuf::from(manifest_dir);
path.pop();
path.pop();
path
} else {
PathBuf::from(".")
}
}
|
{
"chunk": null,
"crate": "grpc-server",
"enum_name": null,
"file_size": 5523,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_grpc-server_301775486885011865
|
clm
|
small_file
|
// connector-service/backend/grpc-server/src/lib.rs
pub mod app;
pub mod configs;
pub mod error;
pub mod logger;
pub mod metrics;
pub mod request;
pub mod server;
pub mod utils;
|
{
"chunk": null,
"crate": "grpc-server",
"enum_name": null,
"file_size": 126,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_grpc-server_-5878268656114972348
|
clm
|
small_file
|
// connector-service/backend/grpc-server/src/server.rs
pub mod disputes;
pub mod health_check;
pub mod payments;
pub mod refunds;
|
{
"chunk": null,
"crate": "grpc-server",
"enum_name": null,
"file_size": 75,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_grpc-server_4855222776862835635
|
clm
|
small_file
|
// connector-service/backend/grpc-server/src/metrics.rs
|
{
"chunk": null,
"crate": "grpc-server",
"enum_name": null,
"file_size": 1,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_grpc-server_-1708118210077285516
|
clm
|
small_file
|
// connector-service/backend/grpc-server/src/main.rs
use grpc_server::{self, app, configs, logger};
#[allow(clippy::unwrap_in_result)]
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
#[cfg(debug_assertions)]
verify_other_config_files();
#[allow(clippy::expect_used)]
let config = configs::Config::new().expect("Failed while parsing config");
let _guard = logger::setup(
&config.log,
grpc_server::service_name!(),
[grpc_server::service_name!(), "grpc_server", "tower_http"],
);
let metrics_server = app::metrics_server_builder(config.clone());
let server = app::server_builder(config);
#[allow(clippy::expect_used)]
tokio::try_join!(metrics_server, server)?;
Ok(())
}
#[cfg(debug_assertions)]
fn verify_other_config_files() {
use std::path::PathBuf;
use crate::configs;
let config_file_names = vec!["production.toml", "sandbox.toml"];
let mut config_path = PathBuf::new();
config_path.push(configs::workspace_path());
let config_directory: String = "config".into();
config_path.push(config_directory);
for config_file_name in config_file_names {
config_path.push(config_file_name);
#[allow(clippy::panic)]
let _ = configs::Config::new_with_config_path(Some(config_path.clone()))
.unwrap_or_else(|_| panic!("Update {config_file_name} with the default config values"));
config_path.pop();
}
}
|
{
"chunk": null,
"crate": "grpc-server",
"enum_name": null,
"file_size": 1418,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_grpc-server_-2612312103591988008
|
clm
|
small_file
|
// connector-service/backend/grpc-server/src/app.rs
use std::{future::Future, net, sync::Arc};
use axum::{extract::Request, http};
use common_utils::consts;
use external_services::shared_metrics as metrics;
use grpc_api_types::{
health_check::health_server,
payments::{
dispute_service_handler, dispute_service_server, payment_service_handler,
payment_service_server, refund_service_handler, refund_service_server,
},
};
use tokio::{
signal::unix::{signal, SignalKind},
sync::oneshot,
};
use tonic::transport::Server;
use tower_http::{request_id::MakeRequestUuid, trace as tower_trace};
use crate::{configs, error::ConfigurationError, logger, utils};
/// # Panics
///
/// Will panic if redis connection establishment fails or signal handling fails
pub async fn server_builder(config: configs::Config) -> Result<(), ConfigurationError> {
let server_config = config.server.clone();
let socket_addr = net::SocketAddr::new(server_config.host.parse()?, server_config.port);
// Signal handler
let (tx, rx) = oneshot::channel();
#[allow(clippy::expect_used)]
tokio::spawn(async move {
let mut sig_int =
signal(SignalKind::interrupt()).expect("Failed to initialize SIGINT signal handler");
let mut sig_term =
signal(SignalKind::terminate()).expect("Failed to initialize SIGTERM signal handler");
let mut sig_quit =
signal(SignalKind::quit()).expect("Failed to initialize QUIT signal handler");
let mut sig_hup =
signal(SignalKind::hangup()).expect("Failed to initialize SIGHUP signal handler");
tokio::select! {
_ = sig_int.recv() => {
logger::info!("Received SIGINT");
tx.send(()).expect("Failed to send SIGINT signal");
}
_ = sig_term.recv() => {
logger::info!("Received SIGTERM");
tx.send(()).expect("Failed to send SIGTERM signal");
}
_ = sig_quit.recv() => {
logger::info!("Received QUIT");
tx.send(()).expect("Failed to send QUIT signal");
}
_ = sig_hup.recv() => {
logger::info!("Received SIGHUP");
tx.send(()).expect("Failed to send SIGHUP signal");
}
}
});
#[allow(clippy::expect_used)]
let shutdown_signal = async {
rx.await.expect("Failed to receive shutdown signal");
logger::info!("Shutdown signal received");
};
let service = Service::new(Arc::new(config));
logger::info!(host = %server_config.host, port = %server_config.port, r#type = ?server_config.type_, "starting connector service");
match server_config.type_ {
configs::ServiceType::Grpc => {
service
.await
.grpc_server(socket_addr, shutdown_signal)
.await?
}
configs::ServiceType::Http => {
service
.await
.http_server(socket_addr, shutdown_signal)
.await?
}
}
Ok(())
}
pub struct Service {
pub health_check_service: crate::server::health_check::HealthCheck,
pub payments_service: crate::server::payments::Payments,
pub refunds_service: crate::server::refunds::Refunds,
pub disputes_service: crate::server::disputes::Disputes,
}
impl Service {
/// # Panics
///
/// Will panic if EventPublisher initialization fails, database password, hash key isn't present in configs or unable to
/// deserialize any of the above keys
#[allow(clippy::expect_used)]
pub async fn new(config: Arc<configs::Config>) -> Self {
// Initialize the global EventPublisher - fail fast on startup
if config.events.enabled {
common_utils::init_event_publisher(&config.events)
.expect("Failed to initialize global EventPublisher during startup");
logger::info!("Global EventPublisher initialized successfully");
} else {
logger::info!("EventPublisher disabled in configuration");
}
Self {
health_check_service: crate::server::health_check::HealthCheck,
payments_service: crate::server::payments::Payments {
config: Arc::clone(&config),
},
refunds_service: crate::server::refunds::Refunds {
config: Arc::clone(&config),
},
disputes_service: crate::server::disputes::Disputes { config },
}
}
pub async fn http_server(
self,
socket: net::SocketAddr,
shutdown_signal: impl Future<Output = ()> + Send + 'static,
) -> Result<(), ConfigurationError> {
let logging_layer = tower_trace::TraceLayer::new_for_http()
.make_span_with(|request: &Request<_>| utils::record_fields_from_header(request))
.on_request(tower_trace::DefaultOnRequest::new().level(tracing::Level::INFO))
.on_response(
tower_trace::DefaultOnResponse::new()
.level(tracing::Level::INFO)
.latency_unit(tower_http::LatencyUnit::Micros),
)
.on_failure(
tower_trace::DefaultOnFailure::new()
.latency_unit(tower_http::LatencyUnit::Micros)
.level(tracing::Level::ERROR),
);
let request_id_layer = tower_http::request_id::SetRequestIdLayer::new(
http::HeaderName::from_static(consts::X_REQUEST_ID),
MakeRequestUuid,
);
let propagate_request_id_layer = tower_http::request_id::PropagateRequestIdLayer::new(
http::HeaderName::from_static(consts::X_REQUEST_ID),
);
let router = axum::Router::new()
.route("/health", axum::routing::get(|| async { "health is good" }))
.merge(payment_service_handler(self.payments_service))
.merge(refund_service_handler(self.refunds_service))
.merge(dispute_service_handler(self.disputes_service))
.layer(logging_layer)
.layer(request_id_layer)
.layer(propagate_request_id_layer);
let listener = tokio::net::TcpListener::bind(socket).await?;
axum::serve(listener, router.into_make_service())
.with_graceful_shutdown(shutdown_signal)
.await?;
Ok(())
}
pub async fn grpc_server(
self,
socket: net::SocketAddr,
shutdown_signal: impl Future<Output = ()>,
) -> Result<(), ConfigurationError> {
let reflection_service = tonic_reflection::server::Builder::configure()
.register_encoded_file_descriptor_set(grpc_api_types::FILE_DESCRIPTOR_SET)
.build_v1()?;
let logging_layer = tower_trace::TraceLayer::new_for_http()
.make_span_with(|request: &http::request::Request<_>| {
utils::record_fields_from_header(request)
})
.on_request(tower_trace::DefaultOnRequest::new().level(tracing::Level::INFO))
.on_response(
tower_trace::DefaultOnResponse::new()
.level(tracing::Level::INFO)
.latency_unit(tower_http::LatencyUnit::Micros),
)
.on_failure(
tower_trace::DefaultOnFailure::new()
.latency_unit(tower_http::LatencyUnit::Micros)
.level(tracing::Level::ERROR),
);
let metrics_layer = metrics::GrpcMetricsLayer::new();
let request_id_layer = tower_http::request_id::SetRequestIdLayer::new(
http::HeaderName::from_static(consts::X_REQUEST_ID),
MakeRequestUuid,
);
let propagate_request_id_layer = tower_http::request_id::PropagateRequestIdLayer::new(
http::HeaderName::from_static(consts::X_REQUEST_ID),
);
Server::builder()
.layer(logging_layer)
.layer(request_id_layer)
.layer(propagate_request_id_layer)
.layer(metrics_layer)
.add_service(reflection_service)
.add_service(health_server::HealthServer::new(self.health_check_service))
.add_service(payment_service_server::PaymentServiceServer::new(
self.payments_service.clone(),
))
.add_service(refund_service_server::RefundServiceServer::new(
self.refunds_service,
))
.add_service(dispute_service_server::DisputeServiceServer::new(
self.disputes_service,
))
.serve_with_shutdown(socket, shutdown_signal)
.await?;
Ok(())
}
}
pub async fn metrics_server_builder(config: configs::Config) -> Result<(), ConfigurationError> {
let listener = config.metrics.tcp_listener().await?;
let router = axum::Router::new().route(
"/metrics",
axum::routing::get(|| async {
let output = metrics::metrics_handler().await;
match output {
Ok(metrics) => Ok(metrics),
Err(error) => {
tracing::error!(?error, "Error fetching metrics");
Err((
http::StatusCode::INTERNAL_SERVER_ERROR,
"Error fetching metrics".to_string(),
))
}
}
}),
);
axum::serve(listener, router.into_make_service())
.with_graceful_shutdown(async {
let output = tokio::signal::ctrl_c().await;
tracing::error!(?output, "shutting down");
})
.await?;
Ok(())
}
|
{
"chunk": null,
"crate": "grpc-server",
"enum_name": null,
"file_size": 9685,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_grpc-server_8407789757677062419
|
clm
|
small_file
|
// connector-service/backend/grpc-server/src/logger/config.rs
//!
//! Logger-specific config.
//!
use serde::Deserialize;
/// Log config settings.
#[derive(Debug, Deserialize, Clone)]
pub struct Log {
/// Logging to a console.
pub console: LogConsole,
/// Logging to Kafka (optional).
#[serde(default)]
pub kafka: Option<LogKafka>,
}
/// Logging to a console.
#[derive(Debug, Deserialize, Clone)]
pub struct LogConsole {
/// Whether you want to see log in your terminal.
pub enabled: bool,
/// What you see in your terminal.
pub level: Level,
/// Log format
pub log_format: LogFormat,
/// Directive which sets the log level for one or more crates/modules.
pub filtering_directive: Option<String>,
}
/// Describes the level of verbosity of a span or event.
#[derive(Debug, Clone, Copy)]
pub struct Level(pub(super) tracing::Level);
impl Level {
/// Returns the most verbose [`tracing::Level`]
pub fn into_level(&self) -> tracing::Level {
self.0
}
}
impl<'de> Deserialize<'de> for Level {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
use std::str::FromStr as _;
let s = String::deserialize(deserializer)?;
tracing::Level::from_str(&s)
.map(Level)
.map_err(serde::de::Error::custom)
}
}
/// Telemetry / tracing.
#[derive(Default, Debug, Deserialize, Clone, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum LogFormat {
/// Default pretty log format
Default,
/// JSON based structured logging
#[default]
Json,
}
/// Logging to Kafka.
#[derive(Debug, Deserialize, Clone)]
pub struct LogKafka {
/// Whether Kafka logging is enabled.
pub enabled: bool,
/// Minimum log level for Kafka logging.
pub level: Level,
/// Directive which sets the log level for one or more crates/modules.
pub filtering_directive: Option<String>,
/// Kafka broker addresses.
pub brokers: Vec<String>,
/// Topic name for logs.
pub topic: String,
/// Batch size for Kafka messages (optional, defaults to Kafka default).
#[serde(default)]
pub batch_size: Option<usize>,
/// Flush interval in milliseconds (optional, defaults to Kafka default).
#[serde(default)]
pub flush_interval_ms: Option<u64>,
/// Buffer limit for Kafka messages (optional, defaults to Kafka default).
#[serde(default)]
pub buffer_limit: Option<usize>,
}
|
{
"chunk": null,
"crate": "grpc-server",
"enum_name": null,
"file_size": 2443,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_grpc-server_-8301123723402502079
|
clm
|
small_file
|
// connector-service/backend/grpc-server/src/logger/env.rs
#[macro_export]
macro_rules! service_name {
() => {
env!("CARGO_BIN_NAME")
};
}
#[macro_export]
macro_rules! git_describe {
() => {
env!("VERGEN_GIT_DESCRIBE")
};
}
#[macro_export]
macro_rules! version {
() => {
concat!(
env!("VERGEN_GIT_DESCRIBE"),
"-",
env!("VERGEN_GIT_SHA"),
"-",
env!("VERGEN_GIT_COMMIT_TIMESTAMP"),
)
};
}
|
{
"chunk": null,
"crate": "grpc-server",
"enum_name": null,
"file_size": 446,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_grpc-server_-1230957448226898650
|
clm
|
small_file
|
// connector-service/backend/grpc-server/src/logger/formatter.rs
//!
//! Formatting [layer](https://docs.rs/tracing-subscriber/0.3.15/tracing_subscriber/layer/trait.Layer.html) for Router.
//!
use std::{
collections::{HashMap, HashSet},
fmt,
io::Write,
};
use common_utils::consts::{
LOG_FILE as FILE, LOG_FN as FN, LOG_FULL_NAME as FULL_NAME, LOG_HOSTNAME as HOSTNAME,
LOG_LEVEL as LEVEL, LOG_LINE as LINE, LOG_MESSAGE as MESSAGE, LOG_PID as PID,
LOG_SERVICE as SERVICE, LOG_TARGET as TARGET, LOG_TIME as TIME,
};
use once_cell::sync::Lazy;
use serde::ser::{SerializeMap, Serializer};
use serde_json::Value;
use super::storage::Storage;
use time::format_description::well_known::Iso8601;
use tracing::{Event, Metadata, Subscriber};
use tracing_subscriber::{
fmt::MakeWriter,
layer::Context,
registry::{LookupSpan, SpanRef},
Layer,
};
// TODO: Documentation coverage for this crate
// Implicit keys
/// Set of predefined implicit keys.
pub static IMPLICIT_KEYS: Lazy<rustc_hash::FxHashSet<&str>> = Lazy::new(|| {
let mut set = rustc_hash::FxHashSet::default();
set.insert(HOSTNAME);
set.insert(PID);
set.insert(LEVEL);
set.insert(TARGET);
set.insert(SERVICE);
set.insert(LINE);
set.insert(FILE);
set.insert(FN);
set.insert(FULL_NAME);
set.insert(TIME);
set
});
/// Describe type of record: entering a span, exiting a span, an event.
#[derive(Clone, Debug)]
pub enum RecordType {
/// Entering a span.
EnterSpan,
/// Exiting a span.
ExitSpan,
/// Event.
Event,
}
impl fmt::Display for RecordType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let repr = match self {
Self::EnterSpan => "START",
Self::ExitSpan => "END",
Self::Event => "EVENT",
};
write!(f, "{repr}")
}
}
///
/// Format log records.
/// `FormattingLayer` relies on the `tracing_bunyan_formatter::JsonStorageLayer` which is storage of entries.
///
#[derive(Debug)]
pub struct FormattingLayer<W>
where
W: for<'a> MakeWriter<'a> + 'static,
{
dst_writer: W,
pid: u32,
hostname: String,
service: String,
default_fields: HashMap<String, Value>,
}
impl<W> FormattingLayer<W>
where
W: for<'a> MakeWriter<'a> + 'static,
{
///
/// Constructor of `FormattingLayer`.
///
/// A `name` will be attached to all records during formatting.
/// A `dst_writer` to forward all records.
///
/// ## Example
/// ```rust,ignore
/// let formatting_layer = router_env::FormattingLayer::new(env::service_name!(),std::io::stdout);
/// ```
///
pub fn new(service: &str, dst_writer: W) -> Self {
Self::new_with_implicit_entries(service, dst_writer, HashMap::new())
}
/// Construct of `FormattingLayer with implicit default entries.
pub fn new_with_implicit_entries(
service: &str,
dst_writer: W,
mut default_fields: HashMap<String, Value>,
) -> Self {
let pid = std::process::id();
let hostname = gethostname::gethostname().to_string_lossy().into_owned();
let service = service.to_string();
default_fields.retain(|key, value| {
if !IMPLICIT_KEYS.contains(key.as_str()) {
true
} else {
#[allow(clippy::print_stderr)]
{
eprintln!(
"Attempting to log a reserved entry. It won't be added to the logs. key: {:?}, value: {:?}",
key, value);
}
false
}
});
Self {
dst_writer,
pid,
hostname,
service,
default_fields,
}
}
/// Serialize common for both span and event entries.
fn common_serialize<S>(
&self,
map_serializer: &mut impl SerializeMap<Error = serde_json::Error>,
metadata: &Metadata<'_>,
span: Option<&SpanRef<'_, S>>,
storage: &Storage<'_>,
name: &str,
) -> Result<(), std::io::Error>
where
S: Subscriber + for<'a> LookupSpan<'a>,
{
let is_extra = |s: &str| !IMPLICIT_KEYS.contains(s);
map_serializer.serialize_entry(HOSTNAME, &self.hostname)?;
map_serializer.serialize_entry(PID, &self.pid)?;
map_serializer.serialize_entry(LEVEL, &format_args!("{}", metadata.level()))?;
map_serializer.serialize_entry(TARGET, metadata.target())?;
map_serializer.serialize_entry(SERVICE, &self.service)?;
map_serializer.serialize_entry(LINE, &metadata.line())?;
map_serializer.serialize_entry(FILE, &metadata.file())?;
map_serializer.serialize_entry(FN, name)?;
map_serializer
.serialize_entry(FULL_NAME, &format_args!("{}::{}", metadata.target(), name))?;
if let Ok(time) = &time::OffsetDateTime::now_utc().format(&Iso8601::DEFAULT) {
map_serializer.serialize_entry(TIME, time)?;
}
// Write down implicit default entries.
for (key, value) in self.default_fields.iter() {
map_serializer.serialize_entry(key, value)?;
}
let mut explicit_entries_set: HashSet<&str> = HashSet::default();
// Write down explicit event's entries.
for (key, value) in storage.values.iter() {
map_serializer.serialize_entry(key, value)?;
explicit_entries_set.insert(key);
}
// Write down entries from the span, if it exists.
if let Some(span) = &span {
let extensions = span.extensions();
if let Some(visitor) = extensions.get::<Storage<'_>>() {
for (key, value) in &visitor.values {
if is_extra(key) && !explicit_entries_set.contains(key) {
map_serializer.serialize_entry(key, value)?;
} else {
#[allow(clippy::print_stderr)]
{
eprintln!(
"Attempting to log a reserved entry. It won't be added to the logs. key: {key:?}, value: {value:?}"
);
}
}
}
}
}
Ok(())
}
///
/// Flush memory buffer into an output stream trailing it with next line.
///
/// Should be done by single `write_all` call to avoid fragmentation of log because of multithreading.
///
fn flush(&self, mut buffer: Vec<u8>) -> Result<(), std::io::Error> {
buffer.write_all(b"\n")?;
self.dst_writer.make_writer().write_all(&buffer)
}
/// Serialize entries of span.
fn span_serialize<S>(
&self,
span: &SpanRef<'_, S>,
ty: RecordType,
) -> Result<Vec<u8>, std::io::Error>
where
S: Subscriber + for<'a> LookupSpan<'a>,
{
let mut buffer = Vec::new();
let mut serializer = serde_json::Serializer::new(&mut buffer);
let mut map_serializer = serializer.serialize_map(None)?;
let message = Self::span_message(span, ty);
let mut storage = Storage::default();
storage.record_value(MESSAGE, message.into());
self.common_serialize(
&mut map_serializer,
span.metadata(),
Some(span),
&storage,
span.name(),
)?;
map_serializer.end()?;
Ok(buffer)
}
/// Serialize event into a buffer of bytes using parent span.
pub fn event_serialize<S>(
&self,
span: &Option<&SpanRef<'_, S>>,
event: &Event<'_>,
) -> std::io::Result<Vec<u8>>
where
S: Subscriber + for<'a> LookupSpan<'a>,
{
let mut buffer = Vec::new();
let mut serializer = serde_json::Serializer::new(&mut buffer);
let mut map_serializer = serializer.serialize_map(None)?;
let mut storage = Storage::default();
event.record(&mut storage);
let name = span.map_or("?", SpanRef::name);
Self::event_message(span, event, &mut storage);
self.common_serialize(&mut map_serializer, event.metadata(), *span, &storage, name)?;
map_serializer.end()?;
Ok(buffer)
}
///
/// Format message of a span.
///
/// Example: "[FN_WITHOUT_COLON - START]"
///
fn span_message<S>(span: &SpanRef<'_, S>, ty: RecordType) -> String
where
S: Subscriber + for<'a> LookupSpan<'a>,
{
format!("[{} - {}]", span.metadata().name().to_uppercase(), ty)
}
///
/// Format message of an event.
///
/// Examples: "[FN_WITHOUT_COLON - EVENT] Message"
///
fn event_message<S>(
span: &Option<&SpanRef<'_, S>>,
event: &Event<'_>,
storage: &mut Storage<'_>,
) where
S: Subscriber + for<'a> LookupSpan<'a>,
{
let message = storage
.values
.entry(MESSAGE)
.or_insert_with(|| event.metadata().target().into());
// Prepend the span name to the message if span exists.
if let (Some(span), Value::String(a)) = (span, message) {
*a = format!("{} {}", Self::span_message(span, RecordType::Event), a,);
}
}
}
#[allow(clippy::expect_used)]
impl<S, W> Layer<S> for FormattingLayer<W>
where
S: Subscriber + for<'a> LookupSpan<'a>,
W: for<'a> MakeWriter<'a> + 'static,
{
fn on_event(&self, event: &Event<'_>, ctx: Context<'_, S>) {
// Event could have no span.
let span = ctx.lookup_current();
let result: std::io::Result<Vec<u8>> = self.event_serialize(&span.as_ref(), event);
if let Ok(formatted) = result {
let _ = self.flush(formatted);
}
}
fn on_enter(&self, id: &tracing::Id, ctx: Context<'_, S>) {
let span = ctx.span(id).expect("No span");
if let Ok(serialized) = self.span_serialize(&span, RecordType::EnterSpan) {
let _ = self.flush(serialized);
}
}
fn on_close(&self, id: tracing::Id, ctx: Context<'_, S>) {
let span = ctx.span(&id).expect("No span");
if let Ok(serialized) = self.span_serialize(&span, RecordType::ExitSpan) {
let _ = self.flush(serialized);
}
}
}
|
{
"chunk": null,
"crate": "grpc-server",
"enum_name": null,
"file_size": 10275,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_grpc-server_6348302695617038329
|
clm
|
small_file
|
// connector-service/backend/grpc-server/src/logger/storage.rs
//!
//! Storing [layer](https://docs.rs/tracing-subscriber/0.3.15/tracing_subscriber/layer/trait.Layer.html) for Router.
//!
use std::{collections::HashMap, fmt, time::Instant};
use tracing::{
field::{Field, Visit},
span::{Attributes, Record},
Id, Subscriber,
};
use tracing_subscriber::{layer::Context, Layer};
/// Storage to store key value pairs of spans.
#[derive(Clone, Debug)]
pub struct StorageSubscription;
/// Storage to store key value pairs of spans.
/// When new entry is crated it stores it in [HashMap] which is owned by `extensions`.
#[derive(Clone, Debug)]
pub struct Storage<'a> {
/// Hash map to store values.
pub values: HashMap<&'a str, serde_json::Value>,
}
impl<'a> Storage<'a> {
/// Default constructor.
pub fn new() -> Self {
Self::default()
}
pub fn record_value(&mut self, key: &'a str, value: serde_json::Value) {
if super::formatter::IMPLICIT_KEYS.contains(key) {
#[allow(clippy::print_stderr)]
{
eprintln!("{key} is a reserved entry. Skipping it. value: {value}");
}
} else {
self.values.insert(key, value);
}
}
}
/// Default constructor.
impl Default for Storage<'_> {
fn default() -> Self {
Self {
values: HashMap::new(),
}
}
}
/// Visitor to store entry.
impl Visit for Storage<'_> {
/// A i64.
fn record_i64(&mut self, field: &Field, value: i64) {
self.record_value(field.name(), serde_json::Value::from(value));
}
/// A u64.
fn record_u64(&mut self, field: &Field, value: u64) {
self.record_value(field.name(), serde_json::Value::from(value));
}
/// A 64-bit floating point.
fn record_f64(&mut self, field: &Field, value: f64) {
self.record_value(field.name(), serde_json::Value::from(value));
}
/// A boolean.
fn record_bool(&mut self, field: &Field, value: bool) {
self.record_value(field.name(), serde_json::Value::from(value));
}
/// A string.
fn record_str(&mut self, field: &Field, value: &str) {
self.record_value(field.name(), serde_json::Value::from(value));
}
/// Otherwise.
fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
match field.name() {
// Skip fields which are already handled
name if name.starts_with("log.") => (),
name if name.starts_with("r#") => {
self.record_value(&name[2..], serde_json::Value::from(format!("{value:?}")));
}
name => {
self.record_value(name, serde_json::Value::from(format!("{value:?}")));
}
};
}
}
#[allow(clippy::expect_used)]
impl<S: Subscriber + for<'a> tracing_subscriber::registry::LookupSpan<'a>> Layer<S>
for StorageSubscription
{
/// On new span.
fn on_new_span(&self, attrs: &Attributes<'_>, id: &Id, ctx: Context<'_, S>) {
let span = ctx.span(id).expect("No span");
let mut visitor = if let Some(parent_span) = span.parent() {
let mut extensions = parent_span.extensions_mut();
extensions
.get_mut::<Storage<'_>>()
.map(|v| v.to_owned())
.unwrap_or_default()
} else {
Storage::default()
};
let mut extensions = span.extensions_mut();
attrs.record(&mut visitor);
extensions.insert(visitor);
}
/// On additional key value pairs store it.
fn on_record(&self, span: &Id, values: &Record<'_>, ctx: Context<'_, S>) {
let span = ctx.span(span).expect("No span");
let mut extensions = span.extensions_mut();
let visitor = extensions
.get_mut::<Storage<'_>>()
.expect("The span does not have storage");
values.record(visitor);
}
/// On enter store time.
fn on_enter(&self, span: &Id, ctx: Context<'_, S>) {
let span = ctx.span(span).expect("No span");
let mut extensions = span.extensions_mut();
if extensions.get_mut::<Instant>().is_none() {
extensions.insert(Instant::now());
}
}
/// On close create an entry about how long did it take.
fn on_close(&self, span: Id, ctx: Context<'_, S>) {
let span = ctx.span(&span).expect("No span");
let elapsed_milliseconds = {
let extensions = span.extensions();
extensions
.get::<Instant>()
.map(|i| i.elapsed().as_millis())
.unwrap_or(0)
};
let mut extensions_mut = span.extensions_mut();
let visitor = extensions_mut
.get_mut::<Storage<'_>>()
.expect("No visitor in extensions");
if let Ok(elapsed) = serde_json::to_value(elapsed_milliseconds) {
visitor.record_value("elapsed_milliseconds", elapsed);
}
}
}
|
{
"chunk": null,
"crate": "grpc-server",
"enum_name": null,
"file_size": 4930,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_grpc-server_8913100032470277647
|
clm
|
small_file
|
// connector-service/backend/grpc-server/src/logger/setup.rs
//! Setup logging subsystem.
use std::collections::{HashMap, HashSet};
use tracing_appender::non_blocking::WorkerGuard;
#[cfg(feature = "kafka")]
use tracing_kafka::KafkaLayer;
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt, Layer};
use super::config;
/// Contains guards necessary for logging
#[derive(Debug)]
pub struct TelemetryGuard {
_log_guards: Vec<WorkerGuard>,
}
/// Setup logging sub-system specifying the logging configuration, service (binary) name, and a
/// list of external crates for which a more verbose logging must be enabled. All crates within the
/// current cargo workspace are automatically considered for verbose logging.
pub fn setup(
config: &config::Log,
service_name: &str,
crates_to_filter: impl AsRef<[&'static str]>,
) -> Result<TelemetryGuard, log_utils::LoggerError> {
let static_top_level_fields = HashMap::from_iter([
("service".to_string(), serde_json::json!(service_name)),
(
"build_version".to_string(),
serde_json::json!(crate::version!()),
),
]);
let console_config = if config.console.enabled {
let console_filter_directive =
config
.console
.filtering_directive
.clone()
.unwrap_or_else(|| {
get_envfilter_directive(
tracing::Level::WARN,
config.console.level.into_level(),
crates_to_filter.as_ref(),
)
});
let log_format = match config.console.log_format {
config::LogFormat::Default => log_utils::ConsoleLogFormat::HumanReadable,
config::LogFormat::Json => {
// Disable color or emphasis related ANSI escape codes for JSON formats
error_stack::Report::set_color_mode(error_stack::fmt::ColorMode::None);
log_utils::ConsoleLogFormat::CompactJson
}
};
Some(log_utils::ConsoleLoggingConfig {
level: config.console.level.into_level(),
log_format,
filtering_directive: Some(console_filter_directive),
print_filtering_directive: log_utils::DirectivePrintTarget::Stderr,
})
} else {
None
};
let logger_config = log_utils::LoggerConfig {
static_top_level_fields: static_top_level_fields.clone(),
top_level_keys: HashSet::new(),
persistent_keys: HashSet::new(),
log_span_lifecycles: true,
additional_fields_placement: log_utils::AdditionalFieldsPlacement::TopLevel,
file_config: None,
console_config,
global_filtering_directive: None,
};
let logging_components = log_utils::build_logging_components(logger_config)?;
let mut subscriber_layers = Vec::new();
subscriber_layers.push(logging_components.storage_layer.boxed());
if let Some(console_layer) = logging_components.console_log_layer {
subscriber_layers.push(console_layer);
}
#[allow(unused_mut)]
let mut kafka_logging_enabled = false;
// Add Kafka layer if configured
#[cfg(feature = "kafka")]
if let Some(kafka_config) = &config.kafka {
if kafka_config.enabled {
// Initialize kafka metrics if the feature is enabled.
// This will cause the application to panic at startup if metric registration fails.
tracing_kafka::init();
let kafka_filter_directive =
kafka_config.filtering_directive.clone().unwrap_or_else(|| {
get_envfilter_directive(
tracing::Level::WARN,
kafka_config.level.into_level(),
crates_to_filter.as_ref(),
)
});
let brokers: Vec<&str> = kafka_config.brokers.iter().map(|s| s.as_str()).collect();
let mut builder = KafkaLayer::builder()
.brokers(&brokers)
.topic(&kafka_config.topic)
.static_fields(static_top_level_fields.clone());
// Add batch_size if configured
if let Some(batch_size) = kafka_config.batch_size {
builder = builder.batch_size(batch_size);
}
// Add flush_interval_ms if configured
if let Some(flush_interval_ms) = kafka_config.flush_interval_ms {
builder = builder.linger_ms(flush_interval_ms);
}
// Add buffer_limit if configured
if let Some(buffer_limit) = kafka_config.buffer_limit {
builder = builder.queue_buffering_max_messages(buffer_limit);
}
let kafka_layer = match builder.build() {
Ok(layer) => {
// Create filter with infinite feedback loop prevention
let kafka_filter_directive = format!(
"{kafka_filter_directive},rdkafka=off,librdkafka=off,kafka=off,kafka_writer=off,tracing_kafka=off",
);
let kafka_filter = tracing_subscriber::EnvFilter::builder()
.with_default_directive(kafka_config.level.into_level().into())
.parse_lossy(kafka_filter_directive);
Some(layer.with_filter(kafka_filter))
}
Err(e) => {
tracing::warn!(error = ?e, "Failed to enable Kafka logging");
// Continue without Kafka
None
}
};
if let Some(layer) = kafka_layer {
subscriber_layers.push(layer.boxed());
kafka_logging_enabled = true;
tracing::info!(topic = %kafka_config.topic, "Kafka logging enabled");
}
}
}
tracing_subscriber::registry()
.with(subscriber_layers)
.init();
tracing::info!(
service_name,
build_version = crate::version!(),
kafka_logging_enabled,
"Logging subsystem initialized"
);
// Returning the TelemetryGuard for logs to be printed and metrics to be collected until it is
// dropped
Ok(TelemetryGuard {
_log_guards: logging_components.guards,
})
}
fn get_envfilter_directive(
default_log_level: tracing::Level,
filter_log_level: tracing::Level,
crates_to_filter: impl AsRef<[&'static str]>,
) -> String {
let mut explicitly_handled_targets = build_info::cargo_workspace_members!();
explicitly_handled_targets.extend(build_info::framework_libs_workspace_members());
explicitly_handled_targets.extend(crates_to_filter.as_ref());
// +1 for the default log level added as a directive
let num_directives = explicitly_handled_targets.len() + 1;
explicitly_handled_targets
.into_iter()
.map(|crate_name| crate_name.replace('-', "_"))
.zip(std::iter::repeat(filter_log_level))
.fold(
{
let mut directives = Vec::with_capacity(num_directives);
directives.push(default_log_level.to_string());
directives
},
|mut directives, (target, level)| {
directives.push(format!("{target}={level}"));
directives
},
)
.join(",")
}
|
{
"chunk": null,
"crate": "grpc-server",
"enum_name": null,
"file_size": 7408,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_grpc-server_-372326334623076254
|
clm
|
small_file
|
// connector-service/backend/grpc-server/src/server/refunds.rs
use std::sync::Arc;
use common_utils::errors::CustomResult;
use connector_integration::types::ConnectorData;
use domain_types::{
connector_flow::{FlowName, RSync},
connector_types::{RefundFlowData, RefundSyncData, RefundsResponseData},
errors::{ApiError, ApplicationErrorResponse},
payment_method_data::DefaultPCIHolder,
router_data::ConnectorAuthType,
types::generate_refund_sync_response,
utils::ForeignTryFrom,
};
use error_stack::ResultExt;
use external_services;
use grpc_api_types::payments::{
refund_service_server::RefundService, RefundResponse, RefundServiceGetRequest,
RefundServiceTransformRequest, RefundServiceTransformResponse, WebhookEventType,
WebhookResponseContent,
};
use crate::{
configs::Config,
error::{IntoGrpcStatus, ReportSwitchExt, ResultExtGrpc},
implement_connector_operation,
request::RequestData,
utils,
};
// Helper trait for refund operations
trait RefundOperationsInternal {
async fn internal_get(
&self,
request: RequestData<RefundServiceGetRequest>,
) -> Result<tonic::Response<RefundResponse>, tonic::Status>;
}
#[derive(Debug)]
pub struct Refunds {
pub config: Arc<Config>,
}
impl RefundOperationsInternal for Refunds {
implement_connector_operation!(
fn_name: internal_get,
log_prefix: "REFUND_SYNC",
request_type: RefundServiceGetRequest,
response_type: RefundResponse,
flow_marker: RSync,
resource_common_data_type: RefundFlowData,
request_data_type: RefundSyncData,
response_data_type: RefundsResponseData,
request_data_constructor: RefundSyncData::foreign_try_from,
common_flow_data_constructor: RefundFlowData::foreign_try_from,
generate_response_fn: generate_refund_sync_response,
all_keys_required: None
);
}
#[tonic::async_trait]
impl RefundService for Refunds {
#[tracing::instrument(
name = "refunds_sync",
fields(
name = common_utils::consts::NAME,
service_name = tracing::field::Empty,
service_method = FlowName::Rsync.to_string(),
request_body = tracing::field::Empty,
response_body = tracing::field::Empty,
error_message = tracing::field::Empty,
merchant_id = tracing::field::Empty,
gateway = tracing::field::Empty,
request_id = tracing::field::Empty,
status_code = tracing::field::Empty,
message_ = "Golden Log Line (incoming)",
response_time = tracing::field::Empty,
tenant_id = tracing::field::Empty,
flow = FlowName::Rsync.to_string(),
flow_specific_fields.status = tracing::field::Empty,
)
skip(self, request)
)]
async fn get(
&self,
request: tonic::Request<RefundServiceGetRequest>,
) -> Result<tonic::Response<RefundResponse>, tonic::Status> {
let service_name = request
.extensions()
.get::<String>()
.cloned()
.unwrap_or_else(|| "RefundService".to_string());
utils::grpc_logging_wrapper(
request,
&service_name,
self.config.clone(),
common_utils::events::FlowName::Rsync,
|request_data| async move { self.internal_get(request_data).await },
)
.await
}
#[tracing::instrument(
name = "refunds_transform",
fields(
name = common_utils::consts::NAME,
service_name = tracing::field::Empty,
service_method = FlowName::IncomingWebhook.to_string(),
request_body = tracing::field::Empty,
response_body = tracing::field::Empty,
error_message = tracing::field::Empty,
merchant_id = tracing::field::Empty,
gateway = tracing::field::Empty,
request_id = tracing::field::Empty,
status_code = tracing::field::Empty,
message_ = "Golden Log Line (incoming)",
response_time = tracing::field::Empty,
tenant_id = tracing::field::Empty,
flow = FlowName::IncomingWebhook.to_string(),
)
)]
async fn transform(
&self,
request: tonic::Request<RefundServiceTransformRequest>,
) -> Result<tonic::Response<RefundServiceTransformResponse>, tonic::Status> {
let service_name = request
.extensions()
.get::<String>()
.cloned()
.unwrap_or_else(|| "RefundService".to_string());
utils::grpc_logging_wrapper(
request,
&service_name,
self.config.clone(),
common_utils::events::FlowName::IncomingWebhook,
|request_data| async move {
let payload = request_data.payload;
let connector = request_data.extracted_metadata.connector;
let connector_auth_details = request_data.extracted_metadata.connector_auth_type;
let request_details = payload
.request_details
.map(domain_types::connector_types::RequestDetails::foreign_try_from)
.ok_or_else(|| {
tonic::Status::invalid_argument("missing request_details in the payload")
})?
.map_err(|e| e.into_grpc_status())?;
let webhook_secrets = payload
.webhook_secrets
.map(|details| {
domain_types::connector_types::ConnectorWebhookSecrets::foreign_try_from(
details,
)
.map_err(|e| e.into_grpc_status())
})
.transpose()?;
// Get connector data
let connector_data = ConnectorData::get_connector_by_name(&connector);
let source_verified = connector_data
.connector
.verify_webhook_source(
request_details.clone(),
webhook_secrets.clone(),
Some(connector_auth_details.clone()),
)
.switch()
.map_err(|e| e.into_grpc_status())?;
let content = get_refunds_webhook_content(
connector_data,
request_details,
webhook_secrets,
Some(connector_auth_details),
)
.await
.map_err(|e| e.into_grpc_status())?;
let response = RefundServiceTransformResponse {
event_type: WebhookEventType::WebhookRefundSuccess.into(),
content: Some(content),
source_verified,
response_ref_id: None,
};
Ok(tonic::Response::new(response))
},
)
.await
}
}
async fn get_refunds_webhook_content(
connector_data: ConnectorData<DefaultPCIHolder>,
request_details: domain_types::connector_types::RequestDetails,
webhook_secrets: Option<domain_types::connector_types::ConnectorWebhookSecrets>,
connector_auth_details: Option<ConnectorAuthType>,
) -> CustomResult<WebhookResponseContent, ApplicationErrorResponse> {
let webhook_details = connector_data
.connector
.process_refund_webhook(request_details, webhook_secrets, connector_auth_details)
.switch()?;
// Generate response
let response = RefundResponse::foreign_try_from(webhook_details).change_context(
ApplicationErrorResponse::InternalServerError(ApiError {
sub_code: "RESPONSE_CONSTRUCTION_ERROR".to_string(),
error_identifier: 500,
error_message: "Error while constructing response".to_string(),
error_object: None,
}),
)?;
Ok(WebhookResponseContent {
content: Some(
grpc_api_types::payments::webhook_response_content::Content::RefundsResponse(response),
),
})
}
|
{
"chunk": null,
"crate": "grpc-server",
"enum_name": null,
"file_size": 8148,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_grpc-server_6130414747938716573
|
clm
|
small_file
|
// connector-service/backend/grpc-server/src/server/health_check.rs
use grpc_api_types::health_check::{self, health_server};
use tonic::{Request, Response, Status};
pub struct HealthCheck;
#[tonic::async_trait]
impl health_server::Health for HealthCheck {
async fn check(
&self,
request: Request<health_check::HealthCheckRequest>,
) -> Result<Response<health_check::HealthCheckResponse>, Status> {
tracing::debug!(?request, "health_check request");
let response = health_check::HealthCheckResponse {
status: health_check::health_check_response::ServingStatus::Serving.into(),
};
tracing::info!(?response, "health_check response");
Ok(Response::new(response))
}
}
|
{
"chunk": null,
"crate": "grpc-server",
"enum_name": null,
"file_size": 679,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_interfaces_-8015963827255197627
|
clm
|
small_file
|
// connector-service/backend/interfaces/src/events.rs
//! Events interface
pub mod connector_api_logs;
pub mod routing_api_logs;
|
{
"chunk": null,
"crate": "interfaces",
"enum_name": null,
"file_size": 76,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_interfaces_-4210072120393553698
|
clm
|
small_file
|
// connector-service/backend/interfaces/src/verification.rs
use common_utils::{crypto, CustomResult};
use domain_types::{
connector_types::ConnectorWebhookSecrets, router_data::ConnectorAuthType,
router_data_v2::RouterDataV2,
};
use error_stack::ResultExt;
pub enum ConnectorSourceVerificationSecrets {
AuthHeaders(ConnectorAuthType),
WebhookSecret(ConnectorWebhookSecrets),
AuthWithWebHookSecret {
auth_headers: ConnectorAuthType,
webhook_secret: ConnectorWebhookSecrets,
},
}
/// Core trait for source verification
pub trait SourceVerification<Flow, ResourceCommonData, Req, Resp> {
fn get_secrets(
&self,
_secrets: ConnectorSourceVerificationSecrets,
) -> CustomResult<Vec<u8>, domain_types::errors::ConnectorError> {
Ok(Vec::new())
}
/// Get the verification algorithm being used
fn get_algorithm(
&self,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, domain_types::errors::ConnectorError>
{
Ok(Box::new(crypto::NoAlgorithm))
}
/// Get the signature/hash value from the payload for verification
fn get_signature(
&self,
_payload: &[u8],
_router_data: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>,
_secrets: &[u8],
) -> CustomResult<Vec<u8>, domain_types::errors::ConnectorError> {
Ok(Vec::new())
}
/// Get the message/payload that should be verified
fn get_message(
&self,
payload: &[u8],
_router_data: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>,
_secrets: &[u8],
) -> CustomResult<Vec<u8>, domain_types::errors::ConnectorError> {
Ok(payload.to_owned())
}
/// Perform the verification
fn verify(
&self,
router_data: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>,
secrets: ConnectorSourceVerificationSecrets,
payload: &[u8],
) -> CustomResult<bool, domain_types::errors::ConnectorError> {
let algorithm = self.get_algorithm()?;
let extracted_secrets = self.get_secrets(secrets)?;
let signature = self.get_signature(payload, router_data, &extracted_secrets)?;
let message = self.get_message(payload, router_data, &extracted_secrets)?;
// Verify the signature against the message
algorithm
.verify_signature(&extracted_secrets, &signature, &message)
.change_context(domain_types::errors::ConnectorError::SourceVerificationFailed)
}
}
|
{
"chunk": null,
"crate": "interfaces",
"enum_name": null,
"file_size": 2457,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_interfaces_-1138128169477141208
|
clm
|
small_file
|
// connector-service/backend/interfaces/src/connector_types.rs
use std::collections::HashSet;
use common_enums::{AttemptStatus, CaptureMethod, PaymentMethod, PaymentMethodType};
use common_utils::{CustomResult, SecretSerdeValue};
use domain_types::{
connector_flow,
connector_types::{
AcceptDisputeData, AccessTokenRequestData, AccessTokenResponseData, ConnectorCustomerData,
ConnectorCustomerResponse, ConnectorSpecifications, ConnectorWebhookSecrets,
DisputeDefendData, DisputeFlowData, DisputeResponseData, DisputeWebhookDetailsResponse,
EventType, PaymentCreateOrderData, PaymentCreateOrderResponse, PaymentFlowData,
PaymentMethodTokenResponse, PaymentMethodTokenizationData, PaymentVoidData,
PaymentsAuthenticateData, PaymentsAuthorizeData, PaymentsCancelPostCaptureData,
PaymentsCaptureData, PaymentsPostAuthenticateData, PaymentsPreAuthenticateData,
PaymentsResponseData, PaymentsSyncData, RefundFlowData, RefundSyncData,
RefundWebhookDetailsResponse, RefundsData, RefundsResponseData, RepeatPaymentData,
RequestDetails, SessionTokenRequestData, SessionTokenResponseData, SetupMandateRequestData,
SubmitEvidenceData, WebhookDetailsResponse,
},
payment_method_data::{PaymentMethodData, PaymentMethodDataTypes},
router_data::ConnectorAuthType,
types::{PaymentMethodDataType, PaymentMethodDetails, SupportedPaymentMethods},
};
use error_stack::ResultExt;
use crate::{api::ConnectorCommon, connector_integration_v2::ConnectorIntegrationV2};
pub trait ConnectorServiceTrait<T: PaymentMethodDataTypes>:
ConnectorCommon
+ ValidationTrait
+ PaymentAuthorizeV2<T>
+ PaymentSyncV2
+ PaymentOrderCreate
+ PaymentSessionToken
+ PaymentAccessToken
+ CreateConnectorCustomer
+ PaymentTokenV2<T>
+ PaymentVoidV2
+ PaymentVoidPostCaptureV2
+ IncomingWebhook
+ RefundV2
+ PaymentCapture
+ SetupMandateV2<T>
+ RepeatPaymentV2
+ AcceptDispute
+ RefundSyncV2
+ DisputeDefend
+ SubmitEvidenceV2
+ PaymentPreAuthenticateV2<T>
+ PaymentAuthenticateV2<T>
+ PaymentPostAuthenticateV2<T>
{
}
pub trait PaymentVoidV2:
ConnectorIntegrationV2<connector_flow::Void, PaymentFlowData, PaymentVoidData, PaymentsResponseData>
{
}
pub trait PaymentVoidPostCaptureV2:
ConnectorIntegrationV2<
connector_flow::VoidPC,
PaymentFlowData,
PaymentsCancelPostCaptureData,
PaymentsResponseData,
>
{
}
pub type BoxedConnector<T> = Box<&'static (dyn ConnectorServiceTrait<T> + Sync)>;
pub trait ValidationTrait {
fn should_do_order_create(&self) -> bool {
false
}
fn should_do_session_token(&self) -> bool {
false
}
fn should_do_access_token(&self) -> bool {
false
}
fn should_create_connector_customer(&self) -> bool {
false
}
fn should_do_payment_method_token(&self) -> bool {
false
}
}
pub trait PaymentOrderCreate:
ConnectorIntegrationV2<
connector_flow::CreateOrder,
PaymentFlowData,
PaymentCreateOrderData,
PaymentCreateOrderResponse,
>
{
}
pub trait PaymentSessionToken:
ConnectorIntegrationV2<
connector_flow::CreateSessionToken,
PaymentFlowData,
SessionTokenRequestData,
SessionTokenResponseData,
>
{
}
pub trait PaymentAccessToken:
ConnectorIntegrationV2<
connector_flow::CreateAccessToken,
PaymentFlowData,
AccessTokenRequestData,
AccessTokenResponseData,
>
{
}
pub trait CreateConnectorCustomer:
ConnectorIntegrationV2<
connector_flow::CreateConnectorCustomer,
PaymentFlowData,
ConnectorCustomerData,
ConnectorCustomerResponse,
>
{
}
pub trait PaymentTokenV2<T: PaymentMethodDataTypes>:
ConnectorIntegrationV2<
connector_flow::PaymentMethodToken,
PaymentFlowData,
PaymentMethodTokenizationData<T>,
PaymentMethodTokenResponse,
>
{
}
pub trait PaymentAuthorizeV2<T: PaymentMethodDataTypes>:
ConnectorIntegrationV2<
connector_flow::Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
>
{
}
pub trait PaymentSyncV2:
ConnectorIntegrationV2<
connector_flow::PSync,
PaymentFlowData,
PaymentsSyncData,
PaymentsResponseData,
>
{
}
pub trait RefundV2:
ConnectorIntegrationV2<connector_flow::Refund, RefundFlowData, RefundsData, RefundsResponseData>
{
}
pub trait RefundSyncV2:
ConnectorIntegrationV2<connector_flow::RSync, RefundFlowData, RefundSyncData, RefundsResponseData>
{
}
pub trait PaymentCapture:
ConnectorIntegrationV2<
connector_flow::Capture,
PaymentFlowData,
PaymentsCaptureData,
PaymentsResponseData,
>
{
}
pub trait SetupMandateV2<T: PaymentMethodDataTypes>:
ConnectorIntegrationV2<
connector_flow::SetupMandate,
PaymentFlowData,
SetupMandateRequestData<T>,
PaymentsResponseData,
>
{
}
pub trait RepeatPaymentV2:
ConnectorIntegrationV2<
connector_flow::RepeatPayment,
PaymentFlowData,
RepeatPaymentData,
PaymentsResponseData,
>
{
}
pub trait AcceptDispute:
ConnectorIntegrationV2<
connector_flow::Accept,
DisputeFlowData,
AcceptDisputeData,
DisputeResponseData,
>
{
}
pub trait SubmitEvidenceV2:
ConnectorIntegrationV2<
connector_flow::SubmitEvidence,
DisputeFlowData,
SubmitEvidenceData,
DisputeResponseData,
>
{
}
pub trait DisputeDefend:
ConnectorIntegrationV2<
connector_flow::DefendDispute,
DisputeFlowData,
DisputeDefendData,
DisputeResponseData,
>
{
}
pub trait PaymentPreAuthenticateV2<T: PaymentMethodDataTypes>:
ConnectorIntegrationV2<
connector_flow::PreAuthenticate,
PaymentFlowData,
PaymentsPreAuthenticateData<T>,
PaymentsResponseData,
>
{
}
pub trait PaymentAuthenticateV2<T: PaymentMethodDataTypes>:
ConnectorIntegrationV2<
connector_flow::Authenticate,
PaymentFlowData,
PaymentsAuthenticateData<T>,
PaymentsResponseData,
>
{
}
pub trait PaymentPostAuthenticateV2<T: PaymentMethodDataTypes>:
ConnectorIntegrationV2<
connector_flow::PostAuthenticate,
PaymentFlowData,
PaymentsPostAuthenticateData<T>,
PaymentsResponseData,
>
{
}
pub trait IncomingWebhook {
fn verify_webhook_source(
&self,
_request: RequestDetails,
_connector_webhook_secret: Option<ConnectorWebhookSecrets>,
_connector_account_details: Option<ConnectorAuthType>,
) -> Result<bool, error_stack::Report<domain_types::errors::ConnectorError>> {
Ok(false)
}
/// fn get_webhook_source_verification_signature
fn get_webhook_source_verification_signature(
&self,
_request: &RequestDetails,
_connector_webhook_secret: &ConnectorWebhookSecrets,
) -> Result<Vec<u8>, error_stack::Report<domain_types::errors::ConnectorError>> {
Ok(Vec::new())
}
/// fn get_webhook_source_verification_message
fn get_webhook_source_verification_message(
&self,
_request: &RequestDetails,
_connector_webhook_secret: &ConnectorWebhookSecrets,
) -> Result<Vec<u8>, error_stack::Report<domain_types::errors::ConnectorError>> {
Ok(Vec::new())
}
fn get_event_type(
&self,
_request: RequestDetails,
_connector_webhook_secret: Option<ConnectorWebhookSecrets>,
_connector_account_details: Option<ConnectorAuthType>,
) -> Result<EventType, error_stack::Report<domain_types::errors::ConnectorError>> {
Err(
domain_types::errors::ConnectorError::NotImplemented("get_event_type".to_string())
.into(),
)
}
fn process_payment_webhook(
&self,
_request: RequestDetails,
_connector_webhook_secret: Option<ConnectorWebhookSecrets>,
_connector_account_details: Option<ConnectorAuthType>,
) -> Result<WebhookDetailsResponse, error_stack::Report<domain_types::errors::ConnectorError>>
{
Err(domain_types::errors::ConnectorError::NotImplemented(
"process_payment_webhook".to_string(),
)
.into())
}
fn process_refund_webhook(
&self,
_request: RequestDetails,
_connector_webhook_secret: Option<ConnectorWebhookSecrets>,
_connector_account_details: Option<ConnectorAuthType>,
) -> Result<
RefundWebhookDetailsResponse,
error_stack::Report<domain_types::errors::ConnectorError>,
> {
Err(domain_types::errors::ConnectorError::NotImplemented(
"process_refund_webhook".to_string(),
)
.into())
}
fn process_dispute_webhook(
&self,
_request: RequestDetails,
_connector_webhook_secret: Option<ConnectorWebhookSecrets>,
_connector_account_details: Option<ConnectorAuthType>,
) -> Result<
DisputeWebhookDetailsResponse,
error_stack::Report<domain_types::errors::ConnectorError>,
> {
Err(domain_types::errors::ConnectorError::NotImplemented(
"process_dispute_webhook".to_string(),
)
.into())
}
/// fn get_webhook_resource_object
fn get_webhook_resource_object(
&self,
_request: RequestDetails,
) -> Result<
Box<dyn hyperswitch_masking::ErasedMaskSerialize>,
error_stack::Report<domain_types::errors::ConnectorError>,
> {
Err(domain_types::errors::ConnectorError::NotImplemented(
"get_webhook_resource_object".to_string(),
)
.into())
}
}
/// trait ConnectorValidation
pub trait ConnectorValidation: ConnectorCommon + ConnectorSpecifications {
/// Validate, the payment request against the connector supported features
fn validate_connector_against_payment_request(
&self,
capture_method: Option<CaptureMethod>,
payment_method: PaymentMethod,
pmt: Option<PaymentMethodType>,
) -> CustomResult<(), domain_types::errors::ConnectorError> {
let capture_method = capture_method.unwrap_or_default();
let is_default_capture_method = [CaptureMethod::Automatic].contains(&capture_method);
let is_feature_supported = match self.get_supported_payment_methods() {
Some(supported_payment_methods) => {
let connector_payment_method_type_info = get_connector_payment_method_type_info(
supported_payment_methods,
payment_method,
pmt,
self.id(),
)?;
connector_payment_method_type_info
.map(|payment_method_type_info| {
payment_method_type_info
.supported_capture_methods
.contains(&capture_method)
})
.unwrap_or(true)
}
None => is_default_capture_method,
};
if is_feature_supported {
Ok(())
} else {
Err(domain_types::errors::ConnectorError::NotSupported {
message: capture_method.to_string(),
connector: self.id(),
}
.into())
}
}
/// fn validate_mandate_payment
fn validate_mandate_payment(
&self,
pm_type: Option<PaymentMethodType>,
_pm_data: PaymentMethodData<domain_types::payment_method_data::DefaultPCIHolder>,
) -> CustomResult<(), domain_types::errors::ConnectorError> {
let connector = self.id();
match pm_type {
Some(pm_type) => Err(domain_types::errors::ConnectorError::NotSupported {
message: format!("{pm_type} mandate payment"),
connector,
}
.into()),
None => Err(domain_types::errors::ConnectorError::NotSupported {
message: " mandate payment".to_string(),
connector,
}
.into()),
}
}
/// fn validate_psync_reference_id
fn validate_psync_reference_id(
&self,
data: &PaymentsSyncData,
_is_three_ds: bool,
_status: AttemptStatus,
_connector_meta_data: Option<SecretSerdeValue>,
) -> CustomResult<(), domain_types::errors::ConnectorError> {
data.connector_transaction_id
.get_connector_transaction_id()
.change_context(domain_types::errors::ConnectorError::MissingConnectorTransactionID)
.map(|_| ())
}
/// fn is_webhook_source_verification_mandatory
fn is_webhook_source_verification_mandatory(&self) -> bool {
false
}
}
fn get_connector_payment_method_type_info(
supported_payment_method: &SupportedPaymentMethods,
payment_method: PaymentMethod,
payment_method_type: Option<PaymentMethodType>,
connector: &'static str,
) -> CustomResult<Option<PaymentMethodDetails>, domain_types::errors::ConnectorError> {
let payment_method_details =
supported_payment_method
.get(&payment_method)
.ok_or_else(|| domain_types::errors::ConnectorError::NotSupported {
message: payment_method.to_string(),
connector,
})?;
payment_method_type
.map(|pmt| {
payment_method_details.get(&pmt).cloned().ok_or_else(|| {
domain_types::errors::ConnectorError::NotSupported {
message: format!("{payment_method} {pmt}"),
connector,
}
.into()
})
})
.transpose()
}
pub fn is_mandate_supported<T: PaymentMethodDataTypes>(
selected_pmd: PaymentMethodData<T>,
payment_method_type: Option<PaymentMethodType>,
mandate_implemented_pmds: HashSet<PaymentMethodDataType>,
connector: &'static str,
) -> Result<(), error_stack::Report<domain_types::errors::ConnectorError>> {
if mandate_implemented_pmds.contains(&PaymentMethodDataType::from(selected_pmd.clone())) {
Ok(())
} else {
match payment_method_type {
Some(pm_type) => Err(domain_types::errors::ConnectorError::NotSupported {
message: format!("{pm_type} mandate payment"),
connector,
}
.into()),
None => Err(domain_types::errors::ConnectorError::NotSupported {
message: "mandate payment".to_string(),
connector,
}
.into()),
}
}
}
|
{
"chunk": null,
"crate": "interfaces",
"enum_name": null,
"file_size": 14419,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_interfaces_5453561983035210806
|
clm
|
small_file
|
// connector-service/backend/interfaces/src/lib.rs
pub mod api;
pub mod authentication;
pub mod connector_integration_v2;
pub mod connector_types;
pub mod disputes;
pub mod events;
pub mod integrity;
pub mod routing;
pub mod verification;
pub mod webhooks;
|
{
"chunk": null,
"crate": "interfaces",
"enum_name": null,
"file_size": 206,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_interfaces_5771632197509749618
|
clm
|
small_file
|
// connector-service/backend/interfaces/src/disputes.rs
//! Disputes interface
use common_utils::types::StringMinorUnit;
use time::PrimitiveDateTime;
/// struct DisputePayload
#[derive(Default, Debug)]
pub struct DisputePayload {
/// amount
pub amount: StringMinorUnit,
/// currency
pub currency: common_enums::enums::Currency,
/// dispute_stage
pub dispute_stage: common_enums::enums::DisputeStage,
/// connector_status
pub connector_status: String,
/// connector_dispute_id
pub connector_dispute_id: String,
/// connector_reason
pub connector_reason: Option<String>,
/// connector_reason_code
pub connector_reason_code: Option<String>,
/// challenge_required_by
pub challenge_required_by: Option<PrimitiveDateTime>,
/// created_at
pub created_at: Option<PrimitiveDateTime>,
/// updated_at
pub updated_at: Option<PrimitiveDateTime>,
}
|
{
"chunk": null,
"crate": "interfaces",
"enum_name": null,
"file_size": 861,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_interfaces_3630394773618043277
|
clm
|
small_file
|
// connector-service/backend/interfaces/src/webhooks.rs
use common_utils::{crypto, ext_traits::ValueExt, CustomResult};
use domain_types::connector_types::ConnectorWebhookSecrets;
use error_stack::ResultExt;
use hyperswitch_masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::api::{ApplicationResponse, ConnectorCommon};
#[derive(Debug)]
pub struct IncomingWebhookRequestDetails<'a> {
/// method
pub method: http::Method,
/// uri
pub uri: http::Uri,
/// headers
pub headers: &'a actix_web::http::header::HeaderMap,
/// body
pub body: &'a [u8],
/// query_params
pub query_params: String,
}
#[derive(Debug)]
pub enum IncomingWebhookFlowError {
/// Resource not found for the webhook
ResourceNotFound,
/// Internal error for the webhook
InternalError,
}
/// Trait defining incoming webhook
#[async_trait::async_trait]
pub trait IncomingWebhook: ConnectorCommon + Sync {
/// fn get_webhook_body_decoding_algorithm
fn get_webhook_body_decoding_algorithm(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::DecodeMessage + Send>, domain_types::errors::ConnectorError>
{
Ok(Box::new(crypto::NoAlgorithm))
}
/// fn get_webhook_body_decoding_message
fn get_webhook_body_decoding_message(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Vec<u8>, domain_types::errors::ConnectorError> {
Ok(request.body.to_vec())
}
/// fn decode_webhook_body
async fn decode_webhook_body(
&self,
request: &IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
connector_name: &str,
) -> CustomResult<Vec<u8>, domain_types::errors::ConnectorError> {
let algorithm = self.get_webhook_body_decoding_algorithm(request)?;
let message = self
.get_webhook_body_decoding_message(request)
.change_context(domain_types::errors::ConnectorError::WebhookBodyDecodingFailed)?;
let secret = self
.get_webhook_source_verification_merchant_secret(
merchant_id,
connector_name,
connector_webhook_details,
)
.await
.change_context(
domain_types::errors::ConnectorError::WebhookSourceVerificationFailed,
)?;
algorithm
.decode_message(&secret.secret, message.into())
.change_context(domain_types::errors::ConnectorError::WebhookBodyDecodingFailed)
}
/// fn get_webhook_source_verification_algorithm
fn get_webhook_source_verification_algorithm(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, domain_types::errors::ConnectorError>
{
Ok(Box::new(crypto::NoAlgorithm))
}
/// fn get_webhook_source_verification_merchant_secret
async fn get_webhook_source_verification_merchant_secret(
&self,
merchant_id: &common_utils::id_type::MerchantId,
connector_name: &str,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<ConnectorWebhookSecrets, domain_types::errors::ConnectorError> {
let debug_suffix =
format!("For merchant_id: {merchant_id:?}, and connector_name: {connector_name}");
let default_secret = "default_secret".to_string();
let merchant_secret = match connector_webhook_details {
Some(merchant_connector_webhook_details) => {
let connector_webhook_details = merchant_connector_webhook_details
.parse_value::<MerchantConnectorWebhookDetails>(
"MerchantConnectorWebhookDetails",
)
.change_context_lazy(|| {
domain_types::errors::ConnectorError::WebhookSourceVerificationFailed
})
.attach_printable_lazy(|| {
format!(
"Deserializing MerchantConnectorWebhookDetails failed {debug_suffix}"
)
})?;
ConnectorWebhookSecrets {
secret: connector_webhook_details
.merchant_secret
.expose()
.into_bytes(),
additional_secret: connector_webhook_details.additional_secret,
}
}
None => ConnectorWebhookSecrets {
secret: default_secret.into_bytes(),
additional_secret: None,
},
};
//need to fetch merchant secret from config table with caching in future for enhanced performance
//If merchant has not set the secret for webhook source verification, "default_secret" is returned.
//So it will fail during verification step and goes to psync flow.
Ok(merchant_secret)
}
/// fn get_webhook_source_verification_signature
fn get_webhook_source_verification_signature(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, domain_types::errors::ConnectorError> {
Ok(Vec::new())
}
/// fn get_webhook_source_verification_message
fn get_webhook_source_verification_message(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, domain_types::errors::ConnectorError> {
Ok(Vec::new())
}
/// fn verify_webhook_source
async fn verify_webhook_source(
&self,
request: &IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>,
connector_name: &str,
) -> CustomResult<bool, domain_types::errors::ConnectorError> {
let algorithm = self
.get_webhook_source_verification_algorithm(request)
.change_context(
domain_types::errors::ConnectorError::WebhookSourceVerificationFailed,
)?;
let connector_webhook_secrets = self
.get_webhook_source_verification_merchant_secret(
merchant_id,
connector_name,
connector_webhook_details,
)
.await
.change_context(
domain_types::errors::ConnectorError::WebhookSourceVerificationFailed,
)?;
let signature = self
.get_webhook_source_verification_signature(request, &connector_webhook_secrets)
.change_context(
domain_types::errors::ConnectorError::WebhookSourceVerificationFailed,
)?;
let message = self
.get_webhook_source_verification_message(
request,
merchant_id,
&connector_webhook_secrets,
)
.change_context(
domain_types::errors::ConnectorError::WebhookSourceVerificationFailed,
)?;
algorithm
.verify_signature(&connector_webhook_secrets.secret, &signature, &message)
.change_context(domain_types::errors::ConnectorError::WebhookSourceVerificationFailed)
}
/// fn get_webhook_event_type
fn get_webhook_event_type(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<IncomingWebhookEvent, domain_types::errors::ConnectorError>;
/// fn get_webhook_resource_object
fn get_webhook_resource_object(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<
Box<dyn hyperswitch_masking::ErasedMaskSerialize>,
domain_types::errors::ConnectorError,
>;
/// fn get_webhook_api_response
fn get_webhook_api_response(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
_error_kind: Option<IncomingWebhookFlowError>,
) -> CustomResult<ApplicationResponse<serde_json::Value>, domain_types::errors::ConnectorError>
{
Ok(ApplicationResponse::StatusOk)
}
/// fn get_dispute_details
fn get_dispute_details(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<crate::disputes::DisputePayload, domain_types::errors::ConnectorError> {
Err(domain_types::errors::ConnectorError::NotImplemented(
"get_dispute_details method".to_string(),
)
.into())
}
/// fn get_external_authentication_details
fn get_external_authentication_details(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<
crate::authentication::ExternalAuthenticationPayload,
domain_types::errors::ConnectorError,
> {
Err(domain_types::errors::ConnectorError::NotImplemented(
"get_external_authentication_details method".to_string(),
)
.into())
}
/// fn get_mandate_details
fn get_mandate_details(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<
Option<domain_types::router_flow_types::ConnectorMandateDetails>,
domain_types::errors::ConnectorError,
> {
Ok(None)
}
/// fn get_network_txn_id
fn get_network_txn_id(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<
Option<domain_types::router_flow_types::ConnectorNetworkTxnId>,
domain_types::errors::ConnectorError,
> {
Ok(None)
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Copy)]
#[serde(rename_all = "snake_case")]
pub enum IncomingWebhookEvent {
/// Authorization + Capture success
PaymentIntentFailure,
/// Authorization + Capture failure
PaymentIntentSuccess,
PaymentIntentProcessing,
PaymentIntentPartiallyFunded,
PaymentIntentCancelled,
PaymentIntentCancelFailure,
PaymentIntentAuthorizationSuccess,
PaymentIntentAuthorizationFailure,
PaymentIntentCaptureSuccess,
PaymentIntentCaptureFailure,
PaymentActionRequired,
EventNotSupported,
SourceChargeable,
SourceTransactionCreated,
RefundFailure,
RefundSuccess,
DisputeOpened,
DisputeExpired,
DisputeAccepted,
DisputeCancelled,
DisputeChallenged,
// dispute has been successfully challenged by the merchant
DisputeWon,
// dispute has been unsuccessfully challenged
DisputeLost,
MandateActive,
MandateRevoked,
EndpointVerification,
ExternalAuthenticationARes,
FrmApproved,
FrmRejected,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct MerchantConnectorWebhookDetails {
pub merchant_secret: Secret<String>,
pub additional_secret: Option<Secret<String>>,
}
|
{
"chunk": null,
"crate": "interfaces",
"enum_name": null,
"file_size": 11267,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_interfaces_2565298324350207870
|
clm
|
small_file
|
// connector-service/backend/interfaces/src/connector_integration_v2.rs
//! definition of the new connector integration trait
use common_utils::{
events,
request::{Method, Request, RequestBuilder, RequestContent},
CustomResult,
};
use domain_types::{router_data::ErrorResponse, router_data_v2::RouterDataV2};
use hyperswitch_masking::Maskable;
use serde_json::json;
use crate::{
api::{self},
verification::SourceVerification,
};
/// alias for Box of a type that implements trait ConnectorIntegrationV2
pub type BoxedConnectorIntegrationV2<'a, Flow, ResourceCommonData, Req, Resp> =
Box<&'a (dyn ConnectorIntegrationV2<Flow, ResourceCommonData, Req, Resp> + Send + Sync)>;
/// trait with a function that returns BoxedConnectorIntegrationV2
pub trait ConnectorIntegrationAnyV2<Flow, ResourceCommonData, Req, Resp>:
Send + Sync + 'static
{
/// function what returns BoxedConnectorIntegrationV2
fn get_connector_integration_v2(
&self,
) -> BoxedConnectorIntegrationV2<'_, Flow, ResourceCommonData, Req, Resp>;
}
impl<S, Flow, ResourceCommonData, Req, Resp>
ConnectorIntegrationAnyV2<Flow, ResourceCommonData, Req, Resp> for S
where
S: ConnectorIntegrationV2<Flow, ResourceCommonData, Req, Resp> + Send + Sync,
{
fn get_connector_integration_v2(
&self,
) -> BoxedConnectorIntegrationV2<'_, Flow, ResourceCommonData, Req, Resp> {
Box::new(self)
}
}
/// The new connector integration trait with an additional ResourceCommonData generic parameter
pub trait ConnectorIntegrationV2<Flow, ResourceCommonData, Req, Resp>:
ConnectorIntegrationAnyV2<Flow, ResourceCommonData, Req, Resp>
+ Sync
+ api::ConnectorCommon
+ SourceVerification<Flow, ResourceCommonData, Req, Resp>
{
/// returns a vec of tuple of header key and value
fn get_headers(
&self,
_req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>,
) -> CustomResult<Vec<(String, Maskable<String>)>, domain_types::errors::ConnectorError> {
Ok(vec![])
}
/// returns content type
fn get_content_type(&self) -> &'static str {
mime::APPLICATION_JSON.essence_str()
}
/// primarily used when creating signature based on request method of payment flow
fn get_http_method(&self) -> Method {
Method::Post
}
/// returns url
fn get_url(
&self,
_req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>,
) -> CustomResult<String, domain_types::errors::ConnectorError> {
// metrics::UNIMPLEMENTED_FLOW
// .add(1, router_env::metric_attributes!(("connector", self.id()))); // TODO: discuss env
Ok(String::new())
}
/// returns request body
fn get_request_body(
&self,
_req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>,
) -> CustomResult<Option<RequestContent>, domain_types::errors::ConnectorError> {
Ok(None)
}
/// returns form data
fn get_request_form_data(
&self,
_req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>,
) -> CustomResult<Option<reqwest::multipart::Form>, domain_types::errors::ConnectorError> {
Ok(None)
}
/// builds the request and returns it
fn build_request_v2(
&self,
req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>,
) -> CustomResult<Option<Request>, domain_types::errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(self.get_http_method())
.url(self.get_url(req)?.as_str())
.attach_default_headers()
.headers(self.get_headers(req)?)
.set_optional_body(self.get_request_body(req)?)
.add_certificate(self.get_certificate(req)?)
.add_certificate_key(self.get_certificate_key(req)?)
.build(),
))
}
/// accepts the raw api response and decodes it
fn handle_response_v2(
&self,
data: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>,
event_builder: Option<&mut events::Event>,
_res: domain_types::router_response_types::Response,
) -> CustomResult<
RouterDataV2<Flow, ResourceCommonData, Req, Resp>,
domain_types::errors::ConnectorError,
>
where
Flow: Clone,
ResourceCommonData: Clone,
Req: Clone,
Resp: Clone,
{
if let Some(e) = event_builder {
e.set_connector_response(&json!({"error": "Not Implemented"}))
}
Ok(data.clone())
}
/// accepts the raw api error response and decodes it
fn get_error_response_v2(
&self,
res: domain_types::router_response_types::Response,
event_builder: Option<&mut events::Event>,
) -> CustomResult<ErrorResponse, domain_types::errors::ConnectorError> {
if let Some(event) = event_builder {
event.set_connector_response(&json!({"error": "Error response parsing not implemented", "status_code": res.status_code}))
}
Ok(ErrorResponse::get_not_implemented())
}
/// accepts the raw 5xx error response and decodes it
fn get_5xx_error_response(
&self,
res: domain_types::router_response_types::Response,
event_builder: Option<&mut events::Event>,
) -> CustomResult<ErrorResponse, domain_types::errors::ConnectorError> {
let error_message = match res.status_code {
500 => "internal_server_error",
501 => "not_implemented",
502 => "bad_gateway",
503 => "service_unavailable",
504 => "gateway_timeout",
505 => "http_version_not_supported",
506 => "variant_also_negotiates",
507 => "insufficient_storage",
508 => "loop_detected",
510 => "not_extended",
511 => "network_authentication_required",
_ => "unknown_error",
};
if let Some(event) = event_builder {
event.set_connector_response(
&json!({"error": error_message, "status_code": res.status_code}),
)
}
Ok(ErrorResponse {
code: res.status_code.to_string(),
message: error_message.to_string(),
reason: String::from_utf8(res.response.to_vec()).ok(),
status_code: res.status_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
// whenever capture sync is implemented at the connector side, this method should be overridden
/// retunes the capture sync method
// fn get_multiple_capture_sync_method(
// &self,
// ) -> CustomResult<api::CaptureSyncMethod, domain_types::errors::ConnectorError> {
// Err(domain_types::errors::ConnectorError::NotImplemented("multiple capture sync".into()).into())
// }
/// returns certificate string
fn get_certificate(
&self,
_req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>,
) -> CustomResult<
Option<hyperswitch_masking::Secret<String>>,
domain_types::errors::ConnectorError,
> {
Ok(None)
}
/// returns private key string
fn get_certificate_key(
&self,
_req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>,
) -> CustomResult<
Option<hyperswitch_masking::Secret<String>>,
domain_types::errors::ConnectorError,
> {
Ok(None)
}
}
|
{
"chunk": null,
"crate": "interfaces",
"enum_name": null,
"file_size": 7533,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_interfaces_-6275142288305207495
|
clm
|
small_file
|
// connector-service/backend/interfaces/src/authentication.rs
//! Authentication interface
/// struct ExternalAuthenticationPayload
#[derive(Clone, serde::Deserialize, Debug, serde::Serialize, PartialEq, Eq)]
pub struct ExternalAuthenticationPayload {
/// trans_status
pub trans_status: common_enums::TransactionStatus,
/// authentication_value
pub authentication_value: Option<hyperswitch_masking::Secret<String>>,
/// eci
pub eci: Option<String>,
}
|
{
"chunk": null,
"crate": "interfaces",
"enum_name": null,
"file_size": 414,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_interfaces_-8407711303800421270
|
clm
|
small_file
|
// connector-service/backend/interfaces/src/routing.rs
use common_enums::RoutableConnectors;
use utoipa::ToSchema;
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(from = "RoutableChoiceSerde", into = "RoutableChoiceSerde")]
pub struct RoutableConnectorChoice {
#[serde(skip)]
pub choice_kind: RoutableChoiceKind,
pub connector: RoutableConnectors,
#[schema(value_type = Option<String>)]
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, PartialEq)]
pub enum RoutableChoiceKind {
OnlyConnector,
FullStruct,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(untagged)]
pub enum RoutableChoiceSerde {
OnlyConnector(Box<RoutableConnectors>),
FullStruct {
connector: RoutableConnectors,
merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
},
}
impl From<RoutableChoiceSerde> for RoutableConnectorChoice {
fn from(value: RoutableChoiceSerde) -> Self {
match value {
RoutableChoiceSerde::OnlyConnector(connector) => Self {
choice_kind: RoutableChoiceKind::OnlyConnector,
connector: *connector,
merchant_connector_id: None,
},
RoutableChoiceSerde::FullStruct {
connector,
merchant_connector_id,
} => Self {
choice_kind: RoutableChoiceKind::FullStruct,
connector,
merchant_connector_id,
},
}
}
}
impl From<RoutableConnectorChoice> for RoutableChoiceSerde {
fn from(value: RoutableConnectorChoice) -> Self {
match value.choice_kind {
RoutableChoiceKind::OnlyConnector => Self::OnlyConnector(Box::new(value.connector)),
RoutableChoiceKind::FullStruct => Self::FullStruct {
connector: value.connector,
merchant_connector_id: value.merchant_connector_id,
},
}
}
}
|
{
"chunk": null,
"crate": "interfaces",
"enum_name": null,
"file_size": 2048,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_interfaces_6351965063930718391
|
clm
|
small_file
|
// connector-service/backend/interfaces/src/api.rs
use common_enums::CurrencyUnit;
use common_utils::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
events, CustomResult,
};
use domain_types::{
api::{GenericLinks, PaymentLinkAction, RedirectionFormData},
payment_address::RedirectionResponse,
router_data::{ConnectorAuthType, ErrorResponse},
types::Connectors,
};
use hyperswitch_masking;
pub trait ConnectorCommon {
/// Name of the connector (in lowercase).
fn id(&self) -> &'static str;
/// Connector accepted currency unit as either "Base" or "Minor"
fn get_currency_unit(&self) -> CurrencyUnit {
CurrencyUnit::Minor // Default implementation should be remove once it is implemented in all connectors
}
/// HTTP header used for authorization.
fn get_auth_header(
&self,
_auth_type: &ConnectorAuthType,
) -> CustomResult<
Vec<(String, hyperswitch_masking::Maskable<String>)>,
domain_types::errors::ConnectorError,
> {
Ok(Vec::new())
}
/// HTTP `Content-Type` to be used for POST requests.
/// Defaults to `application/json`.
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
// FIXME write doc - think about this
// fn headers(&self) -> Vec<(&str, &str)>;
/// The base URL for interacting with the connector's API.
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str;
/// common error response for a connector if it is same in all case
fn build_error_response(
&self,
res: domain_types::router_response_types::Response,
_event_builder: Option<&mut events::Event>,
) -> CustomResult<ErrorResponse, domain_types::errors::ConnectorError> {
Ok(ErrorResponse {
status_code: res.status_code,
code: NO_ERROR_CODE.to_string(),
message: NO_ERROR_MESSAGE.to_string(),
reason: None,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
}
#[derive(Debug, Eq, PartialEq)]
pub enum ApplicationResponse<R> {
Json(R),
StatusOk,
TextPlain(String),
JsonForRedirection(RedirectionResponse),
Form(Box<RedirectionFormData>),
PaymentLinkForm(Box<PaymentLinkAction>),
FileData((Vec<u8>, mime::Mime)),
JsonWithHeaders((R, Vec<(String, hyperswitch_masking::Maskable<String>)>)),
GenericLinkForm(Box<GenericLinks>),
}
|
{
"chunk": null,
"crate": "interfaces",
"enum_name": null,
"file_size": 2523,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_interfaces_-1715344998119786497
|
clm
|
small_file
|
// connector-service/backend/interfaces/src/events/routing_api_logs.rs
//! Routing API logs interface
use std::fmt;
use common_utils::request::Method;
use serde::Serialize;
use serde_json::json;
use time::OffsetDateTime;
use tracing_actix_web::RequestId;
use crate::routing::RoutableConnectorChoice;
/// RoutingEngine enum
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum RoutingEngine {
/// Dynamo for routing
IntelligentRouter,
/// Decision engine for routing
DecisionEngine,
}
/// Method type enum
#[derive(Debug, Clone, Copy, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ApiMethod {
/// grpc call
Grpc,
/// Rest call
Rest(Method),
}
impl fmt::Display for ApiMethod {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Grpc => write!(f, "Grpc"),
Self::Rest(method) => write!(f, "Rest ({method})"),
}
}
}
#[derive(Debug, Serialize)]
/// RoutingEvent type
pub struct RoutingEvent {
// tenant_id: common_utils::id_type::TenantId,
routable_connectors: String,
payment_connector: Option<String>,
flow: String,
request: String,
response: Option<String>,
error: Option<String>,
url: String,
method: String,
payment_id: String,
profile_id: common_utils::id_type::ProfileId,
merchant_id: common_utils::id_type::MerchantId,
created_at: i128,
status_code: Option<u16>,
request_id: String,
routing_engine: RoutingEngine,
routing_approach: Option<String>,
}
impl RoutingEvent {
/// fn new RoutingEvent
#[allow(clippy::too_many_arguments)]
pub fn new(
// tenant_id: common_utils::id_type::TenantId,
routable_connectors: String,
flow: &str,
request: serde_json::Value,
url: String,
method: ApiMethod,
payment_id: String,
profile_id: common_utils::id_type::ProfileId,
merchant_id: common_utils::id_type::MerchantId,
request_id: Option<RequestId>,
routing_engine: RoutingEngine,
) -> Self {
Self {
// tenant_id,
routable_connectors,
flow: flow.to_string(),
request: request.to_string(),
response: None,
error: None,
url,
method: method.to_string(),
payment_id,
profile_id,
merchant_id,
created_at: OffsetDateTime::now_utc().unix_timestamp_nanos(),
status_code: None,
request_id: request_id
.map(|i| i.as_hyphenated().to_string())
.unwrap_or("NO_REQUEST_ID".to_string()),
routing_engine,
payment_connector: None,
routing_approach: None,
}
}
/// fn set_response_body
pub fn set_response_body<T: Serialize>(&mut self, response: &T) {
match hyperswitch_masking::masked_serialize(response) {
Ok(masked) => {
self.response = Some(masked.to_string());
}
Err(er) => self.set_error(json!({"error": er.to_string()})),
}
}
/// fn set_error_response_body
pub fn set_error_response_body<T: Serialize>(&mut self, response: &T) {
match hyperswitch_masking::masked_serialize(response) {
Ok(masked) => {
self.error = Some(masked.to_string());
}
Err(er) => self.set_error(json!({"error": er.to_string()})),
}
}
/// fn set_error
pub fn set_error(&mut self, error: serde_json::Value) {
self.error = Some(error.to_string());
}
/// set response status code
pub fn set_status_code(&mut self, code: u16) {
self.status_code = Some(code);
}
/// set response status code
pub fn set_routable_connectors(&mut self, connectors: Vec<RoutableConnectorChoice>) {
let connectors = connectors
.into_iter()
.map(|c| {
format!(
"{:?}:{:?}",
c.connector,
c.merchant_connector_id
.map(|id| id.get_string_repr().to_string())
.unwrap_or(String::from(""))
)
})
.collect::<Vec<_>>()
.join(",");
self.routable_connectors = connectors;
}
/// set payment connector
pub fn set_payment_connector(&mut self, connector: RoutableConnectorChoice) {
self.payment_connector = Some(format!(
"{:?}:{:?}",
connector.connector,
connector
.merchant_connector_id
.map(|id| id.get_string_repr().to_string())
.unwrap_or(String::from(""))
));
}
/// set routing approach
pub fn set_routing_approach(&mut self, approach: String) {
self.routing_approach = Some(approach);
}
/// Returns the request ID of the event.
pub fn get_request_id(&self) -> &str {
&self.request_id
}
/// Returns the merchant ID of the event.
pub fn get_merchant_id(&self) -> &str {
self.merchant_id.get_string_repr()
}
/// Returns the payment ID of the event.
pub fn get_payment_id(&self) -> &str {
&self.payment_id
}
/// Returns the profile ID of the event.
pub fn get_profile_id(&self) -> &str {
self.profile_id.get_string_repr()
}
}
|
{
"chunk": null,
"crate": "interfaces",
"enum_name": null,
"file_size": 5400,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_interfaces_-4718366131698857213
|
clm
|
small_file
|
// connector-service/backend/interfaces/src/events/connector_api_logs.rs
//! Connector API logs interface
use common_utils::request::Method;
use serde::Serialize;
use serde_json::json;
use time::OffsetDateTime;
use tracing_actix_web::RequestId;
/// struct ConnectorEvent
#[derive(Debug, Serialize)]
pub struct ConnectorEvent {
// tenant_id: common_utils::id_type::TenantId,
connector_name: String,
flow: String,
request: String,
masked_response: Option<String>,
error: Option<String>,
url: String,
method: String,
payment_id: String,
merchant_id: common_utils::id_type::MerchantId,
created_at: i128,
/// Connector Event Request ID
pub request_id: String,
latency: u128,
refund_id: Option<String>,
dispute_id: Option<String>,
status_code: u16,
}
impl ConnectorEvent {
/// fn new ConnectorEvent
#[allow(clippy::too_many_arguments)]
pub fn new(
// tenant_id: common_utils::id_type::TenantId,
connector_name: String,
flow: &str,
request: serde_json::Value,
url: String,
method: Method,
payment_id: String,
merchant_id: common_utils::id_type::MerchantId,
request_id: Option<&RequestId>,
latency: u128,
refund_id: Option<String>,
dispute_id: Option<String>,
status_code: u16,
) -> Self {
Self {
// tenant_id,
connector_name,
flow: flow
.rsplit_once("::")
.map(|(_, s)| s)
.unwrap_or(flow)
.to_string(),
request: request.to_string(),
masked_response: None,
error: None,
url,
method: method.to_string(),
payment_id,
merchant_id,
created_at: OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000,
request_id: request_id
.map(|i| i.as_hyphenated().to_string())
.unwrap_or("NO_REQUEST_ID".to_string()),
latency,
refund_id,
dispute_id,
status_code,
}
}
/// fn set_response_body
pub fn set_response_body<T: Serialize>(&mut self, response: &T) {
match hyperswitch_masking::masked_serialize(response) {
Ok(masked) => {
self.masked_response = Some(masked.to_string());
}
Err(er) => self.set_error(json!({"error": er.to_string()})),
}
}
/// fn set_error_response_body
pub fn set_error_response_body<T: Serialize>(&mut self, response: &T) {
match hyperswitch_masking::masked_serialize(response) {
Ok(masked) => {
self.error = Some(masked.to_string());
}
Err(er) => self.set_error(json!({"error": er.to_string()})),
}
}
/// fn set_error
pub fn set_error(&mut self, error: serde_json::Value) {
self.error = Some(error.to_string());
}
}
|
{
"chunk": null,
"crate": "interfaces",
"enum_name": null,
"file_size": 2932,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_rust-grpc-client_1726435839525134115
|
clm
|
small_file
|
// connector-service/sdk/rust-grpc-client/src/lib.rs
pub use grpc_api_types::{health_check, payments};
|
{
"chunk": null,
"crate": "rust-grpc-client",
"enum_name": null,
"file_size": 50,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_small_file_example-rs_-6592229781991902862
|
clm
|
small_file
|
// connector-service/examples/example-rs/src/main.rs
use rust_grpc_client::payments::{self, payment_service_client::PaymentServiceClient,Address, PhoneDetails};
use std::error::Error;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
// Get the URL from command line arguments
let args = std::env::args().collect::<Vec<_>>();
if args.len() < 2 {
eprintln!("Usage: {} <url> [operation]", args[0]);
eprintln!("Operations: authorize, sync");
std::process::exit(1);
}
let url = &args[1];
let operation = args.get(2).map(|s| s.as_str()).unwrap_or("authorize");
let response = match operation {
"authorize" => {
let auth_response = make_payment_authorization_request(url.to_string()).await?;
format!("Authorization Response: {:?}", auth_response)
}
"sync" => {
let sync_response = make_payment_sync_request(url.to_string()).await?;
format!("Sync Response: {:?}", sync_response)
}
_ => {
eprintln!(
"Unknown operation: {}. Use 'authorize' or 'sync'.",
operation
);
std::process::exit(1);
}
};
// Print the response
println!("{}", response);
Ok(())
}
/// Creates a gRPC client and sends a payment authorization request
async fn make_payment_authorization_request(
url: String,
) -> Result<tonic::Response<payments::PaymentsAuthorizeResponse>, Box<dyn Error>> {
// Create a gRPC client
let mut client = PaymentServiceClient::connect(url).await?;
let api_key = std::env::var("API_KEY").unwrap_or_else(|_| "default_api_key".to_string());
let key1 = std::env::var("KEY1").unwrap_or_else(|_| "default_key1".to_string());
println!("api_key is {} and key1 is {}", api_key,key1);
// Create a request with the updated values
let request = payments::PaymentsAuthorizeRequest {
amount: 1000 as i64,
currency: payments::Currency::Usd as i32,
// connector: payments::Connector::Adyen as i32,
// auth_creds: Some(payments::AuthType {
// auth_details: Some(payments::auth_type::AuthDetails::BodyKey( // Changed to BodyKey
// payments::BodyKey {
// api_key,
// key1
// },
// )),
// }),
// connector: payments::Connector::Adyen as i32,
// auth_creds: Some(payments::AuthType {
// auth_details: Some(payments::auth_type::AuthDetails::BodyKey( // Changed to BodyKey
// payments::BodyKey {
// api_key,
// key1
// },
// )),
// }),
payment_method: payments::PaymentMethod::Card as i32,
payment_method_data: Some(payments::PaymentMethodData {
data: Some(payments::payment_method_data::Data::Card(payments::Card {
card_number: "5123456789012346".to_string(), // Updated card number
card_exp_month: "03".to_string(),
card_exp_year: "2030".to_string(),
card_cvc: "100".to_string(), // Updated CVC
..Default::default()
})),
}),
// connector_customer: Some("customer_12345".to_string()),
// return_url: Some("www.google.com".to_string()),
address:Some(payments::PaymentAddress{
shipping:None,
billing:Some(Address { address: None, phone: Some(PhoneDetails { number: Some("1234567890".to_string()), country_code: Some("+1".to_string()) }), email: Some("sweta.sharma@juspay.in".to_string()) }),
unified_payment_method_billing: None,
payment_method_billing: None
}),
auth_type: payments::AuthenticationType::ThreeDs as i32,
connector_request_reference_id: "ref_12345".to_string(),
enrolled_for_3ds: true,
request_incremental_authorization: false,
minor_amount: 1000 as i64,
email: Some("sweta.sharma@juspay.in".to_string()),
connector_customer: Some("cus_1234".to_string()),
return_url: Some("www.google.com".to_string()),
browser_info: Some(payments::BrowserInformation {
// Added browser_info
user_agent: Some("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)".to_string()),
accept_header: Some(
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8".to_string(),
),
language: Some("en-US".to_string()),
color_depth: Some(24),
screen_height: Some(1080),
screen_width: Some(1920),
java_enabled: Some(false),
..Default::default()
}),
..Default::default()
};
let mut request = tonic::Request::new(request);
request
.metadata_mut()
.append("x-connector", "adyen".parse().unwrap());
request
.metadata_mut()
.append("x-auth", "body-key".parse().unwrap());
request
.metadata_mut()
.append("x-api-key", api_key.parse().unwrap());
request
.metadata_mut()
.append("x-key1", key1.parse().unwrap());
// Send the request
let response = client.payment_authorize(request).await?;
Ok(response)
}
/// Creates a gRPC client and sends a payment sync request
async fn make_payment_sync_request(
url: String,
) -> Result<tonic::Response<payments::PaymentsSyncResponse>, Box<dyn Error>> {
// Create a gRPC client
let mut client = PaymentServiceClient::connect(url).await?;
let resource_id =
std::env::var("RESOURCE_ID").unwrap_or_else(|_| "pay_QHj9Thiy5mCC4Y".to_string());
let api_key = std::env::var("API_KEY").unwrap_or_else(|_| "default_api_key".to_string());
let key1 = std::env::var("KEY1").unwrap_or_else(|_| "default_key1".to_string());
// Create a request
let request = payments::PaymentsSyncRequest {
// connector: payments::Connector::Razorpay as i32,
// auth_creds: Some(payments::AuthType {
// auth_details: Some(payments::auth_type::AuthDetails::BodyKey(
// payments::BodyKey {
// api_key,
// key1
// },
// )),
// }),
resource_id,
connector_request_reference_id: Some("conn_req_abc".to_string()),
};
let mut request = tonic::Request::new(request);
request
.metadata_mut()
.append("x-connector", "razorpay".parse().unwrap());
request
.metadata_mut()
.append("x-auth", "body-key".parse().unwrap());
request
.metadata_mut()
.append("x-api-key", api_key.parse().unwrap());
request
.metadata_mut()
.append("x-key1", key1.parse().unwrap());
let response = client.payment_sync(request).await?;
Ok(response)
}
|
{
"chunk": null,
"crate": "example-rs",
"enum_name": null,
"file_size": 6870,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_module_ucs_common_utils_-4191580895164688042
|
clm
|
module
|
// connector-service/backend/common_utils/src/new_types.rs
// Crate: ucs_common_utils
// Structs: MaskedBankAccount
// Enums:
|
{
"chunk": null,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 0,
"num_items": null,
"num_structs": 1,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_module_ucs_common_utils_-6020438553597064532
|
clm
|
module
|
// connector-service/backend/common_utils/src/request.rs
// Crate: ucs_common_utils
// Structs: Request, RequestBuilder
// Enums: Method, ContentType, RequestContent
|
{
"chunk": null,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 3,
"num_items": null,
"num_structs": 2,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_module_ucs_common_utils_4276938976373144801
|
clm
|
module
|
// connector-service/backend/common_utils/src/consts.rs
// Crate: ucs_common_utils
// Structs:
// Enums: Env
|
{
"chunk": null,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 1,
"num_items": null,
"num_structs": 0,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_module_ucs_common_utils_1414821583984559341
|
clm
|
module
|
// connector-service/backend/common_utils/src/types.rs
// Crate: ucs_common_utils
// Structs: StringMinorUnitForConnector, StringMajorUnitForCore, StringMajorUnitForConnector, FloatMajorUnitForConnector, MinorUnitForConnector, MinorUnit, StringMinorUnit, FloatMajorUnit, StringMajorUnit, TimeRange, SemanticVersion
// Enums:
|
{
"chunk": null,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 0,
"num_items": null,
"num_structs": 11,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_module_ucs_common_utils_-4813005579221307816
|
clm
|
module
|
// connector-service/backend/common_utils/src/events.rs
// Crate: ucs_common_utils
// Structs: MaskedSerdeValue, Event, EventConfig
// Enums: ApiEventsType, FlowName, EventStage
|
{
"chunk": null,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 3,
"num_items": null,
"num_structs": 3,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_module_ucs_common_utils_-1874607272906183358
|
clm
|
module
|
// connector-service/backend/common_utils/src/metadata.rs
// Crate: ucs_common_utils
// Structs: HeaderMaskingConfig, Config, MaskedMetadata
// Enums:
|
{
"chunk": null,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 0,
"num_items": null,
"num_structs": 3,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_module_ucs_common_utils_7052884170592430104
|
clm
|
module
|
// connector-service/backend/common_utils/src/lib.rs
// Crate: ucs_common_utils
// Structs: DDMMYYYY, YYYYMMDD, YYYYMMDDHHmmss, DateTime
// Enums: DateFormat
|
{
"chunk": null,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 1,
"num_items": null,
"num_structs": 4,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_module_ucs_common_utils_-5627216939917239271
|
clm
|
module
|
// connector-service/backend/common_utils/src/global_id.rs
// Crate: ucs_common_utils
// Structs: GlobalId, CellId
// Enums: GlobalEntity, CellIdError, GlobalIdError
|
{
"chunk": null,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 3,
"num_items": null,
"num_structs": 2,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_module_ucs_common_utils_6732291692182265096
|
clm
|
module
|
// connector-service/backend/common_utils/src/pii.rs
// Crate: ucs_common_utils
// Structs: Email
// Enums: EmailStrategy, IpAddress, UpiVpaMaskingStrategy, EncryptionStrategy
|
{
"chunk": null,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 4,
"num_items": null,
"num_structs": 1,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_module_ucs_common_utils_2179811235784210369
|
clm
|
module
|
// connector-service/backend/common_utils/src/errors.rs
// Crate: ucs_common_utils
// Structs: IntegrityCheckError
// Enums: ParsingError, ValidationError, PercentageError, CryptoError, EventPublisherError
|
{
"chunk": null,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 5,
"num_items": null,
"num_structs": 1,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_module_ucs_common_utils_45732705880422454
|
clm
|
module
|
// connector-service/backend/common_utils/src/lineage.rs
// Crate: ucs_common_utils
// Structs: LineageIds
// Enums: LineageParseError
|
{
"chunk": null,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 1,
"num_items": null,
"num_structs": 1,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_module_ucs_common_utils_-841769499540836508
|
clm
|
module
|
// connector-service/backend/common_utils/src/id_type.rs
// Crate: ucs_common_utils
// Structs: AlphaNumericId, AlphaNumericIdError, CustomerId, MerchantId, LengthId
// Enums: LengthIdError
|
{
"chunk": null,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 1,
"num_items": null,
"num_structs": 5,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_module_ucs_common_utils_8833799470967369792
|
clm
|
module
|
// connector-service/backend/common_utils/src/crypto.rs
// Crate: ucs_common_utils
// Structs: NonceSequence, NoAlgorithm, HmacSha1, HmacSha256, HmacSha512, Blake3, GcmAes256, Ed25519, Sha512, Sha256, Md5, Encryptable
// Enums:
|
{
"chunk": null,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 0,
"num_items": null,
"num_structs": 12,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_module_ucs_common_utils_2048526090272796786
|
clm
|
module
|
// connector-service/backend/common_utils/src/event_publisher.rs
// Crate: ucs_common_utils
// Structs: EventPublisher
// Enums:
|
{
"chunk": null,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 0,
"num_items": null,
"num_structs": 1,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_module_ucs_common_utils_-4895347235318218796
|
clm
|
module
|
// connector-service/backend/common_utils/src/global_id/payment_methods.rs
// Crate: ucs_common_utils
// Structs: GlobalPaymentMethodId, GlobalPaymentMethodSessionId
// Enums: GlobalPaymentMethodIdError, GlobalPaymentMethodSessionIdError
|
{
"chunk": null,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 2,
"num_items": null,
"num_structs": 2,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_module_ucs_common_utils_2591687643226154011
|
clm
|
module
|
// connector-service/backend/common_utils/src/global_id/refunds.rs
// Crate: ucs_common_utils
// Structs: GlobalRefundId
// Enums:
|
{
"chunk": null,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 0,
"num_items": null,
"num_structs": 1,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_module_connector-integration_1661134184692456114
|
clm
|
module
|
// connector-service/backend/connector-integration/src/types.rs
// Crate: connector-integration
// Structs: ConnectorData, ResponseRouterData
// Enums:
|
{
"chunk": null,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 0,
"num_items": null,
"num_structs": 2,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_module_connector-integration_-6237025837336624155
|
clm
|
module
|
// connector-service/backend/connector-integration/src/connectors/razorpay.rs
// Crate: connector-integration
// Structs: Razorpay
// Enums:
|
{
"chunk": null,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 0,
"num_items": null,
"num_structs": 1,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_module_connector-integration_3314128609778487701
|
clm
|
module
|
// connector-service/backend/connector-integration/src/connectors/razorpayv2.rs
// Crate: connector-integration
// Structs: RazorpayV2
// Enums:
|
{
"chunk": null,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 0,
"num_items": null,
"num_structs": 1,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_module_connector-integration_-7996050285594493577
|
clm
|
module
|
// connector-service/backend/connector-integration/src/connectors/macros.rs
// Crate: connector-integration
// Structs: NoRequestBody, NoRequestBodyTemplating, Bridge
// Enums:
|
{
"chunk": null,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 0,
"num_items": null,
"num_structs": 3,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_module_connector-integration_814751693867000820
|
clm
|
module
|
// connector-service/backend/connector-integration/src/connectors/helcim/transformers.rs
// Crate: connector-integration
// Structs: HelcimAuthType, HelcimPaymentsRequest, HelcimBillingAddress, HelcimInvoice, HelcimLineItems, HelcimCard, HelcimPaymentsResponse, HelcimMetaData, HelcimCaptureRequest, HelcimVoidRequest, HelcimSetupMandateRequest, HelcimRefundRequest, RefundResponse, HelcimPaymentsErrorResponse
// Enums: HelcimPaymentStatus, HelcimTransactionType, HelcimRefundTransactionType, HelcimErrorTypes, HelcimErrorResponse
|
{
"chunk": null,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 5,
"num_items": null,
"num_structs": 14,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_module_connector-integration_-5184931324552524607
|
clm
|
module
|
// connector-service/backend/connector-integration/src/connectors/braintree/transformers.rs
// Crate: connector-integration
// Structs: GenericBraintreeRequest, GenericVariableInput, BraintreeApiErrorResponse, ErrorsObject, TransactionError, CreditCardError, ErrorObject, BraintreeErrorResponse, ApiErrorResponse, BraintreeAuthType, PaymentInput, BraintreeMeta, CustomerBody, RegularTransactionBody, VaultTransactionBody, TransactionTiming, AuthResponse, PaymentMethodInfo, TransactionAuthChargeResponseBody, DataAuthResponse
// Enums: GenericBraintreeResponse, ErrorResponses, BraintreePaymentsRequest, TransactionBody, BraintreeAuthResponse, BraintreeCompleteAuthResponse, BraintreePaymentStatus, BraintreePaymentsResponse, BraintreeCompleteChargeResponse, BraintreeRefundStatus, BraintreeRSyncResponse, BraintreeTokenResponse, BraintreeRevokeMandateResponse, BraintreeCancelResponse
|
{
"chunk": null,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 14,
"num_items": null,
"num_structs": 84,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_module_connector-integration_-5409969266194052518
|
clm
|
module
|
// connector-service/backend/connector-integration/src/connectors/worldpay/response.rs
// Crate: connector-integration
// Structs: WorldpayPaymentsResponse, AuthorizedResponse, MandateToken, FraudHighRiskResponse, RefusedResponse, Advice, ThreeDsResponse, ThreeDsChallengedResponse, AuthenticationResponse, ThreeDsChallenge, CompleteThreeDsActionLink, DDCResponse, DDCToken, DDCActionLink, SelfLink, SelfLinkInner, ActionLinks, ActionLink, Fraud, WorldpayEventResponse
// Enums: WorldpayPaymentResponseFields, IssuerResponse, PaymentOutcome, FraudOutcome, EventType, RiskType, Detail, Risk, WorldpayWebhookStatus
|
{
"chunk": null,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 9,
"num_items": null,
"num_structs": 31,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_module_connector-integration_9109066662545807561
|
clm
|
module
|
// connector-service/backend/connector-integration/src/connectors/worldpay/transformers.rs
// Crate: connector-integration
// Structs: WorldpayConnectorMetadataObject, WorldpayAuthType
// Enums:
|
{
"chunk": null,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 0,
"num_items": null,
"num_structs": 2,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_module_connector-integration_426009472564931438
|
clm
|
module
|
// connector-service/backend/connector-integration/src/connectors/worldpay/requests.rs
// Crate: connector-integration
// Structs: WorldpayAuthorizeRequest, Merchant, Instruction, TokenCreation, CustomerAgreement, CardPayment, RawCardDetails, CardToken, WalletPayment, ExpiryDate, BillingAddress, Customer, ThreeDS, NetworkToken, AutoSettlement, ThreeDSRequest, ThreeDSRequestDeviceData, ThreeDSRequestChallenge, InstructionNarrative, PaymentValue
// Enums: TokenCreationType, CustomerAgreementType, StoredCardUsageType, PaymentInstrument, PaymentType, Channel, CustomerAuthentication, ThreeDSVersion, CustomerAuthType, ThreeDSRequestChannel, PaymentMethod
|
{
"chunk": null,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 11,
"num_items": null,
"num_structs": 24,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_module_connector-integration_-8005942479899491151
|
clm
|
module
|
// connector-service/backend/connector-integration/src/connectors/payu/transformers.rs
// Crate: connector-integration
// Structs: PayuAuthType, PayuPaymentRequest, PayuPaymentResponse, PayuResult, PayuUpiApp, PayuErrorResponse, PayuSyncRequest, PayuSyncResponse, PayuTransactionDetail
// Enums: PayuStatusValue
|
{
"chunk": null,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 1,
"num_items": null,
"num_structs": 9,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_module_connector-integration_-2910212303359634675
|
clm
|
module
|
// connector-service/backend/connector-integration/src/connectors/elavon/transformers.rs
// Crate: connector-integration
// Structs: ElavonAuthType, CardPaymentRequest, XMLElavonRequest, XMLPSyncRequest, XMLCaptureRequest, XMLRefundRequest, XMLRSyncRequest, PaymentResponse, ElavonErrorResponse, ElavonPaymentsResponse, ElavonCaptureResponse, ElavonRefundResponse, XmlIshResponse, XmlIshResponse, XmlIshResponse, SyncRequest, ElavonCaptureRequest, ElavonRefundRequest, ElavonRSyncResponse, ElavonPSyncResponse
// Enums: TransactionType, ElavonPaymentsRequest, SslResult, ElavonResult, TransactionSyncStatus, SyncTransactionType
|
{
"chunk": null,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 6,
"num_items": null,
"num_structs": 20,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_module_connector-integration_3522933810268649801
|
clm
|
module
|
// connector-service/backend/connector-integration/src/connectors/phonepe/transformers.rs
// Crate: connector-integration
// Structs: PhonepePaymentsRequest, PhonepePaymentRequestPayload, PhonepeDeviceContext, PhonepePaymentInstrument, PhonepeSyncRequest, PhonepeErrorResponse, PhonepePaymentsResponse, PhonepeSyncResponse, PhonepeResponseData, PhonepeInstrumentResponse, PhonepeSyncResponseData, PhonepeAuthType
// Enums:
|
{
"chunk": null,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 0,
"num_items": null,
"num_structs": 12,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_module_connector-integration_353540475883723703
|
clm
|
module
|
// connector-service/backend/connector-integration/src/connectors/novalnet/transformers.rs
// Crate: connector-integration
// Structs: NovalnetPaymentsRequestMerchant, NovalnetPaymentsRequestBilling, NovalnetPaymentsRequestCustomer, NovalnetCard, NovalnetRawCardDetails, NovalnetMandate, NovalnetGooglePay, NovalnetApplePay, NovalnetCustom, NovalnetPaymentsRequestTransaction, NovalnetPaymentsRequest, NovalnetAuthType, ResultData, NovalnetPaymentsResponseTransactionData, NovalnetPaymentsResponse, NovalnetResponseCustomer, NovalnetResponseBilling, NovalnetResponseMerchant, NovalnetAuthorizationResponse, NovalnetSyncResponseTransactionData
// Enums: NovalNetPaymentTypes, NovalNetPaymentData, NovalNetAmount, NovalnetTransactionStatus, NovalnetAPIStatus, NovalnetResponsePaymentData, CaptureType, WebhookEventType, NovalnetWebhookTransactionData, WebhookDisputeStatus
|
{
"chunk": null,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 10,
"num_items": null,
"num_structs": 45,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_module_connector-integration_-8249547783947283321
|
clm
|
module
|
// connector-service/backend/connector-integration/src/connectors/adyen/transformers.rs
// Crate: connector-integration
// Structs: Amount, AdyenCard, AdyenBrowserInfo, Address, AdyenMpiData, AdditionalData, RiskData, ShopperName, LineItem, AdyenSplitData, AdyenGPay, AdyenApplePay, AdyenPaymentRequest, SetupMandateRequest, AdyenVoidRequest, AdyenRouterData1, AdyenAuthType, AdyenPSyncResponse, SetupMandateResponse, AdyenResponse
// Enums: Currency, CardBrand, ConnectorError, AdyenPaymentMethod, AuthType, PaymentMethod, AdyenShopperInteraction, AdyenRecurringModel, Channel, PaymentType, AdyenSplitType, AdyenPaymentResponse, ActionType, AdyenStatus, CaptureMethod, PaymentMethodType, AdyenVoidStatus, WebhookEventCode, DisputeStatus, AdyenRedirectRequestTypes
|
{
"chunk": null,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 21,
"num_items": null,
"num_structs": 47,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_module_connector-integration_2054780185909450401
|
clm
|
module
|
// connector-service/backend/connector-integration/src/connectors/worldpayvantiv/transformers.rs
// Crate: connector-integration
// Structs: WorldpayvantivMetadataObject, WorldpayvantivPaymentMetadata, WorldpayvantivPaymentsRequest, WorldpayvantivAuthType, CnpOnlineRequest, Authentication, Authorization, Sale, CaptureRequest, AuthReversal, VoidRequest, RefundRequest, CardData, TokenData, WorldpayvantivCardData, TokenizationData, BillToAddress, ShipToAddress, EnhancedData, LineItemData
// Enums: PaymentInfo, VantivProcessingType, WorldpayvativCardType, OrderSource, WorldpayvantivResponseCode, PaymentStatus, WorldpayvantivPaymentFlow, OperationId
|
{
"chunk": null,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 8,
"num_items": null,
"num_structs": 46,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
connector-service_module_connector-integration_8396971848464489452
|
clm
|
module
|
// connector-service/backend/connector-integration/src/connectors/authorizedotnet/transformers.rs
// Crate: connector-integration
// Structs: AuthorizedotnetRawCardNumber, MerchantAuthentication, CreditCardDetails, Order, BillTo, ShipTo, CustomerDetails, UserField, UserFields, ProcessingOptions, SubsequentAuthInformation, AuthorizationIndicator, CreateProfileDetails, CustomerProfileDetails, PaymentProfileDetails, AuthorizedotnetTransactionRequest, TransactionSettings, TransactionSetting, CreateTransactionRequest, AuthorizedotnetPaymentsRequest
// Enums: AuthorizationType, PaymentDetails, TransactionType, Reason, ProfileDetails, AuthorizedotnetRefundPaymentDetails, TransactionResponse, stomerType {, lidationMode {, thorizedotnetPaymentStatus {, thorizedotnetRefundStatus {, sultCode {, eration {, ncStatus {, yncStatus {, thorizedotnetWebhookEvent {, thorizedotnetIncomingWebhookEventType {
|
{
"chunk": null,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 17,
"num_items": null,
"num_structs": 73,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.