id stringlengths 20 153 | type stringclasses 1
value | granularity stringclasses 14
values | content stringlengths 16 84.3k | metadata dict |
|---|---|---|---|---|
connector-service_body_interfaces_5586597295264513272 | clm | function_body | // connector-service/backend/interfaces/src/connector_integration_v2.rs
// Function: build_request_v2
{
Ok(Some(
RequestBuilder::new()
.method(self.get_http_method())
.url(self.get_url(req)?.as_str())
.attach_default_headers()
.headers(self.get_headers(req)?)
.set_optional_body(self.get_request_body(req)?)
.add_certificate(self.get_certificate(req)?)
.add_certificate_key(self.get_certificate_key(req)?)
.build(),
))
}
| {
"chunk": null,
"crate": "interfaces",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "build_request_v2",
"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_body_interfaces_3410150817892312159 | clm | function_body | // connector-service/backend/interfaces/src/connector_integration_v2.rs
// Function: handle_response_v2
{
if let Some(e) = event_builder {
e.set_connector_response(&json!({"error": "Not Implemented"}))
}
Ok(data.clone())
}
| {
"chunk": null,
"crate": "interfaces",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "handle_response_v2",
"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_body_interfaces_-2191993840471531092 | clm | function_body | // connector-service/backend/interfaces/src/connector_integration_v2.rs
// Function: get_error_response_v2
{
if let Some(event) = event_builder {
event.set_connector_response(&json!({"error": "Error response parsing not implemented", "status_code": res.status_code}))
}
Ok(ErrorResponse::get_not_implemented())
}
| {
"chunk": null,
"crate": "interfaces",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "get_error_response_v2",
"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_body_interfaces_2946311555777257891 | clm | function_body | // connector-service/backend/interfaces/src/connector_integration_v2.rs
// Function: get_5xx_error_response
{
let error_message = match res.status_code {
500 => "internal_server_error",
501 => "not_implemented",
502 => "bad_gateway",
503 => "service_unavailable",
504 => "gateway_timeout",
505 => "http_version_not_supported",
506 => "variant_also_negotiates",
507 => "insufficient_storage",
508 => "loop_detected",
510 => "not_extended",
511 => "network_authentication_required",
_ => "unknown_error",
};
if let Some(event) = event_builder {
event.set_connector_response(
&json!({"error": error_message, "status_code": res.status_code}),
)
}
Ok(ErrorResponse {
code: res.status_code.to_string(),
message: error_message.to_string(),
reason: String::from_utf8(res.response.to_vec()).ok(),
status_code: res.status_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
| {
"chunk": null,
"crate": "interfaces",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "get_5xx_error_response",
"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_body_interfaces_-1107571576907130061 | clm | function_body | // connector-service/backend/interfaces/src/routing.rs
// Function: from
{
match value.choice_kind {
RoutableChoiceKind::OnlyConnector => Self::OnlyConnector(Box::new(value.connector)),
RoutableChoiceKind::FullStruct => Self::FullStruct {
connector: value.connector,
merchant_connector_id: value.merchant_connector_id,
},
}
}
| {
"chunk": null,
"crate": "interfaces",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "from",
"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_body_interfaces_-3354065068773545319 | clm | function_body | // connector-service/backend/interfaces/src/api.rs
// Function: get_currency_unit
{
CurrencyUnit::Minor // Default implementation should be remove once it is implemented in all connectors
}
| {
"chunk": null,
"crate": "interfaces",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "get_currency_unit",
"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_body_interfaces_1437126371773985393 | clm | function_body | // connector-service/backend/interfaces/src/api.rs
// Function: build_error_response
{
Ok(ErrorResponse {
status_code: res.status_code,
code: NO_ERROR_CODE.to_string(),
message: NO_ERROR_MESSAGE.to_string(),
reason: None,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
| {
"chunk": null,
"crate": "interfaces",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "build_error_response",
"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_body_interfaces_-1142216780450418505 | clm | function_body | // connector-service/backend/interfaces/src/events/routing_api_logs.rs
// Function: fmt
{
match self {
Self::Grpc => write!(f, "Grpc"),
Self::Rest(method) => write!(f, "Rest ({method})"),
}
}
| {
"chunk": null,
"crate": "interfaces",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "fmt",
"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_body_interfaces_-894004033856134410 | clm | function_body | // connector-service/backend/interfaces/src/events/routing_api_logs.rs
// Function: new
{
Self {
// tenant_id,
routable_connectors,
flow: flow.to_string(),
request: request.to_string(),
response: None,
error: None,
url,
method: method.to_string(),
payment_id,
profile_id,
merchant_id,
created_at: OffsetDateTime::now_utc().unix_timestamp_nanos(),
status_code: None,
request_id: request_id
.map(|i| i.as_hyphenated().to_string())
.unwrap_or("NO_REQUEST_ID".to_string()),
routing_engine,
payment_connector: None,
routing_approach: None,
}
}
| {
"chunk": null,
"crate": "interfaces",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "new",
"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_body_interfaces_194142193830043864 | clm | function_body | // connector-service/backend/interfaces/src/events/routing_api_logs.rs
// Function: set_response_body
{
match hyperswitch_masking::masked_serialize(response) {
Ok(masked) => {
self.response = Some(masked.to_string());
}
Err(er) => self.set_error(json!({"error": er.to_string()})),
}
}
| {
"chunk": null,
"crate": "interfaces",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "set_response_body",
"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_body_interfaces_2042826047251046568 | clm | function_body | // connector-service/backend/interfaces/src/events/routing_api_logs.rs
// Function: set_error_response_body
{
match hyperswitch_masking::masked_serialize(response) {
Ok(masked) => {
self.error = Some(masked.to_string());
}
Err(er) => self.set_error(json!({"error": er.to_string()})),
}
}
| {
"chunk": null,
"crate": "interfaces",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "set_error_response_body",
"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_body_interfaces_-7174398996036853649 | clm | function_body | // connector-service/backend/interfaces/src/events/routing_api_logs.rs
// Function: set_routable_connectors
{
let connectors = connectors
.into_iter()
.map(|c| {
format!(
"{:?}:{:?}",
c.connector,
c.merchant_connector_id
.map(|id| id.get_string_repr().to_string())
.unwrap_or(String::from(""))
)
})
.collect::<Vec<_>>()
.join(",");
self.routable_connectors = connectors;
}
| {
"chunk": null,
"crate": "interfaces",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "set_routable_connectors",
"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_body_interfaces_63904391771406050 | clm | function_body | // connector-service/backend/interfaces/src/events/routing_api_logs.rs
// Function: set_payment_connector
{
self.payment_connector = Some(format!(
"{:?}:{:?}",
connector.connector,
connector
.merchant_connector_id
.map(|id| id.get_string_repr().to_string())
.unwrap_or(String::from(""))
));
}
| {
"chunk": null,
"crate": "interfaces",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "set_payment_connector",
"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_body_interfaces_1498027703277549055 | clm | function_body | // connector-service/backend/interfaces/src/events/connector_api_logs.rs
// Function: new
{
Self {
// tenant_id,
connector_name,
flow: flow
.rsplit_once("::")
.map(|(_, s)| s)
.unwrap_or(flow)
.to_string(),
request: request.to_string(),
masked_response: None,
error: None,
url,
method: method.to_string(),
payment_id,
merchant_id,
created_at: OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000,
request_id: request_id
.map(|i| i.as_hyphenated().to_string())
.unwrap_or("NO_REQUEST_ID".to_string()),
latency,
refund_id,
dispute_id,
status_code,
}
}
| {
"chunk": null,
"crate": "interfaces",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "new",
"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_body_interfaces_-2092832140578729063 | clm | function_body | // connector-service/backend/interfaces/src/events/connector_api_logs.rs
// Function: set_response_body
{
match hyperswitch_masking::masked_serialize(response) {
Ok(masked) => {
self.masked_response = Some(masked.to_string());
}
Err(er) => self.set_error(json!({"error": er.to_string()})),
}
}
| {
"chunk": null,
"crate": "interfaces",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "set_response_body",
"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_body_interfaces_-6116274920850924247 | clm | function_body | // connector-service/backend/interfaces/src/events/connector_api_logs.rs
// Function: set_error_response_body
{
match hyperswitch_masking::masked_serialize(response) {
Ok(masked) => {
self.error = Some(masked.to_string());
}
Err(er) => self.set_error(json!({"error": er.to_string()})),
}
}
| {
"chunk": null,
"crate": "interfaces",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "set_error_response_body",
"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_body_example-cli_-6146637904536187103 | clm | function_body | // connector-service/examples/example-cli/src/bin/jus.rs
// Function: fmt
{
match self {
ConnectorChoice::Adyen => write!(f, "adyen"),
ConnectorChoice::Razorpay => write!(f, "razorpay"),
}
}
| {
"chunk": null,
"crate": "example-cli",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "fmt",
"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_body_example-cli_8837193193406108535 | clm | function_body | // connector-service/examples/example-cli/src/bin/jus.rs
// Function: default
{
AuthType::HeaderKey // Using HeaderKey as default since it requires the least parameters
}
| {
"chunk": null,
"crate": "example-cli",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "default",
"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_body_example-cli_7674769024910695307 | clm | function_body | // connector-service/examples/example-cli/src/bin/jus.rs
// Function: connect_client
{
println!("Attempting to connect to gRPC server at: {}", url);
// Validate URL format
if !url.starts_with("http://") && !url.starts_with("https://") {
return Err(anyhow!("URL must start with http:// or https://"));
}
let endpoint = Endpoint::try_from(url.to_string())
.with_context(|| format!("Failed to create endpoint for URL: {}", url))?;
// Add connection timeout
let endpoint = endpoint.connect_timeout(std::time::Duration::from_secs(5));
println!("Connecting to server...");
let channel = match endpoint.connect().await {
Ok(channel) => {
println!("Successfully connected to gRPC server");
channel
}
Err(err) => {
println!("Connection error: {}", err);
println!("Troubleshooting tips:");
println!("1. Make sure the server is running on the specified host and port");
println!("2. Check if the URL format is correct (e.g., http://localhost:8080)");
println!("3. Verify that the server is accepting gRPC connections");
println!(
"4. Check if there are any network issues or firewalls blocking the connection"
);
return Err(anyhow!("Failed to connect to gRPC server: {}", err));
}
};
Ok(PaymentClient::new(channel))
}
| {
"chunk": null,
"crate": "example-cli",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "connect_client",
"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_body_example-cli_-1694698559473580759 | clm | function_body | // connector-service/examples/example-cli/src/bin/jus.rs
// Function: get_auth_details
{
match auth.auth_type {
AuthType::BodyKey => {
let key1 = auth
.key1
.clone()
.ok_or_else(|| anyhow!("key1 is required for BodyKey authentication"))?;
Ok(payments::AuthType {
auth_details: Some(payments::auth_type::AuthDetails::BodyKey(
payments::BodyKey {
api_key: auth.api_key.clone(),
key1,
},
)),
})
}
AuthType::HeaderKey => Ok(payments::AuthType {
auth_details: Some(payments::auth_type::AuthDetails::HeaderKey(
payments::HeaderKey {
api_key: auth.api_key.clone(),
},
)),
}),
AuthType::SignatureKey => {
let key1 = auth
.key1
.clone()
.ok_or_else(|| anyhow!("key1 is required for SignatureKey authentication"))?;
let api_secret = auth
.api_secret
.clone()
.ok_or_else(|| anyhow!("api_secret is required for SignatureKey authentication"))?;
Ok(payments::AuthType {
auth_details: Some(payments::auth_type::AuthDetails::SignatureKey(
payments::SignatureKey {
api_key: auth.api_key.clone(),
key1,
api_secret,
},
)),
})
}
}
}
| {
"chunk": null,
"crate": "example-cli",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "get_auth_details",
"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_body_example-cli_-894360342730031568 | clm | function_body | // connector-service/examples/example-cli/src/bin/jus.rs
// Function: parse_currency
{
match currency_str.to_lowercase().as_str() {
"usd" => Ok(payments::Currency::Usd as i32),
"gbp" => Ok(payments::Currency::Gbp as i32),
"eur" => Ok(payments::Currency::Eur as i32),
_ => Err(anyhow!(
"Unsupported currency: {}. Use usd, gbp, eur",
currency_str
)),
}
}
| {
"chunk": null,
"crate": "example-cli",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "parse_currency",
"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_body_example-cli_-1740350405261401915 | clm | function_body | // connector-service/examples/example-cli/src/bin/jus.rs
// Function: load_credential_file
{
println!("Loading credential data from: {}", file_path.display());
let file = File::open(file_path)
.with_context(|| format!("Failed to open credential file: {}", file_path.display()))?;
let reader = BufReader::new(file);
let cred_data: CredentialData = serde_json::from_reader(reader)
.with_context(|| format!("Failed to parse credential file: {}", file_path.display()))?;
Ok(cred_data)
}
| {
"chunk": null,
"crate": "example-cli",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "load_credential_file",
"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_body_example-cli_3970863639206417057 | clm | function_body | // connector-service/examples/example-cli/src/bin/jus.rs
// Function: load_payment_file
{
println!("Loading payment data from: {}", file_path.display());
let file = File::open(file_path)
.with_context(|| format!("Failed to open payment file: {}", file_path.display()))?;
let reader = BufReader::new(file);
let payment_data: PaymentData = serde_json::from_reader(reader)
.with_context(|| format!("Failed to parse payment file: {}", file_path.display()))?;
Ok(payment_data)
}
| {
"chunk": null,
"crate": "example-cli",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "load_payment_file",
"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_body_example-cli_-6992751037042548980 | clm | function_body | // connector-service/examples/example-cli/src/bin/jus.rs
// Function: load_sync_file
{
println!("Loading sync data from: {}", file_path.display());
let file = File::open(file_path)
.with_context(|| format!("Failed to open sync file: {}", file_path.display()))?;
let reader = BufReader::new(file);
let sync_data: GetData = serde_json::from_reader(reader)
.with_context(|| format!("Failed to parse sync file: {}", file_path.display()))?;
Ok(sync_data)
}
| {
"chunk": null,
"crate": "example-cli",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "load_sync_file",
"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_body_example-cli_6897390100038249888 | clm | function_body | // connector-service/examples/example-cli/src/bin/jus.rs
// Function: handle_pay
{
// Initialize auth details if not provided
let mut auth_details = AuthDetails::default();
let mut card_details = CardArgs::default();
// Load credential file if provided
if let Some(cred_file) = &args.cred_file {
let cred_data = load_credential_file(cred_file)?;
// Set connector if not provided in command line
if args.connector.is_none() {
args.connector = Some(cred_data.connector);
println!(
"Using connector from credential file: {:?}",
cred_data.connector
);
}
// Set auth details from credential file
auth_details = cred_data.auth;
println!("Using authentication details from credential file");
}
// Override with command line auth if provided
if let Some(cmd_auth) = &args.auth {
if !cmd_auth.api_key.is_empty() {
auth_details.api_key = cmd_auth.api_key.clone();
}
if cmd_auth.key1.is_some() {
auth_details.key1 = cmd_auth.key1.clone();
}
if cmd_auth.api_secret.is_some() {
auth_details.api_secret = cmd_auth.api_secret.clone();
}
if cmd_auth.auth_type != AuthType::default() {
auth_details.auth_type = cmd_auth.auth_type;
}
}
// Load payment file if provided
if let Some(payment_file) = &args.payment_file {
let payment_data = load_payment_file(payment_file)?;
// Set payment data if not provided in command line
if args.amount.is_none() {
args.amount = Some(payment_data.amount);
println!("Using amount from payment file: {}", payment_data.amount);
}
if args.currency.is_none() {
args.currency = Some(payment_data.currency.clone());
println!(
"Using currency from payment file: {}",
payment_data.currency
);
}
if args.email.is_none() {
args.email = payment_data.email.clone();
println!("Using email from payment file: {:?}", payment_data.email);
}
// Set card details from payment file
card_details = payment_data.card;
println!("Using card details from payment file");
}
// Override with command line card details if provided
if let Some(cmd_card) = &args.card {
if !cmd_card.number.is_empty() {
card_details.number = cmd_card.number.clone();
}
if !cmd_card.exp_month.is_empty() {
card_details.exp_month = cmd_card.exp_month.clone();
}
if !cmd_card.exp_year.is_empty() {
card_details.exp_year = cmd_card.exp_year.clone();
}
if !cmd_card.cvc.is_empty() {
card_details.cvc = cmd_card.cvc.clone();
}
}
// Validate required fields
let connector = args.connector.ok_or_else(|| {
anyhow!("Connector is required either via --connector or in the credential file")
})?;
let amount = args
.amount
.ok_or_else(|| anyhow!("Amount is required either via --amount or in the payment file"))?;
let currency_str = args.currency.as_deref().ok_or_else(|| {
anyhow!("Currency is required either via --currency or in the payment file")
})?;
let currency = parse_currency(currency_str)?;
// Validate card details
if card_details.number.is_empty() {
return Err(anyhow!(
"Card number is required either via --number or in the payment file"
));
}
if card_details.exp_month.is_empty() {
return Err(anyhow!(
"Card expiry month is required either via --exp-month or in the payment file"
));
}
if card_details.exp_year.is_empty() {
return Err(anyhow!(
"Card expiry year is required either via --exp-year or in the payment file"
));
}
if card_details.cvc.is_empty() {
return Err(anyhow!(
"Card CVC is required either via --cvc or in the payment file"
));
}
// Connect to the server
let mut client = connect_client(&args.url).await?;
// Create metadata with auth details
let mut metadata = MetadataMap::new();
// Add connector
metadata.insert(
X_CONNECTOR,
connector.to_string().parse().unwrap(),
);
// Add auth details based on auth type
match auth_details.auth_type {
AuthType::HeaderKey => {
metadata.insert(
X_AUTH,
"header-key".parse().unwrap(),
);
metadata.insert(
X_API_KEY,
auth_details.api_key.parse().unwrap(),
);
}
AuthType::BodyKey => {
metadata.insert(
X_AUTH,
"body-key".parse().unwrap(),
);
metadata.insert(
X_API_KEY,
auth_details.api_key.parse().unwrap(),
);
if let Some(key1) = auth_details.key1 {
metadata.insert(
X_KEY1,
key1.parse().unwrap(),
);
}
}
AuthType::SignatureKey => {
metadata.insert(
X_AUTH,
"signature-key".parse().unwrap(),
);
metadata.insert(
X_API_KEY,
auth_details.api_key.parse().unwrap(),
);
if let Some(key1) = auth_details.key1 {
metadata.insert(
X_KEY1,
key1.parse().unwrap(),
);
}
if let Some(api_secret) = auth_details.api_secret {
metadata.insert(
X_API_SECRET,
api_secret.parse().unwrap(),
);
}
}
}
let request = payments::PaymentsAuthorizeRequest {
amount,
currency,
payment_method: payments::PaymentMethod::Card as i32,
payment_method_data: Some(payments::PaymentMethodData {
data: Some(payments::payment_method_data::Data::Card(payments::Card {
card_number: card_details.number,
card_exp_month: card_details.exp_month,
card_exp_year: card_details.exp_year,
card_cvc: card_details.cvc,
..Default::default()
})),
}),
email: args.email,
address: Some(payments::PaymentAddress::default()),
auth_type: payments::AuthenticationType::NoThreeDs as i32,
minor_amount: amount,
connector_request_reference_id: format!(
"cli-ref-{}",
chrono::Utc::now().timestamp_millis()
),
capture_method: args.capture_method.map(|cm| {
match cm.to_lowercase().as_str() {
"automatic" => payments::CaptureMethod::Automatic as i32,
"manual" => payments::CaptureMethod::Manual as i32,
"manual_multiple" => payments::CaptureMethod::ManualMultiple as i32,
"scheduled" => payments::CaptureMethod::Scheduled as i32,
"sequential_automatic" => payments::CaptureMethod::SequentialAutomatic as i32,
_ => payments::CaptureMethod::Automatic as i32,
}
}),
return_url: args.return_url,
webhook_url: args.webhook_url,
complete_authorize_url: args.complete_authorize_url,
off_session: args.off_session,
order_category: args.order_category,
enrolled_for_3ds: args.enrolled_for_3ds.unwrap_or(false),
payment_experience: args.payment_experience.map(|pe| {
match pe.to_lowercase().as_str() {
"redirect_to_url" => payments::PaymentExperience::RedirectToUrl as i32,
"invoke_sdk_client" => payments::PaymentExperience::InvokeSdkClient as i32,
"display_qr_code" => payments::PaymentExperience::DisplayQrCode as i32,
"one_click" => payments::PaymentExperience::OneClick as i32,
"link_wallet" => payments::PaymentExperience::LinkWallet as i32,
"invoke_payment_app" => payments::PaymentExperience::InvokePaymentApp as i32,
"display_wait_screen" => payments::PaymentExperience::DisplayWaitScreen as i32,
"collect_otp" => payments::PaymentExperience::CollectOtp as i32,
_ => payments::PaymentExperience::RedirectToUrl as i32,
}
}),
payment_method_type: args.payment_method_type.map(|pmt| {
match pmt.to_lowercase().as_str() {
"card" => payments::PaymentMethodType::Credit as i32,
"credit" => payments::PaymentMethodType::Credit as i32,
"debit" => payments::PaymentMethodType::Debit as i32,
_ => payments::PaymentMethodType::Credit as i32,
}
}),
request_incremental_authorization: args.request_incremental_authorization.unwrap_or(false),
request_extended_authorization: args.request_extended_authorization.unwrap_or(false),
merchant_order_reference_id: args.merchant_order_reference_id,
shipping_cost: args.shipping_cost,
setup_future_usage: args.future_usage.map(|fu| {
match fu.to_lowercase().as_str() {
"off_session" => payments::FutureUsage::OffSession as i32,
"on_session" => payments::FutureUsage::OnSession as i32,
_ => payments::FutureUsage::OffSession as i32,
}
}),
..Default::default()
};
let response = client.payment_authorize(Request::from_parts(metadata, Extensions::default(), request)).await;
match response {
Ok(response) => {
println!(
"{}",
serde_json::to_string_pretty(&response.into_inner()).unwrap()
);
Ok(())
}
Err(err) => {
println!("Error during authorize call: {:#?}", err);
Err(anyhow!("Authorize call failed"))
}
}
}
| {
"chunk": null,
"crate": "example-cli",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "handle_pay",
"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_body_example-cli_1725713902385429256 | clm | function_body | // connector-service/examples/example-cli/src/bin/jus.rs
// Function: handle_get
{
// Initialize auth details if not provided
let mut auth_details = AuthDetails::default();
// Load credential file if provided
if let Some(cred_file) = &args.cred_file {
let cred_data = load_credential_file(cred_file)?;
// Set connector if not provided in command line
if args.connector.is_none() {
args.connector = Some(cred_data.connector);
println!(
"Using connector from credential file: {:?}",
cred_data.connector
);
}
// Set auth details from credential file
auth_details = cred_data.auth;
println!("Using authentication details from credential file");
}
// Override with command line auth if provided
if let Some(cmd_auth) = &args.auth {
if !cmd_auth.api_key.is_empty() {
auth_details.api_key = cmd_auth.api_key.clone();
}
if cmd_auth.key1.is_some() {
auth_details.key1 = cmd_auth.key1.clone();
}
if cmd_auth.api_secret.is_some() {
auth_details.api_secret = cmd_auth.api_secret.clone();
}
if cmd_auth.auth_type != AuthType::default() {
auth_details.auth_type = cmd_auth.auth_type;
}
}
// Load sync file if provided
if let Some(get_file) = &args.get_file {
let sync_data = load_sync_file(get_file)?;
// Set payment_id if not provided in command line
if args.payment_id.is_none() {
args.payment_id = Some(sync_data.payment_id.clone());
println!("Using resource ID from sync file: {}", sync_data.payment_id);
}
}
// Validate required fields
let connector = args.connector.ok_or_else(|| {
anyhow!("Connector is required either via --connector or in the credential file")
})?;
let payment_id = args.payment_id.as_deref().ok_or_else(|| {
anyhow!("Resource ID is required either via --resource-id or in the sync file")
})?;
// Connect to the server
let mut client = connect_client(&args.url).await?;
// Create metadata with auth details
let mut metadata = MetadataMap::new();
// Add connector
metadata.insert(
X_CONNECTOR,
connector.to_string().parse().unwrap(),
);
// Add auth details based on auth type
match auth_details.auth_type {
AuthType::HeaderKey => {
metadata.insert(
X_AUTH,
"header-key".parse().unwrap(),
);
metadata.insert(
X_API_KEY,
auth_details.api_key.parse().unwrap(),
);
}
AuthType::BodyKey => {
metadata.insert(
X_AUTH,
"body-key".parse().unwrap(),
);
metadata.insert(
X_API_KEY,
auth_details.api_key.parse().unwrap(),
);
if let Some(key1) = auth_details.key1 {
metadata.insert(
X_KEY1,
key1.parse().unwrap(),
);
}
}
AuthType::SignatureKey => {
metadata.insert(
X_AUTH,
"signature-key".parse().unwrap(),
);
metadata.insert(
X_API_KEY,
auth_details.api_key.parse().unwrap(),
);
if let Some(key1) = auth_details.key1 {
metadata.insert(
X_KEY1,
key1.parse().unwrap(),
);
}
if let Some(api_secret) = auth_details.api_secret {
metadata.insert(
X_API_SECRET,
api_secret.parse().unwrap(),
);
}
}
}
let request = payments::PaymentsSyncRequest {
resource_id: payment_id.to_string(),
connector_request_reference_id: Some(format!(
"cli-sync-ref-{}",
chrono::Utc::now().timestamp_millis()
)),
};
let response = client.payment_sync(Request::from_parts(metadata, Extensions::default(), request)).await;
match response {
Ok(response) => {
println!(
"{}",
serde_json::to_string_pretty(&response.into_inner()).unwrap()
);
Ok(())
}
Err(err) => {
println!("Error during sync call: {:#?}", err);
Err(anyhow!("Sync call failed"))
}
}
}
| {
"chunk": null,
"crate": "example-cli",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "handle_get",
"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_body_example-cli_1365687687321940161 | clm | function_body | // connector-service/examples/example-cli/src/bin/jus.rs
// Function: main
{
let cli = Cli::parse();
match &cli.command {
Command::Pay(args) => {
handle_pay(args.clone()).await?;
}
Command::Get(args) => {
handle_get(args.clone()).await?;
}
}
Ok(())
}
| {
"chunk": null,
"crate": "example-cli",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "main",
"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_body_example-tui_-3366845153177734059 | clm | function_body | // connector-service/examples/example-tui/src/main.rs
// Function: from
{
match choice {
ConnectorChoice::Adyen => payments::Connector::Adyen as i32,
ConnectorChoice::Razorpay => payments::Connector::Razorpay as i32,
// Add mappings
}
}
| {
"chunk": null,
"crate": "example-tui",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "from",
"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_body_example-tui_-8307166825194623405 | clm | function_body | // connector-service/examples/example-tui/src/main.rs
// Function: connect_client
{
let endpoint = Endpoint::try_from(url.to_string())
.with_context(|| format!("Failed to create endpoint for URL: {}", url))?;
// Optional: Configure endpoint (e.g., timeouts)
// let endpoint = endpoint.connect_timeout(std::time::Duration::from_secs(5));
let channel = endpoint
.connect()
.await
.with_context(|| format!("Failed to connect channel to gRPC server at URL: {}", url))?;
Ok(PaymentClient::new(channel))
}
| {
"chunk": null,
"crate": "example-tui",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "connect_client",
"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_body_example-tui_4871775574026598389 | clm | function_body | // connector-service/examples/example-tui/src/main.rs
// Function: handle_set
{
if args.len() < 3 {
// Updated help hint for auth headerkey
return Err(anyhow!(
"Usage: set <key> <value...> \nKeys: url, connector, amount, currency, email, resource_id, auth, card\nAuth Types: bodykey <api_key> <key1>, headerkey <api_key>"
));
}
let key = args[1].to_lowercase();
let value_parts = &args[2..];
let state = &mut ctx.state;
match key.as_str() {
"url" => {
let new_url = value_parts[0].clone().trim().to_string();
// Disconnect old client if URL changes
ctx.client = None;
state.url = Some(new_url.clone());
// Attempt to connect immediately when URL is set
let rt = Runtime::new().context("Failed to create Tokio runtime for connect")?;
match rt.block_on(connect_client(&new_url)) {
Ok(client) => {
ctx.client = Some(client); // Store the actual client
Ok(format!("URL set to: {} and client connected.", new_url))
}
Err(e) => {
state.url = Some(new_url.clone());
// Provide more context on connection failure
Err(anyhow!(
"URL set to: {}, but failed to connect client: {:?}",
new_url,
e
))
}
}
}
"connector" => {
let connector_str = value_parts[0].to_lowercase();
let connector = ConnectorChoice::from_str(&connector_str).map_err(|_| {
anyhow!(
"Invalid connector '{}'. Valid options: {:?}",
value_parts[0],
ConnectorChoice::VARIANTS
)
})?;
state.connector = Some(connector);
Ok(format!("Connector set to: {:?}", connector))
}
"amount" => {
let amount = value_parts[0]
.parse::<i64>()
.with_context(|| format!("Invalid amount value: {}", value_parts[0]))?;
state.amount = Some(amount);
Ok(format!("Amount set to: {}", amount))
}
"currency" => {
let currency_str = value_parts[0].to_lowercase();
let currency_val = match currency_str.as_str() {
"usd" => payments::Currency::Usd as i32,
"gbp" => payments::Currency::Gbp as i32,
"eur" => payments::Currency::Eur as i32,
_ => {
return Err(anyhow!(
"Unsupported currency: {}. Use usd, gbp, eur, etc.",
currency_str
));
}
};
state.currency = Some(currency_val);
Ok(format!(
"Currency set to: {} ({})",
currency_str, currency_val
))
}
"email" => {
state.email = Some(value_parts[0].clone());
Ok(format!("Email set to: {}", value_parts[0]))
}
"resource_id" => {
state.resource_id = Some(value_parts[0].clone());
Ok(format!("Resource ID set to: {}", value_parts[0]))
}
// "auth" => {
// if value_parts.len() < 1 {
// return Err(anyhow!("Usage: set auth <type> [params...]"));
// }
// let auth_type = value_parts[0].to_lowercase();
// match auth_type.as_str() {
// "bodykey" => {
// if value_parts.len() != 3 {
// return Err(anyhow!("Usage: set auth bodykey <api_key> <key1>"));
// }
// state.auth_details = Some(AuthDetailsChoice::BodyKey {
// api_key: value_parts[1].clone(),
// key1: value_parts[2].clone(),
// });
// Ok("Auth set to: BodyKey".to_string())
// }
// "headerkey" => {
// // Updated headerkey to expect only api_key
// if value_parts.len() != 2 {
// // <-- Changed from 3 to 2
// return Err(anyhow!("Usage: set auth headerkey <api_key>")); // <-- Updated usage
// }
// state.auth_details = Some(AuthDetailsChoice::HeaderKey {
// api_key: value_parts[1].clone(), // <-- Only api_key
// });
// Ok("Auth set to: HeaderKey".to_string())
// }
// "signaturekey" => {
// if value_parts.len() != 4 {
// return Err(anyhow!("Usage: set auth bodykey <api_key> <key1>"));
// }
// state.auth_details = Some(AuthDetailsChoice::SignatureKey {
// api_key: value_parts[1].clone(),
// key1: value_parts[2].clone(),
// api_secret: value_parts[3].clone(),
// });
// Ok("Auth set to: SignatureKey".to_string())
// }
// _ => Err(anyhow!(
// "Unknown auth type: {}. Supported: bodykey, headerkey",
// auth_type
// )),
// }
// }
"api_key" => {
state.api_key = Some(value_parts[0].to_string());
Ok(format!("API key set to: {}", value_parts[0]))
}
"key1" => {
state.key1 = Some(value_parts[0].to_string());
Ok(format!("Key1 set to: {}", value_parts[0]))
}
"auth" => {
state.auth_details = Some(value_parts[0].to_string());
Ok(format!("Auth set to: {}", value_parts[0]))
}
"card" => {
if value_parts.len() < 2 {
return Err(anyhow!("Usage: set card <field> <value>"));
}
let field = value_parts[0].to_lowercase();
let value = &value_parts[1];
match field.as_str() {
"number" => {
state.card_number = Some(value.clone());
Ok("Card number set".to_string())
}
"exp_month" => {
state.card_exp_month = Some(value.clone());
Ok("Card expiry month set".to_string())
}
"exp_year" => {
state.card_exp_year = Some(value.clone());
Ok("Card expiry year set".to_string())
}
"cvc" => {
state.card_cvc = Some(value.clone());
Ok("Card CVC set".to_string())
}
_ => Err(anyhow!(
"Unknown card field: {}. Use number, exp_month, exp_year, cvc",
field
)),
}
}
_ => Err(anyhow!("Unknown set key: {}", key)),
}
}
| {
"chunk": null,
"crate": "example-tui",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "handle_set",
"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_body_example-tui_3755996350107444746 | clm | function_body | // connector-service/examples/example-tui/src/main.rs
// Function: handle_unset
{
if args.len() < 2 {
return Err(anyhow!(
"Usage: unset <key>\nKeys: url, connector, amount, currency, email, resource_id, auth, card, card.number, ..."
));
}
let key = args[1].to_lowercase();
let state = &mut ctx.state;
match key.as_str() {
"url" => {
state.url = None;
ctx.client = None;
Ok("URL unset and client disconnected".to_string())
}
"connector" => {
state.connector = None;
Ok("Connector unset".to_string())
}
"amount" => {
state.amount = None;
Ok("Amount unset".to_string())
}
"currency" => {
state.currency = None;
Ok("Currency unset".to_string())
}
"email" => {
state.email = None;
Ok("Email unset".to_string())
}
"api_key" => {
state.api_key = None;
Ok("Api key unset".to_string())
}
"key1" => {
state.key1 = None;
Ok("Key1 unset".to_string())
}
"resource_id" => {
state.resource_id = None;
Ok("Resource ID unset".to_string())
}
"auth" => {
state.auth_details = None;
Ok("Auth details unset".to_string())
}
"card" => {
state.card_number = None;
state.card_exp_month = None;
state.card_exp_year = None;
state.card_cvc = None;
Ok("All card details unset".to_string())
}
"card.number" => {
state.card_number = None;
Ok("Card number unset".to_string())
}
"card.exp_month" => {
state.card_exp_month = None;
Ok("Card expiry month unset".to_string())
}
"card.exp_year" => {
state.card_exp_year = None;
Ok("Card expiry year unset".to_string())
}
"card.cvc" => {
state.card_cvc = None;
Ok("Card CVC unset".to_string())
}
_ => Err(anyhow!("Unknown unset key: {}", key)),
}
}
| {
"chunk": null,
"crate": "example-tui",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "handle_unset",
"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_body_example-tui_-1123979395212433318 | clm | function_body | // connector-service/examples/example-tui/src/main.rs
// Function: handle_call_async
{
if args.len() < 2 {
return Err(anyhow!(
"Usage: call <operation>\nOperations: authorize, sync"
));
}
let operation = args[1].to_lowercase();
let state = &ctx.state;
// // Get a mutable reference to the client stored in the context
// let client = ctx
// .client
// .as_mut()
// .ok_or_else(|| anyhow!("Client not connected. Use 'set url <value>' first."))?;
let mut client = connect_client(&state.url.as_ref().unwrap()).await?;
// let auth_creds = state
// .auth_details
// .clone()
// .ok_or_else(|| anyhow!("Authentication details are not set."))?
// .into();
// let connector_val = state
// .connector
// .ok_or_else(|| anyhow!("Connector is not set."))?;
match operation.as_str() {
"authorize" => {
let amount = state.amount.ok_or_else(|| anyhow!("Amount is not set."))?;
let currency = state
.currency
.ok_or_else(|| anyhow!("Currency is not set."))?;
let card_number = state
.card_number
.as_ref()
.ok_or_else(|| anyhow!("Card number is not set."))?;
let card_exp_month = state
.card_exp_month
.as_ref()
.ok_or_else(|| anyhow!("Card expiry month is not set."))?;
let card_exp_year = state
.card_exp_year
.as_ref()
.ok_or_else(|| anyhow!("Card expiry year is not set."))?;
let card_cvc = state
.card_cvc
.as_ref()
.ok_or_else(|| anyhow!("Card CVC is not set."))?;
let request = payments::PaymentsAuthorizeRequest {
amount,
currency,
// connector: connector_val.into(),
// auth_creds: Some(auth_creds),
connector_customer: Some("cus_1234".to_string()),
return_url: Some("www.google.com".to_string()),
payment_method: payments::PaymentMethod::Card as i32,
payment_method_data: Some(payments::PaymentMethodData {
data: Some(payments::payment_method_data::Data::Card(payments::Card {
card_number: card_number.clone(),
card_exp_month: card_exp_month.clone(),
card_exp_year: card_exp_year.clone(),
card_cvc: card_cvc.clone(),
..Default::default()
})),
}),
email: state.email.clone(),
address: Some(payments::PaymentAddress::default()),
auth_type: payments::AuthenticationType::NoThreeDs as i32,
minor_amount: amount,
request_incremental_authorization: false,
connector_request_reference_id: format!(
"shell-ref-{}",
chrono::Utc::now().timestamp_millis()
),
browser_info: Some(payments::BrowserInformation {
user_agent: Some("Mozilla/5.0".to_string()),
accept_header: Some("*/*".to_string()),
language: Some("en-US".to_string()),
color_depth: Some(24),
screen_height: Some(1080),
screen_width: Some(1920),
java_enabled: Some(false),
java_script_enabled: None,
time_zone: None,
ip_address: None,
os_type: None,
os_version: None,
device_model: None,
accept_language: None,
}),
..Default::default()
};
// println!("Sending Authorize request: {:#?}", request);
// Call the method on the mutable client reference
let mut request = tonic::Request::new(request);
request
.metadata_mut()
.append("x-connector", "adyen".parse().unwrap());
request.metadata_mut().append(
"x-auth",
MetadataValue::from_str(&state.auth_details.clone().unwrap())?,
);
request.metadata_mut().append(
"x-api-key",
MetadataValue::from_str(&state.api_key.clone().unwrap())?,
);
request.metadata_mut().append(
"x-key1",
MetadataValue::from_str(&state.key1.clone().unwrap())?,
);
let response = client.payment_authorize(request).await;
match response {
Ok(response) => Ok(format!("{:#?}", response.into_inner())),
Err(err) => Ok(format!("Error during authorize call: {:#?}", err)),
}
// Use Debug formatting for potentially multi-line responses
}
"sync" => {
let resource_id = state
.resource_id
.as_ref()
.ok_or_else(|| anyhow!("Resource ID is not set."))?;
let request = payments::PaymentsSyncRequest {
// connector: connector_val.into(),
// auth_creds: Some(auth_creds),
resource_id: resource_id.clone(),
connector_request_reference_id: Some(format!(
"shell-sync-ref-{}",
chrono::Utc::now().timestamp_millis()
)),
};
// println!("Sending Sync request: {:#?}", request);
// Call the method on the mutable client reference
let mut request = tonic::Request::new(request);
request
.metadata_mut()
.append("x-connector", "razorpay".parse().unwrap());
request.metadata_mut().append(
"x-auth",
MetadataValue::from_str(&state.auth_details.clone().unwrap())?,
);
request.metadata_mut().append(
"x-api-key",
MetadataValue::from_str(&state.api_key.clone().unwrap())?,
);
request.metadata_mut().append(
"x-key1",
MetadataValue::from_str(&state.key1.clone().unwrap())?,
);
let response = client
.payment_sync(request)
.await
.context("Sync call failed")?;
// Use Debug formatting for potentially multi-line responses
Ok(format!("{:#?}", response.into_inner()))
}
_ => Err(anyhow!(
"Unknown call operation: {}. Use authorize or sync",
operation
)),
}
}
| {
"chunk": null,
"crate": "example-tui",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "handle_call_async",
"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_body_example-tui_-714866424322400689 | clm | function_body | // connector-service/examples/example-tui/src/main.rs
// Function: handle_show
{
// Use Debug formatting which might produce multiple lines
Ok(format!("{:#?}", ctx.state))
}
| {
"chunk": null,
"crate": "example-tui",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "handle_show",
"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_body_example-tui_4333398320400413768 | clm | function_body | // connector-service/examples/example-tui/src/main.rs
// Function: handle_help
{
// Help text itself contains newlines
Ok("Available Commands:\n".to_string() +
" set <key> <value...> - Set a configuration value. Keys: url, connector, amount, currency, email, resource_id, auth, card\n" +
" Example: set url http://localhost:8080\n" +
" Example: set connector adyen\n" +
" Example: set amount 1000\n" +
" Example: set currency usd\n" +
" Example: set email user@example.com\n" +
" Example: set resource_id pay_12345\n" +
" Example: set auth bodykey your_api_key your_key1\n" +
" Example: set auth headerkey your_api_key\n" + // <-- Updated example
" Example: set auth signaturekey your_api_key your_key1 your_api_secret\n" +
" Example: set card number 1234...5678\n" +
" Example: set card exp_month 12\n" +
" Example: set card exp_year 2030\n" +
" Example: set card cvc 123\n" +
" unset <key> - Unset a configuration value. Keys: url, connector, amount, currency, email, resource_id, auth, card, card.number, ...\n" +
" Example: unset card.cvc\n" +
" Example: unset auth\n" +
" call <operation> - Call a gRPC method. Operations: authorize, sync\n" +
" Example: call authorize\n" +
" show - Show the current configuration state.\n" +
" help - Show this help message.\n" +
" exit - Exit the shell.")
}
| {
"chunk": null,
"crate": "example-tui",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "handle_help",
"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_body_example-tui_-3265188872032491676 | clm | function_body | // connector-service/examples/example-tui/src/main.rs
// Function: execute
{
let args = parse_command_parts(&cmd_input.command);
if args.is_empty() {
// Correctly create an empty CommandOutput
let empty_output = command::CommandOutput {
prompt: cmd_input.prompt,
command: cmd_input.command,
stdin: cmd_input.stdin.unwrap_or_default(),
stdout: Vec::new(), // Empty stdout
stderr: Vec::new(),
};
return Ok(command::OutputAction::Command(empty_output));
}
let command_name = args[0].to_lowercase();
// Create runtime once for the execution block if needed
let rt = Runtime::new().context("Failed to create Tokio runtime")?;
let result: Result<String> = match command_name.as_str() {
"set" => handle_set(&args, ctx),
"unset" => handle_unset(&args, ctx),
// Block on the async call handler
"call" => rt.block_on(handle_call_async(&args, ctx)),
"show" => handle_show(ctx),
"help" => handle_help(),
"exit" | "quit" => return Ok(command::OutputAction::Exit),
"clear" => return Ok(command::OutputAction::Clear),
_ => Err(anyhow!("Unknown command: {}", command_name)),
};
// Construct the output, splitting successful stdout messages into lines
let output = match result {
Ok(stdout_msg) => command::CommandOutput {
prompt: cmd_input.prompt,
command: cmd_input.command,
stdin: cmd_input.stdin.unwrap_or_default(),
// --- FIX: Split stdout_msg by lines ---
stdout: stdout_msg.lines().map(String::from).collect(),
// --- End Fix ---
stderr: Vec::new(),
},
Err(e) => command::CommandOutput {
prompt: cmd_input.prompt,
command: cmd_input.command,
stdin: cmd_input.stdin.unwrap_or_default(),
stdout: Vec::new(),
// Keep stderr as a single-element vector for the error message
stderr: vec![format!("Error: {:?}", e)],
},
};
Ok(command::OutputAction::Command(output))
}
| {
"chunk": null,
"crate": "example-tui",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "execute",
"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_body_example-tui_2883769806655230144 | clm | function_body | // connector-service/examples/example-tui/src/main.rs
// Function: prepare
{
shelgon::Prepare {
command: cmd.to_string(),
stdin_required: false,
}
}
| {
"chunk": null,
"crate": "example-tui",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "prepare",
"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_body_example-tui_7448895803087590536 | clm | function_body | // connector-service/examples/example-tui/src/main.rs
// Function: completion
{
let commands = ["set", "unset", "call", "show", "help", "exit", "clear"];
let mut completions = Vec::new();
let mut remaining = String::new();
let parts = parse_command_parts(incomplete_command);
if parts.len() <= 1 {
let current_part = parts.first().map_or("", |s| s.as_str());
let mut exact_match = None;
for &cmd in commands.iter() {
if cmd.starts_with(current_part) {
completions.push(cmd.to_string());
if cmd == current_part {
exact_match = Some(cmd);
}
}
}
if completions.len() == 1 && exact_match.is_none() {
remaining = completions[0]
.strip_prefix(current_part)
.unwrap_or("")
.to_string();
completions.clear();
} else if exact_match.is_some() {
completions.clear();
// TODO: Add argument/subcommand completion
}
} else {
// TODO: Add argument completion
}
Ok((remaining, completions))
}
| {
"chunk": null,
"crate": "example-tui",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "completion",
"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_body_example-tui_-1943675055762165951 | clm | function_body | // connector-service/examples/example-tui/src/main.rs
// Function: main
{
println!("gRPC Payment Shell (Shelgon / Crate). Type 'help' for commands.");
let rt = Runtime::new().context("Failed to create Tokio runtime")?;
let initial_state = AppState::default();
let context = ShellContext {
state: initial_state,
client: None,
};
let app = renderer::App::<PaymentShellExecutor>::new_with_executor(
rt,
PaymentShellExecutor {},
context,
);
app.execute()
}
| {
"chunk": null,
"crate": "example-tui",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "main",
"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_body_example-rs_-3290270492931238266 | clm | function_body | // connector-service/examples/example-rs/src/main.rs
// Function: main
{
// Get the URL from command line arguments
let args = std::env::args().collect::<Vec<_>>();
if args.len() < 2 {
eprintln!("Usage: {} <url> [operation]", args[0]);
eprintln!("Operations: authorize, sync");
std::process::exit(1);
}
let url = &args[1];
let operation = args.get(2).map(|s| s.as_str()).unwrap_or("authorize");
let response = match operation {
"authorize" => {
let auth_response = make_payment_authorization_request(url.to_string()).await?;
format!("Authorization Response: {:?}", auth_response)
}
"sync" => {
let sync_response = make_payment_sync_request(url.to_string()).await?;
format!("Sync Response: {:?}", sync_response)
}
_ => {
eprintln!(
"Unknown operation: {}. Use 'authorize' or 'sync'.",
operation
);
std::process::exit(1);
}
};
// Print the response
println!("{}", response);
Ok(())
}
| {
"chunk": null,
"crate": "example-rs",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "main",
"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_body_example-rs_1349521275250551843 | clm | function_body | // connector-service/examples/example-rs/src/main.rs
// Function: make_payment_authorization_request
{
// Create a gRPC client
let mut client = PaymentServiceClient::connect(url).await?;
let api_key = std::env::var("API_KEY").unwrap_or_else(|_| "default_api_key".to_string());
let key1 = std::env::var("KEY1").unwrap_or_else(|_| "default_key1".to_string());
println!("api_key is {} and key1 is {}", api_key,key1);
// Create a request with the updated values
let request = payments::PaymentsAuthorizeRequest {
amount: 1000 as i64,
currency: payments::Currency::Usd as i32,
// connector: payments::Connector::Adyen as i32,
// auth_creds: Some(payments::AuthType {
// auth_details: Some(payments::auth_type::AuthDetails::BodyKey( // Changed to BodyKey
// payments::BodyKey {
// api_key,
// key1
// },
// )),
// }),
// connector: payments::Connector::Adyen as i32,
// auth_creds: Some(payments::AuthType {
// auth_details: Some(payments::auth_type::AuthDetails::BodyKey( // Changed to BodyKey
// payments::BodyKey {
// api_key,
// key1
// },
// )),
// }),
payment_method: payments::PaymentMethod::Card as i32,
payment_method_data: Some(payments::PaymentMethodData {
data: Some(payments::payment_method_data::Data::Card(payments::Card {
card_number: "5123456789012346".to_string(), // Updated card number
card_exp_month: "03".to_string(),
card_exp_year: "2030".to_string(),
card_cvc: "100".to_string(), // Updated CVC
..Default::default()
})),
}),
// connector_customer: Some("customer_12345".to_string()),
// return_url: Some("www.google.com".to_string()),
address:Some(payments::PaymentAddress{
shipping:None,
billing:Some(Address { address: None, phone: Some(PhoneDetails { number: Some("1234567890".to_string()), country_code: Some("+1".to_string()) }), email: Some("sweta.sharma@juspay.in".to_string()) }),
unified_payment_method_billing: None,
payment_method_billing: None
}),
auth_type: payments::AuthenticationType::ThreeDs as i32,
connector_request_reference_id: "ref_12345".to_string(),
enrolled_for_3ds: true,
request_incremental_authorization: false,
minor_amount: 1000 as i64,
email: Some("sweta.sharma@juspay.in".to_string()),
connector_customer: Some("cus_1234".to_string()),
return_url: Some("www.google.com".to_string()),
browser_info: Some(payments::BrowserInformation {
// Added browser_info
user_agent: Some("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)".to_string()),
accept_header: Some(
"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8".to_string(),
),
language: Some("en-US".to_string()),
color_depth: Some(24),
screen_height: Some(1080),
screen_width: Some(1920),
java_enabled: Some(false),
..Default::default()
}),
..Default::default()
};
let mut request = tonic::Request::new(request);
request
.metadata_mut()
.append("x-connector", "adyen".parse().unwrap());
request
.metadata_mut()
.append("x-auth", "body-key".parse().unwrap());
request
.metadata_mut()
.append("x-api-key", api_key.parse().unwrap());
request
.metadata_mut()
.append("x-key1", key1.parse().unwrap());
// Send the request
let response = client.payment_authorize(request).await?;
Ok(response)
}
| {
"chunk": null,
"crate": "example-rs",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "make_payment_authorization_request",
"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_body_example-rs_3238262882933904096 | clm | function_body | // connector-service/examples/example-rs/src/main.rs
// Function: make_payment_sync_request
{
// Create a gRPC client
let mut client = PaymentServiceClient::connect(url).await?;
let resource_id =
std::env::var("RESOURCE_ID").unwrap_or_else(|_| "pay_QHj9Thiy5mCC4Y".to_string());
let api_key = std::env::var("API_KEY").unwrap_or_else(|_| "default_api_key".to_string());
let key1 = std::env::var("KEY1").unwrap_or_else(|_| "default_key1".to_string());
// Create a request
let request = payments::PaymentsSyncRequest {
// connector: payments::Connector::Razorpay as i32,
// auth_creds: Some(payments::AuthType {
// auth_details: Some(payments::auth_type::AuthDetails::BodyKey(
// payments::BodyKey {
// api_key,
// key1
// },
// )),
// }),
resource_id,
connector_request_reference_id: Some("conn_req_abc".to_string()),
};
let mut request = tonic::Request::new(request);
request
.metadata_mut()
.append("x-connector", "razorpay".parse().unwrap());
request
.metadata_mut()
.append("x-auth", "body-key".parse().unwrap());
request
.metadata_mut()
.append("x-api-key", api_key.parse().unwrap());
request
.metadata_mut()
.append("x-key1", key1.parse().unwrap());
let response = client.payment_sync(request).await?;
Ok(response)
}
| {
"chunk": null,
"crate": "example-rs",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": "make_payment_sync_request",
"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_ucs_common_utils_-4191580895164688042_0 | clm | mini_chunk | // connector-service/backend/common_utils/src/new_types.rs
use hyperswitch_masking::{ExposeInterface, Secret};
fn apply_mask(val: &str, unmasked_char_count: usize, min_masked_char_count: usize) -> String {
let len = val.len();
if len <= unmasked_char_count {
return val.to_string();
}
let mask_start_index =
// For showing only last `unmasked_char_count` characters
if len < (unmasked_char_count * 2 + min_masked_char_count) {
0
// For showing first and last `unmasked_char_count` characters
} else {
unmasked_char_count
};
let mask_end_index = len - unmasked_char_count - 1;
let range = mask_start_index..=mask_end_index;
val.chars()
.enumerate()
.fold(String::new(), |mut acc, (index, ch)| {
if ch.is_alphanumeric() && range.contains(&index) {
acc.push('*');
} else {
acc.push(ch);
}
acc
})
}
/// Masked bank account
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct MaskedBankAccount(Secret<String>);
impl From<String> for MaskedBankAccount {
fn from(src: String) -> Self {
let masked_value = apply_mask(src.as_ref(), 4, 4);
Self(Secret::from(masked_value))
}
}
impl From<Secret<String>> for MaskedBankAccount {
fn from(secret: Secret<String>) -> Self {
Self::from(secret.expose())
}
}
| {
"chunk": 0,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_3535915762892100610_0 | clm | mini_chunk | // connector-service/backend/common_utils/src/ext_traits.rs
//! This module holds traits for extending functionalities for existing datatypes
//! & inbuilt datatypes.
use error_stack::ResultExt;
use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret, Strategy};
use quick_xml::de;
use serde::{Deserialize, Serialize};
use crate::{
errors::{self, CustomResult},
fp_utils::when,
};
/// Encode interface
/// An interface for performing type conversions and serialization
pub trait Encode<'e>
where
Self: 'e + std::fmt::Debug,
{
/// Converting `Self` into an intermediate representation `<P>`
/// and then performing encoding operation using the `Serialize` trait from `serde`
/// Specifically to convert into json, by using `serde_json`
fn convert_and_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError>
where
P: TryFrom<&'e Self> + Serialize,
Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt,
<Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize;
/// Converting `Self` into an intermediate representation `<P>`
/// and then performing encoding operation using the `Serialize` trait from `serde`
/// Specifically, to convert into urlencoded, by using `serde_urlencoded`
fn convert_and_url_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError>
where
P: TryFrom<&'e Self> + Serialize,
Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt,
<Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize;
/// Functionality, for specifically encoding `Self` into `String`
/// after serialization by using `serde::Serialize`
fn url_encode(&'e self) -> CustomResult<String, errors::ParsingError>
where
Self: Serialize;
/// Functionality, for specifically encoding `Self` into `String`
/// after serialization by using `serde::Serialize`
/// specifically, to convert into JSON `String`.
fn encode_to_string_of_json(&'e self) -> CustomResult<String, errors::ParsingError>
where
Self: Serialize;
/// Functionality, for specifically encoding `Self` into `String`
/// after serialization by using `serde::Serialize`
/// specifically, to convert into XML `String`.
fn encode_to_string_of_xml(&'e self) -> CustomResult<String, errors::ParsingError>
where
Self: Serialize;
/// Functionality, for specifically encoding `Self` into `serde_json::Value`
/// after serialization by using `serde::Serialize`
fn encode_to_value(&'e self) -> CustomResult<serde_json::Value, errors::ParsingError>
where
Self: Serialize;
/// Functionality, for specifically encoding `Self` into `Vec<u8>`
/// after serialization by using `serde::Serialize`
fn encode_to_vec(&'e self) -> CustomResult<Vec<u8>, errors::ParsingError>
where
Self: Serialize;
}
impl<'e, A> Encode<'e> for A
where
Self: 'e + std::fmt::Debug,
{
fn convert_and_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError>
where
P: TryFrom<&'e Self> + Serialize,
Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt,
<Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize,
{
serde_json::to_string(
&P::try_from(self).change_context(errors::ParsingError::UnknownError)?,
)
.change_context(errors::ParsingError::EncodeError("string"))
.attach_printable_lazy(|| format!("Unable to convert {self:?} to a request"))
}
fn convert_and_url_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError>
where
P: TryFrom<&'e Self> + Serialize,
Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt,
<Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize,
{
serde_urlencoded::to_string(
&P::try_from(self).change_context(errors::ParsingError::UnknownError)?,
)
.change_context(errors::ParsingError::EncodeError("url-encoded"))
.attach_printable_lazy(|| format!("Unable to convert {self:?} to a request"))
}
fn url_encode(&'e self) -> CustomResult<String, errors::ParsingError>
where
Self: Serialize,
{
serde_urlencoded::to_string(self)
| {
"chunk": 0,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_3535915762892100610_1 | clm | mini_chunk | // connector-service/backend/common_utils/src/ext_traits.rs
.change_context(errors::ParsingError::EncodeError("url-encoded"))
.attach_printable_lazy(|| format!("Unable to convert {self:?} to a request"))
}
fn encode_to_string_of_json(&'e self) -> CustomResult<String, errors::ParsingError>
where
Self: Serialize,
{
serde_json::to_string(self)
.change_context(errors::ParsingError::EncodeError("json"))
.attach_printable_lazy(|| format!("Unable to convert {self:?} to a request"))
}
fn encode_to_string_of_xml(&'e self) -> CustomResult<String, errors::ParsingError>
where
Self: Serialize,
{
quick_xml::se::to_string(self)
.change_context(errors::ParsingError::EncodeError("xml"))
.attach_printable_lazy(|| format!("Unable to convert {self:?} to a request"))
}
fn encode_to_value(&'e self) -> CustomResult<serde_json::Value, errors::ParsingError>
where
Self: Serialize,
{
serde_json::to_value(self)
.change_context(errors::ParsingError::EncodeError("json-value"))
.attach_printable_lazy(|| format!("Unable to convert {self:?} to a value"))
}
fn encode_to_vec(&'e self) -> CustomResult<Vec<u8>, errors::ParsingError>
where
Self: Serialize,
{
serde_json::to_vec(self)
.change_context(errors::ParsingError::EncodeError("byte-vec"))
.attach_printable_lazy(|| format!("Unable to convert {self:?} to a value"))
}
}
/// Extending functionalities of `bytes::Bytes`
pub trait BytesExt {
/// Convert `bytes::Bytes` into type `<T>` using `serde::Deserialize`
fn parse_struct<'de, T>(
&'de self,
type_name: &'static str,
) -> CustomResult<T, errors::ParsingError>
where
T: Deserialize<'de>;
}
impl BytesExt for bytes::Bytes {
fn parse_struct<'de, T>(
&'de self,
type_name: &'static str,
) -> CustomResult<T, errors::ParsingError>
where
T: Deserialize<'de>,
{
use bytes::Buf;
serde_json::from_slice::<T>(self.chunk())
.change_context(errors::ParsingError::StructParseFailure(type_name))
.attach_printable_lazy(|| {
let variable_type = std::any::type_name::<T>();
format!("Unable to parse {variable_type} from bytes {self:?}")
})
}
}
/// Extending functionalities of `[u8]` for performing parsing
pub trait ByteSliceExt {
/// Convert `[u8]` into type `<T>` by using `serde::Deserialize`
fn parse_struct<'de, T>(
&'de self,
type_name: &'static str,
) -> CustomResult<T, errors::ParsingError>
where
T: Deserialize<'de>;
}
impl ByteSliceExt for [u8] {
#[track_caller]
fn parse_struct<'de, T>(
&'de self,
type_name: &'static str,
) -> CustomResult<T, errors::ParsingError>
where
T: Deserialize<'de>,
{
serde_json::from_slice(self)
.change_context(errors::ParsingError::StructParseFailure(type_name))
.attach_printable_lazy(|| format!("Unable to parse {type_name} from &[u8] {:?}", &self))
}
}
/// Extension trait for validating application configuration. This trait provides utilities to
/// check whether the value is either the default value or is empty.
pub trait ConfigExt {
/// Returns whether the value of `self` is the default value for `Self`.
fn is_default(&self) -> bool
where
Self: Default + PartialEq<Self>,
{
*self == Self::default()
}
/// Returns whether the value of `self` is empty after trimming whitespace on both left and
/// right ends.
fn is_empty_after_trim(&self) -> bool;
/// Returns whether the value of `self` is the default value for `Self` or empty after trimming
/// whitespace on both left and right ends.
fn is_default_or_empty(&self) -> bool
where
Self: Default + PartialEq<Self>,
{
self.is_default() || self.is_empty_after_trim()
}
}
impl ConfigExt for u32 {
fn is_empty_after_trim(&self) -> bool {
false
}
}
impl ConfigExt for String {
fn is_empty_after_trim(&self) -> bool {
self.trim().is_empty()
}
}
impl<T, U> ConfigExt for Secret<T, U>
where
T: ConfigExt + Default + PartialEq<T>,
U: Strategy<T>,
{
fn is_default(&self) -> bool
where
| {
"chunk": 1,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_3535915762892100610_2 | clm | mini_chunk | // connector-service/backend/common_utils/src/ext_traits.rs
T: Default + PartialEq<T>,
{
*self.peek() == T::default()
}
fn is_empty_after_trim(&self) -> bool {
self.peek().is_empty_after_trim()
}
fn is_default_or_empty(&self) -> bool
where
T: Default + PartialEq<T>,
{
self.peek().is_default() || self.peek().is_empty_after_trim()
}
}
/// Extension trait for deserializing XML strings using `quick-xml` crate
pub trait XmlExt {
/// Deserialize an XML string into the specified type `<T>`.
fn parse_xml<T>(self) -> Result<T, de::DeError>
where
T: serde::de::DeserializeOwned;
}
impl XmlExt for &str {
fn parse_xml<T>(self) -> Result<T, de::DeError>
where
T: serde::de::DeserializeOwned,
{
de::from_str(self)
}
}
/// Helper function to deserialize XML response to struct with proper error handling
pub fn deserialize_xml_to_struct<T>(response: &str) -> CustomResult<T, errors::ParsingError>
where
T: serde::de::DeserializeOwned,
{
response
.parse_xml()
.change_context(errors::ParsingError::StructParseFailure("XML Response"))
.attach_printable_lazy(|| {
let variable_type = std::any::type_name::<T>();
format!("Unable to parse {variable_type} from XML response: {response}")
})
}
/// Extending functionalities of `serde_json::Value` for performing parsing
pub trait ValueExt {
/// Convert `serde_json::Value` into type `<T>` by using `serde::Deserialize`
fn parse_value<T>(self, type_name: &'static str) -> CustomResult<T, errors::ParsingError>
where
T: serde::de::DeserializeOwned;
}
impl ValueExt for serde_json::Value {
fn parse_value<T>(self, type_name: &'static str) -> CustomResult<T, errors::ParsingError>
where
T: serde::de::DeserializeOwned,
{
let debug = format!(
"Unable to parse {type_name} from serde_json::Value: {:?}",
&self
);
serde_json::from_value::<T>(self)
.change_context(errors::ParsingError::StructParseFailure(type_name))
.attach_printable_lazy(|| debug)
}
}
impl<MaskingStrategy> ValueExt for Secret<serde_json::Value, MaskingStrategy>
where
MaskingStrategy: Strategy<serde_json::Value>,
{
fn parse_value<T>(self, type_name: &'static str) -> CustomResult<T, errors::ParsingError>
where
T: serde::de::DeserializeOwned,
{
self.expose().parse_value(type_name)
}
}
/// Extending functionalities of Wrapper types for idiomatic async operations
#[cfg(feature = "async_ext")]
#[cfg_attr(feature = "async_ext", async_trait::async_trait)]
pub trait AsyncExt<A> {
/// Output type of the map function
type WrappedSelf<T>;
/// Extending map by allowing functions which are async
async fn async_map<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B>
where
F: FnOnce(A) -> Fut + Send,
Fut: futures::Future<Output = B> + Send;
/// Extending the `and_then` by allowing functions which are async
async fn async_and_then<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B>
where
F: FnOnce(A) -> Fut + Send,
Fut: futures::Future<Output = Self::WrappedSelf<B>> + Send;
/// Extending `unwrap_or_else` to allow async fallback
async fn async_unwrap_or_else<F, Fut>(self, func: F) -> A
where
F: FnOnce() -> Fut + Send,
Fut: futures::Future<Output = A> + Send;
}
#[cfg(feature = "async_ext")]
#[cfg_attr(feature = "async_ext", async_trait::async_trait)]
impl<A: Send, E: Send + std::fmt::Debug> AsyncExt<A> for Result<A, E> {
type WrappedSelf<T> = Result<T, E>;
async fn async_and_then<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B>
where
F: FnOnce(A) -> Fut + Send,
Fut: futures::Future<Output = Self::WrappedSelf<B>> + Send,
{
match self {
Ok(a) => func(a).await,
Err(err) => Err(err),
}
}
async fn async_map<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B>
where
F: FnOnce(A) -> Fut + Send,
Fut: futures::Future<Output = B> + Send,
{
match self {
Ok(a) => Ok(func(a).await),
Err(err) => Err(err),
}
}
async fn async_unwrap_or_else<F, Fut>(self, func: F) -> A
where
F: FnOnce() -> Fut + Send,
Fut: futures::Future<Output = A> + Send,
{
| {
"chunk": 2,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_3535915762892100610_3 | clm | mini_chunk | // connector-service/backend/common_utils/src/ext_traits.rs
match self {
Ok(a) => a,
Err(_err) => func().await,
}
}
}
#[cfg(feature = "async_ext")]
#[cfg_attr(feature = "async_ext", async_trait::async_trait)]
impl<A: Send> AsyncExt<A> for Option<A> {
type WrappedSelf<T> = Option<T>;
async fn async_and_then<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B>
where
F: FnOnce(A) -> Fut + Send,
Fut: futures::Future<Output = Self::WrappedSelf<B>> + Send,
{
match self {
Some(a) => func(a).await,
None => None,
}
}
async fn async_map<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B>
where
F: FnOnce(A) -> Fut + Send,
Fut: futures::Future<Output = B> + Send,
{
match self {
Some(a) => Some(func(a).await),
None => None,
}
}
async fn async_unwrap_or_else<F, Fut>(self, func: F) -> A
where
F: FnOnce() -> Fut + Send,
Fut: futures::Future<Output = A> + Send,
{
match self {
Some(a) => a,
None => func().await,
}
}
}
pub trait OptionExt<T> {
/// check if the current option is Some
fn check_value_present(
&self,
field_name: &'static str,
) -> CustomResult<(), errors::ValidationError>;
/// Throw missing required field error when the value is None
fn get_required_value(
self,
field_name: &'static str,
) -> CustomResult<T, errors::ValidationError>;
/// Try parsing the option as Enum
fn parse_enum<E>(self, enum_name: &'static str) -> CustomResult<E, errors::ParsingError>
where
T: AsRef<str>,
E: std::str::FromStr,
// Requirement for converting the `Err` variant of `FromStr` to `Report<Err>`
<E as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static;
/// Try parsing the option as Type
fn parse_value<U>(self, type_name: &'static str) -> CustomResult<U, errors::ParsingError>
where
T: ValueExt,
U: serde::de::DeserializeOwned;
/// update option value
fn update_value(&mut self, value: Option<T>);
}
impl<T> OptionExt<T> for Option<T>
where
T: std::fmt::Debug,
{
#[track_caller]
fn check_value_present(
&self,
field_name: &'static str,
) -> CustomResult<(), errors::ValidationError> {
when(self.is_none(), || {
Err(errors::ValidationError::MissingRequiredField {
field_name: field_name.to_string(),
})
.attach_printable(format!("Missing required field {field_name} in {self:?}"))
})
}
// This will allow the error message that was generated in this function to point to the call site
#[track_caller]
fn get_required_value(
self,
field_name: &'static str,
) -> CustomResult<T, errors::ValidationError> {
match self {
Some(v) => Ok(v),
None => Err(errors::ValidationError::MissingRequiredField {
field_name: field_name.to_string(),
})
.attach_printable(format!("Missing required field {field_name} in {self:?}")),
}
}
#[track_caller]
fn parse_enum<E>(self, enum_name: &'static str) -> CustomResult<E, errors::ParsingError>
where
T: AsRef<str>,
E: std::str::FromStr,
<E as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static,
{
let value = self
.get_required_value(enum_name)
.change_context(errors::ParsingError::UnknownError)?;
E::from_str(value.as_ref())
.change_context(errors::ParsingError::UnknownError)
.attach_printable_lazy(|| format!("Invalid {{ {enum_name}: {value:?} }} "))
}
#[track_caller]
fn parse_value<U>(self, type_name: &'static str) -> CustomResult<U, errors::ParsingError>
where
T: ValueExt,
U: serde::de::DeserializeOwned,
{
let value = self
.get_required_value(type_name)
.change_context(errors::ParsingError::UnknownError)?;
value.parse_value(type_name)
}
fn update_value(&mut self, value: Self) {
if let Some(a) = value {
*self = Some(a)
}
}
}
/// Extending functionalities of `String` for performing parsing
pub trait StringExt<T> {
| {
"chunk": 3,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_3535915762892100610_4 | clm | mini_chunk | // connector-service/backend/common_utils/src/ext_traits.rs
/// Convert `String` into type `<T>` (which being an `enum`)
fn parse_enum(self, enum_name: &'static str) -> CustomResult<T, errors::ParsingError>
where
T: std::str::FromStr,
// Requirement for converting the `Err` variant of `FromStr` to `Report<Err>`
<T as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static;
/// Convert `serde_json::Value` into type `<T>` by using `serde::Deserialize`
fn parse_struct<'de>(
&'de self,
type_name: &'static str,
) -> CustomResult<T, errors::ParsingError>
where
T: Deserialize<'de>;
}
impl<T> StringExt<T> for String {
fn parse_enum(self, enum_name: &'static str) -> CustomResult<T, errors::ParsingError>
where
T: std::str::FromStr,
<T as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static,
{
T::from_str(&self)
.change_context(errors::ParsingError::EnumParseFailure(enum_name))
.attach_printable_lazy(|| format!("Invalid enum variant {self:?} for enum {enum_name}"))
}
fn parse_struct<'de>(
&'de self,
type_name: &'static str,
) -> CustomResult<T, errors::ParsingError>
where
T: Deserialize<'de>,
{
serde_json::from_str::<T>(self)
.change_context(errors::ParsingError::StructParseFailure(type_name))
.attach_printable_lazy(|| {
format!("Unable to parse {type_name} from string {:?}", &self)
})
}
}
| {
"chunk": 4,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_-6020438553597064532_0 | clm | mini_chunk | // connector-service/backend/common_utils/src/request.rs
use hyperswitch_masking::{Maskable, Secret};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
pub type Headers = std::collections::HashSet<(String, Maskable<String>)>;
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
Deserialize,
Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[serde(rename_all = "UPPERCASE")]
#[strum(serialize_all = "UPPERCASE")]
pub enum Method {
Get,
Post,
Put,
Delete,
Patch,
}
#[derive(Deserialize, Serialize, Debug)]
pub enum ContentType {
Json,
FormUrlEncoded,
FormData,
Xml,
}
fn default_request_headers() -> [(String, Maskable<String>); 1] {
use http::header;
[(header::VIA.to_string(), "HyperSwitch".to_string().into())]
}
#[derive(Debug)]
pub struct Request {
pub url: String,
pub headers: Headers,
pub method: Method,
pub certificate: Option<Secret<String>>,
pub certificate_key: Option<Secret<String>>,
pub body: Option<RequestContent>,
pub ca_certificate: Option<Secret<String>>,
}
impl std::fmt::Debug for RequestContent {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Json(_) => "JsonRequestBody",
Self::FormUrlEncoded(_) => "FormUrlEncodedRequestBody",
Self::FormData(_) => "FormDataRequestBody",
Self::Xml(_) => "XmlRequestBody",
Self::RawBytes(_) => "RawBytesRequestBody",
})
}
}
pub enum RequestContent {
Json(Box<dyn hyperswitch_masking::ErasedMaskSerialize + Send>),
FormUrlEncoded(Box<dyn hyperswitch_masking::ErasedMaskSerialize + Send>),
FormData(reqwest::multipart::Form),
Xml(Box<dyn hyperswitch_masking::ErasedMaskSerialize + Send>),
RawBytes(Vec<u8>),
}
impl RequestContent {
pub fn get_inner_value(&self) -> Secret<String> {
match self {
Self::Json(i) => serde_json::to_string(&i).unwrap_or_default().into(),
Self::FormUrlEncoded(i) => serde_urlencoded::to_string(i).unwrap_or_default().into(),
Self::Xml(i) => quick_xml::se::to_string(&i).unwrap_or_default().into(),
Self::FormData(_) => String::new().into(),
Self::RawBytes(_) => String::new().into(),
}
}
}
impl Request {
pub fn new(method: Method, url: &str) -> Self {
Self {
method,
url: String::from(url),
headers: std::collections::HashSet::new(),
certificate: None,
certificate_key: None,
body: None,
ca_certificate: None,
}
}
pub fn set_body<T: Into<RequestContent>>(&mut self, body: T) {
self.body.replace(body.into());
}
pub fn add_default_headers(&mut self) {
self.headers.extend(default_request_headers());
}
pub fn add_header(&mut self, header: &str, value: Maskable<String>) {
self.headers.insert((String::from(header), value));
}
pub fn add_certificate(&mut self, certificate: Option<Secret<String>>) {
self.certificate = certificate;
}
pub fn add_certificate_key(&mut self, certificate_key: Option<Secret<String>>) {
self.certificate = certificate_key;
}
}
#[derive(Debug)]
pub struct RequestBuilder {
pub url: String,
pub headers: Headers,
pub method: Method,
pub certificate: Option<Secret<String>>,
pub certificate_key: Option<Secret<String>>,
pub body: Option<RequestContent>,
pub ca_certificate: Option<Secret<String>>,
}
impl RequestBuilder {
pub fn new() -> Self {
Self {
method: Method::Get,
url: String::with_capacity(1024),
headers: std::collections::HashSet::new(),
certificate: None,
certificate_key: None,
body: None,
ca_certificate: None,
}
}
pub fn url(mut self, url: &str) -> Self {
self.url = url.into();
self
}
pub fn method(mut self, method: Method) -> Self {
self.method = method;
self
}
pub fn attach_default_headers(mut self) -> Self {
self.headers.extend(default_request_headers());
self
}
pub fn header(mut self, header: &str, value: &str) -> Self {
self.headers.insert((header.into(), value.into()));
self
}
pub fn headers(mut self, headers: Vec<(String, Maskable<String>)>) -> Self {
| {
"chunk": 0,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_-6020438553597064532_1 | clm | mini_chunk | // connector-service/backend/common_utils/src/request.rs
self.headers.extend(headers);
self
}
pub fn set_optional_body<T: Into<RequestContent>>(mut self, body: Option<T>) -> Self {
body.map(|body| self.body.replace(body.into()));
self
}
pub fn set_body<T: Into<RequestContent>>(mut self, body: T) -> Self {
self.body.replace(body.into());
self
}
pub fn add_certificate(mut self, certificate: Option<Secret<String>>) -> Self {
self.certificate = certificate;
self
}
pub fn add_certificate_key(mut self, certificate_key: Option<Secret<String>>) -> Self {
self.certificate_key = certificate_key;
self
}
pub fn add_ca_certificate_pem(mut self, ca_certificate: Option<Secret<String>>) -> Self {
self.ca_certificate = ca_certificate;
self
}
pub fn build(self) -> Request {
Request {
method: self.method,
url: self.url,
headers: self.headers,
certificate: self.certificate,
certificate_key: self.certificate_key,
body: self.body,
ca_certificate: self.ca_certificate,
}
}
}
impl Default for RequestBuilder {
fn default() -> Self {
Self::new()
}
}
| {
"chunk": 1,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_4276938976373144801_0 | clm | mini_chunk | // connector-service/backend/common_utils/src/consts.rs
//! Consolidated constants for the connector service
// =============================================================================
// ID Generation and Length Constants
// =============================================================================
use serde::{de::IntoDeserializer, Deserialize};
pub const ID_LENGTH: usize = 20;
/// Characters to use for generating NanoID
pub(crate) const ALPHABETS: [char; 62] = [
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B',
'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
'V', 'W', 'X', 'Y', 'Z',
];
/// Max Length for MerchantReferenceId
pub const MAX_ALLOWED_MERCHANT_REFERENCE_ID_LENGTH: u8 = 64;
/// Minimum allowed length for MerchantReferenceId
pub const MIN_REQUIRED_MERCHANT_REFERENCE_ID_LENGTH: u8 = 1;
/// Length of a cell identifier in a distributed system
pub const CELL_IDENTIFIER_LENGTH: u8 = 5;
/// Minimum length required for a global id
pub const MAX_GLOBAL_ID_LENGTH: u8 = 64;
/// Maximum length allowed for a global id
pub const MIN_GLOBAL_ID_LENGTH: u8 = 32;
// =============================================================================
// HTTP Headers
// =============================================================================
/// Header key for tenant identification
pub const X_TENANT_ID: &str = "x-tenant-id";
/// Header key for request ID
pub const X_REQUEST_ID: &str = "x-request-id";
/// Header key for connector identification
pub const X_CONNECTOR_NAME: &str = "x-connector";
/// Header key for merchant identification
pub const X_MERCHANT_ID: &str = "x-merchant-id";
/// Header key for reference identification
pub const X_REFERENCE_ID: &str = "x-reference-id";
pub const X_SOURCE_NAME: &str = "x-source";
pub const X_CONNECTOR_SERVICE: &str = "connector-service";
pub const X_FLOW_NAME: &str = "x-flow";
/// Header key for shadow mode
pub const X_SHADOW_MODE: &str = "x-shadow-mode";
// =============================================================================
// Authentication Headers (Internal)
// =============================================================================
/// Authentication header
pub const X_AUTH: &str = "x-auth";
/// API key header for authentication
pub const X_API_KEY: &str = "x-api-key";
/// API key header variant
pub const X_KEY1: &str = "x-key1";
/// API key header variant
pub const X_KEY2: &str = "x-key2";
/// API secret header
pub const X_API_SECRET: &str = "x-api-secret";
/// Auth Key Map header
pub const X_AUTH_KEY_MAP: &str = "x-auth-key-map";
/// Header key for external vault metadata
pub const X_EXTERNAL_VAULT_METADATA: &str = "x-external-vault-metadata";
/// Header key for lineage metadata fields
pub const X_LINEAGE_IDS: &str = "x-lineage-ids";
/// Prefix for lineage fields in additional_fields
pub const LINEAGE_FIELD_PREFIX: &str = "lineage_";
// =============================================================================
// Error Messages and Codes
// =============================================================================
/// No error message string const
pub const NO_ERROR_MESSAGE: &str = "No error message";
/// No error code string const
pub const NO_ERROR_CODE: &str = "No error code";
/// A string constant representing a redacted or masked value
pub const REDACTED: &str = "Redacted";
pub const UNSUPPORTED_ERROR_MESSAGE: &str = "Unsupported response type";
// =============================================================================
// Card Validation Constants
// =============================================================================
/// Minimum limit of a card number will not be less than 8 by ISO standards
pub const MIN_CARD_NUMBER_LENGTH: usize = 8;
/// Maximum limit of a card number will not exceed 19 by ISO standards
pub const MAX_CARD_NUMBER_LENGTH: usize = 19;
// =============================================================================
// Log Field Names
// =============================================================================
/// Log field for message content
pub const LOG_MESSAGE: &str = "message";
/// Log field for hostname
pub const LOG_HOSTNAME: &str = "hostname";
| {
"chunk": 0,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_4276938976373144801_1 | clm | mini_chunk | // connector-service/backend/common_utils/src/consts.rs
/// Log field for process ID
pub const LOG_PID: &str = "pid";
/// Log field for log level
pub const LOG_LEVEL: &str = "level";
/// Log field for target
pub const LOG_TARGET: &str = "target";
/// Log field for service name
pub const LOG_SERVICE: &str = "service";
/// Log field for line number
pub const LOG_LINE: &str = "line";
/// Log field for file name
pub const LOG_FILE: &str = "file";
/// Log field for function name
pub const LOG_FN: &str = "fn";
/// Log field for full name
pub const LOG_FULL_NAME: &str = "full_name";
/// Log field for timestamp
pub const LOG_TIME: &str = "time";
/// Constant variable for name
pub const NAME: &str = "UCS";
/// Constant variable for payment service name
pub const PAYMENT_SERVICE_NAME: &str = "payment_service";
pub const CONST_DEVELOPMENT: &str = "development";
pub const CONST_PRODUCTION: &str = "production";
// =============================================================================
// Environment and Configuration
// =============================================================================
pub const ENV_PREFIX: &str = "CS";
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Env {
Development,
Production,
Sandbox,
}
impl Env {
/// Returns the current environment based on the `CS__COMMON__ENVIRONMENT` environment variable.
///
/// If the environment variable is not set, it defaults to `Development` in debug builds
/// and `Production` in release builds.
///
/// # Panics
///
/// Panics if the `CS__COMMON__ENVIRONMENT` environment variable contains an invalid value
/// that cannot be deserialized into one of the valid environment variants.
#[allow(clippy::panic)]
pub fn current_env() -> Self {
let env_key = format!("{ENV_PREFIX}__COMMON__ENVIRONMENT");
std::env::var(&env_key).map_or_else(
|_| Self::Development,
|v| {
Self::deserialize(v.into_deserializer()).unwrap_or_else(|err: serde_json::Error| {
panic!("Invalid value found in environment variable {env_key}: {err}")
})
},
)
}
pub const fn config_path(self) -> &'static str {
match self {
Self::Development => "development.toml",
Self::Production => "production.toml",
Self::Sandbox => "sandbox.toml",
}
}
}
impl std::fmt::Display for Env {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Development => write!(f, "development"),
Self::Production => write!(f, "production"),
Self::Sandbox => write!(f, "sandbox"),
}
}
}
| {
"chunk": 1,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_1414821583984559341_0 | clm | mini_chunk | // connector-service/backend/common_utils/src/types.rs
//! Types that can be used in other crates
use std::{
fmt::Display,
iter::Sum,
ops::{Add, Mul, Sub},
str::FromStr,
};
use common_enums::enums;
use error_stack::ResultExt;
use hyperswitch_masking::Deserialize;
use rust_decimal::{
prelude::{FromPrimitive, ToPrimitive},
Decimal,
};
use semver::Version;
use serde::Serialize;
use time::PrimitiveDateTime;
use utoipa::ToSchema;
use crate::errors::ParsingError;
/// Amount convertor trait for connector
pub trait AmountConvertor: Send {
/// Output type for the connector
type Output;
/// helps in conversion of connector required amount type
fn convert(
&self,
amount: MinorUnit,
currency: enums::Currency,
) -> Result<Self::Output, error_stack::Report<ParsingError>>;
/// helps in converting back connector required amount type to core minor unit
fn convert_back(
&self,
amount: Self::Output,
currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<ParsingError>>;
}
/// Connector required amount type
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub struct StringMinorUnitForConnector;
impl AmountConvertor for StringMinorUnitForConnector {
type Output = StringMinorUnit;
fn convert(
&self,
amount: MinorUnit,
_currency: enums::Currency,
) -> Result<Self::Output, error_stack::Report<ParsingError>> {
amount.to_minor_unit_as_string()
}
fn convert_back(
&self,
amount: Self::Output,
_currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<ParsingError>> {
amount.to_minor_unit_as_i64()
}
}
/// Core required conversion type
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq)]
pub struct StringMajorUnitForCore;
impl AmountConvertor for StringMajorUnitForCore {
type Output = StringMajorUnit;
fn convert(
&self,
amount: MinorUnit,
currency: enums::Currency,
) -> Result<Self::Output, error_stack::Report<ParsingError>> {
amount.to_major_unit_as_string(currency)
}
fn convert_back(
&self,
amount: StringMajorUnit,
currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<ParsingError>> {
amount.to_minor_unit_as_i64(currency)
}
}
/// Connector required amount type
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq)]
pub struct StringMajorUnitForConnector;
impl AmountConvertor for StringMajorUnitForConnector {
type Output = StringMajorUnit;
fn convert(
&self,
amount: MinorUnit,
currency: enums::Currency,
) -> Result<Self::Output, error_stack::Report<ParsingError>> {
amount.to_major_unit_as_string(currency)
}
fn convert_back(
&self,
amount: StringMajorUnit,
currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<ParsingError>> {
amount.to_minor_unit_as_i64(currency)
}
}
/// Connector required amount type
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq)]
pub struct FloatMajorUnitForConnector;
impl AmountConvertor for FloatMajorUnitForConnector {
type Output = FloatMajorUnit;
fn convert(
&self,
amount: MinorUnit,
currency: enums::Currency,
) -> Result<Self::Output, error_stack::Report<ParsingError>> {
amount.to_major_unit_as_f64(currency)
}
fn convert_back(
&self,
amount: FloatMajorUnit,
currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<ParsingError>> {
amount.to_minor_unit_as_i64(currency)
}
}
/// Connector required amount type
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq)]
pub struct MinorUnitForConnector;
impl AmountConvertor for MinorUnitForConnector {
type Output = MinorUnit;
fn convert(
&self,
amount: MinorUnit,
_currency: enums::Currency,
) -> Result<Self::Output, error_stack::Report<ParsingError>> {
Ok(amount)
}
fn convert_back(
&self,
amount: MinorUnit,
_currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<ParsingError>> {
Ok(amount)
}
}
/// This Unit struct represents MinorUnit in which core amount works
#[derive(
Default,
Debug,
serde::Deserialize,
| {
"chunk": 0,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_1414821583984559341_1 | clm | mini_chunk | // connector-service/backend/common_utils/src/types.rs
serde::Serialize,
Clone,
Copy,
PartialEq,
Eq,
Hash,
ToSchema,
PartialOrd,
)]
pub struct MinorUnit(pub i64);
impl MinorUnit {
/// gets amount as i64 value will be removed in future
pub fn get_amount_as_i64(self) -> i64 {
self.0
}
/// forms a new minor default unit i.e zero
pub fn zero() -> Self {
Self(0)
}
/// forms a new minor unit from amount
pub fn new(value: i64) -> Self {
Self(value)
}
/// checks if the amount is greater than the given value
pub fn is_greater_than(&self, value: i64) -> bool {
self.get_amount_as_i64() > value
}
/// Convert the amount to its major denomination based on Currency and return String
/// This method now validates currency support and will error for unsupported currencies.
/// Paypal Connector accepts Zero and Two decimal currency but not three decimal and it should be updated as required for 3 decimal currencies.
/// Paypal Ref - https://developer.paypal.com/docs/reports/reference/paypal-supported-currencies/
fn to_major_unit_as_string(
self,
currency: enums::Currency,
) -> Result<StringMajorUnit, error_stack::Report<ParsingError>> {
let amount_f64 = self.to_major_unit_as_f64(currency)?;
let decimal_places = currency
.number_of_digits_after_decimal_point()
.change_context(ParsingError::StructParseFailure(
"currency decimal configuration",
))?;
let amount_string = if decimal_places == 0 {
amount_f64.0.to_string()
} else if decimal_places == 3 {
format!("{:.3}", amount_f64.0)
} else if decimal_places == 4 {
format!("{:.4}", amount_f64.0)
} else {
format!("{:.2}", amount_f64.0) // 2 decimal places
};
Ok(StringMajorUnit::new(amount_string))
}
/// Convert the amount to its major denomination based on Currency and return f64
/// This method now validates currency support and will error for unsupported currencies.
fn to_major_unit_as_f64(
self,
currency: enums::Currency,
) -> Result<FloatMajorUnit, error_stack::Report<ParsingError>> {
let amount_decimal =
Decimal::from_i64(self.0).ok_or(ParsingError::I64ToDecimalConversionFailure)?;
let decimal_places = currency
.number_of_digits_after_decimal_point()
.change_context(ParsingError::StructParseFailure(
"currency decimal configuration",
))?;
let amount = if decimal_places == 0 {
amount_decimal
} else if decimal_places == 3 {
amount_decimal / Decimal::from(1000)
} else if decimal_places == 4 {
amount_decimal / Decimal::from(10000)
} else {
amount_decimal / Decimal::from(100) // 2 decimal places
};
let amount_f64 = amount
.to_f64()
.ok_or(ParsingError::FloatToDecimalConversionFailure)?;
Ok(FloatMajorUnit::new(amount_f64))
}
///Convert minor unit to string minor unit
fn to_minor_unit_as_string(self) -> Result<StringMinorUnit, error_stack::Report<ParsingError>> {
Ok(StringMinorUnit::new(self.0.to_string()))
}
}
impl Display for MinorUnit {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl Add for MinorUnit {
type Output = Self;
fn add(self, a2: Self) -> Self {
Self(self.0 + a2.0)
}
}
impl Sub for MinorUnit {
type Output = Self;
fn sub(self, a2: Self) -> Self {
Self(self.0 - a2.0)
}
}
impl Mul<u16> for MinorUnit {
type Output = Self;
fn mul(self, a2: u16) -> Self::Output {
Self(self.0 * i64::from(a2))
}
}
impl Sum for MinorUnit {
fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
iter.fold(Self(0), |a, b| a + b)
}
}
/// Connector specific types to send
#[derive(
Default,
Debug,
serde::Deserialize,
serde::Serialize,
Clone,
PartialEq,
Eq,
Hash,
ToSchema,
PartialOrd,
)]
pub struct StringMinorUnit(String);
impl StringMinorUnit {
/// forms a new minor unit in string from amount
fn new(value: String) -> Self {
Self(value)
}
/// converts to minor unit i64 from minor unit string value
| {
"chunk": 1,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_1414821583984559341_2 | clm | mini_chunk | // connector-service/backend/common_utils/src/types.rs
fn to_minor_unit_as_i64(&self) -> Result<MinorUnit, error_stack::Report<ParsingError>> {
let amount_string = &self.0;
let amount_decimal = Decimal::from_str(amount_string).map_err(|e| {
ParsingError::StringToDecimalConversionFailure {
error: e.to_string(),
}
})?;
let amount_i64 = amount_decimal
.to_i64()
.ok_or(ParsingError::DecimalToI64ConversionFailure)?;
Ok(MinorUnit::new(amount_i64))
}
}
impl Display for StringMinorUnit {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
/// Connector specific types to send
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq)]
pub struct FloatMajorUnit(pub f64);
impl FloatMajorUnit {
/// forms a new major unit from amount
fn new(value: f64) -> Self {
Self(value)
}
/// forms a new major unit with zero amount
pub fn zero() -> Self {
Self(0.0)
}
/// converts to minor unit as i64 from FloatMajorUnit
fn to_minor_unit_as_i64(
self,
currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<ParsingError>> {
let amount_decimal =
Decimal::from_f64(self.0).ok_or(ParsingError::FloatToDecimalConversionFailure)?;
let amount = if currency.is_zero_decimal_currency() {
amount_decimal
} else if currency.is_three_decimal_currency() {
amount_decimal * Decimal::from(1000)
} else {
amount_decimal * Decimal::from(100)
};
let amount_i64 = amount
.to_i64()
.ok_or(ParsingError::DecimalToI64ConversionFailure)?;
Ok(MinorUnit::new(amount_i64))
}
}
/// Connector specific types to send
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, PartialEq, Eq)]
pub struct StringMajorUnit(String);
impl StringMajorUnit {
/// forms a new major unit from amount
fn new(value: String) -> Self {
Self(value)
}
/// Converts to minor unit as i64 from StringMajorUnit
fn to_minor_unit_as_i64(
&self,
currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<ParsingError>> {
let amount_decimal = Decimal::from_str(&self.0).map_err(|e| {
ParsingError::StringToDecimalConversionFailure {
error: e.to_string(),
}
})?;
let amount = if currency.is_zero_decimal_currency() {
amount_decimal
} else if currency.is_three_decimal_currency() {
amount_decimal * Decimal::from(1000)
} else {
amount_decimal * Decimal::from(100)
};
let amount_i64 = amount
.to_i64()
.ok_or(ParsingError::DecimalToI64ConversionFailure)?;
Ok(MinorUnit::new(amount_i64))
}
/// forms a new StringMajorUnit default unit i.e zero
pub fn zero() -> Self {
Self("0".to_string())
}
/// Get string amount from struct to be removed in future
pub fn get_amount_as_string(&self) -> String {
self.0.clone()
}
}
/// A type representing a range of time for filtering, including a mandatory start time and an optional end time.
#[derive(
Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash, ToSchema,
)]
pub struct TimeRange {
/// The start time to filter payments list or to get list of filters. To get list of filters start time is needed to be passed
#[serde(with = "crate::custom_serde::iso8601")]
#[serde(alias = "startTime")]
pub start_time: PrimitiveDateTime,
/// The end time to filter payments list or to get list of filters. If not passed the default time is now
#[serde(default, with = "crate::custom_serde::iso8601::option")]
#[serde(alias = "endTime")]
pub end_time: Option<PrimitiveDateTime>,
}
/// This struct lets us represent a semantic version type
#[derive(Debug, Clone, PartialEq, Eq, Ord, PartialOrd, Serialize, serde::Deserialize)]
pub struct SemanticVersion(#[serde(with = "Version")] Version);
impl SemanticVersion {
/// returns major version number
pub fn get_major(&self) -> u64 {
self.0.major
}
/// returns minor version number
pub fn get_minor(&self) -> u64 {
| {
"chunk": 2,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_1414821583984559341_3 | clm | mini_chunk | // connector-service/backend/common_utils/src/types.rs
self.0.minor
}
/// Constructs new SemanticVersion instance
pub fn new(major: u64, minor: u64, patch: u64) -> Self {
Self(Version::new(major, minor, patch))
}
}
impl Display for SemanticVersion {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl FromStr for SemanticVersion {
type Err = error_stack::Report<ParsingError>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self(Version::from_str(s).change_context(
ParsingError::StructParseFailure("SemanticVersion"),
)?))
}
}
| {
"chunk": 3,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_-4813005579221307816_0 | clm | mini_chunk | // connector-service/backend/common_utils/src/events.rs
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use crate::{
global_id::{
customer::GlobalCustomerId,
payment::GlobalPaymentId,
payment_methods::{GlobalPaymentMethodId, GlobalPaymentMethodSessionId},
refunds::GlobalRefundId,
token::GlobalTokenId,
},
id_type::{self, ApiKeyId, MerchantConnectorAccountId, ProfileAcquirerId},
lineage,
types::TimeRange,
};
/// Wrapper type that enforces masked serialization for Serde values
#[derive(Debug, Clone, Serialize)]
#[serde(transparent)]
pub struct MaskedSerdeValue {
inner: serde_json::Value,
}
impl MaskedSerdeValue {
pub fn from_masked<T: Serialize>(value: &T) -> Result<Self, serde_json::Error> {
let masked_value = hyperswitch_masking::masked_serialize(value)?;
Ok(Self {
inner: masked_value,
})
}
pub fn from_masked_optional<T: Serialize>(value: &T, context: &str) -> Option<Self> {
hyperswitch_masking::masked_serialize(value)
.map(|masked_value| Self {
inner: masked_value,
})
.inspect_err(|e| {
tracing::error!(
error_category = ?e.classify(),
context = context,
"Failed to mask serialize data"
);
})
.ok()
}
pub fn inner(&self) -> &serde_json::Value {
&self.inner
}
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(tag = "flow_type", rename_all = "snake_case")]
pub enum ApiEventsType {
Payout {
payout_id: String,
},
Payment {
payment_id: GlobalPaymentId,
},
Refund {
payment_id: Option<GlobalPaymentId>,
refund_id: GlobalRefundId,
},
PaymentMethod {
payment_method_id: GlobalPaymentMethodId,
payment_method_type: Option<common_enums::PaymentMethod>,
payment_method_subtype: Option<common_enums::PaymentMethodType>,
},
PaymentMethodCreate,
Customer {
customer_id: Option<GlobalCustomerId>,
},
BusinessProfile {
profile_id: id_type::ProfileId,
},
ApiKey {
key_id: ApiKeyId,
},
User {
user_id: String,
},
PaymentMethodList {
payment_id: Option<String>,
},
PaymentMethodListForPaymentMethods {
payment_method_id: GlobalPaymentMethodId,
},
Webhooks {
connector: MerchantConnectorAccountId,
payment_id: Option<GlobalPaymentId>,
},
Routing,
ResourceListAPI,
PaymentRedirectionResponse {
payment_id: GlobalPaymentId,
},
Gsm,
// TODO: This has to be removed once the corresponding apiEventTypes are created
Miscellaneous,
Keymanager,
RustLocker,
ApplePayCertificatesMigration,
FraudCheck,
Recon,
ExternalServiceAuth,
Dispute {
dispute_id: String,
},
Events {
merchant_id: id_type::MerchantId,
},
PaymentMethodCollectLink {
link_id: String,
},
Poll {
poll_id: String,
},
Analytics,
ClientSecret {
key_id: id_type::ClientSecretId,
},
PaymentMethodSession {
payment_method_session_id: GlobalPaymentMethodSessionId,
},
Token {
token_id: Option<GlobalTokenId>,
},
ProcessTracker,
ProfileAcquirer {
profile_acquirer_id: ProfileAcquirerId,
},
ThreeDsDecisionRule,
}
pub trait ApiEventMetric {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
None
}
}
impl ApiEventMetric for serde_json::Value {}
impl ApiEventMetric for () {}
impl ApiEventMetric for GlobalPaymentId {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Payment {
payment_id: self.clone(),
})
}
}
impl<Q: ApiEventMetric, E> ApiEventMetric for Result<Q, E> {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
match self {
Ok(q) => q.get_api_event_type(),
Err(_) => None,
}
}
}
// TODO: Ideally all these types should be replaced by newtype responses
impl<T> ApiEventMetric for Vec<T> {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Miscellaneous)
}
}
#[macro_export]
macro_rules! impl_api_event_type {
($event: ident, ($($type:ty),+))=> {
$(
impl ApiEventMetric for $type {
| {
"chunk": 0,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_-4813005579221307816_1 | clm | mini_chunk | // connector-service/backend/common_utils/src/events.rs
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::$event)
}
}
)+
};
}
impl_api_event_type!(
Miscellaneous,
(
String,
id_type::MerchantId,
(Option<i64>, Option<i64>, String),
(Option<i64>, Option<i64>, id_type::MerchantId),
bool
)
);
impl<T: ApiEventMetric> ApiEventMetric for &T {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
T::get_api_event_type(self)
}
}
impl ApiEventMetric for TimeRange {}
#[derive(Debug, Clone, Serialize)]
pub struct Event {
pub request_id: String,
pub timestamp: i128,
pub flow_type: FlowName,
pub connector: String,
pub url: Option<String>,
pub stage: EventStage,
pub latency_ms: Option<u64>,
pub status_code: Option<i32>,
pub request_data: Option<MaskedSerdeValue>,
pub response_data: Option<MaskedSerdeValue>,
pub headers: HashMap<String, String>,
#[serde(flatten)]
pub additional_fields: HashMap<String, MaskedSerdeValue>,
#[serde(flatten)]
pub lineage_ids: lineage::LineageIds<'static>,
}
impl Event {
pub fn add_reference_id(&mut self, reference_id: Option<&str>) {
reference_id
.and_then(|ref_id| {
MaskedSerdeValue::from_masked_optional(&ref_id.to_string(), "reference_id")
})
.map(|masked_ref| {
self.additional_fields
.insert("reference_id".to_string(), masked_ref);
});
}
pub fn set_grpc_error_response(&mut self, tonic_error: &tonic::Status) {
self.status_code = Some(tonic_error.code().into());
let error_body = serde_json::json!({
"grpc_code": i32::from(tonic_error.code()),
"grpc_code_name": format!("{:?}", tonic_error.code())
});
self.response_data =
MaskedSerdeValue::from_masked_optional(&error_body, "grpc_error_response");
}
pub fn set_grpc_success_response<R: Serialize>(&mut self, response: &R) {
self.status_code = Some(0);
self.response_data =
MaskedSerdeValue::from_masked_optional(response, "grpc_success_response");
}
pub fn set_connector_response<R: Serialize>(&mut self, response: &R) {
self.response_data = MaskedSerdeValue::from_masked_optional(response, "connector_response");
}
}
#[derive(strum::Display)]
#[strum(serialize_all = "snake_case")]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum FlowName {
Authorize,
Refund,
Capture,
Void,
VoidPostCapture,
Psync,
Rsync,
AcceptDispute,
SubmitEvidence,
DefendDispute,
Dsync,
IncomingWebhook,
SetupMandate,
RepeatPayment,
CreateOrder,
CreateSessionToken,
CreateAccessToken,
CreateConnectorCustomer,
PaymentMethodToken,
PreAuthenticate,
Authenticate,
PostAuthenticate,
Unknown,
}
impl FlowName {
pub fn as_str(&self) -> &'static str {
match self {
Self::Authorize => "Authorize",
Self::Refund => "Refund",
Self::Capture => "Capture",
Self::Void => "Void",
Self::VoidPostCapture => "VoidPostCapture",
Self::Psync => "Psync",
Self::Rsync => "Rsync",
Self::AcceptDispute => "AcceptDispute",
Self::SubmitEvidence => "SubmitEvidence",
Self::DefendDispute => "DefendDispute",
Self::Dsync => "Dsync",
Self::IncomingWebhook => "IncomingWebhook",
Self::SetupMandate => "SetupMandate",
Self::RepeatPayment => "RepeatPayment",
Self::CreateOrder => "CreateOrder",
Self::PaymentMethodToken => "PaymentMethodToken",
Self::CreateSessionToken => "CreateSessionToken",
Self::CreateAccessToken => "CreateAccessToken",
Self::CreateConnectorCustomer => "CreateConnectorCustomer",
Self::PreAuthenticate => "PreAuthenticate",
Self::Authenticate => "Authenticate",
Self::PostAuthenticate => "PostAuthenticate",
Self::Unknown => "Unknown",
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum EventStage {
ConnectorCall,
GrpcRequest,
}
impl EventStage {
pub fn as_str(&self) -> &'static str {
match self {
| {
"chunk": 1,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_-4813005579221307816_2 | clm | mini_chunk | // connector-service/backend/common_utils/src/events.rs
Self::ConnectorCall => "CONNECTOR_CALL",
Self::GrpcRequest => "GRPC_REQUEST",
}
}
}
/// Configuration for events system
#[derive(Debug, Clone, Deserialize)]
pub struct EventConfig {
pub enabled: bool,
pub topic: String,
pub brokers: Vec<String>,
pub partition_key_field: String,
#[serde(default)]
pub transformations: HashMap<String, String>, // target_path → source_field
#[serde(default)]
pub static_values: HashMap<String, String>, // target_path → static_value
#[serde(default)]
pub extractions: HashMap<String, String>, // target_path → extraction_path
}
impl Default for EventConfig {
fn default() -> Self {
Self {
enabled: false,
topic: "events".to_string(),
brokers: vec!["localhost:9092".to_string()],
partition_key_field: "request_id".to_string(),
transformations: HashMap::new(),
static_values: HashMap::new(),
extractions: HashMap::new(),
}
}
}
| {
"chunk": 2,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_-1874607272906183358_0 | clm | mini_chunk | // connector-service/backend/common_utils/src/metadata.rs
use std::collections::HashSet;
use bytes::Bytes;
use hyperswitch_masking::{Maskable, Secret};
/// Configuration for header masking in gRPC metadata.
#[derive(Debug, Clone)]
pub struct HeaderMaskingConfig {
unmasked_keys: HashSet<String>,
}
impl HeaderMaskingConfig {
pub fn new(unmasked_keys: HashSet<String>) -> Self {
Self { unmasked_keys }
}
pub fn should_unmask(&self, key: &str) -> bool {
self.unmasked_keys.contains(&key.to_lowercase())
}
}
impl<'de> serde::Deserialize<'de> for HeaderMaskingConfig {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(serde::Deserialize)]
struct Config {
keys: Vec<String>,
}
Config::deserialize(deserializer).map(|config| Self {
unmasked_keys: config
.keys
.into_iter()
.map(|key| key.to_lowercase())
.collect(),
})
}
}
impl Default for HeaderMaskingConfig {
fn default() -> Self {
Self {
unmasked_keys: ["content-type", "content-length", "user-agent"]
.iter()
.map(|&key| key.to_string())
.collect(),
}
}
}
/// Secure wrapper for gRPC metadata with configurable masking.
/// ASCII headers:
/// - get(key) -> Secret<String> - Forces explicit .expose() call
/// - get_raw(key) -> String - Raw access
/// - get_maskable(key) -> Maskable<String> - For logging/observability
///
/// Binary headers:
/// - get_bin(key) -> Secret<Bytes> - Forces explicit .expose() call
/// - get_bin_raw(key) -> Bytes - Raw access
/// - get_bin_maskable(key) -> Maskable<String> - Base64 encoded for logging
/// - get_all_masked() -> HashMap<String, String> - Safe for logging
#[derive(Clone)]
pub struct MaskedMetadata {
raw_metadata: tonic::metadata::MetadataMap,
masking_config: HeaderMaskingConfig,
}
impl std::fmt::Debug for MaskedMetadata {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("MaskedMetadata")
.field("masked_headers", &self.get_all_masked())
.field("masking_config", &self.masking_config)
.finish()
}
}
impl MaskedMetadata {
pub fn new(
raw_metadata: tonic::metadata::MetadataMap,
masking_config: HeaderMaskingConfig,
) -> Self {
Self {
raw_metadata,
masking_config,
}
}
/// Always returns Secret - business logic must call .expose() explicitly
pub fn get(&self, key: &str) -> Option<Secret<String>> {
self.raw_metadata
.get(key)
.and_then(|value| value.to_str().ok())
.map(|s| Secret::new(s.to_string()))
}
/// Returns raw string value regardless of config
pub fn get_raw(&self, key: &str) -> Option<String> {
self.raw_metadata
.get(key)
.and_then(|value| value.to_str().ok())
.map(|s| s.to_string())
}
/// Returns Maskable with enum variants for logging (masked/unmasked)
pub fn get_maskable(&self, key: &str) -> Option<Maskable<String>> {
self.raw_metadata
.get(key)
.and_then(|value| value.to_str().ok())
.map(|s| {
if self.masking_config.should_unmask(key) {
Maskable::new_normal(s.to_string())
} else {
Maskable::new_masked(Secret::new(s.to_string()))
}
})
}
/// Always returns Secret<Bytes> - business logic must call .expose() explicitly
pub fn get_bin(&self, key: &str) -> Option<Secret<Bytes>> {
self.raw_metadata
.get_bin(key)
.and_then(|value| value.to_bytes().ok())
.map(Secret::new)
}
/// Returns raw Bytes value regardless of config
pub fn get_bin_raw(&self, key: &str) -> Option<Bytes> {
self.raw_metadata
.get_bin(key)
.and_then(|value| value.to_bytes().ok())
}
/// Returns Maskable<String> with base64 encoding for binary headers
pub fn get_bin_maskable(&self, key: &str) -> Option<Maskable<String>> {
self.raw_metadata.get_bin(key).map(|value| {
let encoded = String::from_utf8_lossy(value.as_encoded_bytes()).to_string();
| {
"chunk": 0,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_-1874607272906183358_1 | clm | mini_chunk | // connector-service/backend/common_utils/src/metadata.rs
if self.masking_config.should_unmask(key) {
Maskable::new_normal(encoded)
} else {
Maskable::new_masked(Secret::new(encoded))
}
})
}
/// Get all metadata as HashMap with masking for logging
pub fn get_all_masked(&self) -> std::collections::HashMap<String, String> {
self.raw_metadata
.iter()
.filter_map(|entry| {
let key_name = match entry {
tonic::metadata::KeyAndValueRef::Ascii(key, _) => key.as_str(),
tonic::metadata::KeyAndValueRef::Binary(key, _) => key.as_str(),
};
let masked_value = match entry {
tonic::metadata::KeyAndValueRef::Ascii(_, _) => self
.get_maskable(key_name)
.map(|maskable| format!("{maskable:?}")),
tonic::metadata::KeyAndValueRef::Binary(_, _) => self
.get_bin_maskable(key_name)
.map(|maskable| format!("{maskable:?}")),
};
masked_value.map(|value| (key_name.to_string(), value))
})
.collect()
}
}
| {
"chunk": 1,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_7052884170592430104_0 | clm | mini_chunk | // connector-service/backend/common_utils/src/lib.rs
//! Common utilities for connector service
pub mod crypto;
pub mod custom_serde;
pub mod errors;
pub mod ext_traits;
pub mod fp_utils;
pub mod id_type;
pub mod lineage;
pub mod macros;
pub mod metadata;
pub mod new_types;
pub mod pii;
pub mod request;
pub mod types;
// Re-export commonly used items
pub use errors::{CustomResult, EventPublisherError, ParsingError, ValidationError};
#[cfg(feature = "kafka")]
pub use event_publisher::{emit_event_with_config, init_event_publisher};
#[cfg(not(feature = "kafka"))]
pub fn init_event_publisher(_config: &events::EventConfig) -> CustomResult<(), ()> {
Ok(())
}
#[cfg(not(feature = "kafka"))]
pub fn emit_event_with_config(_event: events::Event, _config: &events::EventConfig) {
// No-op when kafka feature is disabled
}
pub use global_id::{CellId, GlobalPaymentId};
pub use id_type::{CustomerId, MerchantId};
pub use pii::{Email, SecretSerdeValue};
pub use request::{Method, Request, RequestContent};
pub use types::{
AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector, MinorUnit, MinorUnitForConnector,
StringMajorUnit, StringMajorUnitForConnector, StringMinorUnit,
};
pub mod events;
pub mod global_id;
pub mod consts;
#[cfg(feature = "kafka")]
pub mod event_publisher;
fn generate_ref_id_with_default_length<const MAX_LENGTH: u8, const MIN_LENGTH: u8>(
prefix: &str,
) -> id_type::LengthId<MAX_LENGTH, MIN_LENGTH> {
id_type::LengthId::<MAX_LENGTH, MIN_LENGTH>::new(prefix)
}
/// Generate a time-ordered (time-sortable) unique identifier using the current time
#[inline]
pub fn generate_time_ordered_id(prefix: &str) -> String {
format!("{prefix}_{}", uuid::Uuid::now_v7().as_simple())
}
pub mod date_time {
#[cfg(feature = "async_ext")]
use std::time::Instant;
use std::{marker::PhantomData, num::NonZeroU8};
use hyperswitch_masking::{Deserialize, Serialize};
use time::{
format_description::{
well_known::iso8601::{Config, EncodedConfig, Iso8601, TimePrecision},
BorrowedFormatItem,
},
OffsetDateTime, PrimitiveDateTime,
};
/// Enum to represent date formats
#[derive(Debug)]
pub enum DateFormat {
/// Format the date in 20191105081132 format
YYYYMMDDHHmmss,
/// Format the date in 20191105 format
YYYYMMDD,
/// Format the date in 201911050811 format
YYYYMMDDHHmm,
/// Format the date in 05112019081132 format
DDMMYYYYHHmmss,
}
/// Create a new [`PrimitiveDateTime`] with the current date and time in UTC.
pub fn now() -> PrimitiveDateTime {
let utc_date_time = OffsetDateTime::now_utc();
PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time())
}
/// Convert from OffsetDateTime to PrimitiveDateTime
pub fn convert_to_pdt(offset_time: OffsetDateTime) -> PrimitiveDateTime {
PrimitiveDateTime::new(offset_time.date(), offset_time.time())
}
/// Return the UNIX timestamp of the current date and time in UTC
pub fn now_unix_timestamp() -> i64 {
OffsetDateTime::now_utc().unix_timestamp()
}
/// Calculate execution time for a async block in milliseconds
#[cfg(feature = "async_ext")]
pub async fn time_it<T, Fut: futures::Future<Output = T>, F: FnOnce() -> Fut>(
block: F,
) -> (T, f64) {
let start = Instant::now();
let result = block().await;
(result, start.elapsed().as_secs_f64() * 1000f64)
}
/// Return the given date and time in UTC with the given format Eg: format: YYYYMMDDHHmmss Eg: 20191105081132
pub fn format_date(
date: PrimitiveDateTime,
format: DateFormat,
) -> Result<String, time::error::Format> {
let format = <&[BorrowedFormatItem<'_>]>::from(format);
date.format(&format)
}
/// Return the current date and time in UTC with the format [year]-[month]-[day]T[hour]:[minute]:[second].mmmZ Eg: 2023-02-15T13:33:18.898Z
pub fn date_as_yyyymmddthhmmssmmmz() -> Result<String, time::error::Format> {
const ISO_CONFIG: EncodedConfig = Config::DEFAULT
.set_time_precision(TimePrecision::Second {
decimal_digits: NonZeroU8::new(3),
})
.encode();
now().assume_utc().format(&Iso8601::<ISO_CONFIG>)
}
impl From<DateFormat> for &[BorrowedFormatItem<'_>] {
| {
"chunk": 0,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_7052884170592430104_1 | clm | mini_chunk | // connector-service/backend/common_utils/src/lib.rs
fn from(format: DateFormat) -> Self {
match format {
DateFormat::YYYYMMDDHHmmss => time::macros::format_description!("[year repr:full][month padding:zero repr:numerical][day padding:zero][hour padding:zero repr:24][minute padding:zero][second padding:zero]"),
DateFormat::YYYYMMDD => time::macros::format_description!("[year repr:full][month padding:zero repr:numerical][day padding:zero]"),
DateFormat::YYYYMMDDHHmm => time::macros::format_description!("[year repr:full][month padding:zero repr:numerical][day padding:zero][hour padding:zero repr:24][minute padding:zero]"),
DateFormat::DDMMYYYYHHmmss => time::macros::format_description!("[day padding:zero][month padding:zero repr:numerical][year repr:full][hour padding:zero repr:24][minute padding:zero][second padding:zero]"),
}
}
}
/// Format the date in 05112019 format
#[derive(Debug, Clone)]
pub struct DDMMYYYY;
/// Format the date in 20191105 format
#[derive(Debug, Clone)]
pub struct YYYYMMDD;
/// Format the date in 20191105081132 format
#[derive(Debug, Clone)]
pub struct YYYYMMDDHHmmss;
/// To serialize the date in Dateformats like YYYYMMDDHHmmss, YYYYMMDD, DDMMYYYY
#[derive(Debug, Deserialize, Clone)]
pub struct DateTime<T: TimeStrategy> {
inner: PhantomData<T>,
value: PrimitiveDateTime,
}
impl<T: TimeStrategy> From<PrimitiveDateTime> for DateTime<T> {
fn from(value: PrimitiveDateTime) -> Self {
Self {
inner: PhantomData,
value,
}
}
}
/// Time strategy for the Date, Eg: YYYYMMDDHHmmss, YYYYMMDD, DDMMYYYY
pub trait TimeStrategy {
/// Stringify the date as per the Time strategy
fn fmt(input: &PrimitiveDateTime, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
}
impl<T: TimeStrategy> Serialize for DateTime<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.collect_str(self)
}
}
impl<T: TimeStrategy> std::fmt::Display for DateTime<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
T::fmt(&self.value, f)
}
}
impl TimeStrategy for DDMMYYYY {
fn fmt(input: &PrimitiveDateTime, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let year = input.year();
#[allow(clippy::as_conversions)]
let month = input.month() as u8;
let day = input.day();
let output = format!("{day:02}{month:02}{year}");
f.write_str(&output)
}
}
impl TimeStrategy for YYYYMMDD {
fn fmt(input: &PrimitiveDateTime, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let year = input.year();
#[allow(clippy::as_conversions)]
let month: u8 = input.month() as u8;
let day = input.day();
let output = format!("{year}{month:02}{day:02}");
f.write_str(&output)
}
}
impl TimeStrategy for YYYYMMDDHHmmss {
fn fmt(input: &PrimitiveDateTime, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let year = input.year();
#[allow(clippy::as_conversions)]
let month = input.month() as u8;
let day = input.day();
let hour = input.hour();
let minute = input.minute();
let second = input.second();
let output = format!("{year}{month:02}{day:02}{hour:02}{minute:02}{second:02}");
f.write_str(&output)
}
}
}
| {
"chunk": 1,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_-5627216939917239271_0 | clm | mini_chunk | // connector-service/backend/common_utils/src/global_id.rs
pub(super) mod customer;
pub(super) mod payment;
pub use payment::GlobalPaymentId;
pub(super) mod payment_methods;
pub(super) mod refunds;
pub(super) mod token;
use error_stack::ResultExt;
use thiserror::Error;
use crate::{
consts::{CELL_IDENTIFIER_LENGTH, MAX_GLOBAL_ID_LENGTH, MIN_GLOBAL_ID_LENGTH},
errors, generate_time_ordered_id,
id_type::{AlphaNumericId, AlphaNumericIdError, LengthId, LengthIdError},
};
#[derive(Debug, Clone, Hash, PartialEq, Eq, serde::Serialize)]
/// A global id that can be used to identify any entity
/// This id will have information about the entity and cell in a distributed system architecture
pub(crate) struct GlobalId(LengthId<MAX_GLOBAL_ID_LENGTH, MIN_GLOBAL_ID_LENGTH>);
#[derive(Clone, Copy)]
/// Entities that can be identified by a global id
pub(crate) enum GlobalEntity {
Customer,
Payment,
#[allow(dead_code)]
Attempt,
PaymentMethod,
Refund,
PaymentMethodSession,
Token,
}
impl GlobalEntity {
fn prefix(self) -> &'static str {
match self {
Self::Customer => "cus",
Self::Payment => "pay",
Self::PaymentMethod => "pm",
Self::Attempt => "att",
Self::Refund => "ref",
Self::PaymentMethodSession => "pms",
Self::Token => "tok",
}
}
}
/// Cell identifier for an instance / deployment of application
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct CellId(LengthId<CELL_IDENTIFIER_LENGTH, CELL_IDENTIFIER_LENGTH>);
impl Default for CellId {
fn default() -> Self {
Self::from_str("cell1").unwrap_or_else(|_| {
let id = AlphaNumericId::new_unchecked("cell1".to_string());
Self(LengthId::new_unchecked(id))
})
}
}
#[derive(Debug, Error, PartialEq, Eq)]
pub enum CellIdError {
#[error("cell id error: {0}")]
InvalidCellLength(LengthIdError),
#[error("{0}")]
InvalidCellIdFormat(AlphaNumericIdError),
}
impl From<LengthIdError> for CellIdError {
fn from(error: LengthIdError) -> Self {
Self::InvalidCellLength(error)
}
}
impl From<AlphaNumericIdError> for CellIdError {
fn from(error: AlphaNumericIdError) -> Self {
Self::InvalidCellIdFormat(error)
}
}
impl CellId {
/// Create a new cell id from a string
fn from_str(cell_id_string: impl AsRef<str>) -> Result<Self, CellIdError> {
let trimmed_input_string = cell_id_string.as_ref().trim().to_string();
let alphanumeric_id = AlphaNumericId::from(trimmed_input_string.into())?;
let length_id = LengthId::from_alphanumeric_id(alphanumeric_id)?;
Ok(Self(length_id))
}
/// Create a new cell id from a string
pub fn from_string(
input_string: impl AsRef<str>,
) -> error_stack::Result<Self, errors::ValidationError> {
Self::from_str(input_string).change_context(
errors::ValidationError::IncorrectValueProvided {
field_name: "cell_id",
},
)
}
/// Get the string representation of the cell id
fn get_string_repr(&self) -> &str {
&self.0 .0 .0
}
}
impl<'de> serde::Deserialize<'de> for CellId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let deserialized_string = String::deserialize(deserializer)?;
Self::from_str(deserialized_string.as_str()).map_err(serde::de::Error::custom)
}
}
/// Error generated from violation of constraints for MerchantReferenceId
#[derive(Debug, Error, PartialEq, Eq)]
pub(crate) enum GlobalIdError {
/// The format for the global id is invalid
#[error("The id format is invalid, expected format is {{cell_id:5}}_{{entity_prefix:3}}_{{uuid:32}}_{{random:24}}")]
InvalidIdFormat,
/// LengthIdError and AlphanumericIdError
#[error("{0}")]
LengthIdError(#[from] LengthIdError),
/// CellIdError because of invalid cell id format
#[error("{0}")]
CellIdError(#[from] CellIdError),
}
impl GlobalId {
/// Create a new global id from entity and cell information
/// The entity prefix is used to identify the entity, `cus` for customers, `pay`` for payments etc.
pub fn generate(cell_id: &CellId, entity: GlobalEntity) -> Self {
let prefix = format!("{}_{}", cell_id.get_string_repr(), entity.prefix());
| {
"chunk": 0,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_-5627216939917239271_1 | clm | mini_chunk | // connector-service/backend/common_utils/src/global_id.rs
let id = generate_time_ordered_id(&prefix);
let alphanumeric_id = AlphaNumericId::new_unchecked(id);
Self(LengthId::new_unchecked(alphanumeric_id))
}
pub(crate) fn from_string(
input_string: std::borrow::Cow<'static, str>,
) -> Result<Self, GlobalIdError> {
let length_id = LengthId::from(input_string)?;
let input_string = &length_id.0 .0;
let (cell_id, _remaining) = input_string
.split_once("_")
.ok_or(GlobalIdError::InvalidIdFormat)?;
CellId::from_str(cell_id)?;
Ok(Self(length_id))
}
pub(crate) fn get_string_repr(&self) -> &str {
&self.0 .0 .0
}
}
/// Deserialize the global id from string
/// The format should match {cell_id:5}_{entity_prefix:3}_{time_ordered_id:32}_{.*:24}
impl<'de> serde::Deserialize<'de> for GlobalId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let deserialized_string = String::deserialize(deserializer)?;
Self::from_string(deserialized_string.into()).map_err(serde::de::Error::custom)
}
}
#[cfg(test)]
mod global_id_tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn test_cell_id_from_str() {
let cell_id_string = "12345";
let cell_id = CellId::from_str(cell_id_string).unwrap();
assert_eq!(cell_id.get_string_repr(), cell_id_string);
}
#[test]
fn test_global_id_generate() {
let cell_id_string = "12345";
let entity = GlobalEntity::Customer;
let cell_id = CellId::from_str(cell_id_string).unwrap();
let global_id = GlobalId::generate(&cell_id, entity);
// Generate a regex for globalid
// Eg - 12abc_cus_abcdefghijklmnopqrstuvwxyz1234567890
let regex = regex::Regex::new(r"[a-z0-9]{5}_cus_[a-z0-9]{32}").unwrap();
assert!(regex.is_match(&global_id.0 .0 .0));
}
#[test]
fn test_global_id_from_string() {
let input_string = "12345_cus_abcdefghijklmnopqrstuvwxyz1234567890";
let global_id = GlobalId::from_string(input_string.into()).unwrap();
assert_eq!(global_id.0 .0 .0, input_string);
}
#[test]
fn test_global_id_deser() {
let input_string_for_serde_json_conversion =
r#""12345_cus_abcdefghijklmnopqrstuvwxyz1234567890""#;
let input_string = "12345_cus_abcdefghijklmnopqrstuvwxyz1234567890";
let global_id =
serde_json::from_str::<GlobalId>(input_string_for_serde_json_conversion).unwrap();
assert_eq!(global_id.0 .0 .0, input_string);
}
#[test]
fn test_global_id_deser_error() {
let input_string_for_serde_json_conversion =
r#""123_45_cus_abcdefghijklmnopqrstuvwxyz1234567890""#;
let global_id = serde_json::from_str::<GlobalId>(input_string_for_serde_json_conversion);
assert!(global_id.is_err());
let expected_error_message = format!(
"cell id error: the minimum required length for this field is {CELL_IDENTIFIER_LENGTH}"
);
let error_message = global_id.unwrap_err().to_string();
assert_eq!(error_message, expected_error_message);
}
}
| {
"chunk": 1,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_8679312917364799131_0 | clm | mini_chunk | // connector-service/backend/common_utils/src/fp_utils.rs
//! Functional programming utilities
use crate::consts::{ALPHABETS, ID_LENGTH};
/// The Applicative trait provides a pure behavior,
/// which can be used to create values of type f a from values of type a.
pub trait Applicative<R> {
/// The Associative type acts as a (f a) wrapper for Self.
type WrappedSelf<T>;
/// Applicative::pure(_) is abstraction with lifts any arbitrary type to underlying higher
/// order type
fn pure(v: R) -> Self::WrappedSelf<R>;
}
impl<R> Applicative<R> for Option<R> {
type WrappedSelf<T> = Option<T>;
fn pure(v: R) -> Self::WrappedSelf<R> {
Some(v)
}
}
impl<R, E> Applicative<R> for Result<R, E> {
type WrappedSelf<T> = Result<T, E>;
fn pure(v: R) -> Self::WrappedSelf<R> {
Ok(v)
}
}
/// based on the condition provided into the `predicate`
pub fn when<W: Applicative<(), WrappedSelf<()> = W>, F>(predicate: bool, f: F) -> W
where
F: FnOnce() -> W,
{
if predicate {
f()
} else {
W::pure(())
}
}
#[inline]
pub fn generate_id_with_default_len(prefix: &str) -> String {
let len: usize = ID_LENGTH;
format!("{}_{}", prefix, nanoid::nanoid!(len, &ALPHABETS))
}
#[inline]
pub fn generate_id(length: usize, prefix: &str) -> String {
format!("{}_{}", prefix, nanoid::nanoid!(length, &ALPHABETS))
}
| {
"chunk": 0,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_6732291692182265096_0 | clm | mini_chunk | // connector-service/backend/common_utils/src/pii.rs
//! Personal Identifiable Information protection.
use std::{convert::AsRef, fmt, ops, str::FromStr};
use error_stack::ResultExt;
use hyperswitch_masking::{ExposeInterface, Secret, Strategy, WithType};
use serde::Deserialize;
use crate::{
consts::REDACTED,
errors::{self, ValidationError},
};
/// Type alias for serde_json value which has Secret Information
pub type SecretSerdeValue = Secret<serde_json::Value>;
/// Strategy for masking Email
#[derive(Debug, Copy, Clone, Deserialize)]
pub enum EmailStrategy {}
impl<T> Strategy<T> for EmailStrategy
where
T: AsRef<str> + fmt::Debug,
{
fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let val_str: &str = val.as_ref();
match val_str.split_once('@') {
Some((a, b)) => write!(f, "{}@{}", "*".repeat(a.len()), b),
None => WithType::fmt(val, f),
}
}
}
/// Email address
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, Default)]
#[serde(try_from = "String")]
pub struct Email(Secret<String, EmailStrategy>);
impl ExposeInterface<Secret<String, EmailStrategy>> for Email {
fn expose(self) -> Secret<String, EmailStrategy> {
self.0
}
}
impl TryFrom<String> for Email {
type Error = error_stack::Report<errors::ParsingError>;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::from_str(&value).change_context(errors::ParsingError::EmailParsingError)
}
}
impl ops::Deref for Email {
type Target = Secret<String, EmailStrategy>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl ops::DerefMut for Email {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl FromStr for Email {
type Err = error_stack::Report<ValidationError>;
fn from_str(email: &str) -> Result<Self, Self::Err> {
if email.eq(REDACTED) {
return Ok(Self(Secret::new(email.to_string())));
}
// Basic email validation - in production you'd use a more robust validator
if email.contains('@') && email.len() > 3 {
let secret = Secret::<String, EmailStrategy>::new(email.to_string());
Ok(Self(secret))
} else {
Err(ValidationError::InvalidValue {
message: "Invalid email address format".into(),
}
.into())
}
}
}
/// IP address strategy
#[derive(Debug)]
pub enum IpAddress {}
impl<T> Strategy<T> for IpAddress
where
T: AsRef<str>,
{
fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let val_str: &str = val.as_ref();
let segments: Vec<&str> = val_str.split('.').collect();
if segments.len() != 4 {
return WithType::fmt(val, f);
}
for seg in segments.iter() {
if seg.is_empty() || seg.len() > 3 {
return WithType::fmt(val, f);
}
}
if let Some(segments) = segments.first() {
write!(f, "{segments}.**.**.**")
} else {
WithType::fmt(val, f)
}
}
}
/// Strategy for masking UPI VPA's
#[derive(Debug)]
pub enum UpiVpaMaskingStrategy {}
impl<T> Strategy<T> for UpiVpaMaskingStrategy
where
T: AsRef<str> + fmt::Debug,
{
fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let vpa_str: &str = val.as_ref();
if let Some((user_identifier, bank_or_psp)) = vpa_str.split_once('@') {
let masked_user_identifier = "*".repeat(user_identifier.len());
write!(f, "{masked_user_identifier}@{bank_or_psp}")
} else {
WithType::fmt(val, f)
}
}
}
#[derive(Debug)]
pub enum EncryptionStrategy {}
impl<T> Strategy<T> for EncryptionStrategy
where
T: AsRef<[u8]>,
{
fn fmt(value: &T, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(
fmt,
"*** Encrypted data of length {} bytes ***",
value.as_ref().len()
)
}
}
| {
"chunk": 0,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_2179811235784210369_0 | clm | mini_chunk | // connector-service/backend/common_utils/src/errors.rs
//! Errors and error specific types for universal use
use crate::types::MinorUnit;
/// Custom Result
/// A custom datatype that wraps the error variant <E> into a report, allowing
/// error_stack::Report<E> specific extendability
///
/// Effectively, equivalent to `Result<T, error_stack::Report<E>>`
pub type CustomResult<T, E> = error_stack::Result<T, E>;
/// Parsing Errors
#[allow(missing_docs)] // Only to prevent warnings about struct fields not being documented
#[derive(Debug, thiserror::Error)]
pub enum ParsingError {
///Failed to parse enum
#[error("Failed to parse enum: {0}")]
EnumParseFailure(&'static str),
///Failed to parse struct
#[error("Failed to parse struct: {0}")]
StructParseFailure(&'static str),
/// Failed to encode data to given format
#[error("Failed to serialize to {0} format")]
EncodeError(&'static str),
/// Failed to parse data
#[error("Unknown error while parsing")]
UnknownError,
/// Failed to parse datetime
#[error("Failed to parse datetime")]
DateTimeParsingError,
/// Failed to parse email
#[error("Failed to parse email")]
EmailParsingError,
/// Failed to parse phone number
#[error("Failed to parse phone number")]
PhoneNumberParsingError,
/// Failed to parse Float value for converting to decimal points
#[error("Failed to parse Float value for converting to decimal points")]
FloatToDecimalConversionFailure,
/// Failed to parse Decimal value for i64 value conversion
#[error("Failed to parse Decimal value for i64 value conversion")]
DecimalToI64ConversionFailure,
/// Failed to parse string value for f64 value conversion
#[error("Failed to parse string value for f64 value conversion")]
StringToFloatConversionFailure,
/// Failed to parse i64 value for f64 value conversion
#[error("Failed to parse i64 value for f64 value conversion")]
I64ToDecimalConversionFailure,
/// Failed to parse String value to Decimal value conversion because `error`
#[error("Failed to parse String value to Decimal value conversion because {error}")]
StringToDecimalConversionFailure { error: String },
/// Failed to convert the given integer because of integer overflow error
#[error("Integer Overflow error")]
IntegerOverflow,
}
/// Validation errors.
#[allow(missing_docs)] // Only to prevent warnings about struct fields not being documented
#[derive(Debug, thiserror::Error, Clone, PartialEq)]
pub enum ValidationError {
/// The provided input is missing a required field.
#[error("Missing required field: {field_name}")]
MissingRequiredField { field_name: String },
/// An incorrect value was provided for the field specified by `field_name`.
#[error("Incorrect value provided for field: {field_name}")]
IncorrectValueProvided { field_name: &'static str },
/// An invalid input was provided.
#[error("{message}")]
InvalidValue { message: String },
}
/// Api Models construction error
#[derive(Debug, Clone, thiserror::Error, PartialEq)]
pub enum PercentageError {
/// Percentage Value provided was invalid
#[error("Invalid Percentage value")]
InvalidPercentageValue,
/// Error occurred while calculating percentage
#[error("Failed apply percentage of {percentage} on {amount}")]
UnableToApplyPercentage {
/// percentage value
percentage: f32,
/// amount value
amount: MinorUnit,
},
}
/// Allow [error_stack::Report] to convert between error types
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)
}
}
/// Allows [error_stack::Report] to change between error contexts
| {
"chunk": 0,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_2179811235784210369_1 | clm | mini_chunk | // connector-service/backend/common_utils/src/errors.rs
/// 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))
}
}
}
}
#[derive(Debug, thiserror::Error)]
pub enum CryptoError {
/// The cryptographic algorithm was unable to encode the message
#[error("Failed to encode given message")]
EncodingFailed,
/// The cryptographic algorithm was unable to decode the message
#[error("Failed to decode given message")]
DecodingFailed,
/// The cryptographic algorithm was unable to sign the message
#[error("Failed to sign message")]
MessageSigningFailed,
/// The cryptographic algorithm was unable to verify the given signature
#[error("Failed to verify signature")]
SignatureVerificationFailed,
/// The provided key length is invalid for the cryptographic algorithm
#[error("Invalid key length")]
InvalidKeyLength,
/// The provided IV length is invalid for the cryptographic algorithm
#[error("Invalid IV length")]
InvalidIvLength,
}
impl ErrorSwitchFrom<common_enums::CurrencyError> for ParsingError {
fn switch_from(error: &common_enums::CurrencyError) -> Self {
match error {
common_enums::CurrencyError::UnsupportedCurrency { .. } => {
Self::StructParseFailure("currency decimal configuration")
}
}
}
}
/// Integrity check errors.
#[derive(Debug, Clone, PartialEq, Default)]
pub struct IntegrityCheckError {
/// Field names for which integrity check failed!
pub field_names: String,
/// Connector transaction reference id
pub connector_transaction_id: Option<String>,
}
/// Event publisher errors.
#[derive(Debug, thiserror::Error)]
pub enum EventPublisherError {
/// Failed to initialize Kafka writer
#[error("Failed to initialize Kafka writer")]
KafkaWriterInitializationFailed,
/// Failed to serialize event data
#[error("Failed to serialize event data")]
EventSerializationFailed,
/// Failed to publish event to Kafka
#[error("Failed to publish event to Kafka")]
EventPublishFailed,
/// Invalid configuration provided
#[error("Invalid configuration: {message}")]
InvalidConfiguration { message: String },
/// Event publisher already initialized
#[error("Event publisher already initialized")]
AlreadyInitialized,
/// Failed to process event transformations
#[error("Failed to process event transformations")]
EventProcessingFailed,
/// Invalid path provided for nested value setting
#[error("Invalid path provided: {path}")]
InvalidPath { path: String },
}
| {
"chunk": 1,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_45732705880422454_0 | clm | mini_chunk | // connector-service/backend/common_utils/src/lineage.rs
//! Lineage ID domain types for tracking request lineage across services
use std::collections::HashMap;
/// A domain type representing lineage IDs as key-value pairs(uses hashmap internally).
///
/// This type can deserialize only from URL-encoded format (e.g., "trace_id=123&span_id=456")
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct LineageIds<'a> {
prefix: &'a str,
inner: HashMap<String, String>,
}
impl<'a> LineageIds<'a> {
/// Create a new LineageIds from prefix and URL-encoded string
pub fn new(prefix: &'a str, url_encoded_string: &str) -> Result<Self, LineageParseError> {
Ok(Self {
prefix,
inner: serde_urlencoded::from_str(url_encoded_string)
.map_err(|e| LineageParseError::InvalidFormat(e.to_string()))?,
})
}
/// Create a new empty LineageIds
pub fn empty(prefix: &'a str) -> Self {
Self {
prefix,
inner: HashMap::new(),
}
}
/// Get the inner HashMap with prefixed keys
pub fn inner(&self) -> HashMap<String, String> {
self.inner
.iter()
.map(|(k, v)| (format!("{}{}", self.prefix, k), v.clone()))
.collect()
}
/// Get the inner HashMap without prefix (raw keys)
pub fn inner_raw(&self) -> &HashMap<String, String> {
&self.inner
}
/// Convert to an owned LineageIds with 'static lifetime
pub fn to_owned(&self) -> LineageIds<'static> {
LineageIds {
prefix: Box::leak(self.prefix.to_string().into_boxed_str()),
inner: self.inner.clone(),
}
}
}
impl serde::Serialize for LineageIds<'_> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let prefixed_map = self.inner();
prefixed_map.serialize(serializer)
}
}
/// Error type for lineage parsing operations
#[derive(Debug, thiserror::Error)]
pub enum LineageParseError {
#[error("Invalid lineage header format: {0}")]
InvalidFormat(String),
#[error("URL decoding failed: {0}")]
UrlDecoding(String),
}
| {
"chunk": 0,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_-841769499540836508_0 | clm | mini_chunk | // connector-service/backend/common_utils/src/id_type.rs
//! Common ID types
use std::{borrow::Cow, fmt::Debug};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use crate::{
fp_utils::{generate_id_with_default_len, when},
CustomResult, ValidationError,
};
/// A type for alphanumeric ids
#[derive(Debug, PartialEq, Hash, Serialize, Clone, Eq)]
pub(crate) struct AlphaNumericId(pub String);
impl AlphaNumericId {
/// Generate a new alphanumeric id of default length
pub(crate) fn new(prefix: &str) -> Self {
Self(generate_id_with_default_len(prefix))
}
}
#[derive(Debug, Deserialize, Hash, Serialize, Error, Eq, PartialEq)]
#[error("value `{0}` contains invalid character `{1}`")]
/// The error type for alphanumeric id
pub struct AlphaNumericIdError(String, char);
impl<'de> Deserialize<'de> for AlphaNumericId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let deserialized_string = String::deserialize(deserializer)?;
Self::from(deserialized_string.into()).map_err(serde::de::Error::custom)
}
}
impl AlphaNumericId {
/// Creates a new alphanumeric id from string by applying validation checks
pub fn from(input_string: Cow<'static, str>) -> Result<Self, AlphaNumericIdError> {
// For simplicity, we'll accept any string - in production you'd validate alphanumeric
Ok(Self(input_string.to_string()))
}
/// Create a new alphanumeric id without any validations
pub(crate) fn new_unchecked(input_string: String) -> Self {
Self(input_string)
}
}
/// Simple ID types for customer and merchant
#[derive(Debug, Clone, Serialize, Hash, PartialEq, Eq)]
pub struct CustomerId(String);
impl Default for CustomerId {
fn default() -> Self {
Self("cus_default".to_string())
}
}
impl CustomerId {
pub fn get_string_repr(&self) -> &str {
&self.0
}
}
impl<'de> Deserialize<'de> for CustomerId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
Ok(Self(s))
}
}
impl FromStr for CustomerId {
type Err = error_stack::Report<ValidationError>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self(s.to_string()))
}
}
impl TryFrom<Cow<'_, str>> for CustomerId {
type Error = error_stack::Report<ValidationError>;
fn try_from(value: Cow<'_, str>) -> Result<Self, Self::Error> {
Ok(Self(value.to_string()))
}
}
impl hyperswitch_masking::SerializableSecret for CustomerId {}
#[derive(Debug, Clone, Serialize, Hash, PartialEq, Eq)]
pub struct MerchantId(String);
impl Default for MerchantId {
fn default() -> Self {
Self("mer_default".to_string())
}
}
impl MerchantId {
pub fn get_string_repr(&self) -> &str {
&self.0
}
}
impl<'de> Deserialize<'de> for MerchantId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = String::deserialize(deserializer)?;
Ok(Self(s))
}
}
impl FromStr for MerchantId {
type Err = std::convert::Infallible;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self(s.to_string()))
}
}
crate::id_type!(
PaymentId,
"A type for payment_id that can be used for payment ids"
);
crate::impl_id_type_methods!(PaymentId, "payment_id");
// This is to display the `PaymentId` as PaymentId(abcd)
crate::impl_debug_id_type!(PaymentId);
crate::impl_default_id_type!(PaymentId, "pay");
crate::impl_try_from_cow_str_id_type!(PaymentId, "payment_id");
impl PaymentId {
/// Get the hash key to be stored in redis
pub fn get_hash_key_for_kv_store(&self) -> String {
format!("pi_{}", self.0 .0 .0)
}
// This function should be removed once we have a better way to handle mandatory payment id in other flows
/// Get payment id in the format of irrelevant_payment_id_in_{flow}
pub fn get_irrelevant_id(flow: &str) -> Self {
let alphanumeric_id =
AlphaNumericId::new_unchecked(format!("irrelevant_payment_id_in_{flow}"));
let id = LengthId::new_unchecked(alphanumeric_id);
Self(id)
}
/// Get the attempt id for the payment id based on the attempt count
pub fn get_attempt_id(&self, attempt_count: i16) -> String {
| {
"chunk": 0,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_-841769499540836508_1 | clm | mini_chunk | // connector-service/backend/common_utils/src/id_type.rs
format!("{}_{attempt_count}", self.get_string_repr())
}
/// Generate a client id for the payment id
pub fn generate_client_secret(&self) -> String {
generate_id_with_default_len(&format!("{}_secret", self.get_string_repr()))
}
/// Generate a key for pm_auth
pub fn get_pm_auth_key(&self) -> String {
format!("pm_auth_{}", self.get_string_repr())
}
/// Get external authentication request poll id
pub fn get_external_authentication_request_poll_id(&self) -> String {
format!("external_authentication_{}", self.get_string_repr())
}
/// Generate a test payment id with prefix test_
pub fn generate_test_payment_id_for_sample_data() -> Self {
let id = generate_id_with_default_len("test");
let alphanumeric_id = AlphaNumericId::new_unchecked(id);
let id = LengthId::new_unchecked(alphanumeric_id);
Self(id)
}
/// Wrap a string inside PaymentId
pub fn wrap(payment_id_string: String) -> CustomResult<Self, ValidationError> {
Self::try_from(Cow::from(payment_id_string))
}
}
#[derive(Debug, Clone, Serialize, Hash, Deserialize, PartialEq, Eq)]
pub(crate) struct LengthId<const MAX_LENGTH: u8, const MIN_LENGTH: u8>(pub AlphaNumericId);
impl<const MAX_LENGTH: u8, const MIN_LENGTH: u8> LengthId<MAX_LENGTH, MIN_LENGTH> {
/// Generates new [MerchantReferenceId] from the given input string
pub fn from(input_string: Cow<'static, str>) -> Result<Self, LengthIdError> {
let trimmed_input_string = input_string.trim().to_string();
let length_of_input_string = u8::try_from(trimmed_input_string.len())
.map_err(|_| LengthIdError::MaxLengthViolated(MAX_LENGTH))?;
when(length_of_input_string > MAX_LENGTH, || {
Err(LengthIdError::MaxLengthViolated(MAX_LENGTH))
})?;
when(length_of_input_string < MIN_LENGTH, || {
Err(LengthIdError::MinLengthViolated(MIN_LENGTH))
})?;
let alphanumeric_id = match AlphaNumericId::from(trimmed_input_string.into()) {
Ok(valid_alphanumeric_id) => valid_alphanumeric_id,
Err(error) => Err(LengthIdError::AlphanumericIdError(error))?,
};
Ok(Self(alphanumeric_id))
}
/// Generate a new MerchantRefId of default length with the given prefix
pub fn new(prefix: &str) -> Self {
Self(AlphaNumericId::new(prefix))
}
/// Use this function only if you are sure that the length is within the range
pub(crate) fn new_unchecked(alphanumeric_id: AlphaNumericId) -> Self {
Self(alphanumeric_id)
}
/// Create a new LengthId from aplhanumeric id
pub(crate) fn from_alphanumeric_id(
alphanumeric_id: AlphaNumericId,
) -> Result<Self, LengthIdError> {
let length_of_input_string = alphanumeric_id.0.len();
let length_of_input_string = u8::try_from(length_of_input_string)
.map_err(|_| LengthIdError::MaxLengthViolated(MAX_LENGTH))?;
when(length_of_input_string > MAX_LENGTH, || {
Err(LengthIdError::MaxLengthViolated(MAX_LENGTH))
})?;
when(length_of_input_string < MIN_LENGTH, || {
Err(LengthIdError::MinLengthViolated(MIN_LENGTH))
})?;
Ok(Self(alphanumeric_id))
}
}
#[derive(Debug, Error, PartialEq, Eq)]
pub enum LengthIdError {
#[error("the maximum allowed length for this field is {0}")]
/// Maximum length of string violated
MaxLengthViolated(u8),
#[error("the minimum required length for this field is {0}")]
/// Minimum length of string violated
MinLengthViolated(u8),
#[error("{0}")]
/// Input contains invalid characters
AlphanumericIdError(AlphaNumericIdError),
}
impl From<AlphaNumericIdError> for LengthIdError {
fn from(alphanumeric_id_error: AlphaNumericIdError) -> Self {
Self::AlphanumericIdError(alphanumeric_id_error)
}
}
use std::str::FromStr;
crate::id_type!(
ProfileId,
"A type for profile_id that can be used for business profile ids"
);
crate::impl_id_type_methods!(ProfileId, "profile_id");
// This is to display the `ProfileId` as ProfileId(abcd)
crate::impl_debug_id_type!(ProfileId);
crate::impl_try_from_cow_str_id_type!(ProfileId, "profile_id");
crate::impl_generate_id_id_type!(ProfileId, "pro");
| {
"chunk": 1,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_-841769499540836508_2 | clm | mini_chunk | // connector-service/backend/common_utils/src/id_type.rs
crate::impl_serializable_secret_id_type!(ProfileId);
impl crate::events::ApiEventMetric for ProfileId {
fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> {
Some(crate::events::ApiEventsType::BusinessProfile {
profile_id: self.clone(),
})
}
}
impl FromStr for ProfileId {
type Err = error_stack::Report<ValidationError>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let cow_string = Cow::Owned(s.to_string());
Self::try_from(cow_string)
}
}
/// An interface to generate object identifiers.
pub trait GenerateId {
/// Generates a random object identifier.
fn generate() -> Self;
}
crate::id_type!(
ClientSecretId,
"A type for key_id that can be used for Ephemeral key IDs"
);
crate::impl_id_type_methods!(ClientSecretId, "key_id");
// This is to display the `ClientSecretId` as ClientSecretId(abcd)
crate::impl_debug_id_type!(ClientSecretId);
crate::impl_try_from_cow_str_id_type!(ClientSecretId, "key_id");
crate::impl_generate_id_id_type!(ClientSecretId, "csi");
crate::impl_serializable_secret_id_type!(ClientSecretId);
impl crate::events::ApiEventMetric for ClientSecretId {
fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> {
Some(crate::events::ApiEventsType::ClientSecret {
key_id: self.clone(),
})
}
}
crate::impl_default_id_type!(ClientSecretId, "key");
impl ClientSecretId {
/// Generate a key for redis
pub fn generate_redis_key(&self) -> String {
format!("cs_{}", self.get_string_repr())
}
}
crate::id_type!(
ApiKeyId,
"A type for key_id that can be used for API key IDs"
);
crate::impl_id_type_methods!(ApiKeyId, "key_id");
// This is to display the `ApiKeyId` as ApiKeyId(abcd)
crate::impl_debug_id_type!(ApiKeyId);
crate::impl_try_from_cow_str_id_type!(ApiKeyId, "key_id");
crate::impl_serializable_secret_id_type!(ApiKeyId);
impl ApiKeyId {
/// Generate Api Key Id from prefix
pub fn generate_key_id(prefix: &'static str) -> Self {
Self(crate::generate_ref_id_with_default_length(prefix))
}
}
impl crate::events::ApiEventMetric for ApiKeyId {
fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> {
Some(crate::events::ApiEventsType::ApiKey {
key_id: self.clone(),
})
}
}
impl crate::events::ApiEventMetric for (MerchantId, ApiKeyId) {
fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> {
Some(crate::events::ApiEventsType::ApiKey {
key_id: self.1.clone(),
})
}
}
impl crate::events::ApiEventMetric for (&MerchantId, &ApiKeyId) {
fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> {
Some(crate::events::ApiEventsType::ApiKey {
key_id: self.1.clone(),
})
}
}
crate::impl_default_id_type!(ApiKeyId, "key");
crate::id_type!(
MerchantConnectorAccountId,
"A type for merchant_connector_id that can be used for merchant_connector_account ids"
);
crate::impl_id_type_methods!(MerchantConnectorAccountId, "merchant_connector_id");
// This is to display the `MerchantConnectorAccountId` as MerchantConnectorAccountId(abcd)
crate::impl_debug_id_type!(MerchantConnectorAccountId);
crate::impl_generate_id_id_type!(MerchantConnectorAccountId, "mca");
crate::impl_try_from_cow_str_id_type!(MerchantConnectorAccountId, "merchant_connector_id");
crate::impl_serializable_secret_id_type!(MerchantConnectorAccountId);
impl MerchantConnectorAccountId {
/// Get a merchant connector account id from String
pub fn wrap(merchant_connector_account_id: String) -> CustomResult<Self, ValidationError> {
Self::try_from(Cow::from(merchant_connector_account_id))
}
}
crate::id_type!(
ProfileAcquirerId,
"A type for profile_acquirer_id that can be used for profile acquirer ids"
);
crate::impl_id_type_methods!(ProfileAcquirerId, "profile_acquirer_id");
// This is to display the `ProfileAcquirerId` as ProfileAcquirerId(abcd)
crate::impl_debug_id_type!(ProfileAcquirerId);
crate::impl_try_from_cow_str_id_type!(ProfileAcquirerId, "profile_acquirer_id");
crate::impl_generate_id_id_type!(ProfileAcquirerId, "pro_acq");
crate::impl_serializable_secret_id_type!(ProfileAcquirerId);
impl Ord for ProfileAcquirerId {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
| {
"chunk": 2,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_-841769499540836508_3 | clm | mini_chunk | // connector-service/backend/common_utils/src/id_type.rs
self.0 .0 .0.cmp(&other.0 .0 .0)
}
}
impl PartialOrd for ProfileAcquirerId {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl crate::events::ApiEventMetric for ProfileAcquirerId {
fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> {
Some(crate::events::ApiEventsType::ProfileAcquirer {
profile_acquirer_id: self.clone(),
})
}
}
impl FromStr for ProfileAcquirerId {
type Err = error_stack::Report<ValidationError>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let cow_string = Cow::Owned(s.to_string());
Self::try_from(cow_string)
}
}
| {
"chunk": 3,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_5683649008329316125_0 | clm | mini_chunk | // connector-service/backend/common_utils/src/macros.rs
mod id_type {
/// Defines an ID type.
#[macro_export]
macro_rules! id_type {
($type:ident, $doc:literal, $max_length:expr, $min_length:expr) => {
#[doc = $doc]
#[derive(
Clone, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize, utoipa::ToSchema,
)]
#[schema(value_type = String)]
pub struct $type($crate::id_type::LengthId<$max_length, $min_length>);
};
($type:ident, $doc:literal) => {
$crate::id_type!(
$type,
$doc,
{ $crate::consts::MAX_ALLOWED_MERCHANT_REFERENCE_ID_LENGTH },
{ $crate::consts::MIN_REQUIRED_MERCHANT_REFERENCE_ID_LENGTH }
);
};
}
/// Defines a Global Id type
#[macro_export]
macro_rules! global_id_type {
($type:ident, $doc:literal) => {
#[doc = $doc]
#[derive(Debug, Clone, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct $type($crate::global_id::GlobalId);
};
}
/// Implements common methods on the specified ID type.
#[macro_export]
macro_rules! impl_id_type_methods {
($type:ty, $field_name:literal) => {
impl $type {
/// Get the string representation of the ID type.
pub fn get_string_repr(&self) -> &str {
&self.0 .0 .0
}
}
};
}
/// Implements the `Debug` trait on the specified ID type.
#[macro_export]
macro_rules! impl_debug_id_type {
($type:ty) => {
impl core::fmt::Debug for $type {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_tuple(stringify!($type))
.field(&self.0 .0 .0)
.finish()
}
}
};
}
/// Implements the `TryFrom<Cow<'static, str>>` trait on the specified ID type.
#[macro_export]
macro_rules! impl_try_from_cow_str_id_type {
($type:ty, $field_name:literal) => {
impl TryFrom<std::borrow::Cow<'static, str>> for $type {
type Error = error_stack::Report<$crate::errors::ValidationError>;
fn try_from(value: std::borrow::Cow<'static, str>) -> Result<Self, Self::Error> {
use error_stack::ResultExt;
let merchant_ref_id = $crate::id_type::LengthId::from(value).change_context(
$crate::errors::ValidationError::IncorrectValueProvided {
field_name: $field_name,
},
)?;
Ok(Self(merchant_ref_id))
}
}
};
}
/// Implements the `Default` trait on the specified ID type.
#[macro_export]
macro_rules! impl_default_id_type {
($type:ty, $prefix:literal) => {
impl Default for $type {
fn default() -> Self {
Self($crate::generate_ref_id_with_default_length($prefix))
}
}
};
}
/// Implements the `GenerateId` trait on the specified ID type.
#[macro_export]
macro_rules! impl_generate_id_id_type {
($type:ty, $prefix:literal) => {
impl $crate::id_type::GenerateId for $type {
fn generate() -> Self {
Self($crate::generate_ref_id_with_default_length($prefix))
}
}
};
}
/// Implements the `SerializableSecret` trait on the specified ID type.
#[macro_export]
macro_rules! impl_serializable_secret_id_type {
($type:ty) => {
impl hyperswitch_masking::SerializableSecret for $type {}
};
}
}
/// Collects names of all optional fields that are `None`.
/// This is typically useful for constructing error messages including a list of all missing fields.
#[macro_export]
macro_rules! collect_missing_value_keys {
[$(($key:literal, $option:expr)),+] => {
{
let mut keys: Vec<&'static str> = Vec::new();
$(
if $option.is_none() {
keys.push($key);
}
)*
keys
}
};
}
| {
"chunk": 0,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_8833799470967369792_0 | clm | mini_chunk | // connector-service/backend/common_utils/src/crypto.rs
//! Utilities for cryptographic algorithms
use std::ops::Deref;
use error_stack::ResultExt;
use hyperswitch_masking::{ExposeInterface, Secret};
use md5;
use ring::{
aead::{self, BoundKey, OpeningKey, SealingKey, UnboundKey},
hmac,
};
use crate::{
errors::{self, CustomResult},
pii::{self, EncryptionStrategy},
};
#[derive(Clone, Debug)]
struct NonceSequence(u128);
impl NonceSequence {
/// Byte index at which sequence number starts in a 16-byte (128-bit) sequence.
/// This byte index considers the big endian order used while encoding and decoding the nonce
/// to/from a 128-bit unsigned integer.
const SEQUENCE_NUMBER_START_INDEX: usize = 4;
/// Generate a random nonce sequence.
fn new() -> Result<Self, ring::error::Unspecified> {
use ring::rand::{SecureRandom, SystemRandom};
let rng = SystemRandom::new();
// 96-bit sequence number, stored in a 128-bit unsigned integer in big-endian order
let mut sequence_number = [0_u8; 128 / 8];
rng.fill(&mut sequence_number[Self::SEQUENCE_NUMBER_START_INDEX..])?;
let sequence_number = u128::from_be_bytes(sequence_number);
Ok(Self(sequence_number))
}
/// Returns the current nonce value as bytes.
fn current(&self) -> [u8; aead::NONCE_LEN] {
let mut nonce = [0_u8; aead::NONCE_LEN];
nonce.copy_from_slice(&self.0.to_be_bytes()[Self::SEQUENCE_NUMBER_START_INDEX..]);
nonce
}
/// Constructs a nonce sequence from bytes
fn from_bytes(bytes: [u8; aead::NONCE_LEN]) -> Self {
let mut sequence_number = [0_u8; 128 / 8];
sequence_number[Self::SEQUENCE_NUMBER_START_INDEX..].copy_from_slice(&bytes);
let sequence_number = u128::from_be_bytes(sequence_number);
Self(sequence_number)
}
}
impl aead::NonceSequence for NonceSequence {
fn advance(&mut self) -> Result<aead::Nonce, ring::error::Unspecified> {
let mut nonce = [0_u8; aead::NONCE_LEN];
nonce.copy_from_slice(&self.0.to_be_bytes()[Self::SEQUENCE_NUMBER_START_INDEX..]);
// Increment sequence number
self.0 = self.0.wrapping_add(1);
// Return previous sequence number as bytes
Ok(aead::Nonce::assume_unique_for_key(nonce))
}
}
/// Trait for cryptographically signing messages
pub trait SignMessage {
/// Takes in a secret and a message and returns the calculated signature as bytes
fn sign_message(
&self,
_secret: &[u8],
_msg: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError>;
}
/// Trait for cryptographically verifying a message against a signature
pub trait VerifySignature {
/// Takes in a secret, the signature and the message and verifies the message
/// against the signature
fn verify_signature(
&self,
_secret: &[u8],
_signature: &[u8],
_msg: &[u8],
) -> CustomResult<bool, errors::CryptoError>;
}
/// Trait for cryptographically encoding a message
pub trait EncodeMessage {
/// Takes in a secret and the message and encodes it, returning bytes
fn encode_message(
&self,
_secret: &[u8],
_msg: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError>;
}
/// Trait for cryptographically decoding a message
pub trait DecodeMessage {
/// Takes in a secret, an encoded messages and attempts to decode it, returning bytes
fn decode_message(
&self,
_secret: &[u8],
_msg: Secret<Vec<u8>, EncryptionStrategy>,
) -> CustomResult<Vec<u8>, errors::CryptoError>;
}
/// Represents no cryptographic algorithm.
/// Implements all crypto traits and acts like a Nop
#[derive(Debug)]
pub struct NoAlgorithm;
impl SignMessage for NoAlgorithm {
fn sign_message(
&self,
_secret: &[u8],
_msg: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError> {
Ok(Vec::new())
}
}
impl VerifySignature for NoAlgorithm {
fn verify_signature(
&self,
_secret: &[u8],
_signature: &[u8],
_msg: &[u8],
) -> CustomResult<bool, errors::CryptoError> {
Ok(true)
}
}
impl EncodeMessage for NoAlgorithm {
fn encode_message(
&self,
_secret: &[u8],
msg: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError> {
Ok(msg.to_vec())
}
}
impl DecodeMessage for NoAlgorithm {
fn decode_message(
| {
"chunk": 0,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_8833799470967369792_1 | clm | mini_chunk | // connector-service/backend/common_utils/src/crypto.rs
&self,
_secret: &[u8],
msg: Secret<Vec<u8>, EncryptionStrategy>,
) -> CustomResult<Vec<u8>, errors::CryptoError> {
Ok(msg.expose())
}
}
/// Represents the HMAC-SHA-1 algorithm
#[derive(Debug)]
pub struct HmacSha1;
impl SignMessage for HmacSha1 {
fn sign_message(
&self,
secret: &[u8],
msg: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError> {
let key = hmac::Key::new(hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY, secret);
Ok(hmac::sign(&key, msg).as_ref().to_vec())
}
}
impl VerifySignature for HmacSha1 {
fn verify_signature(
&self,
secret: &[u8],
signature: &[u8],
msg: &[u8],
) -> CustomResult<bool, errors::CryptoError> {
let key = hmac::Key::new(hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY, secret);
Ok(hmac::verify(&key, msg, signature).is_ok())
}
}
/// Represents the HMAC-SHA-256 algorithm
#[derive(Debug)]
pub struct HmacSha256;
impl SignMessage for HmacSha256 {
fn sign_message(
&self,
secret: &[u8],
msg: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError> {
let key = hmac::Key::new(hmac::HMAC_SHA256, secret);
Ok(hmac::sign(&key, msg).as_ref().to_vec())
}
}
impl VerifySignature for HmacSha256 {
fn verify_signature(
&self,
secret: &[u8],
signature: &[u8],
msg: &[u8],
) -> CustomResult<bool, errors::CryptoError> {
let key = hmac::Key::new(hmac::HMAC_SHA256, secret);
Ok(hmac::verify(&key, msg, signature).is_ok())
}
}
/// Represents the HMAC-SHA-512 algorithm
#[derive(Debug)]
pub struct HmacSha512;
impl SignMessage for HmacSha512 {
fn sign_message(
&self,
secret: &[u8],
msg: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError> {
let key = hmac::Key::new(hmac::HMAC_SHA512, secret);
Ok(hmac::sign(&key, msg).as_ref().to_vec())
}
}
impl VerifySignature for HmacSha512 {
fn verify_signature(
&self,
secret: &[u8],
signature: &[u8],
msg: &[u8],
) -> CustomResult<bool, errors::CryptoError> {
let key = hmac::Key::new(hmac::HMAC_SHA512, secret);
Ok(hmac::verify(&key, msg, signature).is_ok())
}
}
/// Blake3
#[derive(Debug)]
pub struct Blake3(String);
impl Blake3 {
/// Create a new instance of Blake3 with a key
pub fn new(key: impl Into<String>) -> Self {
Self(key.into())
}
}
impl SignMessage for Blake3 {
fn sign_message(
&self,
secret: &[u8],
msg: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError> {
let key = blake3::derive_key(&self.0, secret);
let output = blake3::keyed_hash(&key, msg).as_bytes().to_vec();
Ok(output)
}
}
impl VerifySignature for Blake3 {
fn verify_signature(
&self,
secret: &[u8],
signature: &[u8],
msg: &[u8],
) -> CustomResult<bool, errors::CryptoError> {
let key = blake3::derive_key(&self.0, secret);
let output = blake3::keyed_hash(&key, msg);
Ok(output.as_bytes() == signature)
}
}
/// Represents the GCM-AES-256 algorithm
#[derive(Debug)]
pub struct GcmAes256;
impl EncodeMessage for GcmAes256 {
fn encode_message(
&self,
secret: &[u8],
msg: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError> {
let nonce_sequence =
NonceSequence::new().change_context(errors::CryptoError::EncodingFailed)?;
let current_nonce = nonce_sequence.current();
let key = UnboundKey::new(&aead::AES_256_GCM, secret)
.change_context(errors::CryptoError::EncodingFailed)?;
let mut key = SealingKey::new(key, nonce_sequence);
let mut in_out = msg.to_vec();
key.seal_in_place_append_tag(aead::Aad::empty(), &mut in_out)
.change_context(errors::CryptoError::EncodingFailed)?;
in_out.splice(0..0, current_nonce);
Ok(in_out)
}
}
impl DecodeMessage for GcmAes256 {
fn decode_message(
&self,
secret: &[u8],
msg: Secret<Vec<u8>, EncryptionStrategy>,
) -> CustomResult<Vec<u8>, errors::CryptoError> {
let msg = msg.expose();
let key = UnboundKey::new(&aead::AES_256_GCM, secret)
.change_context(errors::CryptoError::DecodingFailed)?;
let nonce_sequence = NonceSequence::from_bytes(
| {
"chunk": 1,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_8833799470967369792_2 | clm | mini_chunk | // connector-service/backend/common_utils/src/crypto.rs
<[u8; aead::NONCE_LEN]>::try_from(
msg.get(..aead::NONCE_LEN)
.ok_or(errors::CryptoError::DecodingFailed)
.attach_printable("Failed to read the nonce form the encrypted ciphertext")?,
)
.change_context(errors::CryptoError::DecodingFailed)?,
);
let mut key = OpeningKey::new(key, nonce_sequence);
let mut binding = msg;
let output = binding.as_mut_slice();
let result = key
.open_within(aead::Aad::empty(), output, aead::NONCE_LEN..)
.change_context(errors::CryptoError::DecodingFailed)?;
Ok(result.to_vec())
}
}
/// Represents the ED25519 signature verification algorithm
#[derive(Debug)]
pub struct Ed25519;
impl Ed25519 {
/// ED25519 algorithm constants
const ED25519_PUBLIC_KEY_LEN: usize = 32;
const ED25519_SIGNATURE_LEN: usize = 64;
/// Validates ED25519 inputs (public key and signature lengths)
fn validate_inputs(
public_key: &[u8],
signature: &[u8],
) -> CustomResult<(), errors::CryptoError> {
// Validate public key length
if public_key.len() != Self::ED25519_PUBLIC_KEY_LEN {
return Err(errors::CryptoError::InvalidKeyLength).attach_printable(format!(
"Invalid ED25519 public key length: expected {} bytes, got {}",
Self::ED25519_PUBLIC_KEY_LEN,
public_key.len()
));
}
// Validate signature length
if signature.len() != Self::ED25519_SIGNATURE_LEN {
return Err(errors::CryptoError::InvalidKeyLength).attach_printable(format!(
"Invalid ED25519 signature length: expected {} bytes, got {}",
Self::ED25519_SIGNATURE_LEN,
signature.len()
));
}
Ok(())
}
}
impl VerifySignature for Ed25519 {
fn verify_signature(
&self,
public_key: &[u8],
signature: &[u8], // ED25519 signature bytes (must be 64 bytes)
msg: &[u8], // Message that was signed
) -> CustomResult<bool, errors::CryptoError> {
// Validate inputs first
Self::validate_inputs(public_key, signature)?;
// Create unparsed public key
let ring_public_key =
ring::signature::UnparsedPublicKey::new(&ring::signature::ED25519, public_key);
// Perform verification
match ring_public_key.verify(msg, signature) {
Ok(()) => Ok(true),
Err(_err) => Err(errors::CryptoError::SignatureVerificationFailed)
.attach_printable("ED25519 signature verification failed"),
}
}
}
impl SignMessage for Ed25519 {
fn sign_message(
&self,
secret: &[u8],
msg: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError> {
if secret.len() != 32 {
return Err(errors::CryptoError::InvalidKeyLength).attach_printable(format!(
"Invalid ED25519 private key length: expected 32 bytes, got {}",
secret.len()
));
}
let key_pair = ring::signature::Ed25519KeyPair::from_seed_unchecked(secret)
.change_context(errors::CryptoError::MessageSigningFailed)
.attach_printable("Failed to create ED25519 key pair from seed")?;
let signature = key_pair.sign(msg);
Ok(signature.as_ref().to_vec())
}
}
/// Secure Hash Algorithm 512
#[derive(Debug)]
pub struct Sha512;
/// Secure Hash Algorithm 256
#[derive(Debug)]
pub struct Sha256;
/// Trait for generating a digest for SHA
pub trait GenerateDigest {
/// takes a message and creates a digest for it
fn generate_digest(&self, message: &[u8]) -> CustomResult<Vec<u8>, errors::CryptoError>;
}
impl GenerateDigest for Sha512 {
fn generate_digest(&self, message: &[u8]) -> CustomResult<Vec<u8>, errors::CryptoError> {
let digest = ring::digest::digest(&ring::digest::SHA512, message);
Ok(digest.as_ref().to_vec())
}
}
impl VerifySignature for Sha512 {
fn verify_signature(
&self,
_secret: &[u8],
signature: &[u8],
msg: &[u8],
) -> CustomResult<bool, errors::CryptoError> {
let msg_str = std::str::from_utf8(msg)
.change_context(errors::CryptoError::EncodingFailed)?
.to_owned();
| {
"chunk": 2,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_8833799470967369792_3 | clm | mini_chunk | // connector-service/backend/common_utils/src/crypto.rs
let hashed_digest = hex::encode(
Self.generate_digest(msg_str.as_bytes())
.change_context(errors::CryptoError::SignatureVerificationFailed)?,
);
let hashed_digest_into_bytes = hashed_digest.into_bytes();
Ok(hashed_digest_into_bytes == signature)
}
}
/// MD5 hash function
#[derive(Debug)]
pub struct Md5;
impl GenerateDigest for Md5 {
fn generate_digest(&self, message: &[u8]) -> CustomResult<Vec<u8>, errors::CryptoError> {
let digest = md5::compute(message);
Ok(digest.as_ref().to_vec())
}
}
impl VerifySignature for Md5 {
fn verify_signature(
&self,
_secret: &[u8],
signature: &[u8],
msg: &[u8],
) -> CustomResult<bool, errors::CryptoError> {
let hashed_digest = Self
.generate_digest(msg)
.change_context(errors::CryptoError::SignatureVerificationFailed)?;
Ok(hashed_digest == signature)
}
}
impl GenerateDigest for Sha256 {
fn generate_digest(&self, message: &[u8]) -> CustomResult<Vec<u8>, errors::CryptoError> {
let digest = ring::digest::digest(&ring::digest::SHA256, message);
Ok(digest.as_ref().to_vec())
}
}
impl VerifySignature for Sha256 {
fn verify_signature(
&self,
_secret: &[u8],
signature: &[u8],
msg: &[u8],
) -> CustomResult<bool, errors::CryptoError> {
let hashed_digest = Self
.generate_digest(msg)
.change_context(errors::CryptoError::SignatureVerificationFailed)?;
let hashed_digest_into_bytes = hashed_digest.as_slice();
Ok(hashed_digest_into_bytes == signature)
}
}
/// Generate a random string using a cryptographically secure pseudo-random number generator
/// (CSPRNG). Typically used for generating (readable) keys and passwords.
#[inline]
pub fn generate_cryptographically_secure_random_string(length: usize) -> String {
use rand::distributions::DistString;
rand::distributions::Alphanumeric.sample_string(&mut rand::rngs::OsRng, length)
}
/// Generate an array of random bytes using a cryptographically secure pseudo-random number
/// generator (CSPRNG). Typically used for generating keys.
#[inline]
pub fn generate_cryptographically_secure_random_bytes<const N: usize>() -> [u8; N] {
use rand::RngCore;
let mut bytes = [0; N];
rand::rngs::OsRng.fill_bytes(&mut bytes);
bytes
}
/// A wrapper type to store the encrypted data for sensitive pii domain data types
#[derive(Debug, Clone)]
pub struct Encryptable<T: Clone> {
inner: T,
encrypted: Secret<Vec<u8>, EncryptionStrategy>,
}
impl<T: Clone, S: hyperswitch_masking::Strategy<T>> Encryptable<Secret<T, S>> {
/// constructor function to be used by the encryptor and decryptor to generate the data type
pub fn new(
masked_data: Secret<T, S>,
encrypted_data: Secret<Vec<u8>, EncryptionStrategy>,
) -> Self {
Self {
inner: masked_data,
encrypted: encrypted_data,
}
}
}
impl<T: Clone> Encryptable<T> {
/// Get the inner data while consuming self
#[inline]
pub fn into_inner(self) -> T {
self.inner
}
/// Get the reference to inner value
#[inline]
pub fn get_inner(&self) -> &T {
&self.inner
}
/// Get the inner encrypted data while consuming self
#[inline]
pub fn into_encrypted(self) -> Secret<Vec<u8>, EncryptionStrategy> {
self.encrypted
}
/// Deserialize inner value and return new Encryptable object
pub fn deserialize_inner_value<U, F>(
self,
f: F,
) -> CustomResult<Encryptable<U>, errors::ParsingError>
where
F: FnOnce(T) -> CustomResult<U, errors::ParsingError>,
U: Clone,
{
let inner = self.inner;
let encrypted = self.encrypted;
let inner = f(inner)?;
Ok(Encryptable { inner, encrypted })
}
/// consume self and modify the inner value
pub fn map<U: Clone>(self, f: impl FnOnce(T) -> U) -> Encryptable<U> {
let encrypted_data = self.encrypted;
let masked_data = f(self.inner);
Encryptable {
inner: masked_data,
encrypted: encrypted_data,
}
}
}
impl<T: Clone> Deref for Encryptable<Secret<T>> {
type Target = Secret<T>;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
| {
"chunk": 3,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_8833799470967369792_4 | clm | mini_chunk | // connector-service/backend/common_utils/src/crypto.rs
impl<T: Clone> hyperswitch_masking::Serialize for Encryptable<T>
where
T: hyperswitch_masking::Serialize,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.inner.serialize(serializer)
}
}
impl<T: Clone> PartialEq for Encryptable<T>
where
T: PartialEq,
{
fn eq(&self, other: &Self) -> bool {
self.inner.eq(&other.inner)
}
}
/// Type alias for `Option<Encryptable<Secret<String>>>`
pub type OptionalEncryptableSecretString = Option<Encryptable<Secret<String>>>;
/// Type alias for `Option<Encryptable<Secret<String>>>` used for `name` field
pub type OptionalEncryptableName = Option<Encryptable<Secret<String>>>;
/// Type alias for `Option<Encryptable<Secret<String>>>` used for `email` field
pub type OptionalEncryptableEmail = Option<Encryptable<Secret<String, pii::EmailStrategy>>>;
/// Type alias for `Option<Encryptable<Secret<String>>>` used for `phone` field
pub type OptionalEncryptablePhone = Option<Encryptable<Secret<String>>>;
/// Type alias for `Option<Encryptable<Secret<serde_json::Value>>>`
pub type OptionalEncryptableValue = Option<Encryptable<Secret<serde_json::Value>>>;
/// Type alias for `Option<Secret<serde_json::Value>>`
pub type OptionalSecretValue = Option<Secret<serde_json::Value>>;
/// Type alias for `Encryptable<Secret<String>>` used for `name` field
pub type EncryptableName = Encryptable<Secret<String>>;
/// Type alias for `Encryptable<Secret<String>>` used for `email` field
pub type EncryptableEmail = Encryptable<Secret<String, pii::EmailStrategy>>;
#[cfg(test)]
mod crypto_tests {
#![allow(clippy::expect_used)]
use super::{DecodeMessage, EncodeMessage, SignMessage, VerifySignature};
use crate::crypto::GenerateDigest;
#[test]
fn test_hmac_sha256_sign_message() {
let message = r#"{"type":"payment_intent"}"#.as_bytes();
let secret = "hmac_secret_1234".as_bytes();
let right_signature =
hex::decode("d5550730377011948f12cc28889bee590d2a5434d6f54b87562f2dbc2657823e")
.expect("Right signature decoding");
let signature = super::HmacSha256
.sign_message(secret, message)
.expect("Signature");
assert_eq!(signature, right_signature);
}
#[test]
fn test_hmac_sha256_verify_signature() {
let right_signature =
hex::decode("d5550730377011948f12cc28889bee590d2a5434d6f54b87562f2dbc2657823e")
.expect("Right signature decoding");
let wrong_signature =
hex::decode("d5550730377011948f12cc28889bee590d2a5434d6f54b87562f2dbc2657823f")
.expect("Wrong signature decoding");
let secret = "hmac_secret_1234".as_bytes();
let data = r#"{"type":"payment_intent"}"#.as_bytes();
let right_verified = super::HmacSha256
.verify_signature(secret, &right_signature, data)
.expect("Right signature verification result");
assert!(right_verified);
let wrong_verified = super::HmacSha256
.verify_signature(secret, &wrong_signature, data)
.expect("Wrong signature verification result");
assert!(!wrong_verified);
}
#[test]
fn test_sha256_verify_signature() {
let right_signature =
hex::decode("123250a72f4e961f31661dbcee0fec0f4714715dc5ae1b573f908a0a5381ddba")
.expect("Right signature decoding");
let wrong_signature =
hex::decode("123250a72f4e961f31661dbcee0fec0f4714715dc5ae1b573f908a0a5381ddbb")
.expect("Wrong signature decoding");
let secret = "".as_bytes();
let data = r#"AJHFH9349JASFJHADJ9834115USD2020-11-13.13:22:34711000000021406655APPROVED12345product_id"#.as_bytes();
let right_verified = super::Sha256
.verify_signature(secret, &right_signature, data)
.expect("Right signature verification result");
assert!(right_verified);
let wrong_verified = super::Sha256
.verify_signature(secret, &wrong_signature, data)
.expect("Wrong signature verification result");
assert!(!wrong_verified);
}
#[test]
fn test_hmac_sha512_sign_message() {
let message = r#"{"type":"payment_intent"}"#.as_bytes();
| {
"chunk": 4,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_8833799470967369792_5 | clm | mini_chunk | // connector-service/backend/common_utils/src/crypto.rs
let secret = "hmac_secret_1234".as_bytes();
let right_signature = hex::decode("38b0bc1ea66b14793e39cd58e93d37b799a507442d0dd8d37443fa95dec58e57da6db4742636fea31201c48e57a66e73a308a2e5a5c6bb831e4e39fe2227c00f")
.expect("signature decoding");
let signature = super::HmacSha512
.sign_message(secret, message)
.expect("Signature");
assert_eq!(signature, right_signature);
}
#[test]
fn test_hmac_sha512_verify_signature() {
let right_signature = hex::decode("38b0bc1ea66b14793e39cd58e93d37b799a507442d0dd8d37443fa95dec58e57da6db4742636fea31201c48e57a66e73a308a2e5a5c6bb831e4e39fe2227c00f")
.expect("signature decoding");
let wrong_signature =
hex::decode("d5550730377011948f12cc28889bee590d2a5434d6f54b87562f2dbc2657823f")
.expect("Wrong signature decoding");
let secret = "hmac_secret_1234".as_bytes();
let data = r#"{"type":"payment_intent"}"#.as_bytes();
let right_verified = super::HmacSha512
.verify_signature(secret, &right_signature, data)
.expect("Right signature verification result");
assert!(right_verified);
let wrong_verified = super::HmacSha256
.verify_signature(secret, &wrong_signature, data)
.expect("Wrong signature verification result");
assert!(!wrong_verified);
}
#[test]
fn test_gcm_aes_256_encode_message() {
let message = r#"{"type":"PAYMENT"}"#.as_bytes();
let secret =
hex::decode("000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f")
.expect("Secret decoding");
let algorithm = super::GcmAes256;
let encoded_message = algorithm
.encode_message(&secret, message)
.expect("Encoded message and tag");
assert_eq!(
algorithm
.decode_message(&secret, encoded_message.into())
.expect("Decode Failed"),
message
);
}
#[test]
fn test_gcm_aes_256_decode_message() {
// Inputs taken from AES GCM test vectors provided by NIST
// https://github.com/briansmith/ring/blob/95948b3977013aed16db92ae32e6b8384496a740/tests/aead_aes_256_gcm_tests.txt#L447-L452
let right_secret =
hex::decode("feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308308")
.expect("Secret decoding");
let wrong_secret =
hex::decode("feffe9928665731c6d6a8f9467308308feffe9928665731c6d6a8f9467308309")
.expect("Secret decoding");
let message =
// The three parts of the message are the nonce, ciphertext and tag from the test vector
hex::decode(
"cafebabefacedbaddecaf888\
522dc1f099567d07f47f37a32a84427d643a8cdcbfe5c0c97598a2bd2555d1aa8cb08e48590dbb3da7b08b1056828838c5f61e6393ba7a0abcc9f662898015ad\
b094dac5d93471bdec1a502270e3cc6c"
).expect("Message decoding");
let algorithm = super::GcmAes256;
let decoded = algorithm
.decode_message(&right_secret, message.clone().into())
.expect("Decoded message");
assert_eq!(
decoded,
hex::decode("d9313225f88406e5a55909c5aff5269a86a7a9531534f7da2e4c303d8a318a721c3c0c95956809532fcf0e2449a6b525b16aedf5aa0de657ba637b391aafd255")
.expect("Decoded plaintext message")
);
let err_decoded = algorithm.decode_message(&wrong_secret, message.into());
assert!(err_decoded.is_err());
}
#[test]
fn test_md5_digest() {
let message = "abcdefghijklmnopqrstuvwxyz".as_bytes();
assert_eq!(
format!(
"{}",
hex::encode(super::Md5.generate_digest(message).expect("Digest"))
),
"c3fcd3d76192e4007dfb496cca67e13b"
);
}
#[test]
fn test_md5_verify_signature() {
let right_signature =
hex::decode("c3fcd3d76192e4007dfb496cca67e13b").expect("signature decoding");
let wrong_signature =
hex::decode("d5550730377011948f12cc28889bee590d2a5434d6f54b87562f2dbc2657823f")
.expect("Wrong signature decoding");
let secret = "".as_bytes();
| {
"chunk": 5,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_8833799470967369792_6 | clm | mini_chunk | // connector-service/backend/common_utils/src/crypto.rs
let data = "abcdefghijklmnopqrstuvwxyz".as_bytes();
let right_verified = super::Md5
.verify_signature(secret, &right_signature, data)
.expect("Right signature verification result");
assert!(right_verified);
let wrong_verified = super::Md5
.verify_signature(secret, &wrong_signature, data)
.expect("Wrong signature verification result");
assert!(!wrong_verified);
}
}
| {
"chunk": 6,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_2048526090272796786_0 | clm | mini_chunk | // connector-service/backend/common_utils/src/event_publisher.rs
use std::sync::Arc;
use hyperswitch_masking::ErasedMaskSerialize;
use once_cell::sync::OnceCell;
use rdkafka::message::{Header, OwnedHeaders};
use serde_json;
use tracing_kafka::{builder::KafkaWriterBuilder, KafkaWriter};
use crate::{
events::{Event, EventConfig},
CustomResult, EventPublisherError,
};
const PARTITION_KEY_METADATA: &str = "partitionKey";
/// Global static EventPublisher instance
static EVENT_PUBLISHER: OnceCell<EventPublisher> = OnceCell::new();
/// An event publisher that sends events directly to Kafka.
#[derive(Clone)]
pub struct EventPublisher {
writer: Arc<KafkaWriter>,
config: EventConfig,
}
impl EventPublisher {
/// Creates a new EventPublisher, initializing the KafkaWriter.
pub fn new(config: &EventConfig) -> CustomResult<Self, EventPublisherError> {
// Validate configuration before attempting to create writer
if config.brokers.is_empty() {
return Err(error_stack::Report::new(
EventPublisherError::InvalidConfiguration {
message: "brokers list cannot be empty".to_string(),
},
));
}
if config.topic.is_empty() {
return Err(error_stack::Report::new(
EventPublisherError::InvalidConfiguration {
message: "topic cannot be empty".to_string(),
},
));
}
tracing::debug!(
brokers = ?config.brokers,
topic = %config.topic,
"Creating EventPublisher with configuration"
);
let writer = KafkaWriterBuilder::new()
.brokers(config.brokers.clone())
.topic(config.topic.clone())
.build()
.map_err(|e| {
error_stack::Report::new(EventPublisherError::KafkaWriterInitializationFailed)
.attach_printable(format!("KafkaWriter build failed: {e}"))
.attach_printable(format!(
"Brokers: {:?}, Topic: {}",
config.brokers, config.topic
))
})?;
tracing::info!("EventPublisher created successfully");
Ok(Self {
writer: Arc::new(writer),
config: config.clone(),
})
}
/// Publishes a single event to Kafka with metadata as headers.
pub fn publish_event(
&self,
event: serde_json::Value,
topic: &str,
partition_key_field: &str,
) -> CustomResult<(), EventPublisherError> {
let metadata = OwnedHeaders::new();
self.publish_event_with_metadata(event, topic, partition_key_field, metadata)
}
/// Publishes a single event to Kafka with custom metadata.
pub fn publish_event_with_metadata(
&self,
event: serde_json::Value,
topic: &str,
partition_key_field: &str,
metadata: OwnedHeaders,
) -> CustomResult<(), EventPublisherError> {
tracing::debug!(
topic = %topic,
partition_key_field = %partition_key_field,
"Starting event publication to Kafka"
);
let mut headers = metadata;
let key = if let Some(partition_key_value) =
event.get(partition_key_field).and_then(|v| v.as_str())
{
headers = headers.insert(Header {
key: PARTITION_KEY_METADATA,
value: Some(partition_key_value.as_bytes()),
});
Some(partition_key_value)
} else {
tracing::warn!(
partition_key_field = %partition_key_field,
"Partition key field not found in event, message will be published without key"
);
None
};
let event_bytes = serde_json::to_vec(&event).map_err(|e| {
error_stack::Report::new(EventPublisherError::EventSerializationFailed)
.attach_printable(format!("Failed to serialize Event to JSON bytes: {e}"))
})?;
self.writer
.publish_event(&self.config.topic, key, &event_bytes, Some(headers))
.map_err(|e| {
let event_json = serde_json::to_string(&event).unwrap_or_default();
error_stack::Report::new(EventPublisherError::EventPublishFailed)
.attach_printable(format!("Kafka publish failed: {e}"))
| {
"chunk": 0,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_2048526090272796786_1 | clm | mini_chunk | // connector-service/backend/common_utils/src/event_publisher.rs
.attach_printable(format!(
"Topic: {}, Event size: {} bytes",
self.config.topic,
event_bytes.len()
))
.attach_printable(format!("Failed event: {event_json}"))
})?;
let event_json = serde_json::to_string(&event).unwrap_or_default();
tracing::info!(
full_event = %event_json,
"Event successfully published to Kafka"
);
Ok(())
}
pub fn emit_event_with_config(
&self,
base_event: Event,
config: &EventConfig,
) -> CustomResult<(), EventPublisherError> {
let metadata = self.build_kafka_metadata(&base_event);
let processed_event = self.process_event(&base_event)?;
self.publish_event_with_metadata(
processed_event,
&config.topic,
&config.partition_key_field,
metadata,
)
}
fn build_kafka_metadata(&self, event: &Event) -> OwnedHeaders {
let mut headers = OwnedHeaders::new();
// Add lineage headers from Event.lineage_ids
for (key, value) in event.lineage_ids.inner() {
headers = headers.insert(Header {
key: &key,
value: Some(value.as_bytes()),
});
}
let ref_id_option = event
.additional_fields
.get("reference_id")
.and_then(|ref_id_value| ref_id_value.inner().as_str());
// Add reference_id from Event.additional_fields
if let Some(ref_id_str) = ref_id_option {
headers = headers.insert(Header {
key: "reference_id",
value: Some(ref_id_str.as_bytes()),
});
}
headers
}
fn process_event(&self, event: &Event) -> CustomResult<serde_json::Value, EventPublisherError> {
let mut result = event.masked_serialize().map_err(|e| {
error_stack::Report::new(EventPublisherError::EventSerializationFailed)
.attach_printable(format!("Event masked serialization failed: {e}"))
})?;
// Process transformations
for (target_path, source_field) in &self.config.transformations {
if let Some(value) = result.get(source_field).cloned() {
// Replace _DOT_ and _dot_ with . to support nested keys in environment variables
let normalized_path = target_path.replace("_DOT_", ".").replace("_dot_", ".");
if let Err(e) = self.set_nested_value(&mut result, &normalized_path, value) {
tracing::warn!(
target_path = %target_path,
normalized_path = %normalized_path,
source_field = %source_field,
error = %e,
"Failed to set transformation, continuing with event processing"
);
}
}
}
// Process static values - log warnings but continue processing
for (target_path, static_value) in &self.config.static_values {
// Replace _DOT_ and _dot_ with . to support nested keys in environment variables
let normalized_path = target_path.replace("_DOT_", ".").replace("_dot_", ".");
let value = serde_json::json!(static_value);
if let Err(e) = self.set_nested_value(&mut result, &normalized_path, value) {
tracing::warn!(
target_path = %target_path,
normalized_path = %normalized_path,
static_value = %static_value,
error = %e,
"Failed to set static value, continuing with event processing"
);
}
}
// Process extraction
for (target_path, extraction_path) in &self.config.extractions {
if let Some(value) = self.extract_from_request(&result, extraction_path) {
// Replace _DOT_ and _dot_ with . to support nested keys in environment variables
let normalized_path = target_path.replace("_DOT_", ".").replace("_dot_", ".");
if let Err(e) = self.set_nested_value(&mut result, &normalized_path, value) {
| {
"chunk": 1,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_2048526090272796786_2 | clm | mini_chunk | // connector-service/backend/common_utils/src/event_publisher.rs
tracing::warn!(
target_path = %target_path,
normalized_path = %normalized_path,
extraction_path = %extraction_path,
error = %e,
"Failed to set extraction, continuing with event processing"
);
}
}
}
Ok(result)
}
fn extract_from_request(
&self,
event_value: &serde_json::Value,
extraction_path: &str,
) -> Option<serde_json::Value> {
let mut path_parts = extraction_path.split('.');
let first_part = path_parts.next()?;
let source = match first_part {
"req" => event_value.get("request_data")?.clone(),
_ => return None,
};
let mut current = &source;
for part in path_parts {
current = current.get(part)?;
}
Some(current.clone())
}
fn set_nested_value(
&self,
target: &mut serde_json::Value,
path: &str,
value: serde_json::Value,
) -> CustomResult<(), EventPublisherError> {
let path_parts: Vec<&str> = path.split('.').filter(|s| !s.is_empty()).collect();
if path_parts.is_empty() {
return Err(error_stack::Report::new(EventPublisherError::InvalidPath {
path: path.to_string(),
}));
}
if path_parts.len() == 1 {
if let Some(key) = path_parts.first() {
target[*key] = value;
return Ok(());
}
}
let result = path_parts.iter().enumerate().try_fold(
target,
|current,
(index, &part)|
-> CustomResult<&mut serde_json::Value, EventPublisherError> {
if index == path_parts.len() - 1 {
current[part] = value.clone();
Ok(current)
} else {
if !current[part].is_object() {
current[part] = serde_json::json!({});
}
current.get_mut(part).ok_or_else(|| {
error_stack::Report::new(EventPublisherError::InvalidPath {
path: format!("{path}.{part}"),
})
})
}
},
);
result.map(|_| ())
}
}
/// Initialize the global EventPublisher with the given configuration
pub fn init_event_publisher(config: &EventConfig) -> CustomResult<(), EventPublisherError> {
tracing::info!(
enabled = config.enabled,
"Initializing global EventPublisher"
);
let publisher = EventPublisher::new(config)?;
EVENT_PUBLISHER.set(publisher).map_err(|failed_publisher| {
error_stack::Report::new(EventPublisherError::AlreadyInitialized)
.attach_printable("EventPublisher was already initialized")
.attach_printable(format!(
"Existing config: brokers={:?}, topic={}",
failed_publisher.config.brokers, failed_publisher.config.topic
))
.attach_printable(format!(
"New config: brokers={:?}, topic={}",
config.brokers, config.topic
))
})?;
tracing::info!("Global EventPublisher initialized successfully");
Ok(())
}
/// Get or initialize the global EventPublisher
fn get_event_publisher(
config: &EventConfig,
) -> CustomResult<&'static EventPublisher, EventPublisherError> {
EVENT_PUBLISHER.get_or_try_init(|| EventPublisher::new(config))
}
/// Standalone function to emit events using the global EventPublisher
pub fn emit_event_with_config(event: Event, config: &EventConfig) {
if !config.enabled {
tracing::info!("Event publishing disabled");
return;
}
// just log the error if publishing fails
let _ = get_event_publisher(config)
.and_then(|publisher| publisher.emit_event_with_config(event, config))
.inspect_err(|e| {
tracing::error!(error = ?e, "Failed to emit event");
});
}
| {
"chunk": 2,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_3964809568807133229_0 | clm | mini_chunk | // connector-service/backend/common_utils/src/custom_serde.rs
/// Use the well-known ISO 8601 format when serializing and deserializing an
/// [`PrimitiveDateTime`][PrimitiveDateTime].
///
/// [PrimitiveDateTime]: ::time::PrimitiveDateTime
pub mod iso8601 {
use std::num::NonZeroU8;
use serde::{ser::Error as _, Deserializer, Serialize, Serializer};
use time::{
format_description::well_known::{
iso8601::{Config, EncodedConfig, TimePrecision},
Iso8601,
},
serde::iso8601,
PrimitiveDateTime, UtcOffset,
};
const FORMAT_CONFIG: EncodedConfig = Config::DEFAULT
.set_time_precision(TimePrecision::Second {
decimal_digits: NonZeroU8::new(3),
})
.encode();
/// Serialize a [`PrimitiveDateTime`] using the well-known ISO 8601 format.
pub fn serialize<S>(date_time: &PrimitiveDateTime, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
date_time
.assume_utc()
.format(&Iso8601::<FORMAT_CONFIG>)
.map_err(S::Error::custom)?
.serialize(serializer)
}
/// Deserialize an [`PrimitiveDateTime`] from its ISO 8601 representation.
pub fn deserialize<'a, D>(deserializer: D) -> Result<PrimitiveDateTime, D::Error>
where
D: Deserializer<'a>,
{
iso8601::deserialize(deserializer).map(|offset_date_time| {
let utc_date_time = offset_date_time.to_offset(UtcOffset::UTC);
PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time())
})
}
/// Use the well-known ISO 8601 format when serializing and deserializing an
/// [`Option<PrimitiveDateTime>`][PrimitiveDateTime].
///
/// [PrimitiveDateTime]: ::time::PrimitiveDateTime
pub mod option {
use serde::Serialize;
use time::format_description::well_known::Iso8601;
use super::*;
/// Serialize an [`Option<PrimitiveDateTime>`] using the well-known ISO 8601 format.
pub fn serialize<S>(
date_time: &Option<PrimitiveDateTime>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
date_time
.map(|date_time| date_time.assume_utc().format(&Iso8601::<FORMAT_CONFIG>))
.transpose()
.map_err(S::Error::custom)?
.serialize(serializer)
}
/// Deserialize an [`Option<PrimitiveDateTime>`] from its ISO 8601 representation.
pub fn deserialize<'a, D>(deserializer: D) -> Result<Option<PrimitiveDateTime>, D::Error>
where
D: Deserializer<'a>,
{
iso8601::option::deserialize(deserializer).map(|option_offset_date_time| {
option_offset_date_time.map(|offset_date_time| {
let utc_date_time = offset_date_time.to_offset(UtcOffset::UTC);
PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time())
})
})
}
}
/// Use the well-known ISO 8601 format which is without timezone when serializing and deserializing an
/// [`Option<PrimitiveDateTime>`][PrimitiveDateTime].
///
/// [PrimitiveDateTime]: ::time::PrimitiveDateTime
pub mod option_without_timezone {
use serde::{de, Deserialize, Serialize};
use time::macros::format_description;
use super::*;
/// Serialize an [`Option<PrimitiveDateTime>`] using the well-known ISO 8601 format which is without timezone.
pub fn serialize<S>(
date_time: &Option<PrimitiveDateTime>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
date_time
.map(|date_time| {
let format =
format_description!("[year]-[month]-[day]T[hour]:[minute]:[second]");
date_time.assume_utc().format(format)
})
.transpose()
.map_err(S::Error::custom)?
.serialize(serializer)
}
/// Deserialize an [`Option<PrimitiveDateTime>`] from its ISO 8601 representation.
pub fn deserialize<'a, D>(deserializer: D) -> Result<Option<PrimitiveDateTime>, D::Error>
where
D: Deserializer<'a>,
{
| {
"chunk": 0,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_3964809568807133229_1 | clm | mini_chunk | // connector-service/backend/common_utils/src/custom_serde.rs
Option::deserialize(deserializer)?
.map(|time_string| {
let format =
format_description!("[year]-[month]-[day]T[hour]:[minute]:[second]");
PrimitiveDateTime::parse(time_string, format).map_err(|_| {
de::Error::custom(format!(
"Failed to parse PrimitiveDateTime from {time_string}"
))
})
})
.transpose()
}
}
}
/// Use the UNIX timestamp when serializing and deserializing an
/// [`PrimitiveDateTime`][PrimitiveDateTime].
///
/// [PrimitiveDateTime]: ::time::PrimitiveDateTime
pub mod timestamp {
use serde::{Deserializer, Serialize, Serializer};
use time::{serde::timestamp, PrimitiveDateTime, UtcOffset};
/// Serialize a [`PrimitiveDateTime`] using UNIX timestamp.
pub fn serialize<S>(date_time: &PrimitiveDateTime, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
date_time
.assume_utc()
.unix_timestamp()
.serialize(serializer)
}
/// Deserialize an [`PrimitiveDateTime`] from UNIX timestamp.
pub fn deserialize<'a, D>(deserializer: D) -> Result<PrimitiveDateTime, D::Error>
where
D: Deserializer<'a>,
{
timestamp::deserialize(deserializer).map(|offset_date_time| {
let utc_date_time = offset_date_time.to_offset(UtcOffset::UTC);
PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time())
})
}
/// Use the UNIX timestamp when serializing and deserializing an
/// [`Option<PrimitiveDateTime>`][PrimitiveDateTime].
///
/// [PrimitiveDateTime]: ::time::PrimitiveDateTime
pub mod option {
use serde::Serialize;
use super::*;
/// Serialize an [`Option<PrimitiveDateTime>`] from UNIX timestamp.
pub fn serialize<S>(
date_time: &Option<PrimitiveDateTime>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
date_time
.map(|date_time| date_time.assume_utc().unix_timestamp())
.serialize(serializer)
}
/// Deserialize an [`Option<PrimitiveDateTime>`] from UNIX timestamp.
pub fn deserialize<'a, D>(deserializer: D) -> Result<Option<PrimitiveDateTime>, D::Error>
where
D: Deserializer<'a>,
{
timestamp::option::deserialize(deserializer).map(|option_offset_date_time| {
option_offset_date_time.map(|offset_date_time| {
let utc_date_time = offset_date_time.to_offset(UtcOffset::UTC);
PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time())
})
})
}
}
}
| {
"chunk": 1,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_-4895347235318218796_0 | clm | mini_chunk | // connector-service/backend/common_utils/src/global_id/payment_methods.rs
use error_stack::ResultExt;
use crate::{
errors::CustomResult,
global_id::{CellId, GlobalEntity, GlobalId},
};
/// A global id that can be used to identify a payment method
#[derive(Debug, Clone, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct GlobalPaymentMethodId(GlobalId);
/// A global id that can be used to identify a payment method session
#[derive(Debug, Clone, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct GlobalPaymentMethodSessionId(GlobalId);
#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)]
pub enum GlobalPaymentMethodIdError {
#[error("Failed to construct GlobalPaymentMethodId")]
ConstructionError,
}
#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)]
pub enum GlobalPaymentMethodSessionIdError {
#[error("Failed to construct GlobalPaymentMethodSessionId")]
ConstructionError,
}
impl GlobalPaymentMethodSessionId {
/// Create a new GlobalPaymentMethodSessionId from cell id information
pub fn generate(
cell_id: &CellId,
) -> error_stack::Result<Self, GlobalPaymentMethodSessionIdError> {
let global_id = GlobalId::generate(cell_id, GlobalEntity::PaymentMethodSession);
Ok(Self(global_id))
}
/// Get the string representation of the id
pub fn get_string_repr(&self) -> &str {
self.0.get_string_repr()
}
/// Construct a redis key from the id to be stored in redis
pub fn get_redis_key(&self) -> String {
format!("payment_method_session:{}", self.get_string_repr())
}
}
impl crate::events::ApiEventMetric for GlobalPaymentMethodSessionId {
fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> {
Some(crate::events::ApiEventsType::PaymentMethodSession {
payment_method_session_id: self.clone(),
})
}
}
impl GlobalPaymentMethodId {
/// Create a new GlobalPaymentMethodId from cell id information
pub fn generate(cell_id: &CellId) -> error_stack::Result<Self, GlobalPaymentMethodIdError> {
let global_id = GlobalId::generate(cell_id, GlobalEntity::PaymentMethod);
Ok(Self(global_id))
}
/// Get string representation of the id
pub fn get_string_repr(&self) -> &str {
self.0.get_string_repr()
}
/// Construct a new GlobalPaymentMethodId from a string
pub fn generate_from_string(value: String) -> CustomResult<Self, GlobalPaymentMethodIdError> {
let id = GlobalId::from_string(value.into())
.change_context(GlobalPaymentMethodIdError::ConstructionError)?;
Ok(Self(id))
}
}
| {
"chunk": 0,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_2591687643226154011_0 | clm | mini_chunk | // connector-service/backend/common_utils/src/global_id/refunds.rs
use error_stack::ResultExt;
use crate::{errors, global_id::CellId};
/// A global id that can be used to identify a refund
#[derive(Debug, Clone, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct GlobalRefundId(super::GlobalId);
impl GlobalRefundId {
/// Get string representation of the id
pub fn get_string_repr(&self) -> &str {
self.0.get_string_repr()
}
/// Generate a new GlobalRefundId from a cell id
pub fn generate(cell_id: &CellId) -> Self {
let global_id = super::GlobalId::generate(cell_id, super::GlobalEntity::Refund);
Self(global_id)
}
}
// TODO: refactor the macro to include this id use case as well
impl TryFrom<std::borrow::Cow<'static, str>> for GlobalRefundId {
type Error = error_stack::Report<errors::ValidationError>;
fn try_from(value: std::borrow::Cow<'static, str>) -> Result<Self, Self::Error> {
let merchant_ref_id = super::GlobalId::from_string(value).change_context(
errors::ValidationError::IncorrectValueProvided {
field_name: "refund_id",
},
)?;
Ok(Self(merchant_ref_id))
}
}
| {
"chunk": 0,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_4154652033531294868_0 | clm | mini_chunk | // connector-service/backend/common_utils/src/global_id/token.rs
use crate::global_id::CellId;
crate::global_id_type!(
GlobalTokenId,
"A global id that can be used to identify a token.
The format will be `<cell_id>_<entity_prefix>_<time_ordered_id>`.
Example: `cell1_tok_uu1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p`"
);
impl GlobalTokenId {
/// Get string representation of the id
pub fn get_string_repr(&self) -> &str {
self.0.get_string_repr()
}
/// Generate a new GlobalTokenId from a cell id
pub fn generate(cell_id: &CellId) -> Self {
let global_id = super::GlobalId::generate(cell_id, super::GlobalEntity::Token);
Self(global_id)
}
}
impl crate::events::ApiEventMetric for GlobalTokenId {
fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> {
Some(crate::events::ApiEventsType::Token {
token_id: Some(self.clone()),
})
}
}
| {
"chunk": 0,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_-6586181602109849698_0 | clm | mini_chunk | // connector-service/backend/common_utils/src/global_id/payment.rs
use common_enums::enums;
use error_stack::ResultExt;
use crate::{errors, global_id::CellId};
crate::global_id_type!(
GlobalPaymentId,
"A global id that can be used to identify a payment.
The format will be `<cell_id>_<entity_prefix>_<time_ordered_id>`.
Example: `cell1_pay_uu1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p`"
);
impl GlobalPaymentId {
/// Get string representation of the id
pub fn get_string_repr(&self) -> &str {
self.0.get_string_repr()
}
/// Generate a new GlobalPaymentId from a cell id
pub fn generate(cell_id: &CellId) -> Self {
let global_id = super::GlobalId::generate(cell_id, super::GlobalEntity::Payment);
Self(global_id)
}
/// Generate the id for revenue recovery Execute PT workflow
pub fn get_execute_revenue_recovery_id(
&self,
task: &str,
runner: enums::ProcessTrackerRunner,
) -> String {
format!("{runner}_{task}_{}", self.get_string_repr())
}
}
// TODO: refactor the macro to include this id use case as well
impl TryFrom<std::borrow::Cow<'static, str>> for GlobalPaymentId {
type Error = error_stack::Report<errors::ValidationError>;
fn try_from(value: std::borrow::Cow<'static, str>) -> Result<Self, Self::Error> {
let merchant_ref_id = super::GlobalId::from_string(value).change_context(
errors::ValidationError::IncorrectValueProvided {
field_name: "payment_id",
},
)?;
Ok(Self(merchant_ref_id))
}
}
crate::global_id_type!(
GlobalAttemptId,
"A global id that can be used to identify a payment attempt"
);
impl GlobalAttemptId {
/// Generate a new GlobalAttemptId from a cell id
#[allow(dead_code)]
pub fn generate(cell_id: &CellId) -> Self {
let global_id = super::GlobalId::generate(cell_id, super::GlobalEntity::Attempt);
Self(global_id)
}
/// Get string representation of the id
#[allow(dead_code)]
pub fn get_string_repr(&self) -> &str {
self.0.get_string_repr()
}
/// Generate the id for Revenue Recovery Psync PT workflow
#[allow(dead_code)]
pub fn get_psync_revenue_recovery_id(
&self,
task: &str,
runner: enums::ProcessTrackerRunner,
) -> String {
format!("{runner}_{task}_{}", self.get_string_repr())
}
}
impl TryFrom<std::borrow::Cow<'static, str>> for GlobalAttemptId {
type Error = error_stack::Report<errors::ValidationError>;
fn try_from(value: std::borrow::Cow<'static, str>) -> Result<Self, Self::Error> {
let global_attempt_id = super::GlobalId::from_string(value).change_context(
errors::ValidationError::IncorrectValueProvided {
field_name: "payment_id",
},
)?;
Ok(Self(global_attempt_id))
}
}
| {
"chunk": 0,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_ucs_common_utils_-1764418433195637174_0 | clm | mini_chunk | // connector-service/backend/common_utils/src/global_id/customer.rs
use crate::{errors, global_id::CellId};
crate::global_id_type!(
GlobalCustomerId,
"A global id that can be used to identify a customer.
Example: `cell1_cus_uu1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p`"
);
impl GlobalCustomerId {
/// Get string representation of the id
pub fn get_string_repr(&self) -> &str {
self.0.get_string_repr()
}
/// Generate a new GlobalCustomerId from a cell id
pub fn generate(cell_id: &CellId) -> Self {
let global_id = super::GlobalId::generate(cell_id, super::GlobalEntity::Customer);
Self(global_id)
}
}
impl TryFrom<GlobalCustomerId> for crate::id_type::CustomerId {
type Error = error_stack::Report<errors::ValidationError>;
fn try_from(value: GlobalCustomerId) -> Result<Self, Self::Error> {
Self::try_from(std::borrow::Cow::from(value.get_string_repr().to_owned()))
}
}
impl crate::events::ApiEventMetric for GlobalCustomerId {
fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> {
Some(crate::events::ApiEventsType::Customer {
customer_id: Some(self.clone()),
})
}
}
| {
"chunk": 0,
"crate": "ucs_common_utils",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_connector-integration_1661134184692456114_0 | clm | mini_chunk | // connector-service/backend/connector-integration/src/types.rs
use std::fmt::Debug;
use domain_types::{connector_types::ConnectorEnum, payment_method_data::PaymentMethodDataTypes};
use interfaces::connector_types::BoxedConnector;
use crate::connectors::{
Aci, Adyen, Authorizedotnet, Bluecode, Braintree, Cashfree, Cashtocode, Checkout, Cryptopay,
Cybersource, Dlocal, Elavon, Fiserv, Fiuu, Helcim, Mifinity, Nexinets, Noon, Novalnet, Payload,
Paytm, Payu, Phonepe, Placetopay, Rapyd, Razorpay, RazorpayV2, Stripe, Trustpay, Volt,
Worldpay, Worldpayvantiv, Xendit,
};
#[derive(Clone)]
pub struct ConnectorData<T: PaymentMethodDataTypes + Debug + Default + Send + Sync + 'static> {
pub connector: BoxedConnector<T>,
pub connector_name: ConnectorEnum,
}
impl<T: PaymentMethodDataTypes + Debug + Default + Send + Sync + 'static + serde::Serialize>
ConnectorData<T>
{
pub fn get_connector_by_name(connector_name: &ConnectorEnum) -> Self {
let connector = Self::convert_connector(*connector_name);
Self {
connector,
connector_name: *connector_name,
}
}
fn convert_connector(connector_name: ConnectorEnum) -> BoxedConnector<T> {
match connector_name {
ConnectorEnum::Adyen => Box::new(Adyen::new()),
ConnectorEnum::Razorpay => Box::new(Razorpay::new()),
ConnectorEnum::RazorpayV2 => Box::new(RazorpayV2::new()),
ConnectorEnum::Fiserv => Box::new(Fiserv::new()),
ConnectorEnum::Elavon => Box::new(Elavon::new()),
ConnectorEnum::Xendit => Box::new(Xendit::new()),
ConnectorEnum::Checkout => Box::new(Checkout::new()),
ConnectorEnum::Authorizedotnet => Box::new(Authorizedotnet::new()),
ConnectorEnum::Mifinity => Box::new(Mifinity::new()),
ConnectorEnum::Phonepe => Box::new(Phonepe::new()),
ConnectorEnum::Cashfree => Box::new(Cashfree::new()),
ConnectorEnum::Fiuu => Box::new(Fiuu::new()),
ConnectorEnum::Payu => Box::new(Payu::new()),
ConnectorEnum::Paytm => Box::new(Paytm::new()),
ConnectorEnum::Cashtocode => Box::new(Cashtocode::new()),
ConnectorEnum::Novalnet => Box::new(Novalnet::new()),
ConnectorEnum::Nexinets => Box::new(Nexinets::new()),
ConnectorEnum::Noon => Box::new(Noon::new()),
ConnectorEnum::Volt => Box::new(Volt::new()),
ConnectorEnum::Braintree => Box::new(Braintree::new()),
ConnectorEnum::Bluecode => Box::new(Bluecode::new()),
ConnectorEnum::Cryptopay => Box::new(Cryptopay::new()),
ConnectorEnum::Helcim => Box::new(Helcim::new()),
ConnectorEnum::Dlocal => Box::new(Dlocal::new()),
ConnectorEnum::Placetopay => Box::new(Placetopay::new()),
ConnectorEnum::Rapyd => Box::new(Rapyd::new()),
ConnectorEnum::Aci => Box::new(Aci::new()),
ConnectorEnum::Trustpay => Box::new(Trustpay::new()),
ConnectorEnum::Stripe => Box::new(Stripe::new()),
ConnectorEnum::Cybersource => Box::new(Cybersource::new()),
ConnectorEnum::Worldpay => Box::new(Worldpay::new()),
ConnectorEnum::Worldpayvantiv => Box::new(Worldpayvantiv::new()),
ConnectorEnum::Payload => Box::new(Payload::new()),
}
}
}
pub struct ResponseRouterData<Response, RouterData> {
pub response: Response,
pub router_data: RouterData,
pub http_code: u16,
}
| {
"chunk": 0,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_connector-integration_-67203261144202079_0 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors.rs
pub mod adyen;
pub mod razorpay;
pub mod authorizedotnet;
pub mod fiserv;
pub mod razorpayv2;
pub use self::{
adyen::Adyen, authorizedotnet::Authorizedotnet, fiserv::Fiserv, mifinity::Mifinity,
razorpay::Razorpay, razorpayv2::RazorpayV2,
};
pub mod elavon;
pub use self::elavon::Elavon;
pub mod xendit;
pub use self::xendit::Xendit;
pub mod macros;
pub mod checkout;
pub use self::checkout::Checkout;
pub mod mifinity;
pub mod phonepe;
pub use self::phonepe::Phonepe;
pub mod cashfree;
pub use self::cashfree::Cashfree;
pub mod paytm;
pub use self::paytm::Paytm;
pub mod fiuu;
pub use self::fiuu::Fiuu;
pub mod payu;
pub use self::payu::Payu;
pub mod cashtocode;
pub use self::cashtocode::Cashtocode;
pub mod novalnet;
pub use self::novalnet::Novalnet;
pub mod nexinets;
pub use self::nexinets::Nexinets;
pub mod noon;
pub use self::noon::Noon;
pub mod braintree;
pub use self::braintree::Braintree;
pub mod volt;
pub use self::volt::Volt;
pub mod bluecode;
pub use self::bluecode::Bluecode;
pub mod cryptopay;
pub use self::cryptopay::Cryptopay;
pub mod dlocal;
pub use self::dlocal::Dlocal;
pub mod helcim;
pub use self::helcim::Helcim;
pub mod placetopay;
pub use self::placetopay::Placetopay;
pub mod rapyd;
pub use self::rapyd::Rapyd;
pub mod aci;
pub use self::aci::Aci;
pub mod trustpay;
pub use self::trustpay::Trustpay;
pub mod stripe;
pub use self::stripe::Stripe;
pub mod cybersource;
pub use self::cybersource::Cybersource;
pub mod worldpay;
pub use self::worldpay::Worldpay;
pub mod worldpayvantiv;
pub use self::worldpayvantiv::Worldpayvantiv;
pub mod payload;
pub use self::payload::Payload;
| {
"chunk": 0,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_connector-integration_-4518986933431497461_0 | clm | mini_chunk | // connector-service/backend/connector-integration/src/utils.rs
pub mod xml_utils;
use common_utils::{types::MinorUnit, CustomResult};
use domain_types::{
connector_types::{
PaymentVoidData, PaymentsAuthorizeData, PaymentsCaptureData, PaymentsSyncData,
RepeatPaymentData, SetupMandateRequestData,
},
errors,
payment_method_data::PaymentMethodDataTypes,
router_data::ErrorResponse,
router_response_types::Response,
};
use error_stack::{Report, ResultExt};
use hyperswitch_masking::{ExposeInterface, Secret};
use serde_json::Value;
use std::str::FromStr;
pub use xml_utils::preprocess_xml_response_bytes;
type Error = error_stack::Report<errors::ConnectorError>;
use common_enums::enums;
use serde::{Deserialize, Serialize};
#[macro_export]
macro_rules! with_error_response_body {
($event_builder:ident, $response:ident) => {
if let Some(body) = $event_builder {
body.set_connector_response(&$response);
}
};
}
#[macro_export]
macro_rules! with_response_body {
($event_builder:ident, $response:ident) => {
if let Some(body) = $event_builder {
body.set_connector_response(&$response);
}
};
}
pub trait PaymentsAuthorizeRequestData {
fn get_router_return_url(&self) -> Result<String, Error>;
}
impl<
T: PaymentMethodDataTypes + std::fmt::Debug + std::marker::Sync + std::marker::Send + 'static,
> PaymentsAuthorizeRequestData for PaymentsAuthorizeData<T>
{
fn get_router_return_url(&self) -> Result<String, Error> {
self.router_return_url
.clone()
.ok_or_else(missing_field_err("return_url"))
}
}
pub fn missing_field_err(
message: &'static str,
) -> Box<dyn Fn() -> error_stack::Report<errors::ConnectorError> + 'static> {
Box::new(move || {
errors::ConnectorError::MissingRequiredField {
field_name: message,
}
.into()
})
}
pub(crate) fn get_unimplemented_payment_method_error_message(connector: &str) -> String {
format!("Selected payment method through {connector}")
}
pub(crate) fn to_connector_meta_from_secret<T>(
connector_meta: Option<Secret<Value>>,
) -> Result<T, Error>
where
T: serde::de::DeserializeOwned,
{
let connector_meta_secret =
connector_meta.ok_or_else(missing_field_err("connector_meta_data"))?;
let json_value = connector_meta_secret.expose();
let parsed: T = match json_value {
Value::String(json_str) => serde_json::from_str(&json_str)
.map_err(Report::from)
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "merchant_connector_account.metadata",
})?,
_ => serde_json::from_value(json_value.clone())
.map_err(Report::from)
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "merchant_connector_account.metadata",
})?,
};
Ok(parsed)
}
pub(crate) fn handle_json_response_deserialization_failure(
res: Response,
_connector: &'static str,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response_data = String::from_utf8(res.response.to_vec())
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
// check for whether the response is in json format
match serde_json::from_str::<Value>(&response_data) {
// in case of unexpected response but in json format
Ok(_) => Err(errors::ConnectorError::ResponseDeserializationFailed)?,
// in case of unexpected response but in html or string format
Err(_error_msg) => Ok(ErrorResponse {
status_code: res.status_code,
code: "No error code".to_string(),
message: "Unsupported response type".to_string(),
reason: Some(response_data),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
}),
}
}
pub fn is_refund_failure(status: enums::RefundStatus) -> bool {
match status {
common_enums::RefundStatus::Failure | common_enums::RefundStatus::TransactionFailure => {
true
}
common_enums::RefundStatus::ManualReview
| common_enums::RefundStatus::Pending
| common_enums::RefundStatus::Success => false,
}
}
| {
"chunk": 0,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_connector-integration_-4518986933431497461_1 | clm | mini_chunk | // connector-service/backend/connector-integration/src/utils.rs
pub fn deserialize_zero_minor_amount_as_none<'de, D>(
deserializer: D,
) -> Result<Option<MinorUnit>, D::Error>
where
D: serde::de::Deserializer<'de>,
{
let amount = Option::<MinorUnit>::deserialize(deserializer)?;
match amount {
Some(value) if value.get_amount_as_i64() == 0 => Ok(None),
_ => Ok(amount),
}
}
pub fn convert_uppercase<'de, D, T>(v: D) -> Result<T, D::Error>
where
D: serde::Deserializer<'de>,
T: FromStr,
<T as FromStr>::Err: std::fmt::Debug + std::fmt::Display + std::error::Error,
{
use serde::de::Error;
let output = <&str>::deserialize(v)?;
output.to_uppercase().parse::<T>().map_err(D::Error::custom)
}
pub trait SplitPaymentData {
fn get_split_payment_data(&self)
-> Option<domain_types::connector_types::SplitPaymentsRequest>;
}
impl SplitPaymentData for PaymentsCaptureData {
fn get_split_payment_data(
&self,
) -> Option<domain_types::connector_types::SplitPaymentsRequest> {
None
}
}
impl<T: PaymentMethodDataTypes> SplitPaymentData for PaymentsAuthorizeData<T> {
fn get_split_payment_data(
&self,
) -> Option<domain_types::connector_types::SplitPaymentsRequest> {
self.split_payments.clone()
}
}
impl SplitPaymentData for RepeatPaymentData {
fn get_split_payment_data(
&self,
) -> Option<domain_types::connector_types::SplitPaymentsRequest> {
self.split_payments.clone()
}
}
impl SplitPaymentData for PaymentsSyncData {
fn get_split_payment_data(
&self,
) -> Option<domain_types::connector_types::SplitPaymentsRequest> {
self.split_payments.clone()
}
}
impl SplitPaymentData for PaymentVoidData {
fn get_split_payment_data(
&self,
) -> Option<domain_types::connector_types::SplitPaymentsRequest> {
None
}
}
impl<T: PaymentMethodDataTypes> SplitPaymentData for SetupMandateRequestData<T> {
fn get_split_payment_data(
&self,
) -> Option<domain_types::connector_types::SplitPaymentsRequest> {
None
}
}
pub fn serialize_to_xml_string_with_root<T: Serialize>(
root_name: &str,
data: &T,
) -> Result<String, Error> {
let xml_content = quick_xml::se::to_string_with_root(root_name, data)
.change_context(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to serialize XML with root")?;
let full_xml = format!("<?xml version=\"1.0\" encoding=\"UTF-8\"?>{}", xml_content);
Ok(full_xml)
}
| {
"chunk": 1,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_connector-integration_-2288493413238451084_0 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/nexinets.rs
pub mod transformers;
use std::fmt::Debug;
use common_utils::{errors::CustomResult, events, ext_traits::ByteSliceExt};
use domain_types::{
connector_flow::{
Accept, Authenticate, Authorize, Capture, CreateAccessToken, CreateConnectorCustomer,
CreateOrder, CreateSessionToken, DefendDispute, PSync, PaymentMethodToken,
PostAuthenticate, PreAuthenticate, RSync, Refund, RepeatPayment, SetupMandate,
SubmitEvidence, Void, VoidPC,
},
connector_types::{
AcceptDisputeData, AccessTokenRequestData, AccessTokenResponseData, ConnectorCustomerData,
ConnectorCustomerResponse, DisputeDefendData, DisputeFlowData, DisputeResponseData,
PaymentCreateOrderData, PaymentCreateOrderResponse, PaymentFlowData,
PaymentMethodTokenResponse, PaymentMethodTokenizationData, PaymentVoidData,
PaymentsAuthenticateData, PaymentsAuthorizeData, PaymentsCancelPostCaptureData,
PaymentsCaptureData, PaymentsPostAuthenticateData, PaymentsPreAuthenticateData,
PaymentsResponseData, PaymentsSyncData, RefundFlowData, RefundSyncData, RefundsData,
RefundsResponseData, RepeatPaymentData, SessionTokenRequestData, SessionTokenResponseData,
SetupMandateRequestData, SubmitEvidenceData,
},
errors,
payment_method_data::PaymentMethodDataTypes,
router_data::{ConnectorAuthType, ErrorResponse},
router_data_v2::RouterDataV2,
router_response_types::Response,
types::Connectors,
};
use hyperswitch_masking::{Mask, Maskable};
use interfaces::{
api::ConnectorCommon, connector_integration_v2::ConnectorIntegrationV2, connector_types,
};
use serde::Serialize;
use serde_json;
use transformers::{
self as nexinets, NexinetsCaptureOrVoidRequest, NexinetsErrorResponse,
NexinetsPaymentResponse as NexinetsCaptureResponse, NexinetsPaymentResponse,
NexinetsPaymentsRequest, NexinetsPreAuthOrDebitResponse, NexinetsRefundRequest,
NexinetsRefundResponse, NexinetsRefundResponse as RefundSyncResponse,
};
use super::macros;
use crate::{types::ResponseRouterData, with_error_response_body};
pub const BASE64_ENGINE: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD;
use error_stack::ResultExt;
pub(crate) mod headers {
pub(crate) const CONTENT_TYPE: &str = "Content-Type";
pub(crate) const AUTHORIZATION: &str = "Authorization";
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize> ConnectorCommon
for Nexinets<T>
{
fn id(&self) -> &'static str {
"nexinets"
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let auth = nexinets::NexinetsAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
auth.api_key.into_masked(),
)])
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.nexinets.base_url.as_ref()
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut events::Event>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: NexinetsErrorResponse = res
.response
.parse_struct("NexinetsErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
with_error_response_body!(event_builder, response);
let errors = response.errors;
let mut message = String::new();
let mut static_message = String::new();
for error in errors.iter() {
let field = error.field.to_owned().unwrap_or_default();
let mut msg = String::new();
if !field.is_empty() {
msg.push_str(format!("{} : {}", field, error.message).as_str());
} else {
error.message.clone_into(&mut msg)
}
if message.is_empty() {
message.push_str(&msg);
static_message.push_str(&msg);
} else {
message.push_str(format!(", {msg}").as_str());
}
}
| {
"chunk": 0,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_connector-integration_-2288493413238451084_1 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/nexinets.rs
let connector_reason = format!("reason : {} , message : {}", response.message, message);
Ok(ErrorResponse {
status_code: response.status,
code: response.code.to_string(),
message: static_message,
reason: Some(connector_reason),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
}
//marker traits
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
connector_types::ConnectorServiceTrait<T> for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
connector_types::PaymentAuthorizeV2<T> for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
connector_types::PaymentSyncV2 for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
connector_types::PaymentSessionToken for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
connector_types::PaymentAccessToken for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
connector_types::CreateConnectorCustomer for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
connector_types::PaymentVoidV2 for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
connector_types::RefundSyncV2 for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
connector_types::RefundV2 for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
connector_types::PaymentCapture for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
connector_types::ValidationTrait for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
connector_types::PaymentOrderCreate for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
connector_types::SetupMandateV2<T> for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
connector_types::RepeatPaymentV2 for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
connector_types::PaymentVoidPostCaptureV2 for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
ConnectorIntegrationV2<
VoidPC,
PaymentFlowData,
PaymentsCancelPostCaptureData,
PaymentsResponseData,
> for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
connector_types::AcceptDispute for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
connector_types::SubmitEvidenceV2 for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
connector_types::DisputeDefend for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
connector_types::IncomingWebhook for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
connector_types::PaymentTokenV2<T> for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
connector_types::PaymentPreAuthenticateV2<T> for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
connector_types::PaymentAuthenticateV2<T> for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
connector_types::PaymentPostAuthenticateV2<T> for Nexinets<T>
{
}
macros::create_all_prerequisites!(
connector_name: Nexinets,
generic_type: T,
api: [
(
flow: Authorize,
request_body: NexinetsPaymentsRequest<T>,
response_body: NexinetsPreAuthOrDebitResponse,
router_data: RouterDataV2<Authorize, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData>,
),
(
flow: PSync,
response_body: NexinetsPaymentResponse,
| {
"chunk": 1,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_connector-integration_-2288493413238451084_2 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/nexinets.rs
router_data: RouterDataV2<PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>,
),
(
flow: Capture,
request_body: NexinetsCaptureOrVoidRequest,
response_body: NexinetsCaptureResponse,
router_data: RouterDataV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>,
),
(
flow: Refund,
request_body: NexinetsRefundRequest,
response_body: NexinetsRefundResponse,
router_data: RouterDataV2<Refund, RefundFlowData, RefundsData, RefundsResponseData>,
),
(
flow: RSync,
response_body: RefundSyncResponse,
router_data: RouterDataV2<RSync, RefundFlowData, RefundSyncData, RefundsResponseData>,
)
],
amount_converters: [],
member_functions: {
pub fn build_headers<F, FCD, Req, Res>(
&self,
req: &RouterDataV2<F, FCD, Req, Res>,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError>
where
Self: ConnectorIntegrationV2<F, FCD, Req, Res>,
{
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
pub fn connector_base_url_payments<'a, F, Req, Res>(
&self,
req: &'a RouterDataV2<F, PaymentFlowData, Req, Res>,
) -> &'a str {
&req.resource_common_data.connectors.nexinets.base_url
}
pub fn connector_base_url_refunds<'a, F, Req, Res>(
&self,
req: &'a RouterDataV2<F, RefundFlowData, Req, Res>,
) -> &'a str {
&req.resource_common_data.connectors.nexinets.base_url
}
}
);
macros::macro_connector_implementation!(
connector_default_implementations: [get_content_type, get_error_response_v2],
connector: Nexinets,
curl_request: Json(NexinetsPaymentsRequest),
curl_response: NexinetsPreAuthOrDebitResponse,
flow_name: Authorize,
resource_common_data: PaymentFlowData,
flow_request: PaymentsAuthorizeData<T>,
flow_response: PaymentsResponseData,
http_method: Post,
generic_type: T,
[PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize],
other_functions: {
fn get_headers(
&self,
req: &RouterDataV2<Authorize, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData>,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req)
}
fn get_url(
&self,
req: &RouterDataV2<Authorize, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData>,
) -> CustomResult<String, errors::ConnectorError> {
let url = if matches!(
req.request.capture_method,
Some(common_enums::CaptureMethod::Automatic) | Some(common_enums::CaptureMethod::SequentialAutomatic)
) {
format!("{}/orders/debit", self.connector_base_url_payments(req))
} else {
format!("{}/orders/preauth", self.connector_base_url_payments(req))
};
Ok(url)
}
}
);
// Macro implementations for PSync, Capture, Refund, and RSync flows
macros::macro_connector_implementation!(
connector_default_implementations: [get_content_type, get_error_response_v2],
connector: Nexinets,
curl_response: NexinetsPreAuthOrDebitResponse,
flow_name: PSync,
resource_common_data: PaymentFlowData,
flow_request: PaymentsSyncData,
flow_response: PaymentsResponseData,
http_method: Get,
generic_type: T,
[PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize],
other_functions: {
fn get_headers(
&self,
req: &RouterDataV2<PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req)
}
fn get_url(
&self,
req: &RouterDataV2<PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData>,
| {
"chunk": 2,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_connector-integration_-2288493413238451084_3 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/nexinets.rs
) -> CustomResult<String, errors::ConnectorError> {
let transaction_id = req.request.get_connector_transaction_id()?;
let order_id = &req.resource_common_data.connector_request_reference_id;
Ok(format!(
"{}/orders/{order_id}/transactions/{transaction_id}",
self.connector_base_url_payments(req),
))
}
}
);
macros::macro_connector_implementation!(
connector_default_implementations: [get_content_type, get_error_response_v2],
connector: Nexinets,
curl_request: Json(NexinetsCaptureOrVoidRequest),
curl_response: NexinetsCaptureResponse,
flow_name: Capture,
resource_common_data: PaymentFlowData,
flow_request: PaymentsCaptureData,
flow_response: PaymentsResponseData,
http_method: Post,
generic_type: T,
[PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize],
other_functions: {
fn get_headers(
&self,
req: &RouterDataV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req)
}
fn get_url(
&self,
req: &RouterDataV2<Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData>,
) -> CustomResult<String, errors::ConnectorError> {
let order_id = &req.resource_common_data.connector_request_reference_id;
let transaction_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}/orders/{order_id}/transactions/{transaction_id}/capture",
self.connector_base_url_payments(req),
))
}
}
);
macros::macro_connector_implementation!(
connector_default_implementations: [get_content_type, get_error_response_v2],
connector: Nexinets,
curl_request: Json(NexinetsRefundRequest),
curl_response: NexinetsRefundResponse,
flow_name: Refund,
resource_common_data: RefundFlowData,
flow_request: RefundsData,
flow_response: RefundsResponseData,
http_method: Post,
generic_type: T,
[PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize],
other_functions: {
fn get_headers(
&self,
req: &RouterDataV2<Refund, RefundFlowData, RefundsData, RefundsResponseData>,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req)
}
fn get_url(
&self,
req: &RouterDataV2<Refund, RefundFlowData, RefundsData, RefundsResponseData>,
) -> CustomResult<String, errors::ConnectorError> {
let connector_metadata = req
.request
.get_connector_metadata()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "connector_metadata",
})?;
// connector_metadata is a Value::String, so extract and parse
let metadata_str = connector_metadata
.as_str()
.ok_or(errors::ConnectorError::InvalidDataFormat {
field_name: "connector_metadata as string",
})?;
let parsed_metadata: serde_json::Value =
serde_json::from_str(metadata_str).change_context(
errors::ConnectorError::ParsingFailed
)?;
let order_id = parsed_metadata
.get("order_id")
.and_then(|v| v.as_str())
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "order_id in connector_metadata",
})?;
Ok(format!(
"{}/orders/{order_id}/transactions/{}/refund",
self.connector_base_url_refunds(req),
req.request.connector_transaction_id
))
}
}
);
macros::macro_connector_implementation!(
connector_default_implementations: [get_content_type, get_error_response_v2],
connector: Nexinets,
curl_response: RefundSyncResponse,
flow_name: RSync,
| {
"chunk": 3,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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_connector-integration_-2288493413238451084_4 | clm | mini_chunk | // connector-service/backend/connector-integration/src/connectors/nexinets.rs
resource_common_data: RefundFlowData,
flow_request: RefundSyncData,
flow_response: RefundsResponseData,
http_method: Get,
generic_type: T,
[PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize],
other_functions: {
fn get_headers(
&self,
req: &RouterDataV2<RSync, RefundFlowData, RefundSyncData, RefundsResponseData>,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req)
}
fn get_url(
&self,
req: &RouterDataV2<RSync, RefundFlowData, RefundSyncData, RefundsResponseData>,
) -> CustomResult<String, errors::ConnectorError> {
let transaction_id = req
.request
.connector_refund_id
.clone();
let order_id = req.resource_common_data.connector_request_reference_id.clone();
Ok(format!(
"{}/orders/{order_id}/transactions/{transaction_id}",
self.connector_base_url_refunds(req),
))
}
}
);
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
ConnectorIntegrationV2<
CreateOrder,
PaymentFlowData,
PaymentCreateOrderData,
PaymentCreateOrderResponse,
> for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
ConnectorIntegrationV2<
CreateSessionToken,
PaymentFlowData,
SessionTokenRequestData,
SessionTokenResponseData,
> for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
ConnectorIntegrationV2<
CreateAccessToken,
PaymentFlowData,
AccessTokenRequestData,
AccessTokenResponseData,
> for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
ConnectorIntegrationV2<
CreateConnectorCustomer,
PaymentFlowData,
ConnectorCustomerData,
ConnectorCustomerResponse,
> for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
ConnectorIntegrationV2<SubmitEvidence, DisputeFlowData, SubmitEvidenceData, DisputeResponseData>
for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
ConnectorIntegrationV2<DefendDispute, DisputeFlowData, DisputeDefendData, DisputeResponseData>
for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
ConnectorIntegrationV2<Accept, DisputeFlowData, AcceptDisputeData, DisputeResponseData>
for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
ConnectorIntegrationV2<
SetupMandate,
PaymentFlowData,
SetupMandateRequestData<T>,
PaymentsResponseData,
> for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
ConnectorIntegrationV2<Void, PaymentFlowData, PaymentVoidData, PaymentsResponseData>
for Nexinets<T>
{
}
// SourceVerification implementations for all flows
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
interfaces::verification::SourceVerification<
Authorize,
PaymentFlowData,
PaymentsAuthorizeData<T>,
PaymentsResponseData,
> for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
interfaces::verification::SourceVerification<
PSync,
PaymentFlowData,
PaymentsSyncData,
PaymentsResponseData,
> for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
interfaces::verification::SourceVerification<
Capture,
PaymentFlowData,
PaymentsCaptureData,
PaymentsResponseData,
> for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
interfaces::verification::SourceVerification<
Void,
PaymentFlowData,
PaymentVoidData,
PaymentsResponseData,
> for Nexinets<T>
{
}
impl<T: PaymentMethodDataTypes + Debug + Sync + Send + 'static + Serialize>
interfaces::verification::SourceVerification<
CreateSessionToken,
PaymentFlowData,
SessionTokenRequestData,
SessionTokenResponseData,
| {
"chunk": 4,
"crate": "connector-integration",
"enum_name": null,
"file_size": null,
"for_type": null,
"function_name": null,
"is_async": null,
"is_pub": null,
"lines": null,
"method_name": null,
"num_enums": 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.