id stringlengths 20 153 | type stringclasses 1
value | granularity stringclasses 14
values | content stringlengths 16 84.3k | metadata dict |
|---|---|---|---|---|
connector-service_mini_grpc-server_6064476266321129275_4 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/aci_payment_flows_test.rs
let auth_request = create_payment_authorize_request(common_enums::CaptureMethod::Automatic);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_aci_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_aci_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 - allow both AUTHORIZED and PENDING states
let acceptable_sync_statuses = [
i32::from(PaymentStatus::Authorized),
i32::from(PaymentStatus::Charged),
];
assert!(
acceptable_sync_statuses.contains(&sync_response.status),
"Payment should be in AUTHORIZED or CHARGED state, but was: {}",
sync_response.status
);
});
}
// Test payment authorization with manual capture
#[tokio::test]
async fn test_payment_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request with manual capture
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_aci_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();
assert!(
auth_response.transaction_id.is_some(),
"Transaction ID should be present"
);
// Extract the transaction ID
let transaction_id = extract_transaction_id(&auth_response);
// Verify payment status is authorized (for manual capture)
assert!(
auth_response.status == i32::from(PaymentStatus::Authorized),
"Payment should be in AUTHORIZED state with manual capture"
);
// Create capture request
let capture_request = create_payment_capture_request(&transaction_id);
// Add metadata headers for capture request
let mut capture_grpc_request = Request::new(capture_request);
add_aci_metadata(&mut capture_grpc_request);
// Send the capture request
let capture_response = client
.capture(capture_grpc_request)
.await
.expect("gRPC payment_capture call failed")
.into_inner();
// Verify payment status is charged after capture
assert!(
capture_response.status == i32::from(PaymentStatus::Charged),
"Payment should be in CHARGED state after capture"
);
});
}
// Test refund flow
#[tokio::test]
async fn test_refund() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// First create a payment to refund
let auth_request = create_payment_authorize_request(common_enums::CaptureMethod::Automatic);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_aci_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);
// Verify payment status - allow both CHARGED and PENDING states
let acceptable_payment_statuses = [i32::from(PaymentStatus::Charged)];
assert!(
| {
"chunk": 4,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_6064476266321129275_5 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/aci_payment_flows_test.rs
acceptable_payment_statuses.contains(&auth_response.status),
"Payment should be in CHARGED state before attempting refund, but was: {}",
auth_response.status
);
tokio::time::sleep(std::time::Duration::from_secs(2)).await;
// Create refund request
let refund_request = create_refund_request(&transaction_id);
// Add metadata headers for refund request
let mut refund_grpc_request = Request::new(refund_request);
add_aci_metadata(&mut refund_grpc_request);
// Send the refund request
let refund_response = client
.refund(refund_grpc_request)
.await
.expect("gRPC refund call failed")
.into_inner();
// Extract the refund ID
let refund_id = refund_response.refund_id.clone();
// Verify the refund response
assert!(!refund_id.is_empty(), "Refund ID should not be empty");
assert!(
refund_response.status == i32::from(RefundStatus::RefundSuccess)
|| refund_response.status == i32::from(RefundStatus::RefundPending),
"Refund should be in SUCCESS or PENDING state"
);
});
}
// Test payment void flow
#[tokio::test]
async fn test_payment_void() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// First create a payment with manual capture (so it stays in authorized state)
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_aci_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);
// Verify payment is in authorized state
assert!(
auth_response.status == i32::from(PaymentStatus::Authorized),
"Payment should be in AUTHORIZED state before void"
);
// Create void request
let void_request = create_payment_void_request(&transaction_id);
// Add metadata headers for void request
let mut void_grpc_request = Request::new(void_request);
add_aci_metadata(&mut void_grpc_request);
// Send the void request
let void_response = client
.void(void_grpc_request)
.await
.expect("gRPC payment_void call failed")
.into_inner();
// Verify the void response
assert!(
void_response.status == i32::from(PaymentStatus::Voided),
"Payment should be in VOIDED state after void"
);
});
}
// Test register (setup mandate) flow
#[tokio::test]
async fn test_register() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the register request
let request = create_register_request();
// Add metadata headers
let mut grpc_request = Request::new(request);
add_aci_metadata(&mut grpc_request);
// Send the request
let response = client
.register(grpc_request)
.await
.expect("gRPC register call failed")
.into_inner();
// Verify the response
assert!(
response.registration_id.is_some(),
"Registration ID should be present"
);
// Check if we have a mandate reference
assert!(
response.mandate_reference.is_some(),
"Mandate reference should be present"
);
// Verify the mandate reference has the expected structure
if let Some(mandate_ref) = &response.mandate_reference {
assert!(
mandate_ref.mandate_id.is_some(),
"Mandate ID should be present"
);
// Verify the mandate ID is not empty
if let Some(mandate_id) = &mandate_ref.mandate_id {
assert!(!mandate_id.is_empty(), "Mandate ID should not be empty");
}
}
// Verify no error occurred
assert!(
| {
"chunk": 5,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_6064476266321129275_6 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/aci_payment_flows_test.rs
response.error_message.is_none() || response.error_message.as_ref().unwrap().is_empty(),
"No error message should be present for successful register"
);
});
}
// Test repeat payment (MIT) flow using previously created mandate
#[tokio::test]
async fn test_repeat_everything() {
grpc_test!(client, PaymentServiceClient<Channel>, {
tokio::time::sleep(std::time::Duration::from_secs(4)).await;
// First, create a mandate using register
let register_request = create_register_request();
let mut register_grpc_request = Request::new(register_request);
add_aci_metadata(&mut register_grpc_request);
let register_response = client
.register(register_grpc_request)
.await
.expect("gRPC register call failed")
.into_inner();
// Verify we got a mandate reference
assert!(
register_response.mandate_reference.is_some(),
"Mandate reference should be present"
);
let mandate_id = register_response
.mandate_reference
.as_ref()
.unwrap()
.mandate_id
.as_ref()
.expect("Mandate ID should be present");
// Now perform a repeat payment using the mandate
let repeat_request = create_repeat_payment_request(mandate_id);
let mut repeat_grpc_request = Request::new(repeat_request);
add_aci_metadata(&mut repeat_grpc_request);
// Send the repeat payment request
let repeat_response = client
.repeat_everything(repeat_grpc_request)
.await
.expect("gRPC repeat_everything call failed")
.into_inner();
// Verify the response
assert!(
repeat_response.transaction_id.is_some(),
"Transaction ID should be present"
);
});
}
| {
"chunk": 6,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_3819165835490215078_0 | clm | mini_chunk | // 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)),
| {
"chunk": 0,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_3819165835490215078_1 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/cryptopay_payment_flows_test.rs
// 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": 1,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-1482355156531562553_0 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/noon_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,
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, refund_service_client::RefundServiceClient,
AuthenticationType, CaptureMethod, CardDetails, CardPaymentMethodType, Currency,
Identifier, PaymentMethod, PaymentServiceAuthorizeRequest, PaymentServiceAuthorizeResponse,
PaymentServiceCaptureRequest, PaymentServiceGetRequest, PaymentServiceRefundRequest,
PaymentServiceVoidRequest, PaymentStatus, RefundServiceGetRequest, RefundStatus,
},
};
use hyperswitch_masking::{ExposeInterface, Secret};
use tonic::{transport::Channel, Request};
// Constants for Noon connector
const CONNECTOR_NAME: &str = "noon";
const AUTH_TYPE: &str = "signature-key";
// Test card data
const TEST_AMOUNT: i64 = 1000;
const TEST_CARD_NUMBER: &str = "4456530000001096"; // Valid test card for Noon
const TEST_CARD_EXP_MONTH: &str = "04";
const TEST_CARD_EXP_YEAR: &str = "2026";
const TEST_CARD_CVC: &str = "323";
const TEST_CARD_HOLDER: &str = "joseph Doe";
const TEST_EMAIL: &str = "customer@example.com";
// Helper function to get current timestamp
fn get_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
// Helper function to add Noon metadata headers to a request
fn add_noon_metadata<T>(request: &mut Request<T>) {
let auth = utils::credential_utils::load_connector_auth(CONNECTOR_NAME)
.expect("Failed to load noon 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 noon"),
};
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"));
// 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"),
);
request.metadata_mut().append(
"x-api-secret",
api_secret.parse().expect("Failed to parse x-api-secret"),
);
// 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!("noon_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 extract connector request ref 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
| {
"chunk": 0,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-1482355156531562553_1 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/noon_payment_flows_test.rs
fn create_payment_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_network: Some(1),
card_issuer: None,
card_type: None,
card_issuing_country_alpha2: None,
bank_code: None,
nick_name: None,
});
let mut metadata = HashMap::new();
metadata.insert(
"description".to_string(),
"Its my first payment request".to_string(),
);
PaymentServiceAuthorizeRequest {
amount: TEST_AMOUNT,
minor_amount: TEST_AMOUNT,
currency: i32::from(Currency::Aed),
payment_method: Some(PaymentMethod {
payment_method: Some(payment_method::PaymentMethod::Card(CardPaymentMethodType {
card_type: Some(card_details),
})),
}),
return_url: Some("https://duck.com".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!("noon_test_{}", get_timestamp()))),
}),
enrolled_for_3ds: false,
request_incremental_authorization: false,
capture_method: Some(i32::from(capture_method)),
order_category: Some("PAY".to_string()),
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,
request_ref_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(request_ref_id.to_string())),
}),
// all_keys_required: None,
capture_method: None,
handle_response: None,
amount: TEST_AMOUNT,
currency: i32::from(Currency::Aed),
state: None,
}
}
// Helper function to create a payment capture request
fn create_payment_capture_request(transaction_id: &str) -> PaymentServiceCaptureRequest {
PaymentServiceCaptureRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
amount_to_capture: TEST_AMOUNT,
currency: i32::from(Currency::Aed),
multiple_capture_data: None,
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(format!("capture_ref_{}", get_timestamp()))),
}),
..Default::default()
}
}
// Helper function to create a payment void request
fn create_payment_void_request(transaction_id: &str) -> PaymentServiceVoidRequest {
PaymentServiceVoidRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
cancellation_reason: None,
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(format!("void_ref_{}", get_timestamp()))),
}),
all_keys_required: None,
browser_info: None,
amount: None,
currency: None,
..Default::default()
}
}
// Helper function to create a refund request
fn create_refund_request(transaction_id: &str) -> PaymentServiceRefundRequest {
PaymentServiceRefundRequest {
refund_id: format!("refund_{}", get_timestamp()),
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
currency: i32::from(Currency::Aed),
payment_amount: TEST_AMOUNT,
refund_amount: TEST_AMOUNT,
minor_payment_amount: TEST_AMOUNT,
minor_refund_amount: TEST_AMOUNT,
reason: None,
webhook_url: None,
| {
"chunk": 1,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-1482355156531562553_2 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/noon_payment_flows_test.rs
browser_info: None,
merchant_account_id: None,
capture_method: None,
request_ref_id: None,
..Default::default()
}
}
// Helper function to create a refund sync request
fn create_refund_sync_request(transaction_id: &str, refund_id: &str) -> RefundServiceGetRequest {
RefundServiceGetRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
refund_id: refund_id.to_string(),
refund_reason: None,
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(format!("rsync_ref_{}", get_timestamp()))),
}),
browser_info: None,
refund_metadata: HashMap::new(),
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(CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_noon_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
// Verify the response
assert!(
response.transaction_id.is_some(),
"Resource ID should be present"
);
assert!(
response.status == i32::from(PaymentStatus::AuthenticationPending),
"Payment should be in AuthenticationPending state"
);
});
}
// Test payment authorization with manual capture
#[tokio::test]
async fn test_payment_authorization_manual_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request with manual capture
let auth_request = create_payment_authorize_request(CaptureMethod::Manual);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_noon_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();
assert!(
auth_response.transaction_id.is_some(),
"Transaction ID should be present"
);
// Extract the transaction ID
let transaction_id = extract_transaction_id(&auth_response);
// Verify payment status is authorized
if auth_response.status == i32::from(PaymentStatus::Authorized) {
// Create capture request
let capture_request = create_payment_capture_request(&transaction_id);
// Add metadata headers for capture request
let mut capture_grpc_request = Request::new(capture_request);
add_noon_metadata(&mut capture_grpc_request);
// Send the capture request
let capture_response = client
.capture(capture_grpc_request)
.await
.expect("gRPC payment_capture call failed")
.into_inner();
// Verify payment status is charged after capture
assert!(
capture_response.status == i32::from(PaymentStatus::Charged),
"Payment should be in CHARGED state after capture"
);
}
});
}
// Test payment void
#[tokio::test]
async fn test_payment_void() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// First create a payment with manual capture to void
| {
"chunk": 2,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-1482355156531562553_3 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/noon_payment_flows_test.rs
let auth_request = create_payment_authorize_request(CaptureMethod::Manual);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_noon_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);
// Extract the request ref ID
let request_ref_id = extract_request_ref_id(&auth_response);
// After authentication, sync the payment to get updated status
let sync_request = create_payment_sync_request(&transaction_id, &request_ref_id);
let mut sync_grpc_request = Request::new(sync_request);
add_noon_metadata(&mut sync_grpc_request);
let sync_response = client
.get(sync_grpc_request)
.await
.expect("gRPC payment_sync call failed")
.into_inner();
std::thread::sleep(std::time::Duration::from_secs(1));
// Verify payment status is authorized
if sync_response.status == i32::from(PaymentStatus::Authorized) {
// Create void request with a unique reference ID
let void_request = create_payment_void_request(&transaction_id);
// Add metadata headers for void request
let mut void_grpc_request = Request::new(void_request);
add_noon_metadata(&mut void_grpc_request);
// Send the void request
let void_response = client
.void(void_grpc_request)
.await
.expect("gRPC void_payment call failed")
.into_inner();
// Verify the void response
assert!(
void_response.transaction_id.is_some(),
"Transaction ID should be present in void response"
);
assert!(
void_response.status == i32::from(PaymentStatus::Voided),
"Payment should be in VOIDED state after void"
);
// Verify the payment status with a sync operation
let sync_request = create_payment_sync_request(&transaction_id, &request_ref_id);
let mut sync_grpc_request = Request::new(sync_request);
add_noon_metadata(&mut sync_grpc_request);
// Send the sync request to verify void status
let sync_response = client
.get(sync_grpc_request)
.await
.expect("gRPC payment_sync call failed")
.into_inner();
// Verify the payment is properly voided
assert!(
sync_response.status == i32::from(PaymentStatus::Voided),
"Payment should be in VOIDED state after void sync"
);
}
});
}
// 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(CaptureMethod::Automatic);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_noon_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);
// Extract the request ref ID
let request_ref_id = extract_request_ref_id(&auth_response);
// Wait longer for the transaction to be processed - some async processing may happen
std::thread::sleep(std::time::Duration::from_secs(2));
// Create sync request with the specific transaction ID
let sync_request = create_payment_sync_request(&transaction_id, &request_ref_id);
// Add metadata headers for sync request
let mut sync_grpc_request = Request::new(sync_request);
add_noon_metadata(&mut sync_grpc_request);
| {
"chunk": 3,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-1482355156531562553_4 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/noon_payment_flows_test.rs
// Send the sync request
let sync_response = client
.get(sync_grpc_request)
.await
.expect("Payment sync request failed")
.into_inner();
// Verify the sync response - could be charged, authorized, or pending for automatic capture
assert!(
sync_response.status == i32::from(PaymentStatus::AuthenticationPending)
|| sync_response.status == i32::from(PaymentStatus::Charged),
"Payment should be in AUTHENTICATIONPENDING or CHARGED state"
);
});
}
// Test refund flow
#[tokio::test]
async fn test_refund() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// First create a payment with automatic capture
let auth_request = create_payment_authorize_request(CaptureMethod::Automatic);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_noon_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);
// Extract the request ref ID
let request_ref_id = extract_request_ref_id(&auth_response);
// Verify payment status is authorized (for manual capture)
assert!(
auth_response.status == i32::from(PaymentStatus::AuthenticationPending),
"Payment should be in AUTHENTICATIONPENDING state with auto capture"
);
// Create sync request with the specific transaction ID
let sync_request = create_payment_sync_request(&transaction_id, &request_ref_id);
// Add metadata headers for sync request
let mut sync_grpc_request = Request::new(sync_request);
add_noon_metadata(&mut sync_grpc_request);
// Send the sync request
let sync_response = client
.get(sync_grpc_request)
.await
.expect("Payment sync request failed")
.into_inner();
// Allow more time for the capture to be processed - increase wait time
std::thread::sleep(std::time::Duration::from_secs(1));
if sync_response.status == i32::from(PaymentStatus::Authorized) {
// Create refund request with a unique refund_id that includes timestamp
let refund_request = create_refund_request(&transaction_id);
// Add metadata headers for refund request
let mut refund_grpc_request = Request::new(refund_request);
add_noon_metadata(&mut refund_grpc_request);
// Send the refund request
let refund_response = client
.refund(refund_grpc_request)
.await
.expect("Refund request failed")
.into_inner();
// Extract the refund ID
let _refund_id = refund_response.refund_id.clone();
// Verify the refund status
assert!(
refund_response.status == i32::from(RefundStatus::RefundSuccess)
|| refund_response.status == i32::from(RefundStatus::RefundPending),
"Refund should be in SUCCESS or PENDING state"
);
}
});
}
// Test refund sync flow
#[tokio::test]
async fn test_refund_sync() {
grpc_test!(client, PaymentServiceClient<Channel>, {
grpc_test!(refund_client, RefundServiceClient<Channel>, {
// First create a payment with manual capture (same as the script)
let auth_request = create_payment_authorize_request(CaptureMethod::Automatic);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_noon_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);
| {
"chunk": 4,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-1482355156531562553_5 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/noon_payment_flows_test.rs
// Verify payment status is authorized (for manual capture)
assert!(
auth_response.status == i32::from(PaymentStatus::AuthenticationPending),
"Payment should be in AUTHENTICATIONPENDING state with auto capture"
);
// Create refund request
let refund_request = create_refund_request(&transaction_id);
// Add metadata headers for refund request
let mut refund_grpc_request = Request::new(refund_request);
add_noon_metadata(&mut refund_grpc_request);
// Send the refund request and expect a successful response
let refund_response = client
.refund(refund_grpc_request)
.await
.expect("gRPC refund call failed")
.into_inner();
if refund_response.status == i32::from(RefundStatus::RefundSuccess) {
// Extract the request ref ID
let request_ref_id = extract_request_ref_id(&auth_response);
// Allow more time for the refund to be processed
std::thread::sleep(std::time::Duration::from_secs(4));
// Create refund sync request
let refund_sync_request =
create_refund_sync_request(&transaction_id, &request_ref_id);
// Add metadata headers for refund sync request
let mut refund_sync_grpc_request = Request::new(refund_sync_request);
add_noon_metadata(&mut refund_sync_grpc_request);
// Send the refund sync request and expect a successful response
let response = refund_client
.get(refund_sync_grpc_request)
.await
.expect("gRPC refund_sync call failed");
let refund_sync_response = response.into_inner();
// Verify the refund sync status
assert!(
refund_sync_response.status == i32::from(RefundStatus::RefundSuccess)
|| refund_sync_response.status == i32::from(RefundStatus::RefundPending),
"Refund sync should be in SUCCESS or PENDING state"
);
}
});
});
}
| {
"chunk": 5,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_559727822511286263_0 | clm | mini_chunk | // 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,
| {
"chunk": 0,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_559727822511286263_1 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/bluecode_payment_flows_test.rs
) -> 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
| {
"chunk": 1,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_559727822511286263_2 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/bluecode_payment_flows_test.rs
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": 2,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-2461549616556699474_0 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/fiserv_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,
str::FromStr,
time::{SystemTime, UNIX_EPOCH},
};
use base64::{engine::general_purpose, Engine};
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, refund_service_client::RefundServiceClient,
AuthenticationType, CaptureMethod, CardDetails, CardPaymentMethodType, Currency,
Identifier, PaymentMethod, PaymentServiceAuthorizeRequest, PaymentServiceAuthorizeResponse,
PaymentServiceCaptureRequest, PaymentServiceGetRequest, PaymentServiceRefundRequest,
PaymentStatus, RefundServiceGetRequest, RefundStatus,
},
};
use hyperswitch_masking::{ExposeInterface, Secret};
use tonic::{transport::Channel, Request};
// Constants for Fiserv connector
const CONNECTOR_NAME: &str = "fiserv";
// Test card data
const TEST_AMOUNT: i64 = 1000;
const TEST_CARD_NUMBER: &str = "4005550000000019"; // Valid test card for Fiserv
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";
// Helper function to get current timestamp
fn get_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
// Helper function to add Fiserv metadata headers to a request
fn add_fiserv_metadata<T>(request: &mut Request<T>) {
let auth = utils::credential_utils::load_connector_auth(CONNECTOR_NAME)
.expect("Failed to load fiserv 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 fiserv"),
};
// Get the terminal_id from metadata
let metadata = utils::credential_utils::load_connector_metadata(CONNECTOR_NAME)
.expect("Failed to load fiserv metadata");
let terminal_id = metadata
.get("terminal_id")
.expect("terminal_id not found in fiserv metadata")
.clone();
request.metadata_mut().append(
"x-connector",
CONNECTOR_NAME.parse().expect("Failed to parse x-connector"),
);
request.metadata_mut().append(
"x-auth",
"signature-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"),
);
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"),
);
// 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#"{{"terminal_id":"{terminal_id}"}}"#);
// For capture operations, the connector looks for terminal_id in connector_metadata
let base64_metadata = general_purpose::STANDARD.encode(metadata_json.as_bytes());
request.metadata_mut().append(
"x-metadata",
metadata_json.parse().expect("Failed to parse x-metadata"),
);
// Also add connector-metadata-id explicitly to handle capture operation
request.metadata_mut().append(
"connector-metadata-id",
metadata_json
.parse()
.expect("Failed to parse connector-metadata-id"),
);
// Add base64-encoded metadata as x-connector-metadata
request.metadata_mut().append(
"x-connector-metadata",
base64_metadata
.parse()
.expect("Failed to parse x-connector-metadata"),
);
request.metadata_mut().append(
"x-merchant-id",
"test_merchant"
.parse()
.expect("Failed to parse x-merchant-id"),
);
request.metadata_mut().append(
"x-tenant-id",
| {
"chunk": 0,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-2461549616556699474_1 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/fiserv_payment_flows_test.rs
"default".parse().expect("Failed to parse x-tenant-id"),
);
request.metadata_mut().append(
"x-request-id",
format!("test_request_{}", get_timestamp())
.parse()
.expect("Failed to parse x-request-id"),
);
request.metadata_mut().append(
"x-connector-request-reference-id",
format!("conn_ref_{}", get_timestamp())
.parse()
.expect("Failed to parse x-connector-request-reference-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 authorization request
fn create_payment_authorize_request(
capture_method: CaptureMethod,
) -> PaymentServiceAuthorizeRequest {
// Get terminal_id for metadata
let metadata = utils::credential_utils::load_connector_metadata(CONNECTOR_NAME)
.expect("Failed to load fiserv metadata");
let terminal_id = metadata
.get("terminal_id")
.expect("terminal_id not found in fiserv metadata")
.clone();
// Create connector metadata as a proper JSON object
let mut connector_metadata = HashMap::new();
connector_metadata.insert("terminal_id".to_string(), terminal_id);
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);
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: None,
card_type: None,
card_issuing_country_alpha2: None,
bank_code: None,
nick_name: None,
});
// Initialize with all required fields
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),
})),
}), //i32::from(payment_method::PaymentMethod::Card),
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!("fiserv_test_{}", get_timestamp()))),
}), //format!("fiserv_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)),
metadata,
..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(format!("fiserv_sync_{}", get_timestamp()))),
}),
// all_keys_required: None,
capture_method: None,
handle_response: None,
amount: TEST_AMOUNT,
currency: i32::from(Currency::Usd),
state: None,
}
}
// Helper function to create a payment capture request
fn create_payment_capture_request(transaction_id: &str) -> PaymentServiceCaptureRequest {
| {
"chunk": 1,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-2461549616556699474_2 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/fiserv_payment_flows_test.rs
let metadata = utils::credential_utils::load_connector_metadata(CONNECTOR_NAME)
.expect("Failed to load fiserv metadata");
let terminal_id = metadata
.get("terminal_id")
.expect("terminal_id not found in fiserv metadata")
.clone();
// Create connector metadata as a proper JSON object
let mut connector_metadata = HashMap::new();
connector_metadata.insert("terminal_id".to_string(), terminal_id);
let connector_metadata_json =
serde_json::to_string(&connector_metadata).expect("Failed to serialize connector metadata");
let mut connector_metadata = HashMap::new();
connector_metadata.insert("connector_metadata".to_string(), connector_metadata_json);
PaymentServiceCaptureRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
amount_to_capture: TEST_AMOUNT,
currency: i32::from(Currency::Usd),
multiple_capture_data: None,
connector_metadata,
request_ref_id: None, // all_keys_required: None,
browser_info: None,
capture_method: None,
state: None,
}
}
// Helper function to create a refund request
fn create_refund_request(transaction_id: &str) -> PaymentServiceRefundRequest {
let metadata = utils::credential_utils::load_connector_metadata(CONNECTOR_NAME)
.expect("Failed to load fiserv metadata");
let terminal_id = metadata
.get("terminal_id")
.expect("terminal_id not found in fiserv metadata")
.clone();
// Create connector metadata as a proper JSON object
let mut connector_metadata = HashMap::new();
connector_metadata.insert("terminal_id".to_string(), terminal_id);
let connector_metadata_json =
serde_json::to_string(&connector_metadata).expect("Failed to serialize connector metadata");
let mut metadata = HashMap::new();
metadata.insert("connector_metadata".to_string(), connector_metadata_json);
PaymentServiceRefundRequest {
refund_id: format!("refund_{}", get_timestamp()),
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
currency: i32::from(Currency::Usd),
payment_amount: TEST_AMOUNT,
refund_amount: TEST_AMOUNT,
minor_payment_amount: TEST_AMOUNT,
minor_refund_amount: TEST_AMOUNT,
// connector_refund_id: None,
reason: None,
webhook_url: None,
metadata: metadata.clone(), // Add terminal_id for the main connector_metadata field
refund_metadata: metadata, // Add terminal_id for refund
browser_info: None,
merchant_account_id: None,
capture_method: None,
request_ref_id: None, // all_keys_required: None,
state: None,
}
}
// Helper function to create a refund sync request
fn create_refund_sync_request(transaction_id: &str, refund_id: &str) -> RefundServiceGetRequest {
RefundServiceGetRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
refund_id: refund_id.to_string(),
refund_reason: None,
request_ref_id: None, // all_keys_required: None,
browser_info: None,
refund_metadata: HashMap::new(),
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(CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_fiserv_metadata(&mut grpc_request);
// Send the request
| {
"chunk": 2,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-2461549616556699474_3 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/fiserv_payment_flows_test.rs
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::Charged),
"Payment should be in CHARGED state"
);
});
}
// Test payment authorization with manual capture
#[tokio::test]
async fn test_payment_authorization_manual_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request with manual capture
let auth_request = create_payment_authorize_request(CaptureMethod::Manual);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_fiserv_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();
assert!(
auth_response.transaction_id.is_some(),
"Resource ID should be present"
);
// Extract the transaction ID
let transaction_id = extract_transaction_id(&auth_response);
// Verify payment status is authorized (for manual capture)
assert!(
auth_response.status == i32::from(PaymentStatus::Authorized),
"Payment should be in AUTHORIZED state with manual capture"
);
// Create capture request (which already includes proper connector metadata)
let capture_request = create_payment_capture_request(&transaction_id);
// Add metadata headers for capture request
let mut capture_grpc_request = Request::new(capture_request);
add_fiserv_metadata(&mut capture_grpc_request);
// Send the capture request
let capture_result = client.capture(capture_grpc_request).await;
// Add debugging for capture failure
let capture_response = match capture_result {
Ok(response) => response.into_inner(),
Err(status) => {
println!("=== FISERV CAPTURE DEBUG ===");
println!("Capture failed with status: {:?}", status);
println!("Error code: {:?}", status.code());
println!("Error message: {:?}", status.message());
println!("Metadata: {:?}", status.metadata());
println!("=== END DEBUG ===");
panic!("gRPC payment_capture call failed: {}", status);
}
};
// Verify payment status is charged after capture
assert!(
capture_response.status == i32::from(PaymentStatus::Charged),
"Payment should be in CHARGED state after capture"
);
});
}
// 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(CaptureMethod::Manual);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_fiserv_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_fiserv_metadata(&mut sync_grpc_request);
// Send the sync request
let sync_response = client
.get(sync_grpc_request)
.await
| {
"chunk": 3,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-2461549616556699474_4 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/fiserv_payment_flows_test.rs
.expect("gRPC payment_sync call failed")
.into_inner();
// Verify the sync response
assert!(
sync_response.status == i32::from(PaymentStatus::Authorized),
"Payment should be in Authorized state"
);
});
}
// Test refund flow - handles both success and error cases
#[tokio::test]
async fn test_refund() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// First create a payment
let auth_request = create_payment_authorize_request(CaptureMethod::Automatic);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_fiserv_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);
// Verify payment status
assert!(
auth_response.status == i32::from(PaymentStatus::Charged)
|| auth_response.status == i32::from(PaymentStatus::Authorized),
"Payment should be in CHARGED or AUTHORIZED state before attempting refund"
);
// Make sure the payment is fully processed by checking its status via sync
let sync_request = create_payment_sync_request(&transaction_id);
let mut sync_grpc_request = Request::new(sync_request);
add_fiserv_metadata(&mut sync_grpc_request);
// Wait a bit longer to ensure the payment is fully processed
tokio::time::sleep(tokio::time::Duration::from_secs(5)).await;
// Send the sync request to verify payment status
let _sync_response = client
.get(sync_grpc_request)
.await
.expect("gRPC payment_sync call failed")
.into_inner();
// Create refund request
let refund_request = create_refund_request(&transaction_id);
// Add metadata headers for refund request
let mut refund_grpc_request = Request::new(refund_request);
add_fiserv_metadata(&mut refund_grpc_request);
// Send the refund request and handle both success and error cases
let refund_result = client.refund(refund_grpc_request).await;
match refund_result {
Ok(response) => {
let refund_response = response.into_inner();
// Extract the refund ID
let _refund_id = refund_response.refund_id.clone();
// Verify the refund status
assert!(
refund_response.status == i32::from(RefundStatus::RefundSuccess)
|| refund_response.status == i32::from(RefundStatus::RefundPending),
"Refund should be in SUCCESS or PENDING state"
);
}
Err(status) => {
// If the refund fails, it could be due to timing issues or payment not being in the right state
// This is acceptable for our test scenario - we're testing the connector functionality
// Verify the error message is reasonable
assert!(
status.message().contains("processing error")
|| status.message().contains("not found")
|| status.message().contains("payment state"),
"Error should be related to processing or payment state issues"
);
}
}
});
}
// Test refund sync flow - runs as a separate test since refund + sync is complex
#[tokio::test]
async fn test_refund_sync() {
grpc_test!(client, PaymentServiceClient<Channel>, {
grpc_test!(refund_client, RefundServiceClient<Channel>, {
// Run a standalone test specifically for refund sync
// We'll directly test the payment sync functionality since the payment sync test already passes
// And use a mock refund ID for testing the refund sync functionality
// First create a payment
let auth_request = create_payment_authorize_request(CaptureMethod::Automatic);
| {
"chunk": 4,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-2461549616556699474_5 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/fiserv_payment_flows_test.rs
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_fiserv_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 with debugging
let transaction_id = match &auth_response.transaction_id {
Some(id) => match id.id_type.as_ref().unwrap() {
IdType::Id(id) => id.clone(),
IdType::NoResponseIdMarker(_) => {
println!("=== FISERV REFUND SYNC DEBUG ===");
println!("NoResponseIdMarker detected in refund sync test");
println!("Auth response: {:?}", auth_response);
println!("=== END DEBUG ===");
panic!("NoResponseIdMarker found - authentication issue");
}
IdType::EncodedData(_) => {
println!("EncodedData found instead of transaction ID");
panic!("Unexpected EncodedData in transaction ID");
}
},
None => panic!("Resource ID is None"),
};
// Wait for payment to process
tokio::time::sleep(tokio::time::Duration::from_secs(3)).await;
// Create sync request to check payment status
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_fiserv_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 payment is in a good state
assert!(
sync_response.status == i32::from(PaymentStatus::Charged)
|| sync_response.status == i32::from(PaymentStatus::Authorized),
"Payment should be in CHARGED or AUTHORIZED state"
);
// Use a mock refund ID for sync testing
// The format mimics what would come from a real Fiserv refund
let mock_refund_id = format!("refund_sync_test_{}", get_timestamp());
// Create refund sync request with our mock ID
let refund_sync_request = create_refund_sync_request(&transaction_id, &mock_refund_id);
// Add metadata headers for refund sync request
let mut refund_sync_grpc_request = Request::new(refund_sync_request);
add_fiserv_metadata(&mut refund_sync_grpc_request);
// Send the refund sync request and expect a not found response or pending status
let refund_sync_result = refund_client.get(refund_sync_grpc_request).await; //client.refund(refund_sync_grpc_request).await;
// For a mock refund ID, we expect either a failure (not found) or a pending status
// Both outcomes are valid for this test scenario
match refund_sync_result {
Ok(response) => {
// If we got a response, it should be in a pending state
let status = response.into_inner().status;
assert_eq!(
status,
i32::from(RefundStatus::RefundPending),
"If response received, refund should be in PENDING state for a mock ID"
);
}
Err(status) => {
// An error is also acceptable if the mock ID isn't found
assert!(
status.message().contains("not found")
|| status.message().contains("processing error"),
"Error should indicate refund not found or processing error"
);
}
}
});
});
}
| {
"chunk": 5,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_6234876021404422116_0 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/elavon_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,
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, refund_service_client::RefundServiceClient,
AuthenticationType, CaptureMethod, CardDetails, CardPaymentMethodType, Currency,
Identifier, PaymentMethod, PaymentServiceAuthorizeRequest, PaymentServiceAuthorizeResponse,
PaymentServiceCaptureRequest, PaymentServiceGetRequest, PaymentServiceRefundRequest,
PaymentStatus, RefundServiceGetRequest, RefundStatus,
},
};
use hyperswitch_masking::{ExposeInterface, Secret};
use tonic::{transport::Channel, Request};
// Constants for Elavon connector
const CONNECTOR_NAME: &str = "elavon";
const TEST_AMOUNT: i64 = 1000;
const TEST_CARD_NUMBER: &str = "4124939999999990";
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";
// Note: This file contains tests for Elavon payment flows.
// We're implementing the tests one by one, starting with basic functionality.
// Helper function to get current timestamp
fn get_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
// Helper function to add Elavon metadata headers to a request
fn add_elavon_metadata<T>(request: &mut Request<T>) {
let auth = utils::credential_utils::load_connector_auth(CONNECTOR_NAME)
.expect("Failed to load elavon credentials");
let (api_key, api_user, 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 elavon"),
};
request.metadata_mut().append(
"x-connector",
CONNECTOR_NAME.parse().expect("Failed to parse x-connector"),
);
request.metadata_mut().append(
"x-auth",
"signature-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"),
);
request
.metadata_mut()
.append("x-key1", api_user.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",
"test_merchant"
.parse()
.expect("Failed to parse x-merchant-id"),
);
request.metadata_mut().append(
"x-tenant-id",
"default".parse().expect("Failed to parse x-tenant-id"),
);
request.metadata_mut().append(
"x-request-id",
format!("test_request_{}", get_timestamp())
.parse()
.expect("Failed to parse x-request-id"),
);
request.metadata_mut().append(
"x-connector-request-reference-id",
format!("conn_ref_{}", get_timestamp())
.parse()
.expect("Failed to parse x-connector-request-reference-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 authorization request
fn create_payment_authorize_request(
capture_method: CaptureMethod,
) -> PaymentServiceAuthorizeRequest {
// Initialize with all required fields to avoid field_reassign_with_default warning
let card_details = card_payment_method_type::CardType::Credit(CardDetails {
| {
"chunk": 0,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_6234876021404422116_1 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/elavon_payment_flows_test.rs
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: None,
card_type: None,
card_issuing_country_alpha2: None,
bank_code: None,
nick_name: 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),
})),
}),
// payment_method_data: Some(grpc_api_types::payments::PaymentMethodData {
// data: Some(grpc_api_types::payments::payment_method_data::Data::Card(
// grpc_api_types::payments::Card {
// card_number: TEST_CARD_NUMBER.to_string(),
// card_exp_month: TEST_CARD_EXP_MONTH.to_string(),
// card_exp_year: TEST_CARD_EXP_YEAR.to_string(),
// card_cvc: TEST_CARD_CVC.to_string(),
// card_holder_name: Some(TEST_CARD_HOLDER.to_string()),
// card_issuer: None,
// card_network: None,
// card_type: None,
// card_issuing_country: None,
// bank_code: None,
// nick_name: None,
// },
// )),
// }),
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!("elavon_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)),
// all_keys_required: Some(false),
..Default::default()
}
}
// 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(CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_elavon_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
// Add comprehensive logging for debugging
println!("=== ELAVON 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!("Transaction ID: {:?}", response.transaction_id);
println!("=== END DEBUG ===");
// Check if we have a valid transaction ID or if it's a NoResponseIdMarker (auth issue)
if let Some(ref tx_id) = response.transaction_id {
if let Some(ref id_type) = tx_id.id_type {
match id_type {
IdType::NoResponseIdMarker(_) => {
println!("Elavon authentication/credential issue detected - NoResponseIdMarker");
return; // Exit early since we can't proceed with invalid credentials
}
IdType::Id(_) => {
// Valid transaction ID, continue with test
}
IdType::EncodedData(_) => {
// Handle encoded data case
| {
"chunk": 1,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_6234876021404422116_2 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/elavon_payment_flows_test.rs
println!("Elavon returned encoded data");
}
}
}
}
// Verify the response
assert!(
response.transaction_id.is_some(),
"Resource ID should be present"
);
// Extract the transaction ID (using underscore prefix since it's used for assertions only)
let _transaction_id = extract_transaction_id(&response);
// Verify payment status
assert_eq!(
response.status,
i32::from(PaymentStatus::Charged),
"Payment should be in CHARGED state"
);
});
}
#[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
);
});
}
// 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!("elavon_sync_{}", get_timestamp()))),
}), // Some(format!("elavon_sync_{}", get_timestamp())),
// all_keys_required: Some(false),
capture_method: None,
handle_response: None,
amount: TEST_AMOUNT,
currency: i32::from(Currency::Usd),
state: None,
}
}
// 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(CaptureMethod::Manual);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_elavon_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_elavon_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::Authorized),
"Payment should be in Authorized state"
);
});
}
// Helper function to create a payment capture request
fn create_payment_capture_request(transaction_id: &str) -> PaymentServiceCaptureRequest {
PaymentServiceCaptureRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
amount_to_capture: TEST_AMOUNT,
currency: i32::from(Currency::Usd),
multiple_capture_data: None,
connector_metadata: HashMap::new(),
request_ref_id: None,
browser_info: None,
capture_method: None,
state: None,
}
}
// Test payment authorization with manual capture
#[tokio::test]
async fn test_payment_authorization_manual_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request with manual capture
let auth_request = create_payment_authorize_request(CaptureMethod::Manual);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_elavon_metadata(&mut auth_grpc_request);
// Send the auth request
let auth_response = client
| {
"chunk": 2,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_6234876021404422116_3 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/elavon_payment_flows_test.rs
.authorize(auth_grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
assert!(
auth_response.transaction_id.is_some(),
"Resource ID should be present"
);
// Extract the transaction ID
let transaction_id = extract_transaction_id(&auth_response);
// Verify payment status
// Note: Even though we set capture_method to Manual, Elavon might still auto-capture
// the payment depending on the configuration, so we accept both Authorized and Charged states
assert!(
auth_response.status == i32::from(PaymentStatus::Authorized),
"Payment should be in AUTHORIZED state"
);
// Create capture request
let capture_request = create_payment_capture_request(&transaction_id);
// Add metadata headers for capture request
let mut capture_grpc_request = Request::new(capture_request);
add_elavon_metadata(&mut capture_grpc_request);
// Send the capture request
let capture_response = client
.capture(capture_grpc_request)
.await
.expect("gRPC payment_capture call failed")
.into_inner();
// Note: If the payment was already auto-captured, the capture request might fail
// with an error like "Invalid Transaction ID: The transaction ID is invalid for this transaction type"
// In this case, we'll accept either a CHARGED status
assert!(
capture_response.status == i32::from(PaymentStatus::Charged),
"Payment should be in CHARGED state"
);
});
}
// Helper function to create a refund request
fn create_refund_request(transaction_id: &str) -> PaymentServiceRefundRequest {
PaymentServiceRefundRequest {
refund_id: format!("refund_{}", get_timestamp()),
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
currency: i32::from(Currency::Usd),
payment_amount: TEST_AMOUNT,
refund_amount: TEST_AMOUNT,
minor_payment_amount: TEST_AMOUNT,
minor_refund_amount: TEST_AMOUNT,
// connector_refund_id: None,
reason: None,
webhook_url: None,
metadata: HashMap::new(),
refund_metadata: HashMap::new(),
browser_info: None,
merchant_account_id: None,
capture_method: None,
request_ref_id: None, // all_keys_required: Some(false),
state: None,
}
}
// Helper function to create a refund sync request
fn create_refund_sync_request(transaction_id: &str, refund_id: &str) -> RefundServiceGetRequest {
RefundServiceGetRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
refund_id: refund_id.to_string(),
refund_reason: None,
browser_info: None,
request_ref_id: None, // all_keys_required: None,
refund_metadata: HashMap::new(),
state: None,
}
}
// Test refund flow
#[tokio::test]
async fn test_refund() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// First create a payment to refund
let auth_request = create_payment_authorize_request(CaptureMethod::Automatic);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_elavon_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 refund request
let refund_request = create_refund_request(&transaction_id);
// Add metadata headers for refund request
let mut refund_grpc_request = Request::new(refund_request);
add_elavon_metadata(&mut refund_grpc_request);
// Send the refund request
let refund_response = client
.refund(refund_grpc_request)
.await
.expect("gRPC refund call failed")
.into_inner();
| {
"chunk": 3,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_6234876021404422116_4 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/elavon_payment_flows_test.rs
// Extract the refund ID
let refund_id = refund_response.refund_id.clone();
// Verify the refund response
assert!(!refund_id.is_empty(), "Refund ID should not be empty");
assert!(
refund_response.status == i32::from(RefundStatus::RefundSuccess),
"Refund should be in SUCCESS state"
);
});
}
// Test refund sync flow
#[tokio::test]
async fn test_refund_sync() {
grpc_test!(client, PaymentServiceClient<Channel>, {
grpc_test!(refund_client, RefundServiceClient<Channel>, {
let auth_request = create_payment_authorize_request(CaptureMethod::Automatic);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_elavon_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 refund request
let refund_request = create_refund_request(&transaction_id);
// Add metadata headers for refund request
let mut refund_grpc_request = Request::new(refund_request);
add_elavon_metadata(&mut refund_grpc_request);
// Send the refund request
let refund_response = client
.refund(refund_grpc_request)
.await
.expect("gRPC refund call failed")
.into_inner();
// Extract the refund ID
let refund_id = refund_response.refund_id.clone();
// Verify the refund response
assert!(!refund_id.is_empty(), "Refund ID should not be empty");
// Create refund sync request
let refund_sync_request = create_refund_sync_request(&transaction_id, &refund_id);
// Add metadata headers for refund sync request
let mut refund_sync_grpc_request = Request::new(refund_sync_request);
add_elavon_metadata(&mut refund_sync_grpc_request);
// Send the refund sync request
let refund_sync_response = refund_client
.get(refund_sync_grpc_request)
.await
.expect("gRPC refund_sync call failed")
.into_inner();
// Verify the refund sync response
assert!(
refund_sync_response.status == i32::from(RefundStatus::RefundPending)
|| refund_sync_response.status == i32::from(RefundStatus::RefundSuccess),
"Refund should be in PENDING or SUCCESS state"
);
});
// First create a payment to refund
});
}
| {
"chunk": 4,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_1085031906548635793_0 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/rapyd_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,
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,
BrowserInformation, CaptureMethod, CardDetails, CardPaymentMethodType, CountryAlpha2,
Currency, Identifier, PaymentAddress, PaymentMethod, PaymentServiceAuthorizeRequest,
PaymentServiceAuthorizeResponse, PaymentServiceCaptureRequest, PaymentServiceGetRequest,
PaymentServiceRefundRequest, PaymentServiceVoidRequest, PaymentStatus, RefundStatus,
},
};
use hyperswitch_masking::{ExposeInterface, Secret};
use tonic::{transport::Channel, Request};
// Constants for rapyd connector
const CONNECTOR_NAME: &str = "rapyd";
const TEST_AMOUNT: i64 = 1000;
const TEST_CARD_NUMBER: &str = "4111111111111111";
const TEST_CARD_EXP_MONTH: &str = "10";
const TEST_CARD_EXP_YEAR: &str = "2030";
const TEST_CARD_CVC: &str = "123";
const TEST_CARD_HOLDER: &str = "Test User";
const TEST_EMAIL: &str = "customer@example.com";
// Helper function to get current timestamp
fn get_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
// Helper function to add rapyd metadata headers to a request
fn add_rapyd_metadata<T>(request: &mut Request<T>) {
let auth = utils::credential_utils::load_connector_auth(CONNECTOR_NAME)
.expect("Failed to load rapyd 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 rapyd"),
};
request.metadata_mut().append(
"x-connector",
CONNECTOR_NAME.parse().expect("Failed to parse x-connector"),
);
request.metadata_mut().append(
"x-auth",
"body-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"),
);
request
.metadata_mut()
.append("x-key1", key1.parse().expect("Failed to parse x-key1"));
request.metadata_mut().append(
"x-merchant-id",
"test_merchant"
.parse()
.expect("Failed to parse x-merchant-id"),
);
request.metadata_mut().append(
"x-tenant-id",
"default".parse().expect("Failed to parse x-tenant-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 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 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::default();
// Set request reference ID
let mut request_ref_id = Identifier::default();
request_ref_id.id_type = Some(IdType::Id(format!("rapyd_test_{}", get_timestamp())));
request.request_ref_id = Some(request_ref_id);
// Set the basic payment details
request.amount = TEST_AMOUNT;
request.minor_amount = TEST_AMOUNT;
request.currency = i32::from(Currency::Usd);
// Set up card payment method using the correct structure
let card_details = card_payment_method_type::CardType::Credit(CardDetails {
card_number: Some(CardNumber::from_str(TEST_CARD_NUMBER).unwrap()),
| {
"chunk": 0,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_1085031906548635793_1 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/rapyd_payment_flows_test.rs
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_i32), // Default to Visa network
card_type: None,
card_issuing_country_alpha2: None,
bank_code: None,
nick_name: None,
});
request.payment_method = Some(PaymentMethod {
payment_method: Some(payment_method::PaymentMethod::Card(CardPaymentMethodType {
card_type: Some(card_details),
})),
});
// Set connector customer ID
request.customer_id = Some("TEST_CONNECTOR".to_string());
// Set the customer information with static email (can be made dynamic)
request.email = Some(TEST_EMAIL.to_string().into());
// Set up address structure
request.address = Some(PaymentAddress {
billing_address: Some(Address {
first_name: Some("Test".to_string().into()),
last_name: Some("User".to_string().into()),
line1: Some("123 Test Street".to_string().into()),
line2: None,
line3: None,
city: Some("Test City".to_string().into()),
state: Some("NY".to_string().into()),
zip_code: Some("10001".to_string().into()),
country_alpha2_code: Some(i32::from(CountryAlpha2::Us)),
phone_number: None,
phone_country_code: None,
email: None,
}),
shipping_address: None,
});
// Set up browser information
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 (compatible; TestAgent/1.0)".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);
// Set return URL
request.return_url = Some("https://example.com/return".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 with proper conversion
if let common_enums::CaptureMethod::Manual = capture_method {
request.capture_method = Some(i32::from(CaptureMethod::Manual));
} else {
request.capture_method = Some(i32::from(CaptureMethod::Automatic));
}
// Set connector metadata (empty for generic template)
request.metadata = HashMap::new();
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!("rapyd_sync_{}", get_timestamp()))),
}),
capture_method: None,
handle_response: None,
amount: TEST_AMOUNT,
currency: i32::from(Currency::Usd),
state: None,
}
}
// Helper function to create a payment capture request
fn create_payment_capture_request(transaction_id: &str) -> PaymentServiceCaptureRequest {
PaymentServiceCaptureRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
amount_to_capture: TEST_AMOUNT,
currency: i32::from(Currency::Usd),
multiple_capture_data: None,
connector_metadata: HashMap::new(),
request_ref_id: None,
browser_info: None,
capture_method: None,
state: None,
}
}
// Helper function to create a refund request
| {
"chunk": 1,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_1085031906548635793_2 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/rapyd_payment_flows_test.rs
fn create_refund_request(transaction_id: &str) -> PaymentServiceRefundRequest {
PaymentServiceRefundRequest {
refund_id: format!("refund_{}", get_timestamp()),
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
currency: i32::from(Currency::Usd),
payment_amount: TEST_AMOUNT,
refund_amount: TEST_AMOUNT,
minor_payment_amount: TEST_AMOUNT,
minor_refund_amount: TEST_AMOUNT,
reason: None,
webhook_url: None,
metadata: HashMap::new(),
refund_metadata: HashMap::new(),
browser_info: None,
merchant_account_id: None,
capture_method: None,
request_ref_id: None,
state: None,
}
}
// Helper function to create a payment void request
fn create_payment_void_request(transaction_id: &str) -> PaymentServiceVoidRequest {
PaymentServiceVoidRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
cancellation_reason: Some("Customer requested cancellation".to_string()),
request_ref_id: None,
all_keys_required: None,
browser_info: None,
amount: None,
currency: None,
..Default::default()
}
}
#[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_rapyd_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
// Verify the response
assert!(
response.transaction_id.is_some(),
"Transaction ID should be present"
);
// Extract the transaction ID
let _transaction_id = extract_transaction_id(&response);
// Verify payment status
assert_eq!(
response.status,
i32::from(PaymentStatus::Charged),
"Payment should be in CHARGED state for automatic capture"
);
});
}
// Test payment authorization with manual capture
#[tokio::test]
async fn test_payment_authorization_manual_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request with manual capture
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_rapyd_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();
assert!(
auth_response.transaction_id.is_some(),
"Transaction ID should be present"
);
// Extract the transaction ID
let _transaction_id = extract_transaction_id(&auth_response);
// Verify payment status is authorized (for manual capture)
assert_eq!(
auth_response.status,
i32::from(PaymentStatus::Authorized),
"Payment should be in AUTHORIZED state with manual capture"
);
});
}
// Test payment sync
#[tokio::test]
async fn test_payment_sync() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// First create a payment to sync
| {
"chunk": 2,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_1085031906548635793_3 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/rapyd_payment_flows_test.rs
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_rapyd_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_rapyd_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 - allow both AUTHORIZED and PENDING states
let acceptable_sync_statuses = [
i32::from(PaymentStatus::Authorized),
i32::from(PaymentStatus::Pending),
];
assert!(
acceptable_sync_statuses.contains(&sync_response.status),
"Payment should be in AUTHORIZED or PENDING state, but was: {}",
sync_response.status
);
});
}
// Test payment authorization with manual capture
#[tokio::test]
async fn test_payment_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request with manual capture
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_rapyd_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();
assert!(
auth_response.transaction_id.is_some(),
"Transaction ID should be present"
);
// Extract the transaction ID
let transaction_id = extract_transaction_id(&auth_response);
// Verify payment status is authorized (for manual capture)
assert!(
auth_response.status == i32::from(PaymentStatus::Authorized),
"Payment should be in AUTHORIZED state with manual capture"
);
// Create capture request
let capture_request = create_payment_capture_request(&transaction_id);
// Add metadata headers for capture request
let mut capture_grpc_request = Request::new(capture_request);
add_rapyd_metadata(&mut capture_grpc_request);
// Send the capture request
let capture_response = client
.capture(capture_grpc_request)
.await
.expect("gRPC payment_capture call failed")
.into_inner();
// Verify payment status is charged after capture
assert!(
capture_response.status == i32::from(PaymentStatus::Charged),
"Payment should be in CHARGED state after capture"
);
});
}
// Test refund flow
#[tokio::test]
async fn test_refund() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// First create a payment to refund
let auth_request = create_payment_authorize_request(common_enums::CaptureMethod::Automatic);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_rapyd_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);
// Verify payment status - allow both CHARGED and PENDING states
let acceptable_payment_statuses = [
i32::from(PaymentStatus::Charged),
| {
"chunk": 3,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_1085031906548635793_4 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/rapyd_payment_flows_test.rs
i32::from(PaymentStatus::Pending),
];
assert!(
acceptable_payment_statuses.contains(&auth_response.status),
"Payment should be in CHARGED or PENDING state before attempting refund, but was: {}",
auth_response.status
);
// Create refund request
let refund_request = create_refund_request(&transaction_id);
// Add metadata headers for refund request
let mut refund_grpc_request = Request::new(refund_request);
add_rapyd_metadata(&mut refund_grpc_request);
// Send the refund request
let refund_response = client
.refund(refund_grpc_request)
.await
.expect("gRPC refund call failed")
.into_inner();
// Extract the refund ID
let refund_id = refund_response.refund_id.clone();
// Verify the refund response
assert!(!refund_id.is_empty(), "Refund ID should not be empty");
assert!(
refund_response.status == i32::from(RefundStatus::RefundSuccess)
|| refund_response.status == i32::from(RefundStatus::RefundPending),
"Refund should be in SUCCESS or PENDING state"
);
});
}
// Test payment void flow
#[tokio::test]
async fn test_payment_void() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// First create a payment with manual capture (so it stays in authorized state)
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_rapyd_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);
// Verify payment is in authorized state
assert!(
auth_response.status == i32::from(PaymentStatus::Authorized),
"Payment should be in AUTHORIZED state before void"
);
// Create void request
let void_request = create_payment_void_request(&transaction_id);
// Add metadata headers for void request
let mut void_grpc_request = Request::new(void_request);
add_rapyd_metadata(&mut void_grpc_request);
// Send the void request
let void_response = client
.void(void_grpc_request)
.await
.expect("gRPC payment_void call failed")
.into_inner();
// Verify the void response
assert!(
void_response.status == i32::from(PaymentStatus::Voided),
"Payment should be in VOIDED state after void"
);
});
}
| {
"chunk": 4,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-8692831922258415912_0 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/placetopay_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,
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, refund_service_client::RefundServiceClient,
Address, AuthenticationType, BrowserInformation, CaptureMethod, CardDetails,
CardPaymentMethodType, CountryAlpha2, Currency, Identifier, PaymentAddress, PaymentMethod,
PaymentServiceAuthorizeRequest, PaymentServiceAuthorizeResponse,
PaymentServiceCaptureRequest, PaymentServiceGetRequest, PaymentServiceRefundRequest,
PaymentServiceVoidRequest, PaymentStatus, RefundServiceGetRequest, RefundStatus,
},
};
use hyperswitch_masking::{ExposeInterface, Secret};
use tonic::{transport::Channel, Request};
// Constants for placetopay connector
const CONNECTOR_NAME: &str = "placetopay";
const TEST_AMOUNT: i64 = 1000;
const TEST_CARD_NUMBER: &str = "4111111111111111";
const TEST_CARD_EXP_MONTH: &str = "10";
const TEST_CARD_EXP_YEAR: &str = "2030";
const TEST_CARD_CVC: &str = "123";
const TEST_CARD_HOLDER: &str = "Test User";
const TEST_EMAIL: &str = "customer@example.com";
// Helper function to get current timestamp
fn get_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
// Helper function to add placetopay metadata headers to a request
fn add_placetopay_metadata<T>(request: &mut Request<T>) {
let auth = utils::credential_utils::load_connector_auth(CONNECTOR_NAME)
.expect("Failed to load placetopay 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 placetopay"),
};
request.metadata_mut().append(
"x-connector",
CONNECTOR_NAME.parse().expect("Failed to parse x-connector"),
);
request.metadata_mut().append(
"x-auth",
"body-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"),
);
request
.metadata_mut()
.append("x-key1", key1.parse().expect("Failed to parse x-key1"));
request.metadata_mut().append(
"x-merchant-id",
"test_merchant"
.parse()
.expect("Failed to parse x-merchant-id"),
);
request.metadata_mut().append(
"x-tenant-id",
"default".parse().expect("Failed to parse x-tenant-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_transaction_id(response: &PaymentServiceAuthorizeResponse) -> String {
match &response.transaction_id {
Some(id) => match id.id_type.as_ref().unwrap() {
IdType::Id(id) => {
if id == "NoResponseIdMarker" {
panic!("Placetopay validation error - check required fields like ip_address and description");
} else {
id.clone()
}
}
_ => panic!("Expected connector transaction ID"),
},
None => panic!("Transaction ID is None"),
}
}
// 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 {
let mut request = PaymentServiceAuthorizeRequest::default();
// Set request reference ID
let mut request_ref_id = Identifier::default();
request_ref_id.id_type = Some(IdType::Id(format!("placetopay_test_{}", get_timestamp())));
request.request_ref_id = Some(request_ref_id);
// Set the basic payment details
request.amount = TEST_AMOUNT;
| {
"chunk": 0,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-8692831922258415912_1 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/placetopay_payment_flows_test.rs
request.minor_amount = TEST_AMOUNT;
request.currency = i32::from(Currency::Usd);
// Set up card payment method
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_i32),
card_type: None,
card_issuing_country_alpha2: None,
bank_code: None,
nick_name: None,
});
request.payment_method = Some(PaymentMethod {
payment_method: Some(payment_method::PaymentMethod::Card(CardPaymentMethodType {
card_type: Some(card_details),
})),
});
request.customer_id = Some("TEST_CONNECTOR".to_string());
request.email = Some(TEST_EMAIL.to_string().into());
// Set up address structure
request.address = Some(PaymentAddress {
billing_address: Some(Address {
first_name: Some("Test".to_string().into()),
last_name: Some("User".to_string().into()),
line1: Some("123 Test Street".to_string().into()),
line2: None,
line3: None,
city: Some("Test City".to_string().into()),
state: Some("NY".to_string().into()),
zip_code: Some("10001".to_string().into()),
country_alpha2_code: Some(i32::from(CountryAlpha2::Us)),
phone_number: None,
phone_country_code: None,
email: None,
}),
shipping_address: None,
});
// Set up browser information with required fields for Placetopay
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 (compatible; TestAgent/1.0)".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: Some("127.0.0.1".to_string()), // Required by Placetopay
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("https://example.com/return".to_string());
// Set transaction details
request.auth_type = i32::from(AuthenticationType::NoThreeDs);
request.request_incremental_authorization = true;
request.enrolled_for_3ds = true;
// Set capture method
if let common_enums::CaptureMethod::Manual = capture_method {
request.capture_method = Some(i32::from(CaptureMethod::Manual));
} else {
request.capture_method = Some(i32::from(CaptureMethod::Automatic));
}
// Required by Placetopay
request.description = Some("Test payment for Placetopay connector".to_string());
request.metadata = HashMap::new();
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!("placetopay_sync_{}", get_timestamp()))),
}),
capture_method: None,
handle_response: None,
amount: TEST_AMOUNT,
currency: i32::from(Currency::Usd),
state: None,
}
}
// Helper function to create a payment capture request
fn create_payment_capture_request(transaction_id: &str) -> PaymentServiceCaptureRequest {
PaymentServiceCaptureRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
amount_to_capture: TEST_AMOUNT,
currency: i32::from(Currency::Usd),
multiple_capture_data: None,
| {
"chunk": 1,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-8692831922258415912_2 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/placetopay_payment_flows_test.rs
connector_metadata: HashMap::new(),
request_ref_id: None,
browser_info: None,
capture_method: None,
state: None,
}
}
// Helper function to create a refund request
fn create_refund_request(transaction_id: &str) -> PaymentServiceRefundRequest {
PaymentServiceRefundRequest {
refund_id: format!("refund_{}", get_timestamp()),
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
currency: i32::from(Currency::Usd),
payment_amount: TEST_AMOUNT,
refund_amount: TEST_AMOUNT,
minor_payment_amount: TEST_AMOUNT,
minor_refund_amount: TEST_AMOUNT,
reason: None,
webhook_url: None,
metadata: HashMap::new(),
refund_metadata: HashMap::new(),
browser_info: None,
merchant_account_id: None,
capture_method: None,
request_ref_id: None,
state: None,
}
}
// Helper function to create a refund sync request
fn create_refund_sync_request(transaction_id: &str, refund_id: &str) -> RefundServiceGetRequest {
RefundServiceGetRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
refund_id: refund_id.to_string(),
refund_reason: None,
browser_info: None,
request_ref_id: None,
refund_metadata: HashMap::new(),
state: None,
}
}
// Helper function to create a payment void request
fn create_payment_void_request(transaction_id: &str) -> PaymentServiceVoidRequest {
PaymentServiceVoidRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
cancellation_reason: Some("Customer requested cancellation".to_string()),
request_ref_id: None,
all_keys_required: None,
browser_info: None,
amount: None,
currency: None,
..Default::default()
}
}
#[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>, {
let request = create_payment_authorize_request(common_enums::CaptureMethod::Automatic);
let mut grpc_request = Request::new(request);
add_placetopay_metadata(&mut grpc_request);
let response = client
.authorize(grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
assert!(
response.transaction_id.is_some(),
"Transaction ID should be present"
);
let _transaction_id = extract_transaction_id(&response);
assert_eq!(
response.status,
i32::from(PaymentStatus::Charged),
"Payment should be in CHARGED state for automatic capture"
);
});
}
// Test payment authorization with manual capture
#[tokio::test]
async fn test_payment_authorization_manual_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let auth_request = create_payment_authorize_request(common_enums::CaptureMethod::Manual);
let mut auth_grpc_request = Request::new(auth_request);
add_placetopay_metadata(&mut auth_grpc_request);
let auth_response = client
.authorize(auth_grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
assert!(
auth_response.transaction_id.is_some(),
"Transaction ID should be present"
);
let _transaction_id = extract_transaction_id(&auth_response);
// Placetopay auto-charges payments regardless of capture method setting
let acceptable_statuses = [
i32::from(PaymentStatus::Authorized),
| {
"chunk": 2,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-8692831922258415912_3 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/placetopay_payment_flows_test.rs
i32::from(PaymentStatus::Charged), // Placetopay auto-charges
];
assert!(
acceptable_statuses.contains(&auth_response.status),
"Payment should be in AUTHORIZED or CHARGED state with manual capture, but was: {}",
auth_response.status
);
});
}
// Test payment sync
#[tokio::test]
async fn test_payment_sync() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let auth_request = create_payment_authorize_request(common_enums::CaptureMethod::Manual);
let mut auth_grpc_request = Request::new(auth_request);
add_placetopay_metadata(&mut auth_grpc_request);
let auth_response = client
.authorize(auth_grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
let transaction_id = extract_transaction_id(&auth_response);
let sync_request = create_payment_sync_request(&transaction_id);
let mut sync_grpc_request = Request::new(sync_request);
add_placetopay_metadata(&mut sync_grpc_request);
let sync_response = client
.get(sync_grpc_request)
.await
.expect("gRPC payment_sync call failed")
.into_inner();
// Placetopay auto-charges payments regardless of capture method setting
let acceptable_sync_statuses = [
i32::from(PaymentStatus::Authorized),
i32::from(PaymentStatus::Pending),
i32::from(PaymentStatus::Charged), // Placetopay auto-charges
];
assert!(
acceptable_sync_statuses.contains(&sync_response.status),
"Payment should be in AUTHORIZED, PENDING, or CHARGED state, but was: {}",
sync_response.status
);
});
}
// Test payment capture flow
#[tokio::test]
async fn test_payment_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let auth_request = create_payment_authorize_request(common_enums::CaptureMethod::Manual);
let mut auth_grpc_request = Request::new(auth_request);
add_placetopay_metadata(&mut auth_grpc_request);
let auth_response = client
.authorize(auth_grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
assert!(
auth_response.transaction_id.is_some(),
"Transaction ID should be present"
);
let transaction_id = extract_transaction_id(&auth_response);
// Placetopay auto-charges payments even when manual capture is requested
if auth_response.status == i32::from(PaymentStatus::Charged) {
// Test passed - payment is already captured
return;
}
// If payment is still authorized, attempt capture
if auth_response.status == i32::from(PaymentStatus::Authorized) {
let capture_request = create_payment_capture_request(&transaction_id);
let mut capture_grpc_request = Request::new(capture_request);
add_placetopay_metadata(&mut capture_grpc_request);
let capture_response = client
.capture(capture_grpc_request)
.await
.expect("gRPC payment_capture call failed")
.into_inner();
assert!(
capture_response.status == i32::from(PaymentStatus::Charged),
"Payment should be in CHARGED state after capture"
);
} else {
panic!("Unexpected payment status: {}", auth_response.status);
}
});
}
// Test refund flow
#[tokio::test]
async fn test_refund() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let auth_request = create_payment_authorize_request(common_enums::CaptureMethod::Automatic);
let mut auth_grpc_request = Request::new(auth_request);
add_placetopay_metadata(&mut auth_grpc_request);
let auth_response = client
.authorize(auth_grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
let transaction_id = extract_transaction_id(&auth_response);
let acceptable_payment_statuses = [
i32::from(PaymentStatus::Charged),
| {
"chunk": 3,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-8692831922258415912_4 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/placetopay_payment_flows_test.rs
i32::from(PaymentStatus::Pending),
];
assert!(
acceptable_payment_statuses.contains(&auth_response.status),
"Payment should be in CHARGED or PENDING state before attempting refund, but was: {}",
auth_response.status
);
let refund_request = create_refund_request(&transaction_id);
let mut refund_grpc_request = Request::new(refund_request);
add_placetopay_metadata(&mut refund_grpc_request);
let refund_response = client
.refund(refund_grpc_request)
.await
.expect("gRPC refund call failed")
.into_inner();
let refund_id = refund_response.refund_id.clone();
// Placetopay may not support refunds with test credentials
if refund_id.is_empty() {
// Skip refund test if connector doesn't support refunds properly
return;
}
assert!(
refund_response.status == i32::from(RefundStatus::RefundSuccess)
|| refund_response.status == i32::from(RefundStatus::RefundPending),
"Refund should be in SUCCESS or PENDING state"
);
});
}
// Test refund sync flow
#[tokio::test]
async fn test_refund_sync() {
grpc_test!(client, PaymentServiceClient<Channel>, {
grpc_test!(refund_client, RefundServiceClient<Channel>, {
let auth_request =
create_payment_authorize_request(common_enums::CaptureMethod::Automatic);
let mut auth_grpc_request = Request::new(auth_request);
add_placetopay_metadata(&mut auth_grpc_request);
let auth_response = client
.authorize(auth_grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
let transaction_id = extract_transaction_id(&auth_response);
let refund_request = create_refund_request(&transaction_id);
let mut refund_grpc_request = Request::new(refund_request);
add_placetopay_metadata(&mut refund_grpc_request);
let refund_response = client
.refund(refund_grpc_request)
.await
.expect("gRPC refund call failed")
.into_inner();
let refund_id = refund_response.refund_id.clone();
// Placetopay may not support refunds with test credentials
if refund_id.is_empty() {
return;
}
let refund_sync_request = create_refund_sync_request(&transaction_id, &refund_id);
let mut refund_sync_grpc_request = Request::new(refund_sync_request);
add_placetopay_metadata(&mut refund_sync_grpc_request);
let refund_sync_response = refund_client
.get(refund_sync_grpc_request)
.await
.expect("gRPC refund_sync call failed")
.into_inner();
assert!(
refund_sync_response.status == i32::from(RefundStatus::RefundPending)
|| refund_sync_response.status == i32::from(RefundStatus::RefundSuccess),
"Refund should be in PENDING or SUCCESS state"
);
});
});
}
// Test payment void flow
#[tokio::test]
async fn test_payment_void() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// First create a payment with manual capture (so it stays in authorized state)
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_placetopay_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);
// Placetopay auto-charges payments, making void impossible for charged payments
if auth_response.status == i32::from(PaymentStatus::Charged) {
// Test passed - void not applicable for auto-charged payments
| {
"chunk": 4,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-8692831922258415912_5 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/placetopay_payment_flows_test.rs
return;
}
// If payment is still authorized, void should work
if auth_response.status == i32::from(PaymentStatus::Authorized) {
let void_request = create_payment_void_request(&transaction_id);
let mut void_grpc_request = Request::new(void_request);
add_placetopay_metadata(&mut void_grpc_request);
let void_response = client
.void(void_grpc_request)
.await
.expect("gRPC payment_void call failed")
.into_inner();
assert!(
void_response.status == i32::from(PaymentStatus::Voided),
"Payment should be in VOIDED state after void"
);
} else {
panic!("Unexpected payment status for void: {}", auth_response.status);
}
});
}
| {
"chunk": 5,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_6580252036373041860_0 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/adyen_dispute_webhook_test.rs
#![allow(clippy::expect_used)]
#![allow(clippy::panic)]
use grpc_server::{app, configs};
use hyperswitch_masking::ExposeInterface;
mod common;
mod utils;
use grpc_api_types::payments::{
payment_service_client::PaymentServiceClient,
webhook_response_content::Content as GrpcWebhookContent, DisputeStage as GrpcDisputeStage,
DisputeStatus as GrpcDisputeStatus, DisputesSyncResponse, PaymentServiceTransformRequest,
RequestDetails,
};
use serde_json::json;
use tonic::{transport::Channel, Request};
// Helper function to construct Adyen webhook JSON body
fn build_adyen_webhook_json_body(
event_code: &str,
reason: &str,
adyen_dispute_status: Option<&str>,
) -> serde_json::Value {
let mut additional_data = serde_json::Map::new();
if let Some(status) = adyen_dispute_status {
additional_data.insert("disputeStatus".to_string(), json!(status));
}
let psp_reference = "9915555555555555"; // Default
let original_reference = "9913333333333333"; // Default
let merchant_account_code = "YOUR_MERCHANT_ACCOUNT"; // Default
let merchant_reference = "YOUR_REFERENCE"; // Default
let payment_method = "mc"; // Default
let amount_currency = "EUR"; // Default
let amount_value = 1000; // Default
let event_date = "2023-12-01T12:00:00Z"; // Default
let success_status = "true";
json!({
"live": "false",
"notificationItems": [
{
"NotificationRequestItem": {
"eventCode": event_code,
"success": success_status,
"pspReference": psp_reference,
"originalReference": original_reference,
"merchantAccountCode": merchant_account_code,
"merchantReference": merchant_reference,
"paymentMethod": payment_method,
"eventDate": event_date,
"additionalData": additional_data,
"reason": reason,
"amount": {
"value": amount_value,
"currency": amount_currency
}
}
}
]
})
}
// Helper to make the gRPC call and return the DisputesSyncResponse
async fn process_webhook_and_get_response(
client: &mut PaymentServiceClient<Channel>,
json_body: serde_json::Value,
) -> DisputesSyncResponse {
let request_body_bytes =
serde_json::to_vec(&json_body).expect("Failed to serialize json_body to Vec<u8>");
let mut request = Request::new(PaymentServiceTransformRequest {
request_ref_id: Some(grpc_api_types::payments::Identifier {
id_type: Some(grpc_api_types::payments::identifier::IdType::Id(
"webhook_test".to_string(),
)),
}),
request_details: Some(RequestDetails {
method: grpc_api_types::payments::HttpMethod::Post.into(),
headers: std::collections::HashMap::new(),
uri: Some("/webhooks/adyen".to_string()),
query_params: None,
body: request_body_bytes,
}),
webhook_secrets: None,
state: None,
});
let auth = utils::credential_utils::load_connector_auth("adyen")
.expect("Failed to load adyen 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 adyen"),
};
request.metadata_mut().append(
"x-connector",
"adyen".parse().expect("Failed to parse x-connector"),
);
request.metadata_mut().append(
"x-auth",
"signature-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"),
);
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"),
);
let response = client
.transform(request)
.await
.expect("gRPC transform call failed")
| {
"chunk": 0,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_6580252036373041860_1 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/adyen_dispute_webhook_test.rs
.into_inner();
match response.content.and_then(|c| c.content) {
Some(GrpcWebhookContent::DisputesResponse(dispute_response)) => {
DisputesSyncResponse {
stage: dispute_response.dispute_stage,
status: dispute_response.dispute_status,
dispute_message: dispute_response.dispute_message,
dispute_id: dispute_response.dispute_id.unwrap_or("".to_string()), // TODO need a fix
connector_response_reference_id: None, // TODO need a fix
}
}
_ => {
//if the content is not a DisputesResponse, return a dummy DisputesSyncResponse
DisputesSyncResponse {
stage: 0,
status: 0,
dispute_message: None,
dispute_id: "".to_string(),
connector_response_reference_id: None,
}
}
}
}
// --- Test Cases ---
// Adyen Doc: https://docs.adyen.com/risk-management/disputes-api/dispute-notifications/#notification_of_chargeback
#[tokio::test]
async fn test_notification_of_chargeback_undefended() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_code = "NOTIFICATION_OF_CHARGEBACK";
let reason = "Fraudulent transaction";
let adyen_dispute_status = Some("Undefended");
let json_body = build_adyen_webhook_json_body(event_code, reason, adyen_dispute_status);
let dispute_response = process_webhook_and_get_response(&mut client, json_body).await;
assert_eq!(
grpc_api_types::payments::DisputeStage::try_from(dispute_response.stage)
.expect("Failed to convert i32 to DisputeStage"),
grpc_api_types::payments::DisputeStage::PreDispute
);
assert_eq!(
GrpcDisputeStatus::try_from(dispute_response.status)
.expect("Failed to convert i32 to DisputeStatus"),
GrpcDisputeStatus::DisputeOpened
);
assert_eq!(dispute_response.dispute_message, Some(reason.to_string()));
});
}
// Adyen Doc: https://docs.adyen.com/risk-management/disputes-api/dispute-notifications/#notification_of_chargeback
#[tokio::test]
async fn test_notification_of_chargeback_pending() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_code = "NOTIFICATION_OF_CHARGEBACK";
let reason = "Product not received";
let adyen_dispute_status = Some("Pending");
let json_body = build_adyen_webhook_json_body(event_code, reason, adyen_dispute_status);
let dispute_response = process_webhook_and_get_response(&mut client, json_body).await;
assert_eq!(
GrpcDisputeStage::try_from(dispute_response.stage)
.expect("Failed to convert i32 to DisputeStage"),
GrpcDisputeStage::PreDispute
);
assert_eq!(
GrpcDisputeStatus::try_from(dispute_response.status)
.expect("Failed to convert i32 to DisputeStatus"),
GrpcDisputeStatus::DisputeOpened
);
assert_eq!(dispute_response.dispute_message, Some(reason.to_string()));
});
}
// Adyen Doc: https://docs.adyen.com/risk-management/disputes-api/dispute-notifications/#chargeback
#[tokio::test]
async fn test_chargeback_undefended() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_code = "CHARGEBACK";
let reason = "Service not rendered";
let adyen_dispute_status = Some("Undefended");
let json_body = build_adyen_webhook_json_body(event_code, reason, adyen_dispute_status);
let dispute_response = process_webhook_and_get_response(&mut client, json_body).await;
assert_eq!(
GrpcDisputeStage::try_from(dispute_response.stage)
.expect("Failed to convert i32 to DisputeStage"),
GrpcDisputeStage::ActiveDispute
);
assert_eq!(
GrpcDisputeStatus::try_from(dispute_response.status)
.expect("Failed to convert i32 to DisputeStatus"),
GrpcDisputeStatus::DisputeOpened
);
assert_eq!(dispute_response.dispute_message, Some(reason.to_string()));
});
}
// Adyen Doc: https://docs.adyen.com/risk-management/disputes-api/dispute-notifications/#chargeback
#[tokio::test]
| {
"chunk": 1,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_6580252036373041860_2 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/adyen_dispute_webhook_test.rs
async fn test_chargeback_pending() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_code = "CHARGEBACK";
let reason = "Credit not processed";
let adyen_dispute_status = Some("Pending");
let json_body = build_adyen_webhook_json_body(event_code, reason, adyen_dispute_status);
let dispute_response = process_webhook_and_get_response(&mut client, json_body).await;
assert_eq!(
GrpcDisputeStage::try_from(dispute_response.stage)
.expect("Failed to convert i32 to DisputeStage"),
GrpcDisputeStage::ActiveDispute
);
assert_eq!(
GrpcDisputeStatus::try_from(dispute_response.status)
.expect("Failed to convert i32 to DisputeStatus"),
GrpcDisputeStatus::DisputeOpened
);
assert_eq!(dispute_response.dispute_message, Some(reason.to_string()));
});
}
// Adyen Doc: https://docs.adyen.com/risk-management/disputes-api/dispute-notifications/#chargeback
#[tokio::test]
async fn test_chargeback_lost() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_code = "CHARGEBACK";
let reason = "Duplicate transaction";
let adyen_dispute_status = Some("Lost");
let json_body = build_adyen_webhook_json_body(event_code, reason, adyen_dispute_status);
let dispute_response = process_webhook_and_get_response(&mut client, json_body).await;
assert_eq!(
GrpcDisputeStage::try_from(dispute_response.stage)
.expect("Failed to convert i32 to DisputeStage"),
GrpcDisputeStage::ActiveDispute
);
assert_eq!(
GrpcDisputeStatus::try_from(dispute_response.status)
.expect("Failed to convert i32 to DisputeStatus"),
GrpcDisputeStatus::DisputeLost
);
assert_eq!(dispute_response.dispute_message, Some(reason.to_string()));
});
}
// Adyen Doc: https://docs.adyen.com/risk-management/disputes-api/dispute-notifications/#chargeback
#[tokio::test]
async fn test_chargeback_accepted() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_code = "CHARGEBACK";
let reason = "Fraudulent transaction - merchant accepted";
let adyen_dispute_status = Some("Accepted");
let json_body = build_adyen_webhook_json_body(event_code, reason, adyen_dispute_status);
let dispute_response = process_webhook_and_get_response(&mut client, json_body).await;
assert_eq!(
GrpcDisputeStage::try_from(dispute_response.stage)
.expect("Failed to convert i32 to DisputeStage"),
GrpcDisputeStage::ActiveDispute
);
assert_eq!(
GrpcDisputeStatus::try_from(dispute_response.status)
.expect("Failed to convert i32 to DisputeStatus"),
GrpcDisputeStatus::DisputeAccepted
);
assert_eq!(dispute_response.dispute_message, Some(reason.to_string()));
});
}
// Adyen Doc: https://docs.adyen.com/risk-management/disputes-api/dispute-notifications/#chargeback_reversed
#[tokio::test]
async fn test_chargeback_reversed_pending() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_code = "CHARGEBACK_REVERSED";
let reason = "Defense successful, awaiting bank review";
let adyen_dispute_status = Some("Pending");
let json_body = build_adyen_webhook_json_body(event_code, reason, adyen_dispute_status);
let dispute_response = process_webhook_and_get_response(&mut client, json_body).await;
assert_eq!(
GrpcDisputeStage::try_from(dispute_response.stage)
.expect("Failed to convert i32 to DisputeStage"),
GrpcDisputeStage::ActiveDispute
);
assert_eq!(
GrpcDisputeStatus::try_from(dispute_response.status)
.expect("Failed to convert i32 to DisputeStatus"),
GrpcDisputeStatus::DisputeChallenged
);
assert_eq!(dispute_response.dispute_message, Some(reason.to_string()));
});
}
// Adyen Doc: https://docs.adyen.com/risk-management/disputes-api/dispute-notifications/#chargeback_reversed
#[tokio::test]
async fn test_chargeback_reversed_won() {
grpc_test!(client, PaymentServiceClient<Channel>, {
| {
"chunk": 2,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_6580252036373041860_3 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/adyen_dispute_webhook_test.rs
let event_code = "CHARGEBACK_REVERSED";
let reason = "Defense accepted by bank";
let adyen_dispute_status = Some("Won");
let json_body = build_adyen_webhook_json_body(event_code, reason, adyen_dispute_status);
let dispute_response = process_webhook_and_get_response(&mut client, json_body).await;
assert_eq!(
GrpcDisputeStage::try_from(dispute_response.stage)
.expect("Failed to convert i32 to DisputeStage"),
GrpcDisputeStage::ActiveDispute
);
assert_eq!(
GrpcDisputeStatus::try_from(dispute_response.status)
.expect("Failed to convert i32 to DisputeStatus"),
GrpcDisputeStatus::DisputeWon
);
assert_eq!(dispute_response.dispute_message, Some(reason.to_string()));
});
}
// Adyen Doc: https://docs.adyen.com/risk-management/disputes-api/dispute-notifications/#second_chargeback
#[tokio::test]
async fn test_second_chargeback_lost() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_code = "SECOND_CHARGEBACK";
let reason = "Defense declined after initial reversal";
let adyen_dispute_status = Some("Lost");
let json_body = build_adyen_webhook_json_body(event_code, reason, adyen_dispute_status);
let dispute_response = process_webhook_and_get_response(&mut client, json_body).await;
assert_eq!(
GrpcDisputeStage::try_from(dispute_response.stage)
.expect("Failed to convert i32 to DisputeStage"),
GrpcDisputeStage::PreArbitration
);
assert_eq!(
GrpcDisputeStatus::try_from(dispute_response.status)
.expect("Failed to convert i32 to DisputeStatus"),
GrpcDisputeStatus::DisputeLost
);
assert_eq!(dispute_response.dispute_message, Some(reason.to_string()));
});
}
// Adyen Doc: https://docs.adyen.com/risk-management/disputes-api/dispute-notifications/#prearbitration_won
#[tokio::test]
async fn test_prearbitration_won_with_status_won() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_code = "PREARBITRATION_WON";
let reason = "Pre-arbitration won by merchant";
let adyen_dispute_status = Some("Won");
let json_body = build_adyen_webhook_json_body(event_code, reason, adyen_dispute_status);
let dispute_response = process_webhook_and_get_response(&mut client, json_body).await;
assert_eq!(
GrpcDisputeStage::try_from(dispute_response.stage)
.expect("Failed to convert i32 to DisputeStage"),
GrpcDisputeStage::PreArbitration
);
assert_eq!(
GrpcDisputeStatus::try_from(dispute_response.status)
.expect("Failed to convert i32 to DisputeStatus"),
GrpcDisputeStatus::DisputeWon
);
assert_eq!(dispute_response.dispute_message, Some(reason.to_string()));
});
}
// Adyen Doc: https://docs.adyen.com/risk-management/disputes-api/dispute-notifications/#prearbitration_won
#[tokio::test]
async fn test_prearbitration_won_with_status_pending() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_code = "PREARBITRATION_WON";
let reason = "Pre-arbitration outcome pending";
let adyen_dispute_status = Some("Pending");
let json_body = build_adyen_webhook_json_body(event_code, reason, adyen_dispute_status);
let dispute_response = process_webhook_and_get_response(&mut client, json_body).await;
assert_eq!(
GrpcDisputeStage::try_from(dispute_response.stage)
.expect("Failed to convert i32 to DisputeStage"),
GrpcDisputeStage::PreArbitration
);
assert_eq!(
GrpcDisputeStatus::try_from(dispute_response.status)
.expect("Failed to convert i32 to DisputeStatus"),
GrpcDisputeStatus::DisputeOpened
);
assert_eq!(dispute_response.dispute_message, Some(reason.to_string()));
});
}
// Adyen Doc: https://docs.adyen.com/risk-management/disputes-api/dispute-notifications/#prearbitration_lost
#[tokio::test]
async fn test_prearbitration_lost() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_code = "PREARBITRATION_LOST";
| {
"chunk": 3,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_6580252036373041860_4 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/adyen_dispute_webhook_test.rs
let reason = "Pre-arbitration lost by merchant";
let adyen_dispute_status = Some("Lost");
let json_body = build_adyen_webhook_json_body(event_code, reason, adyen_dispute_status);
let dispute_response = process_webhook_and_get_response(&mut client, json_body).await;
assert_eq!(
GrpcDisputeStage::try_from(dispute_response.stage)
.expect("Failed to convert i32 to DisputeStage"),
GrpcDisputeStage::PreArbitration
);
assert_eq!(
GrpcDisputeStatus::try_from(dispute_response.status)
.expect("Failed to convert i32 to DisputeStatus"),
GrpcDisputeStatus::DisputeLost
);
assert_eq!(dispute_response.dispute_message, Some(reason.to_string()));
});
}
| {
"chunk": 4,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_3350236631919853906_0 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/checkout_payment_flows_test.rs
#![allow(clippy::expect_used)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::panic)]
use cards::CardNumber;
use grpc_server::{app, configs};
use hyperswitch_masking::{ExposeInterface, Secret};
mod common;
mod utils;
use std::{
str::FromStr,
time::{SystemTime, UNIX_EPOCH},
};
use grpc_api_types::{
health_check::{health_client::HealthClient, HealthCheckRequest},
payments::{
card_payment_method_type, identifier::IdType, payment_method,
payment_service_client::PaymentServiceClient, refund_service_client::RefundServiceClient,
AuthenticationType, CaptureMethod, CardDetails, CardPaymentMethodType, Currency,
Identifier, PaymentMethod, PaymentServiceAuthorizeRequest, PaymentServiceAuthorizeResponse,
PaymentServiceCaptureRequest, PaymentServiceGetRequest, PaymentServiceRefundRequest,
PaymentServiceVoidRequest, PaymentStatus, RefundServiceGetRequest, RefundStatus,
},
};
use tonic::{transport::Channel, Request};
// Constants for Checkout connector
const CONNECTOR_NAME: &str = "checkout";
const AUTH_TYPE: &str = "signature-key";
// Test card data
const TEST_AMOUNT: i64 = 1000;
const AUTO_CAPTURE_CARD_NUMBER: &str = "4000020000000000"; // Card number from checkout_grpcurl_test.sh for auto capture
const MANUAL_CAPTURE_CARD_NUMBER: &str = "4242424242424242"; // Card number from checkout_grpcurl_test.sh for manual capture
const TEST_CARD_EXP_MONTH: &str = "12";
const TEST_CARD_EXP_YEAR: &str = "2025";
const TEST_CARD_CVC: &str = "100";
const TEST_CARD_HOLDER: &str = "Test User";
const TEST_EMAIL: &str = "customer@example.com";
// Helper function to get current timestamp
fn get_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_secs()
}
// Helper function to add checkout metadata headers to a request
fn add_checkout_metadata<T>(request: &mut Request<T>) {
let auth = utils::credential_utils::load_connector_auth(CONNECTOR_NAME)
.expect("Failed to load checkout 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 checkout"),
};
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",
"test_merchant"
.parse()
.expect("Failed to parse x-merchant-id"),
);
request.metadata_mut().append(
"x-tenant-id",
"default".parse().expect("Failed to parse x-tenant-id"),
);
request.metadata_mut().append(
"x-request-id",
format!("test_request_{}", get_timestamp())
.parse()
.expect("Failed to parse x-request-id"),
);
request.metadata_mut().append(
"x-connector-request-reference-id",
format!("conn_ref_{}", get_timestamp())
.parse()
.expect("Failed to parse x-connector-request-reference-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 authorization request
fn create_payment_authorize_request(
capture_method: CaptureMethod,
) -> PaymentServiceAuthorizeRequest {
// Select the correct card number based on capture method
| {
"chunk": 0,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_3350236631919853906_1 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/checkout_payment_flows_test.rs
let card_number = match capture_method {
CaptureMethod::Automatic => Some(CardNumber::from_str(AUTO_CAPTURE_CARD_NUMBER).unwrap()),
CaptureMethod::Manual => Some(CardNumber::from_str(MANUAL_CAPTURE_CARD_NUMBER).unwrap()),
_ => Some(CardNumber::from_str(MANUAL_CAPTURE_CARD_NUMBER).unwrap()), // Default to manual capture card
};
let card_details = card_payment_method_type::CardType::Credit(CardDetails {
card_number,
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: None,
card_type: None,
card_issuing_country_alpha2: None,
bank_code: None,
nick_name: None,
});
// Initialize with all required fields
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),
})),
}),
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!("checkout_test_{}", get_timestamp()))),
}),
enrolled_for_3ds: false,
request_incremental_authorization: false,
capture_method: Some(i32::from(capture_method)),
metadata: std::collections::HashMap::new(),
..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(format!("checkout_sync_{}", get_timestamp()))),
}),
capture_method: None,
handle_response: None,
amount: TEST_AMOUNT,
currency: i32::from(Currency::Usd),
state: None,
}
}
// Helper function to create a payment capture request
fn create_payment_capture_request(transaction_id: &str) -> PaymentServiceCaptureRequest {
PaymentServiceCaptureRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
amount_to_capture: TEST_AMOUNT,
currency: i32::from(Currency::Usd),
multiple_capture_data: None,
connector_metadata: std::collections::HashMap::new(),
request_ref_id: None,
browser_info: None,
capture_method: None,
state: None,
}
}
// Helper function to create a refund request
fn create_refund_request(transaction_id: &str) -> PaymentServiceRefundRequest {
PaymentServiceRefundRequest {
refund_id: format!("refund_{}", get_timestamp()),
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
currency: i32::from(Currency::Usd),
payment_amount: TEST_AMOUNT,
refund_amount: TEST_AMOUNT,
minor_payment_amount: TEST_AMOUNT,
minor_refund_amount: TEST_AMOUNT,
reason: Some("Test refund".to_string()),
webhook_url: None,
metadata: std::collections::HashMap::new(),
refund_metadata: std::collections::HashMap::new(),
browser_info: None,
merchant_account_id: None,
capture_method: None,
request_ref_id: None,
state: None,
}
}
// Helper function to create a refund sync request
fn create_refund_sync_request(transaction_id: &str, refund_id: &str) -> RefundServiceGetRequest {
RefundServiceGetRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
refund_id: refund_id.to_string(),
refund_reason: None,
| {
"chunk": 1,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_3350236631919853906_2 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/checkout_payment_flows_test.rs
request_ref_id: None,
browser_info: None,
refund_metadata: std::collections::HashMap::new(),
state: None,
}
}
// Helper function to sleep for a short duration to allow server processing
fn allow_processing_time() {
std::thread::sleep(std::time::Duration::from_secs(3));
}
// Helper function to create a payment void request
fn create_payment_void_request(transaction_id: &str) -> PaymentServiceVoidRequest {
PaymentServiceVoidRequest {
transaction_id: Some(Identifier {
id_type: Some(IdType::Id(transaction_id.to_string())),
}),
cancellation_reason: None,
request_ref_id: Some(Identifier {
id_type: Some(IdType::Id(format!("void_ref_{}", get_timestamp()))),
}),
all_keys_required: None,
browser_info: None,
amount: None,
currency: None,
..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_payment_authorize_request(CaptureMethod::Automatic);
// Add metadata headers
let mut grpc_request = Request::new(request);
add_checkout_metadata(&mut grpc_request);
// Send the request
let response = client
.authorize(grpc_request)
.await
.expect("gRPC payment_authorize call failed")
.into_inner();
// Verify the response
assert!(
response.transaction_id.is_some(),
"Transaction ID should be present"
);
// Extract the transaction ID
let transaction_id = extract_transaction_id(&response);
// Verify payment status - for automatic capture, should be PENDING according to our implementation
assert!(
response.status == i32::from(PaymentStatus::Pending),
"Payment should be in PENDING state for automatic capture before sync"
);
// Wait longer for the transaction to be fully processed
std::thread::sleep(std::time::Duration::from_secs(10));
// Create sync request with the transaction ID
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_checkout_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();
// After the sync, payment should be in CHARGED state based on connector_meta with Capture intent
assert_eq!(
sync_response.status,
i32::from(PaymentStatus::Charged),
"Payment should be in CHARGED state after sync with Capture intent"
);
});
}
// Test payment authorization with manual capture
#[tokio::test]
async fn test_payment_authorization_manual_capture() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// Create the payment authorization request with manual capture
let auth_request = create_payment_authorize_request(CaptureMethod::Manual);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_checkout_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();
assert!(
auth_response.transaction_id.is_some(),
"Transaction ID should be present"
| {
"chunk": 2,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_3350236631919853906_3 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/checkout_payment_flows_test.rs
);
// Extract the transaction ID
let transaction_id = extract_transaction_id(&auth_response);
// Verify payment status is authorized (for manual capture, as per our implementation)
assert!(
auth_response.status == i32::from(PaymentStatus::Authorized),
"Payment should be in AUTHORIZED state with manual capture (Authorize intent)"
);
// Create capture request
let capture_request = create_payment_capture_request(&transaction_id);
// Add metadata headers for capture request
let mut capture_grpc_request = Request::new(capture_request);
add_checkout_metadata(&mut capture_grpc_request);
// Send the capture request
let capture_response = client
.capture(capture_grpc_request)
.await
.expect("gRPC payment_capture call failed")
.into_inner();
// Verify payment status is charged after capture
assert!(
capture_response.status == i32::from(PaymentStatus::Charged),
"Payment should be in CHARGED state after capture"
);
});
}
// 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(CaptureMethod::Automatic);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_checkout_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);
// Wait longer for the transaction to be processed - some async processing may happen
std::thread::sleep(std::time::Duration::from_secs(5));
// Create sync request with the specific transaction ID
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_checkout_metadata(&mut sync_grpc_request);
// Send the sync request
let sync_response = client
.get(sync_grpc_request)
.await
.expect("Payment sync request failed")
.into_inner();
// Verify the sync response - could be charged, authorized, or pending for automatic capture
assert!(
sync_response.status == i32::from(PaymentStatus::Charged),
"Payment should be in CHARGED state"
);
});
}
// Test refund flow
#[tokio::test]
async fn test_refund() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// First create a payment with manual capture (same as the script)
let auth_request = create_payment_authorize_request(CaptureMethod::Manual);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_checkout_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);
// Verify payment status is authorized (for manual capture)
assert!(
auth_response.status == i32::from(PaymentStatus::Authorized),
"Payment should be in AUTHORIZED state with manual capture"
);
// Create capture request
let capture_request = create_payment_capture_request(&transaction_id);
// Add metadata headers for capture request
let mut capture_grpc_request = Request::new(capture_request);
add_checkout_metadata(&mut capture_grpc_request);
// Send the capture request
let capture_response = client
.capture(capture_grpc_request)
.await
.expect("gRPC payment_capture call failed")
.into_inner();
| {
"chunk": 3,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_3350236631919853906_4 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/checkout_payment_flows_test.rs
// Verify payment status is charged after capture
assert!(
capture_response.status == i32::from(PaymentStatus::Charged),
"Payment should be in CHARGED state after capture"
);
// Allow more time for the capture to be processed - increase wait time
std::thread::sleep(std::time::Duration::from_secs(5));
// Create refund request with a unique refund_id that includes timestamp
let refund_request = create_refund_request(&transaction_id);
// Add metadata headers for refund request
let mut refund_grpc_request = Request::new(refund_request);
add_checkout_metadata(&mut refund_grpc_request);
// Send the refund request
let refund_response = client
.refund(refund_grpc_request)
.await
.expect("Refund request failed")
.into_inner();
// Extract the refund ID
let _refund_id = refund_response.refund_id.clone();
// Verify the refund status
assert!(
refund_response.status == i32::from(RefundStatus::RefundSuccess)
|| refund_response.status == i32::from(RefundStatus::RefundPending),
"Refund should be in SUCCESS or PENDING state"
);
});
}
// Test refund sync flow
#[tokio::test]
#[ignore] // Service not implemented on server side - Status code: Unimplemented
async fn test_refund_sync() {
grpc_test!(client, PaymentServiceClient<Channel>, {
grpc_test!(refund_client, RefundServiceClient<Channel>, {
// First create a payment with manual capture (same as the script)
let auth_request = create_payment_authorize_request(CaptureMethod::Manual);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_checkout_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);
// Verify payment status is authorized (for manual capture)
assert!(
auth_response.status == i32::from(PaymentStatus::Authorized),
"Payment should be in AUTHORIZED state with manual capture"
);
// Create capture request
let capture_request = create_payment_capture_request(&transaction_id);
// Add metadata headers for capture request
let mut capture_grpc_request = Request::new(capture_request);
add_checkout_metadata(&mut capture_grpc_request);
// Send the capture request
let capture_response = client
.capture(capture_grpc_request)
.await
.expect("gRPC payment_capture call failed")
.into_inner();
// Verify payment status is charged after capture
assert!(
capture_response.status == i32::from(PaymentStatus::Charged),
"Payment should be in CHARGED state after capture"
);
// Allow more time for the capture to be processed
std::thread::sleep(std::time::Duration::from_secs(5));
// Create refund request
let refund_request = create_refund_request(&transaction_id);
// Add metadata headers for refund request
let mut refund_grpc_request = Request::new(refund_request);
add_checkout_metadata(&mut refund_grpc_request);
// Send the refund request and expect a successful response
let refund_response = client
.refund(refund_grpc_request)
.await
.expect("gRPC refund call failed")
.into_inner();
// Extract the refund ID
let refund_id = refund_response.refund_id.clone();
// Allow more time for the refund to be processed
std::thread::sleep(std::time::Duration::from_secs(5));
// Create refund sync request
| {
"chunk": 4,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_3350236631919853906_5 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/checkout_payment_flows_test.rs
let refund_sync_request = create_refund_sync_request(&transaction_id, &refund_id);
// Add metadata headers for refund sync request
let mut refund_sync_grpc_request = Request::new(refund_sync_request);
add_checkout_metadata(&mut refund_sync_grpc_request);
// Send the refund sync request and expect a successful response
let response = refund_client
.get(refund_sync_grpc_request)
.await
.expect("gRPC refund_sync call failed");
let refund_sync_response = response.into_inner();
// Verify the refund sync status
assert!(
refund_sync_response.status == i32::from(RefundStatus::RefundSuccess)
|| refund_sync_response.status == i32::from(RefundStatus::RefundPending),
"Refund sync should be in SUCCESS or PENDING state"
);
});
});
}
// Test payment void
#[tokio::test]
async fn test_payment_void() {
grpc_test!(client, PaymentServiceClient<Channel>, {
// First create a payment with manual capture to void
let auth_request = create_payment_authorize_request(CaptureMethod::Manual);
// Add metadata headers for auth request
let mut auth_grpc_request = Request::new(auth_request);
add_checkout_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);
// Verify payment status
assert!(
auth_response.status == i32::from(PaymentStatus::Authorized),
"Payment should be in AUTHORIZED state before voiding"
);
// Allow some time for the authorization to be processed
allow_processing_time();
// Create void request with a unique reference ID
let void_request = create_payment_void_request(&transaction_id);
// Add metadata headers for void request
let mut void_grpc_request = Request::new(void_request);
add_checkout_metadata(&mut void_grpc_request);
// Send the void request
let void_response = client
.void(void_grpc_request)
.await
.expect("gRPC void_payment call failed")
.into_inner();
// Verify the void response
assert!(
void_response.transaction_id.is_some(),
"Transaction ID should be present in void response"
);
assert!(
void_response.status == i32::from(PaymentStatus::Voided),
"Payment should be in VOIDED state after void"
);
// Allow time for void to process
allow_processing_time();
// Verify the payment status with a sync operation
let sync_request = create_payment_sync_request(&transaction_id);
let mut sync_grpc_request = Request::new(sync_request);
add_checkout_metadata(&mut sync_grpc_request);
// Send the sync request to verify void status
let sync_response = client
.get(sync_grpc_request)
.await
.expect("gRPC payment_sync call failed")
.into_inner();
// Verify the payment is properly voided
assert!(
sync_response.status == i32::from(PaymentStatus::Voided),
"Payment should be in VOIDED state after void sync"
);
});
}
| {
"chunk": 5,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_5340641875733848070_0 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/authorizedotnet_webhook_test.rs
#![allow(clippy::expect_used, clippy::indexing_slicing)]
#![allow(clippy::panic)]
use grpc_server::{app, configs};
use hyperswitch_masking::ExposeInterface;
mod common;
mod utils;
use std::fmt::Write;
use common_utils::crypto::{HmacSha512, SignMessage};
use grpc_api_types::payments::{
payment_service_client::PaymentServiceClient, PaymentServiceTransformRequest, RequestDetails,
};
use serde_json::json;
use tonic::{transport::Channel, Request};
// Helper function to construct Authorize.Net customer payment profile creation webhook JSON body
fn build_authorizedotnet_payment_profile_webhook_json_body(
event_type: &str,
customer_profile_id: u64,
payment_profile_id: &str,
customer_type: &str,
) -> serde_json::Value {
let notification_id = "7201C905-B01E-4622-B807-AC2B646A3815"; // Default
let event_date = "2016-03-23T06:19:09.5297562Z"; // Default
let webhook_id = "6239A0BE-D8F4-4A33-8FAD-901C02EED51F"; // Default
let payload = json!({
"customerProfileId": customer_profile_id,
"entityName": "customerPaymentProfile",
"id": payment_profile_id,
"customerType": customer_type
});
json!({
"notificationId": notification_id,
"eventType": event_type,
"eventDate": event_date,
"webhookId": webhook_id,
"payload": payload
})
}
// Helper function to construct Authorize.Net customer creation webhook JSON body
fn build_authorizedotnet_customer_webhook_json_body(
event_type: &str,
customer_profile_id: &str,
payment_profile_id: &str,
merchant_customer_id: Option<&str>,
description: Option<&str>,
) -> serde_json::Value {
let notification_id = "5c3f7e00-1265-4e8e-abd0-a7d734163881"; // Default
let event_date = "2016-03-23T05:23:06.5430555Z"; // Default
let webhook_id = "0b90f2e8-02ae-4d1d-b2e0-1bd167e60176"; // Default
let payload = json!({
"paymentProfiles": [{
"id": payment_profile_id,
"customerType": "individual"
}],
"merchantCustomerId": merchant_customer_id.unwrap_or("cust457"),
"description": description.unwrap_or("Profile created by Subscription"),
"entityName": "customerProfile",
"id": customer_profile_id
});
json!({
"notificationId": notification_id,
"eventType": event_type,
"eventDate": event_date,
"webhookId": webhook_id,
"payload": payload
})
}
// Helper function to construct Authorize.Net webhook JSON body
fn build_authorizedotnet_webhook_json_body(
event_type: &str,
response_code: u8,
transaction_id: &str,
amount: Option<f64>,
merchant_reference_id: Option<&str>,
auth_code: Option<&str>,
message_text: Option<&str>,
) -> serde_json::Value {
let notification_id = "550e8400-e29b-41d4-a716-446655440000"; // Default
let event_date = "2023-12-01T12:00:00Z"; // Default
let webhook_id = "webhook_123"; // Default
let entity_name = "transaction"; // Default
let mut payload = json!({
"responseCode": response_code,
"entityName": entity_name,
"id": transaction_id,
});
// Add optional fields if provided
if let Some(ref_id) = merchant_reference_id {
payload["merchantReferenceId"] = json!(ref_id);
}
if let Some(auth) = auth_code {
payload["authCode"] = json!(auth);
}
if let Some(amt) = amount {
if event_type.contains("authorization") || event_type.contains("authcapture") {
payload["authAmount"] = json!(amt);
} else if event_type.contains("capture") || event_type.contains("refund") {
payload["settleAmount"] = json!(amt);
}
}
if let Some(msg) = message_text {
payload["messageText"] = json!(msg);
}
// Add common fields
payload["avsResponse"] = json!("Y");
payload["cvvResponse"] = json!("M");
json!({
"notificationId": notification_id,
"eventType": event_type,
"eventDate": event_date,
"webhookId": webhook_id,
"payload": payload
})
}
// Helper function to generate HMAC-SHA512 signature for testing
fn generate_webhook_signature(webhook_body: &[u8], secret: &str) -> String {
let crypto_algorithm = HmacSha512;
let signature = crypto_algorithm
.sign_message(secret.as_bytes(), webhook_body)
| {
"chunk": 0,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_5340641875733848070_1 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/authorizedotnet_webhook_test.rs
.expect("Failed to generate signature");
// Convert bytes to hex string manually
let mut hex_string = String::with_capacity(signature.len() * 2);
for b in signature {
write!(&mut hex_string, "{b:02x}").expect("writing to a String should never fail");
}
format!("sha512={hex_string}")
}
// Helper to make the gRPC call and return success/failure status
async fn process_webhook_request(
client: &mut PaymentServiceClient<Channel>,
json_body: serde_json::Value,
include_signature: bool,
) -> Result<(), String> {
let request_body_bytes =
serde_json::to_vec(&json_body).expect("Failed to serialize json_body to Vec<u8>");
let mut headers = std::collections::HashMap::new();
// Get webhook_secret from metadata
let metadata = utils::credential_utils::load_connector_metadata("authorizedotnet")
.expect("Failed to load authorizedotnet metadata");
let webhook_secret = metadata
.get("webhook_secret")
.expect("webhook_secret not found in authorizedotnet metadata")
.clone();
if include_signature {
let signature = generate_webhook_signature(&request_body_bytes, &webhook_secret);
headers.insert("X-ANET-Signature".to_string(), signature);
}
let webhook_secrets = Some(grpc_api_types::payments::WebhookSecrets {
secret: webhook_secret.clone(),
additional_secret: None,
});
let mut request = Request::new(PaymentServiceTransformRequest {
request_ref_id: Some(grpc_api_types::payments::Identifier {
id_type: Some(grpc_api_types::payments::identifier::IdType::Id(
"webhook_test".to_string(),
)),
}),
request_details: Some(RequestDetails {
method: grpc_api_types::payments::HttpMethod::Post.into(),
headers,
uri: Some("/webhooks/authorizedotnet".to_string()),
query_params: None,
body: request_body_bytes,
}),
webhook_secrets,
state: None,
});
// Use the same metadata pattern as the payment flows test
let auth = utils::credential_utils::load_connector_auth("authorizedotnet")
.expect("Failed to load authorizedotnet 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 authorizedotnet"),
};
request.metadata_mut().append(
"x-connector",
"authorizedotnet"
.parse()
.expect("Failed to parse x-connector"),
);
request.metadata_mut().append(
"x-auth",
"body-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"),
);
request
.metadata_mut()
.append("x-key1", key1.parse().expect("Failed to parse x-key1"));
request.metadata_mut().append(
"x-merchant-id",
"test_merchant"
.parse()
.expect("Failed to parse x-merchant-id"),
);
request.metadata_mut().append(
"x-tenant-id",
"default".parse().expect("Failed to parse x-tenant-id"),
);
request.metadata_mut().append(
"x-request-id",
"webhook_test_req"
.parse()
.expect("Failed to parse x-request-id"),
);
let _response = client
.transform(request)
.await
.map_err(|e| format!("gRPC transform call failed: {e}"))?;
// Response processed successfully
// If we get a response, the webhook was processed successfully
Ok(())
}
// --- Payment Authorization Event Tests ---
#[tokio::test]
async fn test_payment_authorization_approved() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_type = "net.authorize.payment.authorization.created";
let response_code = 1; // Approved
let transaction_id = "60123456789";
let amount = Some(100.50);
let auth_code = Some("ABC123");
let message_text = Some("This transaction has been approved.");
let json_body = build_authorizedotnet_webhook_json_body(
event_type,
response_code,
transaction_id,
amount,
Some("REF123"),
| {
"chunk": 1,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_5340641875733848070_2 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/authorizedotnet_webhook_test.rs
auth_code,
message_text,
);
// Test that webhook processing succeeds
let result = process_webhook_request(&mut client, json_body, true).await;
// Check result in assertion below
assert!(
result.is_ok(),
"Payment authorization approved webhook should be processed successfully"
);
});
}
#[tokio::test]
async fn test_payment_authorization_declined() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_type = "net.authorize.payment.authorization.created";
let response_code = 2; // Declined
let transaction_id = "60123456790";
let message_text = Some("This transaction has been declined.");
let json_body = build_authorizedotnet_webhook_json_body(
event_type,
response_code,
transaction_id,
None,
Some("REF124"),
None,
message_text,
);
// Test that webhook processing succeeds
let result = process_webhook_request(&mut client, json_body, true).await;
assert!(
result.is_ok(),
"Payment authorization declined webhook should be processed successfully"
);
});
}
#[tokio::test]
async fn test_payment_authorization_held() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_type = "net.authorize.payment.authorization.created";
let response_code = 4; // Held for review
let transaction_id = "60123456791";
let message_text = Some("This transaction is being held for review.");
let json_body = build_authorizedotnet_webhook_json_body(
event_type,
response_code,
transaction_id,
Some(75.25),
Some("REF125"),
None,
message_text,
);
// Test that webhook processing succeeds
let result = process_webhook_request(&mut client, json_body, true).await;
assert!(
result.is_ok(),
"Payment authorization held webhook should be processed successfully"
);
});
}
// --- Payment Auth-Capture Event Tests ---
#[tokio::test]
async fn test_payment_authcapture_approved() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_type = "net.authorize.payment.authcapture.created";
let response_code = 1; // Approved
let transaction_id = "60123456792";
let amount = Some(200.00);
let json_body = build_authorizedotnet_webhook_json_body(
event_type,
response_code,
transaction_id,
amount,
Some("REF126"),
Some("XYZ789"),
Some("This transaction has been approved."),
);
// Test that webhook processing succeeds
let result = process_webhook_request(&mut client, json_body, true).await;
assert!(
result.is_ok(),
"Payment authcapture approved webhook should be processed successfully"
);
});
}
#[tokio::test]
async fn test_payment_authcapture_declined() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_type = "net.authorize.payment.authcapture.created";
let response_code = 2; // Declined
let transaction_id = "60123456793";
let json_body = build_authorizedotnet_webhook_json_body(
event_type,
response_code,
transaction_id,
None,
Some("REF127"),
None,
Some("This transaction has been declined."),
);
// Test that webhook processing succeeds
let result = process_webhook_request(&mut client, json_body, true).await;
assert!(
result.is_ok(),
"Payment authcapture declined webhook should be processed successfully"
);
});
}
#[tokio::test]
async fn test_payment_authcapture_held() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_type = "net.authorize.payment.authcapture.created";
let response_code = 4; // Held for review
let transaction_id = "60123456794";
let json_body = build_authorizedotnet_webhook_json_body(
event_type,
response_code,
transaction_id,
Some(150.75),
Some("REF128"),
None,
| {
"chunk": 2,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_5340641875733848070_3 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/authorizedotnet_webhook_test.rs
Some("This transaction is being held for review."),
);
// Test that webhook processing succeeds
let result = process_webhook_request(&mut client, json_body, true).await;
assert!(
result.is_ok(),
"Payment authcapture held webhook should be processed successfully"
);
});
}
// --- Payment Capture Event Tests ---
#[tokio::test]
async fn test_payment_capture_approved() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_type = "net.authorize.payment.capture.created";
let response_code = 1; // Approved
let transaction_id = "60123456795";
let amount = Some(100.00);
let json_body = build_authorizedotnet_webhook_json_body(
event_type,
response_code,
transaction_id,
amount,
Some("REF129"),
None,
Some("This transaction has been captured."),
);
// Test that webhook processing succeeds
let result = process_webhook_request(&mut client, json_body, true).await;
assert!(
result.is_ok(),
"Payment capture approved webhook should be processed successfully"
);
});
}
#[tokio::test]
async fn test_payment_capture_declined() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_type = "net.authorize.payment.capture.created";
let response_code = 2; // Declined
let transaction_id = "60123456796";
let json_body = build_authorizedotnet_webhook_json_body(
event_type,
response_code,
transaction_id,
None,
Some("REF130"),
None,
Some("This capture has been declined."),
);
// Test that webhook processing succeeds
let result = process_webhook_request(&mut client, json_body, true).await;
assert!(
result.is_ok(),
"Payment capture declined webhook should be processed successfully"
);
});
}
// --- Payment Void Event Tests ---
#[tokio::test]
async fn test_payment_void_approved() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_type = "net.authorize.payment.void.created";
let response_code = 1; // Approved
let transaction_id = "60123456797";
let json_body = build_authorizedotnet_webhook_json_body(
event_type,
response_code,
transaction_id,
None,
Some("REF131"),
None,
Some("This transaction has been voided."),
);
// Test that webhook processing succeeds
let result = process_webhook_request(&mut client, json_body, true).await;
assert!(
result.is_ok(),
"Payment void approved webhook should be processed successfully"
);
});
}
#[tokio::test]
async fn test_payment_void_failed() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_type = "net.authorize.payment.void.created";
let response_code = 2; // Failed
let transaction_id = "60123456798";
let json_body = build_authorizedotnet_webhook_json_body(
event_type,
response_code,
transaction_id,
None,
Some("REF132"),
None,
Some("This void has failed."),
);
// Test that webhook processing succeeds
let result = process_webhook_request(&mut client, json_body, true).await;
assert!(
result.is_ok(),
"Payment void failed webhook should be processed successfully"
);
});
}
// --- Payment Prior Auth Capture Event Tests ---
#[tokio::test]
async fn test_payment_prior_auth_capture_approved() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_type = "net.authorize.payment.priorAuthCapture.created";
let response_code = 1; // Approved
let transaction_id = "60123456799";
let amount = Some(85.50);
let json_body = build_authorizedotnet_webhook_json_body(
event_type,
response_code,
transaction_id,
amount,
Some("REF133"),
None,
Some("This prior authorization capture has been approved."),
);
// Test that webhook processing succeeds
| {
"chunk": 3,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_5340641875733848070_4 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/authorizedotnet_webhook_test.rs
let result = process_webhook_request(&mut client, json_body, true).await;
assert!(
result.is_ok(),
"Payment prior auth capture approved webhook should be processed successfully"
);
});
}
#[tokio::test]
async fn test_payment_prior_auth_capture_declined() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_type = "net.authorize.payment.priorAuthCapture.created";
let response_code = 2; // Declined
let transaction_id = "60123456800";
let json_body = build_authorizedotnet_webhook_json_body(
event_type,
response_code,
transaction_id,
None,
Some("REF134"),
None,
Some("This prior authorization capture has been declined."),
);
// Test that webhook processing succeeds
let result = process_webhook_request(&mut client, json_body, true).await;
assert!(
result.is_ok(),
"Payment prior auth capture declined webhook should be processed successfully"
);
});
}
// --- Refund Event Tests ---
#[tokio::test]
async fn test_payment_refund_approved() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_type = "net.authorize.payment.refund.created";
let response_code = 1; // Approved
let transaction_id = "60123456801";
let amount = Some(50.25);
let json_body = build_authorizedotnet_webhook_json_body(
event_type,
response_code,
transaction_id,
amount,
Some("REF135"),
None,
Some("This refund has been approved."),
);
// Test that webhook processing succeeds
let result = process_webhook_request(&mut client, json_body, true).await;
assert!(
result.is_ok(),
"Payment refund approved webhook should be processed successfully"
);
});
}
#[tokio::test]
async fn test_payment_refund_declined() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_type = "net.authorize.payment.refund.created";
let response_code = 2; // Declined
let transaction_id = "60123456802";
let json_body = build_authorizedotnet_webhook_json_body(
event_type,
response_code,
transaction_id,
None,
Some("REF136"),
None,
Some("This refund has been declined."),
);
// Test that webhook processing succeeds
let result = process_webhook_request(&mut client, json_body, true).await;
assert!(
result.is_ok(),
"Payment refund declined webhook should be processed successfully"
);
});
}
#[tokio::test]
async fn test_payment_refund_held() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_type = "net.authorize.payment.refund.created";
let response_code = 4; // Held for review
let transaction_id = "60123456803";
let amount = Some(25.00);
let json_body = build_authorizedotnet_webhook_json_body(
event_type,
response_code,
transaction_id,
amount,
Some("REF137"),
None,
Some("This refund is being held for review."),
);
// Test that webhook processing succeeds
let result = process_webhook_request(&mut client, json_body, true).await;
assert!(
result.is_ok(),
"Payment refund held webhook should be processed successfully"
);
});
}
// --- Security and Error Tests ---
#[tokio::test]
async fn test_webhook_signature_verification_valid() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_type = "net.authorize.payment.authorization.created";
let response_code = 1;
let transaction_id = "60123456804";
let json_body = build_authorizedotnet_webhook_json_body(
event_type,
response_code,
transaction_id,
Some(100.0),
Some("REF138"),
Some("ABC123"),
Some("Valid signature test."),
);
// This should succeed with valid signature
let result = process_webhook_request(&mut client, json_body, true).await;
| {
"chunk": 4,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_5340641875733848070_5 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/authorizedotnet_webhook_test.rs
assert!(result.is_ok(), "Valid signature should be accepted");
});
}
#[tokio::test]
async fn test_webhook_missing_signature() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_type = "net.authorize.payment.authorization.created";
let response_code = 1;
let transaction_id = "60123456806";
let json_body = build_authorizedotnet_webhook_json_body(
event_type,
response_code,
transaction_id,
Some(100.0),
Some("REF140"),
Some("ABC123"),
Some("Missing signature test."),
);
// Process without signature - the gRPC server requires signatures even when verification is not mandatory
let result = process_webhook_request(&mut client, json_body, false).await;
// The gRPC server returns "Signature not found" when no signature is provided
// This is expected behavior even though verification is not mandatory for Authorize.Net
match result {
Ok(_) => {
// If it succeeds, that's fine - the system handled missing signature gracefully
}
Err(e) => {
// Expect signature not found error
assert!(
e.contains("Signature not found for incoming webhook"),
"Expected 'Signature not found' error but got: {e}"
);
}
}
});
}
#[tokio::test]
async fn test_webhook_malformed_body() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let malformed_json = json!({
"invalid": "structure",
"missing": "required_fields"
});
let request_body_bytes =
serde_json::to_vec(&malformed_json).expect("Failed to serialize malformed json");
let mut request = Request::new(PaymentServiceTransformRequest {
request_ref_id: Some(grpc_api_types::payments::Identifier {
id_type: Some(grpc_api_types::payments::identifier::IdType::Id(
"webhook_test".to_string(),
)),
}),
request_details: Some(RequestDetails {
method: grpc_api_types::payments::HttpMethod::Post.into(),
headers: std::collections::HashMap::new(),
uri: Some("/webhooks/authorizedotnet".to_string()),
query_params: None,
body: request_body_bytes,
}),
webhook_secrets: None,
state: None,
});
let auth = utils::credential_utils::load_connector_auth("authorizedotnet")
.expect("Failed to load authorizedotnet credentials");
let api_key = match auth {
domain_types::router_data::ConnectorAuthType::BodyKey { api_key, .. } => {
api_key.expose()
}
_ => panic!("Expected BodyKey auth type for authorizedotnet"),
};
// Get transaction_key from metadata
let metadata = utils::credential_utils::load_connector_metadata("authorizedotnet")
.expect("Failed to load authorizedotnet metadata");
let transaction_key = metadata
.get("transaction_key")
.expect("transaction_key not found in authorizedotnet metadata")
.clone();
request.metadata_mut().append(
"x-connector",
"authorizedotnet"
.parse()
.expect("Failed to parse x-connector"),
);
request.metadata_mut().append(
"x-auth",
"signature-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"),
);
request.metadata_mut().append(
"x-transaction-key",
transaction_key
.parse()
.expect("Failed to parse x-transaction-key"),
);
// This should fail due to malformed body
let response = client.transform(request).await;
// We expect this to fail or return an error response
match response {
Ok(_resp) => {
// If it succeeds, the response should indicate parsing failure
// We'll accept this as the system handled it gracefully
| {
"chunk": 5,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_5340641875733848070_6 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/authorizedotnet_webhook_test.rs
}
Err(_) => {
// This is expected - malformed body should cause failure
}
}
});
}
// --- Customer Created Event Tests ---
#[tokio::test]
async fn test_customer_created_approved() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_type = "net.authorize.customer.created";
let customer_profile_id = "394";
let payment_profile_id = "694";
let json_body = build_authorizedotnet_customer_webhook_json_body(
event_type,
customer_profile_id,
payment_profile_id,
Some("cust457"),
Some("Profile created by Subscription: 1447"),
);
// Test that webhook processing succeeds
let result = process_webhook_request(&mut client, json_body, true).await;
assert!(
result.is_ok(),
"Customer created webhook should be processed successfully"
);
});
}
#[tokio::test]
async fn test_customer_created_with_different_customer_id() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_type = "net.authorize.customer.created";
let customer_profile_id = "395";
let payment_profile_id = "695";
let json_body = build_authorizedotnet_customer_webhook_json_body(
event_type,
customer_profile_id,
payment_profile_id,
Some("cust458"),
Some("Profile created for mandate setup"),
);
// Test that webhook processing succeeds
let result = process_webhook_request(&mut client, json_body, true).await;
assert!(
result.is_ok(),
"Customer creation webhook with different ID should be processed successfully"
);
});
}
// --- Customer Payment Profile Created Event Tests ---
#[tokio::test]
async fn test_customer_payment_profile_created_individual() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_type = "net.authorize.customer.paymentProfile.created";
let customer_profile_id = 394;
let payment_profile_id = "694";
let customer_type = "individual";
let json_body = build_authorizedotnet_payment_profile_webhook_json_body(
event_type,
customer_profile_id,
payment_profile_id,
customer_type,
);
// Test that webhook processing succeeds
let result = process_webhook_request(&mut client, json_body, true).await;
assert!(
result.is_ok(),
"Customer payment profile created webhook for individual should be processed successfully"
);
});
}
#[tokio::test]
async fn test_customer_payment_profile_created_business() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_type = "net.authorize.customer.paymentProfile.created";
let customer_profile_id = 395;
let payment_profile_id = "695";
let customer_type = "business";
let json_body = build_authorizedotnet_payment_profile_webhook_json_body(
event_type,
customer_profile_id,
payment_profile_id,
customer_type,
);
// Test that webhook processing succeeds
let result = process_webhook_request(&mut client, json_body, true).await;
assert!(
result.is_ok(),
"Customer payment profile created webhook for business should be processed successfully"
);
});
}
#[tokio::test]
async fn test_webhook_unknown_event_type() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let unknown_event_type = "net.authorize.unknown.event.type";
let response_code = 1;
let transaction_id = "60123456807";
let json_body = build_authorizedotnet_webhook_json_body(
unknown_event_type,
response_code,
transaction_id,
Some(100.0),
Some("REF141"),
Some("ABC123"),
Some("Unknown event type test."),
);
let result = process_webhook_request(&mut client, json_body, true).await;
// The system should handle unknown event types gracefully
// This could either succeed with a default handling or fail gracefully
match result {
Ok(()) => {
// System handled unknown event type gracefully
| {
"chunk": 6,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_5340641875733848070_7 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/authorizedotnet_webhook_test.rs
}
Err(_) => {
// System appropriately rejected unknown event type
}
}
});
}
// --- Webhook Source Verification Tests ---
#[tokio::test]
async fn test_webhook_source_verification_valid_signature() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_type = "net.authorize.payment.authorization.created";
let response_code = 1;
let transaction_id = "60123456808";
let json_body = build_authorizedotnet_webhook_json_body(
event_type,
response_code,
transaction_id,
Some(100.0),
Some("REF142"),
Some("ABC123"),
Some("Valid signature verification test."),
);
// Test with valid signature - the helper function already generates correct signatures
let result = process_webhook_request(&mut client, json_body, true).await;
assert!(
result.is_ok(),
"Webhook with valid signature should be processed successfully"
);
});
}
#[tokio::test]
async fn test_webhook_source_verification_invalid_signature() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_type = "net.authorize.payment.authorization.created";
let response_code = 1;
let transaction_id = "60123456809";
let json_body = build_authorizedotnet_webhook_json_body(
event_type,
response_code,
transaction_id,
Some(100.0),
Some("REF143"),
Some("ABC123"),
Some("Invalid signature verification test."),
);
let request_body_bytes =
serde_json::to_vec(&json_body).expect("Failed to serialize json_body to Vec<u8>");
let mut headers = std::collections::HashMap::new();
// Add an invalid signature
headers.insert(
"X-ANET-Signature".to_string(),
"sha512=invalidhexsignature".to_string(),
);
// Get webhook_secret from metadata
let metadata = utils::credential_utils::load_connector_metadata("authorizedotnet")
.expect("Failed to load authorizedotnet metadata");
let webhook_secret = metadata
.get("webhook_secret")
.expect("webhook_secret not found in authorizedotnet metadata")
.clone();
let webhook_secrets = Some(grpc_api_types::payments::WebhookSecrets {
secret: webhook_secret.clone(),
additional_secret: None,
});
let mut request = Request::new(PaymentServiceTransformRequest {
request_ref_id: Some(grpc_api_types::payments::Identifier {
id_type: Some(grpc_api_types::payments::identifier::IdType::Id(
"webhook_test".to_string(),
)),
}),
request_details: Some(RequestDetails {
method: grpc_api_types::payments::HttpMethod::Post.into(),
headers,
uri: Some("/webhooks/authorizedotnet".to_string()),
query_params: None,
body: request_body_bytes,
}),
webhook_secrets,
state: None,
});
let auth = utils::credential_utils::load_connector_auth("authorizedotnet")
.expect("Failed to load authorizedotnet 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 authorizedotnet"),
};
request.metadata_mut().append(
"x-connector",
"authorizedotnet"
.parse()
.expect("Failed to parse x-connector"),
);
request.metadata_mut().append(
"x-auth",
"body-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"),
);
request
.metadata_mut()
.append("x-key1", key1.parse().expect("Failed to parse x-key1"));
request.metadata_mut().append(
"x-merchant-id",
"test_merchant"
.parse()
| {
"chunk": 7,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_5340641875733848070_8 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/authorizedotnet_webhook_test.rs
.expect("Failed to parse x-merchant-id"),
);
request.metadata_mut().append(
"x-tenant-id",
"default".parse().expect("Failed to parse x-tenant-id"),
);
request.metadata_mut().append(
"x-request-id",
"webhook_test_req"
.parse()
.expect("Failed to parse x-request-id"),
);
// This should still process the webhook but with source_verified = false
let response = client.transform(request).await;
assert!(
response.is_ok(),
"Webhook with invalid signature should still be processed"
);
// Note: The response should have source_verified = false, but UCS continues processing
});
}
#[tokio::test]
async fn test_webhook_source_verification_missing_signature() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_type = "net.authorize.payment.authorization.created";
let response_code = 1;
let transaction_id = "60123456810";
let json_body = build_authorizedotnet_webhook_json_body(
event_type,
response_code,
transaction_id,
Some(100.0),
Some("REF144"),
Some("ABC123"),
Some("Missing signature verification test."),
);
let request_body_bytes =
serde_json::to_vec(&json_body).expect("Failed to serialize json_body to Vec<u8>");
// Don't add any signature header
let headers = std::collections::HashMap::new();
// Get webhook_secret from metadata
let metadata = utils::credential_utils::load_connector_metadata("authorizedotnet")
.expect("Failed to load authorizedotnet metadata");
let webhook_secret = metadata
.get("webhook_secret")
.expect("webhook_secret not found in authorizedotnet metadata")
.clone();
let webhook_secrets = Some(grpc_api_types::payments::WebhookSecrets {
secret: webhook_secret.clone(),
additional_secret: None,
});
let mut request = Request::new(PaymentServiceTransformRequest {
request_ref_id: Some(grpc_api_types::payments::Identifier {
id_type: Some(grpc_api_types::payments::identifier::IdType::Id(
"webhook_test".to_string(),
)),
}),
request_details: Some(RequestDetails {
method: grpc_api_types::payments::HttpMethod::Post.into(),
headers,
uri: Some("/webhooks/authorizedotnet".to_string()),
query_params: None,
body: request_body_bytes,
}),
webhook_secrets,
state: None,
});
let auth = utils::credential_utils::load_connector_auth("authorizedotnet")
.expect("Failed to load authorizedotnet 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 authorizedotnet"),
};
request.metadata_mut().append(
"x-connector",
"authorizedotnet"
.parse()
.expect("Failed to parse x-connector"),
);
request.metadata_mut().append(
"x-auth",
"body-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"),
);
request
.metadata_mut()
.append("x-key1", key1.parse().expect("Failed to parse x-key1"));
request.metadata_mut().append(
"x-merchant-id",
"test_merchant"
.parse()
.expect("Failed to parse x-merchant-id"),
);
request.metadata_mut().append(
"x-tenant-id",
"default".parse().expect("Failed to parse x-tenant-id"),
);
request.metadata_mut().append(
"x-request-id",
"webhook_test_req"
.parse()
.expect("Failed to parse x-request-id"),
);
| {
"chunk": 8,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_5340641875733848070_9 | clm | mini_chunk | // connector-service/backend/grpc-server/tests/beta_tests/authorizedotnet_webhook_test.rs
// This should still process the webhook but with source_verified = false
let response = client.transform(request).await;
assert!(
response.is_ok(),
"Webhook without signature should still be processed"
);
// Note: The response should have source_verified = false, but UCS continues processing
});
}
#[tokio::test]
async fn test_webhook_source_verification_no_secret_provided() {
grpc_test!(client, PaymentServiceClient<Channel>, {
let event_type = "net.authorize.payment.authorization.created";
let response_code = 1;
let transaction_id = "60123456811";
let json_body = build_authorizedotnet_webhook_json_body(
event_type,
response_code,
transaction_id,
Some(100.0),
Some("REF145"),
Some("ABC123"),
Some("No secret provided verification test."),
);
let request_body_bytes =
serde_json::to_vec(&json_body).expect("Failed to serialize json_body to Vec<u8>");
let mut headers = std::collections::HashMap::new();
headers.insert(
"X-ANET-Signature".to_string(),
"sha512=somesignature".to_string(),
);
// Don't provide webhook secrets (None)
let webhook_secrets = None;
let mut request = Request::new(PaymentServiceTransformRequest {
request_ref_id: Some(grpc_api_types::payments::Identifier {
id_type: Some(grpc_api_types::payments::identifier::IdType::Id(
"webhook_test".to_string(),
)),
}),
request_details: Some(RequestDetails {
method: grpc_api_types::payments::HttpMethod::Post.into(),
headers,
uri: Some("/webhooks/authorizedotnet".to_string()),
query_params: None,
body: request_body_bytes,
}),
webhook_secrets,
state: None,
});
let auth = utils::credential_utils::load_connector_auth("authorizedotnet")
.expect("Failed to load authorizedotnet 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 authorizedotnet"),
};
request.metadata_mut().append(
"x-connector",
"authorizedotnet"
.parse()
.expect("Failed to parse x-connector"),
);
request.metadata_mut().append(
"x-auth",
"body-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"),
);
request
.metadata_mut()
.append("x-key1", key1.parse().expect("Failed to parse x-key1"));
request.metadata_mut().append(
"x-merchant-id",
"test_merchant"
.parse()
.expect("Failed to parse x-merchant-id"),
);
request.metadata_mut().append(
"x-tenant-id",
"default".parse().expect("Failed to parse x-tenant-id"),
);
request.metadata_mut().append(
"x-request-id",
"webhook_test_req"
.parse()
.expect("Failed to parse x-request-id"),
);
// This should process the webhook with source_verified = false (no secret to verify against)
let response = client.transform(request).await;
assert!(
response.is_ok(),
"Webhook without webhook secret should still be processed"
);
// Note: The response should have source_verified = false, but UCS continues processing
});
}
| {
"chunk": 9,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_5381403527828220498_0 | clm | mini_chunk | // 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": 0,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-2425448326891067086_0 | clm | mini_chunk | // 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
| {
"chunk": 0,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-2425448326891067086_1 | clm | mini_chunk | // connector-service/backend/grpc-server/src/error.rs
| 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,
| {
"chunk": 1,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-2425448326891067086_2 | clm | mini_chunk | // connector-service/backend/grpc-server/src/error.rs
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": 2,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_8674746398584233230_0 | clm | mini_chunk | // 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 {
| {
"chunk": 0,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_8674746398584233230_1 | clm | mini_chunk | // connector-service/backend/grpc-server/src/configs.rs
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": 1,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-1708118210077285516_0 | clm | mini_chunk | // 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": 0,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-2612312103591988008_0 | clm | mini_chunk | // 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 {
| {
"chunk": 0,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-2612312103591988008_1 | clm | mini_chunk | // connector-service/backend/grpc-server/src/app.rs
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)
| {
"chunk": 1,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-2612312103591988008_2 | clm | mini_chunk | // connector-service/backend/grpc-server/src/app.rs
.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": 2,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_4018572258718428657_0 | clm | mini_chunk | // connector-service/backend/grpc-server/src/utils.rs
use std::{str::FromStr, sync::Arc};
use common_utils::{
consts::{
self, X_API_KEY, X_API_SECRET, X_AUTH, X_AUTH_KEY_MAP, X_KEY1, X_KEY2, X_SHADOW_MODE,
},
errors::CustomResult,
events::{Event, EventStage, FlowName, MaskedSerdeValue},
lineage::LineageIds,
};
use domain_types::{
connector_flow::{
Accept, Authenticate, Authorize, Capture, CreateOrder, CreateSessionToken, DefendDispute,
PSync, PaymentMethodToken, PostAuthenticate, PreAuthenticate, RSync, Refund, RepeatPayment,
SetupMandate, SubmitEvidence, Void, VoidPC,
},
connector_types,
errors::{ApiError, ApplicationErrorResponse},
router_data::ConnectorAuthType,
};
use error_stack::{Report, ResultExt};
use http::request::Request;
use hyperswitch_masking;
use tonic::metadata;
use crate::{configs, error::ResultExtGrpc, request::RequestData};
use std::collections::HashMap;
// Helper function to map flow markers to flow names
pub fn flow_marker_to_flow_name<F>() -> FlowName
where
F: 'static,
{
let type_id = std::any::TypeId::of::<F>();
if type_id == std::any::TypeId::of::<Authorize>() {
FlowName::Authorize
} else if type_id == std::any::TypeId::of::<PSync>() {
FlowName::Psync
} else if type_id == std::any::TypeId::of::<RSync>() {
FlowName::Rsync
} else if type_id == std::any::TypeId::of::<Void>() {
FlowName::Void
} else if type_id == std::any::TypeId::of::<VoidPC>() {
FlowName::VoidPostCapture
} else if type_id == std::any::TypeId::of::<Refund>() {
FlowName::Refund
} else if type_id == std::any::TypeId::of::<Capture>() {
FlowName::Capture
} else if type_id == std::any::TypeId::of::<SetupMandate>() {
FlowName::SetupMandate
} else if type_id == std::any::TypeId::of::<RepeatPayment>() {
FlowName::RepeatPayment
} else if type_id == std::any::TypeId::of::<CreateOrder>() {
FlowName::CreateOrder
} else if type_id == std::any::TypeId::of::<CreateSessionToken>() {
FlowName::CreateSessionToken
} else if type_id == std::any::TypeId::of::<Accept>() {
FlowName::AcceptDispute
} else if type_id == std::any::TypeId::of::<DefendDispute>() {
FlowName::DefendDispute
} else if type_id == std::any::TypeId::of::<SubmitEvidence>() {
FlowName::SubmitEvidence
} else if type_id == std::any::TypeId::of::<PaymentMethodToken>() {
FlowName::PaymentMethodToken
} else if type_id == std::any::TypeId::of::<PreAuthenticate>() {
FlowName::PreAuthenticate
} else if type_id == std::any::TypeId::of::<Authenticate>() {
FlowName::Authenticate
} else if type_id == std::any::TypeId::of::<PostAuthenticate>() {
FlowName::PostAuthenticate
} else {
tracing::warn!("Unknown flow marker type: {}", std::any::type_name::<F>());
FlowName::Unknown
}
}
/// Extract lineage fields from header
pub fn extract_lineage_fields_from_metadata(
metadata: &metadata::MetadataMap,
config: &configs::LineageConfig,
) -> LineageIds<'static> {
if !config.enabled {
return LineageIds::empty(&config.field_prefix).to_owned();
}
metadata
.get(&config.header_name)
.and_then(|value| value.to_str().ok())
.map(|header_value| LineageIds::new(&config.field_prefix, header_value))
.transpose()
.inspect(|value| {
tracing::info!(
parsed_fields = ?value,
"Successfully parsed lineage header"
)
})
.inspect_err(|err| {
tracing::warn!(
error = %err,
"Failed to parse lineage header, continuing without lineage fields"
)
})
.ok()
.flatten()
.unwrap_or_else(|| LineageIds::empty(&config.field_prefix))
.to_owned()
}
/// Record the header's fields in request's trace
pub fn record_fields_from_header<B: hyper::body::Body>(request: &Request<B>) -> tracing::Span {
let url_path = request.uri().path();
let span = tracing::debug_span!(
"request",
uri = %url_path,
version = ?request.version(),
tenant_id = tracing::field::Empty,
request_id = tracing::field::Empty,
);
request
.headers()
.get(consts::X_TENANT_ID)
| {
"chunk": 0,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_4018572258718428657_1 | clm | mini_chunk | // connector-service/backend/grpc-server/src/utils.rs
.and_then(|value| value.to_str().ok())
.map(|tenant_id| span.record("tenant_id", tenant_id));
request
.headers()
.get(consts::X_REQUEST_ID)
.and_then(|value| value.to_str().ok())
.map(|request_id| span.record("request_id", request_id));
span
}
/// Struct to hold extracted metadata payload
///
/// SECURITY WARNING: This struct should only contain non-sensitive business metadata.
/// For any sensitive data (API keys, tokens, credentials, etc.), always:
/// 1. Wrap in hyperswitch_masking::Secret<T>
/// 2. Extract via MaskedMetadata methods instead of adding here
///
#[derive(Clone, Debug)]
pub struct MetadataPayload {
pub tenant_id: String,
pub request_id: String,
pub merchant_id: String,
pub connector: connector_types::ConnectorEnum,
pub lineage_ids: LineageIds<'static>,
pub connector_auth_type: ConnectorAuthType,
pub reference_id: Option<String>,
pub shadow_mode: bool,
}
pub fn get_metadata_payload(
metadata: &metadata::MetadataMap,
server_config: Arc<configs::Config>,
) -> CustomResult<MetadataPayload, ApplicationErrorResponse> {
let connector = connector_from_metadata(metadata)?;
let merchant_id = merchant_id_from_metadata(metadata)?;
let tenant_id = tenant_id_from_metadata(metadata)?;
let request_id = request_id_from_metadata(metadata)?;
let lineage_ids = extract_lineage_fields_from_metadata(metadata, &server_config.lineage);
let connector_auth_type = auth_from_metadata(metadata)?;
let reference_id = reference_id_from_metadata(metadata)?;
let shadow_mode = shadow_mode_from_metadata(metadata);
Ok(MetadataPayload {
tenant_id,
request_id,
merchant_id,
connector,
lineage_ids,
connector_auth_type,
reference_id,
shadow_mode,
})
}
pub fn connector_from_metadata(
metadata: &metadata::MetadataMap,
) -> CustomResult<connector_types::ConnectorEnum, ApplicationErrorResponse> {
parse_metadata(metadata, consts::X_CONNECTOR_NAME).and_then(|inner| {
connector_types::ConnectorEnum::from_str(inner).map_err(|e| {
Report::new(ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "INVALID_CONNECTOR".to_string(),
error_identifier: 400,
error_message: format!("Invalid connector: {e}"),
error_object: None,
}))
})
})
}
pub fn merchant_id_from_metadata(
metadata: &metadata::MetadataMap,
) -> CustomResult<String, ApplicationErrorResponse> {
parse_metadata(metadata, consts::X_MERCHANT_ID)
.map(|inner| inner.to_string())
.map_err(|e| {
Report::new(ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "MISSING_MERCHANT_ID".to_string(),
error_identifier: 400,
error_message: format!("Missing merchant ID in request metadata: {e}"),
error_object: None,
}))
})
}
pub fn request_id_from_metadata(
metadata: &metadata::MetadataMap,
) -> CustomResult<String, ApplicationErrorResponse> {
parse_metadata(metadata, consts::X_REQUEST_ID)
.map(|inner| inner.to_string())
.map_err(|e| {
Report::new(ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "MISSING_REQUEST_ID".to_string(),
error_identifier: 400,
error_message: format!("Missing request ID in request metadata: {e}"),
error_object: None,
}))
})
}
pub fn tenant_id_from_metadata(
metadata: &metadata::MetadataMap,
) -> CustomResult<String, ApplicationErrorResponse> {
parse_metadata(metadata, consts::X_TENANT_ID)
.map(|s| s.to_string())
.or_else(|_| Ok("DefaultTenantId".to_string()))
}
pub fn reference_id_from_metadata(
metadata: &metadata::MetadataMap,
) -> CustomResult<Option<String>, ApplicationErrorResponse> {
parse_optional_metadata(metadata, consts::X_REFERENCE_ID).map(|s| s.map(|s| s.to_string()))
}
pub fn shadow_mode_from_metadata(metadata: &metadata::MetadataMap) -> bool {
parse_optional_metadata(metadata, X_SHADOW_MODE)
.ok()
.flatten()
.map(|value| value.to_lowercase() == "true")
.unwrap_or(false)
}
pub fn auth_from_metadata(
metadata: &metadata::MetadataMap,
| {
"chunk": 1,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_4018572258718428657_2 | clm | mini_chunk | // connector-service/backend/grpc-server/src/utils.rs
) -> CustomResult<ConnectorAuthType, ApplicationErrorResponse> {
let auth = parse_metadata(metadata, X_AUTH)?;
#[allow(clippy::wildcard_in_or_patterns)]
match auth {
"header-key" => Ok(ConnectorAuthType::HeaderKey {
api_key: parse_metadata(metadata, X_API_KEY)?.to_string().into(),
}),
"body-key" => Ok(ConnectorAuthType::BodyKey {
api_key: parse_metadata(metadata, X_API_KEY)?.to_string().into(),
key1: parse_metadata(metadata, X_KEY1)?.to_string().into(),
}),
"signature-key" => Ok(ConnectorAuthType::SignatureKey {
api_key: parse_metadata(metadata, X_API_KEY)?.to_string().into(),
key1: parse_metadata(metadata, X_KEY1)?.to_string().into(),
api_secret: parse_metadata(metadata, X_API_SECRET)?.to_string().into(),
}),
"multi-auth-key" => Ok(ConnectorAuthType::MultiAuthKey {
api_key: parse_metadata(metadata, X_API_KEY)?.to_string().into(),
key1: parse_metadata(metadata, X_KEY1)?.to_string().into(),
key2: parse_metadata(metadata, X_KEY2)?.to_string().into(),
api_secret: parse_metadata(metadata, X_API_SECRET)?.to_string().into(),
}),
"no-key" => Ok(ConnectorAuthType::NoKey),
"temporary-auth" => Ok(ConnectorAuthType::TemporaryAuth),
"currency-auth-key" => {
let auth_key_map_str = parse_metadata(metadata, X_AUTH_KEY_MAP)?;
let auth_key_map: HashMap<
common_enums::enums::Currency,
common_utils::pii::SecretSerdeValue,
> = serde_json::from_str(auth_key_map_str).change_context(
ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "INVALID_AUTH_KEY_MAP".to_string(),
error_identifier: 400,
error_message: "Invalid auth-key-map format".to_string(),
error_object: None,
}),
)?;
Ok(ConnectorAuthType::CurrencyAuthKey { auth_key_map })
}
"certificate-auth" | _ => Err(Report::new(ApplicationErrorResponse::BadRequest(
ApiError {
sub_code: "INVALID_AUTH_TYPE".to_string(),
error_identifier: 400,
error_message: format!("Invalid auth type: {auth}"),
error_object: None,
},
))),
}
}
fn parse_metadata<'a>(
metadata: &'a metadata::MetadataMap,
key: &str,
) -> CustomResult<&'a str, ApplicationErrorResponse> {
metadata
.get(key)
.ok_or_else(|| {
Report::new(ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "MISSING_METADATA".to_string(),
error_identifier: 400,
error_message: format!("Missing {key} in request metadata"),
error_object: None,
}))
})
.and_then(|value| {
value.to_str().map_err(|e| {
Report::new(ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "INVALID_METADATA".to_string(),
error_identifier: 400,
error_message: format!("Invalid {key} in request metadata: {e}"),
error_object: None,
}))
})
})
}
fn parse_optional_metadata<'a>(
metadata: &'a metadata::MetadataMap,
key: &str,
) -> CustomResult<Option<&'a str>, ApplicationErrorResponse> {
metadata
.get(key)
.map(|value| value.to_str())
.transpose()
.map_err(|e| {
Report::new(ApplicationErrorResponse::BadRequest(ApiError {
sub_code: "INVALID_METADATA".to_string(),
error_identifier: 400,
error_message: format!("Invalid {key} in request metadata: {e}"),
error_object: None,
}))
})
}
pub fn log_before_initialization<T>(
request_data: &RequestData<T>,
service_name: &str,
) -> CustomResult<(), ApplicationErrorResponse>
where
T: serde::Serialize,
{
let metadata_payload = &request_data.extracted_metadata;
let MetadataPayload {
connector,
merchant_id,
tenant_id,
request_id,
..
} = metadata_payload;
let current_span = tracing::Span::current();
| {
"chunk": 2,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_4018572258718428657_3 | clm | mini_chunk | // connector-service/backend/grpc-server/src/utils.rs
let req_body_json = match hyperswitch_masking::masked_serialize(&request_data.payload) {
Ok(masked_value) => masked_value.to_string(),
Err(e) => {
tracing::error!("Masked serialization error: {:?}", e);
"<masked serialization error>".to_string()
}
};
current_span.record("service_name", service_name);
current_span.record("request_body", req_body_json);
current_span.record("gateway", connector.to_string());
current_span.record("merchant_id", merchant_id);
current_span.record("tenant_id", tenant_id);
current_span.record("request_id", request_id);
tracing::info!("Golden Log Line (incoming)");
Ok(())
}
pub fn log_after_initialization<T>(result: &Result<tonic::Response<T>, tonic::Status>)
where
T: serde::Serialize + std::fmt::Debug,
{
let current_span = tracing::Span::current();
// let duration = start_time.elapsed().as_millis();
// current_span.record("response_time", duration);
match &result {
Ok(response) => {
current_span.record("response_body", tracing::field::debug(response.get_ref()));
let res_ref = response.get_ref();
// Try converting to JSON Value
if let Ok(serde_json::Value::Object(map)) = serde_json::to_value(res_ref) {
if let Some(status_val) = map.get("status") {
let status_num_opt = status_val.as_number();
let status_u32_opt: Option<u32> = status_num_opt
.and_then(|n| n.as_u64())
.and_then(|n| u32::try_from(n).ok());
let status_str = if let Some(s) = status_u32_opt {
common_enums::AttemptStatus::try_from(s)
.unwrap_or(common_enums::AttemptStatus::Unknown)
.to_string()
} else {
common_enums::AttemptStatus::Unknown.to_string()
};
current_span.record("flow_specific_fields.status", status_str);
}
} else {
tracing::warn!("Could not serialize response to JSON to extract status");
}
}
Err(status) => {
current_span.record("error_message", status.message());
current_span.record("status_code", status.code().to_string());
}
}
tracing::info!("Golden Log Line (incoming)");
}
pub async fn grpc_logging_wrapper<T, F, Fut, R>(
request: tonic::Request<T>,
service_name: &str,
config: Arc<configs::Config>,
flow_name: FlowName,
handler: F,
) -> Result<tonic::Response<R>, tonic::Status>
where
T: serde::Serialize
+ std::fmt::Debug
+ Send
+ 'static
+ hyperswitch_masking::ErasedMaskSerialize,
F: FnOnce(RequestData<T>) -> Fut + Send,
Fut: std::future::Future<Output = Result<tonic::Response<R>, tonic::Status>> + Send,
R: serde::Serialize + std::fmt::Debug + hyperswitch_masking::ErasedMaskSerialize,
{
let current_span = tracing::Span::current();
let start_time = tokio::time::Instant::now();
let masked_request_data =
MaskedSerdeValue::from_masked_optional(request.get_ref(), "grpc_request");
let mut event_metadata_payload = None;
let mut event_headers = HashMap::new();
let grpc_response = async {
let request_data = RequestData::from_grpc_request(request, config.clone())?;
log_before_initialization(&request_data, service_name).into_grpc_status()?;
event_headers = request_data.masked_metadata.get_all_masked();
event_metadata_payload = Some(request_data.extracted_metadata.clone());
let result = handler(request_data).await;
let duration = start_time.elapsed().as_millis();
current_span.record("response_time", duration);
log_after_initialization(&result);
result
}
.await;
create_and_emit_grpc_event(
masked_request_data,
&grpc_response,
start_time,
flow_name,
&config,
event_metadata_payload.as_ref(),
event_headers,
);
grpc_response
}
fn create_and_emit_grpc_event<R>(
masked_request_data: Option<MaskedSerdeValue>,
grpc_response: &Result<tonic::Response<R>, tonic::Status>,
| {
"chunk": 3,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_4018572258718428657_4 | clm | mini_chunk | // connector-service/backend/grpc-server/src/utils.rs
start_time: tokio::time::Instant,
flow_name: FlowName,
config: &configs::Config,
metadata_payload: Option<&MetadataPayload>,
masked_headers: HashMap<String, String>,
) where
R: serde::Serialize,
{
let mut grpc_event = Event {
request_id: metadata_payload.map_or("unknown".to_string(), |md| md.request_id.clone()),
timestamp: chrono::Utc::now().timestamp().into(),
flow_type: flow_name,
connector: metadata_payload.map_or("unknown".to_string(), |md| md.connector.to_string()),
url: None,
stage: EventStage::GrpcRequest,
latency_ms: Some(u64::try_from(start_time.elapsed().as_millis()).unwrap_or(u64::MAX)),
status_code: None,
request_data: masked_request_data,
response_data: None,
headers: masked_headers,
additional_fields: HashMap::new(),
lineage_ids: metadata_payload
.map_or_else(|| LineageIds::empty(""), |md| md.lineage_ids.clone()),
};
grpc_event
.add_reference_id(metadata_payload.and_then(|metadata| metadata.reference_id.as_deref()));
match grpc_response {
Ok(response) => grpc_event.set_grpc_success_response(response.get_ref()),
Err(error) => grpc_event.set_grpc_error_response(error),
}
common_utils::emit_event_with_config(grpc_event, &config.events);
}
#[macro_export]
macro_rules! implement_connector_operation {
(
fn_name: $fn_name:ident,
log_prefix: $log_prefix:literal,
request_type: $request_type:ty,
response_type: $response_type:ty,
flow_marker: $flow_marker:ty,
resource_common_data_type: $resource_common_data_type:ty,
request_data_type: $request_data_type:ty,
response_data_type: $response_data_type:ty,
request_data_constructor: $request_data_constructor:path,
common_flow_data_constructor: $common_flow_data_constructor:path,
generate_response_fn: $generate_response_fn:path,
all_keys_required: $all_keys_required:expr
) => {
async fn $fn_name(
&self,
request: $crate::request::RequestData<$request_type>,
) -> Result<tonic::Response<$response_type>, tonic::Status> {
tracing::info!(concat!($log_prefix, "_FLOW: initiated"));
let service_name = request
.extensions
.get::<String>()
.cloned()
.unwrap_or_else(|| "unknown_service".to_string());
let result = Box::pin(async{
let $crate::request::RequestData {
payload,
extracted_metadata: metadata_payload,
masked_metadata,
extensions: _ // unused in macro
} = request;
let (connector, request_id, connector_auth_details) = (metadata_payload.connector, metadata_payload.request_id, metadata_payload.connector_auth_type);
// Get connector data
let connector_data: ConnectorData<domain_types::payment_method_data::DefaultPCIHolder> = connector_integration::types::ConnectorData::get_connector_by_name(&connector);
// Get connector integration
let connector_integration: interfaces::connector_integration_v2::BoxedConnectorIntegrationV2<
'_,
$flow_marker,
$resource_common_data_type,
$request_data_type,
$response_data_type,
> = connector_data.connector.get_connector_integration_v2();
// Create connector request data
let specific_request_data = $request_data_constructor(payload.clone())
.into_grpc_status()?;
// Create common request data
let common_flow_data = $common_flow_data_constructor((payload.clone(), self.config.connectors.clone(), &masked_metadata))
.into_grpc_status()?;
// Create router data
let router_data = domain_types::router_data_v2::RouterDataV2::<
$flow_marker,
$resource_common_data_type,
$request_data_type,
$response_data_type,
> {
flow: std::marker::PhantomData,
resource_common_data: common_flow_data,
| {
"chunk": 4,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_4018572258718428657_5 | clm | mini_chunk | // connector-service/backend/grpc-server/src/utils.rs
connector_auth_type: connector_auth_details,
request: specific_request_data,
response: Err(domain_types::router_data::ErrorResponse::default()),
};
// Execute connector processing
let flow_name = $crate::utils::flow_marker_to_flow_name::<$flow_marker>();
let event_params = external_services::service::EventProcessingParams {
connector_name: &connector.to_string(),
service_name: &service_name,
flow_name,
event_config: &self.config.events,
request_id: &request_id,
lineage_ids: &metadata_payload.lineage_ids,
reference_id: &metadata_payload.reference_id,
shadow_mode: metadata_payload.shadow_mode,
};
let response_result = external_services::service::execute_connector_processing_step(
&self.config.proxy,
connector_integration,
router_data,
$all_keys_required,
event_params,
None,
common_enums::CallConnectorAction::Trigger,
)
.await
.switch()
.into_grpc_status()?;
// Generate response
let final_response = $generate_response_fn(response_result)
.into_grpc_status()?;
Ok(tonic::Response::new(final_response))
}).await;
result
}
}
}
| {
"chunk": 5,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_8407789757677062419_0 | clm | mini_chunk | // 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": 0,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-8301123723402502079_0 | clm | mini_chunk | // 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": 0,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-1230957448226898650_0 | clm | mini_chunk | // 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())?;
| {
"chunk": 0,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-1230957448226898650_1 | clm | mini_chunk | // connector-service/backend/grpc-server/src/logger/formatter.rs
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>,
{
| {
"chunk": 1,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-1230957448226898650_2 | clm | mini_chunk | // connector-service/backend/grpc-server/src/logger/formatter.rs
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": 2,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_6348302695617038329_0 | clm | mini_chunk | // 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 = {
| {
"chunk": 0,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_6348302695617038329_1 | clm | mini_chunk | // connector-service/backend/grpc-server/src/logger/storage.rs
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": 1,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_8913100032470277647_0 | clm | mini_chunk | // 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);
}
| {
"chunk": 0,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_8913100032470277647_1 | clm | mini_chunk | // connector-service/backend/grpc-server/src/logger/setup.rs
// 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": 1,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-372326334623076254_0 | clm | mini_chunk | // 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> {
| {
"chunk": 0,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_-372326334623076254_1 | clm | mini_chunk | // connector-service/backend/grpc-server/src/server/refunds.rs
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": 1,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_8474653292087038763_0 | clm | mini_chunk | // connector-service/backend/grpc-server/src/server/payments.rs
use std::{collections::HashMap, fmt::Debug, sync::Arc};
use common_enums;
use common_utils::{
errors::CustomResult, events::FlowName, lineage, metadata::MaskedMetadata, SecretSerdeValue,
};
use connector_integration::types::ConnectorData;
use domain_types::{
connector_flow::{
Authenticate, Authorize, Capture, CreateAccessToken, CreateConnectorCustomer, CreateOrder,
CreateSessionToken, PSync, PaymentMethodToken, PostAuthenticate, PreAuthenticate, Refund,
RepeatPayment, SetupMandate, Void, VoidPC,
},
connector_types::{
AccessTokenRequestData, AccessTokenResponseData, ConnectorCustomerData,
ConnectorCustomerResponse, ConnectorResponseHeaders, PaymentCreateOrderData,
PaymentCreateOrderResponse, PaymentFlowData, PaymentMethodTokenResponse,
PaymentMethodTokenizationData, PaymentVoidData, PaymentsAuthenticateData,
PaymentsAuthorizeData, PaymentsCancelPostCaptureData, PaymentsCaptureData,
PaymentsPostAuthenticateData, PaymentsPreAuthenticateData, PaymentsResponseData,
PaymentsSyncData, RawConnectorRequestResponse, RefundFlowData, RefundsData,
RefundsResponseData, RepeatPaymentData, SessionTokenRequestData, SessionTokenResponseData,
SetupMandateRequestData,
},
errors::{ApiError, ApplicationErrorResponse},
payment_method_data::{DefaultPCIHolder, PaymentMethodDataTypes, VaultTokenHolder},
router_data::{ConnectorAuthType, ErrorResponse},
router_data_v2::RouterDataV2,
router_response_types,
types::{
generate_payment_capture_response, generate_payment_sync_response,
generate_payment_void_post_capture_response, generate_payment_void_response,
generate_refund_response, generate_repeat_payment_response,
generate_setup_mandate_response,
},
utils::{ForeignFrom, ForeignTryFrom},
};
use error_stack::ResultExt;
use external_services::service::EventProcessingParams;
use grpc_api_types::payments::{
payment_method, payment_service_server::PaymentService, DisputeResponse,
PaymentServiceAuthenticateRequest, PaymentServiceAuthenticateResponse,
PaymentServiceAuthorizeRequest, PaymentServiceAuthorizeResponse, PaymentServiceCaptureRequest,
PaymentServiceCaptureResponse, PaymentServiceDisputeRequest, PaymentServiceGetRequest,
PaymentServiceGetResponse, PaymentServicePostAuthenticateRequest,
PaymentServicePostAuthenticateResponse, PaymentServicePreAuthenticateRequest,
PaymentServicePreAuthenticateResponse, PaymentServiceRefundRequest,
PaymentServiceRegisterRequest, PaymentServiceRegisterResponse,
PaymentServiceRepeatEverythingRequest, PaymentServiceRepeatEverythingResponse,
PaymentServiceTransformRequest, PaymentServiceTransformResponse,
PaymentServiceVoidPostCaptureRequest, PaymentServiceVoidPostCaptureResponse,
PaymentServiceVoidRequest, PaymentServiceVoidResponse, RefundResponse,
WebhookTransformationStatus,
};
use hyperswitch_masking::ExposeInterface;
use injector::{TokenData, VaultConnectors};
use interfaces::connector_integration_v2::BoxedConnectorIntegrationV2;
use tracing::info;
use crate::{
configs::Config,
error::{IntoGrpcStatus, PaymentAuthorizationError, ReportSwitchExt, ResultExtGrpc},
implement_connector_operation,
request::RequestData,
utils::{self, grpc_logging_wrapper},
};
#[derive(Debug, Clone)]
struct EventParams<'a> {
_connector_name: &'a str,
_service_name: &'a str,
request_id: &'a str,
lineage_ids: &'a lineage::LineageIds<'a>,
reference_id: &'a Option<String>,
shadow_mode: bool,
}
/// Helper function for converting CardDetails to TokenData with structured types
#[derive(Debug, serde::Serialize)]
struct CardTokenData {
card_number: String,
cvv: String,
exp_month: String,
exp_year: String,
}
trait ToTokenData {
fn to_token_data(&self) -> TokenData;
fn to_token_data_with_vault(&self, vault_connector: VaultConnectors) -> TokenData;
}
impl ToTokenData for grpc_api_types::payments::CardDetails {
fn to_token_data(&self) -> TokenData {
self.to_token_data_with_vault(VaultConnectors::VGS)
}
fn to_token_data_with_vault(&self, vault_connector: VaultConnectors) -> TokenData {
let card_data = CardTokenData {
card_number: self
| {
"chunk": 0,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_8474653292087038763_1 | clm | mini_chunk | // connector-service/backend/grpc-server/src/server/payments.rs
.card_number
.as_ref()
.map(|cn| cn.to_string())
.unwrap_or_default(),
cvv: self
.card_cvc
.as_ref()
.map(|cvc| cvc.clone().expose().to_string())
.unwrap_or_default(),
exp_month: self
.card_exp_month
.as_ref()
.map(|em| em.clone().expose().to_string())
.unwrap_or_default(),
exp_year: self
.card_exp_year
.as_ref()
.map(|ey| ey.clone().expose().to_string())
.unwrap_or_default(),
};
let card_json = serde_json::to_value(card_data).unwrap_or(serde_json::Value::Null);
TokenData {
specific_token_data: SecretSerdeValue::new(card_json),
vault_connector,
}
}
}
// Helper trait for payment operations
trait PaymentOperationsInternal {
async fn internal_void_payment(
&self,
request: RequestData<PaymentServiceVoidRequest>,
) -> Result<tonic::Response<PaymentServiceVoidResponse>, tonic::Status>;
async fn internal_void_post_capture(
&self,
request: RequestData<PaymentServiceVoidPostCaptureRequest>,
) -> Result<tonic::Response<PaymentServiceVoidPostCaptureResponse>, tonic::Status>;
async fn internal_refund(
&self,
request: RequestData<PaymentServiceRefundRequest>,
) -> Result<tonic::Response<RefundResponse>, tonic::Status>;
async fn internal_payment_capture(
&self,
request: RequestData<PaymentServiceCaptureRequest>,
) -> Result<tonic::Response<PaymentServiceCaptureResponse>, tonic::Status>;
async fn internal_pre_authenticate(
&self,
request: RequestData<PaymentServicePreAuthenticateRequest>,
) -> Result<tonic::Response<PaymentServicePreAuthenticateResponse>, tonic::Status>;
async fn internal_authenticate(
&self,
request: RequestData<PaymentServiceAuthenticateRequest>,
) -> Result<tonic::Response<PaymentServiceAuthenticateResponse>, tonic::Status>;
async fn internal_post_authenticate(
&self,
request: RequestData<PaymentServicePostAuthenticateRequest>,
) -> Result<tonic::Response<PaymentServicePostAuthenticateResponse>, tonic::Status>;
}
#[derive(Clone)]
pub struct Payments {
pub config: Arc<Config>,
}
impl Payments {
#[allow(clippy::too_many_arguments)]
async fn process_authorization_internal<
T: PaymentMethodDataTypes
+ Default
+ Eq
+ Debug
+ Send
+ serde::Serialize
+ serde::de::DeserializeOwned
+ Clone
+ Sync
+ domain_types::types::CardConversionHelper<T>
+ 'static,
>(
&self,
payload: PaymentServiceAuthorizeRequest,
connector: domain_types::connector_types::ConnectorEnum,
connector_auth_details: ConnectorAuthType,
metadata: &MaskedMetadata,
metadata_payload: &utils::MetadataPayload,
service_name: &str,
request_id: &str,
token_data: Option<TokenData>,
) -> Result<PaymentServiceAuthorizeResponse, PaymentAuthorizationError> {
//get connector data
let connector_data = ConnectorData::get_connector_by_name(&connector);
// Get connector integration
let connector_integration: BoxedConnectorIntegrationV2<
'_,
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
> = connector_data.connector.get_connector_integration_v2();
// Create common request data
let payment_flow_data = PaymentFlowData::foreign_try_from((
payload.clone(),
self.config.connectors.clone(),
metadata,
))
.map_err(|err| {
tracing::error!("Failed to process payment flow data: {:?}", err);
PaymentAuthorizationError::new(
grpc_api_types::payments::PaymentStatus::Pending,
Some("Failed to process payment flow data".to_string()),
Some("PAYMENT_FLOW_ERROR".to_string()),
None,
)
})?;
let lineage_ids = &metadata_payload.lineage_ids;
| {
"chunk": 1,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_8474653292087038763_2 | clm | mini_chunk | // connector-service/backend/grpc-server/src/server/payments.rs
let reference_id = &metadata_payload.reference_id;
let should_do_order_create = connector_data.connector.should_do_order_create();
let payment_flow_data = if should_do_order_create {
let event_params = EventParams {
_connector_name: &connector.to_string(),
_service_name: service_name,
request_id,
lineage_ids,
reference_id,
shadow_mode: metadata_payload.shadow_mode,
};
let order_id = Box::pin(self.handle_order_creation(
connector_data.clone(),
&payment_flow_data,
connector_auth_details.clone(),
&payload,
&connector.to_string(),
service_name,
event_params,
))
.await?;
tracing::info!("Order created successfully with order_id: {}", order_id);
payment_flow_data.set_order_reference_id(Some(order_id))
} else {
payment_flow_data
};
let should_do_session_token = connector_data.connector.should_do_session_token();
let payment_flow_data = if should_do_session_token {
let event_params = EventParams {
_connector_name: &connector.to_string(),
_service_name: service_name,
request_id,
lineage_ids,
reference_id,
shadow_mode: metadata_payload.shadow_mode,
};
let payment_session_data = Box::pin(self.handle_session_token(
connector_data.clone(),
&payment_flow_data,
connector_auth_details.clone(),
&payload,
&connector.to_string(),
service_name,
event_params,
))
.await?;
tracing::info!(
"Session Token created successfully with session_id: {}",
payment_session_data.session_token
);
payment_flow_data.set_session_token_id(Some(payment_session_data.session_token))
} else {
payment_flow_data
};
// Extract access token from Hyperswitch request
let cached_access_token = payload
.state
.as_ref()
.and_then(|state| state.access_token.as_ref())
.map(|access| (access.token.clone(), access.expires_in_seconds));
// Check if connector supports access tokens
let should_do_access_token = connector_data.connector.should_do_access_token();
// Conditional token generation - ONLY if not provided in request
let payment_flow_data = if should_do_access_token {
let access_token_data = match cached_access_token {
Some((token, expires_in)) => {
// If provided cached token - use it, don't generate new one
tracing::info!("Using cached access token from Hyperswitch");
Some(AccessTokenResponseData {
access_token: token,
token_type: None,
expires_in,
})
}
None => {
// No cached token - generate fresh one
tracing::info!("No cached access token found, generating new token");
let event_params = EventParams {
_connector_name: &connector.to_string(),
_service_name: service_name,
request_id,
lineage_ids,
reference_id,
shadow_mode: metadata_payload.shadow_mode,
};
let access_token_data = Box::pin(self.handle_access_token(
connector_data.clone(),
&payment_flow_data,
connector_auth_details.clone(),
&connector.to_string(),
service_name,
event_params,
))
.await?;
tracing::info!(
"Access token created successfully with expiry: {:?}",
| {
"chunk": 2,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_8474653292087038763_3 | clm | mini_chunk | // connector-service/backend/grpc-server/src/server/payments.rs
access_token_data.expires_in
);
Some(access_token_data)
}
};
// Store in flow data for connector API calls
payment_flow_data.set_access_token(access_token_data)
} else {
// Connector doesn't support access tokens
payment_flow_data
};
// Extract connector customer ID (if provided by Hyperswitch)
let cached_connector_customer_id = payload.connector_customer_id.clone();
// Check if connector supports customer creation
let should_create_connector_customer =
connector_data.connector.should_create_connector_customer();
// Conditional customer creation - ONLY if connector needs it AND no existing customer ID
let payment_flow_data = if should_create_connector_customer {
match cached_connector_customer_id {
Some(_customer_id) => payment_flow_data,
None => {
let event_params = EventParams {
_connector_name: &connector.to_string(),
_service_name: service_name,
request_id,
lineage_ids,
reference_id,
shadow_mode: metadata_payload.shadow_mode,
};
let connector_customer_response = Box::pin(self.handle_connector_customer(
connector_data.clone(),
&payment_flow_data,
connector_auth_details.clone(),
&payload,
&connector.to_string(),
service_name,
event_params,
))
.await?;
payment_flow_data.set_connector_customer_id(Some(
connector_customer_response.connector_customer_id,
))
}
}
} else {
// Connector doesn't support customer creation
payment_flow_data
};
let should_do_payment_method_token =
connector_data.connector.should_do_payment_method_token();
let payment_flow_data = if should_do_payment_method_token {
let event_params = EventParams {
_connector_name: &connector.to_string(),
_service_name: service_name,
request_id,
lineage_ids,
reference_id,
shadow_mode: metadata_payload.shadow_mode,
};
let payment_method_token_data = self
.handle_payment_session_token(
connector_data.clone(),
&payment_flow_data,
connector_auth_details.clone(),
event_params,
&payload,
&connector.to_string(),
service_name,
)
.await?;
tracing::info!("Payment Method Token created successfully");
payment_flow_data.set_payment_method_token(Some(payment_method_token_data.token))
} else {
payment_flow_data
};
// This duplicate session token check has been removed - the session token handling is already done above
// Create connector request data
let payment_authorize_data = PaymentsAuthorizeData::foreign_try_from(payload.clone())
.map_err(|err| {
tracing::error!("Failed to process payment authorize data: {:?}", err);
PaymentAuthorizationError::new(
grpc_api_types::payments::PaymentStatus::Pending,
Some("Failed to process payment authorize data".to_string()),
Some("PAYMENT_AUTHORIZE_DATA_ERROR".to_string()),
None,
)
})?
// Set session token from payment flow data if available
.set_session_token(payment_flow_data.session_token.clone());
// Construct router data
let router_data = RouterDataV2::<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
| {
"chunk": 3,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_8474653292087038763_4 | clm | mini_chunk | // connector-service/backend/grpc-server/src/server/payments.rs
PaymentsResponseData,
> {
flow: std::marker::PhantomData,
resource_common_data: payment_flow_data.clone(),
connector_auth_type: connector_auth_details.clone(),
request: payment_authorize_data,
response: Err(ErrorResponse::default()),
};
// Execute connector processing
let event_params = EventProcessingParams {
connector_name: &connector.to_string(),
service_name,
flow_name: FlowName::Authorize,
event_config: &self.config.events,
request_id,
lineage_ids,
reference_id,
shadow_mode: metadata_payload.shadow_mode,
};
// Execute connector processing
let response = external_services::service::execute_connector_processing_step(
&self.config.proxy,
connector_integration,
router_data,
None,
event_params,
token_data,
common_enums::CallConnectorAction::Trigger,
)
.await;
// Generate response - pass both success and error cases
let authorize_response = match response {
Ok(success_response) => domain_types::types::generate_payment_authorize_response(
success_response,
)
.map_err(|err| {
tracing::error!("Failed to generate authorize response: {:?}", err);
PaymentAuthorizationError::new(
grpc_api_types::payments::PaymentStatus::Pending,
Some("Failed to generate authorize response".to_string()),
Some("RESPONSE_GENERATION_ERROR".to_string()),
None,
)
})?,
Err(error_report) => {
// Convert error to RouterDataV2 with error response
let error_router_data = RouterDataV2 {
flow: std::marker::PhantomData,
resource_common_data: payment_flow_data,
connector_auth_type: connector_auth_details,
request: PaymentsAuthorizeData::foreign_try_from(payload.clone()).map_err(
|err| {
tracing::error!(
"Failed to process payment authorize data in error path: {:?}",
err
);
PaymentAuthorizationError::new(
grpc_api_types::payments::PaymentStatus::Pending,
Some(
"Failed to process payment authorize data in error path"
.to_string(),
),
Some("PAYMENT_AUTHORIZE_DATA_ERROR".to_string()),
None,
)
},
)?,
response: Err(ErrorResponse {
status_code: 400,
code: "CONNECTOR_ERROR".to_string(),
message: format!("{error_report}"),
reason: None,
attempt_status: Some(common_enums::AttemptStatus::Failure),
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
}),
};
domain_types::types::generate_payment_authorize_response::<T>(error_router_data)
.map_err(|err| {
tracing::error!(
"Failed to generate authorize response for connector error: {:?}",
err
);
PaymentAuthorizationError::new(
grpc_api_types::payments::PaymentStatus::Pending,
Some(format!("Connector error: {error_report}")),
Some("CONNECTOR_ERROR".to_string()),
None,
)
})?
}
};
| {
"chunk": 4,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_8474653292087038763_5 | clm | mini_chunk | // connector-service/backend/grpc-server/src/server/payments.rs
Ok(authorize_response)
}
#[allow(clippy::too_many_arguments)]
async fn handle_order_creation<
T: PaymentMethodDataTypes
+ Default
+ Eq
+ Debug
+ Send
+ serde::Serialize
+ serde::de::DeserializeOwned
+ Clone
+ Sync
+ domain_types::types::CardConversionHelper<T>,
>(
&self,
connector_data: ConnectorData<T>,
payment_flow_data: &PaymentFlowData,
connector_auth_details: ConnectorAuthType,
payload: &PaymentServiceAuthorizeRequest,
connector_name: &str,
service_name: &str,
event_params: EventParams<'_>,
) -> Result<String, PaymentAuthorizationError> {
// Get connector integration
let connector_integration: BoxedConnectorIntegrationV2<
'_,
CreateOrder,
PaymentFlowData,
PaymentCreateOrderData,
PaymentCreateOrderResponse,
> = connector_data.connector.get_connector_integration_v2();
let currency =
common_enums::Currency::foreign_try_from(payload.currency()).map_err(|e| {
PaymentAuthorizationError::new(
grpc_api_types::payments::PaymentStatus::Pending,
Some(format!("Currency conversion failed: {e}")),
Some("CURRENCY_ERROR".to_string()),
None,
)
})?;
let order_create_data = PaymentCreateOrderData {
amount: common_utils::types::MinorUnit::new(payload.minor_amount),
currency,
integrity_object: None,
metadata: if payload.metadata.is_empty() {
None
} else {
Some(serde_json::to_value(payload.metadata.clone()).unwrap_or_default())
},
webhook_url: payload.webhook_url.clone(),
};
let order_router_data = RouterDataV2::<
CreateOrder,
PaymentFlowData,
PaymentCreateOrderData,
PaymentCreateOrderResponse,
> {
flow: std::marker::PhantomData,
resource_common_data: payment_flow_data.clone(),
connector_auth_type: connector_auth_details,
request: order_create_data,
response: Err(ErrorResponse::default()),
};
// Create event processing parameters
let external_event_params = EventProcessingParams {
connector_name,
service_name,
flow_name: FlowName::CreateOrder,
event_config: &self.config.events,
request_id: event_params.request_id,
lineage_ids: event_params.lineage_ids,
reference_id: event_params.reference_id,
shadow_mode: event_params.shadow_mode,
};
// Execute connector processing
let response = Box::pin(
external_services::service::execute_connector_processing_step(
&self.config.proxy,
connector_integration,
order_router_data,
None,
external_event_params,
None,
common_enums::CallConnectorAction::Trigger,
),
)
.await
.map_err(
|e: error_stack::Report<domain_types::errors::ConnectorError>| {
PaymentAuthorizationError::new(
grpc_api_types::payments::PaymentStatus::Pending,
Some(format!("Order creation failed: {e}")),
Some("ORDER_CREATION_ERROR".to_string()),
None,
)
},
)?;
match response.response {
Ok(PaymentCreateOrderResponse { order_id, .. }) => Ok(order_id),
Err(e) => Err(PaymentAuthorizationError::new(
grpc_api_types::payments::PaymentStatus::Pending,
Some(e.message.clone()),
Some(e.code.clone()),
Some(e.status_code.into()),
)),
}
}
#[allow(clippy::too_many_arguments)]
async fn handle_order_creation_for_setup_mandate<
T: PaymentMethodDataTypes
+ Default
+ Eq
+ Debug
+ Send
+ serde::Serialize
| {
"chunk": 5,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_8474653292087038763_6 | clm | mini_chunk | // connector-service/backend/grpc-server/src/server/payments.rs
+ serde::de::DeserializeOwned
+ Clone
+ Sync
+ domain_types::types::CardConversionHelper<T>,
>(
&self,
connector_data: ConnectorData<T>,
payment_flow_data: &PaymentFlowData,
connector_auth_details: ConnectorAuthType,
event_params: EventParams<'_>,
payload: &PaymentServiceRegisterRequest,
connector_name: &str,
service_name: &str,
) -> Result<String, tonic::Status> {
// Get connector integration
let connector_integration: BoxedConnectorIntegrationV2<
'_,
CreateOrder,
PaymentFlowData,
PaymentCreateOrderData,
PaymentCreateOrderResponse,
> = connector_data.connector.get_connector_integration_v2();
let currency = common_enums::Currency::foreign_try_from(payload.currency())
.map_err(|e| e.into_grpc_status())?;
let order_create_data = PaymentCreateOrderData {
amount: common_utils::types::MinorUnit::new(0),
currency,
integrity_object: None,
metadata: if payload.metadata.is_empty() {
None
} else {
Some(serde_json::to_value(payload.metadata.clone()).unwrap_or_default())
},
webhook_url: payload.webhook_url.clone(),
};
let order_router_data = RouterDataV2::<
CreateOrder,
PaymentFlowData,
PaymentCreateOrderData,
PaymentCreateOrderResponse,
> {
flow: std::marker::PhantomData,
resource_common_data: payment_flow_data.clone(),
connector_auth_type: connector_auth_details,
request: order_create_data,
response: Err(ErrorResponse::default()),
};
// Execute connector processing
let external_event_params = EventProcessingParams {
connector_name,
service_name,
flow_name: FlowName::CreateOrder,
event_config: &self.config.events,
request_id: event_params.request_id,
lineage_ids: event_params.lineage_ids,
reference_id: event_params.reference_id,
shadow_mode: event_params.shadow_mode,
};
// Execute connector processing
let response = Box::pin(
external_services::service::execute_connector_processing_step(
&self.config.proxy,
connector_integration,
order_router_data,
None,
external_event_params,
None,
common_enums::CallConnectorAction::Trigger,
),
)
.await
.switch()
.map_err(|e| e.into_grpc_status())?;
match response.response {
Ok(PaymentCreateOrderResponse { order_id, .. }) => Ok(order_id),
Err(ErrorResponse { message, .. }) => Err(tonic::Status::internal(format!(
"Order creation error: {message}"
))),
}
}
#[allow(clippy::too_many_arguments)]
async fn handle_session_token<
T: PaymentMethodDataTypes
+ Default
+ Eq
+ Debug
+ Send
+ serde::Serialize
+ serde::de::DeserializeOwned
+ Clone
+ Sync
+ domain_types::types::CardConversionHelper<T>
+ 'static,
P: serde::Serialize + Clone,
>(
&self,
connector_data: ConnectorData<T>,
payment_flow_data: &PaymentFlowData,
connector_auth_details: ConnectorAuthType,
payload: &P,
connector_name: &str,
service_name: &str,
event_params: EventParams<'_>,
) -> Result<SessionTokenResponseData, PaymentAuthorizationError>
where
SessionTokenRequestData: ForeignTryFrom<P, Error = ApplicationErrorResponse>,
{
// Get connector integration
let connector_integration: BoxedConnectorIntegrationV2<
'_,
CreateSessionToken,
PaymentFlowData,
SessionTokenRequestData,
SessionTokenResponseData,
> = connector_data.connector.get_connector_integration_v2();
// Create session token request data using try_from_foreign
| {
"chunk": 6,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_8474653292087038763_7 | clm | mini_chunk | // connector-service/backend/grpc-server/src/server/payments.rs
let session_token_request_data = SessionTokenRequestData::foreign_try_from(payload.clone())
.map_err(|e| {
PaymentAuthorizationError::new(
grpc_api_types::payments::PaymentStatus::Pending,
Some(format!("Session Token creation failed: {e}")),
Some("SESSION_TOKEN_CREATION_ERROR".to_string()),
Some(400), // Bad Request - client data issue
)
})?;
let session_token_router_data = RouterDataV2::<
CreateSessionToken,
PaymentFlowData,
SessionTokenRequestData,
SessionTokenResponseData,
> {
flow: std::marker::PhantomData,
resource_common_data: payment_flow_data.clone(),
connector_auth_type: connector_auth_details,
request: session_token_request_data,
response: Err(ErrorResponse::default()),
};
// Create event processing parameters
let external_event_params = EventProcessingParams {
connector_name,
service_name,
flow_name: FlowName::CreateSessionToken,
event_config: &self.config.events,
request_id: event_params.request_id,
lineage_ids: event_params.lineage_ids,
reference_id: event_params.reference_id,
shadow_mode: event_params.shadow_mode,
};
// Execute connector processing
let response = external_services::service::execute_connector_processing_step(
&self.config.proxy,
connector_integration,
session_token_router_data,
None,
external_event_params,
None,
common_enums::CallConnectorAction::Trigger,
)
.await
.switch()
.map_err(|e: error_stack::Report<ApplicationErrorResponse>| {
PaymentAuthorizationError::new(
grpc_api_types::payments::PaymentStatus::Pending,
Some(format!("Session Token creation failed: {e}")),
Some("SESSION_TOKEN_CREATION_ERROR".to_string()),
Some(500), // Internal Server Error - connector processing failed
)
})?;
match response.response {
Ok(session_token_data) => {
tracing::info!(
"Session token created successfully: {}",
session_token_data.session_token
);
Ok(session_token_data)
}
Err(ErrorResponse {
message,
status_code,
..
}) => Err(PaymentAuthorizationError::new(
grpc_api_types::payments::PaymentStatus::Pending,
Some(format!("Session Token creation failed: {message}")),
Some("SESSION_TOKEN_CREATION_ERROR".to_string()),
Some(status_code.into()), // Use actual status code from ErrorResponse
)),
}
}
#[allow(clippy::too_many_arguments)]
async fn handle_access_token<
T: PaymentMethodDataTypes
+ Default
+ Eq
+ Debug
+ Send
+ serde::Serialize
+ serde::de::DeserializeOwned
+ Clone
+ Sync
+ domain_types::types::CardConversionHelper<T>
+ 'static,
>(
&self,
connector_data: ConnectorData<T>,
payment_flow_data: &PaymentFlowData,
connector_auth_details: ConnectorAuthType,
connector_name: &str,
service_name: &str,
event_params: EventParams<'_>,
) -> Result<AccessTokenResponseData, PaymentAuthorizationError>
where
AccessTokenRequestData:
for<'a> ForeignTryFrom<&'a ConnectorAuthType, Error = ApplicationErrorResponse>,
{
// Get connector integration for CreateAccessToken flow
let connector_integration: BoxedConnectorIntegrationV2<
'_,
CreateAccessToken,
PaymentFlowData,
AccessTokenRequestData,
AccessTokenResponseData,
> = connector_data.connector.get_connector_integration_v2();
// Create access token request data - grant type determined by connector
| {
"chunk": 7,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_8474653292087038763_8 | clm | mini_chunk | // connector-service/backend/grpc-server/src/server/payments.rs
let access_token_request_data = AccessTokenRequestData::foreign_try_from(
&connector_auth_details, // Contains connector-specific auth details
)
.map_err(|e| {
PaymentAuthorizationError::new(
grpc_api_types::payments::PaymentStatus::Pending,
Some(format!("Failed to create access token request: {e}")),
Some("ACCESS_TOKEN_REQUEST_ERROR".to_string()),
Some(400),
)
})?;
// Create router data for access token flow
let access_token_router_data = RouterDataV2::<
CreateAccessToken,
PaymentFlowData,
AccessTokenRequestData,
AccessTokenResponseData,
> {
flow: std::marker::PhantomData,
resource_common_data: payment_flow_data.clone(),
connector_auth_type: connector_auth_details,
request: access_token_request_data,
response: Err(ErrorResponse::default()),
};
// Execute connector processing
let external_event_params = EventProcessingParams {
connector_name,
service_name,
flow_name: FlowName::CreateAccessToken,
event_config: &self.config.events,
request_id: event_params.request_id,
lineage_ids: event_params.lineage_ids,
reference_id: event_params.reference_id,
shadow_mode: event_params.shadow_mode,
};
let response = external_services::service::execute_connector_processing_step(
&self.config.proxy,
connector_integration,
access_token_router_data,
None,
external_event_params,
None,
common_enums::CallConnectorAction::Trigger,
)
.await
.switch()
.map_err(|e: error_stack::Report<ApplicationErrorResponse>| {
PaymentAuthorizationError::new(
grpc_api_types::payments::PaymentStatus::Pending,
Some(format!("Access Token creation failed: {e}")),
Some("ACCESS_TOKEN_CREATION_ERROR".to_string()),
Some(500),
)
})?;
match response.response {
Ok(access_token_data) => {
tracing::info!(
"Access token created successfully with expiry: {:?}",
access_token_data.expires_in
);
Ok(access_token_data)
}
Err(ErrorResponse {
message,
status_code,
..
}) => Err(PaymentAuthorizationError::new(
grpc_api_types::payments::PaymentStatus::Pending,
Some(format!("Access Token creation failed: {message}")),
Some("ACCESS_TOKEN_CREATION_ERROR".to_string()),
Some(status_code.into()),
)),
}
}
#[allow(clippy::too_many_arguments)]
async fn handle_connector_customer<
T: PaymentMethodDataTypes
+ Default
+ Eq
+ Debug
+ Send
+ serde::Serialize
+ serde::de::DeserializeOwned
+ Clone
+ Sync
+ domain_types::types::CardConversionHelper<T>
+ 'static,
>(
&self,
connector_data: ConnectorData<T>,
payment_flow_data: &PaymentFlowData,
connector_auth_details: ConnectorAuthType,
payload: &PaymentServiceAuthorizeRequest,
connector_name: &str,
service_name: &str,
event_params: EventParams<'_>,
) -> Result<ConnectorCustomerResponse, PaymentAuthorizationError> {
// Get connector integration for CreateConnectorCustomer flow
let connector_integration: BoxedConnectorIntegrationV2<
'_,
CreateConnectorCustomer,
PaymentFlowData,
ConnectorCustomerData,
ConnectorCustomerResponse,
> = connector_data.connector.get_connector_integration_v2();
// Create connector customer request data using ForeignTryFrom
let connector_customer_request_data =
ConnectorCustomerData::foreign_try_from(payload.clone()).map_err(|err| {
| {
"chunk": 8,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_8474653292087038763_9 | clm | mini_chunk | // connector-service/backend/grpc-server/src/server/payments.rs
tracing::error!("Failed to process connector customer data: {:?}", err);
PaymentAuthorizationError::new(
grpc_api_types::payments::PaymentStatus::Pending,
Some("Failed to process connector customer data".to_string()),
Some("CONNECTOR_CUSTOMER_DATA_ERROR".to_string()),
None,
)
})?;
// Create router data for connector customer flow
let connector_customer_router_data = RouterDataV2::<
CreateConnectorCustomer,
PaymentFlowData,
ConnectorCustomerData,
ConnectorCustomerResponse,
> {
flow: std::marker::PhantomData,
resource_common_data: payment_flow_data.clone(),
connector_auth_type: connector_auth_details,
request: connector_customer_request_data,
response: Err(ErrorResponse::default()),
};
// Execute connector processing
let external_event_params = EventProcessingParams {
connector_name,
service_name,
flow_name: FlowName::CreateConnectorCustomer,
event_config: &self.config.events,
request_id: event_params.request_id,
lineage_ids: event_params.lineage_ids,
reference_id: event_params.reference_id,
shadow_mode: event_params.shadow_mode,
};
let response = Box::pin(
external_services::service::execute_connector_processing_step(
&self.config.proxy,
connector_integration,
connector_customer_router_data,
None,
external_event_params,
None,
common_enums::CallConnectorAction::Trigger,
),
)
.await
.switch()
.map_err(|e: error_stack::Report<ApplicationErrorResponse>| {
PaymentAuthorizationError::new(
grpc_api_types::payments::PaymentStatus::Pending,
Some(format!("Connector customer creation failed: {e}")),
Some("CONNECTOR_CUSTOMER_CREATION_ERROR".to_string()),
Some(500),
)
})?;
match response.response {
Ok(connector_customer_data) => Ok(connector_customer_data),
Err(ErrorResponse {
message,
status_code,
..
}) => Err(PaymentAuthorizationError::new(
grpc_api_types::payments::PaymentStatus::Pending,
Some(format!("Connector customer creation failed: {message}")),
Some("CONNECTOR_CUSTOMER_CREATION_ERROR".to_string()),
Some(status_code.into()),
)),
}
}
#[allow(clippy::too_many_arguments)]
async fn handle_connector_customer_for_setup_mandate<
T: PaymentMethodDataTypes
+ Default
+ Eq
+ Debug
+ Send
+ serde::Serialize
+ serde::de::DeserializeOwned
+ Clone
+ Sync
+ domain_types::types::CardConversionHelper<T>
+ 'static,
>(
&self,
connector_data: ConnectorData<T>,
payment_flow_data: &PaymentFlowData,
connector_auth_details: ConnectorAuthType,
payload: &PaymentServiceRegisterRequest,
connector_name: &str,
service_name: &str,
event_params: EventParams<'_>,
) -> Result<ConnectorCustomerResponse, tonic::Status> {
// Get connector integration for CreateConnectorCustomer flow
let connector_integration: BoxedConnectorIntegrationV2<
'_,
CreateConnectorCustomer,
PaymentFlowData,
ConnectorCustomerData,
ConnectorCustomerResponse,
> = connector_data.connector.get_connector_integration_v2();
// Create connector customer request data using ForeignTryFrom
let connector_customer_request_data =
ConnectorCustomerData::foreign_try_from(payload.clone()).map_err(|err| {
tracing::error!("Failed to process connector customer data: {:?}", err);
tonic::Status::internal(format!("Failed to process connector customer data: {err}"))
| {
"chunk": 9,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_8474653292087038763_10 | clm | mini_chunk | // connector-service/backend/grpc-server/src/server/payments.rs
})?;
// Create router data for connector customer flow
let connector_customer_router_data = RouterDataV2::<
CreateConnectorCustomer,
PaymentFlowData,
ConnectorCustomerData,
ConnectorCustomerResponse,
> {
flow: std::marker::PhantomData,
resource_common_data: payment_flow_data.clone(),
connector_auth_type: connector_auth_details,
request: connector_customer_request_data,
response: Err(ErrorResponse::default()),
};
// Execute connector processing
let external_event_params = EventProcessingParams {
connector_name,
service_name,
flow_name: FlowName::CreateConnectorCustomer,
event_config: &self.config.events,
request_id: event_params.request_id,
lineage_ids: event_params.lineage_ids,
reference_id: event_params.reference_id,
shadow_mode: event_params.shadow_mode,
};
let response = Box::pin(
external_services::service::execute_connector_processing_step(
&self.config.proxy,
connector_integration,
connector_customer_router_data,
None,
external_event_params,
None,
common_enums::CallConnectorAction::Trigger,
),
)
.await
.switch()
.map_err(|e: error_stack::Report<ApplicationErrorResponse>| {
tonic::Status::internal(format!("Connector customer creation failed: {e}"))
})?;
match response.response {
Ok(connector_customer_data) => Ok(connector_customer_data),
Err(ErrorResponse {
message,
status_code,
..
}) => Err(tonic::Status::internal(format!(
"Connector customer creation failed: {message} (status: {status_code})"
))),
}
}
#[allow(clippy::too_many_arguments)]
async fn handle_payment_session_token<
T: PaymentMethodDataTypes
+ Default
+ Eq
+ Debug
+ Send
+ serde::Serialize
+ serde::de::DeserializeOwned
+ Clone
+ Sync
+ domain_types::types::CardConversionHelper<T>,
>(
&self,
connector_data: ConnectorData<T>,
payment_flow_data: &PaymentFlowData,
connector_auth_details: ConnectorAuthType,
event_params: EventParams<'_>,
payload: &PaymentServiceAuthorizeRequest,
connector_name: &str,
service_name: &str,
) -> Result<PaymentMethodTokenResponse, PaymentAuthorizationError> {
// Get connector integration
let connector_integration: BoxedConnectorIntegrationV2<
'_,
PaymentMethodToken,
PaymentFlowData,
PaymentMethodTokenizationData<T>,
PaymentMethodTokenResponse,
> = connector_data.connector.get_connector_integration_v2();
let currency =
common_enums::Currency::foreign_try_from(payload.currency()).map_err(|e| {
PaymentAuthorizationError::new(
grpc_api_types::payments::PaymentStatus::Pending,
Some(format!("Currency conversion failed: {e}")),
Some("CURRENCY_ERROR".to_string()),
None,
)
})?;
let payment_method_tokenization_data = PaymentMethodTokenizationData {
amount: common_utils::types::MinorUnit::new(payload.amount),
currency,
integrity_object: None,
browser_info: None,
customer_acceptance: None,
mandate_id: None,
setup_future_usage: None,
setup_mandate_details: None,
payment_method_data:
domain_types::payment_method_data::PaymentMethodData::foreign_try_from(
payload.payment_method.clone().ok_or_else(|| {
PaymentAuthorizationError::new(
grpc_api_types::payments::PaymentStatus::Pending,
Some("Payment method is required".to_string()),
| {
"chunk": 10,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_8474653292087038763_11 | clm | mini_chunk | // connector-service/backend/grpc-server/src/server/payments.rs
Some("PAYMENT_METHOD_MISSING".to_string()),
None,
)
})?,
)
.map_err(|e| {
PaymentAuthorizationError::new(
grpc_api_types::payments::PaymentStatus::Pending,
Some(format!("Payment method data conversion failed: {e}")),
Some("PAYMENT_METHOD_DATA_ERROR".to_string()),
None,
)
})?,
};
let payment_method_token_router_data = RouterDataV2::<
PaymentMethodToken,
PaymentFlowData,
PaymentMethodTokenizationData<T>,
PaymentMethodTokenResponse,
> {
flow: std::marker::PhantomData,
resource_common_data: payment_flow_data.clone(),
connector_auth_type: connector_auth_details,
request: payment_method_tokenization_data,
response: Err(ErrorResponse::default()),
};
// Execute connector processing
let external_event_params = EventProcessingParams {
connector_name,
service_name,
flow_name: FlowName::PaymentMethodToken,
event_config: &self.config.events,
request_id: event_params.request_id,
lineage_ids: event_params.lineage_ids,
reference_id: event_params.reference_id,
shadow_mode: event_params.shadow_mode,
};
let response = external_services::service::execute_connector_processing_step(
&self.config.proxy,
connector_integration,
payment_method_token_router_data,
None,
external_event_params,
None,
common_enums::CallConnectorAction::Trigger,
)
.await
.switch()
.map_err(|e: error_stack::Report<ApplicationErrorResponse>| {
PaymentAuthorizationError::new(
grpc_api_types::payments::PaymentStatus::Pending,
Some(format!("Payment Method Token creation failed: {e}")),
Some("PAYMENT_METHOD_TOKEN_CREATION_ERROR".to_string()),
Some(500),
)
})?;
match response.response {
Ok(payment_method_token_data) => {
tracing::info!("Payment method token created successfully");
Ok(payment_method_token_data)
}
Err(ErrorResponse {
message,
status_code,
..
}) => Err(PaymentAuthorizationError::new(
grpc_api_types::payments::PaymentStatus::Pending,
Some(format!("Payment Method Token creation failed: {message}")),
Some("PAYMENT_METHOD_TOKEN_CREATION_ERROR".to_string()),
Some(status_code.into()),
)),
}
}
}
impl PaymentOperationsInternal for Payments {
implement_connector_operation!(
fn_name: internal_void_payment,
log_prefix: "PAYMENT_VOID",
request_type: PaymentServiceVoidRequest,
response_type: PaymentServiceVoidResponse,
flow_marker: Void,
resource_common_data_type: PaymentFlowData,
request_data_type: PaymentVoidData,
response_data_type: PaymentsResponseData,
request_data_constructor: PaymentVoidData::foreign_try_from,
common_flow_data_constructor: PaymentFlowData::foreign_try_from,
generate_response_fn: generate_payment_void_response,
all_keys_required: None
);
implement_connector_operation!(
fn_name: internal_refund,
log_prefix: "REFUND",
request_type: PaymentServiceRefundRequest,
response_type: RefundResponse,
flow_marker: Refund,
resource_common_data_type: RefundFlowData,
request_data_type: RefundsData,
response_data_type: RefundsResponseData,
request_data_constructor: RefundsData::foreign_try_from,
common_flow_data_constructor: RefundFlowData::foreign_try_from,
generate_response_fn: generate_refund_response,
all_keys_required: None
);
implement_connector_operation!(
fn_name: internal_payment_capture,
log_prefix: "PAYMENT_CAPTURE",
| {
"chunk": 11,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_8474653292087038763_12 | clm | mini_chunk | // connector-service/backend/grpc-server/src/server/payments.rs
request_type: PaymentServiceCaptureRequest,
response_type: PaymentServiceCaptureResponse,
flow_marker: Capture,
resource_common_data_type: PaymentFlowData,
request_data_type: PaymentsCaptureData,
response_data_type: PaymentsResponseData,
request_data_constructor: PaymentsCaptureData::foreign_try_from,
common_flow_data_constructor: PaymentFlowData::foreign_try_from,
generate_response_fn: generate_payment_capture_response,
all_keys_required: None
);
implement_connector_operation!(
fn_name: internal_pre_authenticate,
log_prefix: "PRE_AUTHENTICATE",
request_type: PaymentServicePreAuthenticateRequest,
response_type: PaymentServicePreAuthenticateResponse,
flow_marker: PreAuthenticate,
resource_common_data_type: PaymentFlowData,
request_data_type: PaymentsPreAuthenticateData<DefaultPCIHolder>,
response_data_type: PaymentsResponseData,
request_data_constructor: PaymentsPreAuthenticateData::foreign_try_from,
common_flow_data_constructor: PaymentFlowData::foreign_try_from,
generate_response_fn: generate_payment_pre_authenticate_response,
all_keys_required: None
);
implement_connector_operation!(
fn_name: internal_authenticate,
log_prefix: "AUTHENTICATE",
request_type: PaymentServiceAuthenticateRequest,
response_type: PaymentServiceAuthenticateResponse,
flow_marker: Authenticate,
resource_common_data_type: PaymentFlowData,
request_data_type: PaymentsAuthenticateData<DefaultPCIHolder>,
response_data_type: PaymentsResponseData,
request_data_constructor: PaymentsAuthenticateData::foreign_try_from,
common_flow_data_constructor: PaymentFlowData::foreign_try_from,
generate_response_fn: generate_payment_authenticate_response,
all_keys_required: None
);
implement_connector_operation!(
fn_name: internal_post_authenticate,
log_prefix: "POST_AUTHENTICATE",
request_type: PaymentServicePostAuthenticateRequest,
response_type: PaymentServicePostAuthenticateResponse,
flow_marker: PostAuthenticate,
resource_common_data_type: PaymentFlowData,
request_data_type: PaymentsPostAuthenticateData<DefaultPCIHolder>,
response_data_type: PaymentsResponseData,
request_data_constructor: PaymentsPostAuthenticateData::foreign_try_from,
common_flow_data_constructor: PaymentFlowData::foreign_try_from,
generate_response_fn: generate_payment_post_authenticate_response,
all_keys_required: None
);
implement_connector_operation!(
fn_name: internal_void_post_capture,
log_prefix: "PAYMENT_VOID_POST_CAPTURE",
request_type: PaymentServiceVoidPostCaptureRequest,
response_type: PaymentServiceVoidPostCaptureResponse,
flow_marker: VoidPC,
resource_common_data_type: PaymentFlowData,
request_data_type: PaymentsCancelPostCaptureData,
response_data_type: PaymentsResponseData,
request_data_constructor: PaymentsCancelPostCaptureData::foreign_try_from,
common_flow_data_constructor: PaymentFlowData::foreign_try_from,
generate_response_fn: generate_payment_void_post_capture_response,
all_keys_required: None
);
}
#[tonic::async_trait]
impl PaymentService for Payments {
#[tracing::instrument(
name = "payment_authorize",
fields(
name = common_utils::consts::NAME,
service_name = tracing::field::Empty,
service_method = FlowName::Authorize.as_str(),
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::Authorize.as_str(),
flow_specific_fields.status = tracing::field::Empty,
)
| {
"chunk": 12,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_8474653292087038763_13 | clm | mini_chunk | // connector-service/backend/grpc-server/src/server/payments.rs
skip(self, request)
)]
async fn authorize(
&self,
request: tonic::Request<PaymentServiceAuthorizeRequest>,
) -> Result<tonic::Response<PaymentServiceAuthorizeResponse>, tonic::Status> {
info!("PAYMENT_AUTHORIZE_FLOW: initiated");
let service_name = request
.extensions()
.get::<String>()
.cloned()
.unwrap_or_else(|| "PaymentService".to_string());
grpc_logging_wrapper(request, &service_name, self.config.clone(), FlowName::Authorize, |request_data| {
let service_name = service_name.clone();
Box::pin(async move {
let metadata_payload = request_data.extracted_metadata;
let metadata = &request_data.masked_metadata;
let payload = request_data.payload;
let authorize_response = match payload.payment_method.as_ref() {
Some(pm) => {
match pm.payment_method.as_ref() {
Some(payment_method::PaymentMethod::Card(card_details)) => {
match &card_details.card_type {
Some(grpc_api_types::payments::card_payment_method_type::CardType::CreditProxy(proxy_card_details)) | Some(grpc_api_types::payments::card_payment_method_type::CardType::DebitProxy(proxy_card_details)) => {
let token_data = proxy_card_details.to_token_data();
match Box::pin(self.process_authorization_internal::<VaultTokenHolder>(
payload.clone(),
metadata_payload.connector,
metadata_payload.connector_auth_type.clone(),
metadata,
&metadata_payload,
&service_name,
&metadata_payload.request_id,
Some(token_data),
))
.await
{
Ok(response) => {
tracing::info!("INJECTOR: Authorization completed successfully with injector");
response
},
Err(error_response) => {
tracing::error!("INJECTOR: Authorization failed with injector - error: {:?}", error_response);
PaymentServiceAuthorizeResponse::from(error_response)
},
}
}
_ => {
tracing::info!("REGULAR: Processing regular payment (no injector)");
match Box::pin(self.process_authorization_internal::<DefaultPCIHolder>(
payload.clone(),
metadata_payload.connector,
metadata_payload.connector_auth_type.clone(),
metadata,
&metadata_payload,
&service_name,
&metadata_payload.request_id,
None,
))
.await
{
Ok(response) => {
tracing::info!("REGULAR: Authorization completed successfully without injector");
response
},
| {
"chunk": 13,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_8474653292087038763_14 | clm | mini_chunk | // connector-service/backend/grpc-server/src/server/payments.rs
Err(error_response) => {
tracing::error!("REGULAR: Authorization failed without injector - error: {:?}", error_response);
PaymentServiceAuthorizeResponse::from(error_response)
},
}
}
}
}
_ => {
match Box::pin(self.process_authorization_internal::<DefaultPCIHolder>(
payload.clone(),
metadata_payload.connector,
metadata_payload.connector_auth_type.clone(),
metadata,
&metadata_payload,
&service_name,
&metadata_payload.request_id,
None,
))
.await
{
Ok(response) => response,
Err(error_response) => PaymentServiceAuthorizeResponse::from(error_response),
}
}
}
}
_ => {
match Box::pin(self.process_authorization_internal::<DefaultPCIHolder>(
payload.clone(),
metadata_payload.connector,
metadata_payload.connector_auth_type.clone(),
metadata,
&metadata_payload,
&service_name,
&metadata_payload.request_id,
None,
))
.await
{
Ok(response) => response,
Err(error_response) => PaymentServiceAuthorizeResponse::from(error_response),
}
}
};
Ok(tonic::Response::new(authorize_response))
})
})
.await
}
#[tracing::instrument(
name = "payment_sync",
fields(
name = common_utils::consts::NAME,
service_name = common_utils::consts::PAYMENT_SERVICE_NAME,
service_method = FlowName::Psync.as_str(),
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::Psync.as_str(),
flow_specific_fields.status = tracing::field::Empty,
)
skip(self, request)
)]
async fn get(
&self,
request: tonic::Request<PaymentServiceGetRequest>,
) -> Result<tonic::Response<PaymentServiceGetResponse>, tonic::Status> {
info!("PAYMENT_SYNC_FLOW: initiated");
let service_name = request
.extensions()
.get::<String>()
.cloned()
.unwrap_or_else(|| "PaymentService".to_string());
grpc_logging_wrapper(
request,
&service_name,
self.config.clone(),
FlowName::Psync,
|request_data| {
let service_name = service_name.clone();
Box::pin(async move {
let metadata_payload = request_data.extracted_metadata;
let utils::MetadataPayload {
connector,
ref request_id,
ref lineage_ids,
ref reference_id,
..
| {
"chunk": 14,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"repo": "connector-service",
"start_line": null,
"struct_name": null,
"total_crates": null,
"trait_name": null
} |
connector-service_mini_grpc-server_8474653292087038763_15 | clm | mini_chunk | // connector-service/backend/grpc-server/src/server/payments.rs
} = metadata_payload;
let payload = request_data.payload;
// Get connector data
let connector_data: ConnectorData<DefaultPCIHolder> =
ConnectorData::get_connector_by_name(&connector);
// Get connector integration
let connector_integration: BoxedConnectorIntegrationV2<
'_,
PSync,
PaymentFlowData,
PaymentsSyncData,
PaymentsResponseData,
> = connector_data.connector.get_connector_integration_v2();
// Create connector request data
let payments_sync_data =
PaymentsSyncData::foreign_try_from(payload.clone()).into_grpc_status()?;
// Create common request data
let payment_flow_data = PaymentFlowData::foreign_try_from((
payload.clone(),
self.config.connectors.clone(),
&request_data.masked_metadata,
))
.into_grpc_status()?;
// Extract access token from Hyperswitch request
let cached_access_token = payload
.state
.as_ref()
.and_then(|state| state.access_token.as_ref())
.map(|access| (access.token.clone(), access.expires_in_seconds));
// Check if connector supports access tokens
let should_do_access_token = connector_data.connector.should_do_access_token();
// Conditional token generation - ONLY if not provided in request
let payment_flow_data = if should_do_access_token {
let access_token_data = match cached_access_token {
Some((token, expires_in)) => {
// If provided cached token - use it, don't generate new one
tracing::info!("Using cached access token from Hyperswitch");
Some(AccessTokenResponseData {
access_token: token,
token_type: None,
expires_in,
})
}
None => {
// No cached token - generate fresh one
tracing::info!(
"No cached access token found, generating new token"
);
let event_params = EventParams {
_connector_name: &connector.to_string(),
_service_name: &service_name,
request_id,
lineage_ids,
reference_id,
shadow_mode: metadata_payload.shadow_mode,
};
let access_token_data = Box::pin(self.handle_access_token(
connector_data.clone(),
&payment_flow_data,
metadata_payload.connector_auth_type.clone(),
&metadata_payload.connector.to_string(),
&service_name,
event_params,
))
.await
.map_err(|e| {
let message = e.error_message.unwrap_or_else(|| {
"Access token creation failed".to_string()
});
tonic::Status::internal(message)
})?;
tracing::info!(
| {
"chunk": 15,
"crate": "grpc-server",
"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": null,
"num_items": null,
"num_structs": null,
"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.