id
stringlengths
20
153
type
stringclasses
1 value
granularity
stringclasses
14 values
content
stringlengths
16
84.3k
metadata
dict
connector-service_snippet_-7964693969177594414_325_50
clm
snippet
// connector-service/examples/example-tui/src/main.rs } 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" => {
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 50, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 325, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_350_15
clm
snippet
// connector-service/examples/example-tui/src/main.rs } "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;
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 15, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 350, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_350_30
clm
snippet
// connector-service/examples/example-tui/src/main.rs } "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;
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 30, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 350, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_350_50
clm
snippet
// connector-service/examples/example-tui/src/main.rs } "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)), } } // Async handler for gRPC calls async fn handle_call_async(args: &[String], ctx: &mut ShellContext) -> Result<String> { if args.len() < 2 { return Err(anyhow!( "Usage: call <operation>\nOperations: authorize, sync" ));
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 50, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 350, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_375_15
clm
snippet
// connector-service/examples/example-tui/src/main.rs 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()) }
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 15, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 375, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_375_30
clm
snippet
// connector-service/examples/example-tui/src/main.rs 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)), } } // Async handler for gRPC calls async fn handle_call_async(args: &[String], ctx: &mut ShellContext) -> Result<String> { 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
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 30, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 375, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_375_50
clm
snippet
// connector-service/examples/example-tui/src/main.rs 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)), } } // Async handler for gRPC calls async fn handle_call_async(args: &[String], ctx: &mut ShellContext) -> Result<String> { 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
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 50, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 375, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_400_15
clm
snippet
// connector-service/examples/example-tui/src/main.rs } 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()
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 15, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 400, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_400_30
clm
snippet
// connector-service/examples/example-tui/src/main.rs } 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()
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 30, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 400, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_400_50
clm
snippet
// connector-service/examples/example-tui/src/main.rs } 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()),
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 50, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 400, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_425_15
clm
snippet
// connector-service/examples/example-tui/src/main.rs .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
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 15, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 425, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_425_30
clm
snippet
// connector-service/examples/example-tui/src/main.rs .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(),
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 30, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 425, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_425_50
clm
snippet
// connector-service/examples/example-tui/src/main.rs .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),
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 50, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 425, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_450_15
clm
snippet
// connector-service/examples/example-tui/src/main.rs 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,
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 15, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 450, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_450_30
clm
snippet
// connector-service/examples/example-tui/src/main.rs 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,
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 30, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 450, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_450_50
clm
snippet
// connector-service/examples/example-tui/src/main.rs 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(
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 50, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 450, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_475_15
clm
snippet
// connector-service/examples/example-tui/src/main.rs 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);
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 15, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 475, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_475_30
clm
snippet
// connector-service/examples/example-tui/src/main.rs 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",
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 30, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 475, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_475_50
clm
snippet
// connector-service/examples/example-tui/src/main.rs 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!(
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 50, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 475, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_500_15
clm
snippet
// connector-service/examples/example-tui/src/main.rs "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 }
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 15, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 500, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_500_30
clm
snippet
// connector-service/examples/example-tui/src/main.rs "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() )), };
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 30, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 500, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_500_50
clm
snippet
// connector-service/examples/example-tui/src/main.rs "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)
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 50, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 500, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_525_15
clm
snippet
// connector-service/examples/example-tui/src/main.rs "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())?, );
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 15, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 525, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_525_30
clm
snippet
// connector-service/examples/example-tui/src/main.rs "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())) }
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 30, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 525, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_525_50
clm
snippet
// connector-service/examples/example-tui/src/main.rs "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 )), } } fn handle_show(ctx: &ShellContext) -> Result<String> { // Use Debug formatting which might produce multiple lines Ok(format!("{:#?}", ctx.state)) } // Updated help text for auth headerkey fn handle_help() -> Result<String> { // 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" +
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 50, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 525, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_550_15
clm
snippet
// connector-service/examples/example-tui/src/main.rs .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 )), } } fn handle_show(ctx: &ShellContext) -> Result<String> { // 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": null, "is_async": null, "is_pub": null, "lines": 15, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 550, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_550_30
clm
snippet
// connector-service/examples/example-tui/src/main.rs .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 )), } } fn handle_show(ctx: &ShellContext) -> Result<String> { // Use Debug formatting which might produce multiple lines Ok(format!("{:#?}", ctx.state)) } // Updated help text for auth headerkey fn handle_help() -> Result<String> { // 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
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 30, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 550, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_550_50
clm
snippet
// connector-service/examples/example-tui/src/main.rs .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 )), } } fn handle_show(ctx: &ShellContext) -> Result<String> { // Use Debug formatting which might produce multiple lines Ok(format!("{:#?}", ctx.state)) } // Updated help text for auth headerkey fn handle_help() -> Result<String> { // 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.") } // --- Shelgon Execute Implementation --- impl command::Execute for PaymentShellExecutor { type Context = ShellContext; fn prompt(&self, _ctx: &Self::Context) -> String {
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 50, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 550, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_575_15
clm
snippet
// connector-service/examples/example-tui/src/main.rs " 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" +
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 15, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 575, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_575_30
clm
snippet
// connector-service/examples/example-tui/src/main.rs " 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.") } // --- Shelgon Execute Implementation --- impl command::Execute for PaymentShellExecutor { type Context = ShellContext; fn prompt(&self, _ctx: &Self::Context) -> String { ">> ".to_string() } fn execute( &self,
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 30, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 575, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_575_50
clm
snippet
// connector-service/examples/example-tui/src/main.rs " 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.") } // --- Shelgon Execute Implementation --- impl command::Execute for PaymentShellExecutor { type Context = ShellContext; fn prompt(&self, _ctx: &Self::Context) -> String { ">> ".to_string() } fn execute( &self, ctx: &mut Self::Context, cmd_input: command::CommandInput, ) -> anyhow::Result<command::OutputAction> { 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")?;
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 50, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 575, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_600_15
clm
snippet
// connector-service/examples/example-tui/src/main.rs ">> ".to_string() } fn execute( &self, ctx: &mut Self::Context, cmd_input: command::CommandInput, ) -> anyhow::Result<command::OutputAction> { 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(),
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 15, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 600, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_600_30
clm
snippet
// connector-service/examples/example-tui/src/main.rs ">> ".to_string() } fn execute( &self, ctx: &mut Self::Context, cmd_input: command::CommandInput, ) -> anyhow::Result<command::OutputAction> { 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)),
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 30, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 600, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_600_50
clm
snippet
// connector-service/examples/example-tui/src/main.rs ">> ".to_string() } fn execute( &self, ctx: &mut Self::Context, cmd_input: command::CommandInput, ) -> anyhow::Result<command::OutputAction> { 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,
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 50, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 600, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_625_15
clm
snippet
// connector-service/examples/example-tui/src/main.rs 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 {
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 15, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 625, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_625_30
clm
snippet
// connector-service/examples/example-tui/src/main.rs 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)],
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 30, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 625, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_625_50
clm
snippet
// connector-service/examples/example-tui/src/main.rs 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)) } fn prepare(&self, cmd: &str) -> shelgon::Prepare { shelgon::Prepare { command: cmd.to_string(), stdin_required: false, } } fn completion( &self, _ctx: &Self::Context, incomplete_command: &str, ) -> anyhow::Result<(String, Vec<String>)> { let commands = ["set", "unset", "call", "show", "help", "exit", "clear"]; let mut completions = Vec::new();
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 50, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 625, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_650_15
clm
snippet
// connector-service/examples/example-tui/src/main.rs 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)) } fn prepare(&self, cmd: &str) -> shelgon::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": null, "is_async": null, "is_pub": null, "lines": 15, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 650, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_650_30
clm
snippet
// connector-service/examples/example-tui/src/main.rs 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)) } fn prepare(&self, cmd: &str) -> shelgon::Prepare { shelgon::Prepare { command: cmd.to_string(), stdin_required: false, } } fn completion( &self, _ctx: &Self::Context, incomplete_command: &str, ) -> anyhow::Result<(String, Vec<String>)> { 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());
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 30, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 650, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_650_50
clm
snippet
// connector-service/examples/example-tui/src/main.rs 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)) } fn prepare(&self, cmd: &str) -> shelgon::Prepare { shelgon::Prepare { command: cmd.to_string(), stdin_required: false, } } fn completion( &self, _ctx: &Self::Context, incomplete_command: &str, ) -> anyhow::Result<(String, Vec<String>)> { 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 {
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 50, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 650, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_675_15
clm
snippet
// connector-service/examples/example-tui/src/main.rs 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() {
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 15, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 675, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_675_30
clm
snippet
// connector-service/examples/example-tui/src/main.rs 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": null, "is_async": null, "is_pub": null, "lines": 30, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 675, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_675_50
clm
snippet
// connector-service/examples/example-tui/src/main.rs 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)) } } // --- Main Function --- fn main() -> anyhow::Result<()> { 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": null, "is_async": null, "is_pub": null, "lines": 50, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 675, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_700_15
clm
snippet
// connector-service/examples/example-tui/src/main.rs // TODO: Add argument completion } Ok((remaining, completions)) } } // --- Main Function --- fn main() -> anyhow::Result<()> { 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,
{ "chunk": null, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 15, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 700, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_700_30
clm
snippet
// connector-service/examples/example-tui/src/main.rs // TODO: Add argument completion } Ok((remaining, completions)) } } // --- Main Function --- fn main() -> anyhow::Result<()> { 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": null, "is_async": null, "is_pub": null, "lines": 25, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 700, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-7964693969177594414_700_50
clm
snippet
// connector-service/examples/example-tui/src/main.rs // TODO: Add argument completion } Ok((remaining, completions)) } } // --- Main Function --- fn main() -> anyhow::Result<()> { 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": null, "is_async": null, "is_pub": null, "lines": 25, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 700, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-6592229781991902862_0_15
clm
snippet
// connector-service/examples/example-rs/src/main.rs use rust_grpc_client::payments::{self, payment_service_client::PaymentServiceClient,Address, PhoneDetails}; use std::error::Error; #[tokio::main] async fn main() -> Result<(), Box<dyn Error>> { // Get the URL from command line arguments let args = std::env::args().collect::<Vec<_>>(); if args.len() < 2 { eprintln!("Usage: {} <url> [operation]", args[0]); eprintln!("Operations: authorize, sync"); std::process::exit(1); } let url = &args[1]; let operation = args.get(2).map(|s| s.as_str()).unwrap_or("authorize");
{ "chunk": null, "crate": "example-rs", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 15, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 0, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-6592229781991902862_0_30
clm
snippet
// connector-service/examples/example-rs/src/main.rs use rust_grpc_client::payments::{self, payment_service_client::PaymentServiceClient,Address, PhoneDetails}; use std::error::Error; #[tokio::main] async fn main() -> Result<(), Box<dyn Error>> { // Get the URL from command line arguments let args = std::env::args().collect::<Vec<_>>(); if args.len() < 2 { eprintln!("Usage: {} <url> [operation]", args[0]); eprintln!("Operations: authorize, sync"); std::process::exit(1); } let url = &args[1]; let operation = args.get(2).map(|s| s.as_str()).unwrap_or("authorize"); let response = match operation { "authorize" => { let auth_response = make_payment_authorization_request(url.to_string()).await?; format!("Authorization Response: {:?}", auth_response) } "sync" => { let sync_response = make_payment_sync_request(url.to_string()).await?; format!("Sync Response: {:?}", sync_response) } _ => { eprintln!( "Unknown operation: {}. Use 'authorize' or 'sync'.", operation );
{ "chunk": null, "crate": "example-rs", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 30, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 0, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-6592229781991902862_0_50
clm
snippet
// connector-service/examples/example-rs/src/main.rs use rust_grpc_client::payments::{self, payment_service_client::PaymentServiceClient,Address, PhoneDetails}; use std::error::Error; #[tokio::main] async fn main() -> Result<(), Box<dyn Error>> { // Get the URL from command line arguments let args = std::env::args().collect::<Vec<_>>(); if args.len() < 2 { eprintln!("Usage: {} <url> [operation]", args[0]); eprintln!("Operations: authorize, sync"); std::process::exit(1); } let url = &args[1]; let operation = args.get(2).map(|s| s.as_str()).unwrap_or("authorize"); let response = match operation { "authorize" => { let auth_response = make_payment_authorization_request(url.to_string()).await?; format!("Authorization Response: {:?}", auth_response) } "sync" => { let sync_response = make_payment_sync_request(url.to_string()).await?; format!("Sync Response: {:?}", sync_response) } _ => { eprintln!( "Unknown operation: {}. Use 'authorize' or 'sync'.", operation ); std::process::exit(1); } }; // Print the response println!("{}", response); Ok(()) } /// Creates a gRPC client and sends a payment authorization request async fn make_payment_authorization_request( url: String, ) -> Result<tonic::Response<payments::PaymentsAuthorizeResponse>, Box<dyn Error>> { // Create a gRPC client let mut client = PaymentServiceClient::connect(url).await?; let api_key = std::env::var("API_KEY").unwrap_or_else(|_| "default_api_key".to_string()); let key1 = std::env::var("KEY1").unwrap_or_else(|_| "default_key1".to_string()); println!("api_key is {} and key1 is {}", api_key,key1);
{ "chunk": null, "crate": "example-rs", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 50, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 0, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-6592229781991902862_25_15
clm
snippet
// connector-service/examples/example-rs/src/main.rs _ => { eprintln!( "Unknown operation: {}. Use 'authorize' or 'sync'.", operation ); std::process::exit(1); } }; // Print the response println!("{}", response); Ok(()) } /// Creates a gRPC client and sends a payment authorization request
{ "chunk": null, "crate": "example-rs", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 15, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 25, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-6592229781991902862_25_30
clm
snippet
// connector-service/examples/example-rs/src/main.rs _ => { eprintln!( "Unknown operation: {}. Use 'authorize' or 'sync'.", operation ); std::process::exit(1); } }; // Print the response println!("{}", response); Ok(()) } /// Creates a gRPC client and sends a payment authorization request async fn make_payment_authorization_request( url: String, ) -> Result<tonic::Response<payments::PaymentsAuthorizeResponse>, Box<dyn Error>> { // Create a gRPC client let mut client = PaymentServiceClient::connect(url).await?; let api_key = std::env::var("API_KEY").unwrap_or_else(|_| "default_api_key".to_string()); let key1 = std::env::var("KEY1").unwrap_or_else(|_| "default_key1".to_string()); println!("api_key is {} and key1 is {}", api_key,key1); // Create a request with the updated values let request = payments::PaymentsAuthorizeRequest { amount: 1000 as i64, currency: payments::Currency::Usd as i32, // connector: payments::Connector::Adyen as i32,
{ "chunk": null, "crate": "example-rs", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 30, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 25, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-6592229781991902862_25_50
clm
snippet
// connector-service/examples/example-rs/src/main.rs _ => { eprintln!( "Unknown operation: {}. Use 'authorize' or 'sync'.", operation ); std::process::exit(1); } }; // Print the response println!("{}", response); Ok(()) } /// Creates a gRPC client and sends a payment authorization request async fn make_payment_authorization_request( url: String, ) -> Result<tonic::Response<payments::PaymentsAuthorizeResponse>, Box<dyn Error>> { // Create a gRPC client let mut client = PaymentServiceClient::connect(url).await?; let api_key = std::env::var("API_KEY").unwrap_or_else(|_| "default_api_key".to_string()); let key1 = std::env::var("KEY1").unwrap_or_else(|_| "default_key1".to_string()); println!("api_key is {} and key1 is {}", api_key,key1); // Create a request with the updated values let request = payments::PaymentsAuthorizeRequest { amount: 1000 as i64, currency: payments::Currency::Usd as i32, // connector: payments::Connector::Adyen as i32, // auth_creds: Some(payments::AuthType { // auth_details: Some(payments::auth_type::AuthDetails::BodyKey( // Changed to BodyKey // payments::BodyKey { // api_key, // key1 // }, // )), // }), // connector: payments::Connector::Adyen as i32, // auth_creds: Some(payments::AuthType { // auth_details: Some(payments::auth_type::AuthDetails::BodyKey( // Changed to BodyKey // payments::BodyKey { // api_key, // key1 // }, // )), // }), payment_method: payments::PaymentMethod::Card as i32, payment_method_data: Some(payments::PaymentMethodData { data: Some(payments::payment_method_data::Data::Card(payments::Card {
{ "chunk": null, "crate": "example-rs", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 50, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 25, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-6592229781991902862_50_15
clm
snippet
// connector-service/examples/example-rs/src/main.rs // 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 {
{ "chunk": null, "crate": "example-rs", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 15, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 50, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-6592229781991902862_50_30
clm
snippet
// connector-service/examples/example-rs/src/main.rs // 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()
{ "chunk": null, "crate": "example-rs", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 30, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 50, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-6592229781991902862_50_50
clm
snippet
// connector-service/examples/example-rs/src/main.rs // 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
{ "chunk": null, "crate": "example-rs", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 50, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 50, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-6592229781991902862_75_15
clm
snippet
// connector-service/examples/example-rs/src/main.rs 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 }),
{ "chunk": null, "crate": "example-rs", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 15, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 75, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-6592229781991902862_75_30
clm
snippet
// connector-service/examples/example-rs/src/main.rs 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()),
{ "chunk": null, "crate": "example-rs", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 30, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 75, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-6592229781991902862_75_50
clm
snippet
// connector-service/examples/example-rs/src/main.rs 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
{ "chunk": null, "crate": "example-rs", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 50, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 75, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-6592229781991902862_100_15
clm
snippet
// connector-service/examples/example-rs/src/main.rs 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);
{ "chunk": null, "crate": "example-rs", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 15, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 100, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-6592229781991902862_100_30
clm
snippet
// connector-service/examples/example-rs/src/main.rs 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?;
{ "chunk": null, "crate": "example-rs", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 30, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 100, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-6592229781991902862_100_50
clm
snippet
// connector-service/examples/example-rs/src/main.rs user_agent: Some("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)".to_string()), accept_header: Some( "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8".to_string(), ), language: Some("en-US".to_string()), color_depth: Some(24), screen_height: Some(1080), screen_width: Some(1920), java_enabled: Some(false), ..Default::default() }), ..Default::default() }; let mut request = tonic::Request::new(request); request .metadata_mut() .append("x-connector", "adyen".parse().unwrap()); request .metadata_mut() .append("x-auth", "body-key".parse().unwrap()); request .metadata_mut() .append("x-api-key", api_key.parse().unwrap()); request .metadata_mut() .append("x-key1", key1.parse().unwrap()); // Send the request let response = client.payment_authorize(request).await?; Ok(response) } /// Creates a gRPC client and sends a payment sync request async fn make_payment_sync_request( url: String, ) -> Result<tonic::Response<payments::PaymentsSyncResponse>, Box<dyn Error>> { // Create a gRPC client let mut client = PaymentServiceClient::connect(url).await?; let resource_id = std::env::var("RESOURCE_ID").unwrap_or_else(|_| "pay_QHj9Thiy5mCC4Y".to_string()); let api_key = std::env::var("API_KEY").unwrap_or_else(|_| "default_api_key".to_string()); let key1 = std::env::var("KEY1").unwrap_or_else(|_| "default_key1".to_string()); // Create a request let request = payments::PaymentsSyncRequest { // connector: payments::Connector::Razorpay as i32,
{ "chunk": null, "crate": "example-rs", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 50, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 100, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-6592229781991902862_125_15
clm
snippet
// connector-service/examples/example-rs/src/main.rs .metadata_mut() .append("x-key1", key1.parse().unwrap()); // Send the request let response = client.payment_authorize(request).await?; Ok(response) } /// Creates a gRPC client and sends a payment sync request async fn make_payment_sync_request( url: String, ) -> Result<tonic::Response<payments::PaymentsSyncResponse>, Box<dyn Error>> { // Create a gRPC client let mut client = PaymentServiceClient::connect(url).await?;
{ "chunk": null, "crate": "example-rs", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 15, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 125, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-6592229781991902862_125_30
clm
snippet
// connector-service/examples/example-rs/src/main.rs .metadata_mut() .append("x-key1", key1.parse().unwrap()); // Send the request let response = client.payment_authorize(request).await?; Ok(response) } /// Creates a gRPC client and sends a payment sync request async fn make_payment_sync_request( url: String, ) -> Result<tonic::Response<payments::PaymentsSyncResponse>, Box<dyn Error>> { // Create a gRPC client let mut client = PaymentServiceClient::connect(url).await?; let resource_id = std::env::var("RESOURCE_ID").unwrap_or_else(|_| "pay_QHj9Thiy5mCC4Y".to_string()); let api_key = std::env::var("API_KEY").unwrap_or_else(|_| "default_api_key".to_string()); let key1 = std::env::var("KEY1").unwrap_or_else(|_| "default_key1".to_string()); // Create a request let request = payments::PaymentsSyncRequest { // connector: payments::Connector::Razorpay as i32, // auth_creds: Some(payments::AuthType { // auth_details: Some(payments::auth_type::AuthDetails::BodyKey( // payments::BodyKey { // api_key, // key1
{ "chunk": null, "crate": "example-rs", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 30, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 125, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-6592229781991902862_125_50
clm
snippet
// connector-service/examples/example-rs/src/main.rs .metadata_mut() .append("x-key1", key1.parse().unwrap()); // Send the request let response = client.payment_authorize(request).await?; Ok(response) } /// Creates a gRPC client and sends a payment sync request async fn make_payment_sync_request( url: String, ) -> Result<tonic::Response<payments::PaymentsSyncResponse>, Box<dyn Error>> { // Create a gRPC client let mut client = PaymentServiceClient::connect(url).await?; let resource_id = std::env::var("RESOURCE_ID").unwrap_or_else(|_| "pay_QHj9Thiy5mCC4Y".to_string()); let api_key = std::env::var("API_KEY").unwrap_or_else(|_| "default_api_key".to_string()); let key1 = std::env::var("KEY1").unwrap_or_else(|_| "default_key1".to_string()); // Create a request let request = payments::PaymentsSyncRequest { // connector: payments::Connector::Razorpay as i32, // auth_creds: Some(payments::AuthType { // auth_details: Some(payments::auth_type::AuthDetails::BodyKey( // payments::BodyKey { // api_key, // key1 // }, // )), // }), resource_id, connector_request_reference_id: Some("conn_req_abc".to_string()), }; let mut request = tonic::Request::new(request); request .metadata_mut() .append("x-connector", "razorpay".parse().unwrap()); request .metadata_mut() .append("x-auth", "body-key".parse().unwrap()); request .metadata_mut() .append("x-api-key", api_key.parse().unwrap()); request .metadata_mut() .append("x-key1", key1.parse().unwrap());
{ "chunk": null, "crate": "example-rs", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 50, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 125, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-6592229781991902862_150_15
clm
snippet
// connector-service/examples/example-rs/src/main.rs // 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()
{ "chunk": null, "crate": "example-rs", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 15, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 150, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-6592229781991902862_150_30
clm
snippet
// connector-service/examples/example-rs/src/main.rs // 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": null, "is_async": null, "is_pub": null, "lines": 30, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 150, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-6592229781991902862_150_50
clm
snippet
// connector-service/examples/example-rs/src/main.rs // 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": null, "is_async": null, "is_pub": null, "lines": 30, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 150, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_small_file_ucs_common_utils_-4191580895164688042
clm
small_file
// 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": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": 1388, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_small_file_ucs_common_utils_-6020438553597064532
clm
small_file
// 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 { 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": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": 5697, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_small_file_ucs_common_utils_4276938976373144801
clm
small_file
// 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"; /// 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": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": 7044, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_small_file_ucs_common_utils_1414821583984559341
clm
small_file
// 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, 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 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 { 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": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": 13885, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_small_file_ucs_common_utils_-4813005579221307816
clm
small_file
// 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 { 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 { 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": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": 9938, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_small_file_ucs_common_utils_-1874607272906183358
clm
small_file
// 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(); 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": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": 5620, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_small_file_ucs_common_utils_7052884170592430104
clm
small_file
// 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<'_>] { 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": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": 8127, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_small_file_ucs_common_utils_-5627216939917239271
clm
small_file
// 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()); 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": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": 7610, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_small_file_ucs_common_utils_8679312917364799131
clm
small_file
// 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": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": 1333, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_small_file_ucs_common_utils_6732291692182265096
clm
small_file
// 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": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": 4004, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_small_file_ucs_common_utils_2179811235784210369
clm
small_file
// 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 /// 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": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": 7538, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_small_file_ucs_common_utils_45732705880422454
clm
small_file
// 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": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": 2142, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_small_file_ucs_common_utils_-841769499540836508
clm
small_file
// 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 { 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"); 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 { 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": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": 13826, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_small_file_ucs_common_utils_5683649008329316125
clm
small_file
// 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": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": 4356, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_small_file_ucs_common_utils_2048526090272796786
clm
small_file
// 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}")) .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) { 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": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": 12890, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_small_file_ucs_common_utils_3964809568807133229
clm
small_file
// 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>, { 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": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": 7249, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_small_file_ucs_common_utils_-4895347235318218796
clm
small_file
// 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": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": 2603, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_small_file_ucs_common_utils_2591687643226154011
clm
small_file
// 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": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": 1159, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_small_file_ucs_common_utils_4154652033531294868
clm
small_file
// 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": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": 870, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_small_file_ucs_common_utils_-6586181602109849698
clm
small_file
// 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": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": 2823, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_small_file_ucs_common_utils_-1764418433195637174
clm
small_file
// 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": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": 1130, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_small_file_connector-integration_1661134184692456114
clm
small_file
// 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": null, "crate": "connector-integration", "enum_name": null, "file_size": 3482, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_small_file_connector-integration_-67203261144202079
clm
small_file
// 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": null, "crate": "connector-integration", "enum_name": null, "file_size": 1646, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_small_file_connector-integration_-2707148647924166777
clm
small_file
// connector-service/backend/connector-integration/src/lib.rs pub mod connectors; pub mod types; pub mod utils;
{ "chunk": null, "crate": "connector-integration", "enum_name": null, "file_size": 50, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_small_file_connector-integration_-4518986933431497461
clm
small_file
// 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, } } 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": null, "crate": "connector-integration", "enum_name": null, "file_size": 6906, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_small_file_connector-integration_-5409969266194052518
clm
small_file
// connector-service/backend/connector-integration/src/connectors/worldpay/response.rs use domain_types::errors; use error_stack::ResultExt; use hyperswitch_masking::Secret; use serde::{Deserialize, Serialize}; use url::Url; use super::requests::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct WorldpayPaymentsResponse { pub outcome: PaymentOutcome, pub transaction_reference: Option<String>, #[serde(rename = "_links", skip_serializing_if = "Option::is_none")] pub links: Option<SelfLink>, #[serde(rename = "_actions", skip_serializing_if = "Option::is_none")] pub actions: Option<ActionLinks>, #[serde(flatten)] pub other_fields: Option<WorldpayPaymentResponseFields>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(untagged)] pub enum WorldpayPaymentResponseFields { RefusedResponse(RefusedResponse), DDCResponse(DDCResponse), ThreeDsChallenged(ThreeDsChallengedResponse), FraudHighRisk(FraudHighRiskResponse), AuthorizedResponse(Box<AuthorizedResponse>), } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AuthorizedResponse { pub payment_instrument: PaymentsResPaymentInstrument, #[serde(skip_serializing_if = "Option::is_none")] pub issuer: Option<Issuer>, #[serde(skip_serializing_if = "Option::is_none")] pub scheme: Option<PaymentsResponseScheme>, #[serde(skip_serializing_if = "Option::is_none")] pub description: Option<String>, pub risk_factors: Option<Vec<RiskFactorsInner>>, pub fraud: Option<Fraud>, /// Mandate's token pub token: Option<MandateToken>, /// Network transaction ID pub scheme_reference: Option<Secret<String>>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct MandateToken { pub href: Secret<String>, pub token_id: String, pub token_expiry_date_time: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct FraudHighRiskResponse { pub score: f32, pub reason: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RefusedResponse { pub refusal_description: String, // Access Worldpay returns a raw response code in the refusalCode field (if enabled) containing the unmodified response code received either directly from the card scheme for Worldpay-acquired transactions, or from third party acquirers. pub refusal_code: String, pub risk_factors: Option<Vec<RiskFactorsInner>>, pub fraud: Option<Fraud>, #[serde(rename = "threeDS")] pub three_ds: Option<ThreeDsResponse>, pub advice: Option<Advice>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Advice { pub code: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ThreeDsResponse { pub outcome: String, pub issuer_response: IssuerResponse, pub version: Option<String>, pub eci: Option<String>, pub applied: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ThreeDsChallengedResponse { pub authentication: AuthenticationResponse, pub challenge: ThreeDsChallenge, #[serde(rename = "_actions")] pub actions: CompleteThreeDsActionLink, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AuthenticationResponse { pub version: String, pub eci: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ThreeDsChallenge { pub reference: String, pub url: Url, pub jwt: Secret<String>, pub payload: Secret<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CompleteThreeDsActionLink { #[serde(rename = "complete3dsChallenge")] pub complete_three_ds_challenge: ActionLink, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum IssuerResponse { Challenged, Frictionless, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct DDCResponse { pub device_data_collection: DDCToken, #[serde(rename = "_actions")] pub actions: DDCActionLink, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DDCToken { pub jwt: Secret<String>, pub url: Url, pub bin: Secret<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DDCActionLink { #[serde(rename = "supply3dsDeviceData")] pub supply_ddc_data: ActionLink, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum PaymentOutcome { #[serde(alias = "authorized", alias = "Authorized")] Authorized, Refused, SentForSettlement, SentForRefund, FraudHighRisk, #[serde(alias = "3dsDeviceDataRequired")] ThreeDsDeviceDataRequired, SentForCancellation, #[serde(alias = "3dsAuthenticationFailed")] ThreeDsAuthenticationFailed, SentForPartialRefund, #[serde(alias = "3dsChallenged")] ThreeDsChallenged, #[serde(alias = "3dsUnavailable")] ThreeDsUnavailable, } impl std::fmt::Display for PaymentOutcome { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Self::Authorized => write!(f, "authorized"), Self::Refused => write!(f, "refused"), Self::SentForSettlement => write!(f, "sentForSettlement"), Self::SentForRefund => write!(f, "sentForRefund"), Self::FraudHighRisk => write!(f, "fraudHighRisk"), Self::ThreeDsDeviceDataRequired => write!(f, "3dsDeviceDataRequired"), Self::SentForCancellation => write!(f, "sentForCancellation"), Self::ThreeDsAuthenticationFailed => write!(f, "3dsAuthenticationFailed"), Self::SentForPartialRefund => write!(f, "sentForPartialRefund"), Self::ThreeDsChallenged => write!(f, "3dsChallenged"), Self::ThreeDsUnavailable => write!(f, "3dsUnavailable"), } } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SelfLink { #[serde(rename = "self")] pub self_link: SelfLinkInner, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SelfLinkInner { pub href: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ActionLinks { supply_3ds_device_data: Option<ActionLink>, settle_payment: Option<ActionLink>, partially_settle_payment: Option<ActionLink>, refund_payment: Option<ActionLink>, partially_refund_payment: Option<ActionLink>, cancel_payment: Option<ActionLink>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ActionLink { pub href: String, pub method: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Fraud { pub outcome: FraudOutcome, pub score: f32, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum FraudOutcome { LowRisk, HighRisk, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct WorldpayEventResponse { pub last_event: EventType, #[serde(rename = "_links", skip_serializing_if = "Option::is_none")] pub links: Option<EventLinks>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub enum EventType { SentForAuthorization, #[serde(alias = "Authorized")] Authorized, #[serde(alias = "Sent for Settlement")] SentForSettlement, Settled, SettlementFailed, Cancelled, Error, Expired, Refused, #[serde(alias = "Sent for Refund")] SentForRefund, Refunded, RefundFailed, #[serde(other)] Unknown, } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] pub struct EventLinks { #[serde(rename = "payments:events", skip_serializing_if = "Option::is_none")] pub events: Option<String>, } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] pub struct PaymentLink { pub href: String, } pub fn get_resource_id<T, F>( response: WorldpayPaymentsResponse, connector_transaction_id: Option<String>, transform_fn: F, ) -> Result<T, error_stack::Report<errors::ConnectorError>> where F: Fn(String) -> T, { // First check top-level _links (for capture, authorize, etc.) let optional_reference_id = response .links .as_ref() .and_then(|link| link.self_link.href.rsplit_once('/').map(|(_, h)| h)) .or_else(|| { // Fallback to variant-specific logic for DDC and 3DS challenges response .other_fields .as_ref() .and_then(|other_fields| match other_fields { WorldpayPaymentResponseFields::DDCResponse(res) => { res.actions.supply_ddc_data.href.split('/').nth_back(1) } WorldpayPaymentResponseFields::ThreeDsChallenged(res) => res .actions .complete_three_ds_challenge .href .split('/') .nth_back(1), _ => None, }) }) .map(|href| { urlencoding::decode(href) .map(|s| transform_fn(s.into_owned())) .change_context(errors::ConnectorError::ResponseHandlingFailed) }) .transpose()?; optional_reference_id .or_else(|| response.transaction_reference.map(&transform_fn)) .or_else(|| connector_transaction_id.map(&transform_fn)) .ok_or_else(|| { errors::ConnectorError::MissingRequiredField { field_name: "_links.self.href or transactionReference", } .into() }) } pub struct ResponseIdStr { pub id: String, } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Issuer { pub authorization_code: Secret<String>, } impl Issuer { pub fn new(code: String) -> Self { Self { authorization_code: Secret::new(code), } } } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PaymentsResPaymentInstrument { #[serde(rename = "type")] pub payment_instrument_type: String, pub card_bin: Option<String>, pub last_four: Option<String>, pub expiry_date: Option<ExpiryDate>, pub card_brand: Option<String>, pub funding_type: Option<String>, pub category: Option<String>, pub issuer_name: Option<String>, pub payment_account_reference: Option<Secret<String>>, } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RiskFactorsInner { #[serde(rename = "type")] pub risk_type: RiskType, #[serde(skip_serializing_if = "Option::is_none")] pub detail: Option<Detail>, pub risk: Risk, } impl RiskFactorsInner { pub fn new(risk_type: RiskType, risk: Risk) -> Self { Self { risk_type, detail: None, risk, } } } #[derive( Clone, Copy, Default, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize, )] #[serde(rename_all = "camelCase")] pub enum RiskType { #[default] Avs, Cvc, RiskProfile, } #[derive( Clone, Copy, Default, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize, )] #[serde(rename_all = "lowercase")] pub enum Detail { #[default] Address, Postcode, } #[derive( Clone, Copy, Default, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize, )] #[serde(rename_all = "camelCase")] pub enum Risk { #[default] NotChecked, NotMatched, NotSupplied, VerificationFailed, } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] pub struct PaymentsResponseScheme { pub reference: String, } impl PaymentsResponseScheme { pub fn new(reference: String) -> Self { Self { reference } } } #[derive(Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub struct WorldpayErrorResponse { pub error_name: String, pub message: String, pub validation_errors: Option<serde_json::Value>, } impl WorldpayErrorResponse { pub fn default(status_code: u16) -> Self { match status_code { code @ 404 => Self { error_name: format!("{code} Not found"), message: "Resource not found".to_string(), validation_errors: None, }, code => Self { error_name: code.to_string(), message: "Unknown error".to_string(), validation_errors: None, }, } } } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct WorldpayWebhookTransactionId { pub event_details: EventDetails, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct EventDetails { #[serde(rename = "type")] pub event_type: EventType, pub transaction_reference: String, /// Mandate's token pub token: Option<MandateToken>, /// Network transaction ID pub scheme_reference: Option<Secret<String>>, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct WorldpayWebhookEventType { pub event_id: String, pub event_timestamp: String, pub event_details: EventDetails, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "camelCase")] pub enum WorldpayWebhookStatus { SentForSettlement, Authorized, SentForAuthorization, Cancelled, Error, Expired, Refused, SentForRefund, RefundFailed, } // Type aliases to avoid duplicate template structs in macro generation pub type WorldpayAuthorizeResponse = WorldpayPaymentsResponse; pub type WorldpaySyncResponse = WorldpayEventResponse; pub type WorldpayCaptureResponse = WorldpayPaymentsResponse; pub type WorldpayVoidResponse = WorldpayPaymentsResponse; pub type WorldpayRefundResponse = WorldpayPaymentsResponse; pub type WorldpayRefundSyncResponse = WorldpayEventResponse; pub type WorldpayAuthenticateResponse = WorldpayPaymentsResponse; pub type WorldpayPreAuthenticateResponse = WorldpayPaymentsResponse; pub type WorldpayPostAuthenticateResponse = WorldpayPaymentsResponse; pub type WorldpayRepeatPaymentResponse = WorldpayPaymentsResponse;
{ "chunk": null, "crate": "connector-integration", "enum_name": null, "file_size": 14839, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_small_file_connector-integration_426009472564931438
clm
small_file
// connector-service/backend/connector-integration/src/connectors/worldpay/requests.rs use common_utils::types::MinorUnit; use hyperswitch_masking::Secret; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct WorldpayAuthorizeRequest< T: domain_types::payment_method_data::PaymentMethodDataTypes + std::fmt::Debug + std::marker::Sync + std::marker::Send + 'static + serde::Serialize, > { pub transaction_reference: String, pub merchant: Merchant, pub instruction: Instruction<T>, #[serde(skip_serializing_if = "Option::is_none")] pub customer: Option<Customer>, } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Merchant { pub entity: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] pub mcc: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub payment_facilitator: Option<PaymentFacilitator>, } #[derive(Clone, Debug, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct Instruction< T: domain_types::payment_method_data::PaymentMethodDataTypes + std::fmt::Debug + std::marker::Sync + std::marker::Send + 'static + serde::Serialize, > { #[serde(skip_serializing_if = "Option::is_none")] pub settlement: Option<AutoSettlement>, pub method: PaymentMethod, pub payment_instrument: PaymentInstrument<T>, pub narrative: InstructionNarrative, pub value: PaymentValue, #[serde(skip_serializing_if = "Option::is_none")] pub debt_repayment: Option<bool>, #[serde(rename = "threeDS", skip_serializing_if = "Option::is_none")] pub three_ds: Option<ThreeDSRequest>, /// For setting up mandates pub token_creation: Option<TokenCreation>, /// For specifying CIT vs MIT pub customer_agreement: Option<CustomerAgreement>, } #[derive(Clone, Debug, PartialEq, Serialize)] pub struct TokenCreation { #[serde(rename = "type")] pub token_type: TokenCreationType, } #[derive(Clone, Debug, PartialEq, Serialize)] #[serde(rename_all = "lowercase")] pub enum TokenCreationType { Worldpay, } #[serde_with::skip_serializing_none] #[derive(Clone, Debug, PartialEq, Serialize)] #[serde(rename_all = "camelCase")] pub struct CustomerAgreement { #[serde(rename = "type")] pub agreement_type: CustomerAgreementType, pub stored_card_usage: Option<StoredCardUsageType>, #[serde(skip_serializing_if = "Option::is_none")] pub scheme_reference: Option<Secret<String>>, } #[derive(Clone, Debug, PartialEq, Serialize)] #[serde(rename_all = "lowercase")] pub enum CustomerAgreementType { Subscription, Unscheduled, } #[derive(Clone, Debug, PartialEq, Serialize)] #[serde(rename_all = "lowercase")] pub enum StoredCardUsageType { First, Subsequent, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(untagged)] pub enum PaymentInstrument< T: domain_types::payment_method_data::PaymentMethodDataTypes + std::fmt::Debug + std::marker::Sync + std::marker::Send + 'static + serde::Serialize, > { Card(CardPayment<T>), CardToken(CardToken), RawCardForNTI(RawCardDetails<domain_types::payment_method_data::DefaultPCIHolder>), Googlepay(WalletPayment), Applepay(WalletPayment), } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CardPayment< T: domain_types::payment_method_data::PaymentMethodDataTypes + std::fmt::Debug + std::marker::Sync + std::marker::Send + 'static + serde::Serialize, > { #[serde(flatten)] pub raw_card_details: RawCardDetails<T>, pub cvc: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] pub card_holder_name: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] pub billing_address: Option<BillingAddress>, } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RawCardDetails< T: domain_types::payment_method_data::PaymentMethodDataTypes + std::fmt::Debug + std::marker::Sync + std::marker::Send + 'static + serde::Serialize, > { #[serde(rename = "type")] pub payment_type: PaymentType, pub card_number: domain_types::payment_method_data::RawCardNumber<T>, pub expiry_date: ExpiryDate, } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct CardToken { #[serde(rename = "type")] pub payment_type: PaymentType, pub href: String, #[serde(skip_serializing_if = "Option::is_none")] pub cvc: Option<Secret<String>>, } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct WalletPayment { #[serde(rename = "type")] pub payment_type: PaymentType, pub wallet_token: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] pub billing_address: Option<BillingAddress>, } #[derive( Clone, Copy, Debug, Eq, Default, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize, )] #[serde(rename_all = "lowercase")] pub enum PaymentType { #[default] Plain, Token, Encrypted, Checkout, } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] pub struct ExpiryDate { pub month: Secret<i8>, pub year: Secret<i32>, } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BillingAddress { pub address1: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] pub address2: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] pub address3: Option<Secret<String>>, pub city: String, #[serde(skip_serializing_if = "Option::is_none")] pub state: Option<Secret<String>>, pub postal_code: Secret<String>, pub country_code: common_enums::CountryAlpha2, } #[derive( Clone, Copy, Default, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize, )] #[serde(rename_all = "camelCase")] pub enum Channel { #[default] Ecom, Moto, } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct Customer { #[serde(skip_serializing_if = "Option::is_none")] pub risk_profile: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub authentication: Option<CustomerAuthentication>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum CustomerAuthentication { ThreeDS(ThreeDS), Token(NetworkToken), } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ThreeDS { #[serde(skip_serializing_if = "Option::is_none")] pub authentication_value: Option<Secret<String>>, pub version: ThreeDSVersion, #[serde(skip_serializing_if = "Option::is_none")] pub transaction_id: Option<String>, pub eci: String, #[serde(rename = "type")] pub auth_type: CustomerAuthType, } #[derive( Clone, Copy, Default, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize, )] pub enum ThreeDSVersion { #[default] #[serde(rename = "1")] One, #[serde(rename = "2")] Two, } #[derive( Clone, Copy, Default, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize, )] pub enum CustomerAuthType { #[serde(rename = "3DS")] #[default] Variant3Ds, #[serde(rename = "card/networkToken")] NetworkToken, } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NetworkToken { #[serde(rename = "type")] pub auth_type: CustomerAuthType, pub authentication_value: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] pub eci: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct AutoSettlement { pub auto: bool, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ThreeDSRequest { #[serde(rename = "type")] pub three_ds_type: String, pub mode: String, pub device_data: ThreeDSRequestDeviceData, pub challenge: ThreeDSRequestChallenge, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ThreeDSRequestDeviceData { pub accept_header: String, pub user_agent_header: String, pub browser_language: Option<String>, pub browser_screen_width: Option<u32>, pub browser_screen_height: Option<u32>, pub browser_color_depth: Option<String>, pub time_zone: Option<String>, pub browser_java_enabled: Option<bool>, pub browser_javascript_enabled: Option<bool>, pub channel: Option<ThreeDSRequestChannel>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum ThreeDSRequestChannel { Browser, Native, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ThreeDSRequestChallenge { pub return_url: String, #[serde(skip_serializing_if = "Option::is_none")] pub preference: Option<String>, } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum PaymentMethod { #[default] Card, ApplePay, GooglePay, } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct InstructionNarrative { pub line1: String, } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] pub struct PaymentValue { pub amount: MinorUnit, pub currency: common_enums::Currency, } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct PaymentFacilitator { pub pf_id: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] pub iso_id: Option<Secret<String>>, pub sub_merchant: SubMerchant, } #[derive(Clone, Debug, PartialEq, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SubMerchant { pub city: String, pub name: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] pub state: Option<String>, pub postal_code: Secret<String>, pub merchant_id: Secret<String>, pub country_code: String, pub street: Secret<String>, #[serde(skip_serializing_if = "Option::is_none")] pub tax_id: Option<Secret<String>>, } #[derive(Default, Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct WorldpayPartialRequest { #[serde(skip_serializing_if = "Option::is_none")] pub value: Option<PaymentValue>, #[serde(skip_serializing_if = "Option::is_none")] pub reference: Option<String>, } // Type aliases to avoid duplicate template structs in macro generation pub type WorldpayCaptureRequest = WorldpayPartialRequest; pub type WorldpayRefundRequest = WorldpayPartialRequest; pub(super) const THREE_DS_MODE: &str = "always"; pub(super) const THREE_DS_TYPE: &str = "integrated"; pub(super) const THREE_DS_CHALLENGE_PREFERENCE: &str = "challengeMandated"; #[derive(Clone, Debug, Default, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct WorldpayAuthenticateRequest { #[serde(skip_serializing_if = "Option::is_none")] pub collection_reference: Option<String>, } // Type aliases to avoid duplicate template structs in macro generation pub type WorldpayPreAuthenticateRequest = WorldpayAuthenticateRequest; pub type WorldpayPostAuthenticateRequest = WorldpayAuthenticateRequest; // RepeatPayment uses the same request structure as Authorize (MIT vs CIT) pub type WorldpayRepeatPaymentRequest<T> = WorldpayAuthorizeRequest<T>;
{ "chunk": null, "crate": "connector-integration", "enum_name": null, "file_size": 11993, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_small_file_connector-integration_-7118378565780451163
clm
small_file
// connector-service/backend/connector-integration/src/connectors/phonepe/constants.rs //! Constants for PhonePe connector // ===== API ENDPOINTS ===== pub const API_PAY_ENDPOINT: &str = "pg/v1/pay"; pub const API_STATUS_ENDPOINT: &str = "pg/v1/status"; // ===== UPI INSTRUMENT TYPES ===== pub const UPI_INTENT: &str = "UPI_INTENT"; pub const UPI_COLLECT: &str = "UPI_COLLECT"; pub const UPI_QR: &str = "UPI_QR"; // ===== DEFAULT VALUES ===== pub const DEFAULT_KEY_INDEX: &str = "1"; pub const DEFAULT_DEVICE_OS: &str = "Android"; pub const DEFAULT_IP: &str = "127.0.0.1"; pub const DEFAULT_USER_AGENT: &str = "Mozilla/5.0"; // ===== CHECKSUM ===== pub const CHECKSUM_SEPARATOR: &str = "###"; // ===== CONTENT TYPES ===== pub const APPLICATION_JSON: &str = "application/json";
{ "chunk": null, "crate": "connector-integration", "enum_name": null, "file_size": 695, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_small_file_connector-integration_6052179881447595478
clm
small_file
// connector-service/backend/connector-integration/src/connectors/phonepe/headers.rs //! Header constants for PhonePe connector pub const CONTENT_TYPE: &str = "Content-Type"; pub const AUTHORIZATION: &str = "Authorization"; pub const X_VERIFY: &str = "X-VERIFY"; pub const X_MERCHANT_ID: &str = "X-MERCHANT-ID";
{ "chunk": null, "crate": "connector-integration", "enum_name": null, "file_size": 228, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_small_file_connector-integration_-7174082965644870196
clm
small_file
// connector-service/backend/connector-integration/src/connectors/payload/responses.rs use common_utils::FloatMajorUnit; use hyperswitch_masking::Secret; use serde::{Deserialize, Serialize}; // PaymentsResponse #[derive(Default, Debug, Clone, Copy, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] pub enum PayloadPaymentStatus { Authorized, Declined, Processed, #[default] Processing, Rejected, Voided, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum PayloadPaymentsResponse { PayloadCardsResponse(PayloadCardsResponseData), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "snake_case")] pub enum AvsResponse { Unknown, NoMatch, Zip, Street, StreetAndZip, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct PayloadCardsResponseData { pub amount: FloatMajorUnit, pub avs: Option<AvsResponse>, pub customer_id: Option<Secret<String>>, #[serde(rename = "id")] pub transaction_id: String, #[serde(rename = "payment_method_id")] pub connector_payment_method_id: Option<Secret<String>>, pub processing_id: Option<Secret<String>>, pub processing_method_id: Option<String>, pub ref_number: Option<String>, pub status: PayloadPaymentStatus, pub status_code: Option<String>, pub status_message: Option<String>, #[serde(rename = "type")] pub response_type: Option<String>, } // Type definition for Refund Response // Added based on assumptions since this is not provided in the documentation #[derive(Debug, Copy, Serialize, Default, Deserialize, Clone)] #[serde(rename_all = "snake_case")] pub enum RefundStatus { Declined, Processed, #[default] Processing, Rejected, } #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct RefundsLedger { pub amount: FloatMajorUnit, #[serde(rename = "assoc_transaction_id")] pub associated_transaction_id: String, // Connector transaction id #[serde(rename = "id")] pub ledger_id: Secret<String>, } #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct PayloadRefundResponse { pub amount: FloatMajorUnit, #[serde(rename = "id")] pub transaction_id: String, pub ledger: Vec<RefundsLedger>, #[serde(rename = "payment_method_id")] pub connector_payment_method_id: Option<Secret<String>>, pub processing_id: Option<Secret<String>>, pub ref_number: Option<String>, pub status: RefundStatus, pub status_code: Option<String>, pub status_message: Option<String>, } #[derive(Default, Debug, Serialize, Deserialize, PartialEq)] pub struct PayloadErrorResponse { pub error_type: String, pub error_description: String, pub object: String, /// Payload returns arbitrary details in JSON format pub details: Option<serde_json::Value>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "snake_case")] pub enum PayloadWebhooksTrigger { Payment, Processed, Authorized, Credit, Refund, Reversal, Void, AutomaticPayment, Decline, Deposit, Reject, #[serde(rename = "payment_activation:status")] PaymentActivationStatus, #[serde(rename = "payment_link:status")] PaymentLinkStatus, ProcessingStatus, BankAccountReject, Chargeback, ChargebackReversal, #[serde(rename = "transaction:operation")] TransactionOperation, #[serde(rename = "transaction:operation:clear")] TransactionOperationClear, } // Webhook response structures #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PayloadWebhookEvent { pub object: String, // Added to match actual webhook structure pub trigger: PayloadWebhooksTrigger, pub webhook_id: String, pub triggered_at: String, // Added to match actual webhook structure // Webhooks Payload pub triggered_on: PayloadEventDetails, pub url: String, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct PayloadEventDetails { #[serde(rename = "id")] pub transaction_id: Option<String>, pub object: String, pub value: Option<serde_json::Value>, // Changed to handle any value type including null } // Type aliases to avoid duplicate templating types in macro pub type PayloadAuthorizeResponse = PayloadPaymentsResponse; pub type PayloadPSyncResponse = PayloadPaymentsResponse; pub type PayloadCaptureResponse = PayloadPaymentsResponse; pub type PayloadVoidResponse = PayloadPaymentsResponse; pub type PayloadSetupMandateResponse = PayloadPaymentsResponse; pub type PayloadRepeatPaymentResponse = PayloadPaymentsResponse; pub type PayloadRSyncResponse = PayloadRefundResponse;
{ "chunk": null, "crate": "connector-integration", "enum_name": null, "file_size": 4654, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_small_file_connector-integration_-6316223293833694220
clm
small_file
// connector-service/backend/connector-integration/src/connectors/payload/requests.rs use common_utils::types::FloatMajorUnit; use domain_types::payment_method_data::{PaymentMethodDataTypes, RawCardNumber}; use hyperswitch_masking::Secret; use serde::{Deserialize, Serialize}; use crate::connectors::payload::responses; #[derive(Debug, Serialize, PartialEq)] #[serde(untagged)] pub enum PayloadPaymentsRequest<T: PaymentMethodDataTypes> { PayloadCardsRequest(Box<PayloadCardsRequestData<T>>), PayloadMandateRequest(Box<PayloadMandateRequestData>), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "snake_case")] pub enum TransactionTypes { Credit, Chargeback, ChargebackReversal, Deposit, Payment, Refund, Reversal, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct BillingAddress { #[serde(rename = "payment_method[billing_address][city]")] pub city: String, #[serde(rename = "payment_method[billing_address][country_code]")] pub country: common_enums::CountryAlpha2, #[serde(rename = "payment_method[billing_address][postal_code]")] pub postal_code: Secret<String>, #[serde(rename = "payment_method[billing_address][state_province]")] pub state_province: Secret<String>, #[serde(rename = "payment_method[billing_address][street_address]")] pub street_address: Secret<String>, } #[derive(Debug, Clone, Serialize, PartialEq)] pub struct PayloadCardsRequestData<T: PaymentMethodDataTypes> { pub amount: FloatMajorUnit, #[serde(flatten)] pub card: PayloadCard<T>, #[serde(rename = "type")] pub transaction_types: TransactionTypes, // For manual capture, set status to "authorized", otherwise omit #[serde(skip_serializing_if = "Option::is_none")] pub status: Option<responses::PayloadPaymentStatus>, #[serde(rename = "payment_method[type]")] pub payment_method_type: String, // Billing address fields are for AVS validation #[serde(flatten)] pub billing_address: BillingAddress, pub processing_id: Option<Secret<String>>, /// Allows one-time payment by customer without saving their payment method /// This is true by default #[serde(rename = "payment_method[keep_active]")] pub keep_active: bool, } #[derive(Debug, Clone, Serialize, PartialEq)] pub struct PayloadMandateRequestData { pub amount: FloatMajorUnit, #[serde(rename = "type")] pub transaction_types: TransactionTypes, // Based on the connectors' response, we can do recurring payment either based on a default payment method id saved in the customer profile or a specific payment method id // Connector by default, saves every payment method pub payment_method_id: Secret<String>, // For manual capture, set status to "authorized", otherwise omit #[serde(skip_serializing_if = "Option::is_none")] pub status: Option<responses::PayloadPaymentStatus>, } #[derive(Default, Clone, Debug, Serialize, Eq, PartialEq)] pub struct PayloadCard<T: PaymentMethodDataTypes> { #[serde(rename = "payment_method[card][card_number]")] pub number: RawCardNumber<T>, #[serde(rename = "payment_method[card][expiry]")] pub expiry: Secret<String>, #[serde(rename = "payment_method[card][card_code]")] pub cvc: Secret<String>, } #[derive(Clone, Debug, Serialize, PartialEq)] pub struct PayloadVoidRequest { pub status: responses::PayloadPaymentStatus, } // Type definition for CaptureRequest #[derive(Clone, Debug, Serialize, PartialEq)] pub struct PayloadCaptureRequest { pub status: responses::PayloadPaymentStatus, } // Type definition for RefundRequest #[derive(Debug, Serialize)] pub struct PayloadRefundRequest { #[serde(rename = "type")] pub transaction_type: TransactionTypes, pub amount: FloatMajorUnit, #[serde(rename = "ledger[0][assoc_transaction_id]")] pub ledger_assoc_transaction_id: String, } // Type alias for RepeatPayment request (same structure as PayloadPaymentsRequest) pub type PayloadRepeatPaymentRequest<T> = PayloadPaymentsRequest<T>;
{ "chunk": null, "crate": "connector-integration", "enum_name": null, "file_size": 4014, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_small_file_connector-integration_-3671819979525078476
clm
small_file
// connector-service/backend/connector-integration/src/connectors/bluecode/test.rs #[cfg(test)] mod tests { pub mod authorize { use std::{borrow::Cow, marker::PhantomData}; use common_utils::{ pii::{self, Email}, request::RequestContent, types::MinorUnit, }; use domain_types::{ self, connector_flow::Authorize, connector_types::{ ConnectorEnum, PaymentFlowData, PaymentsAuthorizeData, PaymentsResponseData, }, payment_method_data::{DefaultPCIHolder, PaymentMethodData, WalletData}, router_data::{ConnectorAuthType, ErrorResponse}, router_data_v2::RouterDataV2, types::{ConnectorParams, Connectors}, }; use hyperswitch_masking::Secret; use interfaces::{ connector_integration_v2::BoxedConnectorIntegrationV2, connector_types::BoxedConnector, }; use serde_json::json; use crate::{connectors::Bluecode, types::ConnectorData}; #[test] fn test_build_request_valid() { let api_key = "test_bluecode_api_key".to_string(); let req: RouterDataV2< Authorize, PaymentFlowData, PaymentsAuthorizeData<DefaultPCIHolder>, PaymentsResponseData, > = RouterDataV2 { flow: PhantomData::<domain_types::connector_flow::Authorize>, resource_common_data: PaymentFlowData { vault_headers: None, merchant_id: common_utils::id_type::MerchantId::default(), customer_id: None, connector_customer: Some("conn_cust_987654".to_string()), payment_id: "pay_abcdef123456".to_string(), attempt_id: "attempt_123456abcdef".to_string(), status: common_enums::AttemptStatus::Pending, payment_method: common_enums::PaymentMethod::Wallet, description: Some("Payment for order #12345".to_string()), return_url: Some("https://www.google.com".to_string()), address: domain_types::payment_address::PaymentAddress::new( None, Some(domain_types::payment_address::Address { address: Some(domain_types::payment_address::AddressDetails { first_name: Some(Secret::new("John".to_string())), last_name: Some(Secret::new("Doe".to_string())), line1: Some(Secret::new("123 Main St".to_string())), city: Some("Anytown".to_string()), zip: Some(Secret::new("12345".to_string())), country: Some(common_enums::CountryAlpha2::US), ..Default::default() }), phone: None, email: None, }), None, None, ), auth_type: common_enums::AuthenticationType::NoThreeDs, connector_meta_data: Some(pii::SecretSerdeValue::new( serde_json::json!({ "shop_name": "test_shop" }), )), amount_captured: None, minor_amount_captured: None, access_token: None, session_token: None, reference_id: None, payment_method_token: None, preprocessing_id: None, connector_api_version: None, connector_request_reference_id: "conn_ref_123456789".to_string(), test_mode: None, connector_http_status_code: None, connectors: Connectors { bluecode: ConnectorParams { base_url: "https://api.bluecode.com/".to_string(), dispute_base_url: None, ..Default::default() }, ..Default::default() }, external_latency: None, connector_response_headers: None, raw_connector_response: None, raw_connector_request: None, minor_amount_capturable: None, connector_response: None, recurring_mandate_payment_data: None, }, connector_auth_type: ConnectorAuthType::HeaderKey { api_key: Secret::new(api_key), }, request: PaymentsAuthorizeData { authentication_data: None, access_token: None, payment_method_data: PaymentMethodData::Wallet(WalletData::BluecodeRedirect {}), amount: 1000, order_tax_amount: None, email: Some( Email::try_from("test@example.com".to_string()) .expect("Failed to parse email"), ), customer_name: None, currency: common_enums::Currency::USD, confirm: true, statement_descriptor_suffix: None, statement_descriptor: None, capture_method: None, integrity_object: None, router_return_url: Some("https://www.google.com".to_string()), webhook_url: Some("https://webhook.site/".to_string()), complete_authorize_url: None, mandate_id: None, setup_future_usage: None, off_session: None, browser_info: None, order_category: None, session_token: None, enrolled_for_3ds: false, related_transaction_id: None, payment_experience: None, payment_method_type: None, customer_id: Some( common_utils::id_type::CustomerId::try_from(Cow::from( "cus_123456789".to_string(), )) .unwrap(), ), request_incremental_authorization: false, metadata: None, minor_amount: MinorUnit::new(1000), merchant_order_reference_id: None, shipping_cost: None, merchant_account_id: None, merchant_config_currency: None, all_keys_required: None, customer_acceptance: None, split_payments: None, request_extended_authorization: None, setup_mandate_details: None, enable_overcapture: None, merchant_account_metadata: None, }, response: Err(ErrorResponse::default()), }; let connector: BoxedConnector<DefaultPCIHolder> = Box::new(Bluecode::new()); let connector_data = ConnectorData { connector, connector_name: ConnectorEnum::Bluecode, }; let connector_integration: BoxedConnectorIntegrationV2< '_, Authorize, PaymentFlowData, PaymentsAuthorizeData<DefaultPCIHolder>, PaymentsResponseData, > = connector_data.connector.get_connector_integration_v2(); let request = connector_integration.build_request_v2(&req).unwrap(); let req_body = request.as_ref().map(|request_val| { let masked_request = match request_val.body.as_ref() { Some(request_content) => match request_content { RequestContent::Json(i) | RequestContent::FormUrlEncoded(i) | RequestContent::Xml(i) => i.masked_serialize().unwrap_or( json!({ "error": "failed to mask serialize connector request"}), ), RequestContent::FormData(_) => json!({"request_type": "FORM_DATA"}), RequestContent::RawBytes(_) => json!({"request_type": "RAW_BYTES"}), }, None => serde_json::Value::Null, }; masked_request }); println!("request: {req_body:?}"); assert_eq!( req_body.as_ref().unwrap()["reference"], "conn_ref_123456789" ); } #[test] fn test_build_request_missing_fields() { let api_key = "test_bluecode_api_key_missing".to_string(); let req: RouterDataV2< Authorize, PaymentFlowData, PaymentsAuthorizeData<DefaultPCIHolder>, PaymentsResponseData, > = RouterDataV2 { flow: PhantomData::<Authorize>, resource_common_data: PaymentFlowData { vault_headers: None, merchant_id: common_utils::id_type::MerchantId::default(), customer_id: None, connector_customer: None, payment_id: "".to_string(), attempt_id: "".to_string(), status: common_enums::AttemptStatus::Pending, payment_method: common_enums::PaymentMethod::Wallet, description: None, return_url: None, address: domain_types::payment_address::PaymentAddress::new( None, None, None, None, ), auth_type: common_enums::AuthenticationType::NoThreeDs, connector_meta_data: None, amount_captured: None, minor_amount_captured: None, access_token: None, session_token: None, reference_id: None, payment_method_token: None, preprocessing_id: None, connector_api_version: None, connector_request_reference_id: "".to_string(), test_mode: None, connector_http_status_code: None, connectors: Connectors { bluecode: ConnectorParams { base_url: "https://api.bluecode.com/".to_string(), dispute_base_url: None, ..Default::default() }, ..Default::default() }, external_latency: None, connector_response_headers: None, raw_connector_response: None, raw_connector_request: None, minor_amount_capturable: None, connector_response: None, recurring_mandate_payment_data: None, }, connector_auth_type: ConnectorAuthType::HeaderKey { api_key: Secret::new(api_key), }, request: PaymentsAuthorizeData { authentication_data: None, access_token: None, payment_method_data: PaymentMethodData::Wallet(WalletData::BluecodeRedirect {}), amount: 0, order_tax_amount: None, email: None, customer_name: None, currency: common_enums::Currency::USD, confirm: true, statement_descriptor_suffix: None, statement_descriptor: None, capture_method: None, router_return_url: None, webhook_url: None, complete_authorize_url: None, mandate_id: None, setup_future_usage: None, off_session: None, browser_info: None, integrity_object: None, order_category: None, session_token: None, enrolled_for_3ds: false, related_transaction_id: None, payment_experience: None, payment_method_type: None, customer_id: None, request_incremental_authorization: false, metadata: None, minor_amount: MinorUnit::new(0), merchant_order_reference_id: None, shipping_cost: None, merchant_account_id: None, merchant_config_currency: None, all_keys_required: None, customer_acceptance: None, split_payments: None, request_extended_authorization: None, setup_mandate_details: None, enable_overcapture: None, merchant_account_metadata: None, }, response: Err(ErrorResponse::default()), }; let connector: BoxedConnector<DefaultPCIHolder> = Box::new(Bluecode::new()); let connector_data = ConnectorData { connector, connector_name: ConnectorEnum::Bluecode, }; let connector_integration: BoxedConnectorIntegrationV2< '_, Authorize, PaymentFlowData, PaymentsAuthorizeData<DefaultPCIHolder>, PaymentsResponseData, > = connector_data.connector.get_connector_integration_v2(); let result = connector_integration.build_request_v2(&req); assert!(result.is_err(), "Expected error for missing fields"); } } }
{ "chunk": null, "crate": "connector-integration", "enum_name": null, "file_size": 14410, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_small_file_connector-integration_306050111147943451
clm
small_file
// connector-service/backend/connector-integration/src/connectors/bluecode/transformers.rs use common_enums::{self, enums, AttemptStatus}; use common_utils::{ consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE}, pii, request::Method, types::FloatMajorUnit, }; use domain_types::{ connector_flow::Authorize, connector_types::{ PaymentFlowData, PaymentsAuthorizeData, PaymentsResponseData, PaymentsSyncData, ResponseId, }, errors::{self}, payment_method_data::{PaymentMethodData, PaymentMethodDataTypes, WalletData}, router_data::{ConnectorAuthType, ErrorResponse}, router_data_v2::RouterDataV2, }; use error_stack::ResultExt; use hyperswitch_masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; use crate::types::ResponseRouterData; // Auth pub struct BluecodeAuthType { pub(super) api_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for BluecodeAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::HeaderKey { api_key } => Ok(Self { api_key: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } // Requests #[derive(Debug, Serialize)] pub struct BluecodePaymentsRequest { pub amount: FloatMajorUnit, pub currency: enums::Currency, pub payment_provider: String, pub shop_name: String, pub reference: String, pub ip_address: Option<Secret<String, pii::IpAddress>>, pub first_name: Secret<String>, pub last_name: Secret<String>, pub billing_address_country_code_iso: enums::CountryAlpha2, pub billing_address_city: String, pub billing_address_line1: Secret<String>, pub billing_address_postal_code: Option<Secret<String>>, pub webhook_url: url::Url, pub success_url: url::Url, pub failure_url: url::Url, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct BluecodeWebhookResponse { pub id: Option<i64>, pub order_id: String, pub user_id: Option<i64>, pub customer_id: Option<String>, pub customer_email: Option<common_utils::Email>, pub customer_phone: Option<Secret<String>>, pub status: BluecodePaymentStatus, pub payment_provider: Option<String>, pub payment_connector: Option<String>, pub payment_method: Option<String>, pub payment_method_type: Option<String>, pub shop_name: Option<String>, pub sender_name: Option<String>, pub sender_email: Option<String>, pub description: Option<String>, pub amount: FloatMajorUnit, pub currency: enums::Currency, pub charged_amount: Option<FloatMajorUnit>, pub charged_amount_currency: Option<String>, pub charged_fx_amount: Option<FloatMajorUnit>, pub charged_fx_amount_currency: Option<enums::Currency>, pub is_underpaid: Option<bool>, pub billing_amount: Option<FloatMajorUnit>, pub billing_currency: Option<String>, pub language: Option<String>, pub ip_address: Option<Secret<String, common_utils::pii::IpAddress>>, pub first_name: Option<Secret<String>>, pub last_name: Option<Secret<String>>, pub billing_address_line1: Option<Secret<String>>, pub billing_address_city: Option<Secret<String>>, pub billing_address_postal_code: Option<Secret<String>>, pub billing_address_country: Option<String>, pub billing_address_country_code_iso: Option<enums::CountryAlpha2>, pub shipping_address_country_code_iso: Option<enums::CountryAlpha2>, pub success_url: Option<url::Url>, pub failure_url: Option<url::Url>, pub source: Option<String>, pub bonus_code: Option<String>, pub dob: Option<String>, pub fees_amount: Option<f64>, pub fx_margin_amount: Option<f64>, pub fx_margin_percent: Option<f64>, pub fees_percent: Option<f64>, pub reseller_id: Option<String>, } #[derive(Debug, Serialize)] pub struct BluecodeCaptureRequest; #[derive(Debug, Serialize)] pub struct BluecodeVoidRequest; #[derive(Debug, Serialize)] pub struct BluecodeRefundRequest { pub amount: FloatMajorUnit, } impl TryFrom<&pii::SecretSerdeValue> for BluecodeMetadataObject { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(secret_value: &pii::SecretSerdeValue) -> Result<Self, Self::Error> { match secret_value.peek() { serde_json::Value::String(s) => serde_json::from_str(s).change_context( errors::ConnectorError::InvalidConnectorConfig { config: "Deserializing BluecodeMetadataObject from connector_meta_data string", }, ), value => serde_json::from_value(value.clone()).change_context( errors::ConnectorError::InvalidConnectorConfig { config: "Deserializing BluecodeMetadataObject from connector_meta_data value", }, ), } } } // Request TryFrom implementations impl< T: PaymentMethodDataTypes + std::fmt::Debug + std::marker::Sync + std::marker::Send + 'static + Serialize, > TryFrom< super::BluecodeRouterData< RouterDataV2< Authorize, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData, >, T, >, > for BluecodePaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: super::BluecodeRouterData< RouterDataV2< Authorize, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData, >, T, >, ) -> Result<Self, Self::Error> { if item.router_data.request.capture_method == Some(enums::CaptureMethod::Manual) { return Err(errors::ConnectorError::CaptureMethodNotSupported.into()); } match item.router_data.request.payment_method_data.clone() { PaymentMethodData::Wallet(WalletData::BluecodeRedirect {}) => { let amount = item .connector .amount_converter .convert( item.router_data.request.minor_amount, item.router_data.request.currency, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; let bluecode_mca_metadata = BluecodeMetadataObject::try_from( &item.router_data.resource_common_data.get_connector_meta()?, )?; Ok(Self { amount, currency: item.router_data.request.currency, payment_provider: "bluecode_payment".to_string(), shop_name: bluecode_mca_metadata.shop_name.clone(), reference: item .router_data .resource_common_data .connector_request_reference_id .clone(), ip_address: item.router_data.request.get_ip_address_as_optional(), first_name: item .router_data .resource_common_data .get_billing_first_name()?, last_name: item .router_data .resource_common_data .get_billing_last_name()?, billing_address_country_code_iso: item .router_data .resource_common_data .get_billing_country()?, billing_address_city: item .router_data .resource_common_data .get_billing_city()?, billing_address_line1: item .router_data .resource_common_data .get_billing_line1()?, billing_address_postal_code: item .router_data .resource_common_data .get_optional_billing_zip(), webhook_url: url::Url::parse(&item.router_data.request.get_webhook_url()?) .change_context(errors::ConnectorError::ParsingFailed)?, success_url: url::Url::parse( &item.router_data.request.get_router_return_url()?, ) .change_context(errors::ConnectorError::ParsingFailed)?, failure_url: url::Url::parse( &item.router_data.request.get_router_return_url()?, ) .change_context(errors::ConnectorError::ParsingFailed)?, }) } _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), } } } // Responses #[derive(Debug, Clone, Serialize, Deserialize)] pub struct BluecodePaymentsResponse { pub id: i64, pub order_id: String, pub amount: FloatMajorUnit, pub currency: enums::Currency, pub charged_amount: FloatMajorUnit, pub charged_currency: enums::Currency, pub status: BluecodePaymentStatus, pub payment_link: url::Url, pub etoken: Secret<String>, pub payment_request_id: String, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct BluecodeSyncResponse { pub id: Option<i64>, pub order_id: String, pub status: BluecodePaymentStatus, pub amount: FloatMajorUnit, pub currency: enums::Currency, } #[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum BluecodePaymentStatus { Pending, PaymentInitiated, ManualProcessing, Failed, Completed, } impl From<BluecodePaymentStatus> for AttemptStatus { fn from(item: BluecodePaymentStatus) -> Self { match item { BluecodePaymentStatus::ManualProcessing => Self::Pending, BluecodePaymentStatus::Pending | BluecodePaymentStatus::PaymentInitiated => { Self::AuthenticationPending } BluecodePaymentStatus::Failed => Self::Failure, BluecodePaymentStatus::Completed => Self::Charged, } } } // Response TryFrom implementations impl<F, T> TryFrom< ResponseRouterData< BluecodePaymentsResponse, RouterDataV2<F, PaymentFlowData, T, PaymentsResponseData>, >, > for RouterDataV2<F, PaymentFlowData, T, PaymentsResponseData> where T: Clone, { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< BluecodePaymentsResponse, RouterDataV2<F, PaymentFlowData, T, PaymentsResponseData>, >, ) -> Result<Self, Self::Error> { let redirection_data = Some(domain_types::router_response_types::RedirectForm::Form { endpoint: item.response.payment_link.to_string(), method: Method::Get, form_fields: Default::default(), }); let response = Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(item.response.order_id), redirection_data: redirection_data.map(Box::new), mandate_reference: None, connector_metadata: None, network_txn_id: None, connector_response_reference_id: Some(item.response.payment_request_id), incremental_authorization_allowed: None, status_code: item.http_code, }); Ok(Self { response, resource_common_data: PaymentFlowData { status: AttemptStatus::from(item.response.status), ..item.router_data.resource_common_data }, ..item.router_data }) } } impl<F> TryFrom<ResponseRouterData<BluecodeSyncResponse, Self>> for RouterDataV2<F, PaymentFlowData, PaymentsSyncData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: ResponseRouterData<BluecodeSyncResponse, Self>) -> Result<Self, Self::Error> { let ResponseRouterData { response, router_data, http_code, } = item; let status = AttemptStatus::from(response.status); let response = if status == common_enums::AttemptStatus::Failure { Err(ErrorResponse { code: NO_ERROR_CODE.to_string(), message: NO_ERROR_MESSAGE.to_string(), reason: Some(NO_ERROR_MESSAGE.to_string()), attempt_status: Some(status), connector_transaction_id: Some(response.order_id.clone()), status_code: http_code, network_advice_code: None, network_decline_code: None, network_error_message: None, }) } else { Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(response.order_id.clone()), redirection_data: None, mandate_reference: None, connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, status_code: http_code, }) }; Ok(Self { response, resource_common_data: PaymentFlowData { status, ..router_data.resource_common_data }, ..router_data }) } } // Error #[derive(Debug, Serialize, Deserialize)] pub struct BluecodeErrorResponse { pub message: String, pub context_data: std::collections::HashMap<String, Value>, } // Webhooks, metadata etc. #[derive(Debug, Default, Serialize, Deserialize)] pub struct BluecodeMetadataObject { pub shop_name: String, } pub fn sort_and_minify_json(value: &Value) -> Result<String, errors::ConnectorError> { fn sort_value(val: &Value) -> Value { match val { Value::Object(map) => { let mut entries: Vec<_> = map.iter().collect(); entries.sort_by_key(|(k, _)| k.to_owned()); let sorted_map: Map<String, Value> = entries .into_iter() .map(|(k, v)| (k.clone(), sort_value(v))) .collect(); Value::Object(sorted_map) } Value::Array(arr) => Value::Array(arr.iter().map(sort_value).collect()), _ => val.clone(), } } let sorted_value = sort_value(value); serde_json::to_string(&sorted_value) .map_err(|_| errors::ConnectorError::WebhookBodyDecodingFailed) }
{ "chunk": null, "crate": "connector-integration", "enum_name": null, "file_size": 15103, "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 }