id stringlengths 11 116 | type stringclasses 1
value | granularity stringclasses 4
values | content stringlengths 16 477k | metadata dict |
|---|---|---|---|---|
fn_clm_external_services_upload_file_6443311555561730543 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/file_storage/file_system
// Implementation of FileSystem for FileStorageInterface
/// Saves the provided file data to the file system under the specified file key.
async fn upload_file(
&self,
file_key: &str,
file: Vec<u8>,
) -> CustomResult<(), FileStorageError> {
self.upload_file(file_key, file)
.await
.change_context(FileStorageError::UploadFailed)?;
Ok(())
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 24,
"total_crates": null
} |
fn_clm_external_services_retrieve_file_6443311555561730543 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/file_storage/file_system
// Implementation of FileSystem for FileStorageInterface
/// Retrieves the file content associated with the specified file key from the file system.
async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, FileStorageError> {
Ok(self
.retrieve_file(file_key)
.await
.change_context(FileStorageError::RetrieveFailed)?)
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 24,
"total_crates": null
} |
fn_clm_external_services_delete_file_6443311555561730543 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/file_storage/file_system
// Implementation of FileSystem for FileStorageInterface
/// Deletes the file associated with the specified file key from the file system.
async fn delete_file(&self, file_key: &str) -> CustomResult<(), FileStorageError> {
self.delete_file(file_key)
.await
.change_context(FileStorageError::DeleteFailed)?;
Ok(())
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 21,
"total_crates": null
} |
fn_clm_external_services_get_file_path_6443311555561730543 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/file_storage/file_system
/// Constructs the file path for a given file key within the file system.
/// The file path is generated based on the workspace path and the provided file key.
fn get_file_path(file_key: impl AsRef<str>) -> PathBuf {
let mut file_path = PathBuf::new();
file_path.push(std::env::current_dir().unwrap_or(".".into()));
file_path.push("files");
file_path.push(file_key.as_ref());
file_path
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 16,
"total_crates": null
} |
fn_clm_external_services_new_-2000283242844065826 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/file_storage/aws_s3
// Inherent implementation for AwsFileStorageClient
/// Creates a new AWS S3 file storage client.
pub(super) async fn new(config: &AwsFileStorageConfig) -> Self {
let region_provider = RegionProviderChain::first_try(Region::new(config.region.clone()));
let sdk_config = aws_config::from_env().region(region_provider).load().await;
Self {
inner_client: Client::new(&sdk_config),
bucket_name: config.bucket_name.clone(),
}
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14479,
"total_crates": null
} |
fn_clm_external_services_validate_-2000283242844065826 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/file_storage/aws_s3
// Inherent implementation for AwsFileStorageConfig
/// Validates the AWS S3 file storage configuration.
pub(super) fn validate(&self) -> Result<(), InvalidFileStorageConfig> {
use common_utils::fp_utils::when;
when(self.region.is_default_or_empty(), || {
Err(InvalidFileStorageConfig("aws s3 region must not be empty"))
})?;
when(self.bucket_name.is_default_or_empty(), || {
Err(InvalidFileStorageConfig(
"aws s3 bucket name must not be empty",
))
})
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 231,
"total_crates": null
} |
fn_clm_external_services_upload_file_-2000283242844065826 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/file_storage/aws_s3
// Implementation of AwsFileStorageClient for FileStorageInterface
/// Uploads a file to AWS S3.
async fn upload_file(
&self,
file_key: &str,
file: Vec<u8>,
) -> CustomResult<(), FileStorageError> {
self.upload_file(file_key, file)
.await
.change_context(FileStorageError::UploadFailed)?;
Ok(())
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 24,
"total_crates": null
} |
fn_clm_external_services_retrieve_file_-2000283242844065826 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/file_storage/aws_s3
// Implementation of AwsFileStorageClient for FileStorageInterface
/// Retrieves a file from AWS S3.
async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, FileStorageError> {
Ok(self
.retrieve_file(file_key)
.await
.change_context(FileStorageError::RetrieveFailed)?)
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 24,
"total_crates": null
} |
fn_clm_external_services_delete_file_-2000283242844065826 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/file_storage/aws_s3
// Implementation of AwsFileStorageClient for FileStorageInterface
/// Deletes a file from AWS S3.
async fn delete_file(&self, file_key: &str) -> CustomResult<(), FileStorageError> {
self.delete_file(file_key)
.await
.change_context(FileStorageError::DeleteFailed)?;
Ok(())
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 21,
"total_crates": null
} |
fn_clm_external_services_validate_-2311798538485878475 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/managers/secrets_management
// Inherent implementation for SecretsManagementConfig
/// Verifies that the client configuration is usable
pub fn validate(&self) -> Result<(), &'static str> {
match self {
#[cfg(feature = "aws_kms")]
Self::AwsKms { aws_kms } => aws_kms.validate(),
#[cfg(feature = "hashicorp-vault")]
Self::HashiCorpVault { hc_vault } => hc_vault.validate(),
Self::NoEncryption => Ok(()),
}
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 223,
"total_crates": null
} |
fn_clm_external_services_get_secret_management_client_-2311798538485878475 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/managers/secrets_management
// Inherent implementation for SecretsManagementConfig
/// Retrieves the appropriate secret management client based on the configuration.
pub async fn get_secret_management_client(
&self,
) -> CustomResult<Box<dyn SecretManagementInterface>, SecretsManagementError> {
match self {
#[cfg(feature = "aws_kms")]
Self::AwsKms { aws_kms } => {
Ok(Box::new(aws_kms::core::AwsKmsClient::new(aws_kms).await))
}
#[cfg(feature = "hashicorp-vault")]
Self::HashiCorpVault { hc_vault } => {
hashicorp_vault::core::HashiCorpVault::new(hc_vault)
.change_context(SecretsManagementError::ClientCreationFailed)
.map(|inner| -> Box<dyn SecretManagementInterface> { Box::new(inner) })
}
Self::NoEncryption => Ok(Box::new(NoEncryption)),
}
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 35,
"total_crates": null
} |
fn_clm_external_services_validate_-5772774202332400350 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/managers/encryption_management
// Inherent implementation for EncryptionManagementConfig
/// Verifies that the client configuration is usable
pub fn validate(&self) -> Result<(), &'static str> {
match self {
#[cfg(feature = "aws_kms")]
Self::AwsKms { aws_kms } => aws_kms.validate(),
Self::NoEncryption => Ok(()),
}
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 221,
"total_crates": null
} |
fn_clm_external_services_get_encryption_management_client_-5772774202332400350 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/managers/encryption_management
// Inherent implementation for EncryptionManagementConfig
/// Retrieves the appropriate encryption client based on the configuration.
pub async fn get_encryption_management_client(
&self,
) -> CustomResult<Arc<dyn EncryptionManagementInterface>, EncryptionError> {
Ok(match self {
#[cfg(feature = "aws_kms")]
Self::AwsKms { aws_kms } => Arc::new(aws_kms::core::AwsKmsClient::new(aws_kms).await),
Self::NoEncryption => Arc::new(NoEncryption),
})
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 27,
"total_crates": null
} |
fn_clm_external_services_decrypt_-1086686959092261861 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/no_encryption/core
// Inherent implementation for NoEncryption
/// Decryption functionality
pub fn decrypt(&self, data: impl AsRef<[u8]>) -> Vec<u8> {
data.as_ref().into()
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 52,
"total_crates": null
} |
fn_clm_external_services_encrypt_-1086686959092261861 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/no_encryption/core
// Inherent implementation for NoEncryption
/// Encryption functionality
pub fn encrypt(&self, data: impl AsRef<[u8]>) -> Vec<u8> {
data.as_ref().into()
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 49,
"total_crates": null
} |
fn_clm_external_services_get_secret_-6912714844158479302 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/no_encryption/implementers
// Implementation of NoEncryption for SecretManagementInterface
async fn get_secret(
&self,
input: Secret<String>,
) -> CustomResult<Secret<String>, SecretsManagementError> {
String::from_utf8(self.decrypt(input.expose()))
.map(Into::into)
.change_context(SecretsManagementError::FetchSecretFailed)
.attach_printable("Failed to convert decrypted value to UTF-8")
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 104,
"total_crates": null
} |
fn_clm_external_services_decrypt_-6912714844158479302 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/no_encryption/implementers
// Implementation of NoEncryption for EncryptionManagementInterface
async fn decrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError> {
Ok(self.decrypt(input))
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 40,
"total_crates": null
} |
fn_clm_external_services_encrypt_-6912714844158479302 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/no_encryption/implementers
// Implementation of NoEncryption for EncryptionManagementInterface
async fn encrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError> {
Ok(self.encrypt(input))
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 37,
"total_crates": null
} |
fn_clm_external_services_new_5428978503985758258 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/aws_kms/core
// Inherent implementation for AwsKmsClient
/// Constructs a new AWS KMS client.
pub async fn new(config: &AwsKmsConfig) -> Self {
let region_provider = RegionProviderChain::first_try(Region::new(config.region.clone()));
let sdk_config = aws_config::from_env().region(region_provider).load().await;
Self {
inner_client: Client::new(&sdk_config),
key_id: config.key_id.clone(),
}
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14479,
"total_crates": null
} |
fn_clm_external_services_validate_5428978503985758258 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/aws_kms/core
// Inherent implementation for AwsKmsConfig
/// Verifies that the [`AwsKmsClient`] configuration is usable.
pub fn validate(&self) -> Result<(), &'static str> {
use common_utils::{ext_traits::ConfigExt, fp_utils::when};
when(self.key_id.is_default_or_empty(), || {
Err("KMS AWS key ID must not be empty")
})?;
when(self.region.is_default_or_empty(), || {
Err("KMS AWS region must not be empty")
})
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 227,
"total_crates": null
} |
fn_clm_external_services_decrypt_5428978503985758258 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/aws_kms/core
// Inherent implementation for AwsKmsClient
/// Decrypts the provided base64-encoded encrypted data using the AWS KMS SDK. We assume that
/// the SDK has the values required to interact with the AWS KMS APIs (`AWS_ACCESS_KEY_ID` and
/// `AWS_SECRET_ACCESS_KEY`) either set in environment variables, or that the SDK is running in
/// a machine that is able to assume an IAM role.
pub async fn decrypt(&self, data: impl AsRef<[u8]>) -> CustomResult<String, AwsKmsError> {
let start = Instant::now();
let data = consts::BASE64_ENGINE
.decode(data)
.change_context(AwsKmsError::Base64DecodingFailed)?;
let ciphertext_blob = Blob::new(data);
let decrypt_output = self
.inner_client
.decrypt()
.key_id(&self.key_id)
.ciphertext_blob(ciphertext_blob)
.send()
.await
.inspect_err(|error| {
// Logging using `Debug` representation of the error as the `Display`
// representation does not hold sufficient information.
logger::error!(aws_kms_sdk_error=?error, "Failed to AWS KMS decrypt data");
metrics::AWS_KMS_DECRYPTION_FAILURES.add(1, &[]);
})
.change_context(AwsKmsError::DecryptionFailed)?;
let output = decrypt_output
.plaintext
.ok_or(report!(AwsKmsError::MissingPlaintextDecryptionOutput))
.and_then(|blob| {
String::from_utf8(blob.into_inner()).change_context(AwsKmsError::Utf8DecodingFailed)
})?;
let time_taken = start.elapsed();
metrics::AWS_KMS_DECRYPT_TIME.record(time_taken.as_secs_f64(), &[]);
Ok(output)
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 86,
"total_crates": null
} |
fn_clm_external_services_encrypt_5428978503985758258 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/aws_kms/core
// Inherent implementation for AwsKmsClient
/// Encrypts the provided String data using the AWS KMS SDK. We assume that
/// the SDK has the values required to interact with the AWS KMS APIs (`AWS_ACCESS_KEY_ID` and
/// `AWS_SECRET_ACCESS_KEY`) either set in environment variables, or that the SDK is running in
/// a machine that is able to assume an IAM role.
pub async fn encrypt(&self, data: impl AsRef<[u8]>) -> CustomResult<String, AwsKmsError> {
let start = Instant::now();
let plaintext_blob = Blob::new(data.as_ref());
let encrypted_output = self
.inner_client
.encrypt()
.key_id(&self.key_id)
.plaintext(plaintext_blob)
.send()
.await
.inspect_err(|error| {
// Logging using `Debug` representation of the error as the `Display`
// representation does not hold sufficient information.
logger::error!(aws_kms_sdk_error=?error, "Failed to AWS KMS encrypt data");
metrics::AWS_KMS_ENCRYPTION_FAILURES.add(1, &[]);
})
.change_context(AwsKmsError::EncryptionFailed)?;
let output = encrypted_output
.ciphertext_blob
.ok_or(AwsKmsError::MissingCiphertextEncryptionOutput)
.map(|blob| consts::BASE64_ENGINE.encode(blob.into_inner()))?;
let time_taken = start.elapsed();
metrics::AWS_KMS_ENCRYPT_TIME.record(time_taken.as_secs_f64(), &[]);
Ok(output)
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 79,
"total_crates": null
} |
fn_clm_external_services_check_aws_kms_encryption_5428978503985758258 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/aws_kms/core
async fn check_aws_kms_encryption() {
std::env::set_var("AWS_SECRET_ACCESS_KEY", "YOUR SECRET ACCESS KEY");
std::env::set_var("AWS_ACCESS_KEY_ID", "YOUR AWS ACCESS KEY ID");
use super::*;
let config = AwsKmsConfig {
key_id: "YOUR AWS KMS KEY ID".to_string(),
region: "AWS REGION".to_string(),
};
let data = "hello".to_string();
let binding = data.as_bytes();
let kms_encrypted_fingerprint = AwsKmsClient::new(&config)
.await
.encrypt(binding)
.await
.expect("aws kms encryption failed");
println!("{kms_encrypted_fingerprint}");
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 16,
"total_crates": null
} |
fn_clm_external_services_get_secret_3292068361999423685 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/aws_kms/implementers
// Implementation of AwsKmsClient for SecretManagementInterface
async fn get_secret(
&self,
input: Secret<String>,
) -> CustomResult<Secret<String>, SecretsManagementError> {
self.decrypt(input.peek())
.await
.change_context(SecretsManagementError::FetchSecretFailed)
.map(Into::into)
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 100,
"total_crates": null
} |
fn_clm_external_services_decrypt_3292068361999423685 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/aws_kms/implementers
// Implementation of AwsKmsClient for EncryptionManagementInterface
async fn decrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError> {
self.decrypt(input)
.await
.change_context(EncryptionError::DecryptionFailed)
.map(|val| val.into_bytes())
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 46,
"total_crates": null
} |
fn_clm_external_services_encrypt_3292068361999423685 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/aws_kms/implementers
// Implementation of AwsKmsClient for EncryptionManagementInterface
async fn encrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError> {
self.encrypt(input)
.await
.change_context(EncryptionError::EncryptionFailed)
.map(|val| val.into_bytes())
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 43,
"total_crates": null
} |
fn_clm_external_services_new_327877765888171431 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/superposition/types
// Inherent implementation for ConfigContext
/// Create a new empty context
pub fn new() -> Self {
Self::default()
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14465,
"total_crates": null
} |
fn_clm_external_services_default_327877765888171431 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/superposition/types
// Implementation of SuperpositionClientConfig for Default
fn default() -> Self {
Self {
enabled: false,
endpoint: String::new(),
token: Secret::new(String::new()),
org_id: String::new(),
workspace_id: String::new(),
polling_interval: 15,
request_timeout: None,
}
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 7713,
"total_crates": null
} |
fn_clm_external_services_try_from_327877765888171431 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/superposition/types
// Implementation of JsonValue for TryFrom<open_feature::StructValue>
fn try_from(sv: open_feature::StructValue) -> Result<Self, Self::Error> {
let capacity = sv.fields.len();
sv.fields
.into_iter()
.try_fold(
serde_json::Map::with_capacity(capacity),
|mut map, (k, v)| {
let value = super::convert_open_feature_value(v)?;
map.insert(k, value);
Ok(map)
},
)
.map(|map| Self(serde_json::Value::Object(map)))
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 2675,
"total_crates": null
} |
fn_clm_external_services_into_inner_327877765888171431 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/superposition/types
// Inherent implementation for JsonValue
/// Consume the wrapper and return the inner JSON value
pub(super) fn into_inner(self) -> serde_json::Value {
self.0
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 2061,
"total_crates": null
} |
fn_clm_external_services_validate_327877765888171431 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/superposition/types
// Inherent implementation for SuperpositionClientConfig
/// Validate the Superposition configuration
pub fn validate(&self) -> Result<(), SuperpositionError> {
if !self.enabled {
return Ok(());
}
when(self.endpoint.is_empty(), || {
Err(SuperpositionError::InvalidConfiguration(
"Superposition endpoint cannot be empty".to_string(),
))
})?;
when(url::Url::parse(&self.endpoint).is_err(), || {
Err(SuperpositionError::InvalidConfiguration(
"Superposition endpoint must be a valid URL".to_string(),
))
})?;
when(self.token.clone().expose().is_empty(), || {
Err(SuperpositionError::InvalidConfiguration(
"Superposition token cannot be empty".to_string(),
))
})?;
when(self.org_id.is_empty(), || {
Err(SuperpositionError::InvalidConfiguration(
"Superposition org_id cannot be empty".to_string(),
))
})?;
when(self.workspace_id.is_empty(), || {
Err(SuperpositionError::InvalidConfiguration(
"Superposition workspace_id cannot be empty".to_string(),
))
})?;
Ok(())
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 265,
"total_crates": null
} |
fn_clm_external_services_perform_health_check_-1467357567945343445 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/grpc_client/health_check_client
// Implementation of None for HealthCheckClient
/// Perform health check for all services involved
pub async fn perform_health_check(
&self,
config: &GrpcClientSettings,
) -> HealthCheckResult<HealthCheckMap> {
let dynamic_routing_config = &config.dynamic_routing_client;
let connection = match dynamic_routing_config {
Some(DynamicRoutingClientConfig::Enabled {
host,
port,
service,
}) => Some((host.clone(), *port, service.clone())),
_ => None,
};
let health_client = self
.clients
.get(&HealthCheckServices::DynamicRoutingService);
// SAFETY : This is a safe cast as there exists a valid
// integer value for this variant
#[allow(clippy::as_conversions)]
let expected_status = ServingStatus::Serving as i32;
let mut service_map = HealthCheckMap::new();
let health_check_succeed = connection
.as_ref()
.async_map(|conn| self.get_response_from_grpc_service(conn.2.clone(), health_client))
.await
.transpose()
.change_context(HealthCheckError::ConnectionError(
"error calling dynamic routing service".to_string(),
))
.map_err(|err| logger::error!(error=?err))
.ok()
.flatten()
.is_some_and(|resp| resp.status == expected_status);
connection.and_then(|_conn| {
service_map.insert(
HealthCheckServices::DynamicRoutingService,
health_check_succeed,
)
});
Ok(service_map)
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 57,
"total_crates": null
} |
fn_clm_external_services_build_connections_-1467357567945343445 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/grpc_client/health_check_client
// Implementation of None for HealthCheckClient
/// Build connections to all gRPC services
pub async fn build_connections(
config: &GrpcClientSettings,
client: Client,
) -> Result<Self, Box<dyn std::error::Error>> {
let dynamic_routing_config = &config.dynamic_routing_client;
let connection = match dynamic_routing_config {
Some(DynamicRoutingClientConfig::Enabled {
host,
port,
service,
}) => Some((host.clone(), *port, service.clone())),
_ => None,
};
let mut client_map = HashMap::new();
if let Some(conn) = connection {
let uri = format!("http://{}:{}", conn.0, conn.1).parse::<tonic::transport::Uri>()?;
let health_client = HealthClient::with_origin(client, uri);
client_map.insert(HealthCheckServices::DynamicRoutingService, health_client);
}
Ok(Self {
clients: client_map,
})
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 34,
"total_crates": null
} |
fn_clm_external_services_get_response_from_grpc_service_-1467357567945343445 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/grpc_client/health_check_client
// Implementation of None for HealthCheckClient
async fn get_response_from_grpc_service(
&self,
service: String,
client: Option<&HealthClient<Client>>,
) -> HealthCheckResult<HealthCheckResponse> {
let request = tonic::Request::new(HealthCheckRequest { service });
let mut client = client
.ok_or(HealthCheckError::MissingFields(
"[health_client]".to_string(),
))?
.clone();
let response = client
.check(request)
.await
.change_context(HealthCheckError::ConnectionError(
"Failed to call dynamic routing service".to_string(),
))?
.into_inner();
Ok(response)
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 31,
"total_crates": null
} |
fn_clm_external_services_build_unified_connector_service_grpc_headers_4861670135421457472 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/grpc_client/unified_connector_service
/// Build the gRPC Headers for Unified Connector Service Request
pub fn build_unified_connector_service_grpc_headers(
meta: ConnectorAuthMetadata,
grpc_headers: GrpcHeadersUcs,
) -> Result<MetadataMap, UnifiedConnectorServiceError> {
let mut metadata = MetadataMap::new();
let parse =
|key: &str, value: &str| -> Result<MetadataValue<_>, UnifiedConnectorServiceError> {
value.parse::<MetadataValue<_>>().map_err(|error| {
logger::error!(?error);
UnifiedConnectorServiceError::HeaderInjectionFailed(key.to_string())
})
};
metadata.append(
consts::UCS_HEADER_CONNECTOR,
parse("connector", &meta.connector_name)?,
);
metadata.append(
consts::UCS_HEADER_AUTH_TYPE,
parse("auth_type", &meta.auth_type)?,
);
if let Some(api_key) = meta.api_key {
metadata.append(
consts::UCS_HEADER_API_KEY,
parse("api_key", api_key.peek())?,
);
}
if let Some(key1) = meta.key1 {
metadata.append(consts::UCS_HEADER_KEY1, parse("key1", key1.peek())?);
}
if let Some(api_secret) = meta.api_secret {
metadata.append(
consts::UCS_HEADER_API_SECRET,
parse("api_secret", api_secret.peek())?,
);
}
if let Some(auth_key_map) = meta.auth_key_map {
let auth_key_map_str = serde_json::to_string(&auth_key_map).map_err(|error| {
logger::error!(?error);
UnifiedConnectorServiceError::ParsingFailed
})?;
metadata.append(
consts::UCS_HEADER_AUTH_KEY_MAP,
parse("auth_key_map", &auth_key_map_str)?,
);
}
metadata.append(
common_utils_consts::X_MERCHANT_ID,
parse(common_utils_consts::X_MERCHANT_ID, meta.merchant_id.peek())?,
);
if let Some(external_vault_proxy_metadata) = grpc_headers.external_vault_proxy_metadata {
metadata.append(
consts::UCS_HEADER_EXTERNAL_VAULT_METADATA,
parse("external_vault_metadata", &external_vault_proxy_metadata)?,
);
};
let lineage_ids_str = grpc_headers
.lineage_ids
.get_url_encoded_string()
.map_err(|err| {
logger::error!(?err);
UnifiedConnectorServiceError::HeaderInjectionFailed(consts::UCS_LINEAGE_IDS.to_string())
})?;
metadata.append(
consts::UCS_LINEAGE_IDS,
parse(consts::UCS_LINEAGE_IDS, &lineage_ids_str)?,
);
if let Some(reference_id) = grpc_headers.merchant_reference_id {
metadata.append(
consts::UCS_HEADER_REFERENCE_ID,
parse(
consts::UCS_HEADER_REFERENCE_ID,
reference_id.get_string_repr(),
)?,
);
};
if let Some(request_id) = grpc_headers.request_id {
metadata.append(
common_utils_consts::X_REQUEST_ID,
parse(common_utils_consts::X_REQUEST_ID, &request_id)?,
);
};
if let Some(shadow_mode) = grpc_headers.shadow_mode {
metadata.append(
common_utils_consts::X_UNIFIED_CONNECTOR_SERVICE_MODE,
parse(
common_utils_consts::X_UNIFIED_CONNECTOR_SERVICE_MODE,
&shadow_mode.to_string(),
)?,
);
}
if let Err(err) = grpc_headers
.tenant_id
.parse()
.map(|tenant_id| metadata.append(common_utils_consts::TENANT_HEADER, tenant_id))
{
logger::error!(
header_parse_error=?err,
tenant_id=?grpc_headers.tenant_id,
"Failed to parse tenant_id header for UCS gRPC request: {}",
common_utils_consts::TENANT_HEADER
);
}
Ok(metadata)
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 111,
"total_crates": null
} |
fn_clm_external_services_payment_authorize_4861670135421457472 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/grpc_client/unified_connector_service
// Implementation of None for UnifiedConnectorServiceClient
/// Performs Payment Authorize
pub async fn payment_authorize(
&self,
payment_authorize_request: payments_grpc::PaymentServiceAuthorizeRequest,
connector_auth_metadata: ConnectorAuthMetadata,
grpc_headers: GrpcHeadersUcs,
) -> UnifiedConnectorServiceResult<tonic::Response<PaymentServiceAuthorizeResponse>> {
let mut request = tonic::Request::new(payment_authorize_request);
let connector_name = connector_auth_metadata.connector_name.clone();
let metadata =
build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;
*request.metadata_mut() = metadata;
self.client
.clone()
.authorize(request)
.await
.change_context(UnifiedConnectorServiceError::PaymentAuthorizeFailure)
.inspect_err(|error| {
logger::error!(
grpc_error=?error,
method="payment_authorize",
connector_name=?connector_name,
"UCS payment authorize gRPC call failed"
)
})
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 43,
"total_crates": null
} |
fn_clm_external_services_payment_get_4861670135421457472 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/grpc_client/unified_connector_service
// Implementation of None for UnifiedConnectorServiceClient
/// Performs Payment Sync/Get
pub async fn payment_get(
&self,
payment_get_request: payments_grpc::PaymentServiceGetRequest,
connector_auth_metadata: ConnectorAuthMetadata,
grpc_headers: GrpcHeadersUcs,
) -> UnifiedConnectorServiceResult<tonic::Response<payments_grpc::PaymentServiceGetResponse>>
{
let mut request = tonic::Request::new(payment_get_request);
let connector_name = connector_auth_metadata.connector_name.clone();
let metadata =
build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;
*request.metadata_mut() = metadata;
self.client
.clone()
.get(request)
.await
.change_context(UnifiedConnectorServiceError::PaymentGetFailure)
.inspect_err(|error| {
logger::error!(
grpc_error=?error,
method="payment_get",
connector_name=?connector_name,
"UCS payment get/sync gRPC call failed"
)
})
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 37,
"total_crates": null
} |
fn_clm_external_services_payment_setup_mandate_4861670135421457472 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/grpc_client/unified_connector_service
// Implementation of None for UnifiedConnectorServiceClient
/// Performs Payment Setup Mandate
pub async fn payment_setup_mandate(
&self,
payment_register_request: payments_grpc::PaymentServiceRegisterRequest,
connector_auth_metadata: ConnectorAuthMetadata,
grpc_headers: GrpcHeadersUcs,
) -> UnifiedConnectorServiceResult<tonic::Response<payments_grpc::PaymentServiceRegisterResponse>>
{
let mut request = tonic::Request::new(payment_register_request);
let connector_name = connector_auth_metadata.connector_name.clone();
let metadata =
build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;
*request.metadata_mut() = metadata;
self.client
.clone()
.register(request)
.await
.change_context(UnifiedConnectorServiceError::PaymentRegisterFailure)
.inspect_err(|error| {
logger::error!(
grpc_error=?error,
method="payment_setup_mandate",
connector_name=?connector_name,
"UCS payment setup mandate gRPC call failed"
)
})
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 37,
"total_crates": null
} |
fn_clm_external_services_payment_repeat_4861670135421457472 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/grpc_client/unified_connector_service
// Implementation of None for UnifiedConnectorServiceClient
/// Performs Payment repeat (MIT - Merchant Initiated Transaction).
pub async fn payment_repeat(
&self,
payment_repeat_request: payments_grpc::PaymentServiceRepeatEverythingRequest,
connector_auth_metadata: ConnectorAuthMetadata,
grpc_headers: GrpcHeadersUcs,
) -> UnifiedConnectorServiceResult<
tonic::Response<payments_grpc::PaymentServiceRepeatEverythingResponse>,
> {
let mut request = tonic::Request::new(payment_repeat_request);
let connector_name = connector_auth_metadata.connector_name.clone();
let metadata =
build_unified_connector_service_grpc_headers(connector_auth_metadata, grpc_headers)?;
*request.metadata_mut() = metadata;
self.client
.clone()
.repeat_everything(request)
.await
.change_context(UnifiedConnectorServiceError::PaymentRepeatEverythingFailure)
.inspect_err(|error| {
logger::error!(
grpc_error=?error,
method="payment_repeat",
connector_name=?connector_name,
"UCS payment repeat gRPC call failed"
)
})
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 37,
"total_crates": null
} |
fn_clm_external_services_get_dynamic_routing_connection_434055429132977546 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/grpc_client/dynamic_routing
// Inherent implementation for DynamicRoutingClientConfig
/// establish connection with the server
pub fn get_dynamic_routing_connection(
self,
client: Client,
) -> Result<Option<RoutingStrategy>, Box<dyn std::error::Error>> {
match self {
Self::Enabled { host, port, .. } => {
let uri = format!("http://{host}:{port}").parse::<tonic::transport::Uri>()?;
logger::info!("Connection established with dynamic routing gRPC Server");
let (success_rate_client, contract_based_client, elimination_based_client) = (
SuccessRateCalculatorClient::with_origin(client.clone(), uri.clone()),
ContractScoreCalculatorClient::with_origin(client.clone(), uri.clone()),
EliminationAnalyserClient::with_origin(client, uri),
);
Ok(Some(RoutingStrategy {
success_rate_client,
contract_based_client,
elimination_based_client,
}))
}
Self::Disabled => Ok(None),
}
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 35,
"total_crates": null
} |
fn_clm_external_services_add_recovery_headers_4046408955831391427 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/grpc_client/revenue_recovery
// Implementation of tonic::Request<T> for AddRecoveryHeaders
fn add_recovery_headers(&mut self, headers: GrpcRecoveryHeaders) {
headers.request_id.map(|request_id| {
request_id
.parse()
.map(|request_id_val| {
self
.metadata_mut()
.append(consts::X_REQUEST_ID, request_id_val)
})
.inspect_err(
|err| logger::warn!(header_parse_error=?err,"invalid {} received",consts::X_REQUEST_ID),
)
.ok();
});
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 25,
"total_crates": null
} |
fn_clm_external_services_create_revenue_recovery_grpc_request_4046408955831391427 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/grpc_client/revenue_recovery
/// Creates a tonic::Request with recovery headers added.
pub(crate) fn create_revenue_recovery_grpc_request<T: Debug>(
message: T,
recovery_headers: GrpcRecoveryHeaders,
) -> tonic::Request<T> {
let mut request = tonic::Request::new(message);
request.add_recovery_headers(recovery_headers);
request
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 17,
"total_crates": null
} |
fn_clm_external_services_foreign_try_from_-657950532223310013 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/grpc_client/dynamic_routing/elimination_based_client
// Implementation of EliminationBucketConfig for ForeignTryFrom<EliminationConfig>
fn foreign_try_from(config: EliminationConfig) -> Result<Self, Self::Error> {
Ok(Self {
bucket_size: config
.bucket_size
.get_required_value("bucket_size")
.change_context(DynamicRoutingError::MissingRequiredField {
field: "bucket_size".to_string(),
})?,
bucket_leak_interval_in_secs: config
.bucket_leak_interval_in_secs
.get_required_value("bucket_leak_interval_in_secs")
.change_context(DynamicRoutingError::MissingRequiredField {
field: "bucket_leak_interval_in_secs".to_string(),
})?,
})
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 440,
"total_crates": null
} |
fn_clm_external_services_perform_elimination_routing_-657950532223310013 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/grpc_client/dynamic_routing/elimination_based_client
// Implementation of EliminationAnalyserClient<Client> for EliminationBasedRouting
async fn perform_elimination_routing(
&self,
id: String,
params: String,
label_input: Vec<RoutableConnectorChoice>,
configs: Option<EliminationConfig>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<EliminationResponse> {
let labels = label_input
.into_iter()
.map(|conn_choice| conn_choice.to_string())
.collect::<Vec<_>>();
let config = configs.map(ForeignTryFrom::foreign_try_from).transpose()?;
let request = grpc_client::create_grpc_request(
EliminationRequest {
id,
params,
labels,
config,
},
headers,
);
let response = self
.clone()
.get_elimination_status(request)
.await
.change_context(DynamicRoutingError::EliminationRateRoutingFailure(
"Failed to perform the elimination analysis".to_string(),
))?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 38,
"total_crates": null
} |
fn_clm_external_services_update_elimination_bucket_config_-657950532223310013 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/grpc_client/dynamic_routing/elimination_based_client
// Implementation of EliminationAnalyserClient<Client> for EliminationBasedRouting
async fn update_elimination_bucket_config(
&self,
id: String,
params: String,
report: Vec<RoutableConnectorChoiceWithBucketName>,
configs: Option<EliminationConfig>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<UpdateEliminationBucketResponse> {
let config = configs.map(ForeignTryFrom::foreign_try_from).transpose()?;
let labels_with_bucket_name = report
.into_iter()
.map(|conn_choice_with_bucket| LabelWithBucketName {
label: conn_choice_with_bucket
.routable_connector_choice
.to_string(),
bucket_name: conn_choice_with_bucket.bucket_name,
})
.collect::<Vec<_>>();
let request = grpc_client::create_grpc_request(
UpdateEliminationBucketRequest {
id,
params,
labels_with_bucket_name,
config,
},
headers,
);
let response = self
.clone()
.update_elimination_bucket(request)
.await
.change_context(DynamicRoutingError::EliminationRateRoutingFailure(
"Failed to update the elimination bucket".to_string(),
))?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 35,
"total_crates": null
} |
fn_clm_external_services_invalidate_elimination_bucket_-657950532223310013 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/grpc_client/dynamic_routing/elimination_based_client
// Implementation of EliminationAnalyserClient<Client> for EliminationBasedRouting
async fn invalidate_elimination_bucket(
&self,
id: String,
headers: GrpcHeaders,
) -> DynamicRoutingResult<InvalidateBucketResponse> {
let request = grpc_client::create_grpc_request(InvalidateBucketRequest { id }, headers);
let response = self
.clone()
.invalidate_bucket(request)
.await
.change_context(DynamicRoutingError::EliminationRateRoutingFailure(
"Failed to invalidate the elimination bucket".to_string(),
))?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 25,
"total_crates": null
} |
fn_clm_external_services_foreign_try_from_-8573382143543490697 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/grpc_client/dynamic_routing/success_rate_client
// Implementation of CalGlobalSuccessRateConfig for ForeignTryFrom<SuccessBasedRoutingConfigBody>
fn foreign_try_from(config: SuccessBasedRoutingConfigBody) -> Result<Self, Self::Error> {
Ok(Self {
entity_min_aggregates_size: config
.min_aggregates_size
.get_required_value("min_aggregate_size")
.change_context(DynamicRoutingError::MissingRequiredField {
field: "min_aggregates_size".to_string(),
})?,
entity_default_success_rate: config
.default_success_rate
.get_required_value("default_success_rate")
.change_context(DynamicRoutingError::MissingRequiredField {
field: "default_success_rate".to_string(),
})?,
})
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 440,
"total_crates": null
} |
fn_clm_external_services_update_success_rate_-8573382143543490697 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/grpc_client/dynamic_routing/success_rate_client
// Implementation of SuccessRateCalculatorClient<Client> for SuccessBasedDynamicRouting
async fn update_success_rate(
&self,
id: String,
success_rate_based_config: SuccessBasedRoutingConfig,
params: String,
label_input: Vec<RoutableConnectorChoiceWithStatus>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<UpdateSuccessRateWindowResponse> {
let config = success_rate_based_config
.config
.map(ForeignTryFrom::foreign_try_from)
.transpose()?;
let labels_with_status = label_input
.clone()
.into_iter()
.map(|conn_choice| LabelWithStatus {
label: conn_choice.routable_connector_choice.to_string(),
status: conn_choice.status,
})
.collect();
let global_labels_with_status = label_input
.into_iter()
.map(|conn_choice| LabelWithStatus {
label: conn_choice.routable_connector_choice.connector.to_string(),
status: conn_choice.status,
})
.collect();
let request = grpc_client::create_grpc_request(
UpdateSuccessRateWindowRequest {
id,
params,
labels_with_status,
config,
global_labels_with_status,
},
headers,
);
let response = self
.clone()
.update_success_rate_window(request)
.await
.change_context(DynamicRoutingError::SuccessRateBasedRoutingFailure(
"Failed to update the success rate window".to_string(),
))?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 47,
"total_crates": null
} |
fn_clm_external_services_calculate_entity_and_global_success_rate_-8573382143543490697 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/grpc_client/dynamic_routing/success_rate_client
// Implementation of SuccessRateCalculatorClient<Client> for SuccessBasedDynamicRouting
async fn calculate_entity_and_global_success_rate(
&self,
id: String,
success_rate_based_config: SuccessBasedRoutingConfig,
params: String,
label_input: Vec<RoutableConnectorChoice>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<CalGlobalSuccessRateResponse> {
let labels = label_input
.clone()
.into_iter()
.map(|conn_choice| conn_choice.to_string())
.collect::<Vec<_>>();
let global_labels = label_input
.into_iter()
.map(|conn_choice| conn_choice.connector.to_string())
.collect::<Vec<_>>();
let config = success_rate_based_config
.config
.map(ForeignTryFrom::foreign_try_from)
.transpose()?;
let request = grpc_client::create_grpc_request(
CalGlobalSuccessRateRequest {
entity_id: id,
entity_params: params,
entity_labels: labels,
global_labels,
config,
},
headers,
);
let response = self
.clone()
.fetch_entity_and_global_success_rate(request)
.await
.change_context(DynamicRoutingError::SuccessRateBasedRoutingFailure(
"Failed to fetch the entity and global success rate".to_string(),
))?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 43,
"total_crates": null
} |
fn_clm_external_services_calculate_success_rate_-8573382143543490697 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/grpc_client/dynamic_routing/success_rate_client
// Implementation of SuccessRateCalculatorClient<Client> for SuccessBasedDynamicRouting
async fn calculate_success_rate(
&self,
id: String,
success_rate_based_config: SuccessBasedRoutingConfig,
params: String,
label_input: Vec<RoutableConnectorChoice>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<CalSuccessRateResponse> {
let labels = label_input
.into_iter()
.map(|conn_choice| conn_choice.to_string())
.collect::<Vec<_>>();
let config = success_rate_based_config
.config
.map(ForeignTryFrom::foreign_try_from)
.transpose()?;
let request = grpc_client::create_grpc_request(
CalSuccessRateRequest {
id,
params,
labels,
config,
},
headers,
);
let response = self
.clone()
.fetch_success_rate(request)
.await
.change_context(DynamicRoutingError::SuccessRateBasedRoutingFailure(
"Failed to fetch the success rate".to_string(),
))?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 35,
"total_crates": null
} |
fn_clm_external_services_invalidate_success_rate_routing_keys_-8573382143543490697 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/grpc_client/dynamic_routing/success_rate_client
// Implementation of SuccessRateCalculatorClient<Client> for SuccessBasedDynamicRouting
async fn invalidate_success_rate_routing_keys(
&self,
id: String,
headers: GrpcHeaders,
) -> DynamicRoutingResult<InvalidateWindowsResponse> {
let request = grpc_client::create_grpc_request(InvalidateWindowsRequest { id }, headers);
let response = self
.clone()
.invalidate_windows(request)
.await
.change_context(DynamicRoutingError::SuccessRateBasedRoutingFailure(
"Failed to invalidate the success rate routing keys".to_string(),
))?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 25,
"total_crates": null
} |
fn_clm_external_services_foreign_try_from_-4224376731579693474 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client
// Implementation of CalContractScoreConfig for ForeignTryFrom<ContractBasedRoutingConfigBody>
fn foreign_try_from(config: ContractBasedRoutingConfigBody) -> Result<Self, Self::Error> {
Ok(Self {
constants: config
.constants
.get_required_value("constants")
.change_context(DynamicRoutingError::MissingRequiredField {
field: "constants".to_string(),
})?,
time_scale: config.time_scale.clone().map(TimeScale::foreign_from),
})
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 438,
"total_crates": null
} |
fn_clm_external_services_foreign_from_-4224376731579693474 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client
// Implementation of ProtoLabelInfo for ForeignFrom<LabelInformation>
fn foreign_from(config: LabelInformation) -> Self {
Self {
label: format!(
"{}:{}",
config.label.clone(),
config.mca_id.get_string_repr()
),
target_count: config.target_count,
target_time: config.target_time,
current_count: u64::default(),
}
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 214,
"total_crates": null
} |
fn_clm_external_services_calculate_contract_score_-4224376731579693474 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client
// Implementation of ContractScoreCalculatorClient<Client> for ContractBasedDynamicRouting
async fn calculate_contract_score(
&self,
id: String,
config: ContractBasedRoutingConfig,
params: String,
label_input: Vec<RoutableConnectorChoice>,
headers: GrpcHeaders,
) -> DynamicRoutingResult<CalContractScoreResponse> {
let labels = label_input
.into_iter()
.map(|conn_choice| conn_choice.to_string())
.collect::<Vec<_>>();
let config = config
.config
.map(ForeignTryFrom::foreign_try_from)
.transpose()?;
let request = grpc_client::create_grpc_request(
CalContractScoreRequest {
id,
params,
labels,
config,
},
headers,
);
let response = self
.clone()
.fetch_contract_score(request)
.await
.map_err(|err| match err.code() {
Code::NotFound => DynamicRoutingError::ContractNotFound,
_ => DynamicRoutingError::ContractBasedRoutingFailure(err.to_string()),
})?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 40,
"total_crates": null
} |
fn_clm_external_services_update_contracts_-4224376731579693474 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client
// Implementation of ContractScoreCalculatorClient<Client> for ContractBasedDynamicRouting
async fn update_contracts(
&self,
id: String,
label_info: Vec<LabelInformation>,
params: String,
_response: Vec<RoutableConnectorChoiceWithStatus>,
incr_count: u64,
headers: GrpcHeaders,
) -> DynamicRoutingResult<UpdateContractResponse> {
let mut labels_information = label_info
.into_iter()
.map(ProtoLabelInfo::foreign_from)
.collect::<Vec<_>>();
labels_information
.iter_mut()
.for_each(|info| info.current_count += incr_count);
let request = grpc_client::create_grpc_request(
UpdateContractRequest {
id,
params,
labels_information,
},
headers,
);
let response = self
.clone()
.update_contract(request)
.await
.change_context(DynamicRoutingError::ContractBasedRoutingFailure(
"Failed to update the contracts".to_string(),
))?
.into_inner();
logger::info!(dynamic_routing_response=?response);
Ok(response)
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 36,
"total_crates": null
} |
fn_clm_external_services_invalidate_contracts_-4224376731579693474 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client
// Implementation of ContractScoreCalculatorClient<Client> for ContractBasedDynamicRouting
async fn invalidate_contracts(
&self,
id: String,
headers: GrpcHeaders,
) -> DynamicRoutingResult<InvalidateContractResponse> {
let request = grpc_client::create_grpc_request(InvalidateContractRequest { id }, headers);
let response = self
.clone()
.invalidate_contract(request)
.await
.change_context(DynamicRoutingError::ContractBasedRoutingFailure(
"Failed to invalidate the contracts".to_string(),
))?
.into_inner();
Ok(response)
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 25,
"total_crates": null
} |
fn_clm_external_services_validate_1182830238634037889 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/grpc_client/revenue_recovery/recovery_decider_client
// Inherent implementation for RecoveryDeciderClientConfig
/// Validate the configuration
pub fn validate(&self) -> Result<(), RecoveryDeciderError> {
use common_utils::fp_utils::when;
when(self.base_url.is_empty(), || {
Err(RecoveryDeciderError::ConfigError(
"Recovery Decider base URL cannot be empty when configuration is provided"
.to_string(),
))
})
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 227,
"total_crates": null
} |
fn_clm_external_services_get_recovery_decider_connection_1182830238634037889 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/grpc_client/revenue_recovery/recovery_decider_client
// Inherent implementation for RecoveryDeciderClientConfig
/// create a connection
pub fn get_recovery_decider_connection(
&self,
hyper_client: Client,
) -> Result<DeciderClient<Client>, Report<RecoveryDeciderError>> {
let uri = self
.base_url
.parse::<tonic::transport::Uri>()
.map_err(Report::from)
.change_context(RecoveryDeciderError::ConfigError(format!(
"Invalid URI: {}",
self.base_url
)))?;
let service_client = DeciderClient::with_origin(hyper_client, uri);
Ok(service_client)
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 29,
"total_crates": null
} |
fn_clm_external_services_decide_on_retry_1182830238634037889 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/grpc_client/revenue_recovery/recovery_decider_client
// Implementation of DeciderClient<Client> for RecoveryDeciderClientInterface
async fn decide_on_retry(
&mut self,
request_payload: DeciderRequest,
recovery_headers: super::GrpcRecoveryHeaders,
) -> RecoveryDeciderResult<DeciderResponse> {
let request =
super::create_revenue_recovery_grpc_request(request_payload, recovery_headers);
logger::debug!(decider_request =?request);
let grpc_response = self
.decide(request)
.await
.change_context(RecoveryDeciderError::ServiceError(
"Decider service call failed".to_string(),
))?
.into_inner();
logger::debug!(grpc_decider_response =?grpc_response);
Ok(grpc_response)
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 23,
"total_crates": null
} |
fn_clm_external_services_validate_-3799855670246986663 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/email/ses
// Implementation of None for SESConfig
/// Validation for the SES client specific configs
pub fn validate(&self) -> Result<(), &'static str> {
use common_utils::{ext_traits::ConfigExt, fp_utils::when};
when(self.email_role_arn.is_default_or_empty(), || {
Err("email.aws_ses.email_role_arn must not be empty")
})?;
when(self.sts_role_session_name.is_default_or_empty(), || {
Err("email.aws_ses.sts_role_session_name must not be empty")
})
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 227,
"total_crates": null
} |
fn_clm_external_services_create_client_-3799855670246986663 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/email/ses
// Inherent implementation for AwsSes
/// A helper function to create ses client
pub async fn create_client(
conf: &EmailSettings,
ses_config: &SESConfig,
proxy_url: Option<impl AsRef<str>>,
) -> CustomResult<Client, AwsSesError> {
let sts_config = Self::get_shared_config(conf.aws_region.to_owned(), proxy_url.as_ref())?
.load()
.await;
let role = aws_sdk_sts::Client::new(&sts_config)
.assume_role()
.role_arn(&ses_config.email_role_arn)
.role_session_name(&ses_config.sts_role_session_name)
.send()
.await
.change_context(AwsSesError::AssumeRoleFailure {
region: conf.aws_region.to_owned(),
role_arn: ses_config.email_role_arn.to_owned(),
session_name: ses_config.sts_role_session_name.to_owned(),
})?;
let creds = role.credentials().ok_or(
report!(AwsSesError::TemporaryCredentialsMissing(format!(
"{role:?}"
)))
.attach_printable("Credentials object not available"),
)?;
let credentials = Credentials::new(
creds.access_key_id(),
creds.secret_access_key(),
Some(creds.session_token().to_owned()),
u64::try_from(creds.expiration().as_nanos())
.ok()
.map(Duration::from_nanos)
.and_then(|val| SystemTime::UNIX_EPOCH.checked_add(val)),
"custom_provider",
);
logger::debug!(
"Obtained SES temporary credentials with expiry {:?}",
credentials.expiry()
);
let ses_config = Self::get_shared_config(conf.aws_region.to_owned(), proxy_url)?
.credentials_provider(credentials)
.load()
.await;
Ok(Client::new(&ses_config))
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 105,
"total_crates": null
} |
fn_clm_external_services_create_-3799855670246986663 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/email/ses
// Inherent implementation for AwsSes
/// Constructs a new AwsSes client
pub async fn create(
conf: &EmailSettings,
ses_config: &SESConfig,
proxy_url: Option<impl AsRef<str>>,
) -> Self {
// Build the client initially which will help us know if the email configuration is correct
Self::create_client(conf, ses_config, proxy_url)
.await
.map_err(|error| logger::error!(?error, "Failed to initialize SES Client"))
.ok();
Self {
sender: conf.sender_email.clone(),
ses_config: ses_config.clone(),
settings: conf.clone(),
}
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 78,
"total_crates": null
} |
fn_clm_external_services_send_email_-3799855670246986663 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/email/ses
// Implementation of AwsSes for EmailClient
async fn send_email(
&self,
recipient: pii::Email,
subject: String,
body: Self::RichText,
proxy_url: Option<&String>,
) -> EmailResult<()> {
// Not using the same email client which was created at startup as the role session would expire
// Create a client every time when the email is being sent
let email_client = Self::create_client(&self.settings, &self.ses_config, proxy_url)
.await
.change_context(EmailError::ClientBuildingFailure)?;
email_client
.send_email()
.from_email_address(self.sender.to_owned())
.destination(
Destination::builder()
.to_addresses(recipient.peek())
.build(),
)
.content(
EmailContent::builder()
.simple(
Message::builder()
.subject(
Content::builder()
.data(subject)
.build()
.change_context(EmailError::ContentBuildFailure)?,
)
.body(body)
.build(),
)
.build(),
)
.send()
.await
.map_err(|e| AwsSesError::SendingFailure(Box::new(e)))
.change_context(EmailError::EmailSendingFailure)?;
Ok(())
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 68,
"total_crates": null
} |
fn_clm_external_services_convert_to_rich_text_-3799855670246986663 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/email/ses
// Implementation of AwsSes for EmailClient
fn convert_to_rich_text(
&self,
intermediate_string: IntermediateString,
) -> CustomResult<Self::RichText, EmailError> {
let email_body = Body::builder()
.html(
Content::builder()
.data(intermediate_string.into_inner())
.charset("UTF-8")
.build()
.change_context(EmailError::ContentBuildFailure)?,
)
.build();
Ok(email_body)
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 29,
"total_crates": null
} |
fn_clm_external_services_create_-4883370010201602958 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/email/no_email
// Inherent implementation for NoEmailClient
/// Constructs a new client when email is disabled
pub async fn create() -> Self {
Self {}
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 66,
"total_crates": null
} |
fn_clm_external_services_send_email_-4883370010201602958 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/email/no_email
// Implementation of NoEmailClient for EmailClient
async fn send_email(
&self,
_recipient: pii::Email,
_subject: String,
_body: Self::RichText,
_proxy_url: Option<&String>,
) -> EmailResult<()> {
logger::info!("Email not sent as email support is disabled, please enable any of the supported email clients to send emails");
Ok(())
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14,
"total_crates": null
} |
fn_clm_external_services_convert_to_rich_text_-4883370010201602958 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/email/no_email
// Implementation of NoEmailClient for EmailClient
fn convert_to_rich_text(
&self,
intermediate_string: IntermediateString,
) -> CustomResult<Self::RichText, EmailError> {
Ok(intermediate_string.into_inner())
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 13,
"total_crates": null
} |
fn_clm_external_services_validate_-2456641570340612897 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/email/smtp
// Implementation of None for SmtpServerConfig
/// Validation for the SMTP server client specific configs
pub fn validate(&self) -> Result<(), &'static str> {
use common_utils::{ext_traits::ConfigExt, fp_utils::when};
when(self.host.is_default_or_empty(), || {
Err("email.smtp.host must not be empty")
})?;
self.username.clone().zip(self.password.clone()).map_or(
Ok(()),
|(username, password)| {
when(username.peek().is_default_or_empty(), || {
Err("email.smtp.username must not be empty")
})?;
when(password.peek().is_default_or_empty(), || {
Err("email.smtp.password must not be empty")
})
},
)?;
Ok(())
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 243,
"total_crates": null
} |
fn_clm_external_services_create_client_-2456641570340612897 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/email/smtp
// Inherent implementation for SmtpServer
/// A helper function to create SMTP server client
pub fn create_client(&self) -> Result<SmtpTransport, SmtpError> {
let host = self.smtp_config.host.clone();
let port = self.smtp_config.port;
let timeout = Some(Duration::from_secs(self.smtp_config.timeout));
let credentials = self
.smtp_config
.username
.clone()
.zip(self.smtp_config.password.clone())
.map(|(username, password)| {
Credentials::new(username.peek().to_owned(), password.peek().to_owned())
});
match &self.smtp_config.connection {
SmtpConnection::StartTls => match credentials {
Some(credentials) => Ok(SmtpTransport::starttls_relay(&host)
.map_err(SmtpError::ConnectionFailure)?
.port(port)
.timeout(timeout)
.credentials(credentials)
.build()),
None => Ok(SmtpTransport::starttls_relay(&host)
.map_err(SmtpError::ConnectionFailure)?
.port(port)
.timeout(timeout)
.build()),
},
SmtpConnection::Plaintext => match credentials {
Some(credentials) => Ok(SmtpTransport::builder_dangerous(&host)
.port(port)
.timeout(timeout)
.credentials(credentials)
.build()),
None => Ok(SmtpTransport::builder_dangerous(&host)
.port(port)
.timeout(timeout)
.build()),
},
}
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 101,
"total_crates": null
} |
fn_clm_external_services_create_-2456641570340612897 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/email/smtp
// Inherent implementation for SmtpServer
/// Constructs a new SMTP client
pub async fn create(conf: &EmailSettings, smtp_config: SmtpServerConfig) -> Self {
Self {
sender: conf.sender_email.clone(),
smtp_config: smtp_config.clone(),
}
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 70,
"total_crates": null
} |
fn_clm_external_services_send_email_-2456641570340612897 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/email/smtp
// Implementation of SmtpServer for EmailClient
async fn send_email(
&self,
recipient: pii::Email,
subject: String,
body: Self::RichText,
_proxy_url: Option<&String>,
) -> EmailResult<()> {
// Create a client every time when the email is being sent
let email_client =
Self::create_client(self).change_context(EmailError::EmailSendingFailure)?;
let email = Message::builder()
.to(Self::to_mail_box(recipient.peek().to_string())?)
.from(Self::to_mail_box(self.sender.clone())?)
.subject(subject)
.header(ContentType::TEXT_HTML)
.body(body)
.map_err(SmtpError::MessageBuildingFailed)
.change_context(EmailError::EmailSendingFailure)?;
email_client
.send(&email)
.map_err(SmtpError::SendingFailure)
.change_context(EmailError::EmailSendingFailure)?;
Ok(())
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 50,
"total_crates": null
} |
fn_clm_external_services_to_mail_box_-2456641570340612897 | clm | function | // Repository: hyperswitch
// Crate: external_services
// Module: crates/external_services/src/email/smtp
// Inherent implementation for SmtpServer
/// helper function to convert email id into Mailbox
fn to_mail_box(email: String) -> EmailResult<Mailbox> {
Ok(Mailbox::new(
None,
email
.parse()
.map_err(SmtpError::EmailParsingFailed)
.change_context(EmailError::EmailSendingFailure)?,
))
}
| {
"crate": "external_services",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 22,
"total_crates": null
} |
fn_clm_euclid_macros_knowledge_6180411282091019233 | clm | function | // Repository: hyperswitch
// Crate: euclid_macros
// Module: crates/euclid_macros/src/lib
pub fn knowledge(ts: TokenStream) -> TokenStream {
match inner::knowledge_inner(ts.into()) {
Ok(ts) => ts.into(),
Err(e) => e.into_compile_error().into(),
}
}
| {
"crate": "euclid_macros",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 20,
"total_crates": null
} |
fn_clm_euclid_macros_enum_nums_6180411282091019233 | clm | function | // Repository: hyperswitch
// Crate: euclid_macros
// Module: crates/euclid_macros/src/lib
pub fn enum_nums(ts: TokenStream) -> TokenStream {
inner::enum_nums_inner(ts)
}
| {
"crate": "euclid_macros",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 12,
"total_crates": null
} |
fn_clm_euclid_macros_error_7679541349067252623 | clm | function | // Repository: hyperswitch
// Crate: euclid_macros
// Module: crates/euclid_macros/src/inner/enum_nums
fn error() -> TokenStream2 {
syn::Error::new(
Span::call_site(),
"'EnumNums' can only be derived on enums with unit variants".to_string(),
)
.to_compile_error()
}
| {
"crate": "euclid_macros",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 95,
"total_crates": null
} |
fn_clm_euclid_macros_enum_nums_inner_7679541349067252623 | clm | function | // Repository: hyperswitch
// Crate: euclid_macros
// Module: crates/euclid_macros/src/inner/enum_nums
pub(crate) fn enum_nums_inner(ts: TokenStream) -> TokenStream {
let derive_input = syn::parse_macro_input!(ts as syn::DeriveInput);
let enum_obj = match derive_input.data {
syn::Data::Enum(e) => e,
_ => return error().into(),
};
let enum_name = derive_input.ident;
let mut match_arms = Vec::<TokenStream2>::with_capacity(enum_obj.variants.len());
for (i, variant) in enum_obj.variants.iter().enumerate() {
match variant.fields {
syn::Fields::Unit => {}
_ => return error().into(),
}
let var_ident = &variant.ident;
match_arms.push(quote! { Self::#var_ident => #i });
}
let impl_block = quote! {
impl #enum_name {
pub fn to_num(&self) -> usize {
match self {
#(#match_arms),*
}
}
}
};
impl_block.into()
}
| {
"crate": "euclid_macros",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 33,
"total_crates": null
} |
fn_clm_euclid_macros_to_string_3249742868210120849 | clm | function | // Repository: hyperswitch
// Crate: euclid_macros
// Module: crates/euclid_macros/src/inner/knowledge
// Inherent implementation for ValueType
fn to_string(&self, key: &str) -> String {
match self {
Self::Any => format!("{key}(any)"),
Self::EnumVariant(s) => format!("{key}({s})"),
Self::Number { number, comparison } => {
format!("{key}({comparison}{number})")
}
}
}
| {
"crate": "euclid_macros",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14744,
"total_crates": null
} |
fn_clm_euclid_macros_new_3249742868210120849 | clm | function | // Repository: hyperswitch
// Crate: euclid_macros
// Module: crates/euclid_macros/src/inner/knowledge
// Implementation of None for GenContext
fn new() -> Self {
Self {
next_idx: 1,
next_node_idx: 1,
idx2atom: FxHashMap::default(),
atom2idx: FxHashMap::default(),
edges: FxHashMap::default(),
compiled_atoms: FxHashMap::default(),
}
}
| {
"crate": "euclid_macros",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14461,
"total_crates": null
} |
fn_clm_euclid_macros_parse_3249742868210120849 | clm | function | // Repository: hyperswitch
// Crate: euclid_macros
// Module: crates/euclid_macros/src/inner/knowledge
// Implementation of Program for Parse
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let mut rules: Vec<Rc<Rule>> = Vec::new();
while !input.is_empty() {
rules.push(Rc::new(input.parse::<Rule>()?));
}
Ok(Self { rules })
}
| {
"crate": "euclid_macros",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 454,
"total_crates": null
} |
fn_clm_euclid_macros_cycle_dfs_3249742868210120849 | clm | function | // Repository: hyperswitch
// Crate: euclid_macros
// Module: crates/euclid_macros/src/inner/knowledge
// Implementation of None for GenContext
fn cycle_dfs(
&self,
node_id: usize,
explored: &mut FxHashSet<usize>,
visited: &mut FxHashSet<usize>,
order: &mut Vec<usize>,
) -> Result<Option<Vec<usize>>, String> {
if explored.contains(&node_id) {
let position = order
.iter()
.position(|v| *v == node_id)
.ok_or_else(|| "Error deciding cycle order".to_string())?;
let cycle_order = order
.get(position..)
.ok_or_else(|| "Error getting cycle order".to_string())?
.to_vec();
Ok(Some(cycle_order))
} else if visited.contains(&node_id) {
Ok(None)
} else {
visited.insert(node_id);
explored.insert(node_id);
order.push(node_id);
let dests = self
.edges
.get(&node_id)
.ok_or_else(|| "Error getting edges of node".to_string())?;
for dest in dests.iter().copied() {
if let Some(cycle) = self.cycle_dfs(dest, explored, visited, order)? {
return Ok(Some(cycle));
}
}
order.pop();
Ok(None)
}
}
| {
"crate": "euclid_macros",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 54,
"total_crates": null
} |
fn_clm_euclid_macros_detect_graph_cycles_3249742868210120849 | clm | function | // Repository: hyperswitch
// Crate: euclid_macros
// Module: crates/euclid_macros/src/inner/knowledge
// Implementation of None for GenContext
fn detect_graph_cycles(&self) -> Result<(), String> {
let start_nodes = self.edges.keys().copied().collect::<Vec<usize>>();
let mut total_visited = FxHashSet::<usize>::default();
for node_id in start_nodes.iter().copied() {
let mut explored = FxHashSet::<usize>::default();
let mut order = Vec::<usize>::new();
match self.cycle_dfs(node_id, &mut explored, &mut total_visited, &mut order)? {
None => {}
Some(order) => {
let mut display_strings = Vec::<String>::with_capacity(order.len() + 1);
for cycle_node_id in order {
let node = self.idx2atom.get(&cycle_node_id).ok_or_else(|| {
"Failed to find node during cycle display creation".to_string()
})?;
display_strings.push(node.to_string());
}
let first = display_strings
.first()
.cloned()
.ok_or("Unable to fill cycle display array")?;
display_strings.push(first);
return Err(format!("Found cycle: {}", display_strings.join(" -> ")));
}
}
}
Ok(())
}
| {
"crate": "euclid_macros",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 49,
"total_crates": null
} |
fn_clm_masking_zeroize_2360117845480941133 | clm | function | // Repository: hyperswitch
// Crate: masking
// Purpose: PII protection and data masking
// Module: crates/masking/tests/basic
// Implementation of AccountNumber for ZeroizableSecret
fn zeroize(&mut self) {
self.0.zeroize();
}
| {
"crate": "masking",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 25,
"total_crates": null
} |
fn_clm_masking_basic_2360117845480941133 | clm | function | // Repository: hyperswitch
// Crate: masking
// Purpose: PII protection and data masking
// Module: crates/masking/tests/basic
fn basic() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
#[cfg_attr(feature = "serde", derive(Serialize))]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AccountNumber(String);
#[cfg(feature = "alloc")]
impl ZeroizableSecret for AccountNumber {
fn zeroize(&mut self) {
self.0.zeroize();
}
}
#[cfg(feature = "serde")]
impl SerializableSecret for AccountNumber {}
#[cfg_attr(feature = "serde", derive(Serialize))]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Composite {
secret_number: Secret<AccountNumber>,
not_secret: String,
}
// construct
let secret_number = Secret::<AccountNumber>::new(AccountNumber("abc".to_string()));
let not_secret = "not secret".to_string();
let composite = Composite {
secret_number,
not_secret,
};
// clone
#[allow(clippy::redundant_clone)] // We are asserting that the cloned value is equal
let composite2 = composite.clone();
assert_eq!(composite, composite2);
// format
let got = format!("{composite:?}");
let exp = r#"Composite { secret_number: *** basic::basic::AccountNumber ***, not_secret: "not secret" }"#;
assert_eq!(got, exp);
// serialize
#[cfg(feature = "serde")]
{
let got = serde_json::to_string(&composite).unwrap();
let exp = r#"{"secret_number":"abc","not_secret":"not secret"}"#;
assert_eq!(got, exp);
}
// end
Ok(())
}
| {
"crate": "masking",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14,
"total_crates": null
} |
fn_clm_masking_without_serialize_2360117845480941133 | clm | function | // Repository: hyperswitch
// Crate: masking
// Purpose: PII protection and data masking
// Module: crates/masking/tests/basic
fn without_serialize() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
#[cfg_attr(feature = "serde", derive(Serialize))]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AccountNumber(String);
#[cfg(feature = "alloc")]
impl ZeroizableSecret for AccountNumber {
fn zeroize(&mut self) {
self.0.zeroize();
}
}
#[cfg_attr(feature = "serde", derive(Serialize))]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Composite {
#[cfg_attr(feature = "serde", serde(skip))]
secret_number: Secret<AccountNumber>,
not_secret: String,
}
// construct
let secret_number = Secret::<AccountNumber>::new(AccountNumber("abc".to_string()));
let not_secret = "not secret".to_string();
let composite = Composite {
secret_number,
not_secret,
};
// format
let got = format!("{composite:?}");
let exp = r#"Composite { secret_number: *** basic::without_serialize::AccountNumber ***, not_secret: "not secret" }"#;
assert_eq!(got, exp);
// serialize
#[cfg(feature = "serde")]
{
let got = serde_json::to_string(&composite).unwrap();
let exp = r#"{"not_secret":"not secret"}"#;
assert_eq!(got, exp);
}
// end
Ok(())
}
| {
"crate": "masking",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 12,
"total_crates": null
} |
fn_clm_masking_for_string_2360117845480941133 | clm | function | // Repository: hyperswitch
// Crate: masking
// Purpose: PII protection and data masking
// Module: crates/masking/tests/basic
fn for_string() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
#[cfg_attr(all(feature = "alloc", feature = "serde"), derive(Serialize))]
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Composite {
secret_number: Secret<String>,
not_secret: String,
}
// construct
let secret_number = Secret::<String>::new("abc".to_string());
let not_secret = "not secret".to_string();
let composite = Composite {
secret_number,
not_secret,
};
// clone
#[allow(clippy::redundant_clone)] // We are asserting that the cloned value is equal
let composite2 = composite.clone();
assert_eq!(composite, composite2);
// format
let got = format!("{composite:?}");
let exp =
r#"Composite { secret_number: *** alloc::string::String ***, not_secret: "not secret" }"#;
assert_eq!(got, exp);
// serialize
#[cfg(all(feature = "alloc", feature = "serde"))]
{
let got = serde_json::to_string(&composite).unwrap();
let exp = r#"{"secret_number":"abc","not_secret":"not secret"}"#;
assert_eq!(got, exp);
}
// end
Ok(())
}
| {
"crate": "masking",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 10,
"total_crates": null
} |
fn_clm_masking_fmt_5830369588327829564 | clm | function | // Repository: hyperswitch
// Crate: masking
// Purpose: PII protection and data masking
// Module: crates/masking/src/strategy
// Implementation of WithoutType for Strategy<T>
fn fmt(_: &T, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt.write_str("*** ***")
}
| {
"crate": "masking",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 40,
"total_crates": null
} |
fn_clm_masking_expose_-5098255901369738420 | clm | function | // Repository: hyperswitch
// Crate: masking
// Purpose: PII protection and data masking
// Module: crates/masking/src/abs
// Implementation of Secret<S, I> for ExposeInterface<S>
fn expose(self) -> S {
self.inner_secret
}
| {
"crate": "masking",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 887,
"total_crates": null
} |
fn_clm_masking_switch_strategy_-5098255901369738420 | clm | function | // Repository: hyperswitch
// Crate: masking
// Purpose: PII protection and data masking
// Module: crates/masking/src/abs
// Implementation of Secret<S, FromStrategy> for SwitchStrategy<FromStrategy, ToStrategy>
fn switch_strategy(self) -> Self::Output {
Secret::new(self.inner_secret)
}
| {
"crate": "masking",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 70,
"total_crates": null
} |
fn_clm_masking_expose_option_-5098255901369738420 | clm | function | // Repository: hyperswitch
// Crate: masking
// Purpose: PII protection and data masking
// Module: crates/masking/src/abs
// Implementation of Option<Secret<S, I>> for ExposeOptionInterface<Option<S>>
fn expose_option(self) -> Option<S> {
self.map(ExposeInterface::expose)
}
| {
"crate": "masking",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 52,
"total_crates": null
} |
fn_clm_masking_clone_-2729277852852699987 | clm | function | // Repository: hyperswitch
// Crate: masking
// Purpose: PII protection and data masking
// Module: crates/masking/src/strong_secret
// Implementation of StrongSecret<Secret, MaskingStrategy> for Clone
fn clone(&self) -> Self {
Self {
inner_secret: self.inner_secret.clone(),
masking_strategy: PhantomData,
}
}
| {
"crate": "masking",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 27325,
"total_crates": null
} |
fn_clm_masking_new_-2729277852852699987 | clm | function | // Repository: hyperswitch
// Crate: masking
// Purpose: PII protection and data masking
// Module: crates/masking/src/strong_secret
// Inherent implementation for StrongSecret<Secret, MaskingStrategy>
/// Take ownership of a secret value
pub fn new(secret: Secret) -> Self {
Self {
inner_secret: secret,
masking_strategy: PhantomData,
}
}
| {
"crate": "masking",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14463,
"total_crates": null
} |
fn_clm_masking_default_-2729277852852699987 | clm | function | // Repository: hyperswitch
// Crate: masking
// Purpose: PII protection and data masking
// Module: crates/masking/src/strong_secret
// Implementation of StrongSecret<Secret, MaskingStrategy> for Default
fn default() -> Self {
Secret::default().into()
}
| {
"crate": "masking",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 7707,
"total_crates": null
} |
fn_clm_masking_from_-2729277852852699987 | clm | function | // Repository: hyperswitch
// Crate: masking
// Purpose: PII protection and data masking
// Module: crates/masking/src/strong_secret
// Implementation of StrongSecret<Secret, MaskingStrategy> for From<Secret>
fn from(secret: Secret) -> Self {
Self::new(secret)
}
| {
"crate": "masking",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 2602,
"total_crates": null
} |
fn_clm_masking_eq_-2729277852852699987 | clm | function | // Repository: hyperswitch
// Crate: masking
// Purpose: PII protection and data masking
// Module: crates/masking/src/strong_secret
// Implementation of StrongSecret<Secret, MaskingStrategy> for PartialEq
fn eq(&self, other: &Self) -> bool {
StrongEq::strong_eq(self.peek(), other.peek())
}
| {
"crate": "masking",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 1664,
"total_crates": null
} |
fn_clm_masking_clone_3894462210123451612 | clm | function | // Repository: hyperswitch
// Crate: masking
// Purpose: PII protection and data masking
// Module: crates/masking/src/serde
// Implementation of PIISerializer for Clone
fn clone(&self) -> Self {
Self {
inner: JsonValueSerializer,
}
}
| {
"crate": "masking",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 27323,
"total_crates": null
} |
fn_clm_masking_deserialize_3894462210123451612 | clm | function | // Repository: hyperswitch
// Crate: masking
// Purpose: PII protection and data masking
// Module: crates/masking/src/serde
// Implementation of StrongSecret<T, I> for Deserialize<'de>
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
T::deserialize(deserializer).map(Self::new)
}
| {
"crate": "masking",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 138,
"total_crates": null
} |
fn_clm_masking_serialize_3894462210123451612 | clm | function | // Repository: hyperswitch
// Crate: masking
// Purpose: PII protection and data masking
// Module: crates/masking/src/serde
// Implementation of None for Serialize
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
erased_serde::serialize(self, serializer)
}
| {
"crate": "masking",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 85,
"total_crates": null
} |
fn_clm_masking_masked_serialize_3894462210123451612 | clm | function | // Repository: hyperswitch
// Crate: masking
// Purpose: PII protection and data masking
// Module: crates/masking/src/serde
// Implementation of T for ErasedMaskSerialize
fn masked_serialize(&self) -> Result<Value, serde_json::Error> {
masked_serialize(self)
}
| {
"crate": "masking",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 79,
"total_crates": null
} |
fn_clm_masking_serialize_str_3894462210123451612 | clm | function | // Repository: hyperswitch
// Crate: masking
// Purpose: PII protection and data masking
// Module: crates/masking/src/serde
// Implementation of PIISerializer for Serializer
fn serialize_str(self, value: &str) -> Result<Self::Ok, Self::Error> {
Ok(Value::String(value.to_owned()))
}
| {
"crate": "masking",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 30,
"total_crates": null
} |
fn_clm_masking_from_-1768448059029681441 | clm | function | // Repository: hyperswitch
// Crate: masking
// Purpose: PII protection and data masking
// Module: crates/masking/src/maskable
// Implementation of Maskable<String> for From<&str>
fn from(value: &str) -> Self {
Self::new_normal(value.to_string())
}
| {
"crate": "masking",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 2604,
"total_crates": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.