id stringlengths 11 116 | type stringclasses 1
value | granularity stringclasses 4
values | content stringlengths 16 477k | metadata dict |
|---|---|---|---|---|
fn_clm_drainer_start_drainer_-2632385815477408767 | clm | function | // Repository: hyperswitch
// Crate: drainer
// Purpose: Redis stream processing and database writing
// Module: crates/drainer/src/lib
pub async fn start_drainer(
stores: HashMap<id_type::TenantId, Arc<Store>>,
conf: DrainerSettings,
) -> errors::DrainerResult<()> {
let drainer_handler = handler::Handler::from_conf(conf, stores);
let (tx, rx) = mpsc::channel::<()>(1);
let signal = get_allowed_signals().change_context(errors::DrainerError::SignalError(
"Failed while getting allowed signals".to_string(),
))?;
let handle = signal.handle();
let task_handle =
tokio::spawn(common_utils::signals::signal_handler(signal, tx.clone()).in_current_span());
let handler_clone = drainer_handler.clone();
tokio::task::spawn(async move { handler_clone.shutdown_listener(rx).await });
drainer_handler.spawn_error_handlers(tx)?;
drainer_handler.spawn().await?;
handle.close();
let _ = task_handle
.await
.map_err(|err| logger::error!("Failed while joining signal handler: {:?}", err));
Ok(())
}
| {
"crate": "drainer",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 47,
"total_crates": null
} |
fn_clm_drainer_start_web_server_-2632385815477408767 | clm | function | // Repository: hyperswitch
// Crate: drainer
// Purpose: Redis stream processing and database writing
// Module: crates/drainer/src/lib
pub async fn start_web_server(
conf: Settings,
stores: HashMap<id_type::TenantId, Arc<Store>>,
) -> Result<Server, errors::DrainerError> {
let server = conf.server.clone();
let web_server = actix_web::HttpServer::new(move || {
actix_web::App::new().service(health_check::Health::server(conf.clone(), stores.clone()))
})
.bind((server.host.as_str(), server.port))?
.run();
let _ = web_server.handle();
Ok(web_server)
}
| {
"crate": "drainer",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 38,
"total_crates": null
} |
fn_clm_drainer_execute_query_2244440832628988976 | clm | function | // Repository: hyperswitch
// Crate: drainer
// Purpose: Redis stream processing and database writing
// Module: crates/drainer/src/query
// Implementation of kv::DBOperation for ExecuteQuery
async fn execute_query(
self,
store: &Arc<Store>,
pushed_at: i64,
) -> CustomResult<(), DatabaseError> {
let conn = pg_connection(&store.master_pool).await;
let operation = self.operation();
let table = self.table();
let tags = router_env::metric_attributes!(("operation", operation), ("table", table));
let (result, execution_time) =
Box::pin(common_utils::date_time::time_it(|| self.execute(&conn))).await;
push_drainer_delay(pushed_at, operation, table, tags);
metrics::QUERY_EXECUTION_TIME.record(execution_time, tags);
match result {
Ok(result) => {
logger::info!(operation = operation, table = table, ?result);
metrics::SUCCESSFUL_QUERY_EXECUTION.add(1, tags);
Ok(())
}
Err(err) => {
logger::error!(operation = operation, table = table, ?err);
metrics::ERRORS_WHILE_QUERY_EXECUTION.add(1, tags);
Err(err)
}
}
}
| {
"crate": "drainer",
"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_drainer_push_drainer_delay_2244440832628988976 | clm | function | // Repository: hyperswitch
// Crate: drainer
// Purpose: Redis stream processing and database writing
// Module: crates/drainer/src/query
fn push_drainer_delay(
pushed_at: i64,
operation: &str,
table: &str,
tags: &[router_env::opentelemetry::KeyValue],
) {
let drained_at = common_utils::date_time::now_unix_timestamp();
let delay = drained_at - pushed_at;
logger::debug!(operation, table, delay = format!("{delay} secs"));
match u64::try_from(delay) {
Ok(delay) => metrics::DRAINER_DELAY_SECONDS.record(delay, tags),
Err(error) => logger::error!(
pushed_at,
drained_at,
delay,
?error,
"Invalid drainer delay"
),
}
}
| {
"crate": "drainer",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 9,
"total_crates": null
} |
fn_clm_drainer_new_-586909321122191491 | clm | function | // Repository: hyperswitch
// Crate: drainer
// Purpose: Redis stream processing and database writing
// Module: crates/drainer/src/services
// Inherent implementation for Store
/// # Panics
///
/// Panics if there is a failure while obtaining the HashiCorp client using the provided configuration.
/// This panic indicates a critical failure in setting up external services, and the application cannot proceed without a valid HashiCorp client.
pub async fn new(config: &crate::Settings, test_transaction: bool, tenant: &Tenant) -> Self {
let redis_conn = crate::connection::redis_connection(config).await;
Self {
master_pool: diesel_make_pg_pool(
config.master_database.get_inner(),
test_transaction,
&tenant.schema,
)
.await,
redis_conn: Arc::new(RedisConnectionPool::clone(
&redis_conn,
&tenant.redis_key_prefix,
)),
config: StoreConfig {
drainer_stream_name: config.drainer.stream_name.clone(),
drainer_num_partitions: config.drainer.num_partitions,
use_legacy_version: config.redis.use_legacy_version,
},
request_id: None,
}
}
| {
"crate": "drainer",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 14475,
"total_crates": null
} |
fn_clm_drainer_log_and_return_error_response_-586909321122191491 | clm | function | // Repository: hyperswitch
// Crate: drainer
// Purpose: Redis stream processing and database writing
// Module: crates/drainer/src/services
pub fn log_and_return_error_response<T>(error: Report<T>) -> HttpResponse
where
T: error_stack::Context + ResponseError + Clone,
{
logger::error!(?error);
let body = serde_json::json!({
"message": error.to_string()
})
.to_string();
HttpResponse::InternalServerError()
.content_type(mime::APPLICATION_JSON)
.body(body)
}
| {
"crate": "drainer",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 306,
"total_crates": null
} |
fn_clm_drainer_http_response_json_-586909321122191491 | clm | function | // Repository: hyperswitch
// Crate: drainer
// Purpose: Redis stream processing and database writing
// Module: crates/drainer/src/services
pub fn http_response_json<T: body::MessageBody + 'static>(response: T) -> HttpResponse {
HttpResponse::Ok()
.content_type(mime::APPLICATION_JSON)
.body(response)
}
| {
"crate": "drainer",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 26,
"total_crates": null
} |
fn_clm_drainer_use_legacy_version_-586909321122191491 | clm | function | // Repository: hyperswitch
// Crate: drainer
// Purpose: Redis stream processing and database writing
// Module: crates/drainer/src/services
// Inherent implementation for Store
pub fn use_legacy_version(&self) -> bool {
self.config.use_legacy_version
}
| {
"crate": "drainer",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 24,
"total_crates": null
} |
fn_clm_drainer_from_3949756182577909628 | clm | function | // Repository: hyperswitch
// Crate: drainer
// Purpose: Redis stream processing and database writing
// Module: crates/drainer/src/errors
// Implementation of DrainerError for From<error_stack::Report<redis::errors::RedisError>>
fn from(err: error_stack::Report<redis::errors::RedisError>) -> Self {
Self::RedisError(err)
}
| {
"crate": "drainer",
"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_drainer_status_code_3949756182577909628 | clm | function | // Repository: hyperswitch
// Crate: drainer
// Purpose: Redis stream processing and database writing
// Module: crates/drainer/src/errors
// Implementation of HealthCheckError for actix_web::ResponseError
fn status_code(&self) -> reqwest::StatusCode {
use reqwest::StatusCode;
match self {
Self::DbError { .. } | Self::RedisError { .. } => StatusCode::INTERNAL_SERVER_ERROR,
}
}
| {
"crate": "drainer",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 26,
"total_crates": null
} |
fn_clm_drainer_main_-5840686286782209117 | clm | function | // Repository: hyperswitch
// Crate: drainer
// Purpose: Redis stream processing and database writing
// Module: crates/drainer/src/main
async fn main() -> DrainerResult<()> {
// Get configuration
let cmd_line = <settings::CmdLineConf as clap::Parser>::parse();
#[allow(clippy::expect_used)]
let conf = settings::Settings::with_config_path(cmd_line.config_path)
.expect("Unable to construct application configuration");
#[allow(clippy::expect_used)]
conf.validate()
.expect("Failed to validate drainer configuration");
let state = settings::AppState::new(conf.clone()).await;
let mut stores = HashMap::new();
for (tenant_name, tenant) in conf.multitenancy.get_tenants() {
let store = std::sync::Arc::new(services::Store::new(&state.conf, false, tenant).await);
stores.insert(tenant_name.clone(), store);
}
#[allow(clippy::print_stdout)] // The logger has not yet been initialized
#[cfg(feature = "vergen")]
{
println!("Starting drainer (Version: {})", router_env::git_tag!());
}
let _guard = router_env::setup(
&conf.log,
router_env::service_name!(),
[router_env::service_name!()],
);
#[allow(clippy::expect_used)]
let web_server = Box::pin(start_web_server(
state.conf.as_ref().clone(),
stores.clone(),
))
.await
.expect("Failed to create the server");
tokio::spawn(
async move {
let _ = web_server.await;
logger::error!("The health check probe stopped working!");
}
.in_current_span(),
);
logger::debug!(startup_config=?conf);
logger::info!("Drainer started [{:?}] [{:?}]", conf.drainer, conf.log);
start_drainer(stores.clone(), conf.drainer).await?;
Ok(())
}
| {
"crate": "drainer",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 42,
"total_crates": null
} |
fn_clm_drainer_from_-2871278182507632568 | clm | function | // Repository: hyperswitch
// Crate: drainer
// Purpose: Redis stream processing and database writing
// Module: crates/drainer/src/health_check
// Implementation of HealthCheckDBError for From<diesel::result::Error>
fn from(error: diesel::result::Error) -> Self {
match error {
diesel::result::Error::DatabaseError(_, _) => Self::DbError,
diesel::result::Error::RollbackErrorOnCommit { .. }
| diesel::result::Error::RollbackTransaction
| diesel::result::Error::AlreadyInTransaction
| diesel::result::Error::NotInTransaction
| diesel::result::Error::BrokenTransactionManager => Self::TransactionError,
_ => Self::UnknownError,
}
}
| {
"crate": "drainer",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 2600,
"total_crates": null
} |
fn_clm_drainer_server_-2871278182507632568 | clm | function | // Repository: hyperswitch
// Crate: drainer
// Purpose: Redis stream processing and database writing
// Module: crates/drainer/src/health_check
// Inherent implementation for Health
pub fn server(conf: Settings, stores: HashMap<id_type::TenantId, Arc<Store>>) -> Scope {
web::scope("health")
.app_data(web::Data::new(conf))
.app_data(web::Data::new(stores))
.service(web::resource("").route(web::get().to(health)))
.service(web::resource("/ready").route(web::get().to(deep_health_check)))
}
| {
"crate": "drainer",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 234,
"total_crates": null
} |
fn_clm_drainer_health_check_redis_-2871278182507632568 | clm | function | // Repository: hyperswitch
// Crate: drainer
// Purpose: Redis stream processing and database writing
// Module: crates/drainer/src/health_check
// Implementation of Store for HealthCheckInterface
async fn health_check_redis(
&self,
_conf: &Settings,
) -> CustomResult<(), HealthCheckRedisError> {
let redis_conn = self.redis_conn.clone();
redis_conn
.serialize_and_set_key_with_expiry(&"test_key".into(), "test_value", 30)
.await
.change_context(HealthCheckRedisError::SetFailed)?;
logger::debug!("Redis set_key was successful");
redis_conn
.get_key::<()>(&"test_key".into())
.await
.change_context(HealthCheckRedisError::GetFailed)?;
logger::debug!("Redis get_key was successful");
redis_conn
.delete_key(&"test_key".into())
.await
.change_context(HealthCheckRedisError::DeleteFailed)?;
logger::debug!("Redis delete_key was successful");
redis_conn
.stream_append_entry(
&TEST_STREAM_NAME.into(),
&redis_interface::RedisEntryId::AutoGeneratedID,
TEST_STREAM_DATA.to_vec(),
)
.await
.change_context(HealthCheckRedisError::StreamAppendFailed)?;
logger::debug!("Stream append succeeded");
let output = redis_conn
.stream_read_entries(TEST_STREAM_NAME, "0-0", Some(10))
.await
.change_context(HealthCheckRedisError::StreamReadFailed)?;
logger::debug!("Stream read succeeded");
let (_, id_to_trim) = output
.get(&redis_conn.add_prefix(TEST_STREAM_NAME))
.and_then(|entries| {
entries
.last()
.map(|last_entry| (entries, last_entry.0.clone()))
})
.ok_or(error_stack::report!(
HealthCheckRedisError::StreamReadFailed
))?;
logger::debug!("Stream parse succeeded");
redis_conn
.stream_trim_entries(
&TEST_STREAM_NAME.into(),
(
redis_interface::StreamCapKind::MinID,
redis_interface::StreamCapTrim::Exact,
id_to_trim,
),
)
.await
.change_context(HealthCheckRedisError::StreamTrimFailed)?;
logger::debug!("Stream trim succeeded");
Ok(())
}
| {
"crate": "drainer",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 67,
"total_crates": null
} |
fn_clm_drainer_deep_health_check_-2871278182507632568 | clm | function | // Repository: hyperswitch
// Crate: drainer
// Purpose: Redis stream processing and database writing
// Module: crates/drainer/src/health_check
pub async fn deep_health_check(
conf: web::Data<Settings>,
stores: web::Data<HashMap<String, Arc<Store>>>,
) -> impl actix_web::Responder {
let mut deep_health_res = HashMap::new();
for (tenant, store) in stores.iter() {
logger::info!("Tenant: {:?}", tenant);
let response = match deep_health_check_func(conf.clone(), store).await {
Ok(response) => serde_json::to_string(&response)
.map_err(|err| {
logger::error!(serialization_error=?err);
})
.unwrap_or_default(),
Err(err) => return log_and_return_error_response(err),
};
deep_health_res.insert(tenant.clone(), response);
}
services::http_response_json(
serde_json::to_string(&deep_health_res)
.map_err(|err| {
logger::error!(serialization_error=?err);
})
.unwrap_or_default(),
)
}
| {
"crate": "drainer",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 59,
"total_crates": null
} |
fn_clm_drainer_health_check_db_-2871278182507632568 | clm | function | // Repository: hyperswitch
// Crate: drainer
// Purpose: Redis stream processing and database writing
// Module: crates/drainer/src/health_check
// Implementation of Store for HealthCheckInterface
async fn health_check_db(&self) -> CustomResult<(), HealthCheckDBError> {
let conn = pg_connection(&self.master_pool).await;
conn
.transaction_async(|conn| {
Box::pin(async move {
let query =
diesel::select(diesel::dsl::sql::<diesel::sql_types::Integer>("1 + 1"));
let _x: i32 = query.get_result_async(&conn).await.map_err(|err| {
logger::error!(read_err=?err,"Error while reading element in the database");
HealthCheckDBError::DbReadError
})?;
logger::debug!("Database read was successful");
let config = ConfigNew {
key: "test_key".to_string(),
config: "test_value".to_string(),
};
config.insert(&conn).await.map_err(|err| {
logger::error!(write_err=?err,"Error while writing to database");
HealthCheckDBError::DbWriteError
})?;
logger::debug!("Database write was successful");
Config::delete_by_key(&conn, "test_key").await.map_err(|err| {
logger::error!(delete_err=?err,"Error while deleting element in the database");
HealthCheckDBError::DbDeleteError
})?;
logger::debug!("Database delete was successful");
Ok::<_, HealthCheckDBError>(())
})
})
.await?;
Ok(())
}
| {
"crate": "drainer",
"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_drainer_convert_to_raw_secret_-7014516517257123265 | clm | function | // Repository: hyperswitch
// Crate: drainer
// Purpose: Redis stream processing and database writing
// Module: crates/drainer/src/secrets_transformers
// Implementation of Database for SecretsHandler
async fn convert_to_raw_secret(
value: SecretStateContainer<Self, SecuredSecret>,
secret_management_client: &dyn SecretManagementInterface,
) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {
let secured_db_config = value.get_inner();
let raw_db_password = secret_management_client
.get_secret(secured_db_config.password.clone())
.await?;
Ok(value.transition_state(|db| Self {
password: raw_db_password,
..db
}))
}
| {
"crate": "drainer",
"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_drainer_fetch_raw_secrets_-7014516517257123265 | clm | function | // Repository: hyperswitch
// Crate: drainer
// Purpose: Redis stream processing and database writing
// Module: crates/drainer/src/secrets_transformers
/// # Panics
///
/// Will panic even if fetching raw secret fails for at least one config value
pub async fn fetch_raw_secrets(
conf: Settings<SecuredSecret>,
secret_management_client: &dyn SecretManagementInterface,
) -> Settings<RawSecret> {
#[allow(clippy::expect_used)]
let database = Database::convert_to_raw_secret(conf.master_database, secret_management_client)
.await
.expect("Failed to decrypt database password");
Settings {
server: conf.server,
master_database: database,
redis: conf.redis,
log: conf.log,
drainer: conf.drainer,
encryption_management: conf.encryption_management,
secrets_management: conf.secrets_management,
multitenancy: conf.multitenancy,
}
}
| {
"crate": "drainer",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 15,
"total_crates": null
} |
fn_clm_drainer_new_-3990976048695871595 | clm | function | // Repository: hyperswitch
// Crate: drainer
// Purpose: Redis stream processing and database writing
// Module: crates/drainer/src/settings
// Implementation of None for Settings<SecuredSecret>
pub fn new() -> Result<Self, errors::DrainerError> {
Self::with_config_path(None)
}
| {
"crate": "drainer",
"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_drainer_default_-3990976048695871595 | clm | function | // Repository: hyperswitch
// Crate: drainer
// Purpose: Redis stream processing and database writing
// Module: crates/drainer/src/settings
// Implementation of Server for Default
fn default() -> Self {
Self {
host: "127.0.0.1".to_string(),
port: 8080,
workers: 1,
}
}
| {
"crate": "drainer",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 7705,
"total_crates": null
} |
fn_clm_drainer_validate_-3990976048695871595 | clm | function | // Repository: hyperswitch
// Crate: drainer
// Purpose: Redis stream processing and database writing
// Module: crates/drainer/src/settings
// Implementation of None for Settings<SecuredSecret>
pub fn validate(&self) -> Result<(), errors::DrainerError> {
self.server.validate()?;
self.master_database.get_inner().validate()?;
// The logger may not yet be initialized when validating the application configuration
#[allow(clippy::print_stderr)]
self.redis.validate().map_err(|error| {
eprintln!("{error}");
errors::DrainerError::ConfigParsingError("invalid Redis configuration".into())
})?;
self.drainer.validate()?;
// The logger may not yet be initialized when validating the application configuration
#[allow(clippy::print_stderr)]
self.secrets_management.validate().map_err(|error| {
eprintln!("{error}");
errors::DrainerError::ConfigParsingError(
"invalid secrets management configuration".into(),
)
})?;
// The logger may not yet be initialized when validating the application configuration
#[allow(clippy::print_stderr)]
self.encryption_management.validate().map_err(|error| {
eprintln!("{error}");
errors::DrainerError::ConfigParsingError(
"invalid encryption management configuration".into(),
)
})?;
Ok(())
}
| {
"crate": "drainer",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 251,
"total_crates": null
} |
fn_clm_drainer_deserialize_-3990976048695871595 | clm | function | // Repository: hyperswitch
// Crate: drainer
// Purpose: Redis stream processing and database writing
// Module: crates/drainer/src/settings
// Implementation of TenantConfig for Deserialize<'de>
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
#[derive(Deserialize)]
struct Inner {
base_url: String,
schema: String,
accounts_schema: String,
redis_key_prefix: String,
clickhouse_database: String,
}
let hashmap = <HashMap<id_type::TenantId, Inner>>::deserialize(deserializer)?;
Ok(Self(
hashmap
.into_iter()
.map(|(key, value)| {
(
key.clone(),
Tenant {
tenant_id: key,
base_url: value.base_url,
schema: value.schema,
accounts_schema: value.accounts_schema,
redis_key_prefix: value.redis_key_prefix,
clickhouse_database: value.clickhouse_database,
},
)
})
.collect(),
))
}
| {
"crate": "drainer",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 146,
"total_crates": null
} |
fn_clm_drainer_with_config_path_-3990976048695871595 | clm | function | // Repository: hyperswitch
// Crate: drainer
// Purpose: Redis stream processing and database writing
// Module: crates/drainer/src/settings
// Implementation of None for Settings<SecuredSecret>
pub fn with_config_path(config_path: Option<PathBuf>) -> Result<Self, errors::DrainerError> {
// Configuration values are picked up in the following priority order (1 being least
// priority):
// 1. Defaults from the implementation of the `Default` trait.
// 2. Values from config file. The config file accessed depends on the environment
// specified by the `RUN_ENV` environment variable. `RUN_ENV` can be one of
// `development`, `sandbox` or `production`. If nothing is specified for `RUN_ENV`,
// `/config/development.toml` file is read.
// 3. Environment variables prefixed with `DRAINER` and each level separated by double
// underscores.
//
// Values in config file override the defaults in `Default` trait, and the values set using
// environment variables override both the defaults and the config file values.
let environment = env::which();
let config_path = router_env::Config::config_path(&environment.to_string(), config_path);
let config = router_env::Config::builder(&environment.to_string())?
.add_source(File::from(config_path).required(false))
.add_source(
Environment::with_prefix("DRAINER")
.try_parsing(true)
.separator("__")
.list_separator(",")
.with_list_parse_key("redis.cluster_urls"),
)
.build()?;
// The logger may not yet be initialized when constructing the application configuration
#[allow(clippy::print_stderr)]
serde_path_to_error::deserialize(config).map_err(|error| {
logger::error!(%error, "Unable to deserialize application configuration");
eprintln!("Unable to deserialize application configuration: {error}");
errors::DrainerError::from(error.into_inner())
})
}
| {
"crate": "drainer",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 71,
"total_crates": null
} |
fn_clm_drainer_diesel_make_pg_pool_8153045751546000059 | clm | function | // Repository: hyperswitch
// Crate: drainer
// Purpose: Redis stream processing and database writing
// Module: crates/drainer/src/connection
pub async fn diesel_make_pg_pool(
database: &Database,
_test_transaction: bool,
schema: &str,
) -> PgPool {
let database_url = database.get_database_url(schema);
let manager = async_bb8_diesel::ConnectionManager::<PgConnection>::new(database_url);
let pool = bb8::Pool::builder()
.max_size(database.pool_size)
.connection_timeout(std::time::Duration::from_secs(database.connection_timeout));
pool.build(manager)
.await
.expect("Failed to create PostgreSQL connection pool")
}
| {
"crate": "drainer",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 39,
"total_crates": null
} |
fn_clm_drainer_pg_connection_8153045751546000059 | clm | function | // Repository: hyperswitch
// Crate: drainer
// Purpose: Redis stream processing and database writing
// Module: crates/drainer/src/connection
pub async fn pg_connection(
pool: &PgPool,
) -> PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>> {
pool.get()
.await
.expect("Couldn't retrieve PostgreSQL connection")
}
| {
"crate": "drainer",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 18,
"total_crates": null
} |
fn_clm_drainer_redis_connection_8153045751546000059 | clm | function | // Repository: hyperswitch
// Crate: drainer
// Purpose: Redis stream processing and database writing
// Module: crates/drainer/src/connection
pub async fn redis_connection(conf: &Settings) -> redis_interface::RedisConnectionPool {
redis_interface::RedisConnectionPool::new(&conf.redis)
.await
.expect("Failed to create Redis connection Pool")
}
| {
"crate": "drainer",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 15,
"total_crates": null
} |
fn_clm_drainer_deserialize_i64_-6508630305979915794 | clm | function | // Repository: hyperswitch
// Crate: drainer
// Purpose: Redis stream processing and database writing
// Module: crates/drainer/src/utils
pub(crate) fn deserialize_i64<'de, D>(deserializer: D) -> Result<i64, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = serde_json::Value::deserialize(deserializer)?;
match s {
serde_json::Value::String(str_val) => str_val.parse().map_err(serde::de::Error::custom),
serde_json::Value::Number(num_val) => match num_val.as_i64() {
Some(val) => Ok(val),
None => Err(serde::de::Error::custom(format!(
"could not convert {num_val:?} to i64"
))),
},
other => Err(serde::de::Error::custom(format!(
"unexpected data format - expected string or number, got: {other:?}"
))),
}
}
| {
"crate": "drainer",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 22,
"total_crates": null
} |
fn_clm_drainer_increment_stream_index_-6508630305979915794 | clm | function | // Repository: hyperswitch
// Crate: drainer
// Purpose: Redis stream processing and database writing
// Module: crates/drainer/src/utils
pub async fn increment_stream_index(
(index, jobs_picked): (u8, Arc<atomic::AtomicU8>),
total_streams: u8,
) -> u8 {
if index == total_streams - 1 {
match jobs_picked.load(atomic::Ordering::SeqCst) {
0 => metrics::CYCLES_COMPLETED_UNSUCCESSFULLY.add(1, &[]),
_ => metrics::CYCLES_COMPLETED_SUCCESSFULLY.add(1, &[]),
}
jobs_picked.store(0, atomic::Ordering::SeqCst);
0
} else {
index + 1
}
}
| {
"crate": "drainer",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 21,
"total_crates": null
} |
fn_clm_drainer_deserialize_db_op_-6508630305979915794 | clm | function | // Repository: hyperswitch
// Crate: drainer
// Purpose: Redis stream processing and database writing
// Module: crates/drainer/src/utils
pub(crate) fn deserialize_db_op<'de, D>(deserializer: D) -> Result<kv::DBOperation, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = serde_json::Value::deserialize(deserializer)?;
match s {
serde_json::Value::String(str_val) => {
serde_json::from_str(&str_val).map_err(serde::de::Error::custom)
}
other => Err(serde::de::Error::custom(format!(
"unexpected data format - expected string got: {other:?}"
))),
}
}
| {
"crate": "drainer",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 18,
"total_crates": null
} |
fn_clm_drainer_parse_stream_entries_-6508630305979915794 | clm | function | // Repository: hyperswitch
// Crate: drainer
// Purpose: Redis stream processing and database writing
// Module: crates/drainer/src/utils
pub fn parse_stream_entries<'a>(
read_result: &'a StreamReadResult,
stream_name: &str,
) -> errors::DrainerResult<&'a StreamEntries> {
read_result.get(stream_name).ok_or_else(|| {
report!(errors::DrainerError::RedisError(report!(
redis::errors::RedisError::NotFound
)))
})
}
| {
"crate": "drainer",
"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_router_derive_setter_-5482677868486952959 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/lib
pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = syn::parse_macro_input!(input as syn::DeriveInput);
let ident = &input.ident;
// All the fields in the parent struct
let fields = if let syn::Data::Struct(syn::DataStruct {
fields: syn::Fields::Named(syn::FieldsNamed { ref named, .. }),
..
}) = input.data
{
named
} else {
// FIXME: Use `compile_error!()` instead
panic!("You can't use this proc-macro on structs without fields");
};
// Methods in the build struct like if the struct is
// Struct i {n: u32}
// this will be
// pub fn set_n(&mut self,n: u32)
let build_methods = fields.iter().map(|f| {
let name = f.ident.as_ref().unwrap();
let method_name = format!("set_{name}");
let method_ident = syn::Ident::new(&method_name, name.span());
let ty = &f.ty;
if check_if_auth_based_attr_is_present(f, "auth_based") {
quote::quote! {
pub fn #method_ident(&mut self, val:#ty, is_merchant_flow: bool)->&mut Self{
if is_merchant_flow {
self.#name = val;
}
self
}
}
} else {
quote::quote! {
pub fn #method_ident(&mut self, val:#ty)->&mut Self{
self.#name = val;
self
}
}
}
});
let output = quote::quote! {
#[automatically_derived]
impl #ident {
#(#build_methods)*
}
};
output.into()
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 24,
"total_crates": null
} |
fn_clm_router_derive_validate_config_-5482677868486952959 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/lib
pub fn validate_config(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = syn::parse_macro_input!(input as syn::DeriveInput);
macros::misc::validate_config(input)
.unwrap_or_else(|error| error.into_compile_error())
.into()
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 21,
"total_crates": null
} |
fn_clm_router_derive_try_get_enum_variant_-5482677868486952959 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/lib
pub fn try_get_enum_variant(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = syn::parse_macro_input!(input as syn::DeriveInput);
macros::try_get_enum::try_get_enum_variant(input)
.unwrap_or_else(|error| error.into_compile_error())
.into()
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 21,
"total_crates": null
} |
fn_clm_router_derive_debug_as_display_derive_-5482677868486952959 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/lib
pub fn debug_as_display_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let ast = syn::parse_macro_input!(input as syn::DeriveInput);
let tokens =
macros::debug_as_display_inner(&ast).unwrap_or_else(|error| error.to_compile_error());
tokens.into()
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 18,
"total_crates": null
} |
fn_clm_router_derive_diesel_enum_derive_-5482677868486952959 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/lib
pub fn diesel_enum_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let ast = syn::parse_macro_input!(input as syn::DeriveInput);
let tokens =
macros::diesel_enum_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error());
tokens.into()
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 18,
"total_crates": null
} |
fn_clm_router_derive_debug_as_display_inner_7705114799558246236 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros
pub(crate) fn debug_as_display_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
let name = &ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
Ok(quote! {
#[automatically_derived]
impl #impl_generics ::core::fmt::Display for #name #ty_generics #where_clause {
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::result::Result<(), ::core::fmt::Error> {
f.write_str(&format!("{:?}", self))
}
}
})
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 15,
"total_crates": null
} |
fn_clm_router_derive_parse_5549632855035762791 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/operation
// Implementation of OperationsEnumMeta for Parse
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let lookahead = input.lookahead1();
if lookahead.peek(operations_keyword::operations) {
let keyword = input.parse()?;
input.parse::<syn::Token![=]>()?;
let value = get_conversions(input)?;
Ok(Self::Operations { keyword, value })
} else if lookahead.peek(operations_keyword::flow) {
let keyword = input.parse()?;
input.parse::<syn::Token![=]>()?;
let value = get_derives(input)?;
Ok(Self::Flow { keyword, value })
} else {
Err(lookahead.error())
}
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 462,
"total_crates": null
} |
fn_clm_router_derive_get_req_type_5549632855035762791 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/operation
// Inherent implementation for Conversion
fn get_req_type(ident: Derives) -> syn::Ident {
match ident {
Derives::Authorize => syn::Ident::new("PaymentsRequest", Span::call_site()),
Derives::AuthorizeData => syn::Ident::new("PaymentsAuthorizeData", Span::call_site()),
Derives::Sync => syn::Ident::new("PaymentsRetrieveRequest", Span::call_site()),
Derives::SyncData => syn::Ident::new("PaymentsSyncData", Span::call_site()),
Derives::Cancel => syn::Ident::new("PaymentsCancelRequest", Span::call_site()),
Derives::CancelData => syn::Ident::new("PaymentsCancelData", Span::call_site()),
Derives::ApproveData => syn::Ident::new("PaymentsApproveData", Span::call_site()),
Derives::Reject => syn::Ident::new("PaymentsRejectRequest", Span::call_site()),
Derives::RejectData => syn::Ident::new("PaymentsRejectData", Span::call_site()),
Derives::Capture => syn::Ident::new("PaymentsCaptureRequest", Span::call_site()),
Derives::CaptureData => syn::Ident::new("PaymentsCaptureData", Span::call_site()),
Derives::CompleteAuthorizeData => {
syn::Ident::new("CompleteAuthorizeData", Span::call_site())
}
Derives::Start => syn::Ident::new("PaymentsStartRequest", Span::call_site()),
Derives::Verify => syn::Ident::new("VerifyRequest", Span::call_site()),
Derives::SetupMandateData => {
syn::Ident::new("SetupMandateRequestData", Span::call_site())
}
Derives::Session => syn::Ident::new("PaymentsSessionRequest", Span::call_site()),
Derives::SessionData => syn::Ident::new("PaymentsSessionData", Span::call_site()),
Derives::IncrementalAuthorization => {
syn::Ident::new("PaymentsIncrementalAuthorizationRequest", Span::call_site())
}
Derives::IncrementalAuthorizationData => {
syn::Ident::new("PaymentsIncrementalAuthorizationData", Span::call_site())
}
Derives::SdkSessionUpdate => {
syn::Ident::new("PaymentsDynamicTaxCalculationRequest", Span::call_site())
}
Derives::SdkSessionUpdateData => {
syn::Ident::new("SdkPaymentsSessionUpdateData", Span::call_site())
}
Derives::PostSessionTokens => {
syn::Ident::new("PaymentsPostSessionTokensRequest", Span::call_site())
}
Derives::PostSessionTokensData => {
syn::Ident::new("PaymentsPostSessionTokensData", Span::call_site())
}
Derives::UpdateMetadata => {
syn::Ident::new("PaymentsUpdateMetadataRequest", Span::call_site())
}
Derives::UpdateMetadataData => {
syn::Ident::new("PaymentsUpdateMetadataData", Span::call_site())
}
Derives::CancelPostCapture => {
syn::Ident::new("PaymentsCancelPostCaptureRequest", Span::call_site())
}
Derives::CancelPostCaptureData => {
syn::Ident::new("PaymentsCancelPostCaptureData", Span::call_site())
}
Derives::ExtendAuthorization => {
syn::Ident::new("PaymentsExtendAuthorizationRequest", Span::call_site())
}
Derives::ExtendAuthorizationData => {
syn::Ident::new("PaymentsExtendAuthorizationData", Span::call_site())
}
}
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 136,
"total_crates": null
} |
fn_clm_router_derive_get_metadata_5549632855035762791 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/operation
// Implementation of DeriveInput for OperationsDeriveInputExt
fn get_metadata(&self) -> syn::Result<Vec<OperationsEnumMeta>> {
helpers::get_metadata_inner("operation", &self.attrs)
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 103,
"total_crates": null
} |
fn_clm_router_derive_operation_derive_inner_5549632855035762791 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/operation
pub fn operation_derive_inner(input: DeriveInput) -> syn::Result<proc_macro::TokenStream> {
let struct_name = &input.ident;
let operations_meta = input.get_metadata()?;
let operation_properties = get_operation_properties(operations_meta)?;
let current_crate = syn::Ident::new("crate", Span::call_site());
let trait_derive = operation_properties
.clone()
.flows
.into_iter()
.map(|derive| {
let fns = operation_properties
.operations
.iter()
.map(|conversion| conversion.to_function(derive));
derive.to_operation(fns, struct_name)
})
.collect::<Vec<_>>();
let ref_trait_derive = operation_properties
.flows
.into_iter()
.map(|derive| {
let fns = operation_properties
.operations
.iter()
.map(|conversion| conversion.to_ref_function(derive));
derive.to_ref_operation(fns, struct_name)
})
.collect::<Vec<_>>();
let trait_derive = quote! {
#(#ref_trait_derive)* #(#trait_derive)*
};
let output = quote! {
const _: () = {
use #current_crate::core::errors::RouterResult;
use #current_crate::core::payments::{PaymentData,operations::{
ValidateRequest,
PostUpdateTracker,
GetTracker,
UpdateTracker,
}};
use #current_crate::types::{
SetupMandateRequestData,
PaymentsSyncData,
PaymentsCaptureData,
PaymentsCancelData,
PaymentsApproveData,
PaymentsRejectData,
PaymentsAuthorizeData,
PaymentsSessionData,
CompleteAuthorizeData,
PaymentsIncrementalAuthorizationData,
SdkPaymentsSessionUpdateData,
PaymentsPostSessionTokensData,
PaymentsUpdateMetadataData,
PaymentsCancelPostCaptureData,
PaymentsExtendAuthorizationData,
api::{
PaymentsCaptureRequest,
PaymentsCancelRequest,
PaymentsApproveRequest,
PaymentsRejectRequest,
PaymentsRetrieveRequest,
PaymentsRequest,
PaymentsStartRequest,
PaymentsSessionRequest,
VerifyRequest,
PaymentsDynamicTaxCalculationRequest,
PaymentsIncrementalAuthorizationRequest,
PaymentsPostSessionTokensRequest,
PaymentsUpdateMetadataRequest,
PaymentsCancelPostCaptureRequest,
PaymentsExtendAuthorizationRequest,
}
};
#trait_derive
};
};
Ok(proc_macro::TokenStream::from(output))
}
| {
"crate": "router_derive",
"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_router_derive_to_tokens_5549632855035762791 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/operation
// Implementation of OperationsEnumMeta for ToTokens
fn to_tokens(&self, tokens: &mut TokenStream) {
match self {
Self::Operations { keyword, .. } => keyword.to_tokens(tokens),
Self::Flow { keyword, .. } => keyword.to_tokens(tokens),
}
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 48,
"total_crates": null
} |
fn_clm_router_derive_implement_serialize_-8887927557055227125 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/api_error
fn implement_serialize(
enum_name: &Ident,
generics: (&ImplGenerics<'_>, &TypeGenerics<'_>, Option<&WhereClause>),
type_properties: &ErrorTypeProperties,
variants_properties_map: &HashMap<&Variant, ErrorVariantProperties>,
) -> TokenStream {
let (impl_generics, ty_generics, where_clause) = generics;
let mut arms = Vec::new();
for (&variant, properties) in variants_properties_map.iter() {
let ident = &variant.ident;
let params = match variant.fields {
Fields::Unit => quote! {},
Fields::Unnamed(..) => quote! { (..) },
Fields::Named(ref fields) => {
let fields = fields
.named
.iter()
.map(|f| {
// Safety: Named fields are guaranteed to have an identifier.
#[allow(clippy::unwrap_used)]
f.ident.as_ref().unwrap()
})
.collect::<Punctuated<&Ident, Comma>>();
quote! { {#fields} }
}
};
// Safety: Missing attributes are already checked before this function is called.
#[allow(clippy::unwrap_used)]
let error_message = properties.message.as_ref().unwrap();
let msg_unused_fields =
get_unused_fields(&variant.fields, &error_message.value(), &properties.ignore);
// Safety: Missing attributes are already checked before this function is called.
#[allow(clippy::unwrap_used)]
let error_type_enum = type_properties.error_type_enum.as_ref().unwrap();
let response_definition = if msg_unused_fields.is_empty() {
quote! {
#[derive(Clone, Debug, serde::Serialize)]
struct ErrorResponse {
#[serde(rename = "type")]
error_type: #error_type_enum,
code: String,
message: String,
}
}
} else {
let mut extra_fields = Vec::new();
for field in &msg_unused_fields {
let vis = &field.vis;
// Safety: `msq_unused_fields` is expected to contain named fields only.
#[allow(clippy::unwrap_used)]
let ident = &field.ident.as_ref().unwrap();
let ty = &field.ty;
extra_fields.push(quote! { #vis #ident: #ty });
}
quote! {
#[derive(Clone, Debug, serde::Serialize)]
struct ErrorResponse #ty_generics #where_clause {
#[serde(rename = "type")]
error_type: #error_type_enum,
code: String,
message: String,
#(#extra_fields),*
}
}
};
// Safety: Missing attributes are already checked before this function is called.
#[allow(clippy::unwrap_used)]
let error_type = properties.error_type.as_ref().unwrap();
// Safety: Missing attributes are already checked before this function is called.
#[allow(clippy::unwrap_used)]
let code = properties.code.as_ref().unwrap();
// Safety: Missing attributes are already checked before this function is called.
#[allow(clippy::unwrap_used)]
let message = properties.message.as_ref().unwrap();
let extra_fields = msg_unused_fields
.iter()
.map(|field| {
// Safety: `extra_fields` is expected to contain named fields only.
#[allow(clippy::unwrap_used)]
let field_name = field.ident.as_ref().unwrap();
quote! { #field_name: #field_name.to_owned() }
})
.collect::<Vec<TokenStream>>();
arms.push(quote! {
#enum_name::#ident #params => {
#response_definition
let response = ErrorResponse {
error_type: #error_type,
code: #code.to_string(),
message: format!(#message),
#(#extra_fields),*
};
response.serialize(serializer)
}
});
}
quote! {
#[automatically_derived]
impl #impl_generics serde::Serialize for #enum_name #ty_generics #where_clause {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match self {
#(#arms),*
}
}
}
}
}
| {
"crate": "router_derive",
"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_router_derive_api_error_derive_inner_-8887927557055227125 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/api_error
pub(crate) fn api_error_derive_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
let name = &ast.ident;
let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
let variants = match &ast.data {
Data::Enum(e) => &e.variants,
_ => return Err(non_enum_error()),
};
let type_properties = ast.get_type_properties()?;
let mut variants_properties_map = HashMap::new();
for variant in variants {
let variant_properties = variant.get_variant_properties()?;
check_missing_attributes(variant, &variant_properties)?;
variants_properties_map.insert(variant, variant_properties);
}
let error_type_fn = implement_error_type(name, &type_properties, &variants_properties_map);
let error_code_fn = implement_error_code(name, &variants_properties_map);
let error_message_fn = implement_error_message(name, &variants_properties_map);
let serialize_impl = implement_serialize(
name,
(&impl_generics, &ty_generics, where_clause),
&type_properties,
&variants_properties_map,
);
Ok(quote! {
#[automatically_derived]
impl #impl_generics std::error::Error for #name #ty_generics #where_clause {}
#[automatically_derived]
impl #impl_generics #name #ty_generics #where_clause {
#error_type_fn
#error_code_fn
#error_message_fn
}
#serialize_impl
})
}
| {
"crate": "router_derive",
"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_router_derive_implement_error_message_-8887927557055227125 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/api_error
fn implement_error_message(
enum_name: &Ident,
variants_properties_map: &HashMap<&Variant, ErrorVariantProperties>,
) -> TokenStream {
let mut arms = Vec::new();
for (&variant, properties) in variants_properties_map.iter() {
let ident = &variant.ident;
let params = match variant.fields {
Fields::Unit => quote! {},
Fields::Unnamed(..) => quote! { (..) },
Fields::Named(ref fields) => {
let fields = fields
.named
.iter()
.map(|f| {
// Safety: Named fields are guaranteed to have an identifier.
#[allow(clippy::unwrap_used)]
f.ident.as_ref().unwrap()
})
.collect::<Punctuated<&Ident, Comma>>();
quote! { {#fields} }
}
};
// Safety: Missing attributes are already checked before this function is called.
#[allow(clippy::unwrap_used)]
let error_message = properties.message.as_ref().unwrap();
arms.push(quote! { #enum_name::#ident #params => format!(#error_message) });
}
quote! {
pub fn error_message(&self) -> String {
match self {
#(#arms),*
}
}
}
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 17,
"total_crates": null
} |
fn_clm_router_derive_implement_error_type_-8887927557055227125 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/api_error
fn implement_error_type(
enum_name: &Ident,
type_properties: &ErrorTypeProperties,
variants_properties_map: &HashMap<&Variant, ErrorVariantProperties>,
) -> TokenStream {
let mut arms = Vec::new();
for (&variant, properties) in variants_properties_map.iter() {
let ident = &variant.ident;
let params = match variant.fields {
Fields::Unit => quote! {},
Fields::Unnamed(..) => quote! { (..) },
Fields::Named(..) => quote! { {..} },
};
// Safety: Missing attributes are already checked before this function is called.
#[allow(clippy::unwrap_used)]
let error_type = properties.error_type.as_ref().unwrap();
arms.push(quote! { #enum_name::#ident #params => #error_type });
}
// Safety: Missing attributes are already checked before this function is called.
#[allow(clippy::unwrap_used)]
let error_type_enum = type_properties.error_type_enum.as_ref().unwrap();
quote! {
pub fn error_type(&self) -> #error_type_enum {
match self {
#(#arms),*
}
}
}
}
| {
"crate": "router_derive",
"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_router_derive_implement_error_code_-8887927557055227125 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/api_error
fn implement_error_code(
enum_name: &Ident,
variants_properties_map: &HashMap<&Variant, ErrorVariantProperties>,
) -> TokenStream {
let mut arms = Vec::new();
for (&variant, properties) in variants_properties_map.iter() {
let ident = &variant.ident;
let params = match variant.fields {
Fields::Unit => quote! {},
Fields::Unnamed(..) => quote! { (..) },
Fields::Named(..) => quote! { {..} },
};
// Safety: Missing attributes are already checked before this function is called.
#[allow(clippy::unwrap_used)]
let error_code = properties.code.as_ref().unwrap();
arms.push(quote! { #enum_name::#ident #params => #error_code.to_string() });
}
quote! {
pub fn error_code(&self) -> String {
match self {
#(#arms),*
}
}
}
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 11,
"total_crates": null
} |
fn_clm_router_derive_parse_-5359276554233412005 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/try_get_enum
// Implementation of TryGetEnumMeta for Parse
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let error_type = input.parse()?;
_ = input.parse::<syn::Token![::]>()?;
let variant = input.parse()?;
Ok(Self {
error_type,
variant,
})
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 450,
"total_crates": null
} |
fn_clm_router_derive_get_metadata_-5359276554233412005 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/try_get_enum
// Implementation of syn::DeriveInput for TryGetDeriveInputExt
fn get_metadata(&self) -> syn::Result<Vec<TryGetEnumMeta>> {
super::helpers::get_metadata_inner("error", &self.attrs)
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 103,
"total_crates": null
} |
fn_clm_router_derive_try_get_enum_variant_-5359276554233412005 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/try_get_enum
/// Try and get the variants for an enum
pub fn try_get_enum_variant(
input: syn::DeriveInput,
) -> Result<proc_macro2::TokenStream, syn::Error> {
let name = &input.ident;
let parsed_error_type = input.get_metadata()?;
let (error_type, error_variant) = parsed_error_type
.first()
.ok_or(syn::Error::new(
Span::call_site(),
"One error should be specified",
))
.map(|error_struct| (&error_struct.error_type, &error_struct.variant))?;
let (impl_generics, generics, where_clause) = input.generics.split_for_impl();
let variants = get_enum_variants(&input.data)?;
let try_into_fns = variants.iter().map(|variant| {
let variant_name = &variant.ident;
let variant_field = get_enum_variant_field(variant)?;
let variant_types = variant_field.iter().map(|f|f.ty.clone());
let try_into_fn = syn::Ident::new(
&format!("try_into_{}", variant_name.to_string().to_lowercase()),
Span::call_site(),
);
Ok(quote::quote! {
pub fn #try_into_fn(self)->Result<(#(#variant_types),*),error_stack::Report<#error_type>> {
match self {
Self::#variant_name(inner) => Ok(inner),
_=> Err(error_stack::report!(#error_type::#error_variant)),
}
}
})
}).collect::<Result<Vec<proc_macro2::TokenStream>,syn::Error>>()?;
let expanded = quote::quote! {
impl #impl_generics #name #generics #where_clause {
#(#try_into_fns)*
}
};
Ok(expanded)
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 45,
"total_crates": null
} |
fn_clm_router_derive_to_tokens_-5359276554233412005 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/try_get_enum
// Implementation of TryGetEnumMeta for ToTokens
fn to_tokens(&self, _: &mut proc_macro2::TokenStream) {}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 44,
"total_crates": null
} |
fn_clm_router_derive_get_enum_variant_field_-5359276554233412005 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/try_get_enum
/// Get Field from an enum variant
fn get_enum_variant_field(
variant: &syn::Variant,
) -> syn::Result<Punctuated<syn::Field, syn::token::Comma>> {
let field = match variant.fields.clone() {
syn::Fields::Unnamed(un) => un.unnamed,
syn::Fields::Named(n) => n.named,
syn::Fields::Unit => {
return Err(super::helpers::syn_error(
Span::call_site(),
"The enum is a unit variant it's not supported",
))
}
};
Ok(field)
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 9,
"total_crates": null
} |
fn_clm_router_derive_validate_config_-4087634010163170548 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/misc
/// Implement the `validate` function for the struct by calling `validate` function on the fields
pub fn validate_config(input: syn::DeriveInput) -> Result<proc_macro2::TokenStream, syn::Error> {
let fields = super::helpers::get_struct_fields(input.data)
.map_err(|error| syn::Error::new(proc_macro2::Span::call_site(), error))?;
let struct_name = input.ident;
let function_expansions = fields
.into_iter()
.flat_map(|field| field.ident.to_owned().zip(get_field_type(field.ty)))
.filter_map(|(field_ident, field_type_ident)| {
// Check if a field is a leaf field, only String ( connector urls ) is supported for now
let field_ident_string = field_ident.to_string();
let is_optional_field = field_type_ident.eq("Option");
let is_secret_field = field_type_ident.eq("Secret");
// Do not call validate if it is an optional field
if !is_optional_field && !is_secret_field {
let is_leaf_field = field_type_ident.eq("String");
let validate_expansion = if is_leaf_field {
quote::quote!(common_utils::fp_utils::when(
self.#field_ident.is_empty(),
|| {
Err(ApplicationError::InvalidConfigurationValueError(
format!("{} must not be empty for {}", #field_ident_string, parent_field).into(),
))
}
)?;
)
} else {
quote::quote!(
self.#field_ident.validate(#field_ident_string)?;
)
};
Some(validate_expansion)
} else {
None
}
})
.collect::<Vec<_>>();
let expansion = quote::quote! {
impl #struct_name {
/// Validates that the configuration provided for the `parent_field` does not contain empty or default values
pub fn validate(&self, parent_field: &str) -> Result<(), ApplicationError> {
#(#function_expansions)*
Ok(())
}
}
};
Ok(expansion)
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 41,
"total_crates": null
} |
fn_clm_router_derive_get_field_type_-4087634010163170548 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/misc
pub fn get_field_type(field_type: syn::Type) -> Option<syn::Ident> {
if let syn::Type::Path(path) = field_type {
path.path
.segments
.last()
.map(|last_path_segment| last_path_segment.ident.to_owned())
} else {
None
}
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 31,
"total_crates": null
} |
fn_clm_router_derive_parse_1259981678078719150 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/diesel
// Implementation of DieselEnumMeta for Parse
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let lookahead = input.lookahead1();
if lookahead.peek(diesel_keyword::storage_type) {
let keyword = input.parse()?;
input.parse::<syn::Token![=]>()?;
let value = input.parse()?;
Ok(Self::StorageTypeEnum { keyword, value })
} else {
Err(lookahead.error())
}
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 456,
"total_crates": null
} |
fn_clm_router_derive_get_metadata_1259981678078719150 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/diesel
// Implementation of DeriveInput for DieselDeriveInputExt
fn get_metadata(&self) -> syn::Result<Vec<DieselEnumMeta>> {
helpers::get_metadata_inner("storage_type", &self.attrs)
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 103,
"total_crates": null
} |
fn_clm_router_derive_to_tokens_1259981678078719150 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/diesel
// Implementation of DieselEnumMeta for ToTokens
fn to_tokens(&self, tokens: &mut TokenStream) {
match self {
Self::StorageTypeEnum { keyword, .. } => keyword.to_tokens(tokens),
}
}
| {
"crate": "router_derive",
"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_router_derive_diesel_enum_derive_inner_1259981678078719150 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/diesel
pub(crate) fn diesel_enum_derive_inner(ast: &DeriveInput) -> syn::Result<TokenStream> {
let storage_type = ast.get_metadata()?;
match storage_type
.first()
.ok_or(syn::Error::new(
Span::call_site(),
"Storage type must be specified",
))?
.get_storage_type()
{
StorageType::Text => diesel_enum_text_derive_inner(ast),
StorageType::DbEnum => diesel_enum_db_enum_derive_inner(ast),
}
}
| {
"crate": "router_derive",
"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_router_derive_get_storage_type_1259981678078719150 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/diesel
// Inherent implementation for DieselEnumMeta
pub fn get_storage_type(&self) -> &StorageType {
match self {
Self::StorageTypeEnum { value, .. } => value,
}
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 21,
"total_crates": null
} |
fn_clm_router_derive_occurrence_error_-124509380520410068 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/helpers
pub(super) fn occurrence_error<T: ToTokens>(
first_keyword: T,
second_keyword: T,
attr: &str,
) -> syn::Error {
let mut error = syn::Error::new_spanned(
second_keyword,
format!("Found multiple occurrences of error({attr})"),
);
error.combine(syn::Error::new_spanned(first_keyword, "first one here"));
error
}
| {
"crate": "router_derive",
"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_router_derive_get_metadata_inner_-124509380520410068 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/helpers
pub(super) fn get_metadata_inner<'a, T: Parse + Spanned>(
ident: &str,
attrs: impl IntoIterator<Item = &'a Attribute>,
) -> syn::Result<Vec<T>> {
attrs
.into_iter()
.filter(|attr| attr.path().is_ident(ident))
.try_fold(Vec::new(), |mut vec, attr| {
vec.extend(attr.parse_args_with(Punctuated::<T, Token![,]>::parse_terminated)?);
Ok(vec)
})
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 41,
"total_crates": null
} |
fn_clm_router_derive_get_struct_fields_-124509380520410068 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/helpers
pub(super) fn get_struct_fields(
data: syn::Data,
) -> syn::Result<Punctuated<syn::Field, syn::token::Comma>> {
if let syn::Data::Struct(syn::DataStruct {
fields: syn::Fields::Named(syn::FieldsNamed { ref named, .. }),
..
}) = data
{
Ok(named.to_owned())
} else {
Err(syn::Error::new(
Span::call_site(),
"This macro cannot be used on structs with no fields",
))
}
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 28,
"total_crates": null
} |
fn_clm_router_derive_non_enum_error_-124509380520410068 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/helpers
pub fn non_enum_error() -> syn::Error {
syn::Error::new(Span::call_site(), "This macro only supports enums.")
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 26,
"total_crates": null
} |
fn_clm_router_derive_syn_error_-124509380520410068 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/helpers
pub(super) fn syn_error(span: Span, message: &str) -> syn::Error {
syn::Error::new(span, message)
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 21,
"total_crates": null
} |
fn_clm_router_derive_validate_schema_derive_8903875287290467985 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/schema
pub fn validate_schema_derive(input: syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
let name = &input.ident;
// Extract struct fields
let fields = macro_helpers::get_struct_fields(input.data)
.map_err(|error| syn::Error::new(proc_macro2::Span::call_site(), error))?;
// Map over each field
let validation_checks = fields.iter().filter_map(|field| {
let field_name = field.ident.as_ref()?;
let field_type = &field.ty;
// Check if field type is valid for validation
let is_field_valid = match IsSchemaFieldApplicableForValidation::from(field_type) {
IsSchemaFieldApplicableForValidation::Invalid => return None,
val => val,
};
// Parse attribute parameters for 'schema'
let schema_params = match field.get_schema_parameters() {
Ok(params) => params,
Err(_) => return None,
};
let min_length = schema_params.min_length;
let max_length = schema_params.max_length;
// Skip if no length validation is needed
if min_length.is_none() && max_length.is_none() {
return None;
}
let min_check = min_length.map(|min_val| {
quote! {
if value_len < #min_val {
return Err(format!("{} must be at least {} characters long. Received {} characters",
stringify!(#field_name), #min_val, value_len));
}
}
}).unwrap_or_else(|| quote! {});
let max_check = max_length.map(|max_val| {
quote! {
if value_len > #max_val {
return Err(format!("{} must be at most {} characters long. Received {} characters",
stringify!(#field_name), #max_val, value_len));
}
}
}).unwrap_or_else(|| quote! {});
// Generate length validation
if is_field_valid == IsSchemaFieldApplicableForValidation::ValidOptional {
Some(quote! {
if let Some(value) = &self.#field_name {
let value_len = value.as_str().len();
#min_check
#max_check
}
})
} else {
Some(quote! {
{
let value_len = self.#field_name.as_str().len();
#min_check
#max_check
}
})
}
}).collect::<Vec<_>>();
Ok(quote! {
impl #name {
pub fn validate(&self) -> Result<(), String> {
#(#validation_checks)*
Ok(())
}
}
})
}
| {
"crate": "router_derive",
"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_router_derive_parse_6256026180815849393 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/to_encryptable
// Implementation of FieldMeta for Parse
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let _meta_type: Ident = input.parse()?;
input.parse::<syn::Token![=]>()?;
let value: Ident = input.parse()?;
Ok(Self { _meta_type, value })
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 450,
"total_crates": null
} |
fn_clm_router_derive_generate_impls_6256026180815849393 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/to_encryptable
// Implementation of None for StructType
/// Generates the ToEncryptable trait implementation
fn generate_impls(
self,
gen1: proc_macro2::TokenStream,
gen2: proc_macro2::TokenStream,
gen3: proc_macro2::TokenStream,
impl_st: proc_macro2::TokenStream,
inner: &[Field],
) -> proc_macro2::TokenStream {
let map_length = inner.len();
let to_encryptable_impl = inner.iter().flat_map(|field| {
get_field_type(field.ty.clone()).map(|field_ty| {
let is_option = field_ty.eq("Option");
let field_ident = &field.ident;
let field_ident_string = field_ident.as_ref().map(|s| s.to_string());
if is_option || self == Self::Updated {
quote! { self.#field_ident.map(|s| map.insert(#field_ident_string.to_string(), s)) }
} else {
quote! { map.insert(#field_ident_string.to_string(), self.#field_ident) }
}
})
});
let from_encryptable_impl = inner.iter().flat_map(|field| {
get_field_type(field.ty.clone()).map(|field_ty| {
let is_option = field_ty.eq("Option");
let field_ident = &field.ident;
let field_ident_string = field_ident.as_ref().map(|s| s.to_string());
if is_option || self == Self::Updated {
quote! { #field_ident: map.remove(#field_ident_string) }
} else {
quote! {
#field_ident: map.remove(#field_ident_string).ok_or(
error_stack::report!(common_utils::errors::ParsingError::EncodeError(
"Unable to convert from HashMap",
))
)?
}
}
})
});
quote! {
impl ToEncryptable<#gen1, #gen2, #gen3> for #impl_st {
fn to_encryptable(self) -> FxHashMap<String, #gen3> {
let mut map = FxHashMap::with_capacity_and_hasher(#map_length, Default::default());
#(#to_encryptable_impl;)*
map
}
fn from_encryptable(
mut map: FxHashMap<String, Encryptable<#gen2>>,
) -> CustomResult<#gen1, common_utils::errors::ParsingError> {
Ok(#gen1 {
#(#from_encryptable_impl,)*
})
}
}
}
}
| {
"crate": "router_derive",
"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_router_derive_to_tokens_6256026180815849393 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/to_encryptable
// Implementation of FieldMeta for quote::ToTokens
fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
self.value.to_tokens(tokens);
}
| {
"crate": "router_derive",
"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_router_derive_generate_to_encryptable_6256026180815849393 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/to_encryptable
/// This function generates the temporary struct and ToEncryptable impls for the temporary structs
fn generate_to_encryptable(
struct_name: Ident,
fields: Vec<Field>,
) -> syn::Result<proc_macro2::TokenStream> {
let struct_types = [
// The first two are to be used as return types we do not need to implement ToEncryptable
// on it
("Decrypted", StructType::Decrypted),
("DecryptedUpdate", StructType::DecryptedUpdate),
("FromRequestEncryptable", StructType::FromRequest),
("Encrypted", StructType::Encrypted),
("UpdateEncryptable", StructType::Updated),
];
let inner_types = get_field_and_inner_types(&fields);
let inner_type = inner_types.first().ok_or_else(|| {
syn::Error::new(
proc_macro2::Span::call_site(),
"Please use the macro with attribute #[encrypt] on the fields you want to encrypt",
)
})?;
let provided_ty = get_encryption_ty_meta(&inner_type.0)
.map(|ty| ty.value.clone())
.unwrap_or(inner_type.1.clone());
let structs = struct_types.iter().map(|(prefix, struct_type)| {
let name = format_ident!("{}{}", prefix, struct_name);
let temp_fields = struct_type.generate_struct_fields(&inner_types);
quote! {
pub struct #name {
#(#temp_fields,)*
}
}
});
// These implementations shouldn't be implemented Decrypted and DecryptedUpdate temp structs
// So skip the first two entries in the list
let impls = struct_types
.iter()
.skip(2)
.map(|(prefix, struct_type)| {
let name = format_ident!("{}{}", prefix, struct_name);
let impl_block = if *struct_type != StructType::DecryptedUpdate
|| *struct_type != StructType::Decrypted
{
let (gen1, gen2, gen3) = match struct_type {
StructType::FromRequest => {
let decrypted_name = format_ident!("Decrypted{}", struct_name);
(
quote! { #decrypted_name },
quote! { Secret<#provided_ty> },
quote! { Secret<#provided_ty> },
)
}
StructType::Encrypted => {
let decrypted_name = format_ident!("Decrypted{}", struct_name);
(
quote! { #decrypted_name },
quote! { Secret<#provided_ty> },
quote! { Encryption },
)
}
StructType::Updated => {
let decrypted_update_name = format_ident!("DecryptedUpdate{}", struct_name);
(
quote! { #decrypted_update_name },
quote! { Secret<#provided_ty> },
quote! { Secret<#provided_ty> },
)
}
//Unreachable statement
_ => (quote! {}, quote! {}, quote! {}),
};
struct_type.generate_impls(gen1, gen2, gen3, quote! { #name }, &fields)
} else {
quote! {}
};
Ok(quote! {
#impl_block
})
})
.collect::<syn::Result<Vec<_>>>()?;
Ok(quote! {
#(#structs)*
#(#impls)*
})
}
| {
"crate": "router_derive",
"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_router_derive_generate_struct_fields_6256026180815849393 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/to_encryptable
// Implementation of None for StructType
/// Generates the fields for temporary structs which consists of the fields that should be
/// encrypted/decrypted
fn generate_struct_fields(self, fields: &[(Field, Ident)]) -> Vec<proc_macro2::TokenStream> {
fields
.iter()
.map(|(field, inner_ty)| {
let provided_ty = get_encryption_ty_meta(field);
let is_option = get_field_type(field.ty.clone())
.map(|f| f.eq("Option"))
.unwrap_or_default();
let ident = &field.ident;
let inner_ty = if let Some(ref ty) = provided_ty {
&ty.value
} else {
inner_ty
};
match (self, is_option) {
(Self::Encrypted, true) => quote! { pub #ident: Option<Encryption> },
(Self::Encrypted, false) => quote! { pub #ident: Encryption },
(Self::Decrypted, true) => {
quote! { pub #ident: Option<Encryptable<Secret<#inner_ty>>> }
}
(Self::Decrypted, false) => {
quote! { pub #ident: Encryptable<Secret<#inner_ty>> }
}
(Self::DecryptedUpdate, _) => {
quote! { pub #ident: Option<Encryptable<Secret<#inner_ty>>> }
}
(Self::FromRequest, true) => {
quote! { pub #ident: Option<Secret<#inner_ty>> }
}
(Self::FromRequest, false) => quote! { pub #ident: Secret<#inner_ty> },
(Self::Updated, _) => quote! { pub #ident: Option<Secret<#inner_ty>> },
}
})
.collect()
}
| {
"crate": "router_derive",
"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_router_derive_parse_3969858902956416270 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/generate_schema
// Implementation of SchemaMeta for Parse
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let struct_name = input.parse::<syn::Ident>()?;
input.parse::<syn::Token![=]>()?;
let type_ident = input.parse::<syn::Ident>()?;
Ok(Self {
struct_name,
type_ident,
})
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 446,
"total_crates": null
} |
fn_clm_router_derive_polymorphic_macro_derive_inner_3969858902956416270 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/generate_schema
pub fn polymorphic_macro_derive_inner(
input: syn::DeriveInput,
) -> syn::Result<proc_macro2::TokenStream> {
let schemas_to_create =
helpers::get_metadata_inner::<syn::Ident>("generate_schemas", &input.attrs)?;
let fields = helpers::get_struct_fields(input.data)
.map_err(|error| syn::Error::new(proc_macro2::Span::call_site(), error))?;
// Go through all the fields and create a mapping of required fields for a schema
// PaymentsCreate -> ["amount","currency"]
// This will be stored in the hashmap with key as
// required_fields -> ((amount, PaymentsCreate), (currency, PaymentsCreate))
// and values as the type
//
// (amount, PaymentsCreate) -> Amount
let mut required_fields = HashMap::<(syn::Ident, syn::Ident), syn::Ident>::new();
// These fields will be removed in the schema
// PaymentsUpdate -> ["client_secret"]
// This will be stored in a hashset
// hide_fields -> ((client_secret, PaymentsUpdate))
let mut hide_fields = HashSet::<(syn::Ident, syn::Ident)>::new();
let mut all_fields = IndexMap::<syn::Field, Vec<syn::Attribute>>::new();
for field in fields {
// Partition the attributes of a field into two vectors
// One with #[mandatory_in] attributes present
// Rest of the attributes ( include only the schema attribute, serde is not required)
let (mandatory_attribute, other_attributes) = field
.attrs
.iter()
.partition::<Vec<_>, _>(|attribute| attribute.path().is_ident("mandatory_in"));
let hidden_fields = field
.attrs
.iter()
.filter(|attribute| attribute.path().is_ident("remove_in"))
.collect::<Vec<_>>();
// Other attributes ( schema ) are to be printed as is
other_attributes
.iter()
.filter(|attribute| {
attribute.path().is_ident("schema") || attribute.path().is_ident("doc")
})
.for_each(|attribute| {
// Since attributes will be modified, the field should not contain any attributes
// So create a field, with previous attributes removed
let mut field_without_attributes = field.clone();
field_without_attributes.attrs.clear();
all_fields
.entry(field_without_attributes.to_owned())
.or_default()
.push(attribute.to_owned().to_owned());
});
// Mandatory attributes are to be inserted into hashset
// The hashset will store it in this format
// ("amount", PaymentsCreateRequest)
// ("currency", PaymentsConfirmRequest)
//
// For these attributes, we need to later add #[schema(required = true)] attribute
let field_ident = field.ident.ok_or(syn::Error::new(
proc_macro2::Span::call_site(),
"Cannot use `mandatory_in` on unnamed fields",
))?;
// Parse the #[mandatory_in(PaymentsCreateRequest = u64)] and insert into hashmap
// key -> ("amount", PaymentsCreateRequest)
// value -> u64
if let Some(mandatory_in_attribute) =
helpers::get_metadata_inner::<SchemaMeta>("mandatory_in", mandatory_attribute)?.first()
{
let key = (
field_ident.clone(),
mandatory_in_attribute.struct_name.clone(),
);
let value = mandatory_in_attribute.type_ident.clone();
required_fields.insert(key, value);
}
// Hidden fields are to be inserted in the Hashset
// The hashset will store it in this format
// ("client_secret", PaymentsUpdate)
//
// These fields will not be added to the struct
_ = hidden_fields
.iter()
// Filter only #[mandatory_in] attributes
.map(|&attribute| get_inner_path_ident(attribute))
.try_for_each(|schemas| {
let res = schemas
.map_err(|error| syn::Error::new(proc_macro2::Span::call_site(), error))?
.iter()
.map(|schema| (field_ident.clone(), schema.to_owned()))
.collect::<HashSet<_>>();
hide_fields.extend(res);
Ok::<_, syn::Error>(())
});
}
// iterate over the schemas and build them with their fields
let schemas = schemas_to_create
.iter()
.map(|schema| {
let fields = all_fields
.iter()
.filter_map(|(field, attributes)| {
let mut final_attributes = attributes.clone();
if let Some(field_ident) = field.ident.to_owned() {
// If the field is required for this schema, then add
// #[schema(value_type = type)] for this field
if let Some(required_field_type) =
required_fields.get(&(field_ident.clone(), schema.to_owned()))
{
// This is a required field in the Schema
// Add the value type and remove original value type ( if present )
let attribute_without_schema_type = attributes
.iter()
.filter(|attribute| !attribute.path().is_ident("schema"))
.map(Clone::clone)
.collect::<Vec<_>>();
final_attributes = attribute_without_schema_type;
let value_type_attribute: syn::Attribute =
parse_quote!(#[schema(value_type = #required_field_type)]);
final_attributes.push(value_type_attribute);
}
}
// If the field is to be not shown then
let is_hidden_field = field
.ident
.clone()
.map(|field_ident| hide_fields.contains(&(field_ident, schema.to_owned())))
.unwrap_or(false);
if is_hidden_field {
None
} else {
Some(quote::quote! {
#(#final_attributes)*
#field,
})
}
})
.collect::<Vec<_>>();
quote::quote! {
#[derive(utoipa::ToSchema)]
pub struct #schema {
#(#fields)*
}
}
})
.collect::<Vec<_>>();
Ok(quote::quote! {
#(#schemas)*
})
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 151,
"total_crates": null
} |
fn_clm_router_derive_to_tokens_3969858902956416270 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/generate_schema
// Implementation of SchemaMeta for quote::ToTokens
fn to_tokens(&self, _: &mut proc_macro2::TokenStream) {}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 44,
"total_crates": null
} |
fn_clm_router_derive_get_field_type_3969858902956416270 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/generate_schema
/// Get the type of field
fn get_field_type(field_type: syn::Type) -> syn::Result<syn::Ident> {
if let syn::Type::Path(path) = field_type {
path.path
.segments
.last()
.map(|last_path_segment| last_path_segment.ident.to_owned())
.ok_or(syn::Error::new(
proc_macro2::Span::call_site(),
"Atleast one ident must be specified",
))
} else {
Err(syn::Error::new(
proc_macro2::Span::call_site(),
"Only path fields are supported",
))
}
}
| {
"crate": "router_derive",
"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_router_derive_get_inner_option_type_3969858902956416270 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/generate_schema
/// Get the inner type of option
fn get_inner_option_type(field: &syn::Type) -> syn::Result<syn::Ident> {
if let syn::Type::Path(ref path) = &field {
if let Some(segment) = path.path.segments.last() {
if let syn::PathArguments::AngleBracketed(ref args) = &segment.arguments {
if let Some(syn::GenericArgument::Type(ty)) = args.args.first() {
return get_field_type(ty.clone());
}
}
}
}
Err(syn::Error::new(
proc_macro2::Span::call_site(),
"Only path fields are supported",
))
}
| {
"crate": "router_derive",
"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_router_derive_parse_-4070316807076880415 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/generate_permissions
// Implementation of ResourceInput for Parse
fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
let resource_name: Ident = input.parse()?;
input.parse::<Token![:]>()?; // Expect ':'
let content;
braced!(content in input);
let (_scopes_label, scopes) = parse_label_with_punctuated_data(&content)?;
content.parse::<Comma>()?;
let (_entities_label, entities) = parse_label_with_punctuated_data(&content)?;
Ok(Self {
resource_name,
scopes,
entities,
})
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 452,
"total_crates": null
} |
fn_clm_router_derive_generate_permissions_inner_-4070316807076880415 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/generate_permissions
pub fn generate_permissions_inner(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as Input);
let res = input.permissions.iter();
let mut enum_keys = Vec::new();
let mut scope_impl_per = Vec::new();
let mut entity_impl_per = Vec::new();
let mut resource_impl_per = Vec::new();
let mut entity_impl_res = Vec::new();
for per in res {
let resource_name = &per.resource_name;
let mut permissions = Vec::new();
for scope in per.scopes.iter() {
for entity in per.entities.iter() {
let key = format_ident!("{}{}{}", entity, per.resource_name, scope);
enum_keys.push(quote! { #key });
scope_impl_per.push(quote! { Permission::#key => PermissionScope::#scope });
entity_impl_per.push(quote! { Permission::#key => EntityType::#entity });
resource_impl_per.push(quote! { Permission::#key => Resource::#resource_name });
permissions.push(quote! { Permission::#key });
}
let entities_iter = per.entities.iter();
entity_impl_res
.push(quote! { Resource::#resource_name => vec![#(EntityType::#entities_iter),*] });
}
}
let expanded = quote! {
#[derive(
Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash, Debug, serde::Serialize, serde::Deserialize, strum::Display
)]
pub enum Permission {
#(#enum_keys),*
}
impl Permission {
pub fn scope(&self) -> PermissionScope {
match self {
#(#scope_impl_per),*
}
}
pub fn entity_type(&self) -> EntityType {
match self {
#(#entity_impl_per),*
}
}
pub fn resource(&self) -> Resource {
match self {
#(#resource_impl_per),*
}
}
}
pub trait ResourceExt {
fn entities(&self) -> Vec<EntityType>;
}
impl ResourceExt for Resource {
fn entities(&self) -> Vec<EntityType> {
match self {
#(#entity_impl_res),*
}
}
}
};
expanded.into()
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 47,
"total_crates": null
} |
fn_clm_router_derive_parse_label_with_punctuated_data_-4070316807076880415 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/generate_permissions
fn parse_label_with_punctuated_data<T: Parse>(
input: &ParseBuffer<'_>,
) -> syn::Result<(Ident, Punctuated<T, Token![,]>)> {
let label: Ident = input.parse()?;
input.parse::<Token![:]>()?; // Expect ':'
let content;
bracketed!(content in input); // Parse the list inside []
let data = Punctuated::<T, Token![,]>::parse_terminated(&content)?;
Ok((label, data))
}
| {
"crate": "router_derive",
"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_router_derive_parse_-4224980119330890800 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/api_error/helpers
// Implementation of VariantMeta for Parse
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let lookahead = input.lookahead1();
if lookahead.peek(keyword::error_type) {
let keyword = input.parse()?;
let _: Token![=] = input.parse()?;
let value = input.parse()?;
Ok(Self::ErrorType { keyword, value })
} else if lookahead.peek(keyword::code) {
let keyword = input.parse()?;
let _: Token![=] = input.parse()?;
let value = input.parse()?;
Ok(Self::Code { keyword, value })
} else if lookahead.peek(keyword::message) {
let keyword = input.parse()?;
let _: Token![=] = input.parse()?;
let value = input.parse()?;
Ok(Self::Message { keyword, value })
} else if lookahead.peek(keyword::ignore) {
let keyword = input.parse()?;
let _: Token![=] = input.parse()?;
let value = input.parse()?;
Ok(Self::Ignore { keyword, value })
} else {
Err(lookahead.error())
}
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 482,
"total_crates": null
} |
fn_clm_router_derive_get_metadata_-4224980119330890800 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/api_error/helpers
// Implementation of Variant for VariantExt
fn get_metadata(&self) -> syn::Result<Vec<VariantMeta>> {
get_metadata_inner("error", &self.attrs)
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 103,
"total_crates": null
} |
fn_clm_router_derive_to_tokens_-4224980119330890800 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/api_error/helpers
// Implementation of VariantMeta for ToTokens
fn to_tokens(&self, tokens: &mut TokenStream) {
match self {
Self::ErrorType { keyword, .. } => keyword.to_tokens(tokens),
Self::Code { keyword, .. } => keyword.to_tokens(tokens),
Self::Message { keyword, .. } => keyword.to_tokens(tokens),
Self::Ignore { keyword, .. } => keyword.to_tokens(tokens),
}
}
| {
"crate": "router_derive",
"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_router_derive_get_unused_fields_-4224980119330890800 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/api_error/helpers
/// Get all the fields not used in the error message.
pub(super) fn get_unused_fields(
fields: &Fields,
message: &str,
ignore: &std::collections::HashSet<String>,
) -> Vec<Field> {
let fields = match fields {
Fields::Unit => Vec::new(),
Fields::Unnamed(_) => Vec::new(),
Fields::Named(fields) => fields.named.iter().cloned().collect(),
};
fields
.iter()
.filter(|&field| {
// Safety: Named fields are guaranteed to have an identifier.
#[allow(clippy::unwrap_used)]
let field_name = format!("{}", field.ident.as_ref().unwrap());
!message.contains(&field_name) && !ignore.contains(&field_name)
})
.cloned()
.collect()
}
| {
"crate": "router_derive",
"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_router_derive_get_variant_properties_-4224980119330890800 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/api_error/helpers
// Implementation of Variant for HasErrorVariantProperties
fn get_variant_properties(&self) -> syn::Result<ErrorVariantProperties> {
let mut output = ErrorVariantProperties::default();
let mut error_type_keyword = None;
let mut code_keyword = None;
let mut message_keyword = None;
let mut ignore_keyword = None;
for meta in self.get_metadata()? {
match meta {
VariantMeta::ErrorType { keyword, value } => {
if let Some(first_keyword) = error_type_keyword {
return Err(occurrence_error(first_keyword, keyword, "error_type"));
}
error_type_keyword = Some(keyword);
output.error_type = Some(value);
}
VariantMeta::Code { keyword, value } => {
if let Some(first_keyword) = code_keyword {
return Err(occurrence_error(first_keyword, keyword, "code"));
}
code_keyword = Some(keyword);
output.code = Some(value);
}
VariantMeta::Message { keyword, value } => {
if let Some(first_keyword) = message_keyword {
return Err(occurrence_error(first_keyword, keyword, "message"));
}
message_keyword = Some(keyword);
output.message = Some(value);
}
VariantMeta::Ignore { keyword, value } => {
if let Some(first_keyword) = ignore_keyword {
return Err(occurrence_error(first_keyword, keyword, "ignore"));
}
ignore_keyword = Some(keyword);
output.ignore = value
.value()
.replace(' ', "")
.split(',')
.map(ToString::to_string)
.collect();
}
}
}
Ok(output)
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 33,
"total_crates": null
} |
fn_clm_router_derive_from_7682133559693408056 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/schema/helpers
// Implementation of IsSchemaFieldApplicableForValidation for From<&syn::Type>
fn from(ty: &syn::Type) -> Self {
if let syn::Type::Path(type_path) = ty {
if let Some(segment) = type_path.path.segments.last() {
let ident = &segment.ident;
if ident == "String" || ident == "Url" {
return Self::Valid;
}
if ident == "Option" {
if let syn::PathArguments::AngleBracketed(generic_args) = &segment.arguments {
if let Some(syn::GenericArgument::Type(syn::Type::Path(inner_path))) =
generic_args.args.first()
{
if let Some(inner_segment) = inner_path.path.segments.last() {
if inner_segment.ident == "String" || inner_segment.ident == "Url" {
return Self::ValidOptional;
}
}
}
}
}
}
}
Self::Invalid
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 2606,
"total_crates": null
} |
fn_clm_router_derive_parse_7682133559693408056 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/schema/helpers
// Implementation of SchemaParameterVariant for Parse
fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> {
let lookahead = input.lookahead1();
if lookahead.peek(keyword::value_type) {
let keyword = input.parse()?;
input.parse::<Token![=]>()?;
let value = input.parse()?;
Ok(Self::ValueType { keyword, value })
} else if lookahead.peek(keyword::min_length) {
let keyword = input.parse()?;
input.parse::<Token![=]>()?;
let value = input.parse()?;
Ok(Self::MinLength { keyword, value })
} else if lookahead.peek(keyword::max_length) {
let keyword = input.parse()?;
input.parse::<Token![=]>()?;
let value = input.parse()?;
Ok(Self::MaxLength { keyword, value })
} else if lookahead.peek(keyword::example) {
let keyword = input.parse()?;
input.parse::<Token![=]>()?;
let value = input.parse()?;
Ok(Self::Example { keyword, value })
} else {
Err(lookahead.error())
}
}
| {
"crate": "router_derive",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 474,
"total_crates": null
} |
fn_clm_router_derive_to_tokens_7682133559693408056 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/schema/helpers
// Implementation of SchemaParameterVariant for ToTokens
fn to_tokens(&self, tokens: &mut TokenStream) {
match self {
Self::ValueType { keyword, .. } => keyword.to_tokens(tokens),
Self::MinLength { keyword, .. } => keyword.to_tokens(tokens),
Self::MaxLength { keyword, .. } => keyword.to_tokens(tokens),
Self::Example { keyword, .. } => keyword.to_tokens(tokens),
}
}
| {
"crate": "router_derive",
"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_router_derive_get_schema_parameters_7682133559693408056 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/schema/helpers
// Implementation of Field for HasSchemaParameters
fn get_schema_parameters(&self) -> syn::Result<SchemaParameters> {
let mut output = SchemaParameters::default();
let mut value_type_keyword = None;
let mut min_length_keyword = None;
let mut max_length_keyword = None;
let mut example_keyword = None;
for meta in self.get_schema_metadata()? {
match meta {
SchemaParameterVariant::ValueType { keyword, value } => {
if let Some(first_keyword) = value_type_keyword {
return Err(occurrence_error(first_keyword, keyword, "value_type"));
}
value_type_keyword = Some(keyword);
output.value_type = Some(value);
}
SchemaParameterVariant::MinLength { keyword, value } => {
if let Some(first_keyword) = min_length_keyword {
return Err(occurrence_error(first_keyword, keyword, "min_length"));
}
min_length_keyword = Some(keyword);
let min_length = value.base10_parse::<usize>()?;
output.min_length = Some(min_length);
}
SchemaParameterVariant::MaxLength { keyword, value } => {
if let Some(first_keyword) = max_length_keyword {
return Err(occurrence_error(first_keyword, keyword, "max_length"));
}
max_length_keyword = Some(keyword);
let max_length = value.base10_parse::<usize>()?;
output.max_length = Some(max_length);
}
SchemaParameterVariant::Example { keyword, value } => {
if let Some(first_keyword) = example_keyword {
return Err(occurrence_error(first_keyword, keyword, "example"));
}
example_keyword = Some(keyword);
output.example = Some(value.value());
}
}
}
Ok(output)
}
| {
"crate": "router_derive",
"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_router_derive_get_schema_metadata_7682133559693408056 | clm | function | // Repository: hyperswitch
// Crate: router_derive
// Module: crates/router_derive/src/macros/schema/helpers
// Implementation of Field for FieldExt
fn get_schema_metadata(&self) -> syn::Result<Vec<SchemaParameterVariant>> {
get_metadata_inner("schema", &self.attrs)
}
| {
"crate": "router_derive",
"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_subscriptions_create_and_confirm_subscription_6185449983308256030 | clm | function | // Repository: hyperswitch
// Crate: subscriptions
// Module: crates/subscriptions/src/core
/// Creates and confirms a subscription in one operation.
pub async fn create_and_confirm_subscription(
state: SessionState,
merchant_context: MerchantContext,
profile_id: common_utils::id_type::ProfileId,
request: subscription_types::CreateAndConfirmSubscriptionRequest,
) -> RouterResponse<subscription_types::ConfirmSubscriptionResponse> {
let subscription_id = common_utils::id_type::SubscriptionId::generate();
let profile =
SubscriptionHandler::find_business_profile(&state, &merchant_context, &profile_id)
.await
.attach_printable("subscriptions: failed to find business profile")?;
let customer =
SubscriptionHandler::find_customer(&state, &merchant_context, &request.customer_id)
.await
.attach_printable("subscriptions: failed to find customer")?;
let billing_handler = BillingHandler::create(
&state,
merchant_context.get_merchant_account(),
merchant_context.get_merchant_key_store(),
profile.clone(),
)
.await?;
let subscription_handler = SubscriptionHandler::new(&state, &merchant_context);
let mut subs_handler = subscription_handler
.create_subscription_entry(
subscription_id.clone(),
&request.customer_id,
billing_handler.connector_name,
billing_handler.merchant_connector_id.clone(),
request.merchant_reference_id.clone(),
&profile.clone(),
request.plan_id.clone(),
Some(request.item_price_id.clone()),
)
.await
.attach_printable("subscriptions: failed to create subscription entry")?;
let invoice_handler = subs_handler.get_invoice_handler(profile.clone());
let customer_create_response = billing_handler
.create_customer_on_connector(
&state,
customer.clone(),
request.customer_id.clone(),
request.get_billing_address(),
request
.payment_details
.payment_method_data
.clone()
.and_then(|data| data.payment_method_data),
)
.await?;
let _customer_updated_response = SubscriptionHandler::update_connector_customer_id_in_customer(
&state,
&merchant_context,
&billing_handler.merchant_connector_id,
&customer,
customer_create_response,
)
.await
.attach_printable("Failed to update customer with connector customer ID")?;
let subscription_create_response = billing_handler
.create_subscription_on_connector(
&state,
subs_handler.subscription.clone(),
Some(request.item_price_id.clone()),
request.get_billing_address(),
)
.await?;
let invoice_details = subscription_create_response.invoice_details;
let (amount, currency) =
InvoiceHandler::get_amount_and_currency((None, None), invoice_details.clone());
let payment_response = invoice_handler
.create_and_confirm_payment(&state, &request, amount, currency)
.await?;
let invoice_entry = invoice_handler
.create_invoice_entry(
&state,
profile.get_billing_processor_id()?,
Some(payment_response.payment_id.clone()),
amount,
currency,
invoice_details
.clone()
.and_then(|invoice| invoice.status)
.unwrap_or(connector_enums::InvoiceStatus::InvoiceCreated),
billing_handler.connector_name,
None,
invoice_details.clone().map(|invoice| invoice.id),
)
.await?;
invoice_handler
.create_invoice_sync_job(
&state,
&invoice_entry,
invoice_details.clone().map(|details| details.id),
billing_handler.connector_name,
)
.await?;
subs_handler
.update_subscription(
hyperswitch_domain_models::subscription::SubscriptionUpdate::new(
Some(
subscription_create_response
.subscription_id
.get_string_repr()
.to_string(),
),
payment_response.payment_method_id.clone(),
Some(SubscriptionStatus::from(subscription_create_response.status).to_string()),
request.plan_id,
Some(request.item_price_id),
),
)
.await?;
let response = subs_handler.generate_response(
&invoice_entry,
&payment_response,
subscription_create_response.status,
)?;
Ok(ApplicationResponse::Json(response))
}
| {
"crate": "subscriptions",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 123,
"total_crates": null
} |
fn_clm_subscriptions_confirm_subscription_6185449983308256030 | clm | function | // Repository: hyperswitch
// Crate: subscriptions
// Module: crates/subscriptions/src/core
pub async fn confirm_subscription(
state: SessionState,
merchant_context: MerchantContext,
profile_id: common_utils::id_type::ProfileId,
request: subscription_types::ConfirmSubscriptionRequest,
subscription_id: common_utils::id_type::SubscriptionId,
) -> RouterResponse<subscription_types::ConfirmSubscriptionResponse> {
// Find the subscription from database
let profile =
SubscriptionHandler::find_business_profile(&state, &merchant_context, &profile_id)
.await
.attach_printable("subscriptions: failed to find business profile")?;
let handler = SubscriptionHandler::new(&state, &merchant_context);
if let Some(client_secret) = request.client_secret.clone() {
handler
.find_and_validate_subscription(&client_secret.into())
.await?
};
let mut subscription_entry = handler.find_subscription(subscription_id).await?;
let customer = SubscriptionHandler::find_customer(
&state,
&merchant_context,
&subscription_entry.subscription.customer_id,
)
.await
.attach_printable("subscriptions: failed to find customer")?;
let invoice_handler = subscription_entry.get_invoice_handler(profile.clone());
let invoice = invoice_handler
.get_latest_invoice(&state)
.await
.attach_printable("subscriptions: failed to get latest invoice")?;
let payment_response = invoice_handler
.confirm_payment(
&state,
invoice
.payment_intent_id
.ok_or(errors::ApiErrorResponse::MissingRequiredField {
field_name: "payment_intent_id",
})?,
&request,
)
.await?;
let billing_handler = BillingHandler::create(
&state,
merchant_context.get_merchant_account(),
merchant_context.get_merchant_key_store(),
profile.clone(),
)
.await?;
let invoice_handler = subscription_entry.get_invoice_handler(profile);
let subscription = subscription_entry.subscription.clone();
let customer_create_response = billing_handler
.create_customer_on_connector(
&state,
customer.clone(),
subscription.customer_id.clone(),
request.get_billing_address(),
request
.payment_details
.payment_method_data
.payment_method_data
.clone(),
)
.await?;
let _customer_updated_response = SubscriptionHandler::update_connector_customer_id_in_customer(
&state,
&merchant_context,
&billing_handler.merchant_connector_id,
&customer,
customer_create_response,
)
.await
.attach_printable("Failed to update customer with connector customer ID")?;
let subscription_create_response = billing_handler
.create_subscription_on_connector(
&state,
subscription.clone(),
subscription.item_price_id.clone(),
request.get_billing_address(),
)
.await?;
let invoice_details = subscription_create_response.invoice_details;
let update_request = InvoiceUpdateRequest::update_payment_and_status(
payment_response.payment_method_id.clone(),
Some(payment_response.payment_id.clone()),
invoice_details
.clone()
.and_then(|invoice| invoice.status)
.unwrap_or(connector_enums::InvoiceStatus::InvoiceCreated),
invoice_details.clone().map(|invoice| invoice.id),
);
let invoice_entry = invoice_handler
.update_invoice(&state, invoice.id, update_request)
.await?;
invoice_handler
.create_invoice_sync_job(
&state,
&invoice_entry,
invoice_details.map(|invoice| invoice.id),
billing_handler.connector_name,
)
.await?;
subscription_entry
.update_subscription(
hyperswitch_domain_models::subscription::SubscriptionUpdate::new(
Some(
subscription_create_response
.subscription_id
.get_string_repr()
.to_string(),
),
payment_response.payment_method_id.clone(),
Some(SubscriptionStatus::from(subscription_create_response.status).to_string()),
subscription.plan_id.clone(),
subscription.item_price_id.clone(),
),
)
.await?;
let response = subscription_entry.generate_response(
&invoice_entry,
&payment_response,
subscription_create_response.status,
)?;
Ok(ApplicationResponse::Json(response))
}
| {
"crate": "subscriptions",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 121,
"total_crates": null
} |
fn_clm_subscriptions_create_subscription_6185449983308256030 | clm | function | // Repository: hyperswitch
// Crate: subscriptions
// Module: crates/subscriptions/src/core
pub async fn create_subscription(
state: SessionState,
merchant_context: MerchantContext,
profile_id: common_utils::id_type::ProfileId,
request: subscription_types::CreateSubscriptionRequest,
) -> RouterResponse<SubscriptionResponse> {
let subscription_id = common_utils::id_type::SubscriptionId::generate();
let profile =
SubscriptionHandler::find_business_profile(&state, &merchant_context, &profile_id)
.await
.attach_printable("subscriptions: failed to find business profile")?;
let _customer =
SubscriptionHandler::find_customer(&state, &merchant_context, &request.customer_id)
.await
.attach_printable("subscriptions: failed to find customer")?;
let billing_handler = BillingHandler::create(
&state,
merchant_context.get_merchant_account(),
merchant_context.get_merchant_key_store(),
profile.clone(),
)
.await?;
let subscription_handler = SubscriptionHandler::new(&state, &merchant_context);
let mut subscription = subscription_handler
.create_subscription_entry(
subscription_id,
&request.customer_id,
billing_handler.connector_name,
billing_handler.merchant_connector_id.clone(),
request.merchant_reference_id.clone(),
&profile.clone(),
request.plan_id.clone(),
Some(request.item_price_id.clone()),
)
.await
.attach_printable("subscriptions: failed to create subscription entry")?;
let estimate_request = subscription_types::EstimateSubscriptionQuery {
plan_id: request.plan_id.clone(),
item_price_id: request.item_price_id.clone(),
coupon_code: None,
};
let estimate = billing_handler
.get_subscription_estimate(&state, estimate_request)
.await?;
let invoice_handler = subscription.get_invoice_handler(profile.clone());
let payment = invoice_handler
.create_payment_with_confirm_false(
subscription.handler.state,
&request,
estimate.total,
estimate.currency,
)
.await
.attach_printable("subscriptions: failed to create payment")?;
let invoice = invoice_handler
.create_invoice_entry(
&state,
billing_handler.merchant_connector_id,
Some(payment.payment_id.clone()),
estimate.total,
estimate.currency,
connector_enums::InvoiceStatus::InvoiceCreated,
billing_handler.connector_name,
None,
None,
)
.await
.attach_printable("subscriptions: failed to create invoice")?;
subscription
.update_subscription(
hyperswitch_domain_models::subscription::SubscriptionUpdate::new(
None,
payment.payment_method_id.clone(),
None,
request.plan_id,
Some(request.item_price_id),
),
)
.await
.attach_printable("subscriptions: failed to update subscription")?;
let response = subscription.to_subscription_response(Some(payment), Some(&invoice))?;
Ok(ApplicationResponse::Json(response))
}
| {
"crate": "subscriptions",
"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_subscriptions_update_subscription_6185449983308256030 | clm | function | // Repository: hyperswitch
// Crate: subscriptions
// Module: crates/subscriptions/src/core
pub async fn update_subscription(
state: SessionState,
merchant_context: MerchantContext,
profile_id: common_utils::id_type::ProfileId,
subscription_id: common_utils::id_type::SubscriptionId,
request: subscription_types::UpdateSubscriptionRequest,
) -> RouterResponse<SubscriptionResponse> {
let profile =
SubscriptionHandler::find_business_profile(&state, &merchant_context, &profile_id)
.await
.attach_printable(
"subscriptions: failed to find business profile in get_subscription",
)?;
let handler = SubscriptionHandler::new(&state, &merchant_context);
let mut subscription_entry = handler.find_subscription(subscription_id).await?;
let invoice_handler = subscription_entry.get_invoice_handler(profile.clone());
let invoice = invoice_handler
.get_latest_invoice(&state)
.await
.attach_printable("subscriptions: failed to get latest invoice")?;
let subscription = subscription_entry.subscription.clone();
subscription_entry
.update_subscription(
hyperswitch_domain_models::subscription::SubscriptionUpdate::new(
None,
None,
None,
Some(request.plan_id.clone()),
Some(request.item_price_id.clone()),
),
)
.await?;
let billing_handler = BillingHandler::create(
&state,
merchant_context.get_merchant_account(),
merchant_context.get_merchant_key_store(),
profile.clone(),
)
.await?;
let estimate_request = subscription_types::EstimateSubscriptionQuery {
plan_id: Some(request.plan_id.clone()),
item_price_id: request.item_price_id.clone(),
coupon_code: None,
};
let estimate = billing_handler
.get_subscription_estimate(&state, estimate_request)
.await?;
let update_request = InvoiceUpdateRequest::update_amount_and_currency(
estimate.total,
estimate.currency.to_string(),
);
let invoice_entry = invoice_handler
.update_invoice(&state, invoice.id, update_request)
.await?;
let _payment_response = invoice_handler
.update_payment(
&state,
estimate.total,
estimate.currency,
invoice_entry.payment_intent_id.ok_or(
errors::ApiErrorResponse::MissingRequiredField {
field_name: "payment_intent_id",
},
)?,
)
.await?;
Box::pin(get_subscription(
state,
merchant_context,
profile_id,
subscription.id,
))
.await
}
| {
"crate": "subscriptions",
"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_subscriptions_get_subscription_plans_6185449983308256030 | clm | function | // Repository: hyperswitch
// Crate: subscriptions
// Module: crates/subscriptions/src/core
pub async fn get_subscription_plans(
state: SessionState,
merchant_context: MerchantContext,
profile_id: common_utils::id_type::ProfileId,
query: subscription_types::GetPlansQuery,
) -> RouterResponse<Vec<subscription_types::GetPlansResponse>> {
let profile =
SubscriptionHandler::find_business_profile(&state, &merchant_context, &profile_id)
.await
.attach_printable("subscriptions: failed to find business profile")?;
let subscription_handler = SubscriptionHandler::new(&state, &merchant_context);
if let Some(client_secret) = query.client_secret {
subscription_handler
.find_and_validate_subscription(&client_secret.into())
.await?
};
let billing_handler = BillingHandler::create(
&state,
merchant_context.get_merchant_account(),
merchant_context.get_merchant_key_store(),
profile.clone(),
)
.await?;
let get_plans_response = billing_handler
.get_subscription_plans(&state, query.limit, query.offset)
.await?;
let mut response = Vec::new();
for plan in &get_plans_response.list {
let plan_price_response = billing_handler
.get_subscription_plan_prices(&state, plan.subscription_provider_plan_id.clone())
.await?;
response.push(subscription_types::GetPlansResponse {
plan_id: plan.subscription_provider_plan_id.clone(),
name: plan.name.clone(),
description: plan.description.clone(),
price_id: plan_price_response
.list
.into_iter()
.map(subscription_types::SubscriptionPlanPrices::from)
.collect::<Vec<_>>(),
});
}
Ok(ApplicationResponse::Json(response))
}
| {
"crate": "subscriptions",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": true,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 56,
"total_crates": null
} |
fn_clm_subscriptions_to_not_found_response_-1161139873123478555 | clm | function | // Repository: hyperswitch
// Crate: subscriptions
// Module: crates/subscriptions/src/helpers
// Implementation of error_stack::Result<T, storage_impl::StorageError> for StorageErrorExt<T, api_error_response::ApiErrorResponse>
fn to_not_found_response(
self,
not_found_response: api_error_response::ApiErrorResponse,
) -> error_stack::Result<T, api_error_response::ApiErrorResponse> {
self.map_err(|err| {
let new_err = match err.current_context() {
storage_impl::StorageError::ValueNotFound(_) => not_found_response,
storage_impl::StorageError::CustomerRedacted => {
api_error_response::ApiErrorResponse::CustomerRedacted
}
_ => api_error_response::ApiErrorResponse::InternalServerError,
};
err.change_context(new_err)
})
}
| {
"crate": "subscriptions",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 1466,
"total_crates": null
} |
fn_clm_subscriptions_to_duplicate_response_-1161139873123478555 | clm | function | // Repository: hyperswitch
// Crate: subscriptions
// Module: crates/subscriptions/src/helpers
// Implementation of error_stack::Result<T, storage_impl::StorageError> for StorageErrorExt<T, api_error_response::ApiErrorResponse>
fn to_duplicate_response(
self,
duplicate_response: api_error_response::ApiErrorResponse,
) -> error_stack::Result<T, api_error_response::ApiErrorResponse> {
self.map_err(|err| {
let new_err = match err.current_context() {
storage_impl::StorageError::DuplicateValue { .. } => duplicate_response,
_ => api_error_response::ApiErrorResponse::InternalServerError,
};
err.change_context(new_err)
})
}
| {
"crate": "subscriptions",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 131,
"total_crates": null
} |
fn_clm_subscriptions_from_-1539132807351947295 | clm | function | // Repository: hyperswitch
// Crate: subscriptions
// Module: crates/subscriptions/src/state
// Implementation of keymanager::KeyManagerState for From<&SubscriptionState>
fn from(state: &SubscriptionState) -> Self {
state.key_manager_state.clone()
}
| {
"crate": "subscriptions",
"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_subscriptions_event_handler_-1539132807351947295 | clm | function | // Repository: hyperswitch
// Crate: subscriptions
// Module: crates/subscriptions/src/state
// Implementation of SubscriptionState for hyperswitch_interfaces::api_client::ApiClientWrapper
fn event_handler(&self) -> &dyn hyperswitch_interfaces::events::EventHandlerInterface {
self.event_handler.as_ref()
}
| {
"crate": "subscriptions",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 73,
"total_crates": null
} |
fn_clm_subscriptions_get_request_id_-1539132807351947295 | clm | function | // Repository: hyperswitch
// Crate: subscriptions
// Module: crates/subscriptions/src/state
// Implementation of SubscriptionState for hyperswitch_interfaces::api_client::ApiClientWrapper
fn get_request_id(&self) -> Option<RequestId> {
self.api_client.get_request_id()
}
| {
"crate": "subscriptions",
"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_subscriptions_get_request_id_str_-1539132807351947295 | clm | function | // Repository: hyperswitch
// Crate: subscriptions
// Module: crates/subscriptions/src/state
// Implementation of SubscriptionState for hyperswitch_interfaces::api_client::ApiClientWrapper
fn get_request_id_str(&self) -> Option<String> {
self.api_client
.get_request_id()
.map(|req_id| req_id.as_hyphenated().to_string())
}
| {
"crate": "subscriptions",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 19,
"total_crates": null
} |
fn_clm_subscriptions_get_tenant_-1539132807351947295 | clm | function | // Repository: hyperswitch
// Crate: subscriptions
// Module: crates/subscriptions/src/state
// Implementation of SubscriptionState for hyperswitch_interfaces::api_client::ApiClientWrapper
fn get_tenant(&self) -> configs::Tenant {
self.tenant.clone()
}
| {
"crate": "subscriptions",
"file": null,
"file_size": null,
"is_async": false,
"is_pub": false,
"num_enums": null,
"num_structs": null,
"num_tables": null,
"score": 19,
"total_crates": null
} |
fn_clm_subscriptions_incoming_webhook_flow_8917916842878828388 | clm | function | // Repository: hyperswitch
// Crate: subscriptions
// Module: crates/subscriptions/src/webhooks
pub async fn incoming_webhook_flow(
state: SessionState,
merchant_context: merchant_context::MerchantContext,
business_profile: business_profile::Profile,
_webhook_details: api_models::webhooks::IncomingWebhookDetails,
source_verified: bool,
connector_enum: &connector_integration_interface::ConnectorEnum,
request_details: &hyperswitch_interfaces::webhooks::IncomingWebhookRequestDetails<'_>,
event_type: api_models::webhooks::IncomingWebhookEvent,
merchant_connector_account: merchant_connector_account::MerchantConnectorAccount,
) -> CustomResult<WebhookResponseTracker, errors::ApiErrorResponse> {
let billing_connector_mca_id = merchant_connector_account.merchant_connector_id.clone();
// Only process invoice_generated events for MIT payments
if event_type != api_models::webhooks::IncomingWebhookEvent::InvoiceGenerated {
return Ok(WebhookResponseTracker::NoEffect);
}
if !source_verified {
logger::error!("Webhook source verification failed for subscription webhook flow");
return Err(report!(
errors::ApiErrorResponse::WebhookAuthenticationFailed
));
}
let connector_name = connector_enum.id().to_string();
let connector = Connector::from_str(&connector_name)
.change_context(ConnectorError::InvalidConnectorName)
.change_context(errors::ApiErrorResponse::IncorrectConnectorNameGiven)
.attach_printable_lazy(|| format!("unable to parse connector name {connector_name}"))?;
let mit_payment_data = connector_enum
.get_subscription_mit_payment_data(request_details)
.change_context(errors::ApiErrorResponse::WebhookProcessingFailure)
.attach_printable("Failed to extract MIT payment data from subscription webhook")?;
let profile_id = business_profile.get_id().clone();
let profile =
SubscriptionHandler::find_business_profile(&state, &merchant_context, &profile_id)
.await
.attach_printable(
"subscriptions: failed to find business profile in get_subscription",
)?;
let handler = SubscriptionHandler::new(&state, &merchant_context);
let subscription_id = mit_payment_data.subscription_id.clone();
let subscription_with_handler = handler
.find_subscription(subscription_id.clone())
.await
.attach_printable("subscriptions: failed to get subscription entry in get_subscription")?;
let invoice_handler = subscription_with_handler.get_invoice_handler(profile.clone());
let invoice = invoice_handler
.find_invoice_by_subscription_id_connector_invoice_id(
&state,
subscription_id,
mit_payment_data.invoice_id.clone(),
)
.await
.attach_printable(
"subscriptions: failed to get invoice by subscription id and connector invoice id",
)?;
if let Some(invoice) = invoice {
// During CIT payment we would have already created invoice entry with status as PaymentPending or Paid.
// So we skip incoming webhook for the already processed invoice
if invoice.status != InvoiceStatus::InvoiceCreated {
logger::info!("Invoice is already being processed, skipping MIT payment creation");
return Ok(WebhookResponseTracker::NoEffect);
}
}
let payment_method_id = subscription_with_handler
.subscription
.payment_method_id
.clone()
.ok_or(errors::ApiErrorResponse::GenericNotFoundError {
message: "No payment method found for subscription".to_string(),
})
.attach_printable("No payment method found for subscription")?;
logger::info!("Payment method ID found: {}", payment_method_id);
let payment_id = generate_id(consts::ID_LENGTH, "pay");
let payment_id = common_utils::id_type::PaymentId::wrap(payment_id).change_context(
errors::ApiErrorResponse::InvalidDataValue {
field_name: "payment_id",
},
)?;
// Multiple MIT payments for the same invoice_generated event is avoided by having the unique constraint on (subscription_id, connector_invoice_id) in the invoices table
let invoice_entry = invoice_handler
.create_invoice_entry(
&state,
billing_connector_mca_id.clone(),
Some(payment_id),
mit_payment_data.amount_due,
mit_payment_data.currency_code,
InvoiceStatus::PaymentPending,
connector,
None,
Some(mit_payment_data.invoice_id.clone()),
)
.await?;
// Create a sync job for the invoice with generated payment_id before initiating MIT payment creation.
// This ensures that if payment creation call fails, the sync job can still retrieve the payment status
invoice_handler
.create_invoice_sync_job(
&state,
&invoice_entry,
Some(mit_payment_data.invoice_id.clone()),
connector,
)
.await?;
let payment_response = invoice_handler
.create_mit_payment(
&state,
mit_payment_data.amount_due,
mit_payment_data.currency_code,
&payment_method_id.clone(),
)
.await?;
let update_request = invoice::InvoiceUpdateRequest::update_payment_and_status(
payment_response.payment_method_id,
Some(payment_response.payment_id.clone()),
InvoiceStatus::from(payment_response.status),
Some(mit_payment_data.invoice_id.clone()),
);
let _updated_invoice = invoice_handler
.update_invoice(&state, invoice_entry.id.clone(), update_request)
.await?;
Ok(WebhookResponseTracker::NoEffect)
}
| {
"crate": "subscriptions",
"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
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.