text stringlengths 81 477k | file_path stringlengths 22 92 | module stringlengths 13 87 | token_count int64 24 94.8k | has_source_code bool 1 class |
|---|---|---|---|---|
// File: crates/diesel_models/src/query/blocklist.rs
// Module: diesel_models::src::query::blocklist
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
use super::generics;
use crate::{
blocklist::{Blocklist, BlocklistNew},
schema::blocklist::dsl,
PgPooledConn, StorageResult,
};
impl BlocklistNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Blocklist> {
generics::generic_insert(conn, self).await
}
}
impl Blocklist {
pub async fn find_by_merchant_id_fingerprint_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
fingerprint_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::fingerprint_id.eq(fingerprint_id.to_owned())),
)
.await
}
pub async fn list_by_merchant_id_data_kind(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
data_kind: common_enums::BlocklistDataKind,
limit: i64,
offset: i64,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::data_kind.eq(data_kind.to_owned())),
Some(limit),
Some(offset),
Some(dsl::created_at.desc()),
)
.await
}
pub async fn list_by_merchant_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::merchant_id.eq(merchant_id.to_owned()),
None,
None,
Some(dsl::created_at.desc()),
)
.await
}
pub async fn delete_by_merchant_id_fingerprint_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
fingerprint_id: &str,
) -> StorageResult<Self> {
generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::fingerprint_id.eq(fingerprint_id.to_owned())),
)
.await
}
}
| crates/diesel_models/src/query/blocklist.rs | diesel_models::src::query::blocklist | 598 | true |
// File: crates/diesel_models/src/query/user.rs
// Module: diesel_models::src::query::user
use common_utils::pii;
use diesel::{associations::HasTable, ExpressionMethods};
pub mod sample_data;
pub mod theme;
use crate::{
query::generics, schema::users::dsl as users_dsl, user::*, PgPooledConn, StorageResult,
};
impl UserNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<User> {
generics::generic_insert(conn, self).await
}
}
impl User {
pub async fn find_by_user_email(
conn: &PgPooledConn,
user_email: &pii::Email,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
users_dsl::email.eq(user_email.to_owned()),
)
.await
}
pub async fn find_by_user_id(conn: &PgPooledConn, user_id: &str) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
users_dsl::user_id.eq(user_id.to_owned()),
)
.await
}
pub async fn update_by_user_id(
conn: &PgPooledConn,
user_id: &str,
user_update: UserUpdate,
) -> StorageResult<Self> {
generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
_,
_,
_,
>(
conn,
users_dsl::user_id.eq(user_id.to_owned()),
UserUpdateInternal::from(user_update),
)
.await
}
pub async fn update_by_user_email(
conn: &PgPooledConn,
user_email: &pii::Email,
user_update: UserUpdate,
) -> StorageResult<Self> {
generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
_,
_,
_,
>(
conn,
users_dsl::email.eq(user_email.to_owned()),
UserUpdateInternal::from(user_update),
)
.await
}
pub async fn delete_by_user_id(conn: &PgPooledConn, user_id: &str) -> StorageResult<bool> {
generics::generic_delete::<<Self as HasTable>::Table, _>(
conn,
users_dsl::user_id.eq(user_id.to_owned()),
)
.await
}
pub async fn find_users_by_user_ids(
conn: &PgPooledConn,
user_ids: Vec<String>,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
<Self as HasTable>::Table,
_,
<<Self as HasTable>::Table as diesel::Table>::PrimaryKey,
_,
>(conn, users_dsl::user_id.eq_any(user_ids), None, None, None)
.await
}
}
| crates/diesel_models/src/query/user.rs | diesel_models::src::query::user | 651 | true |
// File: crates/diesel_models/src/query/user_role.rs
// Module: diesel_models::src::query::user_role
use async_bb8_diesel::AsyncRunQueryDsl;
use common_utils::id_type;
use diesel::{
associations::HasTable,
debug_query,
pg::Pg,
result::Error as DieselError,
sql_types::{Bool, Nullable},
BoolExpressionMethods, ExpressionMethods, QueryDsl,
};
use error_stack::{report, ResultExt};
use crate::{
enums::{UserRoleVersion, UserStatus},
errors,
query::generics,
schema::user_roles::dsl,
user_role::*,
PgPooledConn, StorageResult,
};
impl UserRoleNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<UserRole> {
generics::generic_insert(conn, self).await
}
}
impl UserRole {
fn check_user_in_lineage(
tenant_id: id_type::TenantId,
org_id: Option<id_type::OrganizationId>,
merchant_id: Option<id_type::MerchantId>,
profile_id: Option<id_type::ProfileId>,
) -> Box<
dyn diesel::BoxableExpression<<Self as HasTable>::Table, Pg, SqlType = Nullable<Bool>>
+ 'static,
> {
// Checking in user roles, for a user in token hierarchy, only one of the relations will be true:
// either tenant level, org level, merchant level, or profile level
// Tenant-level: (tenant_id = ? && org_id = null && merchant_id = null && profile_id = null)
// Org-level: (org_id = ? && merchant_id = null && profile_id = null)
// Merchant-level: (org_id = ? && merchant_id = ? && profile_id = null)
// Profile-level: (org_id = ? && merchant_id = ? && profile_id = ?)
Box::new(
// Tenant-level condition
dsl::tenant_id
.eq(tenant_id.clone())
.and(dsl::org_id.is_null())
.and(dsl::merchant_id.is_null())
.and(dsl::profile_id.is_null())
.or(
// Org-level condition
dsl::tenant_id
.eq(tenant_id.clone())
.and(dsl::org_id.eq(org_id.clone()))
.and(dsl::merchant_id.is_null())
.and(dsl::profile_id.is_null()),
)
.or(
// Merchant-level condition
dsl::tenant_id
.eq(tenant_id.clone())
.and(dsl::org_id.eq(org_id.clone()))
.and(dsl::merchant_id.eq(merchant_id.clone()))
.and(dsl::profile_id.is_null()),
)
.or(
// Profile-level condition
dsl::tenant_id
.eq(tenant_id)
.and(dsl::org_id.eq(org_id))
.and(dsl::merchant_id.eq(merchant_id))
.and(dsl::profile_id.eq(profile_id)),
),
)
}
pub async fn find_by_user_id_tenant_id_org_id_merchant_id_profile_id(
conn: &PgPooledConn,
user_id: String,
tenant_id: id_type::TenantId,
org_id: id_type::OrganizationId,
merchant_id: id_type::MerchantId,
profile_id: id_type::ProfileId,
version: UserRoleVersion,
) -> StorageResult<Self> {
let check_lineage = Self::check_user_in_lineage(
tenant_id,
Some(org_id),
Some(merchant_id),
Some(profile_id),
);
let predicate = dsl::user_id
.eq(user_id)
.and(check_lineage)
.and(dsl::version.eq(version));
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(conn, predicate).await
}
#[allow(clippy::too_many_arguments)]
pub async fn update_by_user_id_tenant_id_org_id_merchant_id_profile_id(
conn: &PgPooledConn,
user_id: String,
tenant_id: id_type::TenantId,
org_id: id_type::OrganizationId,
merchant_id: Option<id_type::MerchantId>,
profile_id: Option<id_type::ProfileId>,
update: UserRoleUpdate,
version: UserRoleVersion,
) -> StorageResult<Self> {
let check_lineage = dsl::tenant_id
.eq(tenant_id.clone())
.and(dsl::org_id.is_null())
.and(dsl::merchant_id.is_null())
.and(dsl::profile_id.is_null())
.or(
// Org-level condition
dsl::tenant_id
.eq(tenant_id.clone())
.and(dsl::org_id.eq(org_id.clone()))
.and(dsl::merchant_id.is_null())
.and(dsl::profile_id.is_null()),
)
.or(
// Merchant-level condition
dsl::tenant_id
.eq(tenant_id.clone())
.and(dsl::org_id.eq(org_id.clone()))
.and(dsl::merchant_id.eq(merchant_id.clone()))
.and(dsl::profile_id.is_null()),
)
.or(
// Profile-level condition
dsl::tenant_id
.eq(tenant_id)
.and(dsl::org_id.eq(org_id))
.and(dsl::merchant_id.eq(merchant_id))
.and(dsl::profile_id.eq(profile_id)),
);
let predicate = dsl::user_id
.eq(user_id)
.and(check_lineage)
.and(dsl::version.eq(version));
generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
UserRoleUpdateInternal,
_,
_,
>(conn, predicate, update.into())
.await
}
pub async fn delete_by_user_id_tenant_id_org_id_merchant_id_profile_id(
conn: &PgPooledConn,
user_id: String,
tenant_id: id_type::TenantId,
org_id: id_type::OrganizationId,
merchant_id: id_type::MerchantId,
profile_id: id_type::ProfileId,
version: UserRoleVersion,
) -> StorageResult<Self> {
let check_lineage = Self::check_user_in_lineage(
tenant_id,
Some(org_id),
Some(merchant_id),
Some(profile_id),
);
let predicate = dsl::user_id
.eq(user_id)
.and(check_lineage)
.and(dsl::version.eq(version));
generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(conn, predicate)
.await
}
#[allow(clippy::too_many_arguments)]
pub async fn generic_user_roles_list_for_user(
conn: &PgPooledConn,
user_id: String,
tenant_id: id_type::TenantId,
org_id: Option<id_type::OrganizationId>,
merchant_id: Option<id_type::MerchantId>,
profile_id: Option<id_type::ProfileId>,
entity_id: Option<String>,
status: Option<UserStatus>,
version: Option<UserRoleVersion>,
limit: Option<u32>,
) -> StorageResult<Vec<Self>> {
let mut query = <Self as HasTable>::table()
.filter(dsl::user_id.eq(user_id).and(dsl::tenant_id.eq(tenant_id)))
.into_boxed();
if let Some(org_id) = org_id {
query = query.filter(dsl::org_id.eq(org_id));
}
if let Some(merchant_id) = merchant_id {
query = query.filter(dsl::merchant_id.eq(merchant_id));
}
if let Some(profile_id) = profile_id {
query = query.filter(dsl::profile_id.eq(profile_id));
}
if let Some(entity_id) = entity_id {
query = query.filter(dsl::entity_id.eq(entity_id));
}
if let Some(version) = version {
query = query.filter(dsl::version.eq(version));
}
if let Some(status) = status {
query = query.filter(dsl::status.eq(status));
}
if let Some(limit) = limit {
query = query.limit(limit.into());
}
router_env::logger::debug!(query = %debug_query::<Pg,_>(&query).to_string());
match generics::db_metrics::track_database_call::<Self, _, _>(
query.get_results_async(conn),
generics::db_metrics::DatabaseOperation::Filter,
)
.await
{
Ok(value) => Ok(value),
Err(err) => match err {
DieselError::NotFound => {
Err(report!(err)).change_context(errors::DatabaseError::NotFound)
}
_ => Err(report!(err)).change_context(errors::DatabaseError::Others),
},
}
}
#[allow(clippy::too_many_arguments)]
pub async fn generic_user_roles_list_for_org_and_extra(
conn: &PgPooledConn,
user_id: Option<String>,
tenant_id: id_type::TenantId,
org_id: id_type::OrganizationId,
merchant_id: Option<id_type::MerchantId>,
profile_id: Option<id_type::ProfileId>,
version: Option<UserRoleVersion>,
limit: Option<u32>,
) -> StorageResult<Vec<Self>> {
let mut query = <Self as HasTable>::table()
.filter(dsl::org_id.eq(org_id).and(dsl::tenant_id.eq(tenant_id)))
.into_boxed();
if let Some(user_id) = user_id {
query = query.filter(dsl::user_id.eq(user_id));
}
if let Some(merchant_id) = merchant_id {
query = query.filter(dsl::merchant_id.eq(merchant_id));
}
if let Some(profile_id) = profile_id {
query = query.filter(dsl::profile_id.eq(profile_id));
}
if let Some(version) = version {
query = query.filter(dsl::version.eq(version));
}
if let Some(limit) = limit {
query = query.limit(limit.into());
}
router_env::logger::debug!(query = %debug_query::<Pg,_>(&query).to_string());
match generics::db_metrics::track_database_call::<Self, _, _>(
query.get_results_async(conn),
generics::db_metrics::DatabaseOperation::Filter,
)
.await
{
Ok(value) => Ok(value),
Err(err) => match err {
DieselError::NotFound => {
Err(report!(err)).change_context(errors::DatabaseError::NotFound)
}
_ => Err(report!(err)).change_context(errors::DatabaseError::Others),
},
}
}
pub async fn list_user_roles_by_user_id_across_tenants(
conn: &PgPooledConn,
user_id: String,
limit: Option<u32>,
) -> StorageResult<Vec<Self>> {
let mut query = <Self as HasTable>::table()
.filter(dsl::user_id.eq(user_id))
.into_boxed();
if let Some(limit) = limit {
query = query.limit(limit.into());
}
router_env::logger::debug!(query = %debug_query::<Pg,_>(&query).to_string());
match generics::db_metrics::track_database_call::<Self, _, _>(
query.get_results_async(conn),
generics::db_metrics::DatabaseOperation::Filter,
)
.await
{
Ok(value) => Ok(value),
Err(err) => match err {
DieselError::NotFound => {
Err(report!(err)).change_context(errors::DatabaseError::NotFound)
}
_ => Err(report!(err)).change_context(errors::DatabaseError::Others),
},
}
}
}
| crates/diesel_models/src/query/user_role.rs | diesel_models::src::query::user_role | 2,554 | true |
// File: crates/diesel_models/src/query/locker_mock_up.rs
// Module: diesel_models::src::query::locker_mock_up
use diesel::{associations::HasTable, ExpressionMethods};
use super::generics;
use crate::{
locker_mock_up::{LockerMockUp, LockerMockUpNew},
schema::locker_mock_up::dsl,
PgPooledConn, StorageResult,
};
impl LockerMockUpNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<LockerMockUp> {
generics::generic_insert(conn, self).await
}
}
impl LockerMockUp {
pub async fn find_by_card_id(conn: &PgPooledConn, card_id: &str) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::card_id.eq(card_id.to_owned()),
)
.await
}
pub async fn delete_by_card_id(conn: &PgPooledConn, card_id: &str) -> StorageResult<Self> {
generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(
conn,
dsl::card_id.eq(card_id.to_owned()),
)
.await
}
}
| crates/diesel_models/src/query/locker_mock_up.rs | diesel_models::src::query::locker_mock_up | 273 | true |
// File: crates/diesel_models/src/query/refund.rs
// Module: diesel_models::src::query::refund
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, Table};
use super::generics;
#[cfg(feature = "v1")]
use crate::schema::refund::dsl;
#[cfg(feature = "v2")]
use crate::schema_v2::refund::dsl;
use crate::{
errors,
refund::{Refund, RefundNew, RefundUpdate, RefundUpdateInternal},
PgPooledConn, StorageResult,
};
impl RefundNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Refund> {
generics::generic_insert(conn, self).await
}
}
#[cfg(feature = "v1")]
impl Refund {
pub async fn update(self, conn: &PgPooledConn, refund: RefundUpdate) -> StorageResult<Self> {
match generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
_,
_,
_,
>(
conn,
dsl::refund_id
.eq(self.refund_id.to_owned())
.and(dsl::merchant_id.eq(self.merchant_id.to_owned())),
RefundUpdateInternal::from(refund),
)
.await
{
Err(error) => match error.current_context() {
errors::DatabaseError::NoFieldsToUpdate => Ok(self),
_ => Err(error),
},
result => result,
}
}
// This is required to be changed for KV.
pub async fn find_by_merchant_id_refund_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
refund_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::refund_id.eq(refund_id.to_owned())),
)
.await
}
pub async fn find_by_merchant_id_connector_refund_id_connector(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
connector_refund_id: &str,
connector: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::connector_refund_id.eq(connector_refund_id.to_owned()))
.and(dsl::connector.eq(connector.to_owned())),
)
.await
}
pub async fn find_by_internal_reference_id_merchant_id(
conn: &PgPooledConn,
internal_reference_id: &str,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::internal_reference_id.eq(internal_reference_id.to_owned())),
)
.await
}
pub async fn find_by_merchant_id_connector_transaction_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
connector_transaction_id: &str,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
<Self as HasTable>::Table,
_,
<<Self as HasTable>::Table as Table>::PrimaryKey,
_,
>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::connector_transaction_id.eq(connector_transaction_id.to_owned())),
None,
None,
None,
)
.await
}
pub async fn find_by_payment_id_merchant_id(
conn: &PgPooledConn,
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
<Self as HasTable>::Table,
_,
<<Self as HasTable>::Table as Table>::PrimaryKey,
_,
>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::payment_id.eq(payment_id.to_owned())),
None,
None,
None,
)
.await
}
}
#[cfg(feature = "v2")]
impl Refund {
pub async fn update_with_id(
self,
conn: &PgPooledConn,
refund: RefundUpdate,
) -> StorageResult<Self> {
match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>(
conn,
self.id.to_owned(),
RefundUpdateInternal::from(refund),
)
.await
{
Err(error) => match error.current_context() {
errors::DatabaseError::NoFieldsToUpdate => Ok(self),
_ => Err(error),
},
result => result,
}
}
pub async fn find_by_global_id(
conn: &PgPooledConn,
id: &common_utils::id_type::GlobalRefundId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::id.eq(id.to_owned()),
)
.await
}
pub async fn find_by_merchant_id_connector_transaction_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
connector_transaction_id: &str,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
<Self as HasTable>::Table,
_,
<<Self as HasTable>::Table as Table>::PrimaryKey,
_,
>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::connector_transaction_id.eq(connector_transaction_id.to_owned())),
None,
None,
None,
)
.await
}
}
| crates/diesel_models/src/query/refund.rs | diesel_models::src::query::refund | 1,355 | true |
// File: crates/diesel_models/src/query/generics.rs
// Module: diesel_models::src::query::generics
use std::fmt::Debug;
use async_bb8_diesel::AsyncRunQueryDsl;
use diesel::{
associations::HasTable,
debug_query,
dsl::{count_star, Find, IsNotNull, Limit},
helper_types::{Filter, IntoBoxed},
insertable::CanInsertInSingleQuery,
pg::{Pg, PgConnection},
query_builder::{
AsChangeset, AsQuery, DeleteStatement, InsertStatement, IntoUpdateTarget, QueryFragment,
QueryId, UpdateStatement,
},
query_dsl::{
methods::{BoxedDsl, FilterDsl, FindDsl, LimitDsl, OffsetDsl, OrderDsl, SelectDsl},
LoadQuery, RunQueryDsl,
},
result::Error as DieselError,
Expression, ExpressionMethods, Insertable, QueryDsl, QuerySource, Table,
};
use error_stack::{report, ResultExt};
use router_env::logger;
use crate::{errors, query::utils::GetPrimaryKey, PgPooledConn, StorageResult};
pub mod db_metrics {
#[derive(Debug)]
pub enum DatabaseOperation {
FindOne,
Filter,
Update,
Insert,
Delete,
DeleteWithResult,
UpdateWithResults,
UpdateOne,
Count,
}
#[inline]
pub async fn track_database_call<T, Fut, U>(future: Fut, operation: DatabaseOperation) -> U
where
Fut: std::future::Future<Output = U>,
{
let start = std::time::Instant::now();
let output = future.await;
let time_elapsed = start.elapsed();
let table_name = std::any::type_name::<T>().rsplit("::").nth(1);
let attributes = router_env::metric_attributes!(
("table", table_name.unwrap_or("undefined")),
("operation", format!("{:?}", operation))
);
crate::metrics::DATABASE_CALLS_COUNT.add(1, attributes);
crate::metrics::DATABASE_CALL_TIME.record(time_elapsed.as_secs_f64(), attributes);
output
}
}
use db_metrics::*;
pub async fn generic_insert<T, V, R>(conn: &PgPooledConn, values: V) -> StorageResult<R>
where
T: HasTable<Table = T> + Table + 'static + Debug,
V: Debug + Insertable<T>,
<T as QuerySource>::FromClause: QueryFragment<Pg> + Debug,
<V as Insertable<T>>::Values: CanInsertInSingleQuery<Pg> + QueryFragment<Pg> + 'static,
InsertStatement<T, <V as Insertable<T>>::Values>:
AsQuery + LoadQuery<'static, PgConnection, R> + Send,
R: Send + 'static,
{
let debug_values = format!("{values:?}");
let query = diesel::insert_into(<T as HasTable>::table()).values(values);
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
match track_database_call::<T, _, _>(query.get_result_async(conn), DatabaseOperation::Insert)
.await
{
Ok(value) => Ok(value),
Err(err) => match err {
DieselError::DatabaseError(diesel::result::DatabaseErrorKind::UniqueViolation, _) => {
Err(report!(err)).change_context(errors::DatabaseError::UniqueViolation)
}
_ => Err(report!(err)).change_context(errors::DatabaseError::Others),
},
}
.attach_printable_lazy(|| format!("Error while inserting {debug_values}"))
}
pub async fn generic_update<T, V, P>(
conn: &PgPooledConn,
predicate: P,
values: V,
) -> StorageResult<usize>
where
T: FilterDsl<P> + HasTable<Table = T> + Table + 'static,
V: AsChangeset<Target = <Filter<T, P> as HasTable>::Table> + Debug,
Filter<T, P>: IntoUpdateTarget,
UpdateStatement<
<Filter<T, P> as HasTable>::Table,
<Filter<T, P> as IntoUpdateTarget>::WhereClause,
<V as AsChangeset>::Changeset,
>: AsQuery + QueryFragment<Pg> + QueryId + Send + 'static,
{
let debug_values = format!("{values:?}");
let query = diesel::update(<T as HasTable>::table().filter(predicate)).set(values);
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
track_database_call::<T, _, _>(query.execute_async(conn), DatabaseOperation::Update)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable_lazy(|| format!("Error while updating {debug_values}"))
}
pub async fn generic_update_with_results<T, V, P, R>(
conn: &PgPooledConn,
predicate: P,
values: V,
) -> StorageResult<Vec<R>>
where
T: FilterDsl<P> + HasTable<Table = T> + Table + 'static,
V: AsChangeset<Target = <Filter<T, P> as HasTable>::Table> + Debug + 'static,
Filter<T, P>: IntoUpdateTarget + 'static,
UpdateStatement<
<Filter<T, P> as HasTable>::Table,
<Filter<T, P> as IntoUpdateTarget>::WhereClause,
<V as AsChangeset>::Changeset,
>: AsQuery + LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + Clone,
R: Send + 'static,
// For cloning query (UpdateStatement)
<Filter<T, P> as HasTable>::Table: Clone,
<Filter<T, P> as IntoUpdateTarget>::WhereClause: Clone,
<V as AsChangeset>::Changeset: Clone,
<<Filter<T, P> as HasTable>::Table as QuerySource>::FromClause: Clone,
{
let debug_values = format!("{values:?}");
let query = diesel::update(<T as HasTable>::table().filter(predicate)).set(values);
match track_database_call::<T, _, _>(
query.to_owned().get_results_async(conn),
DatabaseOperation::UpdateWithResults,
)
.await
{
Ok(result) => {
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
Ok(result)
}
Err(DieselError::QueryBuilderError(_)) => {
Err(report!(errors::DatabaseError::NoFieldsToUpdate))
.attach_printable_lazy(|| format!("Error while updating {debug_values}"))
}
Err(DieselError::NotFound) => Err(report!(errors::DatabaseError::NotFound))
.attach_printable_lazy(|| format!("Error while updating {debug_values}")),
Err(error) => Err(error)
.change_context(errors::DatabaseError::Others)
.attach_printable_lazy(|| format!("Error while updating {debug_values}")),
}
}
pub async fn generic_update_with_unique_predicate_get_result<T, V, P, R>(
conn: &PgPooledConn,
predicate: P,
values: V,
) -> StorageResult<R>
where
T: FilterDsl<P> + HasTable<Table = T> + Table + 'static,
V: AsChangeset<Target = <Filter<T, P> as HasTable>::Table> + Debug + 'static,
Filter<T, P>: IntoUpdateTarget + 'static,
UpdateStatement<
<Filter<T, P> as HasTable>::Table,
<Filter<T, P> as IntoUpdateTarget>::WhereClause,
<V as AsChangeset>::Changeset,
>: AsQuery + LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send,
R: Send + 'static,
// For cloning query (UpdateStatement)
<Filter<T, P> as HasTable>::Table: Clone,
<Filter<T, P> as IntoUpdateTarget>::WhereClause: Clone,
<V as AsChangeset>::Changeset: Clone,
<<Filter<T, P> as HasTable>::Table as QuerySource>::FromClause: Clone,
{
generic_update_with_results::<<T as HasTable>::Table, _, _, _>(conn, predicate, values)
.await
.map(|mut vec_r| {
if vec_r.is_empty() {
Err(errors::DatabaseError::NotFound)
} else if vec_r.len() != 1 {
Err(errors::DatabaseError::Others)
} else {
vec_r.pop().ok_or(errors::DatabaseError::Others)
}
.attach_printable("Maybe not queried using a unique key")
})?
}
pub async fn generic_update_by_id<T, V, Pk, R>(
conn: &PgPooledConn,
id: Pk,
values: V,
) -> StorageResult<R>
where
T: FindDsl<Pk> + HasTable<Table = T> + LimitDsl + Table + 'static,
V: AsChangeset<Target = <Find<T, Pk> as HasTable>::Table> + Debug,
Find<T, Pk>: IntoUpdateTarget + QueryFragment<Pg> + RunQueryDsl<PgConnection> + Send + 'static,
UpdateStatement<
<Find<T, Pk> as HasTable>::Table,
<Find<T, Pk> as IntoUpdateTarget>::WhereClause,
<V as AsChangeset>::Changeset,
>: AsQuery + LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static,
Find<T, Pk>: LimitDsl,
Limit<Find<T, Pk>>: LoadQuery<'static, PgConnection, R>,
R: Send + 'static,
Pk: Clone + Debug,
// For cloning query (UpdateStatement)
<Find<T, Pk> as HasTable>::Table: Clone,
<Find<T, Pk> as IntoUpdateTarget>::WhereClause: Clone,
<V as AsChangeset>::Changeset: Clone,
<<Find<T, Pk> as HasTable>::Table as QuerySource>::FromClause: Clone,
{
let debug_values = format!("{values:?}");
let query = diesel::update(<T as HasTable>::table().find(id.to_owned())).set(values);
match track_database_call::<T, _, _>(
query.to_owned().get_result_async(conn),
DatabaseOperation::UpdateOne,
)
.await
{
Ok(result) => {
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
Ok(result)
}
Err(DieselError::QueryBuilderError(_)) => {
Err(report!(errors::DatabaseError::NoFieldsToUpdate))
.attach_printable_lazy(|| format!("Error while updating by ID {debug_values}"))
}
Err(DieselError::NotFound) => Err(report!(errors::DatabaseError::NotFound))
.attach_printable_lazy(|| format!("Error while updating by ID {debug_values}")),
Err(error) => Err(error)
.change_context(errors::DatabaseError::Others)
.attach_printable_lazy(|| format!("Error while updating by ID {debug_values}")),
}
}
pub async fn generic_delete<T, P>(conn: &PgPooledConn, predicate: P) -> StorageResult<bool>
where
T: FilterDsl<P> + HasTable<Table = T> + Table + 'static,
Filter<T, P>: IntoUpdateTarget,
DeleteStatement<
<Filter<T, P> as HasTable>::Table,
<Filter<T, P> as IntoUpdateTarget>::WhereClause,
>: AsQuery + QueryFragment<Pg> + QueryId + Send + 'static,
{
let query = diesel::delete(<T as HasTable>::table().filter(predicate));
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
track_database_call::<T, _, _>(query.execute_async(conn), DatabaseOperation::Delete)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error while deleting")
.and_then(|result| match result {
n if n > 0 => {
logger::debug!("{n} records deleted");
Ok(true)
}
0 => {
Err(report!(errors::DatabaseError::NotFound).attach_printable("No records deleted"))
}
_ => Ok(true), // n is usize, rustc requires this for exhaustive check
})
}
pub async fn generic_delete_one_with_result<T, P, R>(
conn: &PgPooledConn,
predicate: P,
) -> StorageResult<R>
where
T: FilterDsl<P> + HasTable<Table = T> + Table + 'static,
Filter<T, P>: IntoUpdateTarget,
DeleteStatement<
<Filter<T, P> as HasTable>::Table,
<Filter<T, P> as IntoUpdateTarget>::WhereClause,
>: AsQuery + LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static,
R: Send + Clone + 'static,
{
let query = diesel::delete(<T as HasTable>::table().filter(predicate));
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
track_database_call::<T, _, _>(
query.get_results_async(conn),
DatabaseOperation::DeleteWithResult,
)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error while deleting")
.and_then(|result| {
result.first().cloned().ok_or_else(|| {
report!(errors::DatabaseError::NotFound)
.attach_printable("Object to be deleted does not exist")
})
})
}
async fn generic_find_by_id_core<T, Pk, R>(conn: &PgPooledConn, id: Pk) -> StorageResult<R>
where
T: FindDsl<Pk> + HasTable<Table = T> + LimitDsl + Table + 'static,
Find<T, Pk>: LimitDsl + QueryFragment<Pg> + RunQueryDsl<PgConnection> + Send + 'static,
Limit<Find<T, Pk>>: LoadQuery<'static, PgConnection, R>,
Pk: Clone + Debug,
R: Send + 'static,
{
let query = <T as HasTable>::table().find(id.to_owned());
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
match track_database_call::<T, _, _>(query.first_async(conn), DatabaseOperation::FindOne).await
{
Ok(value) => Ok(value),
Err(err) => match err {
DieselError::NotFound => {
Err(report!(err)).change_context(errors::DatabaseError::NotFound)
}
_ => Err(report!(err)).change_context(errors::DatabaseError::Others),
},
}
.attach_printable_lazy(|| format!("Error finding record by primary key: {id:?}"))
}
pub async fn generic_find_by_id<T, Pk, R>(conn: &PgPooledConn, id: Pk) -> StorageResult<R>
where
T: FindDsl<Pk> + HasTable<Table = T> + LimitDsl + Table + 'static,
Find<T, Pk>: LimitDsl + QueryFragment<Pg> + RunQueryDsl<PgConnection> + Send + 'static,
Limit<Find<T, Pk>>: LoadQuery<'static, PgConnection, R>,
Pk: Clone + Debug,
R: Send + 'static,
{
generic_find_by_id_core::<T, _, _>(conn, id).await
}
pub async fn generic_find_by_id_optional<T, Pk, R>(
conn: &PgPooledConn,
id: Pk,
) -> StorageResult<Option<R>>
where
T: FindDsl<Pk> + HasTable<Table = T> + LimitDsl + Table + 'static,
<T as HasTable>::Table: FindDsl<Pk>,
Find<T, Pk>: LimitDsl + QueryFragment<Pg> + RunQueryDsl<PgConnection> + Send + 'static,
Limit<Find<T, Pk>>: LoadQuery<'static, PgConnection, R>,
Pk: Clone + Debug,
R: Send + 'static,
{
to_optional(generic_find_by_id_core::<T, _, _>(conn, id).await)
}
async fn generic_find_one_core<T, P, R>(conn: &PgPooledConn, predicate: P) -> StorageResult<R>
where
T: FilterDsl<P> + HasTable<Table = T> + Table + 'static,
Filter<T, P>: LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static,
R: Send + 'static,
{
let query = <T as HasTable>::table().filter(predicate);
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
track_database_call::<T, _, _>(query.get_result_async(conn), DatabaseOperation::FindOne)
.await
.map_err(|err| match err {
DieselError::NotFound => report!(err).change_context(errors::DatabaseError::NotFound),
_ => report!(err).change_context(errors::DatabaseError::Others),
})
.attach_printable("Error finding record by predicate")
}
pub async fn generic_find_one<T, P, R>(conn: &PgPooledConn, predicate: P) -> StorageResult<R>
where
T: FilterDsl<P> + HasTable<Table = T> + Table + 'static,
Filter<T, P>: LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static,
R: Send + 'static,
{
generic_find_one_core::<T, _, _>(conn, predicate).await
}
pub async fn generic_find_one_optional<T, P, R>(
conn: &PgPooledConn,
predicate: P,
) -> StorageResult<Option<R>>
where
T: FilterDsl<P> + HasTable<Table = T> + Table + 'static,
Filter<T, P>: LoadQuery<'static, PgConnection, R> + QueryFragment<Pg> + Send + 'static,
R: Send + 'static,
{
to_optional(generic_find_one_core::<T, _, _>(conn, predicate).await)
}
pub(super) async fn generic_filter<T, P, O, R>(
conn: &PgPooledConn,
predicate: P,
limit: Option<i64>,
offset: Option<i64>,
order: Option<O>,
) -> StorageResult<Vec<R>>
where
T: HasTable<Table = T> + Table + BoxedDsl<'static, Pg> + GetPrimaryKey + 'static,
IntoBoxed<'static, T, Pg>: FilterDsl<P, Output = IntoBoxed<'static, T, Pg>>
+ FilterDsl<IsNotNull<T::PK>, Output = IntoBoxed<'static, T, Pg>>
+ LimitDsl<Output = IntoBoxed<'static, T, Pg>>
+ OffsetDsl<Output = IntoBoxed<'static, T, Pg>>
+ OrderDsl<O, Output = IntoBoxed<'static, T, Pg>>
+ LoadQuery<'static, PgConnection, R>
+ QueryFragment<Pg>
+ Send,
O: Expression,
R: Send + 'static,
{
let mut query = T::table().into_boxed();
query = query
.filter(predicate)
.filter(T::table().get_primary_key().is_not_null());
if let Some(limit) = limit {
query = query.limit(limit);
}
if let Some(offset) = offset {
query = query.offset(offset);
}
if let Some(order) = order {
query = query.order(order);
}
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
track_database_call::<T, _, _>(query.get_results_async(conn), DatabaseOperation::Filter)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error filtering records by predicate")
}
pub async fn generic_count<T, P>(conn: &PgPooledConn, predicate: P) -> StorageResult<usize>
where
T: FilterDsl<P> + HasTable<Table = T> + Table + SelectDsl<count_star> + 'static,
Filter<T, P>: SelectDsl<count_star>,
diesel::dsl::Select<Filter<T, P>, count_star>:
LoadQuery<'static, PgConnection, i64> + QueryFragment<Pg> + Send + 'static,
{
let query = <T as HasTable>::table()
.filter(predicate)
.select(count_star());
logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
let count_i64: i64 =
track_database_call::<T, _, _>(query.get_result_async(conn), DatabaseOperation::Count)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error counting records by predicate")?;
let count_usize = usize::try_from(count_i64).map_err(|_| {
report!(errors::DatabaseError::Others).attach_printable("Count value does not fit in usize")
})?;
Ok(count_usize)
}
fn to_optional<T>(arg: StorageResult<T>) -> StorageResult<Option<T>> {
match arg {
Ok(value) => Ok(Some(value)),
Err(err) => match err.current_context() {
errors::DatabaseError::NotFound => Ok(None),
_ => Err(err),
},
}
}
| crates/diesel_models/src/query/generics.rs | diesel_models::src::query::generics | 4,760 | true |
// File: crates/diesel_models/src/query/process_tracker.rs
// Module: diesel_models::src::query::process_tracker
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, Table};
use router_env::{instrument, tracing};
use time::PrimitiveDateTime;
use super::generics;
use crate::{
enums, errors,
process_tracker::{
ProcessTracker, ProcessTrackerNew, ProcessTrackerUpdate, ProcessTrackerUpdateInternal,
},
schema::process_tracker::dsl,
PgPooledConn, StorageResult,
};
impl ProcessTrackerNew {
#[instrument(skip(conn))]
pub async fn insert_process(self, conn: &PgPooledConn) -> StorageResult<ProcessTracker> {
generics::generic_insert(conn, self).await
}
}
impl ProcessTracker {
#[instrument(skip(conn))]
pub async fn update(
self,
conn: &PgPooledConn,
process: ProcessTrackerUpdate,
) -> StorageResult<Self> {
match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>(
conn,
self.id.clone(),
ProcessTrackerUpdateInternal::from(process),
)
.await
{
Err(error) => match error.current_context() {
errors::DatabaseError::NoFieldsToUpdate => Ok(self),
_ => Err(error),
},
result => result,
}
}
#[instrument(skip(conn))]
pub async fn update_process_status_by_ids(
conn: &PgPooledConn,
task_ids: Vec<String>,
task_update: ProcessTrackerUpdate,
) -> StorageResult<usize> {
generics::generic_update::<<Self as HasTable>::Table, _, _>(
conn,
dsl::id.eq_any(task_ids),
ProcessTrackerUpdateInternal::from(task_update),
)
.await
}
#[instrument(skip(conn))]
pub async fn find_process_by_id(conn: &PgPooledConn, id: &str) -> StorageResult<Option<Self>> {
generics::generic_find_by_id_optional::<<Self as HasTable>::Table, _, _>(
conn,
id.to_owned(),
)
.await
}
#[instrument(skip(conn))]
pub async fn find_processes_by_time_status(
conn: &PgPooledConn,
time_lower_limit: PrimitiveDateTime,
time_upper_limit: PrimitiveDateTime,
status: enums::ProcessTrackerStatus,
limit: Option<i64>,
version: enums::ApiVersion,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
<Self as HasTable>::Table,
_,
<<Self as HasTable>::Table as Table>::PrimaryKey,
_,
>(
conn,
dsl::schedule_time
.between(time_lower_limit, time_upper_limit)
.and(dsl::status.eq(status))
.and(dsl::version.eq(version)),
limit,
None,
None,
)
.await
}
#[instrument(skip(conn))]
pub async fn find_processes_to_clean(
conn: &PgPooledConn,
time_lower_limit: PrimitiveDateTime,
time_upper_limit: PrimitiveDateTime,
runner: &str,
limit: usize,
) -> StorageResult<Vec<Self>> {
let mut x: Vec<Self> = generics::generic_filter::<
<Self as HasTable>::Table,
_,
<<Self as HasTable>::Table as Table>::PrimaryKey,
_,
>(
conn,
dsl::schedule_time
.between(time_lower_limit, time_upper_limit)
.and(dsl::status.eq(enums::ProcessTrackerStatus::ProcessStarted))
.and(dsl::runner.eq(runner.to_owned())),
None,
None,
None,
)
.await?;
x.sort_by(|a, b| a.schedule_time.cmp(&b.schedule_time));
x.truncate(limit);
Ok(x)
}
#[instrument(skip(conn))]
pub async fn reinitialize_limbo_processes(
conn: &PgPooledConn,
ids: Vec<String>,
schedule_time: PrimitiveDateTime,
) -> StorageResult<usize> {
generics::generic_update::<<Self as HasTable>::Table, _, _>(
conn,
dsl::status
.eq(enums::ProcessTrackerStatus::ProcessStarted)
.and(dsl::id.eq_any(ids)),
(
dsl::status.eq(enums::ProcessTrackerStatus::Processing),
dsl::schedule_time.eq(schedule_time),
),
)
.await
}
}
| crates/diesel_models/src/query/process_tracker.rs | diesel_models::src::query::process_tracker | 967 | true |
// File: crates/diesel_models/src/query/business_profile.rs
// Module: diesel_models::src::query::business_profile
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, Table};
use super::generics;
#[cfg(feature = "v1")]
use crate::schema::business_profile::dsl::{self, profile_id as dsl_identifier};
#[cfg(feature = "v2")]
use crate::schema_v2::business_profile::dsl::{self, id as dsl_identifier};
use crate::{
business_profile::{Profile, ProfileNew, ProfileUpdateInternal},
errors, PgPooledConn, StorageResult,
};
impl ProfileNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Profile> {
generics::generic_insert(conn, self).await
}
}
impl Profile {
pub async fn update_by_profile_id(
self,
conn: &PgPooledConn,
business_profile: ProfileUpdateInternal,
) -> StorageResult<Self> {
match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>(
conn,
self.get_id().to_owned(),
business_profile,
)
.await
{
Err(error) => match error.current_context() {
errors::DatabaseError::NoFieldsToUpdate => Ok(self),
_ => Err(error),
},
result => result,
}
}
pub async fn find_by_profile_id(
conn: &PgPooledConn,
profile_id: &common_utils::id_type::ProfileId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl_identifier.eq(profile_id.to_owned()),
)
.await
}
pub async fn find_by_merchant_id_profile_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
profile_id: &common_utils::id_type::ProfileId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl_identifier.eq(profile_id.to_owned())),
)
.await
}
pub async fn find_by_profile_name_merchant_id(
conn: &PgPooledConn,
profile_name: &str,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::profile_name
.eq(profile_name.to_owned())
.and(dsl::merchant_id.eq(merchant_id.to_owned())),
)
.await
}
pub async fn list_profile_by_merchant_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
<Self as HasTable>::Table,
_,
<<Self as HasTable>::Table as Table>::PrimaryKey,
_,
>(
conn,
dsl::merchant_id.eq(merchant_id.to_owned()),
None,
None,
None,
)
.await
}
pub async fn delete_by_profile_id_merchant_id(
conn: &PgPooledConn,
profile_id: &common_utils::id_type::ProfileId,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<bool> {
generics::generic_delete::<<Self as HasTable>::Table, _>(
conn,
dsl_identifier
.eq(profile_id.to_owned())
.and(dsl::merchant_id.eq(merchant_id.to_owned())),
)
.await
}
}
| crates/diesel_models/src/query/business_profile.rs | diesel_models::src::query::business_profile | 827 | true |
// File: crates/diesel_models/src/query/payment_link.rs
// Module: diesel_models::src::query::payment_link
use diesel::{associations::HasTable, ExpressionMethods};
use super::generics;
use crate::{
payment_link::{PaymentLink, PaymentLinkNew},
schema::payment_link::dsl,
PgPooledConn, StorageResult,
};
impl PaymentLinkNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<PaymentLink> {
generics::generic_insert(conn, self).await
}
}
impl PaymentLink {
pub async fn find_link_by_payment_link_id(
conn: &PgPooledConn,
payment_link_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::payment_link_id.eq(payment_link_id.to_owned()),
)
.await
}
}
| crates/diesel_models/src/query/payment_link.rs | diesel_models::src::query::payment_link | 202 | true |
// File: crates/diesel_models/src/query/invoice.rs
// Module: diesel_models::src::query::invoice
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
use super::generics;
use crate::{
invoice::{Invoice, InvoiceNew, InvoiceUpdate},
schema::invoice::dsl,
PgPooledConn, StorageResult,
};
impl InvoiceNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Invoice> {
generics::generic_insert(conn, self).await
}
}
impl Invoice {
pub async fn find_invoice_by_id_invoice_id(
conn: &PgPooledConn,
id: String,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::id.eq(id.to_owned()),
)
.await
}
pub async fn update_invoice_entry(
conn: &PgPooledConn,
id: String,
invoice_update: InvoiceUpdate,
) -> StorageResult<Self> {
generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
_,
_,
_,
>(conn, dsl::id.eq(id.to_owned()), invoice_update)
.await
}
pub async fn list_invoices_by_subscription_id(
conn: &PgPooledConn,
subscription_id: String,
limit: Option<i64>,
offset: Option<i64>,
order_by_ascending_order: bool,
) -> StorageResult<Vec<Self>> {
if order_by_ascending_order {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::subscription_id.eq(subscription_id.to_owned()),
limit,
offset,
Some(dsl::created_at.asc()),
)
.await
} else {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::subscription_id.eq(subscription_id.to_owned()),
limit,
offset,
Some(dsl::created_at.desc()),
)
.await
}
}
pub async fn get_invoice_by_subscription_id_connector_invoice_id(
conn: &PgPooledConn,
subscription_id: String,
connector_invoice_id: common_utils::id_type::InvoiceId,
) -> StorageResult<Option<Self>> {
generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>(
conn,
dsl::subscription_id
.eq(subscription_id.to_owned())
.and(dsl::connector_invoice_id.eq(connector_invoice_id.to_owned())),
)
.await
}
}
| crates/diesel_models/src/query/invoice.rs | diesel_models::src::query::invoice | 583 | true |
// File: crates/diesel_models/src/query/generic_link.rs
// Module: diesel_models::src::query::generic_link
use common_utils::{errors, ext_traits::ValueExt, link_utils::GenericLinkStatus};
use diesel::{associations::HasTable, ExpressionMethods};
use error_stack::{report, Report, ResultExt};
use super::generics;
use crate::{
errors as db_errors,
generic_link::{
GenericLink, GenericLinkData, GenericLinkNew, GenericLinkState, GenericLinkUpdateInternal,
PaymentMethodCollectLink, PayoutLink, PayoutLinkUpdate,
},
schema::generic_link::dsl,
PgPooledConn, StorageResult,
};
impl GenericLinkNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<GenericLinkState> {
generics::generic_insert(conn, self)
.await
.and_then(|res: GenericLink| {
GenericLinkState::try_from(res)
.change_context(db_errors::DatabaseError::Others)
.attach_printable("failed to parse generic link data from DB")
})
}
pub async fn insert_pm_collect_link(
self,
conn: &PgPooledConn,
) -> StorageResult<PaymentMethodCollectLink> {
generics::generic_insert(conn, self)
.await
.and_then(|res: GenericLink| {
PaymentMethodCollectLink::try_from(res)
.change_context(db_errors::DatabaseError::Others)
.attach_printable("failed to parse payment method collect link data from DB")
})
}
pub async fn insert_payout_link(self, conn: &PgPooledConn) -> StorageResult<PayoutLink> {
generics::generic_insert(conn, self)
.await
.and_then(|res: GenericLink| {
PayoutLink::try_from(res)
.change_context(db_errors::DatabaseError::Others)
.attach_printable("failed to parse payout link data from DB")
})
}
}
impl GenericLink {
pub async fn find_generic_link_by_link_id(
conn: &PgPooledConn,
link_id: &str,
) -> StorageResult<GenericLinkState> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::link_id.eq(link_id.to_owned()),
)
.await
.and_then(|res: Self| {
GenericLinkState::try_from(res)
.change_context(db_errors::DatabaseError::Others)
.attach_printable("failed to parse generic link data from DB")
})
}
pub async fn find_pm_collect_link_by_link_id(
conn: &PgPooledConn,
link_id: &str,
) -> StorageResult<PaymentMethodCollectLink> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::link_id.eq(link_id.to_owned()),
)
.await
.and_then(|res: Self| {
PaymentMethodCollectLink::try_from(res)
.change_context(db_errors::DatabaseError::Others)
.attach_printable("failed to parse payment method collect link data from DB")
})
}
pub async fn find_payout_link_by_link_id(
conn: &PgPooledConn,
link_id: &str,
) -> StorageResult<PayoutLink> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::link_id.eq(link_id.to_owned()),
)
.await
.and_then(|res: Self| {
PayoutLink::try_from(res)
.change_context(db_errors::DatabaseError::Others)
.attach_printable("failed to parse payout link data from DB")
})
}
}
impl PayoutLink {
pub async fn update_payout_link(
self,
conn: &PgPooledConn,
payout_link_update: PayoutLinkUpdate,
) -> StorageResult<Self> {
generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::link_id.eq(self.link_id.to_owned()),
GenericLinkUpdateInternal::from(payout_link_update),
)
.await
.and_then(|mut payout_links| {
payout_links
.pop()
.ok_or(error_stack::report!(db_errors::DatabaseError::NotFound))
})
.or_else(|error| match error.current_context() {
db_errors::DatabaseError::NoFieldsToUpdate => Ok(self),
_ => Err(error),
})
}
}
impl TryFrom<GenericLink> for GenericLinkState {
type Error = Report<errors::ParsingError>;
fn try_from(db_val: GenericLink) -> Result<Self, Self::Error> {
let link_data = match db_val.link_type {
common_enums::GenericLinkType::PaymentMethodCollect => {
let link_data = db_val
.link_data
.parse_value("PaymentMethodCollectLinkData")?;
GenericLinkData::PaymentMethodCollect(link_data)
}
common_enums::GenericLinkType::PayoutLink => {
let link_data = db_val.link_data.parse_value("PayoutLinkData")?;
GenericLinkData::PayoutLink(link_data)
}
};
Ok(Self {
link_id: db_val.link_id,
primary_reference: db_val.primary_reference,
merchant_id: db_val.merchant_id,
created_at: db_val.created_at,
last_modified_at: db_val.last_modified_at,
expiry: db_val.expiry,
link_data,
link_status: db_val.link_status,
link_type: db_val.link_type,
url: db_val.url,
return_url: db_val.return_url,
})
}
}
impl TryFrom<GenericLink> for PaymentMethodCollectLink {
type Error = Report<errors::ParsingError>;
fn try_from(db_val: GenericLink) -> Result<Self, Self::Error> {
let (link_data, link_status) = match db_val.link_type {
common_enums::GenericLinkType::PaymentMethodCollect => {
let link_data = db_val
.link_data
.parse_value("PaymentMethodCollectLinkData")?;
let link_status = match db_val.link_status {
GenericLinkStatus::PaymentMethodCollect(status) => Ok(status),
_ => Err(report!(errors::ParsingError::EnumParseFailure(
"GenericLinkStatus"
)))
.attach_printable_lazy(|| {
format!(
"Invalid status for PaymentMethodCollectLink - {:?}",
db_val.link_status
)
}),
}?;
(link_data, link_status)
}
_ => Err(report!(errors::ParsingError::UnknownError)).attach_printable_lazy(|| {
format!(
"Invalid link_type for PaymentMethodCollectLink - {}",
db_val.link_type
)
})?,
};
Ok(Self {
link_id: db_val.link_id,
primary_reference: db_val.primary_reference,
merchant_id: db_val.merchant_id,
created_at: db_val.created_at,
last_modified_at: db_val.last_modified_at,
expiry: db_val.expiry,
link_data,
link_status,
link_type: db_val.link_type,
url: db_val.url,
return_url: db_val.return_url,
})
}
}
impl TryFrom<GenericLink> for PayoutLink {
type Error = Report<errors::ParsingError>;
fn try_from(db_val: GenericLink) -> Result<Self, Self::Error> {
let (link_data, link_status) = match db_val.link_type {
common_enums::GenericLinkType::PayoutLink => {
let link_data = db_val.link_data.parse_value("PayoutLinkData")?;
let link_status = match db_val.link_status {
GenericLinkStatus::PayoutLink(status) => Ok(status),
_ => Err(report!(errors::ParsingError::EnumParseFailure(
"GenericLinkStatus"
)))
.attach_printable_lazy(|| {
format!("Invalid status for PayoutLink - {:?}", db_val.link_status)
}),
}?;
(link_data, link_status)
}
_ => Err(report!(errors::ParsingError::UnknownError)).attach_printable_lazy(|| {
format!("Invalid link_type for PayoutLink - {}", db_val.link_type)
})?,
};
Ok(Self {
link_id: db_val.link_id,
primary_reference: common_utils::id_type::PayoutId::try_from(std::borrow::Cow::Owned(
db_val.primary_reference,
))
.change_context(errors::ParsingError::UnknownError)
.attach_printable("Failed to parse PayoutId from primary_reference string")?,
merchant_id: db_val.merchant_id,
created_at: db_val.created_at,
last_modified_at: db_val.last_modified_at,
expiry: db_val.expiry,
link_data,
link_status,
link_type: db_val.link_type,
url: db_val.url,
return_url: db_val.return_url,
})
}
}
| crates/diesel_models/src/query/generic_link.rs | diesel_models::src::query::generic_link | 1,959 | true |
// File: crates/diesel_models/src/query/unified_translations.rs
// Module: diesel_models::src::query::unified_translations
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
use error_stack::report;
use crate::{
errors,
query::generics,
schema::unified_translations::dsl,
unified_translations::{UnifiedTranslationsUpdateInternal, *},
PgPooledConn, StorageResult,
};
impl UnifiedTranslationsNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<UnifiedTranslations> {
generics::generic_insert(conn, self).await
}
}
impl UnifiedTranslations {
pub async fn find_by_unified_code_unified_message_locale(
conn: &PgPooledConn,
unified_code: String,
unified_message: String,
locale: String,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::unified_code
.eq(unified_code)
.and(dsl::unified_message.eq(unified_message))
.and(dsl::locale.eq(locale)),
)
.await
}
pub async fn update_by_unified_code_unified_message_locale(
conn: &PgPooledConn,
unified_code: String,
unified_message: String,
locale: String,
data: UnifiedTranslationsUpdate,
) -> StorageResult<Self> {
generics::generic_update_with_results::<
<Self as HasTable>::Table,
UnifiedTranslationsUpdateInternal,
_,
_,
>(
conn,
dsl::unified_code
.eq(unified_code)
.and(dsl::unified_message.eq(unified_message))
.and(dsl::locale.eq(locale)),
data.into(),
)
.await?
.first()
.cloned()
.ok_or_else(|| {
report!(errors::DatabaseError::NotFound)
.attach_printable("Error while updating unified_translations entry")
})
}
pub async fn delete_by_unified_code_unified_message_locale(
conn: &PgPooledConn,
unified_code: String,
unified_message: String,
locale: String,
) -> StorageResult<bool> {
generics::generic_delete::<<Self as HasTable>::Table, _>(
conn,
dsl::unified_code
.eq(unified_code)
.and(dsl::unified_message.eq(unified_message))
.and(dsl::locale.eq(locale)),
)
.await
}
}
| crates/diesel_models/src/query/unified_translations.rs | diesel_models::src::query::unified_translations | 557 | true |
// File: crates/diesel_models/src/query/api_keys.rs
// Module: diesel_models::src::query::api_keys
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
use super::generics;
use crate::{
api_keys::{ApiKey, ApiKeyNew, ApiKeyUpdate, ApiKeyUpdateInternal, HashedApiKey},
errors,
schema::api_keys::dsl,
PgPooledConn, StorageResult,
};
impl ApiKeyNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<ApiKey> {
generics::generic_insert(conn, self).await
}
}
impl ApiKey {
pub async fn update_by_merchant_id_key_id(
conn: &PgPooledConn,
merchant_id: common_utils::id_type::MerchantId,
key_id: common_utils::id_type::ApiKeyId,
api_key_update: ApiKeyUpdate,
) -> StorageResult<Self> {
match generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
_,
_,
_,
>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::key_id.eq(key_id.to_owned())),
ApiKeyUpdateInternal::from(api_key_update),
)
.await
{
Err(error) => match error.current_context() {
errors::DatabaseError::NotFound => {
Err(error.attach_printable("API key with the given key ID does not exist"))
}
errors::DatabaseError::NoFieldsToUpdate => {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::key_id.eq(key_id.to_owned())),
)
.await
}
_ => Err(error),
},
result => result,
}
}
pub async fn revoke_by_merchant_id_key_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
key_id: &common_utils::id_type::ApiKeyId,
) -> StorageResult<bool> {
generics::generic_delete::<<Self as HasTable>::Table, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::key_id.eq(key_id.to_owned())),
)
.await
}
pub async fn find_optional_by_merchant_id_key_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
key_id: &common_utils::id_type::ApiKeyId,
) -> StorageResult<Option<Self>> {
generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::key_id.eq(key_id.to_owned())),
)
.await
}
pub async fn find_optional_by_hashed_api_key(
conn: &PgPooledConn,
hashed_api_key: HashedApiKey,
) -> StorageResult<Option<Self>> {
generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>(
conn,
dsl::hashed_api_key.eq(hashed_api_key),
)
.await
}
pub async fn find_by_merchant_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
limit: Option<i64>,
offset: Option<i64>,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::merchant_id.eq(merchant_id.to_owned()),
limit,
offset,
Some(dsl::created_at.asc()),
)
.await
}
}
| crates/diesel_models/src/query/api_keys.rs | diesel_models::src::query::api_keys | 848 | true |
// File: crates/diesel_models/src/query/dashboard_metadata.rs
// Module: diesel_models::src::query::dashboard_metadata
use common_utils::id_type;
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
use crate::{
enums,
query::generics,
schema::dashboard_metadata::dsl,
user::dashboard_metadata::{
DashboardMetadata, DashboardMetadataNew, DashboardMetadataUpdate,
DashboardMetadataUpdateInternal,
},
PgPooledConn, StorageResult,
};
impl DashboardMetadataNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<DashboardMetadata> {
generics::generic_insert(conn, self).await
}
}
impl DashboardMetadata {
pub async fn update(
conn: &PgPooledConn,
user_id: Option<String>,
merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
data_key: enums::DashboardMetadata,
dashboard_metadata_update: DashboardMetadataUpdate,
) -> StorageResult<Self> {
let predicate = dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::org_id.eq(org_id.to_owned()))
.and(dsl::data_key.eq(data_key.to_owned()));
if let Some(uid) = user_id {
generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
_,
_,
_,
>(
conn,
predicate.and(dsl::user_id.eq(uid)),
DashboardMetadataUpdateInternal::from(dashboard_metadata_update),
)
.await
} else {
generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
_,
_,
_,
>(
conn,
predicate.and(dsl::user_id.is_null()),
DashboardMetadataUpdateInternal::from(dashboard_metadata_update),
)
.await
}
}
pub async fn find_user_scoped_dashboard_metadata(
conn: &PgPooledConn,
user_id: String,
merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
data_types: Vec<enums::DashboardMetadata>,
) -> StorageResult<Vec<Self>> {
let predicate = dsl::user_id
.eq(user_id)
.and(dsl::merchant_id.eq(merchant_id))
.and(dsl::org_id.eq(org_id))
.and(dsl::data_key.eq_any(data_types));
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
predicate,
None,
None,
Some(dsl::last_modified_at.asc()),
)
.await
}
pub async fn find_merchant_scoped_dashboard_metadata(
conn: &PgPooledConn,
merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
data_types: Vec<enums::DashboardMetadata>,
) -> StorageResult<Vec<Self>> {
let predicate = dsl::merchant_id
.eq(merchant_id)
.and(dsl::org_id.eq(org_id))
.and(dsl::data_key.eq_any(data_types));
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
predicate,
None,
None,
Some(dsl::last_modified_at.asc()),
)
.await
}
pub async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id(
conn: &PgPooledConn,
user_id: String,
merchant_id: id_type::MerchantId,
) -> StorageResult<bool> {
generics::generic_delete::<<Self as HasTable>::Table, _>(
conn,
dsl::user_id
.eq(user_id)
.and(dsl::merchant_id.eq(merchant_id)),
)
.await
}
pub async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key(
conn: &PgPooledConn,
user_id: String,
merchant_id: id_type::MerchantId,
data_key: enums::DashboardMetadata,
) -> StorageResult<Self> {
generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(
conn,
dsl::user_id
.eq(user_id)
.and(dsl::merchant_id.eq(merchant_id))
.and(dsl::data_key.eq(data_key)),
)
.await
}
}
| crates/diesel_models/src/query/dashboard_metadata.rs | diesel_models::src::query::dashboard_metadata | 964 | true |
// File: crates/diesel_models/src/query/customers.rs
// Module: diesel_models::src::query::customers
use common_utils::id_type;
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
use super::generics;
#[cfg(feature = "v1")]
use crate::schema::customers::dsl;
#[cfg(feature = "v2")]
use crate::schema_v2::customers::dsl;
use crate::{
customers::{Customer, CustomerNew, CustomerUpdateInternal},
errors, PgPooledConn, StorageResult,
};
impl CustomerNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Customer> {
generics::generic_insert(conn, self).await
}
}
pub struct CustomerListConstraints {
pub limit: i64,
pub offset: Option<i64>,
pub customer_id: Option<id_type::CustomerId>,
pub time_range: Option<common_utils::types::TimeRange>,
}
impl Customer {
#[cfg(feature = "v2")]
pub async fn update_by_id(
conn: &PgPooledConn,
id: id_type::GlobalCustomerId,
customer: CustomerUpdateInternal,
) -> StorageResult<Self> {
match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>(
conn,
id.clone(),
customer,
)
.await
{
Err(error) => match error.current_context() {
errors::DatabaseError::NoFieldsToUpdate => {
generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, id).await
}
_ => Err(error),
},
result => result,
}
}
#[cfg(feature = "v2")]
pub async fn find_by_global_id(
conn: &PgPooledConn,
id: &id_type::GlobalCustomerId,
) -> StorageResult<Self> {
generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, id.to_owned()).await
}
#[cfg(feature = "v1")]
pub async fn get_customer_count_by_merchant_id_and_constraints(
conn: &PgPooledConn,
merchant_id: &id_type::MerchantId,
customer_list_constraints: CustomerListConstraints,
) -> StorageResult<usize> {
if let Some(customer_id) = customer_list_constraints.customer_id {
let predicate = dsl::merchant_id
.eq(merchant_id.clone())
.and(dsl::customer_id.eq(customer_id));
generics::generic_count::<<Self as HasTable>::Table, _>(conn, predicate).await
} else if let Some(time_range) = customer_list_constraints.time_range {
let start_time = time_range.start_time;
let end_time = time_range
.end_time
.unwrap_or_else(common_utils::date_time::now);
let predicate = dsl::merchant_id
.eq(merchant_id.clone())
.and(dsl::created_at.between(start_time, end_time));
generics::generic_count::<<Self as HasTable>::Table, _>(conn, predicate).await
} else {
generics::generic_count::<<Self as HasTable>::Table, _>(
conn,
dsl::merchant_id.eq(merchant_id.to_owned()),
)
.await
}
}
#[cfg(feature = "v2")]
pub async fn get_customer_count_by_merchant_id_and_constraints(
conn: &PgPooledConn,
merchant_id: &id_type::MerchantId,
customer_list_constraints: CustomerListConstraints,
) -> StorageResult<usize> {
if let Some(customer_id) = customer_list_constraints.customer_id {
let predicate = dsl::merchant_id
.eq(merchant_id.clone())
.and(dsl::merchant_reference_id.eq(customer_id));
generics::generic_count::<<Self as HasTable>::Table, _>(conn, predicate).await
} else if let Some(time_range) = customer_list_constraints.time_range {
let start_time = time_range.start_time;
let end_time = time_range
.end_time
.unwrap_or_else(common_utils::date_time::now);
let predicate = dsl::merchant_id
.eq(merchant_id.clone())
.and(dsl::created_at.between(start_time, end_time));
generics::generic_count::<<Self as HasTable>::Table, _>(conn, predicate).await
} else {
generics::generic_count::<<Self as HasTable>::Table, _>(
conn,
dsl::merchant_id.eq(merchant_id.to_owned()),
)
.await
}
}
#[cfg(feature = "v1")]
pub async fn list_customers_by_merchant_id_and_constraints(
conn: &PgPooledConn,
merchant_id: &id_type::MerchantId,
constraints: CustomerListConstraints,
) -> StorageResult<Vec<Self>> {
if let Some(customer_id) = constraints.customer_id {
let predicate = dsl::merchant_id
.eq(merchant_id.clone())
.and(dsl::customer_id.eq(customer_id));
generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>(
conn,
predicate,
Some(constraints.limit),
constraints.offset,
Some(dsl::created_at),
)
.await
} else if let Some(time_range) = constraints.time_range {
let start_time = time_range.start_time;
let end_time = time_range
.end_time
.unwrap_or_else(common_utils::date_time::now);
let predicate = dsl::merchant_id
.eq(merchant_id.clone())
.and(dsl::created_at.between(start_time, end_time));
generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>(
conn,
predicate,
Some(constraints.limit),
constraints.offset,
Some(dsl::created_at),
)
.await
} else {
let predicate = dsl::merchant_id.eq(merchant_id.clone());
generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>(
conn,
predicate,
Some(constraints.limit),
constraints.offset,
Some(dsl::created_at),
)
.await
}
}
#[cfg(feature = "v2")]
pub async fn list_customers_by_merchant_id_and_constraints(
conn: &PgPooledConn,
merchant_id: &id_type::MerchantId,
constraints: CustomerListConstraints,
) -> StorageResult<Vec<Self>> {
if let Some(customer_id) = constraints.customer_id {
let predicate = dsl::merchant_id
.eq(merchant_id.clone())
.and(dsl::merchant_reference_id.eq(customer_id));
generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>(
conn,
predicate,
Some(constraints.limit),
constraints.offset,
Some(dsl::created_at),
)
.await
} else if let Some(time_range) = constraints.time_range {
let start_time = time_range.start_time;
let end_time = time_range
.end_time
.unwrap_or_else(common_utils::date_time::now);
let predicate = dsl::merchant_id
.eq(merchant_id.clone())
.and(dsl::created_at.between(start_time, end_time));
generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>(
conn,
predicate,
Some(constraints.limit),
constraints.offset,
Some(dsl::created_at),
)
.await
} else {
let predicate = dsl::merchant_id.eq(merchant_id.clone());
generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>(
conn,
predicate,
Some(constraints.limit),
constraints.offset,
Some(dsl::created_at),
)
.await
}
}
#[cfg(feature = "v2")]
pub async fn find_optional_by_merchant_id_merchant_reference_id(
conn: &PgPooledConn,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> StorageResult<Option<Self>> {
generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::merchant_reference_id.eq(customer_id.to_owned())),
)
.await
}
#[cfg(feature = "v1")]
pub async fn find_optional_by_customer_id_merchant_id(
conn: &PgPooledConn,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> StorageResult<Option<Self>> {
generics::generic_find_by_id_optional::<<Self as HasTable>::Table, _, _>(
conn,
(customer_id.to_owned(), merchant_id.to_owned()),
)
.await
}
#[cfg(feature = "v1")]
pub async fn update_by_customer_id_merchant_id(
conn: &PgPooledConn,
customer_id: id_type::CustomerId,
merchant_id: id_type::MerchantId,
customer: CustomerUpdateInternal,
) -> StorageResult<Self> {
match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>(
conn,
(customer_id.clone(), merchant_id.clone()),
customer,
)
.await
{
Err(error) => match error.current_context() {
errors::DatabaseError::NoFieldsToUpdate => {
generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(
conn,
(customer_id, merchant_id),
)
.await
}
_ => Err(error),
},
result => result,
}
}
#[cfg(feature = "v1")]
pub async fn delete_by_customer_id_merchant_id(
conn: &PgPooledConn,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> StorageResult<bool> {
generics::generic_delete::<<Self as HasTable>::Table, _>(
conn,
dsl::customer_id
.eq(customer_id.to_owned())
.and(dsl::merchant_id.eq(merchant_id.to_owned())),
)
.await
}
#[cfg(feature = "v2")]
pub async fn find_by_merchant_reference_id_merchant_id(
conn: &PgPooledConn,
merchant_reference_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::merchant_reference_id.eq(merchant_reference_id.to_owned())),
)
.await
}
#[cfg(feature = "v1")]
pub async fn find_by_customer_id_merchant_id(
conn: &PgPooledConn,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> StorageResult<Self> {
generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(
conn,
(customer_id.to_owned(), merchant_id.to_owned()),
)
.await
}
}
| crates/diesel_models/src/query/customers.rs | diesel_models::src::query::customers | 2,457 | true |
// File: crates/diesel_models/src/query/gsm.rs
// Module: diesel_models::src::query::gsm
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
use error_stack::report;
use crate::{
errors, gsm::*, query::generics, schema::gateway_status_map::dsl, PgPooledConn, StorageResult,
};
impl GatewayStatusMappingNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<GatewayStatusMap> {
generics::generic_insert(conn, self).await
}
}
impl GatewayStatusMap {
pub async fn find(
conn: &PgPooledConn,
connector: String,
flow: String,
sub_flow: String,
code: String,
message: String,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::connector
.eq(connector)
.and(dsl::flow.eq(flow))
.and(dsl::sub_flow.eq(sub_flow))
.and(dsl::code.eq(code))
.and(dsl::message.eq(message)),
)
.await
}
pub async fn retrieve_decision(
conn: &PgPooledConn,
connector: String,
flow: String,
sub_flow: String,
code: String,
message: String,
) -> StorageResult<String> {
Self::find(conn, connector, flow, sub_flow, code, message)
.await
.map(|item| item.decision)
}
pub async fn update(
conn: &PgPooledConn,
connector: String,
flow: String,
sub_flow: String,
code: String,
message: String,
gsm: GatewayStatusMappingUpdate,
) -> StorageResult<Self> {
generics::generic_update_with_results::<
<Self as HasTable>::Table,
GatewayStatusMapperUpdateInternal,
_,
_,
>(
conn,
dsl::connector
.eq(connector)
.and(dsl::flow.eq(flow))
.and(dsl::sub_flow.eq(sub_flow))
.and(dsl::code.eq(code))
.and(dsl::message.eq(message)),
gsm.into(),
)
.await?
.first()
.cloned()
.ok_or_else(|| {
report!(errors::DatabaseError::NotFound)
.attach_printable("Error while updating gsm entry")
})
}
pub async fn delete(
conn: &PgPooledConn,
connector: String,
flow: String,
sub_flow: String,
code: String,
message: String,
) -> StorageResult<bool> {
generics::generic_delete::<<Self as HasTable>::Table, _>(
conn,
dsl::connector
.eq(connector)
.and(dsl::flow.eq(flow))
.and(dsl::sub_flow.eq(sub_flow))
.and(dsl::code.eq(code))
.and(dsl::message.eq(message)),
)
.await
}
}
| crates/diesel_models/src/query/gsm.rs | diesel_models::src::query::gsm | 678 | true |
// File: crates/diesel_models/src/query/connector_response.rs
// Module: diesel_models::src::query::connector_response
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
use router_env::{instrument, logger, tracing};
use super::generics;
use crate::{
connector_response::{
ConnectorResponse, ConnectorResponseNew, ConnectorResponseUpdate,
ConnectorResponseUpdateInternal,
},
errors,
payment_attempt::{PaymentAttempt, PaymentAttemptUpdate, PaymentAttemptUpdateInternal},
schema::{connector_response::dsl, payment_attempt::dsl as pa_dsl},
PgPooledConn, StorageResult,
};
impl ConnectorResponseNew {
#[instrument(skip(conn))]
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<ConnectorResponse> {
let payment_attempt_update = PaymentAttemptUpdate::ConnectorResponse {
authentication_data: self.authentication_data.clone(),
encoded_data: self.encoded_data.clone(),
connector_transaction_id: self.connector_transaction_id.clone(),
connector: self.connector_name.clone(),
updated_by: self.updated_by.clone(),
charge_id: self.charge_id.clone(),
};
let _payment_attempt: Result<PaymentAttempt, _> =
generics::generic_update_with_unique_predicate_get_result::<
<PaymentAttempt as HasTable>::Table,
_,
_,
_,
>(
conn,
pa_dsl::attempt_id
.eq(self.attempt_id.to_owned())
.and(pa_dsl::merchant_id.eq(self.merchant_id.to_owned())),
PaymentAttemptUpdateInternal::from(payment_attempt_update),
)
.await
.inspect_err(|err| {
logger::error!(
"Error while updating payment attempt in connector_response flow {:?}",
err
);
});
generics::generic_insert(conn, self).await
}
}
impl ConnectorResponse {
#[instrument(skip(conn))]
pub async fn update(
self,
conn: &PgPooledConn,
connector_response: ConnectorResponseUpdate,
) -> StorageResult<Self> {
let payment_attempt_update = match connector_response.clone() {
ConnectorResponseUpdate::ResponseUpdate {
connector_transaction_id,
authentication_data,
encoded_data,
connector_name,
charge_id,
updated_by,
} => PaymentAttemptUpdate::ConnectorResponse {
authentication_data,
encoded_data,
connector_transaction_id,
connector: connector_name,
charge_id,
updated_by,
},
ConnectorResponseUpdate::ErrorUpdate {
connector_name,
updated_by,
} => PaymentAttemptUpdate::ConnectorResponse {
authentication_data: None,
encoded_data: None,
connector_transaction_id: None,
connector: connector_name,
charge_id: None,
updated_by,
},
};
let _payment_attempt: Result<PaymentAttempt, _> =
generics::generic_update_with_unique_predicate_get_result::<
<PaymentAttempt as HasTable>::Table,
_,
_,
_,
>(
conn,
pa_dsl::attempt_id
.eq(self.attempt_id.to_owned())
.and(pa_dsl::merchant_id.eq(self.merchant_id.to_owned())),
PaymentAttemptUpdateInternal::from(payment_attempt_update),
)
.await
.inspect_err(|err| {
logger::error!(
"Error while updating payment attempt in connector_response flow {:?}",
err
);
});
let connector_response_result =
match generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
_,
_,
_,
>(
conn,
dsl::merchant_id
.eq(self.merchant_id.clone())
.and(dsl::payment_id.eq(self.payment_id.clone()))
.and(dsl::attempt_id.eq(self.attempt_id.clone())),
ConnectorResponseUpdateInternal::from(connector_response),
)
.await
{
Err(error) => match error.current_context() {
errors::DatabaseError::NoFieldsToUpdate => Ok(self),
_ => Err(error),
},
result => result,
};
connector_response_result
}
#[instrument(skip(conn))]
pub async fn find_by_payment_id_merchant_id_attempt_id(
conn: &PgPooledConn,
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
attempt_id: &str,
) -> StorageResult<Self> {
let connector_response: Self =
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id.eq(merchant_id.to_owned()).and(
dsl::payment_id
.eq(payment_id.to_owned())
.and(dsl::attempt_id.eq(attempt_id.to_owned())),
),
)
.await?;
match generics::generic_find_one::<<PaymentAttempt as HasTable>::Table, _, _>(
conn,
pa_dsl::payment_id.eq(payment_id.to_owned()).and(
pa_dsl::merchant_id
.eq(merchant_id.to_owned())
.and(pa_dsl::attempt_id.eq(attempt_id.to_owned())),
),
)
.await
{
Ok::<PaymentAttempt, _>(payment_attempt) => {
if payment_attempt.authentication_data != connector_response.authentication_data {
logger::error!(
"Not Equal pa_authentication_data : {:?}, cr_authentication_data: {:?} ",
payment_attempt.authentication_data,
connector_response.authentication_data
);
}
if payment_attempt.encoded_data != connector_response.encoded_data {
logger::error!(
"Not Equal pa_encoded_data : {:?}, cr_encoded_data: {:?} ",
payment_attempt.encoded_data,
connector_response.encoded_data
);
}
if payment_attempt.connector_transaction_id
!= connector_response.connector_transaction_id
{
logger::error!(
"Not Equal pa_connector_transaction_id : {:?}, cr_connector_transaction_id: {:?} ",
payment_attempt.connector_transaction_id,
connector_response.connector_transaction_id
);
}
if payment_attempt.connector != connector_response.connector_name {
logger::error!(
"Not Equal pa_connector : {:?}, cr_connector_name: {:?} ",
payment_attempt.connector,
connector_response.connector_name
);
}
}
Err(err) => {
logger::error!(
"Error while finding payment attempt in connector_response flow {:?}",
err
);
}
}
Ok(connector_response)
}
}
| crates/diesel_models/src/query/connector_response.rs | diesel_models::src::query::connector_response | 1,383 | true |
// File: crates/diesel_models/src/query/hyperswitch_ai_interaction.rs
// Module: diesel_models::src::query::hyperswitch_ai_interaction
use diesel::{associations::HasTable, ExpressionMethods};
use crate::{
hyperswitch_ai_interaction::{HyperswitchAiInteraction, HyperswitchAiInteractionNew},
query::generics,
schema::hyperswitch_ai_interaction::dsl,
PgPooledConn, StorageResult,
};
impl HyperswitchAiInteractionNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<HyperswitchAiInteraction> {
generics::generic_insert(conn, self).await
}
}
impl HyperswitchAiInteraction {
pub async fn filter_by_optional_merchant_id(
conn: &PgPooledConn,
merchant_id: Option<&common_utils::id_type::MerchantId>,
limit: i64,
offset: i64,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::merchant_id.eq(merchant_id.cloned()),
Some(limit),
Some(offset),
Some(dsl::created_at.desc()),
)
.await
}
}
| crates/diesel_models/src/query/hyperswitch_ai_interaction.rs | diesel_models::src::query::hyperswitch_ai_interaction | 268 | true |
// File: crates/diesel_models/src/query/payout_attempt.rs
// Module: diesel_models::src::query::payout_attempt
use std::collections::HashSet;
use async_bb8_diesel::AsyncRunQueryDsl;
use diesel::{
associations::HasTable,
query_dsl::methods::{DistinctDsl, FilterDsl, SelectDsl},
BoolExpressionMethods, ExpressionMethods,
};
use error_stack::{report, ResultExt};
use super::generics;
use crate::{
enums,
errors::DatabaseError,
payout_attempt::{
PayoutAttempt, PayoutAttemptNew, PayoutAttemptUpdate, PayoutAttemptUpdateInternal,
},
schema::{payout_attempt::dsl, payouts as payout_dsl},
Payouts, PgPooledConn, StorageResult,
};
impl PayoutAttemptNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<PayoutAttempt> {
generics::generic_insert(conn, self).await
}
}
impl PayoutAttempt {
pub async fn update_with_attempt_id(
self,
conn: &PgPooledConn,
payout_attempt_update: PayoutAttemptUpdate,
) -> StorageResult<Self> {
match generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
_,
_,
_,
>(
conn,
dsl::payout_attempt_id
.eq(self.payout_attempt_id.to_owned())
.and(dsl::merchant_id.eq(self.merchant_id.to_owned())),
PayoutAttemptUpdateInternal::from(payout_attempt_update),
)
.await
{
Err(error) => match error.current_context() {
DatabaseError::NoFieldsToUpdate => Ok(self),
_ => Err(error),
},
result => result,
}
}
pub async fn find_by_merchant_id_payout_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
payout_id: &common_utils::id_type::PayoutId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::payout_id.eq(payout_id.to_owned())),
)
.await
}
pub async fn find_by_merchant_id_payout_attempt_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
payout_attempt_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::payout_attempt_id.eq(payout_attempt_id.to_owned())),
)
.await
}
pub async fn find_by_merchant_id_connector_payout_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
connector_payout_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::connector_payout_id.eq(connector_payout_id.to_owned())),
)
.await
}
pub async fn find_by_merchant_id_merchant_order_reference_id(
conn: &PgPooledConn,
merchant_id_input: &common_utils::id_type::MerchantId,
merchant_order_reference_id_input: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id.eq(merchant_id_input.to_owned()).and(
dsl::merchant_order_reference_id.eq(merchant_order_reference_id_input.to_owned()),
),
)
.await
}
pub async fn update_by_merchant_id_payout_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
payout_id: &common_utils::id_type::PayoutId,
payout: PayoutAttemptUpdate,
) -> StorageResult<Self> {
generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::payout_id.eq(payout_id.to_owned())),
PayoutAttemptUpdateInternal::from(payout),
)
.await?
.first()
.cloned()
.ok_or_else(|| {
report!(DatabaseError::NotFound).attach_printable("Error while updating payout")
})
}
pub async fn update_by_merchant_id_payout_attempt_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
payout_attempt_id: &str,
payout: PayoutAttemptUpdate,
) -> StorageResult<Self> {
generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::payout_attempt_id.eq(payout_attempt_id.to_owned())),
PayoutAttemptUpdateInternal::from(payout),
)
.await?
.first()
.cloned()
.ok_or_else(|| {
report!(DatabaseError::NotFound).attach_printable("Error while updating payout")
})
}
pub async fn get_filters_for_payouts(
conn: &PgPooledConn,
payouts: &[Payouts],
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<(
Vec<String>,
Vec<enums::Currency>,
Vec<enums::PayoutStatus>,
Vec<enums::PayoutType>,
)> {
let active_attempt_ids = payouts
.iter()
.map(|payout| {
format!(
"{}_{}",
payout.payout_id.get_string_repr(),
payout.attempt_count.clone()
)
})
.collect::<Vec<String>>();
let active_payout_ids = payouts
.iter()
.map(|payout| payout.payout_id.to_owned())
.collect::<Vec<common_utils::id_type::PayoutId>>();
let filter = <Self as HasTable>::table()
.filter(dsl::merchant_id.eq(merchant_id.to_owned()))
.filter(dsl::payout_attempt_id.eq_any(active_attempt_ids));
let payouts_filter = <Payouts as HasTable>::table()
.filter(payout_dsl::merchant_id.eq(merchant_id.to_owned()))
.filter(payout_dsl::payout_id.eq_any(active_payout_ids));
let payout_status: Vec<enums::PayoutStatus> = payouts
.iter()
.map(|payout| payout.status)
.collect::<HashSet<enums::PayoutStatus>>()
.into_iter()
.collect();
let filter_connector = filter
.clone()
.select(dsl::connector)
.distinct()
.get_results_async::<Option<String>>(conn)
.await
.change_context(DatabaseError::Others)
.attach_printable("Error filtering records by connector")?
.into_iter()
.flatten()
.collect::<Vec<String>>();
let filter_currency = payouts_filter
.clone()
.select(payout_dsl::destination_currency)
.distinct()
.get_results_async::<enums::Currency>(conn)
.await
.change_context(DatabaseError::Others)
.attach_printable("Error filtering records by currency")?
.into_iter()
.collect::<Vec<enums::Currency>>();
let filter_payout_method = payouts_filter
.clone()
.select(payout_dsl::payout_type)
.distinct()
.get_results_async::<Option<enums::PayoutType>>(conn)
.await
.change_context(DatabaseError::Others)
.attach_printable("Error filtering records by payout type")?
.into_iter()
.flatten()
.collect::<Vec<enums::PayoutType>>();
Ok((
filter_connector,
filter_currency,
payout_status,
filter_payout_method,
))
}
}
| crates/diesel_models/src/query/payout_attempt.rs | diesel_models::src::query::payout_attempt | 1,813 | true |
// File: crates/diesel_models/src/query/authentication.rs
// Module: diesel_models::src::query::authentication
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
use super::generics;
use crate::{
authentication::{
Authentication, AuthenticationNew, AuthenticationUpdate, AuthenticationUpdateInternal,
},
errors,
schema::authentication::dsl,
PgPooledConn, StorageResult,
};
impl AuthenticationNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Authentication> {
generics::generic_insert(conn, self).await
}
}
impl Authentication {
pub async fn update_by_merchant_id_authentication_id(
conn: &PgPooledConn,
merchant_id: common_utils::id_type::MerchantId,
authentication_id: common_utils::id_type::AuthenticationId,
authorization_update: AuthenticationUpdate,
) -> StorageResult<Self> {
match generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
_,
_,
_,
>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::authentication_id.eq(authentication_id.to_owned())),
AuthenticationUpdateInternal::from(authorization_update),
)
.await
{
Err(error) => match error.current_context() {
errors::DatabaseError::NotFound => Err(error.attach_printable(
"Authentication with the given Authentication ID does not exist",
)),
errors::DatabaseError::NoFieldsToUpdate => {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::authentication_id.eq(authentication_id.to_owned())),
)
.await
}
_ => Err(error),
},
result => result,
}
}
pub async fn find_by_merchant_id_authentication_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
authentication_id: &common_utils::id_type::AuthenticationId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::authentication_id.eq(authentication_id.to_owned())),
)
.await
}
pub async fn find_authentication_by_merchant_id_connector_authentication_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
connector_authentication_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::connector_authentication_id.eq(connector_authentication_id.to_owned())),
)
.await
}
}
| crates/diesel_models/src/query/authentication.rs | diesel_models::src::query::authentication | 638 | true |
// File: crates/diesel_models/src/query/merchant_key_store.rs
// Module: diesel_models::src::query::merchant_key_store
use diesel::{associations::HasTable, ExpressionMethods};
use super::generics;
use crate::{
merchant_key_store::{MerchantKeyStore, MerchantKeyStoreNew},
schema::merchant_key_store::dsl,
PgPooledConn, StorageResult,
};
impl MerchantKeyStoreNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<MerchantKeyStore> {
generics::generic_insert(conn, self).await
}
}
impl MerchantKeyStore {
pub async fn find_by_merchant_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id.eq(merchant_id.to_owned()),
)
.await
}
pub async fn delete_by_merchant_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<bool> {
generics::generic_delete::<<Self as HasTable>::Table, _>(
conn,
dsl::merchant_id.eq(merchant_id.to_owned()),
)
.await
}
pub async fn list_multiple_key_stores(
conn: &PgPooledConn,
merchant_ids: Vec<common_utils::id_type::MerchantId>,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
<Self as HasTable>::Table,
_,
<<Self as HasTable>::Table as diesel::Table>::PrimaryKey,
_,
>(
conn,
dsl::merchant_id.eq_any(merchant_ids),
None,
None,
None,
)
.await
}
pub async fn list_all_key_stores(
conn: &PgPooledConn,
from: u32,
limit: u32,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
<Self as HasTable>::Table,
_,
<<Self as HasTable>::Table as diesel::Table>::PrimaryKey,
_,
>(
conn,
dsl::merchant_id.ne_all(vec!["".to_string()]),
Some(limit.into()),
Some(from.into()),
None,
)
.await
}
}
| crates/diesel_models/src/query/merchant_key_store.rs | diesel_models::src::query::merchant_key_store | 534 | true |
// File: crates/diesel_models/src/query/user_key_store.rs
// Module: diesel_models::src::query::user_key_store
use diesel::{associations::HasTable, ExpressionMethods};
use super::generics;
use crate::{
schema::user_key_store::dsl,
user_key_store::{UserKeyStore, UserKeyStoreNew},
PgPooledConn, StorageResult,
};
impl UserKeyStoreNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<UserKeyStore> {
generics::generic_insert(conn, self).await
}
}
impl UserKeyStore {
pub async fn get_all_user_key_stores(
conn: &PgPooledConn,
from: u32,
limit: u32,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
<Self as HasTable>::Table,
_,
<<Self as HasTable>::Table as diesel::Table>::PrimaryKey,
_,
>(
conn,
dsl::user_id.ne_all(vec!["".to_string()]),
Some(limit.into()),
Some(from.into()),
None,
)
.await
}
pub async fn find_by_user_id(conn: &PgPooledConn, user_id: &str) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::user_id.eq(user_id.to_owned()),
)
.await
}
}
| crates/diesel_models/src/query/user_key_store.rs | diesel_models::src::query::user_key_store | 323 | true |
// File: crates/diesel_models/src/query/reverse_lookup.rs
// Module: diesel_models::src::query::reverse_lookup
use diesel::{associations::HasTable, ExpressionMethods};
use super::generics;
use crate::{
reverse_lookup::{ReverseLookup, ReverseLookupNew},
schema::reverse_lookup::dsl,
PgPooledConn, StorageResult,
};
impl ReverseLookupNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<ReverseLookup> {
generics::generic_insert(conn, self).await
}
pub async fn batch_insert(
reverse_lookups: Vec<Self>,
conn: &PgPooledConn,
) -> StorageResult<()> {
generics::generic_insert::<_, _, ReverseLookup>(conn, reverse_lookups).await?;
Ok(())
}
}
impl ReverseLookup {
pub async fn find_by_lookup_id(lookup_id: &str, conn: &PgPooledConn) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::lookup_id.eq(lookup_id.to_owned()),
)
.await
}
}
| crates/diesel_models/src/query/reverse_lookup.rs | diesel_models::src::query::reverse_lookup | 250 | true |
// File: crates/diesel_models/src/query/relay.rs
// Module: diesel_models::src::query::relay
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
use super::generics;
use crate::{
errors,
relay::{Relay, RelayNew, RelayUpdateInternal},
schema::relay::dsl,
PgPooledConn, StorageResult,
};
impl RelayNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Relay> {
generics::generic_insert(conn, self).await
}
}
impl Relay {
pub async fn update(
self,
conn: &PgPooledConn,
relay: RelayUpdateInternal,
) -> StorageResult<Self> {
match generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
_,
_,
_,
>(conn, dsl::id.eq(self.id.to_owned()), relay)
.await
{
Err(error) => match error.current_context() {
errors::DatabaseError::NoFieldsToUpdate => Ok(self),
_ => Err(error),
},
result => result,
}
}
pub async fn find_by_id(
conn: &PgPooledConn,
id: &common_utils::id_type::RelayId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::id.eq(id.to_owned()),
)
.await
}
pub async fn find_by_profile_id_connector_reference_id(
conn: &PgPooledConn,
profile_id: &common_utils::id_type::ProfileId,
connector_reference_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::profile_id
.eq(profile_id.to_owned())
.and(dsl::connector_reference_id.eq(connector_reference_id.to_owned())),
)
.await
}
}
| crates/diesel_models/src/query/relay.rs | diesel_models::src::query::relay | 445 | true |
// File: crates/diesel_models/src/query/mandate.rs
// Module: diesel_models::src::query::mandate
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, Table};
use error_stack::report;
use super::generics;
use crate::{errors, mandate::*, schema::mandate::dsl, PgPooledConn, StorageResult};
impl MandateNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Mandate> {
generics::generic_insert(conn, self).await
}
}
impl Mandate {
pub async fn find_by_merchant_id_mandate_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
mandate_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::mandate_id.eq(mandate_id.to_owned())),
)
.await
}
pub async fn find_by_merchant_id_connector_mandate_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
connector_mandate_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::connector_mandate_id.eq(connector_mandate_id.to_owned())),
)
.await
}
pub async fn find_by_merchant_id_customer_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
customer_id: &common_utils::id_type::CustomerId,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
<Self as HasTable>::Table,
_,
<<Self as HasTable>::Table as Table>::PrimaryKey,
_,
>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::customer_id.eq(customer_id.to_owned())),
None,
None,
None,
)
.await
}
//Fix this function once V2 mandate is schema is being built
#[cfg(feature = "v2")]
pub async fn find_by_global_customer_id(
conn: &PgPooledConn,
customer_id: &common_utils::id_type::GlobalCustomerId,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
<Self as HasTable>::Table,
_,
<<Self as HasTable>::Table as Table>::PrimaryKey,
_,
>(
conn,
dsl::customer_id.eq(customer_id.to_owned()),
None,
None,
None,
)
.await
}
pub async fn update_by_merchant_id_mandate_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
mandate_id: &str,
mandate: MandateUpdateInternal,
) -> StorageResult<Self> {
generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::mandate_id.eq(mandate_id.to_owned())),
mandate,
)
.await?
.first()
.cloned()
.ok_or_else(|| {
report!(errors::DatabaseError::NotFound)
.attach_printable("Error while updating mandate")
})
}
}
| crates/diesel_models/src/query/mandate.rs | diesel_models::src::query::mandate | 810 | true |
// File: crates/diesel_models/src/query/utils.rs
// Module: diesel_models::src::query::utils
use diesel;
use crate::{schema, schema_v2};
/// This trait will return a single column as primary key even in case of composite primary key.
///
/// In case of composite key, it will return the column that is used as local unique.
pub(super) trait GetPrimaryKey: diesel::Table {
type PK: diesel::ExpressionMethods;
fn get_primary_key(&self) -> Self::PK;
}
/// This trait must be implemented for all composite keys.
pub(super) trait CompositeKey {
type UK;
/// It will return the local unique key of the composite key.
///
/// If `(attempt_id, merchant_id)` is the composite key for `payment_attempt` table, then it will return `attempt_id`.
fn get_local_unique_key(&self) -> Self::UK;
}
/// implementation of `CompositeKey` trait for all the composite keys must be done here.
mod composite_key {
use super::{schema, schema_v2, CompositeKey};
impl CompositeKey for <schema::payment_attempt::table as diesel::Table>::PrimaryKey {
type UK = schema::payment_attempt::dsl::attempt_id;
fn get_local_unique_key(&self) -> Self::UK {
self.0
}
}
impl CompositeKey for <schema::refund::table as diesel::Table>::PrimaryKey {
type UK = schema::refund::dsl::refund_id;
fn get_local_unique_key(&self) -> Self::UK {
self.1
}
}
impl CompositeKey for <schema::customers::table as diesel::Table>::PrimaryKey {
type UK = schema::customers::dsl::customer_id;
fn get_local_unique_key(&self) -> Self::UK {
self.0
}
}
impl CompositeKey for <schema::blocklist::table as diesel::Table>::PrimaryKey {
type UK = schema::blocklist::dsl::fingerprint_id;
fn get_local_unique_key(&self) -> Self::UK {
self.1
}
}
impl CompositeKey for <schema::incremental_authorization::table as diesel::Table>::PrimaryKey {
type UK = schema::incremental_authorization::dsl::authorization_id;
fn get_local_unique_key(&self) -> Self::UK {
self.0
}
}
impl CompositeKey for <schema::hyperswitch_ai_interaction::table as diesel::Table>::PrimaryKey {
type UK = schema::hyperswitch_ai_interaction::dsl::id;
fn get_local_unique_key(&self) -> Self::UK {
self.0
}
}
impl CompositeKey for <schema_v2::incremental_authorization::table as diesel::Table>::PrimaryKey {
type UK = schema_v2::incremental_authorization::dsl::authorization_id;
fn get_local_unique_key(&self) -> Self::UK {
self.0
}
}
impl CompositeKey for <schema_v2::blocklist::table as diesel::Table>::PrimaryKey {
type UK = schema_v2::blocklist::dsl::fingerprint_id;
fn get_local_unique_key(&self) -> Self::UK {
self.1
}
}
}
/// This macro will implement the `GetPrimaryKey` trait for all the tables with single primary key.
macro_rules! impl_get_primary_key {
($($table:ty),*) => {
$(
impl GetPrimaryKey for $table
{
type PK = <$table as diesel::Table>::PrimaryKey;
fn get_primary_key(&self) -> Self::PK {
<Self as diesel::Table>::primary_key(self)
}
}
)*
};
}
impl_get_primary_key!(
// v1 tables
schema::dashboard_metadata::table,
schema::merchant_connector_account::table,
schema::merchant_key_store::table,
schema::payment_methods::table,
schema::user_authentication_methods::table,
schema::user_key_store::table,
schema::users::table,
schema::api_keys::table,
schema::captures::table,
schema::business_profile::table,
schema::mandate::dsl::mandate,
schema::dispute::table,
schema::events::table,
schema::merchant_account::table,
schema::process_tracker::table,
schema::invoice::table,
// v2 tables
schema_v2::dashboard_metadata::table,
schema_v2::merchant_connector_account::table,
schema_v2::merchant_key_store::table,
schema_v2::payment_methods::table,
schema_v2::user_authentication_methods::table,
schema_v2::user_key_store::table,
schema_v2::users::table,
schema_v2::api_keys::table,
schema_v2::captures::table,
schema_v2::business_profile::table,
schema_v2::mandate::table,
schema_v2::dispute::table,
schema_v2::events::table,
schema_v2::merchant_account::table,
schema_v2::process_tracker::table,
schema_v2::refund::table,
schema_v2::customers::table,
schema_v2::payment_attempt::table
);
/// This macro will implement the `GetPrimaryKey` trait for all the tables with composite key.
macro_rules! impl_get_primary_key_for_composite {
($($table:ty),*) => {
$(
impl GetPrimaryKey for $table
{
type PK = <<$table as diesel::Table>::PrimaryKey as CompositeKey>::UK;
fn get_primary_key(&self) -> Self::PK {
<Self as diesel::Table>::primary_key(self).get_local_unique_key()
}
}
)*
};
}
impl_get_primary_key_for_composite!(
schema::payment_attempt::table,
schema::refund::table,
schema::customers::table,
schema::blocklist::table,
schema::incremental_authorization::table,
schema::hyperswitch_ai_interaction::table,
schema_v2::incremental_authorization::table,
schema_v2::blocklist::table
);
| crates/diesel_models/src/query/utils.rs | diesel_models::src::query::utils | 1,315 | true |
// File: crates/diesel_models/src/query/payment_intent.rs
// Module: diesel_models::src::query::payment_intent
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
use super::generics;
#[cfg(feature = "v1")]
use crate::schema::payment_intent::dsl;
#[cfg(feature = "v2")]
use crate::schema_v2::payment_intent::dsl;
use crate::{
errors,
payment_intent::{self, PaymentIntent, PaymentIntentNew},
PgPooledConn, StorageResult,
};
impl PaymentIntentNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<PaymentIntent> {
generics::generic_insert(conn, self).await
}
}
impl PaymentIntent {
#[cfg(feature = "v2")]
pub async fn update(
self,
conn: &PgPooledConn,
payment_intent_update: payment_intent::PaymentIntentUpdateInternal,
) -> StorageResult<Self> {
match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>(
conn,
self.id.to_owned(),
payment_intent_update,
)
.await
{
Err(error) => match error.current_context() {
errors::DatabaseError::NoFieldsToUpdate => Ok(self),
_ => Err(error),
},
Ok(payment_intent) => Ok(payment_intent),
}
}
#[cfg(feature = "v2")]
pub async fn find_by_global_id(
conn: &PgPooledConn,
id: &common_utils::id_type::GlobalPaymentId,
) -> StorageResult<Self> {
generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, id.to_owned()).await
}
#[cfg(feature = "v1")]
pub async fn update(
self,
conn: &PgPooledConn,
payment_intent: payment_intent::PaymentIntentUpdate,
) -> StorageResult<Self> {
match generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::payment_id
.eq(self.payment_id.to_owned())
.and(dsl::merchant_id.eq(self.merchant_id.to_owned())),
payment_intent::PaymentIntentUpdateInternal::from(payment_intent),
)
.await
{
Err(error) => match error.current_context() {
errors::DatabaseError::NoFieldsToUpdate => Ok(self),
_ => Err(error),
},
Ok(mut payment_intents) => payment_intents
.pop()
.ok_or(error_stack::report!(errors::DatabaseError::NotFound)),
}
}
#[cfg(feature = "v2")]
pub async fn find_by_merchant_reference_id_merchant_id(
conn: &PgPooledConn,
merchant_reference_id: &str,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::merchant_reference_id.eq(merchant_reference_id.to_owned())),
)
.await
}
// This query should be removed in the future because direct queries to the intent table without an intent ID are not allowed.
// In an active-active setup, a lookup table should be implemented, and the merchant reference ID will serve as the idempotency key.
#[cfg(feature = "v2")]
pub async fn find_by_merchant_reference_id_profile_id(
conn: &PgPooledConn,
merchant_reference_id: &common_utils::id_type::PaymentReferenceId,
profile_id: &common_utils::id_type::ProfileId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::profile_id
.eq(profile_id.to_owned())
.and(dsl::merchant_reference_id.eq(merchant_reference_id.to_owned())),
)
.await
}
#[cfg(feature = "v1")]
pub async fn find_by_payment_id_merchant_id(
conn: &PgPooledConn,
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::payment_id.eq(payment_id.to_owned())),
)
.await
}
#[cfg(feature = "v2")]
pub async fn find_optional_by_merchant_reference_id_merchant_id(
conn: &PgPooledConn,
merchant_reference_id: &str,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Option<Self>> {
generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::merchant_reference_id.eq(merchant_reference_id.to_owned())),
)
.await
}
#[cfg(feature = "v1")]
pub async fn find_optional_by_payment_id_merchant_id(
conn: &PgPooledConn,
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Option<Self>> {
generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::payment_id.eq(payment_id.to_owned())),
)
.await
}
}
| crates/diesel_models/src/query/payment_intent.rs | diesel_models::src::query::payment_intent | 1,257 | true |
// File: crates/diesel_models/src/query/capture.rs
// Module: diesel_models::src::query::capture
use common_utils::types::ConnectorTransactionIdTrait;
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
use super::generics;
use crate::{
capture::{Capture, CaptureNew, CaptureUpdate, CaptureUpdateInternal},
errors,
schema::captures::dsl,
PgPooledConn, StorageResult,
};
impl CaptureNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Capture> {
generics::generic_insert(conn, self).await
}
}
impl Capture {
pub async fn find_by_capture_id(conn: &PgPooledConn, capture_id: &str) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::capture_id.eq(capture_id.to_owned()),
)
.await
}
pub async fn update_with_capture_id(
self,
conn: &PgPooledConn,
capture: CaptureUpdate,
) -> StorageResult<Self> {
match generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
_,
_,
_,
>(
conn,
dsl::capture_id.eq(self.capture_id.to_owned()),
CaptureUpdateInternal::from(capture),
)
.await
{
Err(error) => match error.current_context() {
errors::DatabaseError::NoFieldsToUpdate => Ok(self),
_ => Err(error),
},
result => result,
}
}
pub async fn find_all_by_merchant_id_payment_id_authorized_attempt_id(
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
authorized_attempt_id: &str,
conn: &PgPooledConn,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::authorized_attempt_id
.eq(authorized_attempt_id.to_owned())
.and(dsl::merchant_id.eq(merchant_id.to_owned()))
.and(dsl::payment_id.eq(payment_id.to_owned())),
None,
None,
Some(dsl::created_at.asc()),
)
.await
}
}
impl ConnectorTransactionIdTrait for Capture {
fn get_optional_connector_transaction_id(&self) -> Option<&String> {
match self
.connector_capture_id
.as_ref()
.map(|capture_id| capture_id.get_txn_id(self.processor_capture_data.as_ref()))
.transpose()
{
Ok(capture_id) => capture_id,
// In case hashed data is missing from DB, use the hashed ID as connector transaction ID
Err(_) => self
.connector_capture_id
.as_ref()
.map(|txn_id| txn_id.get_id()),
}
}
}
| crates/diesel_models/src/query/capture.rs | diesel_models::src::query::capture | 643 | true |
// File: crates/diesel_models/src/query/authorization.rs
// Module: diesel_models::src::query::authorization
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
use super::generics;
use crate::{
authorization::{
Authorization, AuthorizationNew, AuthorizationUpdate, AuthorizationUpdateInternal,
},
errors,
schema::incremental_authorization::dsl,
PgPooledConn, StorageResult,
};
impl AuthorizationNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Authorization> {
generics::generic_insert(conn, self).await
}
}
impl Authorization {
pub async fn update_by_merchant_id_authorization_id(
conn: &PgPooledConn,
merchant_id: common_utils::id_type::MerchantId,
authorization_id: String,
authorization_update: AuthorizationUpdate,
) -> StorageResult<Self> {
match generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
_,
_,
_,
>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::authorization_id.eq(authorization_id.to_owned())),
AuthorizationUpdateInternal::from(authorization_update),
)
.await
{
Err(error) => match error.current_context() {
errors::DatabaseError::NotFound => Err(error.attach_printable(
"Authorization with the given Authorization ID does not exist",
)),
errors::DatabaseError::NoFieldsToUpdate => {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::authorization_id.eq(authorization_id.to_owned())),
)
.await
}
_ => Err(error),
},
result => result,
}
}
pub async fn find_by_merchant_id_payment_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::payment_id.eq(payment_id.to_owned())),
None,
None,
Some(dsl::created_at.asc()),
)
.await
}
}
| crates/diesel_models/src/query/authorization.rs | diesel_models::src::query::authorization | 536 | true |
// File: crates/diesel_models/src/query/user_authentication_method.rs
// Module: diesel_models::src::query::user_authentication_method
use diesel::{associations::HasTable, ExpressionMethods};
use crate::{
query::generics, schema::user_authentication_methods::dsl, user_authentication_method::*,
PgPooledConn, StorageResult,
};
impl UserAuthenticationMethodNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<UserAuthenticationMethod> {
generics::generic_insert(conn, self).await
}
}
impl UserAuthenticationMethod {
pub async fn get_user_authentication_method_by_id(
conn: &PgPooledConn,
id: &str,
) -> StorageResult<Self> {
generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(conn, id.to_owned()).await
}
pub async fn list_user_authentication_methods_for_auth_id(
conn: &PgPooledConn,
auth_id: &str,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::auth_id.eq(auth_id.to_owned()),
None,
None,
Some(dsl::last_modified_at.asc()),
)
.await
}
pub async fn list_user_authentication_methods_for_owner_id(
conn: &PgPooledConn,
owner_id: &str,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::owner_id.eq(owner_id.to_owned()),
None,
None,
Some(dsl::last_modified_at.asc()),
)
.await
}
pub async fn update_user_authentication_method(
conn: &PgPooledConn,
id: &str,
user_authentication_method_update: UserAuthenticationMethodUpdate,
) -> StorageResult<Self> {
generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
_,
_,
_,
>(
conn,
dsl::id.eq(id.to_owned()),
OrgAuthenticationMethodUpdateInternal::from(user_authentication_method_update),
)
.await
}
pub async fn list_user_authentication_methods_for_email_domain(
conn: &PgPooledConn,
email_domain: &str,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::email_domain.eq(email_domain.to_owned()),
None,
None,
Some(dsl::last_modified_at.asc()),
)
.await
}
}
| crates/diesel_models/src/query/user_authentication_method.rs | diesel_models::src::query::user_authentication_method | 576 | true |
// File: crates/diesel_models/src/query/file.rs
// Module: diesel_models::src::query::file
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
use super::generics;
use crate::{
errors,
file::{FileMetadata, FileMetadataNew, FileMetadataUpdate, FileMetadataUpdateInternal},
schema::file_metadata::dsl,
PgPooledConn, StorageResult,
};
impl FileMetadataNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<FileMetadata> {
generics::generic_insert(conn, self).await
}
}
impl FileMetadata {
pub async fn find_by_merchant_id_file_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
file_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::file_id.eq(file_id.to_owned())),
)
.await
}
pub async fn delete_by_merchant_id_file_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
file_id: &str,
) -> StorageResult<bool> {
generics::generic_delete::<<Self as HasTable>::Table, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::file_id.eq(file_id.to_owned())),
)
.await
}
pub async fn update(
self,
conn: &PgPooledConn,
file_metadata: FileMetadataUpdate,
) -> StorageResult<Self> {
match generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
_,
_,
_,
>(
conn,
dsl::file_id.eq(self.file_id.to_owned()),
FileMetadataUpdateInternal::from(file_metadata),
)
.await
{
Err(error) => match error.current_context() {
errors::DatabaseError::NoFieldsToUpdate => Ok(self),
_ => Err(error),
},
result => result,
}
}
}
| crates/diesel_models/src/query/file.rs | diesel_models::src::query::file | 494 | true |
// File: crates/diesel_models/src/query/user/theme.rs
// Module: diesel_models::src::query::user::theme
use async_bb8_diesel::AsyncRunQueryDsl;
use common_utils::types::user::ThemeLineage;
use diesel::{
associations::HasTable,
debug_query,
pg::Pg,
result::Error as DieselError,
sql_types::{Bool, Nullable},
BoolExpressionMethods, ExpressionMethods, NullableExpressionMethods, QueryDsl,
};
use error_stack::{report, ResultExt};
use router_env::logger;
use crate::{
errors::DatabaseError,
query::generics::{
self,
db_metrics::{track_database_call, DatabaseOperation},
},
schema::themes::dsl,
user::theme::{Theme, ThemeNew, ThemeUpdate, ThemeUpdateInternal},
PgPooledConn, StorageResult,
};
impl ThemeNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Theme> {
generics::generic_insert(conn, self).await
}
}
impl Theme {
fn lineage_filter(
lineage: ThemeLineage,
) -> Box<
dyn diesel::BoxableExpression<<Self as HasTable>::Table, Pg, SqlType = Nullable<Bool>>
+ 'static,
> {
match lineage {
ThemeLineage::Tenant { tenant_id } => Box::new(
dsl::tenant_id
.eq(tenant_id)
.and(dsl::org_id.is_null())
.and(dsl::merchant_id.is_null())
.and(dsl::profile_id.is_null())
.nullable(),
),
ThemeLineage::Organization { tenant_id, org_id } => Box::new(
dsl::tenant_id
.eq(tenant_id)
.and(dsl::org_id.eq(org_id))
.and(dsl::merchant_id.is_null())
.and(dsl::profile_id.is_null()),
),
ThemeLineage::Merchant {
tenant_id,
org_id,
merchant_id,
} => Box::new(
dsl::tenant_id
.eq(tenant_id)
.and(dsl::org_id.eq(org_id))
.and(dsl::merchant_id.eq(merchant_id))
.and(dsl::profile_id.is_null()),
),
ThemeLineage::Profile {
tenant_id,
org_id,
merchant_id,
profile_id,
} => Box::new(
dsl::tenant_id
.eq(tenant_id)
.and(dsl::org_id.eq(org_id))
.and(dsl::merchant_id.eq(merchant_id))
.and(dsl::profile_id.eq(profile_id)),
),
}
}
/// Matches all themes that belong to the specified hierarchy level or below
fn lineage_hierarchy_filter(
lineage: ThemeLineage,
) -> Box<
dyn diesel::BoxableExpression<<Self as HasTable>::Table, Pg, SqlType = Nullable<Bool>>
+ 'static,
> {
match lineage {
ThemeLineage::Tenant { tenant_id } => Box::new(dsl::tenant_id.eq(tenant_id).nullable()),
ThemeLineage::Organization { tenant_id, org_id } => Box::new(
dsl::tenant_id
.eq(tenant_id)
.and(dsl::org_id.eq(org_id))
.nullable(),
),
ThemeLineage::Merchant {
tenant_id,
org_id,
merchant_id,
} => Box::new(
dsl::tenant_id
.eq(tenant_id)
.and(dsl::org_id.eq(org_id))
.and(dsl::merchant_id.eq(merchant_id))
.nullable(),
),
ThemeLineage::Profile {
tenant_id,
org_id,
merchant_id,
profile_id,
} => Box::new(
dsl::tenant_id
.eq(tenant_id)
.and(dsl::org_id.eq(org_id))
.and(dsl::merchant_id.eq(merchant_id))
.and(dsl::profile_id.eq(profile_id))
.nullable(),
),
}
}
pub async fn find_by_theme_id(conn: &PgPooledConn, theme_id: String) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::theme_id.eq(theme_id),
)
.await
}
pub async fn find_most_specific_theme_in_lineage(
conn: &PgPooledConn,
lineage: ThemeLineage,
) -> StorageResult<Self> {
let query = <Self as HasTable>::table().into_boxed();
let query =
lineage
.get_same_and_higher_lineages()
.into_iter()
.fold(query, |mut query, lineage| {
query = query.or_filter(Self::lineage_filter(lineage));
query
});
logger::debug!(query = %debug_query::<Pg,_>(&query).to_string());
let data: Vec<Self> = match track_database_call::<Self, _, _>(
query.get_results_async(conn),
DatabaseOperation::Filter,
)
.await
{
Ok(value) => Ok(value),
Err(err) => match err {
DieselError::NotFound => Err(report!(err)).change_context(DatabaseError::NotFound),
_ => Err(report!(err)).change_context(DatabaseError::Others),
},
}?;
data.into_iter()
.min_by_key(|theme| theme.entity_type)
.ok_or(report!(DatabaseError::NotFound))
}
pub async fn find_by_lineage(
conn: &PgPooledConn,
lineage: ThemeLineage,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
Self::lineage_filter(lineage),
)
.await
}
pub async fn update_by_theme_id(
conn: &PgPooledConn,
theme_id: String,
update: ThemeUpdate,
) -> StorageResult<Self> {
let update_internal: ThemeUpdateInternal = update.into();
let predicate = dsl::theme_id.eq(theme_id);
generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
_,
_,
_,
>(conn, predicate, update_internal)
.await
}
pub async fn delete_by_theme_id_and_lineage(
conn: &PgPooledConn,
theme_id: String,
lineage: ThemeLineage,
) -> StorageResult<Self> {
generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(
conn,
dsl::theme_id
.eq(theme_id)
.and(Self::lineage_filter(lineage)),
)
.await
}
pub async fn delete_by_theme_id(conn: &PgPooledConn, theme_id: String) -> StorageResult<Self> {
generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(
conn,
dsl::theme_id.eq(theme_id),
)
.await
}
/// Finds all themes that match the specified lineage hierarchy.
pub async fn find_all_by_lineage_hierarchy(
conn: &PgPooledConn,
lineage: ThemeLineage,
) -> StorageResult<Vec<Self>> {
let filter = Self::lineage_hierarchy_filter(lineage);
let query = <Self as HasTable>::table().filter(filter).into_boxed();
logger::debug!(query = %debug_query::<Pg,_>(&query).to_string());
match track_database_call::<Self, _, _>(
query.get_results_async(conn),
DatabaseOperation::Filter,
)
.await
{
Ok(themes) => Ok(themes),
Err(err) => match err {
DieselError::NotFound => Err(report!(err)).change_context(DatabaseError::NotFound),
_ => Err(report!(err)).change_context(DatabaseError::Others),
},
}
}
}
| crates/diesel_models/src/query/user/theme.rs | diesel_models::src::query::user::theme | 1,733 | true |
// File: crates/diesel_models/src/query/user/sample_data.rs
// Module: diesel_models::src::query::user::sample_data
use async_bb8_diesel::AsyncRunQueryDsl;
use diesel::{associations::HasTable, debug_query, ExpressionMethods, TextExpressionMethods};
use error_stack::ResultExt;
use router_env::logger;
#[cfg(feature = "v1")]
use crate::schema::{
payment_attempt::dsl as payment_attempt_dsl, payment_intent::dsl as payment_intent_dsl,
refund::dsl as refund_dsl,
};
#[cfg(feature = "v2")]
use crate::schema_v2::{
payment_attempt::dsl as payment_attempt_dsl, payment_intent::dsl as payment_intent_dsl,
refund::dsl as refund_dsl,
};
use crate::{
errors, schema::dispute::dsl as dispute_dsl, Dispute, DisputeNew, PaymentAttempt,
PaymentIntent, PgPooledConn, Refund, RefundNew, StorageResult,
};
#[cfg(feature = "v1")]
use crate::{user, PaymentIntentNew};
#[cfg(feature = "v1")]
pub async fn insert_payment_intents(
conn: &PgPooledConn,
batch: Vec<PaymentIntentNew>,
) -> StorageResult<Vec<PaymentIntent>> {
let query = diesel::insert_into(<PaymentIntent>::table()).values(batch);
logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string());
query
.get_results_async(conn)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error while inserting payment intents")
}
#[cfg(feature = "v1")]
pub async fn insert_payment_attempts(
conn: &PgPooledConn,
batch: Vec<user::sample_data::PaymentAttemptBatchNew>,
) -> StorageResult<Vec<PaymentAttempt>> {
let query = diesel::insert_into(<PaymentAttempt>::table()).values(batch);
logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string());
query
.get_results_async(conn)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error while inserting payment attempts")
}
pub async fn insert_refunds(
conn: &PgPooledConn,
batch: Vec<RefundNew>,
) -> StorageResult<Vec<Refund>> {
let query = diesel::insert_into(<Refund>::table()).values(batch);
logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string());
query
.get_results_async(conn)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error while inserting refunds")
}
pub async fn insert_disputes(
conn: &PgPooledConn,
batch: Vec<DisputeNew>,
) -> StorageResult<Vec<Dispute>> {
let query = diesel::insert_into(<Dispute>::table()).values(batch);
logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string());
query
.get_results_async(conn)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error while inserting disputes")
}
#[cfg(feature = "v1")]
pub async fn delete_payment_intents(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Vec<PaymentIntent>> {
let query = diesel::delete(<PaymentIntent>::table())
.filter(payment_intent_dsl::merchant_id.eq(merchant_id.to_owned()))
.filter(payment_intent_dsl::payment_id.like("test_%"));
logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string());
query
.get_results_async(conn)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error while deleting payment intents")
.and_then(|result| match result.len() {
n if n > 0 => {
logger::debug!("{n} records deleted");
Ok(result)
}
0 => Err(error_stack::report!(errors::DatabaseError::NotFound)
.attach_printable("No records deleted")),
_ => Ok(result),
})
}
#[cfg(feature = "v2")]
pub async fn delete_payment_intents(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Vec<PaymentIntent>> {
let query = diesel::delete(<PaymentIntent>::table())
.filter(payment_intent_dsl::merchant_id.eq(merchant_id.to_owned()))
.filter(payment_intent_dsl::merchant_reference_id.like("test_%"));
logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string());
query
.get_results_async(conn)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error while deleting payment intents")
.and_then(|result| match result.len() {
n if n > 0 => {
logger::debug!("{n} records deleted");
Ok(result)
}
0 => Err(error_stack::report!(errors::DatabaseError::NotFound)
.attach_printable("No records deleted")),
_ => Ok(result),
})
}
pub async fn delete_payment_attempts(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Vec<PaymentAttempt>> {
let query = diesel::delete(<PaymentAttempt>::table())
.filter(payment_attempt_dsl::merchant_id.eq(merchant_id.to_owned()))
.filter(payment_attempt_dsl::payment_id.like("test_%"));
logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string());
query
.get_results_async(conn)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error while deleting payment attempts")
.and_then(|result| match result.len() {
n if n > 0 => {
logger::debug!("{n} records deleted");
Ok(result)
}
0 => Err(error_stack::report!(errors::DatabaseError::NotFound)
.attach_printable("No records deleted")),
_ => Ok(result),
})
}
pub async fn delete_refunds(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Vec<Refund>> {
let query = diesel::delete(<Refund>::table())
.filter(refund_dsl::merchant_id.eq(merchant_id.to_owned()))
.filter(refund_dsl::payment_id.like("test_%"));
logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string());
query
.get_results_async(conn)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error while deleting refunds")
.and_then(|result| match result.len() {
n if n > 0 => {
logger::debug!("{n} records deleted");
Ok(result)
}
0 => Err(error_stack::report!(errors::DatabaseError::NotFound)
.attach_printable("No records deleted")),
_ => Ok(result),
})
}
pub async fn delete_disputes(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Vec<Dispute>> {
let query = diesel::delete(<Dispute>::table())
.filter(dispute_dsl::merchant_id.eq(merchant_id.to_owned()))
.filter(dispute_dsl::dispute_id.like("test_%"));
logger::debug!(query = %debug_query::<diesel::pg::Pg,_>(&query).to_string());
query
.get_results_async(conn)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Error while deleting disputes")
.and_then(|result| match result.len() {
n if n > 0 => {
logger::debug!("{n} records deleted");
Ok(result)
}
0 => Err(error_stack::report!(errors::DatabaseError::NotFound)
.attach_printable("No records deleted")),
_ => Ok(result),
})
}
| crates/diesel_models/src/query/user/sample_data.rs | diesel_models::src::query::user::sample_data | 1,820 | true |
// File: crates/scheduler/src/flow.rs
// Module: scheduler::src::flow
#[derive(Copy, Clone, Debug, strum::Display, strum::EnumString)]
#[strum(serialize_all = "snake_case")]
pub enum SchedulerFlow {
Producer,
Consumer,
Cleaner,
}
| crates/scheduler/src/flow.rs | scheduler::src::flow | 66 | true |
// File: crates/scheduler/src/producer.rs
// Module: scheduler::src::producer
use std::sync::Arc;
use common_utils::{errors::CustomResult, id_type};
use diesel_models::enums::ProcessTrackerStatus;
use error_stack::{report, ResultExt};
use router_env::{
instrument,
tracing::{self, Instrument},
};
use time::Duration;
use tokio::sync::mpsc;
use super::{
env::logger::{self, debug, error, warn},
metrics,
};
use crate::{
configs::settings::SchedulerSettings, errors, flow::SchedulerFlow,
scheduler::SchedulerInterface, utils::*, SchedulerAppState, SchedulerSessionState,
};
#[instrument(skip_all)]
pub async fn start_producer<T, U, F>(
state: &T,
scheduler_settings: Arc<SchedulerSettings>,
(tx, mut rx): (mpsc::Sender<()>, mpsc::Receiver<()>),
app_state_to_session_state: F,
) -> CustomResult<(), errors::ProcessTrackerError>
where
F: Fn(&T, &id_type::TenantId) -> CustomResult<U, errors::ProcessTrackerError>,
T: SchedulerAppState,
U: SchedulerSessionState,
{
use std::time::Duration;
use rand::distributions::{Distribution, Uniform};
let mut rng = rand::thread_rng();
// TODO: this can be removed once rand-0.9 is released
// reference - https://github.com/rust-random/rand/issues/1326#issuecomment-1635331942
#[allow(unknown_lints)]
#[allow(clippy::unnecessary_fallible_conversions)]
let timeout = Uniform::try_from(0..=scheduler_settings.loop_interval)
.change_context(errors::ProcessTrackerError::ConfigurationError)?;
tokio::time::sleep(Duration::from_millis(timeout.sample(&mut rng))).await;
let mut interval =
tokio::time::interval(Duration::from_millis(scheduler_settings.loop_interval));
let mut shutdown_interval = tokio::time::interval(Duration::from_millis(
scheduler_settings.graceful_shutdown_interval,
));
let signal = common_utils::signals::get_allowed_signals()
.map_err(|error| {
logger::error!("Signal Handler Error: {:?}", error);
errors::ProcessTrackerError::ConfigurationError
})
.attach_printable("Failed while creating a signals handler")?;
let handle = signal.handle();
let task_handle =
tokio::spawn(common_utils::signals::signal_handler(signal, tx).in_current_span());
loop {
match rx.try_recv() {
Err(mpsc::error::TryRecvError::Empty) => {
interval.tick().await;
let tenants = state.get_tenants();
for tenant in tenants {
let session_state = app_state_to_session_state(state, &tenant)?;
match run_producer_flow(&session_state, &scheduler_settings).await {
Ok(_) => (),
Err(error) => {
// Intentionally not propagating error to caller.
// Any errors that occur in the producer flow must be handled here only, as
// this is the topmost level function which is concerned with the producer flow.
error!(?error);
}
}
}
}
Ok(()) | Err(mpsc::error::TryRecvError::Disconnected) => {
logger::debug!("Awaiting shutdown!");
rx.close();
shutdown_interval.tick().await;
logger::info!("Terminating producer");
break;
}
}
}
handle.close();
task_handle
.await
.change_context(errors::ProcessTrackerError::UnexpectedFlow)?;
Ok(())
}
#[instrument(skip_all)]
pub async fn run_producer_flow<T>(
state: &T,
settings: &SchedulerSettings,
) -> CustomResult<(), errors::ProcessTrackerError>
where
T: SchedulerSessionState,
{
lock_acquire_release::<_, _, _>(state.get_db().as_scheduler(), settings, move || async {
let tasks = fetch_producer_tasks(state.get_db().as_scheduler(), settings).await?;
debug!("Producer count of tasks {}", tasks.len());
// [#268]: Allow task based segregation of tasks
divide_and_append_tasks(
state.get_db().as_scheduler(),
SchedulerFlow::Producer,
tasks,
settings,
)
.await?;
Ok(())
})
.await?;
Ok(())
}
#[instrument(skip_all)]
pub async fn fetch_producer_tasks(
db: &dyn SchedulerInterface,
conf: &SchedulerSettings,
) -> CustomResult<Vec<storage::ProcessTracker>, errors::ProcessTrackerError> {
let upper = conf.producer.upper_fetch_limit;
let lower = conf.producer.lower_fetch_limit;
let now = common_utils::date_time::now();
// Add these to validations
let time_upper_limit = now.checked_add(Duration::seconds(upper)).ok_or_else(|| {
report!(errors::ProcessTrackerError::ConfigurationError)
.attach_printable("Error obtaining upper limit to fetch producer tasks")
})?;
let time_lower_limit = now.checked_sub(Duration::seconds(lower)).ok_or_else(|| {
report!(errors::ProcessTrackerError::ConfigurationError)
.attach_printable("Error obtaining lower limit to fetch producer tasks")
})?;
let mut new_tasks = db
.find_processes_by_time_status(
time_lower_limit,
time_upper_limit,
ProcessTrackerStatus::New,
None,
)
.await
.change_context(errors::ProcessTrackerError::ProcessFetchingFailed)?;
let mut pending_tasks = db
.find_processes_by_time_status(
time_lower_limit,
time_upper_limit,
ProcessTrackerStatus::Pending,
None,
)
.await
.change_context(errors::ProcessTrackerError::ProcessFetchingFailed)?;
if new_tasks.is_empty() {
warn!("No new tasks found for producer to schedule");
}
if pending_tasks.is_empty() {
warn!("No pending tasks found for producer to schedule");
}
new_tasks.append(&mut pending_tasks);
// Safety: Assuming we won't deal with more than `u64::MAX` tasks at once
#[allow(clippy::as_conversions)]
metrics::TASKS_PICKED_COUNT.add(new_tasks.len() as u64, &[]);
Ok(new_tasks)
}
| crates/scheduler/src/producer.rs | scheduler::src::producer | 1,354 | true |
// File: crates/scheduler/src/env.rs
// Module: scheduler::src::env
#[doc(inline)]
pub use router_env::*;
| crates/scheduler/src/env.rs | scheduler::src::env | 29 | true |
// File: crates/scheduler/src/configs.rs
// Module: scheduler::src::configs
pub mod defaults;
pub mod settings;
pub mod validations;
| crates/scheduler/src/configs.rs | scheduler::src::configs | 32 | true |
// File: crates/scheduler/src/lib.rs
// Module: scheduler::src::lib
pub mod configs;
pub mod consumer;
pub mod db;
pub mod env;
pub mod errors;
pub mod flow;
pub mod metrics;
pub mod producer;
pub mod scheduler;
pub mod settings;
pub mod utils;
pub use self::{consumer::types, flow::*, scheduler::*};
| crates/scheduler/src/lib.rs | scheduler::src::lib | 77 | true |
// File: crates/scheduler/src/db.rs
// Module: scheduler::src::db
pub mod process_tracker;
pub mod queue;
| crates/scheduler/src/db.rs | scheduler::src::db | 28 | true |
// File: crates/scheduler/src/metrics.rs
// Module: scheduler::src::metrics
use router_env::{counter_metric, global_meter, histogram_metric_f64};
global_meter!(PT_METER, "PROCESS_TRACKER");
histogram_metric_f64!(CONSUMER_OPS, PT_METER);
counter_metric!(PAYMENT_COUNT, PT_METER); // No. of payments created
counter_metric!(TASKS_PICKED_COUNT, PT_METER); // Tasks picked by
counter_metric!(BATCHES_CREATED, PT_METER); // Batches added to stream
counter_metric!(BATCHES_CONSUMED, PT_METER); // Batches consumed by consumer
counter_metric!(TASK_CONSUMED, PT_METER); // Tasks consumed by consumer
counter_metric!(TASK_PROCESSED, PT_METER); // Tasks completed processing
counter_metric!(TASK_FINISHED, PT_METER); // Tasks finished
counter_metric!(TASK_RETRIED, PT_METER); // Tasks added for retries
| crates/scheduler/src/metrics.rs | scheduler::src::metrics | 208 | true |
// File: crates/scheduler/src/scheduler.rs
// Module: scheduler::src::scheduler
use std::sync::Arc;
use common_utils::{errors::CustomResult, id_type};
#[cfg(feature = "kv_store")]
use storage_impl::kv_router_store::KVRouterStore;
use storage_impl::mock_db::MockDb;
#[cfg(not(feature = "kv_store"))]
use storage_impl::RouterStore;
use tokio::sync::mpsc;
use super::env::logger::error;
pub use crate::{
configs::settings::SchedulerSettings,
consumer::{self, workflows},
db::{process_tracker::ProcessTrackerInterface, queue::QueueInterface},
errors,
flow::SchedulerFlow,
producer,
};
#[cfg(not(feature = "olap"))]
type StoreType = storage_impl::database::store::Store;
#[cfg(feature = "olap")]
type StoreType = storage_impl::database::store::ReplicaStore;
#[cfg(not(feature = "kv_store"))]
pub type Store = RouterStore<StoreType>;
#[cfg(feature = "kv_store")]
pub type Store = KVRouterStore<StoreType>;
pub trait AsSchedulerInterface {
fn as_scheduler(&self) -> &dyn SchedulerInterface;
}
impl<T: SchedulerInterface> AsSchedulerInterface for T {
fn as_scheduler(&self) -> &dyn SchedulerInterface {
self
}
}
#[async_trait::async_trait]
pub trait SchedulerInterface:
ProcessTrackerInterface + QueueInterface + AsSchedulerInterface
{
}
#[async_trait::async_trait]
impl SchedulerInterface for Store {}
#[async_trait::async_trait]
impl SchedulerInterface for MockDb {}
#[async_trait::async_trait]
pub trait SchedulerAppState: Send + Sync + Clone {
fn get_tenants(&self) -> Vec<id_type::TenantId>;
}
#[async_trait::async_trait]
pub trait SchedulerSessionState: Send + Sync + Clone {
fn get_db(&self) -> Box<dyn SchedulerInterface>;
}
pub async fn start_process_tracker<
T: SchedulerAppState + 'static,
U: SchedulerSessionState + 'static,
F,
>(
state: &T,
scheduler_flow: SchedulerFlow,
scheduler_settings: Arc<SchedulerSettings>,
channel: (mpsc::Sender<()>, mpsc::Receiver<()>),
runner_from_task: impl workflows::ProcessTrackerWorkflows<U> + 'static + Copy + std::fmt::Debug,
app_state_to_session_state: F,
) -> CustomResult<(), errors::ProcessTrackerError>
where
F: Fn(&T, &id_type::TenantId) -> CustomResult<U, errors::ProcessTrackerError>,
{
match scheduler_flow {
SchedulerFlow::Producer => {
producer::start_producer(
state,
scheduler_settings,
channel,
app_state_to_session_state,
)
.await?
}
SchedulerFlow::Consumer => {
consumer::start_consumer(
state,
scheduler_settings,
runner_from_task,
channel,
app_state_to_session_state,
)
.await?
}
SchedulerFlow::Cleaner => {
error!("This flow has not been implemented yet!");
}
}
Ok(())
}
| crates/scheduler/src/scheduler.rs | scheduler::src::scheduler | 666 | true |
// File: crates/scheduler/src/errors.rs
// Module: scheduler::src::errors
pub use common_utils::errors::{ParsingError, ValidationError};
#[cfg(feature = "email")]
use external_services::email::EmailError;
use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse;
pub use redis_interface::errors::RedisError;
pub use storage_impl::errors::ApplicationError;
use storage_impl::errors::{RecoveryError, StorageError};
use crate::env::logger::{self, error};
#[derive(Debug, thiserror::Error)]
pub enum ProcessTrackerError {
#[error("An unexpected flow was specified")]
UnexpectedFlow,
#[error("Failed to serialize object")]
SerializationFailed,
#[error("Failed to deserialize object")]
DeserializationFailed,
#[error("Missing required field")]
MissingRequiredField,
#[error("Failed to insert process batch into stream")]
BatchInsertionFailed,
#[error("Failed to insert process into stream")]
ProcessInsertionFailed,
#[error("The process batch with the specified details was not found")]
BatchNotFound,
#[error("Failed to update process batch in stream")]
BatchUpdateFailed,
#[error("Failed to delete process batch from stream")]
BatchDeleteFailed,
#[error("An error occurred when trying to read process tracker configuration")]
ConfigurationError,
#[error("Failed to update process in database")]
ProcessUpdateFailed,
#[error("Failed to fetch processes from database")]
ProcessFetchingFailed,
#[error("Failed while fetching: {resource_name}")]
ResourceFetchingFailed { resource_name: String },
#[error("Failed while executing: {flow}")]
FlowExecutionError { flow: &'static str },
#[error("Not Implemented")]
NotImplemented,
#[error("Job not found")]
JobNotFound,
#[error("Received Error ApiResponseError")]
EApiErrorResponse,
#[error("Received Error ClientError")]
EClientError,
#[error("Received RecoveryError: {0:?}")]
ERecoveryError(error_stack::Report<RecoveryError>),
#[error("Received Error StorageError: {0:?}")]
EStorageError(error_stack::Report<StorageError>),
#[error("Received Error RedisError: {0:?}")]
ERedisError(error_stack::Report<RedisError>),
#[error("Received Error ParsingError: {0:?}")]
EParsingError(error_stack::Report<ParsingError>),
#[error("Validation Error Received: {0:?}")]
EValidationError(error_stack::Report<ValidationError>),
#[cfg(feature = "email")]
#[error("Received Error EmailError: {0:?}")]
EEmailError(error_stack::Report<EmailError>),
#[error("Type Conversion error")]
TypeConversionError,
#[error("Tenant not found")]
TenantNotFound,
}
#[macro_export]
macro_rules! error_to_process_tracker_error {
($($path: ident)::+ < $st: ident >, $($path2:ident)::* ($($inner_path2:ident)::+ <$st2:ident>) ) => {
impl From<$($path)::+ <$st>> for ProcessTrackerError {
fn from(err: $($path)::+ <$st> ) -> Self {
$($path2)::*(err)
}
}
};
($($path: ident)::+ <$($inner_path:ident)::+>, $($path2:ident)::* ($($inner_path2:ident)::+ <$st2:ident>) ) => {
impl<'a> From< $($path)::+ <$($inner_path)::+> > for ProcessTrackerError {
fn from(err: $($path)::+ <$($inner_path)::+> ) -> Self {
$($path2)::*(err)
}
}
};
}
pub trait PTError: Send + Sync + 'static {
fn to_pt_error(&self) -> ProcessTrackerError;
}
impl<T: PTError> From<T> for ProcessTrackerError {
fn from(value: T) -> Self {
value.to_pt_error()
}
}
impl PTError for ApiErrorResponse {
fn to_pt_error(&self) -> ProcessTrackerError {
ProcessTrackerError::EApiErrorResponse
}
}
impl<T: PTError + std::fmt::Debug + std::fmt::Display> From<error_stack::Report<T>>
for ProcessTrackerError
{
fn from(error: error_stack::Report<T>) -> Self {
logger::error!(?error);
error.current_context().to_pt_error()
}
}
error_to_process_tracker_error!(
error_stack::Report<StorageError>,
ProcessTrackerError::EStorageError(error_stack::Report<StorageError>)
);
error_to_process_tracker_error!(
error_stack::Report<RedisError>,
ProcessTrackerError::ERedisError(error_stack::Report<RedisError>)
);
error_to_process_tracker_error!(
error_stack::Report<ParsingError>,
ProcessTrackerError::EParsingError(error_stack::Report<ParsingError>)
);
error_to_process_tracker_error!(
error_stack::Report<ValidationError>,
ProcessTrackerError::EValidationError(error_stack::Report<ValidationError>)
);
#[cfg(feature = "email")]
error_to_process_tracker_error!(
error_stack::Report<EmailError>,
ProcessTrackerError::EEmailError(error_stack::Report<EmailError>)
);
error_to_process_tracker_error!(
error_stack::Report<RecoveryError>,
ProcessTrackerError::ERecoveryError(error_stack::Report<RecoveryError>)
);
| crates/scheduler/src/errors.rs | scheduler::src::errors | 1,154 | true |
// File: crates/scheduler/src/settings.rs
// Module: scheduler::src::settings
use common_utils::ext_traits::ConfigExt;
use serde::Deserialize;
use storage_impl::errors::ApplicationError;
pub use crate::configs::settings::SchedulerSettings;
#[derive(Debug, Clone, Deserialize)]
pub struct ProducerSettings {
pub upper_fetch_limit: i64,
pub lower_fetch_limit: i64,
pub lock_key: String,
pub lock_ttl: i64,
pub batch_size: usize,
}
#[derive(Debug, Clone, Deserialize)]
pub struct ConsumerSettings {
pub disabled: bool,
pub consumer_group: String,
}
#[cfg(feature = "kv_store")]
#[derive(Debug, Clone, Deserialize)]
pub struct DrainerSettings {
pub stream_name: String,
pub num_partitions: u8,
pub max_read_count: u64,
pub shutdown_interval: u32, // in milliseconds
pub loop_interval: u32, // in milliseconds
}
impl ProducerSettings {
pub fn validate(&self) -> Result<(), ApplicationError> {
common_utils::fp_utils::when(self.lock_key.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"producer lock key must not be empty".into(),
))
})
}
}
#[cfg(feature = "kv_store")]
impl DrainerSettings {
pub fn validate(&self) -> Result<(), ApplicationError> {
common_utils::fp_utils::when(self.stream_name.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"drainer stream name must not be empty".into(),
))
})
}
}
impl Default for ProducerSettings {
fn default() -> Self {
Self {
upper_fetch_limit: 0,
lower_fetch_limit: 1800,
lock_key: "PRODUCER_LOCKING_KEY".into(),
lock_ttl: 160,
batch_size: 200,
}
}
}
impl Default for ConsumerSettings {
fn default() -> Self {
Self {
disabled: false,
consumer_group: "SCHEDULER_GROUP".into(),
}
}
}
#[cfg(feature = "kv_store")]
impl Default for DrainerSettings {
fn default() -> Self {
Self {
stream_name: "DRAINER_STREAM".into(),
num_partitions: 64,
max_read_count: 100,
shutdown_interval: 1000,
loop_interval: 500,
}
}
}
| crates/scheduler/src/settings.rs | scheduler::src::settings | 543 | true |
// File: crates/scheduler/src/consumer.rs
// Module: scheduler::src::consumer
// TODO: Figure out what to log
use std::{
sync::{self, atomic},
time as std_time,
};
pub mod types;
pub mod workflows;
use common_utils::{errors::CustomResult, id_type, signals::get_allowed_signals};
use diesel_models::enums;
pub use diesel_models::{self, process_tracker as storage};
use error_stack::ResultExt;
use futures::future;
use redis_interface::{RedisConnectionPool, RedisEntryId};
use router_env::{
instrument,
tracing::{self, Instrument},
};
use time::PrimitiveDateTime;
use tokio::sync::mpsc;
use uuid::Uuid;
use super::env::logger;
pub use super::workflows::ProcessTrackerWorkflow;
use crate::{
configs::settings::SchedulerSettings, db::process_tracker::ProcessTrackerInterface, errors,
metrics, utils as pt_utils, SchedulerAppState, SchedulerInterface, SchedulerSessionState,
};
// Valid consumer business statuses
pub fn valid_business_statuses() -> Vec<&'static str> {
vec![storage::business_status::PENDING]
}
#[instrument(skip_all)]
pub async fn start_consumer<T: SchedulerAppState + 'static, U: SchedulerSessionState + 'static, F>(
state: &T,
settings: sync::Arc<SchedulerSettings>,
workflow_selector: impl workflows::ProcessTrackerWorkflows<U> + 'static + Copy + std::fmt::Debug,
(tx, mut rx): (mpsc::Sender<()>, mpsc::Receiver<()>),
app_state_to_session_state: F,
) -> CustomResult<(), errors::ProcessTrackerError>
where
F: Fn(&T, &id_type::TenantId) -> CustomResult<U, errors::ProcessTrackerError>,
{
use std::time::Duration;
use rand::distributions::{Distribution, Uniform};
let mut rng = rand::thread_rng();
// TODO: this can be removed once rand-0.9 is released
// reference - https://github.com/rust-random/rand/issues/1326#issuecomment-1635331942
#[allow(unknown_lints)]
#[allow(clippy::unnecessary_fallible_conversions)]
let timeout = Uniform::try_from(0..=settings.loop_interval)
.change_context(errors::ProcessTrackerError::ConfigurationError)?;
tokio::time::sleep(Duration::from_millis(timeout.sample(&mut rng))).await;
let mut interval = tokio::time::interval(Duration::from_millis(settings.loop_interval));
let mut shutdown_interval =
tokio::time::interval(Duration::from_millis(settings.graceful_shutdown_interval));
let consumer_operation_counter = sync::Arc::new(atomic::AtomicU64::new(0));
let signal = get_allowed_signals()
.map_err(|error| {
logger::error!(?error, "Signal Handler Error");
errors::ProcessTrackerError::ConfigurationError
})
.attach_printable("Failed while creating a signals handler")?;
let handle = signal.handle();
let task_handle =
tokio::spawn(common_utils::signals::signal_handler(signal, tx).in_current_span());
'consumer: loop {
match rx.try_recv() {
Err(mpsc::error::TryRecvError::Empty) => {
interval.tick().await;
// A guard from env to disable the consumer
if settings.consumer.disabled {
continue;
}
consumer_operation_counter.fetch_add(1, atomic::Ordering::SeqCst);
let start_time = std_time::Instant::now();
let tenants = state.get_tenants();
for tenant in tenants {
let session_state = app_state_to_session_state(state, &tenant)?;
pt_utils::consumer_operation_handler(
session_state.clone(),
settings.clone(),
|error| {
logger::error!(?error, "Failed to perform consumer operation");
},
workflow_selector,
)
.await;
}
let end_time = std_time::Instant::now();
let duration = end_time.saturating_duration_since(start_time).as_secs_f64();
logger::debug!("Time taken to execute consumer_operation: {}s", duration);
let current_count =
consumer_operation_counter.fetch_sub(1, atomic::Ordering::SeqCst);
logger::info!("Current tasks being executed: {}", current_count);
}
Ok(()) | Err(mpsc::error::TryRecvError::Disconnected) => {
logger::debug!("Awaiting shutdown!");
rx.close();
loop {
shutdown_interval.tick().await;
let active_tasks = consumer_operation_counter.load(atomic::Ordering::Acquire);
logger::info!("Active tasks: {active_tasks}");
match active_tasks {
0 => {
logger::info!("Terminating consumer");
break 'consumer;
}
_ => continue,
}
}
}
}
}
handle.close();
task_handle
.await
.change_context(errors::ProcessTrackerError::UnexpectedFlow)?;
Ok(())
}
#[instrument(skip_all)]
pub async fn consumer_operations<T: SchedulerSessionState + 'static>(
state: &T,
settings: &SchedulerSettings,
workflow_selector: impl workflows::ProcessTrackerWorkflows<T> + 'static + Copy + std::fmt::Debug,
) -> CustomResult<(), errors::ProcessTrackerError> {
let stream_name = settings.stream.clone();
let group_name = settings.consumer.consumer_group.clone();
let consumer_name = format!("consumer_{}", Uuid::new_v4());
let _group_created = &mut state
.get_db()
.consumer_group_create(&stream_name, &group_name, &RedisEntryId::AfterLastID)
.await;
let mut tasks = state
.get_db()
.as_scheduler()
.fetch_consumer_tasks(&stream_name, &group_name, &consumer_name)
.await?;
if !tasks.is_empty() {
logger::info!("{} picked {} tasks", consumer_name, tasks.len());
}
let mut handler = vec![];
for task in tasks.iter_mut() {
let pickup_time = common_utils::date_time::now();
pt_utils::add_histogram_metrics(&pickup_time, task, &stream_name);
metrics::TASK_CONSUMED.add(1, &[]);
handler.push(tokio::task::spawn(start_workflow(
state.clone(),
task.clone(),
pickup_time,
workflow_selector,
)))
}
future::join_all(handler).await;
Ok(())
}
#[instrument(skip(db, redis_conn))]
pub async fn fetch_consumer_tasks(
db: &dyn ProcessTrackerInterface,
redis_conn: &RedisConnectionPool,
stream_name: &str,
group_name: &str,
consumer_name: &str,
) -> CustomResult<Vec<storage::ProcessTracker>, errors::ProcessTrackerError> {
let batches = pt_utils::get_batches(redis_conn, stream_name, group_name, consumer_name).await?;
// Returning early to avoid execution of database queries when `batches` is empty
if batches.is_empty() {
return Ok(Vec::new());
}
let mut tasks = batches.into_iter().fold(Vec::new(), |mut acc, batch| {
acc.extend_from_slice(
batch
.trackers
.into_iter()
.filter(|task| task.is_valid_business_status(&valid_business_statuses()))
.collect::<Vec<_>>()
.as_slice(),
);
acc
});
let task_ids = tasks
.iter()
.map(|task| task.id.to_owned())
.collect::<Vec<_>>();
db.process_tracker_update_process_status_by_ids(
task_ids,
storage::ProcessTrackerUpdate::StatusUpdate {
status: enums::ProcessTrackerStatus::ProcessStarted,
business_status: None,
},
)
.await
.change_context(errors::ProcessTrackerError::ProcessFetchingFailed)?;
tasks
.iter_mut()
.for_each(|x| x.status = enums::ProcessTrackerStatus::ProcessStarted);
Ok(tasks)
}
// Accept flow_options if required
#[instrument(skip(state), fields(workflow_id))]
pub async fn start_workflow<T>(
state: T,
process: storage::ProcessTracker,
_pickup_time: PrimitiveDateTime,
workflow_selector: impl workflows::ProcessTrackerWorkflows<T> + 'static + std::fmt::Debug,
) -> CustomResult<(), errors::ProcessTrackerError>
where
T: SchedulerSessionState,
{
tracing::Span::current().record("workflow_id", Uuid::new_v4().to_string());
logger::info!(pt.name=?process.name, pt.id=%process.id);
let res = workflow_selector
.trigger_workflow(&state.clone(), process.clone())
.await
.inspect_err(|error| {
logger::error!(?error, "Failed to trigger workflow");
});
metrics::TASK_PROCESSED.add(1, &[]);
res
}
#[instrument(skip_all)]
pub async fn consumer_error_handler(
state: &(dyn SchedulerInterface + 'static),
process: storage::ProcessTracker,
error: errors::ProcessTrackerError,
) -> CustomResult<(), errors::ProcessTrackerError> {
logger::error!(pt.name=?process.name, pt.id=%process.id, ?error, "Failed to execute workflow");
state
.process_tracker_update_process_status_by_ids(
vec![process.id],
storage::ProcessTrackerUpdate::StatusUpdate {
status: enums::ProcessTrackerStatus::Finish,
business_status: Some(String::from(storage::business_status::GLOBAL_ERROR)),
},
)
.await
.change_context(errors::ProcessTrackerError::ProcessUpdateFailed)?;
Ok(())
}
pub async fn create_task(
db: &dyn ProcessTrackerInterface,
process_tracker_entry: storage::ProcessTrackerNew,
) -> CustomResult<(), storage_impl::errors::StorageError> {
db.insert_process(process_tracker_entry).await?;
Ok(())
}
| crates/scheduler/src/consumer.rs | scheduler::src::consumer | 2,134 | true |
// File: crates/scheduler/src/utils.rs
// Module: scheduler::src::utils
use std::sync;
use common_utils::errors::CustomResult;
use diesel_models::enums::{self, ProcessTrackerStatus};
pub use diesel_models::process_tracker as storage;
use error_stack::{report, ResultExt};
use redis_interface::{RedisConnectionPool, RedisEntryId};
use router_env::{instrument, tracing};
use uuid::Uuid;
use super::{
consumer::{self, types::process_data, workflows},
env::logger,
};
use crate::{
configs::settings::SchedulerSettings, consumer::types::ProcessTrackerBatch, errors,
flow::SchedulerFlow, metrics, SchedulerInterface, SchedulerSessionState,
};
pub async fn divide_and_append_tasks<T>(
state: &T,
flow: SchedulerFlow,
tasks: Vec<storage::ProcessTracker>,
settings: &SchedulerSettings,
) -> CustomResult<(), errors::ProcessTrackerError>
where
T: SchedulerInterface + Send + Sync + ?Sized,
{
let batches = divide(tasks, settings);
// Safety: Assuming we won't deal with more than `u64::MAX` batches at once
#[allow(clippy::as_conversions)]
metrics::BATCHES_CREATED.add(batches.len() as u64, &[]); // Metrics
for batch in batches {
let result = update_status_and_append(state, flow, batch).await;
match result {
Ok(_) => (),
Err(error) => logger::error!(?error),
}
}
Ok(())
}
pub async fn update_status_and_append<T>(
state: &T,
flow: SchedulerFlow,
pt_batch: ProcessTrackerBatch,
) -> CustomResult<(), errors::ProcessTrackerError>
where
T: SchedulerInterface + Send + Sync + ?Sized,
{
let process_ids: Vec<String> = pt_batch
.trackers
.iter()
.map(|process| process.id.to_owned())
.collect();
match flow {
SchedulerFlow::Producer => state
.process_tracker_update_process_status_by_ids(
process_ids,
storage::ProcessTrackerUpdate::StatusUpdate {
status: ProcessTrackerStatus::Processing,
business_status: None,
},
)
.await
.map_or_else(
|error| {
logger::error!(?error, "Error while updating process status");
Err(error.change_context(errors::ProcessTrackerError::ProcessUpdateFailed))
},
|count| {
logger::debug!("Updated status of {count} processes");
Ok(())
},
),
SchedulerFlow::Cleaner => {
let res = state
.reinitialize_limbo_processes(process_ids, common_utils::date_time::now())
.await;
match res {
Ok(count) => {
logger::debug!("Reinitialized {count} processes");
Ok(())
}
Err(error) => {
logger::error!(?error, "Error while reinitializing processes");
Err(error.change_context(errors::ProcessTrackerError::ProcessUpdateFailed))
}
}
}
_ => {
let error = format!("Unexpected scheduler flow {flow:?}");
logger::error!(%error);
Err(report!(errors::ProcessTrackerError::UnexpectedFlow).attach_printable(error))
}
}?;
let field_value_pairs = pt_batch.to_redis_field_value_pairs()?;
match state
.stream_append_entry(
&pt_batch.stream_name,
&RedisEntryId::AutoGeneratedID,
field_value_pairs,
)
.await
.change_context(errors::ProcessTrackerError::BatchInsertionFailed)
{
Ok(x) => Ok(x),
Err(mut err) => {
let update_res = state
.process_tracker_update_process_status_by_ids(
pt_batch
.trackers
.iter()
.map(|process| process.id.clone())
.collect(),
storage::ProcessTrackerUpdate::StatusUpdate {
status: ProcessTrackerStatus::Processing,
business_status: None,
},
)
.await
.map_or_else(
|error| {
logger::error!(?error, "Error while updating process status");
Err(error.change_context(errors::ProcessTrackerError::ProcessUpdateFailed))
},
|count| {
logger::debug!("Updated status of {count} processes");
Ok(())
},
);
match update_res {
Ok(_) => (),
Err(inner_err) => {
err.extend_one(inner_err);
}
};
Err(err)
}
}
}
pub fn divide(
tasks: Vec<storage::ProcessTracker>,
conf: &SchedulerSettings,
) -> Vec<ProcessTrackerBatch> {
let now = common_utils::date_time::now();
let batch_size = conf.producer.batch_size;
divide_into_batches(batch_size, tasks, now, conf)
}
pub fn divide_into_batches(
batch_size: usize,
tasks: Vec<storage::ProcessTracker>,
batch_creation_time: time::PrimitiveDateTime,
conf: &SchedulerSettings,
) -> Vec<ProcessTrackerBatch> {
let batch_id = Uuid::new_v4().to_string();
tasks
.chunks(batch_size)
.fold(Vec::new(), |mut batches, item| {
let batch = ProcessTrackerBatch {
id: batch_id.clone(),
group_name: conf.consumer.consumer_group.clone(),
stream_name: conf.stream.clone(),
connection_name: String::new(),
created_time: batch_creation_time,
rule: String::new(), // is it required?
trackers: item.to_vec(),
};
batches.push(batch);
batches
})
}
pub async fn get_batches(
conn: &RedisConnectionPool,
stream_name: &str,
group_name: &str,
consumer_name: &str,
) -> CustomResult<Vec<ProcessTrackerBatch>, errors::ProcessTrackerError> {
let response = match conn
.stream_read_with_options(
stream_name,
RedisEntryId::UndeliveredEntryID,
// Update logic for collecting to Vec and flattening, if count > 1 is provided
Some(1),
None,
Some((group_name, consumer_name)),
)
.await
{
Ok(response) => response,
Err(error) => {
if let redis_interface::errors::RedisError::StreamEmptyOrNotAvailable =
error.current_context()
{
logger::debug!("No batches processed as stream is empty");
return Ok(Vec::new());
} else {
return Err(error.change_context(errors::ProcessTrackerError::BatchNotFound));
}
}
};
metrics::BATCHES_CONSUMED.add(1, &[]);
let (batches, entry_ids): (Vec<Vec<ProcessTrackerBatch>>, Vec<Vec<String>>) = response.into_values().map(|entries| {
entries.into_iter().try_fold(
(Vec::new(), Vec::new()),
|(mut batches, mut entry_ids), entry| {
// Redis entry ID
entry_ids.push(entry.0);
// Value HashMap
batches.push(ProcessTrackerBatch::from_redis_stream_entry(entry.1)?);
Ok((batches, entry_ids))
},
)
}).collect::<CustomResult<Vec<(Vec<ProcessTrackerBatch>, Vec<String>)>, errors::ProcessTrackerError>>()?
.into_iter()
.unzip();
// Flattening the Vec's since the count provided above is 1. This needs to be updated if a
// count greater than 1 is provided.
let batches = batches.into_iter().flatten().collect::<Vec<_>>();
let entry_ids = entry_ids.into_iter().flatten().collect::<Vec<_>>();
conn.stream_acknowledge_entries(&stream_name.into(), group_name, entry_ids.clone())
.await
.map_err(|error| {
logger::error!(?error, "Error acknowledging batch in stream");
error.change_context(errors::ProcessTrackerError::BatchUpdateFailed)
})?;
conn.stream_delete_entries(&stream_name.into(), entry_ids.clone())
.await
.map_err(|error| {
logger::error!(?error, "Error deleting batch from stream");
error.change_context(errors::ProcessTrackerError::BatchDeleteFailed)
})?;
Ok(batches)
}
pub fn get_process_tracker_id<'a>(
runner: storage::ProcessTrackerRunner,
task_name: &'a str,
txn_id: &'a str,
merchant_id: &'a common_utils::id_type::MerchantId,
) -> String {
format!(
"{runner}_{task_name}_{txn_id}_{}",
merchant_id.get_string_repr()
)
}
pub fn get_process_tracker_id_for_dispute_list<'a>(
runner: storage::ProcessTrackerRunner,
merchant_connector_account_id: &'a common_utils::id_type::MerchantConnectorAccountId,
created_from: time::PrimitiveDateTime,
merchant_id: &'a common_utils::id_type::MerchantId,
) -> String {
format!(
"{runner}_{:04}{}{:02}{:02}_{}_{}",
created_from.year(),
created_from.month(),
created_from.day(),
created_from.hour(),
merchant_connector_account_id.get_string_repr(),
merchant_id.get_string_repr()
)
}
pub fn get_time_from_delta(delta: Option<i32>) -> Option<time::PrimitiveDateTime> {
delta.map(|t| common_utils::date_time::now().saturating_add(time::Duration::seconds(t.into())))
}
#[instrument(skip_all)]
pub async fn consumer_operation_handler<E, T>(
state: T,
settings: sync::Arc<SchedulerSettings>,
error_handler_fun: E,
workflow_selector: impl workflows::ProcessTrackerWorkflows<T> + 'static + Copy + std::fmt::Debug,
) where
// Error handler function
E: FnOnce(error_stack::Report<errors::ProcessTrackerError>),
T: SchedulerSessionState + Send + Sync + 'static,
{
match consumer::consumer_operations(&state, &settings, workflow_selector).await {
Ok(_) => (),
Err(err) => error_handler_fun(err),
}
}
pub fn add_histogram_metrics(
pickup_time: &time::PrimitiveDateTime,
task: &mut storage::ProcessTracker,
stream_name: &str,
) {
#[warn(clippy::option_map_unit_fn)]
if let Some((schedule_time, runner)) = task.schedule_time.as_ref().zip(task.runner.as_ref()) {
let pickup_schedule_delta = (*pickup_time - *schedule_time).as_seconds_f64();
logger::info!("Time delta for scheduled tasks: {pickup_schedule_delta} seconds");
let runner_name = runner.clone();
metrics::CONSUMER_OPS.record(
pickup_schedule_delta,
router_env::metric_attributes!((stream_name.to_owned(), runner_name)),
);
};
}
pub fn get_schedule_time(
mapping: process_data::ConnectorPTMapping,
merchant_id: &common_utils::id_type::MerchantId,
retry_count: i32,
) -> Option<i32> {
let mapping = match mapping.custom_merchant_mapping.get(merchant_id) {
Some(map) => map.clone(),
None => mapping.default_mapping,
};
// For first try, get the `start_after` time
if retry_count == 0 {
Some(mapping.start_after)
} else {
get_delay(retry_count, &mapping.frequencies)
}
}
pub fn get_pm_schedule_time(
mapping: process_data::PaymentMethodsPTMapping,
pm: enums::PaymentMethod,
retry_count: i32,
) -> Option<i32> {
let mapping = match mapping.custom_pm_mapping.get(&pm) {
Some(map) => map.clone(),
None => mapping.default_mapping,
};
if retry_count == 0 {
Some(mapping.start_after)
} else {
get_delay(retry_count, &mapping.frequencies)
}
}
pub fn get_outgoing_webhook_retry_schedule_time(
mapping: process_data::OutgoingWebhookRetryProcessTrackerMapping,
merchant_id: &common_utils::id_type::MerchantId,
retry_count: i32,
) -> Option<i32> {
let retry_mapping = match mapping.custom_merchant_mapping.get(merchant_id) {
Some(map) => map.clone(),
None => mapping.default_mapping,
};
// For first try, get the `start_after` time
if retry_count == 0 {
Some(retry_mapping.start_after)
} else {
get_delay(retry_count, &retry_mapping.frequencies)
}
}
pub fn get_pcr_payments_retry_schedule_time(
mapping: process_data::RevenueRecoveryPaymentProcessTrackerMapping,
merchant_id: &common_utils::id_type::MerchantId,
retry_count: i32,
) -> Option<i32> {
let mapping = match mapping.custom_merchant_mapping.get(merchant_id) {
Some(map) => map.clone(),
None => mapping.default_mapping,
};
// TODO: check if the current scheduled time is not more than the configured timerange
// For first try, get the `start_after` time
if retry_count == 0 {
Some(mapping.start_after)
} else {
get_delay(retry_count, &mapping.frequencies)
}
}
pub fn get_subscription_invoice_sync_retry_schedule_time(
mapping: process_data::SubscriptionInvoiceSyncPTMapping,
merchant_id: &common_utils::id_type::MerchantId,
retry_count: i32,
) -> Option<i32> {
let mapping = match mapping.custom_merchant_mapping.get(merchant_id) {
Some(map) => map.clone(),
None => mapping.default_mapping,
};
if retry_count == 0 {
Some(mapping.start_after)
} else {
get_delay(retry_count, &mapping.frequencies)
}
}
/// Get the delay based on the retry count
pub fn get_delay<'a>(
retry_count: i32,
frequencies: impl IntoIterator<Item = &'a (i32, i32)>,
) -> Option<i32> {
// Preferably, fix this by using unsigned ints
if retry_count <= 0 {
return None;
}
let mut cumulative_count = 0;
for &(frequency, count) in frequencies.into_iter() {
cumulative_count += count;
if cumulative_count >= retry_count {
return Some(frequency);
}
}
None
}
pub(crate) async fn lock_acquire_release<T, F, Fut>(
state: &T,
settings: &SchedulerSettings,
callback: F,
) -> CustomResult<(), errors::ProcessTrackerError>
where
F: Fn() -> Fut,
T: SchedulerInterface + Send + Sync + ?Sized,
Fut: futures::Future<Output = CustomResult<(), errors::ProcessTrackerError>>,
{
let tag = "PRODUCER_LOCK";
let lock_key = &settings.producer.lock_key;
let lock_val = "LOCKED";
let ttl = settings.producer.lock_ttl;
if state
.acquire_pt_lock(tag, lock_key, lock_val, ttl)
.await
.change_context(errors::ProcessTrackerError::ERedisError(
errors::RedisError::RedisConnectionError.into(),
))?
{
let result = callback().await;
state
.release_pt_lock(tag, lock_key)
.await
.map_err(errors::ProcessTrackerError::ERedisError)?;
result
} else {
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_get_delay() {
let frequency_count = vec![(300, 10), (600, 5), (1800, 3), (3600, 2)];
let retry_counts_and_expected_delays = [
(-4, None),
(-2, None),
(0, None),
(4, Some(300)),
(7, Some(300)),
(10, Some(300)),
(12, Some(600)),
(16, Some(1800)),
(18, Some(1800)),
(20, Some(3600)),
(24, None),
(30, None),
];
for (retry_count, expected_delay) in retry_counts_and_expected_delays {
let delay = get_delay(retry_count, &frequency_count);
assert_eq!(
delay, expected_delay,
"Delay and expected delay differ for `retry_count` = {retry_count}"
);
}
}
}
| crates/scheduler/src/utils.rs | scheduler::src::utils | 3,569 | true |
// File: crates/scheduler/src/configs/defaults.rs
// Module: scheduler::src::configs::defaults
impl Default for super::settings::SchedulerSettings {
fn default() -> Self {
Self {
stream: "SCHEDULER_STREAM".into(),
producer: super::settings::ProducerSettings::default(),
consumer: super::settings::ConsumerSettings::default(),
graceful_shutdown_interval: 60000,
loop_interval: 5000,
server: super::settings::Server::default(),
}
}
}
impl Default for super::settings::ProducerSettings {
fn default() -> Self {
Self {
upper_fetch_limit: 0,
lower_fetch_limit: 1800,
lock_key: "PRODUCER_LOCKING_KEY".into(),
lock_ttl: 160,
batch_size: 200,
}
}
}
impl Default for super::settings::ConsumerSettings {
fn default() -> Self {
Self {
disabled: false,
consumer_group: "SCHEDULER_GROUP".into(),
}
}
}
impl Default for super::settings::Server {
fn default() -> Self {
Self {
port: 8080,
workers: num_cpus::get_physical(),
host: "localhost".into(),
}
}
}
| crates/scheduler/src/configs/defaults.rs | scheduler::src::configs::defaults | 286 | true |
// File: crates/scheduler/src/configs/settings.rs
// Module: scheduler::src::configs::settings
pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry};
use serde::Deserialize;
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct SchedulerSettings {
pub stream: String,
pub producer: ProducerSettings,
pub consumer: ConsumerSettings,
pub loop_interval: u64,
pub graceful_shutdown_interval: u64,
pub server: Server,
}
#[derive(Debug, Deserialize, Clone)]
#[serde(default)]
pub struct Server {
pub port: u16,
pub workers: usize,
pub host: String,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct ProducerSettings {
pub upper_fetch_limit: i64,
pub lower_fetch_limit: i64,
pub lock_key: String,
pub lock_ttl: i64,
pub batch_size: usize,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
pub struct ConsumerSettings {
pub disabled: bool,
pub consumer_group: String,
}
| crates/scheduler/src/configs/settings.rs | scheduler::src::configs::settings | 239 | true |
// File: crates/scheduler/src/configs/validations.rs
// Module: scheduler::src::configs::validations
use common_utils::ext_traits::ConfigExt;
use storage_impl::errors::ApplicationError;
impl super::settings::SchedulerSettings {
pub fn validate(&self) -> Result<(), ApplicationError> {
use common_utils::fp_utils::when;
when(self.stream.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"scheduler stream must not be empty".into(),
))
})?;
when(self.consumer.consumer_group.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"scheduler consumer group must not be empty".into(),
))
})?;
self.producer.validate()?;
self.server.validate()?;
Ok(())
}
}
impl super::settings::ProducerSettings {
pub fn validate(&self) -> Result<(), ApplicationError> {
common_utils::fp_utils::when(self.lock_key.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"producer lock key must not be empty".into(),
))
})
}
}
impl super::settings::Server {
pub fn validate(&self) -> Result<(), ApplicationError> {
common_utils::fp_utils::when(self.host.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"server host must not be empty".into(),
))
})
}
}
| crates/scheduler/src/configs/validations.rs | scheduler::src::configs::validations | 308 | true |
// File: crates/scheduler/src/db/queue.rs
// Module: scheduler::src::db::queue
use common_utils::errors::CustomResult;
use diesel_models::process_tracker as storage;
use redis_interface::{errors::RedisError, RedisEntryId, SetnxReply};
use router_env::logger;
use storage_impl::{mock_db::MockDb, redis::kv_store::RedisConnInterface};
use crate::{errors::ProcessTrackerError, scheduler::Store};
#[async_trait::async_trait]
pub trait QueueInterface {
async fn fetch_consumer_tasks(
&self,
stream_name: &str,
group_name: &str,
consumer_name: &str,
) -> CustomResult<Vec<storage::ProcessTracker>, ProcessTrackerError>;
async fn consumer_group_create(
&self,
stream: &str,
group: &str,
id: &RedisEntryId,
) -> CustomResult<(), RedisError>;
async fn acquire_pt_lock(
&self,
tag: &str,
lock_key: &str,
lock_val: &str,
ttl: i64,
) -> CustomResult<bool, RedisError>;
async fn release_pt_lock(&self, tag: &str, lock_key: &str) -> CustomResult<bool, RedisError>;
async fn stream_append_entry(
&self,
stream: &str,
entry_id: &RedisEntryId,
fields: Vec<(&str, String)>,
) -> CustomResult<(), RedisError>;
async fn get_key(&self, key: &str) -> CustomResult<Vec<u8>, RedisError>;
}
#[async_trait::async_trait]
impl QueueInterface for Store {
async fn fetch_consumer_tasks(
&self,
stream_name: &str,
group_name: &str,
consumer_name: &str,
) -> CustomResult<Vec<storage::ProcessTracker>, ProcessTrackerError> {
crate::consumer::fetch_consumer_tasks(
self,
&self
.get_redis_conn()
.map_err(ProcessTrackerError::ERedisError)?
.clone(),
stream_name,
group_name,
consumer_name,
)
.await
}
async fn consumer_group_create(
&self,
stream: &str,
group: &str,
id: &RedisEntryId,
) -> CustomResult<(), RedisError> {
self.get_redis_conn()?
.consumer_group_create(&stream.into(), group, id)
.await
}
async fn acquire_pt_lock(
&self,
tag: &str,
lock_key: &str,
lock_val: &str,
ttl: i64,
) -> CustomResult<bool, RedisError> {
let conn = self.get_redis_conn()?.clone();
let is_lock_acquired = conn
.set_key_if_not_exists_with_expiry(&lock_key.into(), lock_val, None)
.await;
Ok(match is_lock_acquired {
Ok(SetnxReply::KeySet) => match conn.set_expiry(&lock_key.into(), ttl).await {
Ok(()) => true,
#[allow(unused_must_use)]
Err(error) => {
logger::error!(?error);
conn.delete_key(&lock_key.into()).await;
false
}
},
Ok(SetnxReply::KeyNotSet) => {
logger::error!(%tag, "Lock not acquired, previous fetch still in progress");
false
}
Err(error) => {
logger::error!(?error, %tag, "Error while locking");
false
}
})
}
async fn release_pt_lock(&self, tag: &str, lock_key: &str) -> CustomResult<bool, RedisError> {
let is_lock_released = self.get_redis_conn()?.delete_key(&lock_key.into()).await;
Ok(match is_lock_released {
Ok(_del_reply) => true,
Err(error) => {
logger::error!(?error, %tag, "Error while releasing lock");
false
}
})
}
async fn stream_append_entry(
&self,
stream: &str,
entry_id: &RedisEntryId,
fields: Vec<(&str, String)>,
) -> CustomResult<(), RedisError> {
self.get_redis_conn()?
.stream_append_entry(&stream.into(), entry_id, fields)
.await
}
async fn get_key(&self, key: &str) -> CustomResult<Vec<u8>, RedisError> {
self.get_redis_conn()?.get_key::<Vec<u8>>(&key.into()).await
}
}
#[async_trait::async_trait]
impl QueueInterface for MockDb {
async fn fetch_consumer_tasks(
&self,
_stream_name: &str,
_group_name: &str,
_consumer_name: &str,
) -> CustomResult<Vec<storage::ProcessTracker>, ProcessTrackerError> {
// [#172]: Implement function for `MockDb`
Err(ProcessTrackerError::ResourceFetchingFailed {
resource_name: "consumer_tasks".to_string(),
})?
}
async fn consumer_group_create(
&self,
_stream: &str,
_group: &str,
_id: &RedisEntryId,
) -> CustomResult<(), RedisError> {
// [#172]: Implement function for `MockDb`
Err(RedisError::ConsumerGroupCreateFailed)?
}
async fn acquire_pt_lock(
&self,
_tag: &str,
_lock_key: &str,
_lock_val: &str,
_ttl: i64,
) -> CustomResult<bool, RedisError> {
// [#172]: Implement function for `MockDb`
Ok(false)
}
async fn release_pt_lock(&self, _tag: &str, _lock_key: &str) -> CustomResult<bool, RedisError> {
// [#172]: Implement function for `MockDb`
Ok(false)
}
async fn stream_append_entry(
&self,
_stream: &str,
_entry_id: &RedisEntryId,
_fields: Vec<(&str, String)>,
) -> CustomResult<(), RedisError> {
// [#172]: Implement function for `MockDb`
Err(RedisError::StreamAppendFailed)?
}
async fn get_key(&self, _key: &str) -> CustomResult<Vec<u8>, RedisError> {
Err(RedisError::RedisConnectionError.into())
}
}
| crates/scheduler/src/db/queue.rs | scheduler::src::db::queue | 1,402 | true |
// File: crates/scheduler/src/db/process_tracker.rs
// Module: scheduler::src::db::process_tracker
use common_utils::errors::CustomResult;
pub use diesel_models as storage;
use diesel_models::enums as storage_enums;
use error_stack::{report, ResultExt};
use storage_impl::{connection, errors, mock_db::MockDb};
use time::PrimitiveDateTime;
use crate::{metrics, scheduler::Store};
#[async_trait::async_trait]
pub trait ProcessTrackerInterface: Send + Sync + 'static {
async fn reinitialize_limbo_processes(
&self,
ids: Vec<String>,
schedule_time: PrimitiveDateTime,
) -> CustomResult<usize, errors::StorageError>;
async fn find_process_by_id(
&self,
id: &str,
) -> CustomResult<Option<storage::ProcessTracker>, errors::StorageError>;
async fn update_process(
&self,
this: storage::ProcessTracker,
process: storage::ProcessTrackerUpdate,
) -> CustomResult<storage::ProcessTracker, errors::StorageError>;
async fn process_tracker_update_process_status_by_ids(
&self,
task_ids: Vec<String>,
task_update: storage::ProcessTrackerUpdate,
) -> CustomResult<usize, errors::StorageError>;
async fn insert_process(
&self,
new: storage::ProcessTrackerNew,
) -> CustomResult<storage::ProcessTracker, errors::StorageError>;
async fn reset_process(
&self,
this: storage::ProcessTracker,
schedule_time: PrimitiveDateTime,
) -> CustomResult<(), errors::StorageError>;
async fn retry_process(
&self,
this: storage::ProcessTracker,
schedule_time: PrimitiveDateTime,
) -> CustomResult<(), errors::StorageError>;
async fn finish_process_with_business_status(
&self,
this: storage::ProcessTracker,
business_status: &'static str,
) -> CustomResult<(), errors::StorageError>;
async fn find_processes_by_time_status(
&self,
time_lower_limit: PrimitiveDateTime,
time_upper_limit: PrimitiveDateTime,
status: storage_enums::ProcessTrackerStatus,
limit: Option<i64>,
) -> CustomResult<Vec<storage::ProcessTracker>, errors::StorageError>;
}
#[async_trait::async_trait]
impl ProcessTrackerInterface for Store {
async fn find_process_by_id(
&self,
id: &str,
) -> CustomResult<Option<storage::ProcessTracker>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::ProcessTracker::find_process_by_id(&conn, id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
async fn reinitialize_limbo_processes(
&self,
ids: Vec<String>,
schedule_time: PrimitiveDateTime,
) -> CustomResult<usize, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::ProcessTracker::reinitialize_limbo_processes(&conn, ids, schedule_time)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
async fn find_processes_by_time_status(
&self,
time_lower_limit: PrimitiveDateTime,
time_upper_limit: PrimitiveDateTime,
status: storage_enums::ProcessTrackerStatus,
limit: Option<i64>,
) -> CustomResult<Vec<storage::ProcessTracker>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::ProcessTracker::find_processes_by_time_status(
&conn,
time_lower_limit,
time_upper_limit,
status,
limit,
common_types::consts::API_VERSION,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
async fn insert_process(
&self,
new: storage::ProcessTrackerNew,
) -> CustomResult<storage::ProcessTracker, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
new.insert_process(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
async fn update_process(
&self,
this: storage::ProcessTracker,
process: storage::ProcessTrackerUpdate,
) -> CustomResult<storage::ProcessTracker, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
this.update(&conn, process)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
async fn reset_process(
&self,
this: storage::ProcessTracker,
schedule_time: PrimitiveDateTime,
) -> CustomResult<(), errors::StorageError> {
self.update_process(
this,
storage::ProcessTrackerUpdate::StatusRetryUpdate {
status: storage_enums::ProcessTrackerStatus::New,
retry_count: 0,
schedule_time,
},
)
.await?;
Ok(())
}
async fn retry_process(
&self,
this: storage::ProcessTracker,
schedule_time: PrimitiveDateTime,
) -> CustomResult<(), errors::StorageError> {
metrics::TASK_RETRIED.add(1, &[]);
let retry_count = this.retry_count + 1;
self.update_process(
this,
storage::ProcessTrackerUpdate::StatusRetryUpdate {
status: storage_enums::ProcessTrackerStatus::Pending,
retry_count,
schedule_time,
},
)
.await?;
Ok(())
}
async fn finish_process_with_business_status(
&self,
this: storage::ProcessTracker,
business_status: &'static str,
) -> CustomResult<(), errors::StorageError> {
self.update_process(
this,
storage::ProcessTrackerUpdate::StatusUpdate {
status: storage_enums::ProcessTrackerStatus::Finish,
business_status: Some(String::from(business_status)),
},
)
.await
.attach_printable("Failed to update business status of process")?;
metrics::TASK_FINISHED.add(1, &[]);
Ok(())
}
async fn process_tracker_update_process_status_by_ids(
&self,
task_ids: Vec<String>,
task_update: storage::ProcessTrackerUpdate,
) -> CustomResult<usize, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::ProcessTracker::update_process_status_by_ids(&conn, task_ids, task_update)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
#[async_trait::async_trait]
impl ProcessTrackerInterface for MockDb {
async fn find_process_by_id(
&self,
id: &str,
) -> CustomResult<Option<storage::ProcessTracker>, errors::StorageError> {
let optional = self
.processes
.lock()
.await
.iter()
.find(|process| process.id == id)
.cloned();
Ok(optional)
}
async fn reinitialize_limbo_processes(
&self,
_ids: Vec<String>,
_schedule_time: PrimitiveDateTime,
) -> CustomResult<usize, errors::StorageError> {
// [#172]: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
}
async fn find_processes_by_time_status(
&self,
_time_lower_limit: PrimitiveDateTime,
_time_upper_limit: PrimitiveDateTime,
_status: storage_enums::ProcessTrackerStatus,
_limit: Option<i64>,
) -> CustomResult<Vec<storage::ProcessTracker>, errors::StorageError> {
// [#172]: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
}
async fn insert_process(
&self,
new: storage::ProcessTrackerNew,
) -> CustomResult<storage::ProcessTracker, errors::StorageError> {
let mut processes = self.processes.lock().await;
let process = storage::ProcessTracker {
id: new.id,
name: new.name,
tag: new.tag,
runner: new.runner,
retry_count: new.retry_count,
schedule_time: new.schedule_time,
rule: new.rule,
tracking_data: new.tracking_data,
business_status: new.business_status,
status: new.status,
event: new.event,
created_at: new.created_at,
updated_at: new.updated_at,
version: new.version,
};
processes.push(process.clone());
Ok(process)
}
async fn update_process(
&self,
_this: storage::ProcessTracker,
_process: storage::ProcessTrackerUpdate,
) -> CustomResult<storage::ProcessTracker, errors::StorageError> {
// [#172]: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
}
async fn reset_process(
&self,
_this: storage::ProcessTracker,
_schedule_time: PrimitiveDateTime,
) -> CustomResult<(), errors::StorageError> {
// [#172]: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
}
async fn retry_process(
&self,
_this: storage::ProcessTracker,
_schedule_time: PrimitiveDateTime,
) -> CustomResult<(), errors::StorageError> {
// [#172]: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
}
async fn finish_process_with_business_status(
&self,
_this: storage::ProcessTracker,
_business_status: &'static str,
) -> CustomResult<(), errors::StorageError> {
// [#172]: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
}
async fn process_tracker_update_process_status_by_ids(
&self,
_task_ids: Vec<String>,
_task_update: storage::ProcessTrackerUpdate,
) -> CustomResult<usize, errors::StorageError> {
// [#172]: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
}
}
| crates/scheduler/src/db/process_tracker.rs | scheduler::src::db::process_tracker | 2,201 | true |
// File: crates/scheduler/src/consumer/types.rs
// Module: scheduler::src::consumer::types
pub mod batch;
pub mod process_data;
pub use self::batch::ProcessTrackerBatch;
| crates/scheduler/src/consumer/types.rs | scheduler::src::consumer::types | 42 | true |
// File: crates/scheduler/src/consumer/workflows.rs
// Module: scheduler::src::consumer::workflows
use async_trait::async_trait;
use common_utils::errors::CustomResult;
pub use diesel_models::process_tracker as storage;
use diesel_models::process_tracker::business_status;
use router_env::logger;
use crate::{errors, SchedulerSessionState};
pub type WorkflowSelectorFn =
fn(&storage::ProcessTracker) -> Result<(), errors::ProcessTrackerError>;
#[async_trait]
pub trait ProcessTrackerWorkflows<T>: Send + Sync {
// The core execution of the workflow
async fn trigger_workflow<'a>(
&'a self,
_state: &'a T,
_process: storage::ProcessTracker,
) -> CustomResult<(), errors::ProcessTrackerError> {
Err(errors::ProcessTrackerError::NotImplemented)?
}
async fn execute_workflow<'a>(
&'a self,
operation: Box<dyn ProcessTrackerWorkflow<T>>,
state: &'a T,
process: storage::ProcessTracker,
) -> CustomResult<(), errors::ProcessTrackerError>
where
T: SchedulerSessionState,
{
let app_state = &state.clone();
let output = operation.execute_workflow(app_state, process.clone()).await;
match output {
Ok(_) => operation.success_handler(app_state, process).await,
Err(error) => match operation
.error_handler(app_state, process.clone(), error)
.await
{
Ok(_) => (),
Err(error) => {
logger::error!(
?error,
"Failed to handle process tracker workflow execution error"
);
let status = app_state
.get_db()
.as_scheduler()
.finish_process_with_business_status(
process,
business_status::GLOBAL_FAILURE,
)
.await;
if let Err(error) = status {
logger::error!(?error, "Failed to update process business status");
}
}
},
};
Ok(())
}
}
#[async_trait]
pub trait ProcessTrackerWorkflow<T>: Send + Sync {
/// The core execution of the workflow
async fn execute_workflow<'a>(
&'a self,
_state: &'a T,
_process: storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
Err(errors::ProcessTrackerError::NotImplemented)?
}
/// Callback function after successful execution of the `execute_workflow`
async fn success_handler<'a>(&'a self, _state: &'a T, _process: storage::ProcessTracker) {}
/// Callback function after error received from `execute_workflow`
async fn error_handler<'a>(
&'a self,
_state: &'a T,
_process: storage::ProcessTracker,
_error: errors::ProcessTrackerError,
) -> CustomResult<(), errors::ProcessTrackerError> {
Err(errors::ProcessTrackerError::NotImplemented)?
}
}
| crates/scheduler/src/consumer/workflows.rs | scheduler::src::consumer::workflows | 622 | true |
// File: crates/scheduler/src/consumer/types/batch.rs
// Module: scheduler::src::consumer::types::batch
use std::collections::HashMap;
use common_utils::{errors::CustomResult, ext_traits::OptionExt};
use diesel_models::process_tracker::ProcessTracker;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
use crate::errors;
#[derive(Debug, Clone)]
pub struct ProcessTrackerBatch {
pub id: String,
pub group_name: String,
pub stream_name: String,
pub connection_name: String,
pub created_time: PrimitiveDateTime,
pub rule: String, // is it required?
pub trackers: Vec<ProcessTracker>, /* FIXME: Add sized also here, list */
}
impl ProcessTrackerBatch {
pub fn to_redis_field_value_pairs(
&self,
) -> CustomResult<Vec<(&str, String)>, errors::ProcessTrackerError> {
Ok(vec![
("id", self.id.to_string()),
("group_name", self.group_name.to_string()),
("stream_name", self.stream_name.to_string()),
("connection_name", self.connection_name.to_string()),
(
"created_time",
self.created_time.assume_utc().unix_timestamp().to_string(),
),
("rule", self.rule.to_string()),
(
"trackers",
serde_json::to_string(&self.trackers)
.change_context(errors::ProcessTrackerError::SerializationFailed)
.attach_printable_lazy(|| {
format!("Unable to stringify trackers: {:?}", self.trackers)
})?,
),
])
}
pub fn from_redis_stream_entry(
entry: HashMap<String, Option<String>>,
) -> CustomResult<Self, errors::ProcessTrackerError> {
let mut entry = entry;
let id = entry
.remove("id")
.flatten()
.get_required_value("id")
.change_context(errors::ProcessTrackerError::MissingRequiredField)?;
let group_name = entry
.remove("group_name")
.flatten()
.get_required_value("group_name")
.change_context(errors::ProcessTrackerError::MissingRequiredField)?;
let stream_name = entry
.remove("stream_name")
.flatten()
.get_required_value("stream_name")
.change_context(errors::ProcessTrackerError::MissingRequiredField)?;
let connection_name = entry
.remove("connection_name")
.flatten()
.get_required_value("connection_name")
.change_context(errors::ProcessTrackerError::MissingRequiredField)?;
let created_time = entry
.remove("created_time")
.flatten()
.get_required_value("created_time")
.change_context(errors::ProcessTrackerError::MissingRequiredField)?;
//make it parser error
let created_time = {
let offset_date_time = time::OffsetDateTime::from_unix_timestamp(
created_time
.as_str()
.parse::<i64>()
.change_context(errors::ParsingError::UnknownError)
.change_context(errors::ProcessTrackerError::DeserializationFailed)?,
)
.attach_printable_lazy(|| format!("Unable to parse time {}", &created_time))
.change_context(errors::ProcessTrackerError::MissingRequiredField)?;
PrimitiveDateTime::new(offset_date_time.date(), offset_date_time.time())
};
let rule = entry
.remove("rule")
.flatten()
.get_required_value("rule")
.change_context(errors::ProcessTrackerError::MissingRequiredField)?;
let trackers = entry
.remove("trackers")
.flatten()
.get_required_value("trackers")
.change_context(errors::ProcessTrackerError::MissingRequiredField)?;
let trackers = serde_json::from_str::<Vec<ProcessTracker>>(trackers.as_str())
.change_context(errors::ParsingError::UnknownError)
.attach_printable_lazy(|| {
format!("Unable to parse trackers from JSON string: {trackers:?}")
})
.change_context(errors::ProcessTrackerError::DeserializationFailed)
.attach_printable("Error parsing ProcessTracker from redis stream entry")?;
Ok(Self {
id,
group_name,
stream_name,
connection_name,
created_time,
rule,
trackers,
})
}
}
| crates/scheduler/src/consumer/types/batch.rs | scheduler::src::consumer::types::batch | 897 | true |
// File: crates/scheduler/src/consumer/types/process_data.rs
// Module: scheduler::src::consumer::types::process_data
use std::collections::HashMap;
use diesel_models::enums;
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct RetryMapping {
pub start_after: i32,
pub frequencies: Vec<(i32, i32)>, // (frequency, count)
}
#[derive(Serialize, Deserialize)]
pub struct ConnectorPTMapping {
pub default_mapping: RetryMapping,
pub custom_merchant_mapping: HashMap<common_utils::id_type::MerchantId, RetryMapping>,
pub max_retries_count: i32,
}
impl Default for ConnectorPTMapping {
fn default() -> Self {
Self {
custom_merchant_mapping: HashMap::new(),
default_mapping: RetryMapping {
start_after: 60,
frequencies: vec![(300, 5)],
},
max_retries_count: 5,
}
}
}
#[derive(Serialize, Deserialize)]
pub struct SubscriptionInvoiceSyncPTMapping {
pub default_mapping: RetryMapping,
pub custom_merchant_mapping: HashMap<common_utils::id_type::MerchantId, RetryMapping>,
pub max_retries_count: i32,
}
impl Default for SubscriptionInvoiceSyncPTMapping {
fn default() -> Self {
Self {
custom_merchant_mapping: HashMap::new(),
default_mapping: RetryMapping {
start_after: 60,
frequencies: vec![(300, 5)],
},
max_retries_count: 5,
}
}
}
#[derive(Serialize, Deserialize)]
pub struct PaymentMethodsPTMapping {
pub default_mapping: RetryMapping,
pub custom_pm_mapping: HashMap<enums::PaymentMethod, RetryMapping>,
pub max_retries_count: i32,
}
impl Default for PaymentMethodsPTMapping {
fn default() -> Self {
Self {
custom_pm_mapping: HashMap::new(),
default_mapping: RetryMapping {
start_after: 900,
frequencies: vec![(300, 5)],
},
max_retries_count: 5,
}
}
}
/// Configuration for outgoing webhook retries.
#[derive(Debug, Serialize, Deserialize)]
pub struct OutgoingWebhookRetryProcessTrackerMapping {
/// Default (fallback) retry configuration used when no merchant-specific retry configuration
/// exists.
pub default_mapping: RetryMapping,
/// Merchant-specific retry configuration.
pub custom_merchant_mapping: HashMap<common_utils::id_type::MerchantId, RetryMapping>,
}
impl Default for OutgoingWebhookRetryProcessTrackerMapping {
fn default() -> Self {
Self {
default_mapping: RetryMapping {
// 1st attempt happens after 1 minute
start_after: 60,
frequencies: vec![
// 2nd and 3rd attempts happen at intervals of 5 minutes each
(60 * 5, 2),
// 4th, 5th, 6th, 7th and 8th attempts happen at intervals of 10 minutes each
(60 * 10, 5),
// 9th, 10th, 11th, 12th and 13th attempts happen at intervals of 1 hour each
(60 * 60, 5),
// 14th, 15th and 16th attempts happen at intervals of 6 hours each
(60 * 60 * 6, 3),
],
},
custom_merchant_mapping: HashMap::new(),
}
}
}
/// Configuration for outgoing webhook retries.
#[derive(Debug, Serialize, Deserialize)]
pub struct RevenueRecoveryPaymentProcessTrackerMapping {
/// Default (fallback) retry configuration used when no merchant-specific retry configuration
/// exists.
pub default_mapping: RetryMapping,
/// Merchant-specific retry configuration.
pub custom_merchant_mapping: HashMap<common_utils::id_type::MerchantId, RetryMapping>,
}
impl Default for RevenueRecoveryPaymentProcessTrackerMapping {
fn default() -> Self {
Self {
default_mapping: RetryMapping {
// 1st attempt happens after 1 minute of it being
start_after: 60,
frequencies: vec![
// 2nd and 3rd attempts happen at intervals of 3 hours each
(60 * 60 * 3, 2),
// 4th, 5th, 6th attempts happen at intervals of 6 hours each
(60 * 60 * 6, 3),
// 7th, 8th, 9th attempts happen at intervals of 9 hour each
(60 * 60 * 9, 3),
// 10th, 11th and 12th attempts happen at intervals of 12 hours each
(60 * 60 * 12, 3),
// 13th, 14th and 15th attempts happen at intervals of 18 hours each
(60 * 60 * 18, 3),
],
},
custom_merchant_mapping: HashMap::new(),
}
}
}
| crates/scheduler/src/consumer/types/process_data.rs | scheduler::src::consumer::types::process_data | 1,142 | true |
// File: crates/smithy-generator/build.rs
// Module: smithy-generator::build
// crates/smithy-generator/build.rs
use std::{fs, path::Path};
use regex::Regex;
fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("cargo:rerun-if-changed=../");
run_build()
}
fn run_build() -> Result<(), Box<dyn std::error::Error>> {
let workspace_root = get_workspace_root()?;
let mut smithy_models = Vec::new();
// Scan all crates in the workspace for SmithyModel derives
let crates_dir = workspace_root.join("crates");
if let Ok(entries) = fs::read_dir(&crates_dir) {
for entry in entries.flatten() {
if entry.file_type().map(|ft| ft.is_dir()).unwrap_or(false) {
let crate_path = entry.path();
let crate_name = match crate_path.file_name() {
Some(name) => name.to_string_lossy(),
None => {
println!(
"cargo:warning=Skipping crate with invalid path: {}",
crate_path.display()
);
continue;
}
};
// Skip the smithy crate itself to avoid self-dependency
if crate_name == "smithy"
|| crate_name == "smithy-core"
|| crate_name == "smithy-generator"
{
continue;
}
if let Err(e) =
scan_crate_for_smithy_models(&crate_path, &crate_name, &mut smithy_models)
{
println!("cargo:warning=Failed to scan crate {}: {}", crate_name, e);
}
}
}
}
// Generate the registry file
generate_model_registry(&smithy_models)?;
Ok(())
}
fn get_workspace_root() -> Result<std::path::PathBuf, Box<dyn std::error::Error>> {
let manifest_dir = std::env::var("CARGO_MANIFEST_DIR")
.map_err(|_| "CARGO_MANIFEST_DIR environment variable not set")?;
let manifest_path = Path::new(&manifest_dir);
let parent1 = manifest_path
.parent()
.ok_or("Cannot get parent directory of CARGO_MANIFEST_DIR")?;
let workspace_root = parent1
.parent()
.ok_or("Cannot get workspace root directory")?;
Ok(workspace_root.to_path_buf())
}
fn scan_crate_for_smithy_models(
crate_path: &Path,
crate_name: &str,
models: &mut Vec<SmithyModelInfo>,
) -> Result<(), Box<dyn std::error::Error>> {
let src_path = crate_path.join("src");
if !src_path.exists() {
return Ok(());
}
scan_directory(&src_path, crate_name, "", models)?;
Ok(())
}
fn scan_directory(
dir: &Path,
crate_name: &str,
module_path: &str,
models: &mut Vec<SmithyModelInfo>,
) -> Result<(), Box<dyn std::error::Error>> {
if let Ok(entries) = fs::read_dir(dir) {
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
let dir_name = match path.file_name() {
Some(name) => name.to_string_lossy(),
None => {
println!(
"cargo:warning=Skipping directory with invalid name: {}",
path.display()
);
continue;
}
};
let new_module_path = if module_path.is_empty() {
dir_name.to_string()
} else {
format!("{}::{}", module_path, dir_name)
};
scan_directory(&path, crate_name, &new_module_path, models)?;
} else if path.extension().map(|ext| ext == "rs").unwrap_or(false) {
if let Err(e) = scan_rust_file(&path, crate_name, module_path, models) {
println!(
"cargo:warning=Failed to scan Rust file {}: {}",
path.display(),
e
);
}
}
}
}
Ok(())
}
fn scan_rust_file(
file_path: &Path,
crate_name: &str,
module_path: &str,
models: &mut Vec<SmithyModelInfo>,
) -> Result<(), Box<dyn std::error::Error>> {
if let Ok(content) = fs::read_to_string(file_path) {
// Enhanced regex that handles comments, doc comments, and multiple attributes
// between derive and struct/enum declarations
let re = Regex::new(r"(?ms)^#\[derive\(([^)]*(?:\([^)]*\))*[^)]*)\)\]\s*(?:(?:#\[[^\]]*\]\s*)|(?://[^\r\n]*\s*)|(?:///[^\r\n]*\s*)|(?:/\*.*?\*/\s*))*(?:pub\s+)?(?:struct|enum)\s+([A-Z][A-Za-z0-9_]*)\s*[<\{\(]")
.map_err(|e| format!("Failed to compile regex: {}", e))?;
for captures in re.captures_iter(&content) {
let derive_content = match captures.get(1) {
Some(capture) => capture.as_str(),
None => {
println!(
"cargo:warning=Missing derive content in regex capture for {}",
file_path.display()
);
continue;
}
};
let item_name = match captures.get(2) {
Some(capture) => capture.as_str(),
None => {
println!(
"cargo:warning=Missing item name in regex capture for {}",
file_path.display()
);
continue;
}
};
// Check if "SmithyModel" is present in the derive macro's content.
if derive_content.contains("SmithyModel") {
// Validate that the item name is a valid Rust identifier
if is_valid_rust_identifier(item_name) {
let full_module_path = create_module_path(file_path, crate_name, module_path)?;
models.push(SmithyModelInfo {
struct_name: item_name.to_string(),
module_path: full_module_path,
});
} else {
println!(
"cargo:warning=Skipping invalid identifier: {} in {}",
item_name,
file_path.display()
);
}
}
}
}
Ok(())
}
fn is_valid_rust_identifier(name: &str) -> bool {
if name.is_empty() {
return false;
}
// Rust identifiers must start with a letter or underscore
let first_char = match name.chars().next() {
Some(ch) => ch,
None => return false, // This shouldn't happen since we checked is_empty above, but being safe
};
if !first_char.is_ascii_alphabetic() && first_char != '_' {
return false;
}
// Must not be a Rust keyword
let keywords = [
"as", "break", "const", "continue", "crate", "else", "enum", "extern", "false", "fn",
"for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref",
"return", "self", "Self", "static", "struct", "super", "trait", "true", "type", "unsafe",
"use", "where", "while", "async", "await", "dyn", "is", "abstract", "become", "box", "do",
"final", "macro", "override", "priv", "typeof", "unsized", "virtual", "yield", "try",
];
if keywords.contains(&name) {
return false;
}
// All other characters must be alphanumeric or underscore
name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
}
fn create_module_path(
file_path: &Path,
crate_name: &str,
module_path: &str,
) -> Result<String, Box<dyn std::error::Error>> {
let file_name = file_path
.file_stem()
.and_then(|s| s.to_str())
.ok_or_else(|| {
format!(
"Cannot extract file name from path: {}",
file_path.display()
)
})?;
let crate_name_normalized = crate_name.replace('-', "_");
let result = if file_name == "lib" || file_name == "mod" {
if module_path.is_empty() {
crate_name_normalized
} else {
format!("{}::{}", crate_name_normalized, module_path)
}
} else if module_path.is_empty() {
format!("{}::{}", crate_name_normalized, file_name)
} else {
format!("{}::{}::{}", crate_name_normalized, module_path, file_name)
};
Ok(result)
}
#[derive(Debug)]
struct SmithyModelInfo {
struct_name: String,
module_path: String,
}
fn generate_model_registry(models: &[SmithyModelInfo]) -> Result<(), Box<dyn std::error::Error>> {
let out_dir = std::env::var("OUT_DIR").map_err(|_| "OUT_DIR environment variable not set")?;
let registry_path = Path::new(&out_dir).join("model_registry.rs");
let mut content = String::new();
content.push_str("// Auto-generated model registry\n");
content.push_str("// DO NOT EDIT - This file is generated by build.rs\n\n");
if !models.is_empty() {
content.push_str("use smithy_core::{SmithyModel, SmithyModelGenerator};\n\n");
// Generate imports
for model in models {
content.push_str(&format!(
"use {}::{};\n",
model.module_path, model.struct_name
));
}
content.push_str("\npub fn discover_smithy_models() -> Vec<SmithyModel> {\n");
content.push_str(" let mut models = Vec::new();\n\n");
// Generate model collection calls
for model in models {
content.push_str(&format!(
" models.push({}::generate_smithy_model());\n",
model.struct_name
));
}
content.push_str("\n models\n");
content.push_str("}\n");
} else {
// Generate empty function if no models found
content.push_str("use smithy_core::SmithyModel;\n\n");
content.push_str("pub fn discover_smithy_models() -> Vec<SmithyModel> {\n");
content.push_str(
" router_env::logger::info!(\"No SmithyModel structs found in workspace\");\n",
);
content.push_str(" Vec::new()\n");
content.push_str("}\n");
}
fs::write(®istry_path, content).map_err(|e| {
format!(
"Failed to write model registry to {}: {}",
registry_path.display(),
e
)
})?;
Ok(())
}
| crates/smithy-generator/build.rs | smithy-generator::build | 2,375 | true |
// File: crates/smithy-generator/src/main.rs
// Module: smithy-generator::src::main
// crates/smithy-generator/main.rs
use std::path::Path;
use router_env::logger;
use smithy_core::SmithyGenerator;
// Include the auto-generated model registry
include!(concat!(env!("OUT_DIR"), "/model_registry.rs"));
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut generator = SmithyGenerator::new();
logger::info!("Discovering Smithy models from workspace...");
// Automatically discover and add all models
let models = discover_smithy_models();
logger::info!("Found {} Smithy models", models.len());
if models.is_empty() {
logger::info!("No SmithyModel structs found. Make sure your structs:");
logger::info!(" 1. Derive SmithyModel: #[derive(SmithyModel)]");
logger::info!(" 2. Are in a crate that smithy can access");
logger::info!(" 3. Have the correct smithy attributes");
return Ok(());
}
for model in models {
logger::info!(" Processing namespace: {}", model.namespace);
let shape_names: Vec<_> = model.shapes.keys().collect();
logger::info!(" Shapes: {:?}", shape_names);
generator.add_model(model);
}
logger::info!("Generating Smithy IDL files...");
// Generate IDL files
let output_dir = Path::new("smithy/models");
let absolute_output_dir = std::env::current_dir()?.join(output_dir);
logger::info!("Output directory: {}", absolute_output_dir.display());
generator.generate_idl(output_dir)?;
logger::info!("✅ Smithy models generated successfully!");
logger::info!("Files written to: {}", absolute_output_dir.display());
// List generated files
if let Ok(entries) = std::fs::read_dir(output_dir) {
logger::info!("Generated files:");
for entry in entries.flatten() {
if entry.file_type().map(|ft| ft.is_file()).unwrap_or(false) {
logger::info!(" - {}", entry.file_name().to_string_lossy());
}
}
}
Ok(())
}
| crates/smithy-generator/src/main.rs | smithy-generator::src::main | 474 | true |
// File: crates/openapi/src/openapi.rs
// Module: openapi::src::openapi
use crate::routes;
#[derive(utoipa::OpenApi)]
#[openapi(
info(
title = "Hyperswitch - API Documentation",
contact(
name = "Hyperswitch Support",
url = "https://hyperswitch.io",
email = "hyperswitch@juspay.in"
),
// terms_of_service = "https://www.juspay.io/terms",
description = r#"
## Get started
Hyperswitch provides a collection of APIs that enable you to process and manage payments.
Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes.
You can consume the APIs directly using your favorite HTTP/REST library.
We have a testing environment referred to "sandbox", which you can setup to test API calls without
affecting production data.
Currently, our sandbox environment is live while our production environment is under development
and will be available soon.
You can sign up on our Dashboard to get API keys to access Hyperswitch API.
### Environment
Use the following base URLs when making requests to the APIs:
| Environment | Base URL |
|---------------|------------------------------------|
| Sandbox | <https://sandbox.hyperswitch.io> |
| Production | <https://api.hyperswitch.io> |
## Authentication
When you sign up on our [dashboard](https://app.hyperswitch.io) and create a merchant
account, you are given a secret key (also referred as api-key) and a publishable key.
You may authenticate all API requests with Hyperswitch server by providing the appropriate key in
the request Authorization header.
| Key | Description |
|-----------------|-----------------------------------------------------------------------------------------------|
| api-key | Private key. Used to authenticate all API requests from your merchant server |
| publishable key | Unique identifier for your account. Used to authenticate API requests from your app's client |
Never share your secret api keys. Keep them guarded and secure.
"#,
),
servers(
(url = "https://sandbox.hyperswitch.io", description = "Sandbox Environment")
),
tags(
(name = "Merchant Account", description = "Create and manage merchant accounts"),
(name = "Profile", description = "Create and manage profiles"),
(name = "Merchant Connector Account", description = "Create and manage merchant connector accounts"),
(name = "Payments", description = "Create and manage one-time payments, recurring payments and mandates"),
(name = "Refunds", description = "Create and manage refunds for successful payments"),
(name = "Mandates", description = "Manage mandates"),
(name = "Customers", description = "Create and manage customers"),
(name = "Payment Methods", description = "Create and manage payment methods of customers"),
(name = "Disputes", description = "Manage disputes"),
(name = "API Key", description = "Create and manage API Keys"),
(name = "Payouts", description = "Create and manage payouts"),
(name = "payment link", description = "Create payment link"),
(name = "Routing", description = "Create and manage routing configurations"),
(name = "Event", description = "Manage events"),
(name = "Authentication", description = "Create and manage authentication"),
(name = "Subscriptions", description = "Subscription management and billing endpoints")
),
// The paths will be displayed in the same order as they are registered here
paths(
// Routes for payments
routes::payments::payments_create,
routes::payments::payments_update,
routes::payments::payments_confirm,
routes::payments::payments_retrieve,
routes::payments::payments_capture,
routes::payments::payments_connector_session,
routes::payments::payments_cancel,
routes::payments::payments_cancel_post_capture,
routes::payments::payments_extend_authorization,
routes::payments::payments_list,
routes::payments::payments_incremental_authorization,
routes::payment_link::payment_link_retrieve,
routes::payments::payments_external_authentication,
routes::payments::payments_complete_authorize,
routes::payments::payments_post_session_tokens,
routes::payments::payments_update_metadata,
routes::payments::payments_submit_eligibility,
// Routes for relay
routes::relay::relay,
routes::relay::relay_retrieve,
// Routes for refunds
routes::refunds::refunds_create,
routes::refunds::refunds_retrieve,
routes::refunds::refunds_update,
routes::refunds::refunds_list,
// Routes for Organization
routes::organization::organization_create,
routes::organization::organization_retrieve,
routes::organization::organization_update,
// Routes for merchant account
routes::merchant_account::merchant_account_create,
routes::merchant_account::retrieve_merchant_account,
routes::merchant_account::update_merchant_account,
routes::merchant_account::delete_merchant_account,
routes::merchant_account::merchant_account_kv_status,
// Routes for merchant connector account
routes::merchant_connector_account::connector_create,
routes::merchant_connector_account::connector_retrieve,
routes::merchant_connector_account::connector_list,
routes::merchant_connector_account::connector_update,
routes::merchant_connector_account::connector_delete,
//Routes for gsm
routes::gsm::create_gsm_rule,
routes::gsm::get_gsm_rule,
routes::gsm::update_gsm_rule,
routes::gsm::delete_gsm_rule,
// Routes for mandates
routes::mandates::get_mandate,
routes::mandates::revoke_mandate,
routes::mandates::customers_mandates_list,
//Routes for customers
routes::customers::customers_create,
routes::customers::customers_retrieve,
routes::customers::customers_list,
routes::customers::customers_update,
routes::customers::customers_delete,
//Routes for payment methods
routes::payment_method::create_payment_method_api,
routes::payment_method::list_payment_method_api,
routes::payment_method::list_customer_payment_method_api,
routes::payment_method::list_customer_payment_method_api_client,
routes::payment_method::default_payment_method_set_api,
routes::payment_method::payment_method_retrieve_api,
routes::payment_method::payment_method_update_api,
routes::payment_method::payment_method_delete_api,
// Routes for Profile
routes::profile::profile_create,
routes::profile::profile_list,
routes::profile::profile_retrieve,
routes::profile::profile_update,
routes::profile::profile_delete,
// Routes for disputes
routes::disputes::retrieve_dispute,
routes::disputes::retrieve_disputes_list,
// Routes for routing
routes::routing::routing_create_config,
routes::routing::routing_link_config,
routes::routing::routing_retrieve_config,
routes::routing::list_routing_configs,
routes::routing::routing_unlink_config,
routes::routing::routing_update_default_config,
routes::routing::routing_retrieve_default_config,
routes::routing::routing_retrieve_linked_config,
routes::routing::routing_retrieve_default_config_for_profiles,
routes::routing::routing_update_default_config_for_profile,
routes::routing::success_based_routing_update_configs,
routes::routing::toggle_success_based_routing,
routes::routing::toggle_elimination_routing,
routes::routing::contract_based_routing_setup_config,
routes::routing::contract_based_routing_update_configs,
routes::routing::call_decide_gateway_open_router,
routes::routing::call_update_gateway_score_open_router,
routes::routing::evaluate_routing_rule,
// Routes for blocklist
routes::blocklist::remove_entry_from_blocklist,
routes::blocklist::list_blocked_payment_methods,
routes::blocklist::add_entry_to_blocklist,
routes::blocklist::toggle_blocklist_guard,
// Routes for payouts
routes::payouts::payouts_create,
routes::payouts::payouts_retrieve,
routes::payouts::payouts_update,
routes::payouts::payouts_cancel,
routes::payouts::payouts_fulfill,
routes::payouts::payouts_list,
routes::payouts::payouts_confirm,
routes::payouts::payouts_list_filters,
routes::payouts::payouts_list_by_filter,
// Routes for api keys
routes::api_keys::api_key_create,
routes::api_keys::api_key_retrieve,
routes::api_keys::api_key_update,
routes::api_keys::api_key_revoke,
routes::api_keys::api_key_list,
// Routes for events
routes::webhook_events::list_initial_webhook_delivery_attempts,
routes::webhook_events::list_initial_webhook_delivery_attempts_with_jwtauth,
routes::webhook_events::list_webhook_delivery_attempts,
routes::webhook_events::retry_webhook_delivery_attempt,
// Routes for poll apis
routes::poll::retrieve_poll_status,
// Routes for profile acquirer account
routes::profile_acquirer::profile_acquirer_create,
routes::profile_acquirer::profile_acquirer_update,
// Routes for 3DS Decision Rule
routes::three_ds_decision_rule::three_ds_decision_rule_execute,
// Routes for authentication
routes::authentication::authentication_create,
// Routes for platform account
routes::platform::create_platform_account,
//Routes for subscriptions
routes::subscriptions::create_and_confirm_subscription,
routes::subscriptions::create_subscription,
routes::subscriptions::confirm_subscription,
routes::subscriptions::get_subscription,
routes::subscriptions::update_subscription,
routes::subscriptions::get_subscription_plans,
routes::subscriptions::get_estimate,
),
components(schemas(
common_utils::types::MinorUnit,
common_utils::types::StringMinorUnit,
common_utils::types::TimeRange,
common_utils::link_utils::GenericLinkUiConfig,
common_utils::link_utils::EnabledPaymentMethod,
common_utils::payout_method_utils::AdditionalPayoutMethodData,
common_utils::payout_method_utils::CardAdditionalData,
common_utils::payout_method_utils::BankAdditionalData,
common_utils::payout_method_utils::WalletAdditionalData,
common_utils::payout_method_utils::BankRedirectAdditionalData,
common_utils::payout_method_utils::AchBankTransferAdditionalData,
common_utils::payout_method_utils::BacsBankTransferAdditionalData,
common_utils::payout_method_utils::SepaBankTransferAdditionalData,
common_utils::payout_method_utils::PixBankTransferAdditionalData,
common_utils::payout_method_utils::PaypalAdditionalData,
common_utils::payout_method_utils::InteracAdditionalData,
common_utils::payout_method_utils::VenmoAdditionalData,
common_utils::payout_method_utils::ApplePayDecryptAdditionalData,
common_types::payments::SplitPaymentsRequest,
common_types::payments::GpayTokenizationData,
common_types::payments::GPayPredecryptData,
common_types::payments::GpayEcryptedTokenizationData,
common_types::payments::ApplePayPaymentData,
common_types::payments::ApplePayPredecryptData,
common_types::payments::ApplePayCryptogramData,
common_types::payments::StripeSplitPaymentRequest,
common_types::domain::AdyenSplitData,
common_types::domain::AdyenSplitItem,
common_types::payments::AcceptanceType,
common_types::payments::CustomerAcceptance,
common_types::payments::OnlineMandate,
common_types::payments::XenditSplitRequest,
common_types::payments::XenditSplitRoute,
common_types::payments::XenditChargeResponseData,
common_types::payments::XenditMultipleSplitResponse,
common_types::payments::XenditMultipleSplitRequest,
common_types::domain::XenditSplitSubMerchantData,
common_utils::types::ChargeRefunds,
common_types::refunds::SplitRefund,
common_types::refunds::StripeSplitRefundRequest,
common_types::payments::ConnectorChargeResponseData,
common_types::payments::StripeChargeResponseData,
common_types::three_ds_decision_rule_engine::ThreeDSDecisionRule,
common_types::three_ds_decision_rule_engine::ThreeDSDecision,
common_types::payments::MerchantCountryCode,
api_models::enums::PaymentChannel,
api_models::three_ds_decision_rule::ThreeDsDecisionRuleExecuteRequest,
api_models::three_ds_decision_rule::ThreeDsDecisionRuleExecuteResponse,
api_models::three_ds_decision_rule::PaymentData,
api_models::three_ds_decision_rule::PaymentMethodMetaData,
api_models::three_ds_decision_rule::CustomerDeviceData,
api_models::three_ds_decision_rule::IssuerData,
api_models::three_ds_decision_rule::AcquirerData,
api_models::refunds::RefundRequest,
api_models::refunds::RefundType,
api_models::refunds::RefundResponse,
api_models::refunds::RefundStatus,
api_models::refunds::RefundUpdateRequest,
api_models::organization::OrganizationCreateRequest,
api_models::organization::OrganizationUpdateRequest,
api_models::organization::OrganizationResponse,
api_models::admin::MerchantAccountCreate,
api_models::admin::MerchantAccountUpdate,
api_models::admin::MerchantAccountDeleteResponse,
api_models::admin::MerchantConnectorDeleteResponse,
api_models::admin::MerchantConnectorResponse,
api_models::admin::MerchantConnectorListResponse,
api_models::admin::AuthenticationConnectorDetails,
api_models::admin::ExtendedCardInfoConfig,
api_models::admin::BusinessGenericLinkConfig,
api_models::admin::BusinessCollectLinkConfig,
api_models::admin::BusinessPayoutLinkConfig,
api_models::admin::CardTestingGuardConfig,
api_models::admin::CardTestingGuardStatus,
api_models::customers::CustomerRequest,
api_models::customers::CustomerUpdateRequest,
api_models::customers::CustomerDeleteResponse,
api_models::payment_methods::PaymentMethodCreate,
api_models::payment_methods::PaymentMethodResponse,
api_models::payment_methods::CustomerPaymentMethod,
common_types::three_ds_decision_rule_engine::ThreeDSDecisionRule,
common_types::domain::AcquirerConfigMap,
common_types::domain::AcquirerConfig,
api_models::payment_methods::PaymentMethodListResponse,
api_models::payment_methods::ResponsePaymentMethodsEnabled,
api_models::payment_methods::ResponsePaymentMethodTypes,
api_models::payment_methods::PaymentExperienceTypes,
api_models::payment_methods::CardNetworkTypes,
api_models::payment_methods::BankDebitTypes,
api_models::payment_methods::BankTransferTypes,
api_models::payment_methods::CustomerPaymentMethodsListResponse,
api_models::payment_methods::PaymentMethodDeleteResponse,
api_models::payment_methods::PaymentMethodUpdate,
api_models::payment_methods::CustomerDefaultPaymentMethodResponse,
api_models::payment_methods::CardDetailFromLocker,
api_models::payment_methods::PaymentMethodCreateData,
api_models::payment_methods::CardDetail,
api_models::payment_methods::CardDetailUpdate,
api_models::payment_methods::RequestPaymentMethodTypes,
api_models::poll::PollResponse,
api_models::poll::PollStatus,
api_models::customers::CustomerResponse,
api_models::admin::AcceptedCountries,
api_models::admin::AcceptedCurrencies,
api_models::enums::AdyenSplitType,
api_models::enums::PaymentType,
api_models::enums::MitCategory,
api_models::enums::ScaExemptionType,
api_models::enums::PaymentMethod,
api_models::enums::TriggeredBy,
api_models::enums::TokenDataType,
api_models::enums::PaymentMethodType,
api_models::enums::ConnectorType,
api_models::enums::PayoutConnectors,
api_models::enums::AuthenticationConnectors,
api_models::enums::Currency,
api_models::enums::DocumentKind,
api_models::enums::IntentStatus,
api_models::enums::CaptureMethod,
api_models::enums::FutureUsage,
api_models::enums::AuthenticationType,
api_models::enums::Connector,
api_models::enums::PaymentMethod,
api_models::enums::PaymentMethodIssuerCode,
api_models::enums::TaxStatus,
api_models::enums::MandateStatus,
api_models::enums::PaymentExperience,
api_models::enums::BankNames,
api_models::enums::BankType,
api_models::enums::BankHolderType,
api_models::enums::CardNetwork,
api_models::enums::MerchantCategoryCode,
api_models::enums::DisputeStage,
api_models::enums::DisputeStatus,
api_models::enums::CountryAlpha2,
api_models::enums::Country,
api_models::enums::CountryAlpha3,
api_models::enums::FieldType,
api_models::enums::FrmAction,
api_models::enums::FrmPreferredFlowTypes,
api_models::enums::RetryAction,
api_models::enums::AttemptStatus,
api_models::enums::CaptureStatus,
api_models::enums::ReconStatus,
api_models::enums::ConnectorStatus,
api_models::enums::AuthorizationStatus,
api_models::enums::ElementPosition,
api_models::enums::ElementSize,
api_models::enums::SizeVariants,
api_models::enums::MerchantProductType,
api_models::enums::PaymentLinkDetailsLayout,
api_models::enums::PaymentMethodStatus,
api_models::enums::UIWidgetFormLayout,
api_models::enums::MerchantProductType,
api_models::enums::HyperswitchConnectorCategory,
api_models::enums::ConnectorIntegrationStatus,
api_models::enums::CardDiscovery,
api_models::enums::FeatureStatus,
api_models::enums::MerchantProductType,
api_models::enums::CtpServiceProvider,
api_models::enums::PaymentLinkSdkLabelType,
api_models::enums::OrganizationType,
api_models::enums::PaymentLinkShowSdkTerms,
api_models::enums::ExternalVaultEnabled,
api_models::enums::GooglePayCardFundingSource,
api_models::enums::VaultSdk,
api_models::admin::ExternalVaultConnectorDetails,
api_models::admin::MerchantConnectorCreate,
api_models::admin::AdditionalMerchantData,
api_models::admin::ConnectorWalletDetails,
api_models::admin::MerchantRecipientData,
api_models::admin::MerchantAccountData,
api_models::admin::MerchantConnectorUpdate,
api_models::admin::PrimaryBusinessDetails,
api_models::admin::FrmConfigs,
api_models::admin::FrmPaymentMethod,
api_models::admin::FrmPaymentMethodType,
api_models::admin::PaymentMethodsEnabled,
api_models::admin::MerchantConnectorDetailsWrap,
api_models::admin::MerchantConnectorDetails,
api_models::admin::MerchantConnectorWebhookDetails,
api_models::admin::ProfileCreate,
api_models::admin::ProfileResponse,
api_models::admin::BusinessPaymentLinkConfig,
api_models::admin::PaymentLinkBackgroundImageConfig,
api_models::admin::PaymentLinkConfigRequest,
api_models::admin::PaymentLinkConfig,
api_models::admin::PaymentLinkTransactionDetails,
api_models::admin::TransactionDetailsUiConfiguration,
api_models::disputes::DisputeResponse,
api_models::disputes::DisputeResponsePaymentsRetrieve,
api_models::gsm::GsmCreateRequest,
api_models::gsm::GsmRetrieveRequest,
api_models::gsm::GsmUpdateRequest,
api_models::gsm::GsmDeleteRequest,
api_models::gsm::GsmDeleteResponse,
api_models::gsm::GsmResponse,
api_models::enums::GsmDecision,
api_models::enums::GsmFeature,
common_types::domain::GsmFeatureData,
common_types::domain::RetryFeatureData,
api_models::payments::AddressDetails,
api_models::payments::BankDebitData,
api_models::payments::AliPayQr,
api_models::payments::AliPayRedirection,
api_models::payments::MomoRedirection,
api_models::payments::TouchNGoRedirection,
api_models::payments::GcashRedirection,
api_models::payments::KakaoPayRedirection,
api_models::payments::AliPayHkRedirection,
api_models::payments::GoPayRedirection,
api_models::payments::MbWayRedirection,
api_models::payments::MobilePayRedirection,
api_models::payments::WeChatPayRedirection,
api_models::payments::WeChatPayQr,
api_models::payments::BankDebitBilling,
api_models::payments::CryptoData,
api_models::payments::RewardData,
api_models::payments::UpiData,
api_models::payments::UpiCollectData,
api_models::payments::UpiIntentData,
api_models::payments::UpiQrData,
api_models::payments::VoucherData,
api_models::payments::BoletoVoucherData,
api_models::payments::AlfamartVoucherData,
api_models::payments::IndomaretVoucherData,
api_models::payments::Address,
api_models::payments::VoucherData,
api_models::payments::JCSVoucherData,
api_models::payments::AlfamartVoucherData,
api_models::payments::IndomaretVoucherData,
api_models::payments::BankRedirectData,
api_models::payments::RealTimePaymentData,
api_models::payments::BankRedirectBilling,
api_models::payments::BankRedirectBilling,
api_models::payments::ConnectorMetadata,
api_models::payments::FeatureMetadata,
api_models::payments::ApplepayConnectorMetadataRequest,
api_models::payments::SessionTokenInfo,
api_models::payments::PaymentProcessingDetailsAt,
api_models::payments::ApplepayInitiative,
api_models::payments::PaymentProcessingDetails,
api_models::payments::PaymentMethodDataResponseWithBilling,
api_models::payments::PaymentMethodDataResponse,
api_models::payments::CardResponse,
api_models::payments::PaylaterResponse,
api_models::payments::KlarnaSdkPaymentMethodResponse,
api_models::payments::SwishQrData,
api_models::payments::RevolutPayData,
api_models::payments::AirwallexData,
api_models::payments::BraintreeData,
api_models::payments::NoonData,
api_models::payments::OrderDetailsWithAmount,
api_models::payments::NextActionType,
api_models::payments::WalletData,
api_models::payments::NextActionData,
api_models::payments::PayLaterData,
api_models::payments::MandateData,
api_models::payments::PhoneDetails,
api_models::payments::PaymentMethodData,
api_models::payments::PaymentMethodDataRequest,
api_models::payments::MandateType,
api_models::payments::MandateAmountData,
api_models::payments::Card,
api_models::payments::CardRedirectData,
api_models::payments::CardToken,
api_models::payments::PaymentsRequest,
api_models::payments::PaymentsCreateRequest,
api_models::payments::PaymentsUpdateRequest,
api_models::payments::PaymentsConfirmRequest,
api_models::payments::PaymentsResponse,
api_models::payments::PaymentsCreateResponseOpenApi,
api_models::payments::PaymentsEligibilityRequest,
api_models::payments::PaymentsEligibilityResponse,
api_models::payments::PaymentsCreateResponseOpenApi,
api_models::errors::types::GenericErrorResponseOpenApi,
api_models::payments::PaymentRetrieveBody,
api_models::payments::PaymentsRetrieveRequest,
api_models::payments::PaymentsCaptureRequest,
api_models::payments::PaymentsSessionRequest,
api_models::payments::PaymentsSessionResponse,
api_models::payments::PazeWalletData,
api_models::payments::SessionToken,
api_models::payments::ApplePaySessionResponse,
api_models::payments::NullObject,
api_models::payments::ThirdPartySdkSessionResponse,
api_models::payments::NoThirdPartySdkSessionResponse,
api_models::payments::SecretInfoToInitiateSdk,
api_models::payments::ApplePayPaymentRequest,
api_models::payments::ApplePayBillingContactFields,
api_models::payments::ApplePayShippingContactFields,
api_models::payments::ApplePayRecurringPaymentRequest,
api_models::payments::ApplePayRegularBillingRequest,
api_models::payments::ApplePayPaymentTiming,
api_models::payments::RecurringPaymentIntervalUnit,
api_models::payments::ApplePayRecurringDetails,
api_models::payments::ApplePayRegularBillingDetails,
api_models::payments::ApplePayAddressParameters,
api_models::payments::AmountInfo,
api_models::payments::ClickToPaySessionResponse,
api_models::enums::ProductType,
api_models::enums::MerchantAccountType,
api_models::enums::MerchantAccountRequestType,
api_models::payments::GooglePayWalletData,
api_models::payments::PayPalWalletData,
api_models::payments::PaypalRedirection,
api_models::payments::GpayMerchantInfo,
api_models::payments::GpayAllowedPaymentMethods,
api_models::payments::GpayAllowedMethodsParameters,
api_models::payments::GpayTokenizationSpecification,
api_models::payments::GpayTokenParameters,
api_models::payments::GpayTransactionInfo,
api_models::payments::GpaySessionTokenResponse,
api_models::payments::GooglePayThirdPartySdkData,
api_models::payments::KlarnaSessionTokenResponse,
api_models::payments::PaypalSessionTokenResponse,
api_models::payments::PaypalFlow,
api_models::payments::PaypalTransactionInfo,
api_models::payments::ApplepaySessionTokenResponse,
api_models::payments::SdkNextAction,
api_models::payments::NextActionCall,
api_models::payments::SdkNextActionData,
api_models::payments::SamsungPayWalletData,
api_models::payments::WeChatPay,
api_models::payments::GooglePayPaymentMethodInfo,
api_models::payments::ApplePayWalletData,
api_models::payments::SamsungPayWalletCredentials,
api_models::payments::SamsungPayWebWalletData,
api_models::payments::SamsungPayAppWalletData,
api_models::payments::SamsungPayCardBrand,
api_models::payments::SamsungPayTokenData,
api_models::payments::ApplepayPaymentMethod,
api_models::payments::PaymentsCancelRequest,
api_models::payments::PaymentsCancelPostCaptureRequest,
api_models::payments::PaymentListConstraints,
api_models::payments::PaymentListResponse,
api_models::payments::CashappQr,
api_models::payments::BankTransferData,
api_models::payments::BankTransferNextStepsData,
api_models::payments::SepaAndBacsBillingDetails,
api_models::payments::AchBillingDetails,
api_models::payments::MultibancoBillingDetails,
api_models::payments::DokuBillingDetails,
api_models::payments::BankTransferInstructions,
api_models::payments::MobilePaymentNextStepData,
api_models::payments::MobilePaymentConsent,
api_models::payments::IframeData,
api_models::payments::ReceiverDetails,
api_models::payments::AchTransfer,
api_models::payments::MultibancoTransferInstructions,
api_models::payments::DokuBankTransferInstructions,
api_models::payments::AmazonPayRedirectData,
api_models::payments::SkrillData,
api_models::payments::PayseraData,
api_models::payments::ApplePayRedirectData,
api_models::payments::ApplePayThirdPartySdkData,
api_models::payments::GooglePayRedirectData,
api_models::payments::GooglePayThirdPartySdk,
api_models::payments::GooglePaySessionResponse,
api_models::payments::PazeSessionTokenResponse,
api_models::payments::SamsungPaySessionTokenResponse,
api_models::payments::SamsungPayMerchantPaymentInformation,
api_models::payments::SamsungPayAmountDetails,
api_models::payments::SamsungPayAmountFormat,
api_models::payments::SamsungPayProtocolType,
api_models::payments::GpayShippingAddressParameters,
api_models::payments::GpayBillingAddressParameters,
api_models::payments::GpayBillingAddressFormat,
api_models::payments::NetworkDetails,
api_models::payments::SepaBankTransferInstructions,
api_models::payments::BacsBankTransferInstructions,
api_models::payments::RedirectResponse,
api_models::payments::RequestSurchargeDetails,
api_models::payments::PaymentAttemptResponse,
api_models::payments::CaptureResponse,
api_models::payments::PaymentsIncrementalAuthorizationRequest,
api_models::payments::IncrementalAuthorizationResponse,
api_models::payments::PaymentsCompleteAuthorizeRequest,
api_models::payments::PaymentsExternalAuthenticationRequest,
api_models::payments::PaymentsExternalAuthenticationResponse,
api_models::payments::SdkInformation,
api_models::payments::DeviceChannel,
api_models::payments::ThreeDsCompletionIndicator,
api_models::payments::MifinityData,
api_models::enums::TransactionStatus,
api_models::payments::BrowserInformation,
api_models::payments::PaymentCreatePaymentLinkConfig,
api_models::payments::ThreeDsData,
api_models::payments::ThreeDsMethodData,
api_models::payments::ThreeDsMethodKey,
api_models::payments::PollConfigResponse,
api_models::payments::PollConfig,
api_models::payments::ExternalAuthenticationDetailsResponse,
api_models::payments::ExtendedCardInfo,
api_models::payments::AmazonPaySessionTokenData,
api_models::payments::AmazonPayMerchantCredentials,
api_models::payments::AmazonPayWalletData,
api_models::payments::AmazonPaySessionTokenResponse,
api_models::payments::AmazonPayPaymentIntent,
api_models::payments::AmazonPayDeliveryOptions,
api_models::payments::AmazonPayDeliveryPrice,
api_models::payments::AmazonPayShippingMethod,
api_models::payment_methods::RequiredFieldInfo,
api_models::payment_methods::DefaultPaymentMethod,
api_models::payment_methods::MaskedBankDetails,
api_models::payment_methods::SurchargeDetailsResponse,
api_models::payment_methods::SurchargeResponse,
api_models::payment_methods::SurchargePercentage,
api_models::payment_methods::PaymentMethodCollectLinkRequest,
api_models::payment_methods::PaymentMethodCollectLinkResponse,
api_models::payment_methods::CardType,
api_models::payment_methods::CardNetworkTokenizeRequest,
api_models::payment_methods::CardNetworkTokenizeResponse,
api_models::payment_methods::TokenizeDataRequest,
api_models::payment_methods::TokenizeCardRequest,
api_models::payment_methods::TokenizePaymentMethodRequest,
api_models::refunds::RefundListRequest,
api_models::refunds::RefundListResponse,
api_models::relay::RelayRequest,
api_models::relay::RelayResponse,
api_models::enums::RelayType,
api_models::relay::RelayData,
api_models::relay::RelayRefundRequestData,
api_models::enums::RelayStatus,
api_models::relay::RelayError,
api_models::payments::AmountFilter,
api_models::mandates::MandateRevokedResponse,
api_models::mandates::MandateResponse,
api_models::mandates::MandateCardDetails,
api_models::mandates::RecurringDetails,
api_models::mandates::NetworkTransactionIdAndCardDetails,
api_models::mandates::ProcessorPaymentToken,
api_models::ephemeral_key::EphemeralKeyCreateResponse,
api_models::payments::CustomerDetails,
api_models::payments::GiftCardData,
api_models::payments::GiftCardDetails,
api_models::payments::BHNGiftCardDetails,
api_models::payments::MobilePaymentData,
api_models::payments::MobilePaymentResponse,
api_models::payments::Address,
api_models::payments::BankCodeResponse,
api_models::payouts::CardPayout,
api_models::payouts::Wallet,
api_models::payouts::Paypal,
api_models::payouts::BankRedirect,
api_models::payouts::Interac,
api_models::payouts::Venmo,
api_models::payouts::AchBankTransfer,
api_models::payouts::BacsBankTransfer,
api_models::payouts::SepaBankTransfer,
api_models::payouts::PixBankTransfer,
api_models::payouts::PayoutsCreateRequest,
api_models::payouts::PayoutUpdateRequest,
api_models::payouts::PayoutConfirmRequest,
api_models::payouts::PayoutCancelRequest,
api_models::payouts::PayoutFulfillRequest,
api_models::payouts::PayoutRetrieveRequest,
api_models::payouts::PayoutAttemptResponse,
api_models::payouts::PayoutCreateResponse,
api_models::payouts::PayoutListConstraints,
api_models::payouts::PayoutListFilters,
api_models::payouts::PayoutListFilterConstraints,
api_models::payouts::PayoutListResponse,
api_models::payouts::PayoutRetrieveBody,
api_models::payouts::PayoutMethodData,
api_models::payouts::PayoutMethodDataResponse,
api_models::payouts::PayoutLinkResponse,
api_models::payouts::Bank,
api_models::payouts::ApplePayDecrypt,
api_models::payouts::PayoutCreatePayoutLinkConfig,
api_models::enums::PayoutEntityType,
api_models::enums::PayoutSendPriority,
api_models::enums::PayoutStatus,
api_models::enums::PayoutType,
api_models::enums::TransactionType,
api_models::payments::FrmMessage,
api_models::webhooks::OutgoingWebhook,
api_models::webhooks::OutgoingWebhookContent,
api_models::enums::EventClass,
api_models::enums::EventType,
api_models::enums::DecoupledAuthenticationType,
api_models::enums::AuthenticationStatus,
api_models::admin::MerchantAccountResponse,
api_models::admin::MerchantConnectorId,
api_models::admin::MerchantDetails,
api_models::admin::ToggleKVRequest,
api_models::admin::ToggleKVResponse,
api_models::admin::WebhookDetails,
api_models::api_keys::ApiKeyExpiration,
api_models::api_keys::CreateApiKeyRequest,
api_models::api_keys::CreateApiKeyResponse,
api_models::api_keys::RetrieveApiKeyResponse,
api_models::api_keys::RevokeApiKeyResponse,
api_models::api_keys::UpdateApiKeyRequest,
api_models::payments::RetrievePaymentLinkRequest,
api_models::payments::PaymentLinkResponse,
api_models::payments::RetrievePaymentLinkResponse,
api_models::payments::PaymentLinkInitiateRequest,
api_models::payouts::PayoutLinkInitiateRequest,
api_models::payments::ExtendedCardInfoResponse,
api_models::payments::GooglePayAssuranceDetails,
api_models::routing::RoutingConfigRequest,
api_models::routing::RoutingDictionaryRecord,
api_models::routing::RoutingKind,
api_models::routing::RoutableConnectorChoice,
api_models::routing::DynamicRoutingFeatures,
api_models::routing::SuccessBasedRoutingConfig,
api_models::routing::DynamicRoutingConfigParams,
api_models::routing::CurrentBlockThreshold,
api_models::routing::SuccessBasedRoutingConfigBody,
api_models::routing::ContractBasedRoutingConfig,
api_models::routing::ContractBasedRoutingConfigBody,
api_models::routing::LabelInformation,
api_models::routing::ContractBasedTimeScale,
api_models::routing::LinkedRoutingConfigRetrieveResponse,
api_models::routing::RoutingRetrieveResponse,
api_models::routing::ProfileDefaultRoutingConfig,
api_models::routing::MerchantRoutingAlgorithm,
api_models::routing::RoutingAlgorithmKind,
api_models::routing::RoutingDictionary,
api_models::routing::RoutingAlgorithmWrapper,
api_models::routing::EliminationRoutingConfig,
api_models::open_router::DecisionEngineEliminationData,
api_models::routing::EliminationAnalyserConfig,
api_models::routing::DynamicRoutingAlgorithm,
api_models::routing::StaticRoutingAlgorithm,
api_models::routing::StraightThroughAlgorithm,
api_models::routing::ConnectorVolumeSplit,
api_models::routing::ConnectorSelection,
api_models::routing::SuccessRateSpecificityLevel,
api_models::routing::ToggleDynamicRoutingQuery,
api_models::routing::ToggleDynamicRoutingPath,
api_models::routing::ProgramThreeDsDecisionRule,
api_models::routing::RuleThreeDsDecisionRule,
api_models::routing::RoutingVolumeSplitResponse,
api_models::routing::ast::RoutableChoiceKind,
api_models::enums::RoutableConnectors,
api_models::routing::ast::ProgramConnectorSelection,
api_models::routing::ast::RuleConnectorSelection,
api_models::routing::ast::IfStatement,
api_models::routing::ast::Comparison,
api_models::routing::ast::ComparisonType,
api_models::routing::ast::ValueType,
api_models::routing::ast::MetadataValue,
api_models::routing::ast::NumberComparison,
api_models::payment_methods::RequestPaymentMethodTypes,
api_models::payments::PaymentLinkStatus,
api_models::blocklist::BlocklistRequest,
api_models::blocklist::BlocklistResponse,
api_models::blocklist::ToggleBlocklistResponse,
api_models::blocklist::ListBlocklistQuery,
api_models::enums::BlocklistDataKind,
api_models::enums::ErrorCategory,
api_models::webhook_events::EventListConstraints,
api_models::webhook_events::EventListItemResponse,
api_models::webhook_events::EventRetrieveResponse,
api_models::webhook_events::OutgoingWebhookRequestContent,
api_models::webhook_events::OutgoingWebhookResponseContent,
api_models::webhook_events::TotalEventsResponse,
api_models::enums::WebhookDeliveryAttempt,
api_models::enums::PaymentChargeType,
api_models::enums::StripeChargeType,
api_models::payments::CustomerDetailsResponse,
api_models::payments::SdkType,
api_models::payments::OpenBankingData,
api_models::payments::OpenBankingSessionToken,
api_models::payments::BankDebitResponse,
api_models::payments::BankRedirectResponse,
api_models::payments::BankTransferResponse,
api_models::payments::CardRedirectResponse,
api_models::payments::CardTokenResponse,
api_models::payments::CryptoResponse,
api_models::payments::GiftCardResponse,
api_models::payments::OpenBankingResponse,
api_models::payments::RealTimePaymentDataResponse,
api_models::payments::UpiResponse,
api_models::payments::VoucherResponse,
api_models::payments::additional_info::CardTokenAdditionalData,
api_models::payments::additional_info::BankDebitAdditionalData,
api_models::payments::additional_info::AchBankDebitAdditionalData,
api_models::payments::additional_info::BacsBankDebitAdditionalData,
api_models::payments::additional_info::BecsBankDebitAdditionalData,
api_models::payments::additional_info::SepaBankDebitAdditionalData,
api_models::payments::additional_info::BankRedirectDetails,
api_models::payments::additional_info::BancontactBankRedirectAdditionalData,
api_models::payments::additional_info::BlikBankRedirectAdditionalData,
api_models::payments::additional_info::GiropayBankRedirectAdditionalData,
api_models::payments::additional_info::BankTransferAdditionalData,
api_models::payments::additional_info::PixBankTransferAdditionalData,
api_models::payments::additional_info::LocalBankTransferAdditionalData,
api_models::payments::additional_info::GiftCardAdditionalData,
api_models::payments::additional_info::GivexGiftCardAdditionalData,
api_models::payments::additional_info::UpiAdditionalData,
api_models::payments::additional_info::UpiCollectAdditionalData,
api_models::payments::additional_info::WalletAdditionalDataForCard,
api_models::payments::PaymentsDynamicTaxCalculationRequest,
api_models::payments::WalletResponse,
api_models::payments::WalletResponseData,
api_models::payments::PaymentsDynamicTaxCalculationResponse,
api_models::payments::DisplayAmountOnSdk,
api_models::payments::PaymentsPostSessionTokensRequest,
api_models::payments::PaymentsPostSessionTokensResponse,
api_models::payments::PaymentsUpdateMetadataRequest,
api_models::payments::PaymentsUpdateMetadataResponse,
api_models::payments::CtpServiceDetails,
api_models::payments::AdyenConnectorMetadata,
api_models::payments::AdyenTestingData,
api_models::feature_matrix::FeatureMatrixListResponse,
api_models::feature_matrix::FeatureMatrixRequest,
api_models::feature_matrix::ConnectorFeatureMatrixResponse,
api_models::feature_matrix::PaymentMethodSpecificFeatures,
api_models::feature_matrix::CardSpecificFeatures,
api_models::feature_matrix::SupportedPaymentMethod,
api_models::open_router::DecisionEngineSuccessRateData,
api_models::open_router::DecisionEngineGatewayWiseExtraScore,
api_models::open_router::DecisionEngineSRSubLevelInputConfig,
api_models::open_router::DecisionEngineEliminationData,
api_models::profile_acquirer::ProfileAcquirerCreate,
api_models::profile_acquirer::ProfileAcquirerUpdate,
api_models::profile_acquirer::ProfileAcquirerResponse,
euclid::frontend::dir::enums::CustomerDevicePlatform,
euclid::frontend::dir::enums::CustomerDeviceType,
euclid::frontend::dir::enums::CustomerDeviceDisplaySize,
api_models::authentication::AuthenticationCreateRequest,
api_models::authentication::AuthenticationResponse,
api_models::authentication::AcquirerDetails,
api_models::authentication::NextAction,
common_utils::request::Method,
api_models::authentication::EligibilityResponseParams,
api_models::authentication::ThreeDsData,
api_models::authentication::AuthenticationEligibilityRequest,
api_models::authentication::AuthenticationEligibilityResponse,
api_models::authentication::AuthenticationSyncRequest,
api_models::authentication::AuthenticationSyncResponse,
api_models::open_router::OpenRouterDecideGatewayRequest,
api_models::open_router::DecideGatewayResponse,
api_models::open_router::UpdateScorePayload,
api_models::open_router::UpdateScoreResponse,
api_models::routing::RoutingEvaluateRequest,
api_models::routing::RoutingEvaluateResponse,
api_models::routing::ValueType,
api_models::routing::DeRoutableConnectorChoice,
api_models::routing::RoutableConnectorChoice,
api_models::open_router::PaymentInfo,
common_utils::id_type::PaymentId,
common_utils::id_type::ProfileId,
api_models::open_router::RankingAlgorithm,
api_models::open_router::TxnStatus,
api_models::open_router::PriorityLogicOutput,
api_models::open_router::PriorityLogicData,
api_models::user::PlatformAccountCreateRequest,
api_models::user::PlatformAccountCreateResponse,
common_utils::id_type::CustomerId,
common_utils::id_type::SubscriptionId,
common_utils::id_type::MerchantId,
common_utils::id_type::InvoiceId,
common_utils::id_type::MerchantConnectorAccountId,
api_models::enums::connector_enums::InvoiceStatus,
api_models::subscription::ClientSecret,
api_models::subscription::CreateAndConfirmSubscriptionRequest,
api_models::subscription::CreateSubscriptionRequest,
api_models::subscription::ConfirmSubscriptionRequest,
api_models::subscription::UpdateSubscriptionRequest,
api_models::subscription::SubscriptionResponse,
api_models::subscription::GetPlansResponse,
api_models::subscription::EstimateSubscriptionResponse,
api_models::subscription::GetPlansQuery,
api_models::subscription::EstimateSubscriptionQuery,
api_models::subscription::ConfirmSubscriptionPaymentDetails,
api_models::subscription::PaymentDetails,
api_models::subscription::CreateSubscriptionPaymentDetails,
api_models::subscription::SubscriptionLineItem,
api_models::subscription::SubscriptionPlanPrices,
api_models::subscription::PaymentResponseData,
api_models::subscription::Invoice,
api_models::subscription::SubscriptionStatus,
api_models::subscription::PeriodUnit,
)),
modifiers(&SecurityAddon)
)]
// Bypass clippy lint for not being constructed
#[allow(dead_code)]
pub(crate) struct ApiDoc;
struct SecurityAddon;
impl utoipa::Modify for SecurityAddon {
fn modify(&self, openapi: &mut utoipa::openapi::OpenApi) {
use utoipa::openapi::security::{
ApiKey, ApiKeyValue, HttpAuthScheme, HttpBuilder, SecurityScheme,
};
if let Some(components) = openapi.components.as_mut() {
components.add_security_schemes_from_iter([
(
"api_key",
SecurityScheme::ApiKey(ApiKey::Header(ApiKeyValue::with_description(
"api-key",
"Use the API key created under your merchant account from the HyperSwitch dashboard. API key is used to authenticate API requests from your merchant server only. Don't expose this key on a website or embed it in a mobile application."
))),
),
(
"admin_api_key",
SecurityScheme::ApiKey(ApiKey::Header(ApiKeyValue::with_description(
"api-key",
"Admin API keys allow you to perform some privileged actions such as \
creating a merchant account and Merchant Connector account."
))),
),
(
"publishable_key",
SecurityScheme::ApiKey(ApiKey::Header(ApiKeyValue::with_description(
"api-key",
"Publishable keys are a type of keys that can be public and have limited \
scope of usage."
))),
),
(
"ephemeral_key",
SecurityScheme::ApiKey(ApiKey::Header(ApiKeyValue::with_description(
"api-key",
"Ephemeral keys provide temporary access to singular data, such as access \
to a single customer object for a short period of time."
))),
),
(
"jwt_key",
SecurityScheme::Http(HttpBuilder::new().scheme(HttpAuthScheme::Bearer).bearer_format("JWT").build())
)
]);
}
}
}
| crates/openapi/src/openapi.rs | openapi::src::openapi | 10,098 | true |
// File: crates/openapi/src/lib.rs
// Module: openapi::src::lib
pub mod routes;
| crates/openapi/src/lib.rs | openapi::src::lib | 24 | true |
// File: crates/openapi/src/routes.rs
// Module: openapi::src::routes
#![allow(unused)]
pub mod api_keys;
pub mod authentication;
pub mod blocklist;
pub mod customers;
pub mod disputes;
pub mod gsm;
pub mod mandates;
pub mod merchant_account;
pub mod merchant_connector_account;
pub mod organization;
pub mod payment_link;
pub mod payment_method;
pub mod payments;
pub mod payouts;
pub mod platform;
pub mod poll;
pub mod profile;
pub mod profile_acquirer;
pub mod proxy;
pub mod refunds;
pub mod relay;
pub mod revenue_recovery;
pub mod routing;
pub mod subscriptions;
pub mod three_ds_decision_rule;
pub mod tokenization;
pub mod webhook_events;
| crates/openapi/src/routes.rs | openapi::src::routes | 149 | true |
// File: crates/openapi/src/main.rs
// Module: openapi::src::main
#[cfg(feature = "v1")]
mod openapi;
#[cfg(feature = "v2")]
mod openapi_v2;
mod routes;
#[allow(clippy::print_stdout)] // Using a logger is not necessary here
fn main() {
#[cfg(all(feature = "v1", feature = "v2"))]
compile_error!("features v1 and v2 are mutually exclusive, please enable only one of them");
#[cfg(feature = "v1")]
let relative_file_path = "api-reference/v1/openapi_spec_v1.json";
#[cfg(feature = "v2")]
let relative_file_path = "api-reference/v2/openapi_spec_v2.json";
#[cfg(any(feature = "v1", feature = "v2"))]
let mut file_path = router_env::workspace_path();
#[cfg(any(feature = "v1", feature = "v2"))]
file_path.push(relative_file_path);
#[cfg(feature = "v1")]
let openapi = <openapi::ApiDoc as utoipa::OpenApi>::openapi();
#[cfg(feature = "v2")]
let openapi = <openapi_v2::ApiDoc as utoipa::OpenApi>::openapi();
#[allow(clippy::expect_used)]
#[cfg(any(feature = "v1", feature = "v2"))]
std::fs::write(
&file_path,
openapi
.to_pretty_json()
.expect("Failed to serialize OpenAPI specification as JSON"),
)
.expect("Failed to write OpenAPI specification to file");
#[allow(clippy::expect_used)]
#[cfg(feature = "v1")]
{
// TODO: Do this using utoipa::extensions after we have upgraded to 5.x
let file_content =
std::fs::read_to_string(&file_path).expect("Failed to read OpenAPI specification file");
let mut lines: Vec<&str> = file_content.lines().collect();
// Insert the new text at line 3 (index 2)
if lines.len() > 2 {
let new_line = " \"x-mcp\": {\n \"enabled\": true\n },";
lines.insert(2, new_line);
}
let modified_content = lines.join("\n");
std::fs::write(&file_path, modified_content)
.expect("Failed to write modified OpenAPI specification to file");
}
#[cfg(any(feature = "v1", feature = "v2"))]
println!("Successfully saved OpenAPI specification file at '{relative_file_path}'");
#[cfg(not(any(feature = "v1", feature = "v2")))]
println!("No feature enabled to generate OpenAPI specification, please enable either 'v1' or 'v2' feature");
}
| crates/openapi/src/main.rs | openapi::src::main | 616 | true |
// File: crates/openapi/src/openapi_v2.rs
// Module: openapi::src::openapi_v2
use crate::routes;
#[derive(utoipa::OpenApi)]
#[openapi(
info(
title = "Hyperswitch - API Documentation",
contact(
name = "Hyperswitch Support",
url = "https://hyperswitch.io",
email = "hyperswitch@juspay.in"
),
// terms_of_service = "https://www.juspay.io/terms",
description = r#"
## Get started
Hyperswitch provides a collection of APIs that enable you to process and manage payments.
Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes.
You can consume the APIs directly using your favorite HTTP/REST library.
We have a testing environment referred to "sandbox", which you can setup to test API calls without
affecting production data.
Currently, our sandbox environment is live while our production environment is under development
and will be available soon.
You can sign up on our Dashboard to get API keys to access Hyperswitch API.
### Environment
Use the following base URLs when making requests to the APIs:
| Environment | Base URL |
|---------------|------------------------------------|
| Sandbox | <https://sandbox.hyperswitch.io> |
| Production | <https://api.hyperswitch.io> |
## Authentication
When you sign up on our [dashboard](https://app.hyperswitch.io) and create a merchant
account, you are given a secret key (also referred as api-key) and a publishable key.
You may authenticate all API requests with Hyperswitch server by providing the appropriate key in
the request Authorization header.
| Key | Description |
|-----------------|-----------------------------------------------------------------------------------------------|
| api-key | Private key. Used to authenticate all API requests from your merchant server |
| publishable key | Unique identifier for your account. Used to authenticate API requests from your app's client |
Never share your secret api keys. Keep them guarded and secure.
"#,
),
servers(
(url = "https://sandbox.hyperswitch.io", description = "Sandbox Environment")
),
tags(
(name = "Merchant Account", description = "Create and manage merchant accounts"),
(name = "Profile", description = "Create and manage profiles"),
(name = "Merchant Connector Account", description = "Create and manage merchant connector accounts"),
(name = "Payments", description = "Create and manage one-time payments, recurring payments and mandates"),
(name = "Refunds", description = "Create and manage refunds for successful payments"),
(name = "Mandates", description = "Manage mandates"),
(name = "Customers", description = "Create and manage customers"),
(name = "Payment Methods", description = "Create and manage payment methods of customers"),
(name = "Disputes", description = "Manage disputes"),
(name = "API Key", description = "Create and manage API Keys"),
(name = "Payouts", description = "Create and manage payouts"),
(name = "payment link", description = "Create payment link"),
(name = "Routing", description = "Create and manage routing configurations"),
(name = "Event", description = "Manage events"),
),
// The paths will be displayed in the same order as they are registered here
paths(
// Routes for Organization
routes::organization::organization_create,
routes::organization::organization_retrieve,
routes::organization::organization_update,
routes::organization::merchant_account_list,
// Routes for merchant connector account
routes::merchant_connector_account::connector_create,
routes::merchant_connector_account::connector_retrieve,
routes::merchant_connector_account::connector_update,
routes::merchant_connector_account::connector_delete,
// Routes for merchant account
routes::merchant_account::merchant_account_create,
routes::merchant_account::merchant_account_retrieve,
routes::merchant_account::merchant_account_update,
routes::merchant_account::profiles_list,
// Routes for profile
routes::profile::profile_create,
routes::profile::profile_retrieve,
routes::profile::profile_update,
routes::profile::connector_list,
// Routes for routing under profile
routes::profile::routing_link_config,
routes::profile::routing_unlink_config,
routes::profile::routing_update_default_config,
routes::profile::routing_retrieve_default_config,
routes::profile::routing_retrieve_linked_config,
// Routes for routing
routes::routing::routing_create_config,
routes::routing::routing_retrieve_config,
// Routes for api keys
routes::api_keys::api_key_create,
routes::api_keys::api_key_retrieve,
routes::api_keys::api_key_update,
routes::api_keys::api_key_revoke,
routes::api_keys::api_key_list,
//Routes for customers
routes::customers::customers_create,
routes::customers::customers_retrieve,
routes::customers::customers_update,
routes::customers::customers_delete,
routes::customers::customers_list,
//Routes for payments
routes::payments::payments_create_intent,
routes::payments::payments_get_intent,
routes::payments::payments_update_intent,
routes::payments::payments_confirm_intent,
routes::payments::payment_status,
routes::payments::payments_create_and_confirm_intent,
routes::payments::payments_connector_session,
routes::payments::list_payment_methods,
routes::payments::payments_list,
routes::payments::payment_check_gift_card_balance,
//Routes for payment methods
routes::payment_method::create_payment_method_api,
routes::payment_method::create_payment_method_intent_api,
routes::payment_method::confirm_payment_method_intent_api,
routes::payment_method::payment_method_update_api,
routes::payment_method::payment_method_retrieve_api,
routes::payment_method::payment_method_delete_api,
routes::payment_method::network_token_status_check_api,
routes::payment_method::list_customer_payment_method_api,
//Routes for payment method session
routes::payment_method::payment_method_session_create,
routes::payment_method::payment_method_session_retrieve,
routes::payment_method::payment_method_session_list_payment_methods,
routes::payment_method::payment_method_session_update_saved_payment_method,
routes::payment_method::payment_method_session_delete_saved_payment_method,
routes::payment_method::payment_method_session_confirm,
//Routes for refunds
routes::refunds::refunds_create,
routes::refunds::refunds_metadata_update,
routes::refunds::refunds_retrieve,
routes::refunds::refunds_list,
// Routes for Revenue Recovery flow under Process Tracker
routes::revenue_recovery::revenue_recovery_pt_retrieve_api,
// Routes for proxy
routes::proxy::proxy_core,
// Route for tokenization
routes::tokenization::create_token_vault_api,
routes::tokenization::delete_tokenized_data_api,
),
components(schemas(
common_utils::types::MinorUnit,
common_utils::types::StringMinorUnit,
common_utils::types::TimeRange,
common_utils::types::BrowserInformation,
common_utils::link_utils::GenericLinkUiConfig,
common_utils::link_utils::EnabledPaymentMethod,
common_utils::payout_method_utils::AdditionalPayoutMethodData,
common_utils::payout_method_utils::CardAdditionalData,
common_utils::payout_method_utils::BankAdditionalData,
common_utils::payout_method_utils::WalletAdditionalData,
common_utils::payout_method_utils::BankRedirectAdditionalData,
common_utils::payout_method_utils::AchBankTransferAdditionalData,
common_utils::payout_method_utils::BacsBankTransferAdditionalData,
common_utils::payout_method_utils::SepaBankTransferAdditionalData,
common_utils::payout_method_utils::PixBankTransferAdditionalData,
common_utils::payout_method_utils::PaypalAdditionalData,
common_utils::payout_method_utils::InteracAdditionalData,
common_utils::payout_method_utils::VenmoAdditionalData,
common_utils::payout_method_utils::ApplePayDecryptAdditionalData,
common_types::payments::SplitPaymentsRequest,
common_types::payments::GpayTokenizationData,
common_types::payments::GPayPredecryptData,
common_types::payments::GpayEcryptedTokenizationData,
common_types::payments::ApplePayPaymentData,
common_types::payments::ApplePayPredecryptData,
common_types::payments::ApplePayCryptogramData,
common_types::payments::ApplePayPaymentData,
common_types::payments::StripeSplitPaymentRequest,
common_types::domain::AdyenSplitData,
common_types::payments::AcceptanceType,
common_types::payments::CustomerAcceptance,
common_types::payments::OnlineMandate,
common_types::payments::XenditSplitRequest,
common_types::payments::XenditSplitRoute,
common_types::payments::XenditChargeResponseData,
common_types::payments::XenditMultipleSplitResponse,
common_types::payments::XenditMultipleSplitRequest,
common_types::domain::XenditSplitSubMerchantData,
common_types::domain::AdyenSplitItem,
common_types::domain::MerchantConnectorAuthDetails,
common_types::refunds::StripeSplitRefundRequest,
common_utils::types::ChargeRefunds,
common_types::payment_methods::PaymentMethodsEnabled,
common_types::payment_methods::PspTokenization,
common_types::payment_methods::NetworkTokenization,
common_types::refunds::SplitRefund,
common_types::payments::ConnectorChargeResponseData,
common_types::payments::StripeChargeResponseData,
common_types::three_ds_decision_rule_engine::ThreeDSDecisionRule,
common_types::three_ds_decision_rule_engine::ThreeDSDecision,
common_types::payments::MerchantCountryCode,
common_utils::request::Method,
api_models::errors::types::GenericErrorResponseOpenApi,
api_models::refunds::RefundsCreateRequest,
api_models::refunds::RefundErrorDetails,
api_models::refunds::RefundType,
api_models::refunds::RefundResponse,
api_models::refunds::RefundStatus,
api_models::refunds::RefundMetadataUpdateRequest,
api_models::organization::OrganizationCreateRequest,
api_models::organization::OrganizationUpdateRequest,
api_models::organization::OrganizationResponse,
api_models::admin::MerchantAccountCreateWithoutOrgId,
api_models::admin::MerchantAccountUpdate,
api_models::admin::MerchantAccountDeleteResponse,
api_models::admin::MerchantConnectorDeleteResponse,
api_models::admin::MerchantConnectorResponse,
api_models::admin::MerchantConnectorListResponse,
api_models::admin::AuthenticationConnectorDetails,
api_models::admin::ExternalVaultConnectorDetails,
api_models::admin::ExtendedCardInfoConfig,
api_models::admin::BusinessGenericLinkConfig,
api_models::admin::BusinessCollectLinkConfig,
api_models::admin::BusinessPayoutLinkConfig,
api_models::admin::MerchantConnectorAccountFeatureMetadata,
api_models::admin::RevenueRecoveryMetadata,
api_models::customers::CustomerRequest,
api_models::customers::CustomerUpdateRequest,
api_models::customers::CustomerDeleteResponse,
api_models::ephemeral_key::ResourceId,
api_models::payment_methods::PaymentMethodCreate,
api_models::payment_methods::PaymentMethodIntentCreate,
api_models::payment_methods::PaymentMethodIntentConfirm,
api_models::payment_methods::AuthenticationDetails,
api_models::payment_methods::PaymentMethodResponse,
api_models::payment_methods::PaymentMethodResponseData,
api_models::payment_methods::CustomerPaymentMethodResponseItem,
api_models::payment_methods::PaymentMethodResponseItem,
api_models::payment_methods::ListMethodsForPaymentMethodsRequest,
api_models::payment_methods::PaymentMethodListResponseForSession,
api_models::payment_methods::CustomerPaymentMethodsListResponse,
api_models::payment_methods::ResponsePaymentMethodsEnabled,
api_models::payment_methods::PaymentMethodSubtypeSpecificData,
api_models::payment_methods::ResponsePaymentMethodTypes,
api_models::payment_methods::PaymentExperienceTypes,
api_models::payment_methods::CardNetworkTypes,
api_models::payment_methods::BankDebitTypes,
api_models::payment_methods::BankTransferTypes,
api_models::payment_methods::PaymentMethodDeleteResponse,
api_models::payment_methods::PaymentMethodUpdate,
api_models::payment_methods::PaymentMethodUpdateData,
api_models::payment_methods::CardDetailFromLocker,
api_models::payment_methods::PaymentMethodCreateData,
api_models::payment_methods::ProxyCardDetails,
api_models::payment_methods::CardDetail,
api_models::payment_methods::CardDetailUpdate,
api_models::payment_methods::CardType,
api_models::payment_methods::RequestPaymentMethodTypes,
api_models::payment_methods::CardType,
api_models::payment_methods::PaymentMethodListData,
api_models::payment_methods::NetworkTokenStatusCheckResponse,
api_models::payment_methods::NetworkTokenStatusCheckSuccessResponse,
api_models::payment_methods::NetworkTokenStatusCheckFailureResponse,
api_models::enums::TokenStatus,
api_models::poll::PollResponse,
api_models::poll::PollStatus,
api_models::customers::CustomerResponse,
api_models::admin::AcceptedCountries,
api_models::admin::AcceptedCurrencies,
api_models::enums::AdyenSplitType,
api_models::enums::ProductType,
api_models::enums::PaymentType,
api_models::enums::ScaExemptionType,
api_models::enums::PaymentMethod,
api_models::enums::PaymentMethodType,
api_models::enums::ConnectorType,
api_models::enums::PayoutConnectors,
api_models::enums::AuthenticationConnectors,
api_models::enums::VaultSdk,
api_models::enums::Currency,
api_models::enums::DocumentKind,
api_models::enums::IntentStatus,
api_models::enums::CaptureMethod,
api_models::enums::FutureUsage,
api_models::enums::AuthenticationType,
api_models::enums::Connector,
api_models::enums::PaymentMethod,
api_models::enums::PaymentMethodIssuerCode,
api_models::enums::MandateStatus,
api_models::enums::MerchantProductType,
api_models::enums::PaymentExperience,
api_models::enums::BankNames,
api_models::enums::BankType,
api_models::enums::BankHolderType,
api_models::enums::CardNetwork,
api_models::enums::MerchantCategoryCode,
api_models::enums::TokenDataType,
api_models::enums::DisputeStage,
api_models::enums::DisputeStatus,
api_models::enums::CountryAlpha2,
api_models::enums::CountryAlpha3,
api_models::enums::FieldType,
api_models::enums::FrmAction,
api_models::enums::FrmPreferredFlowTypes,
api_models::enums::RetryAction,
api_models::enums::AttemptStatus,
api_models::enums::CaptureStatus,
api_models::enums::ReconStatus,
api_models::enums::ConnectorStatus,
api_models::enums::AuthorizationStatus,
api_models::enums::ElementPosition,
api_models::enums::ElementSize,
api_models::enums::TaxStatus,
api_models::enums::SizeVariants,
api_models::enums::MerchantProductType,
api_models::enums::PaymentLinkDetailsLayout,
api_models::enums::PaymentMethodStatus,
api_models::enums::HyperswitchConnectorCategory,
api_models::enums::ConnectorIntegrationStatus,
api_models::enums::FeatureStatus,
api_models::enums::OrderFulfillmentTimeOrigin,
api_models::enums::UIWidgetFormLayout,
api_models::enums::MerchantProductType,
api_models::enums::CtpServiceProvider,
api_models::enums::PaymentLinkSdkLabelType,
api_models::enums::PaymentLinkShowSdkTerms,
api_models::enums::OrganizationType,
api_models::enums::GooglePayCardFundingSource,
api_models::admin::MerchantConnectorCreate,
api_models::admin::AdditionalMerchantData,
api_models::admin::CardTestingGuardConfig,
api_models::admin::CardTestingGuardStatus,
api_models::admin::ConnectorWalletDetails,
api_models::admin::MerchantRecipientData,
api_models::admin::MerchantAccountData,
api_models::admin::MerchantConnectorUpdate,
api_models::admin::PrimaryBusinessDetails,
api_models::admin::FrmConfigs,
api_models::admin::FrmPaymentMethod,
api_models::admin::FrmPaymentMethodType,
api_models::admin::MerchantConnectorDetailsWrap,
api_models::admin::MerchantConnectorDetails,
api_models::admin::MerchantConnectorWebhookDetails,
api_models::admin::ProfileCreate,
api_models::admin::ProfileResponse,
api_models::admin::BusinessPaymentLinkConfig,
api_models::admin::PaymentLinkBackgroundImageConfig,
api_models::admin::PaymentLinkConfigRequest,
api_models::admin::PaymentLinkConfig,
api_models::admin::PaymentLinkTransactionDetails,
api_models::admin::TransactionDetailsUiConfiguration,
api_models::disputes::DisputeResponse,
api_models::disputes::DisputeResponsePaymentsRetrieve,
api_models::gsm::GsmCreateRequest,
api_models::gsm::GsmRetrieveRequest,
api_models::gsm::GsmUpdateRequest,
api_models::gsm::GsmDeleteRequest,
api_models::gsm::GsmDeleteResponse,
api_models::gsm::GsmResponse,
api_models::enums::GsmDecision,
api_models::enums::GsmFeature,
common_types::domain::GsmFeatureData,
common_types::domain::RetryFeatureData,
api_models::payments::NullObject,
api_models::payments::AddressDetails,
api_models::payments::BankDebitData,
api_models::payments::AliPayQr,
api_models::payments::PaymentAttemptFeatureMetadata,
api_models::payments::PaymentAttemptRevenueRecoveryData,
api_models::payments::BillingConnectorPaymentMethodDetails,
api_models::payments::RecordAttemptErrorDetails,
api_models::payments::BillingConnectorAdditionalCardInfo,
api_models::payments::AliPayRedirection,
api_models::payments::MomoRedirection,
api_models::payments::TouchNGoRedirection,
api_models::payments::GcashRedirection,
api_models::payments::KakaoPayRedirection,
api_models::payments::AliPayHkRedirection,
api_models::payments::GoPayRedirection,
api_models::payments::MbWayRedirection,
api_models::payments::MobilePayRedirection,
api_models::payments::WeChatPayRedirection,
api_models::payments::WeChatPayQr,
api_models::payments::BankDebitBilling,
api_models::payments::CryptoData,
api_models::payments::RewardData,
api_models::payments::UpiData,
api_models::payments::UpiCollectData,
api_models::payments::UpiIntentData,
api_models::payments::UpiQrData,
api_models::payments::VoucherData,
api_models::payments::BoletoVoucherData,
api_models::payments::AlfamartVoucherData,
api_models::payments::IndomaretVoucherData,
api_models::payments::Address,
api_models::payments::VoucherData,
api_models::payments::JCSVoucherData,
api_models::payments::AlfamartVoucherData,
api_models::payments::IndomaretVoucherData,
api_models::payments::BankRedirectData,
api_models::payments::RealTimePaymentData,
api_models::payments::BankRedirectBilling,
api_models::payments::BankRedirectBilling,
api_models::payments::ConnectorMetadata,
api_models::payments::FeatureMetadata,
api_models::payments::SdkType,
api_models::payments::ApplepayConnectorMetadataRequest,
api_models::payments::SessionTokenInfo,
api_models::payments::PaymentProcessingDetailsAt,
api_models::payments::ApplepayInitiative,
api_models::payments::PaymentProcessingDetails,
api_models::payments::PaymentMethodDataResponseWithBilling,
api_models::payments::PaymentMethodDataResponse,
api_models::payments::CardResponse,
api_models::payments::PaylaterResponse,
api_models::payments::KlarnaSdkPaymentMethodResponse,
api_models::payments::SwishQrData,
api_models::payments::RevolutPayData,
api_models::payments::AirwallexData,
api_models::payments::BraintreeData,
api_models::payments::NoonData,
api_models::payments::OrderDetailsWithAmount,
api_models::payments::NextActionType,
api_models::payments::WalletData,
api_models::payments::NextActionData,
api_models::payments::PayLaterData,
api_models::payments::MandateData,
api_models::payments::PhoneDetails,
api_models::payments::PaymentMethodData,
api_models::payments::PaymentMethodDataRequest,
api_models::payments::SplitPaymentMethodDataRequest,
api_models::payments::MandateType,
api_models::payments::MandateAmountData,
api_models::payments::Card,
api_models::payments::CardRedirectData,
api_models::payments::CardToken,
api_models::payments::ConnectorTokenDetails,
api_models::payments::PaymentsRequest,
api_models::payments::PaymentsResponse,
api_models::payments::PaymentsListResponseItem,
api_models::payments::PaymentsRetrieveRequest,
api_models::payments::PaymentsStatusRequest,
api_models::payments::PaymentsCaptureRequest,
api_models::payments::PaymentsSessionRequest,
api_models::payments::PaymentsSessionResponse,
api_models::payments::PaymentsCreateIntentRequest,
api_models::payments::PaymentsUpdateIntentRequest,
api_models::payments::PaymentsIntentResponse,
api_models::payments::PaymentAttemptListRequest,
api_models::payments::PaymentAttemptListResponse,
api_models::payments::PazeWalletData,
api_models::payments::AmountDetails,
api_models::payments::AmountDetailsUpdate,
api_models::payments::SessionToken,
api_models::payments::VaultSessionDetails,
api_models::payments::VgsSessionDetails,
api_models::payments::HyperswitchVaultSessionDetails,
api_models::payments::ApplePaySessionResponse,
api_models::payments::ThirdPartySdkSessionResponse,
api_models::payments::NoThirdPartySdkSessionResponse,
api_models::payments::SecretInfoToInitiateSdk,
api_models::payments::ApplePayPaymentRequest,
api_models::payments::ApplePayBillingContactFields,
api_models::payments::ApplePayShippingContactFields,
api_models::payments::ApplePayAddressParameters,
api_models::payments::ApplePayRecurringPaymentRequest,
api_models::payments::ApplePayRegularBillingRequest,
api_models::payments::ApplePayPaymentTiming,
api_models::payments::RecurringPaymentIntervalUnit,
api_models::payments::ApplePayRecurringDetails,
api_models::payments::ApplePayRegularBillingDetails,
api_models::payments::AmountInfo,
api_models::payments::GooglePayWalletData,
api_models::payments::PayPalWalletData,
api_models::payments::PaypalRedirection,
api_models::payments::GpayMerchantInfo,
api_models::payments::GpayAllowedPaymentMethods,
api_models::payments::GpayAllowedMethodsParameters,
api_models::payments::GpayTokenizationSpecification,
api_models::payments::GpayTokenParameters,
api_models::payments::GpayTransactionInfo,
api_models::payments::GpaySessionTokenResponse,
api_models::payments::GooglePayThirdPartySdkData,
api_models::payments::KlarnaSessionTokenResponse,
api_models::payments::PaypalSessionTokenResponse,
api_models::payments::PaypalFlow,
api_models::payments::PaypalTransactionInfo,
api_models::payments::ApplepaySessionTokenResponse,
api_models::payments::SdkNextAction,
api_models::payments::NextActionCall,
api_models::payments::SdkNextActionData,
api_models::payments::SamsungPayWalletData,
api_models::payments::WeChatPay,
api_models::payments::GooglePayPaymentMethodInfo,
api_models::payments::ApplePayWalletData,
api_models::payments::ApplepayPaymentMethod,
api_models::payments::PazeSessionTokenResponse,
api_models::payments::SamsungPaySessionTokenResponse,
api_models::payments::SamsungPayMerchantPaymentInformation,
api_models::payments::SamsungPayAmountDetails,
api_models::payments::SamsungPayAmountFormat,
api_models::payments::SamsungPayProtocolType,
api_models::payments::SamsungPayWalletCredentials,
api_models::payments::SamsungPayWebWalletData,
api_models::payments::SamsungPayAppWalletData,
api_models::payments::SamsungPayCardBrand,
api_models::payments::SamsungPayTokenData,
api_models::payments::PaymentsCancelRequest,
api_models::payments::PaymentListResponse,
api_models::payments::CashappQr,
api_models::payments::BankTransferData,
api_models::payments::BankTransferNextStepsData,
api_models::payments::SepaAndBacsBillingDetails,
api_models::payments::AchBillingDetails,
api_models::payments::MultibancoBillingDetails,
api_models::payments::DokuBillingDetails,
api_models::payments::BankTransferInstructions,
api_models::payments::MobilePaymentNextStepData,
api_models::payments::MobilePaymentConsent,
api_models::payments::IframeData,
api_models::payments::ReceiverDetails,
api_models::payments::AchTransfer,
api_models::payments::MultibancoTransferInstructions,
api_models::payments::DokuBankTransferInstructions,
api_models::payments::AmazonPayRedirectData,
api_models::payments::SkrillData,
api_models::payments::PayseraData,
api_models::payments::ApplePayRedirectData,
api_models::payments::ApplePayThirdPartySdkData,
api_models::payments::GooglePayRedirectData,
api_models::payments::GooglePayThirdPartySdk,
api_models::mandates::NetworkTransactionIdAndCardDetails,
api_models::payments::GooglePaySessionResponse,
api_models::payments::GpayShippingAddressParameters,
api_models::payments::GpayBillingAddressParameters,
api_models::payments::GpayBillingAddressFormat,
api_models::payments::SepaBankTransferInstructions,
api_models::payments::BacsBankTransferInstructions,
api_models::payments::RedirectResponse,
api_models::payments::RequestSurchargeDetails,
api_models::payments::PaymentRevenueRecoveryMetadata,
api_models::payments::BillingConnectorPaymentDetails,
api_models::payments::GiftCardBalanceCheckResponse,
api_models::payments::PaymentsGiftCardBalanceCheckRequest,
api_models::enums::PaymentConnectorTransmission,
api_models::enums::TriggeredBy,
api_models::payments::PaymentAttemptResponse,
api_models::payments::PaymentAttemptRecordResponse,
api_models::payments::PaymentAttemptAmountDetails,
api_models::payments::CaptureResponse,
api_models::payments::PaymentsIncrementalAuthorizationRequest,
api_models::payments::IncrementalAuthorizationResponse,
api_models::payments::PaymentsCompleteAuthorizeRequest,
api_models::payments::PaymentsExternalAuthenticationRequest,
api_models::payments::PaymentsExternalAuthenticationResponse,
api_models::payments::SdkInformation,
api_models::payments::DeviceChannel,
api_models::payments::ThreeDsCompletionIndicator,
api_models::payments::MifinityData,
api_models::payments::ClickToPaySessionResponse,
api_models::enums::TransactionStatus,
api_models::payments::PaymentCreatePaymentLinkConfig,
api_models::payments::ThreeDsData,
api_models::payments::ThreeDsMethodData,
api_models::payments::ThreeDsMethodKey,
api_models::payments::PollConfigResponse,
api_models::payments::PollConfig,
api_models::payments::ExternalAuthenticationDetailsResponse,
api_models::payments::ExtendedCardInfo,
api_models::payments::PaymentsConfirmIntentRequest,
api_models::payments::AmountDetailsResponse,
api_models::payments::BankCodeResponse,
api_models::payments::Order,
api_models::payments::SortOn,
api_models::payments::SortBy,
api_models::payments::PaymentMethodListResponseForPayments,
api_models::payments::ResponsePaymentMethodTypesForPayments,
api_models::payment_methods::CardNetworkTokenizeRequest,
api_models::payment_methods::CardNetworkTokenizeResponse,
api_models::payment_methods::CardType,
api_models::payments::AmazonPaySessionTokenData,
api_models::payments::AmazonPayMerchantCredentials,
api_models::payments::AmazonPayWalletData,
api_models::payments::AmazonPaySessionTokenResponse,
api_models::payments::AmazonPayPaymentIntent,
api_models::payments::AmazonPayDeliveryOptions,
api_models::payments::AmazonPayDeliveryPrice,
api_models::payments::AmazonPayShippingMethod,
api_models::payment_methods::RequiredFieldInfo,
api_models::payment_methods::MaskedBankDetails,
api_models::payment_methods::SurchargeDetailsResponse,
api_models::payment_methods::SurchargeResponse,
api_models::payment_methods::SurchargePercentage,
api_models::payment_methods::PaymentMethodCollectLinkRequest,
api_models::payment_methods::PaymentMethodCollectLinkResponse,
api_models::payment_methods::PaymentMethodSubtypeSpecificData,
api_models::payment_methods::PaymentMethodSessionRequest,
api_models::payment_methods::PaymentMethodSessionResponse,
api_models::payment_methods::PaymentMethodsSessionUpdateRequest,
api_models::payment_methods::NetworkTokenResponse,
api_models::payment_methods::NetworkTokenDetailsPaymentMethod,
api_models::payment_methods::NetworkTokenDetailsResponse,
api_models::payment_methods::TokenDataResponse,
api_models::payment_methods::TokenDetailsResponse,
api_models::payment_methods::TokenizeCardRequest,
api_models::payment_methods::TokenizeDataRequest,
api_models::payment_methods::TokenizePaymentMethodRequest,
api_models::refunds::RefundListRequest,
api_models::refunds::RefundListResponse,
api_models::payments::AmountFilter,
api_models::mandates::MandateRevokedResponse,
api_models::mandates::MandateResponse,
api_models::mandates::MandateCardDetails,
api_models::mandates::RecurringDetails,
api_models::mandates::ProcessorPaymentToken,
api_models::ephemeral_key::ClientSecretResponse,
api_models::payments::CustomerDetails,
api_models::payments::GiftCardData,
api_models::payments::GiftCardDetails,
api_models::payments::BHNGiftCardDetails,
api_models::payments::MobilePaymentData,
api_models::payments::MobilePaymentResponse,
api_models::payments::Address,
api_models::payouts::CardPayout,
api_models::payouts::Wallet,
api_models::payouts::Paypal,
api_models::payouts::BankRedirect,
api_models::payouts::Interac,
api_models::payouts::Venmo,
api_models::payouts::AchBankTransfer,
api_models::payouts::BacsBankTransfer,
api_models::payouts::SepaBankTransfer,
api_models::payouts::PixBankTransfer,
api_models::payouts::PayoutRequest,
api_models::payouts::PayoutAttemptResponse,
api_models::payouts::PayoutActionRequest,
api_models::payouts::PayoutCreateRequest,
api_models::payouts::PayoutCreateResponse,
api_models::payouts::PayoutListConstraints,
api_models::payouts::PayoutListFilterConstraints,
api_models::payouts::PayoutListResponse,
api_models::payouts::PayoutRetrieveBody,
api_models::payouts::PayoutRetrieveRequest,
api_models::payouts::PayoutMethodData,
api_models::payouts::PayoutMethodDataResponse,
api_models::payouts::PayoutLinkResponse,
api_models::payouts::Bank,
api_models::payouts::ApplePayDecrypt,
api_models::payouts::PayoutCreatePayoutLinkConfig,
api_models::enums::PayoutEntityType,
api_models::enums::PayoutSendPriority,
api_models::enums::PayoutStatus,
api_models::enums::PayoutType,
api_models::enums::TransactionType,
api_models::enums::PresenceOfCustomerDuringPayment,
api_models::enums::MitExemptionRequest,
api_models::enums::EnablePaymentLinkRequest,
api_models::enums::RequestIncrementalAuthorization,
api_models::enums::SplitTxnsEnabled,
api_models::enums::External3dsAuthenticationRequest,
api_models::enums::TaxCalculationOverride,
api_models::enums::SurchargeCalculationOverride,
api_models::payments::FrmMessage,
api_models::webhooks::OutgoingWebhook,
api_models::webhooks::OutgoingWebhookContent,
api_models::enums::EventClass,
api_models::enums::EventType,
api_models::enums::DecoupledAuthenticationType,
api_models::enums::AuthenticationStatus,
api_models::enums::UpdateActiveAttempt,
api_models::admin::MerchantAccountResponse,
api_models::admin::MerchantConnectorId,
api_models::admin::MerchantDetails,
api_models::admin::ToggleKVRequest,
api_models::admin::ToggleKVResponse,
api_models::admin::WebhookDetails,
api_models::api_keys::ApiKeyExpiration,
api_models::api_keys::CreateApiKeyRequest,
api_models::api_keys::CreateApiKeyResponse,
api_models::api_keys::RetrieveApiKeyResponse,
api_models::api_keys::RevokeApiKeyResponse,
api_models::api_keys::UpdateApiKeyRequest,
api_models::payments::RetrievePaymentLinkRequest,
api_models::payments::PaymentLinkResponse,
api_models::payments::RetrievePaymentLinkResponse,
api_models::payments::PaymentLinkInitiateRequest,
api_models::payouts::PayoutLinkInitiateRequest,
api_models::payments::ExtendedCardInfoResponse,
api_models::payments::GooglePayAssuranceDetails,
api_models::routing::RoutingConfigRequest,
api_models::routing::RoutingDictionaryRecord,
api_models::routing::RoutingKind,
api_models::routing::RoutableConnectorChoice,
api_models::routing::LinkedRoutingConfigRetrieveResponse,
api_models::routing::RoutingRetrieveResponse,
api_models::routing::ProfileDefaultRoutingConfig,
api_models::routing::MerchantRoutingAlgorithm,
api_models::routing::RoutingAlgorithmKind,
api_models::routing::RoutingDictionary,
api_models::routing::DynamicRoutingConfigParams,
api_models::routing::SuccessBasedRoutingConfig,
api_models::routing::SuccessRateSpecificityLevel,
api_models::routing::CurrentBlockThreshold,
api_models::open_router::DecisionEngineSuccessRateData,
api_models::routing::ContractBasedTimeScale,
api_models::routing::LabelInformation,
api_models::routing::ContractBasedRoutingConfig,
api_models::routing::ContractBasedRoutingConfigBody,
api_models::open_router::DecisionEngineGatewayWiseExtraScore,
api_models::open_router::DecisionEngineSRSubLevelInputConfig,
api_models::open_router::DecisionEngineEliminationData,
api_models::routing::SuccessBasedRoutingConfigBody,
api_models::routing::RoutingAlgorithmWrapper,
api_models::routing::EliminationRoutingConfig,
api_models::open_router::DecisionEngineEliminationData,
api_models::routing::EliminationAnalyserConfig,
api_models::routing::DynamicRoutingAlgorithm,
api_models::routing::StaticRoutingAlgorithm,
api_models::routing::StraightThroughAlgorithm,
api_models::routing::ConnectorVolumeSplit,
api_models::routing::ConnectorSelection,
api_models::routing::ast::RoutableChoiceKind,
api_models::routing::ProgramThreeDsDecisionRule,
api_models::routing::RuleThreeDsDecisionRule,
api_models::enums::RoutableConnectors,
api_models::routing::ast::ProgramConnectorSelection,
api_models::routing::ast::RuleConnectorSelection,
api_models::routing::ast::IfStatement,
api_models::routing::ast::Comparison,
api_models::routing::ast::ComparisonType,
api_models::routing::ast::ValueType,
api_models::routing::ast::MetadataValue,
api_models::routing::ast::NumberComparison,
api_models::routing::RoutingAlgorithmId,
api_models::payment_methods::RequestPaymentMethodTypes,
api_models::payments::PaymentLinkStatus,
api_models::blocklist::BlocklistRequest,
api_models::blocklist::BlocklistResponse,
api_models::blocklist::ToggleBlocklistResponse,
api_models::blocklist::ListBlocklistQuery,
api_models::enums::BlocklistDataKind,
api_models::enums::ErrorCategory,
api_models::webhook_events::EventListItemResponse,
api_models::webhook_events::EventRetrieveResponse,
api_models::webhook_events::OutgoingWebhookRequestContent,
api_models::webhook_events::OutgoingWebhookResponseContent,
api_models::enums::WebhookDeliveryAttempt,
api_models::enums::PaymentChargeType,
api_models::enums::StripeChargeType,
api_models::payments::CustomerDetailsResponse,
api_models::payments::OpenBankingData,
api_models::payments::OpenBankingSessionToken,
api_models::payments::BankDebitResponse,
api_models::payments::BankRedirectResponse,
api_models::payments::BankTransferResponse,
api_models::payments::CardRedirectResponse,
api_models::payments::CardTokenResponse,
api_models::payments::CryptoResponse,
api_models::payments::GiftCardResponse,
api_models::payments::OpenBankingResponse,
api_models::payments::RealTimePaymentDataResponse,
api_models::payments::UpiResponse,
api_models::payments::VoucherResponse,
api_models::payments::additional_info::CardTokenAdditionalData,
api_models::payments::additional_info::BankDebitAdditionalData,
api_models::payments::additional_info::AchBankDebitAdditionalData,
api_models::payments::additional_info::BacsBankDebitAdditionalData,
api_models::payments::additional_info::BecsBankDebitAdditionalData,
api_models::payments::additional_info::SepaBankDebitAdditionalData,
api_models::payments::additional_info::BankRedirectDetails,
api_models::payments::additional_info::BancontactBankRedirectAdditionalData,
api_models::payments::additional_info::BlikBankRedirectAdditionalData,
api_models::payments::additional_info::GiropayBankRedirectAdditionalData,
api_models::payments::additional_info::BankTransferAdditionalData,
api_models::payments::additional_info::PixBankTransferAdditionalData,
api_models::payments::additional_info::LocalBankTransferAdditionalData,
api_models::payments::additional_info::GiftCardAdditionalData,
api_models::payments::additional_info::GivexGiftCardAdditionalData,
api_models::payments::additional_info::UpiAdditionalData,
api_models::payments::additional_info::UpiCollectAdditionalData,
api_models::payments::additional_info::WalletAdditionalDataForCard,
api_models::payments::WalletResponse,
api_models::payments::WalletResponseData,
api_models::payments::PaymentsDynamicTaxCalculationRequest,
api_models::payments::PaymentsDynamicTaxCalculationResponse,
api_models::payments::DisplayAmountOnSdk,
api_models::payments::ErrorDetails,
api_models::payments::CtpServiceDetails,
api_models::payments::AdyenConnectorMetadata,
api_models::payments::AdyenTestingData,
api_models::feature_matrix::FeatureMatrixListResponse,
api_models::feature_matrix::FeatureMatrixRequest,
api_models::feature_matrix::ConnectorFeatureMatrixResponse,
api_models::feature_matrix::PaymentMethodSpecificFeatures,
api_models::feature_matrix::CardSpecificFeatures,
api_models::feature_matrix::SupportedPaymentMethod,
api_models::payment_methods::PaymentMethodSessionUpdateSavedPaymentMethod,
api_models::payment_methods::PaymentMethodSessionDeleteSavedPaymentMethod,
common_utils::types::BrowserInformation,
api_models::enums::TokenizationType,
api_models::enums::NetworkTokenizationToggle,
api_models::payments::PaymentAmountDetailsResponse,
api_models::payment_methods::PaymentMethodSessionConfirmRequest,
api_models::payment_methods::PaymentMethodSessionResponse,
api_models::payment_methods::AuthenticationDetails,
api_models::process_tracker::revenue_recovery::RevenueRecoveryResponse,
api_models::enums::RevenueRecoveryAlgorithmType,
api_models::enums::ProcessTrackerStatus,
api_models::proxy::ProxyRequest,
api_models::proxy::ProxyResponse,
api_models::proxy::TokenType,
routes::payments::ForceSync,
api_models::tokenization::GenericTokenizationRequest,
api_models::tokenization::GenericTokenizationResponse,
api_models::tokenization::DeleteTokenDataRequest,
api_models::tokenization::DeleteTokenDataResponse,
)),
modifiers(&SecurityAddon)
)]
// Bypass clippy lint for not being constructed
#[allow(dead_code)]
pub(crate) struct ApiDoc;
struct SecurityAddon;
impl utoipa::Modify for SecurityAddon {
fn modify(&self, openapi: &mut utoipa::openapi::OpenApi) {
use utoipa::openapi::security::{ApiKey, ApiKeyValue, SecurityScheme};
if let Some(components) = openapi.components.as_mut() {
components.add_security_schemes_from_iter([
(
"api_key",
SecurityScheme::ApiKey(ApiKey::Header(ApiKeyValue::with_description(
"api-key",
"Use the API key created under your merchant account from the HyperSwitch dashboard. API key is used to authenticate API requests from your merchant server only. Don't expose this key on a website or embed it in a mobile application."
))),
),
(
"admin_api_key",
SecurityScheme::ApiKey(ApiKey::Header(ApiKeyValue::with_description(
"api-key",
"Admin API keys allow you to perform some privileged actions such as \
creating a merchant account and Connector account."
))),
),
(
"publishable_key",
SecurityScheme::ApiKey(ApiKey::Header(ApiKeyValue::with_description(
"api-key",
"Publishable keys are a type of keys that can be public and have limited \
scope of usage."
))),
),
(
"ephemeral_key",
SecurityScheme::ApiKey(ApiKey::Header(ApiKeyValue::with_description(
"api-key",
"Ephemeral keys provide temporary access to singular data, such as access \
to a single customer object for a short period of time."
))),
),
]);
}
}
}
| crates/openapi/src/openapi_v2.rs | openapi::src::openapi_v2 | 9,347 | true |
// File: crates/openapi/src/routes/tokenization.rs
// Module: openapi::src::routes::tokenization
use serde_json::json;
use utoipa::OpenApi;
/// Tokenization - Create
///
/// Create a token with customer_id
#[cfg(feature = "v2")]
#[utoipa::path(
post,
path = "/v2/tokenize",
request_body(
content = GenericTokenizationRequest,
examples(("Create a token with customer_id" = (
value = json!({
"customer_id": "12345_cus_0196d94b9c207333a297cbcf31f2e8c8",
"token_request": {
"payment_method_data": {
"card": {
"card_holder_name": "test name"
}
}
}
})
)))
),
responses(
(status = 200, description = "Token created successfully", body = GenericTokenizationResponse),
(status = 400, description = "Invalid request"),
(status = 401, description = "Unauthorized"),
(status = 500, description = "Internal server error")
),
tag = "Tokenization",
operation_id = "create_token_vault_api",
security(("ephemeral_key" = []),("api_key" = []))
)]
pub async fn create_token_vault_api() {}
/// Tokenization - Delete
///
/// Delete a token entry with customer_id and session_id
#[cfg(feature = "v2")]
#[utoipa::path(
delete,
path = "/v2/tokenize/{id}",
request_body(
content = DeleteTokenDataRequest,
examples(("Delete a token entry with customer_id and session_id" = (
value = json!({
"customer_id": "12345_cus_0196d94b9c207333a297cbcf31f2e8c8",
"session_id": "12345_pms_01926c58bc6e77c09e809964e72af8c8",
})
)))
),
responses(
(status = 200, description = "Token deleted successfully", body = DeleteTokenDataResponse),
(status = 400, description = "Invalid request"),
(status = 401, description = "Unauthorized"),
(status = 500, description = "Internal server error")
),
tag = "Tokenization",
operation_id = "delete_tokenized_data_api",
security(("ephemeral_key" = []),("api_key" = []))
)]
pub async fn delete_tokenized_data_api() {}
| crates/openapi/src/routes/tokenization.rs | openapi::src::routes::tokenization | 614 | true |
// File: crates/openapi/src/routes/proxy.rs
// Module: openapi::src::routes::proxy
#[cfg(feature = "v2")]
///Proxy
///
/// Create a proxy request
#[utoipa::path(
post,
path = "/proxy",
request_body(
content = ProxyRequest,
examples((
"Create a proxy request" = (
value = json!({
"request_body": {
"source": {
"type": "card",
"number": "{{$card_number}}",
"expiry_month": "{{$card_exp_month}}",
"expiry_year": "{{$card_exp_year}}",
"billing_address": {
"address_line1": "123 High St.",
"city": "London",
"country": "GB"
}
},
"amount": 6540,
"currency": "USD",
"reference": "ORD-5023-4E89",
"capture": true
},
"destination_url": "https://api.example.com/payments",
"headers": {
"Content-Type": "application/json",
"Authorization": "Bearer sk_test_example"
},
"token": "pm_0196ea5a42a67583863d5b1253d62931",
"token_type": "PaymentMethodId",
"method": "POST"
})
)
))
),
responses(
(status = 200, description = "Proxy request", body = ProxyResponse),
(status = 400, description = "Invalid data")
),
params(
("X-Profile-Id" = String, Header, description = "Profile ID for authentication"),
),
tag = "Proxy",
operation_id = "Proxy Request",
security(("api_key" = []))
)]
pub async fn proxy_core() {}
| crates/openapi/src/routes/proxy.rs | openapi::src::routes::proxy | 417 | true |
// File: crates/openapi/src/routes/refunds.rs
// Module: openapi::src::routes::refunds
/// Refunds - Create
///
/// Creates a refund against an already processed payment. In case of some processors, you can even opt to refund only a partial amount multiple times until the original charge amount has been refunded
#[utoipa::path(
post,
path = "/refunds",
request_body(
content = RefundRequest,
examples(
(
"Create an instant refund to refund the whole amount" = (
value = json!({
"payment_id": "{{payment_id}}",
"refund_type": "instant"
})
)
),
(
"Create an instant refund to refund partial amount" = (
value = json!({
"payment_id": "{{payment_id}}",
"refund_type": "instant",
"amount": 654
})
)
),
(
"Create an instant refund with reason" = (
value = json!({
"payment_id": "{{payment_id}}",
"refund_type": "instant",
"amount": 6540,
"reason": "Customer returned product"
})
)
),
)
),
responses(
(status = 200, description = "Refund created", body = RefundResponse),
(status = 400, description = "Missing Mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Refunds",
operation_id = "Create a Refund",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn refunds_create() {}
/// Refunds - Retrieve
///
/// Retrieves a Refund. This may be used to get the status of a previously initiated refund
#[utoipa::path(
get,
path = "/refunds/{refund_id}",
params(
("refund_id" = String, Path, description = "The identifier for refund")
),
responses(
(status = 200, description = "Refund retrieved", body = RefundResponse),
(status = 404, description = "Refund does not exist in our records")
),
tag = "Refunds",
operation_id = "Retrieve a Refund",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn refunds_retrieve() {}
/// Refunds - Retrieve (POST)
///
/// To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment
#[utoipa::path(
get,
path = "/refunds/sync",
responses(
(status = 200, description = "Refund retrieved", body = RefundResponse),
(status = 404, description = "Refund does not exist in our records")
),
tag = "Refunds",
operation_id = "Retrieve a Refund",
security(("api_key" = []))
)]
pub async fn refunds_retrieve_with_body() {}
/// Refunds - Update
///
/// Updates the properties of a Refund object. This API can be used to attach a reason for the refund or metadata fields
#[utoipa::path(
post,
path = "/refunds/{refund_id}",
params(
("refund_id" = String, Path, description = "The identifier for refund")
),
request_body(
content = RefundUpdateRequest,
examples(
(
"Update refund reason" = (
value = json!({
"reason": "Paid by mistake"
})
)
),
)
),
responses(
(status = 200, description = "Refund updated", body = RefundResponse),
(status = 400, description = "Missing Mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Refunds",
operation_id = "Update a Refund",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn refunds_update() {}
/// Refunds - List
///
/// Lists all the refunds associated with the merchant, or for a specific payment if payment_id is provided
#[utoipa::path(
post,
path = "/refunds/list",
request_body=RefundListRequest,
responses(
(status = 200, description = "List of refunds", body = RefundListResponse),
),
tag = "Refunds",
operation_id = "List all Refunds",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub fn refunds_list() {}
/// Refunds - List For the Given profiles
///
/// Lists all the refunds associated with the merchant or a payment_id if payment_id is not provided
#[utoipa::path(
post,
path = "/refunds/profile/list",
request_body=RefundListRequest,
responses(
(status = 200, description = "List of refunds", body = RefundListResponse),
),
tag = "Refunds",
operation_id = "List all Refunds for the given Profiles",
security(("api_key" = []))
)]
pub fn refunds_list_profile() {}
/// Refunds - Filter
///
/// To list the refunds filters associated with list of connectors, currencies and payment statuses
#[utoipa::path(
post,
path = "/refunds/filter",
request_body=TimeRange,
responses(
(status = 200, description = "List of filters", body = RefundListMetaData),
),
tag = "Refunds",
operation_id = "List all filters for Refunds",
security(("api_key" = []))
)]
pub async fn refunds_filter_list() {}
/// Refunds - Create
///
/// Creates a refund against an already processed payment. In case of some processors, you can even opt to refund only a partial amount multiple times until the original charge amount has been refunded
#[utoipa::path(
post,
path = "/v2/refunds",
request_body(
content = RefundsCreateRequest,
examples(
(
"Create an instant refund to refund the whole amount" = (
value = json!({
"payment_id": "{{payment_id}}",
"merchant_reference_id": "ref_123",
"refund_type": "instant"
})
)
),
(
"Create an instant refund to refund partial amount" = (
value = json!({
"payment_id": "{{payment_id}}",
"merchant_reference_id": "ref_123",
"refund_type": "instant",
"amount": 654
})
)
),
(
"Create an instant refund with reason" = (
value = json!({
"payment_id": "{{payment_id}}",
"merchant_reference_id": "ref_123",
"refund_type": "instant",
"amount": 6540,
"reason": "Customer returned product"
})
)
),
)
),
responses(
(status = 200, description = "Refund created", body = RefundResponse),
(status = 400, description = "Missing Mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Refunds",
operation_id = "Create a Refund",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn refunds_create() {}
/// Refunds - Metadata Update
///
/// Updates the properties of a Refund object. This API can be used to attach a reason for the refund or metadata fields
#[utoipa::path(
put,
path = "/v2/refunds/{id}/update-metadata",
params(
("id" = String, Path, description = "The identifier for refund")
),
request_body(
content = RefundMetadataUpdateRequest,
examples(
(
"Update refund reason" = (
value = json!({
"reason": "Paid by mistake"
})
)
)
)
),
responses(
(status = 200, description = "Refund updated", body = RefundResponse),
(status = 400, description = "Missing Mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Refunds",
operation_id = "Update Refund Metadata and Reason",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn refunds_metadata_update() {}
/// Refunds - Retrieve
///
/// Retrieves a Refund. This may be used to get the status of a previously initiated refund
#[utoipa::path(
get,
path = "/v2/refunds/{id}",
params(
("id" = String, Path, description = "The identifier for refund")
),
responses(
(status = 200, description = "Refund retrieved", body = RefundResponse),
(status = 404, description = "Refund does not exist in our records")
),
tag = "Refunds",
operation_id = "Retrieve a Refund",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn refunds_retrieve() {}
/// Refunds - List
///
/// To list the refunds associated with a payment_id or with the merchant, if payment_id is not provided
#[utoipa::path(
post,
path = "/v2/refunds/list",
request_body=RefundListRequest,
responses(
(status = 200, description = "List of refunds", body = RefundListResponse),
),
tag = "Refunds",
operation_id = "List all Refunds",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub fn refunds_list() {}
| crates/openapi/src/routes/refunds.rs | openapi::src::routes::refunds | 2,122 | true |
// File: crates/openapi/src/routes/organization.rs
// Module: openapi::src::routes::organization
#[cfg(feature = "v1")]
/// Organization - Create
///
/// Create a new organization
#[utoipa::path(
post,
path = "/organization",
request_body(
content = OrganizationCreateRequest,
examples(
(
"Create an organization with organization_name" = (
value = json!({"organization_name": "organization_abc"})
)
),
)
),
responses(
(status = 200, description = "Organization Created", body =OrganizationResponse),
(status = 400, description = "Invalid data")
),
tag = "Organization",
operation_id = "Create an Organization",
security(("admin_api_key" = []))
)]
pub async fn organization_create() {}
#[cfg(feature = "v1")]
/// Organization - Retrieve
///
/// Retrieve an existing organization
#[utoipa::path(
get,
path = "/organization/{id}",
params (("id" = String, Path, description = "The unique identifier for the Organization")),
responses(
(status = 200, description = "Organization Created", body =OrganizationResponse),
(status = 400, description = "Invalid data")
),
tag = "Organization",
operation_id = "Retrieve an Organization",
security(("admin_api_key" = []))
)]
pub async fn organization_retrieve() {}
#[cfg(feature = "v1")]
/// Organization - Update
///
/// Create a new organization for .
#[utoipa::path(
put,
path = "/organization/{id}",
request_body(
content = OrganizationUpdateRequest,
examples(
(
"Update organization_name of the organization" = (
value = json!({"organization_name": "organization_abcd"})
)
),
)
),
params (("id" = String, Path, description = "The unique identifier for the Organization")),
responses(
(status = 200, description = "Organization Created", body =OrganizationResponse),
(status = 400, description = "Invalid data")
),
tag = "Organization",
operation_id = "Update an Organization",
security(("admin_api_key" = []))
)]
pub async fn organization_update() {}
#[cfg(feature = "v2")]
/// Organization - Create
///
/// Create a new organization
#[utoipa::path(
post,
path = "/v2/organizations",
request_body(
content = OrganizationCreateRequest,
examples(
(
"Create an organization with organization_name" = (
value = json!({"organization_name": "organization_abc"})
)
),
)
),
responses(
(status = 200, description = "Organization Created", body =OrganizationResponse),
(status = 400, description = "Invalid data")
),
tag = "Organization",
operation_id = "Create an Organization",
security(("admin_api_key" = []))
)]
pub async fn organization_create() {}
#[cfg(feature = "v2")]
/// Organization - Retrieve
///
/// Retrieve an existing organization
#[utoipa::path(
get,
path = "/v2/organizations/{id}",
params (("id" = String, Path, description = "The unique identifier for the Organization")),
responses(
(status = 200, description = "Organization Created", body =OrganizationResponse),
(status = 400, description = "Invalid data")
),
tag = "Organization",
operation_id = "Retrieve an Organization",
security(("admin_api_key" = []))
)]
pub async fn organization_retrieve() {}
#[cfg(feature = "v2")]
/// Organization - Update
///
/// Create a new organization for .
#[utoipa::path(
put,
path = "/v2/organizations/{id}",
request_body(
content = OrganizationUpdateRequest,
examples(
(
"Update organization_name of the organization" = (
value = json!({"organization_name": "organization_abcd"})
)
),
)
),
params (("id" = String, Path, description = "The unique identifier for the Organization")),
responses(
(status = 200, description = "Organization Created", body =OrganizationResponse),
(status = 400, description = "Invalid data")
),
tag = "Organization",
operation_id = "Update an Organization",
security(("admin_api_key" = []))
)]
pub async fn organization_update() {}
#[cfg(feature = "v2")]
/// Organization - Merchant Account - List
///
/// List merchant accounts for an Organization
#[utoipa::path(
get,
path = "/v2/organizations/{id}/merchant-accounts",
params (("id" = String, Path, description = "The unique identifier for the Organization")),
responses(
(status = 200, description = "Merchant Account list retrieved successfully", body = Vec<MerchantAccountResponse>),
(status = 400, description = "Invalid data")
),
tag = "Organization",
operation_id = "List Merchant Accounts",
security(("admin_api_key" = []))
)]
pub async fn merchant_account_list() {}
| crates/openapi/src/routes/organization.rs | openapi::src::routes::organization | 1,119 | true |
// File: crates/openapi/src/routes/merchant_account.rs
// Module: openapi::src::routes::merchant_account
#[cfg(feature = "v1")]
/// Merchant Account - Create
///
/// Create a new account for a *merchant* and the *merchant* could be a seller or retailer or client who likes to receive and send payments.
#[utoipa::path(
post,
path = "/accounts",
request_body(
content = MerchantAccountCreate,
examples(
(
"Create a merchant account with minimal fields" = (
value = json!({"merchant_id": "merchant_abc"})
)
),
(
"Create a merchant account with webhook url" = (
value = json!({
"merchant_id": "merchant_abc",
"webhook_details" : {
"webhook_url": "https://webhook.site/a5c54f75-1f7e-4545-b781-af525b7e37a0"
}
})
)
),
(
"Create a merchant account with return url" = (
value = json!({"merchant_id": "merchant_abc",
"return_url": "https://example.com"})
)
)
)
),
responses(
(status = 200, description = "Merchant Account Created", body = MerchantAccountResponse),
(status = 400, description = "Invalid data")
),
tag = "Merchant Account",
operation_id = "Create a Merchant Account",
security(("admin_api_key" = []))
)]
pub async fn merchant_account_create() {}
#[cfg(feature = "v2")]
/// Merchant Account - Create
///
/// Create a new account for a *merchant* and the *merchant* could be a seller or retailer or client who likes to receive and send payments.
///
/// Before creating the merchant account, it is mandatory to create an organization.
#[utoipa::path(
post,
path = "/v2/merchant-accounts",
params(
(
"X-Organization-Id" = String, Header,
description = "Organization ID for which the merchant account has to be created.",
example = json!({"X-Organization-Id": "org_abcdefghijklmnop"})
),
),
request_body(
content = MerchantAccountCreate,
examples(
(
"Create a merchant account with minimal fields" = (
value = json!({
"merchant_name": "Cloth Store",
})
)
),
(
"Create a merchant account with merchant details" = (
value = json!({
"merchant_name": "Cloth Store",
"merchant_details": {
"primary_contact_person": "John Doe",
"primary_email": "example@company.com"
}
})
)
),
(
"Create a merchant account with metadata" = (
value = json!({
"merchant_name": "Cloth Store",
"metadata": {
"key_1": "John Doe",
"key_2": "Trends"
}
})
)
),
)
),
responses(
(status = 200, description = "Merchant Account Created", body = MerchantAccountResponse),
(status = 400, description = "Invalid data")
),
tag = "Merchant Account",
operation_id = "Create a Merchant Account",
security(("admin_api_key" = []))
)]
pub async fn merchant_account_create() {}
#[cfg(feature = "v1")]
/// Merchant Account - Retrieve
///
/// Retrieve a *merchant* account details.
#[utoipa::path(
get,
path = "/accounts/{account_id}",
params (("account_id" = String, Path, description = "The unique identifier for the merchant account")),
responses(
(status = 200, description = "Merchant Account Retrieved", body = MerchantAccountResponse),
(status = 404, description = "Merchant account not found")
),
tag = "Merchant Account",
operation_id = "Retrieve a Merchant Account",
security(("admin_api_key" = []))
)]
pub async fn retrieve_merchant_account() {}
#[cfg(feature = "v2")]
/// Merchant Account - Retrieve
///
/// Retrieve a *merchant* account details.
#[utoipa::path(
get,
path = "/v2/merchant-accounts/{id}",
params (("id" = String, Path, description = "The unique identifier for the merchant account")),
responses(
(status = 200, description = "Merchant Account Retrieved", body = MerchantAccountResponse),
(status = 404, description = "Merchant account not found")
),
tag = "Merchant Account",
operation_id = "Retrieve a Merchant Account",
security(("admin_api_key" = []))
)]
pub async fn merchant_account_retrieve() {}
#[cfg(feature = "v1")]
/// Merchant Account - Update
///
/// Updates details of an existing merchant account. Helpful in updating merchant details such as email, contact details, or other configuration details like webhook, routing algorithm etc
#[utoipa::path(
post,
path = "/accounts/{account_id}",
request_body (
content = MerchantAccountUpdate,
examples(
(
"Update merchant name" = (
value = json!({
"merchant_id": "merchant_abc",
"merchant_name": "merchant_name"
})
)
),
("Update webhook url" = (
value = json!({
"merchant_id": "merchant_abc",
"webhook_details": {
"webhook_url": "https://webhook.site/a5c54f75-1f7e-4545-b781-af525b7e37a0"
}
})
)
),
("Update return url" = (
value = json!({
"merchant_id": "merchant_abc",
"return_url": "https://example.com"
})
)))),
params (("account_id" = String, Path, description = "The unique identifier for the merchant account")),
responses(
(status = 200, description = "Merchant Account Updated", body = MerchantAccountResponse),
(status = 404, description = "Merchant account not found")
),
tag = "Merchant Account",
operation_id = "Update a Merchant Account",
security(("admin_api_key" = []))
)]
pub async fn update_merchant_account() {}
#[cfg(feature = "v2")]
/// Merchant Account - Update
///
/// Updates details of an existing merchant account. Helpful in updating merchant details such as email, contact details, or other configuration details like webhook, routing algorithm etc
#[utoipa::path(
put,
path = "/v2/merchant-accounts/{id}",
request_body (
content = MerchantAccountUpdate,
examples(
(
"Update merchant name" = (
value = json!({
"merchant_id": "merchant_abc",
"merchant_name": "merchant_name"
})
)
),
("Update Merchant Details" = (
value = json!({
"merchant_details": {
"primary_contact_person": "John Doe",
"primary_email": "example@company.com"
}
})
)
),
)),
params (("id" = String, Path, description = "The unique identifier for the merchant account")),
responses(
(status = 200, description = "Merchant Account Updated", body = MerchantAccountResponse),
(status = 404, description = "Merchant account not found")
),
tag = "Merchant Account",
operation_id = "Update a Merchant Account",
security(("admin_api_key" = []))
)]
pub async fn merchant_account_update() {}
#[cfg(feature = "v1")]
/// Merchant Account - Delete
///
/// Delete a *merchant* account
#[utoipa::path(
delete,
path = "/accounts/{account_id}",
params (("account_id" = String, Path, description = "The unique identifier for the merchant account")),
responses(
(status = 200, description = "Merchant Account Deleted", body = MerchantAccountDeleteResponse),
(status = 404, description = "Merchant account not found")
),
tag = "Merchant Account",
operation_id = "Delete a Merchant Account",
security(("admin_api_key" = []))
)]
pub async fn delete_merchant_account() {}
#[cfg(feature = "v1")]
/// Merchant Account - KV Status
///
/// Toggle KV mode for the Merchant Account
#[utoipa::path(
post,
path = "/accounts/{account_id}/kv",
request_body (
content = ToggleKVRequest,
examples (
("Enable KV for Merchant" = (
value = json!({
"kv_enabled": "true"
})
)),
("Disable KV for Merchant" = (
value = json!({
"kv_enabled": "false"
})
)))
),
params (("account_id" = String, Path, description = "The unique identifier for the merchant account")),
responses(
(status = 200, description = "KV mode is enabled/disabled for Merchant Account", body = ToggleKVResponse),
(status = 400, description = "Invalid data"),
(status = 404, description = "Merchant account not found")
),
tag = "Merchant Account",
operation_id = "Enable/Disable KV for a Merchant Account",
security(("admin_api_key" = []))
)]
pub async fn merchant_account_kv_status() {}
/// Merchant Connector - List
///
/// List Merchant Connector Details for the merchant
#[utoipa::path(
get,
path = "/accounts/{account_id}/profile/connectors",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
),
responses(
(status = 200, description = "Merchant Connector list retrieved successfully", body = Vec<MerchantConnectorResponse>),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "List all Merchant Connectors for The given Profile",
security(("admin_api_key" = []))
)]
pub async fn payment_connector_list_profile() {}
#[cfg(feature = "v2")]
/// Merchant Account - Profile List
///
/// List profiles for an Merchant
#[utoipa::path(
get,
path = "/v2/merchant-accounts/{id}/profiles",
params (("id" = String, Path, description = "The unique identifier for the Merchant")),
responses(
(status = 200, description = "profile list retrieved successfully", body = Vec<ProfileResponse>),
(status = 400, description = "Invalid data")
),
tag = "Merchant Account",
operation_id = "List Profiles",
security(("admin_api_key" = []))
)]
pub async fn profiles_list() {}
| crates/openapi/src/routes/merchant_account.rs | openapi::src::routes::merchant_account | 2,373 | true |
// File: crates/openapi/src/routes/subscriptions.rs
// Module: openapi::src::routes::subscriptions
use serde_json::json;
use utoipa;
/// Subscription - Create and Confirm
///
/// Creates and confirms a subscription in a single request.
#[utoipa::path(
post,
path = "/subscriptions",
request_body(
content = CreateAndConfirmSubscriptionRequest,
examples((
"Create and confirm subscription" = (
value = json!({
"customer_id": "cust_123456789",
"plan_id": "plan_monthly_basic",
"payment_method_id": "pm_1234567890",
"billing_details": {
"name": "John Doe",
"email": "john@example.com"
}
})
)
))
),
responses(
(status = 200, description = "Subscription created and confirmed successfully", body = SubscriptionResponse),
(status = 400, description = "Invalid subscription data"),
(status = 404, description = "Customer or plan not found")
),
params(
("X-Profile-Id" = String, Header, description = "Profile ID for authentication")
),
tag = "Subscriptions",
operation_id = "Create and Confirm Subscription",
security(("api_key" = []))
)]
pub async fn create_and_confirm_subscription() {}
/// Subscription - Create
///
/// Creates a subscription that requires separate confirmation.
#[utoipa::path(
post,
path = "/subscriptions/create",
request_body(
content = CreateSubscriptionRequest,
examples((
"Create subscription" = (
value = json!({
"customer_id": "cust_123456789",
"plan_id": "plan_monthly_basic",
"trial_days": 7,
"metadata": {
"source": "web_app"
}
})
)
))
),
responses(
(status = 200, description = "Subscription created successfully", body = SubscriptionResponse),
(status = 400, description = "Invalid subscription data"),
(status = 404, description = "Customer or plan not found")
),
params(
("X-Profile-Id" = String, Header, description = "Profile ID for authentication")
),
tag = "Subscriptions",
operation_id = "Create Subscription",
security(("api_key" = []))
)]
pub async fn create_subscription() {}
/// Subscription - Confirm
///
/// Confirms a previously created subscription.
#[utoipa::path(
post,
path = "/subscriptions/{subscription_id}/confirm",
params(
("subscription_id" = String, Path, description = "The unique identifier for the subscription"),
("X-Profile-Id" = String, Header, description = "Profile ID for authentication")
),
request_body(
content = ConfirmSubscriptionRequest,
examples((
"Confirm subscription" = (
value = json!({
"payment_method_id": "pm_1234567890",
"client_secret": "seti_1234567890_secret_abcdef",
"return_url": "https://example.com/return"
})
)
))
),
responses(
(status = 200, description = "Subscription confirmed successfully", body = SubscriptionResponse),
(status = 400, description = "Invalid confirmation data"),
(status = 404, description = "Subscription not found"),
(status = 409, description = "Subscription already confirmed")
),
tag = "Subscriptions",
operation_id = "Confirm Subscription",
security(("api_key" = []), ("client_secret" = []))
)]
pub async fn confirm_subscription() {}
/// Subscription - Retrieve
///
/// Retrieves subscription details by ID.
#[utoipa::path(
get,
path = "/subscriptions/{subscription_id}",
params(
("subscription_id" = String, Path, description = "The unique identifier for the subscription"),
("X-Profile-Id" = String, Header, description = "Profile ID for authentication")
),
responses(
(status = 200, description = "Subscription retrieved successfully", body = SubscriptionResponse),
(status = 404, description = "Subscription not found")
),
tag = "Subscriptions",
operation_id = "Retrieve Subscription",
security(("api_key" = []))
)]
pub async fn get_subscription() {}
/// Subscription - Update
///
/// Updates an existing subscription.
#[utoipa::path(
put,
path = "/subscriptions/{subscription_id}/update",
params(
("subscription_id" = String, Path, description = "The unique identifier for the subscription"),
("X-Profile-Id" = String, Header, description = "Profile ID for authentication")
),
request_body(
content = UpdateSubscriptionRequest,
examples((
"Update subscription" = (
value = json!({
"plan_id": "plan_yearly_premium",
"proration_behavior": "create_prorations",
"metadata": {
"updated_reason": "plan_upgrade"
}
})
)
))
),
responses(
(status = 200, description = "Subscription updated successfully", body = SubscriptionResponse),
(status = 400, description = "Invalid update data"),
(status = 404, description = "Subscription not found")
),
tag = "Subscriptions",
operation_id = "Update Subscription",
security(("api_key" = []))
)]
pub async fn update_subscription() {}
/// Subscription - Get Plans
///
/// Retrieves available subscription plans.
#[utoipa::path(
get,
path = "/subscriptions/plans",
params(
("X-Profile-Id" = String, Header, description = "Profile ID for authentication"),
("limit" = Option<u32>, Query, description = "Number of plans to retrieve"),
("offset" = Option<u32>, Query, description = "Number of plans to skip"),
("product_id" = Option<String>, Query, description = "Filter by product ID")
),
responses(
(status = 200, description = "Plans retrieved successfully", body = Vec<GetPlansResponse>),
(status = 400, description = "Invalid query parameters")
),
tag = "Subscriptions",
operation_id = "Get Subscription Plans",
security(("api_key" = []), ("client_secret" = []))
)]
pub async fn get_subscription_plans() {}
/// Subscription - Get Estimate
///
/// Gets pricing estimate for a subscription.
#[utoipa::path(
get,
path = "/subscriptions/estimate",
params(
("X-Profile-Id" = String, Header, description = "Profile ID for authentication"),
("plan_id" = String, Query, description = "Plan ID for estimation"),
("customer_id" = Option<String>, Query, description = "Customer ID for personalized pricing"),
("coupon_id" = Option<String>, Query, description = "Coupon ID to apply discount"),
("trial_days" = Option<u32>, Query, description = "Number of trial days")
),
responses(
(status = 200, description = "Estimate retrieved successfully", body = EstimateSubscriptionResponse),
(status = 400, description = "Invalid estimation parameters"),
(status = 404, description = "Plan not found")
),
tag = "Subscriptions",
operation_id = "Get Subscription Estimate",
security(("api_key" = []))
)]
pub async fn get_estimate() {}
| crates/openapi/src/routes/subscriptions.rs | openapi::src::routes::subscriptions | 1,655 | true |
// File: crates/openapi/src/routes/payouts.rs
// Module: openapi::src::routes::payouts
/// Payouts - Create
#[utoipa::path(
post,
path = "/payouts/create",
request_body=PayoutsCreateRequest,
responses(
(status = 200, description = "Payout created", body = PayoutCreateResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Payouts",
operation_id = "Create a Payout",
security(("api_key" = []))
)]
pub async fn payouts_create() {}
/// Payouts - Retrieve
#[utoipa::path(
get,
path = "/payouts/{payout_id}",
params(
("payout_id" = String, Path, description = "The identifier for payout"),
("force_sync" = Option<bool>, Query, description = "Sync with the connector to get the payout details (defaults to false)")
),
responses(
(status = 200, description = "Payout retrieved", body = PayoutCreateResponse),
(status = 404, description = "Payout does not exist in our records")
),
tag = "Payouts",
operation_id = "Retrieve a Payout",
security(("api_key" = []))
)]
pub async fn payouts_retrieve() {}
/// Payouts - Update
#[utoipa::path(
post,
path = "/payouts/{payout_id}",
params(
("payout_id" = String, Path, description = "The identifier for payout")
),
request_body=PayoutUpdateRequest,
responses(
(status = 200, description = "Payout updated", body = PayoutCreateResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Payouts",
operation_id = "Update a Payout",
security(("api_key" = []))
)]
pub async fn payouts_update() {}
/// Payouts - Cancel
#[utoipa::path(
post,
path = "/payouts/{payout_id}/cancel",
params(
("payout_id" = String, Path, description = "The identifier for payout")
),
request_body=PayoutCancelRequest,
responses(
(status = 200, description = "Payout cancelled", body = PayoutCreateResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Payouts",
operation_id = "Cancel a Payout",
security(("api_key" = []))
)]
pub async fn payouts_cancel() {}
/// Payouts - Fulfill
#[utoipa::path(
post,
path = "/payouts/{payout_id}/fulfill",
params(
("payout_id" = String, Path, description = "The identifier for payout")
),
request_body=PayoutFulfillRequest,
responses(
(status = 200, description = "Payout fulfilled", body = PayoutCreateResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Payouts",
operation_id = "Fulfill a Payout",
security(("api_key" = []))
)]
pub async fn payouts_fulfill() {}
/// Payouts - List
#[utoipa::path(
get,
path = "/payouts/list",
params(
("customer_id" = String, Query, description = "The identifier for customer"),
("starting_after" = String, Query, description = "A cursor for use in pagination, fetch the next list after some object"),
("ending_before" = String, Query, description = "A cursor for use in pagination, fetch the previous list before some object"),
("limit" = String, Query, description = "limit on the number of objects to return"),
("created" = String, Query, description = "The time at which payout is created"),
("time_range" = String, Query, description = "The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc).")
),
responses(
(status = 200, description = "Payouts listed", body = PayoutListResponse),
(status = 404, description = "Payout not found")
),
tag = "Payouts",
operation_id = "List payouts using generic constraints",
security(("api_key" = []))
)]
pub async fn payouts_list() {}
/// Payouts - List for the Given Profiles
#[utoipa::path(
get,
path = "/payouts/profile/list",
params(
("customer_id" = String, Query, description = "The identifier for customer"),
("starting_after" = String, Query, description = "A cursor for use in pagination, fetch the next list after some object"),
("ending_before" = String, Query, description = "A cursor for use in pagination, fetch the previous list before some object"),
("limit" = String, Query, description = "limit on the number of objects to return"),
("created" = String, Query, description = "The time at which payout is created"),
("time_range" = String, Query, description = "The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc).")
),
responses(
(status = 200, description = "Payouts listed", body = PayoutListResponse),
(status = 404, description = "Payout not found")
),
tag = "Payouts",
operation_id = "List payouts using generic constraints for the given Profiles",
security(("api_key" = []))
)]
pub async fn payouts_list_profile() {}
/// Payouts - List available filters
#[utoipa::path(
post,
path = "/payouts/filter",
request_body=TimeRange,
responses(
(status = 200, description = "Filters listed", body = PayoutListFilters)
),
tag = "Payouts",
operation_id = "List available payout filters",
security(("api_key" = []))
)]
pub async fn payouts_list_filters() {}
/// Payouts - List using filters
#[utoipa::path(
post,
path = "/payouts/list",
request_body=PayoutListFilterConstraints,
responses(
(status = 200, description = "Payouts filtered", body = PayoutListResponse),
(status = 404, description = "Payout not found")
),
tag = "Payouts",
operation_id = "Filter payouts using specific constraints",
security(("api_key" = []))
)]
pub async fn payouts_list_by_filter() {}
/// Payouts - List using filters for the given Profiles
#[utoipa::path(
post,
path = "/payouts/list",
request_body=PayoutListFilterConstraints,
responses(
(status = 200, description = "Payouts filtered", body = PayoutListResponse),
(status = 404, description = "Payout not found")
),
tag = "Payouts",
operation_id = "Filter payouts using specific constraints for the given Profiles",
security(("api_key" = []))
)]
pub async fn payouts_list_by_filter_profile() {}
/// Payouts - Confirm
#[utoipa::path(
post,
path = "/payouts/{payout_id}/confirm",
params(
("payout_id" = String, Path, description = "The identifier for payout")
),
request_body=PayoutConfirmRequest,
responses(
(status = 200, description = "Payout updated", body = PayoutCreateResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Payouts",
operation_id = "Confirm a Payout",
security(("api_key" = []))
)]
pub async fn payouts_confirm() {}
| crates/openapi/src/routes/payouts.rs | openapi::src::routes::payouts | 1,792 | true |
// File: crates/openapi/src/routes/profile.rs
// Module: openapi::src::routes::profile
// ******************************************** V1 profile routes ******************************************** //
#[cfg(feature = "v1")]
/// Profile - Create
///
/// Creates a new *profile* for a merchant
#[utoipa::path(
post,
path = "/account/{account_id}/business_profile",
params (
("account_id" = String, Path, description = "The unique identifier for the merchant account")
),
request_body(
content = ProfileCreate,
examples(
(
"Create a profile with minimal fields" = (
value = json!({})
)
),
(
"Create a profile with profile name" = (
value = json!({
"profile_name": "shoe_business"
})
)
)
)
),
responses(
(status = 200, description = "Profile Created", body = ProfileResponse),
(status = 400, description = "Invalid data")
),
tag = "Profile",
operation_id = "Create A Profile",
security(("api_key" = []))
)]
pub async fn profile_create() {}
#[cfg(feature = "v1")]
/// Profile - Update
///
/// Update the *profile*
#[utoipa::path(
post,
path = "/account/{account_id}/business_profile/{profile_id}",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
("profile_id" = String, Path, description = "The unique identifier for the profile")
),
request_body(
content = ProfileCreate,
examples(
(
"Update profile with profile name fields" = (
value = json!({
"profile_name" : "shoe_business"
})
)
)
)),
responses(
(status = 200, description = "Profile Updated", body = ProfileResponse),
(status = 400, description = "Invalid data")
),
tag = "Profile",
operation_id = "Update a Profile",
security(("api_key" = []))
)]
pub async fn profile_update() {}
#[cfg(feature = "v1")]
/// Profile - Retrieve
///
/// Retrieve existing *profile*
#[utoipa::path(
get,
path = "/account/{account_id}/business_profile/{profile_id}",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
("profile_id" = String, Path, description = "The unique identifier for the profile")
),
responses(
(status = 200, description = "Profile Updated", body = ProfileResponse),
(status = 400, description = "Invalid data")
),
tag = "Profile",
operation_id = "Retrieve a Profile",
security(("api_key" = []))
)]
pub async fn profile_retrieve() {}
// ******************************************** Common profile routes ******************************************** //
/// Profile - Delete
///
/// Delete the *profile*
#[utoipa::path(
delete,
path = "/account/{account_id}/business_profile/{profile_id}",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
("profile_id" = String, Path, description = "The unique identifier for the profile")
),
responses(
(status = 200, description = "Profiles Deleted", body = bool),
(status = 400, description = "Invalid data")
),
tag = "Profile",
operation_id = "Delete the Profile",
security(("admin_api_key" = []))
)]
pub async fn profile_delete() {}
/// Profile - List
///
/// Lists all the *profiles* under a merchant
#[utoipa::path(
get,
path = "/account/{account_id}/business_profile",
params (
("account_id" = String, Path, description = "Merchant Identifier"),
),
responses(
(status = 200, description = "Profiles Retrieved", body = Vec<ProfileResponse>)
),
tag = "Profile",
operation_id = "List Profiles",
security(("api_key" = []))
)]
pub async fn profile_list() {}
// ******************************************** V2 profile routes ******************************************** //
#[cfg(feature = "v2")]
/// Profile - Create
///
/// Creates a new *profile* for a merchant
#[utoipa::path(
post,
path = "/v2/profiles",
params(
(
"X-Merchant-Id" = String, Header,
description = "Merchant ID of the profile.",
example = json!({"X-Merchant-Id": "abc_iG5VNjsN9xuCg7Xx0uWh"})
),
),
request_body(
content = ProfileCreate,
examples(
(
"Create a profile with profile name" = (
value = json!({
"profile_name": "shoe_business"
})
)
)
)
),
responses(
(status = 200, description = "Account Created", body = ProfileResponse),
(status = 400, description = "Invalid data")
),
tag = "Profile",
operation_id = "Create A Profile",
security(("admin_api_key" = []))
)]
pub async fn profile_create() {}
#[cfg(feature = "v2")]
/// Profile - Update
///
/// Update the *profile*
#[utoipa::path(
put,
path = "/v2/profiles/{id}",
params(
("id" = String, Path, description = "The unique identifier for the profile"),
(
"X-Merchant-Id" = String, Header,
description = "Merchant ID of the profile.",
example = json!({"X-Merchant-Id": "abc_iG5VNjsN9xuCg7Xx0uWh"})
),
),
request_body(
content = ProfileCreate,
examples(
(
"Update profile with profile name fields" = (
value = json!({
"profile_name" : "shoe_business"
})
)
)
)),
responses(
(status = 200, description = "Profile Updated", body = ProfileResponse),
(status = 400, description = "Invalid data")
),
tag = "Profile",
operation_id = "Update a Profile",
security(("admin_api_key" = []))
)]
pub async fn profile_update() {}
#[cfg(feature = "v2")]
/// Profile - Activate routing algorithm
///
/// Activates a routing algorithm under a profile
#[utoipa::path(
patch,
path = "/v2/profiles/{id}/activate-routing-algorithm",
request_body ( content = RoutingAlgorithmId,
examples( (
"Activate a routing algorithm" = (
value = json!({
"routing_algorithm_id": "routing_algorithm_123"
})
)
))),
params(
("id" = String, Path, description = "The unique identifier for the profile"),
),
responses(
(status = 200, description = "Routing Algorithm is activated", body = RoutingDictionaryRecord),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 400, description = "Bad request")
),
tag = "Profile",
operation_id = "Activates a routing algorithm under a profile",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_link_config() {}
#[cfg(feature = "v2")]
/// Profile - Deactivate routing algorithm
///
/// Deactivates a routing algorithm under a profile
#[utoipa::path(
patch,
path = "/v2/profiles/{id}/deactivate-routing-algorithm",
params(
("id" = String, Path, description = "The unique identifier for the profile"),
),
responses(
(status = 200, description = "Successfully deactivated routing config", body = RoutingDictionaryRecord),
(status = 500, description = "Internal server error"),
(status = 400, description = "Malformed request"),
(status = 403, description = "Malformed request"),
(status = 422, description = "Unprocessable request")
),
tag = "Profile",
operation_id = " Deactivates a routing algorithm under a profile",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_unlink_config() {}
#[cfg(feature = "v2")]
/// Profile - Update Default Fallback Routing Algorithm
///
/// Update the default fallback routing algorithm for the profile
#[utoipa::path(
patch,
path = "/v2/profiles/{id}/fallback-routing",
request_body = Vec<RoutableConnectorChoice>,
params(
("id" = String, Path, description = "The unique identifier for the profile"),
),
responses(
(status = 200, description = "Successfully updated the default fallback routing algorithm", body = Vec<RoutableConnectorChoice>),
(status = 500, description = "Internal server error"),
(status = 400, description = "Malformed request"),
(status = 422, description = "Unprocessable request")
),
tag = "Profile",
operation_id = "Update the default fallback routing algorithm for the profile",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_update_default_config() {}
#[cfg(feature = "v2")]
/// Profile - Retrieve
///
/// Retrieve existing *profile*
#[utoipa::path(
get,
path = "/v2/profiles/{id}",
params(
("id" = String, Path, description = "The unique identifier for the profile"),
(
"X-Merchant-Id" = String, Header,
description = "Merchant ID of the profile.",
example = json!({"X-Merchant-Id": "abc_iG5VNjsN9xuCg7Xx0uWh"})
),
),
responses(
(status = 200, description = "Profile Updated", body = ProfileResponse),
(status = 400, description = "Invalid data")
),
tag = "Profile",
operation_id = "Retrieve a Profile",
security(("admin_api_key" = []))
)]
pub async fn profile_retrieve() {}
#[cfg(feature = "v2")]
/// Profile - Retrieve Active Routing Algorithm
///_
/// Retrieve active routing algorithm under the profile
#[utoipa::path(
get,
path = "/v2/profiles/{id}/routing-algorithm",
params(
("id" = String, Path, description = "The unique identifier for the profile"),
("limit" = Option<u16>, Query, description = "The number of records of the algorithms to be returned"),
("offset" = Option<u8>, Query, description = "The record offset of the algorithm from which to start gathering the results")),
responses(
(status = 200, description = "Successfully retrieved active config", body = LinkedRoutingConfigRetrieveResponse),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 403, description = "Forbidden")
),
tag = "Profile",
operation_id = "Retrieve the active routing algorithm under the profile",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_retrieve_linked_config() {}
#[cfg(feature = "v2")]
/// Profile - Retrieve Default Fallback Routing Algorithm
///
/// Retrieve the default fallback routing algorithm for the profile
#[utoipa::path(
get,
path = "/v2/profiles/{id}/fallback-routing",
params(
("id" = String, Path, description = "The unique identifier for the profile"),
),
responses(
(status = 200, description = "Successfully retrieved default fallback routing algorithm", body = Vec<RoutableConnectorChoice>),
(status = 500, description = "Internal server error")
),
tag = "Profile",
operation_id = "Retrieve the default fallback routing algorithm for the profile",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_retrieve_default_config() {}
/// Profile - Connector Accounts List
///
/// List Connector Accounts for the profile
#[utoipa::path(
get,
path = "/v2/profiles/{id}/connector-accounts",
params(
("id" = String, Path, description = "The unique identifier for the business profile"),
(
"X-Merchant-Id" = String, Header,
description = "Merchant ID of the profile.",
example = json!({"X-Merchant-Id": "abc_iG5VNjsN9xuCg7Xx0uWh"})
),
),
responses(
(status = 200, description = "Merchant Connector list retrieved successfully", body = Vec<MerchantConnectorResponse>),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Business Profile",
operation_id = "List all Merchant Connectors for Profile",
security(("admin_api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn connector_list() {}
| crates/openapi/src/routes/profile.rs | openapi::src::routes::profile | 2,931 | true |
// File: crates/openapi/src/routes/payment_method.rs
// Module: openapi::src::routes::payment_method
/// PaymentMethods - Create
///
/// Creates and stores a payment method against a customer.
/// In case of cards, this API should be used only by PCI compliant merchants.
#[utoipa::path(
post,
path = "/payment_methods",
request_body (
content = PaymentMethodCreate,
examples (( "Save a card" =(
value =json!( {
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_issuer": "Visa",
"card": {
"card_number": "4242424242424242",
"card_exp_month": "11",
"card_exp_year": "25",
"card_holder_name": "John Doe"
},
"customer_id": "{{customer_id}}"
})
)))
),
responses(
(status = 200, description = "Payment Method Created", body = PaymentMethodResponse),
(status = 400, description = "Invalid Data")
),
tag = "Payment Methods",
operation_id = "Create a Payment Method",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn create_payment_method_api() {}
/// List payment methods for a Merchant
///
/// Lists the applicable payment methods for a particular Merchant ID.
/// Use the client secret and publishable key authorization to list all relevant payment methods of the merchant for the payment corresponding to the client secret.
#[utoipa::path(
get,
path = "/account/payment_methods",
params (
("client_secret" = Option<String>, Query, description = "This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK"),
("accepted_countries" = Option<Vec<CountryAlpha2>>, Query, description = "The two-letter ISO currency code"),
("accepted_currencies" = Option<Vec<Currency>>, Query, description = "The three-letter ISO currency code"),
("amount" = Option<i64>, Query, description = "The amount accepted for processing by the particular payment method."),
("recurring_enabled" = Option<bool>, Query, description = "Indicates whether the payment method is eligible for recurring payments"),
("installment_payment_enabled" = Option<bool>, Query, description = "Indicates whether the payment method is eligible for installment payments"),
("limit" = Option<i64>, Query, description = "Indicates the limit of last used payment methods"),
("card_networks" = Option<Vec<CardNetwork>>, Query, description = "Indicates whether the payment method is eligible for card netwotks"),
),
responses(
(status = 200, description = "Payment Methods retrieved", body = PaymentMethodListResponse),
(status = 400, description = "Invalid Data"),
(status = 404, description = "Payment Methods does not exist in records")
),
tag = "Payment Methods",
operation_id = "List all Payment Methods for a Merchant",
security(("api_key" = []), ("publishable_key" = []))
)]
pub async fn list_payment_method_api() {}
/// List payment methods for a Customer
///
/// Lists all the applicable payment methods for a particular Customer ID.
#[utoipa::path(
get,
path = "/customers/{customer_id}/payment_methods",
params (
("customer_id" = String, Path, description = "The unique identifier for the customer account"),
("client_secret" = Option<String>, Query, description = "This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK"),
("accepted_countries" = Option<Vec<CountryAlpha2>>, Query, description = "The two-letter ISO currency code"),
("accepted_currencies" = Option<Vec<Currency>>, Query, description = "The three-letter ISO currency code"),
("amount" = Option<i64>, Query, description = "The amount accepted for processing by the particular payment method."),
("recurring_enabled" = Option<bool>, Query, description = "Indicates whether the payment method is eligible for recurring payments"),
("installment_payment_enabled" = Option<bool>, Query, description = "Indicates whether the payment method is eligible for installment payments"),
("limit" = Option<i64>, Query, description = "Indicates the limit of last used payment methods"),
("card_networks" = Option<Vec<CardNetwork>>, Query, description = "Indicates whether the payment method is eligible for card netwotks"),
),
responses(
(status = 200, description = "Payment Methods retrieved", body = CustomerPaymentMethodsListResponse),
(status = 400, description = "Invalid Data"),
(status = 404, description = "Payment Methods does not exist in records")
),
tag = "Payment Methods",
operation_id = "List all Payment Methods for a Customer",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn list_customer_payment_method_api() {}
/// List customer saved payment methods for a Payment
///
/// Lists all the applicable payment methods for a particular payment tied to the `client_secret`.
#[utoipa::path(
get,
path = "/customers/payment_methods",
params (
("client_secret" = Option<String>, Query, description = "This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK"),
("accepted_countries" = Option<Vec<CountryAlpha2>>, Query, description = "The two-letter ISO currency code"),
("accepted_currencies" = Option<Vec<Currency>>, Query, description = "The three-letter ISO currency code"),
("amount" = Option<i64>, Query, description = "The amount accepted for processing by the particular payment method."),
("recurring_enabled" = Option<bool>, Query, description = "Indicates whether the payment method is eligible for recurring payments"),
("installment_payment_enabled" = Option<bool>, Query, description = "Indicates whether the payment method is eligible for installment payments"),
("limit" = Option<i64>, Query, description = "Indicates the limit of last used payment methods"),
("card_networks" = Option<Vec<CardNetwork>>, Query, description = "Indicates whether the payment method is eligible for card netwotks"),
),
responses(
(status = 200, description = "Payment Methods retrieved for customer tied to its respective client-secret passed in the param", body = CustomerPaymentMethodsListResponse),
(status = 400, description = "Invalid Data"),
(status = 404, description = "Payment Methods does not exist in records")
),
tag = "Payment Methods",
operation_id = "List Customer Payment Methods via Client Secret",
security(("publishable_key" = []))
)]
pub async fn list_customer_payment_method_api_client() {}
/// Payment Method - Retrieve
///
/// Retrieves a payment method of a customer.
#[utoipa::path(
get,
path = "/payment_methods/{method_id}",
params (
("method_id" = String, Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method retrieved", body = PaymentMethodResponse),
(status = 404, description = "Payment Method does not exist in records")
),
tag = "Payment Methods",
operation_id = "Retrieve a Payment method",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn payment_method_retrieve_api() {}
/// Payment Method - Update
///
/// Update an existing payment method of a customer.
/// This API is useful for use cases such as updating the card number for expired cards to prevent discontinuity in recurring payments.
#[utoipa::path(
post,
path = "/payment_methods/{method_id}/update",
params (
("method_id" = String, Path, description = "The unique identifier for the Payment Method"),
),
request_body = PaymentMethodUpdate,
responses(
(status = 200, description = "Payment Method updated", body = PaymentMethodResponse),
(status = 404, description = "Payment Method does not exist in records")
),
tag = "Payment Methods",
operation_id = "Update a Payment method",
security(("api_key" = []), ("publishable_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn payment_method_update_api() {}
/// Payment Method - Delete
///
/// Deletes a payment method of a customer.
#[utoipa::path(
delete,
path = "/payment_methods/{method_id}",
params (
("method_id" = String, Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method deleted", body = PaymentMethodDeleteResponse),
(status = 404, description = "Payment Method does not exist in records")
),
tag = "Payment Methods",
operation_id = "Delete a Payment method",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn payment_method_delete_api() {}
/// Payment Method - Set Default Payment Method for Customer
///
/// Set the Payment Method as Default for the Customer.
#[utoipa::path(
post,
path = "/{customer_id}/payment_methods/{payment_method_id}/default",
params (
("customer_id" = String,Path, description ="The unique identifier for the Customer"),
("payment_method_id" = String,Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method has been set as default", body =CustomerDefaultPaymentMethodResponse ),
(status = 400, description = "Payment Method has already been set as default for that customer"),
(status = 404, description = "Payment Method not found for the customer")
),
tag = "Payment Methods",
operation_id = "Set the Payment Method as Default",
security(("ephemeral_key" = []))
)]
pub async fn default_payment_method_set_api() {}
/// Payment Method - Create Intent
///
/// Creates a payment method for customer with billing information and other metadata.
#[utoipa::path(
post,
path = "/v2/payment-methods/create-intent",
request_body(
content = PaymentMethodIntentCreate,
// TODO: Add examples
),
responses(
(status = 200, description = "Payment Method Intent Created", body = PaymentMethodResponse),
(status = 400, description = "Invalid Data"),
),
tag = "Payment Methods",
operation_id = "Create Payment Method Intent",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn create_payment_method_intent_api() {}
/// Payment Method - Confirm Intent
///
/// Update a payment method with customer's payment method related information.
#[utoipa::path(
post,
path = "/v2/payment-methods/{id}/confirm-intent",
request_body(
content = PaymentMethodIntentConfirm,
// TODO: Add examples
),
responses(
(status = 200, description = "Payment Method Intent Confirmed", body = PaymentMethodResponse),
(status = 400, description = "Invalid Data"),
),
tag = "Payment Methods",
operation_id = "Confirm Payment Method Intent",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn confirm_payment_method_intent_api() {}
/// Payment Method - Create
///
/// Creates and stores a payment method against a customer. In case of cards, this API should be used only by PCI compliant merchants.
#[utoipa::path(
post,
path = "/v2/payment-methods",
request_body(
content = PaymentMethodCreate,
// TODO: Add examples
),
responses(
(status = 200, description = "Payment Method Created", body = PaymentMethodResponse),
(status = 400, description = "Invalid Data"),
),
tag = "Payment Methods",
operation_id = "Create Payment Method",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn create_payment_method_api() {}
/// Payment Method - Retrieve
///
/// Retrieves a payment method of a customer.
#[utoipa::path(
get,
path = "/v2/payment-methods/{id}",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method Retrieved", body = PaymentMethodResponse),
(status = 404, description = "Payment Method Not Found"),
),
tag = "Payment Methods",
operation_id = "Retrieve Payment Method",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn payment_method_retrieve_api() {}
/// Payment Method - Update
///
/// Update an existing payment method of a customer.
#[utoipa::path(
patch,
path = "/v2/payment-methods/{id}/update-saved-payment-method",
request_body(
content = PaymentMethodUpdate,
// TODO: Add examples
),
responses(
(status = 200, description = "Payment Method Update", body = PaymentMethodResponse),
(status = 400, description = "Invalid Data"),
),
tag = "Payment Methods",
operation_id = "Update Payment Method",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn payment_method_update_api() {}
/// Payment Method - Delete
///
/// Deletes a payment method of a customer.
#[utoipa::path(
delete,
path = "/v2/payment-methods/{id}",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method Retrieved", body = PaymentMethodDeleteResponse),
(status = 404, description = "Payment Method Not Found"),
),
tag = "Payment Methods",
operation_id = "Delete Payment Method",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn payment_method_delete_api() {}
/// Payment Method - Check Network Token Status
///
/// Check the status of a network token for a saved payment method
#[utoipa::path(
get,
path = "/v2/payment-methods/{payment_method_id}/check-network-token-status",
params (
("payment_method_id" = String, Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Network Token Status Retrieved", body = NetworkTokenStatusCheckResponse),
(status = 404, description = "Payment Method Not Found"),
),
tag = "Payment Methods",
operation_id = "Check Network Token Status",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn network_token_status_check_api() {}
/// Payment Method - List Customer Saved Payment Methods
///
/// List the payment methods saved for a customer
#[utoipa::path(
get,
path = "/v2/customers/{id}/saved-payment-methods",
params (
("id" = String, Path, description = "The unique identifier for the customer"),
),
responses(
(status = 200, description = "Payment Methods Retrieved", body = CustomerPaymentMethodsListResponse),
(status = 404, description = "Customer Not Found"),
),
tag = "Payment Methods",
operation_id = "List Customer Saved Payment Methods",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn list_customer_payment_method_api() {}
/// Payment Method Session - Create
///
/// Create a payment method session for a customer
/// This is used to list the saved payment methods for the customer
/// The customer can also add a new payment method using this session
#[cfg(feature = "v2")]
#[utoipa::path(
post,
path = "/v2/payment-method-sessions",
request_body(
content = PaymentMethodSessionRequest,
examples (( "Create a payment method session with customer_id" = (
value =json!( {
"customer_id": "12345_cus_abcdefghijklmnopqrstuvwxyz"
})
)))
),
responses(
(status = 200, description = "Create the payment method session", body = PaymentMethodSessionResponse),
(status = 400, description = "The request is invalid")
),
tag = "Payment Method Session",
operation_id = "Create a payment method session",
security(("api_key" = []))
)]
pub fn payment_method_session_create() {}
/// Payment Method Session - Retrieve
///
/// Retrieve the payment method session
#[cfg(feature = "v2")]
#[utoipa::path(
get,
path = "/v2/payment-method-sessions/{id}",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method Session"),
),
responses(
(status = 200, description = "The payment method session is retrieved successfully", body = PaymentMethodSessionResponse),
(status = 404, description = "The request is invalid")
),
tag = "Payment Method Session",
operation_id = "Retrieve the payment method session",
security(("ephemeral_key" = []))
)]
pub fn payment_method_session_retrieve() {}
/// Payment Method Session - List Payment Methods
///
/// List payment methods for the given payment method session.
/// This endpoint lists the enabled payment methods for the profile and the saved payment methods of the customer.
#[cfg(feature = "v2")]
#[utoipa::path(
get,
path = "/v2/payment-method-sessions/{id}/list-payment-methods",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method Session"),
),
responses(
(status = 200, description = "The payment method session is retrieved successfully", body = PaymentMethodListResponseForSession),
(status = 404, description = "The request is invalid")
),
tag = "Payment Method Session",
operation_id = "List Payment methods for a Payment Method Session",
security(("ephemeral_key" = []))
)]
pub fn payment_method_session_list_payment_methods() {}
/// Payment Method Session - Update a saved payment method
///
/// Update a saved payment method from the given payment method session.
#[cfg(feature = "v2")]
#[utoipa::path(
put,
path = "/v2/payment-method-sessions/{id}/update-saved-payment-method",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method Session"),
),
request_body(
content = PaymentMethodSessionUpdateSavedPaymentMethod,
examples(( "Update the card holder name" = (
value =json!( {
"payment_method_id": "12345_pm_0194b1ecabc172e28aeb71f70a4daba3",
"payment_method_data": {
"card": {
"card_holder_name": "Narayan Bhat"
}
}
}
)
)))
),
responses(
(status = 200, description = "The payment method has been updated successfully", body = PaymentMethodResponse),
(status = 404, description = "The request is invalid")
),
tag = "Payment Method Session",
operation_id = "Update a saved payment method",
security(("ephemeral_key" = []))
)]
pub fn payment_method_session_update_saved_payment_method() {}
/// Payment Method Session - Delete a saved payment method
///
/// Delete a saved payment method from the given payment method session.
#[cfg(feature = "v2")]
#[utoipa::path(
delete,
path = "/v2/payment-method-sessions/{id}",
params (
("id" = String, Path, description = "The unique identifier for the Payment Method Session"),
),
request_body(
content = PaymentMethodSessionDeleteSavedPaymentMethod,
examples(( "Update the card holder name" = (
value =json!( {
"payment_method_id": "12345_pm_0194b1ecabc172e28aeb71f70a4daba3",
}
)
)))
),
responses(
(status = 200, description = "The payment method has been updated successfully", body = PaymentMethodDeleteResponse),
(status = 404, description = "The request is invalid")
),
tag = "Payment Method Session",
operation_id = "Delete a saved payment method",
security(("ephemeral_key" = []))
)]
pub fn payment_method_session_delete_saved_payment_method() {}
/// Card network tokenization - Create using raw card data
///
/// Create a card network token for a customer and store it as a payment method.
/// This API expects raw card details for creating a network token with the card networks.
#[utoipa::path(
post,
path = "/payment_methods/tokenize-card",
request_body = CardNetworkTokenizeRequest,
responses(
(status = 200, description = "Payment Method Created", body = CardNetworkTokenizeResponse),
(status = 404, description = "Customer not found"),
),
tag = "Payment Methods",
operation_id = "Create card network token",
security(("admin_api_key" = []))
)]
pub async fn tokenize_card_api() {}
/// Card network tokenization - Create using existing payment method
///
/// Create a card network token for a customer for an existing payment method.
/// This API expects an existing payment method ID for a card.
#[utoipa::path(
post,
path = "/payment_methods/{id}/tokenize-card",
request_body = CardNetworkTokenizeRequest,
params (
("id" = String, Path, description = "The unique identifier for the Payment Method"),
),
responses(
(status = 200, description = "Payment Method Updated", body = CardNetworkTokenizeResponse),
(status = 404, description = "Customer not found"),
),
tag = "Payment Methods",
operation_id = "Create card network token using Payment Method ID",
security(("admin_api_key" = []))
)]
pub async fn tokenize_card_using_pm_api() {}
/// Payment Method Session - Confirm a payment method session
///
/// **Confirms a payment method session object with the payment method data**
#[utoipa::path(
post,
path = "/v2/payment-method-sessions/{id}/confirm",
params (("id" = String, Path, description = "The unique identifier for the Payment Method Session"),
(
"X-Profile-Id" = String, Header,
description = "Profile ID associated to the payment intent",
example = "pro_abcdefghijklmnop"
)
),
request_body(
content = PaymentMethodSessionConfirmRequest,
examples(
(
"Confirm the payment method session with card details" = (
value = json!({
"payment_method_type": "card",
"payment_method_subtype": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_cvc": "123"
}
},
})
)
),
),
),
responses(
(status = 200, description = "Payment Method created", body = PaymentMethodResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Payment Method Session",
operation_id = "Confirm the payment method session",
security(("publishable_key" = [])),
)]
#[cfg(feature = "v2")]
pub fn payment_method_session_confirm() {}
| crates/openapi/src/routes/payment_method.rs | openapi::src::routes::payment_method | 5,260 | true |
// File: crates/openapi/src/routes/merchant_connector_account.rs
// Module: openapi::src::routes::merchant_connector_account
/// Merchant Connector - Create
///
/// Creates a new Merchant Connector for the merchant account. The connector could be a payment processor/facilitator/acquirer or a provider of specialized services like Fraud/Accounting etc.
#[cfg(feature = "v1")]
#[utoipa::path(
post,
path = "/account/{account_id}/connectors",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account")
),
request_body(
content = MerchantConnectorCreate,
examples(
(
"Create a merchant connector account with minimal fields" = (
value = json!({
"connector_type": "payment_processor",
"connector_name": "adyen",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "{{adyen-api-key}}",
"key1": "{{adyen_merchant_account}}"
}
})
)
),
(
"Create a merchant connector account under a specific profile" = (
value = json!({
"connector_type": "payment_processor",
"connector_name": "adyen",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "{{adyen-api-key}}",
"key1": "{{adyen_merchant_account}}"
},
"profile_id": "{{profile_id}}"
})
)
),
(
"Create a merchant account with custom connector label" = (
value = json!({
"connector_type": "payment_processor",
"connector_name": "adyen",
"connector_label": "EU_adyen",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "{{adyen-api-key}}",
"key1": "{{adyen_merchant_account}}"
}
})
)
),
)
),
responses(
(status = 200, description = "Merchant Connector Created", body = MerchantConnectorResponse),
(status = 400, description = "Missing Mandatory fields"),
),
tag = "Merchant Connector Account",
operation_id = "Create a Merchant Connector",
security(("api_key" = []))
)]
pub async fn connector_create() {}
/// Connector Account - Create
///
/// Creates a new Connector Account for the merchant account. The connector could be a payment processor/facilitator/acquirer or a provider of specialized services like Fraud/Accounting etc.
#[cfg(feature = "v2")]
#[utoipa::path(
post,
path = "/v2/connector-accounts",
request_body(
content = MerchantConnectorCreate,
examples(
(
"Create a merchant connector account with minimal fields" = (
value = json!({
"connector_type": "payment_processor",
"connector_name": "adyen",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "{{adyen-api-key}}",
"key1": "{{adyen_merchant_account}}"
}
})
)
),
(
"Create a merchant connector account under a specific profile" = (
value = json!({
"connector_type": "payment_processor",
"connector_name": "adyen",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "{{adyen-api-key}}",
"key1": "{{adyen_merchant_account}}"
},
"profile_id": "{{profile_id}}"
})
)
),
(
"Create a merchant account with custom connector label" = (
value = json!({
"connector_type": "payment_processor",
"connector_name": "adyen",
"connector_label": "EU_adyen",
"connector_account_details": {
"auth_type": "BodyKey",
"api_key": "{{adyen-api-key}}",
"key1": "{{adyen_merchant_account}}"
}
})
)
),
)
),
responses(
(status = 200, description = "Merchant Connector Created", body = MerchantConnectorResponse),
(status = 400, description = "Missing Mandatory fields"),
),
tag = "Merchant Connector Account",
operation_id = "Create a Merchant Connector",
security(("admin_api_key" = []))
)]
pub async fn connector_create() {}
/// Merchant Connector - Retrieve
///
/// Retrieves details of a Connector account
#[cfg(feature = "v1")]
#[utoipa::path(
get,
path = "/account/{account_id}/connectors/{merchant_connector_id}",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
("merchant_connector_id" = String, Path, description = "The unique identifier for the Merchant Connector")
),
responses(
(status = 200, description = "Merchant Connector retrieved successfully", body = MerchantConnectorResponse),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "Retrieve a Merchant Connector",
security(("api_key" = []))
)]
pub async fn connector_retrieve() {}
/// Connector Account - Retrieve
///
/// Retrieves details of a Connector account
#[cfg(feature = "v2")]
#[utoipa::path(
get,
path = "/v2/connector-accounts/{id}",
params(
("id" = i32, Path, description = "The unique identifier for the Merchant Connector")
),
responses(
(status = 200, description = "Merchant Connector retrieved successfully", body = MerchantConnectorResponse),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "Retrieve a Merchant Connector",
security(("admin_api_key" = []))
)]
pub async fn connector_retrieve() {}
/// Merchant Connector - List
///
/// List Merchant Connector Details for the merchant
#[utoipa::path(
get,
path = "/account/{account_id}/connectors",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
),
responses(
(status = 200, description = "Merchant Connector list retrieved successfully", body = Vec<MerchantConnectorListResponse>),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "List all Merchant Connectors",
security(("api_key" = []))
)]
pub async fn connector_list() {}
/// Merchant Connector - Update
///
/// To update an existing Merchant Connector account. Helpful in enabling/disabling different payment methods and other settings for the connector
#[cfg(feature = "v1")]
#[utoipa::path(
post,
path = "/account/{account_id}/connectors/{merchant_connector_id}",
request_body(
content = MerchantConnectorUpdate,
examples(
(
"Enable card payment method" = (
value = json! ({
"connector_type": "payment_processor",
"payment_methods_enabled": [
{
"payment_method": "card"
}
]
})
)
),
(
"Update webhook secret" = (
value = json! ({
"connector_webhook_details": {
"merchant_secret": "{{webhook_secret}}"
}
})
)
)
),
),
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
("merchant_connector_id" = String, Path, description = "The unique identifier for the Merchant Connector")
),
responses(
(status = 200, description = "Merchant Connector Updated", body = MerchantConnectorResponse),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "Update a Merchant Connector",
security(("api_key" = []))
)]
pub async fn connector_update() {}
/// Connector Account - Update
///
/// To update an existing Connector account. Helpful in enabling/disabling different payment methods and other settings for the connector
#[cfg(feature = "v2")]
#[utoipa::path(
put,
path = "/v2/connector-accounts/{id}",
request_body(
content = MerchantConnectorUpdate,
examples(
(
"Enable card payment method" = (
value = json! ({
"connector_type": "payment_processor",
"payment_methods_enabled": [
{
"payment_method": "card"
}
]
})
)
),
(
"Update webhook secret" = (
value = json! ({
"connector_webhook_details": {
"merchant_secret": "{{webhook_secret}}"
}
})
)
)
),
),
params(
("id" = i32, Path, description = "The unique identifier for the Merchant Connector")
),
responses(
(status = 200, description = "Merchant Connector Updated", body = MerchantConnectorResponse),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "Update a Merchant Connector",
security(("admin_api_key" = []))
)]
pub async fn connector_update() {}
/// Merchant Connector - Delete
///
/// Delete or Detach a Merchant Connector from Merchant Account
#[cfg(feature = "v1")]
#[utoipa::path(
delete,
path = "/account/{account_id}/connectors/{merchant_connector_id}",
params(
("account_id" = String, Path, description = "The unique identifier for the merchant account"),
("merchant_connector_id" = String, Path, description = "The unique identifier for the Merchant Connector")
),
responses(
(status = 200, description = "Merchant Connector Deleted", body = MerchantConnectorDeleteResponse),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "Delete a Merchant Connector",
security(("admin_api_key" = []))
)]
pub async fn connector_delete() {}
/// Merchant Connector - Delete
///
/// Delete or Detach a Merchant Connector from Merchant Account
#[cfg(feature = "v2")]
#[utoipa::path(
delete,
path = "/v2/connector-accounts/{id}",
params(
("id" = i32, Path, description = "The unique identifier for the Merchant Connector")
),
responses(
(status = 200, description = "Merchant Connector Deleted", body = MerchantConnectorDeleteResponse),
(status = 404, description = "Merchant Connector does not exist in records"),
(status = 401, description = "Unauthorized request")
),
tag = "Merchant Connector Account",
operation_id = "Delete a Merchant Connector",
security(("admin_api_key" = []))
)]
pub async fn connector_delete() {}
| crates/openapi/src/routes/merchant_connector_account.rs | openapi::src::routes::merchant_connector_account | 2,484 | true |
// File: crates/openapi/src/routes/payments.rs
// Module: openapi::src::routes::payments
/// Payments - Create
///
/// Creates a payment resource, which represents a customer's intent to pay.
/// This endpoint is the starting point for various payment flows:
///
#[utoipa::path(
post,
path = "/payments",
request_body(
content = PaymentsCreateRequest,
examples(
(
"01. Create a payment with minimal fields" = (
value = json!({"amount": 6540,"currency": "USD"})
)
),
(
"02. Create a payment with customer details and metadata" = (
value = json!({
"amount": 6540,
"currency": "USD",
"payment_id": "abcdefghijklmnopqrstuvwxyz",
"customer": {
"id": "cus_abcdefgh",
"name": "John Dough",
"phone": "9123456789",
"email": "john@example.com"
},
"description": "Its my first payment request",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "some-value",
"udf2": "some-value"
}
})
)
),
(
"03. Create a 3DS payment" = (
value = json!({
"amount": 6540,
"currency": "USD",
"authentication_type": "three_ds"
})
)
),
(
"04. Create a manual capture payment (basic)" = (
value = json!({
"amount": 6540,
"currency": "USD",
"capture_method": "manual"
})
)
),
(
"05. Create a setup mandate payment" = (
value = json!({
"amount": 6540,
"currency": "USD",
"confirm": true,
"customer_id": "StripeCustomer123",
"authentication_type": "no_three_ds",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"setup_future_usage": "off_session",
"mandate_data": {
"customer_acceptance": {
"acceptance_type": "online",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "127.0.0.1",
"user_agent": "amet irure esse"
}
},
"mandate_type": {
"single_use": {
"amount": 6540,
"currency": "USD"
}
}
},
"customer_acceptance": {
"acceptance_type": "online",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "127.0.0.1",
"user_agent": "amet irure esse"
}
}
})
)
),
(
"06. Create a recurring payment with mandate_id" = (
value = json!({
"amount": 6540,
"currency": "USD",
"confirm": true,
"customer_id": "StripeCustomer",
"authentication_type": "no_three_ds",
"mandate_id": "{{mandate_id}}",
"off_session": true
})
)
),
(
"07. Create a payment and save the card" = (
value = json!({
"amount": 6540,
"currency": "USD",
"confirm": true,
"customer_id": "StripeCustomer123",
"authentication_type": "no_three_ds",
"payment_method": "card",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"customer_acceptance": {
"acceptance_type": "online",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "127.0.0.1",
"user_agent": "amet irure esse"
}
},
"setup_future_usage": "off_session"
})
)
),
(
"08. Create a payment using an already saved card's token" = (
value = json!({
"amount": 6540,
"currency": "USD",
"confirm": true,
"client_secret": "{{client_secret}}",
"payment_method": "card",
"payment_token": "{{payment_token}}",
"card_cvc": "123"
})
)
),
(
"09. Create a payment with billing details" = (
value = json!({
"amount": 6540,
"currency": "USD",
"customer": {
"id": "cus_abcdefgh"
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "9123456789",
"country_code": "+91"
}
}
})
)
),
(
"10. Create a Stripe Split Payments CIT call" = (
value = json!({
"amount": 200,
"currency": "USD",
"profile_id": "pro_abcdefghijklmnop",
"confirm": true,
"capture_method": "automatic",
"amount_to_capture": 200,
"customer_id": "StripeCustomer123",
"setup_future_usage": "off_session",
"customer_acceptance": {
"acceptance_type": "offline",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "125.0.0.1",
"user_agent": "amet irure esse"
}
},
"authentication_type": "no_three_ds",
"return_url": "https://hyperswitch.io",
"name": "John Doe",
"phone": "999999999",
"phone_country_code": "+65",
"description": "Its my first payment request",
"payment_method": "card",
"payment_method_type": "debit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "09",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"billing": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "9999999999",
"country_code": "+91"
}
},
"split_payments": {
"stripe_split_payment": {
"charge_type": "direct",
"application_fees": 100,
"transfer_account_id": "acct_123456789"
}
}
})
)
),
(
"11. Create a Stripe Split Payments MIT call" = (
value = json!({
"amount": 200,
"currency": "USD",
"profile_id": "pro_abcdefghijklmnop",
"customer_id": "StripeCustomer123",
"description": "Subsequent Mandate Test Payment (MIT from New CIT Demo)",
"confirm": true,
"off_session": true,
"recurring_details": {
"type": "payment_method_id",
"data": "pm_123456789"
},
"split_payments": {
"stripe_split_payment": {
"charge_type": "direct",
"application_fees": 11,
"transfer_account_id": "acct_123456789"
}
}
})
)
),
),
),
responses(
(status = 200, description = "Payment created", body = PaymentsCreateResponseOpenApi,
examples(
("01. Response for minimal payment creation (requires payment method)" = (
value = json!({
"payment_id": "pay_syxxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "requires_payment_method",
"amount": 6540,
"currency": "USD",
"client_secret": "pay_syxxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:00:00Z",
"amount_capturable": 6540,
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"expires_on": "2023-10-26T10:15:00Z"
})
)),
("02. Response for payment with customer details (requires payment method)" = (
value = json!({
"payment_id": "pay_custmeta_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "requires_payment_method",
"amount": 6540,
"currency": "USD",
"customer_id": "cus_abcdefgh",
"customer": {
"id": "cus_abcdefgh",
"name": "John Dough",
"email": "john@example.com",
"phone": "9123456789"
},
"description": "Its my first payment request",
"statement_descriptor_name": "joseph",
"statement_descriptor_suffix": "JS",
"metadata": {
"udf1": "some-value",
"udf2": "some-value"
},
"client_secret": "pay_custmeta_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:05:00Z",
"ephemeral_key": {
"customer_id": "cus_abcdefgh",
"secret": "epk_ephemeralxxxxxxxxxxxx"
},
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"expires_on": "2023-10-26T10:20:00Z"
})
)),
("03. Response for 3DS payment creation (requires payment method)" = (
value = json!({
"payment_id": "pay_3ds_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "requires_payment_method",
"amount": 6540,
"currency": "USD",
"authentication_type": "three_ds",
"client_secret": "pay_3ds_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:10:00Z",
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"expires_on": "2023-10-26T10:25:00Z"
})
)),
("04. Response for basic manual capture payment (requires payment method)" = (
value = json!({
"payment_id": "pay_manualcap_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "requires_payment_method",
"amount": 6540,
"currency": "USD",
"capture_method": "manual",
"client_secret": "pay_manualcap_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:15:00Z",
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"expires_on": "2023-10-26T10:30:00Z"
})
)),
("05. Response for successful setup mandate payment" = (
value = json!({
"payment_id": "pay_mandatesetup_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "succeeded",
"amount": 6540,
"currency": "USD",
"amount_capturable": 0,
"amount_received": 6540,
"connector": "fauxpay",
"customer_id": "StripeCustomer123",
"mandate_id": "man_xxxxxxxxxxxx",
"mandate_data": {
"customer_acceptance": {
"acceptance_type": "online",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": { "ip_address": "127.0.0.1", "user_agent": "amet irure esse" }
},
"mandate_type": { "single_use": { "amount": 6540, "currency": "USD" } }
},
"setup_future_usage": "on_session",
"payment_method": "card",
"payment_method_data": {
"card": { "last4": "4242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" }
},
"authentication_type": "no_three_ds",
"client_secret": "pay_mandatesetup_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:20:00Z",
"ephemeral_key": { "customer_id": "StripeCustomer123", "secret": "epk_ephemeralxxxxxxxxxxxx" },
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"merchant_connector_id": "mca_mcaconnectorxxxx",
"connector_transaction_id": "txn_connectortransidxxxx"
})
)),
("06. Response for successful recurring payment with mandate_id" = (
value = json!({
"payment_id": "pay_recurring_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "succeeded",
"amount": 6540,
"currency": "USD",
"amount_capturable": 0,
"amount_received": 6540,
"connector": "fauxpay",
"customer_id": "StripeCustomer",
"mandate_id": "{{mandate_id}}",
"off_session": true,
"payment_method": "card",
"authentication_type": "no_three_ds",
"client_secret": "pay_recurring_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:22:00Z",
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"merchant_connector_id": "mca_mcaconnectorxxxx",
"connector_transaction_id": "txn_connectortransidxxxx"
})
)),
("07. Response for successful payment with card saved" = (
value = json!({
"payment_id": "pay_savecard_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "succeeded",
"amount": 6540,
"currency": "USD",
"amount_capturable": 0,
"amount_received": 6540,
"connector": "fauxpay",
"customer_id": "StripeCustomer123",
"setup_future_usage": "on_session",
"payment_method": "card",
"payment_method_data": {
"card": { "last4": "4242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe" }
},
"authentication_type": "no_three_ds",
"client_secret": "pay_savecard_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:25:00Z",
"ephemeral_key": { "customer_id": "StripeCustomer123", "secret": "epk_ephemeralxxxxxxxxxxxx" },
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"merchant_connector_id": "mca_mcaconnectorxxxx",
"connector_transaction_id": "txn_connectortransidxxxx",
"payment_token": null // Assuming payment_token is for subsequent use, not in this response.
})
)),
("08. Response for successful payment using saved card token" = (
value = json!({
"payment_id": "pay_token_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "succeeded",
"amount": 6540,
"currency": "USD",
"amount_capturable": 0,
"amount_received": 6540,
"connector": "fauxpay",
"payment_method": "card",
"payment_token": "{{payment_token}}",
"client_secret": "pay_token_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:27:00Z",
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"merchant_connector_id": "mca_mcaconnectorxxxx",
"connector_transaction_id": "txn_connectortransidxxxx"
})
)),
("09. Response for payment with billing details (requires payment method)" = (
value = json!({
"payment_id": "pay_manualbill_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "requires_payment_method",
"amount": 6540,
"currency": "USD",
"customer_id": "cus_abcdefgh",
"customer": {
"id": "cus_abcdefgh",
"name": "John Dough",
"email": "john@example.com",
"phone": "9123456789"
},
"billing": {
"address": {
"line1": "1467", "line2": "Harrison Street", "city": "San Fransico",
"state": "California", "zip": "94122", "country": "US",
"first_name": "joseph", "last_name": "Doe"
},
"phone": { "number": "9123456789", "country_code": "+91" }
},
"client_secret": "pay_manualbill_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:30:00Z",
"ephemeral_key": { "customer_id": "cus_abcdefgh", "secret": "epk_ephemeralxxxxxxxxxxxx" },
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"expires_on": "2023-10-26T10:45:00Z"
})
)),
("10. Response for the CIT call for Stripe Split Payments" = (
value = json!({
"payment_id": "pay_manualbill_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "succeeded",
"amount": 200,
"currency": "USD",
"customer_id": "cus_abcdefgh",
"payment_method_id": "pm_123456789",
"connector_mandate_id": "pm_abcdefgh",
"customer": {
"id": "cus_abcdefgh",
"name": "John Dough",
"email": "john@example.com",
"phone": "9123456789"
},
"billing": {
"address": {
"line1": "1467", "line2": "Harrison Street", "city": "San Fransico",
"state": "California", "zip": "94122", "country": "US",
"first_name": "joseph", "last_name": "Doe"
},
"phone": { "number": "9123456789", "country_code": "+91" }
},
"client_secret": "pay_manualbill_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:30:00Z",
"ephemeral_key": { "customer_id": "cus_abcdefgh", "secret": "epk_ephemeralxxxxxxxxxxxx" },
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"expires_on": "2023-10-26T10:45:00Z"
})
)),
("11. Response for the MIT call for Stripe Split Payments" = (
value = json!({
"payment_id": "pay_manualbill_xxxxxxxxxxxx",
"merchant_id": "merchant_myyyyyyyyyyyy",
"status": "succeeded",
"amount": 200,
"currency": "USD",
"customer_id": "cus_abcdefgh",
"payment_method_id": "pm_123456789",
"connector_mandate_id": "pm_abcdefgh",
"customer": {
"id": "cus_abcdefgh",
"name": "John Dough",
"email": "john@example.com",
"phone": "9123456789"
},
"billing": {
"address": {
"line1": "1467", "line2": "Harrison Street", "city": "San Fransico",
"state": "California", "zip": "94122", "country": "US",
"first_name": "joseph", "last_name": "Doe"
},
"phone": { "number": "9123456789", "country_code": "+91" }
},
"client_secret": "pay_manualbill_xxxxxxxxxxxx_secret_szzzzzzzzzzz",
"created": "2023-10-26T10:30:00Z",
"ephemeral_key": { "customer_id": "cus_abcdefgh", "secret": "epk_ephemeralxxxxxxxxxxxx" },
"profile_id": "pro_pzzzzzzzzzzz",
"attempt_count": 1,
"expires_on": "2023-10-26T10:45:00Z"
})
))
)
),
(status = 400, description = "Missing Mandatory fields", body = GenericErrorResponseOpenApi),
),
tag = "Payments",
operation_id = "Create a Payment",
security(("api_key" = [])),
)]
pub fn payments_create() {}
/// Payments - Retrieve
///
/// Retrieves a Payment. This API can also be used to get the status of a previously initiated payment or next action for an ongoing payment
#[utoipa::path(
get,
path = "/payments/{payment_id}",
params(
("payment_id" = String, Path, description = "The identifier for payment"),
("force_sync" = Option<bool>, Query, description = "Decider to enable or disable the connector call for retrieve request"),
("client_secret" = Option<String>, Query, description = "This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK"),
("expand_attempts" = Option<bool>, Query, description = "If enabled provides list of attempts linked to payment intent"),
("expand_captures" = Option<bool>, Query, description = "If enabled provides list of captures linked to latest attempt"),
),
responses(
(status = 200, description = "Gets the payment with final status", body = PaymentsResponse),
(status = 404, description = "No payment found")
),
tag = "Payments",
operation_id = "Retrieve a Payment",
security(("api_key" = []), ("publishable_key" = []))
)]
pub fn payments_retrieve() {}
/// Payments - Update
///
/// To update the properties of a *PaymentIntent* object. This may include attaching a payment method, or attaching customer object or metadata fields after the Payment is created
#[utoipa::path(
post,
path = "/payments/{payment_id}",
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
request_body(
content = PaymentsUpdateRequest,
examples(
(
"Update the payment amount" = (
value = json!({
"amount": 7654,
}
)
)
),
(
"Update the shipping address" = (
value = json!(
{
"shipping": {
"address": {
"line1": "1467",
"line2": "Harrison Street",
"line3": "Harrison Street",
"city": "San Fransico",
"state": "California",
"zip": "94122",
"country": "US",
"first_name": "joseph",
"last_name": "Doe"
},
"phone": {
"number": "9123456789",
"country_code": "+91"
}
},
}
)
)
)
)
),
responses(
(status = 200, description = "Payment updated", body = PaymentsCreateResponseOpenApi),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Update a Payment",
security(("api_key" = []), ("publishable_key" = []))
)]
pub fn payments_update() {}
/// Payments - Confirm
///
/// Confirms a payment intent that was previously created with `confirm: false`. This action attempts to authorize the payment with the payment processor.
///
/// Expected status transitions after confirmation:
/// - `succeeded`: If authorization is successful and `capture_method` is `automatic`.
/// - `requires_capture`: If authorization is successful and `capture_method` is `manual`.
/// - `failed`: If authorization fails.
#[utoipa::path(
post,
path = "/payments/{payment_id}/confirm",
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
request_body(
content = PaymentsConfirmRequest,
examples(
(
"Confirm a payment with payment method data" = (
value = json!({
"payment_method": "card",
"payment_method_type": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
"customer_acceptance": {
"acceptance_type": "online",
"accepted_at": "1963-05-03T04:07:52.723Z",
"online": {
"ip_address": "127.0.0.1",
"user_agent": "amet irure esse"
}
}
}
)
)
)
)
),
responses(
(status = 200, description = "Payment confirmed", body = PaymentsCreateResponseOpenApi),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Confirm a Payment",
security(("api_key" = []), ("publishable_key" = []))
)]
pub fn payments_confirm() {}
/// Payments - Capture
///
/// Captures the funds for a previously authorized payment intent where `capture_method` was set to `manual` and the payment is in a `requires_capture` state.
///
/// Upon successful capture, the payment status usually transitions to `succeeded`.
/// The `amount_to_capture` can be specified in the request body; it must be less than or equal to the payment's `amount_capturable`. If omitted, the full capturable amount is captured.
///
/// A payment must be in a capturable state (e.g., `requires_capture`). Attempting to capture an already `succeeded` (and fully captured) payment or one in an invalid state will lead to an error.
///
#[utoipa::path(
post,
path = "/payments/{payment_id}/capture",
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
request_body (
content = PaymentsCaptureRequest,
examples(
(
"Capture the full amount" = (
value = json!({})
)
),
(
"Capture partial amount" = (
value = json!({"amount_to_capture": 654})
)
),
)
),
responses(
(status = 200, description = "Payment captured", body = PaymentsResponse),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Capture a Payment",
security(("api_key" = []))
)]
pub fn payments_capture() {}
#[cfg(feature = "v1")]
/// Payments - Session token
///
/// Creates a session object or a session token for wallets like Apple Pay, Google Pay, etc. These tokens are used by Hyperswitch's SDK to initiate these wallets' SDK.
#[utoipa::path(
post,
path = "/payments/session_tokens",
request_body=PaymentsSessionRequest,
responses(
(status = 200, description = "Payment session object created or session token was retrieved from wallets", body = PaymentsSessionResponse),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Create Session tokens for a Payment",
security(("publishable_key" = []))
)]
pub fn payments_connector_session() {}
#[cfg(feature = "v2")]
/// Payments - Session token
///
/// Creates a session object or a session token for wallets like Apple Pay, Google Pay, etc. These tokens are used by Hyperswitch's SDK to initiate these wallets' SDK.
#[utoipa::path(
post,
path = "/v2/payments/{payment_id}/create-external-sdk-tokens",
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
request_body=PaymentsSessionRequest,
responses(
(status = 200, description = "Payment session object created or session token was retrieved from wallets", body = PaymentsSessionResponse),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Create V2 Session tokens for a Payment",
security(("publishable_key" = []))
)]
pub fn payments_connector_session() {}
/// Payments - Cancel
///
/// A Payment could can be cancelled when it is in one of these statuses: `requires_payment_method`, `requires_capture`, `requires_confirmation`, `requires_customer_action`.
#[utoipa::path(
post,
path = "/payments/{payment_id}/cancel",
request_body (
content = PaymentsCancelRequest,
examples(
(
"Cancel the payment with minimal fields" = (
value = json!({})
)
),
(
"Cancel the payment with cancellation reason" = (
value = json!({"cancellation_reason": "requested_by_customer"})
)
),
)
),
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
responses(
(status = 200, description = "Payment canceled"),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Cancel a Payment",
security(("api_key" = []))
)]
pub fn payments_cancel() {}
/// Payments - Cancel Post Capture
///
/// A Payment could can be cancelled when it is in one of these statuses: `succeeded`, `partially_captured`, `partially_captured_and_capturable`.
#[utoipa::path(
post,
path = "/payments/{payment_id}/cancel_post_capture",
request_body (
content = PaymentsCancelPostCaptureRequest,
examples(
(
"Cancel the payment post capture with minimal fields" = (
value = json!({})
)
),
(
"Cancel the payment post capture with cancellation reason" = (
value = json!({"cancellation_reason": "requested_by_customer"})
)
),
)
),
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
responses(
(status = 200, description = "Payment canceled post capture"),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Cancel a Payment Post Capture",
security(("api_key" = []))
)]
pub fn payments_cancel_post_capture() {}
/// Payments - List
///
/// To list the *payments*
#[cfg(feature = "v1")]
#[utoipa::path(
get,
path = "/payments/list",
params(
("customer_id" = Option<String>, Query, description = "The identifier for the customer"),
("starting_after" = Option<String>, Query, description = "A cursor for use in pagination, fetch the next list after some object"),
("ending_before" = Option<String>, Query, description = "A cursor for use in pagination, fetch the previous list before some object"),
("limit" = Option<i64>, Query, description = "Limit on the number of objects to return"),
("created" = Option<PrimitiveDateTime>, Query, description = "The time at which payment is created"),
("created_lt" = Option<PrimitiveDateTime>, Query, description = "Time less than the payment created time"),
("created_gt" = Option<PrimitiveDateTime>, Query, description = "Time greater than the payment created time"),
("created_lte" = Option<PrimitiveDateTime>, Query, description = "Time less than or equals to the payment created time"),
("created_gte" = Option<PrimitiveDateTime>, Query, description = "Time greater than or equals to the payment created time")
),
responses(
(status = 200, description = "Successfully retrieved a payment list", body = Vec<PaymentListResponse>),
(status = 404, description = "No payments found")
),
tag = "Payments",
operation_id = "List all Payments",
security(("api_key" = []))
)]
pub fn payments_list() {}
/// Profile level Payments - List
///
/// To list the payments
#[utoipa::path(
get,
path = "/payments/list",
params(
("customer_id" = String, Query, description = "The identifier for the customer"),
("starting_after" = String, Query, description = "A cursor for use in pagination, fetch the next list after some object"),
("ending_before" = String, Query, description = "A cursor for use in pagination, fetch the previous list before some object"),
("limit" = i64, Query, description = "Limit on the number of objects to return"),
("created" = PrimitiveDateTime, Query, description = "The time at which payment is created"),
("created_lt" = PrimitiveDateTime, Query, description = "Time less than the payment created time"),
("created_gt" = PrimitiveDateTime, Query, description = "Time greater than the payment created time"),
("created_lte" = PrimitiveDateTime, Query, description = "Time less than or equals to the payment created time"),
("created_gte" = PrimitiveDateTime, Query, description = "Time greater than or equals to the payment created time")
),
responses(
(status = 200, description = "Received payment list"),
(status = 404, description = "No payments found")
),
tag = "Payments",
operation_id = "List all Payments for the Profile",
security(("api_key" = []))
)]
pub async fn profile_payments_list() {}
/// Payments - Incremental Authorization
///
/// Authorized amount for a payment can be incremented if it is in status: requires_capture
#[utoipa::path(
post,
path = "/payments/{payment_id}/incremental_authorization",
request_body=PaymentsIncrementalAuthorizationRequest,
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
responses(
(status = 200, description = "Payment authorized amount incremented", body = PaymentsResponse),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Increment authorized amount for a Payment",
security(("api_key" = []))
)]
pub fn payments_incremental_authorization() {}
/// Payments - Extended Authorization
///
/// Extended authorization is available for payments currently in the `requires_capture` status
/// Call this endpoint to increase the authorization validity period
#[utoipa::path(
post,
path = "/payments/{payment_id}/extend_authorization",
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
responses(
(status = 200, description = "Extended authorization for the payment"),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Extend authorization period for a Payment",
security(("api_key" = []))
)]
pub fn payments_extend_authorization() {}
/// Payments - External 3DS Authentication
///
/// External 3DS Authentication is performed and returns the AuthenticationResponse
#[utoipa::path(
post,
path = "/payments/{payment_id}/3ds/authentication",
request_body=PaymentsExternalAuthenticationRequest,
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
responses(
(status = 200, description = "Authentication created", body = PaymentsExternalAuthenticationResponse),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Initiate external authentication for a Payment",
security(("publishable_key" = []))
)]
pub fn payments_external_authentication() {}
/// Payments - Complete Authorize
#[utoipa::path(
post,
path = "/payments/{payment_id}/complete_authorize",
request_body=PaymentsCompleteAuthorizeRequest,
params(
("payment_id" =String, Path, description = "The identifier for payment")
),
responses(
(status = 200, description = "Payments Complete Authorize Success", body = PaymentsResponse),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Complete Authorize a Payment",
security(("publishable_key" = []))
)]
pub fn payments_complete_authorize() {}
/// Dynamic Tax Calculation
#[utoipa::path(
post,
path = "/payments/{payment_id}/calculate_tax",
request_body=PaymentsDynamicTaxCalculationRequest,
responses(
(status = 200, description = "Tax Calculation is done", body = PaymentsDynamicTaxCalculationResponse),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Create Tax Calculation for a Payment",
security(("publishable_key" = []))
)]
pub fn payments_dynamic_tax_calculation() {}
/// Payments - Post Session Tokens
#[utoipa::path(
post,
path = "/payments/{payment_id}/post_session_tokens",
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
request_body=PaymentsPostSessionTokensRequest,
responses(
(status = 200, description = "Post Session Token is done", body = PaymentsPostSessionTokensResponse),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Create Post Session Tokens for a Payment",
security(("publishable_key" = []))
)]
pub fn payments_post_session_tokens() {}
/// Payments - Update Metadata
#[utoipa::path(
post,
path = "/payments/{payment_id}/update_metadata",
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
request_body=PaymentsUpdateMetadataRequest,
responses(
(status = 200, description = "Metadata updated successfully", body = PaymentsUpdateMetadataResponse),
(status = 400, description = "Missing mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Update Metadata for a Payment",
security(("api_key" = []))
)]
pub fn payments_update_metadata() {}
/// Payments - Submit Eligibility Data
#[utoipa::path(
post,
path = "/payments/{payment_id}/eligibility",
params(
("payment_id" = String, Path, description = "The identifier for payment")
),
request_body=PaymentsEligibilityRequest,
responses(
(status = 200, description = "Eligbility submit is successful", body = PaymentsEligibilityResponse),
(status = 400, description = "Bad Request", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Submit Eligibility data for a Payment",
security(("publishable_key" = []))
)]
pub fn payments_submit_eligibility() {}
/// Payments - Create Intent
///
/// **Creates a payment intent object when amount_details are passed.**
///
/// You will require the 'API - Key' from the Hyperswitch dashboard to make the first call, and use the 'client secret' returned in this API along with your 'publishable key' to make subsequent API calls from your client.
#[utoipa::path(
post,
path = "/v2/payments/create-intent",
request_body(
content = PaymentsCreateIntentRequest,
examples(
(
"Create a payment intent with minimal fields" = (
value = json!({"amount_details": {"order_amount": 6540, "currency": "USD"}})
)
),
),
),
responses(
(status = 200, description = "Payment created", body = PaymentsIntentResponse),
(status = 400, description = "Missing Mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Create a Payment Intent",
security(("api_key" = [])),
)]
#[cfg(feature = "v2")]
pub fn payments_create_intent() {}
/// Payments - Get Intent
///
/// **Get a payment intent object when id is passed in path**
///
/// You will require the 'API - Key' from the Hyperswitch dashboard to make the call.
#[utoipa::path(
get,
path = "/v2/payments/{id}/get-intent",
params (("id" = String, Path, description = "The unique identifier for the Payment Intent")),
responses(
(status = 200, description = "Payment Intent", body = PaymentsIntentResponse),
(status = 404, description = "Payment Intent not found")
),
tag = "Payments",
operation_id = "Get the Payment Intent details",
security(("api_key" = [])),
)]
#[cfg(feature = "v2")]
pub fn payments_get_intent() {}
/// Payments - Update Intent
///
/// **Update a payment intent object**
///
/// You will require the 'API - Key' from the Hyperswitch dashboard to make the call.
#[utoipa::path(
put,
path = "/v2/payments/{id}/update-intent",
params (("id" = String, Path, description = "The unique identifier for the Payment Intent"),
(
"X-Profile-Id" = String, Header,
description = "Profile ID associated to the payment intent",
example = "pro_abcdefghijklmnop"
),
),
request_body(
content = PaymentsUpdateIntentRequest,
examples(
(
"Update a payment intent with minimal fields" = (
value = json!({"amount_details": {"order_amount": 6540, "currency": "USD"}})
)
),
),
),
responses(
(status = 200, description = "Payment Intent Updated", body = PaymentsIntentResponse),
(status = 404, description = "Payment Intent Not Found")
),
tag = "Payments",
operation_id = "Update a Payment Intent",
security(("api_key" = [])),
)]
#[cfg(feature = "v2")]
pub fn payments_update_intent() {}
/// Payments - Confirm Intent
///
/// **Confirms a payment intent object with the payment method data**
///
/// .
#[utoipa::path(
post,
path = "/v2/payments/{id}/confirm-intent",
params (("id" = String, Path, description = "The unique identifier for the Payment Intent"),
(
"X-Profile-Id" = String, Header,
description = "Profile ID associated to the payment intent",
example = "pro_abcdefghijklmnop"
)
),
request_body(
content = PaymentsConfirmIntentRequest,
examples(
(
"Confirm the payment intent with card details" = (
value = json!({
"payment_method_type": "card",
"payment_method_subtype": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
})
)
),
),
),
responses(
(status = 200, description = "Payment created", body = PaymentsResponse),
(status = 400, description = "Missing Mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Confirm Payment Intent",
security(("publishable_key" = [])),
)]
#[cfg(feature = "v2")]
pub fn payments_confirm_intent() {}
/// Payments - Get
///
/// Retrieves a Payment. This API can also be used to get the status of a previously initiated payment or next action for an ongoing payment
#[utoipa::path(
get,
path = "/v2/payments/{id}",
params(
("id" = String, Path, description = "The global payment id"),
("force_sync" = ForceSync, Query, description = "A boolean to indicate whether to force sync the payment status. Value can be true or false")
),
responses(
(status = 200, description = "Gets the payment with final status", body = PaymentsResponse),
(status = 404, description = "No payment found with the given id")
),
tag = "Payments",
operation_id = "Retrieve a Payment",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub fn payment_status() {}
/// Payments - Create and Confirm Intent
///
/// **Creates and confirms a payment intent object when the amount and payment method information are passed.**
///
/// You will require the 'API - Key' from the Hyperswitch dashboard to make the call.
#[utoipa::path(
post,
path = "/v2/payments",
params (
(
"X-Profile-Id" = String, Header,
description = "Profile ID associated to the payment intent",
example = "pro_abcdefghijklmnop"
)
),
request_body(
content = PaymentsRequest,
examples(
(
"Create and confirm the payment intent with amount and card details" = (
value = json!({
"amount_details": {
"order_amount": 6540,
"currency": "USD"
},
"payment_method_type": "card",
"payment_method_subtype": "credit",
"payment_method_data": {
"card": {
"card_number": "4242424242424242",
"card_exp_month": "10",
"card_exp_year": "25",
"card_holder_name": "joseph Doe",
"card_cvc": "123"
}
},
})
)
),
),
),
responses(
(status = 200, description = "Payment created", body = PaymentsResponse),
(status = 400, description = "Missing Mandatory fields", body = GenericErrorResponseOpenApi)
),
tag = "Payments",
operation_id = "Create and Confirm Payment Intent",
security(("api_key" = [])),
)]
pub fn payments_create_and_confirm_intent() {}
#[derive(utoipa::ToSchema)]
#[schema(rename_all = "lowercase")]
pub(crate) enum ForceSync {
/// Force sync with the connector / processor to update the status
True,
/// Do not force sync with the connector / processor. Get the status which is available in the database
False,
}
/// Payments - Payment Methods List
///
/// List the payment methods eligible for a payment. This endpoint also returns the saved payment methods for the customer when the customer_id is passed when creating the payment
#[cfg(feature = "v2")]
#[utoipa::path(
get,
path = "/v2/payments/{id}/payment-methods",
params(
("id" = String, Path, description = "The global payment id"),
(
"X-Profile-Id" = String, Header,
description = "Profile ID associated to the payment intent",
example = "pro_abcdefghijklmnop"
),
),
responses(
(status = 200, description = "Get the payment methods", body = PaymentMethodListResponseForPayments),
(status = 404, description = "No payment found with the given id")
),
tag = "Payments",
operation_id = "Retrieve Payment methods for a Payment",
security(("publishable_key" = []))
)]
pub fn list_payment_methods() {}
/// Payments - List
///
/// To list the *payments*
#[cfg(feature = "v2")]
#[utoipa::path(
get,
path = "/v2/payments/list",
params(api_models::payments::PaymentListConstraints),
responses(
(status = 200, description = "Successfully retrieved a payment list", body = PaymentListResponse),
(status = 404, description = "No payments found")
),
tag = "Payments",
operation_id = "List all Payments",
security(("api_key" = []), ("jwt_key" = []))
)]
pub fn payments_list() {}
/// Payments - Gift Card Balance Check
///
/// Check the balance of the provided gift card. This endpoint also returns whether the gift card balance is enough to cover the entire amount or another payment method is needed
#[cfg(feature = "v2")]
#[utoipa::path(
get,
path = "/v2/payments/{id}/check-gift-card-balance",
params(
("id" = String, Path, description = "The global payment id"),
(
"X-Profile-Id" = String, Header,
description = "Profile ID associated to the payment intent",
example = "pro_abcdefghijklmnop"
),
),
request_body(
content = PaymentsGiftCardBalanceCheckRequest,
),
responses(
(status = 200, description = "Get the Gift Card Balance", body = GiftCardBalanceCheckResponse),
),
tag = "Payments",
operation_id = "Retrieve Gift Card Balance",
security(("publishable_key" = []))
)]
pub fn payment_check_gift_card_balance() {}
| crates/openapi/src/routes/payments.rs | openapi::src::routes::payments | 12,034 | true |
// File: crates/openapi/src/routes/disputes.rs
// Module: openapi::src::routes::disputes
/// Disputes - Retrieve Dispute
/// Retrieves a dispute
#[utoipa::path(
get,
path = "/disputes/{dispute_id}",
params(
("dispute_id" = String, Path, description = "The identifier for dispute"),
("force_sync" = Option<bool>, Query, description = "Decider to enable or disable the connector call for dispute retrieve request"),
),
responses(
(status = 200, description = "The dispute was retrieved successfully", body = DisputeResponse),
(status = 404, description = "Dispute does not exist in our records")
),
tag = "Disputes",
operation_id = "Retrieve a Dispute",
security(("api_key" = []))
)]
pub async fn retrieve_dispute() {}
/// Disputes - List Disputes
/// Lists all the Disputes for a merchant
#[utoipa::path(
get,
path = "/disputes/list",
params(
("limit" = Option<i64>, Query, description = "The maximum number of Dispute Objects to include in the response"),
("dispute_status" = Option<DisputeStatus>, Query, description = "The status of dispute"),
("dispute_stage" = Option<DisputeStage>, Query, description = "The stage of dispute"),
("reason" = Option<String>, Query, description = "The reason for dispute"),
("connector" = Option<String>, Query, description = "The connector linked to dispute"),
("received_time" = Option<PrimitiveDateTime>, Query, description = "The time at which dispute is received"),
("received_time.lt" = Option<PrimitiveDateTime>, Query, description = "Time less than the dispute received time"),
("received_time.gt" = Option<PrimitiveDateTime>, Query, description = "Time greater than the dispute received time"),
("received_time.lte" = Option<PrimitiveDateTime>, Query, description = "Time less than or equals to the dispute received time"),
("received_time.gte" = Option<PrimitiveDateTime>, Query, description = "Time greater than or equals to the dispute received time"),
),
responses(
(status = 200, description = "The dispute list was retrieved successfully", body = Vec<DisputeResponse>),
(status = 401, description = "Unauthorized request")
),
tag = "Disputes",
operation_id = "List Disputes",
security(("api_key" = []))
)]
pub async fn retrieve_disputes_list() {}
/// Disputes - List Disputes for The Given Profiles
/// Lists all the Disputes for a merchant
#[utoipa::path(
get,
path = "/disputes/profile/list",
params(
("limit" = Option<i64>, Query, description = "The maximum number of Dispute Objects to include in the response"),
("dispute_status" = Option<DisputeStatus>, Query, description = "The status of dispute"),
("dispute_stage" = Option<DisputeStage>, Query, description = "The stage of dispute"),
("reason" = Option<String>, Query, description = "The reason for dispute"),
("connector" = Option<String>, Query, description = "The connector linked to dispute"),
("received_time" = Option<PrimitiveDateTime>, Query, description = "The time at which dispute is received"),
("received_time.lt" = Option<PrimitiveDateTime>, Query, description = "Time less than the dispute received time"),
("received_time.gt" = Option<PrimitiveDateTime>, Query, description = "Time greater than the dispute received time"),
("received_time.lte" = Option<PrimitiveDateTime>, Query, description = "Time less than or equals to the dispute received time"),
("received_time.gte" = Option<PrimitiveDateTime>, Query, description = "Time greater than or equals to the dispute received time"),
),
responses(
(status = 200, description = "The dispute list was retrieved successfully", body = Vec<DisputeResponse>),
(status = 401, description = "Unauthorized request")
),
tag = "Disputes",
operation_id = "List Disputes for The given Profiles",
security(("api_key" = []))
)]
pub async fn retrieve_disputes_list_profile() {}
| crates/openapi/src/routes/disputes.rs | openapi::src::routes::disputes | 956 | true |
// File: crates/openapi/src/routes/blocklist.rs
// Module: openapi::src::routes::blocklist
#[utoipa::path(
post,
path = "/blocklist/toggle",
params (
("status" = bool, Query, description = "Boolean value to enable/disable blocklist"),
),
responses(
(status = 200, description = "Blocklist guard enabled/disabled", body = ToggleBlocklistResponse),
(status = 400, description = "Invalid Data")
),
tag = "Blocklist",
operation_id = "Toggle blocklist guard for a particular merchant",
security(("api_key" = []))
)]
pub async fn toggle_blocklist_guard() {}
#[utoipa::path(
post,
path = "/blocklist",
request_body = BlocklistRequest,
responses(
(status = 200, description = "Fingerprint Blocked", body = BlocklistResponse),
(status = 400, description = "Invalid Data")
),
tag = "Blocklist",
operation_id = "Block a Fingerprint",
security(("api_key" = []))
)]
pub async fn add_entry_to_blocklist() {}
#[utoipa::path(
delete,
path = "/blocklist",
request_body = BlocklistRequest,
responses(
(status = 200, description = "Fingerprint Unblocked", body = BlocklistResponse),
(status = 400, description = "Invalid Data")
),
tag = "Blocklist",
operation_id = "Unblock a Fingerprint",
security(("api_key" = []))
)]
pub async fn remove_entry_from_blocklist() {}
#[utoipa::path(
get,
path = "/blocklist",
params (
("data_kind" = BlocklistDataKind, Query, description = "Kind of the fingerprint list requested"),
),
responses(
(status = 200, description = "Blocked Fingerprints", body = BlocklistResponse),
(status = 400, description = "Invalid Data")
),
tag = "Blocklist",
operation_id = "List Blocked fingerprints of a particular kind",
security(("api_key" = []))
)]
pub async fn list_blocked_payment_methods() {}
| crates/openapi/src/routes/blocklist.rs | openapi::src::routes::blocklist | 487 | true |
// File: crates/openapi/src/routes/payment_link.rs
// Module: openapi::src::routes::payment_link
/// Payments Link - Retrieve
///
/// To retrieve the properties of a Payment Link. This may be used to get the status of a previously initiated payment or next action for an ongoing payment
#[utoipa::path(
get,
path = "/payment_link/{payment_link_id}",
params(
("payment_link_id" = String, Path, description = "The identifier for payment link"),
("client_secret" = Option<String>, Query, description = "This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK"),
),
responses(
(status = 200, description = "Gets details regarding payment link", body = RetrievePaymentLinkResponse),
(status = 404, description = "No payment link found")
),
tag = "Payments",
operation_id = "Retrieve a Payment Link",
security(("api_key" = []), ("publishable_key" = []))
)]
pub async fn payment_link_retrieve() {}
| crates/openapi/src/routes/payment_link.rs | openapi::src::routes::payment_link | 237 | true |
// File: crates/openapi/src/routes/poll.rs
// Module: openapi::src::routes::poll
/// Poll - Retrieve Poll Status
#[utoipa::path(
get,
path = "/poll/status/{poll_id}",
params(
("poll_id" = String, Path, description = "The identifier for poll")
),
responses(
(status = 200, description = "The poll status was retrieved successfully", body = PollResponse),
(status = 404, description = "Poll not found")
),
tag = "Poll",
operation_id = "Retrieve Poll Status",
security(("publishable_key" = []))
)]
pub async fn retrieve_poll_status() {}
| crates/openapi/src/routes/poll.rs | openapi::src::routes::poll | 152 | true |
// File: crates/openapi/src/routes/api_keys.rs
// Module: openapi::src::routes::api_keys
#[cfg(feature = "v1")]
/// API Key - Create
///
/// Create a new API Key for accessing our APIs from your servers. The plaintext API Key will be
/// displayed only once on creation, so ensure you store it securely.
#[utoipa::path(
post,
path = "/api_keys/{merchant_id}",
params(("merchant_id" = String, Path, description = "The unique identifier for the merchant account")),
request_body= CreateApiKeyRequest,
responses(
(status = 200, description = "API Key created", body = CreateApiKeyResponse),
(status = 400, description = "Invalid data")
),
tag = "API Key",
operation_id = "Create an API Key",
security(("admin_api_key" = []))
)]
pub async fn api_key_create() {}
#[cfg(feature = "v2")]
/// API Key - Create
///
/// Create a new API Key for accessing our APIs from your servers. The plaintext API Key will be
/// displayed only once on creation, so ensure you store it securely.
#[utoipa::path(
post,
path = "/v2/api-keys",
request_body= CreateApiKeyRequest,
responses(
(status = 200, description = "API Key created", body = CreateApiKeyResponse),
(status = 400, description = "Invalid data")
),
tag = "API Key",
operation_id = "Create an API Key",
security(("admin_api_key" = []))
)]
pub async fn api_key_create() {}
#[cfg(feature = "v1")]
/// API Key - Retrieve
///
/// Retrieve information about the specified API Key.
#[utoipa::path(
get,
path = "/api_keys/{merchant_id}/{key_id}",
params (
("merchant_id" = String, Path, description = "The unique identifier for the merchant account"),
("key_id" = String, Path, description = "The unique identifier for the API Key")
),
responses(
(status = 200, description = "API Key retrieved", body = RetrieveApiKeyResponse),
(status = 404, description = "API Key not found")
),
tag = "API Key",
operation_id = "Retrieve an API Key",
security(("admin_api_key" = []))
)]
pub async fn api_key_retrieve() {}
#[cfg(feature = "v2")]
/// API Key - Retrieve
///
/// Retrieve information about the specified API Key.
#[utoipa::path(
get,
path = "/v2/api-keys/{id}",
params (
("id" = String, Path, description = "The unique identifier for the API Key")
),
responses(
(status = 200, description = "API Key retrieved", body = RetrieveApiKeyResponse),
(status = 404, description = "API Key not found")
),
tag = "API Key",
operation_id = "Retrieve an API Key",
security(("admin_api_key" = []))
)]
pub async fn api_key_retrieve() {}
#[cfg(feature = "v1")]
/// API Key - Update
///
/// Update information for the specified API Key.
#[utoipa::path(
post,
path = "/api_keys/{merchant_id}/{key_id}",
request_body = UpdateApiKeyRequest,
params (
("merchant_id" = String, Path, description = "The unique identifier for the merchant account"),
("key_id" = String, Path, description = "The unique identifier for the API Key")
),
responses(
(status = 200, description = "API Key updated", body = RetrieveApiKeyResponse),
(status = 404, description = "API Key not found")
),
tag = "API Key",
operation_id = "Update an API Key",
security(("admin_api_key" = []))
)]
pub async fn api_key_update() {}
#[cfg(feature = "v2")]
/// API Key - Update
///
/// Update information for the specified API Key.
#[utoipa::path(
put,
path = "/v2/api-keys/{id}",
request_body = UpdateApiKeyRequest,
params (
("id" = String, Path, description = "The unique identifier for the API Key")
),
responses(
(status = 200, description = "API Key updated", body = RetrieveApiKeyResponse),
(status = 404, description = "API Key not found")
),
tag = "API Key",
operation_id = "Update an API Key",
security(("admin_api_key" = []))
)]
pub async fn api_key_update() {}
#[cfg(feature = "v1")]
/// API Key - Revoke
///
/// Revoke the specified API Key. Once revoked, the API Key can no longer be used for
/// authenticating with our APIs.
#[utoipa::path(
delete,
path = "/api_keys/{merchant_id}/{key_id}",
params (
("merchant_id" = String, Path, description = "The unique identifier for the merchant account"),
("key_id" = String, Path, description = "The unique identifier for the API Key")
),
responses(
(status = 200, description = "API Key revoked", body = RevokeApiKeyResponse),
(status = 404, description = "API Key not found")
),
tag = "API Key",
operation_id = "Revoke an API Key",
security(("admin_api_key" = []))
)]
pub async fn api_key_revoke() {}
#[cfg(feature = "v2")]
/// API Key - Revoke
///
/// Revoke the specified API Key. Once revoked, the API Key can no longer be used for
/// authenticating with our APIs.
#[utoipa::path(
delete,
path = "/v2/api-keys/{id}",
params (
("id" = String, Path, description = "The unique identifier for the API Key")
),
responses(
(status = 200, description = "API Key revoked", body = RevokeApiKeyResponse),
(status = 404, description = "API Key not found")
),
tag = "API Key",
operation_id = "Revoke an API Key",
security(("admin_api_key" = []))
)]
pub async fn api_key_revoke() {}
#[cfg(feature = "v1")]
/// API Key - List
///
/// List all the API Keys associated to a merchant account.
#[utoipa::path(
get,
path = "/api_keys/{merchant_id}/list",
params(
("merchant_id" = String, Path, description = "The unique identifier for the merchant account"),
("limit" = Option<i64>, Query, description = "The maximum number of API Keys to include in the response"),
("skip" = Option<i64>, Query, description = "The number of API Keys to skip when retrieving the list of API keys."),
),
responses(
(status = 200, description = "List of API Keys retrieved successfully", body = Vec<RetrieveApiKeyResponse>),
),
tag = "API Key",
operation_id = "List all API Keys associated with a merchant account",
security(("admin_api_key" = []))
)]
pub async fn api_key_list() {}
#[cfg(feature = "v2")]
/// API Key - List
///
/// List all the API Keys associated to a merchant account.
#[utoipa::path(
get,
path = "/v2/api-keys/list",
params(
("limit" = Option<i64>, Query, description = "The maximum number of API Keys to include in the response"),
("skip" = Option<i64>, Query, description = "The number of API Keys to skip when retrieving the list of API keys."),
),
responses(
(status = 200, description = "List of API Keys retrieved successfully", body = Vec<RetrieveApiKeyResponse>),
),
tag = "API Key",
operation_id = "List all API Keys associated with a merchant account",
security(("admin_api_key" = []))
)]
pub async fn api_key_list() {}
| crates/openapi/src/routes/api_keys.rs | openapi::src::routes::api_keys | 1,773 | true |
// File: crates/openapi/src/routes/customers.rs
// Module: openapi::src::routes::customers
/// Customers - Create
///
/// Creates a customer object and stores the customer details to be reused for future payments.
/// Incase the customer already exists in the system, this API will respond with the customer details.
#[utoipa::path(
post,
path = "/customers",
request_body (
content = CustomerRequest,
examples (( "Update name and email of a customer" =(
value =json!( {
"email": "guest@example.com",
"name": "John Doe"
})
)))
),
responses(
(status = 200, description = "Customer Created", body = CustomerResponse),
(status = 400, description = "Invalid data")
),
tag = "Customers",
operation_id = "Create a Customer",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn customers_create() {}
/// Customers - Retrieve
///
/// Retrieves a customer's details.
#[utoipa::path(
get,
path = "/customers/{customer_id}",
params (("customer_id" = String, Path, description = "The unique identifier for the Customer")),
responses(
(status = 200, description = "Customer Retrieved", body = CustomerResponse),
(status = 404, description = "Customer was not found")
),
tag = "Customers",
operation_id = "Retrieve a Customer",
security(("api_key" = []), ("ephemeral_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn customers_retrieve() {}
/// Customers - Update
///
/// Updates the customer's details in a customer object.
#[utoipa::path(
post,
path = "/customers/{customer_id}",
request_body (
content = CustomerUpdateRequest,
examples (( "Update name and email of a customer" =(
value =json!( {
"email": "guest@example.com",
"name": "John Doe"
})
)))
),
params (("customer_id" = String, Path, description = "The unique identifier for the Customer")),
responses(
(status = 200, description = "Customer was Updated", body = CustomerResponse),
(status = 404, description = "Customer was not found")
),
tag = "Customers",
operation_id = "Update a Customer",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn customers_update() {}
/// Customers - Delete
///
/// Delete a customer record.
#[utoipa::path(
delete,
path = "/customers/{customer_id}",
params (("customer_id" = String, Path, description = "The unique identifier for the Customer")),
responses(
(status = 200, description = "Customer was Deleted", body = CustomerDeleteResponse),
(status = 404, description = "Customer was not found")
),
tag = "Customers",
operation_id = "Delete a Customer",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn customers_delete() {}
/// Customers - List
///
/// Lists all the customers for a particular merchant id.
#[utoipa::path(
get,
path = "/customers/list",
params (("offset" = Option<u32>, Query, description = "Offset for pagination"),
("limit" = Option<u16>, Query, description = "Limit for pagination")),
responses(
(status = 200, description = "Customers retrieved", body = Vec<CustomerResponse>),
(status = 400, description = "Invalid Data"),
),
tag = "Customers",
operation_id = "List all Customers for a Merchant",
security(("api_key" = []))
)]
#[cfg(feature = "v1")]
pub async fn customers_list() {}
/// Customers - Create
///
/// Creates a customer object and stores the customer details to be reused for future payments.
/// Incase the customer already exists in the system, this API will respond with the customer details.
#[utoipa::path(
post,
path = "/v2/customers",
request_body (
content = CustomerRequest,
examples (( "Create a customer with name and email" =(
value =json!( {
"email": "guest@example.com",
"name": "John Doe"
})
)))
),
responses(
(status = 200, description = "Customer Created", body = CustomerResponse),
(status = 400, description = "Invalid data")
),
tag = "Customers",
operation_id = "Create a Customer",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn customers_create() {}
/// Customers - Retrieve
///
/// Retrieves a customer's details.
#[utoipa::path(
get,
path = "/v2/customers/{id}",
params (("id" = String, Path, description = "The unique identifier for the Customer")),
responses(
(status = 200, description = "Customer Retrieved", body = CustomerResponse),
(status = 404, description = "Customer was not found")
),
tag = "Customers",
operation_id = "Retrieve a Customer",
security(("api_key" = []), ("ephemeral_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn customers_retrieve() {}
/// Customers - Update
///
/// Updates the customer's details in a customer object.
#[utoipa::path(
post,
path = "/v2/customers/{id}",
request_body (
content = CustomerUpdateRequest,
examples (( "Update name and email of a customer" =(
value =json!( {
"email": "guest@example.com",
"name": "John Doe"
})
)))
),
params (("id" = String, Path, description = "The unique identifier for the Customer")),
responses(
(status = 200, description = "Customer was Updated", body = CustomerResponse),
(status = 404, description = "Customer was not found")
),
tag = "Customers",
operation_id = "Update a Customer",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn customers_update() {}
/// Customers - Delete
///
/// Delete a customer record.
#[utoipa::path(
delete,
path = "/v2/customers/{id}",
params (("id" = String, Path, description = "The unique identifier for the Customer")),
responses(
(status = 200, description = "Customer was Deleted", body = CustomerDeleteResponse),
(status = 404, description = "Customer was not found")
),
tag = "Customers",
operation_id = "Delete a Customer",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn customers_delete() {}
/// Customers - List
///
/// Lists all the customers for a particular merchant id.
#[utoipa::path(
get,
path = "/v2/customers/list",
responses(
(status = 200, description = "Customers retrieved", body = Vec<CustomerResponse>),
(status = 400, description = "Invalid Data"),
),
tag = "Customers",
operation_id = "List all Customers for a Merchant",
security(("api_key" = []))
)]
#[cfg(feature = "v2")]
pub async fn customers_list() {}
| crates/openapi/src/routes/customers.rs | openapi::src::routes::customers | 1,644 | true |
// File: crates/openapi/src/routes/gsm.rs
// Module: openapi::src::routes::gsm
/// Gsm - Create
///
/// Creates a GSM (Global Status Mapping) Rule. A GSM rule is used to map a connector's error message/error code combination during a particular payments flow/sub-flow to Hyperswitch's unified status/error code/error message combination. It is also used to decide the next action in the flow - retry/requeue/do_default
#[utoipa::path(
post,
path = "/gsm",
request_body(
content = GsmCreateRequest,
),
responses(
(status = 200, description = "Gsm created", body = GsmResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Gsm",
operation_id = "Create Gsm Rule",
security(("admin_api_key" = [])),
)]
pub async fn create_gsm_rule() {}
/// Gsm - Get
///
/// Retrieves a Gsm Rule
#[utoipa::path(
post,
path = "/gsm/get",
request_body(
content = GsmRetrieveRequest,
),
responses(
(status = 200, description = "Gsm retrieved", body = GsmResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Gsm",
operation_id = "Retrieve Gsm Rule",
security(("admin_api_key" = [])),
)]
pub async fn get_gsm_rule() {}
/// Gsm - Update
///
/// Updates a Gsm Rule
#[utoipa::path(
post,
path = "/gsm/update",
request_body(
content = GsmUpdateRequest,
),
responses(
(status = 200, description = "Gsm updated", body = GsmResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Gsm",
operation_id = "Update Gsm Rule",
security(("admin_api_key" = [])),
)]
pub async fn update_gsm_rule() {}
/// Gsm - Delete
///
/// Deletes a Gsm Rule
#[utoipa::path(
post,
path = "/gsm/delete",
request_body(
content = GsmDeleteRequest,
),
responses(
(status = 200, description = "Gsm deleted", body = GsmDeleteResponse),
(status = 400, description = "Missing Mandatory fields")
),
tag = "Gsm",
operation_id = "Delete Gsm Rule",
security(("admin_api_key" = [])),
)]
pub async fn delete_gsm_rule() {}
| crates/openapi/src/routes/gsm.rs | openapi::src::routes::gsm | 583 | true |
// File: crates/openapi/src/routes/revenue_recovery.rs
// Module: openapi::src::routes::revenue_recovery
#[cfg(feature = "v2")]
/// Revenue Recovery - Retrieve
///
/// Retrieve the Revenue Recovery Payment Info
#[utoipa::path(
get,
path = "/v2/process-trackers/revenue-recovery-workflow/{revenue_recovery_id}",
params(
("recovery_recovery_id" = String, Path, description = "The payment intent id"),
),
responses(
(status = 200, description = "Revenue Recovery Info Retrieved Successfully", body = RevenueRecoveryResponse),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Revenue Recovery",
operation_id = "Retrieve Revenue Recovery Info",
security(("jwt_key" = []))
)]
pub async fn revenue_recovery_pt_retrieve_api() {}
| crates/openapi/src/routes/revenue_recovery.rs | openapi::src::routes::revenue_recovery | 234 | true |
// File: crates/openapi/src/routes/profile_acquirer.rs
// Module: openapi::src::routes::profile_acquirer
#[cfg(feature = "v1")]
/// Profile Acquirer - Create
///
/// Create a new Profile Acquirer for accessing our APIs from your servers.
#[utoipa::path(
post,
path = "/profile_acquirers",
request_body = ProfileAcquirerCreate,
responses(
(status = 200, description = "Profile Acquirer created", body = ProfileAcquirerResponse),
(status = 400, description = "Invalid data")
),
tag = "Profile Acquirer",
operation_id = "Create a Profile Acquirer",
security(("api_key" = []))
)]
pub async fn profile_acquirer_create() { /* … */
}
#[cfg(feature = "v1")]
/// Profile Acquirer - Update
///
/// Update a Profile Acquirer for accessing our APIs from your servers.
#[utoipa::path(
post,
path = "/profile_acquirers/{profile_id}/{profile_acquirer_id}",
params (
("profile_id" = String, Path, description = "The unique identifier for the Profile"),
("profile_acquirer_id" = String, Path, description = "The unique identifier for the Profile Acquirer")
),
request_body = ProfileAcquirerUpdate,
responses(
(status = 200, description = "Profile Acquirer updated", body = ProfileAcquirerResponse),
(status = 400, description = "Invalid data")
),
tag = "Profile Acquirer",
operation_id = "Update a Profile Acquirer",
security(("api_key" = []))
)]
pub async fn profile_acquirer_update() { /* … */
}
| crates/openapi/src/routes/profile_acquirer.rs | openapi::src::routes::profile_acquirer | 371 | true |
// File: crates/openapi/src/routes/authentication.rs
// Module: openapi::src::routes::authentication
/// Authentication - Create
///
/// Create a new authentication for accessing our APIs from your servers.
///
#[utoipa::path(
post,
path = "/authentication",
request_body = AuthenticationCreateRequest,
responses(
(status = 200, description = "Authentication created", body = AuthenticationResponse),
(status = 400, description = "Invalid data")
),
tag = "Authentication",
operation_id = "Create an Authentication",
security(("api_key" = []))
)]
pub async fn authentication_create() {}
| crates/openapi/src/routes/authentication.rs | openapi::src::routes::authentication | 138 | true |
// File: crates/openapi/src/routes/routing.rs
// Module: openapi::src::routes::routing
#[cfg(feature = "v1")]
/// Routing - Create
///
/// Create a routing config
#[utoipa::path(
post,
path = "/routing",
request_body = RoutingConfigRequest,
responses(
(status = 200, description = "Routing config created", body = RoutingDictionaryRecord),
(status = 400, description = "Request body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Create a routing config",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_create_config() {}
#[cfg(feature = "v2")]
/// Routing - Create
///
/// Create a routing algorithm
#[utoipa::path(
post,
path = "/v2/routing-algorithms",
request_body = RoutingConfigRequest,
responses(
(status = 200, description = "Routing Algorithm created", body = RoutingDictionaryRecord),
(status = 400, description = "Request body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Create a routing algorithm",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_create_config() {}
#[cfg(feature = "v1")]
/// Routing - Activate config
///
/// Activate a routing config
#[utoipa::path(
post,
path = "/routing/{routing_algorithm_id}/activate",
params(
("routing_algorithm_id" = String, Path, description = "The unique identifier for a config"),
),
responses(
(status = 200, description = "Routing config activated", body = RoutingDictionaryRecord),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 400, description = "Bad request")
),
tag = "Routing",
operation_id = "Activate a routing config",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_link_config() {}
#[cfg(feature = "v1")]
/// Routing - Retrieve
///
/// Retrieve a routing algorithm
#[utoipa::path(
get,
path = "/routing/{routing_algorithm_id}",
params(
("routing_algorithm_id" = String, Path, description = "The unique identifier for a config"),
),
responses(
(status = 200, description = "Successfully fetched routing config", body = MerchantRoutingAlgorithm),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 403, description = "Forbidden")
),
tag = "Routing",
operation_id = "Retrieve a routing config",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_retrieve_config() {}
#[cfg(feature = "v2")]
/// Routing - Retrieve
///
/// Retrieve a routing algorithm with its algorithm id
#[utoipa::path(
get,
path = "/v2/routing-algorithms/{id}",
params(
("id" = String, Path, description = "The unique identifier for a routing algorithm"),
),
responses(
(status = 200, description = "Successfully fetched routing algorithm", body = MerchantRoutingAlgorithm),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 403, description = "Forbidden")
),
tag = "Routing",
operation_id = "Retrieve a routing algorithm with its algorithm id",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_retrieve_config() {}
#[cfg(feature = "v1")]
/// Routing - List
///
/// List all routing configs
#[utoipa::path(
get,
path = "/routing",
params(
("limit" = Option<u16>, Query, description = "The number of records to be returned"),
("offset" = Option<u8>, Query, description = "The record offset from which to start gathering of results"),
("profile_id" = Option<String>, Query, description = "The unique identifier for a merchant profile"),
),
responses(
(status = 200, description = "Successfully fetched routing configs", body = RoutingKind),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing")
),
tag = "Routing",
operation_id = "List routing configs",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn list_routing_configs() {}
#[cfg(feature = "v1")]
/// Routing - Deactivate
///
/// Deactivates a routing config
#[utoipa::path(
post,
path = "/routing/deactivate",
request_body = RoutingConfigRequest,
responses(
(status = 200, description = "Successfully deactivated routing config", body = RoutingDictionaryRecord),
(status = 500, description = "Internal server error"),
(status = 400, description = "Malformed request"),
(status = 403, description = "Malformed request"),
(status = 422, description = "Unprocessable request")
),
tag = "Routing",
operation_id = "Deactivate a routing config",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_unlink_config() {}
#[cfg(feature = "v1")]
/// Routing - Update Default Config
///
/// Update default fallback config
#[utoipa::path(
post,
path = "/routing/default",
request_body = Vec<RoutableConnectorChoice>,
responses(
(status = 200, description = "Successfully updated default config", body = Vec<RoutableConnectorChoice>),
(status = 500, description = "Internal server error"),
(status = 400, description = "Malformed request"),
(status = 422, description = "Unprocessable request")
),
tag = "Routing",
operation_id = "Update default fallback config",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_update_default_config() {}
#[cfg(feature = "v1")]
/// Routing - Retrieve Default Config
///
/// Retrieve default fallback config
#[utoipa::path(
get,
path = "/routing/default",
responses(
(status = 200, description = "Successfully retrieved default config", body = Vec<RoutableConnectorChoice>),
(status = 500, description = "Internal server error")
),
tag = "Routing",
operation_id = "Retrieve default fallback config",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_retrieve_default_config() {}
#[cfg(feature = "v1")]
/// Routing - Retrieve Config
///
/// Retrieve active config
#[utoipa::path(
get,
path = "/routing/active",
params(
("profile_id" = Option<String>, Query, description = "The unique identifier for a merchant profile"),
),
responses(
(status = 200, description = "Successfully retrieved active config", body = LinkedRoutingConfigRetrieveResponse),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 403, description = "Forbidden")
),
tag = "Routing",
operation_id = "Retrieve active config",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_retrieve_linked_config() {}
#[cfg(feature = "v1")]
/// Routing - Retrieve Default For Profile
///
/// Retrieve default config for profiles
#[utoipa::path(
get,
path = "/routing/default/profile",
responses(
(status = 200, description = "Successfully retrieved default config", body = ProfileDefaultRoutingConfig),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing")
),
tag = "Routing",
operation_id = "Retrieve default configs for all profiles",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_retrieve_default_config_for_profiles() {}
#[cfg(feature = "v1")]
/// Routing - Update Default For Profile
///
/// Update default config for profiles
#[utoipa::path(
post,
path = "/routing/default/profile/{profile_id}",
request_body = Vec<RoutableConnectorChoice>,
params(
("profile_id" = String, Path, description = "The unique identifier for a profile"),
),
responses(
(status = 200, description = "Successfully updated default config for profile", body = ProfileDefaultRoutingConfig),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 400, description = "Malformed request"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Update default configs for all profiles",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn routing_update_default_config_for_profile() {}
#[cfg(feature = "v1")]
/// Routing - Toggle success based dynamic routing for profile
///
/// Create a success based dynamic routing algorithm
#[utoipa::path(
post,
path = "/account/{account_id}/business_profile/{profile_id}/dynamic_routing/success_based/toggle",
params(
("account_id" = String, Path, description = "Merchant id"),
("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"),
("enable" = DynamicRoutingFeatures, Query, description = "Feature to enable for success based routing"),
),
responses(
(status = 200, description = "Routing Algorithm created", body = RoutingDictionaryRecord),
(status = 400, description = "Request body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Toggle success based dynamic routing algorithm",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn toggle_success_based_routing() {}
#[cfg(feature = "v1")]
/// Routing - Update success based dynamic routing config for profile
///
/// Update success based dynamic routing algorithm
#[utoipa::path(
patch,
path = "/account/{account_id}/business_profile/{profile_id}/dynamic_routing/success_based/config/{algorithm_id}",
params(
("account_id" = String, Path, description = "Merchant id"),
("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"),
("algorithm_id" = String, Path, description = "Success based routing algorithm id which was last activated to update the config"),
),
request_body = SuccessBasedRoutingConfig,
responses(
(status = 200, description = "Routing Algorithm updated", body = RoutingDictionaryRecord),
(status = 400, description = "Update body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Update success based dynamic routing configs",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn success_based_routing_update_configs() {}
#[cfg(feature = "v1")]
/// Routing - Toggle elimination routing for profile
///
/// Create a elimination based dynamic routing algorithm
#[utoipa::path(
post,
path = "/account/{account_id}/business_profile/{profile_id}/dynamic_routing/elimination/toggle",
params(
("account_id" = String, Path, description = "Merchant id"),
("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"),
("enable" = DynamicRoutingFeatures, Query, description = "Feature to enable for elimination based routing"),
),
responses(
(status = 200, description = "Routing Algorithm created", body = RoutingDictionaryRecord),
(status = 400, description = "Request body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Toggle elimination routing algorithm",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn toggle_elimination_routing() {}
#[cfg(feature = "v1")]
/// Routing - Toggle Contract routing for profile
///
/// Create a Contract based dynamic routing algorithm
#[utoipa::path(
post,
path = "/account/{account_id}/business_profile/{profile_id}/dynamic_routing/contracts/toggle",
params(
("account_id" = String, Path, description = "Merchant id"),
("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"),
("enable" = DynamicRoutingFeatures, Query, description = "Feature to enable for contract based routing"),
),
request_body = ContractBasedRoutingConfig,
responses(
(status = 200, description = "Routing Algorithm created", body = RoutingDictionaryRecord),
(status = 400, description = "Request body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Toggle contract routing algorithm",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn contract_based_routing_setup_config() {}
#[cfg(feature = "v1")]
/// Routing - Update contract based dynamic routing config for profile
///
/// Update contract based dynamic routing algorithm
#[utoipa::path(
patch,
path = "/account/{account_id}/business_profile/{profile_id}/dynamic_routing/contracts/config/{algorithm_id}",
params(
("account_id" = String, Path, description = "Merchant id"),
("profile_id" = String, Path, description = "Profile id under which Dynamic routing needs to be toggled"),
("algorithm_id" = String, Path, description = "Contract based routing algorithm id which was last activated to update the config"),
),
request_body = ContractBasedRoutingConfig,
responses(
(status = 200, description = "Routing Algorithm updated", body = RoutingDictionaryRecord),
(status = 400, description = "Update body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Update contract based dynamic routing configs",
security(("api_key" = []), ("jwt_key" = []))
)]
pub async fn contract_based_routing_update_configs() {}
#[cfg(feature = "v1")]
/// Routing - Evaluate
///
/// Evaluate routing rules
#[utoipa::path(
post,
path = "/routing/evaluate",
request_body = OpenRouterDecideGatewayRequest,
responses(
(status = 200, description = "Routing rules evaluated successfully", body = DecideGatewayResponse),
(status = 400, description = "Request body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Evaluate routing rules",
security(("api_key" = []))
)]
pub async fn call_decide_gateway_open_router() {}
#[cfg(feature = "v1")]
/// Routing - Feedback
///
/// Update gateway scores for dynamic routing
#[utoipa::path(
post,
path = "/routing/feedback",
request_body = UpdateScorePayload,
responses(
(status = 200, description = "Gateway score updated successfully", body = UpdateScoreResponse),
(status = 400, description = "Request body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Update gateway scores",
security(("api_key" = []))
)]
pub async fn call_update_gateway_score_open_router() {}
#[cfg(feature = "v1")]
/// Routing - Rule Evaluate
///
/// Evaluate routing rules
#[utoipa::path(
post,
path = "/routing/rule/evaluate",
request_body = RoutingEvaluateRequest,
responses(
(status = 200, description = "Routing rules evaluated successfully", body = RoutingEvaluateResponse),
(status = 400, description = "Request body is malformed"),
(status = 500, description = "Internal server error"),
(status = 404, description = "Resource missing"),
(status = 422, description = "Unprocessable request"),
(status = 403, description = "Forbidden"),
),
tag = "Routing",
operation_id = "Evaluate routing rules (alternative)",
security(("api_key" = []))
)]
pub async fn evaluate_routing_rule() {}
| crates/openapi/src/routes/routing.rs | openapi::src::routes::routing | 4,203 | true |
// File: crates/openapi/src/routes/mandates.rs
// Module: openapi::src::routes::mandates
/// Mandates - Retrieve Mandate
///
/// Retrieves a mandate created using the Payments/Create API
#[utoipa::path(
get,
path = "/mandates/{mandate_id}",
params(
("mandate_id" = String, Path, description = "The identifier for mandate")
),
responses(
(status = 200, description = "The mandate was retrieved successfully", body = MandateResponse),
(status = 404, description = "Mandate does not exist in our records")
),
tag = "Mandates",
operation_id = "Retrieve a Mandate",
security(("api_key" = []))
)]
pub async fn get_mandate() {}
/// Mandates - Revoke Mandate
///
/// Revokes a mandate created using the Payments/Create API
#[utoipa::path(
post,
path = "/mandates/revoke/{mandate_id}",
params(
("mandate_id" = String, Path, description = "The identifier for a mandate")
),
responses(
(status = 200, description = "The mandate was revoked successfully", body = MandateRevokedResponse),
(status = 400, description = "Mandate does not exist in our records")
),
tag = "Mandates",
operation_id = "Revoke a Mandate",
security(("api_key" = []))
)]
pub async fn revoke_mandate() {}
/// Mandates - List Mandates
#[utoipa::path(
get,
path = "/mandates/list",
params(
("limit" = Option<i64>, Query, description = "The maximum number of Mandate Objects to include in the response"),
("mandate_status" = Option<MandateStatus>, Query, description = "The status of mandate"),
("connector" = Option<String>, Query, description = "The connector linked to mandate"),
("created_time" = Option<PrimitiveDateTime>, Query, description = "The time at which mandate is created"),
("created_time.lt" = Option<PrimitiveDateTime>, Query, description = "Time less than the mandate created time"),
("created_time.gt" = Option<PrimitiveDateTime>, Query, description = "Time greater than the mandate created time"),
("created_time.lte" = Option<PrimitiveDateTime>, Query, description = "Time less than or equals to the mandate created time"),
("created_time.gte" = Option<PrimitiveDateTime>, Query, description = "Time greater than or equals to the mandate created time"),
),
responses(
(status = 200, description = "The mandate list was retrieved successfully", body = Vec<MandateResponse>),
(status = 401, description = "Unauthorized request")
),
tag = "Mandates",
operation_id = "List Mandates",
security(("api_key" = []))
)]
pub async fn retrieve_mandates_list() {}
/// Mandates - Customer Mandates List
///
/// Lists all the mandates for a particular customer id.
#[utoipa::path(
get,
path = "/customers/{customer_id}/mandates",
params(
("customer_id" = String, Path, description = "The unique identifier for the customer")
),
responses(
(status = 200, description = "List of retrieved mandates for a customer", body = Vec<MandateResponse>),
(status = 400, description = "Invalid Data"),
),
tag = "Mandates",
operation_id = "List Mandates for a Customer",
security(("api_key" = []))
)]
pub async fn customers_mandates_list() {}
| crates/openapi/src/routes/mandates.rs | openapi::src::routes::mandates | 811 | true |
// File: crates/openapi/src/routes/three_ds_decision_rule.rs
// Module: openapi::src::routes::three_ds_decision_rule
/// 3DS Decision - Execute
#[utoipa::path(
post,
path = "/three_ds_decision/execute",
request_body = ThreeDsDecisionRuleExecuteRequest,
responses(
(status = 200, description = "3DS Decision Rule Executed Successfully", body = ThreeDsDecisionRuleExecuteResponse),
(status = 400, description = "Bad Request")
),
tag = "3DS Decision Rule",
operation_id = "Execute 3DS Decision Rule",
security(("api_key" = []))
)]
pub fn three_ds_decision_rule_execute() {}
| crates/openapi/src/routes/three_ds_decision_rule.rs | openapi::src::routes::three_ds_decision_rule | 157 | true |
// File: crates/openapi/src/routes/platform.rs
// Module: openapi::src::routes::platform
#[cfg(feature = "v1")]
/// Platform - Create
///
/// Create a new platform account
#[utoipa::path(
post,
path = "/user/create_platform",
request_body(
content = PlatformAccountCreateRequest,
description = "Create a platform account with organization_name",
examples(
(
"Create a platform account with organization_name" = (
value = json!({"organization_name": "organization_abc"})
)
)
)
),
responses(
(
status = 200,
description = "Platform Account Created",
body = PlatformAccountCreateResponse,
examples(
(
"Successful Platform Account Creation" = (
description = "Return values for a successfully created platform account",
value = json!({
"org_id": "org_abc",
"org_name": "organization_abc",
"org_type": "platform",
"merchant_id": "merchant_abc",
"merchant_account_type": "platform"
})
)
)
)
),
(status = 400, description = "Invalid data")
),
tag = "Platform",
operation_id = "Create a Platform Account",
security(("jwt_key" = []))
)]
pub async fn create_platform_account() {}
| crates/openapi/src/routes/platform.rs | openapi::src::routes::platform | 294 | true |
// File: crates/openapi/src/routes/webhook_events.rs
// Module: openapi::src::routes::webhook_events
/// Events - List
///
/// List all Events associated with a Merchant Account or Profile.
#[utoipa::path(
post,
path = "/events/{merchant_id}",
params(
(
"merchant_id" = String,
Path,
description = "The unique identifier for the Merchant Account."
),
),
request_body(
content = EventListConstraints,
description = "The constraints that can be applied when listing Events.",
examples (
("example" = (
value = json!({
"created_after": "2023-01-01T00:00:00",
"created_before": "2023-01-31T23:59:59",
"limit": 5,
"offset": 0,
"object_id": "{{object_id}}",
"profile_id": "{{profile_id}}",
"event_classes": ["payments", "refunds"],
"event_types": ["payment_succeeded"],
"is_delivered": true
})
)),
)
),
responses(
(status = 200, description = "List of Events retrieved successfully", body = TotalEventsResponse),
),
tag = "Event",
operation_id = "List all Events associated with a Merchant Account or Profile",
security(("admin_api_key" = []))
)]
pub fn list_initial_webhook_delivery_attempts() {}
/// Events - List
///
/// List all Events associated with a Profile.
#[utoipa::path(
post,
path = "/events/profile/list",
request_body(
content = EventListConstraints,
description = "The constraints that can be applied when listing Events.",
examples (
("example" = (
value = json!({
"created_after": "2023-01-01T00:00:00",
"created_before": "2023-01-31T23:59:59",
"limit": 5,
"offset": 0,
"object_id": "{{object_id}}",
"profile_id": "{{profile_id}}",
"event_classes": ["payments", "refunds"],
"event_types": ["payment_succeeded"],
"is_delivered": true
})
)),
)
),
responses(
(status = 200, description = "List of Events retrieved successfully", body = TotalEventsResponse),
),
tag = "Event",
operation_id = "List all Events associated with a Profile",
security(("jwt_key" = []))
)]
pub fn list_initial_webhook_delivery_attempts_with_jwtauth() {}
/// Events - Delivery Attempt List
///
/// List all delivery attempts for the specified Event.
#[utoipa::path(
get,
path = "/events/{merchant_id}/{event_id}/attempts",
params(
("merchant_id" = String, Path, description = "The unique identifier for the Merchant Account."),
("event_id" = String, Path, description = "The unique identifier for the Event"),
),
responses(
(status = 200, description = "List of delivery attempts retrieved successfully", body = Vec<EventRetrieveResponse>),
),
tag = "Event",
operation_id = "List all delivery attempts for an Event",
security(("admin_api_key" = []))
)]
pub fn list_webhook_delivery_attempts() {}
/// Events - Manual Retry
///
/// Manually retry the delivery of the specified Event.
#[utoipa::path(
post,
path = "/events/{merchant_id}/{event_id}/retry",
params(
("merchant_id" = String, Path, description = "The unique identifier for the Merchant Account."),
("event_id" = String, Path, description = "The unique identifier for the Event"),
),
responses(
(
status = 200,
description = "The delivery of the Event was attempted. \
Check the `response` field in the response payload to identify the status of the delivery attempt.",
body = EventRetrieveResponse
),
),
tag = "Event",
operation_id = "Manually retry the delivery of an Event",
security(("admin_api_key" = []))
)]
pub fn retry_webhook_delivery_attempt() {}
| crates/openapi/src/routes/webhook_events.rs | openapi::src::routes::webhook_events | 943 | true |
// File: crates/openapi/src/routes/relay.rs
// Module: openapi::src::routes::relay
/// Relay - Create
///
/// Creates a relay request.
#[utoipa::path(
post,
path = "/relay",
request_body(
content = RelayRequest,
examples((
"Create a relay request" = (
value = json!({
"connector_resource_id": "7256228702616471803954",
"connector_id": "mca_5apGeP94tMts6rg3U3kR",
"type": "refund",
"data": {
"refund": {
"amount": 6540,
"currency": "USD"
}
}
})
)
))
),
responses(
(status = 200, description = "Relay request", body = RelayResponse),
(status = 400, description = "Invalid data")
),
params(
("X-Profile-Id" = String, Header, description = "Profile ID for authentication"),
("X-Idempotency-Key" = String, Header, description = "Idempotency Key for relay request")
),
tag = "Relay",
operation_id = "Relay Request",
security(("api_key" = []))
)]
pub async fn relay() {}
/// Relay - Retrieve
///
/// Retrieves a relay details.
#[utoipa::path(
get,
path = "/relay/{relay_id}",
params (("relay_id" = String, Path, description = "The unique identifier for the Relay"), ("X-Profile-Id" = String, Header, description = "Profile ID for authentication")),
responses(
(status = 200, description = "Relay Retrieved", body = RelayResponse),
(status = 404, description = "Relay details was not found")
),
tag = "Relay",
operation_id = "Retrieve a Relay details",
security(("api_key" = []), ("ephemeral_key" = []))
)]
pub async fn relay_retrieve() {}
| crates/openapi/src/routes/relay.rs | openapi::src::routes::relay | 467 | true |
// File: crates/drainer/build.rs
// Module: drainer::build
fn main() {
#[cfg(feature = "vergen")]
router_env::vergen::generate_cargo_instructions();
}
| crates/drainer/build.rs | drainer::build | 43 | true |
// File: crates/drainer/src/stream.rs
// Module: drainer::src::stream
use std::collections::HashMap;
use redis_interface as redis;
use router_env::{logger, tracing};
use crate::{errors, metrics, Store};
pub type StreamEntries = Vec<(String, HashMap<String, String>)>;
pub type StreamReadResult = HashMap<String, StreamEntries>;
impl Store {
#[inline(always)]
pub fn drainer_stream(&self, shard_key: &str) -> String {
// Example: {shard_5}_drainer_stream
format!("{{{}}}_{}", shard_key, self.config.drainer_stream_name,)
}
#[inline(always)]
pub(crate) fn get_stream_key_flag(&self, stream_index: u8) -> String {
format!("{}_in_use", self.get_drainer_stream_name(stream_index))
}
#[inline(always)]
pub(crate) fn get_drainer_stream_name(&self, stream_index: u8) -> String {
self.drainer_stream(format!("shard_{stream_index}").as_str())
}
#[router_env::instrument(skip_all)]
pub async fn is_stream_available(&self, stream_index: u8) -> bool {
let stream_key_flag = self.get_stream_key_flag(stream_index);
match self
.redis_conn
.set_key_if_not_exists_with_expiry(&stream_key_flag.as_str().into(), true, None)
.await
{
Ok(resp) => resp == redis::types::SetnxReply::KeySet,
Err(error) => {
logger::error!(operation="lock_stream",err=?error);
false
}
}
}
pub async fn make_stream_available(&self, stream_name_flag: &str) -> errors::DrainerResult<()> {
match self.redis_conn.delete_key(&stream_name_flag.into()).await {
Ok(redis::DelReply::KeyDeleted) => Ok(()),
Ok(redis::DelReply::KeyNotDeleted) => {
logger::error!("Tried to unlock a stream which is already unlocked");
Ok(())
}
Err(error) => Err(errors::DrainerError::from(error).into()),
}
}
pub async fn read_from_stream(
&self,
stream_name: &str,
max_read_count: u64,
) -> errors::DrainerResult<StreamReadResult> {
// "0-0" id gives first entry
let stream_id = "0-0";
let (output, execution_time) = common_utils::date_time::time_it(|| async {
self.redis_conn
.stream_read_entries(stream_name, stream_id, Some(max_read_count))
.await
.map_err(errors::DrainerError::from)
})
.await;
metrics::REDIS_STREAM_READ_TIME.record(
execution_time,
router_env::metric_attributes!(("stream", stream_name.to_owned())),
);
Ok(output?)
}
pub async fn trim_from_stream(
&self,
stream_name: &str,
minimum_entry_id: &str,
) -> errors::DrainerResult<usize> {
let trim_kind = redis::StreamCapKind::MinID;
let trim_type = redis::StreamCapTrim::Exact;
let trim_id = minimum_entry_id;
let (trim_result, execution_time) =
common_utils::date_time::time_it::<errors::DrainerResult<_>, _, _>(|| async {
let trim_result = self
.redis_conn
.stream_trim_entries(&stream_name.into(), (trim_kind, trim_type, trim_id))
.await
.map_err(errors::DrainerError::from)?;
// Since xtrim deletes entries below given id excluding the given id.
// Hence, deleting the minimum entry id
self.redis_conn
.stream_delete_entries(&stream_name.into(), minimum_entry_id)
.await
.map_err(errors::DrainerError::from)?;
Ok(trim_result)
})
.await;
metrics::REDIS_STREAM_TRIM_TIME.record(
execution_time,
router_env::metric_attributes!(("stream", stream_name.to_owned())),
);
// adding 1 because we are deleting the given id too
Ok(trim_result? + 1)
}
pub async fn delete_from_stream(
&self,
stream_name: &str,
entry_id: &str,
) -> errors::DrainerResult<()> {
let (_trim_result, execution_time) =
common_utils::date_time::time_it::<errors::DrainerResult<_>, _, _>(|| async {
self.redis_conn
.stream_delete_entries(&stream_name.into(), entry_id)
.await
.map_err(errors::DrainerError::from)?;
Ok(())
})
.await;
metrics::REDIS_STREAM_DEL_TIME.record(
execution_time,
router_env::metric_attributes!(("stream", stream_name.to_owned())),
);
Ok(())
}
}
| crates/drainer/src/stream.rs | drainer::src::stream | 1,054 | true |
// File: crates/drainer/src/logger.rs
// Module: drainer::src::logger
#[doc(inline)]
pub use router_env::{debug, error, info, warn};
| crates/drainer/src/logger.rs | drainer::src::logger | 38 | true |
// File: crates/drainer/src/types.rs
// Module: drainer::src::types
use std::collections::HashMap;
use common_utils::errors;
use error_stack::ResultExt;
use serde::{de::value::MapDeserializer, Deserialize, Serialize};
use crate::{
kv,
utils::{deserialize_db_op, deserialize_i64},
};
#[derive(Deserialize, Serialize)]
pub struct StreamData {
pub request_id: String,
pub global_id: String,
#[serde(deserialize_with = "deserialize_db_op")]
pub typed_sql: kv::DBOperation,
#[serde(deserialize_with = "deserialize_i64")]
pub pushed_at: i64,
}
impl StreamData {
pub fn from_hashmap(
hashmap: HashMap<String, String>,
) -> errors::CustomResult<Self, errors::ParsingError> {
let iter = MapDeserializer::<
'_,
std::collections::hash_map::IntoIter<String, String>,
serde_json::error::Error,
>::new(hashmap.into_iter());
Self::deserialize(iter)
.change_context(errors::ParsingError::StructParseFailure("StreamData"))
}
}
| crates/drainer/src/types.rs | drainer::src::types | 244 | true |
// File: crates/drainer/src/handler.rs
// Module: drainer::src::handler
use std::{
collections::HashMap,
sync::{atomic, Arc},
};
use common_utils::id_type;
use router_env::tracing::Instrument;
use tokio::{
sync::{mpsc, oneshot},
time::{self, Duration},
};
use crate::{
errors, instrument, logger, metrics, query::ExecuteQuery, tracing, utils, DrainerSettings,
Store, StreamData,
};
/// Handler handles the spawning and closing of drainer
/// Arc is used to enable creating a listener for graceful shutdown
#[derive(Clone)]
pub struct Handler {
inner: Arc<HandlerInner>,
}
impl std::ops::Deref for Handler {
type Target = HandlerInner;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
pub struct HandlerInner {
shutdown_interval: Duration,
loop_interval: Duration,
active_tasks: Arc<atomic::AtomicU64>,
conf: DrainerSettings,
stores: HashMap<id_type::TenantId, Arc<Store>>,
running: Arc<atomic::AtomicBool>,
}
impl Handler {
pub fn from_conf(
conf: DrainerSettings,
stores: HashMap<id_type::TenantId, Arc<Store>>,
) -> Self {
let shutdown_interval = Duration::from_millis(conf.shutdown_interval.into());
let loop_interval = Duration::from_millis(conf.loop_interval.into());
let active_tasks = Arc::new(atomic::AtomicU64::new(0));
let running = Arc::new(atomic::AtomicBool::new(true));
let handler = HandlerInner {
shutdown_interval,
loop_interval,
active_tasks,
conf,
stores,
running,
};
Self {
inner: Arc::new(handler),
}
}
pub fn close(&self) {
self.running.store(false, atomic::Ordering::SeqCst);
}
pub async fn spawn(&self) -> errors::DrainerResult<()> {
let mut stream_index: u8 = 0;
let jobs_picked = Arc::new(atomic::AtomicU8::new(0));
while self.running.load(atomic::Ordering::SeqCst) {
metrics::DRAINER_HEALTH.add(1, &[]);
for store in self.stores.values() {
if store.is_stream_available(stream_index).await {
let _task_handle = tokio::spawn(
drainer_handler(
store.clone(),
stream_index,
self.conf.max_read_count,
self.active_tasks.clone(),
jobs_picked.clone(),
)
.in_current_span(),
);
}
}
stream_index = utils::increment_stream_index(
(stream_index, jobs_picked.clone()),
self.conf.num_partitions,
)
.await;
time::sleep(self.loop_interval).await;
}
Ok(())
}
pub(crate) async fn shutdown_listener(&self, mut rx: mpsc::Receiver<()>) {
while let Some(_c) = rx.recv().await {
logger::info!("Awaiting shutdown!");
metrics::SHUTDOWN_SIGNAL_RECEIVED.add(1, &[]);
let shutdown_started = time::Instant::now();
rx.close();
//Check until the active tasks are zero. This does not include the tasks in the stream.
while self.active_tasks.load(atomic::Ordering::SeqCst) != 0 {
time::sleep(self.shutdown_interval).await;
}
logger::info!("Terminating drainer");
metrics::SUCCESSFUL_SHUTDOWN.add(1, &[]);
let shutdown_ended = shutdown_started.elapsed().as_secs_f64() * 1000f64;
metrics::CLEANUP_TIME.record(shutdown_ended, &[]);
self.close();
}
logger::info!(
tasks_remaining = self.active_tasks.load(atomic::Ordering::SeqCst),
"Drainer shutdown successfully"
)
}
pub fn spawn_error_handlers(&self, tx: mpsc::Sender<()>) -> errors::DrainerResult<()> {
let (redis_error_tx, redis_error_rx) = oneshot::channel();
let redis_conn_clone = self
.stores
.values()
.next()
.map(|store| store.redis_conn.clone());
match redis_conn_clone {
None => {
logger::error!("No redis connection found");
Err(
errors::DrainerError::UnexpectedError("No redis connection found".to_string())
.into(),
)
}
Some(redis_conn_clone) => {
// Spawn a task to monitor if redis is down or not
let _task_handle = tokio::spawn(
async move { redis_conn_clone.on_error(redis_error_tx).await }
.in_current_span(),
);
//Spawns a task to send shutdown signal if redis goes down
let _task_handle =
tokio::spawn(redis_error_receiver(redis_error_rx, tx).in_current_span());
Ok(())
}
}
}
}
pub async fn redis_error_receiver(rx: oneshot::Receiver<()>, shutdown_channel: mpsc::Sender<()>) {
match rx.await {
Ok(_) => {
logger::error!("The redis server failed");
let _ = shutdown_channel.send(()).await.map_err(|err| {
logger::error!("Failed to send signal to the shutdown channel {err}")
});
}
Err(err) => {
logger::error!("Channel receiver error {err}");
}
}
}
#[router_env::instrument(skip_all)]
async fn drainer_handler(
store: Arc<Store>,
stream_index: u8,
max_read_count: u64,
active_tasks: Arc<atomic::AtomicU64>,
jobs_picked: Arc<atomic::AtomicU8>,
) -> errors::DrainerResult<()> {
active_tasks.fetch_add(1, atomic::Ordering::Release);
let stream_name = store.get_drainer_stream_name(stream_index);
let drainer_result = Box::pin(drainer(
store.clone(),
max_read_count,
stream_name.as_str(),
jobs_picked,
))
.await;
if let Err(error) = drainer_result {
logger::error!(?error)
}
let flag_stream_name = store.get_stream_key_flag(stream_index);
let output = store.make_stream_available(flag_stream_name.as_str()).await;
active_tasks.fetch_sub(1, atomic::Ordering::Release);
output.inspect_err(|err| logger::error!(operation = "unlock_stream", err=?err))
}
#[instrument(skip_all, fields(global_id, request_id, session_id))]
async fn drainer(
store: Arc<Store>,
max_read_count: u64,
stream_name: &str,
jobs_picked: Arc<atomic::AtomicU8>,
) -> errors::DrainerResult<()> {
let stream_read = match store.read_from_stream(stream_name, max_read_count).await {
Ok(result) => {
jobs_picked.fetch_add(1, atomic::Ordering::SeqCst);
result
}
Err(error) => {
if let errors::DrainerError::RedisError(redis_err) = error.current_context() {
if let redis_interface::errors::RedisError::StreamEmptyOrNotAvailable =
redis_err.current_context()
{
metrics::STREAM_EMPTY.add(1, &[]);
return Ok(());
} else {
return Err(error);
}
} else {
return Err(error);
}
}
};
// parse_stream_entries returns error if no entries is found, handle it
let entries = utils::parse_stream_entries(
&stream_read,
store.redis_conn.add_prefix(stream_name).as_str(),
)?;
let read_count = entries.len();
metrics::JOBS_PICKED_PER_STREAM.add(
u64::try_from(read_count).unwrap_or(u64::MIN),
router_env::metric_attributes!(("stream", stream_name.to_owned())),
);
let session_id = common_utils::generate_id_with_default_len("drainer_session");
let mut last_processed_id = String::new();
for (entry_id, entry) in entries.clone() {
let data = match StreamData::from_hashmap(entry) {
Ok(data) => data,
Err(err) => {
logger::error!(operation = "deserialization", err=?err);
metrics::STREAM_PARSE_FAIL.add(
1,
router_env::metric_attributes!(("operation", "deserialization")),
);
// break from the loop in case of a deser error
break;
}
};
tracing::Span::current().record("request_id", data.request_id);
tracing::Span::current().record("global_id", data.global_id);
tracing::Span::current().record("session_id", &session_id);
match data.typed_sql.execute_query(&store, data.pushed_at).await {
Ok(_) => {
last_processed_id = entry_id;
}
Err(err) => match err.current_context() {
// In case of Uniqueviolation we can't really do anything to fix it so just clear
// it from the stream
diesel_models::errors::DatabaseError::UniqueViolation => {
last_processed_id = entry_id;
}
// break from the loop in case of an error in query
_ => break,
},
}
if store.use_legacy_version() {
store
.delete_from_stream(stream_name, &last_processed_id)
.await?;
}
}
if !(last_processed_id.is_empty() || store.use_legacy_version()) {
let entries_trimmed = store
.trim_from_stream(stream_name, &last_processed_id)
.await?;
if read_count != entries_trimmed {
logger::error!(
read_entries = %read_count,
trimmed_entries = %entries_trimmed,
?entries,
"Assertion Failed no. of entries read from the stream doesn't match no. of entries trimmed"
);
}
} else {
logger::error!(read_entries = %read_count,?entries,"No streams were processed in this session");
}
Ok(())
}
| crates/drainer/src/handler.rs | drainer::src::handler | 2,184 | true |
// File: crates/drainer/src/lib.rs
// Module: drainer::src::lib
mod connection;
pub mod errors;
mod handler;
mod health_check;
pub mod logger;
pub(crate) mod metrics;
mod query;
pub mod services;
pub mod settings;
mod stream;
mod types;
mod utils;
use std::{collections::HashMap, sync::Arc};
mod secrets_transformers;
use actix_web::dev::Server;
use common_utils::{id_type, signals::get_allowed_signals};
use diesel_models::kv;
use error_stack::ResultExt;
use hyperswitch_interfaces::secrets_interface::secret_state::RawSecret;
use router_env::{
instrument,
tracing::{self, Instrument},
};
use tokio::sync::mpsc;
pub(crate) type Settings = settings::Settings<RawSecret>;
use crate::{
connection::pg_connection, services::Store, settings::DrainerSettings, types::StreamData,
};
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(())
}
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)
}
| crates/drainer/src/lib.rs | drainer::src::lib | 533 | true |
// File: crates/drainer/src/query.rs
// Module: drainer::src::query
use std::sync::Arc;
use common_utils::errors::CustomResult;
use diesel_models::errors::DatabaseError;
use crate::{kv, logger, metrics, pg_connection, services::Store};
#[async_trait::async_trait]
pub trait ExecuteQuery {
async fn execute_query(
self,
store: &Arc<Store>,
pushed_at: i64,
) -> CustomResult<(), DatabaseError>;
}
#[async_trait::async_trait]
impl ExecuteQuery for kv::DBOperation {
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)
}
}
}
}
#[inline(always)]
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"
),
}
}
| crates/drainer/src/query.rs | drainer::src::query | 509 | true |
// File: crates/drainer/src/services.rs
// Module: drainer::src::services
use std::sync::Arc;
use actix_web::{body, HttpResponse, ResponseError};
use error_stack::Report;
use redis_interface::RedisConnectionPool;
use crate::{
connection::{diesel_make_pg_pool, PgPool},
logger,
settings::Tenant,
};
#[derive(Clone)]
pub struct Store {
pub master_pool: PgPool,
pub redis_conn: Arc<RedisConnectionPool>,
pub config: StoreConfig,
pub request_id: Option<String>,
}
#[derive(Clone)]
pub struct StoreConfig {
pub drainer_stream_name: String,
pub drainer_num_partitions: u8,
pub use_legacy_version: bool,
}
impl 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,
}
}
pub fn use_legacy_version(&self) -> bool {
self.config.use_legacy_version
}
}
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)
}
pub fn http_response_json<T: body::MessageBody + 'static>(response: T) -> HttpResponse {
HttpResponse::Ok()
.content_type(mime::APPLICATION_JSON)
.body(response)
}
| crates/drainer/src/services.rs | drainer::src::services | 524 | true |
// File: crates/drainer/src/metrics.rs
// Module: drainer::src::metrics
use router_env::{counter_metric, global_meter, histogram_metric_f64, histogram_metric_u64};
global_meter!(DRAINER_METER, "DRAINER");
counter_metric!(JOBS_PICKED_PER_STREAM, DRAINER_METER);
counter_metric!(CYCLES_COMPLETED_SUCCESSFULLY, DRAINER_METER);
counter_metric!(CYCLES_COMPLETED_UNSUCCESSFULLY, DRAINER_METER);
counter_metric!(ERRORS_WHILE_QUERY_EXECUTION, DRAINER_METER);
counter_metric!(SUCCESSFUL_QUERY_EXECUTION, DRAINER_METER);
counter_metric!(SHUTDOWN_SIGNAL_RECEIVED, DRAINER_METER);
counter_metric!(SUCCESSFUL_SHUTDOWN, DRAINER_METER);
counter_metric!(STREAM_EMPTY, DRAINER_METER);
counter_metric!(STREAM_PARSE_FAIL, DRAINER_METER);
counter_metric!(DRAINER_HEALTH, DRAINER_METER);
histogram_metric_f64!(QUERY_EXECUTION_TIME, DRAINER_METER); // Time in (ms) milliseconds
histogram_metric_f64!(REDIS_STREAM_READ_TIME, DRAINER_METER); // Time in (ms) milliseconds
histogram_metric_f64!(REDIS_STREAM_TRIM_TIME, DRAINER_METER); // Time in (ms) milliseconds
histogram_metric_f64!(CLEANUP_TIME, DRAINER_METER); // Time in (ms) milliseconds
histogram_metric_u64!(DRAINER_DELAY_SECONDS, DRAINER_METER); // Time in (s) seconds
histogram_metric_f64!(REDIS_STREAM_DEL_TIME, DRAINER_METER); // Time in (ms) milliseconds
| crates/drainer/src/metrics.rs | drainer::src::metrics | 365 | true |
// File: crates/drainer/src/errors.rs
// Module: drainer::src::errors
use redis_interface as redis;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum DrainerError {
#[error("Error in parsing config : {0}")]
ConfigParsingError(String),
#[error("Error during redis operation : {0:?}")]
RedisError(error_stack::Report<redis::errors::RedisError>),
#[error("Application configuration error: {0}")]
ConfigurationError(config::ConfigError),
#[error("Error while configuring signals: {0}")]
SignalError(String),
#[error("Error while parsing data from the stream: {0:?}")]
ParsingError(error_stack::Report<common_utils::errors::ParsingError>),
#[error("Unexpected error occurred: {0}")]
UnexpectedError(String),
#[error("I/O: {0}")]
IoError(std::io::Error),
}
#[derive(Debug, Error, Clone, serde::Serialize)]
pub enum HealthCheckError {
#[error("Database health check is failing with error: {message}")]
DbError { message: String },
#[error("Redis health check is failing with error: {message}")]
RedisError { message: String },
}
impl From<std::io::Error> for DrainerError {
fn from(err: std::io::Error) -> Self {
Self::IoError(err)
}
}
pub type DrainerResult<T> = error_stack::Result<T, DrainerError>;
impl From<config::ConfigError> for DrainerError {
fn from(err: config::ConfigError) -> Self {
Self::ConfigurationError(err)
}
}
impl From<error_stack::Report<redis::errors::RedisError>> for DrainerError {
fn from(err: error_stack::Report<redis::errors::RedisError>) -> Self {
Self::RedisError(err)
}
}
impl actix_web::ResponseError for HealthCheckError {
fn status_code(&self) -> reqwest::StatusCode {
use reqwest::StatusCode;
match self {
Self::DbError { .. } | Self::RedisError { .. } => StatusCode::INTERNAL_SERVER_ERROR,
}
}
}
| crates/drainer/src/errors.rs | drainer::src::errors | 466 | true |
// File: crates/drainer/src/main.rs
// Module: drainer::src::main
use std::collections::HashMap;
use drainer::{errors::DrainerResult, logger, services, settings, start_drainer, start_web_server};
use router_env::tracing::Instrument;
#[tokio::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(())
}
| crates/drainer/src/main.rs | drainer::src::main | 460 | true |
// File: crates/drainer/src/health_check.rs
// Module: drainer::src::health_check
use std::{collections::HashMap, sync::Arc};
use actix_web::{web, Scope};
use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl};
use common_utils::{errors::CustomResult, id_type};
use diesel_models::{Config, ConfigNew};
use error_stack::ResultExt;
use router_env::{instrument, logger, tracing};
use crate::{
connection::pg_connection,
errors::HealthCheckError,
services::{self, log_and_return_error_response, Store},
Settings,
};
pub const TEST_STREAM_NAME: &str = "TEST_STREAM_0";
pub const TEST_STREAM_DATA: &[(&str, &str)] = &[("data", "sample_data")];
pub struct Health;
impl 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)))
}
}
#[instrument(skip_all)]
pub async fn health() -> impl actix_web::Responder {
logger::info!("Drainer health was called");
actix_web::HttpResponse::Ok().body("Drainer health is good")
}
#[instrument(skip_all)]
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(),
)
}
#[instrument(skip_all)]
pub async fn deep_health_check_func(
conf: web::Data<Settings>,
store: &Arc<Store>,
) -> Result<DrainerHealthCheckResponse, error_stack::Report<HealthCheckError>> {
logger::info!("Deep health check was called");
logger::debug!("Database health check begin");
let db_status = store
.health_check_db()
.await
.map(|_| true)
.map_err(|error| {
let message = error.to_string();
error.change_context(HealthCheckError::DbError { message })
})?;
logger::debug!("Database health check end");
logger::debug!("Redis health check begin");
let redis_status = store
.health_check_redis(&conf.into_inner())
.await
.map(|_| true)
.map_err(|error| {
let message = error.to_string();
error.change_context(HealthCheckError::RedisError { message })
})?;
logger::debug!("Redis health check end");
Ok(DrainerHealthCheckResponse {
database: db_status,
redis: redis_status,
})
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DrainerHealthCheckResponse {
pub database: bool,
pub redis: bool,
}
#[async_trait::async_trait]
pub trait HealthCheckInterface {
async fn health_check_db(&self) -> CustomResult<(), HealthCheckDBError>;
async fn health_check_redis(&self, conf: &Settings) -> CustomResult<(), HealthCheckRedisError>;
}
#[async_trait::async_trait]
impl HealthCheckInterface for Store {
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(())
}
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(())
}
}
#[allow(clippy::enum_variant_names)]
#[derive(Debug, thiserror::Error)]
pub enum HealthCheckDBError {
#[error("Error while connecting to database")]
DbError,
#[error("Error while writing to database")]
DbWriteError,
#[error("Error while reading element in the database")]
DbReadError,
#[error("Error while deleting element in the database")]
DbDeleteError,
#[error("Unpredictable error occurred")]
UnknownError,
#[error("Error in database transaction")]
TransactionError,
}
impl From<diesel::result::Error> for HealthCheckDBError {
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,
}
}
}
#[allow(clippy::enum_variant_names)]
#[derive(Debug, thiserror::Error)]
pub enum HealthCheckRedisError {
#[error("Failed to set key value in Redis")]
SetFailed,
#[error("Failed to get key value in Redis")]
GetFailed,
#[error("Failed to delete key value in Redis")]
DeleteFailed,
#[error("Failed to append data to the stream in Redis")]
StreamAppendFailed,
#[error("Failed to read data from the stream in Redis")]
StreamReadFailed,
#[error("Failed to trim data from the stream in Redis")]
StreamTrimFailed,
}
| crates/drainer/src/health_check.rs | drainer::src::health_check | 2,025 | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.