id
stringlengths
20
153
type
stringclasses
1 value
granularity
stringclasses
14 values
content
stringlengths
16
84.3k
metadata
dict
connector-service_mini_grpc-server_8474653292087038763_16
clm
mini_chunk
// connector-service/backend/grpc-server/src/server/payments.rs "Access token created successfully with expiry: {:?}", access_token_data.expires_in ); Some(access_token_data) } }; // Store in flow data for connector API calls payment_flow_data.set_access_token(access_token_data) } else { // Connector doesn't support access tokens payment_flow_data }; // Create router data let router_data = RouterDataV2::< PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData, > { flow: std::marker::PhantomData, resource_common_data: payment_flow_data, connector_auth_type: metadata_payload.connector_auth_type.clone(), request: payments_sync_data, response: Err(ErrorResponse::default()), }; // Execute connector processing let flow_name = utils::flow_marker_to_flow_name::<PSync>(); let event_params = EventProcessingParams { connector_name: &metadata_payload.connector.to_string(), service_name: &service_name, flow_name, event_config: &self.config.events, request_id: &metadata_payload.request_id, lineage_ids: &metadata_payload.lineage_ids, reference_id: &metadata_payload.reference_id, shadow_mode: metadata_payload.shadow_mode, }; let consume_or_trigger_flow = match payload.handle_response { Some(resource_object) => { common_enums::CallConnectorAction::HandleResponse(resource_object) } None => common_enums::CallConnectorAction::Trigger, }; let response_result = Box::pin( external_services::service::execute_connector_processing_step( &self.config.proxy, connector_integration, router_data, None, event_params, None, consume_or_trigger_flow, ), ) .await .switch() .into_grpc_status()?; // Generate response let final_response = generate_payment_sync_response(response_result).into_grpc_status()?; Ok(tonic::Response::new(final_response)) }) }, ) .await } #[tracing::instrument( name = "payment_void", fields( name = common_utils::consts::NAME, service_name = common_utils::consts::PAYMENT_SERVICE_NAME, service_method = FlowName::Void.as_str(), request_body = tracing::field::Empty, response_body = tracing::field::Empty, error_message = tracing::field::Empty, merchant_id = tracing::field::Empty, gateway = tracing::field::Empty, request_id = tracing::field::Empty, status_code = tracing::field::Empty, message_ = "Golden Log Line (incoming)", response_time = tracing::field::Empty, tenant_id = tracing::field::Empty, flow = FlowName::Void.as_str(), flow_specific_fields.status = tracing::field::Empty, ) skip(self, request) )] async fn void( &self, request: tonic::Request<PaymentServiceVoidRequest>, ) -> Result<tonic::Response<PaymentServiceVoidResponse>, tonic::Status> { let service_name = request
{ "chunk": 16, "crate": "grpc-server", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_grpc-server_8474653292087038763_17
clm
mini_chunk
// connector-service/backend/grpc-server/src/server/payments.rs .extensions() .get::<String>() .cloned() .unwrap_or_else(|| "PaymentService".to_string()); grpc_logging_wrapper( request, &service_name, self.config.clone(), FlowName::Void, |request_data| async move { self.internal_void_payment(request_data).await }, ) .await } #[tracing::instrument( name = "payment_void_post_capture", fields( name = common_utils::consts::NAME, service_name = common_utils::consts::PAYMENT_SERVICE_NAME, service_method = FlowName::VoidPostCapture.as_str(), request_body = tracing::field::Empty, response_body = tracing::field::Empty, error_message = tracing::field::Empty, merchant_id = tracing::field::Empty, gateway = tracing::field::Empty, request_id = tracing::field::Empty, status_code = tracing::field::Empty, message_ = "Golden Log Line (incoming)", response_time = tracing::field::Empty, tenant_id = tracing::field::Empty, flow = FlowName::VoidPostCapture.as_str(), flow_specific_fields.status = tracing::field::Empty, ) skip(self, request) )] async fn void_post_capture( &self, request: tonic::Request<PaymentServiceVoidPostCaptureRequest>, ) -> Result<tonic::Response<PaymentServiceVoidPostCaptureResponse>, tonic::Status> { let service_name = request .extensions() .get::<String>() .cloned() .unwrap_or_else(|| "PaymentService".to_string()); grpc_logging_wrapper( request, &service_name, self.config.clone(), FlowName::VoidPostCapture, |request_data| async move { self.internal_void_post_capture(request_data).await }, ) .await } #[tracing::instrument( name = "incoming_webhook", fields( name = common_utils::consts::NAME, service_name = common_utils::consts::PAYMENT_SERVICE_NAME, service_method = FlowName::IncomingWebhook.as_str(), request_body = tracing::field::Empty, response_body = tracing::field::Empty, error_message = tracing::field::Empty, merchant_id = tracing::field::Empty, gateway = tracing::field::Empty, request_id = tracing::field::Empty, status_code = tracing::field::Empty, message_ = "Golden Log Line (incoming)", response_time = tracing::field::Empty, tenant_id = tracing::field::Empty, flow = FlowName::IncomingWebhook.as_str(), flow_specific_fields.status = tracing::field::Empty, ) skip(self, request) )] async fn transform( &self, request: tonic::Request<PaymentServiceTransformRequest>, ) -> Result<tonic::Response<PaymentServiceTransformResponse>, tonic::Status> { let service_name = request .extensions() .get::<String>() .cloned() .unwrap_or_else(|| "PaymentService".to_string()); grpc_logging_wrapper( request, &service_name, self.config.clone(), FlowName::IncomingWebhook, |request_data| { async move { let payload = request_data.payload; let metadata_payload = request_data.extracted_metadata; let connector = metadata_payload.connector; let _request_id = &metadata_payload.request_id; let connector_auth_details = &metadata_payload.connector_auth_type; let request_details = payload .request_details .map(domain_types::connector_types::RequestDetails::foreign_try_from) .ok_or_else(|| { tonic::Status::invalid_argument("missing request_details in the payload") })? .map_err(|e| e.into_grpc_status())?; let webhook_secrets = payload .webhook_secrets
{ "chunk": 17, "crate": "grpc-server", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_grpc-server_8474653292087038763_18
clm
mini_chunk
// connector-service/backend/grpc-server/src/server/payments.rs .clone() .map(|details| { domain_types::connector_types::ConnectorWebhookSecrets::foreign_try_from( details, ) .map_err(|e| e.into_grpc_status()) }) .transpose()?; //get connector data let connector_data: ConnectorData<DefaultPCIHolder> = ConnectorData::get_connector_by_name(&connector); let source_verified = match connector_data .connector .verify_webhook_source( request_details.clone(), webhook_secrets.clone(), Some(connector_auth_details.clone()), ) { Ok(result) => result, Err(err) => { tracing::warn!( target: "webhook", "{:?}", err ); false } }; let event_type = connector_data .connector .get_event_type( request_details.clone(), webhook_secrets.clone(), Some(connector_auth_details.clone()), ) .switch() .into_grpc_status()?; // Get content for the webhook based on the event type using categorization let content = if event_type.is_payment_event() { get_payments_webhook_content( connector_data, request_details, webhook_secrets, Some(connector_auth_details.clone()), ) .await .into_grpc_status()? } else if event_type.is_refund_event() { get_refunds_webhook_content( connector_data, request_details, webhook_secrets, Some(connector_auth_details.clone()), ) .await .into_grpc_status()? } else if event_type.is_dispute_event() { get_disputes_webhook_content( connector_data, request_details, webhook_secrets, Some(connector_auth_details.clone()), ) .await .into_grpc_status()? } else { // For all other event types, default to payment webhook content for now // This includes mandate, payout, recovery, and misc events get_payments_webhook_content( connector_data, request_details, webhook_secrets, Some(connector_auth_details.clone()), ) .await .into_grpc_status()? }; let api_event_type = grpc_api_types::payments::WebhookEventType::foreign_try_from(event_type) .map_err(|e| e.into_grpc_status())?; let webhook_transformation_status = match content.content { Some(grpc_api_types::payments::webhook_response_content::Content::IncompleteTransformation(_)) => WebhookTransformationStatus::Incomplete, _ => WebhookTransformationStatus::Complete, }; let response = PaymentServiceTransformResponse { event_type: api_event_type.into(), content: Some(content),
{ "chunk": 18, "crate": "grpc-server", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_grpc-server_8474653292087038763_19
clm
mini_chunk
// connector-service/backend/grpc-server/src/server/payments.rs source_verified, response_ref_id: None, transformation_status: webhook_transformation_status.into(), }; Ok(tonic::Response::new(response)) } }, ) .await } #[tracing::instrument( name = "refund", fields( name = common_utils::consts::NAME, service_name = common_utils::consts::PAYMENT_SERVICE_NAME, service_method = FlowName::Refund.as_str(), request_body = tracing::field::Empty, response_body = tracing::field::Empty, error_message = tracing::field::Empty, merchant_id = tracing::field::Empty, gateway = tracing::field::Empty, request_id = tracing::field::Empty, status_code = tracing::field::Empty, message_ = "Golden Log Line (incoming)", response_time = tracing::field::Empty, tenant_id = tracing::field::Empty, flow = FlowName::Refund.as_str(), flow_specific_fields.status = tracing::field::Empty, ) skip(self, request) )] async fn refund( &self, request: tonic::Request<PaymentServiceRefundRequest>, ) -> Result<tonic::Response<RefundResponse>, tonic::Status> { let service_name = request .extensions() .get::<String>() .cloned() .unwrap_or_else(|| "PaymentService".to_string()); grpc_logging_wrapper( request, &service_name, self.config.clone(), FlowName::Refund, |request_data| async move { self.internal_refund(request_data).await }, ) .await } #[tracing::instrument( name = "defend_dispute", fields( name = common_utils::consts::NAME, service_name = common_utils::consts::PAYMENT_SERVICE_NAME, service_method = FlowName::DefendDispute.as_str(), request_body = tracing::field::Empty, response_body = tracing::field::Empty, error_message = tracing::field::Empty, merchant_id = tracing::field::Empty, gateway = tracing::field::Empty, request_id = tracing::field::Empty, status_code = tracing::field::Empty, message_ = "Golden Log Line (incoming)", response_time = tracing::field::Empty, tenant_id = tracing::field::Empty, flow = FlowName::DefendDispute.as_str(), flow_specific_fields.status = tracing::field::Empty, ) skip(self, request) )] async fn dispute( &self, request: tonic::Request<PaymentServiceDisputeRequest>, ) -> Result<tonic::Response<DisputeResponse>, tonic::Status> { let service_name = request .extensions() .get::<String>() .cloned() .unwrap_or_else(|| "PaymentService".to_string()); grpc_logging_wrapper( request, &service_name, self.config.clone(), FlowName::DefendDispute, |_request_data| async { let response = DisputeResponse { ..Default::default() }; Ok(tonic::Response::new(response)) }, ) .await } #[tracing::instrument( name = "payment_capture", fields( name = common_utils::consts::NAME, service_name = common_utils::consts::PAYMENT_SERVICE_NAME, service_method = FlowName::Capture.as_str(), request_body = tracing::field::Empty, response_body = tracing::field::Empty, error_message = tracing::field::Empty, merchant_id = tracing::field::Empty, gateway = tracing::field::Empty, request_id = tracing::field::Empty, status_code = tracing::field::Empty, message_ = "Golden Log Line (incoming)", response_time = tracing::field::Empty, tenant_id = tracing::field::Empty, flow = FlowName::Capture.as_str(), flow_specific_fields.status = tracing::field::Empty, ) skip(self, request) )]
{ "chunk": 19, "crate": "grpc-server", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_grpc-server_8474653292087038763_20
clm
mini_chunk
// connector-service/backend/grpc-server/src/server/payments.rs async fn capture( &self, request: tonic::Request<PaymentServiceCaptureRequest>, ) -> Result<tonic::Response<PaymentServiceCaptureResponse>, tonic::Status> { let service_name = request .extensions() .get::<String>() .cloned() .unwrap_or_else(|| "PaymentService".to_string()); grpc_logging_wrapper( request, &service_name, self.config.clone(), FlowName::Capture, |request_data| async move { self.internal_payment_capture(request_data).await }, ) .await } #[tracing::instrument( name = "setup_mandate", fields( name = common_utils::consts::NAME, service_name = common_utils::consts::PAYMENT_SERVICE_NAME, service_method = FlowName::SetupMandate.as_str(), request_body = tracing::field::Empty, response_body = tracing::field::Empty, error_message = tracing::field::Empty, merchant_id = tracing::field::Empty, gateway = tracing::field::Empty, request_id = tracing::field::Empty, status_code = tracing::field::Empty, message_ = "Golden Log Line (incoming)", response_time = tracing::field::Empty, tenant_id = tracing::field::Empty, flow = FlowName::SetupMandate.as_str(), flow_specific_fields.status = tracing::field::Empty, ) skip(self, request) )] async fn register( &self, request: tonic::Request<PaymentServiceRegisterRequest>, ) -> Result<tonic::Response<PaymentServiceRegisterResponse>, tonic::Status> { info!("SETUP_MANDATE_FLOW: initiated"); let service_name = request .extensions() .get::<String>() .cloned() .unwrap_or_else(|| "PaymentService".to_string()); grpc_logging_wrapper( request, &service_name, self.config.clone(), FlowName::SetupMandate, |request_data| { let service_name = service_name.clone(); Box::pin(async move { let payload = request_data.payload; let metadata_payload = request_data.extracted_metadata; let (connector, request_id, lineage_ids) = ( metadata_payload.connector, metadata_payload.request_id, metadata_payload.lineage_ids, ); let connector_auth_details = &metadata_payload.connector_auth_type; //get connector data let connector_data = ConnectorData::get_connector_by_name(&connector); // Get connector integration let connector_integration: BoxedConnectorIntegrationV2< '_, SetupMandate, PaymentFlowData, SetupMandateRequestData<DefaultPCIHolder>, PaymentsResponseData, > = connector_data.connector.get_connector_integration_v2(); // Create common request data let payment_flow_data = PaymentFlowData::foreign_try_from(( payload.clone(), self.config.connectors.clone(), self.config.common.environment, &request_data.masked_metadata, )) .map_err(|e| e.into_grpc_status())?; let should_do_order_create = connector_data.connector.should_do_order_create(); let order_id = if should_do_order_create { let event_params = EventParams { _connector_name: &connector.to_string(), _service_name: &service_name, request_id: &request_id, lineage_ids: &lineage_ids, reference_id: &metadata_payload.reference_id, shadow_mode: metadata_payload.shadow_mode, }; Some(
{ "chunk": 20, "crate": "grpc-server", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_grpc-server_8474653292087038763_21
clm
mini_chunk
// connector-service/backend/grpc-server/src/server/payments.rs Box::pin(self.handle_order_creation_for_setup_mandate( connector_data.clone(), &payment_flow_data, connector_auth_details.clone(), event_params, &payload, &connector.to_string(), &service_name, )) .await?, ) } else { None }; let payment_flow_data = payment_flow_data.set_order_reference_id(order_id); // Extract connector customer ID (if provided) let cached_connector_customer_id = payload.connector_customer_id.clone(); // Check if connector supports customer creation let should_create_connector_customer = connector_data.connector.should_create_connector_customer(); // Conditional customer creation - ONLY if connector needs it AND no existing customer ID let payment_flow_data = if should_create_connector_customer { match cached_connector_customer_id { Some(_customer_id) => payment_flow_data, None => { let event_params = EventParams { _connector_name: &connector.to_string(), _service_name: &service_name, request_id: &request_id, lineage_ids: &lineage_ids, reference_id: &metadata_payload.reference_id, shadow_mode: metadata_payload.shadow_mode, }; let connector_customer_response = Box::pin(self.handle_connector_customer_for_setup_mandate( connector_data.clone(), &payment_flow_data, connector_auth_details.clone(), &payload, &connector.to_string(), &service_name, event_params, )) .await?; payment_flow_data.set_connector_customer_id(Some( connector_customer_response.connector_customer_id, )) } } } else { // Connector doesn't support customer creation payment_flow_data }; let setup_mandate_request_data = SetupMandateRequestData::foreign_try_from(payload.clone()) .map_err(|e| e.into_grpc_status())?; // Create router data let router_data: RouterDataV2< SetupMandate, PaymentFlowData, SetupMandateRequestData<DefaultPCIHolder>, PaymentsResponseData, > = RouterDataV2 { flow: std::marker::PhantomData, resource_common_data: payment_flow_data, connector_auth_type: connector_auth_details.clone(), request: setup_mandate_request_data, response: Err(ErrorResponse::default()), }; let event_params = EventProcessingParams { connector_name: &connector.to_string(), service_name: &service_name, flow_name: FlowName::SetupMandate, event_config: &self.config.events,
{ "chunk": 21, "crate": "grpc-server", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_grpc-server_8474653292087038763_22
clm
mini_chunk
// connector-service/backend/grpc-server/src/server/payments.rs request_id: &request_id, lineage_ids: &lineage_ids, reference_id: &metadata_payload.reference_id, shadow_mode: metadata_payload.shadow_mode, }; let response = Box::pin( external_services::service::execute_connector_processing_step( &self.config.proxy, connector_integration, router_data, None, event_params, None, // token_data - None for non-proxy payments common_enums::CallConnectorAction::Trigger, ), ) .await .switch() .map_err(|e| e.into_grpc_status())?; // Generate response let setup_mandate_response = generate_setup_mandate_response(response) .map_err(|e| e.into_grpc_status())?; Ok(tonic::Response::new(setup_mandate_response)) }) }, ) .await } #[tracing::instrument( name = "repeat_payment", fields( name = common_utils::consts::NAME, service_name = common_utils::consts::PAYMENT_SERVICE_NAME, service_method = FlowName::RepeatPayment.as_str(), request_body = tracing::field::Empty, response_body = tracing::field::Empty, error_message = tracing::field::Empty, merchant_id = tracing::field::Empty, gateway = tracing::field::Empty, request_id = tracing::field::Empty, status_code = tracing::field::Empty, message_ = "Golden Log Line (incoming)", response_time = tracing::field::Empty, tenant_id = tracing::field::Empty, ), skip(self, request) )] async fn repeat_everything( &self, request: tonic::Request<PaymentServiceRepeatEverythingRequest>, ) -> Result<tonic::Response<PaymentServiceRepeatEverythingResponse>, tonic::Status> { info!("REPEAT_PAYMENT_FLOW: initiated"); let service_name = request .extensions() .get::<String>() .cloned() .unwrap_or_else(|| "PaymentService".to_string()); grpc_logging_wrapper( request, &service_name, self.config.clone(), FlowName::RepeatPayment, |request_data| { let service_name = service_name.clone(); Box::pin(async move { let payload = request_data.payload; let metadata_payload = request_data.extracted_metadata; let (connector, request_id, lineage_ids) = ( metadata_payload.connector, metadata_payload.request_id, metadata_payload.lineage_ids, ); let connector_auth_details = &metadata_payload.connector_auth_type; //get connector data let connector_data: ConnectorData<DefaultPCIHolder> = ConnectorData::get_connector_by_name(&connector); // Get connector integration let connector_integration: BoxedConnectorIntegrationV2< '_, RepeatPayment, PaymentFlowData, RepeatPaymentData, PaymentsResponseData, > = connector_data.connector.get_connector_integration_v2(); // Create payment flow data let payment_flow_data = PaymentFlowData::foreign_try_from(( payload.clone(), self.config.connectors.clone(), &request_data.masked_metadata, )) .map_err(|e| e.into_grpc_status())?; // Create repeat payment data let repeat_payment_data = RepeatPaymentData::foreign_try_from(payload.clone())
{ "chunk": 22, "crate": "grpc-server", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_grpc-server_8474653292087038763_23
clm
mini_chunk
// connector-service/backend/grpc-server/src/server/payments.rs .map_err(|e| e.into_grpc_status())?; // Create router data let router_data: RouterDataV2< RepeatPayment, PaymentFlowData, RepeatPaymentData, PaymentsResponseData, > = RouterDataV2 { flow: std::marker::PhantomData, resource_common_data: payment_flow_data, connector_auth_type: connector_auth_details.clone(), request: repeat_payment_data, response: Err(ErrorResponse::default()), }; let event_params = EventProcessingParams { connector_name: &connector.to_string(), service_name: &service_name, flow_name: FlowName::RepeatPayment, event_config: &self.config.events, request_id: &request_id, lineage_ids: &lineage_ids, reference_id: &metadata_payload.reference_id, shadow_mode: metadata_payload.shadow_mode, }; let response = Box::pin( external_services::service::execute_connector_processing_step( &self.config.proxy, connector_integration, router_data, None, event_params, None, // token_data - None for non-proxy payments common_enums::CallConnectorAction::Trigger, ), ) .await .switch() .map_err(|e| e.into_grpc_status())?; // Generate response let repeat_payment_response = generate_repeat_payment_response(response) .map_err(|e| e.into_grpc_status())?; Ok(tonic::Response::new(repeat_payment_response)) }) }, ) .await } #[tracing::instrument( name = "pre_authenticate", fields( name = common_utils::consts::NAME, service_name = common_utils::consts::PAYMENT_SERVICE_NAME, service_method = FlowName::PreAuthenticate.as_str(), request_body = tracing::field::Empty, response_body = tracing::field::Empty, error_message = tracing::field::Empty, merchant_id = tracing::field::Empty, gateway = tracing::field::Empty, request_id = tracing::field::Empty, status_code = tracing::field::Empty, message_ = "Golden Log Line (incoming)", response_time = tracing::field::Empty, tenant_id = tracing::field::Empty, flow = FlowName::PreAuthenticate.as_str(), flow_specific_fields.status = tracing::field::Empty, ) skip(self, request) )] async fn pre_authenticate( &self, request: tonic::Request<PaymentServicePreAuthenticateRequest>, ) -> Result<tonic::Response<PaymentServicePreAuthenticateResponse>, tonic::Status> { let service_name = request .extensions() .get::<String>() .cloned() .unwrap_or_else(|| "PaymentService".to_string()); grpc_logging_wrapper( request, &service_name, self.config.clone(), FlowName::PreAuthenticate, |request_data| async move { self.internal_pre_authenticate(request_data).await }, ) .await } #[tracing::instrument( name = "authenticate", fields( name = common_utils::consts::NAME, service_name = common_utils::consts::PAYMENT_SERVICE_NAME, service_method = FlowName::Authenticate.as_str(), request_body = tracing::field::Empty, response_body = tracing::field::Empty, error_message = tracing::field::Empty, merchant_id = tracing::field::Empty,
{ "chunk": 23, "crate": "grpc-server", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_grpc-server_8474653292087038763_24
clm
mini_chunk
// connector-service/backend/grpc-server/src/server/payments.rs gateway = tracing::field::Empty, request_id = tracing::field::Empty, status_code = tracing::field::Empty, message_ = "Golden Log Line (incoming)", response_time = tracing::field::Empty, tenant_id = tracing::field::Empty, flow = FlowName::Authenticate.as_str(), flow_specific_fields.status = tracing::field::Empty, ) skip(self, request) )] async fn authenticate( &self, request: tonic::Request<PaymentServiceAuthenticateRequest>, ) -> Result<tonic::Response<PaymentServiceAuthenticateResponse>, tonic::Status> { let service_name = request .extensions() .get::<String>() .cloned() .unwrap_or_else(|| "PaymentService".to_string()); grpc_logging_wrapper( request, &service_name, self.config.clone(), FlowName::Authenticate, |request_data| async move { self.internal_authenticate(request_data).await }, ) .await } #[tracing::instrument( name = "post_authenticate", fields( name = common_utils::consts::NAME, service_name = common_utils::consts::PAYMENT_SERVICE_NAME, service_method = FlowName::PostAuthenticate.as_str(), request_body = tracing::field::Empty, response_body = tracing::field::Empty, error_message = tracing::field::Empty, merchant_id = tracing::field::Empty, gateway = tracing::field::Empty, request_id = tracing::field::Empty, status_code = tracing::field::Empty, message_ = "Golden Log Line (incoming)", response_time = tracing::field::Empty, tenant_id = tracing::field::Empty, flow = FlowName::PostAuthenticate.as_str(), flow_specific_fields.status = tracing::field::Empty, ) skip(self, request) )] async fn post_authenticate( &self, request: tonic::Request<PaymentServicePostAuthenticateRequest>, ) -> Result<tonic::Response<PaymentServicePostAuthenticateResponse>, tonic::Status> { let service_name = request .extensions() .get::<String>() .cloned() .unwrap_or_else(|| "PaymentService".to_string()); grpc_logging_wrapper( request, &service_name, self.config.clone(), FlowName::PostAuthenticate, |request_data| async move { self.internal_post_authenticate(request_data).await }, ) .await } } async fn get_payments_webhook_content( connector_data: ConnectorData<DefaultPCIHolder>, request_details: domain_types::connector_types::RequestDetails, webhook_secrets: Option<domain_types::connector_types::ConnectorWebhookSecrets>, connector_auth_details: Option<ConnectorAuthType>, ) -> CustomResult<grpc_api_types::payments::WebhookResponseContent, ApplicationErrorResponse> { let webhook_details = connector_data .connector .process_payment_webhook( request_details.clone(), webhook_secrets, connector_auth_details, ) .switch()?; match webhook_details.transformation_status { common_enums::WebhookTransformationStatus::Complete => { // Generate response let response = PaymentServiceGetResponse::foreign_try_from(webhook_details) .change_context(ApplicationErrorResponse::InternalServerError(ApiError { sub_code: "RESPONSE_CONSTRUCTION_ERROR".to_string(), error_identifier: 500, error_message: "Error while constructing response".to_string(), error_object: None, }))?; Ok(grpc_api_types::payments::WebhookResponseContent { content: Some( grpc_api_types::payments::webhook_response_content::Content::PaymentsResponse( response, ), ), }) } common_enums::WebhookTransformationStatus::Incomplete => { let resource_object = connector_data .connector
{ "chunk": 24, "crate": "grpc-server", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_grpc-server_8474653292087038763_25
clm
mini_chunk
// connector-service/backend/grpc-server/src/server/payments.rs .get_webhook_resource_object(request_details) .switch()?; let resource_object_vec = serde_json::to_vec(&resource_object).change_context( ApplicationErrorResponse::InternalServerError(ApiError { sub_code: "SERIALIZATION_ERROR".to_string(), error_identifier: 500, error_message: "Error while serializing resource object".to_string(), error_object: None, }), )?; Ok(grpc_api_types::payments::WebhookResponseContent { content: Some( grpc_api_types::payments::webhook_response_content::Content::IncompleteTransformation( grpc_api_types::payments::IncompleteTransformationResponse { resource_object: resource_object_vec, reason: "Payment information required".to_string(), } ), ), }) } } } async fn get_refunds_webhook_content< T: PaymentMethodDataTypes + Default + Eq + Debug + Send + serde::Serialize + serde::de::DeserializeOwned + Clone + Sync + domain_types::types::CardConversionHelper<T> + 'static, >( connector_data: ConnectorData<T>, request_details: domain_types::connector_types::RequestDetails, webhook_secrets: Option<domain_types::connector_types::ConnectorWebhookSecrets>, connector_auth_details: Option<ConnectorAuthType>, ) -> CustomResult<grpc_api_types::payments::WebhookResponseContent, ApplicationErrorResponse> { let webhook_details = connector_data .connector .process_refund_webhook(request_details, webhook_secrets, connector_auth_details) .switch()?; // Generate response - RefundService should handle this, for now return basic response let response = RefundResponse::foreign_try_from(webhook_details).change_context( ApplicationErrorResponse::InternalServerError(ApiError { sub_code: "RESPONSE_CONSTRUCTION_ERROR".to_string(), error_identifier: 500, error_message: "Error while constructing response".to_string(), error_object: None, }), )?; Ok(grpc_api_types::payments::WebhookResponseContent { content: Some( grpc_api_types::payments::webhook_response_content::Content::RefundsResponse(response), ), }) } async fn get_disputes_webhook_content< T: PaymentMethodDataTypes + Default + Eq + Debug + Send + serde::Serialize + serde::de::DeserializeOwned + Clone + Sync + domain_types::types::CardConversionHelper<T> + 'static, >( connector_data: ConnectorData<T>, request_details: domain_types::connector_types::RequestDetails, webhook_secrets: Option<domain_types::connector_types::ConnectorWebhookSecrets>, connector_auth_details: Option<ConnectorAuthType>, ) -> CustomResult<grpc_api_types::payments::WebhookResponseContent, ApplicationErrorResponse> { let webhook_details = connector_data .connector .process_dispute_webhook(request_details, webhook_secrets, connector_auth_details) .switch()?; // Generate response - DisputeService should handle this, for now return basic response let response = DisputeResponse::foreign_try_from(webhook_details).change_context( ApplicationErrorResponse::InternalServerError(ApiError { sub_code: "RESPONSE_CONSTRUCTION_ERROR".to_string(), error_identifier: 500, error_message: "Error while constructing response".to_string(), error_object: None, }), )?; Ok(grpc_api_types::payments::WebhookResponseContent { content: Some( grpc_api_types::payments::webhook_response_content::Content::DisputesResponse(response), ), }) } pub fn generate_payment_pre_authenticate_response<T: PaymentMethodDataTypes>( router_data_v2: RouterDataV2< PreAuthenticate, PaymentFlowData, PaymentsPreAuthenticateData<T>, PaymentsResponseData, >, ) -> Result<PaymentServicePreAuthenticateResponse, error_stack::Report<ApplicationErrorResponse>> {
{ "chunk": 25, "crate": "grpc-server", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_grpc-server_8474653292087038763_26
clm
mini_chunk
// connector-service/backend/grpc-server/src/server/payments.rs let transaction_response = router_data_v2.response; let status = router_data_v2.resource_common_data.status; let grpc_status = grpc_api_types::payments::PaymentStatus::foreign_from(status); let raw_connector_response = router_data_v2 .resource_common_data .get_raw_connector_response(); let response_headers = router_data_v2 .resource_common_data .get_connector_response_headers_as_map(); let response = match transaction_response { Ok(response) => match response { PaymentsResponseData::PreAuthenticateResponse { redirection_data, connector_response_reference_id, status_code, } => PaymentServicePreAuthenticateResponse { transaction_id: None, redirection_data: redirection_data .map(|form| match *form { router_response_types::RedirectForm::Form { endpoint, method, form_fields, } => Ok::<grpc_api_types::payments::RedirectForm, ApplicationErrorResponse>( grpc_api_types::payments::RedirectForm { form_type: Some( grpc_api_types::payments::redirect_form::FormType::Form( grpc_api_types::payments::FormData { endpoint, method: grpc_api_types::payments::HttpMethod::foreign_from( method, ) .into(), form_fields, }, ), ), }, ), router_response_types::RedirectForm::Html { html_data } => { Ok(grpc_api_types::payments::RedirectForm { form_type: Some( grpc_api_types::payments::redirect_form::FormType::Html( grpc_api_types::payments::HtmlData { html_data }, ), ), }) } router_response_types::RedirectForm::Uri { uri } => { Ok(grpc_api_types::payments::RedirectForm { form_type: Some( grpc_api_types::payments::redirect_form::FormType::Uri( grpc_api_types::payments::UriData { uri }, ), ), }) } router_response_types::RedirectForm::Mifinity { initialization_token, } => Ok(grpc_api_types::payments::RedirectForm { form_type: Some( grpc_api_types::payments::redirect_form::FormType::Uri( grpc_api_types::payments::UriData { uri: initialization_token, }, ), ), }), router_response_types::RedirectForm::CybersourceAuthSetup { access_token, ddc_url, reference_id, } => { let mut form_fields = HashMap::new(); form_fields.insert("access_token".to_string(), access_token); form_fields.insert("ddc_url".to_string(), ddc_url.clone()); form_fields.insert("reference_id".to_string(), reference_id);
{ "chunk": 26, "crate": "grpc-server", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_grpc-server_8474653292087038763_27
clm
mini_chunk
// connector-service/backend/grpc-server/src/server/payments.rs Ok(grpc_api_types::payments::RedirectForm { form_type: Some( grpc_api_types::payments::redirect_form::FormType::Form( grpc_api_types::payments::FormData { endpoint: ddc_url, method: grpc_api_types::payments::HttpMethod::Post .into(), form_fields, }, ), ), }) } _ => Err(ApplicationErrorResponse::BadRequest(ApiError { sub_code: "INVALID_RESPONSE".to_owned(), error_identifier: 400, error_message: "Invalid response from connector".to_owned(), error_object: None, }))?, }) .transpose()?, connector_metadata: HashMap::new(), response_ref_id: connector_response_reference_id.map(|id| { grpc_api_types::payments::Identifier { id_type: Some(grpc_api_types::payments::identifier::IdType::Id(id)), } }), status: grpc_status.into(), error_message: None, error_code: None, raw_connector_response, status_code: status_code.into(), response_headers, network_txn_id: None, state: None, }, _ => { return Err(ApplicationErrorResponse::BadRequest(ApiError { sub_code: "INVALID_RESPONSE".to_owned(), error_identifier: 400, error_message: "Invalid response type for pre authenticate".to_owned(), error_object: None, }) .into()) } }, Err(err) => { let status = err .attempt_status .map(grpc_api_types::payments::PaymentStatus::foreign_from) .unwrap_or_default(); PaymentServicePreAuthenticateResponse { transaction_id: Some(grpc_api_types::payments::Identifier { id_type: Some( grpc_api_types::payments::identifier::IdType::NoResponseIdMarker(()), ), }), redirection_data: None, network_txn_id: None, response_ref_id: None, status: status.into(), error_message: Some(err.message), error_code: Some(err.code), status_code: err.status_code.into(), response_headers, raw_connector_response, connector_metadata: HashMap::new(), state: None, } } }; Ok(response) } pub fn generate_payment_authenticate_response<T: PaymentMethodDataTypes>( router_data_v2: RouterDataV2< Authenticate, PaymentFlowData, PaymentsAuthenticateData<T>, PaymentsResponseData, >, ) -> Result<PaymentServiceAuthenticateResponse, error_stack::Report<ApplicationErrorResponse>> { let transaction_response = router_data_v2.response; let status = router_data_v2.resource_common_data.status; let grpc_status = grpc_api_types::payments::PaymentStatus::foreign_from(status); let raw_connector_response = router_data_v2 .resource_common_data .get_raw_connector_response(); let response_headers = router_data_v2 .resource_common_data .get_connector_response_headers_as_map(); let response = match transaction_response { Ok(response) => match response { PaymentsResponseData::AuthenticateResponse { redirection_data, authentication_data, connector_response_reference_id, status_code, } => PaymentServiceAuthenticateResponse {
{ "chunk": 27, "crate": "grpc-server", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_grpc-server_8474653292087038763_28
clm
mini_chunk
// connector-service/backend/grpc-server/src/server/payments.rs response_ref_id: connector_response_reference_id.map(|id| { grpc_api_types::payments::Identifier { id_type: Some(grpc_api_types::payments::identifier::IdType::Id(id)), } }), transaction_id: None, redirection_data: redirection_data .map(|form| match *form { router_response_types::RedirectForm::Form { endpoint, method, form_fields, } => Ok::<grpc_api_types::payments::RedirectForm, ApplicationErrorResponse>( grpc_api_types::payments::RedirectForm { form_type: Some( grpc_api_types::payments::redirect_form::FormType::Form( grpc_api_types::payments::FormData { endpoint, method: grpc_api_types::payments::HttpMethod::foreign_from( method, ) .into(), form_fields, }, ), ), }, ), router_response_types::RedirectForm::Html { html_data } => { Ok(grpc_api_types::payments::RedirectForm { form_type: Some( grpc_api_types::payments::redirect_form::FormType::Html( grpc_api_types::payments::HtmlData { html_data }, ), ), }) } router_response_types::RedirectForm::Uri { uri } => { Ok(grpc_api_types::payments::RedirectForm { form_type: Some( grpc_api_types::payments::redirect_form::FormType::Uri( grpc_api_types::payments::UriData { uri }, ), ), }) } router_response_types::RedirectForm::Mifinity { initialization_token, } => Ok(grpc_api_types::payments::RedirectForm { form_type: Some( grpc_api_types::payments::redirect_form::FormType::Uri( grpc_api_types::payments::UriData { uri: initialization_token, }, ), ), }), router_response_types::RedirectForm::CybersourceConsumerAuth { access_token, step_up_url, } => { let mut form_fields = HashMap::new(); form_fields.insert("access_token".to_string(), access_token); form_fields.insert("step_up_url".to_string(), step_up_url.clone()); Ok(grpc_api_types::payments::RedirectForm { form_type: Some( grpc_api_types::payments::redirect_form::FormType::Form( grpc_api_types::payments::FormData { endpoint: step_up_url, method: grpc_api_types::payments::HttpMethod::Post .into(), form_fields, },
{ "chunk": 28, "crate": "grpc-server", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_grpc-server_8474653292087038763_29
clm
mini_chunk
// connector-service/backend/grpc-server/src/server/payments.rs ), ), }) } _ => Err(ApplicationErrorResponse::BadRequest(ApiError { sub_code: "INVALID_RESPONSE".to_owned(), error_identifier: 400, error_message: "Invalid response from connector".to_owned(), error_object: None, }))?, }) .transpose()?, connector_metadata: HashMap::new(), authentication_data: authentication_data.map(ForeignFrom::foreign_from), status: grpc_status.into(), error_message: None, error_code: None, raw_connector_response, status_code: status_code.into(), response_headers, network_txn_id: None, state: None, }, _ => { return Err(ApplicationErrorResponse::BadRequest(ApiError { sub_code: "INVALID_RESPONSE".to_owned(), error_identifier: 400, error_message: "Invalid response type for authenticate".to_owned(), error_object: None, }) .into()) } }, Err(err) => { let status = err .attempt_status .map(grpc_api_types::payments::PaymentStatus::foreign_from) .unwrap_or_default(); PaymentServiceAuthenticateResponse { transaction_id: Some(grpc_api_types::payments::Identifier { id_type: Some(grpc_api_types::payments::identifier::IdType::Id( "session_created".to_string(), )), }), redirection_data: None, network_txn_id: None, response_ref_id: None, authentication_data: None, status: status.into(), error_message: Some(err.message), error_code: Some(err.code), status_code: err.status_code.into(), raw_connector_response, response_headers, connector_metadata: HashMap::new(), state: None, } } }; Ok(response) } pub fn generate_payment_post_authenticate_response<T: PaymentMethodDataTypes>( router_data_v2: RouterDataV2< PostAuthenticate, PaymentFlowData, PaymentsPostAuthenticateData<T>, PaymentsResponseData, >, ) -> Result<PaymentServicePostAuthenticateResponse, error_stack::Report<ApplicationErrorResponse>> { let transaction_response = router_data_v2.response; let status = router_data_v2.resource_common_data.status; let grpc_status = grpc_api_types::payments::PaymentStatus::foreign_from(status); let raw_connector_response = router_data_v2 .resource_common_data .get_raw_connector_response(); let response_headers = router_data_v2 .resource_common_data .get_connector_response_headers_as_map(); let response = match transaction_response { Ok(response) => match response { PaymentsResponseData::PostAuthenticateResponse { authentication_data, connector_response_reference_id, status_code, } => PaymentServicePostAuthenticateResponse { transaction_id: None, redirection_data: None, connector_metadata: HashMap::new(), network_txn_id: None, response_ref_id: connector_response_reference_id.map(|id| { grpc_api_types::payments::Identifier { id_type: Some(grpc_api_types::payments::identifier::IdType::Id(id)), } }), authentication_data: authentication_data.map(ForeignFrom::foreign_from), incremental_authorization_allowed: None, status: grpc_status.into(), error_message: None, error_code: None, raw_connector_response,
{ "chunk": 29, "crate": "grpc-server", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_grpc-server_8474653292087038763_30
clm
mini_chunk
// connector-service/backend/grpc-server/src/server/payments.rs status_code: status_code.into(), response_headers, state: None, }, _ => { return Err(ApplicationErrorResponse::BadRequest(ApiError { sub_code: "INVALID_RESPONSE".to_owned(), error_identifier: 400, error_message: "Invalid response type for post authenticate".to_owned(), error_object: None, }) .into()) } }, Err(err) => { let status = err .attempt_status .map(grpc_api_types::payments::PaymentStatus::foreign_from) .unwrap_or_default(); PaymentServicePostAuthenticateResponse { transaction_id: Some(grpc_api_types::payments::Identifier { id_type: Some( grpc_api_types::payments::identifier::IdType::NoResponseIdMarker(()), ), }), redirection_data: None, network_txn_id: None, response_ref_id: None, authentication_data: None, incremental_authorization_allowed: None, status: status.into(), error_message: Some(err.message), error_code: Some(err.code), status_code: err.status_code.into(), response_headers, raw_connector_response, connector_metadata: HashMap::new(), state: None, } } }; Ok(response) }
{ "chunk": 30, "crate": "grpc-server", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_grpc-server_-8187443272928636517_0
clm
mini_chunk
// connector-service/backend/grpc-server/src/server/disputes.rs use std::sync::Arc; use common_utils::errors::CustomResult; use connector_integration::types::ConnectorData; use domain_types::{ connector_flow::{Accept, DefendDispute, FlowName, SubmitEvidence}, connector_types::{ AcceptDisputeData, DisputeDefendData, DisputeFlowData, DisputeResponseData, SubmitEvidenceData, }, errors::{ApiError, ApplicationErrorResponse}, payment_method_data::DefaultPCIHolder, router_data::{ConnectorAuthType, ErrorResponse}, router_data_v2::RouterDataV2, types::{ generate_accept_dispute_response, generate_defend_dispute_response, generate_submit_evidence_response, }, utils::ForeignTryFrom, }; use error_stack::ResultExt; use external_services; use grpc_api_types::payments::{ dispute_service_server::DisputeService, AcceptDisputeRequest, AcceptDisputeResponse, DisputeDefendRequest, DisputeDefendResponse, DisputeResponse, DisputeServiceGetRequest, DisputeServiceSubmitEvidenceRequest, DisputeServiceSubmitEvidenceResponse, DisputeServiceTransformRequest, DisputeServiceTransformResponse, WebhookEventType, WebhookResponseContent, }; use interfaces::connector_integration_v2::BoxedConnectorIntegrationV2; use tracing::info; use crate::{ configs::Config, error::{IntoGrpcStatus, ReportSwitchExt, ResultExtGrpc}, implement_connector_operation, request::RequestData, utils::{grpc_logging_wrapper, MetadataPayload}, }; // Helper trait for dispute operations trait DisputeOperationsInternal { async fn internal_defend( &self, request: RequestData<DisputeDefendRequest>, ) -> Result<tonic::Response<DisputeDefendResponse>, tonic::Status>; } pub struct Disputes { pub config: Arc<Config>, } impl DisputeOperationsInternal for Disputes { implement_connector_operation!( fn_name: internal_defend, log_prefix: "DEFEND_DISPUTE", request_type: DisputeDefendRequest, response_type: DisputeDefendResponse, flow_marker: DefendDispute, resource_common_data_type: DisputeFlowData, request_data_type: DisputeDefendData, response_data_type: DisputeResponseData, request_data_constructor: DisputeDefendData::foreign_try_from, common_flow_data_constructor: DisputeFlowData::foreign_try_from, generate_response_fn: generate_defend_dispute_response, all_keys_required: None ); } #[tonic::async_trait] impl DisputeService for Disputes { #[tracing::instrument( name = "dispute_submit_evidence", fields( name = common_utils::consts::NAME, service_name = tracing::field::Empty, service_method = FlowName::SubmitEvidence.to_string(), request_body = tracing::field::Empty, response_body = tracing::field::Empty, error_message = tracing::field::Empty, merchant_id = tracing::field::Empty, gateway = tracing::field::Empty, request_id = tracing::field::Empty, status_code = tracing::field::Empty, message_ = "Golden Log Line (incoming)", response_time = tracing::field::Empty, tenant_id = tracing::field::Empty, flow = FlowName::SubmitEvidence.to_string(), flow_specific_fields.status = tracing::field::Empty, ) skip(self, request) )] async fn submit_evidence( &self, request: tonic::Request<DisputeServiceSubmitEvidenceRequest>, ) -> Result<tonic::Response<DisputeServiceSubmitEvidenceResponse>, tonic::Status> { info!("DISPUTE_FLOW: initiated"); let service_name = request .extensions() .get::<String>() .cloned() .unwrap_or_else(|| "DisputeService".to_string()); Box::pin(grpc_logging_wrapper( request, &service_name, self.config.clone(), common_utils::events::FlowName::SubmitEvidence, |request_data| { let service_name = service_name.clone(); async move { let payload = request_data.payload; let MetadataPayload { connector, request_id, lineage_ids, connector_auth_type,
{ "chunk": 0, "crate": "grpc-server", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_grpc-server_-8187443272928636517_1
clm
mini_chunk
// connector-service/backend/grpc-server/src/server/disputes.rs reference_id, shadow_mode, .. } = request_data.extracted_metadata; let connector_data: ConnectorData<DefaultPCIHolder> = ConnectorData::get_connector_by_name(&connector); let connector_integration: BoxedConnectorIntegrationV2< '_, SubmitEvidence, DisputeFlowData, SubmitEvidenceData, DisputeResponseData, > = connector_data.connector.get_connector_integration_v2(); let dispute_data = SubmitEvidenceData::foreign_try_from(payload.clone()) .map_err(|e| e.into_grpc_status())?; let dispute_flow_data = DisputeFlowData::foreign_try_from(( payload.clone(), self.config.connectors.clone(), )) .map_err(|e| e.into_grpc_status())?; let router_data: RouterDataV2< SubmitEvidence, DisputeFlowData, SubmitEvidenceData, DisputeResponseData, > = RouterDataV2 { flow: std::marker::PhantomData, resource_common_data: dispute_flow_data, connector_auth_type, request: dispute_data, response: Err(ErrorResponse::default()), }; let event_params = external_services::service::EventProcessingParams { connector_name: &connector.to_string(), service_name: &service_name, flow_name: common_utils::events::FlowName::SubmitEvidence, event_config: &self.config.events, request_id: &request_id, lineage_ids: &lineage_ids, reference_id: &reference_id, shadow_mode, }; let response = external_services::service::execute_connector_processing_step( &self.config.proxy, connector_integration, router_data, None, event_params, None, common_enums::CallConnectorAction::Trigger, ) .await .switch() .map_err(|e| e.into_grpc_status())?; let dispute_response = generate_submit_evidence_response(response) .map_err(|e| e.into_grpc_status())?; Ok(tonic::Response::new(dispute_response)) } }, )) .await } #[tracing::instrument( name = "dispute_sync", fields( name = common_utils::consts::NAME, service_name = tracing::field::Empty, service_method = FlowName::Dsync.to_string(), request_body = tracing::field::Empty, response_body = tracing::field::Empty, error_message = tracing::field::Empty, merchant_id = tracing::field::Empty, gateway = tracing::field::Empty, request_id = tracing::field::Empty, status_code = tracing::field::Empty, message_ = "Golden Log Line (incoming)", response_time = tracing::field::Empty, tenant_id = tracing::field::Empty, flow = FlowName::Dsync.to_string(), flow_specific_fields.status = tracing::field::Empty, ) skip(self, request) )] async fn get( &self, request: tonic::Request<DisputeServiceGetRequest>, ) -> Result<tonic::Response<DisputeResponse>, tonic::Status> { // For now, return a basic dispute response // This will need proper implementation based on domain logic let service_name = request .extensions() .get::<String>() .cloned()
{ "chunk": 1, "crate": "grpc-server", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_grpc-server_-8187443272928636517_2
clm
mini_chunk
// connector-service/backend/grpc-server/src/server/disputes.rs .unwrap_or_else(|| "DisputeService".to_string()); grpc_logging_wrapper( request, &service_name, self.config.clone(), common_utils::events::FlowName::Dsync, |request_data| async { let _payload = request_data.payload; let response = DisputeResponse { ..Default::default() }; Ok(tonic::Response::new(response)) }, ) .await } #[tracing::instrument( name = "dispute_defend", fields( name = common_utils::consts::NAME, service_name = tracing::field::Empty, service_method = FlowName::DefendDispute.to_string(), request_body = tracing::field::Empty, response_body = tracing::field::Empty, error_message = tracing::field::Empty, merchant_id = tracing::field::Empty, gateway = tracing::field::Empty, request_id = tracing::field::Empty, status_code = tracing::field::Empty, message_ = "Golden Log Line (incoming)", response_time = tracing::field::Empty, tenant_id = tracing::field::Empty, flow = FlowName::DefendDispute.to_string(), flow_specific_fields.status = tracing::field::Empty, ) skip(self, request) )] async fn defend( &self, request: tonic::Request<DisputeDefendRequest>, ) -> Result<tonic::Response<DisputeDefendResponse>, tonic::Status> { let service_name = request .extensions() .get::<String>() .cloned() .unwrap_or_else(|| "DisputeService".to_string()); grpc_logging_wrapper( request, &service_name, self.config.clone(), common_utils::events::FlowName::DefendDispute, |request_data| async move { self.internal_defend(request_data).await }, ) .await } #[tracing::instrument( name = "dispute_accept", fields( name = common_utils::consts::NAME, service_name = tracing::field::Empty, service_method = FlowName::AcceptDispute.to_string(), request_body = tracing::field::Empty, response_body = tracing::field::Empty, error_message = tracing::field::Empty, merchant_id = tracing::field::Empty, gateway = tracing::field::Empty, request_id = tracing::field::Empty, status_code = tracing::field::Empty, message_ = "Golden Log Line (incoming)", response_time = tracing::field::Empty, tenant_id = tracing::field::Empty, flow = FlowName::AcceptDispute.to_string(), flow_specific_fields.status = tracing::field::Empty, ) skip(self, request) )] async fn accept( &self, request: tonic::Request<AcceptDisputeRequest>, ) -> Result<tonic::Response<AcceptDisputeResponse>, tonic::Status> { info!("DISPUTE_FLOW: initiated"); let service_name = request .extensions() .get::<String>() .cloned() .unwrap_or_else(|| "DisputeService".to_string()); grpc_logging_wrapper( request, &service_name, self.config.clone(), common_utils::events::FlowName::AcceptDispute, |request_data| { let service_name = service_name.clone(); async move { let payload = request_data.payload; let MetadataPayload { connector, request_id, lineage_ids, connector_auth_type, reference_id, shadow_mode, .. } = request_data.extracted_metadata; let connector_data: ConnectorData<DefaultPCIHolder> = ConnectorData::get_connector_by_name(&connector); let connector_integration: BoxedConnectorIntegrationV2< '_, Accept, DisputeFlowData,
{ "chunk": 2, "crate": "grpc-server", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_grpc-server_-8187443272928636517_3
clm
mini_chunk
// connector-service/backend/grpc-server/src/server/disputes.rs AcceptDisputeData, DisputeResponseData, > = connector_data.connector.get_connector_integration_v2(); let dispute_data = AcceptDisputeData::foreign_try_from(payload.clone()) .map_err(|e| e.into_grpc_status())?; let dispute_flow_data = DisputeFlowData::foreign_try_from(( payload.clone(), self.config.connectors.clone(), )) .map_err(|e| e.into_grpc_status())?; let router_data: RouterDataV2< Accept, DisputeFlowData, AcceptDisputeData, DisputeResponseData, > = RouterDataV2 { flow: std::marker::PhantomData, resource_common_data: dispute_flow_data, connector_auth_type, request: dispute_data, response: Err(ErrorResponse::default()), }; let event_params = external_services::service::EventProcessingParams { connector_name: &connector.to_string(), service_name: &service_name, flow_name: common_utils::events::FlowName::AcceptDispute, event_config: &self.config.events, request_id: &request_id, lineage_ids: &lineage_ids, reference_id: &reference_id, shadow_mode, }; let response = external_services::service::execute_connector_processing_step( &self.config.proxy, connector_integration, router_data, None, event_params, None, common_enums::CallConnectorAction::Trigger, ) .await .switch() .map_err(|e| e.into_grpc_status())?; let dispute_response = generate_accept_dispute_response(response) .map_err(|e| e.into_grpc_status())?; Ok(tonic::Response::new(dispute_response)) } }, ) .await } #[tracing::instrument( name = "distpute_transform", fields( name = common_utils::consts::NAME, service_name = tracing::field::Empty, service_method = FlowName::IncomingWebhook.to_string(), request_body = tracing::field::Empty, response_body = tracing::field::Empty, error_message = tracing::field::Empty, merchant_id = tracing::field::Empty, gateway = tracing::field::Empty, request_id = tracing::field::Empty, status_code = tracing::field::Empty, message_ = "Golden Log Line (incoming)", response_time = tracing::field::Empty, tenant_id = tracing::field::Empty, flow = FlowName::IncomingWebhook.to_string(), flow_specific_fields.status = tracing::field::Empty, ) skip(self, request) )] async fn transform( &self, request: tonic::Request<DisputeServiceTransformRequest>, ) -> Result<tonic::Response<DisputeServiceTransformResponse>, tonic::Status> { let service_name = request .extensions() .get::<String>() .cloned() .unwrap_or_else(|| "DisputeService".to_string()); grpc_logging_wrapper( request, &service_name, self.config.clone(), common_utils::events::FlowName::IncomingWebhook, |request_data| { async move { let connector = request_data.extracted_metadata.connector; let connector_auth_details = request_data.extracted_metadata.connector_auth_type; let payload = request_data.payload; let request_details = payload
{ "chunk": 3, "crate": "grpc-server", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_grpc-server_-8187443272928636517_4
clm
mini_chunk
// connector-service/backend/grpc-server/src/server/disputes.rs .request_details .map(domain_types::connector_types::RequestDetails::foreign_try_from) .ok_or_else(|| { tonic::Status::invalid_argument("missing request_details in the payload") })? .map_err(|e| e.into_grpc_status())?; let webhook_secrets = payload .webhook_secrets .map(|details| { domain_types::connector_types::ConnectorWebhookSecrets::foreign_try_from( details, ) .map_err(|e| e.into_grpc_status()) }) .transpose()?; // Get connector data let connector_data = ConnectorData::get_connector_by_name(&connector); let source_verified = connector_data .connector .verify_webhook_source( request_details.clone(), webhook_secrets.clone(), Some(connector_auth_details.clone()), ) .switch() .map_err(|e| e.into_grpc_status())?; let content = get_disputes_webhook_content( connector_data, request_details, webhook_secrets, Some(connector_auth_details), ) .await .map_err(|e| e.into_grpc_status())?; let response = DisputeServiceTransformResponse { event_type: WebhookEventType::WebhookDisputeOpened.into(), content: Some(content), source_verified, response_ref_id: None, }; Ok(tonic::Response::new(response)) } }, ) .await } } async fn get_disputes_webhook_content( connector_data: ConnectorData<DefaultPCIHolder>, request_details: domain_types::connector_types::RequestDetails, webhook_secrets: Option<domain_types::connector_types::ConnectorWebhookSecrets>, connector_auth_details: Option<ConnectorAuthType>, ) -> CustomResult<WebhookResponseContent, ApplicationErrorResponse> { let webhook_details = connector_data .connector .process_dispute_webhook(request_details, webhook_secrets, connector_auth_details) .switch()?; // Generate response let response = DisputeResponse::foreign_try_from(webhook_details).change_context( ApplicationErrorResponse::InternalServerError(ApiError { sub_code: "RESPONSE_CONSTRUCTION_ERROR".to_string(), error_identifier: 500, error_message: "Error while constructing response".to_string(), error_object: None, }), )?; Ok(WebhookResponseContent { content: Some( grpc_api_types::payments::webhook_response_content::Content::DisputesResponse(response), ), }) }
{ "chunk": 4, "crate": "grpc-server", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_grpc-server_6130414747938716573_0
clm
mini_chunk
// connector-service/backend/grpc-server/src/server/health_check.rs use grpc_api_types::health_check::{self, health_server}; use tonic::{Request, Response, Status}; pub struct HealthCheck; #[tonic::async_trait] impl health_server::Health for HealthCheck { async fn check( &self, request: Request<health_check::HealthCheckRequest>, ) -> Result<Response<health_check::HealthCheckResponse>, Status> { tracing::debug!(?request, "health_check request"); let response = health_check::HealthCheckResponse { status: health_check::health_check_response::ServingStatus::Serving.into(), }; tracing::info!(?response, "health_check response"); Ok(Response::new(response)) } }
{ "chunk": 0, "crate": "grpc-server", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_interfaces_-4210072120393553698_0
clm
mini_chunk
// connector-service/backend/interfaces/src/verification.rs use common_utils::{crypto, CustomResult}; use domain_types::{ connector_types::ConnectorWebhookSecrets, router_data::ConnectorAuthType, router_data_v2::RouterDataV2, }; use error_stack::ResultExt; pub enum ConnectorSourceVerificationSecrets { AuthHeaders(ConnectorAuthType), WebhookSecret(ConnectorWebhookSecrets), AuthWithWebHookSecret { auth_headers: ConnectorAuthType, webhook_secret: ConnectorWebhookSecrets, }, } /// Core trait for source verification pub trait SourceVerification<Flow, ResourceCommonData, Req, Resp> { fn get_secrets( &self, _secrets: ConnectorSourceVerificationSecrets, ) -> CustomResult<Vec<u8>, domain_types::errors::ConnectorError> { Ok(Vec::new()) } /// Get the verification algorithm being used fn get_algorithm( &self, ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, domain_types::errors::ConnectorError> { Ok(Box::new(crypto::NoAlgorithm)) } /// Get the signature/hash value from the payload for verification fn get_signature( &self, _payload: &[u8], _router_data: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>, _secrets: &[u8], ) -> CustomResult<Vec<u8>, domain_types::errors::ConnectorError> { Ok(Vec::new()) } /// Get the message/payload that should be verified fn get_message( &self, payload: &[u8], _router_data: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>, _secrets: &[u8], ) -> CustomResult<Vec<u8>, domain_types::errors::ConnectorError> { Ok(payload.to_owned()) } /// Perform the verification fn verify( &self, router_data: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>, secrets: ConnectorSourceVerificationSecrets, payload: &[u8], ) -> CustomResult<bool, domain_types::errors::ConnectorError> { let algorithm = self.get_algorithm()?; let extracted_secrets = self.get_secrets(secrets)?; let signature = self.get_signature(payload, router_data, &extracted_secrets)?; let message = self.get_message(payload, router_data, &extracted_secrets)?; // Verify the signature against the message algorithm .verify_signature(&extracted_secrets, &signature, &message) .change_context(domain_types::errors::ConnectorError::SourceVerificationFailed) } }
{ "chunk": 0, "crate": "interfaces", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_interfaces_-1138128169477141208_0
clm
mini_chunk
// connector-service/backend/interfaces/src/connector_types.rs use std::collections::HashSet; use common_enums::{AttemptStatus, CaptureMethod, PaymentMethod, PaymentMethodType}; use common_utils::{CustomResult, SecretSerdeValue}; use domain_types::{ connector_flow, connector_types::{ AcceptDisputeData, AccessTokenRequestData, AccessTokenResponseData, ConnectorCustomerData, ConnectorCustomerResponse, ConnectorSpecifications, ConnectorWebhookSecrets, DisputeDefendData, DisputeFlowData, DisputeResponseData, DisputeWebhookDetailsResponse, EventType, PaymentCreateOrderData, PaymentCreateOrderResponse, PaymentFlowData, PaymentMethodTokenResponse, PaymentMethodTokenizationData, PaymentVoidData, PaymentsAuthenticateData, PaymentsAuthorizeData, PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsPostAuthenticateData, PaymentsPreAuthenticateData, PaymentsResponseData, PaymentsSyncData, RefundFlowData, RefundSyncData, RefundWebhookDetailsResponse, RefundsData, RefundsResponseData, RepeatPaymentData, RequestDetails, SessionTokenRequestData, SessionTokenResponseData, SetupMandateRequestData, SubmitEvidenceData, WebhookDetailsResponse, }, payment_method_data::{PaymentMethodData, PaymentMethodDataTypes}, router_data::ConnectorAuthType, types::{PaymentMethodDataType, PaymentMethodDetails, SupportedPaymentMethods}, }; use error_stack::ResultExt; use crate::{api::ConnectorCommon, connector_integration_v2::ConnectorIntegrationV2}; pub trait ConnectorServiceTrait<T: PaymentMethodDataTypes>: ConnectorCommon + ValidationTrait + PaymentAuthorizeV2<T> + PaymentSyncV2 + PaymentOrderCreate + PaymentSessionToken + PaymentAccessToken + CreateConnectorCustomer + PaymentTokenV2<T> + PaymentVoidV2 + PaymentVoidPostCaptureV2 + IncomingWebhook + RefundV2 + PaymentCapture + SetupMandateV2<T> + RepeatPaymentV2 + AcceptDispute + RefundSyncV2 + DisputeDefend + SubmitEvidenceV2 + PaymentPreAuthenticateV2<T> + PaymentAuthenticateV2<T> + PaymentPostAuthenticateV2<T> { } pub trait PaymentVoidV2: ConnectorIntegrationV2<connector_flow::Void, PaymentFlowData, PaymentVoidData, PaymentsResponseData> { } pub trait PaymentVoidPostCaptureV2: ConnectorIntegrationV2< connector_flow::VoidPC, PaymentFlowData, PaymentsCancelPostCaptureData, PaymentsResponseData, > { } pub type BoxedConnector<T> = Box<&'static (dyn ConnectorServiceTrait<T> + Sync)>; pub trait ValidationTrait { fn should_do_order_create(&self) -> bool { false } fn should_do_session_token(&self) -> bool { false } fn should_do_access_token(&self) -> bool { false } fn should_create_connector_customer(&self) -> bool { false } fn should_do_payment_method_token(&self) -> bool { false } } pub trait PaymentOrderCreate: ConnectorIntegrationV2< connector_flow::CreateOrder, PaymentFlowData, PaymentCreateOrderData, PaymentCreateOrderResponse, > { } pub trait PaymentSessionToken: ConnectorIntegrationV2< connector_flow::CreateSessionToken, PaymentFlowData, SessionTokenRequestData, SessionTokenResponseData, > { } pub trait PaymentAccessToken: ConnectorIntegrationV2< connector_flow::CreateAccessToken, PaymentFlowData, AccessTokenRequestData, AccessTokenResponseData, > { } pub trait CreateConnectorCustomer: ConnectorIntegrationV2< connector_flow::CreateConnectorCustomer, PaymentFlowData, ConnectorCustomerData, ConnectorCustomerResponse, > { } pub trait PaymentTokenV2<T: PaymentMethodDataTypes>: ConnectorIntegrationV2< connector_flow::PaymentMethodToken, PaymentFlowData, PaymentMethodTokenizationData<T>, PaymentMethodTokenResponse, > { } pub trait PaymentAuthorizeV2<T: PaymentMethodDataTypes>: ConnectorIntegrationV2< connector_flow::Authorize, PaymentFlowData, PaymentsAuthorizeData<T>, PaymentsResponseData, > { } pub trait PaymentSyncV2: ConnectorIntegrationV2< connector_flow::PSync, PaymentFlowData, PaymentsSyncData, PaymentsResponseData, > { } pub trait RefundV2: ConnectorIntegrationV2<connector_flow::Refund, RefundFlowData, RefundsData, RefundsResponseData> { } pub trait RefundSyncV2: ConnectorIntegrationV2<connector_flow::RSync, RefundFlowData, RefundSyncData, RefundsResponseData> { } pub trait PaymentCapture:
{ "chunk": 0, "crate": "interfaces", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_interfaces_-1138128169477141208_1
clm
mini_chunk
// connector-service/backend/interfaces/src/connector_types.rs ConnectorIntegrationV2< connector_flow::Capture, PaymentFlowData, PaymentsCaptureData, PaymentsResponseData, > { } pub trait SetupMandateV2<T: PaymentMethodDataTypes>: ConnectorIntegrationV2< connector_flow::SetupMandate, PaymentFlowData, SetupMandateRequestData<T>, PaymentsResponseData, > { } pub trait RepeatPaymentV2: ConnectorIntegrationV2< connector_flow::RepeatPayment, PaymentFlowData, RepeatPaymentData, PaymentsResponseData, > { } pub trait AcceptDispute: ConnectorIntegrationV2< connector_flow::Accept, DisputeFlowData, AcceptDisputeData, DisputeResponseData, > { } pub trait SubmitEvidenceV2: ConnectorIntegrationV2< connector_flow::SubmitEvidence, DisputeFlowData, SubmitEvidenceData, DisputeResponseData, > { } pub trait DisputeDefend: ConnectorIntegrationV2< connector_flow::DefendDispute, DisputeFlowData, DisputeDefendData, DisputeResponseData, > { } pub trait PaymentPreAuthenticateV2<T: PaymentMethodDataTypes>: ConnectorIntegrationV2< connector_flow::PreAuthenticate, PaymentFlowData, PaymentsPreAuthenticateData<T>, PaymentsResponseData, > { } pub trait PaymentAuthenticateV2<T: PaymentMethodDataTypes>: ConnectorIntegrationV2< connector_flow::Authenticate, PaymentFlowData, PaymentsAuthenticateData<T>, PaymentsResponseData, > { } pub trait PaymentPostAuthenticateV2<T: PaymentMethodDataTypes>: ConnectorIntegrationV2< connector_flow::PostAuthenticate, PaymentFlowData, PaymentsPostAuthenticateData<T>, PaymentsResponseData, > { } pub trait IncomingWebhook { fn verify_webhook_source( &self, _request: RequestDetails, _connector_webhook_secret: Option<ConnectorWebhookSecrets>, _connector_account_details: Option<ConnectorAuthType>, ) -> Result<bool, error_stack::Report<domain_types::errors::ConnectorError>> { Ok(false) } /// fn get_webhook_source_verification_signature fn get_webhook_source_verification_signature( &self, _request: &RequestDetails, _connector_webhook_secret: &ConnectorWebhookSecrets, ) -> Result<Vec<u8>, error_stack::Report<domain_types::errors::ConnectorError>> { Ok(Vec::new()) } /// fn get_webhook_source_verification_message fn get_webhook_source_verification_message( &self, _request: &RequestDetails, _connector_webhook_secret: &ConnectorWebhookSecrets, ) -> Result<Vec<u8>, error_stack::Report<domain_types::errors::ConnectorError>> { Ok(Vec::new()) } fn get_event_type( &self, _request: RequestDetails, _connector_webhook_secret: Option<ConnectorWebhookSecrets>, _connector_account_details: Option<ConnectorAuthType>, ) -> Result<EventType, error_stack::Report<domain_types::errors::ConnectorError>> { Err( domain_types::errors::ConnectorError::NotImplemented("get_event_type".to_string()) .into(), ) } fn process_payment_webhook( &self, _request: RequestDetails, _connector_webhook_secret: Option<ConnectorWebhookSecrets>, _connector_account_details: Option<ConnectorAuthType>, ) -> Result<WebhookDetailsResponse, error_stack::Report<domain_types::errors::ConnectorError>> { Err(domain_types::errors::ConnectorError::NotImplemented( "process_payment_webhook".to_string(), ) .into()) } fn process_refund_webhook( &self, _request: RequestDetails, _connector_webhook_secret: Option<ConnectorWebhookSecrets>, _connector_account_details: Option<ConnectorAuthType>, ) -> Result< RefundWebhookDetailsResponse, error_stack::Report<domain_types::errors::ConnectorError>, > { Err(domain_types::errors::ConnectorError::NotImplemented( "process_refund_webhook".to_string(), ) .into()) } fn process_dispute_webhook( &self, _request: RequestDetails, _connector_webhook_secret: Option<ConnectorWebhookSecrets>, _connector_account_details: Option<ConnectorAuthType>, ) -> Result< DisputeWebhookDetailsResponse, error_stack::Report<domain_types::errors::ConnectorError>, > { Err(domain_types::errors::ConnectorError::NotImplemented(
{ "chunk": 1, "crate": "interfaces", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_interfaces_-1138128169477141208_2
clm
mini_chunk
// connector-service/backend/interfaces/src/connector_types.rs "process_dispute_webhook".to_string(), ) .into()) } /// fn get_webhook_resource_object fn get_webhook_resource_object( &self, _request: RequestDetails, ) -> Result< Box<dyn hyperswitch_masking::ErasedMaskSerialize>, error_stack::Report<domain_types::errors::ConnectorError>, > { Err(domain_types::errors::ConnectorError::NotImplemented( "get_webhook_resource_object".to_string(), ) .into()) } } /// trait ConnectorValidation pub trait ConnectorValidation: ConnectorCommon + ConnectorSpecifications { /// Validate, the payment request against the connector supported features fn validate_connector_against_payment_request( &self, capture_method: Option<CaptureMethod>, payment_method: PaymentMethod, pmt: Option<PaymentMethodType>, ) -> CustomResult<(), domain_types::errors::ConnectorError> { let capture_method = capture_method.unwrap_or_default(); let is_default_capture_method = [CaptureMethod::Automatic].contains(&capture_method); let is_feature_supported = match self.get_supported_payment_methods() { Some(supported_payment_methods) => { let connector_payment_method_type_info = get_connector_payment_method_type_info( supported_payment_methods, payment_method, pmt, self.id(), )?; connector_payment_method_type_info .map(|payment_method_type_info| { payment_method_type_info .supported_capture_methods .contains(&capture_method) }) .unwrap_or(true) } None => is_default_capture_method, }; if is_feature_supported { Ok(()) } else { Err(domain_types::errors::ConnectorError::NotSupported { message: capture_method.to_string(), connector: self.id(), } .into()) } } /// fn validate_mandate_payment fn validate_mandate_payment( &self, pm_type: Option<PaymentMethodType>, _pm_data: PaymentMethodData<domain_types::payment_method_data::DefaultPCIHolder>, ) -> CustomResult<(), domain_types::errors::ConnectorError> { let connector = self.id(); match pm_type { Some(pm_type) => Err(domain_types::errors::ConnectorError::NotSupported { message: format!("{pm_type} mandate payment"), connector, } .into()), None => Err(domain_types::errors::ConnectorError::NotSupported { message: " mandate payment".to_string(), connector, } .into()), } } /// fn validate_psync_reference_id fn validate_psync_reference_id( &self, data: &PaymentsSyncData, _is_three_ds: bool, _status: AttemptStatus, _connector_meta_data: Option<SecretSerdeValue>, ) -> CustomResult<(), domain_types::errors::ConnectorError> { data.connector_transaction_id .get_connector_transaction_id() .change_context(domain_types::errors::ConnectorError::MissingConnectorTransactionID) .map(|_| ()) } /// fn is_webhook_source_verification_mandatory fn is_webhook_source_verification_mandatory(&self) -> bool { false } } fn get_connector_payment_method_type_info( supported_payment_method: &SupportedPaymentMethods, payment_method: PaymentMethod, payment_method_type: Option<PaymentMethodType>, connector: &'static str, ) -> CustomResult<Option<PaymentMethodDetails>, domain_types::errors::ConnectorError> { let payment_method_details = supported_payment_method .get(&payment_method) .ok_or_else(|| domain_types::errors::ConnectorError::NotSupported { message: payment_method.to_string(), connector, })?; payment_method_type .map(|pmt| { payment_method_details.get(&pmt).cloned().ok_or_else(|| { domain_types::errors::ConnectorError::NotSupported {
{ "chunk": 2, "crate": "interfaces", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_interfaces_-1138128169477141208_3
clm
mini_chunk
// connector-service/backend/interfaces/src/connector_types.rs message: format!("{payment_method} {pmt}"), connector, } .into() }) }) .transpose() } pub fn is_mandate_supported<T: PaymentMethodDataTypes>( selected_pmd: PaymentMethodData<T>, payment_method_type: Option<PaymentMethodType>, mandate_implemented_pmds: HashSet<PaymentMethodDataType>, connector: &'static str, ) -> Result<(), error_stack::Report<domain_types::errors::ConnectorError>> { if mandate_implemented_pmds.contains(&PaymentMethodDataType::from(selected_pmd.clone())) { Ok(()) } else { match payment_method_type { Some(pm_type) => Err(domain_types::errors::ConnectorError::NotSupported { message: format!("{pm_type} mandate payment"), connector, } .into()), None => Err(domain_types::errors::ConnectorError::NotSupported { message: "mandate payment".to_string(), connector, } .into()), } } }
{ "chunk": 3, "crate": "interfaces", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_interfaces_5453561983035210806_0
clm
mini_chunk
// connector-service/backend/interfaces/src/lib.rs pub mod api; pub mod authentication; pub mod connector_integration_v2; pub mod connector_types; pub mod disputes; pub mod events; pub mod integrity; pub mod routing; pub mod verification; pub mod webhooks;
{ "chunk": 0, "crate": "interfaces", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_interfaces_5771632197509749618_0
clm
mini_chunk
// connector-service/backend/interfaces/src/disputes.rs //! Disputes interface use common_utils::types::StringMinorUnit; use time::PrimitiveDateTime; /// struct DisputePayload #[derive(Default, Debug)] pub struct DisputePayload { /// amount pub amount: StringMinorUnit, /// currency pub currency: common_enums::enums::Currency, /// dispute_stage pub dispute_stage: common_enums::enums::DisputeStage, /// connector_status pub connector_status: String, /// connector_dispute_id pub connector_dispute_id: String, /// connector_reason pub connector_reason: Option<String>, /// connector_reason_code pub connector_reason_code: Option<String>, /// challenge_required_by pub challenge_required_by: Option<PrimitiveDateTime>, /// created_at pub created_at: Option<PrimitiveDateTime>, /// updated_at pub updated_at: Option<PrimitiveDateTime>, }
{ "chunk": 0, "crate": "interfaces", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_interfaces_808631026467843198_0
clm
mini_chunk
// connector-service/backend/interfaces/src/integrity.rs //! Integrity checking framework for payment flows //! //! This module provides a comprehensive integrity checking system for payment operations. //! It ensures that request and response data remain consistent across connector interactions //! by comparing critical fields like amounts, currencies, and transaction identifiers. use common_utils::errors::IntegrityCheckError; use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret}; // Domain type imports use domain_types::connector_types::{ AcceptDisputeData, AccessTokenRequestData, ConnectorCustomerData, DisputeDefendData, PaymentCreateOrderData, PaymentMethodTokenizationData, PaymentVoidData, PaymentsAuthenticateData, PaymentsAuthorizeData, PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsPostAuthenticateData, PaymentsPreAuthenticateData, PaymentsSyncData, RefundSyncData, RefundsData, RepeatPaymentData, SessionTokenRequestData, SetupMandateRequestData, SubmitEvidenceData, }; use domain_types::{ payment_method_data::PaymentMethodDataTypes, router_request_types::{ AcceptDisputeIntegrityObject, AccessTokenIntegrityObject, AuthenticateIntegrityObject, AuthoriseIntegrityObject, CaptureIntegrityObject, CreateConnectorCustomerIntegrityObject, CreateOrderIntegrityObject, DefendDisputeIntegrityObject, PaymentMethodTokenIntegrityObject, PaymentSynIntegrityObject, PaymentVoidIntegrityObject, PaymentVoidPostCaptureIntegrityObject, PostAuthenticateIntegrityObject, PreAuthenticateIntegrityObject, RefundIntegrityObject, RefundSyncIntegrityObject, RepeatPaymentIntegrityObject, SessionTokenIntegrityObject, SetupMandateIntegrityObject, SubmitEvidenceIntegrityObject, }, }; // ======================================================================== // CORE TRAITS // ======================================================================== /// Trait for integrity objects that can perform field-by-field comparison pub trait FlowIntegrity { /// The integrity object type for this flow type IntegrityObject; /// Compare request and response integrity objects /// /// # Arguments /// * `req_integrity_object` - Integrity object derived from the request /// * `res_integrity_object` - Integrity object derived from the response /// * `connector_transaction_id` - Optional transaction ID for error context /// /// # Returns /// * `Ok(())` if all fields match /// * `Err(IntegrityCheckError)` if there are mismatches fn compare( req_integrity_object: Self::IntegrityObject, res_integrity_object: Self::IntegrityObject, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError>; } /// Trait for data types that can provide integrity objects pub trait GetIntegrityObject<T: FlowIntegrity> { /// Extract integrity object from response data fn get_response_integrity_object(&self) -> Option<T::IntegrityObject>; /// Generate integrity object from request data fn get_request_integrity_object(&self) -> T::IntegrityObject; } /// Trait for data types that can perform integrity checks pub trait CheckIntegrity<Request, T> { /// Perform integrity check between request and response /// /// # Arguments /// * `request` - The request object containing integrity data /// * `connector_transaction_id` - Optional transaction ID for error context /// /// # Returns /// * `Ok(())` if integrity check passes or no response integrity object exists /// * `Err(IntegrityCheckError)` if integrity check fails fn check_integrity( &self, request: &Request, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError>; } // ======================================================================== // CHECK INTEGRITY IMPLEMENTATIONS // ======================================================================== /// Generic implementation of CheckIntegrity that works for all payment flow types. /// This implementation: /// 1. Checks if response has an integrity object /// 2. If yes, compares it with request integrity object /// 3. If no, passes the check (no integrity validation needed) macro_rules! impl_check_integrity { ($data_type:ident <$generic:ident>) => {
{ "chunk": 0, "crate": "interfaces", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_interfaces_808631026467843198_1
clm
mini_chunk
// connector-service/backend/interfaces/src/integrity.rs impl<T, Request, $generic> CheckIntegrity<Request, T> for $data_type<$generic> where T: FlowIntegrity, Request: GetIntegrityObject<T>, $generic: PaymentMethodDataTypes, { fn check_integrity( &self, request: &Request, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { match request.get_response_integrity_object() { Some(res_integrity_object) => { let req_integrity_object = request.get_request_integrity_object(); T::compare( req_integrity_object, res_integrity_object, connector_transaction_id, ) } None => Ok(()), } } } }; ($data_type:ty) => { impl<T, Request> CheckIntegrity<Request, T> for $data_type where T: FlowIntegrity, Request: GetIntegrityObject<T>, { fn check_integrity( &self, request: &Request, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { match request.get_response_integrity_object() { Some(res_integrity_object) => { let req_integrity_object = request.get_request_integrity_object(); T::compare( req_integrity_object, res_integrity_object, connector_transaction_id, ) } None => Ok(()), } } } }; } // Apply the macro to all payment flow data types impl_check_integrity!(PaymentsAuthorizeData<S>); impl_check_integrity!(PaymentCreateOrderData); impl_check_integrity!(SetupMandateRequestData<S>); impl_check_integrity!(PaymentsSyncData); impl_check_integrity!(PaymentVoidData); impl_check_integrity!(PaymentsCancelPostCaptureData); impl_check_integrity!(RefundsData); impl_check_integrity!(PaymentsCaptureData); impl_check_integrity!(AcceptDisputeData); impl_check_integrity!(DisputeDefendData); impl_check_integrity!(RefundSyncData); impl_check_integrity!(SessionTokenRequestData); impl_check_integrity!(AccessTokenRequestData); impl_check_integrity!(PaymentMethodTokenizationData<S>); impl_check_integrity!(SubmitEvidenceData); impl_check_integrity!(RepeatPaymentData); impl_check_integrity!(PaymentsAuthenticateData<S>); impl_check_integrity!(PaymentsPostAuthenticateData<S>); impl_check_integrity!(PaymentsPreAuthenticateData<S>); impl_check_integrity!(ConnectorCustomerData); // ======================================================================== // GET INTEGRITY OBJECT IMPLEMENTATIONS // ======================================================================== impl<T: PaymentMethodDataTypes> GetIntegrityObject<AuthoriseIntegrityObject> for PaymentsAuthorizeData<T> { fn get_response_integrity_object(&self) -> Option<AuthoriseIntegrityObject> { self.integrity_object.clone() } fn get_request_integrity_object(&self) -> AuthoriseIntegrityObject { AuthoriseIntegrityObject { amount: self.minor_amount, currency: self.currency, } } } impl GetIntegrityObject<CreateOrderIntegrityObject> for PaymentCreateOrderData { fn get_response_integrity_object(&self) -> Option<CreateOrderIntegrityObject> { self.integrity_object.clone() } fn get_request_integrity_object(&self) -> CreateOrderIntegrityObject { CreateOrderIntegrityObject { amount: self.amount, currency: self.currency, } } } impl<T: PaymentMethodDataTypes> GetIntegrityObject<SetupMandateIntegrityObject> for SetupMandateRequestData<T> { fn get_response_integrity_object(&self) -> Option<SetupMandateIntegrityObject> { self.integrity_object.clone() } fn get_request_integrity_object(&self) -> SetupMandateIntegrityObject { SetupMandateIntegrityObject { amount: self.minor_amount, currency: self.currency, } } }
{ "chunk": 1, "crate": "interfaces", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_interfaces_808631026467843198_2
clm
mini_chunk
// connector-service/backend/interfaces/src/integrity.rs impl GetIntegrityObject<PaymentSynIntegrityObject> for PaymentsSyncData { fn get_response_integrity_object(&self) -> Option<PaymentSynIntegrityObject> { self.integrity_object.clone() } fn get_request_integrity_object(&self) -> PaymentSynIntegrityObject { PaymentSynIntegrityObject { amount: self.amount, currency: self.currency, } } } impl GetIntegrityObject<PaymentVoidIntegrityObject> for PaymentVoidData { fn get_response_integrity_object(&self) -> Option<PaymentVoidIntegrityObject> { self.integrity_object.clone() } fn get_request_integrity_object(&self) -> PaymentVoidIntegrityObject { PaymentVoidIntegrityObject { connector_transaction_id: self.connector_transaction_id.clone(), } } } impl GetIntegrityObject<PaymentVoidPostCaptureIntegrityObject> for PaymentsCancelPostCaptureData { fn get_response_integrity_object(&self) -> Option<PaymentVoidPostCaptureIntegrityObject> { self.integrity_object.clone() } fn get_request_integrity_object(&self) -> PaymentVoidPostCaptureIntegrityObject { PaymentVoidPostCaptureIntegrityObject { connector_transaction_id: self.connector_transaction_id.clone(), } } } impl GetIntegrityObject<RefundIntegrityObject> for RefundsData { fn get_response_integrity_object(&self) -> Option<RefundIntegrityObject> { self.integrity_object.clone() } fn get_request_integrity_object(&self) -> RefundIntegrityObject { RefundIntegrityObject { refund_amount: self.minor_refund_amount, currency: self.currency, } } } impl GetIntegrityObject<CaptureIntegrityObject> for PaymentsCaptureData { fn get_response_integrity_object(&self) -> Option<CaptureIntegrityObject> { self.integrity_object.clone() } fn get_request_integrity_object(&self) -> CaptureIntegrityObject { CaptureIntegrityObject { amount_to_capture: self.minor_amount_to_capture, currency: self.currency, } } } impl GetIntegrityObject<AcceptDisputeIntegrityObject> for AcceptDisputeData { fn get_response_integrity_object(&self) -> Option<AcceptDisputeIntegrityObject> { self.integrity_object.clone() } fn get_request_integrity_object(&self) -> AcceptDisputeIntegrityObject { AcceptDisputeIntegrityObject { connector_dispute_id: self.connector_dispute_id.clone(), } } } impl GetIntegrityObject<DefendDisputeIntegrityObject> for DisputeDefendData { fn get_response_integrity_object(&self) -> Option<DefendDisputeIntegrityObject> { self.integrity_object.clone() } fn get_request_integrity_object(&self) -> DefendDisputeIntegrityObject { DefendDisputeIntegrityObject { connector_dispute_id: self.connector_dispute_id.clone(), defense_reason_code: self.defense_reason_code.clone(), } } } impl GetIntegrityObject<RefundSyncIntegrityObject> for RefundSyncData { fn get_response_integrity_object(&self) -> Option<RefundSyncIntegrityObject> { self.integrity_object.clone() } fn get_request_integrity_object(&self) -> RefundSyncIntegrityObject { RefundSyncIntegrityObject { connector_transaction_id: self.connector_transaction_id.clone(), connector_refund_id: self.connector_refund_id.clone(), } } } impl GetIntegrityObject<SubmitEvidenceIntegrityObject> for SubmitEvidenceData { fn get_response_integrity_object(&self) -> Option<SubmitEvidenceIntegrityObject> { self.integrity_object.clone() } fn get_request_integrity_object(&self) -> SubmitEvidenceIntegrityObject { SubmitEvidenceIntegrityObject { connector_dispute_id: self.connector_dispute_id.clone(), } } } impl GetIntegrityObject<RepeatPaymentIntegrityObject> for RepeatPaymentData { fn get_response_integrity_object(&self) -> Option<RepeatPaymentIntegrityObject> { self.integrity_object.clone() } fn get_request_integrity_object(&self) -> RepeatPaymentIntegrityObject { RepeatPaymentIntegrityObject { amount: self.amount, currency: self.currency,
{ "chunk": 2, "crate": "interfaces", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_interfaces_808631026467843198_3
clm
mini_chunk
// connector-service/backend/interfaces/src/integrity.rs mandate_reference: match &self.mandate_reference { domain_types::connector_types::MandateReferenceId::ConnectorMandateId( mandate_ref, ) => mandate_ref .get_connector_mandate_id() .unwrap_or_default() .to_string(), domain_types::connector_types::MandateReferenceId::NetworkMandateId( network_mandate, ) => network_mandate.clone(), domain_types::connector_types::MandateReferenceId::NetworkTokenWithNTI(_) => { String::new() } }, } } } impl GetIntegrityObject<SessionTokenIntegrityObject> for SessionTokenRequestData { fn get_response_integrity_object(&self) -> Option<SessionTokenIntegrityObject> { None // Session token responses don't have integrity objects } fn get_request_integrity_object(&self) -> SessionTokenIntegrityObject { SessionTokenIntegrityObject { amount: self.amount, currency: self.currency, } } } impl GetIntegrityObject<AccessTokenIntegrityObject> for AccessTokenRequestData { fn get_response_integrity_object(&self) -> Option<AccessTokenIntegrityObject> { None } fn get_request_integrity_object(&self) -> AccessTokenIntegrityObject { AccessTokenIntegrityObject { grant_type: self.grant_type.clone(), } } } impl<T: PaymentMethodDataTypes> GetIntegrityObject<PaymentMethodTokenIntegrityObject> for PaymentMethodTokenizationData<T> { fn get_response_integrity_object(&self) -> Option<PaymentMethodTokenIntegrityObject> { self.integrity_object.clone() } fn get_request_integrity_object(&self) -> PaymentMethodTokenIntegrityObject { PaymentMethodTokenIntegrityObject { amount: self.amount, currency: self.currency, } } } impl<T: PaymentMethodDataTypes> GetIntegrityObject<PreAuthenticateIntegrityObject> for PaymentsPreAuthenticateData<T> { fn get_response_integrity_object(&self) -> Option<PreAuthenticateIntegrityObject> { None } fn get_request_integrity_object(&self) -> PreAuthenticateIntegrityObject { PreAuthenticateIntegrityObject { amount: self.amount, currency: self.currency.unwrap_or_default(), } } } impl<T: PaymentMethodDataTypes> GetIntegrityObject<AuthenticateIntegrityObject> for PaymentsAuthenticateData<T> { fn get_response_integrity_object(&self) -> Option<AuthenticateIntegrityObject> { None } fn get_request_integrity_object(&self) -> AuthenticateIntegrityObject { AuthenticateIntegrityObject { amount: self.amount, currency: self.currency.unwrap_or_default(), } } } impl<T: PaymentMethodDataTypes> GetIntegrityObject<PostAuthenticateIntegrityObject> for PaymentsPostAuthenticateData<T> { fn get_response_integrity_object(&self) -> Option<PostAuthenticateIntegrityObject> { None } fn get_request_integrity_object(&self) -> PostAuthenticateIntegrityObject { PostAuthenticateIntegrityObject { amount: self.amount, currency: self.currency.unwrap_or_default(), } } } impl GetIntegrityObject<CreateConnectorCustomerIntegrityObject> for ConnectorCustomerData { fn get_response_integrity_object(&self) -> Option<CreateConnectorCustomerIntegrityObject> { None // Customer creation responses don't have integrity objects } fn get_request_integrity_object(&self) -> CreateConnectorCustomerIntegrityObject { CreateConnectorCustomerIntegrityObject { customer_id: self.customer_id.clone(), email: self.email.as_ref().map(|e| { let email_inner = e.peek().clone().expose(); Secret::new(email_inner.expose()) }), } } } // ======================================================================== // FLOW INTEGRITY IMPLEMENTATIONS // ======================================================================== impl FlowIntegrity for AuthoriseIntegrityObject { type IntegrityObject = Self; fn compare( req_integrity_object: Self,
{ "chunk": 3, "crate": "interfaces", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_interfaces_808631026467843198_4
clm
mini_chunk
// connector-service/backend/interfaces/src/integrity.rs res_integrity_object: Self, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { let mut mismatched_fields = Vec::new(); if req_integrity_object.amount != res_integrity_object.amount { mismatched_fields.push(format_mismatch( "amount", &req_integrity_object.amount.to_string(), &res_integrity_object.amount.to_string(), )); } if req_integrity_object.currency != res_integrity_object.currency { mismatched_fields.push(format_mismatch( "currency", &req_integrity_object.currency.to_string(), &res_integrity_object.currency.to_string(), )); } check_integrity_result(mismatched_fields, connector_transaction_id) } } impl FlowIntegrity for CreateOrderIntegrityObject { type IntegrityObject = Self; fn compare( req_integrity_object: Self, res_integrity_object: Self, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { let mut mismatched_fields = Vec::new(); if req_integrity_object.amount != res_integrity_object.amount { mismatched_fields.push(format_mismatch( "amount", &req_integrity_object.amount.to_string(), &res_integrity_object.amount.to_string(), )); } if req_integrity_object.currency != res_integrity_object.currency { mismatched_fields.push(format_mismatch( "currency", &req_integrity_object.currency.to_string(), &res_integrity_object.currency.to_string(), )); } check_integrity_result(mismatched_fields, connector_transaction_id) } } impl FlowIntegrity for SetupMandateIntegrityObject { type IntegrityObject = Self; fn compare( req_integrity_object: Self, res_integrity_object: Self, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { let mut mismatched_fields = Vec::new(); // Handle optional amount field match (req_integrity_object.amount, res_integrity_object.amount) { (Some(req_amount), Some(res_amount)) if req_amount != res_amount => { mismatched_fields.push(format_mismatch( "amount", &req_amount.to_string(), &res_amount.to_string(), )); } (None, Some(_)) | (Some(_), None) => { mismatched_fields.push("amount is missing in request or response".to_string()); } _ => {} } if req_integrity_object.currency != res_integrity_object.currency { mismatched_fields.push(format_mismatch( "currency", &req_integrity_object.currency.to_string(), &res_integrity_object.currency.to_string(), )); } check_integrity_result(mismatched_fields, connector_transaction_id) } } impl FlowIntegrity for PaymentSynIntegrityObject { type IntegrityObject = Self; fn compare( req_integrity_object: Self, res_integrity_object: Self, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { let mut mismatched_fields = Vec::new(); if req_integrity_object.amount != res_integrity_object.amount { mismatched_fields.push(format_mismatch( "amount", &req_integrity_object.amount.to_string(), &res_integrity_object.amount.to_string(), )); } if req_integrity_object.currency != res_integrity_object.currency { mismatched_fields.push(format_mismatch( "currency", &req_integrity_object.currency.to_string(), &res_integrity_object.currency.to_string(), )); } check_integrity_result(mismatched_fields, connector_transaction_id) } } impl FlowIntegrity for PaymentVoidIntegrityObject { type IntegrityObject = Self; fn compare( req_integrity_object: Self, res_integrity_object: Self, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> {
{ "chunk": 4, "crate": "interfaces", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_interfaces_808631026467843198_5
clm
mini_chunk
// connector-service/backend/interfaces/src/integrity.rs let mut mismatched_fields = Vec::new(); if req_integrity_object.connector_transaction_id != res_integrity_object.connector_transaction_id { mismatched_fields.push(format_mismatch( "connector_transaction_id", &req_integrity_object.connector_transaction_id, &res_integrity_object.connector_transaction_id, )); } check_integrity_result(mismatched_fields, connector_transaction_id) } } impl FlowIntegrity for PaymentVoidPostCaptureIntegrityObject { type IntegrityObject = Self; fn compare( req_integrity_object: Self, res_integrity_object: Self, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { let mut mismatched_fields = Vec::new(); if req_integrity_object.connector_transaction_id != res_integrity_object.connector_transaction_id { mismatched_fields.push(format_mismatch( "connector_transaction_id", &req_integrity_object.connector_transaction_id, &res_integrity_object.connector_transaction_id, )); } check_integrity_result(mismatched_fields, connector_transaction_id) } } impl FlowIntegrity for RefundIntegrityObject { type IntegrityObject = Self; fn compare( req_integrity_object: Self, res_integrity_object: Self, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { let mut mismatched_fields = Vec::new(); if req_integrity_object.refund_amount != res_integrity_object.refund_amount { mismatched_fields.push(format_mismatch( "refund_amount", &req_integrity_object.refund_amount.to_string(), &res_integrity_object.refund_amount.to_string(), )); } if req_integrity_object.currency != res_integrity_object.currency { mismatched_fields.push(format_mismatch( "currency", &req_integrity_object.currency.to_string(), &res_integrity_object.currency.to_string(), )); } check_integrity_result(mismatched_fields, connector_transaction_id) } } impl FlowIntegrity for CaptureIntegrityObject { type IntegrityObject = Self; fn compare( req_integrity_object: Self, res_integrity_object: Self, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { let mut mismatched_fields = Vec::new(); if req_integrity_object.amount_to_capture != res_integrity_object.amount_to_capture { mismatched_fields.push(format_mismatch( "amount_to_capture", &req_integrity_object.amount_to_capture.to_string(), &res_integrity_object.amount_to_capture.to_string(), )); } if req_integrity_object.currency != res_integrity_object.currency { mismatched_fields.push(format_mismatch( "currency", &req_integrity_object.currency.to_string(), &res_integrity_object.currency.to_string(), )); } check_integrity_result(mismatched_fields, connector_transaction_id) } } impl FlowIntegrity for AcceptDisputeIntegrityObject { type IntegrityObject = Self; fn compare( req_integrity_object: Self, res_integrity_object: Self, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { let mut mismatched_fields = Vec::new(); if req_integrity_object.connector_dispute_id != res_integrity_object.connector_dispute_id { mismatched_fields.push(format_mismatch( "connector_dispute_id", &req_integrity_object.connector_dispute_id, &res_integrity_object.connector_dispute_id, )); } check_integrity_result(mismatched_fields, connector_transaction_id) } } impl FlowIntegrity for DefendDisputeIntegrityObject { type IntegrityObject = Self; fn compare( req_integrity_object: Self, res_integrity_object: Self, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { let mut mismatched_fields = Vec::new();
{ "chunk": 5, "crate": "interfaces", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_interfaces_808631026467843198_6
clm
mini_chunk
// connector-service/backend/interfaces/src/integrity.rs if req_integrity_object.connector_dispute_id != res_integrity_object.connector_dispute_id { mismatched_fields.push(format_mismatch( "connector_dispute_id", &req_integrity_object.connector_dispute_id, &res_integrity_object.connector_dispute_id, )); } if req_integrity_object.defense_reason_code != res_integrity_object.defense_reason_code { mismatched_fields.push(format_mismatch( "defense_reason_code", &req_integrity_object.defense_reason_code, &res_integrity_object.defense_reason_code, )); } check_integrity_result(mismatched_fields, connector_transaction_id) } } impl FlowIntegrity for RefundSyncIntegrityObject { type IntegrityObject = Self; fn compare( req_integrity_object: Self, res_integrity_object: Self, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { let mut mismatched_fields = Vec::new(); if req_integrity_object.connector_transaction_id != res_integrity_object.connector_transaction_id { mismatched_fields.push(format_mismatch( "connector_transaction_id", &req_integrity_object.connector_transaction_id, &res_integrity_object.connector_transaction_id, )); } if req_integrity_object.connector_refund_id != res_integrity_object.connector_refund_id { mismatched_fields.push(format_mismatch( "connector_refund_id", &req_integrity_object.connector_refund_id, &res_integrity_object.connector_refund_id, )); } check_integrity_result(mismatched_fields, connector_transaction_id) } } impl FlowIntegrity for SubmitEvidenceIntegrityObject { type IntegrityObject = Self; fn compare( req_integrity_object: Self, res_integrity_object: Self, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { let mut mismatched_fields = Vec::new(); if req_integrity_object.connector_dispute_id != res_integrity_object.connector_dispute_id { mismatched_fields.push(format_mismatch( "connector_dispute_id", &req_integrity_object.connector_dispute_id, &res_integrity_object.connector_dispute_id, )); } check_integrity_result(mismatched_fields, connector_transaction_id) } } impl FlowIntegrity for RepeatPaymentIntegrityObject { type IntegrityObject = Self; fn compare( req_integrity_object: Self, res_integrity_object: Self, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { let mut mismatched_fields = Vec::new(); if req_integrity_object.amount != res_integrity_object.amount { mismatched_fields.push(format_mismatch( "amount", &req_integrity_object.amount.to_string(), &res_integrity_object.amount.to_string(), )); } if req_integrity_object.currency != res_integrity_object.currency { mismatched_fields.push(format_mismatch( "currency", &req_integrity_object.currency.to_string(), &res_integrity_object.currency.to_string(), )); } if req_integrity_object.mandate_reference != res_integrity_object.mandate_reference { mismatched_fields.push(format_mismatch( "mandate_reference", &req_integrity_object.mandate_reference, &res_integrity_object.mandate_reference, )); } check_integrity_result(mismatched_fields, connector_transaction_id) } } impl FlowIntegrity for SessionTokenIntegrityObject { type IntegrityObject = Self; fn compare( req_integrity_object: Self, res_integrity_object: Self, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { let mut mismatched_fields = Vec::new(); if req_integrity_object.amount != res_integrity_object.amount { mismatched_fields.push(format_mismatch( "amount",
{ "chunk": 6, "crate": "interfaces", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_interfaces_808631026467843198_7
clm
mini_chunk
// connector-service/backend/interfaces/src/integrity.rs &req_integrity_object.amount.to_string(), &res_integrity_object.amount.to_string(), )); } if req_integrity_object.currency != res_integrity_object.currency { mismatched_fields.push(format_mismatch( "currency", &req_integrity_object.currency.to_string(), &res_integrity_object.currency.to_string(), )); } check_integrity_result(mismatched_fields, connector_transaction_id) } } impl FlowIntegrity for AccessTokenIntegrityObject { type IntegrityObject = Self; fn compare( req_integrity_object: Self, res_integrity_object: Self, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { let mut mismatched_fields = Vec::new(); if req_integrity_object.grant_type != res_integrity_object.grant_type { mismatched_fields.push(format_mismatch( "grant_type", &req_integrity_object.grant_type, &res_integrity_object.grant_type, )); } check_integrity_result(mismatched_fields, connector_transaction_id) } } impl FlowIntegrity for PaymentMethodTokenIntegrityObject { type IntegrityObject = Self; fn compare( req_integrity_object: Self, res_integrity_object: Self, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { let mut mismatched_fields = Vec::new(); if req_integrity_object.amount != res_integrity_object.amount { mismatched_fields.push(format_mismatch( "amount", &req_integrity_object.amount.to_string(), &res_integrity_object.amount.to_string(), )); } if req_integrity_object.currency != res_integrity_object.currency { mismatched_fields.push(format_mismatch( "currency", &req_integrity_object.currency.to_string(), &res_integrity_object.currency.to_string(), )); } check_integrity_result(mismatched_fields, connector_transaction_id) } } impl FlowIntegrity for PreAuthenticateIntegrityObject { type IntegrityObject = Self; fn compare( req_integrity_object: Self, res_integrity_object: Self, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { let mut mismatched_fields = Vec::new(); if req_integrity_object.amount != res_integrity_object.amount { mismatched_fields.push(format_mismatch( "amount", &req_integrity_object.amount.to_string(), &res_integrity_object.amount.to_string(), )); } if req_integrity_object.currency != res_integrity_object.currency { mismatched_fields.push(format_mismatch( "currency", &req_integrity_object.currency.to_string(), &res_integrity_object.currency.to_string(), )); } check_integrity_result(mismatched_fields, connector_transaction_id) } } impl FlowIntegrity for AuthenticateIntegrityObject { type IntegrityObject = Self; fn compare( req_integrity_object: Self, res_integrity_object: Self, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { let mut mismatched_fields = Vec::new(); if req_integrity_object.amount != res_integrity_object.amount { mismatched_fields.push(format_mismatch( "amount", &req_integrity_object.amount.to_string(), &res_integrity_object.amount.to_string(), )); } if req_integrity_object.currency != res_integrity_object.currency { mismatched_fields.push(format_mismatch( "currency", &req_integrity_object.currency.to_string(), &res_integrity_object.currency.to_string(), )); } check_integrity_result(mismatched_fields, connector_transaction_id) } } impl FlowIntegrity for PostAuthenticateIntegrityObject { type IntegrityObject = Self; fn compare( req_integrity_object: Self, res_integrity_object: Self, connector_transaction_id: Option<String>,
{ "chunk": 7, "crate": "interfaces", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_interfaces_808631026467843198_8
clm
mini_chunk
// connector-service/backend/interfaces/src/integrity.rs ) -> Result<(), IntegrityCheckError> { let mut mismatched_fields = Vec::new(); if req_integrity_object.amount != res_integrity_object.amount { mismatched_fields.push(format_mismatch( "amount", &req_integrity_object.amount.to_string(), &res_integrity_object.amount.to_string(), )); } if req_integrity_object.currency != res_integrity_object.currency { mismatched_fields.push(format_mismatch( "currency", &req_integrity_object.currency.to_string(), &res_integrity_object.currency.to_string(), )); } check_integrity_result(mismatched_fields, connector_transaction_id) } } impl FlowIntegrity for CreateConnectorCustomerIntegrityObject { type IntegrityObject = Self; fn compare( req_integrity_object: Self, res_integrity_object: Self, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { let mut mismatched_fields = Vec::new(); // Check customer_id if req_integrity_object.customer_id != res_integrity_object.customer_id { let req_customer_id = req_integrity_object .customer_id .as_ref() .map(|s| s.clone().expose()) .unwrap_or_else(|| "None".to_string()); let res_customer_id = res_integrity_object .customer_id .as_ref() .map(|s| s.clone().expose()) .unwrap_or_else(|| "None".to_string()); mismatched_fields.push(format_mismatch( "customer_id", &req_customer_id, &res_customer_id, )); } // Check email if req_integrity_object.email != res_integrity_object.email { let req_email = req_integrity_object .email .as_ref() .map(|s| s.clone().expose()) .unwrap_or_else(|| "None".to_string()); let res_email = res_integrity_object .email .as_ref() .map(|s| s.clone().expose()) .unwrap_or_else(|| "None".to_string()); mismatched_fields.push(format_mismatch("email", &req_email, &res_email)); } check_integrity_result(mismatched_fields, connector_transaction_id) } } // ======================================================================== // UTILITY FUNCTIONS // ======================================================================== /// Helper function to format field mismatch messages #[inline] fn format_mismatch(field: &str, expected: &str, found: &str) -> String { format!("{field} expected {expected} but found {found}") } /// Helper function to generate integrity check result #[inline] fn check_integrity_result( mismatched_fields: Vec<String>, connector_transaction_id: Option<String>, ) -> Result<(), IntegrityCheckError> { if mismatched_fields.is_empty() { Ok(()) } else { let field_names = mismatched_fields.join(", "); Err(IntegrityCheckError { field_names, connector_transaction_id, }) } }
{ "chunk": 8, "crate": "interfaces", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_interfaces_3630394773618043277_0
clm
mini_chunk
// connector-service/backend/interfaces/src/webhooks.rs use common_utils::{crypto, ext_traits::ValueExt, CustomResult}; use domain_types::connector_types::ConnectorWebhookSecrets; use error_stack::ResultExt; use hyperswitch_masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::api::{ApplicationResponse, ConnectorCommon}; #[derive(Debug)] pub struct IncomingWebhookRequestDetails<'a> { /// method pub method: http::Method, /// uri pub uri: http::Uri, /// headers pub headers: &'a actix_web::http::header::HeaderMap, /// body pub body: &'a [u8], /// query_params pub query_params: String, } #[derive(Debug)] pub enum IncomingWebhookFlowError { /// Resource not found for the webhook ResourceNotFound, /// Internal error for the webhook InternalError, } /// Trait defining incoming webhook #[async_trait::async_trait] pub trait IncomingWebhook: ConnectorCommon + Sync { /// fn get_webhook_body_decoding_algorithm fn get_webhook_body_decoding_algorithm( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::DecodeMessage + Send>, domain_types::errors::ConnectorError> { Ok(Box::new(crypto::NoAlgorithm)) } /// fn get_webhook_body_decoding_message fn get_webhook_body_decoding_message( &self, request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Vec<u8>, domain_types::errors::ConnectorError> { Ok(request.body.to_vec()) } /// fn decode_webhook_body async fn decode_webhook_body( &self, request: &IncomingWebhookRequestDetails<'_>, merchant_id: &common_utils::id_type::MerchantId, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, connector_name: &str, ) -> CustomResult<Vec<u8>, domain_types::errors::ConnectorError> { let algorithm = self.get_webhook_body_decoding_algorithm(request)?; let message = self .get_webhook_body_decoding_message(request) .change_context(domain_types::errors::ConnectorError::WebhookBodyDecodingFailed)?; let secret = self .get_webhook_source_verification_merchant_secret( merchant_id, connector_name, connector_webhook_details, ) .await .change_context( domain_types::errors::ConnectorError::WebhookSourceVerificationFailed, )?; algorithm .decode_message(&secret.secret, message.into()) .change_context(domain_types::errors::ConnectorError::WebhookBodyDecodingFailed) } /// fn get_webhook_source_verification_algorithm fn get_webhook_source_verification_algorithm( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, domain_types::errors::ConnectorError> { Ok(Box::new(crypto::NoAlgorithm)) } /// fn get_webhook_source_verification_merchant_secret async fn get_webhook_source_verification_merchant_secret( &self, merchant_id: &common_utils::id_type::MerchantId, connector_name: &str, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, ) -> CustomResult<ConnectorWebhookSecrets, domain_types::errors::ConnectorError> { let debug_suffix = format!("For merchant_id: {merchant_id:?}, and connector_name: {connector_name}"); let default_secret = "default_secret".to_string(); let merchant_secret = match connector_webhook_details { Some(merchant_connector_webhook_details) => { let connector_webhook_details = merchant_connector_webhook_details .parse_value::<MerchantConnectorWebhookDetails>( "MerchantConnectorWebhookDetails", ) .change_context_lazy(|| { domain_types::errors::ConnectorError::WebhookSourceVerificationFailed }) .attach_printable_lazy(|| { format!( "Deserializing MerchantConnectorWebhookDetails failed {debug_suffix}" ) })?; ConnectorWebhookSecrets {
{ "chunk": 0, "crate": "interfaces", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_interfaces_3630394773618043277_1
clm
mini_chunk
// connector-service/backend/interfaces/src/webhooks.rs secret: connector_webhook_details .merchant_secret .expose() .into_bytes(), additional_secret: connector_webhook_details.additional_secret, } } None => ConnectorWebhookSecrets { secret: default_secret.into_bytes(), additional_secret: None, }, }; //need to fetch merchant secret from config table with caching in future for enhanced performance //If merchant has not set the secret for webhook source verification, "default_secret" is returned. //So it will fail during verification step and goes to psync flow. Ok(merchant_secret) } /// fn get_webhook_source_verification_signature fn get_webhook_source_verification_signature( &self, _request: &IncomingWebhookRequestDetails<'_>, _connector_webhook_secrets: &ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, domain_types::errors::ConnectorError> { Ok(Vec::new()) } /// fn get_webhook_source_verification_message fn get_webhook_source_verification_message( &self, _request: &IncomingWebhookRequestDetails<'_>, _merchant_id: &common_utils::id_type::MerchantId, _connector_webhook_secrets: &ConnectorWebhookSecrets, ) -> CustomResult<Vec<u8>, domain_types::errors::ConnectorError> { Ok(Vec::new()) } /// fn verify_webhook_source async fn verify_webhook_source( &self, request: &IncomingWebhookRequestDetails<'_>, merchant_id: &common_utils::id_type::MerchantId, connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>, _connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>, connector_name: &str, ) -> CustomResult<bool, domain_types::errors::ConnectorError> { let algorithm = self .get_webhook_source_verification_algorithm(request) .change_context( domain_types::errors::ConnectorError::WebhookSourceVerificationFailed, )?; let connector_webhook_secrets = self .get_webhook_source_verification_merchant_secret( merchant_id, connector_name, connector_webhook_details, ) .await .change_context( domain_types::errors::ConnectorError::WebhookSourceVerificationFailed, )?; let signature = self .get_webhook_source_verification_signature(request, &connector_webhook_secrets) .change_context( domain_types::errors::ConnectorError::WebhookSourceVerificationFailed, )?; let message = self .get_webhook_source_verification_message( request, merchant_id, &connector_webhook_secrets, ) .change_context( domain_types::errors::ConnectorError::WebhookSourceVerificationFailed, )?; algorithm .verify_signature(&connector_webhook_secrets.secret, &signature, &message) .change_context(domain_types::errors::ConnectorError::WebhookSourceVerificationFailed) } /// fn get_webhook_event_type fn get_webhook_event_type( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult<IncomingWebhookEvent, domain_types::errors::ConnectorError>; /// fn get_webhook_resource_object fn get_webhook_resource_object( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult< Box<dyn hyperswitch_masking::ErasedMaskSerialize>, domain_types::errors::ConnectorError, >; /// fn get_webhook_api_response fn get_webhook_api_response( &self, _request: &IncomingWebhookRequestDetails<'_>, _error_kind: Option<IncomingWebhookFlowError>, ) -> CustomResult<ApplicationResponse<serde_json::Value>, domain_types::errors::ConnectorError> { Ok(ApplicationResponse::StatusOk) } /// fn get_dispute_details fn get_dispute_details( &self, _request: &IncomingWebhookRequestDetails<'_>,
{ "chunk": 1, "crate": "interfaces", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_interfaces_3630394773618043277_2
clm
mini_chunk
// connector-service/backend/interfaces/src/webhooks.rs ) -> CustomResult<crate::disputes::DisputePayload, domain_types::errors::ConnectorError> { Err(domain_types::errors::ConnectorError::NotImplemented( "get_dispute_details method".to_string(), ) .into()) } /// fn get_external_authentication_details fn get_external_authentication_details( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult< crate::authentication::ExternalAuthenticationPayload, domain_types::errors::ConnectorError, > { Err(domain_types::errors::ConnectorError::NotImplemented( "get_external_authentication_details method".to_string(), ) .into()) } /// fn get_mandate_details fn get_mandate_details( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult< Option<domain_types::router_flow_types::ConnectorMandateDetails>, domain_types::errors::ConnectorError, > { Ok(None) } /// fn get_network_txn_id fn get_network_txn_id( &self, _request: &IncomingWebhookRequestDetails<'_>, ) -> CustomResult< Option<domain_types::router_flow_types::ConnectorNetworkTxnId>, domain_types::errors::ConnectorError, > { Ok(None) } } #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Copy)] #[serde(rename_all = "snake_case")] pub enum IncomingWebhookEvent { /// Authorization + Capture success PaymentIntentFailure, /// Authorization + Capture failure PaymentIntentSuccess, PaymentIntentProcessing, PaymentIntentPartiallyFunded, PaymentIntentCancelled, PaymentIntentCancelFailure, PaymentIntentAuthorizationSuccess, PaymentIntentAuthorizationFailure, PaymentIntentCaptureSuccess, PaymentIntentCaptureFailure, PaymentActionRequired, EventNotSupported, SourceChargeable, SourceTransactionCreated, RefundFailure, RefundSuccess, DisputeOpened, DisputeExpired, DisputeAccepted, DisputeCancelled, DisputeChallenged, // dispute has been successfully challenged by the merchant DisputeWon, // dispute has been unsuccessfully challenged DisputeLost, MandateActive, MandateRevoked, EndpointVerification, ExternalAuthenticationARes, FrmApproved, FrmRejected, } #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct MerchantConnectorWebhookDetails { pub merchant_secret: Secret<String>, pub additional_secret: Option<Secret<String>>, }
{ "chunk": 2, "crate": "interfaces", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_interfaces_2565298324350207870_0
clm
mini_chunk
// connector-service/backend/interfaces/src/connector_integration_v2.rs //! definition of the new connector integration trait use common_utils::{ events, request::{Method, Request, RequestBuilder, RequestContent}, CustomResult, }; use domain_types::{router_data::ErrorResponse, router_data_v2::RouterDataV2}; use hyperswitch_masking::Maskable; use serde_json::json; use crate::{ api::{self}, verification::SourceVerification, }; /// alias for Box of a type that implements trait ConnectorIntegrationV2 pub type BoxedConnectorIntegrationV2<'a, Flow, ResourceCommonData, Req, Resp> = Box<&'a (dyn ConnectorIntegrationV2<Flow, ResourceCommonData, Req, Resp> + Send + Sync)>; /// trait with a function that returns BoxedConnectorIntegrationV2 pub trait ConnectorIntegrationAnyV2<Flow, ResourceCommonData, Req, Resp>: Send + Sync + 'static { /// function what returns BoxedConnectorIntegrationV2 fn get_connector_integration_v2( &self, ) -> BoxedConnectorIntegrationV2<'_, Flow, ResourceCommonData, Req, Resp>; } impl<S, Flow, ResourceCommonData, Req, Resp> ConnectorIntegrationAnyV2<Flow, ResourceCommonData, Req, Resp> for S where S: ConnectorIntegrationV2<Flow, ResourceCommonData, Req, Resp> + Send + Sync, { fn get_connector_integration_v2( &self, ) -> BoxedConnectorIntegrationV2<'_, Flow, ResourceCommonData, Req, Resp> { Box::new(self) } } /// The new connector integration trait with an additional ResourceCommonData generic parameter pub trait ConnectorIntegrationV2<Flow, ResourceCommonData, Req, Resp>: ConnectorIntegrationAnyV2<Flow, ResourceCommonData, Req, Resp> + Sync + api::ConnectorCommon + SourceVerification<Flow, ResourceCommonData, Req, Resp> { /// returns a vec of tuple of header key and value fn get_headers( &self, _req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>, ) -> CustomResult<Vec<(String, Maskable<String>)>, domain_types::errors::ConnectorError> { Ok(vec![]) } /// returns content type fn get_content_type(&self) -> &'static str { mime::APPLICATION_JSON.essence_str() } /// primarily used when creating signature based on request method of payment flow fn get_http_method(&self) -> Method { Method::Post } /// returns url fn get_url( &self, _req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>, ) -> CustomResult<String, domain_types::errors::ConnectorError> { // metrics::UNIMPLEMENTED_FLOW // .add(1, router_env::metric_attributes!(("connector", self.id()))); // TODO: discuss env Ok(String::new()) } /// returns request body fn get_request_body( &self, _req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>, ) -> CustomResult<Option<RequestContent>, domain_types::errors::ConnectorError> { Ok(None) } /// returns form data fn get_request_form_data( &self, _req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>, ) -> CustomResult<Option<reqwest::multipart::Form>, domain_types::errors::ConnectorError> { Ok(None) } /// builds the request and returns it fn build_request_v2( &self, req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>, ) -> CustomResult<Option<Request>, domain_types::errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(self.get_http_method()) .url(self.get_url(req)?.as_str()) .attach_default_headers() .headers(self.get_headers(req)?) .set_optional_body(self.get_request_body(req)?) .add_certificate(self.get_certificate(req)?) .add_certificate_key(self.get_certificate_key(req)?) .build(), )) } /// accepts the raw api response and decodes it fn handle_response_v2( &self, data: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>, event_builder: Option<&mut events::Event>, _res: domain_types::router_response_types::Response, ) -> CustomResult< RouterDataV2<Flow, ResourceCommonData, Req, Resp>, domain_types::errors::ConnectorError, > where Flow: Clone, ResourceCommonData: Clone, Req: Clone, Resp: Clone, {
{ "chunk": 0, "crate": "interfaces", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_interfaces_2565298324350207870_1
clm
mini_chunk
// connector-service/backend/interfaces/src/connector_integration_v2.rs if let Some(e) = event_builder { e.set_connector_response(&json!({"error": "Not Implemented"})) } Ok(data.clone()) } /// accepts the raw api error response and decodes it fn get_error_response_v2( &self, res: domain_types::router_response_types::Response, event_builder: Option<&mut events::Event>, ) -> CustomResult<ErrorResponse, domain_types::errors::ConnectorError> { if let Some(event) = event_builder { event.set_connector_response(&json!({"error": "Error response parsing not implemented", "status_code": res.status_code})) } Ok(ErrorResponse::get_not_implemented()) } /// accepts the raw 5xx error response and decodes it fn get_5xx_error_response( &self, res: domain_types::router_response_types::Response, event_builder: Option<&mut events::Event>, ) -> CustomResult<ErrorResponse, domain_types::errors::ConnectorError> { let error_message = match res.status_code { 500 => "internal_server_error", 501 => "not_implemented", 502 => "bad_gateway", 503 => "service_unavailable", 504 => "gateway_timeout", 505 => "http_version_not_supported", 506 => "variant_also_negotiates", 507 => "insufficient_storage", 508 => "loop_detected", 510 => "not_extended", 511 => "network_authentication_required", _ => "unknown_error", }; if let Some(event) = event_builder { event.set_connector_response( &json!({"error": error_message, "status_code": res.status_code}), ) } Ok(ErrorResponse { code: res.status_code.to_string(), message: error_message.to_string(), reason: String::from_utf8(res.response.to_vec()).ok(), status_code: res.status_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, }) } // whenever capture sync is implemented at the connector side, this method should be overridden /// retunes the capture sync method // fn get_multiple_capture_sync_method( // &self, // ) -> CustomResult<api::CaptureSyncMethod, domain_types::errors::ConnectorError> { // Err(domain_types::errors::ConnectorError::NotImplemented("multiple capture sync".into()).into()) // } /// returns certificate string fn get_certificate( &self, _req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>, ) -> CustomResult< Option<hyperswitch_masking::Secret<String>>, domain_types::errors::ConnectorError, > { Ok(None) } /// returns private key string fn get_certificate_key( &self, _req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>, ) -> CustomResult< Option<hyperswitch_masking::Secret<String>>, domain_types::errors::ConnectorError, > { Ok(None) } }
{ "chunk": 1, "crate": "interfaces", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_interfaces_-6275142288305207495_0
clm
mini_chunk
// connector-service/backend/interfaces/src/authentication.rs //! Authentication interface /// struct ExternalAuthenticationPayload #[derive(Clone, serde::Deserialize, Debug, serde::Serialize, PartialEq, Eq)] pub struct ExternalAuthenticationPayload { /// trans_status pub trans_status: common_enums::TransactionStatus, /// authentication_value pub authentication_value: Option<hyperswitch_masking::Secret<String>>, /// eci pub eci: Option<String>, }
{ "chunk": 0, "crate": "interfaces", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_interfaces_-8407711303800421270_0
clm
mini_chunk
// connector-service/backend/interfaces/src/routing.rs use common_enums::RoutableConnectors; use utoipa::ToSchema; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(from = "RoutableChoiceSerde", into = "RoutableChoiceSerde")] pub struct RoutableConnectorChoice { #[serde(skip)] pub choice_kind: RoutableChoiceKind, pub connector: RoutableConnectors, #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, PartialEq)] pub enum RoutableChoiceKind { OnlyConnector, FullStruct, } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(untagged)] pub enum RoutableChoiceSerde { OnlyConnector(Box<RoutableConnectors>), FullStruct { connector: RoutableConnectors, merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, }, } impl From<RoutableChoiceSerde> for RoutableConnectorChoice { fn from(value: RoutableChoiceSerde) -> Self { match value { RoutableChoiceSerde::OnlyConnector(connector) => Self { choice_kind: RoutableChoiceKind::OnlyConnector, connector: *connector, merchant_connector_id: None, }, RoutableChoiceSerde::FullStruct { connector, merchant_connector_id, } => Self { choice_kind: RoutableChoiceKind::FullStruct, connector, merchant_connector_id, }, } } } impl From<RoutableConnectorChoice> for RoutableChoiceSerde { fn from(value: RoutableConnectorChoice) -> Self { match value.choice_kind { RoutableChoiceKind::OnlyConnector => Self::OnlyConnector(Box::new(value.connector)), RoutableChoiceKind::FullStruct => Self::FullStruct { connector: value.connector, merchant_connector_id: value.merchant_connector_id, }, } } }
{ "chunk": 0, "crate": "interfaces", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_interfaces_6351965063930718391_0
clm
mini_chunk
// connector-service/backend/interfaces/src/api.rs use common_enums::CurrencyUnit; use common_utils::{ consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE}, events, CustomResult, }; use domain_types::{ api::{GenericLinks, PaymentLinkAction, RedirectionFormData}, payment_address::RedirectionResponse, router_data::{ConnectorAuthType, ErrorResponse}, types::Connectors, }; use hyperswitch_masking; pub trait ConnectorCommon { /// Name of the connector (in lowercase). fn id(&self) -> &'static str; /// Connector accepted currency unit as either "Base" or "Minor" fn get_currency_unit(&self) -> CurrencyUnit { CurrencyUnit::Minor // Default implementation should be remove once it is implemented in all connectors } /// HTTP header used for authorization. fn get_auth_header( &self, _auth_type: &ConnectorAuthType, ) -> CustomResult< Vec<(String, hyperswitch_masking::Maskable<String>)>, domain_types::errors::ConnectorError, > { Ok(Vec::new()) } /// HTTP `Content-Type` to be used for POST requests. /// Defaults to `application/json`. fn common_get_content_type(&self) -> &'static str { "application/json" } // FIXME write doc - think about this // fn headers(&self) -> Vec<(&str, &str)>; /// The base URL for interacting with the connector's API. fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str; /// common error response for a connector if it is same in all case fn build_error_response( &self, res: domain_types::router_response_types::Response, _event_builder: Option<&mut events::Event>, ) -> CustomResult<ErrorResponse, domain_types::errors::ConnectorError> { Ok(ErrorResponse { status_code: res.status_code, code: NO_ERROR_CODE.to_string(), message: NO_ERROR_MESSAGE.to_string(), reason: None, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, }) } } #[derive(Debug, Eq, PartialEq)] pub enum ApplicationResponse<R> { Json(R), StatusOk, TextPlain(String), JsonForRedirection(RedirectionResponse), Form(Box<RedirectionFormData>), PaymentLinkForm(Box<PaymentLinkAction>), FileData((Vec<u8>, mime::Mime)), JsonWithHeaders((R, Vec<(String, hyperswitch_masking::Maskable<String>)>)), GenericLinkForm(Box<GenericLinks>), }
{ "chunk": 0, "crate": "interfaces", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_interfaces_-1715344998119786497_0
clm
mini_chunk
// connector-service/backend/interfaces/src/events/routing_api_logs.rs //! Routing API logs interface use std::fmt; use common_utils::request::Method; use serde::Serialize; use serde_json::json; use time::OffsetDateTime; use tracing_actix_web::RequestId; use crate::routing::RoutableConnectorChoice; /// RoutingEngine enum #[derive(Debug, Clone, Copy, Serialize)] #[serde(rename_all = "snake_case")] pub enum RoutingEngine { /// Dynamo for routing IntelligentRouter, /// Decision engine for routing DecisionEngine, } /// Method type enum #[derive(Debug, Clone, Copy, Serialize)] #[serde(rename_all = "snake_case")] pub enum ApiMethod { /// grpc call Grpc, /// Rest call Rest(Method), } impl fmt::Display for ApiMethod { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Grpc => write!(f, "Grpc"), Self::Rest(method) => write!(f, "Rest ({method})"), } } } #[derive(Debug, Serialize)] /// RoutingEvent type pub struct RoutingEvent { // tenant_id: common_utils::id_type::TenantId, routable_connectors: String, payment_connector: Option<String>, flow: String, request: String, response: Option<String>, error: Option<String>, url: String, method: String, payment_id: String, profile_id: common_utils::id_type::ProfileId, merchant_id: common_utils::id_type::MerchantId, created_at: i128, status_code: Option<u16>, request_id: String, routing_engine: RoutingEngine, routing_approach: Option<String>, } impl RoutingEvent { /// fn new RoutingEvent #[allow(clippy::too_many_arguments)] pub fn new( // tenant_id: common_utils::id_type::TenantId, routable_connectors: String, flow: &str, request: serde_json::Value, url: String, method: ApiMethod, payment_id: String, profile_id: common_utils::id_type::ProfileId, merchant_id: common_utils::id_type::MerchantId, request_id: Option<RequestId>, routing_engine: RoutingEngine, ) -> Self { Self { // tenant_id, routable_connectors, flow: flow.to_string(), request: request.to_string(), response: None, error: None, url, method: method.to_string(), payment_id, profile_id, merchant_id, created_at: OffsetDateTime::now_utc().unix_timestamp_nanos(), status_code: None, request_id: request_id .map(|i| i.as_hyphenated().to_string()) .unwrap_or("NO_REQUEST_ID".to_string()), routing_engine, payment_connector: None, routing_approach: None, } } /// fn set_response_body pub fn set_response_body<T: Serialize>(&mut self, response: &T) { match hyperswitch_masking::masked_serialize(response) { Ok(masked) => { self.response = Some(masked.to_string()); } Err(er) => self.set_error(json!({"error": er.to_string()})), } } /// fn set_error_response_body pub fn set_error_response_body<T: Serialize>(&mut self, response: &T) { match hyperswitch_masking::masked_serialize(response) { Ok(masked) => { self.error = Some(masked.to_string()); } Err(er) => self.set_error(json!({"error": er.to_string()})), } } /// fn set_error pub fn set_error(&mut self, error: serde_json::Value) { self.error = Some(error.to_string()); } /// set response status code pub fn set_status_code(&mut self, code: u16) { self.status_code = Some(code); } /// set response status code pub fn set_routable_connectors(&mut self, connectors: Vec<RoutableConnectorChoice>) { let connectors = connectors .into_iter() .map(|c| { format!( "{:?}:{:?}", c.connector, c.merchant_connector_id .map(|id| id.get_string_repr().to_string()) .unwrap_or(String::from("")) ) }) .collect::<Vec<_>>() .join(","); self.routable_connectors = connectors; } /// set payment connector pub fn set_payment_connector(&mut self, connector: RoutableConnectorChoice) {
{ "chunk": 0, "crate": "interfaces", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_interfaces_-1715344998119786497_1
clm
mini_chunk
// connector-service/backend/interfaces/src/events/routing_api_logs.rs self.payment_connector = Some(format!( "{:?}:{:?}", connector.connector, connector .merchant_connector_id .map(|id| id.get_string_repr().to_string()) .unwrap_or(String::from("")) )); } /// set routing approach pub fn set_routing_approach(&mut self, approach: String) { self.routing_approach = Some(approach); } /// Returns the request ID of the event. pub fn get_request_id(&self) -> &str { &self.request_id } /// Returns the merchant ID of the event. pub fn get_merchant_id(&self) -> &str { self.merchant_id.get_string_repr() } /// Returns the payment ID of the event. pub fn get_payment_id(&self) -> &str { &self.payment_id } /// Returns the profile ID of the event. pub fn get_profile_id(&self) -> &str { self.profile_id.get_string_repr() } }
{ "chunk": 1, "crate": "interfaces", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_interfaces_-4718366131698857213_0
clm
mini_chunk
// connector-service/backend/interfaces/src/events/connector_api_logs.rs //! Connector API logs interface use common_utils::request::Method; use serde::Serialize; use serde_json::json; use time::OffsetDateTime; use tracing_actix_web::RequestId; /// struct ConnectorEvent #[derive(Debug, Serialize)] pub struct ConnectorEvent { // tenant_id: common_utils::id_type::TenantId, connector_name: String, flow: String, request: String, masked_response: Option<String>, error: Option<String>, url: String, method: String, payment_id: String, merchant_id: common_utils::id_type::MerchantId, created_at: i128, /// Connector Event Request ID pub request_id: String, latency: u128, refund_id: Option<String>, dispute_id: Option<String>, status_code: u16, } impl ConnectorEvent { /// fn new ConnectorEvent #[allow(clippy::too_many_arguments)] pub fn new( // tenant_id: common_utils::id_type::TenantId, connector_name: String, flow: &str, request: serde_json::Value, url: String, method: Method, payment_id: String, merchant_id: common_utils::id_type::MerchantId, request_id: Option<&RequestId>, latency: u128, refund_id: Option<String>, dispute_id: Option<String>, status_code: u16, ) -> Self { Self { // tenant_id, connector_name, flow: flow .rsplit_once("::") .map(|(_, s)| s) .unwrap_or(flow) .to_string(), request: request.to_string(), masked_response: None, error: None, url, method: method.to_string(), payment_id, merchant_id, created_at: OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000, request_id: request_id .map(|i| i.as_hyphenated().to_string()) .unwrap_or("NO_REQUEST_ID".to_string()), latency, refund_id, dispute_id, status_code, } } /// fn set_response_body pub fn set_response_body<T: Serialize>(&mut self, response: &T) { match hyperswitch_masking::masked_serialize(response) { Ok(masked) => { self.masked_response = Some(masked.to_string()); } Err(er) => self.set_error(json!({"error": er.to_string()})), } } /// fn set_error_response_body pub fn set_error_response_body<T: Serialize>(&mut self, response: &T) { match hyperswitch_masking::masked_serialize(response) { Ok(masked) => { self.error = Some(masked.to_string()); } Err(er) => self.set_error(json!({"error": er.to_string()})), } } /// fn set_error pub fn set_error(&mut self, error: serde_json::Value) { self.error = Some(error.to_string()); } }
{ "chunk": 0, "crate": "interfaces", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_example-cli_3032402600771296028_0
clm
mini_chunk
// connector-service/examples/example-cli/src/bin/jus.rs // src/main.rs // --- Imports --- use anyhow::{Context, Result, anyhow}; use clap::{Args, Parser, Subcommand}; use serde::{Deserialize, Serialize}; use std::fs::File; use std::io::BufReader; use std::path::PathBuf; use strum::{EnumString, EnumVariantNames}; // For parsing enums use tonic::transport::{Channel, Endpoint}; // For client connection use tonic::metadata::MetadataMap; use tonic::Extensions; use tonic::Request; use tonic::transport::Channel as TonicChannel; // --- Use gRPC types from the crate --- use grpc_api_types::payments; use grpc_api_types::payments::payment_service_client::PaymentServiceClient; // --- Type Aliases --- type PaymentClient = PaymentServiceClient<TonicChannel>; // --- Constants --- const X_CONNECTOR: &str = "x-connector"; const X_AUTH: &str = "x-auth"; const X_API_KEY: &str = "x-api-key"; const X_KEY1: &str = "x-key1"; const X_API_SECRET: &str = "x-api-secret"; // --- Enums --- #[derive( Debug, Clone, Copy, EnumString, EnumVariantNames, PartialEq, clap::ValueEnum, Serialize, Deserialize, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] enum ConnectorChoice { Adyen, Razorpay, } impl std::fmt::Display for ConnectorChoice { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { ConnectorChoice::Adyen => write!(f, "adyen"), ConnectorChoice::Razorpay => write!(f, "razorpay"), } } } // --- Auth Details --- #[derive(Debug, Args, Clone, Serialize, Deserialize, Default)] struct AuthDetails { /// API key for authentication #[arg(long, required = false)] #[serde(default)] api_key: String, /// Key1 for authentication (used in BodyKey and SignatureKey auth) #[arg(long, required = false)] #[serde(default)] key1: Option<String>, /// API secret for authentication (used in SignatureKey auth) #[arg(long, required = false)] #[serde(default)] api_secret: Option<String>, /// Authentication type (bodykey, headerkey, signaturekey) #[arg(long, value_enum, required = false)] #[serde(default)] auth_type: AuthType, } #[derive(Debug, Clone, Copy, clap::ValueEnum, Serialize, Deserialize, PartialEq, Eq)] #[serde(rename_all = "snake_case")] enum AuthType { /// Use body key authentication BodyKey, /// Use header key authentication HeaderKey, /// Use signature key authentication SignatureKey, } impl Default for AuthType { fn default() -> Self { AuthType::HeaderKey // Using HeaderKey as default since it requires the least parameters } } // --- Card Args --- #[derive(Debug, Args, Clone, Serialize, Deserialize, Default)] struct CardArgs { /// Card number #[arg(long, required = false)] #[serde(default)] number: String, /// Card expiry month #[arg(long, required = false)] #[serde(default)] exp_month: String, /// Card expiry year #[arg(long, required = false)] #[serde(default)] exp_year: String, /// Card CVC #[arg(long, required = false)] #[serde(default)] cvc: String, } // --- Credential file structure --- #[derive(Debug, Clone, Serialize, Deserialize)] struct CredentialData { pub connector: ConnectorChoice, pub auth: AuthDetails, } // --- Payment data file structure --- #[derive(Debug, Clone, Serialize, Deserialize)] struct PaymentData { pub amount: i64, pub currency: String, pub email: Option<String>, pub card: CardArgs, } // --- Sync data file structure --- #[derive(Debug, Clone, Serialize, Deserialize)] struct GetData { pub payment_id: String, } // --- Subcommands --- #[derive(Debug, Subcommand, Clone)] enum Command { /// Create a payment Pay(PayArgs), /// Get payment status Get(GetArgs), } // --- Command Args --- #[derive(Debug, Args, Clone)] struct PayArgs { /// URL of the gRPC server #[arg(long)] url: String, /// Connector to use (can be provided via cred_file) #[arg(long, value_enum)] connector: Option<ConnectorChoice>, /// Amount to charge (can be provided via payment_file) #[arg(long)] amount: Option<i64>, /// Currency to use (usd, gbp, eur) (can be provided via payment_file) #[arg(long)] currency: Option<String>, /// Email address (can be provided via payment_file) #[arg(long)] email: Option<String>, /// Path to credential file (contains connector and auth details)
{ "chunk": 0, "crate": "example-cli", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_example-cli_3032402600771296028_1
clm
mini_chunk
// connector-service/examples/example-cli/src/bin/jus.rs #[arg(long)] cred_file: Option<PathBuf>, /// Path to payment data file (contains payment details) #[arg(long)] payment_file: Option<PathBuf>, /// Capture method (automatic, manual, manual_multiple, scheduled, sequential_automatic) #[arg(long)] capture_method: Option<String>, /// Return URL for redirect flows #[arg(long)] return_url: Option<String>, /// Webhook URL for notifications #[arg(long)] webhook_url: Option<String>, /// Complete authorize URL #[arg(long)] complete_authorize_url: Option<String>, /// Future usage (off_session, on_session) #[arg(long)] future_usage: Option<String>, /// Whether the payment is off session #[arg(long)] off_session: Option<bool>, /// Order category #[arg(long)] order_category: Option<String>, /// Whether enrolled for 3DS #[arg(long)] enrolled_for_3ds: Option<bool>, /// Payment experience (redirect_to_url, invoke_sdk_client, etc.) #[arg(long)] payment_experience: Option<String>, /// Payment method type #[arg(long)] payment_method_type: Option<String>, /// Whether to request incremental authorization #[arg(long)] request_incremental_authorization: Option<bool>, /// Whether to request extended authorization #[arg(long)] request_extended_authorization: Option<bool>, /// Merchant order reference ID #[arg(long)] merchant_order_reference_id: Option<String>, /// Shipping cost #[arg(long)] shipping_cost: Option<i64>, #[command(flatten)] auth: Option<AuthDetails>, #[command(flatten)] card: Option<CardArgs>, } #[derive(Debug, Args, Clone)] struct GetArgs { /// URL of the gRPC server #[arg(long)] url: String, /// Connector to use (can be provided via cred_file) #[arg(long, value_enum)] connector: Option<ConnectorChoice>, /// Resource ID to sync (can be provided via get_file) #[arg(long)] payment_id: Option<String>, /// Path to credential file (contains connector and auth details) #[arg(long)] cred_file: Option<PathBuf>, /// Path to sync data file (contains sync details) #[arg(long)] get_file: Option<PathBuf>, #[command(flatten)] auth: Option<AuthDetails>, } // --- Main CLI Args --- #[derive(Debug, Parser, Clone)] #[command(name = "example-cli")] #[command(about = "gRPC Payment CLI Client", long_about = None)] struct Cli { #[command(subcommand)] command: Command, } // --- gRPC Client Helper --- async fn connect_client(url: &str) -> Result<PaymentClient> { println!("Attempting to connect to gRPC server at: {}", url); // Validate URL format if !url.starts_with("http://") && !url.starts_with("https://") { return Err(anyhow!("URL must start with http:// or https://")); } let endpoint = Endpoint::try_from(url.to_string()) .with_context(|| format!("Failed to create endpoint for URL: {}", url))?; // Add connection timeout let endpoint = endpoint.connect_timeout(std::time::Duration::from_secs(5)); println!("Connecting to server..."); let channel = match endpoint.connect().await { Ok(channel) => { println!("Successfully connected to gRPC server"); channel } Err(err) => { println!("Connection error: {}", err); println!("Troubleshooting tips:"); println!("1. Make sure the server is running on the specified host and port"); println!("2. Check if the URL format is correct (e.g., http://localhost:8080)"); println!("3. Verify that the server is accepting gRPC connections"); println!( "4. Check if there are any network issues or firewalls blocking the connection" ); return Err(anyhow!("Failed to connect to gRPC server: {}", err)); } }; Ok(PaymentClient::new(channel)) } // --- Get Auth Details --- fn get_auth_details(auth: &AuthDetails) -> Result<Vec<(String, String)>> { match auth.auth_type { AuthType::BodyKey => { let key1 = auth .key1 .clone() .ok_or_else(|| anyhow!("key1 is required for BodyKey authentication"))?; Ok(payments::AuthType {
{ "chunk": 1, "crate": "example-cli", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_example-cli_3032402600771296028_2
clm
mini_chunk
// connector-service/examples/example-cli/src/bin/jus.rs auth_details: Some(payments::auth_type::AuthDetails::BodyKey( payments::BodyKey { api_key: auth.api_key.clone(), key1, }, )), }) } AuthType::HeaderKey => Ok(payments::AuthType { auth_details: Some(payments::auth_type::AuthDetails::HeaderKey( payments::HeaderKey { api_key: auth.api_key.clone(), }, )), }), AuthType::SignatureKey => { let key1 = auth .key1 .clone() .ok_or_else(|| anyhow!("key1 is required for SignatureKey authentication"))?; let api_secret = auth .api_secret .clone() .ok_or_else(|| anyhow!("api_secret is required for SignatureKey authentication"))?; Ok(payments::AuthType { auth_details: Some(payments::auth_type::AuthDetails::SignatureKey( payments::SignatureKey { api_key: auth.api_key.clone(), key1, api_secret, }, )), }) } } } // --- Parse Currency --- fn parse_currency(currency_str: &str) -> Result<i32> { match currency_str.to_lowercase().as_str() { "usd" => Ok(payments::Currency::Usd as i32), "gbp" => Ok(payments::Currency::Gbp as i32), "eur" => Ok(payments::Currency::Eur as i32), _ => Err(anyhow!( "Unsupported currency: {}. Use usd, gbp, eur", currency_str )), } } // --- Command Handlers --- // --- File Loading Functions --- fn load_credential_file(file_path: &PathBuf) -> Result<CredentialData> { println!("Loading credential data from: {}", file_path.display()); let file = File::open(file_path) .with_context(|| format!("Failed to open credential file: {}", file_path.display()))?; let reader = BufReader::new(file); let cred_data: CredentialData = serde_json::from_reader(reader) .with_context(|| format!("Failed to parse credential file: {}", file_path.display()))?; Ok(cred_data) } fn load_payment_file(file_path: &PathBuf) -> Result<PaymentData> { println!("Loading payment data from: {}", file_path.display()); let file = File::open(file_path) .with_context(|| format!("Failed to open payment file: {}", file_path.display()))?; let reader = BufReader::new(file); let payment_data: PaymentData = serde_json::from_reader(reader) .with_context(|| format!("Failed to parse payment file: {}", file_path.display()))?; Ok(payment_data) } fn load_sync_file(file_path: &PathBuf) -> Result<GetData> { println!("Loading sync data from: {}", file_path.display()); let file = File::open(file_path) .with_context(|| format!("Failed to open sync file: {}", file_path.display()))?; let reader = BufReader::new(file); let sync_data: GetData = serde_json::from_reader(reader) .with_context(|| format!("Failed to parse sync file: {}", file_path.display()))?; Ok(sync_data) } async fn handle_pay(mut args: PayArgs) -> Result<()> { // Initialize auth details if not provided let mut auth_details = AuthDetails::default(); let mut card_details = CardArgs::default(); // Load credential file if provided if let Some(cred_file) = &args.cred_file { let cred_data = load_credential_file(cred_file)?; // Set connector if not provided in command line if args.connector.is_none() { args.connector = Some(cred_data.connector); println!( "Using connector from credential file: {:?}", cred_data.connector ); } // Set auth details from credential file auth_details = cred_data.auth; println!("Using authentication details from credential file"); } // Override with command line auth if provided if let Some(cmd_auth) = &args.auth { if !cmd_auth.api_key.is_empty() { auth_details.api_key = cmd_auth.api_key.clone(); } if cmd_auth.key1.is_some() { auth_details.key1 = cmd_auth.key1.clone(); }
{ "chunk": 2, "crate": "example-cli", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_example-cli_3032402600771296028_3
clm
mini_chunk
// connector-service/examples/example-cli/src/bin/jus.rs if cmd_auth.api_secret.is_some() { auth_details.api_secret = cmd_auth.api_secret.clone(); } if cmd_auth.auth_type != AuthType::default() { auth_details.auth_type = cmd_auth.auth_type; } } // Load payment file if provided if let Some(payment_file) = &args.payment_file { let payment_data = load_payment_file(payment_file)?; // Set payment data if not provided in command line if args.amount.is_none() { args.amount = Some(payment_data.amount); println!("Using amount from payment file: {}", payment_data.amount); } if args.currency.is_none() { args.currency = Some(payment_data.currency.clone()); println!( "Using currency from payment file: {}", payment_data.currency ); } if args.email.is_none() { args.email = payment_data.email.clone(); println!("Using email from payment file: {:?}", payment_data.email); } // Set card details from payment file card_details = payment_data.card; println!("Using card details from payment file"); } // Override with command line card details if provided if let Some(cmd_card) = &args.card { if !cmd_card.number.is_empty() { card_details.number = cmd_card.number.clone(); } if !cmd_card.exp_month.is_empty() { card_details.exp_month = cmd_card.exp_month.clone(); } if !cmd_card.exp_year.is_empty() { card_details.exp_year = cmd_card.exp_year.clone(); } if !cmd_card.cvc.is_empty() { card_details.cvc = cmd_card.cvc.clone(); } } // Validate required fields let connector = args.connector.ok_or_else(|| { anyhow!("Connector is required either via --connector or in the credential file") })?; let amount = args .amount .ok_or_else(|| anyhow!("Amount is required either via --amount or in the payment file"))?; let currency_str = args.currency.as_deref().ok_or_else(|| { anyhow!("Currency is required either via --currency or in the payment file") })?; let currency = parse_currency(currency_str)?; // Validate card details if card_details.number.is_empty() { return Err(anyhow!( "Card number is required either via --number or in the payment file" )); } if card_details.exp_month.is_empty() { return Err(anyhow!( "Card expiry month is required either via --exp-month or in the payment file" )); } if card_details.exp_year.is_empty() { return Err(anyhow!( "Card expiry year is required either via --exp-year or in the payment file" )); } if card_details.cvc.is_empty() { return Err(anyhow!( "Card CVC is required either via --cvc or in the payment file" )); } // Connect to the server let mut client = connect_client(&args.url).await?; // Create metadata with auth details let mut metadata = MetadataMap::new(); // Add connector metadata.insert( X_CONNECTOR, connector.to_string().parse().unwrap(), ); // Add auth details based on auth type match auth_details.auth_type { AuthType::HeaderKey => { metadata.insert( X_AUTH, "header-key".parse().unwrap(), ); metadata.insert( X_API_KEY, auth_details.api_key.parse().unwrap(), ); } AuthType::BodyKey => { metadata.insert( X_AUTH, "body-key".parse().unwrap(), ); metadata.insert( X_API_KEY, auth_details.api_key.parse().unwrap(), ); if let Some(key1) = auth_details.key1 { metadata.insert( X_KEY1, key1.parse().unwrap(), ); } } AuthType::SignatureKey => { metadata.insert( X_AUTH, "signature-key".parse().unwrap(), ); metadata.insert( X_API_KEY, auth_details.api_key.parse().unwrap(),
{ "chunk": 3, "crate": "example-cli", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_example-cli_3032402600771296028_4
clm
mini_chunk
// connector-service/examples/example-cli/src/bin/jus.rs ); if let Some(key1) = auth_details.key1 { metadata.insert( X_KEY1, key1.parse().unwrap(), ); } if let Some(api_secret) = auth_details.api_secret { metadata.insert( X_API_SECRET, api_secret.parse().unwrap(), ); } } } let request = payments::PaymentsAuthorizeRequest { amount, currency, payment_method: payments::PaymentMethod::Card as i32, payment_method_data: Some(payments::PaymentMethodData { data: Some(payments::payment_method_data::Data::Card(payments::Card { card_number: card_details.number, card_exp_month: card_details.exp_month, card_exp_year: card_details.exp_year, card_cvc: card_details.cvc, ..Default::default() })), }), email: args.email, address: Some(payments::PaymentAddress::default()), auth_type: payments::AuthenticationType::NoThreeDs as i32, minor_amount: amount, connector_request_reference_id: format!( "cli-ref-{}", chrono::Utc::now().timestamp_millis() ), capture_method: args.capture_method.map(|cm| { match cm.to_lowercase().as_str() { "automatic" => payments::CaptureMethod::Automatic as i32, "manual" => payments::CaptureMethod::Manual as i32, "manual_multiple" => payments::CaptureMethod::ManualMultiple as i32, "scheduled" => payments::CaptureMethod::Scheduled as i32, "sequential_automatic" => payments::CaptureMethod::SequentialAutomatic as i32, _ => payments::CaptureMethod::Automatic as i32, } }), return_url: args.return_url, webhook_url: args.webhook_url, complete_authorize_url: args.complete_authorize_url, off_session: args.off_session, order_category: args.order_category, enrolled_for_3ds: args.enrolled_for_3ds.unwrap_or(false), payment_experience: args.payment_experience.map(|pe| { match pe.to_lowercase().as_str() { "redirect_to_url" => payments::PaymentExperience::RedirectToUrl as i32, "invoke_sdk_client" => payments::PaymentExperience::InvokeSdkClient as i32, "display_qr_code" => payments::PaymentExperience::DisplayQrCode as i32, "one_click" => payments::PaymentExperience::OneClick as i32, "link_wallet" => payments::PaymentExperience::LinkWallet as i32, "invoke_payment_app" => payments::PaymentExperience::InvokePaymentApp as i32, "display_wait_screen" => payments::PaymentExperience::DisplayWaitScreen as i32, "collect_otp" => payments::PaymentExperience::CollectOtp as i32, _ => payments::PaymentExperience::RedirectToUrl as i32, } }), payment_method_type: args.payment_method_type.map(|pmt| { match pmt.to_lowercase().as_str() { "card" => payments::PaymentMethodType::Credit as i32, "credit" => payments::PaymentMethodType::Credit as i32, "debit" => payments::PaymentMethodType::Debit as i32, _ => payments::PaymentMethodType::Credit as i32, } }), request_incremental_authorization: args.request_incremental_authorization.unwrap_or(false), request_extended_authorization: args.request_extended_authorization.unwrap_or(false), merchant_order_reference_id: args.merchant_order_reference_id, shipping_cost: args.shipping_cost, setup_future_usage: args.future_usage.map(|fu| { match fu.to_lowercase().as_str() { "off_session" => payments::FutureUsage::OffSession as i32, "on_session" => payments::FutureUsage::OnSession as i32, _ => payments::FutureUsage::OffSession as i32, } }), ..Default::default() }; let response = client.payment_authorize(Request::from_parts(metadata, Extensions::default(), request)).await;
{ "chunk": 4, "crate": "example-cli", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_example-cli_3032402600771296028_5
clm
mini_chunk
// connector-service/examples/example-cli/src/bin/jus.rs match response { Ok(response) => { println!( "{}", serde_json::to_string_pretty(&response.into_inner()).unwrap() ); Ok(()) } Err(err) => { println!("Error during authorize call: {:#?}", err); Err(anyhow!("Authorize call failed")) } } } async fn handle_get(mut args: GetArgs) -> Result<()> { // Initialize auth details if not provided let mut auth_details = AuthDetails::default(); // Load credential file if provided if let Some(cred_file) = &args.cred_file { let cred_data = load_credential_file(cred_file)?; // Set connector if not provided in command line if args.connector.is_none() { args.connector = Some(cred_data.connector); println!( "Using connector from credential file: {:?}", cred_data.connector ); } // Set auth details from credential file auth_details = cred_data.auth; println!("Using authentication details from credential file"); } // Override with command line auth if provided if let Some(cmd_auth) = &args.auth { if !cmd_auth.api_key.is_empty() { auth_details.api_key = cmd_auth.api_key.clone(); } if cmd_auth.key1.is_some() { auth_details.key1 = cmd_auth.key1.clone(); } if cmd_auth.api_secret.is_some() { auth_details.api_secret = cmd_auth.api_secret.clone(); } if cmd_auth.auth_type != AuthType::default() { auth_details.auth_type = cmd_auth.auth_type; } } // Load sync file if provided if let Some(get_file) = &args.get_file { let sync_data = load_sync_file(get_file)?; // Set payment_id if not provided in command line if args.payment_id.is_none() { args.payment_id = Some(sync_data.payment_id.clone()); println!("Using resource ID from sync file: {}", sync_data.payment_id); } } // Validate required fields let connector = args.connector.ok_or_else(|| { anyhow!("Connector is required either via --connector or in the credential file") })?; let payment_id = args.payment_id.as_deref().ok_or_else(|| { anyhow!("Resource ID is required either via --resource-id or in the sync file") })?; // Connect to the server let mut client = connect_client(&args.url).await?; // Create metadata with auth details let mut metadata = MetadataMap::new(); // Add connector metadata.insert( X_CONNECTOR, connector.to_string().parse().unwrap(), ); // Add auth details based on auth type match auth_details.auth_type { AuthType::HeaderKey => { metadata.insert( X_AUTH, "header-key".parse().unwrap(), ); metadata.insert( X_API_KEY, auth_details.api_key.parse().unwrap(), ); } AuthType::BodyKey => { metadata.insert( X_AUTH, "body-key".parse().unwrap(), ); metadata.insert( X_API_KEY, auth_details.api_key.parse().unwrap(), ); if let Some(key1) = auth_details.key1 { metadata.insert( X_KEY1, key1.parse().unwrap(), ); } } AuthType::SignatureKey => { metadata.insert( X_AUTH, "signature-key".parse().unwrap(), ); metadata.insert( X_API_KEY, auth_details.api_key.parse().unwrap(), ); if let Some(key1) = auth_details.key1 { metadata.insert( X_KEY1, key1.parse().unwrap(), ); } if let Some(api_secret) = auth_details.api_secret { metadata.insert( X_API_SECRET, api_secret.parse().unwrap(), ); } } } let request = payments::PaymentsSyncRequest { resource_id: payment_id.to_string(), connector_request_reference_id: Some(format!(
{ "chunk": 5, "crate": "example-cli", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_example-cli_3032402600771296028_6
clm
mini_chunk
// connector-service/examples/example-cli/src/bin/jus.rs "cli-sync-ref-{}", chrono::Utc::now().timestamp_millis() )), }; let response = client.payment_sync(Request::from_parts(metadata, Extensions::default(), request)).await; match response { Ok(response) => { println!( "{}", serde_json::to_string_pretty(&response.into_inner()).unwrap() ); Ok(()) } Err(err) => { println!("Error during sync call: {:#?}", err); Err(anyhow!("Sync call failed")) } } } // --- Main --- #[tokio::main] async fn main() -> Result<()> { let cli = Cli::parse(); match &cli.command { Command::Pay(args) => { handle_pay(args.clone()).await?; } Command::Get(args) => { handle_get(args.clone()).await?; } } Ok(()) }
{ "chunk": 6, "crate": "example-cli", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_example-tui_-7964693969177594414_0
clm
mini_chunk
// connector-service/examples/example-tui/src/main.rs // src/main.rs // --- Imports --- use anyhow::{Context, Result, anyhow}; use shelgon::{command, renderer}; // Import shelgon types use std::{env, str::FromStr}; use strum::{EnumString, EnumVariantNames, VariantNames}; // For parsing enums use tokio::runtime::Runtime; // Need runtime for blocking async calls // Import Endpoint for client connection use tonic::{ metadata::MetadataValue, transport::{Channel, Endpoint}, }; // <-- Added Endpoint // --- Use gRPC types from the crate --- use grpc_api_types::payments::{self, Address}; // --- Type Aliases --- // Alias for the client type type PaymentClient = payments::payment_service_client::PaymentServiceClient<Channel>; // --- Enums --- #[derive(Debug, Clone, Copy, EnumString, EnumVariantNames, PartialEq)] #[strum(serialize_all = "snake_case")] enum ConnectorChoice { Adyen, Razorpay, // Add other connectors defined in the crate's payments::Connector enum } impl From<ConnectorChoice> for i32 { fn from(choice: ConnectorChoice) -> Self { match choice { ConnectorChoice::Adyen => payments::Connector::Adyen as i32, ConnectorChoice::Razorpay => payments::Connector::Razorpay as i32, // Add mappings } } } #[derive(Debug, Clone, PartialEq)] enum AuthDetailsChoice { BodyKey { api_key: String, key1: String, }, // Updated HeaderKey to only have api_key HeaderKey { api_key: String, }, // <-- Removed key1 // Add other auth types matching the crate's payments::auth_type::AuthDetails oneof SignatureKey { api_key: String, key1: String, api_secret: String, }, // e.g., NoKey, } // impl From<AuthDetailsChoice> for payments::AuthType { // fn from(choice: AuthDetailsChoice) -> Self { // match choice { // AuthDetailsChoice::BodyKey { api_key, key1 } => payments::AuthType { // auth_details: Some(payments::auth_type::AuthDetails::BodyKey( // payments::BodyKey { api_key, key1 }, // )), // }, // // Updated HeaderKey mapping // AuthDetailsChoice::HeaderKey { api_key } => payments::AuthType { // // <-- Removed key1 // auth_details: Some(payments::auth_type::AuthDetails::HeaderKey( // // Construct HeaderKey correctly using crate type // payments::HeaderKey { api_key }, // <-- Removed key1 // )), // }, // AuthDetailsChoice::SignatureKey { // api_key, // key1, // api_secret, // } => payments::AuthType { // auth_details: Some(payments::auth_type::AuthDetails::SignatureKey( // payments::SignatureKey { // api_key, // key1, // api_secret, // }, // )), // }, // // Add mappings for other AuthDetailsChoice variants if added // // e.g., AuthDetailsChoice::NoKey => payments::AuthType { // // auth_details: Some(payments::auth_type::AuthDetails::NoKey(true)), // // }, // } // } // } // --- Application State --- #[derive(Debug, Default, Clone)] struct AppState { url: Option<String>, connector: Option<ConnectorChoice>, auth_details: Option<String>, card_number: Option<String>, card_exp_month: Option<String>, card_exp_year: Option<String>, card_cvc: Option<String>, amount: Option<i64>, currency: Option<i32>, resource_id: Option<String>, email: Option<String>, api_key: Option<String>, key1: Option<String>, api_secret: Option<String>, } // --- Shelgon Context --- struct ShellContext { state: AppState, // Store the client directly, as it's created from the channel client: Option<PaymentClient>, } // --- Shelgon Executor --- struct PaymentShellExecutor {} // --- Command Parsing (Helper) --- fn parse_command_parts(line: &str) -> Vec<String> { line.split_whitespace().map(String::from).collect() } // --- gRPC Client Helper --- // Corrected function to create endpoint, connect channel, and return client async fn connect_client(url: &str) -> Result<PaymentClient> {
{ "chunk": 0, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_example-tui_-7964693969177594414_1
clm
mini_chunk
// connector-service/examples/example-tui/src/main.rs let endpoint = Endpoint::try_from(url.to_string()) .with_context(|| format!("Failed to create endpoint for URL: {}", url))?; // Optional: Configure endpoint (e.g., timeouts) // let endpoint = endpoint.connect_timeout(std::time::Duration::from_secs(5)); let channel = endpoint .connect() .await .with_context(|| format!("Failed to connect channel to gRPC server at URL: {}", url))?; Ok(PaymentClient::new(channel)) } // --- Command Handlers (Adapted for Shelgon Context) --- fn handle_set(args: &[String], ctx: &mut ShellContext) -> Result<String> { if args.len() < 3 { // Updated help hint for auth headerkey return Err(anyhow!( "Usage: set <key> <value...> \nKeys: url, connector, amount, currency, email, resource_id, auth, card\nAuth Types: bodykey <api_key> <key1>, headerkey <api_key>" )); } let key = args[1].to_lowercase(); let value_parts = &args[2..]; let state = &mut ctx.state; match key.as_str() { "url" => { let new_url = value_parts[0].clone().trim().to_string(); // Disconnect old client if URL changes ctx.client = None; state.url = Some(new_url.clone()); // Attempt to connect immediately when URL is set let rt = Runtime::new().context("Failed to create Tokio runtime for connect")?; match rt.block_on(connect_client(&new_url)) { Ok(client) => { ctx.client = Some(client); // Store the actual client Ok(format!("URL set to: {} and client connected.", new_url)) } Err(e) => { state.url = Some(new_url.clone()); // Provide more context on connection failure Err(anyhow!( "URL set to: {}, but failed to connect client: {:?}", new_url, e )) } } } "connector" => { let connector_str = value_parts[0].to_lowercase(); let connector = ConnectorChoice::from_str(&connector_str).map_err(|_| { anyhow!( "Invalid connector '{}'. Valid options: {:?}", value_parts[0], ConnectorChoice::VARIANTS ) })?; state.connector = Some(connector); Ok(format!("Connector set to: {:?}", connector)) } "amount" => { let amount = value_parts[0] .parse::<i64>() .with_context(|| format!("Invalid amount value: {}", value_parts[0]))?; state.amount = Some(amount); Ok(format!("Amount set to: {}", amount)) } "currency" => { let currency_str = value_parts[0].to_lowercase(); let currency_val = match currency_str.as_str() { "usd" => payments::Currency::Usd as i32, "gbp" => payments::Currency::Gbp as i32, "eur" => payments::Currency::Eur as i32, _ => { return Err(anyhow!( "Unsupported currency: {}. Use usd, gbp, eur, etc.", currency_str )); } }; state.currency = Some(currency_val); Ok(format!( "Currency set to: {} ({})", currency_str, currency_val )) } "email" => { state.email = Some(value_parts[0].clone()); Ok(format!("Email set to: {}", value_parts[0])) } "resource_id" => { state.resource_id = Some(value_parts[0].clone()); Ok(format!("Resource ID set to: {}", value_parts[0])) } // "auth" => { // if value_parts.len() < 1 { // return Err(anyhow!("Usage: set auth <type> [params...]")); // } // let auth_type = value_parts[0].to_lowercase(); // match auth_type.as_str() { // "bodykey" => { // if value_parts.len() != 3 { // return Err(anyhow!("Usage: set auth bodykey <api_key> <key1>")); // }
{ "chunk": 1, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_example-tui_-7964693969177594414_2
clm
mini_chunk
// connector-service/examples/example-tui/src/main.rs // state.auth_details = Some(AuthDetailsChoice::BodyKey { // api_key: value_parts[1].clone(), // key1: value_parts[2].clone(), // }); // Ok("Auth set to: BodyKey".to_string()) // } // "headerkey" => { // // Updated headerkey to expect only api_key // if value_parts.len() != 2 { // // <-- Changed from 3 to 2 // return Err(anyhow!("Usage: set auth headerkey <api_key>")); // <-- Updated usage // } // state.auth_details = Some(AuthDetailsChoice::HeaderKey { // api_key: value_parts[1].clone(), // <-- Only api_key // }); // Ok("Auth set to: HeaderKey".to_string()) // } // "signaturekey" => { // if value_parts.len() != 4 { // return Err(anyhow!("Usage: set auth bodykey <api_key> <key1>")); // } // state.auth_details = Some(AuthDetailsChoice::SignatureKey { // api_key: value_parts[1].clone(), // key1: value_parts[2].clone(), // api_secret: value_parts[3].clone(), // }); // Ok("Auth set to: SignatureKey".to_string()) // } // _ => Err(anyhow!( // "Unknown auth type: {}. Supported: bodykey, headerkey", // auth_type // )), // } // } "api_key" => { state.api_key = Some(value_parts[0].to_string()); Ok(format!("API key set to: {}", value_parts[0])) } "key1" => { state.key1 = Some(value_parts[0].to_string()); Ok(format!("Key1 set to: {}", value_parts[0])) } "auth" => { state.auth_details = Some(value_parts[0].to_string()); Ok(format!("Auth set to: {}", value_parts[0])) } "card" => { if value_parts.len() < 2 { return Err(anyhow!("Usage: set card <field> <value>")); } let field = value_parts[0].to_lowercase(); let value = &value_parts[1]; match field.as_str() { "number" => { state.card_number = Some(value.clone()); Ok("Card number set".to_string()) } "exp_month" => { state.card_exp_month = Some(value.clone()); Ok("Card expiry month set".to_string()) } "exp_year" => { state.card_exp_year = Some(value.clone()); Ok("Card expiry year set".to_string()) } "cvc" => { state.card_cvc = Some(value.clone()); Ok("Card CVC set".to_string()) } _ => Err(anyhow!( "Unknown card field: {}. Use number, exp_month, exp_year, cvc", field )), } } _ => Err(anyhow!("Unknown set key: {}", key)), } } fn handle_unset(args: &[String], ctx: &mut ShellContext) -> Result<String> { if args.len() < 2 { return Err(anyhow!( "Usage: unset <key>\nKeys: url, connector, amount, currency, email, resource_id, auth, card, card.number, ..." )); } let key = args[1].to_lowercase(); let state = &mut ctx.state; match key.as_str() { "url" => { state.url = None; ctx.client = None; Ok("URL unset and client disconnected".to_string()) } "connector" => { state.connector = None; Ok("Connector unset".to_string()) } "amount" => { state.amount = None; Ok("Amount unset".to_string()) } "currency" => { state.currency = None; Ok("Currency unset".to_string()) } "email" => { state.email = None; Ok("Email unset".to_string()) } "api_key" => { state.api_key = None;
{ "chunk": 2, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_example-tui_-7964693969177594414_3
clm
mini_chunk
// connector-service/examples/example-tui/src/main.rs 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" )); } let operation = args[1].to_lowercase(); let state = &ctx.state; // // Get a mutable reference to the client stored in the context // let client = ctx // .client // .as_mut() // .ok_or_else(|| anyhow!("Client not connected. Use 'set url <value>' first."))?; let mut client = connect_client(&state.url.as_ref().unwrap()).await?; // let auth_creds = state // .auth_details // .clone() // .ok_or_else(|| anyhow!("Authentication details are not set."))? // .into(); // let connector_val = state // .connector // .ok_or_else(|| anyhow!("Connector is not set."))?; match operation.as_str() { "authorize" => { let amount = state.amount.ok_or_else(|| anyhow!("Amount is not set."))?; let currency = state .currency .ok_or_else(|| anyhow!("Currency is not set."))?; let card_number = state .card_number .as_ref() .ok_or_else(|| anyhow!("Card number is not set."))?; let card_exp_month = state .card_exp_month .as_ref() .ok_or_else(|| anyhow!("Card expiry month is not set."))?; let card_exp_year = state .card_exp_year .as_ref() .ok_or_else(|| anyhow!("Card expiry year is not set."))?; let card_cvc = state .card_cvc .as_ref() .ok_or_else(|| anyhow!("Card CVC is not set."))?; let request = payments::PaymentsAuthorizeRequest { amount, currency, // connector: connector_val.into(), // auth_creds: Some(auth_creds), connector_customer: Some("cus_1234".to_string()), return_url: Some("www.google.com".to_string()), payment_method: payments::PaymentMethod::Card as i32, payment_method_data: Some(payments::PaymentMethodData { data: Some(payments::payment_method_data::Data::Card(payments::Card { card_number: card_number.clone(), card_exp_month: card_exp_month.clone(), card_exp_year: card_exp_year.clone(), card_cvc: card_cvc.clone(), ..Default::default() })), }), email: state.email.clone(), address: Some(payments::PaymentAddress::default()), auth_type: payments::AuthenticationType::NoThreeDs as i32, minor_amount: amount, request_incremental_authorization: false, connector_request_reference_id: format!( "shell-ref-{}", chrono::Utc::now().timestamp_millis()
{ "chunk": 3, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_example-tui_-7964693969177594414_4
clm
mini_chunk
// connector-service/examples/example-tui/src/main.rs ), browser_info: Some(payments::BrowserInformation { user_agent: Some("Mozilla/5.0".to_string()), accept_header: Some("*/*".to_string()), language: Some("en-US".to_string()), color_depth: Some(24), screen_height: Some(1080), screen_width: Some(1920), java_enabled: Some(false), java_script_enabled: None, time_zone: None, ip_address: None, os_type: None, os_version: None, device_model: None, accept_language: None, }), ..Default::default() }; // println!("Sending Authorize request: {:#?}", request); // Call the method on the mutable client reference let mut request = tonic::Request::new(request); request .metadata_mut() .append("x-connector", "adyen".parse().unwrap()); request.metadata_mut().append( "x-auth", MetadataValue::from_str(&state.auth_details.clone().unwrap())?, ); request.metadata_mut().append( "x-api-key", MetadataValue::from_str(&state.api_key.clone().unwrap())?, ); request.metadata_mut().append( "x-key1", MetadataValue::from_str(&state.key1.clone().unwrap())?, ); let response = client.payment_authorize(request).await; match response { Ok(response) => Ok(format!("{:#?}", response.into_inner())), Err(err) => Ok(format!("Error during authorize call: {:#?}", err)), } // Use Debug formatting for potentially multi-line responses } "sync" => { let resource_id = state .resource_id .as_ref() .ok_or_else(|| anyhow!("Resource ID is not set."))?; let request = payments::PaymentsSyncRequest { // connector: connector_val.into(), // auth_creds: Some(auth_creds), resource_id: resource_id.clone(), connector_request_reference_id: Some(format!( "shell-sync-ref-{}", chrono::Utc::now().timestamp_millis() )), }; // println!("Sending Sync request: {:#?}", request); // Call the method on the mutable client reference let mut request = tonic::Request::new(request); request .metadata_mut() .append("x-connector", "razorpay".parse().unwrap()); request.metadata_mut().append( "x-auth", MetadataValue::from_str(&state.auth_details.clone().unwrap())?, ); request.metadata_mut().append( "x-api-key", MetadataValue::from_str(&state.api_key.clone().unwrap())?, ); request.metadata_mut().append( "x-key1", MetadataValue::from_str(&state.key1.clone().unwrap())?, ); let response = client .payment_sync(request) .await .context("Sync call failed")?; // Use Debug formatting for potentially multi-line responses Ok(format!("{:#?}", response.into_inner())) } _ => Err(anyhow!( "Unknown call operation: {}. Use authorize or sync", operation )), } } 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" +
{ "chunk": 4, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_example-tui_-7964693969177594414_5
clm
mini_chunk
// connector-service/examples/example-tui/src/main.rs " 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 { ">> ".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, 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": 5, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_example-tui_-7964693969177594414_6
clm
mini_chunk
// connector-service/examples/example-tui/src/main.rs 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 { // 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": 6, "crate": "example-tui", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_example-rs_-6592229781991902862_0
clm
mini_chunk
// connector-service/examples/example-rs/src/main.rs use rust_grpc_client::payments::{self, payment_service_client::PaymentServiceClient,Address, PhoneDetails}; use std::error::Error; #[tokio::main] async fn main() -> Result<(), Box<dyn Error>> { // Get the URL from command line arguments let args = std::env::args().collect::<Vec<_>>(); if args.len() < 2 { eprintln!("Usage: {} <url> [operation]", args[0]); eprintln!("Operations: authorize, sync"); std::process::exit(1); } let url = &args[1]; let operation = args.get(2).map(|s| s.as_str()).unwrap_or("authorize"); let response = match operation { "authorize" => { let auth_response = make_payment_authorization_request(url.to_string()).await?; format!("Authorization Response: {:?}", auth_response) } "sync" => { let sync_response = make_payment_sync_request(url.to_string()).await?; format!("Sync Response: {:?}", sync_response) } _ => { eprintln!( "Unknown operation: {}. Use 'authorize' or 'sync'.", operation ); std::process::exit(1); } }; // Print the response println!("{}", response); Ok(()) } /// Creates a gRPC client and sends a payment authorization request async fn make_payment_authorization_request( url: String, ) -> Result<tonic::Response<payments::PaymentsAuthorizeResponse>, Box<dyn Error>> { // Create a gRPC client let mut client = PaymentServiceClient::connect(url).await?; let api_key = std::env::var("API_KEY").unwrap_or_else(|_| "default_api_key".to_string()); let key1 = std::env::var("KEY1").unwrap_or_else(|_| "default_key1".to_string()); println!("api_key is {} and key1 is {}", api_key,key1); // Create a request with the updated values let request = payments::PaymentsAuthorizeRequest { amount: 1000 as i64, currency: payments::Currency::Usd as i32, // connector: payments::Connector::Adyen as i32, // auth_creds: Some(payments::AuthType { // auth_details: Some(payments::auth_type::AuthDetails::BodyKey( // Changed to BodyKey // payments::BodyKey { // api_key, // key1 // }, // )), // }), // connector: payments::Connector::Adyen as i32, // auth_creds: Some(payments::AuthType { // auth_details: Some(payments::auth_type::AuthDetails::BodyKey( // Changed to BodyKey // payments::BodyKey { // api_key, // key1 // }, // )), // }), payment_method: payments::PaymentMethod::Card as i32, payment_method_data: Some(payments::PaymentMethodData { data: Some(payments::payment_method_data::Data::Card(payments::Card { card_number: "5123456789012346".to_string(), // Updated card number card_exp_month: "03".to_string(), card_exp_year: "2030".to_string(), card_cvc: "100".to_string(), // Updated CVC ..Default::default() })), }), // connector_customer: Some("customer_12345".to_string()), // return_url: Some("www.google.com".to_string()), address:Some(payments::PaymentAddress{ shipping:None, billing:Some(Address { address: None, phone: Some(PhoneDetails { number: Some("1234567890".to_string()), country_code: Some("+1".to_string()) }), email: Some("sweta.sharma@juspay.in".to_string()) }), unified_payment_method_billing: None, payment_method_billing: None }), auth_type: payments::AuthenticationType::ThreeDs as i32, connector_request_reference_id: "ref_12345".to_string(), enrolled_for_3ds: true, request_incremental_authorization: false, minor_amount: 1000 as i64, email: Some("sweta.sharma@juspay.in".to_string()), connector_customer: Some("cus_1234".to_string()), return_url: Some("www.google.com".to_string()), browser_info: Some(payments::BrowserInformation { // Added browser_info user_agent: Some("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)".to_string()),
{ "chunk": 0, "crate": "example-rs", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_mini_example-rs_-6592229781991902862_1
clm
mini_chunk
// connector-service/examples/example-rs/src/main.rs accept_header: Some( "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8".to_string(), ), language: Some("en-US".to_string()), color_depth: Some(24), screen_height: Some(1080), screen_width: Some(1920), java_enabled: Some(false), ..Default::default() }), ..Default::default() }; let mut request = tonic::Request::new(request); request .metadata_mut() .append("x-connector", "adyen".parse().unwrap()); request .metadata_mut() .append("x-auth", "body-key".parse().unwrap()); request .metadata_mut() .append("x-api-key", api_key.parse().unwrap()); request .metadata_mut() .append("x-key1", key1.parse().unwrap()); // Send the request let response = client.payment_authorize(request).await?; Ok(response) } /// Creates a gRPC client and sends a payment sync request async fn make_payment_sync_request( url: String, ) -> Result<tonic::Response<payments::PaymentsSyncResponse>, Box<dyn Error>> { // Create a gRPC client let mut client = PaymentServiceClient::connect(url).await?; let resource_id = std::env::var("RESOURCE_ID").unwrap_or_else(|_| "pay_QHj9Thiy5mCC4Y".to_string()); let api_key = std::env::var("API_KEY").unwrap_or_else(|_| "default_api_key".to_string()); let key1 = std::env::var("KEY1").unwrap_or_else(|_| "default_key1".to_string()); // Create a request let request = payments::PaymentsSyncRequest { // connector: payments::Connector::Razorpay as i32, // auth_creds: Some(payments::AuthType { // auth_details: Some(payments::auth_type::AuthDetails::BodyKey( // payments::BodyKey { // api_key, // key1 // }, // )), // }), resource_id, connector_request_reference_id: Some("conn_req_abc".to_string()), }; let mut request = tonic::Request::new(request); request .metadata_mut() .append("x-connector", "razorpay".parse().unwrap()); request .metadata_mut() .append("x-auth", "body-key".parse().unwrap()); request .metadata_mut() .append("x-api-key", api_key.parse().unwrap()); request .metadata_mut() .append("x-key1", key1.parse().unwrap()); let response = client.payment_sync(request).await?; Ok(response) }
{ "chunk": 1, "crate": "example-rs", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": null, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": null, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_-4191580895164688042_0_15
clm
snippet
// 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
{ "chunk": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 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_-4191580895164688042_0_30
clm
snippet
// 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 }) }
{ "chunk": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 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_-4191580895164688042_0_50
clm
snippet
// 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": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 45, "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_-4191580895164688042_25_15
clm
snippet
// connector-service/backend/common_utils/src/new_types.rs 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)) } }
{ "chunk": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 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_-4191580895164688042_25_30
clm
snippet
// connector-service/backend/common_utils/src/new_types.rs 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": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 20, "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_-4191580895164688042_25_50
clm
snippet
// connector-service/backend/common_utils/src/new_types.rs 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": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 20, "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_3535915762892100610_0_15
clm
snippet
// connector-service/backend/common_utils/src/ext_traits.rs //! This module holds traits for extending functionalities for existing datatypes //! & inbuilt datatypes. use error_stack::ResultExt; use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret, Strategy}; use quick_xml::de; use serde::{Deserialize, Serialize}; use crate::{ errors::{self, CustomResult}, fp_utils::when, }; /// Encode interface /// An interface for performing type conversions and serialization
{ "chunk": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 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_3535915762892100610_0_30
clm
snippet
// connector-service/backend/common_utils/src/ext_traits.rs //! This module holds traits for extending functionalities for existing datatypes //! & inbuilt datatypes. use error_stack::ResultExt; use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret, Strategy}; use quick_xml::de; use serde::{Deserialize, Serialize}; use crate::{ errors::{self, CustomResult}, fp_utils::when, }; /// Encode interface /// An interface for performing type conversions and serialization pub trait Encode<'e> where Self: 'e + std::fmt::Debug, { /// Converting `Self` into an intermediate representation `<P>` /// and then performing encoding operation using the `Serialize` trait from `serde` /// Specifically to convert into json, by using `serde_json` fn convert_and_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError> where P: TryFrom<&'e Self> + Serialize, Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt, <Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize; /// Converting `Self` into an intermediate representation `<P>` /// and then performing encoding operation using the `Serialize` trait from `serde`
{ "chunk": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 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_3535915762892100610_0_50
clm
snippet
// connector-service/backend/common_utils/src/ext_traits.rs //! This module holds traits for extending functionalities for existing datatypes //! & inbuilt datatypes. use error_stack::ResultExt; use hyperswitch_masking::{ExposeInterface, PeekInterface, Secret, Strategy}; use quick_xml::de; use serde::{Deserialize, Serialize}; use crate::{ errors::{self, CustomResult}, fp_utils::when, }; /// Encode interface /// An interface for performing type conversions and serialization pub trait Encode<'e> where Self: 'e + std::fmt::Debug, { /// Converting `Self` into an intermediate representation `<P>` /// and then performing encoding operation using the `Serialize` trait from `serde` /// Specifically to convert into json, by using `serde_json` fn convert_and_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError> where P: TryFrom<&'e Self> + Serialize, Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt, <Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize; /// Converting `Self` into an intermediate representation `<P>` /// and then performing encoding operation using the `Serialize` trait from `serde` /// Specifically, to convert into urlencoded, by using `serde_urlencoded` fn convert_and_url_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError> where P: TryFrom<&'e Self> + Serialize, Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt, <Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize; /// Functionality, for specifically encoding `Self` into `String` /// after serialization by using `serde::Serialize` fn url_encode(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize; /// Functionality, for specifically encoding `Self` into `String` /// after serialization by using `serde::Serialize` /// specifically, to convert into JSON `String`. fn encode_to_string_of_json(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize;
{ "chunk": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 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_3535915762892100610_25_15
clm
snippet
// connector-service/backend/common_utils/src/ext_traits.rs Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt, <Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize; /// Converting `Self` into an intermediate representation `<P>` /// and then performing encoding operation using the `Serialize` trait from `serde` /// Specifically, to convert into urlencoded, by using `serde_urlencoded` fn convert_and_url_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError> where P: TryFrom<&'e Self> + Serialize, Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt, <Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize; /// Functionality, for specifically encoding `Self` into `String` /// after serialization by using `serde::Serialize` fn url_encode(&'e self) -> CustomResult<String, errors::ParsingError>
{ "chunk": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 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_3535915762892100610_25_30
clm
snippet
// connector-service/backend/common_utils/src/ext_traits.rs Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt, <Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize; /// Converting `Self` into an intermediate representation `<P>` /// and then performing encoding operation using the `Serialize` trait from `serde` /// Specifically, to convert into urlencoded, by using `serde_urlencoded` fn convert_and_url_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError> where P: TryFrom<&'e Self> + Serialize, Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt, <Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize; /// Functionality, for specifically encoding `Self` into `String` /// after serialization by using `serde::Serialize` fn url_encode(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize; /// Functionality, for specifically encoding `Self` into `String` /// after serialization by using `serde::Serialize` /// specifically, to convert into JSON `String`. fn encode_to_string_of_json(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize; /// Functionality, for specifically encoding `Self` into `String` /// after serialization by using `serde::Serialize` /// specifically, to convert into XML `String`. fn encode_to_string_of_xml(&'e self) -> CustomResult<String, errors::ParsingError> where
{ "chunk": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 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_3535915762892100610_25_50
clm
snippet
// connector-service/backend/common_utils/src/ext_traits.rs Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt, <Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize; /// Converting `Self` into an intermediate representation `<P>` /// and then performing encoding operation using the `Serialize` trait from `serde` /// Specifically, to convert into urlencoded, by using `serde_urlencoded` fn convert_and_url_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError> where P: TryFrom<&'e Self> + Serialize, Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt, <Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize; /// Functionality, for specifically encoding `Self` into `String` /// after serialization by using `serde::Serialize` fn url_encode(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize; /// Functionality, for specifically encoding `Self` into `String` /// after serialization by using `serde::Serialize` /// specifically, to convert into JSON `String`. fn encode_to_string_of_json(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize; /// Functionality, for specifically encoding `Self` into `String` /// after serialization by using `serde::Serialize` /// specifically, to convert into XML `String`. fn encode_to_string_of_xml(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize; /// Functionality, for specifically encoding `Self` into `serde_json::Value` /// after serialization by using `serde::Serialize` fn encode_to_value(&'e self) -> CustomResult<serde_json::Value, errors::ParsingError> where Self: Serialize; /// Functionality, for specifically encoding `Self` into `Vec<u8>` /// after serialization by using `serde::Serialize` fn encode_to_vec(&'e self) -> CustomResult<Vec<u8>, errors::ParsingError> where Self: Serialize; } impl<'e, A> Encode<'e> for A where Self: 'e + std::fmt::Debug, { fn convert_and_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError>
{ "chunk": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 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_3535915762892100610_50_15
clm
snippet
// connector-service/backend/common_utils/src/ext_traits.rs /// Functionality, for specifically encoding `Self` into `String` /// after serialization by using `serde::Serialize` /// specifically, to convert into XML `String`. fn encode_to_string_of_xml(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize; /// Functionality, for specifically encoding `Self` into `serde_json::Value` /// after serialization by using `serde::Serialize` fn encode_to_value(&'e self) -> CustomResult<serde_json::Value, errors::ParsingError> where Self: Serialize; /// Functionality, for specifically encoding `Self` into `Vec<u8>` /// after serialization by using `serde::Serialize`
{ "chunk": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 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_3535915762892100610_50_30
clm
snippet
// connector-service/backend/common_utils/src/ext_traits.rs /// Functionality, for specifically encoding `Self` into `String` /// after serialization by using `serde::Serialize` /// specifically, to convert into XML `String`. fn encode_to_string_of_xml(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize; /// Functionality, for specifically encoding `Self` into `serde_json::Value` /// after serialization by using `serde::Serialize` fn encode_to_value(&'e self) -> CustomResult<serde_json::Value, errors::ParsingError> where Self: Serialize; /// Functionality, for specifically encoding `Self` into `Vec<u8>` /// after serialization by using `serde::Serialize` fn encode_to_vec(&'e self) -> CustomResult<Vec<u8>, errors::ParsingError> where Self: Serialize; } impl<'e, A> Encode<'e> for A where Self: 'e + std::fmt::Debug, { fn convert_and_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError> where P: TryFrom<&'e Self> + Serialize, Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt, <Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize, {
{ "chunk": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 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_3535915762892100610_50_50
clm
snippet
// connector-service/backend/common_utils/src/ext_traits.rs /// Functionality, for specifically encoding `Self` into `String` /// after serialization by using `serde::Serialize` /// specifically, to convert into XML `String`. fn encode_to_string_of_xml(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize; /// Functionality, for specifically encoding `Self` into `serde_json::Value` /// after serialization by using `serde::Serialize` fn encode_to_value(&'e self) -> CustomResult<serde_json::Value, errors::ParsingError> where Self: Serialize; /// Functionality, for specifically encoding `Self` into `Vec<u8>` /// after serialization by using `serde::Serialize` fn encode_to_vec(&'e self) -> CustomResult<Vec<u8>, errors::ParsingError> where Self: Serialize; } impl<'e, A> Encode<'e> for A where Self: 'e + std::fmt::Debug, { fn convert_and_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError> where P: TryFrom<&'e Self> + Serialize, Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt, <Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize, { serde_json::to_string( &P::try_from(self).change_context(errors::ParsingError::UnknownError)?, ) .change_context(errors::ParsingError::EncodeError("string")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a request")) } fn convert_and_url_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError> where P: TryFrom<&'e Self> + Serialize, Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt, <Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize, { serde_urlencoded::to_string( &P::try_from(self).change_context(errors::ParsingError::UnknownError)?, ) .change_context(errors::ParsingError::EncodeError("url-encoded")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a request")) }
{ "chunk": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 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_3535915762892100610_75_15
clm
snippet
// connector-service/backend/common_utils/src/ext_traits.rs where P: TryFrom<&'e Self> + Serialize, Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt, <Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize, { serde_json::to_string( &P::try_from(self).change_context(errors::ParsingError::UnknownError)?, ) .change_context(errors::ParsingError::EncodeError("string")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a request")) } fn convert_and_url_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError> where P: TryFrom<&'e Self> + Serialize,
{ "chunk": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 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_3535915762892100610_75_30
clm
snippet
// connector-service/backend/common_utils/src/ext_traits.rs where P: TryFrom<&'e Self> + Serialize, Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt, <Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize, { serde_json::to_string( &P::try_from(self).change_context(errors::ParsingError::UnknownError)?, ) .change_context(errors::ParsingError::EncodeError("string")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a request")) } fn convert_and_url_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError> where P: TryFrom<&'e Self> + Serialize, Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt, <Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize, { serde_urlencoded::to_string( &P::try_from(self).change_context(errors::ParsingError::UnknownError)?, ) .change_context(errors::ParsingError::EncodeError("url-encoded")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a request")) } fn url_encode(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize, { serde_urlencoded::to_string(self)
{ "chunk": null, "crate": "ucs_common_utils", "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_3535915762892100610_75_50
clm
snippet
// connector-service/backend/common_utils/src/ext_traits.rs where P: TryFrom<&'e Self> + Serialize, Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt, <Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize, { serde_json::to_string( &P::try_from(self).change_context(errors::ParsingError::UnknownError)?, ) .change_context(errors::ParsingError::EncodeError("string")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a request")) } fn convert_and_url_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError> where P: TryFrom<&'e Self> + Serialize, Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt, <Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize, { serde_urlencoded::to_string( &P::try_from(self).change_context(errors::ParsingError::UnknownError)?, ) .change_context(errors::ParsingError::EncodeError("url-encoded")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a request")) } fn url_encode(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize, { serde_urlencoded::to_string(self) .change_context(errors::ParsingError::EncodeError("url-encoded")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a request")) } fn encode_to_string_of_json(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize, { serde_json::to_string(self) .change_context(errors::ParsingError::EncodeError("json")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a request")) } fn encode_to_string_of_xml(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize, { quick_xml::se::to_string(self) .change_context(errors::ParsingError::EncodeError("xml")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a request"))
{ "chunk": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 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_3535915762892100610_100_15
clm
snippet
// connector-service/backend/common_utils/src/ext_traits.rs fn url_encode(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize, { serde_urlencoded::to_string(self) .change_context(errors::ParsingError::EncodeError("url-encoded")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a request")) } fn encode_to_string_of_json(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize, { serde_json::to_string(self) .change_context(errors::ParsingError::EncodeError("json"))
{ "chunk": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 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_3535915762892100610_100_30
clm
snippet
// connector-service/backend/common_utils/src/ext_traits.rs fn url_encode(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize, { serde_urlencoded::to_string(self) .change_context(errors::ParsingError::EncodeError("url-encoded")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a request")) } fn encode_to_string_of_json(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize, { serde_json::to_string(self) .change_context(errors::ParsingError::EncodeError("json")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a request")) } fn encode_to_string_of_xml(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize, { quick_xml::se::to_string(self) .change_context(errors::ParsingError::EncodeError("xml")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a request")) } fn encode_to_value(&'e self) -> CustomResult<serde_json::Value, errors::ParsingError> where Self: Serialize,
{ "chunk": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 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_3535915762892100610_100_50
clm
snippet
// connector-service/backend/common_utils/src/ext_traits.rs fn url_encode(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize, { serde_urlencoded::to_string(self) .change_context(errors::ParsingError::EncodeError("url-encoded")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a request")) } fn encode_to_string_of_json(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize, { serde_json::to_string(self) .change_context(errors::ParsingError::EncodeError("json")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a request")) } fn encode_to_string_of_xml(&'e self) -> CustomResult<String, errors::ParsingError> where Self: Serialize, { quick_xml::se::to_string(self) .change_context(errors::ParsingError::EncodeError("xml")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a request")) } fn encode_to_value(&'e self) -> CustomResult<serde_json::Value, errors::ParsingError> where Self: Serialize, { serde_json::to_value(self) .change_context(errors::ParsingError::EncodeError("json-value")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a value")) } fn encode_to_vec(&'e self) -> CustomResult<Vec<u8>, errors::ParsingError> where Self: Serialize, { serde_json::to_vec(self) .change_context(errors::ParsingError::EncodeError("byte-vec")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a value")) } } /// Extending functionalities of `bytes::Bytes` pub trait BytesExt { /// Convert `bytes::Bytes` into type `<T>` using `serde::Deserialize` fn parse_struct<'de, T>(
{ "chunk": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 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_3535915762892100610_125_15
clm
snippet
// connector-service/backend/common_utils/src/ext_traits.rs } fn encode_to_value(&'e self) -> CustomResult<serde_json::Value, errors::ParsingError> where Self: Serialize, { serde_json::to_value(self) .change_context(errors::ParsingError::EncodeError("json-value")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a value")) } fn encode_to_vec(&'e self) -> CustomResult<Vec<u8>, errors::ParsingError> where Self: Serialize, {
{ "chunk": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 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_3535915762892100610_125_30
clm
snippet
// connector-service/backend/common_utils/src/ext_traits.rs } fn encode_to_value(&'e self) -> CustomResult<serde_json::Value, errors::ParsingError> where Self: Serialize, { serde_json::to_value(self) .change_context(errors::ParsingError::EncodeError("json-value")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a value")) } fn encode_to_vec(&'e self) -> CustomResult<Vec<u8>, errors::ParsingError> where Self: Serialize, { serde_json::to_vec(self) .change_context(errors::ParsingError::EncodeError("byte-vec")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a value")) } } /// Extending functionalities of `bytes::Bytes` pub trait BytesExt { /// Convert `bytes::Bytes` into type `<T>` using `serde::Deserialize` fn parse_struct<'de, T>( &'de self, type_name: &'static str, ) -> CustomResult<T, errors::ParsingError> where T: Deserialize<'de>;
{ "chunk": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 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_3535915762892100610_125_50
clm
snippet
// connector-service/backend/common_utils/src/ext_traits.rs } fn encode_to_value(&'e self) -> CustomResult<serde_json::Value, errors::ParsingError> where Self: Serialize, { serde_json::to_value(self) .change_context(errors::ParsingError::EncodeError("json-value")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a value")) } fn encode_to_vec(&'e self) -> CustomResult<Vec<u8>, errors::ParsingError> where Self: Serialize, { serde_json::to_vec(self) .change_context(errors::ParsingError::EncodeError("byte-vec")) .attach_printable_lazy(|| format!("Unable to convert {self:?} to a value")) } } /// Extending functionalities of `bytes::Bytes` pub trait BytesExt { /// Convert `bytes::Bytes` into type `<T>` using `serde::Deserialize` fn parse_struct<'de, T>( &'de self, type_name: &'static str, ) -> CustomResult<T, errors::ParsingError> where T: Deserialize<'de>; } impl BytesExt for bytes::Bytes { fn parse_struct<'de, T>( &'de self, type_name: &'static str, ) -> CustomResult<T, errors::ParsingError> where T: Deserialize<'de>, { use bytes::Buf; serde_json::from_slice::<T>(self.chunk()) .change_context(errors::ParsingError::StructParseFailure(type_name)) .attach_printable_lazy(|| { let variable_type = std::any::type_name::<T>(); format!("Unable to parse {variable_type} from bytes {self:?}") }) } }
{ "chunk": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 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_3535915762892100610_150_15
clm
snippet
// connector-service/backend/common_utils/src/ext_traits.rs &'de self, type_name: &'static str, ) -> CustomResult<T, errors::ParsingError> where T: Deserialize<'de>; } impl BytesExt for bytes::Bytes { fn parse_struct<'de, T>( &'de self, type_name: &'static str, ) -> CustomResult<T, errors::ParsingError> where T: Deserialize<'de>, {
{ "chunk": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 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_3535915762892100610_150_30
clm
snippet
// connector-service/backend/common_utils/src/ext_traits.rs &'de self, type_name: &'static str, ) -> CustomResult<T, errors::ParsingError> where T: Deserialize<'de>; } impl BytesExt for bytes::Bytes { fn parse_struct<'de, T>( &'de self, type_name: &'static str, ) -> CustomResult<T, errors::ParsingError> where T: Deserialize<'de>, { use bytes::Buf; serde_json::from_slice::<T>(self.chunk()) .change_context(errors::ParsingError::StructParseFailure(type_name)) .attach_printable_lazy(|| { let variable_type = std::any::type_name::<T>(); format!("Unable to parse {variable_type} from bytes {self:?}") }) } } /// Extending functionalities of `[u8]` for performing parsing pub trait ByteSliceExt { /// Convert `[u8]` into type `<T>` by using `serde::Deserialize` fn parse_struct<'de, T>(
{ "chunk": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 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_3535915762892100610_150_50
clm
snippet
// connector-service/backend/common_utils/src/ext_traits.rs &'de self, type_name: &'static str, ) -> CustomResult<T, errors::ParsingError> where T: Deserialize<'de>; } impl BytesExt for bytes::Bytes { fn parse_struct<'de, T>( &'de self, type_name: &'static str, ) -> CustomResult<T, errors::ParsingError> where T: Deserialize<'de>, { use bytes::Buf; serde_json::from_slice::<T>(self.chunk()) .change_context(errors::ParsingError::StructParseFailure(type_name)) .attach_printable_lazy(|| { let variable_type = std::any::type_name::<T>(); format!("Unable to parse {variable_type} from bytes {self:?}") }) } } /// Extending functionalities of `[u8]` for performing parsing pub trait ByteSliceExt { /// Convert `[u8]` into type `<T>` by using `serde::Deserialize` fn parse_struct<'de, T>( &'de self, type_name: &'static str, ) -> CustomResult<T, errors::ParsingError> where T: Deserialize<'de>; } impl ByteSliceExt for [u8] { #[track_caller] fn parse_struct<'de, T>( &'de self, type_name: &'static str, ) -> CustomResult<T, errors::ParsingError> where T: Deserialize<'de>, { serde_json::from_slice(self) .change_context(errors::ParsingError::StructParseFailure(type_name)) .attach_printable_lazy(|| format!("Unable to parse {type_name} from &[u8] {:?}", &self)) }
{ "chunk": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 50, "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_3535915762892100610_175_15
clm
snippet
// connector-service/backend/common_utils/src/ext_traits.rs /// Extending functionalities of `[u8]` for performing parsing pub trait ByteSliceExt { /// Convert `[u8]` into type `<T>` by using `serde::Deserialize` fn parse_struct<'de, T>( &'de self, type_name: &'static str, ) -> CustomResult<T, errors::ParsingError> where T: Deserialize<'de>; } impl ByteSliceExt for [u8] { #[track_caller] fn parse_struct<'de, T>(
{ "chunk": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 15, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 175, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_3535915762892100610_175_30
clm
snippet
// connector-service/backend/common_utils/src/ext_traits.rs /// Extending functionalities of `[u8]` for performing parsing pub trait ByteSliceExt { /// Convert `[u8]` into type `<T>` by using `serde::Deserialize` fn parse_struct<'de, T>( &'de self, type_name: &'static str, ) -> CustomResult<T, errors::ParsingError> where T: Deserialize<'de>; } impl ByteSliceExt for [u8] { #[track_caller] fn parse_struct<'de, T>( &'de self, type_name: &'static str, ) -> CustomResult<T, errors::ParsingError> where T: Deserialize<'de>, { serde_json::from_slice(self) .change_context(errors::ParsingError::StructParseFailure(type_name)) .attach_printable_lazy(|| format!("Unable to parse {type_name} from &[u8] {:?}", &self)) } } /// Extension trait for validating application configuration. This trait provides utilities to /// check whether the value is either the default value or is empty. pub trait ConfigExt {
{ "chunk": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 30, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 175, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_3535915762892100610_175_50
clm
snippet
// connector-service/backend/common_utils/src/ext_traits.rs /// Extending functionalities of `[u8]` for performing parsing pub trait ByteSliceExt { /// Convert `[u8]` into type `<T>` by using `serde::Deserialize` fn parse_struct<'de, T>( &'de self, type_name: &'static str, ) -> CustomResult<T, errors::ParsingError> where T: Deserialize<'de>; } impl ByteSliceExt for [u8] { #[track_caller] fn parse_struct<'de, T>( &'de self, type_name: &'static str, ) -> CustomResult<T, errors::ParsingError> where T: Deserialize<'de>, { serde_json::from_slice(self) .change_context(errors::ParsingError::StructParseFailure(type_name)) .attach_printable_lazy(|| format!("Unable to parse {type_name} from &[u8] {:?}", &self)) } } /// Extension trait for validating application configuration. This trait provides utilities to /// check whether the value is either the default value or is empty. pub trait ConfigExt { /// Returns whether the value of `self` is the default value for `Self`. fn is_default(&self) -> bool where Self: Default + PartialEq<Self>, { *self == Self::default() } /// Returns whether the value of `self` is empty after trimming whitespace on both left and /// right ends. fn is_empty_after_trim(&self) -> bool; /// Returns whether the value of `self` is the default value for `Self` or empty after trimming /// whitespace on both left and right ends. fn is_default_or_empty(&self) -> bool where Self: Default + PartialEq<Self>, { self.is_default() || self.is_empty_after_trim() }
{ "chunk": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 50, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 175, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_3535915762892100610_200_15
clm
snippet
// connector-service/backend/common_utils/src/ext_traits.rs } /// Extension trait for validating application configuration. This trait provides utilities to /// check whether the value is either the default value or is empty. pub trait ConfigExt { /// Returns whether the value of `self` is the default value for `Self`. fn is_default(&self) -> bool where Self: Default + PartialEq<Self>, { *self == Self::default() } /// Returns whether the value of `self` is empty after trimming whitespace on both left and /// right ends.
{ "chunk": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 15, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 200, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_3535915762892100610_200_30
clm
snippet
// connector-service/backend/common_utils/src/ext_traits.rs } /// Extension trait for validating application configuration. This trait provides utilities to /// check whether the value is either the default value or is empty. pub trait ConfigExt { /// Returns whether the value of `self` is the default value for `Self`. fn is_default(&self) -> bool where Self: Default + PartialEq<Self>, { *self == Self::default() } /// Returns whether the value of `self` is empty after trimming whitespace on both left and /// right ends. fn is_empty_after_trim(&self) -> bool; /// Returns whether the value of `self` is the default value for `Self` or empty after trimming /// whitespace on both left and right ends. fn is_default_or_empty(&self) -> bool where Self: Default + PartialEq<Self>, { self.is_default() || self.is_empty_after_trim() } } impl ConfigExt for u32 { fn is_empty_after_trim(&self) -> bool { false
{ "chunk": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 30, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 200, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_3535915762892100610_200_50
clm
snippet
// connector-service/backend/common_utils/src/ext_traits.rs } /// Extension trait for validating application configuration. This trait provides utilities to /// check whether the value is either the default value or is empty. pub trait ConfigExt { /// Returns whether the value of `self` is the default value for `Self`. fn is_default(&self) -> bool where Self: Default + PartialEq<Self>, { *self == Self::default() } /// Returns whether the value of `self` is empty after trimming whitespace on both left and /// right ends. fn is_empty_after_trim(&self) -> bool; /// Returns whether the value of `self` is the default value for `Self` or empty after trimming /// whitespace on both left and right ends. fn is_default_or_empty(&self) -> bool where Self: Default + PartialEq<Self>, { self.is_default() || self.is_empty_after_trim() } } impl ConfigExt for u32 { fn is_empty_after_trim(&self) -> bool { false } } impl ConfigExt for String { fn is_empty_after_trim(&self) -> bool { self.trim().is_empty() } } impl<T, U> ConfigExt for Secret<T, U> where T: ConfigExt + Default + PartialEq<T>, U: Strategy<T>, { fn is_default(&self) -> bool where T: Default + PartialEq<T>, { *self.peek() == T::default() }
{ "chunk": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 50, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 200, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_3535915762892100610_225_15
clm
snippet
// connector-service/backend/common_utils/src/ext_traits.rs } impl ConfigExt for u32 { fn is_empty_after_trim(&self) -> bool { false } } impl ConfigExt for String { fn is_empty_after_trim(&self) -> bool { self.trim().is_empty() } } impl<T, U> ConfigExt for Secret<T, U>
{ "chunk": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 15, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 225, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_3535915762892100610_225_30
clm
snippet
// connector-service/backend/common_utils/src/ext_traits.rs } impl ConfigExt for u32 { fn is_empty_after_trim(&self) -> bool { false } } impl ConfigExt for String { fn is_empty_after_trim(&self) -> bool { self.trim().is_empty() } } impl<T, U> ConfigExt for Secret<T, U> where T: ConfigExt + Default + PartialEq<T>, U: Strategy<T>, { fn is_default(&self) -> bool where T: Default + PartialEq<T>, { *self.peek() == T::default() } fn is_empty_after_trim(&self) -> bool { self.peek().is_empty_after_trim() }
{ "chunk": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 30, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 225, "struct_name": null, "total_crates": null, "trait_name": null }
connector-service_snippet_3535915762892100610_225_50
clm
snippet
// connector-service/backend/common_utils/src/ext_traits.rs } impl ConfigExt for u32 { fn is_empty_after_trim(&self) -> bool { false } } impl ConfigExt for String { fn is_empty_after_trim(&self) -> bool { self.trim().is_empty() } } impl<T, U> ConfigExt for Secret<T, U> where T: ConfigExt + Default + PartialEq<T>, U: Strategy<T>, { fn is_default(&self) -> bool where T: Default + PartialEq<T>, { *self.peek() == T::default() } fn is_empty_after_trim(&self) -> bool { self.peek().is_empty_after_trim() } fn is_default_or_empty(&self) -> bool where T: Default + PartialEq<T>, { self.peek().is_default() || self.peek().is_empty_after_trim() } } /// Extension trait for deserializing XML strings using `quick-xml` crate pub trait XmlExt { /// Deserialize an XML string into the specified type `<T>`. fn parse_xml<T>(self) -> Result<T, de::DeError> where T: serde::de::DeserializeOwned; } impl XmlExt for &str { fn parse_xml<T>(self) -> Result<T, de::DeError> where T: serde::de::DeserializeOwned,
{ "chunk": null, "crate": "ucs_common_utils", "enum_name": null, "file_size": null, "for_type": null, "function_name": null, "is_async": null, "is_pub": null, "lines": 50, "method_name": null, "num_enums": null, "num_items": null, "num_structs": null, "repo": "connector-service", "start_line": 225, "struct_name": null, "total_crates": null, "trait_name": null }