repo stringclasses 4 values | file_path stringlengths 6 193 | extension stringclasses 23 values | content stringlengths 0 1.73M | token_count int64 0 724k | __index_level_0__ int64 0 10.8k |
|---|---|---|---|---|---|
hyperswitch | crates/test_utils/tests/connectors/shift4_ui.rs | .rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct Shift4SeleniumTest;
impl SeleniumTest for Shift4SeleniumTest {
fn get_connector_name(&self) -> String {
"shift4".to_string()
}
}
async fn should_make_3ds_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = Shift4SeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/37"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::ClassName("btn-success"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_giropay_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = Shift4SeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/39"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::ClassName("btn-success"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_ideal_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = Shift4SeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/42"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::ClassName("btn-success"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_sofort_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = Shift4SeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/43"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::ClassName("btn-success"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_eps_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = Shift4SeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/157"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::ClassName("btn-success"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
#[test]
#[serial]
fn should_make_3ds_payment_test() {
tester!(should_make_3ds_payment);
}
#[test]
#[serial]
fn should_make_giropay_payment_test() {
tester!(should_make_giropay_payment);
}
#[test]
#[serial]
fn should_make_ideal_payment_test() {
tester!(should_make_ideal_payment);
}
#[test]
#[serial]
fn should_make_sofort_payment_test() {
tester!(should_make_sofort_payment);
}
#[test]
#[serial]
fn should_make_eps_payment_test() {
tester!(should_make_eps_payment);
}
| 929 | 905 |
hyperswitch | crates/test_utils/tests/connectors/payu_ui.rs | .rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct PayUSeleniumTest;
impl SeleniumTest for PayUSeleniumTest {
fn get_connector_name(&self) -> String {
"payu".to_string()
}
}
async fn should_make_no_3ds_card_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = PayUSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/72"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Sleep(1)),
Event::Assert(Assert::IsPresent("status")),
Event::Assert(Assert::IsPresent("processing")),
],
)
.await?;
Ok(())
}
async fn should_make_gpay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = PayUSeleniumTest {};
conn.make_gpay_payment(web_driver,
&format!("{CHECKOUT_BASE_URL}/gpay?gatewayname=payu&gatewaymerchantid=459551&amount=70.00&country=US¤cy=PLN"),
vec![
Event::Assert(Assert::IsPresent("Status")),
Event::Assert(Assert::IsPresent("processing")),
]).await?;
Ok(())
}
#[test]
#[serial]
fn should_make_no_3ds_card_payment_test() {
tester!(should_make_no_3ds_card_payment);
}
#[test]
#[serial]
#[ignore]
fn should_make_gpay_payment_test() {
tester!(should_make_gpay_payment);
}
| 375 | 906 |
hyperswitch | crates/test_utils/tests/connectors/trustpay_3ds_ui.rs | .rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct TrustpaySeleniumTest;
impl SeleniumTest for TrustpaySeleniumTest {
fn get_connector_name(&self) -> String {
"trustpay_3ds".to_string()
}
}
async fn should_make_trustpay_3ds_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = TrustpaySeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/206"))),
Event::Trigger(Trigger::Sleep(1)),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"button.btn.btn-lg.btn-primary.btn-block",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
#[test]
#[serial]
#[ignore]
fn should_make_trustpay_3ds_payment_test() {
tester!(should_make_trustpay_3ds_payment);
}
| 277 | 907 |
hyperswitch | crates/test_utils/tests/connectors/adyen_uk_ui.rs | .rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct AdyenSeleniumTest;
impl SeleniumTest for AdyenSeleniumTest {
fn get_connector_name(&self) -> String {
"adyen_uk".to_string()
}
}
async fn should_make_adyen_3ds_payment_failed(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/177"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SwitchFrame(By::Name("threeDSIframe"))),
Event::Assert(Assert::IsPresent("AUTHENTICATION DETAILS")),
Event::Trigger(Trigger::SendKeys(By::ClassName("input-field"), "password")),
Event::Trigger(Trigger::Click(By::Id("buttonSubmit"))),
Event::Trigger(Trigger::Sleep(5)),
Event::Assert(Assert::IsPresent("failed")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_3ds_payment_success(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/62"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SwitchFrame(By::Name("threeDSIframe"))),
Event::Assert(Assert::IsPresent("AUTHENTICATION DETAILS")),
Event::Trigger(Trigger::SendKeys(By::ClassName("input-field"), "password")),
Event::Trigger(Trigger::Click(By::Id("buttonSubmit"))),
Event::Trigger(Trigger::Sleep(5)),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_3ds_mandate_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/203"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")), // mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("a.btn"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_3ds_mandate_with_zero_dollar_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/204"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")), // mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("a.btn"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_gpay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_gpay_payment(web_driver,
&format!("{CHECKOUT_BASE_URL}/gpay?gatewayname=adyen&gatewaymerchantid=JuspayDEECOM&amount=70.00&country=US¤cy=USD"),
vec![
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
async fn should_make_adyen_gpay_mandate_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_gpay_payment(web_driver,
&format!("{CHECKOUT_BASE_URL}/gpay?gatewayname=adyen&gatewaymerchantid=JuspayDEECOM&amount=70.00&country=US¤cy=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=7000&mandate_data[mandate_type][multi_use][currency]=USD"),
vec![
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
async fn should_make_adyen_gpay_zero_dollar_mandate_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_gpay_payment(web_driver,
&format!("{CHECKOUT_BASE_URL}/gpay?gatewayname=adyen&gatewaymerchantid=JuspayDEECOM&amount=0.00&country=US¤cy=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD"),
vec![
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
async fn should_make_adyen_klarna_mandate_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/195"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SwitchFrame(By::Id("klarna-apf-iframe"))),
Event::Trigger(Trigger::Sleep(5)),
Event::Trigger(Trigger::Click(By::Id("signInWithBankId"))),
Event::Assert(Assert::IsPresent("Klart att betala")),
Event::EitherOr(
Assert::IsPresent("Klart att betala"),
vec![Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='confirm-and-pay']",
)))],
vec![
Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='SmoothCheckoutPopUp:skip']",
))),
Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='confirm-and-pay']",
))),
],
),
Event::RunIf(
Assert::IsPresent("Färre klick, snabbare betalning"),
vec![Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='SmoothCheckoutPopUp:enable']",
)))],
),
Event::Trigger(Trigger::SwitchTab(Position::Prev)),
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")), // mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_alipay_hk_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/162"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::EitherOr(
Assert::IsPresent("Payment Method Not Available"),
vec![Event::Assert(Assert::IsPresent(
"Please try again or select a different payment method",
))],
vec![
Event::Trigger(Trigger::Click(By::Css("button[value='authorised']"))),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_bizum_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/186"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SendKeys(By::Id("iPhBizInit"), "700000000")),
Event::Trigger(Trigger::Click(By::Id("bBizInit"))),
Event::Trigger(Trigger::Click(By::Css("input.btn.btn-lg.btn-continue"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_clearpay_payment(driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_clearpay_payment(
driver,
&format!("{CHECKOUT_BASE_URL}/saved/163"),
vec![Event::Assert(Assert::IsPresent("succeeded"))],
)
.await?;
Ok(())
}
async fn should_make_adyen_paypal_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_paypal_payment(
web_driver,
&format!("{CHECKOUT_BASE_URL}/saved/202"),
vec![
Event::Trigger(Trigger::Click(By::Id("payment-submit-btn"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=processing"], //final status of this payment method will remain in processing state
)),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_ach_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/58"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_sepa_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/51"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_bacs_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/54"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Status")),
Event::Assert(Assert::IsPresent("processing")), //final status of this payment method will remain in processing state
],
)
.await?;
Ok(())
}
async fn should_make_adyen_ideal_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/52"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::ClassName("btnLink"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_eps_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/61"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("button[value='authorised']"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_bancontact_card_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
let user = &conn
.get_configs()
.automation_configs
.unwrap()
.adyen_bancontact_username
.unwrap();
let pass = &conn
.get_configs()
.automation_configs
.unwrap()
.adyen_bancontact_pass
.unwrap();
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/68"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SendKeys(By::Id("username"), user)),
Event::Trigger(Trigger::SendKeys(By::Id("password"), pass)),
Event::Trigger(Trigger::Click(By::ClassName("button"))),
Event::Trigger(Trigger::Sleep(2)),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_wechatpay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/75"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("button[value='authorised']"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_mbway_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/196"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Status")),
Event::Assert(Assert::IsPresent("processing")), //final status of this payment method will remain in processing state
],
)
.await?;
Ok(())
}
async fn should_make_adyen_ebanking_fi_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/78"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::ClassName("css-ns0tbt"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_onlinebanking_pl_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/197"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Id("user_account_pbl_correct"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded", "status=processing"],
)),
],
)
.await?;
Ok(())
}
#[ignore]
async fn should_make_adyen_giropay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/70"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SendKeys(
By::Css("input[id='tags']"),
"Testbank Fiducia 44448888 GENODETT488",
)),
Event::Trigger(Trigger::Click(By::Css("input[id='tags']"))),
Event::Trigger(Trigger::Sleep(3)),
Event::Trigger(Trigger::Click(By::Id("ui-id-3"))),
Event::Trigger(Trigger::Click(By::ClassName("blueButton"))),
Event::Trigger(Trigger::SendKeys(By::Name("sc"), "10")),
Event::Trigger(Trigger::SendKeys(By::Name("extensionSc"), "4000")),
Event::Trigger(Trigger::SendKeys(By::Name("customerName1"), "Hopper")),
Event::Trigger(Trigger::SendKeys(
By::Name("customerIBAN"),
"DE36444488881234567890",
)),
Event::Trigger(Trigger::Click(By::Css("input[value='Absenden']"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=processing"], //final status of this payment method will remain in processing state
)),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_twint_payment(driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/170"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("button[value='authorised']"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_walley_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/198"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Teknikmössor AB")),
Event::Trigger(Trigger::SwitchFrame(By::ClassName(
"collector-checkout-iframe",
))),
Event::Trigger(Trigger::Click(By::Id("purchase"))),
Event::Trigger(Trigger::Sleep(10)),
Event::Trigger(Trigger::SwitchFrame(By::Css(
"iframe[title='Walley Modal - idp-choices']",
))),
Event::Assert(Assert::IsPresent("Identifisering")),
Event::Trigger(Trigger::Click(By::Id("optionLoggInnMedBankId"))),
Event::Trigger(Trigger::SwitchFrame(By::Css("iframe[title='BankID']"))),
Event::Assert(Assert::IsPresent("Engangskode")),
Event::Trigger(Trigger::SendKeys(By::Css("input[type='password']"), "otp")),
Event::Trigger(Trigger::Sleep(4)),
Event::Trigger(Trigger::Click(By::Css("button[title='Neste']"))),
Event::Assert(Assert::IsPresent("Ditt BankID-passord")),
Event::Trigger(Trigger::Sleep(4)),
Event::Trigger(Trigger::SendKeys(
By::Css("input[type='password']"),
"qwer1234",
)),
Event::Trigger(Trigger::Click(By::Css("button[title='Neste']"))),
Event::Trigger(Trigger::SwitchTab(Position::Prev)),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_dana_payment(driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/175"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SendKeys(
By::Css("input[type='number']"),
"12345678901",
)), // Mobile Number can be any random 11 digit number
Event::Trigger(Trigger::Click(By::Css("button"))),
Event::Trigger(Trigger::SendKeys(By::Css("input[type='number']"), "111111")), // PIN can be any random 11 digit number
Event::Trigger(Trigger::Click(By::ClassName("btn-next"))),
Event::Trigger(Trigger::Sleep(3)),
Event::Trigger(Trigger::Click(By::ClassName("btn-next"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_online_banking_fpx_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/172"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("button[value='authorised']"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_online_banking_thailand_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/184"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("button[value='authorised']"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_touch_n_go_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/185"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("button[value='authorised']"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_swish_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/210"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("status")),
Event::Assert(Assert::IsPresent("processing")),
Event::Assert(Assert::IsPresent("Next Action Type")),
Event::Assert(Assert::IsPresent("qr_code_information")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_blik_payment(driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/64"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Next Action Type")),
Event::Assert(Assert::IsPresent("wait_screen_information")),
],
)
.await?;
Ok(())
}
async fn should_make_adyen_momo_atm_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/238"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Sleep(5)), // Delay for provider to not reject payment for botting
Event::Trigger(Trigger::SendKeys(
By::Id("card-number"),
"9704 0000 0000 0018",
)),
Event::Trigger(Trigger::SendKeys(By::Id("card-expire"), "03/07")),
Event::Trigger(Trigger::SendKeys(By::Id("card-name"), "NGUYEN VAN A")),
Event::Trigger(Trigger::SendKeys(By::Id("number-phone"), "987656666")),
Event::Trigger(Trigger::Click(By::Id("btn-pay-card"))),
Event::Trigger(Trigger::SendKeys(By::Id("napasOtpCode"), "otp")),
Event::Trigger(Trigger::Click(By::Id("napasProcessBtn1"))),
Event::Trigger(Trigger::Sleep(5)), // Delay to get to status page
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
#[test]
#[serial]
fn should_make_adyen_gpay_payment_test() {
tester!(should_make_adyen_gpay_payment);
}
#[test]
#[serial]
fn should_make_adyen_gpay_mandate_payment_test() {
tester!(should_make_adyen_gpay_mandate_payment);
}
#[test]
#[serial]
fn should_make_adyen_gpay_zero_dollar_mandate_payment_test() {
tester!(should_make_adyen_gpay_zero_dollar_mandate_payment);
}
#[test]
#[serial]
fn should_make_adyen_klarna_mandate_payment_test() {
tester!(should_make_adyen_klarna_mandate_payment);
}
#[test]
#[serial]
fn should_make_adyen_3ds_payment_failed_test() {
tester!(should_make_adyen_3ds_payment_failed);
}
#[test]
#[serial]
fn should_make_adyen_3ds_mandate_payment_test() {
tester!(should_make_adyen_3ds_mandate_payment);
}
#[test]
#[serial]
fn should_make_adyen_3ds_mandate_with_zero_dollar_payment_test() {
tester!(should_make_adyen_3ds_mandate_with_zero_dollar_payment);
}
#[test]
#[serial]
fn should_make_adyen_3ds_payment_success_test() {
tester!(should_make_adyen_3ds_payment_success);
}
#[test]
#[serial]
fn should_make_adyen_alipay_hk_payment_test() {
tester!(should_make_adyen_alipay_hk_payment);
}
#[test]
#[serial]
fn should_make_adyen_swish_payment_test() {
tester!(should_make_adyen_swish_payment);
}
#[test]
#[serial]
#[ignore = "Failing from connector side"]
fn should_make_adyen_bizum_payment_test() {
tester!(should_make_adyen_bizum_payment);
}
#[test]
#[serial]
fn should_make_adyen_clearpay_payment_test() {
tester!(should_make_adyen_clearpay_payment);
}
#[test]
#[serial]
fn should_make_adyen_twint_payment_test() {
tester!(should_make_adyen_twint_payment);
}
#[test]
#[serial]
fn should_make_adyen_paypal_payment_test() {
tester!(should_make_adyen_paypal_payment);
}
#[test]
#[serial]
fn should_make_adyen_ach_payment_test() {
tester!(should_make_adyen_ach_payment);
}
#[test]
#[serial]
fn should_make_adyen_sepa_payment_test() {
tester!(should_make_adyen_sepa_payment);
}
#[test]
#[serial]
fn should_make_adyen_bacs_payment_test() {
tester!(should_make_adyen_bacs_payment);
}
#[test]
#[serial]
fn should_make_adyen_ideal_payment_test() {
tester!(should_make_adyen_ideal_payment);
}
#[test]
#[serial]
fn should_make_adyen_eps_payment_test() {
tester!(should_make_adyen_eps_payment);
}
#[test]
#[serial]
fn should_make_adyen_bancontact_card_payment_test() {
tester!(should_make_adyen_bancontact_card_payment);
}
#[test]
#[serial]
fn should_make_adyen_wechatpay_payment_test() {
tester!(should_make_adyen_wechatpay_payment);
}
#[test]
#[serial]
fn should_make_adyen_mbway_payment_test() {
tester!(should_make_adyen_mbway_payment);
}
#[test]
#[serial]
fn should_make_adyen_ebanking_fi_payment_test() {
tester!(should_make_adyen_ebanking_fi_payment);
}
#[test]
#[serial]
fn should_make_adyen_onlinebanking_pl_payment_test() {
tester!(should_make_adyen_onlinebanking_pl_payment);
}
#[ignore]
#[test]
#[serial]
fn should_make_adyen_giropay_payment_test() {
tester!(should_make_adyen_giropay_payment);
}
#[ignore]
#[test]
#[serial]
fn should_make_adyen_walley_payment_test() {
tester!(should_make_adyen_walley_payment);
}
#[test]
#[serial]
fn should_make_adyen_dana_payment_test() {
tester!(should_make_adyen_dana_payment);
}
#[test]
#[serial]
fn should_make_adyen_blik_payment_test() {
tester!(should_make_adyen_blik_payment);
}
#[test]
#[serial]
fn should_make_adyen_online_banking_fpx_payment_test() {
tester!(should_make_adyen_online_banking_fpx_payment);
}
#[test]
#[serial]
fn should_make_adyen_online_banking_thailand_payment_test() {
tester!(should_make_adyen_online_banking_thailand_payment);
}
#[test]
#[serial]
fn should_make_adyen_touch_n_go_payment_test() {
tester!(should_make_adyen_touch_n_go_payment);
}
#[ignore]
#[test]
#[serial]
fn should_make_adyen_momo_atm_payment_test() {
tester!(should_make_adyen_momo_atm_payment);
}
| 7,588 | 908 |
hyperswitch | crates/test_utils/tests/connectors/authorizedotnet_wh_ui.rs | .rs | use rand::Rng;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct AuthorizedotnetSeleniumTest;
impl SeleniumTest for AuthorizedotnetSeleniumTest {
fn get_connector_name(&self) -> String {
"authorizedotnet".to_string()
}
}
async fn should_make_webhook(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AuthorizedotnetSeleniumTest {};
let amount = rand::thread_rng().gen_range(50..1000); //This connector detects it as fraudulent payment if the same amount is used for multiple payments so random amount is passed for testing(
conn.make_webhook_test(
web_driver,
&format!("{CHECKOUT_BASE_URL}/saved/227?amount={amount}"),
vec![
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("status")),
Event::Assert(Assert::IsPresent("processing")),
],
10,
"processing",
)
.await?;
Ok(())
}
#[test]
fn should_make_webhook_test() {
tester!(should_make_webhook);
}
| 259 | 909 |
hyperswitch | crates/test_utils/tests/connectors/worldline_ui.rs | .rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct WorldlineSeleniumTest;
impl SeleniumTest for WorldlineSeleniumTest {
fn get_connector_name(&self) -> String {
"worldline".to_string()
}
}
async fn should_make_card_non_3ds_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = WorldlineSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/71"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("status")),
Event::Assert(Assert::IsPresent("processing")),
],
)
.await?;
Ok(())
}
async fn should_make_worldline_ideal_redirect_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = WorldlineSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/49"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=requires_customer_action", "status=succeeded"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_worldline_giropay_redirect_payment(
c: WebDriver,
) -> Result<(), WebDriverError> {
let conn = WorldlineSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/48"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=requires_customer_action", "status=succeeded"],
)),
],
)
.await?;
Ok(())
}
#[test]
#[serial]
#[ignore]
fn should_make_worldline_giropay_redirect_payment_test() {
tester!(should_make_worldline_giropay_redirect_payment);
}
#[test]
#[serial]
fn should_make_worldline_ideal_redirect_payment_test() {
tester!(should_make_worldline_ideal_redirect_payment);
}
#[test]
#[serial]
fn should_make_card_non_3ds_payment_test() {
tester!(should_make_card_non_3ds_payment);
}
| 577 | 910 |
hyperswitch | crates/test_utils/tests/connectors/bluesnap_wh_ui.rs | .rs | use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct BluesnapSeleniumTest;
impl SeleniumTest for BluesnapSeleniumTest {
fn get_connector_name(&self) -> String {
"bluesnap".to_string()
}
}
async fn should_make_webhook(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = BluesnapSeleniumTest {};
conn.make_webhook_test(
web_driver,
&format!("{CHECKOUT_BASE_URL}/saved/199"),
vec![
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
10,
"succeeded",
)
.await?;
Ok(())
}
#[test]
fn should_make_webhook_test() {
tester!(should_make_webhook);
}
| 189 | 911 |
hyperswitch | crates/test_utils/tests/connectors/bluesnap_ui.rs | .rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct BluesnapSeleniumTest;
impl SeleniumTest for BluesnapSeleniumTest {
fn get_connector_name(&self) -> String {
"bluesnap".to_string()
}
}
async fn should_make_3ds_payment(driver: WebDriver) -> Result<(), WebDriverError> {
let conn = BluesnapSeleniumTest {};
conn.make_redirection_payment(
driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/200"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::RunIf(
Assert::IsElePresent(By::Id("Cardinal-CCA-IFrame")),
vec![
Event::Trigger(Trigger::SwitchFrame(By::Id("Cardinal-CCA-IFrame"))),
Event::Assert(Assert::IsPresent("Enter your code below")),
Event::Trigger(Trigger::SendKeys(By::Name("challengeDataEntry"), "1234")),
Event::Trigger(Trigger::Click(By::ClassName("button.primary"))),
],
),
Event::Trigger(Trigger::Sleep(10)),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_gpay_payment(driver: WebDriver) -> Result<(), WebDriverError> {
let conn = BluesnapSeleniumTest {};
let pub_key = conn
.get_configs()
.automation_configs
.unwrap()
.bluesnap_gateway_merchant_id
.unwrap();
conn.make_gpay_payment(driver,
&format!("{CHECKOUT_BASE_URL}/gpay?gatewayname=bluesnap&gatewaymerchantid={pub_key}&amount=11.00&country=US¤cy=USD"),
vec![
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
#[test]
#[serial]
fn should_make_3ds_payment_test() {
tester!(should_make_3ds_payment);
}
#[test]
#[serial]
fn should_make_gpay_payment_test() {
tester!(should_make_gpay_payment);
}
| 507 | 912 |
hyperswitch | crates/test_utils/tests/connectors/checkout_wh_ui.rs | .rs | use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct CheckoutSeleniumTest;
impl SeleniumTest for CheckoutSeleniumTest {
fn get_connector_name(&self) -> String {
"checkout".to_string()
}
}
async fn should_make_webhook(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = CheckoutSeleniumTest {};
conn.make_webhook_test(
web_driver,
&format!("{CHECKOUT_BASE_URL}/saved/18"),
vec![
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Sleep(8)),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded", "status=processing"],
)),
],
10,
"succeeded",
)
.await?;
Ok(())
}
#[test]
fn should_make_webhook_test() {
tester!(should_make_webhook);
}
| 225 | 913 |
hyperswitch | crates/test_utils/tests/connectors/selenium.rs | .rs | #![allow(
clippy::expect_used,
clippy::panic,
clippy::unwrap_in_result,
clippy::missing_panics_doc,
clippy::unwrap_used
)]
use std::{
collections::{HashMap, HashSet},
env,
io::Read,
path::{MAIN_SEPARATOR, MAIN_SEPARATOR_STR},
time::Duration,
};
use async_trait::async_trait;
use base64::Engine;
use serde::{Deserialize, Serialize};
use serde_json::json;
use test_utils::connector_auth;
use thirtyfour::{components::SelectElement, prelude::*, WebDriver};
#[derive(Clone)]
pub enum Event<'a> {
RunIf(Assert<'a>, Vec<Event<'a>>),
EitherOr(Assert<'a>, Vec<Event<'a>>, Vec<Event<'a>>),
Assert(Assert<'a>),
Trigger(Trigger<'a>),
}
#[derive(Clone)]
#[allow(dead_code)]
pub enum Trigger<'a> {
Goto(&'a str),
Click(By),
ClickNth(By, usize),
SelectOption(By, &'a str),
ChangeQueryParam(&'a str, &'a str),
SwitchTab(Position),
SwitchFrame(By),
Find(By),
Query(By),
SendKeys(By, &'a str),
Sleep(u64),
}
#[derive(Clone)]
pub enum Position {
Prev,
Next,
}
#[derive(Clone)]
pub enum Selector {
Title,
QueryParamStr,
}
#[derive(Clone)]
pub enum Assert<'a> {
Eq(Selector, &'a str),
Contains(Selector, &'a str),
ContainsAny(Selector, Vec<&'a str>),
EitherOfThemExist(&'a str, &'a str),
IsPresent(&'a str),
IsElePresent(By),
IsPresentNow(&'a str),
}
pub static CHECKOUT_BASE_URL: &str = "https://hs-payments-test.netlify.app";
#[async_trait]
pub trait SeleniumTest {
fn get_saved_testcases(&self) -> serde_json::Value {
get_saved_testcases()
}
fn get_configs(&self) -> connector_auth::ConnectorAuthentication {
get_configs()
}
async fn retry_click(
&self,
times: i32,
interval: u64,
driver: &WebDriver,
by: By,
) -> Result<(), WebDriverError> {
let mut res = Ok(());
for _i in 0..times {
res = self.click_element(driver, by.clone()).await;
if res.is_err() {
tokio::time::sleep(Duration::from_secs(interval)).await;
} else {
break;
}
}
return res;
}
fn get_connector_name(&self) -> String;
async fn complete_actions(
&self,
driver: &WebDriver,
actions: Vec<Event<'_>>,
) -> Result<(), WebDriverError> {
for action in actions {
match action {
Event::Assert(assert) => match assert {
Assert::Contains(selector, text) => match selector {
Selector::QueryParamStr => {
let url = driver.current_url().await?;
assert!(url.query().unwrap().contains(text))
}
_ => assert!(driver.title().await?.contains(text)),
},
Assert::ContainsAny(selector, search_keys) => match selector {
Selector::QueryParamStr => {
let url = driver.current_url().await?;
assert!(search_keys
.iter()
.any(|key| url.query().unwrap().contains(key)))
}
_ => assert!(driver.title().await?.contains(search_keys.first().unwrap())),
},
Assert::EitherOfThemExist(text_1, text_2) => assert!(
is_text_present_now(driver, text_1).await?
|| is_text_present_now(driver, text_2).await?
),
Assert::Eq(_selector, text) => assert_eq!(driver.title().await?, text),
Assert::IsPresent(text) => {
assert!(is_text_present(driver, text).await?)
}
Assert::IsElePresent(selector) => {
assert!(is_element_present(driver, selector).await?)
}
Assert::IsPresentNow(text) => {
assert!(is_text_present_now(driver, text).await?)
}
},
Event::RunIf(con_event, events) => match con_event {
Assert::Contains(selector, text) => match selector {
Selector::QueryParamStr => {
let url = driver.current_url().await?;
if url.query().unwrap().contains(text) {
self.complete_actions(driver, events).await?;
}
}
_ => assert!(driver.title().await?.contains(text)),
},
Assert::ContainsAny(selector, keys) => match selector {
Selector::QueryParamStr => {
let url = driver.current_url().await?;
if keys.iter().any(|key| url.query().unwrap().contains(key)) {
self.complete_actions(driver, events).await?;
}
}
_ => assert!(driver.title().await?.contains(keys.first().unwrap())),
},
Assert::Eq(_selector, text) => {
if text == driver.title().await? {
self.complete_actions(driver, events).await?;
}
}
Assert::EitherOfThemExist(text_1, text_2) => {
if is_text_present_now(driver, text_1).await.is_ok()
|| is_text_present_now(driver, text_2).await.is_ok()
{
self.complete_actions(driver, events).await?;
}
}
Assert::IsPresent(text) => {
if is_text_present(driver, text).await.is_ok() {
self.complete_actions(driver, events).await?;
}
}
Assert::IsElePresent(text) => {
if is_element_present(driver, text).await.is_ok() {
self.complete_actions(driver, events).await?;
}
}
Assert::IsPresentNow(text) => {
if is_text_present_now(driver, text).await.is_ok() {
self.complete_actions(driver, events).await?;
}
}
},
Event::EitherOr(con_event, success, failure) => match con_event {
Assert::Contains(selector, text) => match selector {
Selector::QueryParamStr => {
let url = driver.current_url().await?;
self.complete_actions(
driver,
if url.query().unwrap().contains(text) {
success
} else {
failure
},
)
.await?;
}
_ => assert!(driver.title().await?.contains(text)),
},
Assert::ContainsAny(selector, keys) => match selector {
Selector::QueryParamStr => {
let url = driver.current_url().await?;
self.complete_actions(
driver,
if keys.iter().any(|key| url.query().unwrap().contains(key)) {
success
} else {
failure
},
)
.await?;
}
_ => assert!(driver.title().await?.contains(keys.first().unwrap())),
},
Assert::Eq(_selector, text) => {
self.complete_actions(
driver,
if text == driver.title().await? {
success
} else {
failure
},
)
.await?;
}
Assert::EitherOfThemExist(text_1, text_2) => {
self.complete_actions(
driver,
if is_text_present_now(driver, text_1).await.is_ok()
|| is_text_present_now(driver, text_2).await.is_ok()
{
success
} else {
failure
},
)
.await?;
}
Assert::IsPresent(text) => {
self.complete_actions(
driver,
if is_text_present(driver, text).await.is_ok() {
success
} else {
failure
},
)
.await?;
}
Assert::IsElePresent(by) => {
self.complete_actions(
driver,
if is_element_present(driver, by).await.is_ok() {
success
} else {
failure
},
)
.await?;
}
Assert::IsPresentNow(text) => {
self.complete_actions(
driver,
if is_text_present_now(driver, text).await.is_ok() {
success
} else {
failure
},
)
.await?;
}
},
Event::Trigger(trigger) => match trigger {
Trigger::Goto(url) => {
let saved_tests =
serde_json::to_string(&self.get_saved_testcases()).unwrap();
let conf = serde_json::to_string(&self.get_configs()).unwrap();
let configs = self.get_configs().automation_configs.unwrap();
let hs_base_url = configs
.hs_base_url
.unwrap_or_else(|| "http://localhost:8080".to_string());
let configs_url = configs.configs_url.unwrap();
let hs_api_keys = configs.hs_api_keys.unwrap();
let test_env = configs.hs_test_env.unwrap();
let script = &[
format!("localStorage.configs='{configs_url}'").as_str(),
format!("localStorage.current_env='{test_env}'").as_str(),
"localStorage.hs_api_key=''",
format!("localStorage.hs_api_keys='{hs_api_keys}'").as_str(),
format!("localStorage.base_url='{hs_base_url}'").as_str(),
format!("localStorage.hs_api_configs='{conf}'").as_str(),
format!("localStorage.saved_payments=JSON.stringify({saved_tests})")
.as_str(),
"localStorage.force_sync='true'",
format!(
"localStorage.current_connector=\"{}\";",
self.get_connector_name().clone()
)
.as_str(),
]
.join(";");
driver.goto(url).await?;
driver.execute(script, Vec::new()).await?;
}
Trigger::Click(by) => {
self.retry_click(3, 5, driver, by.clone()).await?;
}
Trigger::ClickNth(by, n) => {
let ele = driver.query(by).all().await?.into_iter().nth(n).unwrap();
ele.wait_until().enabled().await?;
ele.wait_until().displayed().await?;
ele.wait_until().clickable().await?;
ele.scroll_into_view().await?;
ele.click().await?;
}
Trigger::Find(by) => {
driver.find(by).await?;
}
Trigger::Query(by) => {
driver.query(by).first().await?;
}
Trigger::SendKeys(by, input) => {
let ele = driver.query(by).first().await?;
ele.wait_until().displayed().await?;
ele.send_keys(&input).await?;
}
Trigger::SelectOption(by, input) => {
let ele = driver.query(by).first().await?;
let select_element = SelectElement::new(&ele).await?;
select_element.select_by_partial_text(input).await?;
}
Trigger::ChangeQueryParam(param, value) => {
let mut url = driver.current_url().await?;
let mut hash_query: HashMap<String, String> =
url.query_pairs().into_owned().collect();
hash_query.insert(param.to_string(), value.to_string());
let url_str = serde_urlencoded::to_string(hash_query)
.expect("Query Param update failed");
url.set_query(Some(&url_str));
driver.goto(url.as_str()).await?;
}
Trigger::Sleep(seconds) => {
tokio::time::sleep(Duration::from_secs(seconds)).await;
}
Trigger::SwitchTab(position) => match position {
Position::Next => {
let windows = driver.windows().await?;
if let Some(window) = windows.iter().next_back() {
driver.switch_to_window(window.to_owned()).await?;
}
}
Position::Prev => {
let windows = driver.windows().await?;
if let Some(window) = windows.into_iter().next() {
driver.switch_to_window(window.to_owned()).await?;
}
}
},
Trigger::SwitchFrame(by) => {
let iframe = driver.query(by).first().await?;
iframe.wait_until().displayed().await?;
iframe.clone().enter_frame().await?;
}
},
}
}
Ok(())
}
async fn click_element(&self, driver: &WebDriver, by: By) -> Result<(), WebDriverError> {
let ele = driver.query(by).first().await?;
ele.wait_until().enabled().await?;
ele.wait_until().displayed().await?;
ele.wait_until().clickable().await?;
ele.scroll_into_view().await?;
ele.click().await
}
async fn make_redirection_payment(
&self,
web_driver: WebDriver,
actions: Vec<Event<'_>>,
) -> Result<(), WebDriverError> {
// To support failure retries
let result = self
.execute_steps(web_driver.clone(), actions.clone())
.await;
if result.is_err() {
self.execute_steps(web_driver, actions).await
} else {
result
}
}
async fn execute_steps(
&self,
web_driver: WebDriver,
actions: Vec<Event<'_>>,
) -> Result<(), WebDriverError> {
let config = self.get_configs().automation_configs.unwrap();
if config.run_minimum_steps.unwrap() {
self.complete_actions(&web_driver, actions.get(..3).unwrap().to_vec())
.await
} else {
self.complete_actions(&web_driver, actions).await
}
}
async fn make_gpay_payment(
&self,
web_driver: WebDriver,
url: &str,
actions: Vec<Event<'_>>,
) -> Result<(), WebDriverError> {
self.execute_gpay_steps(web_driver, url, actions).await
}
async fn execute_gpay_steps(
&self,
web_driver: WebDriver,
url: &str,
actions: Vec<Event<'_>>,
) -> Result<(), WebDriverError> {
let config = self.get_configs().automation_configs.unwrap();
let (email, pass) = (&config.gmail_email.unwrap(), &config.gmail_pass.unwrap());
let default_actions = vec![
Event::Trigger(Trigger::Goto(url)),
Event::Trigger(Trigger::Click(By::Css(".gpay-button"))),
Event::Trigger(Trigger::SwitchTab(Position::Next)),
Event::Trigger(Trigger::Sleep(5)),
Event::RunIf(
Assert::EitherOfThemExist("Use your Google Account", "Sign in"),
vec![
Event::Trigger(Trigger::SendKeys(By::Id("identifierId"), email)),
Event::Trigger(Trigger::ClickNth(By::Tag("button"), 2)),
Event::EitherOr(
Assert::IsPresent("Welcome"),
vec![
Event::Trigger(Trigger::SendKeys(By::Name("Passwd"), pass)),
Event::Trigger(Trigger::Sleep(2)),
Event::Trigger(Trigger::Click(By::Id("passwordNext"))),
Event::Trigger(Trigger::Sleep(10)),
],
vec![
Event::Trigger(Trigger::SendKeys(By::Id("identifierId"), email)),
Event::Trigger(Trigger::ClickNth(By::Tag("button"), 2)),
Event::Trigger(Trigger::SendKeys(By::Name("Passwd"), pass)),
Event::Trigger(Trigger::Sleep(2)),
Event::Trigger(Trigger::Click(By::Id("passwordNext"))),
Event::Trigger(Trigger::Sleep(10)),
],
),
],
),
Event::Trigger(Trigger::SwitchFrame(By::Css(
".bootstrapperIframeContainerElement iframe",
))),
Event::Assert(Assert::IsPresent("Gpay Tester")),
Event::Trigger(Trigger::Click(By::ClassName("jfk-button-action"))),
Event::Trigger(Trigger::SwitchTab(Position::Prev)),
];
self.complete_actions(&web_driver, default_actions).await?;
self.complete_actions(&web_driver, actions).await
}
async fn make_affirm_payment(
&self,
driver: WebDriver,
url: &str,
actions: Vec<Event<'_>>,
) -> Result<(), WebDriverError> {
self.complete_actions(
&driver,
vec![
Event::Trigger(Trigger::Goto(url)),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
],
)
.await?;
let mut affirm_actions = vec![
Event::RunIf(
Assert::IsPresent("Big purchase? No problem."),
vec![
Event::Trigger(Trigger::SendKeys(
By::Css("input[data-testid='phone-number-field']"),
"(833) 549-5574", // any test phone number accepted by affirm
)),
Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='submit-button']",
))),
Event::Trigger(Trigger::SendKeys(
By::Css("input[data-testid='phone-pin-field']"),
"1234",
)),
],
),
Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='skip-payment-button']",
))),
Event::Trigger(Trigger::Click(By::Css("div[data-testid='indicator']"))),
Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='submit-button']",
))),
Event::Trigger(Trigger::Click(By::Css("div[data-testid='indicator']"))),
Event::Trigger(Trigger::Click(By::Css(
"div[data-testid='disclosure-checkbox-indicator']",
))),
Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='submit-button']",
))),
];
affirm_actions.extend(actions);
self.complete_actions(&driver, affirm_actions).await
}
async fn make_webhook_test(
&self,
web_driver: WebDriver,
payment_url: &str,
actions: Vec<Event<'_>>,
webhook_retry_time: u64,
webhook_status: &str,
) -> Result<(), WebDriverError> {
self.complete_actions(
&web_driver,
vec![Event::Trigger(Trigger::Goto(payment_url))],
)
.await?;
self.complete_actions(&web_driver, actions).await?; //additional actions needs to make a payment
self.complete_actions(
&web_driver,
vec![Event::Trigger(Trigger::Goto(&format!(
"{CHECKOUT_BASE_URL}/events"
)))],
)
.await?;
let element = web_driver.query(By::Css("h2.last-payment")).first().await?;
let payment_id = element.text().await?;
let retries = 3; // no of retry times
for _i in 0..retries {
let configs = self.get_configs().automation_configs.unwrap();
let outgoing_webhook_url = configs.hs_webhook_url.unwrap().to_string();
let client = reqwest::Client::new();
let response = client.get(outgoing_webhook_url).send().await.unwrap(); // get events from outgoing webhook endpoint
let body_text = response.text().await.unwrap();
let data: WebhookResponse = serde_json::from_str(&body_text).unwrap();
let last_three_events = data.data.get(data.data.len().saturating_sub(3)..).unwrap(); // Get the last three elements if available
for last_event in last_three_events {
let last_event_body = &last_event.step.request.body;
let decoded_bytes = base64::engine::general_purpose::STANDARD //decode the encoded outgoing webhook event
.decode(last_event_body)
.unwrap();
let decoded_str = String::from_utf8(decoded_bytes).unwrap();
let webhook_response: HsWebhookResponse =
serde_json::from_str(&decoded_str).unwrap();
if payment_id == webhook_response.content.object.payment_id
&& webhook_status == webhook_response.content.object.status
{
return Ok(());
}
}
self.complete_actions(
&web_driver,
vec![Event::Trigger(Trigger::Sleep(webhook_retry_time))],
)
.await?;
}
Err(WebDriverError::CustomError("Webhook Not Found".to_string()))
}
async fn make_paypal_payment(
&self,
web_driver: WebDriver,
url: &str,
actions: Vec<Event<'_>>,
) -> Result<(), WebDriverError> {
let pypl_url = url.to_string();
// To support failure retries
let result = self
.execute_paypal_steps(web_driver.clone(), &pypl_url, actions.clone())
.await;
if result.is_err() {
self.execute_paypal_steps(web_driver.clone(), &pypl_url, actions.clone())
.await
} else {
result
}
}
async fn execute_paypal_steps(
&self,
web_driver: WebDriver,
url: &str,
actions: Vec<Event<'_>>,
) -> Result<(), WebDriverError> {
self.complete_actions(
&web_driver,
vec![
Event::Trigger(Trigger::Goto(url)),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
],
)
.await?;
let (email, pass) = (
&self
.get_configs()
.automation_configs
.unwrap()
.pypl_email
.unwrap(),
&self
.get_configs()
.automation_configs
.unwrap()
.pypl_pass
.unwrap(),
);
let mut pypl_actions = vec![
Event::Trigger(Trigger::Sleep(8)),
Event::RunIf(
Assert::IsPresentNow("Enter your email address to get started"),
vec![
Event::Trigger(Trigger::SendKeys(By::Id("email"), email)),
Event::Trigger(Trigger::Click(By::Id("btnNext"))),
],
),
Event::RunIf(
Assert::IsPresentNow("Password"),
vec![
Event::Trigger(Trigger::SendKeys(By::Id("password"), pass)),
Event::Trigger(Trigger::Click(By::Id("btnLogin"))),
],
),
];
pypl_actions.extend(actions);
self.complete_actions(&web_driver, pypl_actions).await
}
async fn make_clearpay_payment(
&self,
driver: WebDriver,
url: &str,
actions: Vec<Event<'_>>,
) -> Result<(), WebDriverError> {
self.complete_actions(
&driver,
vec![
Event::Trigger(Trigger::Goto(url)),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Sleep(5)),
Event::RunIf(
Assert::IsPresentNow("Manage Cookies"),
vec![
Event::Trigger(Trigger::Click(By::Css("button.cookie-setting-link"))),
Event::Trigger(Trigger::Click(By::Id("accept-recommended-btn-handler"))),
],
),
],
)
.await?;
let (email, pass) = (
&self
.get_configs()
.automation_configs
.unwrap()
.clearpay_email
.unwrap(),
&self
.get_configs()
.automation_configs
.unwrap()
.clearpay_pass
.unwrap(),
);
let mut clearpay_actions = vec![
Event::Trigger(Trigger::Sleep(3)),
Event::EitherOr(
Assert::IsPresent("Please enter your password"),
vec![
Event::Trigger(Trigger::SendKeys(By::Css("input[name='password']"), pass)),
Event::Trigger(Trigger::Click(By::Css("button[type='submit']"))),
],
vec![
Event::Trigger(Trigger::SendKeys(
By::Css("input[name='identifier']"),
email,
)),
Event::Trigger(Trigger::Click(By::Css("button[type='submit']"))),
Event::Trigger(Trigger::Sleep(3)),
Event::Trigger(Trigger::SendKeys(By::Css("input[name='password']"), pass)),
Event::Trigger(Trigger::Click(By::Css("button[type='submit']"))),
],
),
Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='summary-button']",
))),
];
clearpay_actions.extend(actions);
self.complete_actions(&driver, clearpay_actions).await
}
}
async fn is_text_present_now(driver: &WebDriver, key: &str) -> WebDriverResult<bool> {
let mut xpath = "//*[contains(text(),'".to_owned();
xpath.push_str(key);
xpath.push_str("')]");
let result = driver.find(By::XPath(&xpath)).await?;
let display: &str = &result.css_value("display").await?;
if display.is_empty() || display == "none" {
return Err(WebDriverError::CustomError("Element is hidden".to_string()));
}
result.is_present().await
}
async fn is_text_present(driver: &WebDriver, key: &str) -> WebDriverResult<bool> {
let mut xpath = "//*[contains(text(),'".to_owned();
xpath.push_str(key);
xpath.push_str("')]");
let result = driver.query(By::XPath(&xpath)).first().await?;
result.is_present().await
}
async fn is_element_present(driver: &WebDriver, by: By) -> WebDriverResult<bool> {
let element = driver.query(by).first().await?;
element.is_present().await
}
#[macro_export]
macro_rules! tester_inner {
($execute:ident, $webdriver:expr) => {{
use std::{
sync::{Arc, Mutex},
thread,
};
let driver = $webdriver;
// we'll need the session_id from the thread
// NOTE: even if it panics, so can't just return it
let session_id = Arc::new(Mutex::new(None));
// run test in its own thread to catch panics
let sid = session_id.clone();
let res = thread::spawn(move || {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
let driver = runtime
.block_on(driver)
.expect("failed to construct test WebDriver");
*sid.lock().unwrap() = runtime.block_on(driver.session_id()).ok();
// make sure we close, even if an assertion fails
let client = driver.clone();
let x = runtime.block_on(async move {
let run = tokio::spawn($execute(driver)).await;
let _ = client.quit().await;
run
});
drop(runtime);
x.expect("test panicked")
})
.join();
let success = handle_test_error(res);
assert!(success);
}};
}
#[macro_export]
macro_rules! function {
() => {{
fn f() {}
fn type_name_of<T>(_: T) -> &'static str {
std::any::type_name::<T>()
}
let name = type_name_of(f);
&name.get(..name.len() - 3).unwrap()
}};
}
#[macro_export]
macro_rules! tester {
($f:ident) => {{
use $crate::{function, tester_inner};
let test_name = format!("{:?}", function!());
if (should_ignore_test(&test_name)) {
return;
}
let browser = get_browser();
let url = make_url(&browser);
let caps = make_capabilities(&browser);
tester_inner!($f, WebDriver::new(url, caps));
}};
}
fn get_saved_testcases() -> serde_json::Value {
let env_value = env::var("CONNECTOR_TESTS_FILE_PATH").ok();
if env_value.is_none() {
return serde_json::json!("");
}
let path = env_value.unwrap();
let mut file = &std::fs::File::open(path).expect("Failed to open file");
let mut contents = String::new();
file.read_to_string(&mut contents)
.expect("Failed to read file");
// Parse the JSON data
serde_json::from_str(&contents).expect("Failed to parse JSON")
}
fn get_configs() -> connector_auth::ConnectorAuthentication {
let path =
env::var("CONNECTOR_AUTH_FILE_PATH").expect("connector authentication file path not set");
toml::from_str(
&std::fs::read_to_string(path).expect("connector authentication config file not found"),
)
.expect("Failed to read connector authentication config file")
}
pub fn should_ignore_test(name: &str) -> bool {
let conf = get_saved_testcases()
.get("tests_to_ignore")
.unwrap_or(&json!([]))
.clone();
let tests_to_ignore: HashSet<String> =
serde_json::from_value(conf).unwrap_or_else(|_| HashSet::new());
let modules: Vec<_> = name.split("::").collect();
let file_match = format!(
"{}::*",
<&str>::clone(modules.get(1).expect("Error obtaining module path segment"))
);
let module_name = modules
.get(1..3)
.expect("Error obtaining module path segment")
.join("::");
// Ignore if it matches patterns like nuvei_ui::*, nuvei_ui::should_make_nuvei_eps_payment_test
tests_to_ignore.contains(&file_match) || tests_to_ignore.contains(&module_name)
}
pub fn get_browser() -> String {
"firefox".to_string()
}
// based on the browser settings build profile info
pub fn make_capabilities(browser: &str) -> Capabilities {
match browser {
"firefox" => {
let mut caps = DesiredCapabilities::firefox();
let ignore_profile = env::var("IGNORE_BROWSER_PROFILE").ok();
if ignore_profile.is_none() || ignore_profile.unwrap() == "false" {
let profile_path = &format!("-profile={}", get_firefox_profile_path().unwrap());
caps.add_firefox_arg(profile_path).unwrap();
} else {
let profile_path = &format!("-profile={}", get_firefox_profile_path().unwrap());
caps.add_firefox_arg(profile_path).unwrap();
caps.add_firefox_arg("--headless").ok();
}
caps.into()
}
"chrome" => {
let mut caps = DesiredCapabilities::chrome();
let profile_path = &format!("user-data-dir={}", get_chrome_profile_path().unwrap());
caps.add_chrome_arg(profile_path).unwrap();
caps.into()
}
&_ => DesiredCapabilities::safari().into(),
}
}
fn get_chrome_profile_path() -> Result<String, WebDriverError> {
let exe = env::current_exe()?;
let dir = exe.parent().expect("Executable must be in some directory");
let mut base_path = dir
.to_str()
.map(|str| {
let mut fp = str.split(MAIN_SEPARATOR).collect::<Vec<_>>();
fp.truncate(3);
fp.join(MAIN_SEPARATOR_STR)
})
.unwrap();
if env::consts::OS == "macos" {
base_path.push_str(r"/Library/Application\ Support/Google/Chrome/Default");
//Issue: 1573
} // We're only using Firefox on Ubuntu runner
Ok(base_path)
}
fn get_firefox_profile_path() -> Result<String, WebDriverError> {
let exe = env::current_exe()?;
let dir = exe.parent().expect("Executable must be in some directory");
let mut base_path = dir
.to_str()
.map(|str| {
let mut fp = str.split(MAIN_SEPARATOR).collect::<Vec<_>>();
fp.truncate(3);
fp.join(MAIN_SEPARATOR_STR)
})
.unwrap();
if env::consts::OS == "macos" {
base_path.push_str(r#"/Library/Application Support/Firefox/Profiles/hs-test"#);
//Issue: 1573
} else if env::consts::OS == "linux" {
if let Some(home_dir) = env::var_os("HOME") {
if let Some(home_path) = home_dir.to_str() {
let profile_path = format!("{}/.mozilla/firefox/hs-test", home_path);
return Ok(profile_path);
}
}
}
Ok(base_path)
}
pub fn make_url(browser: &str) -> &'static str {
match browser {
"firefox" => "http://localhost:4444",
"chrome" => "http://localhost:9515",
&_ => "",
}
}
pub fn handle_test_error(
res: Result<Result<(), WebDriverError>, Box<dyn std::any::Any + Send>>,
) -> bool {
match res {
Ok(Ok(_)) => true,
Ok(Err(web_driver_error)) => {
eprintln!("test future failed to resolve: {:?}", web_driver_error);
false
}
Err(e) => {
if let Some(web_driver_error) = e.downcast_ref::<WebDriverError>() {
eprintln!("test future panicked: {:?}", web_driver_error);
} else {
eprintln!("test future panicked; an assertion probably failed");
}
false
}
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct WebhookResponse {
data: Vec<WebhookResponseData>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct WebhookResponseData {
step: WebhookRequestData,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct WebhookRequestData {
request: WebhookRequest,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct WebhookRequest {
body: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct HsWebhookResponse {
content: HsWebhookContent,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct HsWebhookContent {
object: HsWebhookObject,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct HsWebhookObject {
payment_id: String,
status: String,
connector: String,
}
| 7,280 | 914 |
hyperswitch | crates/test_utils/tests/connectors/stripe_wh_ui.rs | .rs | use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct StripeSeleniumTest;
impl SeleniumTest for StripeSeleniumTest {
fn get_connector_name(&self) -> String {
"stripe".to_string()
}
}
async fn should_make_webhook(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_webhook_test(
web_driver,
&format!("{CHECKOUT_BASE_URL}/saved/16"),
vec![
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("status")),
Event::Assert(Assert::IsPresent("succeeded")),
],
10,
"succeeded",
)
.await?;
Ok(())
}
#[test]
fn should_make_webhook_test() {
tester!(should_make_webhook);
}
| 196 | 915 |
hyperswitch | crates/test_utils/tests/connectors/authorizedotnet_ui.rs | .rs | use rand::Rng;
use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct AuthorizedotnetSeleniumTest;
impl SeleniumTest for AuthorizedotnetSeleniumTest {
fn get_connector_name(&self) -> String {
"authorizedotnet".to_string()
}
}
async fn should_make_gpay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AuthorizedotnetSeleniumTest {};
let amount = rand::thread_rng().gen_range(1..1000); //This connector detects it as fraudulent payment if the same amount is used for multiple payments so random amount is passed for testing
let pub_key = conn
.get_configs()
.automation_configs
.unwrap()
.authorizedotnet_gateway_merchant_id
.unwrap();
conn.make_gpay_payment(web_driver,
&format!("{CHECKOUT_BASE_URL}/gpay?gatewayname=authorizenet&gatewaymerchantid={pub_key}&amount={amount}&country=US¤cy=USD"),
vec![
Event::Assert(Assert::IsPresent("status")),
Event::Assert(Assert::IsPresent("processing")), // This connector status will be processing for one day
]).await?;
Ok(())
}
async fn should_make_paypal_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AuthorizedotnetSeleniumTest {};
conn.make_paypal_payment(
web_driver,
&format!("{CHECKOUT_BASE_URL}/saved/156"),
vec![
Event::EitherOr(
Assert::IsElePresent(By::Css(".reviewButton")),
vec![Event::Trigger(Trigger::Click(By::Css(".reviewButton")))],
vec![Event::Trigger(Trigger::Click(By::Id("payment-submit-btn")))],
),
Event::Assert(Assert::IsPresent("status")),
Event::Assert(Assert::IsPresent("processing")), // This connector status will be processing for one day
],
)
.await?;
Ok(())
}
#[test]
#[serial]
#[ignore]
fn should_make_gpay_payment_test() {
tester!(should_make_gpay_payment);
}
#[test]
#[serial]
fn should_make_paypal_payment_test() {
tester!(should_make_paypal_payment);
}
| 496 | 916 |
hyperswitch | crates/test_utils/tests/connectors/nexinets_ui.rs | .rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct NexinetsSeleniumTest;
impl SeleniumTest for NexinetsSeleniumTest {
fn get_connector_name(&self) -> String {
"nexinets".to_string()
}
}
async fn should_make_paypal_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = NexinetsSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/220"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"a.btn.btn-primary.btn-block.margin-bottm-15",
))),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded", "status=processing"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_3ds_card_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = NexinetsSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/221"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SwitchFrame(By::Id("threeDSCReqIframe"))),
Event::Trigger(Trigger::SendKeys(By::Id("otp"), "1234")),
Event::Trigger(Trigger::Click(By::Css("button#sendOtp"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded", "status=processing"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_ideal_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = NexinetsSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/222"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"a.btn.btn-primary.btn-block.margin-bottm-15",
))),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded", "status=processing"],
)),
],
)
.await?;
Ok(())
}
#[test]
#[serial]
fn should_make_paypal_payment_test() {
tester!(should_make_paypal_payment);
}
#[test]
#[serial]
fn should_make_3ds_card_payment_test() {
tester!(should_make_3ds_card_payment);
}
#[test]
#[serial]
fn should_make_ideal_payment_test() {
tester!(should_make_ideal_payment);
}
| 671 | 917 |
hyperswitch | crates/test_utils/tests/connectors/nuvei_ui.rs | .rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct NuveiSeleniumTest;
impl SeleniumTest for NuveiSeleniumTest {
fn get_connector_name(&self) -> String {
"nuvei".to_string()
}
}
async fn should_make_nuvei_3ds_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = NuveiSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000027891380961&expmonth=10&expyear=25&cvv=123&amount=200&country=US¤cy=USD"))),
Event::Assert(Assert::IsPresent("Expiry Year")),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Query(By::ClassName("title"))),
Event::Assert(Assert::Eq(Selector::Title, "ThreeDS ACS Emulator - Challenge Page")),
Event::Trigger(Trigger::Click(By::Id("btn1"))),
Event::Trigger(Trigger::Click(By::Id("btn5"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(Selector::QueryParamStr, "status=succeeded")),
]).await?;
Ok(())
}
async fn should_make_nuvei_3ds_mandate_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = NuveiSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000027891380961&expmonth=10&expyear=25&cvv=123&amount=200&country=US¤cy=USD&setup_future_usage=off_session&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=in%20sit&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=7000&mandate_data[mandate_type][multi_use][currency]=USD&mandate_data[mandate_type][multi_use][start_date]=2022-09-10T00:00:00Z&mandate_data[mandate_type][multi_use][end_date]=2023-09-10T00:00:00Z&mandate_data[mandate_type][multi_use][metadata][frequency]=13&return_url={CHECKOUT_BASE_URL}/payments"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Query(By::ClassName("title"))),
Event::Assert(Assert::Eq(Selector::Title, "ThreeDS ACS Emulator - Challenge Page")),
Event::Trigger(Trigger::Click(By::Id("btn1"))),
Event::Trigger(Trigger::Click(By::Id("btn5"))),
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("man_")),//mandate id prefix is present
]).await?;
Ok(())
}
async fn should_make_nuvei_gpay_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = NuveiSeleniumTest {};
conn.make_gpay_payment(c,
&format!("{CHECKOUT_BASE_URL}/gpay?gatewayname=nuveidigital&gatewaymerchantid=googletest&amount=10.00&country=IN¤cy=USD"),
vec![
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
async fn should_make_nuvei_pypl_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = NuveiSeleniumTest {};
conn.make_paypal_payment(
c,
&format!("{CHECKOUT_BASE_URL}/saved/5"),
vec![
Event::Trigger(Trigger::Click(By::Id("payment-submit-btn"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_nuvei_giropay_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = NuveiSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/bank-redirect?amount=1.00&country=DE¤cy=EUR&paymentmethod=giropay"))),
Event::Trigger(Trigger::Click(By::Id("bank-redirect-btn"))),
Event::Assert(Assert::IsPresent("You are about to make a payment using the Giropay service.")),
Event::Trigger(Trigger::Click(By::Id("ctl00_ctl00_mainContent_btnConfirm"))),
Event::RunIf(Assert::IsPresent("Bank suchen"), vec![
Event::Trigger(Trigger::SendKeys(By::Id("bankSearch"), "GIROPAY Testbank 1")),
Event::Trigger(Trigger::Click(By::Id("GIROPAY Testbank 1"))),
]),
Event::Assert(Assert::IsPresent("GIROPAY Testbank 1")),
Event::Trigger(Trigger::Click(By::Css("button[name='claimCheckoutButton']"))),
Event::Assert(Assert::IsPresent("sandbox.paydirekt")),
Event::Trigger(Trigger::Click(By::Id("submitButton"))),
Event::Trigger(Trigger::Sleep(5)),
Event::Trigger(Trigger::SwitchTab(Position::Next)),
Event::Assert(Assert::IsPresent("Sicher bezahlt!")),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(Selector::QueryParamStr, vec!["status=succeeded", "status=processing"]))
]).await?;
Ok(())
}
async fn should_make_nuvei_ideal_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = NuveiSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/bank-redirect?amount=10.00&country=NL¤cy=EUR&paymentmethod=ideal&processingbank=ing"))),
Event::Trigger(Trigger::Click(By::Id("bank-redirect-btn"))),
Event::Assert(Assert::IsPresent("Your account will be debited:")),
Event::Trigger(Trigger::SelectOption(By::Id("ctl00_ctl00_mainContent_ServiceContent_ddlBanks"), "ING Simulator")),
Event::Trigger(Trigger::Click(By::Id("ctl00_ctl00_mainContent_btnConfirm"))),
Event::Assert(Assert::IsPresent("IDEALFORTIS")),
Event::Trigger(Trigger::Sleep(5)),
Event::Trigger(Trigger::Click(By::Id("ctl00_mainContent_btnGo"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(Selector::QueryParamStr, vec!["status=succeeded", "status=processing"]))
]).await?;
Ok(())
}
async fn should_make_nuvei_sofort_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = NuveiSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/bank-redirect?amount=10.00&country=DE¤cy=EUR&paymentmethod=sofort"))),
Event::Trigger(Trigger::Click(By::Id("bank-redirect-btn"))),
Event::Assert(Assert::IsPresent("SOFORT")),
Event::Trigger(Trigger::ChangeQueryParam("sender_holder", "John Doe")),
Event::Trigger(Trigger::Click(By::Id("ctl00_mainContent_btnGo"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(Selector::QueryParamStr, vec!["status=succeeded", "status=processing"]))
]).await?;
Ok(())
}
async fn should_make_nuvei_eps_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = NuveiSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/bank-redirect?amount=10.00&country=AT¤cy=EUR&paymentmethod=eps&processingbank=ing"))),
Event::Trigger(Trigger::Click(By::Id("bank-redirect-btn"))),
Event::Assert(Assert::IsPresent("You are about to make a payment using the EPS service.")),
Event::Trigger(Trigger::SendKeys(By::Id("ctl00_ctl00_mainContent_ServiceContent_txtCustomerName"), "John Doe")),
Event::Trigger(Trigger::Click(By::Id("ctl00_ctl00_mainContent_btnConfirm"))),
Event::Assert(Assert::IsPresent("Simulator")),
Event::Trigger(Trigger::SelectOption(By::Css("select[name='result']"), "Succeeded")),
Event::Trigger(Trigger::Click(By::Id("submitbutton"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(Selector::QueryParamStr, vec!["status=succeeded", "status=processing"]))
]).await?;
Ok(())
}
#[test]
#[serial]
fn should_make_nuvei_3ds_payment_test() {
tester!(should_make_nuvei_3ds_payment);
}
#[test]
#[serial]
fn should_make_nuvei_3ds_mandate_payment_test() {
tester!(should_make_nuvei_3ds_mandate_payment);
}
#[test]
#[serial]
fn should_make_nuvei_gpay_payment_test() {
tester!(should_make_nuvei_gpay_payment);
}
#[test]
#[serial]
fn should_make_nuvei_pypl_payment_test() {
tester!(should_make_nuvei_pypl_payment);
}
#[test]
#[serial]
fn should_make_nuvei_giropay_payment_test() {
tester!(should_make_nuvei_giropay_payment);
}
#[test]
#[serial]
fn should_make_nuvei_ideal_payment_test() {
tester!(should_make_nuvei_ideal_payment);
}
#[test]
#[serial]
fn should_make_nuvei_sofort_payment_test() {
tester!(should_make_nuvei_sofort_payment);
}
#[test]
#[serial]
fn should_make_nuvei_eps_payment_test() {
tester!(should_make_nuvei_eps_payment);
}
| 2,482 | 918 |
hyperswitch | crates/test_utils/tests/connectors/main.rs | .rs | #![allow(
clippy::expect_used,
clippy::panic,
clippy::unwrap_in_result,
clippy::unwrap_used,
clippy::print_stderr
)]
mod aci_ui;
mod adyen_uk_ui;
mod adyen_uk_wh_ui;
mod airwallex_ui;
mod authorizedotnet_ui;
mod authorizedotnet_wh_ui;
mod bambora_ui;
mod bluesnap_ui;
mod bluesnap_wh_ui;
mod checkout_ui;
mod checkout_wh_ui;
mod globalpay_ui;
mod mollie_ui;
mod multisafepay_ui;
mod nexinets_ui;
mod noon_ui;
mod nuvei_ui;
mod paypal_ui;
mod payu_ui;
mod selenium;
mod shift4_ui;
mod stripe_ui;
mod stripe_wh_ui;
mod trustpay_3ds_ui;
mod worldline_ui;
mod zen_ui;
| 179 | 919 |
hyperswitch | crates/test_utils/tests/connectors/aci_ui.rs | .rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct AciSeleniumTest;
impl SeleniumTest for AciSeleniumTest {
fn get_connector_name(&self) -> String {
"aci".to_string()
}
}
async fn should_make_aci_card_mandate_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/180"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")), // mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("a.btn"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_aci_alipay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/213"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Id("submit-success"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_aci_interac_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/14"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("input[value='Continue payment']"))),
Event::Trigger(Trigger::Click(By::Css("input[value='Confirm']"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_aci_eps_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/208"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("input.button-body.button-short"))),
Event::Trigger(Trigger::Click(By::Css("input.button-body.button-short"))),
Event::Trigger(Trigger::Click(By::Css("input.button-body.button-short"))),
Event::Trigger(Trigger::Click(By::Css("input.button-body.button-middle"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_aci_ideal_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/211"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("input.pps-button"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_aci_sofort_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/212"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"button.large.button.primary.expand.form-submitter",
))),
Event::Trigger(Trigger::Click(By::Css(
"button.large.button.primary.expand.form-submitter",
))),
Event::Trigger(Trigger::Click(By::Css(
"button.large.button.primary.expand.form-submitter",
))),
Event::Trigger(Trigger::Click(By::Css(
"button.large.button.primary.expand.form-submitter",
))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_aci_giropay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/209"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SendKeys(By::Name("sc"), "10")),
Event::Trigger(Trigger::SendKeys(By::Name("extensionSc"), "4000")),
Event::Trigger(Trigger::SendKeys(By::Name("customerName1"), "Hopper")),
Event::Trigger(Trigger::Click(By::Css("input[value='Absenden']"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_aci_trustly_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/13"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Sleep(2)),
Event::Trigger(Trigger::Click(By::XPath(
r#"//*[@id="app"]/div[1]/div/div[2]/div/ul/div[4]/div/div[1]/div[2]/div[1]/span"#,
))),
Event::Trigger(Trigger::Click(By::Css(
"button.sc-eJocfa.sc-oeezt.cDgdS.bptgBT",
))),
Event::Trigger(Trigger::SendKeys(
By::Css("input.sc-fXgAZx.hkChHq"),
"123456789",
)),
Event::Trigger(Trigger::Click(By::Css(
"button.sc-eJocfa.sc-oeezt.cDgdS.bptgBT",
))),
Event::Trigger(Trigger::SendKeys(
By::Css("input.sc-fXgAZx.hkChHq"),
"783213",
)),
Event::Trigger(Trigger::Click(By::Css(
"button.sc-eJocfa.sc-oeezt.cDgdS.bptgBT",
))),
Event::Trigger(Trigger::Click(By::Css("div.sc-jJMGnK.laKGqb"))),
Event::Trigger(Trigger::Click(By::Css(
"button.sc-eJocfa.sc-oeezt.cDgdS.bptgBT",
))),
Event::Trigger(Trigger::SendKeys(
By::Css("input.sc-fXgAZx.hkChHq"),
"355508",
)),
Event::Trigger(Trigger::Click(By::Css(
"button.sc-eJocfa.sc-oeezt.cDgdS.bptgBT",
))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_aci_przelewy24_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AciSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/12"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Id("pf31"))),
Event::Trigger(Trigger::Click(By::Css(
"button.btn.btn-lg.btn-info.btn-block",
))),
Event::Trigger(Trigger::Click(By::Css(
"button.btn.btn-success.btn-lg.accept-button",
))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
#[test]
#[serial]
fn should_make_aci_card_mandate_payment_test() {
tester!(should_make_aci_card_mandate_payment);
}
#[test]
#[serial]
fn should_make_aci_alipay_payment_test() {
tester!(should_make_aci_alipay_payment);
}
#[test]
#[serial]
fn should_make_aci_interac_payment_test() {
tester!(should_make_aci_interac_payment);
}
#[test]
#[serial]
fn should_make_aci_eps_payment_test() {
tester!(should_make_aci_eps_payment);
}
#[test]
#[serial]
fn should_make_aci_ideal_payment_test() {
tester!(should_make_aci_ideal_payment);
}
#[test]
#[serial]
fn should_make_aci_sofort_payment_test() {
tester!(should_make_aci_sofort_payment);
}
#[test]
#[serial]
fn should_make_aci_giropay_payment_test() {
tester!(should_make_aci_giropay_payment);
}
#[test]
#[serial]
fn should_make_aci_trustly_payment_test() {
tester!(should_make_aci_trustly_payment);
}
#[test]
#[serial]
fn should_make_aci_przelewy24_payment_test() {
tester!(should_make_aci_przelewy24_payment);
}
| 2,235 | 920 |
hyperswitch | crates/test_utils/tests/connectors/globalpay_ui.rs | .rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct GlobalpaySeleniumTest;
impl SeleniumTest for GlobalpaySeleniumTest {
fn get_connector_name(&self) -> String {
"globalpay".to_string()
}
}
async fn should_make_gpay_payment(driver: WebDriver) -> Result<(), WebDriverError> {
let conn = GlobalpaySeleniumTest {};
let pub_key = conn
.get_configs()
.automation_configs
.unwrap()
.globalpay_gateway_merchant_id
.unwrap();
conn.make_gpay_payment(driver,
&format!("{CHECKOUT_BASE_URL}/gpay?amount=10.00&country=US¤cy=USD&gatewayname=globalpayments&gatewaymerchantid={pub_key}"),
vec![
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
async fn should_make_globalpay_paypal_payment(driver: WebDriver) -> Result<(), WebDriverError> {
let conn = GlobalpaySeleniumTest {};
conn.make_paypal_payment(
driver,
&format!("{CHECKOUT_BASE_URL}/saved/46"),
vec![
Event::Trigger(Trigger::Click(By::Id("payment-submit-btn"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_globalpay_ideal_payment(driver: WebDriver) -> Result<(), WebDriverError> {
let conn = GlobalpaySeleniumTest {};
conn.make_redirection_payment(
driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/53"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Choose your Bank")),
Event::Trigger(Trigger::Click(By::Css("button.btn.btn-primary"))),
Event::Assert(Assert::IsPresent("Login to your Online Banking Account")),
Event::Trigger(Trigger::Click(By::Css("button.btn.btn-primary"))),
Event::Assert(Assert::IsPresent("Transaction Authentication")),
Event::Trigger(Trigger::Click(By::Css("button.btn.btn-primary"))),
Event::Assert(Assert::IsPresent("Payment Successful")),
Event::Trigger(Trigger::Click(By::Css("button.btn.btn-primary"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded", "status=processing"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_globalpay_giropay_payment(driver: WebDriver) -> Result<(), WebDriverError> {
let conn = GlobalpaySeleniumTest {};
conn.make_redirection_payment(
driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/59"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Choose your Bank")),
Event::Trigger(Trigger::Click(By::Css("button.btn.btn-primary"))),
Event::Assert(Assert::IsPresent("Login to your Online Banking Account")),
Event::Trigger(Trigger::Click(By::Css("button.btn.btn-primary"))),
Event::Assert(Assert::IsPresent("Transaction Authentication")),
Event::Trigger(Trigger::Click(By::Css("button.btn.btn-primary"))),
Event::Assert(Assert::IsPresent("Payment Successful")),
Event::Trigger(Trigger::Click(By::Css("button.btn.btn-primary"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded", "status=processing"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_globalpay_eps_payment(driver: WebDriver) -> Result<(), WebDriverError> {
let conn = GlobalpaySeleniumTest {};
conn.make_redirection_payment(
driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/50"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Choose your Bank")),
Event::Trigger(Trigger::Click(By::Css("button.btn.btn-primary"))),
Event::Assert(Assert::IsPresent("Login to your Online Banking Account")),
Event::Trigger(Trigger::Click(By::Css("button.btn.btn-primary"))),
Event::Assert(Assert::IsPresent("Transaction Authentication")),
Event::Trigger(Trigger::Click(By::Css("button.btn.btn-primary"))),
Event::Assert(Assert::IsPresent("Payment Successful")),
Event::Trigger(Trigger::Click(By::Css("button.btn.btn-primary"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded", "status=processing"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_globalpay_sofort_payment(driver: WebDriver) -> Result<(), WebDriverError> {
let conn = GlobalpaySeleniumTest {};
conn.make_redirection_payment(
driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/63"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::RunIf(
Assert::IsPresent("Wählen"),
vec![Event::Trigger(Trigger::Click(By::Css("p.description")))],
),
Event::Assert(Assert::IsPresent("Demo Bank")),
Event::Trigger(Trigger::SendKeys(
By::Id("BackendFormLOGINNAMEUSERID"),
"12345",
)),
Event::Trigger(Trigger::SendKeys(By::Id("BackendFormUSERPIN"), "1234")),
Event::Trigger(Trigger::Click(By::Css(
"button.button-right.primary.has-indicator",
))),
Event::RunIf(
Assert::IsPresent("Kontoauswahl"),
vec![Event::Trigger(Trigger::Click(By::Css(
"button.button-right.primary.has-indicator",
)))],
),
Event::Assert(Assert::IsPresent("PPRO Payment Services Ltd.")),
Event::Trigger(Trigger::SendKeys(By::Id("BackendFormTan"), "12345")),
Event::Trigger(Trigger::Click(By::Css(
"button.button-right.primary.has-indicator",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded", "status=processing"],
)),
],
)
.await?;
Ok(())
}
#[test]
#[serial]
fn should_make_gpay_payment_test() {
tester!(should_make_gpay_payment);
}
#[test]
#[serial]
fn should_make_globalpay_paypal_payment_test() {
tester!(should_make_globalpay_paypal_payment);
}
#[test]
#[serial]
fn should_make_globalpay_ideal_payment_test() {
tester!(should_make_globalpay_ideal_payment);
}
#[test]
#[serial]
fn should_make_globalpay_giropay_payment_test() {
tester!(should_make_globalpay_giropay_payment);
}
#[test]
#[serial]
fn should_make_globalpay_eps_payment_test() {
tester!(should_make_globalpay_eps_payment);
}
#[test]
#[serial]
fn should_make_globalpay_sofort_payment_test() {
tester!(should_make_globalpay_sofort_payment);
}
| 1,705 | 921 |
hyperswitch | crates/test_utils/tests/connectors/mollie_ui.rs | .rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct MollieSeleniumTest;
impl SeleniumTest for MollieSeleniumTest {
fn get_connector_name(&self) -> String {
"mollie".to_string()
}
}
async fn should_make_mollie_paypal_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = MollieSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/32"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Test profile")),
Event::Trigger(Trigger::Click(By::Css("input[value='paid']"))),
Event::Trigger(Trigger::Click(By::Css(
"button[class='button form__button']",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_mollie_sofort_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = MollieSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/29"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Test profile")),
Event::Trigger(Trigger::Click(By::Css("input[value='paid']"))),
Event::Trigger(Trigger::Click(By::Css(
"button[class='button form__button']",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_mollie_ideal_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn: MollieSeleniumTest = MollieSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/36"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Test profile")),
Event::Trigger(Trigger::Click(By::ClassName(
"payment-method-list--bordered",
))),
Event::Assert(Assert::IsPresent("Test profile")),
Event::Trigger(Trigger::Click(By::Css("input[value='paid']"))),
Event::Trigger(Trigger::Click(By::Css(
"button[class='button form__button']",
))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_mollie_eps_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = MollieSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/38"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Test profile")),
Event::Trigger(Trigger::Click(By::Css("input[value='paid']"))),
Event::Trigger(Trigger::Click(By::Css(
"button[class='button form__button']",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_mollie_giropay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = MollieSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/41"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Test profile")),
Event::Trigger(Trigger::Click(By::Css("input[value='paid']"))),
Event::Trigger(Trigger::Click(By::Css(
"button[class='button form__button']",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_mollie_bancontact_card_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = MollieSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/86"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Test profile")),
Event::Trigger(Trigger::Click(By::Css("input[value='paid']"))),
Event::Trigger(Trigger::Click(By::Css(
"button[class='button form__button']",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_mollie_przelewy24_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = MollieSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/87"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Test profile")),
Event::Trigger(Trigger::Click(By::Css("input[value='paid']"))),
Event::Trigger(Trigger::Click(By::Css(
"button[class='button form__button']",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_mollie_3ds_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = MollieSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/148"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Test profile")),
Event::Trigger(Trigger::Click(By::Css("input[value='paid']"))),
Event::Trigger(Trigger::Click(By::Css(
"button[class='button form__button']",
))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
#[test]
#[serial]
fn should_make_mollie_paypal_payment_test() {
tester!(should_make_mollie_paypal_payment);
}
#[test]
#[serial]
fn should_make_mollie_sofort_payment_test() {
tester!(should_make_mollie_sofort_payment);
}
#[test]
#[serial]
fn should_make_mollie_ideal_payment_test() {
tester!(should_make_mollie_ideal_payment);
}
#[test]
#[serial]
fn should_make_mollie_eps_payment_test() {
tester!(should_make_mollie_eps_payment);
}
#[test]
#[serial]
fn should_make_mollie_giropay_payment_test() {
tester!(should_make_mollie_giropay_payment);
}
#[test]
#[serial]
fn should_make_mollie_bancontact_card_payment_test() {
tester!(should_make_mollie_bancontact_card_payment);
}
#[test]
#[serial]
fn should_make_mollie_przelewy24_payment_test() {
tester!(should_make_mollie_przelewy24_payment);
}
#[test]
#[serial]
fn should_make_mollie_3ds_payment_test() {
tester!(should_make_mollie_3ds_payment);
}
| 1,898 | 922 |
hyperswitch | crates/test_utils/tests/connectors/noon_ui.rs | .rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct NoonSeleniumTest;
impl SeleniumTest for NoonSeleniumTest {
fn get_connector_name(&self) -> String {
"noon".to_string()
}
}
async fn should_make_noon_3ds_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = NoonSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/176"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SwitchFrame(By::Id("redirectTo3ds1Frame"))),
Event::Trigger(Trigger::SwitchFrame(By::Css("iframe[frameborder='0']"))),
Event::Trigger(Trigger::SendKeys(By::Css("input.input-field"), "1234")),
Event::Trigger(Trigger::Click(By::Css("input.button.primary"))),
Event::Trigger(Trigger::Sleep(5)),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_noon_3ds_mandate_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = NoonSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/214"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SwitchFrame(By::Id("redirectTo3ds1Frame"))),
Event::Trigger(Trigger::SwitchFrame(By::Css("iframe[frameborder='0']"))),
Event::Trigger(Trigger::SendKeys(By::Css("input.input-field"), "1234")),
Event::Trigger(Trigger::Click(By::Css("input.button.primary"))),
Event::Trigger(Trigger::Sleep(5)),
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")), // mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("a.btn"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_noon_non_3ds_mandate_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = NoonSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/215"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")), // mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("a.btn"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
#[test]
#[serial]
fn should_make_noon_3ds_payment_test() {
tester!(should_make_noon_3ds_payment);
}
#[test]
#[serial]
fn should_make_noon_3ds_mandate_payment_test() {
tester!(should_make_noon_3ds_mandate_payment);
}
#[test]
#[serial]
fn should_make_noon_non_3ds_mandate_payment_test() {
tester!(should_make_noon_non_3ds_mandate_payment);
}
| 866 | 923 |
hyperswitch | crates/test_utils/tests/connectors/paypal_ui.rs | .rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct PaypalSeleniumTest;
impl SeleniumTest for PaypalSeleniumTest {
fn get_connector_name(&self) -> String {
"paypal".to_string()
}
}
async fn should_make_paypal_paypal_wallet_payment(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = PaypalSeleniumTest {};
conn.make_paypal_payment(
web_driver,
&format!("{CHECKOUT_BASE_URL}/saved/21"),
vec![
Event::Trigger(Trigger::Click(By::Css("#payment-submit-btn"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=processing"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_paypal_ideal_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = PaypalSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/181"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Name("Successful"))),
Event::Assert(Assert::IsPresent("processing")),
],
)
.await?;
Ok(())
}
async fn should_make_paypal_giropay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = PaypalSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/233"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Name("Successful"))),
Event::Assert(Assert::IsPresent("processing")),
],
)
.await?;
Ok(())
}
async fn should_make_paypal_eps_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = PaypalSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/234"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Name("Successful"))),
Event::Assert(Assert::IsPresent("processing")),
],
)
.await?;
Ok(())
}
async fn should_make_paypal_sofort_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = PaypalSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/235"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Name("Successful"))),
Event::Assert(Assert::IsPresent("processing")),
],
)
.await?;
Ok(())
}
#[test]
#[serial]
fn should_make_paypal_paypal_wallet_payment_test() {
tester!(should_make_paypal_paypal_wallet_payment);
}
#[test]
#[serial]
fn should_make_paypal_ideal_payment_test() {
tester!(should_make_paypal_ideal_payment);
}
#[test]
#[serial]
fn should_make_paypal_giropay_payment_test() {
tester!(should_make_paypal_giropay_payment);
}
#[test]
#[serial]
fn should_make_paypal_eps_payment_test() {
tester!(should_make_paypal_eps_payment);
}
#[test]
#[serial]
fn should_make_paypal_sofort_payment_test() {
tester!(should_make_paypal_sofort_payment);
}
| 845 | 924 |
hyperswitch | crates/test_utils/tests/connectors/stripe_ui.rs | .rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct StripeSeleniumTest;
impl SeleniumTest for StripeSeleniumTest {
fn get_connector_name(&self) -> String {
"stripe".to_string()
}
}
async fn should_make_3ds_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000000000003063&expmonth=10&expyear=25&cvv=123&amount=100&country=US¤cy=USD"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Id("test-source-authorize-3ds"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(Selector::QueryParamStr, "status=succeeded")),
]).await?;
Ok(())
}
async fn should_make_3ds_mandate_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000002500003155&expmonth=10&expyear=25&cvv=123&amount=10&country=US¤cy=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD&return_url={CHECKOUT_BASE_URL}/payments"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Id("test-source-authorize-3ds"))),
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
async fn should_fail_recurring_payment_due_to_authentication(
c: WebDriver,
) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000002760003184&expmonth=10&expyear=25&cvv=123&amount=10&country=US¤cy=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD&return_url={CHECKOUT_BASE_URL}/payments"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Id("test-source-authorize-3ds"))),
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Your card was declined. This transaction requires authentication.")),
]).await?;
Ok(())
}
async fn should_make_3ds_mandate_with_zero_dollar_payment(
c: WebDriver,
) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(c, vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/card?cname=CL-BRW1&ccnum=4000002500003155&expmonth=10&expyear=25&cvv=123&amount=0&country=US¤cy=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD&return_url={CHECKOUT_BASE_URL}/payments"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Id("test-source-authorize-3ds"))),
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
// Need to be handled as mentioned in https://stripe.com/docs/payments/save-and-reuse?platform=web#charge-saved-payment-method
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
async fn should_make_gpay_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
let pub_key = conn
.get_configs()
.automation_configs
.unwrap()
.stripe_pub_key
.unwrap();
conn.make_gpay_payment(c,
&format!("{CHECKOUT_BASE_URL}/gpay?gatewayname=stripe&gpaycustomfields[stripe:version]=2018-10-31&gpaycustomfields[stripe:publishableKey]={pub_key}&amount=70.00&country=US¤cy=USD"),
vec![
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
async fn should_make_gpay_mandate_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
let pub_key = conn
.get_configs()
.automation_configs
.unwrap()
.stripe_pub_key
.unwrap();
conn.make_gpay_payment(c,
&format!("{CHECKOUT_BASE_URL}/gpay?gatewayname=stripe&gpaycustomfields[stripe:version]=2018-10-31&gpaycustomfields[stripe:publishableKey]={pub_key}&amount=70.00&country=US¤cy=USD&mandate_data[customer_acceptance][acceptance_type]=offline&mandate_data[customer_acceptance][accepted_at]=1963-05-03T04:07:52.723Z&mandate_data[customer_acceptance][online][ip_address]=127.0.0.1&mandate_data[customer_acceptance][online][user_agent]=amet%20irure%20esse&mandate_data[mandate_type][multi_use][amount]=700&mandate_data[mandate_type][multi_use][currency]=USD"),
vec![
Event::Assert(Assert::IsPresent("succeeded")),
Event::Assert(Assert::IsPresent("Mandate ID")),
Event::Assert(Assert::IsPresent("man_")),// mandate id starting with man_
Event::Trigger(Trigger::Click(By::Css("#pm-mandate-btn a"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
#[ignore = "Different flows"]
//https://stripe.com/docs/testing#regulatory-cards
async fn should_make_stripe_klarna_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/19"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SwitchFrame(By::Id("klarna-apf-iframe"))),
Event::RunIf(
Assert::IsPresent("Let’s verify your phone"),
vec![
Event::Trigger(Trigger::SendKeys(By::Id("phone"), "9123456789")),
Event::Trigger(Trigger::Click(By::Id("onContinue"))),
Event::Trigger(Trigger::SendKeys(By::Id("otp_field"), "123456")),
],
),
Event::RunIf(
Assert::IsPresent("We've updated our Shopping terms"),
vec![Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='kaf-button']",
)))],
),
Event::RunIf(
Assert::IsPresent("Pick a plan"),
vec![Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='pick-plan']",
)))],
),
Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='confirm-and-pay']",
))),
Event::RunIf(
Assert::IsPresent("Fewer clicks"),
vec![Event::Trigger(Trigger::Click(By::Css(
"button[data-testid='SmoothCheckoutPopUp:skip']",
)))],
),
Event::Trigger(Trigger::SwitchTab(Position::Prev)),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_afterpay_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/22"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"a[class='common-Button common-Button--default']",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_stripe_alipay_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/35"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"button[class='common-Button common-Button--default']",
))),
Event::Trigger(Trigger::Sleep(5)),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_stripe_ideal_bank_redirect_payment(
c: WebDriver,
) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/2"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"a[class='common-Button common-Button--default']",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_stripe_giropay_bank_redirect_payment(
c: WebDriver,
) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/1"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"a[class='common-Button common-Button--default']",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_stripe_eps_bank_redirect_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/26"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"a[class='common-Button common-Button--default']",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_stripe_bancontact_card_redirect_payment(
c: WebDriver,
) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/28"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"a[class='common-Button common-Button--default']",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_stripe_p24_redirect_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/31"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"a[class='common-Button common-Button--default']",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_stripe_sofort_redirect_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/34"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"a[class='common-Button common-Button--default']",
))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=processing", "status=succeeded"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_stripe_ach_bank_debit_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/56"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::SendKeys(
By::Css("input[class='p-CodePuncher-controllingInput']"),
"11AA",
)),
Event::Trigger(Trigger::Click(By::Css(
"div[class='SubmitButton-IconContainer']",
))),
Event::Assert(Assert::IsPresent("Thanks for your payment")),
Event::Assert(Assert::IsPresent("You completed a payment")),
],
)
.await?;
Ok(())
}
async fn should_make_stripe_sepa_bank_debit_payment(c: WebDriver) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/67"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Status")),
Event::Assert(Assert::IsPresent("processing")),
],
)
.await?;
Ok(())
}
async fn should_make_stripe_affirm_paylater_payment(
driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = StripeSeleniumTest {};
conn.make_affirm_payment(
driver,
&format!("{CHECKOUT_BASE_URL}/saved/110"),
vec![Event::Assert(Assert::IsPresent("succeeded"))],
)
.await?;
Ok(())
}
#[test]
#[serial]
fn should_make_3ds_payment_test() {
tester!(should_make_3ds_payment);
}
#[test]
#[serial]
fn should_make_3ds_mandate_payment_test() {
tester!(should_make_3ds_mandate_payment);
}
#[test]
#[serial]
fn should_fail_recurring_payment_due_to_authentication_test() {
tester!(should_fail_recurring_payment_due_to_authentication);
}
#[test]
#[serial]
fn should_make_3ds_mandate_with_zero_dollar_payment_test() {
tester!(should_make_3ds_mandate_with_zero_dollar_payment);
}
#[test]
#[serial]
fn should_make_gpay_payment_test() {
tester!(should_make_gpay_payment);
}
#[test]
#[serial]
#[ignore]
fn should_make_gpay_mandate_payment_test() {
tester!(should_make_gpay_mandate_payment);
}
#[test]
#[serial]
fn should_make_stripe_klarna_payment_test() {
tester!(should_make_stripe_klarna_payment);
}
#[test]
#[serial]
fn should_make_afterpay_payment_test() {
tester!(should_make_afterpay_payment);
}
#[test]
#[serial]
fn should_make_stripe_alipay_payment_test() {
tester!(should_make_stripe_alipay_payment);
}
#[test]
#[serial]
fn should_make_stripe_ideal_bank_redirect_payment_test() {
tester!(should_make_stripe_ideal_bank_redirect_payment);
}
#[test]
#[serial]
fn should_make_stripe_giropay_bank_redirect_payment_test() {
tester!(should_make_stripe_giropay_bank_redirect_payment);
}
#[test]
#[serial]
fn should_make_stripe_eps_bank_redirect_payment_test() {
tester!(should_make_stripe_eps_bank_redirect_payment);
}
#[test]
#[serial]
fn should_make_stripe_bancontact_card_redirect_payment_test() {
tester!(should_make_stripe_bancontact_card_redirect_payment);
}
#[test]
#[serial]
fn should_make_stripe_p24_redirect_payment_test() {
tester!(should_make_stripe_p24_redirect_payment);
}
#[test]
#[serial]
fn should_make_stripe_sofort_redirect_payment_test() {
tester!(should_make_stripe_sofort_redirect_payment);
}
#[test]
#[serial]
fn should_make_stripe_ach_bank_debit_payment_test() {
tester!(should_make_stripe_ach_bank_debit_payment);
}
#[test]
#[serial]
fn should_make_stripe_sepa_bank_debit_payment_test() {
tester!(should_make_stripe_sepa_bank_debit_payment);
}
#[test]
#[serial]
fn should_make_stripe_affirm_paylater_payment_test() {
tester!(should_make_stripe_affirm_paylater_payment);
}
| 4,825 | 925 |
hyperswitch | crates/test_utils/tests/connectors/multisafepay_ui.rs | .rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct MultisafepaySeleniumTest;
impl SeleniumTest for MultisafepaySeleniumTest {
fn get_connector_name(&self) -> String {
"multisafepay".to_string()
}
}
async fn should_make_multisafepay_3ds_payment_success(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = MultisafepaySeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/207"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_multisafepay_3ds_payment_failed(
web_driver: WebDriver,
) -> Result<(), WebDriverError> {
let conn = MultisafepaySeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/93"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("failed")),
],
)
.await?;
Ok(())
}
async fn should_make_gpay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = MultisafepaySeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/153"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css("button[class='btn btn-default']"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
async fn should_make_paypal_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = MultisafepaySeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/154"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Css(
"button[class='btn btn-msp-success btn-block']",
))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
#[test]
#[serial]
fn should_make_multisafepay_3ds_payment_success_test() {
tester!(should_make_multisafepay_3ds_payment_success);
}
#[test]
#[serial]
fn should_make_multisafepay_3ds_payment_failed_test() {
tester!(should_make_multisafepay_3ds_payment_failed);
}
#[test]
#[serial]
#[ignore]
fn should_make_gpay_payment_test() {
tester!(should_make_gpay_payment);
}
#[test]
#[serial]
fn should_make_paypal_payment_test() {
tester!(should_make_paypal_payment);
}
| 724 | 926 |
hyperswitch | crates/test_utils/tests/connectors/adyen_uk_wh_ui.rs | .rs | use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct AdyenSeleniumTest;
impl SeleniumTest for AdyenSeleniumTest {
fn get_connector_name(&self) -> String {
"adyen_uk".to_string()
}
}
async fn should_make_webhook(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AdyenSeleniumTest {};
conn.make_webhook_test(
web_driver,
&format!("{CHECKOUT_BASE_URL}/saved/104"),
vec![
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
10,
"succeeded",
)
.await?;
Ok(())
}
#[test]
fn should_make_webhook_test() {
tester!(should_make_webhook);
}
| 190 | 927 |
hyperswitch | crates/test_utils/tests/connectors/checkout_ui.rs | .rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct CheckoutSeleniumTest;
impl SeleniumTest for CheckoutSeleniumTest {
fn get_connector_name(&self) -> String {
"checkout".to_string()
}
}
async fn should_make_frictionless_3ds_payment(c: WebDriver) -> Result<(), WebDriverError> {
let mycon = CheckoutSeleniumTest {};
mycon
.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/18"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("Google Search")),
Event::Trigger(Trigger::Sleep(5)), //url gets updated only after some time, so need this timeout to solve the issue
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded", "status=processing"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_3ds_payment(c: WebDriver) -> Result<(), WebDriverError> {
let mycon = CheckoutSeleniumTest {};
mycon
.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/20"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Sleep(5)), //url gets updated only after some time, so need this timeout to solve the issue
Event::Trigger(Trigger::SwitchFrame(By::Name("cko-3ds2-iframe"))),
Event::Trigger(Trigger::SendKeys(By::Id("password"), "Checkout1!")),
Event::Trigger(Trigger::Click(By::Id("txtButton"))),
Event::Trigger(Trigger::Sleep(2)),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded", "status=processing"],
)),
],
)
.await?;
Ok(())
}
async fn should_make_gpay_payment(c: WebDriver) -> Result<(), WebDriverError> {
let mycon = CheckoutSeleniumTest {};
mycon
.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/73"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Sleep(10)), //url gets updated only after some time, so need this timeout to solve the issue
Event::Trigger(Trigger::SwitchFrame(By::Name("cko-3ds2-iframe"))),
Event::Trigger(Trigger::SendKeys(By::Id("password"), "Checkout1!")),
Event::Trigger(Trigger::Click(By::Id("txtButton"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::ContainsAny(
Selector::QueryParamStr,
vec!["status=succeeded", "status=processing"],
)),
],
)
.await?;
Ok(())
}
#[test]
#[serial]
fn should_make_frictionless_3ds_payment_test() {
tester!(should_make_frictionless_3ds_payment);
}
#[test]
#[serial]
fn should_make_3ds_payment_test() {
tester!(should_make_3ds_payment);
}
#[test]
#[serial]
#[ignore]
fn should_make_gpay_payment_test() {
tester!(should_make_gpay_payment);
}
| 796 | 928 |
hyperswitch | crates/test_utils/tests/connectors/airwallex_ui.rs | .rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct AirwallexSeleniumTest;
impl SeleniumTest for AirwallexSeleniumTest {
fn get_connector_name(&self) -> String {
"airwallex".to_string()
}
}
async fn should_make_airwallex_3ds_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AirwallexSeleniumTest {};
conn.make_redirection_payment(
web_driver,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/85"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Query(By::ClassName("title"))),
Event::Assert(Assert::Eq(
Selector::Title,
"Airwallex - Create 3D Secure Payment",
)),
Event::Trigger(Trigger::SendKeys(By::Id("challengeDataEntry"), "1234")),
Event::Trigger(Trigger::Click(By::Id("submit"))),
Event::Assert(Assert::IsPresent("Google")),
Event::Assert(Assert::Contains(
Selector::QueryParamStr,
"status=succeeded",
)),
],
)
.await?;
Ok(())
}
async fn should_make_airwallex_gpay_payment(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = AirwallexSeleniumTest {};
let merchant_name = conn
.get_configs()
.automation_configs
.unwrap()
.airwallex_merchant_name
.unwrap();
conn.make_gpay_payment(web_driver,
&format!("{CHECKOUT_BASE_URL}/gpay?gatewayname=airwallex&gatewaymerchantid={merchant_name}&amount=70.00&country=US¤cy=USD"),
vec![
Event::Trigger(Trigger::Query(By::ClassName("title"))),
Event::Assert(Assert::Eq(Selector::Title, "Airwallex - Create 3D Secure Payment")),
Event::Trigger(Trigger::SendKeys(By::Id("challengeDataEntry"), "1234")),
Event::Trigger(Trigger::Click(By::Id("submit"))),
Event::Assert(Assert::IsPresent("succeeded")),
]).await?;
Ok(())
}
#[test]
#[serial]
fn should_make_airwallex_3ds_payment_test() {
tester!(should_make_airwallex_3ds_payment);
}
#[test]
#[serial]
#[ignore]
fn should_make_airwallex_gpay_payment_test() {
tester!(should_make_airwallex_gpay_payment);
}
| 576 | 929 |
hyperswitch | crates/test_utils/tests/connectors/bambora_ui.rs | .rs | use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct BamboraSeleniumTest;
impl SeleniumTest for BamboraSeleniumTest {
fn get_connector_name(&self) -> String {
"bambora".to_string()
}
}
async fn should_make_3ds_payment(c: WebDriver) -> Result<(), WebDriverError> {
let mycon = BamboraSeleniumTest {};
mycon
.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/33"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Id("continue-transaction"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
#[test]
#[serial]
fn should_make_3ds_payment_test() {
tester!(should_make_3ds_payment);
}
| 225 | 930 |
hyperswitch | crates/test_utils/src/newman_runner.rs | .rs | use std::{
env,
fs::{self, OpenOptions},
io::{self, Write},
path::Path,
process::{exit, Command},
};
use anyhow::{Context, Result};
use clap::{arg, command, Parser, ValueEnum};
use masking::PeekInterface;
use regex::Regex;
use crate::connector_auth::{
ConnectorAuthType, ConnectorAuthentication, ConnectorAuthenticationMap,
};
#[derive(ValueEnum, Clone, Copy)]
pub enum Module {
Connector,
Users,
}
#[derive(Parser)]
#[command(version, about = "Postman collection runner using newman!", long_about = None)]
pub struct Args {
/// Admin API Key of the environment
#[arg(short, long)]
admin_api_key: String,
/// Base URL of the Hyperswitch environment
#[arg(short, long)]
base_url: String,
/// Name of the connector
#[arg(short, long)]
connector_name: Option<String>,
/// Name of the module
#[arg(short, long)]
module_name: Option<Module>,
/// Custom headers
#[arg(short = 'H', long = "header")]
custom_headers: Option<Vec<String>>,
/// Minimum delay in milliseconds to be added before sending a request
/// By default, 7 milliseconds will be the delay
#[arg(short, long, default_value_t = 7)]
delay_request: u32,
/// Folder name of specific tests
#[arg(short, long = "folder")]
folders: Option<String>,
/// Optional Verbose logs
#[arg(short, long)]
verbose: bool,
}
impl Args {
/// Getter for the `module_name` field
pub fn get_module_name(&self) -> Option<Module> {
self.module_name
}
}
pub struct ReturnArgs {
pub newman_command: Command,
pub modified_file_paths: Vec<Option<String>>,
pub collection_path: String,
}
// Generates the name of the collection JSON file for the specified connector.
// Example: CONNECTOR_NAME="stripe" -> OUTPUT: postman/collection-json/stripe.postman_collection.json
#[inline]
fn get_collection_path(name: impl AsRef<str>) -> String {
format!(
"postman/collection-json/{}.postman_collection.json",
name.as_ref()
)
}
// Generates the name of the collection directory for the specified connector.
// Example: CONNECTOR_NAME="stripe" -> OUTPUT: postman/collection-dir/stripe
#[inline]
fn get_dir_path(name: impl AsRef<str>) -> String {
format!("postman/collection-dir/{}", name.as_ref())
}
// This function currently allows you to add only custom headers.
// In future, as we scale, this can be modified based on the need
fn insert_content<T, U>(dir: T, content_to_insert: U) -> io::Result<()>
where
T: AsRef<Path>,
U: AsRef<str>,
{
let file_name = "event.prerequest.js";
let file_path = dir.as_ref().join(file_name);
// Open the file in write mode or create it if it doesn't exist
let mut file = OpenOptions::new()
.append(true)
.create(true)
.open(file_path)?;
write!(file, "{}", content_to_insert.as_ref())?;
Ok(())
}
// This function gives runner for connector or a module
pub fn generate_runner() -> Result<ReturnArgs> {
let args = Args::parse();
match args.get_module_name() {
Some(Module::Users) => generate_newman_command_for_users(),
Some(Module::Connector) => generate_newman_command_for_connector(),
// Running connector tests when no module is passed to keep the previous test behavior same
None => generate_newman_command_for_connector(),
}
}
pub fn generate_newman_command_for_users() -> Result<ReturnArgs> {
let args = Args::parse();
let base_url = args.base_url;
let admin_api_key = args.admin_api_key;
let path = env::var("CONNECTOR_AUTH_FILE_PATH")
.with_context(|| "connector authentication file path not set")?;
let authentication: ConnectorAuthentication = toml::from_str(
&fs::read_to_string(path)
.with_context(|| "connector authentication config file not found")?,
)
.with_context(|| "connector authentication file path not set")?;
let users_configs = authentication
.users
.with_context(|| "user configs not found in authentication file")?;
let collection_path = get_collection_path("users");
let mut newman_command = Command::new("newman");
newman_command.args(["run", &collection_path]);
newman_command.args(["--env-var", &format!("admin_api_key={admin_api_key}")]);
newman_command.args(["--env-var", &format!("baseUrl={base_url}")]);
newman_command.args([
"--env-var",
&format!("user_email={}", users_configs.user_email),
]);
newman_command.args([
"--env-var",
&format!(
"user_base_email_for_signup={}",
users_configs.user_base_email_for_signup
),
]);
newman_command.args([
"--env-var",
&format!(
"user_domain_for_signup={}",
users_configs.user_domain_for_signup
),
]);
newman_command.args([
"--env-var",
&format!("user_password={}", users_configs.user_password),
]);
newman_command.args([
"--env-var",
&format!("wrong_password={}", users_configs.wrong_password),
]);
newman_command.args([
"--delay-request",
format!("{}", &args.delay_request).as_str(),
]);
newman_command.arg("--color").arg("on");
if args.verbose {
newman_command.arg("--verbose");
}
Ok(ReturnArgs {
newman_command,
modified_file_paths: vec![],
collection_path,
})
}
pub fn generate_newman_command_for_connector() -> Result<ReturnArgs> {
let args = Args::parse();
let connector_name = args
.connector_name
.with_context(|| "invalid parameters: connector/module name not found in arguments")?;
let base_url = args.base_url;
let admin_api_key = args.admin_api_key;
let collection_path = get_collection_path(&connector_name);
let collection_dir_path = get_dir_path(&connector_name);
let auth_map = ConnectorAuthenticationMap::new();
let inner_map = auth_map.inner();
/*
Newman runner
Certificate keys are added through secrets in CI, so there's no need to explicitly pass it as arguments.
It can be overridden by explicitly passing certificates as arguments.
If the collection requires certificates (Stripe collection for example) during the merchant connector account create step,
then Stripe's certificates will be passed implicitly (for now).
If any other connector requires certificates to be passed, that has to be passed explicitly for now.
*/
let mut newman_command = Command::new("newman");
newman_command.args(["run", &collection_path]);
newman_command.args(["--env-var", &format!("admin_api_key={admin_api_key}")]);
newman_command.args(["--env-var", &format!("baseUrl={base_url}")]);
let custom_header_exist = check_for_custom_headers(args.custom_headers, &collection_dir_path);
// validation of connector is needed here as a work around to the limitation of the fork of newman that Hyperswitch uses
let (connector_name, modified_collection_file_paths) =
check_connector_for_dynamic_amount(&connector_name);
if let Some(auth_type) = inner_map.get(connector_name) {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => {
newman_command.args([
"--env-var",
&format!("connector_api_key={}", api_key.peek()),
]);
}
ConnectorAuthType::BodyKey { api_key, key1 } => {
newman_command.args([
"--env-var",
&format!("connector_api_key={}", api_key.peek()),
"--env-var",
&format!("connector_key1={}", key1.peek()),
]);
}
ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
} => {
newman_command.args([
"--env-var",
&format!("connector_api_key={}", api_key.peek()),
"--env-var",
&format!("connector_key1={}", key1.peek()),
"--env-var",
&format!("connector_api_secret={}", api_secret.peek()),
]);
}
ConnectorAuthType::MultiAuthKey {
api_key,
key1,
key2,
api_secret,
} => {
newman_command.args([
"--env-var",
&format!("connector_api_key={}", api_key.peek()),
"--env-var",
&format!("connector_key1={}", key1.peek()),
"--env-var",
&format!("connector_key2={}", key2.peek()),
"--env-var",
&format!("connector_api_secret={}", api_secret.peek()),
]);
}
// Handle other ConnectorAuthType variants
_ => {
eprintln!("Invalid authentication type.");
}
}
} else {
eprintln!("Connector not found.");
}
// Add additional environment variables if present
if let Ok(gateway_merchant_id) = env::var("GATEWAY_MERCHANT_ID") {
newman_command.args([
"--env-var",
&format!("gateway_merchant_id={gateway_merchant_id}"),
]);
}
if let Ok(gpay_certificate) = env::var("GPAY_CERTIFICATE") {
newman_command.args(["--env-var", &format!("certificate={gpay_certificate}")]);
}
if let Ok(gpay_certificate_keys) = env::var("GPAY_CERTIFICATE_KEYS") {
newman_command.args([
"--env-var",
&format!("certificate_keys={gpay_certificate_keys}"),
]);
}
newman_command.args([
"--delay-request",
format!("{}", &args.delay_request).as_str(),
]);
newman_command.arg("--color").arg("on");
// Add flags for running specific folders
if let Some(folders) = &args.folders {
let folder_names: Vec<String> = folders.split(',').map(|s| s.trim().to_string()).collect();
for folder_name in folder_names {
if !folder_name.contains("QuickStart") {
// This is a quick fix, "QuickStart" is intentional to have merchant account and API keys set up
// This will be replaced by a more robust and efficient account creation or reuse existing old account
newman_command.args(["--folder", "QuickStart"]);
}
newman_command.args(["--folder", &folder_name]);
}
}
if args.verbose {
newman_command.arg("--verbose");
}
Ok(ReturnArgs {
newman_command,
modified_file_paths: vec![modified_collection_file_paths, custom_header_exist],
collection_path,
})
}
pub fn check_for_custom_headers(headers: Option<Vec<String>>, path: &str) -> Option<String> {
if let Some(headers) = &headers {
for header in headers {
if let Some((key, value)) = header.split_once(':') {
let content_to_insert =
format!(r#"pm.request.headers.add({{key: "{key}", value: "{value}"}});"#);
if let Err(err) = insert_content(path, &content_to_insert) {
eprintln!("An error occurred while inserting the custom header: {err}");
}
} else {
eprintln!("Invalid header format: {}", header);
}
}
return Some(format!("{}/event.prerequest.js", path));
}
None
}
// If the connector name exists in dynamic_amount_connectors,
// the corresponding collection is modified at runtime to remove double quotes
pub fn check_connector_for_dynamic_amount(connector_name: &str) -> (&str, Option<String>) {
let collection_dir_path = get_dir_path(connector_name);
let dynamic_amount_connectors = ["nmi", "powertranz"];
if dynamic_amount_connectors.contains(&connector_name) {
return remove_quotes_for_integer_values(connector_name).unwrap_or((connector_name, None));
}
/*
If connector name does not exist in dynamic_amount_connectors but we want to run it with custom headers,
since we're running from collections directly, we'll have to export the collection again and it is much simpler.
We could directly inject the custom-headers using regex, but it is not encouraged as it is hard
to determine the place of edit.
*/
export_collection(connector_name, collection_dir_path);
(connector_name, None)
}
/*
Existing issue with the fork of newman is that, it requires you to pass variables like `{{value}}` within
double quotes without which it fails to execute.
For integer values like `amount`, this is a bummer as it flags the value stating it is of type
string and not integer.
Refactoring is done in 2 steps:
- Export the collection to json (although the json will be up-to-date, we export it again for safety)
- Use regex to replace the values which removes double quotes from integer values
Ex: \"{{amount}}\" -> {{amount}}
*/
pub fn remove_quotes_for_integer_values(
connector_name: &str,
) -> Result<(&str, Option<String>), io::Error> {
let collection_path = get_collection_path(connector_name);
let collection_dir_path = get_dir_path(connector_name);
let values_to_replace = [
"amount",
"another_random_number",
"capture_amount",
"random_number",
"refund_amount",
];
export_collection(connector_name, collection_dir_path);
let mut contents = fs::read_to_string(&collection_path)?;
for value_to_replace in values_to_replace {
if let Ok(re) = Regex::new(&format!(
r#"\\"(?P<field>\{{\{{{}\}}\}})\\""#,
value_to_replace
)) {
contents = re.replace_all(&contents, "$field").to_string();
} else {
eprintln!("Regex validation failed.");
}
let mut file = OpenOptions::new()
.write(true)
.truncate(true)
.open(&collection_path)?;
file.write_all(contents.as_bytes())?;
}
Ok((connector_name, Some(collection_path)))
}
pub fn export_collection(connector_name: &str, collection_dir_path: String) {
let collection_path = get_collection_path(connector_name);
let mut newman_command = Command::new("newman");
newman_command.args([
"dir-import".to_owned(),
collection_dir_path,
"-o".to_owned(),
collection_path.clone(),
]);
match newman_command.spawn().and_then(|mut child| child.wait()) {
Ok(exit_status) => {
if exit_status.success() {
println!("Conversion of collection from directory structure to json successful!");
} else {
eprintln!("Conversion of collection from directory structure to json failed!");
exit(exit_status.code().unwrap_or(1));
}
}
Err(err) => {
eprintln!("Failed to execute dir-import: {:?}", err);
exit(1);
}
}
}
| 3,271 | 931 |
hyperswitch | crates/test_utils/src/main.rs | .rs | #![allow(clippy::print_stdout, clippy::print_stderr)]
use std::process::{exit, Command};
use anyhow::Result;
use test_utils::newman_runner;
fn main() -> Result<()> {
let mut runner = newman_runner::generate_runner()?;
// Execute the newman command
let output = runner.newman_command.spawn();
let mut child = match output {
Ok(child) => child,
Err(err) => {
eprintln!("Failed to execute command: {err}");
exit(1);
}
};
let status = child.wait();
// Filter out None values leaving behind Some(Path)
let paths: Vec<String> = runner.modified_file_paths.into_iter().flatten().collect();
if !paths.is_empty() {
let git_status = Command::new("git").arg("restore").args(&paths).output();
match git_status {
Ok(output) if !output.status.success() => {
let stderr_str = String::from_utf8_lossy(&output.stderr);
eprintln!("Git command failed with error: {stderr_str}");
}
Ok(_) => {
println!("Git restore successful!");
}
Err(e) => {
eprintln!("Error running Git: {e}");
}
}
}
let exit_code = match status {
Ok(exit_status) => {
if exit_status.success() {
println!("Command executed successfully!");
exit_status.code().unwrap_or(0)
} else {
eprintln!("Command failed with exit code: {:?}", exit_status.code());
exit_status.code().unwrap_or(1)
}
}
Err(err) => {
eprintln!("Failed to wait for command execution: {err}");
exit(1);
}
};
exit(exit_code);
}
| 375 | 932 |
hyperswitch | crates/test_utils/src/connector_auth.rs | .rs | use std::{collections::HashMap, env};
use masking::Secret;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ConnectorAuthentication {
pub aci: Option<BodyKey>,
#[cfg(not(feature = "payouts"))]
pub adyen: Option<BodyKey>,
#[cfg(feature = "payouts")]
pub adyenplatform: Option<HeaderKey>,
#[cfg(feature = "payouts")]
pub adyen: Option<SignatureKey>,
#[cfg(not(feature = "payouts"))]
pub adyen_uk: Option<BodyKey>,
#[cfg(feature = "payouts")]
pub adyen_uk: Option<SignatureKey>,
pub airwallex: Option<BodyKey>,
pub amazonpay: Option<HeaderKey>,
pub authorizedotnet: Option<BodyKey>,
pub bambora: Option<BodyKey>,
pub bamboraapac: Option<HeaderKey>,
pub bankofamerica: Option<SignatureKey>,
pub billwerk: Option<HeaderKey>,
pub bitpay: Option<HeaderKey>,
pub bluesnap: Option<BodyKey>,
pub boku: Option<BodyKey>,
pub cashtocode: Option<BodyKey>,
pub chargebee: Option<HeaderKey>,
pub checkout: Option<SignatureKey>,
pub coinbase: Option<HeaderKey>,
pub coingate: Option<HeaderKey>,
pub cryptopay: Option<BodyKey>,
pub cybersource: Option<SignatureKey>,
pub datatrans: Option<HeaderKey>,
pub deutschebank: Option<SignatureKey>,
pub digitalvirgo: Option<HeaderKey>,
pub dlocal: Option<SignatureKey>,
#[cfg(feature = "dummy_connector")]
pub dummyconnector: Option<HeaderKey>,
pub ebanx: Option<HeaderKey>,
pub elavon: Option<HeaderKey>,
pub facilitapay: Option<BodyKey>,
pub fiserv: Option<SignatureKey>,
pub fiservemea: Option<HeaderKey>,
pub fiuu: Option<HeaderKey>,
pub forte: Option<MultiAuthKey>,
pub getnet: Option<HeaderKey>,
pub globalpay: Option<BodyKey>,
pub globepay: Option<BodyKey>,
pub gocardless: Option<HeaderKey>,
pub gpayments: Option<HeaderKey>,
pub helcim: Option<HeaderKey>,
pub hipay: Option<HeaderKey>,
pub iatapay: Option<SignatureKey>,
pub inespay: Option<HeaderKey>,
pub itaubank: Option<MultiAuthKey>,
pub jpmorgan: Option<BodyKey>,
pub juspaythreedsserver: Option<HeaderKey>,
pub mifinity: Option<HeaderKey>,
pub mollie: Option<BodyKey>,
pub moneris: Option<SignatureKey>,
pub multisafepay: Option<HeaderKey>,
pub netcetera: Option<HeaderKey>,
pub nexinets: Option<BodyKey>,
pub nexixpay: Option<HeaderKey>,
pub nomupay: Option<BodyKey>,
pub noon: Option<SignatureKey>,
pub novalnet: Option<HeaderKey>,
pub nmi: Option<HeaderKey>,
pub nuvei: Option<SignatureKey>,
pub opayo: Option<HeaderKey>,
pub opennode: Option<HeaderKey>,
pub paybox: Option<HeaderKey>,
pub payeezy: Option<SignatureKey>,
pub payme: Option<BodyKey>,
pub payone: Option<HeaderKey>,
pub paypal: Option<BodyKey>,
pub paystack: Option<HeaderKey>,
pub payu: Option<BodyKey>,
pub placetopay: Option<BodyKey>,
pub plaid: Option<BodyKey>,
pub powertranz: Option<BodyKey>,
pub prophetpay: Option<HeaderKey>,
pub rapyd: Option<BodyKey>,
pub razorpay: Option<BodyKey>,
pub recurly: Option<HeaderKey>,
pub redsys: Option<HeaderKey>,
pub shift4: Option<HeaderKey>,
pub square: Option<BodyKey>,
pub stax: Option<HeaderKey>,
pub stripe: Option<HeaderKey>,
pub stripebilling: Option<HeaderKey>,
pub taxjar: Option<HeaderKey>,
pub threedsecureio: Option<HeaderKey>,
pub thunes: Option<HeaderKey>,
pub stripe_au: Option<HeaderKey>,
pub stripe_uk: Option<HeaderKey>,
pub trustpay: Option<SignatureKey>,
pub tsys: Option<SignatureKey>,
pub unified_authentication_service: Option<HeaderKey>,
pub volt: Option<HeaderKey>,
pub wellsfargo: Option<HeaderKey>,
// pub wellsfargopayout: Option<HeaderKey>,
pub wise: Option<BodyKey>,
pub worldpay: Option<BodyKey>,
pub xendit: Option<HeaderKey>,
pub worldline: Option<SignatureKey>,
pub zen: Option<HeaderKey>,
pub zsl: Option<BodyKey>,
pub automation_configs: Option<AutomationConfigs>,
pub users: Option<UsersConfigs>,
}
impl Default for ConnectorAuthentication {
fn default() -> Self {
Self::new()
}
}
#[allow(dead_code)]
impl ConnectorAuthentication {
/// # Panics
///
/// Will panic if `CONNECTOR_AUTH_FILE_PATH` env is not set
#[allow(clippy::expect_used)]
pub fn new() -> Self {
// Do `export CONNECTOR_AUTH_FILE_PATH="/hyperswitch/crates/router/tests/connectors/sample_auth.toml"`
// before running tests in shell
let path = env::var("CONNECTOR_AUTH_FILE_PATH")
.expect("Connector authentication file path not set");
toml::from_str(
&std::fs::read_to_string(path).expect("connector authentication config file not found"),
)
.expect("Failed to read connector authentication config file")
}
}
#[derive(Clone, Debug, Deserialize)]
pub struct ConnectorAuthenticationMap(HashMap<String, ConnectorAuthType>);
impl Default for ConnectorAuthenticationMap {
fn default() -> Self {
Self::new()
}
}
// This is a temporary solution to avoid rust compiler from complaining about unused function
#[allow(dead_code)]
impl ConnectorAuthenticationMap {
pub fn inner(&self) -> &HashMap<String, ConnectorAuthType> {
&self.0
}
/// # Panics
///
/// Will panic if `CONNECTOR_AUTH_FILE_PATH` env is not set
#[allow(clippy::expect_used)]
pub fn new() -> Self {
// Do `export CONNECTOR_AUTH_FILE_PATH="/hyperswitch/crates/router/tests/connectors/sample_auth.toml"`
// before running tests in shell
let path = env::var("CONNECTOR_AUTH_FILE_PATH")
.expect("connector authentication file path not set");
// Read the file contents to a JsonString
let contents =
&std::fs::read_to_string(path).expect("Failed to read connector authentication file");
// Deserialize the JsonString to a HashMap
let auth_config: HashMap<String, toml::Value> =
toml::from_str(contents).expect("Failed to deserialize TOML file");
// auth_config contains the data in below given format:
// {
// "connector_name": Table(
// {
// "api_key": String(
// "API_Key",
// ),
// "api_secret": String(
// "Secret key",
// ),
// "key1": String(
// "key1",
// ),
// "key2": String(
// "key2",
// ),
// },
// ),
// "connector_name": Table(
// ...
// }
// auth_map refines and extracts required information
let auth_map = auth_config
.into_iter()
.map(|(connector_name, config)| {
let auth_type = match config {
toml::Value::Table(table) => {
match (
table.get("api_key"),
table.get("key1"),
table.get("api_secret"),
table.get("key2"),
) {
(Some(api_key), None, None, None) => ConnectorAuthType::HeaderKey {
api_key: Secret::new(
api_key.as_str().unwrap_or_default().to_string(),
),
},
(Some(api_key), Some(key1), None, None) => ConnectorAuthType::BodyKey {
api_key: Secret::new(
api_key.as_str().unwrap_or_default().to_string(),
),
key1: Secret::new(key1.as_str().unwrap_or_default().to_string()),
},
(Some(api_key), Some(key1), Some(api_secret), None) => {
ConnectorAuthType::SignatureKey {
api_key: Secret::new(
api_key.as_str().unwrap_or_default().to_string(),
),
key1: Secret::new(
key1.as_str().unwrap_or_default().to_string(),
),
api_secret: Secret::new(
api_secret.as_str().unwrap_or_default().to_string(),
),
}
}
(Some(api_key), Some(key1), Some(api_secret), Some(key2)) => {
ConnectorAuthType::MultiAuthKey {
api_key: Secret::new(
api_key.as_str().unwrap_or_default().to_string(),
),
key1: Secret::new(
key1.as_str().unwrap_or_default().to_string(),
),
api_secret: Secret::new(
api_secret.as_str().unwrap_or_default().to_string(),
),
key2: Secret::new(
key2.as_str().unwrap_or_default().to_string(),
),
}
}
_ => ConnectorAuthType::NoKey,
}
}
_ => ConnectorAuthType::NoKey,
};
(connector_name, auth_type)
})
.collect();
Self(auth_map)
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct HeaderKey {
pub api_key: Secret<String>,
}
impl From<HeaderKey> for ConnectorAuthType {
fn from(key: HeaderKey) -> Self {
Self::HeaderKey {
api_key: key.api_key,
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct BodyKey {
pub api_key: Secret<String>,
pub key1: Secret<String>,
}
impl From<BodyKey> for ConnectorAuthType {
fn from(key: BodyKey) -> Self {
Self::BodyKey {
api_key: key.api_key,
key1: key.key1,
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct SignatureKey {
pub api_key: Secret<String>,
pub key1: Secret<String>,
pub api_secret: Secret<String>,
}
impl From<SignatureKey> for ConnectorAuthType {
fn from(key: SignatureKey) -> Self {
Self::SignatureKey {
api_key: key.api_key,
key1: key.key1,
api_secret: key.api_secret,
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct MultiAuthKey {
pub api_key: Secret<String>,
pub key1: Secret<String>,
pub api_secret: Secret<String>,
pub key2: Secret<String>,
}
impl From<MultiAuthKey> for ConnectorAuthType {
fn from(key: MultiAuthKey) -> Self {
Self::MultiAuthKey {
api_key: key.api_key,
key1: key.key1,
api_secret: key.api_secret,
key2: key.key2,
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct AutomationConfigs {
pub hs_base_url: Option<String>,
pub hs_api_key: Option<String>,
pub hs_api_keys: Option<String>,
pub hs_webhook_url: Option<String>,
pub hs_test_env: Option<String>,
pub hs_test_browser: Option<String>,
pub chrome_profile_path: Option<String>,
pub firefox_profile_path: Option<String>,
pub pypl_email: Option<String>,
pub pypl_pass: Option<String>,
pub gmail_email: Option<String>,
pub gmail_pass: Option<String>,
pub clearpay_email: Option<String>,
pub clearpay_pass: Option<String>,
pub configs_url: Option<String>,
pub stripe_pub_key: Option<String>,
pub testcases_path: Option<String>,
pub bluesnap_gateway_merchant_id: Option<String>,
pub globalpay_gateway_merchant_id: Option<String>,
pub authorizedotnet_gateway_merchant_id: Option<String>,
pub run_minimum_steps: Option<bool>,
pub airwallex_merchant_name: Option<String>,
pub adyen_bancontact_username: Option<String>,
pub adyen_bancontact_pass: Option<String>,
}
#[derive(Default, Debug, Clone, serde::Deserialize)]
#[serde(tag = "auth_type")]
pub enum ConnectorAuthType {
HeaderKey {
api_key: Secret<String>,
},
BodyKey {
api_key: Secret<String>,
key1: Secret<String>,
},
SignatureKey {
api_key: Secret<String>,
key1: Secret<String>,
api_secret: Secret<String>,
},
MultiAuthKey {
api_key: Secret<String>,
key1: Secret<String>,
api_secret: Secret<String>,
key2: Secret<String>,
},
#[default]
NoKey,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct UsersConfigs {
pub user_email: String,
pub user_password: String,
pub wrong_password: String,
pub user_base_email_for_signup: String,
pub user_domain_for_signup: String,
}
| 2,995 | 933 |
hyperswitch | crates/test_utils/src/lib.rs | .rs | #![allow(clippy::print_stdout, clippy::print_stderr)]
pub mod connector_auth;
pub mod newman_runner;
| 25 | 934 |
hyperswitch | crates/drainer/Cargo.toml | .toml | [package]
name = "drainer"
description = "Application that reads Redis streams and executes queries in database"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
readme = "README.md"
license.workspace = true
[features]
release = ["vergen", "external_services/aws_kms"]
vergen = ["router_env/vergen"]
v1 = ["diesel_models/v1", "hyperswitch_interfaces/v1", "common_utils/v1"]
[dependencies]
actix-web = "4.5.1"
async-bb8-diesel = { git = "https://github.com/jarnura/async-bb8-diesel", rev = "53b4ab901aab7635c8215fd1c2d542c8db443094" }
async-trait = "0.1.79"
bb8 = "0.8"
clap = { version = "4.4.18", default-features = false, features = ["std", "derive", "help", "usage"] }
config = { version = "0.14.0", features = ["toml"] }
diesel = { version = "2.2.3", features = ["postgres"] }
error-stack = "0.4.1"
mime = "0.3.17"
once_cell = "1.19.0"
reqwest = { version = "0.11.27" }
serde = "1.0.197"
serde_json = "1.0.115"
serde_path_to_error = "0.1.16"
thiserror = "1.0.58"
tokio = { version = "1.37.0", features = ["macros", "rt-multi-thread"] }
# First Party Crates
common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals"] }
diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"], default-features = false }
external_services = { version = "0.1.0", path = "../external_services" }
hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces" }
masking = { version = "0.1.0", path = "../masking" }
redis_interface = { version = "0.1.0", path = "../redis_interface" }
router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] }
[build-dependencies]
router_env = { version = "0.1.0", path = "../router_env", default-features = false }
[lints]
workspace = true
| 620 | 935 |
hyperswitch | crates/drainer/build.rs | .rs | fn main() {
#[cfg(feature = "vergen")]
router_env::vergen::generate_cargo_instructions();
}
| 26 | 936 |
hyperswitch | crates/drainer/README.md | .md | # Drainer
Application that reads Redis streams and executes queries in database.
| 15 | 937 |
hyperswitch | crates/drainer/src/query.rs | .rs | 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"
),
}
}
| 489 | 938 |
hyperswitch | crates/drainer/src/metrics.rs | .rs | 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
| 318 | 939 |
hyperswitch | crates/drainer/src/connection.rs | .rs | use bb8::PooledConnection;
use common_utils::DbConnectionParams;
use diesel::PgConnection;
use crate::{settings::Database, Settings};
pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<PgConnection>>;
#[allow(clippy::expect_used)]
pub async fn redis_connection(conf: &Settings) -> redis_interface::RedisConnectionPool {
redis_interface::RedisConnectionPool::new(&conf.redis)
.await
.expect("Failed to create Redis connection Pool")
}
// TODO: use stores defined in storage_impl instead
/// # Panics
///
/// Will panic if could not create a db pool
#[allow(clippy::expect_used)]
pub async fn diesel_make_pg_pool(
database: &Database,
_test_transaction: bool,
schema: &str,
) -> PgPool {
let database_url = database.get_database_url(schema);
let manager = async_bb8_diesel::ConnectionManager::<PgConnection>::new(database_url);
let pool = bb8::Pool::builder()
.max_size(database.pool_size)
.connection_timeout(std::time::Duration::from_secs(database.connection_timeout));
pool.build(manager)
.await
.expect("Failed to create PostgreSQL connection pool")
}
#[allow(clippy::expect_used)]
pub async fn pg_connection(
pool: &PgPool,
) -> PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>> {
pool.get()
.await
.expect("Couldn't retrieve PostgreSQL connection")
}
| 324 | 940 |
hyperswitch | crates/drainer/src/health_check.rs | .rs | 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,
}
| 2,002 | 941 |
hyperswitch | crates/drainer/src/settings.rs | .rs | use std::{collections::HashMap, path::PathBuf, sync::Arc};
use common_utils::{ext_traits::ConfigExt, id_type, DbConnectionParams};
use config::{Environment, File};
use external_services::managers::{
encryption_management::EncryptionManagementConfig, secrets_management::SecretsManagementConfig,
};
use hyperswitch_interfaces::{
encryption_interface::EncryptionManagementInterface,
secrets_interface::secret_state::{
RawSecret, SecretState, SecretStateContainer, SecuredSecret,
},
};
use masking::Secret;
use redis_interface as redis;
pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry};
use router_env::{env, logger};
use serde::Deserialize;
use crate::{errors, secrets_transformers};
#[derive(clap::Parser, Default)]
#[cfg_attr(feature = "vergen", command(version = router_env::version!()))]
pub struct CmdLineConf {
/// Config file.
/// Application will look for "config/config.toml" if this option isn't specified.
#[arg(short = 'f', long, value_name = "FILE")]
pub config_path: Option<PathBuf>,
}
#[derive(Clone)]
pub struct AppState {
pub conf: Arc<Settings<RawSecret>>,
pub encryption_client: Arc<dyn EncryptionManagementInterface>,
}
impl AppState {
/// # Panics
///
/// Panics if secret or encryption management client cannot be initiated
pub async fn new(conf: Settings<SecuredSecret>) -> Self {
#[allow(clippy::expect_used)]
let secret_management_client = conf
.secrets_management
.get_secret_management_client()
.await
.expect("Failed to create secret management client");
let raw_conf =
secrets_transformers::fetch_raw_secrets(conf, &*secret_management_client).await;
#[allow(clippy::expect_used)]
let encryption_client = raw_conf
.encryption_management
.get_encryption_management_client()
.await
.expect("Failed to create encryption management client");
Self {
conf: Arc::new(raw_conf),
encryption_client,
}
}
}
#[derive(Debug, Deserialize, Clone, Default)]
#[serde(default)]
pub struct Settings<S: SecretState> {
pub server: Server,
pub master_database: SecretStateContainer<Database, S>,
pub redis: redis::RedisSettings,
pub log: Log,
pub drainer: DrainerSettings,
pub encryption_management: EncryptionManagementConfig,
pub secrets_management: SecretsManagementConfig,
pub multitenancy: Multitenancy,
}
#[derive(Debug, Deserialize, Clone)]
#[serde(default)]
pub struct Database {
pub username: String,
pub password: Secret<String>,
pub host: String,
pub port: u16,
pub dbname: String,
pub pool_size: u32,
pub connection_timeout: u64,
}
impl DbConnectionParams for Database {
fn get_username(&self) -> &str {
&self.username
}
fn get_password(&self) -> Secret<String> {
self.password.clone()
}
fn get_host(&self) -> &str {
&self.host
}
fn get_port(&self) -> u16 {
self.port
}
fn get_dbname(&self) -> &str {
&self.dbname
}
}
#[derive(Debug, Clone, Deserialize)]
#[serde(default)]
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
}
#[derive(Debug, Deserialize, Clone, Default)]
pub struct Multitenancy {
pub enabled: bool,
pub tenants: TenantConfig,
}
impl Multitenancy {
pub fn get_tenants(&self) -> &HashMap<id_type::TenantId, Tenant> {
&self.tenants.0
}
pub fn get_tenant_ids(&self) -> Vec<id_type::TenantId> {
self.tenants
.0
.values()
.map(|tenant| tenant.tenant_id.clone())
.collect()
}
pub fn get_tenant(&self, tenant_id: &id_type::TenantId) -> Option<&Tenant> {
self.tenants.0.get(tenant_id)
}
}
#[derive(Debug, Clone, Default)]
pub struct TenantConfig(pub HashMap<id_type::TenantId, Tenant>);
impl<'de> Deserialize<'de> for TenantConfig {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
#[derive(Deserialize)]
struct Inner {
base_url: String,
schema: String,
accounts_schema: String,
redis_key_prefix: String,
clickhouse_database: String,
}
let hashmap = <HashMap<id_type::TenantId, Inner>>::deserialize(deserializer)?;
Ok(Self(
hashmap
.into_iter()
.map(|(key, value)| {
(
key.clone(),
Tenant {
tenant_id: key,
base_url: value.base_url,
schema: value.schema,
accounts_schema: value.accounts_schema,
redis_key_prefix: value.redis_key_prefix,
clickhouse_database: value.clickhouse_database,
},
)
})
.collect(),
))
}
}
#[derive(Debug, Deserialize, Clone)]
pub struct Tenant {
pub tenant_id: id_type::TenantId,
pub base_url: String,
pub schema: String,
pub accounts_schema: String,
pub redis_key_prefix: String,
pub clickhouse_database: String,
}
#[derive(Debug, Deserialize, Clone)]
#[serde(default)]
pub struct Server {
pub port: u16,
pub workers: usize,
pub host: String,
}
impl Server {
pub fn validate(&self) -> Result<(), errors::DrainerError> {
common_utils::fp_utils::when(self.host.is_default_or_empty(), || {
Err(errors::DrainerError::ConfigParsingError(
"server host must not be empty".into(),
))
})
}
}
impl Default for Database {
fn default() -> Self {
Self {
username: String::new(),
password: String::new().into(),
host: "localhost".into(),
port: 5432,
dbname: String::new(),
pool_size: 5,
connection_timeout: 10,
}
}
}
impl Default for DrainerSettings {
fn default() -> Self {
Self {
stream_name: "DRAINER_STREAM".into(),
num_partitions: 64,
max_read_count: 100,
shutdown_interval: 1000, // in milliseconds
loop_interval: 100, // in milliseconds
}
}
}
impl Default for Server {
fn default() -> Self {
Self {
host: "127.0.0.1".to_string(),
port: 8080,
workers: 1,
}
}
}
impl Database {
fn validate(&self) -> Result<(), errors::DrainerError> {
use common_utils::fp_utils::when;
when(self.host.is_default_or_empty(), || {
Err(errors::DrainerError::ConfigParsingError(
"database host must not be empty".into(),
))
})?;
when(self.dbname.is_default_or_empty(), || {
Err(errors::DrainerError::ConfigParsingError(
"database name must not be empty".into(),
))
})?;
when(self.username.is_default_or_empty(), || {
Err(errors::DrainerError::ConfigParsingError(
"database user username must not be empty".into(),
))
})?;
when(self.password.is_default_or_empty(), || {
Err(errors::DrainerError::ConfigParsingError(
"database user password must not be empty".into(),
))
})
}
}
impl DrainerSettings {
fn validate(&self) -> Result<(), errors::DrainerError> {
common_utils::fp_utils::when(self.stream_name.is_default_or_empty(), || {
Err(errors::DrainerError::ConfigParsingError(
"drainer stream name must not be empty".into(),
))
})
}
}
impl Settings<SecuredSecret> {
pub fn new() -> Result<Self, errors::DrainerError> {
Self::with_config_path(None)
}
pub fn with_config_path(config_path: Option<PathBuf>) -> Result<Self, errors::DrainerError> {
// Configuration values are picked up in the following priority order (1 being least
// priority):
// 1. Defaults from the implementation of the `Default` trait.
// 2. Values from config file. The config file accessed depends on the environment
// specified by the `RUN_ENV` environment variable. `RUN_ENV` can be one of
// `development`, `sandbox` or `production`. If nothing is specified for `RUN_ENV`,
// `/config/development.toml` file is read.
// 3. Environment variables prefixed with `DRAINER` and each level separated by double
// underscores.
//
// Values in config file override the defaults in `Default` trait, and the values set using
// environment variables override both the defaults and the config file values.
let environment = env::which();
let config_path = router_env::Config::config_path(&environment.to_string(), config_path);
let config = router_env::Config::builder(&environment.to_string())?
.add_source(File::from(config_path).required(false))
.add_source(
Environment::with_prefix("DRAINER")
.try_parsing(true)
.separator("__")
.list_separator(",")
.with_list_parse_key("redis.cluster_urls"),
)
.build()?;
// The logger may not yet be initialized when constructing the application configuration
#[allow(clippy::print_stderr)]
serde_path_to_error::deserialize(config).map_err(|error| {
logger::error!(%error, "Unable to deserialize application configuration");
eprintln!("Unable to deserialize application configuration: {error}");
errors::DrainerError::from(error.into_inner())
})
}
pub fn validate(&self) -> Result<(), errors::DrainerError> {
self.server.validate()?;
self.master_database.get_inner().validate()?;
// The logger may not yet be initialized when validating the application configuration
#[allow(clippy::print_stderr)]
self.redis.validate().map_err(|error| {
eprintln!("{error}");
errors::DrainerError::ConfigParsingError("invalid Redis configuration".into())
})?;
self.drainer.validate()?;
// The logger may not yet be initialized when validating the application configuration
#[allow(clippy::print_stderr)]
self.secrets_management.validate().map_err(|error| {
eprintln!("{error}");
errors::DrainerError::ConfigParsingError(
"invalid secrets management configuration".into(),
)
})?;
// The logger may not yet be initialized when validating the application configuration
#[allow(clippy::print_stderr)]
self.encryption_management.validate().map_err(|error| {
eprintln!("{error}");
errors::DrainerError::ConfigParsingError(
"invalid encryption management configuration".into(),
)
})?;
Ok(())
}
}
| 2,456 | 942 |
hyperswitch | crates/drainer/src/utils.rs | .rs | use std::sync::{atomic, Arc};
use error_stack::report;
use redis_interface as redis;
use serde::de::Deserialize;
use crate::{
errors, kv, metrics,
stream::{StreamEntries, StreamReadResult},
};
pub fn parse_stream_entries<'a>(
read_result: &'a StreamReadResult,
stream_name: &str,
) -> errors::DrainerResult<&'a StreamEntries> {
read_result.get(stream_name).ok_or_else(|| {
report!(errors::DrainerError::RedisError(report!(
redis::errors::RedisError::NotFound
)))
})
}
pub(crate) fn deserialize_i64<'de, D>(deserializer: D) -> Result<i64, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = serde_json::Value::deserialize(deserializer)?;
match s {
serde_json::Value::String(str_val) => str_val.parse().map_err(serde::de::Error::custom),
serde_json::Value::Number(num_val) => match num_val.as_i64() {
Some(val) => Ok(val),
None => Err(serde::de::Error::custom(format!(
"could not convert {num_val:?} to i64"
))),
},
other => Err(serde::de::Error::custom(format!(
"unexpected data format - expected string or number, got: {other:?}"
))),
}
}
pub(crate) fn deserialize_db_op<'de, D>(deserializer: D) -> Result<kv::DBOperation, D::Error>
where
D: serde::Deserializer<'de>,
{
let s = serde_json::Value::deserialize(deserializer)?;
match s {
serde_json::Value::String(str_val) => {
serde_json::from_str(&str_val).map_err(serde::de::Error::custom)
}
other => Err(serde::de::Error::custom(format!(
"unexpected data format - expected string got: {other:?}"
))),
}
}
// Here the output is in the format (stream_index, jobs_picked),
// similar to the first argument of the function
#[inline(always)]
pub async fn increment_stream_index(
(index, jobs_picked): (u8, Arc<atomic::AtomicU8>),
total_streams: u8,
) -> u8 {
if index == total_streams - 1 {
match jobs_picked.load(atomic::Ordering::SeqCst) {
0 => metrics::CYCLES_COMPLETED_UNSUCCESSFULLY.add(1, &[]),
_ => metrics::CYCLES_COMPLETED_SUCCESSFULLY.add(1, &[]),
}
jobs_picked.store(0, atomic::Ordering::SeqCst);
0
} else {
index + 1
}
}
| 611 | 943 |
hyperswitch | crates/drainer/src/handler.rs | .rs | 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 !last_processed_id.is_empty() {
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(())
}
| 2,127 | 944 |
hyperswitch | crates/drainer/src/main.rs | .rs | 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(())
}
| 440 | 945 |
hyperswitch | crates/drainer/src/types.rs | .rs | 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"))
}
}
| 224 | 946 |
hyperswitch | crates/drainer/src/stream.rs | .rs | 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)
}
}
| 887 | 947 |
hyperswitch | crates/drainer/src/logger.rs | .rs | #[doc(inline)]
pub use router_env::{debug, error, info, warn};
| 18 | 948 |
hyperswitch | crates/drainer/src/lib.rs | .rs | 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)
}
| 513 | 949 |
hyperswitch | crates/drainer/src/errors.rs | .rs | 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,
}
}
}
| 446 | 950 |
hyperswitch | crates/drainer/src/secrets_transformers.rs | .rs | use common_utils::errors::CustomResult;
use hyperswitch_interfaces::secrets_interface::{
secret_handler::SecretsHandler,
secret_state::{RawSecret, SecretStateContainer, SecuredSecret},
SecretManagementInterface, SecretsManagementError,
};
use crate::settings::{Database, Settings};
#[async_trait::async_trait]
impl SecretsHandler for Database {
async fn convert_to_raw_secret(
value: SecretStateContainer<Self, SecuredSecret>,
secret_management_client: &dyn SecretManagementInterface,
) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {
let secured_db_config = value.get_inner();
let raw_db_password = secret_management_client
.get_secret(secured_db_config.password.clone())
.await?;
Ok(value.transition_state(|db| Self {
password: raw_db_password,
..db
}))
}
}
/// # Panics
///
/// Will panic even if fetching raw secret fails for at least one config value
pub async fn fetch_raw_secrets(
conf: Settings<SecuredSecret>,
secret_management_client: &dyn SecretManagementInterface,
) -> Settings<RawSecret> {
#[allow(clippy::expect_used)]
let database = Database::convert_to_raw_secret(conf.master_database, secret_management_client)
.await
.expect("Failed to decrypt database password");
Settings {
server: conf.server,
master_database: database,
redis: conf.redis,
log: conf.log,
drainer: conf.drainer,
encryption_management: conf.encryption_management,
secrets_management: conf.secrets_management,
multitenancy: conf.multitenancy,
}
}
| 349 | 951 |
hyperswitch | crates/drainer/src/services.rs | .rs | 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,
}
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,
},
request_id: None,
}
}
}
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)
}
| 464 | 952 |
hyperswitch | crates/euclid/Cargo.toml | .toml | [package]
name = "euclid"
description = "DSL for static routing"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
license.workspace = true
[dependencies]
nom = { version = "7.1.3", features = ["alloc"], optional = true }
once_cell = "1.19.0"
rustc-hash = "1.1.0"
serde = { version = "1.0.197", features = ["derive", "rc"] }
serde_json = "1.0.115"
strum = { version = "0.26", features = ["derive"] }
thiserror = "1.0.58"
utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order"] }
# First party dependencies
common_enums = { version = "0.1.0", path = "../common_enums" }
common_utils = { version = "0.1.0", path = "../common_utils" }
euclid_macros = { version = "0.1.0", path = "../euclid_macros" }
hyperswitch_constraint_graph = { version = "0.1.0", path = "../hyperswitch_constraint_graph", features = ["viz"] }
[features]
default = []
ast_parser = ["dep:nom"]
valued_jit = []
dummy_connector = []
payouts = []
v2 = ["common_enums/v2"]
[dev-dependencies]
criterion = "0.5"
[[bench]]
name = "backends"
harness = false
required-features = ["ast_parser", "valued_jit"]
[lints]
workspace = true
| 365 | 953 |
hyperswitch | crates/euclid/benches/backends.rs | .rs | #![allow(unused, clippy::expect_used)]
use common_utils::types::MinorUnit;
use criterion::{black_box, criterion_group, criterion_main, Criterion};
use euclid::{
backend::{inputs, EuclidBackend, InterpreterBackend, VirInterpreterBackend},
enums,
frontend::ast::{self, parser},
types::DummyOutput,
};
fn get_program_data() -> (ast::Program<DummyOutput>, inputs::BackendInput) {
let code1 = r#"
default: ["stripe", "adyen", "checkout"]
stripe_first: ["stripe", "aci"]
{
payment_method = card & amount = 40 {
payment_method = (card, bank_redirect)
amount = (40, 50)
}
}
adyen_first: ["adyen", "checkout"]
{
payment_method = bank_redirect & amount > 60 {
payment_method = (card, bank_redirect)
amount = (40, 50)
}
}
auth_first: ["authorizedotnet", "adyen"]
{
payment_method = wallet
}
"#;
let inp = inputs::BackendInput {
metadata: None,
payment: inputs::PaymentInput {
amount: MinorUnit::new(32),
card_bin: None,
currency: enums::Currency::USD,
authentication_type: Some(enums::AuthenticationType::NoThreeDs),
capture_method: Some(enums::CaptureMethod::Automatic),
business_country: Some(enums::Country::UnitedStatesOfAmerica),
billing_country: Some(enums::Country::France),
business_label: None,
setup_future_usage: None,
},
payment_method: inputs::PaymentMethodInput {
payment_method: Some(enums::PaymentMethod::PayLater),
payment_method_type: Some(enums::PaymentMethodType::Sofort),
card_network: None,
},
mandate: inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
},
};
let (_, program) = parser::program(code1).expect("Parser");
(program, inp)
}
fn interpreter_vs_jit_vs_vir_interpreter(c: &mut Criterion) {
let (program, binputs) = get_program_data();
let interp_b = InterpreterBackend::with_program(program.clone()).expect("Interpreter backend");
let vir_interp_b =
VirInterpreterBackend::with_program(program).expect("Vir Interpreter Backend");
c.bench_function("Raw Interpreter Backend", |b| {
b.iter(|| {
interp_b
.execute(binputs.clone())
.expect("Interpreter EXECUTION");
});
});
c.bench_function("Valued Interpreter Backend", |b| {
b.iter(|| {
vir_interp_b
.execute(binputs.clone())
.expect("Vir Interpreter execution");
})
});
}
criterion_group!(benches, interpreter_vs_jit_vs_vir_interpreter);
criterion_main!(benches);
| 645 | 954 |
hyperswitch | crates/euclid/src/frontend.rs | .rs | pub mod ast;
pub mod dir;
pub mod vir;
| 12 | 955 |
hyperswitch | crates/euclid/src/enums.rs | .rs | pub use common_enums::{
AuthenticationType, CaptureMethod, CardNetwork, Country, CountryAlpha2, Currency,
FutureUsage as SetupFutureUsage, PaymentMethod, PaymentMethodType, RoutableConnectors,
};
use strum::VariantNames;
pub trait CollectVariants {
fn variants<T: FromIterator<String>>() -> T;
}
macro_rules! collect_variants {
($the_enum:ident) => {
impl $crate::enums::CollectVariants for $the_enum {
fn variants<T>() -> T
where
T: FromIterator<String>,
{
Self::VARIANTS.iter().map(|s| String::from(*s)).collect()
}
}
};
}
pub(crate) use collect_variants;
collect_variants!(PaymentMethod);
collect_variants!(RoutableConnectors);
collect_variants!(PaymentType);
collect_variants!(MandateType);
collect_variants!(MandateAcceptanceType);
collect_variants!(PaymentMethodType);
collect_variants!(CardNetwork);
collect_variants!(AuthenticationType);
collect_variants!(CaptureMethod);
collect_variants!(Currency);
collect_variants!(Country);
collect_variants!(SetupFutureUsage);
#[cfg(feature = "payouts")]
collect_variants!(PayoutType);
#[cfg(feature = "payouts")]
collect_variants!(PayoutBankTransferType);
#[cfg(feature = "payouts")]
collect_variants!(PayoutWalletType);
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum MandateAcceptanceType {
Online,
Offline,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PaymentType {
SetupMandate,
NonMandate,
NewMandate,
UpdateMandate,
PptMandate,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum MandateType {
SingleUse,
MultiUse,
}
#[cfg(feature = "payouts")]
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PayoutBankTransferType {
Ach,
Bacs,
Sepa,
}
#[cfg(feature = "payouts")]
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PayoutWalletType {
Paypal,
}
#[cfg(feature = "payouts")]
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PayoutType {
Card,
BankTransfer,
Wallet,
}
| 902 | 956 |
hyperswitch | crates/euclid/src/dssa.rs | .rs | //! Domain Specific Static Analyzer
pub mod analyzer;
pub mod graph;
pub mod state_machine;
pub mod truth;
pub mod types;
pub mod utils;
| 31 | 957 |
hyperswitch | crates/euclid/src/types.rs | .rs | pub mod transformers;
use common_utils::types::MinorUnit;
use euclid_macros::EnumNums;
use serde::{Deserialize, Serialize};
use strum::VariantNames;
use crate::{
dssa::types::EuclidAnalysable,
enums,
frontend::{
ast,
dir::{DirKeyKind, DirValue, EuclidDirFilter},
},
};
pub type Metadata = std::collections::HashMap<String, serde_json::Value>;
#[derive(
Debug,
Clone,
EnumNums,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumString,
)]
pub enum EuclidKey {
#[strum(serialize = "payment_method")]
PaymentMethod,
#[strum(serialize = "card_bin")]
CardBin,
#[strum(serialize = "metadata")]
Metadata,
#[strum(serialize = "mandate_type")]
MandateType,
#[strum(serialize = "mandate_acceptance_type")]
MandateAcceptanceType,
#[strum(serialize = "payment_type")]
PaymentType,
#[strum(serialize = "payment_method_type")]
PaymentMethodType,
#[strum(serialize = "card_network")]
CardNetwork,
#[strum(serialize = "authentication_type")]
AuthenticationType,
#[strum(serialize = "capture_method")]
CaptureMethod,
#[strum(serialize = "amount")]
PaymentAmount,
#[strum(serialize = "currency")]
PaymentCurrency,
#[strum(serialize = "country", to_string = "business_country")]
BusinessCountry,
#[strum(serialize = "billing_country")]
BillingCountry,
#[strum(serialize = "business_label")]
BusinessLabel,
#[strum(serialize = "setup_future_usage")]
SetupFutureUsage,
}
impl EuclidDirFilter for DummyOutput {
const ALLOWED: &'static [DirKeyKind] = &[
DirKeyKind::AuthenticationType,
DirKeyKind::PaymentMethod,
DirKeyKind::CardType,
DirKeyKind::PaymentCurrency,
DirKeyKind::CaptureMethod,
DirKeyKind::AuthenticationType,
DirKeyKind::CardBin,
DirKeyKind::PayLaterType,
DirKeyKind::PaymentAmount,
DirKeyKind::MetaData,
DirKeyKind::MandateAcceptanceType,
DirKeyKind::MandateType,
DirKeyKind::PaymentType,
DirKeyKind::SetupFutureUsage,
];
}
impl EuclidAnalysable for DummyOutput {
fn get_dir_value_for_analysis(&self, rule_name: String) -> Vec<(DirValue, Metadata)> {
self.outputs
.iter()
.map(|dummyc| {
let metadata_key = "MetadataKey".to_string();
let metadata_value = dummyc;
(
DirValue::MetaData(MetadataValue {
key: metadata_key.clone(),
value: metadata_value.clone(),
}),
std::collections::HashMap::from_iter([(
"DUMMY_OUTPUT".to_string(),
serde_json::json!({
"rule_name":rule_name,
"Metadata_Key" :metadata_key,
"Metadata_Value" : metadata_value,
}),
)]),
)
})
.collect()
}
}
#[derive(Debug, Clone, Serialize)]
pub struct DummyOutput {
pub outputs: Vec<String>,
}
#[derive(Debug, Clone, serde::Serialize, strum::Display)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum DataType {
Number,
EnumVariant,
MetadataValue,
StrValue,
}
impl EuclidKey {
pub fn key_type(&self) -> DataType {
match self {
Self::PaymentMethod => DataType::EnumVariant,
Self::CardBin => DataType::StrValue,
Self::Metadata => DataType::MetadataValue,
Self::PaymentMethodType => DataType::EnumVariant,
Self::CardNetwork => DataType::EnumVariant,
Self::AuthenticationType => DataType::EnumVariant,
Self::CaptureMethod => DataType::EnumVariant,
Self::PaymentAmount => DataType::Number,
Self::PaymentCurrency => DataType::EnumVariant,
Self::BusinessCountry => DataType::EnumVariant,
Self::BillingCountry => DataType::EnumVariant,
Self::MandateType => DataType::EnumVariant,
Self::MandateAcceptanceType => DataType::EnumVariant,
Self::PaymentType => DataType::EnumVariant,
Self::BusinessLabel => DataType::StrValue,
Self::SetupFutureUsage => DataType::EnumVariant,
}
}
}
enums::collect_variants!(EuclidKey);
#[derive(Debug, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum NumValueRefinement {
NotEqual,
GreaterThan,
LessThan,
GreaterThanEqual,
LessThanEqual,
}
impl From<ast::ComparisonType> for Option<NumValueRefinement> {
fn from(comp_type: ast::ComparisonType) -> Self {
match comp_type {
ast::ComparisonType::Equal => None,
ast::ComparisonType::NotEqual => Some(NumValueRefinement::NotEqual),
ast::ComparisonType::GreaterThan => Some(NumValueRefinement::GreaterThan),
ast::ComparisonType::LessThan => Some(NumValueRefinement::LessThan),
ast::ComparisonType::LessThanEqual => Some(NumValueRefinement::LessThanEqual),
ast::ComparisonType::GreaterThanEqual => Some(NumValueRefinement::GreaterThanEqual),
}
}
}
impl From<NumValueRefinement> for ast::ComparisonType {
fn from(value: NumValueRefinement) -> Self {
match value {
NumValueRefinement::NotEqual => Self::NotEqual,
NumValueRefinement::LessThan => Self::LessThan,
NumValueRefinement::GreaterThan => Self::GreaterThan,
NumValueRefinement::GreaterThanEqual => Self::GreaterThanEqual,
NumValueRefinement::LessThanEqual => Self::LessThanEqual,
}
}
}
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct StrValue {
pub value: String,
}
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct MetadataValue {
pub key: String,
pub value: String,
}
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub struct NumValue {
pub number: MinorUnit,
pub refinement: Option<NumValueRefinement>,
}
impl NumValue {
pub fn fits(&self, other: &Self) -> bool {
let this_num = self.number;
let other_num = other.number;
match (&self.refinement, &other.refinement) {
(None, None) => this_num == other_num,
(Some(NumValueRefinement::GreaterThan), None) => other_num > this_num,
(Some(NumValueRefinement::LessThan), None) => other_num < this_num,
(Some(NumValueRefinement::NotEqual), Some(NumValueRefinement::NotEqual)) => {
other_num == this_num
}
(Some(NumValueRefinement::GreaterThan), Some(NumValueRefinement::GreaterThan)) => {
other_num > this_num
}
(Some(NumValueRefinement::LessThan), Some(NumValueRefinement::LessThan)) => {
other_num < this_num
}
(Some(NumValueRefinement::GreaterThanEqual), None) => other_num >= this_num,
(Some(NumValueRefinement::LessThanEqual), None) => other_num <= this_num,
(
Some(NumValueRefinement::GreaterThanEqual),
Some(NumValueRefinement::GreaterThanEqual),
) => other_num >= this_num,
(Some(NumValueRefinement::LessThanEqual), Some(NumValueRefinement::LessThanEqual)) => {
other_num <= this_num
}
_ => false,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum EuclidValue {
PaymentMethod(enums::PaymentMethod),
CardBin(StrValue),
Metadata(MetadataValue),
PaymentMethodType(enums::PaymentMethodType),
CardNetwork(enums::CardNetwork),
AuthenticationType(enums::AuthenticationType),
CaptureMethod(enums::CaptureMethod),
PaymentType(enums::PaymentType),
MandateAcceptanceType(enums::MandateAcceptanceType),
MandateType(enums::MandateType),
PaymentAmount(NumValue),
PaymentCurrency(enums::Currency),
BusinessCountry(enums::Country),
BillingCountry(enums::Country),
BusinessLabel(StrValue),
SetupFutureUsage(enums::SetupFutureUsage),
}
impl EuclidValue {
pub fn get_num_value(&self) -> Option<NumValue> {
match self {
Self::PaymentAmount(val) => Some(val.clone()),
_ => None,
}
}
pub fn get_key(&self) -> EuclidKey {
match self {
Self::PaymentMethod(_) => EuclidKey::PaymentMethod,
Self::CardBin(_) => EuclidKey::CardBin,
Self::Metadata(_) => EuclidKey::Metadata,
Self::PaymentMethodType(_) => EuclidKey::PaymentMethodType,
Self::MandateType(_) => EuclidKey::MandateType,
Self::PaymentType(_) => EuclidKey::PaymentType,
Self::MandateAcceptanceType(_) => EuclidKey::MandateAcceptanceType,
Self::CardNetwork(_) => EuclidKey::CardNetwork,
Self::AuthenticationType(_) => EuclidKey::AuthenticationType,
Self::CaptureMethod(_) => EuclidKey::CaptureMethod,
Self::PaymentAmount(_) => EuclidKey::PaymentAmount,
Self::PaymentCurrency(_) => EuclidKey::PaymentCurrency,
Self::BusinessCountry(_) => EuclidKey::BusinessCountry,
Self::BillingCountry(_) => EuclidKey::BillingCountry,
Self::BusinessLabel(_) => EuclidKey::BusinessLabel,
Self::SetupFutureUsage(_) => EuclidKey::SetupFutureUsage,
}
}
}
#[cfg(test)]
mod global_type_tests {
use super::*;
#[test]
fn test_num_value_fits_greater_than() {
let val1 = NumValue {
number: MinorUnit::new(10),
refinement: Some(NumValueRefinement::GreaterThan),
};
let val2 = NumValue {
number: MinorUnit::new(30),
refinement: Some(NumValueRefinement::GreaterThan),
};
assert!(val1.fits(&val2))
}
#[test]
fn test_num_value_fits_less_than() {
let val1 = NumValue {
number: MinorUnit::new(30),
refinement: Some(NumValueRefinement::LessThan),
};
let val2 = NumValue {
number: MinorUnit::new(10),
refinement: Some(NumValueRefinement::LessThan),
};
assert!(val1.fits(&val2));
}
}
| 2,430 | 958 |
hyperswitch | crates/euclid/src/lib.rs | .rs | #![allow(clippy::result_large_err)]
pub mod backend;
pub mod dssa;
pub mod enums;
pub mod frontend;
pub mod types;
| 30 | 959 |
hyperswitch | crates/euclid/src/backend.rs | .rs | pub mod inputs;
pub mod interpreter;
#[cfg(feature = "valued_jit")]
pub mod vir_interpreter;
pub use inputs::BackendInput;
pub use interpreter::InterpreterBackend;
#[cfg(feature = "valued_jit")]
pub use vir_interpreter::VirInterpreterBackend;
use crate::frontend::ast;
#[derive(Debug, Clone, serde::Serialize)]
pub struct BackendOutput<O> {
pub rule_name: Option<String>,
pub connector_selection: O,
}
pub trait EuclidBackend<O>: Sized {
type Error: serde::Serialize;
fn with_program(program: ast::Program<O>) -> Result<Self, Self::Error>;
fn execute(&self, input: BackendInput) -> Result<BackendOutput<O>, Self::Error>;
}
| 157 | 960 |
hyperswitch | crates/euclid/src/types/transformers.rs | .rs | 1 | 961 | |
hyperswitch | crates/euclid/src/frontend/vir.rs | .rs | //! Valued Intermediate Representation
use serde::{Deserialize, Serialize};
use crate::types::{EuclidValue, Metadata};
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum ValuedComparisonLogic {
NegativeConjunction,
PositiveDisjunction,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ValuedComparison {
pub values: Vec<EuclidValue>,
pub logic: ValuedComparisonLogic,
pub metadata: Metadata,
}
pub type ValuedIfCondition = Vec<ValuedComparison>;
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ValuedIfStatement {
pub condition: ValuedIfCondition,
pub nested: Option<Vec<ValuedIfStatement>>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ValuedRule<O> {
pub name: String,
pub connector_selection: O,
pub statements: Vec<ValuedIfStatement>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ValuedProgram<O> {
pub default_selection: O,
pub rules: Vec<ValuedRule<O>>,
pub metadata: Metadata,
}
| 232 | 962 |
hyperswitch | crates/euclid/src/frontend/dir.rs | .rs | //! Domain Intermediate Representation
pub mod enums;
pub mod lowering;
pub mod transformers;
use strum::IntoEnumIterator;
// use common_utils::types::MinorUnit;
use crate::{enums as euclid_enums, frontend::ast, types};
#[macro_export]
macro_rules! dirval {
(Connector = $name:ident) => {
$crate::frontend::dir::DirValue::Connector(Box::new(
$crate::frontend::ast::ConnectorChoice {
connector: $crate::enums::RoutableConnectors::$name,
},
))
};
($key:ident = $val:ident) => {{
pub use $crate::frontend::dir::enums::*;
$crate::frontend::dir::DirValue::$key($key::$val)
}};
($key:ident = $num:literal) => {{
$crate::frontend::dir::DirValue::$key($crate::types::NumValue {
number: common_utils::types::MinorUnit::new($num),
refinement: None,
})
}};
($key:ident s= $str:literal) => {{
$crate::frontend::dir::DirValue::$key($crate::types::StrValue {
value: $str.to_string(),
})
}};
($key:literal = $str:literal) => {{
$crate::frontend::dir::DirValue::MetaData($crate::types::MetadataValue {
key: $key.to_string(),
value: $str.to_string(),
})
}};
}
#[derive(Debug, Clone, Hash, PartialEq, Eq, serde::Serialize)]
pub struct DirKey {
pub kind: DirKeyKind,
pub value: Option<String>,
}
impl DirKey {
pub fn new(kind: DirKeyKind, value: Option<String>) -> Self {
Self { kind, value }
}
}
#[derive(
Debug,
Clone,
Hash,
PartialEq,
Eq,
serde::Serialize,
strum::Display,
strum::EnumIter,
strum::VariantNames,
strum::EnumString,
strum::EnumMessage,
strum::EnumProperty,
)]
pub enum DirKeyKind {
#[strum(
serialize = "payment_method",
detailed_message = "Different modes of payment - eg. cards, wallets, banks",
props(Category = "Payment Methods")
)]
#[serde(rename = "payment_method")]
PaymentMethod,
#[strum(
serialize = "card_bin",
detailed_message = "First 4 to 6 digits of a payment card number",
props(Category = "Payment Methods")
)]
#[serde(rename = "card_bin")]
CardBin,
#[strum(
serialize = "card_type",
detailed_message = "Type of the payment card - eg. credit, debit",
props(Category = "Payment Methods")
)]
#[serde(rename = "card_type")]
CardType,
#[strum(
serialize = "card_network",
detailed_message = "Network that facilitates payment card transactions",
props(Category = "Payment Methods")
)]
#[serde(rename = "card_network")]
CardNetwork,
#[strum(
serialize = "pay_later",
detailed_message = "Supported types of Pay Later payment method",
props(Category = "Payment Method Types")
)]
#[serde(rename = "pay_later")]
PayLaterType,
#[strum(
serialize = "gift_card",
detailed_message = "Supported types of Gift Card payment method",
props(Category = "Payment Method Types")
)]
#[serde(rename = "gift_card")]
GiftCardType,
#[strum(
serialize = "mandate_acceptance_type",
detailed_message = "Mode of customer acceptance for mandates - online and offline",
props(Category = "Payments")
)]
#[serde(rename = "mandate_acceptance_type")]
MandateAcceptanceType,
#[strum(
serialize = "mandate_type",
detailed_message = "Type of mandate acceptance - single use and multi use",
props(Category = "Payments")
)]
#[serde(rename = "mandate_type")]
MandateType,
#[strum(
serialize = "payment_type",
detailed_message = "Indicates if a payment is mandate or non-mandate",
props(Category = "Payments")
)]
#[serde(rename = "payment_type")]
PaymentType,
#[strum(
serialize = "wallet",
detailed_message = "Supported types of Wallet payment method",
props(Category = "Payment Method Types")
)]
#[serde(rename = "wallet")]
WalletType,
#[strum(
serialize = "upi",
detailed_message = "Supported types of UPI payment method",
props(Category = "Payment Method Types")
)]
#[serde(rename = "upi")]
UpiType,
#[strum(
serialize = "voucher",
detailed_message = "Supported types of Voucher payment method",
props(Category = "Payment Method Types")
)]
#[serde(rename = "voucher")]
VoucherType,
#[strum(
serialize = "bank_transfer",
detailed_message = "Supported types of Bank Transfer payment method",
props(Category = "Payment Method Types")
)]
#[serde(rename = "bank_transfer")]
BankTransferType,
#[strum(
serialize = "bank_redirect",
detailed_message = "Supported types of Bank Redirect payment methods",
props(Category = "Payment Method Types")
)]
#[serde(rename = "bank_redirect")]
BankRedirectType,
#[strum(
serialize = "bank_debit",
detailed_message = "Supported types of Bank Debit payment method",
props(Category = "Payment Method Types")
)]
#[serde(rename = "bank_debit")]
BankDebitType,
#[strum(
serialize = "crypto",
detailed_message = "Supported types of Crypto payment method",
props(Category = "Payment Method Types")
)]
#[serde(rename = "crypto")]
CryptoType,
#[strum(
serialize = "metadata",
detailed_message = "Aribitrary Key and value pair",
props(Category = "Metadata")
)]
#[serde(rename = "metadata")]
MetaData,
#[strum(
serialize = "reward",
detailed_message = "Supported types of Reward payment method",
props(Category = "Payment Method Types")
)]
#[serde(rename = "reward")]
RewardType,
#[strum(
serialize = "amount",
detailed_message = "Value of the transaction",
props(Category = "Payments")
)]
#[serde(rename = "amount")]
PaymentAmount,
#[strum(
serialize = "currency",
detailed_message = "Currency used for the payment",
props(Category = "Payments")
)]
#[serde(rename = "currency")]
PaymentCurrency,
#[strum(
serialize = "authentication_type",
detailed_message = "Type of authentication for the payment",
props(Category = "Payments")
)]
#[serde(rename = "authentication_type")]
AuthenticationType,
#[strum(
serialize = "capture_method",
detailed_message = "Modes of capturing a payment",
props(Category = "Payments")
)]
#[serde(rename = "capture_method")]
CaptureMethod,
#[strum(
serialize = "country",
serialize = "business_country",
detailed_message = "Country of the business unit",
props(Category = "Merchant")
)]
#[serde(rename = "business_country", alias = "country")]
BusinessCountry,
#[strum(
serialize = "billing_country",
detailed_message = "Country of the billing address of the customer",
props(Category = "Customer")
)]
#[serde(rename = "billing_country")]
BillingCountry,
#[serde(skip_deserializing, rename = "connector")]
Connector,
#[strum(
serialize = "business_label",
detailed_message = "Identifier for business unit",
props(Category = "Merchant")
)]
#[serde(rename = "business_label")]
BusinessLabel,
#[strum(
serialize = "setup_future_usage",
detailed_message = "Identifier for recurring payments",
props(Category = "Payments")
)]
#[serde(rename = "setup_future_usage")]
SetupFutureUsage,
#[strum(
serialize = "card_redirect",
detailed_message = "Supported types of Card Redirect payment method",
props(Category = "Payment Method Types")
)]
#[serde(rename = "card_redirect")]
CardRedirectType,
#[serde(rename = "real_time_payment")]
#[strum(
serialize = "real_time_payment",
detailed_message = "Supported types of real time payment method",
props(Category = "Payment Method Types")
)]
RealTimePaymentType,
#[serde(rename = "open_banking")]
#[strum(
serialize = "open_banking",
detailed_message = "Supported types of open banking payment method",
props(Category = "Payment Method Types")
)]
OpenBankingType,
#[serde(rename = "mobile_payment")]
#[strum(
serialize = "mobile_payment",
detailed_message = "Supported types of mobile payment method",
props(Category = "Payment Method Types")
)]
MobilePaymentType,
}
pub trait EuclidDirFilter: Sized
where
Self: 'static,
{
const ALLOWED: &'static [DirKeyKind];
fn get_allowed_keys() -> &'static [DirKeyKind] {
Self::ALLOWED
}
fn is_key_allowed(key: &DirKeyKind) -> bool {
Self::ALLOWED.contains(key)
}
}
impl DirKeyKind {
pub fn get_type(&self) -> types::DataType {
match self {
Self::PaymentMethod => types::DataType::EnumVariant,
Self::CardBin => types::DataType::StrValue,
Self::CardType => types::DataType::EnumVariant,
Self::CardNetwork => types::DataType::EnumVariant,
Self::MetaData => types::DataType::MetadataValue,
Self::MandateType => types::DataType::EnumVariant,
Self::PaymentType => types::DataType::EnumVariant,
Self::MandateAcceptanceType => types::DataType::EnumVariant,
Self::PayLaterType => types::DataType::EnumVariant,
Self::WalletType => types::DataType::EnumVariant,
Self::UpiType => types::DataType::EnumVariant,
Self::VoucherType => types::DataType::EnumVariant,
Self::BankTransferType => types::DataType::EnumVariant,
Self::GiftCardType => types::DataType::EnumVariant,
Self::BankRedirectType => types::DataType::EnumVariant,
Self::CryptoType => types::DataType::EnumVariant,
Self::RewardType => types::DataType::EnumVariant,
Self::PaymentAmount => types::DataType::Number,
Self::PaymentCurrency => types::DataType::EnumVariant,
Self::AuthenticationType => types::DataType::EnumVariant,
Self::CaptureMethod => types::DataType::EnumVariant,
Self::BusinessCountry => types::DataType::EnumVariant,
Self::BillingCountry => types::DataType::EnumVariant,
Self::Connector => types::DataType::EnumVariant,
Self::BankDebitType => types::DataType::EnumVariant,
Self::BusinessLabel => types::DataType::StrValue,
Self::SetupFutureUsage => types::DataType::EnumVariant,
Self::CardRedirectType => types::DataType::EnumVariant,
Self::RealTimePaymentType => types::DataType::EnumVariant,
Self::OpenBankingType => types::DataType::EnumVariant,
Self::MobilePaymentType => types::DataType::EnumVariant,
}
}
pub fn get_value_set(&self) -> Option<Vec<DirValue>> {
match self {
Self::PaymentMethod => Some(
enums::PaymentMethod::iter()
.map(DirValue::PaymentMethod)
.collect(),
),
Self::CardBin => None,
Self::CardType => Some(enums::CardType::iter().map(DirValue::CardType).collect()),
Self::MandateAcceptanceType => Some(
euclid_enums::MandateAcceptanceType::iter()
.map(DirValue::MandateAcceptanceType)
.collect(),
),
Self::PaymentType => Some(
euclid_enums::PaymentType::iter()
.map(DirValue::PaymentType)
.collect(),
),
Self::MandateType => Some(
euclid_enums::MandateType::iter()
.map(DirValue::MandateType)
.collect(),
),
Self::CardNetwork => Some(
enums::CardNetwork::iter()
.map(DirValue::CardNetwork)
.collect(),
),
Self::PayLaterType => Some(
enums::PayLaterType::iter()
.map(DirValue::PayLaterType)
.collect(),
),
Self::MetaData => None,
Self::WalletType => Some(
enums::WalletType::iter()
.map(DirValue::WalletType)
.collect(),
),
Self::UpiType => Some(enums::UpiType::iter().map(DirValue::UpiType).collect()),
Self::VoucherType => Some(
enums::VoucherType::iter()
.map(DirValue::VoucherType)
.collect(),
),
Self::BankTransferType => Some(
enums::BankTransferType::iter()
.map(DirValue::BankTransferType)
.collect(),
),
Self::GiftCardType => Some(
enums::GiftCardType::iter()
.map(DirValue::GiftCardType)
.collect(),
),
Self::BankRedirectType => Some(
enums::BankRedirectType::iter()
.map(DirValue::BankRedirectType)
.collect(),
),
Self::CryptoType => Some(
enums::CryptoType::iter()
.map(DirValue::CryptoType)
.collect(),
),
Self::RewardType => Some(
enums::RewardType::iter()
.map(DirValue::RewardType)
.collect(),
),
Self::PaymentAmount => None,
Self::PaymentCurrency => Some(
enums::PaymentCurrency::iter()
.map(DirValue::PaymentCurrency)
.collect(),
),
Self::AuthenticationType => Some(
enums::AuthenticationType::iter()
.map(DirValue::AuthenticationType)
.collect(),
),
Self::CaptureMethod => Some(
enums::CaptureMethod::iter()
.map(DirValue::CaptureMethod)
.collect(),
),
Self::BankDebitType => Some(
enums::BankDebitType::iter()
.map(DirValue::BankDebitType)
.collect(),
),
Self::BusinessCountry => Some(
enums::Country::iter()
.map(DirValue::BusinessCountry)
.collect(),
),
Self::BillingCountry => Some(
enums::Country::iter()
.map(DirValue::BillingCountry)
.collect(),
),
Self::Connector => Some(
common_enums::RoutableConnectors::iter()
.map(|connector| {
DirValue::Connector(Box::new(ast::ConnectorChoice { connector }))
})
.collect(),
),
Self::BusinessLabel => None,
Self::SetupFutureUsage => Some(
enums::SetupFutureUsage::iter()
.map(DirValue::SetupFutureUsage)
.collect(),
),
Self::CardRedirectType => Some(
enums::CardRedirectType::iter()
.map(DirValue::CardRedirectType)
.collect(),
),
Self::RealTimePaymentType => Some(
enums::RealTimePaymentType::iter()
.map(DirValue::RealTimePaymentType)
.collect(),
),
Self::OpenBankingType => Some(
enums::OpenBankingType::iter()
.map(DirValue::OpenBankingType)
.collect(),
),
Self::MobilePaymentType => Some(
enums::MobilePaymentType::iter()
.map(DirValue::MobilePaymentType)
.collect(),
),
}
}
}
#[derive(
Debug, Clone, Hash, PartialEq, Eq, serde::Serialize, strum::Display, strum::VariantNames,
)]
#[serde(tag = "key", content = "value")]
pub enum DirValue {
#[serde(rename = "payment_method")]
PaymentMethod(enums::PaymentMethod),
#[serde(rename = "card_bin")]
CardBin(types::StrValue),
#[serde(rename = "card_type")]
CardType(enums::CardType),
#[serde(rename = "card_network")]
CardNetwork(enums::CardNetwork),
#[serde(rename = "metadata")]
MetaData(types::MetadataValue),
#[serde(rename = "pay_later")]
PayLaterType(enums::PayLaterType),
#[serde(rename = "wallet")]
WalletType(enums::WalletType),
#[serde(rename = "acceptance_type")]
MandateAcceptanceType(euclid_enums::MandateAcceptanceType),
#[serde(rename = "mandate_type")]
MandateType(euclid_enums::MandateType),
#[serde(rename = "payment_type")]
PaymentType(euclid_enums::PaymentType),
#[serde(rename = "upi")]
UpiType(enums::UpiType),
#[serde(rename = "voucher")]
VoucherType(enums::VoucherType),
#[serde(rename = "bank_transfer")]
BankTransferType(enums::BankTransferType),
#[serde(rename = "bank_redirect")]
BankRedirectType(enums::BankRedirectType),
#[serde(rename = "bank_debit")]
BankDebitType(enums::BankDebitType),
#[serde(rename = "crypto")]
CryptoType(enums::CryptoType),
#[serde(rename = "reward")]
RewardType(enums::RewardType),
#[serde(rename = "gift_card")]
GiftCardType(enums::GiftCardType),
#[serde(rename = "amount")]
PaymentAmount(types::NumValue),
#[serde(rename = "currency")]
PaymentCurrency(enums::PaymentCurrency),
#[serde(rename = "authentication_type")]
AuthenticationType(enums::AuthenticationType),
#[serde(rename = "capture_method")]
CaptureMethod(enums::CaptureMethod),
#[serde(rename = "business_country", alias = "country")]
BusinessCountry(enums::Country),
#[serde(rename = "billing_country")]
BillingCountry(enums::Country),
#[serde(skip_deserializing, rename = "connector")]
Connector(Box<ast::ConnectorChoice>),
#[serde(rename = "business_label")]
BusinessLabel(types::StrValue),
#[serde(rename = "setup_future_usage")]
SetupFutureUsage(enums::SetupFutureUsage),
#[serde(rename = "card_redirect")]
CardRedirectType(enums::CardRedirectType),
#[serde(rename = "real_time_payment")]
RealTimePaymentType(enums::RealTimePaymentType),
#[serde(rename = "open_banking")]
OpenBankingType(enums::OpenBankingType),
#[serde(rename = "mobile_payment")]
MobilePaymentType(enums::MobilePaymentType),
}
impl DirValue {
pub fn get_key(&self) -> DirKey {
let (kind, data) = match self {
Self::PaymentMethod(_) => (DirKeyKind::PaymentMethod, None),
Self::CardBin(_) => (DirKeyKind::CardBin, None),
Self::RewardType(_) => (DirKeyKind::RewardType, None),
Self::BusinessCountry(_) => (DirKeyKind::BusinessCountry, None),
Self::BillingCountry(_) => (DirKeyKind::BillingCountry, None),
Self::BankTransferType(_) => (DirKeyKind::BankTransferType, None),
Self::UpiType(_) => (DirKeyKind::UpiType, None),
Self::CardType(_) => (DirKeyKind::CardType, None),
Self::CardNetwork(_) => (DirKeyKind::CardNetwork, None),
Self::MetaData(met) => (DirKeyKind::MetaData, Some(met.key.clone())),
Self::PayLaterType(_) => (DirKeyKind::PayLaterType, None),
Self::WalletType(_) => (DirKeyKind::WalletType, None),
Self::BankRedirectType(_) => (DirKeyKind::BankRedirectType, None),
Self::CryptoType(_) => (DirKeyKind::CryptoType, None),
Self::AuthenticationType(_) => (DirKeyKind::AuthenticationType, None),
Self::CaptureMethod(_) => (DirKeyKind::CaptureMethod, None),
Self::PaymentAmount(_) => (DirKeyKind::PaymentAmount, None),
Self::PaymentCurrency(_) => (DirKeyKind::PaymentCurrency, None),
Self::Connector(_) => (DirKeyKind::Connector, None),
Self::BankDebitType(_) => (DirKeyKind::BankDebitType, None),
Self::MandateAcceptanceType(_) => (DirKeyKind::MandateAcceptanceType, None),
Self::MandateType(_) => (DirKeyKind::MandateType, None),
Self::PaymentType(_) => (DirKeyKind::PaymentType, None),
Self::BusinessLabel(_) => (DirKeyKind::BusinessLabel, None),
Self::SetupFutureUsage(_) => (DirKeyKind::SetupFutureUsage, None),
Self::CardRedirectType(_) => (DirKeyKind::CardRedirectType, None),
Self::VoucherType(_) => (DirKeyKind::VoucherType, None),
Self::GiftCardType(_) => (DirKeyKind::GiftCardType, None),
Self::RealTimePaymentType(_) => (DirKeyKind::RealTimePaymentType, None),
Self::OpenBankingType(_) => (DirKeyKind::OpenBankingType, None),
Self::MobilePaymentType(_) => (DirKeyKind::MobilePaymentType, None),
};
DirKey::new(kind, data)
}
pub fn get_metadata_val(&self) -> Option<types::MetadataValue> {
match self {
Self::MetaData(val) => Some(val.clone()),
Self::PaymentMethod(_) => None,
Self::CardBin(_) => None,
Self::CardType(_) => None,
Self::CardNetwork(_) => None,
Self::PayLaterType(_) => None,
Self::WalletType(_) => None,
Self::BankRedirectType(_) => None,
Self::CryptoType(_) => None,
Self::AuthenticationType(_) => None,
Self::CaptureMethod(_) => None,
Self::GiftCardType(_) => None,
Self::PaymentAmount(_) => None,
Self::PaymentCurrency(_) => None,
Self::BusinessCountry(_) => None,
Self::BillingCountry(_) => None,
Self::Connector(_) => None,
Self::BankTransferType(_) => None,
Self::UpiType(_) => None,
Self::BankDebitType(_) => None,
Self::RewardType(_) => None,
Self::VoucherType(_) => None,
Self::MandateAcceptanceType(_) => None,
Self::MandateType(_) => None,
Self::PaymentType(_) => None,
Self::BusinessLabel(_) => None,
Self::SetupFutureUsage(_) => None,
Self::CardRedirectType(_) => None,
Self::RealTimePaymentType(_) => None,
Self::OpenBankingType(_) => None,
Self::MobilePaymentType(_) => None,
}
}
pub fn get_str_val(&self) -> Option<types::StrValue> {
match self {
Self::CardBin(val) => Some(val.clone()),
_ => None,
}
}
pub fn get_num_value(&self) -> Option<types::NumValue> {
match self {
Self::PaymentAmount(val) => Some(val.clone()),
_ => None,
}
}
pub fn check_equality(v1: &Self, v2: &Self) -> bool {
match (v1, v2) {
(Self::PaymentMethod(pm1), Self::PaymentMethod(pm2)) => pm1 == pm2,
(Self::CardType(ct1), Self::CardType(ct2)) => ct1 == ct2,
(Self::CardNetwork(cn1), Self::CardNetwork(cn2)) => cn1 == cn2,
(Self::MetaData(md1), Self::MetaData(md2)) => md1 == md2,
(Self::PayLaterType(plt1), Self::PayLaterType(plt2)) => plt1 == plt2,
(Self::WalletType(wt1), Self::WalletType(wt2)) => wt1 == wt2,
(Self::BankDebitType(bdt1), Self::BankDebitType(bdt2)) => bdt1 == bdt2,
(Self::BankRedirectType(brt1), Self::BankRedirectType(brt2)) => brt1 == brt2,
(Self::BankTransferType(btt1), Self::BankTransferType(btt2)) => btt1 == btt2,
(Self::GiftCardType(gct1), Self::GiftCardType(gct2)) => gct1 == gct2,
(Self::CryptoType(ct1), Self::CryptoType(ct2)) => ct1 == ct2,
(Self::AuthenticationType(at1), Self::AuthenticationType(at2)) => at1 == at2,
(Self::CaptureMethod(cm1), Self::CaptureMethod(cm2)) => cm1 == cm2,
(Self::PaymentCurrency(pc1), Self::PaymentCurrency(pc2)) => pc1 == pc2,
(Self::BusinessCountry(c1), Self::BusinessCountry(c2)) => c1 == c2,
(Self::BillingCountry(c1), Self::BillingCountry(c2)) => c1 == c2,
(Self::PaymentType(pt1), Self::PaymentType(pt2)) => pt1 == pt2,
(Self::MandateType(mt1), Self::MandateType(mt2)) => mt1 == mt2,
(Self::MandateAcceptanceType(mat1), Self::MandateAcceptanceType(mat2)) => mat1 == mat2,
(Self::RewardType(rt1), Self::RewardType(rt2)) => rt1 == rt2,
(Self::RealTimePaymentType(rtp1), Self::RealTimePaymentType(rtp2)) => rtp1 == rtp2,
(Self::Connector(c1), Self::Connector(c2)) => c1 == c2,
(Self::BusinessLabel(bl1), Self::BusinessLabel(bl2)) => bl1 == bl2,
(Self::SetupFutureUsage(sfu1), Self::SetupFutureUsage(sfu2)) => sfu1 == sfu2,
(Self::UpiType(ut1), Self::UpiType(ut2)) => ut1 == ut2,
(Self::VoucherType(vt1), Self::VoucherType(vt2)) => vt1 == vt2,
(Self::CardRedirectType(crt1), Self::CardRedirectType(crt2)) => crt1 == crt2,
_ => false,
}
}
}
#[cfg(feature = "payouts")]
#[derive(
Debug,
Clone,
Hash,
PartialEq,
Eq,
serde::Serialize,
strum::Display,
strum::EnumIter,
strum::VariantNames,
strum::EnumString,
strum::EnumMessage,
strum::EnumProperty,
)]
pub enum PayoutDirKeyKind {
#[strum(
serialize = "country",
serialize = "business_country",
detailed_message = "Country of the business unit",
props(Category = "Merchant")
)]
#[serde(rename = "business_country", alias = "country")]
BusinessCountry,
#[strum(
serialize = "billing_country",
detailed_message = "Country of the billing address of the customer",
props(Category = "Customer")
)]
#[serde(rename = "billing_country")]
BillingCountry,
#[strum(
serialize = "business_label",
detailed_message = "Identifier for business unit",
props(Category = "Merchant")
)]
#[serde(rename = "business_label")]
BusinessLabel,
#[strum(
serialize = "amount",
detailed_message = "Value of the transaction",
props(Category = "Order details")
)]
#[serde(rename = "amount")]
PayoutAmount,
#[strum(
serialize = "payment_method",
detailed_message = "Different modes of payout - eg. cards, wallets, banks",
props(Category = "Payout Methods")
)]
#[serde(rename = "payment_method")]
PayoutType,
#[strum(
serialize = "wallet",
detailed_message = "Supported types of Wallets for payouts",
props(Category = "Payout Methods Type")
)]
#[serde(rename = "wallet")]
WalletType,
#[strum(
serialize = "bank_transfer",
detailed_message = "Supported types of Bank transfer types for payouts",
props(Category = "Payout Methods Type")
)]
#[serde(rename = "bank_transfer")]
BankTransferType,
}
#[cfg(feature = "payouts")]
#[derive(
Debug, Clone, Hash, PartialEq, Eq, serde::Serialize, strum::Display, strum::VariantNames,
)]
pub enum PayoutDirValue {
#[serde(rename = "business_country", alias = "country")]
BusinessCountry(enums::Country),
#[serde(rename = "billing_country")]
BillingCountry(enums::Country),
#[serde(rename = "business_label")]
BusinessLabel(types::StrValue),
#[serde(rename = "amount")]
PayoutAmount(types::NumValue),
#[serde(rename = "payment_method")]
PayoutType(common_enums::PayoutType),
#[serde(rename = "wallet")]
WalletType(enums::PayoutWalletType),
#[serde(rename = "bank_transfer")]
BankTransferType(enums::PayoutBankTransferType),
}
#[derive(Debug, Clone)]
pub enum DirComparisonLogic {
NegativeConjunction,
PositiveDisjunction,
}
#[derive(Debug, Clone)]
pub struct DirComparison {
pub values: Vec<DirValue>,
pub logic: DirComparisonLogic,
pub metadata: types::Metadata,
}
pub type DirIfCondition = Vec<DirComparison>;
#[derive(Debug, Clone)]
pub struct DirIfStatement {
pub condition: DirIfCondition,
pub nested: Option<Vec<DirIfStatement>>,
}
#[derive(Debug, Clone)]
pub struct DirRule<O> {
pub name: String,
pub connector_selection: O,
pub statements: Vec<DirIfStatement>,
}
#[derive(Debug, Clone)]
pub struct DirProgram<O> {
pub default_selection: O,
pub rules: Vec<DirRule<O>>,
pub metadata: types::Metadata,
}
#[cfg(test)]
mod test {
#![allow(clippy::expect_used)]
use rustc_hash::FxHashMap;
use strum::IntoEnumIterator;
use super::*;
#[test]
fn test_consistent_dir_key_naming() {
let mut key_names: FxHashMap<DirKeyKind, String> = FxHashMap::default();
for key in DirKeyKind::iter() {
if matches!(key, DirKeyKind::Connector) {
continue;
}
let json_str = if let DirKeyKind::MetaData = key {
r#""metadata""#.to_string()
} else {
serde_json::to_string(&key).expect("JSON Serialization")
};
let display_str = key.to_string();
assert_eq!(
json_str.get(1..json_str.len() - 1).expect("Value metadata"),
display_str
);
key_names.insert(key, display_str);
}
let values = vec![
dirval!(PaymentMethod = Card),
dirval!(CardBin s= "123456"),
dirval!(CardType = Credit),
dirval!(CardNetwork = Visa),
dirval!(PayLaterType = Klarna),
dirval!(WalletType = Paypal),
dirval!(BankRedirectType = Sofort),
dirval!(BankDebitType = Bacs),
dirval!(CryptoType = CryptoCurrency),
dirval!("" = "metadata"),
dirval!(PaymentAmount = 100),
dirval!(PaymentCurrency = USD),
dirval!(CardRedirectType = Benefit),
dirval!(AuthenticationType = ThreeDs),
dirval!(CaptureMethod = Manual),
dirval!(BillingCountry = UnitedStatesOfAmerica),
dirval!(BusinessCountry = France),
];
for val in values {
let json_val = serde_json::to_value(&val).expect("JSON Value Serialization");
let json_key = json_val
.as_object()
.expect("Serialized Object")
.get("key")
.expect("Object Key");
let value_str = json_key.as_str().expect("Value string");
let dir_key = val.get_key();
let key_name = key_names.get(&dir_key.kind).expect("Key name");
assert_eq!(key_name, value_str);
}
}
#[cfg(feature = "ast_parser")]
#[test]
fn test_allowed_dir_keys() {
use crate::types::DummyOutput;
let program_str = r#"
default: ["stripe", "adyen"]
rule_1: ["stripe"]
{
payment_method = card
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let out = ast::lowering::lower_program::<DummyOutput>(program);
assert!(out.is_ok())
}
#[cfg(feature = "ast_parser")]
#[test]
fn test_not_allowed_dir_keys() {
use crate::types::DummyOutput;
let program_str = r#"
default: ["stripe", "adyen"]
rule_1: ["stripe"]
{
bank_debit = ach
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let out = ast::lowering::lower_program::<DummyOutput>(program);
assert!(out.is_err())
}
}
| 7,424 | 963 |
hyperswitch | crates/euclid/src/frontend/ast.rs | .rs | pub mod lowering;
#[cfg(feature = "ast_parser")]
pub mod parser;
use common_enums::RoutableConnectors;
use common_utils::types::MinorUnit;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use crate::types::{DataType, Metadata};
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]
pub struct ConnectorChoice {
pub connector: RoutableConnectors,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ToSchema)]
pub struct MetadataValue {
pub key: String,
pub value: String,
}
/// Represents a value in the DSL
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ToSchema)]
#[serde(tag = "type", content = "value", rename_all = "snake_case")]
pub enum ValueType {
/// Represents a number literal
Number(MinorUnit),
/// Represents an enum variant
EnumVariant(String),
/// Represents a Metadata variant
MetadataVariant(MetadataValue),
/// Represents a arbitrary String value
StrValue(String),
/// Represents an array of numbers. This is basically used for
/// "one of the given numbers" operations
/// eg: payment.method.amount = (1, 2, 3)
NumberArray(Vec<MinorUnit>),
/// Similar to NumberArray but for enum variants
/// eg: payment.method.cardtype = (debit, credit)
EnumVariantArray(Vec<String>),
/// Like a number array but can include comparisons. Useful for
/// conditions like "500 < amount < 1000"
/// eg: payment.amount = (> 500, < 1000)
NumberComparisonArray(Vec<NumberComparison>),
}
impl ValueType {
pub fn get_type(&self) -> DataType {
match self {
Self::Number(_) => DataType::Number,
Self::StrValue(_) => DataType::StrValue,
Self::MetadataVariant(_) => DataType::MetadataValue,
Self::EnumVariant(_) => DataType::EnumVariant,
Self::NumberComparisonArray(_) => DataType::Number,
Self::NumberArray(_) => DataType::Number,
Self::EnumVariantArray(_) => DataType::EnumVariant,
}
}
}
/// Represents a number comparison for "NumberComparisonArrayValue"
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct NumberComparison {
pub comparison_type: ComparisonType,
pub number: MinorUnit,
}
/// Conditional comparison type
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum ComparisonType {
Equal,
NotEqual,
LessThan,
LessThanEqual,
GreaterThan,
GreaterThanEqual,
}
/// Represents a single comparison condition.
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct Comparison {
/// The left hand side which will always be a domain input identifier like "payment.method.cardtype"
pub lhs: String,
/// The comparison operator
pub comparison: ComparisonType,
/// The value to compare against
pub value: ValueType,
/// Additional metadata that the Static Analyzer and Backend does not touch.
/// This can be used to store useful information for the frontend and is required for communication
/// between the static analyzer and the frontend.
#[schema(value_type=HashMap<String, serde_json::Value>)]
pub metadata: Metadata,
}
/// Represents all the conditions of an IF statement
/// eg:
///
/// ```text
/// payment.method = card & payment.method.cardtype = debit & payment.method.network = diners
/// ```
pub type IfCondition = Vec<Comparison>;
/// Represents an IF statement with conditions and optional nested IF statements
///
/// ```text
/// payment.method = card {
/// payment.method.cardtype = (credit, debit) {
/// payment.method.network = (amex, rupay, diners)
/// }
/// }
/// ```
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct IfStatement {
#[schema(value_type=Vec<Comparison>)]
pub condition: IfCondition,
pub nested: Option<Vec<IfStatement>>,
}
/// Represents a rule
///
/// ```text
/// rule_name: [stripe, adyen, checkout]
/// {
/// payment.method = card {
/// payment.method.cardtype = (credit, debit) {
/// payment.method.network = (amex, rupay, diners)
/// }
///
/// payment.method.cardtype = credit
/// }
/// }
/// ```
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
#[aliases(RuleConnectorSelection = Rule<ConnectorSelection>)]
pub struct Rule<O> {
pub name: String,
#[serde(alias = "routingOutput")]
pub connector_selection: O,
pub statements: Vec<IfStatement>,
}
/// The program, having a default connector selection and
/// a bunch of rules. Also can hold arbitrary metadata.
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
#[aliases(ProgramConnectorSelection = Program<ConnectorSelection>)]
pub struct Program<O> {
pub default_selection: O,
#[schema(value_type=RuleConnectorSelection)]
pub rules: Vec<Rule<O>>,
#[schema(value_type=HashMap<String, serde_json::Value>)]
pub metadata: Metadata,
}
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct RoutableConnectorChoice {
#[serde(skip)]
pub choice_kind: RoutableChoiceKind,
pub connector: RoutableConnectors,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
}
#[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)]
pub enum RoutableChoiceKind {
OnlyConnector,
#[default]
FullStruct,
}
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct ConnectorVolumeSplit {
pub connector: RoutableConnectorChoice,
pub split: u8,
}
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum ConnectorSelection {
Priority(Vec<RoutableConnectorChoice>),
VolumeSplit(Vec<ConnectorVolumeSplit>),
}
| 1,366 | 964 |
hyperswitch | crates/euclid/src/frontend/ast/parser.rs | .rs | use common_utils::types::MinorUnit;
use nom::{
branch, bytes::complete, character::complete as pchar, combinator, error, multi, sequence,
};
use crate::{frontend::ast, types::DummyOutput};
pub type ParseResult<T, U> = nom::IResult<T, U, error::VerboseError<T>>;
pub enum EuclidError {
InvalidPercentage(String),
InvalidConnector(String),
InvalidOperator(String),
InvalidNumber(String),
}
pub trait EuclidParsable: Sized {
fn parse_output(input: &str) -> ParseResult<&str, Self>;
}
impl EuclidParsable for DummyOutput {
fn parse_output(input: &str) -> ParseResult<&str, Self> {
let string_w = sequence::delimited(
skip_ws(complete::tag("\"")),
complete::take_while(|c| c != '"'),
skip_ws(complete::tag("\"")),
);
let full_sequence = multi::many0(sequence::preceded(
skip_ws(complete::tag(",")),
sequence::delimited(
skip_ws(complete::tag("\"")),
complete::take_while(|c| c != '"'),
skip_ws(complete::tag("\"")),
),
));
let sequence = sequence::pair(string_w, full_sequence);
error::context(
"dummy_strings",
combinator::map(
sequence::delimited(
skip_ws(complete::tag("[")),
sequence,
skip_ws(complete::tag("]")),
),
|out: (&str, Vec<&str>)| {
let mut first = out.1;
first.insert(0, out.0);
let v = first.iter().map(|s| s.to_string()).collect();
Self { outputs: v }
},
),
)(input)
}
}
pub fn skip_ws<'a, F, O>(inner: F) -> impl FnMut(&'a str) -> ParseResult<&'a str, O>
where
F: FnMut(&'a str) -> ParseResult<&'a str, O> + 'a,
{
sequence::preceded(pchar::multispace0, inner)
}
pub fn num_i64(input: &str) -> ParseResult<&str, i64> {
error::context(
"num_i32",
combinator::map_res(
complete::take_while1(|c: char| c.is_ascii_digit()),
|o: &str| {
o.parse::<i64>()
.map_err(|_| EuclidError::InvalidNumber(o.to_string()))
},
),
)(input)
}
pub fn string_str(input: &str) -> ParseResult<&str, String> {
error::context(
"String",
combinator::map(
sequence::delimited(
complete::tag("\""),
complete::take_while1(|c: char| c != '"'),
complete::tag("\""),
),
|val: &str| val.to_string(),
),
)(input)
}
pub fn identifier(input: &str) -> ParseResult<&str, String> {
error::context(
"identifier",
combinator::map(
sequence::pair(
complete::take_while1(|c: char| c.is_ascii_alphabetic() || c == '_'),
complete::take_while(|c: char| c.is_ascii_alphanumeric() || c == '_'),
),
|out: (&str, &str)| out.0.to_string() + out.1,
),
)(input)
}
pub fn percentage(input: &str) -> ParseResult<&str, u8> {
error::context(
"volume_split_percentage",
combinator::map_res(
sequence::terminated(
complete::take_while_m_n(1, 2, |c: char| c.is_ascii_digit()),
complete::tag("%"),
),
|o: &str| {
o.parse::<u8>()
.map_err(|_| EuclidError::InvalidPercentage(o.to_string()))
},
),
)(input)
}
pub fn number_value(input: &str) -> ParseResult<&str, ast::ValueType> {
error::context(
"number_value",
combinator::map(num_i64, |n| ast::ValueType::Number(MinorUnit::new(n))),
)(input)
}
pub fn str_value(input: &str) -> ParseResult<&str, ast::ValueType> {
error::context(
"str_value",
combinator::map(string_str, ast::ValueType::StrValue),
)(input)
}
pub fn enum_value_string(input: &str) -> ParseResult<&str, String> {
combinator::map(
sequence::pair(
complete::take_while1(|c: char| c.is_ascii_alphabetic() || c == '_'),
complete::take_while(|c: char| c.is_ascii_alphanumeric() || c == '_'),
),
|out: (&str, &str)| out.0.to_string() + out.1,
)(input)
}
pub fn enum_variant_value(input: &str) -> ParseResult<&str, ast::ValueType> {
error::context(
"enum_variant_value",
combinator::map(enum_value_string, ast::ValueType::EnumVariant),
)(input)
}
pub fn number_array_value(input: &str) -> ParseResult<&str, ast::ValueType> {
fn num_minor_unit(input: &str) -> ParseResult<&str, MinorUnit> {
combinator::map(num_i64, MinorUnit::new)(input)
}
let many_with_comma = multi::many0(sequence::preceded(
skip_ws(complete::tag(",")),
skip_ws(num_minor_unit),
));
let full_sequence = sequence::pair(skip_ws(num_minor_unit), many_with_comma);
error::context(
"number_array_value",
combinator::map(
sequence::delimited(
skip_ws(complete::tag("(")),
full_sequence,
skip_ws(complete::tag(")")),
),
|tup: (MinorUnit, Vec<MinorUnit>)| {
let mut rest = tup.1;
rest.insert(0, tup.0);
ast::ValueType::NumberArray(rest)
},
),
)(input)
}
pub fn enum_variant_array_value(input: &str) -> ParseResult<&str, ast::ValueType> {
let many_with_comma = multi::many0(sequence::preceded(
skip_ws(complete::tag(",")),
skip_ws(enum_value_string),
));
let full_sequence = sequence::pair(skip_ws(enum_value_string), many_with_comma);
error::context(
"enum_variant_array_value",
combinator::map(
sequence::delimited(
skip_ws(complete::tag("(")),
full_sequence,
skip_ws(complete::tag(")")),
),
|tup: (String, Vec<String>)| {
let mut rest = tup.1;
rest.insert(0, tup.0);
ast::ValueType::EnumVariantArray(rest)
},
),
)(input)
}
pub fn number_comparison(input: &str) -> ParseResult<&str, ast::NumberComparison> {
let operator = combinator::map_res(
branch::alt((
complete::tag(">="),
complete::tag("<="),
complete::tag(">"),
complete::tag("<"),
)),
|s: &str| match s {
">=" => Ok(ast::ComparisonType::GreaterThanEqual),
"<=" => Ok(ast::ComparisonType::LessThanEqual),
">" => Ok(ast::ComparisonType::GreaterThan),
"<" => Ok(ast::ComparisonType::LessThan),
_ => Err(EuclidError::InvalidOperator(s.to_string())),
},
);
error::context(
"number_comparison",
combinator::map(
sequence::pair(operator, num_i64),
|tup: (ast::ComparisonType, i64)| ast::NumberComparison {
comparison_type: tup.0,
number: MinorUnit::new(tup.1),
},
),
)(input)
}
pub fn number_comparison_array_value(input: &str) -> ParseResult<&str, ast::ValueType> {
let many_with_comma = multi::many0(sequence::preceded(
skip_ws(complete::tag(",")),
skip_ws(number_comparison),
));
let full_sequence = sequence::pair(skip_ws(number_comparison), many_with_comma);
error::context(
"number_comparison_array_value",
combinator::map(
sequence::delimited(
skip_ws(complete::tag("(")),
full_sequence,
skip_ws(complete::tag(")")),
),
|tup: (ast::NumberComparison, Vec<ast::NumberComparison>)| {
let mut rest = tup.1;
rest.insert(0, tup.0);
ast::ValueType::NumberComparisonArray(rest)
},
),
)(input)
}
pub fn value_type(input: &str) -> ParseResult<&str, ast::ValueType> {
error::context(
"value_type",
branch::alt((
number_value,
enum_variant_value,
enum_variant_array_value,
number_array_value,
number_comparison_array_value,
str_value,
)),
)(input)
}
pub fn comparison_type(input: &str) -> ParseResult<&str, ast::ComparisonType> {
error::context(
"comparison_operator",
combinator::map_res(
branch::alt((
complete::tag("/="),
complete::tag(">="),
complete::tag("<="),
complete::tag("="),
complete::tag(">"),
complete::tag("<"),
)),
|s: &str| match s {
"/=" => Ok(ast::ComparisonType::NotEqual),
">=" => Ok(ast::ComparisonType::GreaterThanEqual),
"<=" => Ok(ast::ComparisonType::LessThanEqual),
"=" => Ok(ast::ComparisonType::Equal),
">" => Ok(ast::ComparisonType::GreaterThan),
"<" => Ok(ast::ComparisonType::LessThan),
_ => Err(EuclidError::InvalidOperator(s.to_string())),
},
),
)(input)
}
pub fn comparison(input: &str) -> ParseResult<&str, ast::Comparison> {
error::context(
"condition",
combinator::map(
sequence::tuple((
skip_ws(complete::take_while1(|c: char| {
c.is_ascii_alphabetic() || c == '.' || c == '_'
})),
skip_ws(comparison_type),
skip_ws(value_type),
)),
|tup: (&str, ast::ComparisonType, ast::ValueType)| ast::Comparison {
lhs: tup.0.to_string(),
comparison: tup.1,
value: tup.2,
metadata: std::collections::HashMap::new(),
},
),
)(input)
}
pub fn arbitrary_comparison(input: &str) -> ParseResult<&str, ast::Comparison> {
error::context(
"condition",
combinator::map(
sequence::tuple((
skip_ws(string_str),
skip_ws(comparison_type),
skip_ws(string_str),
)),
|tup: (String, ast::ComparisonType, String)| ast::Comparison {
lhs: "metadata".to_string(),
comparison: tup.1,
value: ast::ValueType::MetadataVariant(ast::MetadataValue {
key: tup.0,
value: tup.2,
}),
metadata: std::collections::HashMap::new(),
},
),
)(input)
}
pub fn comparison_array(input: &str) -> ParseResult<&str, Vec<ast::Comparison>> {
let many_with_ampersand = error::context(
"many_with_amp",
multi::many0(sequence::preceded(skip_ws(complete::tag("&")), comparison)),
);
let full_sequence = sequence::pair(
skip_ws(branch::alt((comparison, arbitrary_comparison))),
many_with_ampersand,
);
error::context(
"comparison_array",
combinator::map(
full_sequence,
|tup: (ast::Comparison, Vec<ast::Comparison>)| {
let mut rest = tup.1;
rest.insert(0, tup.0);
rest
},
),
)(input)
}
pub fn if_statement(input: &str) -> ParseResult<&str, ast::IfStatement> {
let nested_block = sequence::delimited(
skip_ws(complete::tag("{")),
multi::many0(if_statement),
skip_ws(complete::tag("}")),
);
error::context(
"if_statement",
combinator::map(
sequence::pair(comparison_array, combinator::opt(nested_block)),
|tup: (ast::IfCondition, Option<Vec<ast::IfStatement>>)| ast::IfStatement {
condition: tup.0,
nested: tup.1,
},
),
)(input)
}
pub fn rule_conditions_array(input: &str) -> ParseResult<&str, Vec<ast::IfStatement>> {
error::context(
"rules_array",
sequence::delimited(
skip_ws(complete::tag("{")),
multi::many1(if_statement),
skip_ws(complete::tag("}")),
),
)(input)
}
pub fn rule<O: EuclidParsable>(input: &str) -> ParseResult<&str, ast::Rule<O>> {
let rule_name = error::context(
"rule_name",
combinator::map(
skip_ws(sequence::pair(
complete::take_while1(|c: char| c.is_ascii_alphabetic() || c == '_'),
complete::take_while(|c: char| c.is_ascii_alphanumeric() || c == '_'),
)),
|out: (&str, &str)| out.0.to_string() + out.1,
),
);
let connector_selection = error::context(
"parse_output",
sequence::preceded(skip_ws(complete::tag(":")), output),
);
error::context(
"rule",
combinator::map(
sequence::tuple((rule_name, connector_selection, rule_conditions_array)),
|tup: (String, O, Vec<ast::IfStatement>)| ast::Rule {
name: tup.0,
connector_selection: tup.1,
statements: tup.2,
},
),
)(input)
}
pub fn output<O: EuclidParsable>(input: &str) -> ParseResult<&str, O> {
O::parse_output(input)
}
pub fn default_output<O: EuclidParsable + 'static>(input: &str) -> ParseResult<&str, O> {
error::context(
"default_output",
sequence::preceded(
sequence::pair(skip_ws(complete::tag("default")), skip_ws(pchar::char(':'))),
skip_ws(output),
),
)(input)
}
pub fn program<O: EuclidParsable + 'static>(input: &str) -> ParseResult<&str, ast::Program<O>> {
error::context(
"program",
combinator::map(
sequence::pair(default_output, multi::many1(skip_ws(rule::<O>))),
|tup: (O, Vec<ast::Rule<O>>)| ast::Program {
default_selection: tup.0,
rules: tup.1,
metadata: std::collections::HashMap::new(),
},
),
)(input)
}
| 3,334 | 965 |
hyperswitch | crates/euclid/src/frontend/ast/lowering.rs | .rs | //! Analysis for the Lowering logic in ast
//!
//!Certain functions that can be used to perform the complete lowering of ast to dir.
//!This includes lowering of enums, numbers, strings as well as Comparison logics.
use std::str::FromStr;
use crate::{
dssa::types::{AnalysisError, AnalysisErrorType},
enums::CollectVariants,
frontend::{
ast,
dir::{self, enums as dir_enums, EuclidDirFilter},
},
types::{self, DataType},
};
/// lowers the provided key (enum variant) & value to the respective DirValue
///
/// For example
/// ```notrust
/// CardType = Visa
/// ```notrust
///
/// This serves for the purpose were we have the DirKey as an explicit Enum type and value as one
/// of the member of the same Enum.
/// So particularly it lowers a predefined Enum from DirKey to an Enum of DirValue.
macro_rules! lower_enum {
($key:ident, $value:ident) => {
match $value {
ast::ValueType::EnumVariant(ev) => Ok(vec![dir::DirValue::$key(
dir_enums::$key::from_str(&ev).map_err(|_| AnalysisErrorType::InvalidVariant {
key: dir::DirKeyKind::$key.to_string(),
got: ev,
expected: dir_enums::$key::variants(),
})?,
)]),
ast::ValueType::EnumVariantArray(eva) => eva
.into_iter()
.map(|ev| {
Ok(dir::DirValue::$key(
dir_enums::$key::from_str(&ev).map_err(|_| {
AnalysisErrorType::InvalidVariant {
key: dir::DirKeyKind::$key.to_string(),
got: ev,
expected: dir_enums::$key::variants(),
}
})?,
))
})
.collect(),
_ => Err(AnalysisErrorType::InvalidType {
key: dir::DirKeyKind::$key.to_string(),
expected: DataType::EnumVariant,
got: $value.get_type(),
}),
}
};
}
/// lowers the provided key for a numerical value
///
/// For example
/// ```notrust
/// payment_amount = 17052001
/// ```notrust
/// This is for the cases in which there are numerical values involved and they are lowered
/// accordingly on basis of the supplied key, currently payment_amount is the only key having this
/// use case
macro_rules! lower_number {
($key:ident, $value:ident, $comp:ident) => {
match $value {
ast::ValueType::Number(num) => Ok(vec![dir::DirValue::$key(types::NumValue {
number: num,
refinement: $comp.into(),
})]),
ast::ValueType::NumberArray(na) => na
.into_iter()
.map(|num| {
Ok(dir::DirValue::$key(types::NumValue {
number: num,
refinement: $comp.clone().into(),
}))
})
.collect(),
ast::ValueType::NumberComparisonArray(nca) => nca
.into_iter()
.map(|nc| {
Ok(dir::DirValue::$key(types::NumValue {
number: nc.number,
refinement: nc.comparison_type.into(),
}))
})
.collect(),
_ => Err(AnalysisErrorType::InvalidType {
key: dir::DirKeyKind::$key.to_string(),
expected: DataType::Number,
got: $value.get_type(),
}),
}
};
}
/// lowers the provided key & value to the respective DirValue
///
/// For example
/// ```notrust
/// card_bin = "123456"
/// ```notrust
///
/// This serves for the purpose were we have the DirKey as Card_bin and value as an arbitrary string
/// So particularly it lowers an arbitrary value to a predefined key.
macro_rules! lower_str {
($key:ident, $value:ident $(, $validation_closure:expr)?) => {
match $value {
ast::ValueType::StrValue(st) => {
$($validation_closure(&st)?;)?
Ok(vec![dir::DirValue::$key(types::StrValue { value: st })])
}
_ => Err(AnalysisErrorType::InvalidType {
key: dir::DirKeyKind::$key.to_string(),
expected: DataType::StrValue,
got: $value.get_type(),
}),
}
};
}
macro_rules! lower_metadata {
($key:ident, $value:ident) => {
match $value {
ast::ValueType::MetadataVariant(md) => {
Ok(vec![dir::DirValue::$key(types::MetadataValue {
key: md.key,
value: md.value,
})])
}
_ => Err(AnalysisErrorType::InvalidType {
key: dir::DirKeyKind::$key.to_string(),
expected: DataType::MetadataValue,
got: $value.get_type(),
}),
}
};
}
/// lowers the comparison operators for different subtle value types present
/// by throwing required errors for comparisons that can't be performed for a certain value type
/// for example
/// can't have greater/less than operations on enum types
fn lower_comparison_inner<O: EuclidDirFilter>(
comp: ast::Comparison,
) -> Result<Vec<dir::DirValue>, AnalysisErrorType> {
let key_enum = dir::DirKeyKind::from_str(comp.lhs.as_str())
.map_err(|_| AnalysisErrorType::InvalidKey(comp.lhs.clone()))?;
if !O::is_key_allowed(&key_enum) {
return Err(AnalysisErrorType::InvalidKey(key_enum.to_string()));
}
match (&comp.comparison, &comp.value) {
(
ast::ComparisonType::LessThan
| ast::ComparisonType::GreaterThan
| ast::ComparisonType::GreaterThanEqual
| ast::ComparisonType::LessThanEqual,
ast::ValueType::EnumVariant(_),
) => {
Err(AnalysisErrorType::InvalidComparison {
operator: comp.comparison.clone(),
value_type: DataType::EnumVariant,
})?;
}
(
ast::ComparisonType::LessThan
| ast::ComparisonType::GreaterThan
| ast::ComparisonType::GreaterThanEqual
| ast::ComparisonType::LessThanEqual,
ast::ValueType::NumberArray(_),
) => {
Err(AnalysisErrorType::InvalidComparison {
operator: comp.comparison.clone(),
value_type: DataType::Number,
})?;
}
(
ast::ComparisonType::LessThan
| ast::ComparisonType::GreaterThan
| ast::ComparisonType::GreaterThanEqual
| ast::ComparisonType::LessThanEqual,
ast::ValueType::EnumVariantArray(_),
) => {
Err(AnalysisErrorType::InvalidComparison {
operator: comp.comparison.clone(),
value_type: DataType::EnumVariant,
})?;
}
(
ast::ComparisonType::LessThan
| ast::ComparisonType::GreaterThan
| ast::ComparisonType::GreaterThanEqual
| ast::ComparisonType::LessThanEqual,
ast::ValueType::NumberComparisonArray(_),
) => {
Err(AnalysisErrorType::InvalidComparison {
operator: comp.comparison.clone(),
value_type: DataType::Number,
})?;
}
_ => {}
}
let value = comp.value;
let comparison = comp.comparison;
match key_enum {
dir::DirKeyKind::PaymentMethod => lower_enum!(PaymentMethod, value),
dir::DirKeyKind::CardType => lower_enum!(CardType, value),
dir::DirKeyKind::CardNetwork => lower_enum!(CardNetwork, value),
dir::DirKeyKind::PayLaterType => lower_enum!(PayLaterType, value),
dir::DirKeyKind::WalletType => lower_enum!(WalletType, value),
dir::DirKeyKind::BankDebitType => lower_enum!(BankDebitType, value),
dir::DirKeyKind::BankRedirectType => lower_enum!(BankRedirectType, value),
dir::DirKeyKind::CryptoType => lower_enum!(CryptoType, value),
dir::DirKeyKind::PaymentType => lower_enum!(PaymentType, value),
dir::DirKeyKind::MandateType => lower_enum!(MandateType, value),
dir::DirKeyKind::MandateAcceptanceType => lower_enum!(MandateAcceptanceType, value),
dir::DirKeyKind::RewardType => lower_enum!(RewardType, value),
dir::DirKeyKind::PaymentCurrency => lower_enum!(PaymentCurrency, value),
dir::DirKeyKind::AuthenticationType => lower_enum!(AuthenticationType, value),
dir::DirKeyKind::CaptureMethod => lower_enum!(CaptureMethod, value),
dir::DirKeyKind::BusinessCountry => lower_enum!(BusinessCountry, value),
dir::DirKeyKind::BillingCountry => lower_enum!(BillingCountry, value),
dir::DirKeyKind::SetupFutureUsage => lower_enum!(SetupFutureUsage, value),
dir::DirKeyKind::UpiType => lower_enum!(UpiType, value),
dir::DirKeyKind::OpenBankingType => lower_enum!(OpenBankingType, value),
dir::DirKeyKind::VoucherType => lower_enum!(VoucherType, value),
dir::DirKeyKind::GiftCardType => lower_enum!(GiftCardType, value),
dir::DirKeyKind::BankTransferType => lower_enum!(BankTransferType, value),
dir::DirKeyKind::CardRedirectType => lower_enum!(CardRedirectType, value),
dir::DirKeyKind::MobilePaymentType => lower_enum!(MobilePaymentType, value),
dir::DirKeyKind::RealTimePaymentType => lower_enum!(RealTimePaymentType, value),
dir::DirKeyKind::CardBin => {
let validation_closure = |st: &String| -> Result<(), AnalysisErrorType> {
if st.len() == 6 && st.chars().all(|x| x.is_ascii_digit()) {
Ok(())
} else {
Err(AnalysisErrorType::InvalidValue {
key: dir::DirKeyKind::CardBin,
value: st.clone(),
message: Some("Expected 6 digits".to_string()),
})
}
};
lower_str!(CardBin, value, validation_closure)
}
dir::DirKeyKind::BusinessLabel => lower_str!(BusinessLabel, value),
dir::DirKeyKind::MetaData => lower_metadata!(MetaData, value),
dir::DirKeyKind::PaymentAmount => lower_number!(PaymentAmount, value, comparison),
dir::DirKeyKind::Connector => Err(AnalysisErrorType::InvalidKey(
dir::DirKeyKind::Connector.to_string(),
)),
}
}
/// returns all the comparison values by matching them appropriately to ComparisonTypes and in turn
/// calls the lower_comparison_inner function
fn lower_comparison<O: EuclidDirFilter>(
comp: ast::Comparison,
) -> Result<dir::DirComparison, AnalysisError> {
let metadata = comp.metadata.clone();
let logic = match &comp.comparison {
ast::ComparisonType::Equal => dir::DirComparisonLogic::PositiveDisjunction,
ast::ComparisonType::NotEqual => dir::DirComparisonLogic::NegativeConjunction,
ast::ComparisonType::LessThan => dir::DirComparisonLogic::PositiveDisjunction,
ast::ComparisonType::LessThanEqual => dir::DirComparisonLogic::PositiveDisjunction,
ast::ComparisonType::GreaterThanEqual => dir::DirComparisonLogic::PositiveDisjunction,
ast::ComparisonType::GreaterThan => dir::DirComparisonLogic::PositiveDisjunction,
};
let values = lower_comparison_inner::<O>(comp).map_err(|etype| AnalysisError {
error_type: etype,
metadata: metadata.clone(),
})?;
Ok(dir::DirComparison {
values,
logic,
metadata,
})
}
/// lowers the if statement accordingly with a condition and following nested if statements (if
/// present)
fn lower_if_statement<O: EuclidDirFilter>(
stmt: ast::IfStatement,
) -> Result<dir::DirIfStatement, AnalysisError> {
Ok(dir::DirIfStatement {
condition: stmt
.condition
.into_iter()
.map(lower_comparison::<O>)
.collect::<Result<_, _>>()?,
nested: stmt
.nested
.map(|n| n.into_iter().map(lower_if_statement::<O>).collect())
.transpose()?,
})
}
/// lowers the rules supplied accordingly to DirRule struct by specifying the rule_name,
/// connector_selection and statements that are a bunch of if statements
pub fn lower_rule<O: EuclidDirFilter>(
rule: ast::Rule<O>,
) -> Result<dir::DirRule<O>, AnalysisError> {
Ok(dir::DirRule {
name: rule.name,
connector_selection: rule.connector_selection,
statements: rule
.statements
.into_iter()
.map(lower_if_statement::<O>)
.collect::<Result<_, _>>()?,
})
}
/// uses the above rules and lowers the whole ast Program into DirProgram by specifying
/// default_selection that is ast ConnectorSelection, a vector of DirRules and clones the metadata
/// whatever comes in the ast_program
pub fn lower_program<O: EuclidDirFilter>(
program: ast::Program<O>,
) -> Result<dir::DirProgram<O>, AnalysisError> {
Ok(dir::DirProgram {
default_selection: program.default_selection,
rules: program
.rules
.into_iter()
.map(lower_rule)
.collect::<Result<_, _>>()?,
metadata: program.metadata,
})
}
| 2,949 | 966 |
hyperswitch | crates/euclid/src/frontend/dir/enums.rs | .rs | use strum::VariantNames;
use crate::enums::collect_variants;
pub use crate::enums::{
AuthenticationType, CaptureMethod, CardNetwork, Country, Country as BusinessCountry,
Country as BillingCountry, CountryAlpha2, Currency as PaymentCurrency, MandateAcceptanceType,
MandateType, PaymentMethod, PaymentType, RoutableConnectors, SetupFutureUsage,
};
#[cfg(feature = "payouts")]
pub use crate::enums::{PayoutBankTransferType, PayoutType, PayoutWalletType};
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum CardType {
Credit,
Debit,
#[cfg(feature = "v2")]
Card,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum PayLaterType {
Affirm,
AfterpayClearpay,
Alma,
Klarna,
PayBright,
Walley,
Atome,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum WalletType {
GooglePay,
AmazonPay,
ApplePay,
Paypal,
AliPay,
AliPayHk,
MbWay,
MobilePay,
WeChatPay,
SamsungPay,
GoPay,
KakaoPay,
Twint,
Gcash,
Vipps,
Momo,
Dana,
TouchNGo,
Swish,
Cashapp,
Venmo,
Mifinity,
Paze,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum VoucherType {
Boleto,
Efecty,
PagoEfectivo,
RedCompra,
RedPagos,
Alfamart,
Indomaret,
SevenEleven,
Lawson,
MiniStop,
FamilyMart,
Seicomart,
PayEasy,
Oxxo,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum BankRedirectType {
Bizum,
Giropay,
Ideal,
Sofort,
Eft,
Eps,
BancontactCard,
Blik,
Interac,
LocalBankRedirect,
OnlineBankingCzechRepublic,
OnlineBankingFinland,
OnlineBankingPoland,
OnlineBankingSlovakia,
OnlineBankingFpx,
OnlineBankingThailand,
OpenBankingUk,
Przelewy24,
Trustly,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum OpenBankingType {
OpenBankingPIS,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum BankTransferType {
Multibanco,
Ach,
SepaBankTransfer,
Bacs,
BcaBankTransfer,
BniVa,
BriVa,
CimbVa,
DanamonVa,
MandiriVa,
PermataBankTransfer,
Pix,
Pse,
LocalBankTransfer,
InstantBankTransfer,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum GiftCardType {
PaySafeCard,
Givex,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum CardRedirectType {
Benefit,
Knet,
MomoAtm,
CardRedirect,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum MobilePaymentType {
DirectCarrierBilling,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum CryptoType {
CryptoCurrency,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum RealTimePaymentType {
Fps,
DuitNow,
PromptPay,
VietQr,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum UpiType {
UpiCollect,
UpiIntent,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum BankDebitType {
Ach,
Sepa,
Bacs,
Becs,
}
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
strum::Display,
strum::VariantNames,
strum::EnumIter,
strum::EnumString,
serde::Serialize,
serde::Deserialize,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum RewardType {
ClassicReward,
Evoucher,
}
collect_variants!(CardType);
collect_variants!(PayLaterType);
collect_variants!(WalletType);
collect_variants!(BankRedirectType);
collect_variants!(BankDebitType);
collect_variants!(CryptoType);
collect_variants!(RewardType);
collect_variants!(RealTimePaymentType);
collect_variants!(UpiType);
collect_variants!(VoucherType);
collect_variants!(GiftCardType);
collect_variants!(BankTransferType);
collect_variants!(CardRedirectType);
collect_variants!(OpenBankingType);
collect_variants!(MobilePaymentType);
| 1,955 | 967 |
hyperswitch | crates/euclid/src/frontend/dir/transformers.rs | .rs | use crate::{dirval, dssa::types::AnalysisErrorType, enums as global_enums, frontend::dir};
pub trait IntoDirValue {
fn into_dir_value(self) -> Result<dir::DirValue, AnalysisErrorType>;
}
impl IntoDirValue for (global_enums::PaymentMethodType, global_enums::PaymentMethod) {
fn into_dir_value(self) -> Result<dir::DirValue, AnalysisErrorType> {
match self.0 {
global_enums::PaymentMethodType::Credit => Ok(dirval!(CardType = Credit)),
global_enums::PaymentMethodType::Debit => Ok(dirval!(CardType = Debit)),
#[cfg(feature = "v2")]
global_enums::PaymentMethodType::Card => Ok(dirval!(CardType = Card)),
global_enums::PaymentMethodType::Giropay => Ok(dirval!(BankRedirectType = Giropay)),
global_enums::PaymentMethodType::Ideal => Ok(dirval!(BankRedirectType = Ideal)),
global_enums::PaymentMethodType::Sofort => Ok(dirval!(BankRedirectType = Sofort)),
global_enums::PaymentMethodType::DuitNow => Ok(dirval!(RealTimePaymentType = DuitNow)),
global_enums::PaymentMethodType::Eps => Ok(dirval!(BankRedirectType = Eps)),
global_enums::PaymentMethodType::Fps => Ok(dirval!(RealTimePaymentType = Fps)),
global_enums::PaymentMethodType::Klarna => Ok(dirval!(PayLaterType = Klarna)),
global_enums::PaymentMethodType::Affirm => Ok(dirval!(PayLaterType = Affirm)),
global_enums::PaymentMethodType::AfterpayClearpay => {
Ok(dirval!(PayLaterType = AfterpayClearpay))
}
global_enums::PaymentMethodType::AmazonPay => Ok(dirval!(WalletType = AmazonPay)),
global_enums::PaymentMethodType::GooglePay => Ok(dirval!(WalletType = GooglePay)),
global_enums::PaymentMethodType::ApplePay => Ok(dirval!(WalletType = ApplePay)),
global_enums::PaymentMethodType::Paypal => Ok(dirval!(WalletType = Paypal)),
global_enums::PaymentMethodType::CryptoCurrency => {
Ok(dirval!(CryptoType = CryptoCurrency))
}
global_enums::PaymentMethodType::Ach => match self.1 {
global_enums::PaymentMethod::BankDebit => Ok(dirval!(BankDebitType = Ach)),
global_enums::PaymentMethod::BankTransfer => Ok(dirval!(BankTransferType = Ach)),
global_enums::PaymentMethod::PayLater
| global_enums::PaymentMethod::Card
| global_enums::PaymentMethod::CardRedirect
| global_enums::PaymentMethod::Wallet
| global_enums::PaymentMethod::BankRedirect
| global_enums::PaymentMethod::Crypto
| global_enums::PaymentMethod::Reward
| global_enums::PaymentMethod::RealTimePayment
| global_enums::PaymentMethod::Upi
| global_enums::PaymentMethod::Voucher
| global_enums::PaymentMethod::OpenBanking
| global_enums::PaymentMethod::MobilePayment
| global_enums::PaymentMethod::GiftCard => Err(AnalysisErrorType::NotSupported),
},
global_enums::PaymentMethodType::Bacs => match self.1 {
global_enums::PaymentMethod::BankDebit => Ok(dirval!(BankDebitType = Bacs)),
global_enums::PaymentMethod::BankTransfer => Ok(dirval!(BankTransferType = Bacs)),
global_enums::PaymentMethod::PayLater
| global_enums::PaymentMethod::Card
| global_enums::PaymentMethod::CardRedirect
| global_enums::PaymentMethod::Wallet
| global_enums::PaymentMethod::BankRedirect
| global_enums::PaymentMethod::Crypto
| global_enums::PaymentMethod::Reward
| global_enums::PaymentMethod::RealTimePayment
| global_enums::PaymentMethod::Upi
| global_enums::PaymentMethod::Voucher
| global_enums::PaymentMethod::OpenBanking
| global_enums::PaymentMethod::MobilePayment
| global_enums::PaymentMethod::GiftCard => Err(AnalysisErrorType::NotSupported),
},
global_enums::PaymentMethodType::Becs => Ok(dirval!(BankDebitType = Becs)),
global_enums::PaymentMethodType::Sepa => Ok(dirval!(BankDebitType = Sepa)),
global_enums::PaymentMethodType::SepaBankTransfer => {
Ok(dirval!(BankTransferType = SepaBankTransfer))
}
global_enums::PaymentMethodType::AliPay => Ok(dirval!(WalletType = AliPay)),
global_enums::PaymentMethodType::AliPayHk => Ok(dirval!(WalletType = AliPayHk)),
global_enums::PaymentMethodType::BancontactCard => {
Ok(dirval!(BankRedirectType = BancontactCard))
}
global_enums::PaymentMethodType::Blik => Ok(dirval!(BankRedirectType = Blik)),
global_enums::PaymentMethodType::MbWay => Ok(dirval!(WalletType = MbWay)),
global_enums::PaymentMethodType::MobilePay => Ok(dirval!(WalletType = MobilePay)),
global_enums::PaymentMethodType::Cashapp => Ok(dirval!(WalletType = Cashapp)),
global_enums::PaymentMethodType::Multibanco => {
Ok(dirval!(BankTransferType = Multibanco))
}
global_enums::PaymentMethodType::Pix => Ok(dirval!(BankTransferType = Pix)),
global_enums::PaymentMethodType::Pse => Ok(dirval!(BankTransferType = Pse)),
global_enums::PaymentMethodType::Interac => Ok(dirval!(BankRedirectType = Interac)),
global_enums::PaymentMethodType::OnlineBankingCzechRepublic => {
Ok(dirval!(BankRedirectType = OnlineBankingCzechRepublic))
}
global_enums::PaymentMethodType::OnlineBankingFinland => {
Ok(dirval!(BankRedirectType = OnlineBankingFinland))
}
global_enums::PaymentMethodType::OnlineBankingPoland => {
Ok(dirval!(BankRedirectType = OnlineBankingPoland))
}
global_enums::PaymentMethodType::OnlineBankingSlovakia => {
Ok(dirval!(BankRedirectType = OnlineBankingSlovakia))
}
global_enums::PaymentMethodType::Swish => Ok(dirval!(WalletType = Swish)),
global_enums::PaymentMethodType::Trustly => Ok(dirval!(BankRedirectType = Trustly)),
global_enums::PaymentMethodType::Bizum => Ok(dirval!(BankRedirectType = Bizum)),
global_enums::PaymentMethodType::PayBright => Ok(dirval!(PayLaterType = PayBright)),
global_enums::PaymentMethodType::Walley => Ok(dirval!(PayLaterType = Walley)),
global_enums::PaymentMethodType::Przelewy24 => {
Ok(dirval!(BankRedirectType = Przelewy24))
}
global_enums::PaymentMethodType::PromptPay => {
Ok(dirval!(RealTimePaymentType = PromptPay))
}
global_enums::PaymentMethodType::WeChatPay => Ok(dirval!(WalletType = WeChatPay)),
global_enums::PaymentMethodType::ClassicReward => {
Ok(dirval!(RewardType = ClassicReward))
}
global_enums::PaymentMethodType::Evoucher => Ok(dirval!(RewardType = Evoucher)),
global_enums::PaymentMethodType::UpiCollect => Ok(dirval!(UpiType = UpiCollect)),
global_enums::PaymentMethodType::UpiIntent => Ok(dirval!(UpiType = UpiIntent)),
global_enums::PaymentMethodType::SamsungPay => Ok(dirval!(WalletType = SamsungPay)),
global_enums::PaymentMethodType::GoPay => Ok(dirval!(WalletType = GoPay)),
global_enums::PaymentMethodType::KakaoPay => Ok(dirval!(WalletType = KakaoPay)),
global_enums::PaymentMethodType::Twint => Ok(dirval!(WalletType = Twint)),
global_enums::PaymentMethodType::Gcash => Ok(dirval!(WalletType = Gcash)),
global_enums::PaymentMethodType::Vipps => Ok(dirval!(WalletType = Vipps)),
global_enums::PaymentMethodType::VietQr => Ok(dirval!(RealTimePaymentType = VietQr)),
global_enums::PaymentMethodType::Momo => Ok(dirval!(WalletType = Momo)),
global_enums::PaymentMethodType::Alma => Ok(dirval!(PayLaterType = Alma)),
global_enums::PaymentMethodType::Dana => Ok(dirval!(WalletType = Dana)),
global_enums::PaymentMethodType::OnlineBankingFpx => {
Ok(dirval!(BankRedirectType = OnlineBankingFpx))
}
global_enums::PaymentMethodType::LocalBankRedirect => {
Ok(dirval!(BankRedirectType = LocalBankRedirect))
}
global_enums::PaymentMethodType::OnlineBankingThailand => {
Ok(dirval!(BankRedirectType = OnlineBankingThailand))
}
global_enums::PaymentMethodType::TouchNGo => Ok(dirval!(WalletType = TouchNGo)),
global_enums::PaymentMethodType::Atome => Ok(dirval!(PayLaterType = Atome)),
global_enums::PaymentMethodType::Boleto => Ok(dirval!(VoucherType = Boleto)),
global_enums::PaymentMethodType::Efecty => Ok(dirval!(VoucherType = Efecty)),
global_enums::PaymentMethodType::PagoEfectivo => {
Ok(dirval!(VoucherType = PagoEfectivo))
}
global_enums::PaymentMethodType::RedCompra => Ok(dirval!(VoucherType = RedCompra)),
global_enums::PaymentMethodType::RedPagos => Ok(dirval!(VoucherType = RedPagos)),
global_enums::PaymentMethodType::Alfamart => Ok(dirval!(VoucherType = Alfamart)),
global_enums::PaymentMethodType::BcaBankTransfer => {
Ok(dirval!(BankTransferType = BcaBankTransfer))
}
global_enums::PaymentMethodType::BniVa => Ok(dirval!(BankTransferType = BniVa)),
global_enums::PaymentMethodType::BriVa => Ok(dirval!(BankTransferType = BriVa)),
global_enums::PaymentMethodType::CimbVa => Ok(dirval!(BankTransferType = CimbVa)),
global_enums::PaymentMethodType::DanamonVa => Ok(dirval!(BankTransferType = DanamonVa)),
global_enums::PaymentMethodType::Indomaret => Ok(dirval!(VoucherType = Indomaret)),
global_enums::PaymentMethodType::MandiriVa => Ok(dirval!(BankTransferType = MandiriVa)),
global_enums::PaymentMethodType::LocalBankTransfer => {
Ok(dirval!(BankTransferType = LocalBankTransfer))
}
global_enums::PaymentMethodType::InstantBankTransfer => {
Ok(dirval!(BankTransferType = InstantBankTransfer))
}
global_enums::PaymentMethodType::PermataBankTransfer => {
Ok(dirval!(BankTransferType = PermataBankTransfer))
}
global_enums::PaymentMethodType::PaySafeCard => Ok(dirval!(GiftCardType = PaySafeCard)),
global_enums::PaymentMethodType::SevenEleven => Ok(dirval!(VoucherType = SevenEleven)),
global_enums::PaymentMethodType::Lawson => Ok(dirval!(VoucherType = Lawson)),
global_enums::PaymentMethodType::MiniStop => Ok(dirval!(VoucherType = MiniStop)),
global_enums::PaymentMethodType::FamilyMart => Ok(dirval!(VoucherType = FamilyMart)),
global_enums::PaymentMethodType::Seicomart => Ok(dirval!(VoucherType = Seicomart)),
global_enums::PaymentMethodType::PayEasy => Ok(dirval!(VoucherType = PayEasy)),
global_enums::PaymentMethodType::Givex => Ok(dirval!(GiftCardType = Givex)),
global_enums::PaymentMethodType::Benefit => Ok(dirval!(CardRedirectType = Benefit)),
global_enums::PaymentMethodType::Knet => Ok(dirval!(CardRedirectType = Knet)),
global_enums::PaymentMethodType::OpenBankingUk => {
Ok(dirval!(BankRedirectType = OpenBankingUk))
}
global_enums::PaymentMethodType::MomoAtm => Ok(dirval!(CardRedirectType = MomoAtm)),
global_enums::PaymentMethodType::Oxxo => Ok(dirval!(VoucherType = Oxxo)),
global_enums::PaymentMethodType::CardRedirect => {
Ok(dirval!(CardRedirectType = CardRedirect))
}
global_enums::PaymentMethodType::Venmo => Ok(dirval!(WalletType = Venmo)),
global_enums::PaymentMethodType::Mifinity => Ok(dirval!(WalletType = Mifinity)),
global_enums::PaymentMethodType::OpenBankingPIS => {
Ok(dirval!(OpenBankingType = OpenBankingPIS))
}
global_enums::PaymentMethodType::Paze => Ok(dirval!(WalletType = Paze)),
global_enums::PaymentMethodType::DirectCarrierBilling => {
Ok(dirval!(MobilePaymentType = DirectCarrierBilling))
}
global_enums::PaymentMethodType::Eft => Ok(dirval!(BankRedirectType = Eft)),
}
}
}
| 3,037 | 968 |
hyperswitch | crates/euclid/src/frontend/dir/lowering.rs | .rs | //! Analysis of the lowering logic for the DIR
//!
//! Consists of certain functions that supports the lowering logic from DIR to VIR.
//! These includes the lowering of the DIR program and vector of rules , and the lowering of ifstatements
//! ,and comparisonsLogic and also the lowering of the enums of value variants from DIR to VIR.
use super::enums;
use crate::{
dssa::types::{AnalysisError, AnalysisErrorType},
enums as global_enums,
frontend::{dir, vir},
types::EuclidValue,
};
impl From<enums::CardType> for global_enums::PaymentMethodType {
fn from(value: enums::CardType) -> Self {
match value {
enums::CardType::Credit => Self::Credit,
enums::CardType::Debit => Self::Debit,
#[cfg(feature = "v2")]
enums::CardType::Card => Self::Card,
}
}
}
impl From<enums::PayLaterType> for global_enums::PaymentMethodType {
fn from(value: enums::PayLaterType) -> Self {
match value {
enums::PayLaterType::Affirm => Self::Affirm,
enums::PayLaterType::AfterpayClearpay => Self::AfterpayClearpay,
enums::PayLaterType::Alma => Self::Alma,
enums::PayLaterType::Klarna => Self::Klarna,
enums::PayLaterType::PayBright => Self::PayBright,
enums::PayLaterType::Walley => Self::Walley,
enums::PayLaterType::Atome => Self::Atome,
}
}
}
impl From<enums::WalletType> for global_enums::PaymentMethodType {
fn from(value: enums::WalletType) -> Self {
match value {
enums::WalletType::GooglePay => Self::GooglePay,
enums::WalletType::AmazonPay => Self::AmazonPay,
enums::WalletType::ApplePay => Self::ApplePay,
enums::WalletType::Paypal => Self::Paypal,
enums::WalletType::AliPay => Self::AliPay,
enums::WalletType::AliPayHk => Self::AliPayHk,
enums::WalletType::MbWay => Self::MbWay,
enums::WalletType::MobilePay => Self::MobilePay,
enums::WalletType::WeChatPay => Self::WeChatPay,
enums::WalletType::SamsungPay => Self::SamsungPay,
enums::WalletType::GoPay => Self::GoPay,
enums::WalletType::KakaoPay => Self::KakaoPay,
enums::WalletType::Twint => Self::Twint,
enums::WalletType::Gcash => Self::Gcash,
enums::WalletType::Vipps => Self::Vipps,
enums::WalletType::Momo => Self::Momo,
enums::WalletType::Dana => Self::Dana,
enums::WalletType::TouchNGo => Self::TouchNGo,
enums::WalletType::Swish => Self::Swish,
enums::WalletType::Cashapp => Self::Cashapp,
enums::WalletType::Venmo => Self::Venmo,
enums::WalletType::Mifinity => Self::Mifinity,
enums::WalletType::Paze => Self::Paze,
}
}
}
impl From<enums::BankDebitType> for global_enums::PaymentMethodType {
fn from(value: enums::BankDebitType) -> Self {
match value {
enums::BankDebitType::Ach => Self::Ach,
enums::BankDebitType::Sepa => Self::Sepa,
enums::BankDebitType::Bacs => Self::Bacs,
enums::BankDebitType::Becs => Self::Becs,
}
}
}
impl From<enums::UpiType> for global_enums::PaymentMethodType {
fn from(value: enums::UpiType) -> Self {
match value {
enums::UpiType::UpiCollect => Self::UpiCollect,
enums::UpiType::UpiIntent => Self::UpiIntent,
}
}
}
impl From<enums::VoucherType> for global_enums::PaymentMethodType {
fn from(value: enums::VoucherType) -> Self {
match value {
enums::VoucherType::Boleto => Self::Boleto,
enums::VoucherType::Efecty => Self::Efecty,
enums::VoucherType::PagoEfectivo => Self::PagoEfectivo,
enums::VoucherType::RedCompra => Self::RedCompra,
enums::VoucherType::RedPagos => Self::RedPagos,
enums::VoucherType::Alfamart => Self::Alfamart,
enums::VoucherType::Indomaret => Self::Indomaret,
enums::VoucherType::SevenEleven => Self::SevenEleven,
enums::VoucherType::Lawson => Self::Lawson,
enums::VoucherType::MiniStop => Self::MiniStop,
enums::VoucherType::FamilyMart => Self::FamilyMart,
enums::VoucherType::Seicomart => Self::Seicomart,
enums::VoucherType::PayEasy => Self::PayEasy,
enums::VoucherType::Oxxo => Self::Oxxo,
}
}
}
impl From<enums::BankTransferType> for global_enums::PaymentMethodType {
fn from(value: enums::BankTransferType) -> Self {
match value {
enums::BankTransferType::Multibanco => Self::Multibanco,
enums::BankTransferType::Pix => Self::Pix,
enums::BankTransferType::Pse => Self::Pse,
enums::BankTransferType::Ach => Self::Ach,
enums::BankTransferType::SepaBankTransfer => Self::Sepa,
enums::BankTransferType::Bacs => Self::Bacs,
enums::BankTransferType::BcaBankTransfer => Self::BcaBankTransfer,
enums::BankTransferType::BniVa => Self::BniVa,
enums::BankTransferType::BriVa => Self::BriVa,
enums::BankTransferType::CimbVa => Self::CimbVa,
enums::BankTransferType::DanamonVa => Self::DanamonVa,
enums::BankTransferType::MandiriVa => Self::MandiriVa,
enums::BankTransferType::PermataBankTransfer => Self::PermataBankTransfer,
enums::BankTransferType::LocalBankTransfer => Self::LocalBankTransfer,
enums::BankTransferType::InstantBankTransfer => Self::InstantBankTransfer,
}
}
}
impl From<enums::GiftCardType> for global_enums::PaymentMethodType {
fn from(value: enums::GiftCardType) -> Self {
match value {
enums::GiftCardType::PaySafeCard => Self::PaySafeCard,
enums::GiftCardType::Givex => Self::Givex,
}
}
}
impl From<enums::CardRedirectType> for global_enums::PaymentMethodType {
fn from(value: enums::CardRedirectType) -> Self {
match value {
enums::CardRedirectType::Benefit => Self::Benefit,
enums::CardRedirectType::Knet => Self::Knet,
enums::CardRedirectType::MomoAtm => Self::MomoAtm,
enums::CardRedirectType::CardRedirect => Self::CardRedirect,
}
}
}
impl From<enums::MobilePaymentType> for global_enums::PaymentMethodType {
fn from(value: enums::MobilePaymentType) -> Self {
match value {
enums::MobilePaymentType::DirectCarrierBilling => Self::DirectCarrierBilling,
}
}
}
impl From<enums::BankRedirectType> for global_enums::PaymentMethodType {
fn from(value: enums::BankRedirectType) -> Self {
match value {
enums::BankRedirectType::Bizum => Self::Bizum,
enums::BankRedirectType::Giropay => Self::Giropay,
enums::BankRedirectType::Ideal => Self::Ideal,
enums::BankRedirectType::Sofort => Self::Sofort,
enums::BankRedirectType::Eft => Self::Eft,
enums::BankRedirectType::Eps => Self::Eps,
enums::BankRedirectType::BancontactCard => Self::BancontactCard,
enums::BankRedirectType::Blik => Self::Blik,
enums::BankRedirectType::Interac => Self::Interac,
enums::BankRedirectType::LocalBankRedirect => Self::LocalBankRedirect,
enums::BankRedirectType::OnlineBankingCzechRepublic => Self::OnlineBankingCzechRepublic,
enums::BankRedirectType::OnlineBankingFinland => Self::OnlineBankingFinland,
enums::BankRedirectType::OnlineBankingPoland => Self::OnlineBankingPoland,
enums::BankRedirectType::OnlineBankingSlovakia => Self::OnlineBankingSlovakia,
enums::BankRedirectType::OnlineBankingFpx => Self::OnlineBankingFpx,
enums::BankRedirectType::OnlineBankingThailand => Self::OnlineBankingThailand,
enums::BankRedirectType::OpenBankingUk => Self::OpenBankingUk,
enums::BankRedirectType::Przelewy24 => Self::Przelewy24,
enums::BankRedirectType::Trustly => Self::Trustly,
}
}
}
impl From<enums::OpenBankingType> for global_enums::PaymentMethodType {
fn from(value: enums::OpenBankingType) -> Self {
match value {
enums::OpenBankingType::OpenBankingPIS => Self::OpenBankingPIS,
}
}
}
impl From<enums::CryptoType> for global_enums::PaymentMethodType {
fn from(value: enums::CryptoType) -> Self {
match value {
enums::CryptoType::CryptoCurrency => Self::CryptoCurrency,
}
}
}
impl From<enums::RewardType> for global_enums::PaymentMethodType {
fn from(value: enums::RewardType) -> Self {
match value {
enums::RewardType::ClassicReward => Self::ClassicReward,
enums::RewardType::Evoucher => Self::Evoucher,
}
}
}
impl From<enums::RealTimePaymentType> for global_enums::PaymentMethodType {
fn from(value: enums::RealTimePaymentType) -> Self {
match value {
enums::RealTimePaymentType::Fps => Self::Fps,
enums::RealTimePaymentType::DuitNow => Self::DuitNow,
enums::RealTimePaymentType::PromptPay => Self::PromptPay,
enums::RealTimePaymentType::VietQr => Self::VietQr,
}
}
}
/// Analyses of the lowering of the DirValues to EuclidValues .
///
/// For example,
/// ```notrust
/// DirValue::PaymentMethod::Cards -> EuclidValue::PaymentMethod::Cards
/// ```notrust
/// This is a function that lowers the Values of the DIR variants into the Value of the VIR variants.
/// The function for each DirValue variant creates a corresponding EuclidValue variants and if there
/// lacks any direct mapping, it return an Error.
fn lower_value(dir_value: dir::DirValue) -> Result<EuclidValue, AnalysisErrorType> {
Ok(match dir_value {
dir::DirValue::PaymentMethod(pm) => EuclidValue::PaymentMethod(pm),
dir::DirValue::CardBin(ci) => EuclidValue::CardBin(ci),
dir::DirValue::CardType(ct) => EuclidValue::PaymentMethodType(ct.into()),
dir::DirValue::CardNetwork(cn) => EuclidValue::CardNetwork(cn),
dir::DirValue::MetaData(md) => EuclidValue::Metadata(md),
dir::DirValue::PayLaterType(plt) => EuclidValue::PaymentMethodType(plt.into()),
dir::DirValue::WalletType(wt) => EuclidValue::PaymentMethodType(wt.into()),
dir::DirValue::UpiType(ut) => EuclidValue::PaymentMethodType(ut.into()),
dir::DirValue::VoucherType(vt) => EuclidValue::PaymentMethodType(vt.into()),
dir::DirValue::BankTransferType(btt) => EuclidValue::PaymentMethodType(btt.into()),
dir::DirValue::GiftCardType(gct) => EuclidValue::PaymentMethodType(gct.into()),
dir::DirValue::CardRedirectType(crt) => EuclidValue::PaymentMethodType(crt.into()),
dir::DirValue::BankRedirectType(brt) => EuclidValue::PaymentMethodType(brt.into()),
dir::DirValue::CryptoType(ct) => EuclidValue::PaymentMethodType(ct.into()),
dir::DirValue::RealTimePaymentType(rtpt) => EuclidValue::PaymentMethodType(rtpt.into()),
dir::DirValue::AuthenticationType(at) => EuclidValue::AuthenticationType(at),
dir::DirValue::CaptureMethod(cm) => EuclidValue::CaptureMethod(cm),
dir::DirValue::PaymentAmount(pa) => EuclidValue::PaymentAmount(pa),
dir::DirValue::PaymentCurrency(pc) => EuclidValue::PaymentCurrency(pc),
dir::DirValue::BusinessCountry(buc) => EuclidValue::BusinessCountry(buc),
dir::DirValue::BillingCountry(bic) => EuclidValue::BillingCountry(bic),
dir::DirValue::MandateAcceptanceType(mat) => EuclidValue::MandateAcceptanceType(mat),
dir::DirValue::MandateType(mt) => EuclidValue::MandateType(mt),
dir::DirValue::PaymentType(pt) => EuclidValue::PaymentType(pt),
dir::DirValue::Connector(_) => Err(AnalysisErrorType::UnsupportedProgramKey(
dir::DirKeyKind::Connector,
))?,
dir::DirValue::BankDebitType(bdt) => EuclidValue::PaymentMethodType(bdt.into()),
dir::DirValue::RewardType(rt) => EuclidValue::PaymentMethodType(rt.into()),
dir::DirValue::BusinessLabel(bl) => EuclidValue::BusinessLabel(bl),
dir::DirValue::SetupFutureUsage(sfu) => EuclidValue::SetupFutureUsage(sfu),
dir::DirValue::OpenBankingType(ob) => EuclidValue::PaymentMethodType(ob.into()),
dir::DirValue::MobilePaymentType(mp) => EuclidValue::PaymentMethodType(mp.into()),
})
}
fn lower_comparison(
dir_comparison: dir::DirComparison,
) -> Result<vir::ValuedComparison, AnalysisErrorType> {
Ok(vir::ValuedComparison {
values: dir_comparison
.values
.into_iter()
.map(lower_value)
.collect::<Result<_, _>>()?,
logic: match dir_comparison.logic {
dir::DirComparisonLogic::NegativeConjunction => {
vir::ValuedComparisonLogic::NegativeConjunction
}
dir::DirComparisonLogic::PositiveDisjunction => {
vir::ValuedComparisonLogic::PositiveDisjunction
}
},
metadata: dir_comparison.metadata,
})
}
fn lower_if_statement(
dir_if_statement: dir::DirIfStatement,
) -> Result<vir::ValuedIfStatement, AnalysisErrorType> {
Ok(vir::ValuedIfStatement {
condition: dir_if_statement
.condition
.into_iter()
.map(lower_comparison)
.collect::<Result<_, _>>()?,
nested: dir_if_statement
.nested
.map(|v| {
v.into_iter()
.map(lower_if_statement)
.collect::<Result<_, _>>()
})
.transpose()?,
})
}
fn lower_rule<O>(dir_rule: dir::DirRule<O>) -> Result<vir::ValuedRule<O>, AnalysisErrorType> {
Ok(vir::ValuedRule {
name: dir_rule.name,
connector_selection: dir_rule.connector_selection,
statements: dir_rule
.statements
.into_iter()
.map(lower_if_statement)
.collect::<Result<_, _>>()?,
})
}
pub fn lower_program<O>(
dir_program: dir::DirProgram<O>,
) -> Result<vir::ValuedProgram<O>, AnalysisError> {
Ok(vir::ValuedProgram {
default_selection: dir_program.default_selection,
rules: dir_program
.rules
.into_iter()
.map(lower_rule)
.collect::<Result<_, _>>()
.map_err(|e| AnalysisError {
error_type: e,
metadata: Default::default(),
})?,
metadata: dir_program.metadata,
})
}
| 3,676 | 969 |
hyperswitch | crates/euclid/src/dssa/truth.rs | .rs | use euclid_macros::knowledge;
use once_cell::sync::Lazy;
use crate::{dssa::graph::euclid_graph_prelude, frontend::dir};
pub static ANALYSIS_GRAPH: Lazy<hyperswitch_constraint_graph::ConstraintGraph<dir::DirValue>> =
Lazy::new(|| {
knowledge! {
// Payment Method should be `Card` for a CardType to be present
PaymentMethod(Card) ->> CardType(any);
// Payment Method should be `PayLater` for a PayLaterType to be present
PaymentMethod(PayLater) ->> PayLaterType(any);
// Payment Method should be `Wallet` for a WalletType to be present
PaymentMethod(Wallet) ->> WalletType(any);
// Payment Method should be `BankRedirect` for a BankRedirectType to
// be present
PaymentMethod(BankRedirect) ->> BankRedirectType(any);
// Payment Method should be `BankTransfer` for a BankTransferType to
// be present
PaymentMethod(BankTransfer) ->> BankTransferType(any);
// Payment Method should be `GiftCard` for a GiftCardType to
// be present
PaymentMethod(GiftCard) ->> GiftCardType(any);
// Payment Method should be `RealTimePayment` for a RealTimePaymentType to
// be present
PaymentMethod(RealTimePayment) ->> RealTimePaymentType(any);
}
});
| 308 | 970 |
hyperswitch | crates/euclid/src/dssa/utils.rs | .rs | pub struct Unpacker;
| 6 | 971 |
hyperswitch | crates/euclid/src/dssa/graph.rs | .rs | use std::{fmt::Debug, sync::Weak};
use hyperswitch_constraint_graph as cgraph;
use rustc_hash::{FxHashMap, FxHashSet};
use crate::{
dssa::types,
frontend::dir,
types::{DataType, Metadata},
};
pub mod euclid_graph_prelude {
pub use hyperswitch_constraint_graph as cgraph;
pub use rustc_hash::{FxHashMap, FxHashSet};
pub use strum::EnumIter;
pub use crate::{
dssa::graph::*,
frontend::dir::{enums::*, DirKey, DirKeyKind, DirValue},
types::*,
};
}
impl cgraph::KeyNode for dir::DirKey {}
impl cgraph::NodeViz for dir::DirKey {
fn viz(&self) -> String {
self.kind.to_string()
}
}
impl cgraph::ValueNode for dir::DirValue {
type Key = dir::DirKey;
fn get_key(&self) -> Self::Key {
Self::get_key(self)
}
}
impl cgraph::NodeViz for dir::DirValue {
fn viz(&self) -> String {
match self {
Self::PaymentMethod(pm) => pm.to_string(),
Self::CardBin(bin) => bin.value.clone(),
Self::CardType(ct) => ct.to_string(),
Self::CardNetwork(cn) => cn.to_string(),
Self::PayLaterType(plt) => plt.to_string(),
Self::WalletType(wt) => wt.to_string(),
Self::UpiType(ut) => ut.to_string(),
Self::BankTransferType(btt) => btt.to_string(),
Self::BankRedirectType(brt) => brt.to_string(),
Self::BankDebitType(bdt) => bdt.to_string(),
Self::CryptoType(ct) => ct.to_string(),
Self::RewardType(rt) => rt.to_string(),
Self::PaymentAmount(amt) => amt.number.to_string(),
Self::PaymentCurrency(curr) => curr.to_string(),
Self::AuthenticationType(at) => at.to_string(),
Self::CaptureMethod(cm) => cm.to_string(),
Self::BusinessCountry(bc) => bc.to_string(),
Self::BillingCountry(bc) => bc.to_string(),
Self::Connector(conn) => conn.connector.to_string(),
Self::MetaData(mv) => format!("[{} = {}]", mv.key, mv.value),
Self::MandateAcceptanceType(mat) => mat.to_string(),
Self::MandateType(mt) => mt.to_string(),
Self::PaymentType(pt) => pt.to_string(),
Self::VoucherType(vt) => vt.to_string(),
Self::GiftCardType(gct) => gct.to_string(),
Self::BusinessLabel(bl) => bl.value.to_string(),
Self::SetupFutureUsage(sfu) => sfu.to_string(),
Self::CardRedirectType(crt) => crt.to_string(),
Self::RealTimePaymentType(rtpt) => rtpt.to_string(),
Self::OpenBankingType(ob) => ob.to_string(),
Self::MobilePaymentType(mpt) => mpt.to_string(),
}
}
}
#[derive(Debug, Clone, serde::Serialize)]
#[serde(tag = "type", content = "details", rename_all = "snake_case")]
pub enum AnalysisError<V: cgraph::ValueNode> {
Graph(cgraph::GraphError<V>),
AssertionTrace {
trace: Weak<cgraph::AnalysisTrace<V>>,
metadata: Metadata,
},
NegationTrace {
trace: Weak<cgraph::AnalysisTrace<V>>,
metadata: Vec<Metadata>,
},
}
impl<V: cgraph::ValueNode> AnalysisError<V> {
fn assertion_from_graph_error(metadata: &Metadata, graph_error: cgraph::GraphError<V>) -> Self {
match graph_error {
cgraph::GraphError::AnalysisError(trace) => Self::AssertionTrace {
trace,
metadata: metadata.clone(),
},
other => Self::Graph(other),
}
}
fn negation_from_graph_error(
metadata: Vec<&Metadata>,
graph_error: cgraph::GraphError<V>,
) -> Self {
match graph_error {
cgraph::GraphError::AnalysisError(trace) => Self::NegationTrace {
trace,
metadata: metadata.iter().map(|m| (*m).clone()).collect(),
},
other => Self::Graph(other),
}
}
}
#[derive(Debug)]
pub struct AnalysisContext {
keywise_values: FxHashMap<dir::DirKey, FxHashSet<dir::DirValue>>,
}
impl AnalysisContext {
pub fn from_dir_values(vals: impl IntoIterator<Item = dir::DirValue>) -> Self {
let mut keywise_values: FxHashMap<dir::DirKey, FxHashSet<dir::DirValue>> =
FxHashMap::default();
for dir_val in vals {
let key = dir_val.get_key();
let set = keywise_values.entry(key).or_default();
set.insert(dir_val);
}
Self { keywise_values }
}
pub fn insert(&mut self, value: dir::DirValue) {
self.keywise_values
.entry(value.get_key())
.or_default()
.insert(value);
}
pub fn remove(&mut self, value: dir::DirValue) {
let set = self.keywise_values.entry(value.get_key()).or_default();
set.remove(&value);
if set.is_empty() {
self.keywise_values.remove(&value.get_key());
}
}
}
impl cgraph::CheckingContext for AnalysisContext {
type Value = dir::DirValue;
fn from_node_values<L>(vals: impl IntoIterator<Item = L>) -> Self
where
L: Into<Self::Value>,
{
let mut keywise_values: FxHashMap<dir::DirKey, FxHashSet<dir::DirValue>> =
FxHashMap::default();
for dir_val in vals.into_iter().map(L::into) {
let key = dir_val.get_key();
let set = keywise_values.entry(key).or_default();
set.insert(dir_val);
}
Self { keywise_values }
}
fn check_presence(
&self,
value: &cgraph::NodeValue<dir::DirValue>,
strength: cgraph::Strength,
) -> bool {
match value {
cgraph::NodeValue::Key(k) => {
self.keywise_values.contains_key(k) || matches!(strength, cgraph::Strength::Weak)
}
cgraph::NodeValue::Value(val) => {
let key = val.get_key();
let value_set = if let Some(set) = self.keywise_values.get(&key) {
set
} else {
return matches!(strength, cgraph::Strength::Weak);
};
match key.kind.get_type() {
DataType::EnumVariant | DataType::StrValue | DataType::MetadataValue => {
value_set.contains(val)
}
DataType::Number => val.get_num_value().is_some_and(|num_val| {
value_set.iter().any(|ctx_val| {
ctx_val
.get_num_value()
.is_some_and(|ctx_num_val| num_val.fits(&ctx_num_val))
})
}),
}
}
}
}
fn get_values_by_key(
&self,
key: &<Self::Value as cgraph::ValueNode>::Key,
) -> Option<Vec<Self::Value>> {
self.keywise_values
.get(key)
.map(|set| set.iter().cloned().collect())
}
}
pub trait CgraphExt {
fn key_analysis(
&self,
key: dir::DirKey,
ctx: &AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<(), cgraph::GraphError<dir::DirValue>>;
fn value_analysis(
&self,
val: dir::DirValue,
ctx: &AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<(), cgraph::GraphError<dir::DirValue>>;
fn check_value_validity(
&self,
val: dir::DirValue,
analysis_ctx: &AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<bool, cgraph::GraphError<dir::DirValue>>;
fn key_value_analysis(
&self,
val: dir::DirValue,
ctx: &AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<(), cgraph::GraphError<dir::DirValue>>;
fn assertion_analysis(
&self,
positive_ctx: &[(&dir::DirValue, &Metadata)],
analysis_ctx: &AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<(), AnalysisError<dir::DirValue>>;
fn negation_analysis(
&self,
negative_ctx: &[(&[dir::DirValue], &Metadata)],
analysis_ctx: &mut AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<(), AnalysisError<dir::DirValue>>;
fn perform_context_analysis(
&self,
ctx: &types::ConjunctiveContext<'_>,
memo: &mut cgraph::Memoization<dir::DirValue>,
domains: Option<&[String]>,
) -> Result<(), AnalysisError<dir::DirValue>>;
}
impl CgraphExt for cgraph::ConstraintGraph<dir::DirValue> {
fn key_analysis(
&self,
key: dir::DirKey,
ctx: &AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<(), cgraph::GraphError<dir::DirValue>> {
self.value_map
.get(&cgraph::NodeValue::Key(key))
.map_or(Ok(()), |node_id| {
self.check_node(
ctx,
*node_id,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
memo,
cycle_map,
domains,
)
})
}
fn value_analysis(
&self,
val: dir::DirValue,
ctx: &AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<(), cgraph::GraphError<dir::DirValue>> {
self.value_map
.get(&cgraph::NodeValue::Value(val))
.map_or(Ok(()), |node_id| {
self.check_node(
ctx,
*node_id,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
memo,
cycle_map,
domains,
)
})
}
fn check_value_validity(
&self,
val: dir::DirValue,
analysis_ctx: &AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<bool, cgraph::GraphError<dir::DirValue>> {
let maybe_node_id = self.value_map.get(&cgraph::NodeValue::Value(val));
let node_id = if let Some(nid) = maybe_node_id {
nid
} else {
return Ok(false);
};
let result = self.check_node(
analysis_ctx,
*node_id,
cgraph::Relation::Positive,
cgraph::Strength::Weak,
memo,
cycle_map,
domains,
);
match result {
Ok(_) => Ok(true),
Err(e) => {
e.get_analysis_trace()?;
Ok(false)
}
}
}
fn key_value_analysis(
&self,
val: dir::DirValue,
ctx: &AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<(), cgraph::GraphError<dir::DirValue>> {
self.key_analysis(val.get_key(), ctx, memo, cycle_map, domains)
.and_then(|_| self.value_analysis(val, ctx, memo, cycle_map, domains))
}
fn assertion_analysis(
&self,
positive_ctx: &[(&dir::DirValue, &Metadata)],
analysis_ctx: &AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<(), AnalysisError<dir::DirValue>> {
positive_ctx.iter().try_for_each(|(value, metadata)| {
self.key_value_analysis((*value).clone(), analysis_ctx, memo, cycle_map, domains)
.map_err(|e| AnalysisError::assertion_from_graph_error(metadata, e))
})
}
fn negation_analysis(
&self,
negative_ctx: &[(&[dir::DirValue], &Metadata)],
analysis_ctx: &mut AnalysisContext,
memo: &mut cgraph::Memoization<dir::DirValue>,
cycle_map: &mut cgraph::CycleCheck,
domains: Option<&[String]>,
) -> Result<(), AnalysisError<dir::DirValue>> {
let mut keywise_metadata: FxHashMap<dir::DirKey, Vec<&Metadata>> = FxHashMap::default();
let mut keywise_negation: FxHashMap<dir::DirKey, FxHashSet<&dir::DirValue>> =
FxHashMap::default();
for (values, metadata) in negative_ctx {
let mut metadata_added = false;
for dir_value in *values {
if !metadata_added {
keywise_metadata
.entry(dir_value.get_key())
.or_default()
.push(metadata);
metadata_added = true;
}
keywise_negation
.entry(dir_value.get_key())
.or_default()
.insert(dir_value);
}
}
for (key, negation_set) in keywise_negation {
let all_metadata = keywise_metadata.remove(&key).unwrap_or_default();
let first_metadata = all_metadata.first().copied().cloned().unwrap_or_default();
self.key_analysis(key.clone(), analysis_ctx, memo, cycle_map, domains)
.map_err(|e| AnalysisError::assertion_from_graph_error(&first_metadata, e))?;
let mut value_set = if let Some(set) = key.kind.get_value_set() {
set
} else {
continue;
};
value_set.retain(|v| !negation_set.contains(v));
for value in value_set {
analysis_ctx.insert(value.clone());
self.value_analysis(value.clone(), analysis_ctx, memo, cycle_map, domains)
.map_err(|e| {
AnalysisError::negation_from_graph_error(all_metadata.clone(), e)
})?;
analysis_ctx.remove(value);
}
}
Ok(())
}
fn perform_context_analysis(
&self,
ctx: &types::ConjunctiveContext<'_>,
memo: &mut cgraph::Memoization<dir::DirValue>,
domains: Option<&[String]>,
) -> Result<(), AnalysisError<dir::DirValue>> {
let mut analysis_ctx = AnalysisContext::from_dir_values(
ctx.iter()
.filter_map(|ctx_val| ctx_val.value.get_assertion().cloned()),
);
let positive_ctx = ctx
.iter()
.filter_map(|ctx_val| {
ctx_val
.value
.get_assertion()
.map(|val| (val, ctx_val.metadata))
})
.collect::<Vec<_>>();
self.assertion_analysis(
&positive_ctx,
&analysis_ctx,
memo,
&mut cgraph::CycleCheck::new(),
domains,
)?;
let negative_ctx = ctx
.iter()
.filter_map(|ctx_val| {
ctx_val
.value
.get_negation()
.map(|vals| (vals, ctx_val.metadata))
})
.collect::<Vec<_>>();
self.negation_analysis(
&negative_ctx,
&mut analysis_ctx,
memo,
&mut cgraph::CycleCheck::new(),
domains,
)?;
Ok(())
}
}
#[cfg(test)]
mod test {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use std::ops::Deref;
use euclid_macros::knowledge;
use hyperswitch_constraint_graph::CycleCheck;
use super::*;
use crate::{dirval, frontend::dir::enums};
#[test]
fn test_strong_positive_relation_success() {
let graph = knowledge! {
PaymentMethod(Card) ->> CaptureMethod(Automatic);
PaymentMethod(not Wallet)
& PaymentMethod(not PayLater) -> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(CaptureMethod = Automatic),
dirval!(PaymentMethod = Card),
]),
memo,
&mut CycleCheck::new(),
None,
);
assert!(result.is_ok());
}
#[test]
fn test_strong_positive_relation_failure() {
let graph = knowledge! {
PaymentMethod(Card) ->> CaptureMethod(Automatic);
PaymentMethod(not Wallet) -> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([dirval!(CaptureMethod = Automatic)]),
memo,
&mut CycleCheck::new(),
None,
);
assert!(result.is_err());
}
#[test]
fn test_strong_negative_relation_success() {
let graph = knowledge! {
PaymentMethod(Card) -> CaptureMethod(Automatic);
PaymentMethod(not Wallet) ->> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(CaptureMethod = Automatic),
dirval!(PaymentMethod = Card),
]),
memo,
&mut CycleCheck::new(),
None,
);
assert!(result.is_ok());
}
#[test]
fn test_strong_negative_relation_failure() {
let graph = knowledge! {
PaymentMethod(Card) -> CaptureMethod(Automatic);
PaymentMethod(not Wallet) ->> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(CaptureMethod = Automatic),
dirval!(PaymentMethod = Wallet),
]),
memo,
&mut CycleCheck::new(),
None,
);
assert!(result.is_err());
}
#[test]
fn test_normal_one_of_failure() {
let graph = knowledge! {
PaymentMethod(Card) -> CaptureMethod(Automatic);
PaymentMethod(Wallet) -> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(CaptureMethod = Automatic),
dirval!(PaymentMethod = PayLater),
]),
memo,
&mut CycleCheck::new(),
None,
);
assert!(matches!(
*Weak::upgrade(&result.unwrap_err().get_analysis_trace().unwrap())
.expect("Expected Arc"),
cgraph::AnalysisTrace::Value {
predecessors: Some(cgraph::error::ValueTracePredecessor::OneOf(_)),
..
}
));
}
#[test]
fn test_all_aggregator_success() {
let graph = knowledge! {
PaymentMethod(Card) & PaymentMethod(not Wallet) -> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(PaymentMethod = Card),
dirval!(CaptureMethod = Automatic),
]),
memo,
&mut CycleCheck::new(),
None,
);
assert!(result.is_ok());
}
#[test]
fn test_all_aggregator_failure() {
let graph = knowledge! {
PaymentMethod(Card) & PaymentMethod(not Wallet) -> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(CaptureMethod = Automatic),
dirval!(PaymentMethod = PayLater),
]),
memo,
&mut CycleCheck::new(),
None,
);
assert!(result.is_err());
}
#[test]
fn test_all_aggregator_mandatory_failure() {
let graph = knowledge! {
PaymentMethod(Card) & PaymentMethod(not Wallet) ->> CaptureMethod(Automatic);
};
let mut memo = cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(CaptureMethod = Automatic),
dirval!(PaymentMethod = PayLater),
]),
&mut memo,
&mut CycleCheck::new(),
None,
);
assert!(matches!(
*Weak::upgrade(&result.unwrap_err().get_analysis_trace().unwrap())
.expect("Expected Arc"),
cgraph::AnalysisTrace::Value {
predecessors: Some(cgraph::error::ValueTracePredecessor::Mandatory(_)),
..
}
));
}
#[test]
fn test_in_aggregator_success() {
let graph = knowledge! {
PaymentMethod(in [Card, Wallet]) -> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(CaptureMethod = Automatic),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = Wallet),
]),
memo,
&mut CycleCheck::new(),
None,
);
assert!(result.is_ok());
}
#[test]
fn test_in_aggregator_failure() {
let graph = knowledge! {
PaymentMethod(in [Card, Wallet]) -> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(CaptureMethod = Automatic),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = Wallet),
dirval!(PaymentMethod = PayLater),
]),
memo,
&mut CycleCheck::new(),
None,
);
assert!(result.is_err());
}
#[test]
fn test_not_in_aggregator_success() {
let graph = knowledge! {
PaymentMethod(not in [Card, Wallet]) ->> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(CaptureMethod = Automatic),
dirval!(PaymentMethod = PayLater),
dirval!(PaymentMethod = BankRedirect),
]),
memo,
&mut CycleCheck::new(),
None,
);
assert!(result.is_ok());
}
#[test]
fn test_not_in_aggregator_failure() {
let graph = knowledge! {
PaymentMethod(not in [Card, Wallet]) ->> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(CaptureMethod = Automatic),
dirval!(PaymentMethod = PayLater),
dirval!(PaymentMethod = BankRedirect),
dirval!(PaymentMethod = Card),
]),
memo,
&mut CycleCheck::new(),
None,
);
assert!(result.is_err());
}
#[test]
fn test_in_aggregator_failure_trace() {
let graph = knowledge! {
PaymentMethod(in [Card, Wallet]) ->> CaptureMethod(Automatic);
};
let memo = &mut cgraph::Memoization::new();
let result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(CaptureMethod = Automatic),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = Wallet),
dirval!(PaymentMethod = PayLater),
]),
memo,
&mut CycleCheck::new(),
None,
);
if let cgraph::AnalysisTrace::Value {
predecessors: Some(cgraph::error::ValueTracePredecessor::Mandatory(agg_error)),
..
} = Weak::upgrade(&result.unwrap_err().get_analysis_trace().unwrap())
.expect("Expected arc")
.deref()
{
assert!(matches!(
*Weak::upgrade(agg_error.deref()).expect("Expected Arc"),
cgraph::AnalysisTrace::InAggregation {
found: Some(dir::DirValue::PaymentMethod(enums::PaymentMethod::PayLater)),
..
}
));
} else {
panic!("Failed unwrapping OnlyInAggregation trace from AnalysisTrace");
}
}
#[test]
fn test_memoization_in_kgraph() {
let mut builder = cgraph::ConstraintGraphBuilder::new();
let _node_1 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Wallet)),
None,
None::<()>,
);
let _node_2 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::BillingCountry(enums::BillingCountry::India)),
None,
None::<()>,
);
let _node_3 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::BusinessCountry(
enums::BusinessCountry::UnitedStatesOfAmerica,
)),
None,
None::<()>,
);
let mut memo = cgraph::Memoization::new();
let mut cycle_map = CycleCheck::new();
let _edge_1 = builder
.make_edge(
_node_1,
_node_2,
cgraph::Strength::Strong,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to make an edge");
let _edge_2 = builder
.make_edge(
_node_2,
_node_3,
cgraph::Strength::Strong,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to an edge");
let graph = builder.build();
let _result = graph.key_value_analysis(
dirval!(BusinessCountry = UnitedStatesOfAmerica),
&AnalysisContext::from_dir_values([
dirval!(PaymentMethod = Wallet),
dirval!(BillingCountry = India),
dirval!(BusinessCountry = UnitedStatesOfAmerica),
]),
&mut memo,
&mut cycle_map,
None,
);
let _answer = memo
.get(&(
_node_3,
cgraph::Relation::Positive,
cgraph::Strength::Strong,
))
.expect("Memoization not workng");
matches!(_answer, Ok(()));
}
#[test]
fn test_cycle_resolution_in_graph() {
let mut builder = cgraph::ConstraintGraphBuilder::new();
let _node_1 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Wallet)),
None,
None::<()>,
);
let _node_2 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Card)),
None,
None::<()>,
);
let mut memo = cgraph::Memoization::new();
let mut cycle_map = CycleCheck::new();
let _edge_1 = builder
.make_edge(
_node_1,
_node_2,
cgraph::Strength::Weak,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to make an edge");
let _edge_2 = builder
.make_edge(
_node_2,
_node_1,
cgraph::Strength::Weak,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to an edge");
let graph = builder.build();
let _result = graph.key_value_analysis(
dirval!(PaymentMethod = Wallet),
&AnalysisContext::from_dir_values([
dirval!(PaymentMethod = Wallet),
dirval!(PaymentMethod = Card),
]),
&mut memo,
&mut cycle_map,
None,
);
assert!(_result.is_ok());
}
#[test]
fn test_cycle_resolution_in_graph1() {
let mut builder = cgraph::ConstraintGraphBuilder::new();
let _node_1 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::CaptureMethod(
enums::CaptureMethod::Automatic,
)),
None,
None::<()>,
);
let _node_2 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Card)),
None,
None::<()>,
);
let _node_3 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Wallet)),
None,
None::<()>,
);
let mut memo = cgraph::Memoization::new();
let mut cycle_map = CycleCheck::new();
let _edge_1 = builder
.make_edge(
_node_1,
_node_2,
cgraph::Strength::Weak,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to make an edge");
let _edge_2 = builder
.make_edge(
_node_1,
_node_3,
cgraph::Strength::Weak,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to make an edge");
let _edge_3 = builder
.make_edge(
_node_2,
_node_1,
cgraph::Strength::Weak,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to make an edge");
let _edge_4 = builder
.make_edge(
_node_3,
_node_1,
cgraph::Strength::Strong,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to make an edge");
let graph = builder.build();
let _result = graph.key_value_analysis(
dirval!(CaptureMethod = Automatic),
&AnalysisContext::from_dir_values([
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = Wallet),
dirval!(CaptureMethod = Automatic),
]),
&mut memo,
&mut cycle_map,
None,
);
assert!(_result.is_ok());
}
#[test]
fn test_cycle_resolution_in_graph2() {
let mut builder = cgraph::ConstraintGraphBuilder::new();
let _node_0 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::BillingCountry(
enums::BillingCountry::Afghanistan,
)),
None,
None::<()>,
);
let _node_1 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::CaptureMethod(
enums::CaptureMethod::Automatic,
)),
None,
None::<()>,
);
let _node_2 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Card)),
None,
None::<()>,
);
let _node_3 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Wallet)),
None,
None::<()>,
);
let _node_4 = builder.make_value_node(
cgraph::NodeValue::Value(dir::DirValue::PaymentCurrency(enums::PaymentCurrency::USD)),
None,
None::<()>,
);
let mut memo = cgraph::Memoization::new();
let mut cycle_map = CycleCheck::new();
let _edge_1 = builder
.make_edge(
_node_0,
_node_1,
cgraph::Strength::Weak,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to make an edge");
let _edge_2 = builder
.make_edge(
_node_1,
_node_2,
cgraph::Strength::Normal,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to make an edge");
let _edge_3 = builder
.make_edge(
_node_1,
_node_3,
cgraph::Strength::Weak,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to make an edge");
let _edge_4 = builder
.make_edge(
_node_3,
_node_4,
cgraph::Strength::Normal,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to make an edge");
let _edge_5 = builder
.make_edge(
_node_2,
_node_4,
cgraph::Strength::Normal,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to make an edge");
let _edge_6 = builder
.make_edge(
_node_4,
_node_1,
cgraph::Strength::Normal,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to make an edge");
let _edge_7 = builder
.make_edge(
_node_4,
_node_0,
cgraph::Strength::Normal,
cgraph::Relation::Positive,
None::<cgraph::DomainId>,
)
.expect("Failed to make an edge");
let graph = builder.build();
let _result = graph.key_value_analysis(
dirval!(BillingCountry = Afghanistan),
&AnalysisContext::from_dir_values([
dirval!(PaymentCurrency = USD),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = Wallet),
dirval!(CaptureMethod = Automatic),
dirval!(BillingCountry = Afghanistan),
]),
&mut memo,
&mut cycle_map,
None,
);
assert!(_result.is_ok());
}
}
| 7,969 | 972 |
hyperswitch | crates/euclid/src/dssa/types.rs | .rs | use std::{collections::HashMap, fmt};
use serde::Serialize;
use crate::{
dssa::{self, graph},
frontend::{ast, dir},
types::{DataType, EuclidValue, Metadata},
};
pub trait EuclidAnalysable: Sized {
fn get_dir_value_for_analysis(&self, rule_name: String) -> Vec<(dir::DirValue, Metadata)>;
}
#[derive(Debug, Clone)]
pub enum CtxValueKind<'a> {
Assertion(&'a dir::DirValue),
Negation(&'a [dir::DirValue]),
}
impl CtxValueKind<'_> {
pub fn get_assertion(&self) -> Option<&dir::DirValue> {
if let Self::Assertion(val) = self {
Some(val)
} else {
None
}
}
pub fn get_negation(&self) -> Option<&[dir::DirValue]> {
if let Self::Negation(vals) = self {
Some(vals)
} else {
None
}
}
pub fn get_key(&self) -> Option<dir::DirKey> {
match self {
Self::Assertion(val) => Some(val.get_key()),
Self::Negation(vals) => vals.first().map(|v| (*v).get_key()),
}
}
}
#[derive(Debug, Clone)]
pub struct ContextValue<'a> {
pub value: CtxValueKind<'a>,
pub metadata: &'a Metadata,
}
impl<'a> ContextValue<'a> {
#[inline]
pub fn assertion(value: &'a dir::DirValue, metadata: &'a Metadata) -> Self {
Self {
value: CtxValueKind::Assertion(value),
metadata,
}
}
#[inline]
pub fn negation(values: &'a [dir::DirValue], metadata: &'a Metadata) -> Self {
Self {
value: CtxValueKind::Negation(values),
metadata,
}
}
}
pub type ConjunctiveContext<'a> = Vec<ContextValue<'a>>;
#[derive(Clone, Serialize)]
pub enum AnalyzeResult {
AllOk,
}
#[derive(Debug, Clone, Serialize, thiserror::Error)]
pub struct AnalysisError {
#[serde(flatten)]
pub error_type: AnalysisErrorType,
pub metadata: Metadata,
}
impl fmt::Display for AnalysisError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.error_type.fmt(f)
}
}
#[derive(Debug, Clone, Serialize)]
pub struct ValueData {
pub value: dir::DirValue,
pub metadata: Metadata,
}
#[derive(Debug, Clone, Serialize, thiserror::Error)]
#[serde(tag = "type", content = "info", rename_all = "snake_case")]
pub enum AnalysisErrorType {
#[error("Invalid program key given: '{0}'")]
InvalidKey(String),
#[error("Invalid variant '{got}' received for key '{key}'")]
InvalidVariant {
key: String,
expected: Vec<String>,
got: String,
},
#[error(
"Invalid data type for value '{}' (expected {expected}, got {got})",
key
)]
InvalidType {
key: String,
expected: DataType,
got: DataType,
},
#[error("Invalid comparison '{operator:?}' for value type {value_type}")]
InvalidComparison {
operator: ast::ComparisonType,
value_type: DataType,
},
#[error("Invalid value received for length as '{value}: {:?}'", message)]
InvalidValue {
key: dir::DirKeyKind,
value: String,
message: Option<String>,
},
#[error("Conflicting assertions received for key '{}'", .key.kind)]
ConflictingAssertions {
key: dir::DirKey,
values: Vec<ValueData>,
},
#[error("Key '{}' exhaustively negated", .key.kind)]
ExhaustiveNegation {
key: dir::DirKey,
metadata: Vec<Metadata>,
},
#[error("The condition '{value}' was asserted and negated in the same condition")]
NegatedAssertion {
value: dir::DirValue,
assertion_metadata: Metadata,
negation_metadata: Metadata,
},
#[error("Graph analysis error: {0:#?}")]
GraphAnalysis(
graph::AnalysisError<dir::DirValue>,
hyperswitch_constraint_graph::Memoization<dir::DirValue>,
),
#[error("State machine error")]
StateMachine(dssa::state_machine::StateMachineError),
#[error("Unsupported program key '{0}'")]
UnsupportedProgramKey(dir::DirKeyKind),
#[error("Ran into an unimplemented feature")]
NotImplemented,
#[error("The payment method type is not supported under the payment method")]
NotSupported,
}
#[derive(Debug, Clone)]
pub enum ValueType {
EnumVariants(Vec<EuclidValue>),
Number,
}
impl EuclidAnalysable for common_enums::AuthenticationType {
fn get_dir_value_for_analysis(&self, rule_name: String) -> Vec<(dir::DirValue, Metadata)> {
let auth = self.to_string();
let dir_value = match self {
Self::ThreeDs => dir::DirValue::AuthenticationType(Self::ThreeDs),
Self::NoThreeDs => dir::DirValue::AuthenticationType(Self::NoThreeDs),
};
vec![(
dir_value,
HashMap::from_iter([(
"AUTHENTICATION_TYPE".to_string(),
serde_json::json!({
"rule_name": rule_name,
"Authentication_type": auth,
}),
)]),
)]
}
}
| 1,207 | 973 |
hyperswitch | crates/euclid/src/dssa/analyzer.rs | .rs | //! Static Analysis for the Euclid Rule DSL
//!
//! Exposes certain functions that can be used to perform static analysis over programs
//! in the Euclid Rule DSL. These include standard control flow analyses like testing
//! conflicting assertions, to Domain Specific Analyses making use of the
//! [`Knowledge Graph Framework`](crate::dssa::graph).
use hyperswitch_constraint_graph::{ConstraintGraph, Memoization};
use rustc_hash::{FxHashMap, FxHashSet};
use crate::{
dssa::{
graph::CgraphExt,
state_machine, truth,
types::{self, EuclidAnalysable},
},
frontend::{
ast,
dir::{self, EuclidDirFilter},
vir,
},
types::{DataType, Metadata},
};
/// Analyses conflicting assertions on the same key in a conjunctive context.
///
/// For example,
/// ```notrust
/// payment_method = card && ... && payment_method = bank_debit
/// ```notrust
/// This is a condition that will never evaluate to `true` given a single
/// payment method and needs to be caught in analysis.
pub fn analyze_conflicting_assertions(
keywise_assertions: &FxHashMap<dir::DirKey, FxHashSet<&dir::DirValue>>,
assertion_metadata: &FxHashMap<&dir::DirValue, &Metadata>,
) -> Result<(), types::AnalysisError> {
for (key, value_set) in keywise_assertions {
if value_set.len() > 1 {
let err_type = types::AnalysisErrorType::ConflictingAssertions {
key: key.clone(),
values: value_set
.iter()
.map(|val| types::ValueData {
value: (*val).clone(),
metadata: assertion_metadata
.get(val)
.map(|meta| (*meta).clone())
.unwrap_or_default(),
})
.collect(),
};
Err(types::AnalysisError {
error_type: err_type,
metadata: Default::default(),
})?;
}
}
Ok(())
}
/// Analyses exhaustive negations on the same key in a conjunctive context.
///
/// For example,
/// ```notrust
/// authentication_type /= three_ds && ... && authentication_type /= no_three_ds
/// ```notrust
/// This is a condition that will never evaluate to `true` given any authentication_type
/// since all the possible values authentication_type can take have been negated.
pub fn analyze_exhaustive_negations(
keywise_negations: &FxHashMap<dir::DirKey, FxHashSet<&dir::DirValue>>,
keywise_negation_metadata: &FxHashMap<dir::DirKey, Vec<&Metadata>>,
) -> Result<(), types::AnalysisError> {
for (key, negation_set) in keywise_negations {
let mut value_set = if let Some(set) = key.kind.get_value_set() {
set
} else {
continue;
};
value_set.retain(|val| !negation_set.contains(val));
if value_set.is_empty() {
let error_type = types::AnalysisErrorType::ExhaustiveNegation {
key: key.clone(),
metadata: keywise_negation_metadata
.get(key)
.cloned()
.unwrap_or_default()
.iter()
.copied()
.cloned()
.collect(),
};
Err(types::AnalysisError {
error_type,
metadata: Default::default(),
})?;
}
}
Ok(())
}
fn analyze_negated_assertions(
keywise_assertions: &FxHashMap<dir::DirKey, FxHashSet<&dir::DirValue>>,
assertion_metadata: &FxHashMap<&dir::DirValue, &Metadata>,
keywise_negations: &FxHashMap<dir::DirKey, FxHashSet<&dir::DirValue>>,
negation_metadata: &FxHashMap<&dir::DirValue, &Metadata>,
) -> Result<(), types::AnalysisError> {
for (key, negation_set) in keywise_negations {
let assertion_set = if let Some(set) = keywise_assertions.get(key) {
set
} else {
continue;
};
let intersection = negation_set & assertion_set;
intersection.iter().next().map_or(Ok(()), |val| {
let error_type = types::AnalysisErrorType::NegatedAssertion {
value: (*val).clone(),
assertion_metadata: assertion_metadata
.get(*val)
.copied()
.cloned()
.unwrap_or_default(),
negation_metadata: negation_metadata
.get(*val)
.copied()
.cloned()
.unwrap_or_default(),
};
Err(types::AnalysisError {
error_type,
metadata: Default::default(),
})
})?;
}
Ok(())
}
fn perform_condition_analyses(
context: &types::ConjunctiveContext<'_>,
) -> Result<(), types::AnalysisError> {
let mut assertion_metadata: FxHashMap<&dir::DirValue, &Metadata> = FxHashMap::default();
let mut keywise_assertions: FxHashMap<dir::DirKey, FxHashSet<&dir::DirValue>> =
FxHashMap::default();
let mut negation_metadata: FxHashMap<&dir::DirValue, &Metadata> = FxHashMap::default();
let mut keywise_negation_metadata: FxHashMap<dir::DirKey, Vec<&Metadata>> =
FxHashMap::default();
let mut keywise_negations: FxHashMap<dir::DirKey, FxHashSet<&dir::DirValue>> =
FxHashMap::default();
for ctx_val in context {
let key = if let Some(k) = ctx_val.value.get_key() {
k
} else {
continue;
};
if let dir::DirKeyKind::Connector = key.kind {
continue;
}
if !matches!(key.kind.get_type(), DataType::EnumVariant) {
continue;
}
match ctx_val.value {
types::CtxValueKind::Assertion(val) => {
keywise_assertions
.entry(key.clone())
.or_default()
.insert(val);
assertion_metadata.insert(val, ctx_val.metadata);
}
types::CtxValueKind::Negation(vals) => {
let negation_set = keywise_negations.entry(key.clone()).or_default();
for val in vals {
negation_set.insert(val);
negation_metadata.insert(val, ctx_val.metadata);
}
keywise_negation_metadata
.entry(key.clone())
.or_default()
.push(ctx_val.metadata);
}
}
}
analyze_conflicting_assertions(&keywise_assertions, &assertion_metadata)?;
analyze_exhaustive_negations(&keywise_negations, &keywise_negation_metadata)?;
analyze_negated_assertions(
&keywise_assertions,
&assertion_metadata,
&keywise_negations,
&negation_metadata,
)?;
Ok(())
}
fn perform_context_analyses(
context: &types::ConjunctiveContext<'_>,
knowledge_graph: &ConstraintGraph<dir::DirValue>,
) -> Result<(), types::AnalysisError> {
perform_condition_analyses(context)?;
let mut memo = Memoization::new();
knowledge_graph
.perform_context_analysis(context, &mut memo, None)
.map_err(|err| types::AnalysisError {
error_type: types::AnalysisErrorType::GraphAnalysis(err, memo),
metadata: Default::default(),
})?;
Ok(())
}
pub fn analyze<O: EuclidAnalysable + EuclidDirFilter>(
program: ast::Program<O>,
knowledge_graph: Option<&ConstraintGraph<dir::DirValue>>,
) -> Result<vir::ValuedProgram<O>, types::AnalysisError> {
let dir_program = ast::lowering::lower_program(program)?;
let selection_data = state_machine::make_connector_selection_data(&dir_program);
let mut ctx_manager = state_machine::AnalysisContextManager::new(&dir_program, &selection_data);
while let Some(ctx) = ctx_manager.advance().map_err(|err| types::AnalysisError {
metadata: Default::default(),
error_type: types::AnalysisErrorType::StateMachine(err),
})? {
perform_context_analyses(ctx, knowledge_graph.unwrap_or(&truth::ANALYSIS_GRAPH))?;
}
dir::lowering::lower_program(dir_program)
}
#[cfg(all(test, feature = "ast_parser"))]
mod tests {
#![allow(clippy::panic, clippy::expect_used)]
use std::{ops::Deref, sync::Weak};
use euclid_macros::knowledge;
use hyperswitch_constraint_graph as cgraph;
use super::*;
use crate::{
dirval,
dssa::graph::{self, euclid_graph_prelude},
types::DummyOutput,
};
#[test]
fn test_conflicting_assertion_detection() {
let program_str = r#"
default: ["stripe", "adyen"]
stripe_first: ["stripe", "adyen"]
{
payment_method = wallet {
amount > 500 & capture_method = automatic
amount < 500 & payment_method = card
}
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let analysis_result = analyze(program, None);
if let Err(types::AnalysisError {
error_type: types::AnalysisErrorType::ConflictingAssertions { key, values },
..
}) = analysis_result
{
assert!(
matches!(key.kind, dir::DirKeyKind::PaymentMethod),
"Key should be payment_method"
);
let values: Vec<dir::DirValue> = values.into_iter().map(|v| v.value).collect();
assert_eq!(values.len(), 2, "There should be 2 conflicting conditions");
assert!(
values.contains(&dirval!(PaymentMethod = Wallet)),
"Condition should include payment_method = wallet"
);
assert!(
values.contains(&dirval!(PaymentMethod = Card)),
"Condition should include payment_method = card"
);
} else {
panic!("Did not receive conflicting assertions error");
}
}
#[test]
fn test_exhaustive_negation_detection() {
let program_str = r#"
default: ["stripe"]
rule_1: ["adyen"]
{
payment_method /= wallet {
capture_method = manual & payment_method /= card {
authentication_type = three_ds & payment_method /= pay_later {
amount > 1000 & payment_method /= bank_redirect {
payment_method /= crypto
& payment_method /= bank_debit
& payment_method /= bank_transfer
& payment_method /= upi
& payment_method /= reward
& payment_method /= voucher
& payment_method /= gift_card
& payment_method /= card_redirect
& payment_method /= real_time_payment
}
}
}
}
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let analysis_result = analyze(program, None);
if let Err(types::AnalysisError {
error_type: types::AnalysisErrorType::ExhaustiveNegation { key, .. },
..
}) = analysis_result
{
assert!(
matches!(key.kind, dir::DirKeyKind::PaymentMethod),
"Expected key to be payment_method"
);
} else {
panic!("Expected exhaustive negation error");
}
}
#[test]
fn test_negated_assertions_detection() {
let program_str = r#"
default: ["stripe"]
rule_1: ["adyen"]
{
payment_method = wallet {
amount > 500 {
capture_method = automatic
}
amount < 501 {
payment_method /= wallet
}
}
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let analysis_result = analyze(program, None);
if let Err(types::AnalysisError {
error_type: types::AnalysisErrorType::NegatedAssertion { value, .. },
..
}) = analysis_result
{
assert_eq!(
value,
dirval!(PaymentMethod = Wallet),
"Expected to catch payment_method = wallet as conflict"
);
} else {
panic!("Expected negated assertion error");
}
}
#[test]
fn test_negation_graph_analysis() {
let graph = knowledge! {
CaptureMethod(Automatic) ->> PaymentMethod(Card);
};
let program_str = r#"
default: ["stripe"]
rule_1: ["adyen"]
{
amount > 500 {
payment_method = pay_later
}
amount < 500 {
payment_method /= wallet & payment_method /= pay_later
}
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Graph");
let analysis_result = analyze(program, Some(&graph));
let error_type = match analysis_result {
Err(types::AnalysisError { error_type, .. }) => error_type,
_ => panic!("Error_type not found"),
};
let a_err = match error_type {
types::AnalysisErrorType::GraphAnalysis(trace, memo) => (trace, memo),
_ => panic!("Graph Analysis not found"),
};
let (trace, metadata) = match a_err.0 {
graph::AnalysisError::NegationTrace { trace, metadata } => (trace, metadata),
_ => panic!("Negation Trace not found"),
};
let predecessor = match Weak::upgrade(&trace)
.expect("Expected Arc not found")
.deref()
.clone()
{
cgraph::AnalysisTrace::Value { predecessors, .. } => {
let _value = cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(
dir::enums::PaymentMethod::Card,
));
let _relation = cgraph::Relation::Positive;
predecessors
}
_ => panic!("Expected Negation Trace for payment method = card"),
};
let pred = match predecessor {
Some(cgraph::error::ValueTracePredecessor::Mandatory(predecessor)) => predecessor,
_ => panic!("No predecessor found"),
};
assert_eq!(
metadata.len(),
2,
"Expected two metadats for wallet and pay_later"
);
assert!(matches!(
*Weak::upgrade(&pred)
.expect("Expected Arc not found")
.deref(),
cgraph::AnalysisTrace::Value {
value: cgraph::NodeValue::Value(dir::DirValue::CaptureMethod(
dir::enums::CaptureMethod::Automatic
)),
relation: cgraph::Relation::Positive,
info: None,
metadata: None,
predecessors: None,
}
));
}
}
| 3,226 | 974 |
hyperswitch | crates/euclid/src/dssa/state_machine.rs | .rs | use super::types::EuclidAnalysable;
use crate::{dssa::types, frontend::dir, types::Metadata};
#[derive(Debug, Clone, serde::Serialize, thiserror::Error)]
#[serde(tag = "type", content = "info", rename_all = "snake_case")]
pub enum StateMachineError {
#[error("Index out of bounds: {0}")]
IndexOutOfBounds(&'static str),
}
#[derive(Debug)]
struct ComparisonStateMachine<'a> {
values: &'a [dir::DirValue],
logic: &'a dir::DirComparisonLogic,
metadata: &'a Metadata,
count: usize,
ctx_idx: usize,
}
impl<'a> ComparisonStateMachine<'a> {
#[inline]
fn is_finished(&self) -> bool {
self.count + 1 >= self.values.len()
|| matches!(self.logic, dir::DirComparisonLogic::NegativeConjunction)
}
#[inline]
fn advance(&mut self) {
if let dir::DirComparisonLogic::PositiveDisjunction = self.logic {
self.count = (self.count + 1) % self.values.len();
}
}
#[inline]
fn reset(&mut self) {
self.count = 0;
}
#[inline]
fn put(&self, context: &mut types::ConjunctiveContext<'a>) -> Result<(), StateMachineError> {
if let dir::DirComparisonLogic::PositiveDisjunction = self.logic {
*context
.get_mut(self.ctx_idx)
.ok_or(StateMachineError::IndexOutOfBounds(
"in ComparisonStateMachine while indexing into context",
))? = types::ContextValue::assertion(
self.values
.get(self.count)
.ok_or(StateMachineError::IndexOutOfBounds(
"in ComparisonStateMachine while indexing into values",
))?,
self.metadata,
);
}
Ok(())
}
#[inline]
fn push(&self, context: &mut types::ConjunctiveContext<'a>) -> Result<(), StateMachineError> {
match self.logic {
dir::DirComparisonLogic::PositiveDisjunction => {
context.push(types::ContextValue::assertion(
self.values
.get(self.count)
.ok_or(StateMachineError::IndexOutOfBounds(
"in ComparisonStateMachine while pushing",
))?,
self.metadata,
));
}
dir::DirComparisonLogic::NegativeConjunction => {
context.push(types::ContextValue::negation(self.values, self.metadata));
}
}
Ok(())
}
}
#[derive(Debug)]
struct ConditionStateMachine<'a> {
state_machines: Vec<ComparisonStateMachine<'a>>,
start_ctx_idx: usize,
}
impl<'a> ConditionStateMachine<'a> {
fn new(condition: &'a [dir::DirComparison], start_idx: usize) -> Self {
let mut machines = Vec::<ComparisonStateMachine<'a>>::with_capacity(condition.len());
let mut machine_idx = start_idx;
for cond in condition {
let machine = ComparisonStateMachine {
values: &cond.values,
logic: &cond.logic,
metadata: &cond.metadata,
count: 0,
ctx_idx: machine_idx,
};
machines.push(machine);
machine_idx += 1;
}
Self {
state_machines: machines,
start_ctx_idx: start_idx,
}
}
fn init(&self, context: &mut types::ConjunctiveContext<'a>) -> Result<(), StateMachineError> {
for machine in &self.state_machines {
machine.push(context)?;
}
Ok(())
}
#[inline]
fn destroy(&self, context: &mut types::ConjunctiveContext<'a>) {
context.truncate(self.start_ctx_idx);
}
#[inline]
fn is_finished(&self) -> bool {
!self
.state_machines
.iter()
.any(|machine| !machine.is_finished())
}
#[inline]
fn get_next_ctx_idx(&self) -> usize {
self.start_ctx_idx + self.state_machines.len()
}
fn advance(
&mut self,
context: &mut types::ConjunctiveContext<'a>,
) -> Result<(), StateMachineError> {
for machine in self.state_machines.iter_mut().rev() {
if machine.is_finished() {
machine.reset();
machine.put(context)?;
} else {
machine.advance();
machine.put(context)?;
break;
}
}
Ok(())
}
}
#[derive(Debug)]
struct IfStmtStateMachine<'a> {
condition_machine: ConditionStateMachine<'a>,
nested: Vec<&'a dir::DirIfStatement>,
nested_idx: usize,
}
impl<'a> IfStmtStateMachine<'a> {
fn new(stmt: &'a dir::DirIfStatement, ctx_start_idx: usize) -> Self {
let condition_machine = ConditionStateMachine::new(&stmt.condition, ctx_start_idx);
let nested: Vec<&'a dir::DirIfStatement> = match &stmt.nested {
None => Vec::new(),
Some(nested_stmts) => nested_stmts.iter().collect(),
};
Self {
condition_machine,
nested,
nested_idx: 0,
}
}
fn init(
&self,
context: &mut types::ConjunctiveContext<'a>,
) -> Result<Option<Self>, StateMachineError> {
self.condition_machine.init(context)?;
Ok(self
.nested
.first()
.map(|nested| Self::new(nested, self.condition_machine.get_next_ctx_idx())))
}
#[inline]
fn is_finished(&self) -> bool {
self.nested_idx + 1 >= self.nested.len()
}
#[inline]
fn is_condition_machine_finished(&self) -> bool {
self.condition_machine.is_finished()
}
#[inline]
fn destroy(&self, context: &mut types::ConjunctiveContext<'a>) {
self.condition_machine.destroy(context);
}
#[inline]
fn advance_condition_machine(
&mut self,
context: &mut types::ConjunctiveContext<'a>,
) -> Result<(), StateMachineError> {
self.condition_machine.advance(context)?;
Ok(())
}
fn advance(&mut self) -> Result<Option<Self>, StateMachineError> {
if self.nested.is_empty() {
Ok(None)
} else {
self.nested_idx = (self.nested_idx + 1) % self.nested.len();
Ok(Some(Self::new(
self.nested
.get(self.nested_idx)
.ok_or(StateMachineError::IndexOutOfBounds(
"in IfStmtStateMachine while advancing",
))?,
self.condition_machine.get_next_ctx_idx(),
)))
}
}
}
#[derive(Debug)]
struct RuleStateMachine<'a> {
connector_selection_data: &'a [(dir::DirValue, Metadata)],
connectors_added: bool,
if_stmt_machines: Vec<IfStmtStateMachine<'a>>,
running_stack: Vec<IfStmtStateMachine<'a>>,
}
impl<'a> RuleStateMachine<'a> {
fn new<O>(
rule: &'a dir::DirRule<O>,
connector_selection_data: &'a [(dir::DirValue, Metadata)],
) -> Self {
let mut if_stmt_machines: Vec<IfStmtStateMachine<'a>> =
Vec::with_capacity(rule.statements.len());
for stmt in rule.statements.iter().rev() {
if_stmt_machines.push(IfStmtStateMachine::new(
stmt,
connector_selection_data.len(),
));
}
Self {
connector_selection_data,
connectors_added: false,
if_stmt_machines,
running_stack: Vec::new(),
}
}
fn is_finished(&self) -> bool {
self.if_stmt_machines.is_empty() && self.running_stack.is_empty()
}
fn init_next(
&mut self,
context: &mut types::ConjunctiveContext<'a>,
) -> Result<(), StateMachineError> {
if self.if_stmt_machines.is_empty() || !self.running_stack.is_empty() {
return Ok(());
}
if !self.connectors_added {
for (dir_val, metadata) in self.connector_selection_data {
context.push(types::ContextValue::assertion(dir_val, metadata));
}
self.connectors_added = true;
}
context.truncate(self.connector_selection_data.len());
if let Some(mut next_running) = self.if_stmt_machines.pop() {
while let Some(nested_running) = next_running.init(context)? {
self.running_stack.push(next_running);
next_running = nested_running;
}
self.running_stack.push(next_running);
}
Ok(())
}
fn advance(
&mut self,
context: &mut types::ConjunctiveContext<'a>,
) -> Result<(), StateMachineError> {
let mut condition_machines_finished = true;
for stmt_machine in self.running_stack.iter_mut().rev() {
if !stmt_machine.is_condition_machine_finished() {
condition_machines_finished = false;
stmt_machine.advance_condition_machine(context)?;
break;
} else {
stmt_machine.advance_condition_machine(context)?;
}
}
if !condition_machines_finished {
return Ok(());
}
let mut maybe_next_running: Option<IfStmtStateMachine<'a>> = None;
while let Some(last) = self.running_stack.last_mut() {
if !last.is_finished() {
maybe_next_running = last.advance()?;
break;
} else {
last.destroy(context);
self.running_stack.pop();
}
}
if let Some(mut next_running) = maybe_next_running {
while let Some(nested_running) = next_running.init(context)? {
self.running_stack.push(next_running);
next_running = nested_running;
}
self.running_stack.push(next_running);
} else {
self.init_next(context)?;
}
Ok(())
}
}
#[derive(Debug)]
pub struct RuleContextManager<'a> {
context: types::ConjunctiveContext<'a>,
machine: RuleStateMachine<'a>,
init: bool,
}
impl<'a> RuleContextManager<'a> {
pub fn new<O>(
rule: &'a dir::DirRule<O>,
connector_selection_data: &'a [(dir::DirValue, Metadata)],
) -> Self {
Self {
context: Vec::new(),
machine: RuleStateMachine::new(rule, connector_selection_data),
init: false,
}
}
pub fn advance(&mut self) -> Result<Option<&types::ConjunctiveContext<'a>>, StateMachineError> {
if !self.init {
self.init = true;
self.machine.init_next(&mut self.context)?;
Ok(Some(&self.context))
} else if self.machine.is_finished() {
Ok(None)
} else {
self.machine.advance(&mut self.context)?;
if self.machine.is_finished() {
Ok(None)
} else {
Ok(Some(&self.context))
}
}
}
pub fn advance_mut(
&mut self,
) -> Result<Option<&mut types::ConjunctiveContext<'a>>, StateMachineError> {
if !self.init {
self.init = true;
self.machine.init_next(&mut self.context)?;
Ok(Some(&mut self.context))
} else if self.machine.is_finished() {
Ok(None)
} else {
self.machine.advance(&mut self.context)?;
if self.machine.is_finished() {
Ok(None)
} else {
Ok(Some(&mut self.context))
}
}
}
}
#[derive(Debug)]
pub struct ProgramStateMachine<'a> {
rule_machines: Vec<RuleStateMachine<'a>>,
current_rule_machine: Option<RuleStateMachine<'a>>,
is_init: bool,
}
impl<'a> ProgramStateMachine<'a> {
pub fn new<O>(
program: &'a dir::DirProgram<O>,
connector_selection_data: &'a [Vec<(dir::DirValue, Metadata)>],
) -> Self {
let mut rule_machines: Vec<RuleStateMachine<'a>> = program
.rules
.iter()
.zip(connector_selection_data.iter())
.rev()
.map(|(rule, connector_selection_data)| {
RuleStateMachine::new(rule, connector_selection_data)
})
.collect();
Self {
current_rule_machine: rule_machines.pop(),
rule_machines,
is_init: false,
}
}
pub fn is_finished(&self) -> bool {
self.current_rule_machine
.as_ref()
.map_or(true, |rsm| rsm.is_finished())
&& self.rule_machines.is_empty()
}
pub fn init(
&mut self,
context: &mut types::ConjunctiveContext<'a>,
) -> Result<(), StateMachineError> {
if !self.is_init {
if let Some(rsm) = self.current_rule_machine.as_mut() {
rsm.init_next(context)?;
}
self.is_init = true;
}
Ok(())
}
pub fn advance(
&mut self,
context: &mut types::ConjunctiveContext<'a>,
) -> Result<(), StateMachineError> {
if self
.current_rule_machine
.as_ref()
.map_or(true, |rsm| rsm.is_finished())
{
self.current_rule_machine = self.rule_machines.pop();
context.clear();
if let Some(rsm) = self.current_rule_machine.as_mut() {
rsm.init_next(context)?;
}
} else if let Some(rsm) = self.current_rule_machine.as_mut() {
rsm.advance(context)?;
}
Ok(())
}
}
pub struct AnalysisContextManager<'a> {
context: types::ConjunctiveContext<'a>,
machine: ProgramStateMachine<'a>,
init: bool,
}
impl<'a> AnalysisContextManager<'a> {
pub fn new<O>(
program: &'a dir::DirProgram<O>,
connector_selection_data: &'a [Vec<(dir::DirValue, Metadata)>],
) -> Self {
let machine = ProgramStateMachine::new(program, connector_selection_data);
let context: types::ConjunctiveContext<'a> = Vec::new();
Self {
context,
machine,
init: false,
}
}
pub fn advance(&mut self) -> Result<Option<&types::ConjunctiveContext<'a>>, StateMachineError> {
if !self.init {
self.init = true;
self.machine.init(&mut self.context)?;
Ok(Some(&self.context))
} else if self.machine.is_finished() {
Ok(None)
} else {
self.machine.advance(&mut self.context)?;
if self.machine.is_finished() {
Ok(None)
} else {
Ok(Some(&self.context))
}
}
}
}
pub fn make_connector_selection_data<O: EuclidAnalysable>(
program: &dir::DirProgram<O>,
) -> Vec<Vec<(dir::DirValue, Metadata)>> {
program
.rules
.iter()
.map(|rule| {
rule.connector_selection
.get_dir_value_for_analysis(rule.name.clone())
})
.collect()
}
#[cfg(all(test, feature = "ast_parser"))]
mod tests {
#![allow(clippy::expect_used)]
use super::*;
use crate::{dirval, frontend::ast, types::DummyOutput};
#[test]
fn test_correct_contexts() {
let program_str = r#"
default: ["stripe", "adyen"]
stripe_first: ["stripe", "adyen"]
{
payment_method = wallet {
payment_method = (card, bank_redirect) {
currency = USD
currency = GBP
}
payment_method = pay_later {
capture_method = automatic
capture_method = manual
}
}
payment_method = card {
payment_method = (card, bank_redirect) & capture_method = (automatic, manual) {
currency = (USD, GBP)
}
}
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let lowered = ast::lowering::lower_program(program).expect("Lowering");
let selection_data = make_connector_selection_data(&lowered);
let mut state_machine = ProgramStateMachine::new(&lowered, &selection_data);
let mut ctx: types::ConjunctiveContext<'_> = Vec::new();
state_machine.init(&mut ctx).expect("State machine init");
let expected_contexts: Vec<Vec<dir::DirValue>> = vec![
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Wallet),
dirval!(PaymentMethod = Card),
dirval!(PaymentCurrency = USD),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Wallet),
dirval!(PaymentMethod = BankRedirect),
dirval!(PaymentCurrency = USD),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Wallet),
dirval!(PaymentMethod = Card),
dirval!(PaymentCurrency = GBP),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Wallet),
dirval!(PaymentMethod = BankRedirect),
dirval!(PaymentCurrency = GBP),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Wallet),
dirval!(PaymentMethod = PayLater),
dirval!(CaptureMethod = Automatic),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Wallet),
dirval!(PaymentMethod = PayLater),
dirval!(CaptureMethod = Manual),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = Card),
dirval!(CaptureMethod = Automatic),
dirval!(PaymentCurrency = USD),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = Card),
dirval!(CaptureMethod = Automatic),
dirval!(PaymentCurrency = GBP),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = Card),
dirval!(CaptureMethod = Manual),
dirval!(PaymentCurrency = USD),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = Card),
dirval!(CaptureMethod = Manual),
dirval!(PaymentCurrency = GBP),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = BankRedirect),
dirval!(CaptureMethod = Automatic),
dirval!(PaymentCurrency = USD),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = BankRedirect),
dirval!(CaptureMethod = Automatic),
dirval!(PaymentCurrency = GBP),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = BankRedirect),
dirval!(CaptureMethod = Manual),
dirval!(PaymentCurrency = USD),
],
vec![
dirval!("MetadataKey" = "stripe"),
dirval!("MetadataKey" = "adyen"),
dirval!(PaymentMethod = Card),
dirval!(PaymentMethod = BankRedirect),
dirval!(CaptureMethod = Manual),
dirval!(PaymentCurrency = GBP),
],
];
let mut expected_idx = 0usize;
while !state_machine.is_finished() {
let values = ctx
.iter()
.flat_map(|c| match c.value {
types::CtxValueKind::Assertion(val) => vec![val],
types::CtxValueKind::Negation(vals) => vals.iter().collect(),
})
.collect::<Vec<&dir::DirValue>>();
assert_eq!(
values,
expected_contexts
.get(expected_idx)
.expect("Error deriving contexts")
.iter()
.collect::<Vec<&dir::DirValue>>()
);
expected_idx += 1;
state_machine
.advance(&mut ctx)
.expect("State Machine advance");
}
assert_eq!(expected_idx, 14);
let mut ctx_manager = AnalysisContextManager::new(&lowered, &selection_data);
expected_idx = 0;
while let Some(ctx) = ctx_manager.advance().expect("Context Manager Context") {
let values = ctx
.iter()
.flat_map(|c| match c.value {
types::CtxValueKind::Assertion(val) => vec![val],
types::CtxValueKind::Negation(vals) => vals.iter().collect(),
})
.collect::<Vec<&dir::DirValue>>();
assert_eq!(
values,
expected_contexts
.get(expected_idx)
.expect("Error deriving contexts")
.iter()
.collect::<Vec<&dir::DirValue>>()
);
expected_idx += 1;
}
assert_eq!(expected_idx, 14);
}
}
| 4,764 | 975 |
hyperswitch | crates/euclid/src/backend/vir_interpreter.rs | .rs | pub mod types;
use std::fmt::Debug;
use serde::{Deserialize, Serialize};
use crate::{
backend::{self, inputs, EuclidBackend},
frontend::{
ast,
dir::{self, EuclidDirFilter},
vir,
},
};
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct VirInterpreterBackend<O> {
program: vir::ValuedProgram<O>,
}
impl<O> VirInterpreterBackend<O>
where
O: Clone,
{
#[inline]
fn eval_comparison(comp: &vir::ValuedComparison, ctx: &types::Context) -> bool {
match &comp.logic {
vir::ValuedComparisonLogic::PositiveDisjunction => {
comp.values.iter().any(|v| ctx.check_presence(v))
}
vir::ValuedComparisonLogic::NegativeConjunction => {
comp.values.iter().all(|v| !ctx.check_presence(v))
}
}
}
#[inline]
fn eval_condition(cond: &vir::ValuedIfCondition, ctx: &types::Context) -> bool {
cond.iter().all(|comp| Self::eval_comparison(comp, ctx))
}
fn eval_statement(stmt: &vir::ValuedIfStatement, ctx: &types::Context) -> bool {
if Self::eval_condition(&stmt.condition, ctx) {
{
stmt.nested.as_ref().map_or(true, |nested_stmts| {
nested_stmts.iter().any(|s| Self::eval_statement(s, ctx))
})
}
} else {
false
}
}
fn eval_rule(rule: &vir::ValuedRule<O>, ctx: &types::Context) -> bool {
rule.statements
.iter()
.any(|stmt| Self::eval_statement(stmt, ctx))
}
fn eval_program(
program: &vir::ValuedProgram<O>,
ctx: &types::Context,
) -> backend::BackendOutput<O> {
program
.rules
.iter()
.find(|rule| Self::eval_rule(rule, ctx))
.map_or_else(
|| backend::BackendOutput {
connector_selection: program.default_selection.clone(),
rule_name: None,
},
|rule| backend::BackendOutput {
connector_selection: rule.connector_selection.clone(),
rule_name: Some(rule.name.clone()),
},
)
}
}
impl<O> EuclidBackend<O> for VirInterpreterBackend<O>
where
O: Clone + EuclidDirFilter,
{
type Error = types::VirInterpreterError;
fn with_program(program: ast::Program<O>) -> Result<Self, Self::Error> {
let dir_program = ast::lowering::lower_program(program)
.map_err(types::VirInterpreterError::LoweringError)?;
let vir_program = dir::lowering::lower_program(dir_program)
.map_err(types::VirInterpreterError::LoweringError)?;
Ok(Self {
program: vir_program,
})
}
fn execute(
&self,
input: inputs::BackendInput,
) -> Result<backend::BackendOutput<O>, Self::Error> {
let ctx = types::Context::from_input(input);
Ok(Self::eval_program(&self.program, &ctx))
}
}
#[cfg(all(test, feature = "ast_parser"))]
mod test {
#![allow(clippy::expect_used)]
use common_utils::types::MinorUnit;
use rustc_hash::FxHashMap;
use super::*;
use crate::{enums, types::DummyOutput};
#[test]
fn test_execution() {
let program_str = r#"
default: [ "stripe", "adyen"]
rule_1: ["stripe"]
{
pay_later = klarna
}
rule_2: ["adyen"]
{
pay_later = affirm
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let inp = inputs::BackendInput {
metadata: None,
payment: inputs::PaymentInput {
amount: MinorUnit::new(32),
card_bin: None,
currency: enums::Currency::USD,
authentication_type: Some(enums::AuthenticationType::NoThreeDs),
capture_method: Some(enums::CaptureMethod::Automatic),
business_country: Some(enums::Country::UnitedStatesOfAmerica),
billing_country: Some(enums::Country::France),
business_label: None,
setup_future_usage: None,
},
payment_method: inputs::PaymentMethodInput {
payment_method: Some(enums::PaymentMethod::PayLater),
payment_method_type: Some(enums::PaymentMethodType::Affirm),
card_network: None,
},
mandate: inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
},
};
let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program");
let result = backend.execute(inp).expect("Execution");
assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_2");
}
#[test]
fn test_payment_type() {
let program_str = r#"
default: ["stripe", "adyen"]
rule_1: ["stripe"]
{
payment_type = setup_mandate
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let inp = inputs::BackendInput {
metadata: None,
payment: inputs::PaymentInput {
amount: MinorUnit::new(32),
currency: enums::Currency::USD,
card_bin: Some("123456".to_string()),
authentication_type: Some(enums::AuthenticationType::NoThreeDs),
capture_method: Some(enums::CaptureMethod::Automatic),
business_country: Some(enums::Country::UnitedStatesOfAmerica),
billing_country: Some(enums::Country::France),
business_label: None,
setup_future_usage: None,
},
payment_method: inputs::PaymentMethodInput {
payment_method: Some(enums::PaymentMethod::PayLater),
payment_method_type: Some(enums::PaymentMethodType::Affirm),
card_network: None,
},
mandate: inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: Some(enums::PaymentType::SetupMandate),
},
};
let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program");
let result = backend.execute(inp).expect("Execution");
assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1");
}
#[test]
fn test_ppt_flow() {
let program_str = r#"
default: ["stripe", "adyen"]
rule_1: ["stripe"]
{
payment_type = ppt_mandate
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let inp = inputs::BackendInput {
metadata: None,
payment: inputs::PaymentInput {
amount: MinorUnit::new(32),
currency: enums::Currency::USD,
card_bin: Some("123456".to_string()),
authentication_type: Some(enums::AuthenticationType::NoThreeDs),
capture_method: Some(enums::CaptureMethod::Automatic),
business_country: Some(enums::Country::UnitedStatesOfAmerica),
billing_country: Some(enums::Country::France),
business_label: None,
setup_future_usage: None,
},
payment_method: inputs::PaymentMethodInput {
payment_method: Some(enums::PaymentMethod::PayLater),
payment_method_type: Some(enums::PaymentMethodType::Affirm),
card_network: None,
},
mandate: inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: Some(enums::PaymentType::PptMandate),
},
};
let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program");
let result = backend.execute(inp).expect("Execution");
assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1");
}
#[test]
fn test_mandate_type() {
let program_str = r#"
default: ["stripe", "adyen"]
rule_1: ["stripe"]
{
mandate_type = single_use
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let inp = inputs::BackendInput {
metadata: None,
payment: inputs::PaymentInput {
amount: MinorUnit::new(32),
currency: enums::Currency::USD,
card_bin: Some("123456".to_string()),
authentication_type: Some(enums::AuthenticationType::NoThreeDs),
capture_method: Some(enums::CaptureMethod::Automatic),
business_country: Some(enums::Country::UnitedStatesOfAmerica),
billing_country: Some(enums::Country::France),
business_label: None,
setup_future_usage: None,
},
payment_method: inputs::PaymentMethodInput {
payment_method: Some(enums::PaymentMethod::PayLater),
payment_method_type: Some(enums::PaymentMethodType::Affirm),
card_network: None,
},
mandate: inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: Some(enums::MandateType::SingleUse),
payment_type: None,
},
};
let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program");
let result = backend.execute(inp).expect("Execution");
assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1");
}
#[test]
fn test_mandate_acceptance_type() {
let program_str = r#"
default: ["stripe","adyen"]
rule_1: ["stripe"]
{
mandate_acceptance_type = online
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let inp = inputs::BackendInput {
metadata: None,
payment: inputs::PaymentInput {
amount: MinorUnit::new(32),
currency: enums::Currency::USD,
card_bin: Some("123456".to_string()),
authentication_type: Some(enums::AuthenticationType::NoThreeDs),
capture_method: Some(enums::CaptureMethod::Automatic),
business_country: Some(enums::Country::UnitedStatesOfAmerica),
billing_country: Some(enums::Country::France),
business_label: None,
setup_future_usage: None,
},
payment_method: inputs::PaymentMethodInput {
payment_method: Some(enums::PaymentMethod::PayLater),
payment_method_type: Some(enums::PaymentMethodType::Affirm),
card_network: None,
},
mandate: inputs::MandateData {
mandate_acceptance_type: Some(enums::MandateAcceptanceType::Online),
mandate_type: None,
payment_type: None,
},
};
let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program");
let result = backend.execute(inp).expect("Execution");
assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1");
}
#[test]
fn test_card_bin() {
let program_str = r#"
default: ["stripe", "adyen"]
rule_1: ["stripe"]
{
card_bin="123456"
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let inp = inputs::BackendInput {
metadata: None,
payment: inputs::PaymentInput {
amount: MinorUnit::new(32),
currency: enums::Currency::USD,
card_bin: Some("123456".to_string()),
authentication_type: Some(enums::AuthenticationType::NoThreeDs),
capture_method: Some(enums::CaptureMethod::Automatic),
business_country: Some(enums::Country::UnitedStatesOfAmerica),
billing_country: Some(enums::Country::France),
business_label: None,
setup_future_usage: None,
},
payment_method: inputs::PaymentMethodInput {
payment_method: Some(enums::PaymentMethod::PayLater),
payment_method_type: Some(enums::PaymentMethodType::Affirm),
card_network: None,
},
mandate: inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
},
};
let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program");
let result = backend.execute(inp).expect("Execution");
assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1");
}
#[test]
fn test_payment_amount() {
let program_str = r#"
default: ["stripe", "adyen"]
rule_1: ["stripe"]
{
amount = 32
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let inp = inputs::BackendInput {
metadata: None,
payment: inputs::PaymentInput {
amount: MinorUnit::new(32),
currency: enums::Currency::USD,
card_bin: None,
authentication_type: Some(enums::AuthenticationType::NoThreeDs),
capture_method: Some(enums::CaptureMethod::Automatic),
business_country: Some(enums::Country::UnitedStatesOfAmerica),
billing_country: Some(enums::Country::France),
business_label: None,
setup_future_usage: None,
},
payment_method: inputs::PaymentMethodInput {
payment_method: Some(enums::PaymentMethod::PayLater),
payment_method_type: Some(enums::PaymentMethodType::Affirm),
card_network: None,
},
mandate: inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
},
};
let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program");
let result = backend.execute(inp).expect("Execution");
assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1");
}
#[test]
fn test_payment_method() {
let program_str = r#"
default: ["stripe", "adyen"]
rule_1: ["stripe"]
{
payment_method = pay_later
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let inp = inputs::BackendInput {
metadata: None,
payment: inputs::PaymentInput {
amount: MinorUnit::new(32),
currency: enums::Currency::USD,
card_bin: None,
authentication_type: Some(enums::AuthenticationType::NoThreeDs),
capture_method: Some(enums::CaptureMethod::Automatic),
business_country: Some(enums::Country::UnitedStatesOfAmerica),
billing_country: Some(enums::Country::France),
business_label: None,
setup_future_usage: None,
},
payment_method: inputs::PaymentMethodInput {
payment_method: Some(enums::PaymentMethod::PayLater),
payment_method_type: Some(enums::PaymentMethodType::Affirm),
card_network: None,
},
mandate: inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
},
};
let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program");
let result = backend.execute(inp).expect("Execution");
assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1");
}
#[test]
fn test_future_usage() {
let program_str = r#"
default: ["stripe", "adyen"]
rule_1: ["stripe"]
{
setup_future_usage = off_session
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let inp = inputs::BackendInput {
metadata: None,
payment: inputs::PaymentInput {
amount: MinorUnit::new(32),
currency: enums::Currency::USD,
card_bin: None,
authentication_type: Some(enums::AuthenticationType::NoThreeDs),
capture_method: Some(enums::CaptureMethod::Automatic),
business_country: Some(enums::Country::UnitedStatesOfAmerica),
billing_country: Some(enums::Country::France),
business_label: None,
setup_future_usage: Some(enums::SetupFutureUsage::OffSession),
},
payment_method: inputs::PaymentMethodInput {
payment_method: Some(enums::PaymentMethod::PayLater),
payment_method_type: Some(enums::PaymentMethodType::Affirm),
card_network: None,
},
mandate: inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
},
};
let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program");
let result = backend.execute(inp).expect("Execution");
assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1");
}
#[test]
fn test_metadata_execution() {
let program_str = r#"
default: ["stripe"," adyen"]
rule_1: ["stripe"]
{
"metadata_key" = "arbitrary meta"
}
"#;
let mut meta_map = FxHashMap::default();
meta_map.insert("metadata_key".to_string(), "arbitrary meta".to_string());
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let inp = inputs::BackendInput {
metadata: Some(meta_map),
payment: inputs::PaymentInput {
amount: MinorUnit::new(32),
card_bin: None,
currency: enums::Currency::USD,
authentication_type: Some(enums::AuthenticationType::NoThreeDs),
capture_method: Some(enums::CaptureMethod::Automatic),
business_country: Some(enums::Country::UnitedStatesOfAmerica),
billing_country: Some(enums::Country::France),
business_label: None,
setup_future_usage: None,
},
payment_method: inputs::PaymentMethodInput {
payment_method: Some(enums::PaymentMethod::PayLater),
payment_method_type: Some(enums::PaymentMethodType::Affirm),
card_network: None,
},
mandate: inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
},
};
let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program");
let result = backend.execute(inp).expect("Execution");
assert_eq!(result.rule_name.expect("Rule Name").as_str(), "rule_1");
}
#[test]
fn test_less_than_operator() {
let program_str = r#"
default: ["stripe", "adyen"]
rule_1: ["stripe"]
{
amount>=123
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let inp_greater = inputs::BackendInput {
metadata: None,
payment: inputs::PaymentInput {
amount: MinorUnit::new(150),
card_bin: None,
currency: enums::Currency::USD,
authentication_type: Some(enums::AuthenticationType::NoThreeDs),
capture_method: Some(enums::CaptureMethod::Automatic),
business_country: Some(enums::Country::UnitedStatesOfAmerica),
billing_country: Some(enums::Country::France),
business_label: None,
setup_future_usage: None,
},
payment_method: inputs::PaymentMethodInput {
payment_method: Some(enums::PaymentMethod::PayLater),
payment_method_type: Some(enums::PaymentMethodType::Affirm),
card_network: None,
},
mandate: inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
},
};
let mut inp_equal = inp_greater.clone();
inp_equal.payment.amount = MinorUnit::new(123);
let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program");
let result_greater = backend.execute(inp_greater).expect("Execution");
let result_equal = backend.execute(inp_equal).expect("Execution");
assert_eq!(
result_equal.rule_name.expect("Rule Name").as_str(),
"rule_1"
);
assert_eq!(
result_greater.rule_name.expect("Rule Name").as_str(),
"rule_1"
);
}
#[test]
fn test_greater_than_operator() {
let program_str = r#"
default: ["stripe", "adyen"]
rule_1: ["stripe"]
{
amount<=123
}
"#;
let (_, program) = ast::parser::program::<DummyOutput>(program_str).expect("Program");
let inp_lower = inputs::BackendInput {
metadata: None,
payment: inputs::PaymentInput {
amount: MinorUnit::new(120),
card_bin: None,
currency: enums::Currency::USD,
authentication_type: Some(enums::AuthenticationType::NoThreeDs),
capture_method: Some(enums::CaptureMethod::Automatic),
business_country: Some(enums::Country::UnitedStatesOfAmerica),
billing_country: Some(enums::Country::France),
business_label: None,
setup_future_usage: None,
},
payment_method: inputs::PaymentMethodInput {
payment_method: Some(enums::PaymentMethod::PayLater),
payment_method_type: Some(enums::PaymentMethodType::Affirm),
card_network: None,
},
mandate: inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
},
};
let mut inp_equal = inp_lower.clone();
inp_equal.payment.amount = MinorUnit::new(123);
let backend = VirInterpreterBackend::<DummyOutput>::with_program(program).expect("Program");
let result_equal = backend.execute(inp_equal).expect("Execution");
let result_lower = backend.execute(inp_lower).expect("Execution");
assert_eq!(
result_equal.rule_name.expect("Rule Name").as_str(),
"rule_1"
);
assert_eq!(
result_lower.rule_name.expect("Rule Name").as_str(),
"rule_1"
);
}
}
| 4,987 | 976 |
hyperswitch | crates/euclid/src/backend/inputs.rs | .rs | use rustc_hash::FxHashMap;
use serde::{Deserialize, Serialize};
use crate::enums;
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MandateData {
pub mandate_acceptance_type: Option<enums::MandateAcceptanceType>,
pub mandate_type: Option<enums::MandateType>,
pub payment_type: Option<enums::PaymentType>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentMethodInput {
pub payment_method: Option<enums::PaymentMethod>,
pub payment_method_type: Option<enums::PaymentMethodType>,
pub card_network: Option<enums::CardNetwork>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentInput {
pub amount: common_utils::types::MinorUnit,
pub currency: enums::Currency,
pub authentication_type: Option<enums::AuthenticationType>,
pub card_bin: Option<String>,
pub capture_method: Option<enums::CaptureMethod>,
pub business_country: Option<enums::Country>,
pub billing_country: Option<enums::Country>,
pub business_label: Option<String>,
pub setup_future_usage: Option<enums::SetupFutureUsage>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BackendInput {
pub metadata: Option<FxHashMap<String, String>>,
pub payment: PaymentInput,
pub payment_method: PaymentMethodInput,
pub mandate: MandateData,
}
| 300 | 977 |
hyperswitch | crates/euclid/src/backend/interpreter.rs | .rs | pub mod types;
use common_utils::types::MinorUnit;
use crate::{
backend::{self, inputs, EuclidBackend},
frontend::ast,
};
pub struct InterpreterBackend<O> {
program: ast::Program<O>,
}
impl<O> InterpreterBackend<O>
where
O: Clone,
{
fn eval_number_comparison_array(
num: MinorUnit,
array: &[ast::NumberComparison],
) -> Result<bool, types::InterpreterError> {
for comparison in array {
let other = comparison.number;
let res = match comparison.comparison_type {
ast::ComparisonType::GreaterThan => num > other,
ast::ComparisonType::LessThan => num < other,
ast::ComparisonType::LessThanEqual => num <= other,
ast::ComparisonType::GreaterThanEqual => num >= other,
ast::ComparisonType::Equal => num == other,
ast::ComparisonType::NotEqual => num != other,
};
if res {
return Ok(true);
}
}
Ok(false)
}
fn eval_comparison(
comparison: &ast::Comparison,
ctx: &types::Context,
) -> Result<bool, types::InterpreterError> {
use ast::{ComparisonType::*, ValueType::*};
let value = ctx
.get(&comparison.lhs)
.ok_or_else(|| types::InterpreterError {
error_type: types::InterpreterErrorType::InvalidKey(comparison.lhs.clone()),
metadata: comparison.metadata.clone(),
})?;
if let Some(val) = value {
match (val, &comparison.comparison, &comparison.value) {
(EnumVariant(e1), Equal, EnumVariant(e2)) => Ok(e1 == e2),
(EnumVariant(e1), NotEqual, EnumVariant(e2)) => Ok(e1 != e2),
(EnumVariant(e), Equal, EnumVariantArray(evec)) => Ok(evec.iter().any(|v| e == v)),
(EnumVariant(e), NotEqual, EnumVariantArray(evec)) => {
Ok(evec.iter().all(|v| e != v))
}
(Number(n1), Equal, Number(n2)) => Ok(n1 == n2),
(Number(n1), NotEqual, Number(n2)) => Ok(n1 != n2),
(Number(n1), LessThanEqual, Number(n2)) => Ok(n1 <= n2),
(Number(n1), GreaterThanEqual, Number(n2)) => Ok(n1 >= n2),
(Number(n1), LessThan, Number(n2)) => Ok(n1 < n2),
(Number(n1), GreaterThan, Number(n2)) => Ok(n1 > n2),
(Number(n), Equal, NumberArray(nvec)) => Ok(nvec.iter().any(|v| v == n)),
(Number(n), NotEqual, NumberArray(nvec)) => Ok(nvec.iter().all(|v| v != n)),
(Number(n), Equal, NumberComparisonArray(ncvec)) => {
Self::eval_number_comparison_array(*n, ncvec)
}
_ => Err(types::InterpreterError {
error_type: types::InterpreterErrorType::InvalidComparison,
metadata: comparison.metadata.clone(),
}),
}
} else {
Ok(false)
}
}
fn eval_if_condition(
condition: &ast::IfCondition,
ctx: &types::Context,
) -> Result<bool, types::InterpreterError> {
for comparison in condition {
let res = Self::eval_comparison(comparison, ctx)?;
if !res {
return Ok(false);
}
}
Ok(true)
}
fn eval_if_statement(
stmt: &ast::IfStatement,
ctx: &types::Context,
) -> Result<bool, types::InterpreterError> {
let cond_res = Self::eval_if_condition(&stmt.condition, ctx)?;
if !cond_res {
return Ok(false);
}
if let Some(ref nested) = stmt.nested {
for nested_if in nested {
let res = Self::eval_if_statement(nested_if, ctx)?;
if res {
return Ok(true);
}
}
return Ok(false);
}
Ok(true)
}
fn eval_rule_statements(
statements: &[ast::IfStatement],
ctx: &types::Context,
) -> Result<bool, types::InterpreterError> {
for stmt in statements {
let res = Self::eval_if_statement(stmt, ctx)?;
if res {
return Ok(true);
}
}
Ok(false)
}
#[inline]
fn eval_rule(
rule: &ast::Rule<O>,
ctx: &types::Context,
) -> Result<bool, types::InterpreterError> {
Self::eval_rule_statements(&rule.statements, ctx)
}
fn eval_program(
program: &ast::Program<O>,
ctx: &types::Context,
) -> Result<backend::BackendOutput<O>, types::InterpreterError> {
for rule in &program.rules {
let res = Self::eval_rule(rule, ctx)?;
if res {
return Ok(backend::BackendOutput {
connector_selection: rule.connector_selection.clone(),
rule_name: Some(rule.name.clone()),
});
}
}
Ok(backend::BackendOutput {
connector_selection: program.default_selection.clone(),
rule_name: None,
})
}
}
impl<O> EuclidBackend<O> for InterpreterBackend<O>
where
O: Clone,
{
type Error = types::InterpreterError;
fn with_program(program: ast::Program<O>) -> Result<Self, Self::Error> {
Ok(Self { program })
}
fn execute(&self, input: inputs::BackendInput) -> Result<super::BackendOutput<O>, Self::Error> {
let ctx: types::Context = input.into();
Self::eval_program(&self.program, &ctx)
}
}
| 1,262 | 978 |
hyperswitch | crates/euclid/src/backend/vir_interpreter/types.rs | .rs | use rustc_hash::{FxHashMap, FxHashSet};
use crate::{
backend::inputs::BackendInput,
dssa,
types::{self, EuclidKey, EuclidValue, MetadataValue, NumValueRefinement, StrValue},
};
#[derive(Debug, Clone, serde::Serialize, thiserror::Error)]
pub enum VirInterpreterError {
#[error("Error when lowering the program: {0:?}")]
LoweringError(dssa::types::AnalysisError),
}
pub struct Context {
atomic_values: FxHashSet<EuclidValue>,
numeric_values: FxHashMap<EuclidKey, EuclidValue>,
}
impl Context {
pub fn check_presence(&self, value: &EuclidValue) -> bool {
let key = value.get_key();
match key.key_type() {
types::DataType::MetadataValue => self.atomic_values.contains(value),
types::DataType::StrValue => self.atomic_values.contains(value),
types::DataType::EnumVariant => self.atomic_values.contains(value),
types::DataType::Number => {
let ctx_num_value = self
.numeric_values
.get(&key)
.and_then(|value| value.get_num_value());
value.get_num_value().zip(ctx_num_value).is_some_and(
|(program_value, ctx_value)| {
let program_num = program_value.number;
let ctx_num = ctx_value.number;
match &program_value.refinement {
None => program_num == ctx_num,
Some(NumValueRefinement::NotEqual) => ctx_num != program_num,
Some(NumValueRefinement::GreaterThan) => ctx_num > program_num,
Some(NumValueRefinement::GreaterThanEqual) => ctx_num >= program_num,
Some(NumValueRefinement::LessThanEqual) => ctx_num <= program_num,
Some(NumValueRefinement::LessThan) => ctx_num < program_num,
}
},
)
}
}
}
pub fn from_input(input: BackendInput) -> Self {
let payment = input.payment;
let payment_method = input.payment_method;
let meta_data = input.metadata;
let payment_mandate = input.mandate;
let mut enum_values: FxHashSet<EuclidValue> =
FxHashSet::from_iter([EuclidValue::PaymentCurrency(payment.currency)]);
if let Some(pm) = payment_method.payment_method {
enum_values.insert(EuclidValue::PaymentMethod(pm));
}
if let Some(pmt) = payment_method.payment_method_type {
enum_values.insert(EuclidValue::PaymentMethodType(pmt));
}
if let Some(met) = meta_data {
for (key, value) in met.into_iter() {
enum_values.insert(EuclidValue::Metadata(MetadataValue { key, value }));
}
}
if let Some(card_network) = payment_method.card_network {
enum_values.insert(EuclidValue::CardNetwork(card_network));
}
if let Some(at) = payment.authentication_type {
enum_values.insert(EuclidValue::AuthenticationType(at));
}
if let Some(capture_method) = payment.capture_method {
enum_values.insert(EuclidValue::CaptureMethod(capture_method));
}
if let Some(country) = payment.business_country {
enum_values.insert(EuclidValue::BusinessCountry(country));
}
if let Some(country) = payment.billing_country {
enum_values.insert(EuclidValue::BillingCountry(country));
}
if let Some(card_bin) = payment.card_bin {
enum_values.insert(EuclidValue::CardBin(StrValue { value: card_bin }));
}
if let Some(business_label) = payment.business_label {
enum_values.insert(EuclidValue::BusinessLabel(StrValue {
value: business_label,
}));
}
if let Some(setup_future_usage) = payment.setup_future_usage {
enum_values.insert(EuclidValue::SetupFutureUsage(setup_future_usage));
}
if let Some(payment_type) = payment_mandate.payment_type {
enum_values.insert(EuclidValue::PaymentType(payment_type));
}
if let Some(mandate_type) = payment_mandate.mandate_type {
enum_values.insert(EuclidValue::MandateType(mandate_type));
}
if let Some(mandate_acceptance_type) = payment_mandate.mandate_acceptance_type {
enum_values.insert(EuclidValue::MandateAcceptanceType(mandate_acceptance_type));
}
let numeric_values: FxHashMap<EuclidKey, EuclidValue> = FxHashMap::from_iter([(
EuclidKey::PaymentAmount,
EuclidValue::PaymentAmount(types::NumValue {
number: payment.amount,
refinement: None,
}),
)]);
Self {
atomic_values: enum_values,
numeric_values,
}
}
}
| 1,038 | 979 |
hyperswitch | crates/euclid/src/backend/interpreter/types.rs | .rs | use std::{collections::HashMap, fmt, ops::Deref, string::ToString};
use serde::Serialize;
use crate::{backend::inputs, frontend::ast::ValueType, types::EuclidKey};
#[derive(Debug, Clone, Serialize, thiserror::Error)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum InterpreterErrorType {
#[error("Invalid key received '{0}'")]
InvalidKey(String),
#[error("Invalid Comparison")]
InvalidComparison,
}
#[derive(Debug, Clone, Serialize, thiserror::Error)]
pub struct InterpreterError {
pub error_type: InterpreterErrorType,
pub metadata: HashMap<String, serde_json::Value>,
}
impl fmt::Display for InterpreterError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
InterpreterErrorType::fmt(&self.error_type, f)
}
}
pub struct Context(HashMap<String, Option<ValueType>>);
impl Deref for Context {
type Target = HashMap<String, Option<ValueType>>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl From<inputs::BackendInput> for Context {
fn from(input: inputs::BackendInput) -> Self {
let ctx = HashMap::<String, Option<ValueType>>::from_iter([
(
EuclidKey::PaymentMethod.to_string(),
input
.payment_method
.payment_method
.map(|pm| ValueType::EnumVariant(pm.to_string())),
),
(
EuclidKey::PaymentMethodType.to_string(),
input
.payment_method
.payment_method_type
.map(|pt| ValueType::EnumVariant(pt.to_string())),
),
(
EuclidKey::AuthenticationType.to_string(),
input
.payment
.authentication_type
.map(|at| ValueType::EnumVariant(at.to_string())),
),
(
EuclidKey::CaptureMethod.to_string(),
input
.payment
.capture_method
.map(|cm| ValueType::EnumVariant(cm.to_string())),
),
(
EuclidKey::PaymentAmount.to_string(),
Some(ValueType::Number(input.payment.amount)),
),
(
EuclidKey::PaymentCurrency.to_string(),
Some(ValueType::EnumVariant(input.payment.currency.to_string())),
),
]);
Self(ctx)
}
}
| 508 | 980 |
hyperswitch | crates/events/Cargo.toml | .toml | [package]
name = "events"
description = "Events framework for generating events & some sample implementations"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
license.workspace = true
[dependencies]
# First Party crates
masking = { version = "0.1.0", path = "../masking" }
router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] }
# Third Party crates
error-stack = "0.4.1"
serde = "1.0.197"
serde_json = "1.0.114"
thiserror = "1.0.58"
time = "0.3.34"
[lints]
workspace = true
| 177 | 981 |
hyperswitch | crates/events/src/actix.rs | .rs | use router_env::tracing_actix_web::RequestId;
use crate::EventInfo;
impl EventInfo for RequestId {
type Data = String;
fn data(&self) -> error_stack::Result<String, crate::EventsError> {
Ok(self.as_hyphenated().to_string())
}
fn key(&self) -> String {
"request_id".to_string()
}
}
| 84 | 982 |
hyperswitch | crates/events/src/lib.rs | .rs | #![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg_hide))]
#![cfg_attr(docsrs, doc(cfg_hide(doc)))]
#![warn(missing_docs)]
//! A generic event handler system.
//! This library consists of 4 parts:
//! Event Sink: A trait that defines how events are published. This could be a simple logger, a message queue, or a database.
//! EventContext: A struct that holds the event sink and metadata about the event. This is used to create events. This can be used to add metadata to all events, such as the user who triggered the event.
//! EventInfo: A trait that defines the metadata that is sent with the event. It works with the EventContext to add metadata to all events.
//! Event: A trait that defines the event itself. This trait is used to define the data that is sent with the event and defines the event's type & identifier.
mod actix;
use std::{collections::HashMap, sync::Arc};
use error_stack::{Result, ResultExt};
use masking::{ErasedMaskSerialize, Serialize};
use router_env::logger;
use serde::Serializer;
use serde_json::Value;
use time::PrimitiveDateTime;
/// Errors that can occur when working with events.
#[derive(Debug, Clone, thiserror::Error)]
pub enum EventsError {
/// An error occurred when publishing the event.
#[error("Generic Error")]
GenericError,
/// An error occurred when serializing the event.
#[error("Event serialization error")]
SerializationError,
/// An error occurred when publishing/producing the event.
#[error("Event publishing error")]
PublishError,
}
/// An event that can be published.
pub trait Event: EventInfo {
/// The type of the event.
type EventType;
/// The timestamp of the event.
fn timestamp(&self) -> PrimitiveDateTime;
/// The (unique) identifier of the event.
fn identifier(&self) -> String;
/// The class/type of the event. This is used to group/categorize events together.
fn class(&self) -> Self::EventType;
/// Metadata associated with the event
fn metadata(&self) -> HashMap<String, String> {
HashMap::new()
}
}
/// Hold the context information for any events
#[derive(Clone)]
pub struct EventContext<T, A>
where
A: MessagingInterface<MessageClass = T>,
{
message_sink: Arc<A>,
metadata: HashMap<String, Value>,
}
/// intermediary structure to build events with in-place info.
#[must_use = "make sure to call `emit` or `try_emit` to actually emit the event"]
pub struct EventBuilder<T, A, E, D>
where
A: MessagingInterface<MessageClass = T>,
E: Event<EventType = T, Data = D>,
{
message_sink: Arc<A>,
metadata: HashMap<String, Value>,
event: E,
}
/// A flattened event that flattens the context provided to it along with the actual event.
struct FlatMapEvent<T, A: Event<EventType = T>>(HashMap<String, Value>, A);
impl<T, A, E, D> EventBuilder<T, A, E, D>
where
A: MessagingInterface<MessageClass = T>,
E: Event<EventType = T, Data = D>,
{
/// Add metadata to the event.
pub fn with<F: ErasedMaskSerialize, G: EventInfo<Data = F> + 'static>(
mut self,
info: G,
) -> Self {
info.data()
.and_then(|i| {
i.masked_serialize()
.change_context(EventsError::SerializationError)
})
.map_err(|e| {
logger::error!("Error adding event info: {:?}", e);
})
.ok()
.and_then(|data| self.metadata.insert(info.key(), data));
self
}
/// Emit the event and log any errors.
pub fn emit(self) {
self.try_emit()
.map_err(|e| {
logger::error!("Error emitting event: {:?}", e);
})
.ok();
}
/// Emit the event.
pub fn try_emit(self) -> Result<(), EventsError> {
let ts = self.event.timestamp();
let metadata = self.event.metadata();
self.message_sink
.send_message(FlatMapEvent(self.metadata, self.event), metadata, ts)
}
}
impl<T, A> Serialize for FlatMapEvent<T, A>
where
A: Event<EventType = T>,
{
fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut serialize_map: HashMap<_, _> = self
.0
.iter()
.filter_map(|(k, v)| Some((k.clone(), v.masked_serialize().ok()?)))
.collect();
match self.1.data().map(|i| i.masked_serialize()) {
Ok(Ok(Value::Object(map))) => {
for (k, v) in map.into_iter() {
serialize_map.insert(k, v);
}
}
Ok(Ok(i)) => {
serialize_map.insert(self.1.key(), i);
}
i => {
logger::error!("Error serializing event: {:?}", i);
}
};
serialize_map.serialize(serializer)
}
}
impl<T, A> EventContext<T, A>
where
A: MessagingInterface<MessageClass = T>,
{
/// Create a new event context.
pub fn new(message_sink: A) -> Self {
Self {
message_sink: Arc::new(message_sink),
metadata: HashMap::new(),
}
}
/// Add metadata to the event context.
#[track_caller]
pub fn record_info<G: ErasedMaskSerialize, E: EventInfo<Data = G> + 'static>(
&mut self,
info: E,
) {
match info.data().and_then(|i| {
i.masked_serialize()
.change_context(EventsError::SerializationError)
}) {
Ok(data) => {
self.metadata.insert(info.key(), data);
}
Err(e) => {
logger::error!("Error recording event info: {:?}", e);
}
}
}
/// Emit an event.
pub fn try_emit<E: Event<EventType = T>>(&self, event: E) -> Result<(), EventsError> {
EventBuilder {
message_sink: self.message_sink.clone(),
metadata: self.metadata.clone(),
event,
}
.try_emit()
}
/// Emit an event.
pub fn emit<D, E: Event<EventType = T, Data = D>>(&self, event: E) {
EventBuilder {
message_sink: self.message_sink.clone(),
metadata: self.metadata.clone(),
event,
}
.emit()
}
/// Create an event builder.
pub fn event<D, E: Event<EventType = T, Data = D>>(
&self,
event: E,
) -> EventBuilder<T, A, E, D> {
EventBuilder {
message_sink: self.message_sink.clone(),
metadata: self.metadata.clone(),
event,
}
}
}
/// Add information/metadata to the current context of an event.
pub trait EventInfo {
/// The data that is sent with the event.
type Data: ErasedMaskSerialize;
/// The data that is sent with the event.
fn data(&self) -> Result<Self::Data, EventsError>;
/// The key identifying the data for an event.
fn key(&self) -> String;
}
impl EventInfo for (String, String) {
type Data = String;
fn data(&self) -> Result<String, EventsError> {
Ok(self.1.clone())
}
fn key(&self) -> String {
self.0.clone()
}
}
/// A messaging interface for sending messages/events.
/// This can be implemented for any messaging system, such as a message queue, a logger, or a database.
pub trait MessagingInterface {
/// The type of the event used for categorization by the event publisher.
type MessageClass;
/// Send a message that follows the defined message class.
fn send_message<T>(
&self,
data: T,
metadata: HashMap<String, String>,
timestamp: PrimitiveDateTime,
) -> Result<(), EventsError>
where
T: Message<Class = Self::MessageClass> + ErasedMaskSerialize;
}
/// A message that can be sent.
pub trait Message {
/// The type of the event used for categorization by the event publisher.
type Class;
/// The type of the event used for categorization by the event publisher.
fn get_message_class(&self) -> Self::Class;
/// The (unique) identifier of the event.
fn identifier(&self) -> String;
}
impl<T, A> Message for FlatMapEvent<T, A>
where
A: Event<EventType = T>,
{
type Class = T;
fn get_message_class(&self) -> Self::Class {
self.1.class()
}
fn identifier(&self) -> String {
self.1.identifier()
}
}
| 1,959 | 983 |
hyperswitch | crates/hyperswitch_interfaces/Cargo.toml | .toml | [package]
name = "hyperswitch_interfaces"
version = "0.1.0"
edition.workspace = true
rust-version.workspace = true
readme = "README.md"
license.workspace = true
[features]
default = ["dummy_connector", "frm", "payouts"]
dummy_connector = []
v1 = ["hyperswitch_domain_models/v1", "api_models/v1", "common_utils/v1"]
v2 = []
payouts = ["hyperswitch_domain_models/payouts"]
frm = ["hyperswitch_domain_models/frm"]
revenue_recovery= []
[dependencies]
actix-web = "4.5.1"
async-trait = "0.1.79"
bytes = "1.6.0"
dyn-clone = "1.0.17"
error-stack = "0.4.1"
http = "0.2.12"
mime = "0.3.17"
once_cell = "1.19.0"
reqwest = "0.11.27"
serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0.115"
strum = { version = "0.26", features = ["derive"] }
thiserror = "1.0.58"
time = "0.3.35"
url = "2.5.0"
# First party crates
hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false }
masking = { version = "0.1.0", path = "../masking" }
api_models = { version = "0.1.0", path = "../api_models" }
common_enums = { version = "0.1.0", path = "../common_enums" }
common_utils = { version = "0.1.0", path = "../common_utils" }
router_derive = { version = "0.1.0", path = "../router_derive" }
router_env = { version = "0.1.0", path = "../router_env" }
[lints]
workspace = true
| 470 | 984 |
hyperswitch | crates/hyperswitch_interfaces/README.md | .md | # Hyperswitch Interfaces
This crate includes interfaces and its error types
| 15 | 985 |
hyperswitch | crates/hyperswitch_interfaces/src/metrics.rs | .rs | //! Metrics interface
use router_env::{counter_metric, global_meter};
global_meter!(GLOBAL_METER, "ROUTER_API");
counter_metric!(UNIMPLEMENTED_FLOW, GLOBAL_METER);
| 38 | 986 |
hyperswitch | crates/hyperswitch_interfaces/src/disputes.rs | .rs | //! Disputes interface
use time::PrimitiveDateTime;
/// struct DisputePayload
#[derive(Default, Debug)]
pub struct DisputePayload {
/// amount
pub amount: String,
/// currency
pub currency: common_enums::enums::Currency,
/// dispute_stage
pub dispute_stage: common_enums::enums::DisputeStage,
/// connector_status
pub connector_status: String,
/// connector_dispute_id
pub connector_dispute_id: String,
/// connector_reason
pub connector_reason: Option<String>,
/// connector_reason_code
pub connector_reason_code: Option<String>,
/// challenge_required_by
pub challenge_required_by: Option<PrimitiveDateTime>,
/// created_at
pub created_at: Option<PrimitiveDateTime>,
/// updated_at
pub updated_at: Option<PrimitiveDateTime>,
}
| 180 | 987 |
hyperswitch | crates/hyperswitch_interfaces/src/api.rs | .rs | //! API interface
/// authentication module
pub mod authentication;
/// authentication_v2 module
pub mod authentication_v2;
pub mod disputes;
pub mod disputes_v2;
pub mod files;
pub mod files_v2;
#[cfg(feature = "frm")]
pub mod fraud_check;
#[cfg(feature = "frm")]
pub mod fraud_check_v2;
pub mod payments;
pub mod payments_v2;
#[cfg(feature = "payouts")]
pub mod payouts;
#[cfg(feature = "payouts")]
pub mod payouts_v2;
pub mod refunds;
pub mod refunds_v2;
pub mod revenue_recovery;
pub mod revenue_recovery_v2;
use std::fmt::Debug;
use common_enums::{
enums::{CallConnectorAction, CaptureMethod, EventClass, PaymentAction, PaymentMethodType},
PaymentMethod,
};
use common_utils::{
errors::CustomResult,
request::{Method, Request, RequestContent},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
configs::Connectors,
errors::api_error_response::ApiErrorResponse,
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_data_v2::{
flow_common_types::WebhookSourceVerifyData, AccessTokenFlowData, MandateRevokeFlowData,
UasFlowData,
},
router_flow_types::{
mandate_revoke::MandateRevoke, AccessTokenAuth, Authenticate, AuthenticationConfirmation,
PostAuthenticate, PreAuthenticate, VerifyWebhookSource,
},
router_request_types::{
unified_authentication_service::{
UasAuthenticationRequestData, UasAuthenticationResponseData,
UasConfirmationRequestData, UasPostAuthenticationRequestData,
UasPreAuthenticationRequestData,
},
AccessTokenRequestData, MandateRevokeRequestData, VerifyWebhookSourceRequestData,
},
router_response_types::{
ConnectorInfo, MandateRevokeResponseData, PaymentMethodDetails, SupportedPaymentMethods,
VerifyWebhookSourceResponseData,
},
};
use masking::Maskable;
use serde_json::json;
#[cfg(feature = "frm")]
pub use self::fraud_check::*;
#[cfg(feature = "frm")]
pub use self::fraud_check_v2::*;
#[cfg(feature = "payouts")]
pub use self::payouts::*;
#[cfg(feature = "payouts")]
pub use self::payouts_v2::*;
pub use self::{payments::*, refunds::*};
use crate::{
connector_integration_v2::ConnectorIntegrationV2, consts, errors,
events::connector_api_logs::ConnectorEvent, metrics, types, webhooks,
};
/// Connector trait
pub trait Connector:
Send
+ Refund
+ Payment
+ ConnectorRedirectResponse
+ webhooks::IncomingWebhook
+ ConnectorAccessToken
+ disputes::Dispute
+ files::FileUpload
+ ConnectorTransactionId
+ Payouts
+ ConnectorVerifyWebhookSource
+ FraudCheck
+ ConnectorMandateRevoke
+ authentication::ExternalAuthentication
+ TaxCalculation
+ UnifiedAuthenticationService
+ revenue_recovery::RevenueRecovery
{
}
impl<
T: Refund
+ Payment
+ ConnectorRedirectResponse
+ Send
+ webhooks::IncomingWebhook
+ ConnectorAccessToken
+ disputes::Dispute
+ files::FileUpload
+ ConnectorTransactionId
+ Payouts
+ ConnectorVerifyWebhookSource
+ FraudCheck
+ ConnectorMandateRevoke
+ authentication::ExternalAuthentication
+ TaxCalculation
+ UnifiedAuthenticationService
+ revenue_recovery::RevenueRecovery,
> Connector for T
{
}
/// Alias for Box<&'static (dyn Connector + Sync)>
pub type BoxedConnector = Box<&'static (dyn Connector + Sync)>;
/// type BoxedConnectorIntegration
pub type BoxedConnectorIntegration<'a, T, Req, Resp> =
Box<&'a (dyn ConnectorIntegration<T, Req, Resp> + Send + Sync)>;
/// trait ConnectorIntegrationAny
pub trait ConnectorIntegrationAny<T, Req, Resp>: Send + Sync + 'static {
/// fn get_connector_integration
fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp>;
}
impl<S, T, Req, Resp> ConnectorIntegrationAny<T, Req, Resp> for S
where
S: ConnectorIntegration<T, Req, Resp> + Send + Sync,
{
fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp> {
Box::new(self)
}
}
/// trait ConnectorIntegration
pub trait ConnectorIntegration<T, Req, Resp>:
ConnectorIntegrationAny<T, Req, Resp> + Sync + ConnectorCommon
{
/// fn get_headers
fn get_headers(
&self,
_req: &RouterData<T, Req, Resp>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
Ok(vec![])
}
/// fn get_content_type
fn get_content_type(&self) -> &'static str {
mime::APPLICATION_JSON.essence_str()
}
/// fn get_content_type
fn get_accept_type(&self) -> &'static str {
mime::APPLICATION_JSON.essence_str()
}
/// primarily used when creating signature based on request method of payment flow
fn get_http_method(&self) -> Method {
Method::Post
}
/// fn get_url
fn get_url(
&self,
_req: &RouterData<T, Req, Resp>,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(String::new())
}
/// fn get_request_body
fn get_request_body(
&self,
_req: &RouterData<T, Req, Resp>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
Ok(RequestContent::Json(Box::new(json!(r#"{}"#))))
}
/// fn get_request_form_data
fn get_request_form_data(
&self,
_req: &RouterData<T, Req, Resp>,
) -> CustomResult<Option<reqwest::multipart::Form>, errors::ConnectorError> {
Ok(None)
}
/// fn build_request
fn build_request(
&self,
req: &RouterData<T, Req, Resp>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
metrics::UNIMPLEMENTED_FLOW.add(
1,
router_env::metric_attributes!(("connector", req.connector.clone())),
);
Ok(None)
}
/// fn handle_response
fn handle_response(
&self,
data: &RouterData<T, Req, Resp>,
event_builder: Option<&mut ConnectorEvent>,
_res: types::Response,
) -> CustomResult<RouterData<T, Req, Resp>, errors::ConnectorError>
where
T: Clone,
Req: Clone,
Resp: Clone,
{
event_builder.map(|e| e.set_error(json!({"error": "Not Implemented"})));
Ok(data.clone())
}
/// fn get_error_response
fn get_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
event_builder.map(|event| event.set_error(json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
Ok(ErrorResponse::get_not_implemented())
}
/// fn get_5xx_error_response
fn get_5xx_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
event_builder.map(|event| event.set_error(json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
let error_message = match res.status_code {
500 => "internal_server_error",
501 => "not_implemented",
502 => "bad_gateway",
503 => "service_unavailable",
504 => "gateway_timeout",
505 => "http_version_not_supported",
506 => "variant_also_negotiates",
507 => "insufficient_storage",
508 => "loop_detected",
510 => "not_extended",
511 => "network_authentication_required",
_ => "unknown_error",
};
Ok(ErrorResponse {
code: res.status_code.to_string(),
message: error_message.to_string(),
reason: String::from_utf8(res.response.to_vec()).ok(),
status_code: res.status_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
/// whenever capture sync is implemented at the connector side, this method should be overridden
fn get_multiple_capture_sync_method(
&self,
) -> CustomResult<CaptureSyncMethod, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("multiple capture sync".into()).into())
}
/// fn get_certificate
fn get_certificate(
&self,
_req: &RouterData<T, Req, Resp>,
) -> CustomResult<Option<String>, errors::ConnectorError> {
Ok(None)
}
/// fn get_certificate_key
fn get_certificate_key(
&self,
_req: &RouterData<T, Req, Resp>,
) -> CustomResult<Option<String>, errors::ConnectorError> {
Ok(None)
}
}
/// Sync Methods for multiple captures
#[derive(Debug)]
pub enum CaptureSyncMethod {
/// For syncing multiple captures individually
Individual,
/// For syncing multiple captures together
Bulk,
}
/// Connector accepted currency unit as either "Base" or "Minor"
#[derive(Debug)]
pub enum CurrencyUnit {
/// Base currency unit
Base,
/// Minor currency unit
Minor,
}
/// The trait that provides the common
pub trait ConnectorCommon {
/// Name of the connector (in lowercase).
fn id(&self) -> &'static str;
/// Connector accepted currency unit as either "Base" or "Minor"
fn get_currency_unit(&self) -> CurrencyUnit {
CurrencyUnit::Minor // Default implementation should be remove once it is implemented in all connectors
}
/// HTTP header used for authorization.
fn get_auth_header(
&self,
_auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
Ok(Vec::new())
}
/// HTTP `Content-Type` to be used for POST requests.
/// Defaults to `application/json`.
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
// FIXME write doc - think about this
// fn headers(&self) -> Vec<(&str, &str)>;
/// The base URL for interacting with the connector's API.
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str;
/// common error response for a connector if it is same in all case
fn build_error_response(
&self,
res: types::Response,
_event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
Ok(ErrorResponse {
status_code: res.status_code,
code: consts::NO_ERROR_CODE.to_string(),
message: consts::NO_ERROR_MESSAGE.to_string(),
reason: None,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
}
/// The trait that provides specifications about the connector
pub trait ConnectorSpecifications {
/// Details related to payment method supported by the connector
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
None
}
/// Supported webhooks flows
fn get_supported_webhook_flows(&self) -> Option<&'static [EventClass]> {
None
}
/// About the connector
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
None
}
}
/// Extended trait for connector common to allow functions with generic type
pub trait ConnectorCommonExt<Flow, Req, Resp>:
ConnectorCommon + ConnectorIntegration<Flow, Req, Resp>
{
/// common header builder when every request for the connector have same headers
fn build_headers(
&self,
_req: &RouterData<Flow, Req, Resp>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
Ok(Vec::new())
}
}
/// trait ConnectorMandateRevoke
pub trait ConnectorMandateRevoke:
ConnectorIntegration<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>
{
}
/// trait ConnectorMandateRevokeV2
pub trait ConnectorMandateRevokeV2:
ConnectorIntegrationV2<
MandateRevoke,
MandateRevokeFlowData,
MandateRevokeRequestData,
MandateRevokeResponseData,
>
{
}
/// trait ConnectorAccessToken
pub trait ConnectorAccessToken:
ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken>
{
}
/// trait ConnectorAccessTokenV2
pub trait ConnectorAccessTokenV2:
ConnectorIntegrationV2<AccessTokenAuth, AccessTokenFlowData, AccessTokenRequestData, AccessToken>
{
}
/// trait ConnectorVerifyWebhookSource
pub trait ConnectorVerifyWebhookSource:
ConnectorIntegration<
VerifyWebhookSource,
VerifyWebhookSourceRequestData,
VerifyWebhookSourceResponseData,
>
{
}
/// trait ConnectorVerifyWebhookSourceV2
pub trait ConnectorVerifyWebhookSourceV2:
ConnectorIntegrationV2<
VerifyWebhookSource,
WebhookSourceVerifyData,
VerifyWebhookSourceRequestData,
VerifyWebhookSourceResponseData,
>
{
}
/// trait UnifiedAuthenticationService
pub trait UnifiedAuthenticationService:
ConnectorCommon
+ UasPreAuthentication
+ UasPostAuthentication
+ UasAuthenticationConfirmation
+ UasAuthentication
{
}
/// trait UasPreAuthentication
pub trait UasPreAuthentication:
ConnectorIntegration<
PreAuthenticate,
UasPreAuthenticationRequestData,
UasAuthenticationResponseData,
>
{
}
/// trait UasPostAuthentication
pub trait UasPostAuthentication:
ConnectorIntegration<
PostAuthenticate,
UasPostAuthenticationRequestData,
UasAuthenticationResponseData,
>
{
}
/// trait UasAuthenticationConfirmation
pub trait UasAuthenticationConfirmation:
ConnectorIntegration<
AuthenticationConfirmation,
UasConfirmationRequestData,
UasAuthenticationResponseData,
>
{
}
/// trait UasAuthentication
pub trait UasAuthentication:
ConnectorIntegration<Authenticate, UasAuthenticationRequestData, UasAuthenticationResponseData>
{
}
/// trait UnifiedAuthenticationServiceV2
pub trait UnifiedAuthenticationServiceV2:
ConnectorCommon
+ UasPreAuthenticationV2
+ UasPostAuthenticationV2
+ UasAuthenticationV2
+ UasAuthenticationConfirmationV2
{
}
///trait UasPreAuthenticationV2
pub trait UasPreAuthenticationV2:
ConnectorIntegrationV2<
PreAuthenticate,
UasFlowData,
UasPreAuthenticationRequestData,
UasAuthenticationResponseData,
>
{
}
/// trait UasPostAuthenticationV2
pub trait UasPostAuthenticationV2:
ConnectorIntegrationV2<
PostAuthenticate,
UasFlowData,
UasPostAuthenticationRequestData,
UasAuthenticationResponseData,
>
{
}
/// trait UasAuthenticationConfirmationV2
pub trait UasAuthenticationConfirmationV2:
ConnectorIntegrationV2<
AuthenticationConfirmation,
UasFlowData,
UasConfirmationRequestData,
UasAuthenticationResponseData,
>
{
}
/// trait UasAuthenticationV2
pub trait UasAuthenticationV2:
ConnectorIntegrationV2<
Authenticate,
UasFlowData,
UasAuthenticationRequestData,
UasAuthenticationResponseData,
>
{
}
/// trait ConnectorValidation
pub trait ConnectorValidation: ConnectorCommon + ConnectorSpecifications {
/// Validate, the payment request against the connector supported features
fn validate_connector_against_payment_request(
&self,
capture_method: Option<CaptureMethod>,
payment_method: PaymentMethod,
pmt: Option<PaymentMethodType>,
) -> CustomResult<(), errors::ConnectorError> {
let capture_method = capture_method.unwrap_or_default();
let is_default_capture_method =
[CaptureMethod::Automatic, CaptureMethod::SequentialAutomatic]
.contains(&capture_method);
let is_feature_supported = match self.get_supported_payment_methods() {
Some(supported_payment_methods) => {
let connector_payment_method_type_info = get_connector_payment_method_type_info(
supported_payment_methods,
payment_method,
pmt,
self.id(),
)?;
connector_payment_method_type_info
.map(|payment_method_type_info| {
payment_method_type_info
.supported_capture_methods
.contains(&capture_method)
})
.unwrap_or(true)
}
None => is_default_capture_method,
};
if is_feature_supported {
Ok(())
} else {
Err(errors::ConnectorError::NotSupported {
message: capture_method.to_string(),
connector: self.id(),
}
.into())
}
}
/// fn validate_mandate_payment
fn validate_mandate_payment(
&self,
pm_type: Option<PaymentMethodType>,
_pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let connector = self.id();
match pm_type {
Some(pm_type) => Err(errors::ConnectorError::NotSupported {
message: format!("{} mandate payment", pm_type),
connector,
}
.into()),
None => Err(errors::ConnectorError::NotSupported {
message: " mandate payment".to_string(),
connector,
}
.into()),
}
}
/// fn validate_psync_reference_id
fn validate_psync_reference_id(
&self,
data: &hyperswitch_domain_models::router_request_types::PaymentsSyncData,
_is_three_ds: bool,
_status: common_enums::enums::AttemptStatus,
_connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<(), errors::ConnectorError> {
data.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)
.map(|_| ())
}
/// fn is_webhook_source_verification_mandatory
fn is_webhook_source_verification_mandatory(&self) -> bool {
false
}
}
/// trait ConnectorRedirectResponse
pub trait ConnectorRedirectResponse {
/// fn get_flow_type
fn get_flow_type(
&self,
_query_params: &str,
_json_payload: Option<serde_json::Value>,
_action: PaymentAction,
) -> CustomResult<CallConnectorAction, errors::ConnectorError> {
Ok(CallConnectorAction::Avoid)
}
}
/// Empty trait for when payouts feature is disabled
#[cfg(not(feature = "payouts"))]
pub trait Payouts {}
/// Empty trait for when payouts feature is disabled
#[cfg(not(feature = "payouts"))]
pub trait PayoutsV2 {}
/// Empty trait for when frm feature is disabled
#[cfg(not(feature = "frm"))]
pub trait FraudCheck {}
/// Empty trait for when frm feature is disabled
#[cfg(not(feature = "frm"))]
pub trait FraudCheckV2 {}
fn get_connector_payment_method_type_info(
supported_payment_method: &SupportedPaymentMethods,
payment_method: PaymentMethod,
payment_method_type: Option<PaymentMethodType>,
connector: &'static str,
) -> CustomResult<Option<PaymentMethodDetails>, errors::ConnectorError> {
let payment_method_details =
supported_payment_method
.get(&payment_method)
.ok_or_else(|| errors::ConnectorError::NotSupported {
message: payment_method.to_string(),
connector,
})?;
payment_method_type
.map(|pmt| {
payment_method_details.get(&pmt).cloned().ok_or_else(|| {
errors::ConnectorError::NotSupported {
message: format!("{} {}", payment_method, pmt),
connector,
}
.into()
})
})
.transpose()
}
/// ConnectorTransactionId trait
pub trait ConnectorTransactionId: ConnectorCommon + Sync {
/// fn connector_transaction_id
fn connector_transaction_id(
&self,
payment_attempt: hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
) -> Result<Option<String>, ApiErrorResponse> {
Ok(payment_attempt
.get_connector_payment_id()
.map(ToString::to_string))
}
}
| 4,563 | 988 |
hyperswitch | crates/hyperswitch_interfaces/src/authentication.rs | .rs | //! Authentication interface
/// struct ExternalAuthenticationPayload
#[derive(Clone, serde::Deserialize, Debug, serde::Serialize, PartialEq, Eq)]
pub struct ExternalAuthenticationPayload {
/// trans_status
pub trans_status: common_enums::TransactionStatus,
/// authentication_value
pub authentication_value: Option<String>,
/// eci
pub eci: Option<String>,
}
| 78 | 989 |
hyperswitch | crates/hyperswitch_interfaces/src/encryption_interface.rs | .rs | //! Encryption related interface and error types
#![warn(missing_docs, missing_debug_implementations)]
use common_utils::errors::CustomResult;
/// Trait defining the interface for encryption management
#[async_trait::async_trait]
pub trait EncryptionManagementInterface: Sync + Send + dyn_clone::DynClone {
/// Encrypt the given input data
async fn encrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError>;
/// Decrypt the given input data
async fn decrypt(&self, input: &[u8]) -> CustomResult<Vec<u8>, EncryptionError>;
}
dyn_clone::clone_trait_object!(EncryptionManagementInterface);
/// Errors that may occur during above encryption functionalities
#[derive(Debug, thiserror::Error)]
pub enum EncryptionError {
/// An error occurred when encrypting input data.
#[error("Failed to encrypt input data")]
EncryptionFailed,
/// An error occurred when decrypting input data.
#[error("Failed to decrypt input data")]
DecryptionFailed,
}
| 211 | 990 |
hyperswitch | crates/hyperswitch_interfaces/src/webhooks.rs | .rs | //! Webhooks interface
use common_utils::{crypto, errors::CustomResult, ext_traits::ValueExt};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
api::ApplicationResponse, errors::api_error_response::ApiErrorResponse,
};
use masking::{ExposeInterface, Secret};
use crate::{api::ConnectorCommon, errors};
/// struct IncomingWebhookRequestDetails
#[derive(Debug)]
pub struct IncomingWebhookRequestDetails<'a> {
/// method
pub method: http::Method,
/// uri
pub uri: http::Uri,
/// headers
pub headers: &'a actix_web::http::header::HeaderMap,
/// body
pub body: &'a [u8],
/// query_params
pub query_params: String,
}
/// IncomingWebhookFlowError enum defining the error type for incoming webhook
#[derive(Debug)]
pub enum IncomingWebhookFlowError {
/// Resource not found for the webhook
ResourceNotFound,
/// Internal error for the webhook
InternalError,
}
impl From<&ApiErrorResponse> for IncomingWebhookFlowError {
fn from(api_error_response: &ApiErrorResponse) -> Self {
match api_error_response {
ApiErrorResponse::WebhookResourceNotFound
| ApiErrorResponse::DisputeNotFound { .. }
| ApiErrorResponse::PayoutNotFound
| ApiErrorResponse::MandateNotFound
| ApiErrorResponse::PaymentNotFound
| ApiErrorResponse::RefundNotFound
| ApiErrorResponse::AuthenticationNotFound { .. } => Self::ResourceNotFound,
_ => Self::InternalError,
}
}
}
/// Trait defining incoming webhook
#[async_trait::async_trait]
pub trait IncomingWebhook: ConnectorCommon + Sync {
/// fn get_webhook_body_decoding_algorithm
fn get_webhook_body_decoding_algorithm(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::DecodeMessage + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::NoAlgorithm))
}
/// fn get_webhook_body_decoding_message
fn get_webhook_body_decoding_message(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
Ok(request.body.to_vec())
}
/// fn decode_webhook_body
async fn decode_webhook_body(
&self,
request: &IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
connector_name: &str,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let algorithm = self.get_webhook_body_decoding_algorithm(request)?;
let message = self
.get_webhook_body_decoding_message(request)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let secret = self
.get_webhook_source_verification_merchant_secret(
merchant_id,
connector_name,
connector_webhook_details,
)
.await
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
algorithm
.decode_message(&secret.secret, message.into())
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)
}
/// fn get_webhook_source_verification_algorithm
fn get_webhook_source_verification_algorithm(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::NoAlgorithm))
}
/// fn get_webhook_source_verification_merchant_secret
async fn get_webhook_source_verification_merchant_secret(
&self,
merchant_id: &common_utils::id_type::MerchantId,
connector_name: &str,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<api_models::webhooks::ConnectorWebhookSecrets, errors::ConnectorError> {
let debug_suffix = format!(
"For merchant_id: {:?}, and connector_name: {}",
merchant_id, connector_name
);
let default_secret = "default_secret".to_string();
let merchant_secret = match connector_webhook_details {
Some(merchant_connector_webhook_details) => {
let connector_webhook_details = merchant_connector_webhook_details
.parse_value::<api_models::admin::MerchantConnectorWebhookDetails>(
"MerchantConnectorWebhookDetails",
)
.change_context_lazy(|| errors::ConnectorError::WebhookSourceVerificationFailed)
.attach_printable_lazy(|| {
format!(
"Deserializing MerchantConnectorWebhookDetails failed {}",
debug_suffix
)
})?;
api_models::webhooks::ConnectorWebhookSecrets {
secret: connector_webhook_details
.merchant_secret
.expose()
.into_bytes(),
additional_secret: connector_webhook_details.additional_secret,
}
}
None => api_models::webhooks::ConnectorWebhookSecrets {
secret: default_secret.into_bytes(),
additional_secret: None,
},
};
//need to fetch merchant secret from config table with caching in future for enhanced performance
//If merchant has not set the secret for webhook source verification, "default_secret" is returned.
//So it will fail during verification step and goes to psync flow.
Ok(merchant_secret)
}
/// fn get_webhook_source_verification_signature
fn get_webhook_source_verification_signature(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
Ok(Vec::new())
}
/// fn get_webhook_source_verification_message
fn get_webhook_source_verification_message(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
Ok(Vec::new())
}
/// fn verify_webhook_source
async fn verify_webhook_source(
&self,
request: &IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>,
connector_name: &str,
) -> CustomResult<bool, errors::ConnectorError> {
let algorithm = self
.get_webhook_source_verification_algorithm(request)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let connector_webhook_secrets = self
.get_webhook_source_verification_merchant_secret(
merchant_id,
connector_name,
connector_webhook_details,
)
.await
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let signature = self
.get_webhook_source_verification_signature(request, &connector_webhook_secrets)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let message = self
.get_webhook_source_verification_message(
request,
merchant_id,
&connector_webhook_secrets,
)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
algorithm
.verify_signature(&connector_webhook_secrets.secret, &signature, &message)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
}
/// fn get_webhook_object_reference_id
fn get_webhook_object_reference_id(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError>;
/// fn get_webhook_event_type
fn get_webhook_event_type(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError>;
/// fn get_webhook_resource_object
fn get_webhook_resource_object(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError>;
/// fn get_webhook_api_response
fn get_webhook_api_response(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
_error_kind: Option<IncomingWebhookFlowError>,
) -> CustomResult<ApplicationResponse<serde_json::Value>, errors::ConnectorError> {
Ok(ApplicationResponse::StatusOk)
}
/// fn get_dispute_details
fn get_dispute_details(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<crate::disputes::DisputePayload, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_dispute_details method".to_string()).into())
}
/// fn get_external_authentication_details
fn get_external_authentication_details(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<crate::authentication::ExternalAuthenticationPayload, errors::ConnectorError>
{
Err(errors::ConnectorError::NotImplemented(
"get_external_authentication_details method".to_string(),
)
.into())
}
/// fn get_mandate_details
fn get_mandate_details(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<
Option<hyperswitch_domain_models::router_flow_types::ConnectorMandateDetails>,
errors::ConnectorError,
> {
Ok(None)
}
/// fn get_network_txn_id
fn get_network_txn_id(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<
Option<hyperswitch_domain_models::router_flow_types::ConnectorNetworkTxnId>,
errors::ConnectorError,
> {
Ok(None)
}
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
/// get revenue recovery invoice details
fn get_revenue_recovery_attempt_details(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<
hyperswitch_domain_models::revenue_recovery::RevenueRecoveryAttemptData,
errors::ConnectorError,
> {
Err(errors::ConnectorError::NotImplemented(
"get_revenue_recovery_attempt_details method".to_string(),
)
.into())
}
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
/// get revenue recovery transaction details
fn get_revenue_recovery_invoice_details(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<
hyperswitch_domain_models::revenue_recovery::RevenueRecoveryInvoiceData,
errors::ConnectorError,
> {
Err(errors::ConnectorError::NotImplemented(
"get_revenue_recovery_invoice_details method".to_string(),
)
.into())
}
}
| 2,432 | 991 |
hyperswitch | crates/hyperswitch_interfaces/src/consts.rs | .rs | //! connector integration related const declarations
/// No error message string const
pub const NO_ERROR_MESSAGE: &str = "No error message";
/// No error code string const
pub const NO_ERROR_CODE: &str = "No error code";
/// Accepted format for request
pub const ACCEPT_HEADER: &str = "text/html,application/json";
/// User agent for request send from backend server
pub const USER_AGENT: &str = "Hyperswitch-Backend-Server";
| 97 | 992 |
hyperswitch | crates/hyperswitch_interfaces/src/integrity.rs | .rs | use common_utils::errors::IntegrityCheckError;
use hyperswitch_domain_models::router_request_types::{
AuthoriseIntegrityObject, CaptureIntegrityObject, PaymentsAuthorizeData, PaymentsCaptureData,
PaymentsSyncData, RefundIntegrityObject, RefundsData, SyncIntegrityObject,
};
/// Connector Integrity trait to check connector data integrity
pub trait FlowIntegrity {
/// Output type for the connector
type IntegrityObject;
/// helps in connector integrity check
fn compare(
req_integrity_object: Self::IntegrityObject,
res_integrity_object: Self::IntegrityObject,
connector_transaction_id: Option<String>,
) -> Result<(), IntegrityCheckError>;
}
/// Trait to get connector integrity object based on request and response
pub trait GetIntegrityObject<T: FlowIntegrity> {
/// function to get response integrity object
fn get_response_integrity_object(&self) -> Option<T::IntegrityObject>;
/// function to get request integrity object
fn get_request_integrity_object(&self) -> T::IntegrityObject;
}
/// Trait to check flow type, based on which various integrity checks will be performed
pub trait CheckIntegrity<Request, T> {
/// Function to check to initiate integrity check
fn check_integrity(
&self,
request: &Request,
connector_transaction_id: Option<String>,
) -> Result<(), IntegrityCheckError>;
}
impl<T, Request> CheckIntegrity<Request, T> for RefundsData
where
T: FlowIntegrity,
Request: GetIntegrityObject<T>,
{
fn check_integrity(
&self,
request: &Request,
connector_refund_id: Option<String>,
) -> Result<(), IntegrityCheckError> {
match request.get_response_integrity_object() {
Some(res_integrity_object) => {
let req_integrity_object = request.get_request_integrity_object();
T::compare(
req_integrity_object,
res_integrity_object,
connector_refund_id,
)
}
None => Ok(()),
}
}
}
impl<T, Request> CheckIntegrity<Request, T> for PaymentsAuthorizeData
where
T: FlowIntegrity,
Request: GetIntegrityObject<T>,
{
fn check_integrity(
&self,
request: &Request,
connector_transaction_id: Option<String>,
) -> Result<(), IntegrityCheckError> {
match request.get_response_integrity_object() {
Some(res_integrity_object) => {
let req_integrity_object = request.get_request_integrity_object();
T::compare(
req_integrity_object,
res_integrity_object,
connector_transaction_id,
)
}
None => Ok(()),
}
}
}
impl<T, Request> CheckIntegrity<Request, T> for PaymentsCaptureData
where
T: FlowIntegrity,
Request: GetIntegrityObject<T>,
{
fn check_integrity(
&self,
request: &Request,
connector_transaction_id: Option<String>,
) -> Result<(), IntegrityCheckError> {
match request.get_response_integrity_object() {
Some(res_integrity_object) => {
let req_integrity_object = request.get_request_integrity_object();
T::compare(
req_integrity_object,
res_integrity_object,
connector_transaction_id,
)
}
None => Ok(()),
}
}
}
impl<T, Request> CheckIntegrity<Request, T> for PaymentsSyncData
where
T: FlowIntegrity,
Request: GetIntegrityObject<T>,
{
fn check_integrity(
&self,
request: &Request,
connector_transaction_id: Option<String>,
) -> Result<(), IntegrityCheckError> {
match request.get_response_integrity_object() {
Some(res_integrity_object) => {
let req_integrity_object = request.get_request_integrity_object();
T::compare(
req_integrity_object,
res_integrity_object,
connector_transaction_id,
)
}
None => Ok(()),
}
}
}
impl FlowIntegrity for RefundIntegrityObject {
type IntegrityObject = Self;
fn compare(
req_integrity_object: Self,
res_integrity_object: Self,
connector_transaction_id: Option<String>,
) -> Result<(), IntegrityCheckError> {
let mut mismatched_fields = Vec::new();
if req_integrity_object.currency != res_integrity_object.currency {
mismatched_fields.push(format_mismatch(
"currency",
&req_integrity_object.currency.to_string(),
&res_integrity_object.currency.to_string(),
));
}
if req_integrity_object.refund_amount != res_integrity_object.refund_amount {
mismatched_fields.push(format_mismatch(
"refund_amount",
&req_integrity_object.refund_amount.to_string(),
&res_integrity_object.refund_amount.to_string(),
));
}
if mismatched_fields.is_empty() {
Ok(())
} else {
let field_names = mismatched_fields.join(", ");
Err(IntegrityCheckError {
field_names,
connector_transaction_id,
})
}
}
}
impl FlowIntegrity for AuthoriseIntegrityObject {
type IntegrityObject = Self;
fn compare(
req_integrity_object: Self,
res_integrity_object: Self,
connector_transaction_id: Option<String>,
) -> Result<(), IntegrityCheckError> {
let mut mismatched_fields = Vec::new();
if req_integrity_object.amount != res_integrity_object.amount {
mismatched_fields.push(format_mismatch(
"amount",
&req_integrity_object.amount.to_string(),
&res_integrity_object.amount.to_string(),
));
}
if req_integrity_object.currency != res_integrity_object.currency {
mismatched_fields.push(format_mismatch(
"currency",
&req_integrity_object.currency.to_string(),
&res_integrity_object.currency.to_string(),
));
}
if mismatched_fields.is_empty() {
Ok(())
} else {
let field_names = mismatched_fields.join(", ");
Err(IntegrityCheckError {
field_names,
connector_transaction_id,
})
}
}
}
impl FlowIntegrity for SyncIntegrityObject {
type IntegrityObject = Self;
fn compare(
req_integrity_object: Self,
res_integrity_object: Self,
connector_transaction_id: Option<String>,
) -> Result<(), IntegrityCheckError> {
let mut mismatched_fields = Vec::new();
res_integrity_object
.amount
.zip(req_integrity_object.amount)
.map(|(res_amount, req_amount)| {
if res_amount != req_amount {
mismatched_fields.push(format_mismatch(
"amount",
&req_amount.to_string(),
&res_amount.to_string(),
));
}
});
res_integrity_object
.currency
.zip(req_integrity_object.currency)
.map(|(res_currency, req_currency)| {
if res_currency != req_currency {
mismatched_fields.push(format_mismatch(
"currency",
&req_currency.to_string(),
&res_currency.to_string(),
));
}
});
if mismatched_fields.is_empty() {
Ok(())
} else {
let field_names = mismatched_fields.join(", ");
Err(IntegrityCheckError {
field_names,
connector_transaction_id,
})
}
}
}
impl FlowIntegrity for CaptureIntegrityObject {
type IntegrityObject = Self;
fn compare(
req_integrity_object: Self,
res_integrity_object: Self,
connector_transaction_id: Option<String>,
) -> Result<(), IntegrityCheckError> {
let mut mismatched_fields = Vec::new();
res_integrity_object
.capture_amount
.zip(req_integrity_object.capture_amount)
.map(|(res_amount, req_amount)| {
if res_amount != req_amount {
mismatched_fields.push(format_mismatch(
"capture_amount",
&req_amount.to_string(),
&res_amount.to_string(),
));
}
});
if req_integrity_object.currency != res_integrity_object.currency {
mismatched_fields.push(format_mismatch(
"currency",
&req_integrity_object.currency.to_string(),
&res_integrity_object.currency.to_string(),
));
}
if mismatched_fields.is_empty() {
Ok(())
} else {
let field_names = mismatched_fields.join(", ");
Err(IntegrityCheckError {
field_names,
connector_transaction_id,
})
}
}
}
impl GetIntegrityObject<CaptureIntegrityObject> for PaymentsCaptureData {
fn get_response_integrity_object(&self) -> Option<CaptureIntegrityObject> {
self.integrity_object.clone()
}
fn get_request_integrity_object(&self) -> CaptureIntegrityObject {
CaptureIntegrityObject {
capture_amount: Some(self.minor_amount_to_capture),
currency: self.currency,
}
}
}
impl GetIntegrityObject<RefundIntegrityObject> for RefundsData {
fn get_response_integrity_object(&self) -> Option<RefundIntegrityObject> {
self.integrity_object.clone()
}
fn get_request_integrity_object(&self) -> RefundIntegrityObject {
RefundIntegrityObject {
currency: self.currency,
refund_amount: self.minor_refund_amount,
}
}
}
impl GetIntegrityObject<AuthoriseIntegrityObject> for PaymentsAuthorizeData {
fn get_response_integrity_object(&self) -> Option<AuthoriseIntegrityObject> {
self.integrity_object.clone()
}
fn get_request_integrity_object(&self) -> AuthoriseIntegrityObject {
AuthoriseIntegrityObject {
amount: self.minor_amount,
currency: self.currency,
}
}
}
impl GetIntegrityObject<SyncIntegrityObject> for PaymentsSyncData {
fn get_response_integrity_object(&self) -> Option<SyncIntegrityObject> {
self.integrity_object.clone()
}
fn get_request_integrity_object(&self) -> SyncIntegrityObject {
SyncIntegrityObject {
amount: Some(self.amount),
currency: Some(self.currency),
}
}
}
#[inline]
fn format_mismatch(field: &str, expected: &str, found: &str) -> String {
format!("{} expected {} but found {}", field, expected, found)
}
| 2,208 | 993 |
hyperswitch | crates/hyperswitch_interfaces/src/conversion_impls.rs | .rs | use common_utils::{errors::CustomResult, id_type};
use error_stack::ResultExt;
#[cfg(feature = "frm")]
use hyperswitch_domain_models::router_data_v2::flow_common_types::FrmFlowData;
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::router_data_v2::flow_common_types::PayoutFlowData;
use hyperswitch_domain_models::{
payment_address::PaymentAddress,
router_data::{self, RouterData},
router_data_v2::{
flow_common_types::{
AccessTokenFlowData, BillingConnectorPaymentsSyncFlowData, DisputesFlowData,
ExternalAuthenticationFlowData, FilesFlowData, MandateRevokeFlowData, PaymentFlowData,
RefundFlowData, RevenueRecoveryRecordBackData, UasFlowData, WebhookSourceVerifyData,
},
RouterDataV2,
},
};
use crate::{connector_integration_interface::RouterDataConversion, errors::ConnectorError};
fn get_irrelevant_id_string(id_name: &str, flow_name: &str) -> String {
format!("irrelevant {id_name} in {flow_name} flow")
}
fn get_default_router_data<F, Req, Resp>(
tenant_id: id_type::TenantId,
flow_name: &str,
request: Req,
response: Result<Resp, router_data::ErrorResponse>,
) -> RouterData<F, Req, Resp> {
RouterData {
tenant_id,
flow: std::marker::PhantomData,
merchant_id: id_type::MerchantId::get_irrelevant_merchant_id(),
customer_id: None,
connector_customer: None,
connector: get_irrelevant_id_string("connector", flow_name),
payment_id: id_type::PaymentId::get_irrelevant_id(flow_name)
.get_string_repr()
.to_owned(),
attempt_id: get_irrelevant_id_string("attempt_id", flow_name),
status: common_enums::AttemptStatus::default(),
payment_method: common_enums::PaymentMethod::default(),
connector_auth_type: router_data::ConnectorAuthType::default(),
description: None,
address: PaymentAddress::default(),
auth_type: common_enums::AuthenticationType::default(),
connector_meta_data: None,
connector_wallets_details: None,
amount_captured: None,
access_token: None,
session_token: None,
reference_id: None,
payment_method_token: None,
recurring_mandate_payment_data: None,
preprocessing_id: None,
payment_method_balance: None,
connector_api_version: None,
request,
response,
connector_request_reference_id: get_irrelevant_id_string(
"connector_request_reference_id",
flow_name,
),
#[cfg(feature = "payouts")]
payout_method_data: None,
#[cfg(feature = "payouts")]
quote_id: None,
test_mode: None,
connector_http_status_code: None,
external_latency: None,
apple_pay_flow: None,
frm_metadata: None,
dispute_id: None,
refund_id: None,
connector_response: None,
payment_method_status: None,
minor_amount_captured: None,
integrity_check: Ok(()),
additional_merchant_data: None,
header_payload: None,
connector_mandate_request_reference_id: None,
authentication_id: None,
psd2_sca_exemption_type: None,
}
}
impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for AccessTokenFlowData {
fn from_old_router_data(
old_router_data: &RouterData<T, Req, Resp>,
) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError>
where
Self: Sized,
{
let resource_common_data = Self {};
Ok(RouterDataV2 {
flow: std::marker::PhantomData,
tenant_id: old_router_data.tenant_id.clone(),
resource_common_data,
connector_auth_type: old_router_data.connector_auth_type.clone(),
request: old_router_data.request.clone(),
response: old_router_data.response.clone(),
})
}
fn to_old_router_data(
new_router_data: RouterDataV2<T, Self, Req, Resp>,
) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError>
where
Self: Sized,
{
let Self {} = new_router_data.resource_common_data;
let request = new_router_data.request.clone();
let response = new_router_data.response.clone();
let router_data = get_default_router_data(
new_router_data.tenant_id.clone(),
"access token",
request,
response,
);
Ok(router_data)
}
}
impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for PaymentFlowData {
fn from_old_router_data(
old_router_data: &RouterData<T, Req, Resp>,
) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError>
where
Self: Sized,
{
let resource_common_data = Self {
merchant_id: old_router_data.merchant_id.clone(),
customer_id: old_router_data.customer_id.clone(),
connector_customer: old_router_data.connector_customer.clone(),
payment_id: old_router_data.payment_id.clone(),
attempt_id: old_router_data.attempt_id.clone(),
status: old_router_data.status,
payment_method: old_router_data.payment_method,
description: old_router_data.description.clone(),
address: old_router_data.address.clone(),
auth_type: old_router_data.auth_type,
connector_meta_data: old_router_data.connector_meta_data.clone(),
amount_captured: old_router_data.amount_captured,
minor_amount_captured: old_router_data.minor_amount_captured,
access_token: old_router_data.access_token.clone(),
session_token: old_router_data.session_token.clone(),
reference_id: old_router_data.reference_id.clone(),
payment_method_token: old_router_data.payment_method_token.clone(),
recurring_mandate_payment_data: old_router_data.recurring_mandate_payment_data.clone(),
preprocessing_id: old_router_data.preprocessing_id.clone(),
payment_method_balance: old_router_data.payment_method_balance.clone(),
connector_api_version: old_router_data.connector_api_version.clone(),
connector_request_reference_id: old_router_data.connector_request_reference_id.clone(),
test_mode: old_router_data.test_mode,
connector_http_status_code: old_router_data.connector_http_status_code,
external_latency: old_router_data.external_latency,
apple_pay_flow: old_router_data.apple_pay_flow.clone(),
connector_response: old_router_data.connector_response.clone(),
payment_method_status: old_router_data.payment_method_status,
};
Ok(RouterDataV2 {
flow: std::marker::PhantomData,
tenant_id: old_router_data.tenant_id.clone(),
resource_common_data,
connector_auth_type: old_router_data.connector_auth_type.clone(),
request: old_router_data.request.clone(),
response: old_router_data.response.clone(),
})
}
fn to_old_router_data(
new_router_data: RouterDataV2<T, Self, Req, Resp>,
) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError>
where
Self: Sized,
{
let Self {
merchant_id,
customer_id,
connector_customer,
payment_id,
attempt_id,
status,
payment_method,
description,
address,
auth_type,
connector_meta_data,
amount_captured,
minor_amount_captured,
access_token,
session_token,
reference_id,
payment_method_token,
recurring_mandate_payment_data,
preprocessing_id,
payment_method_balance,
connector_api_version,
connector_request_reference_id,
test_mode,
connector_http_status_code,
external_latency,
apple_pay_flow,
connector_response,
payment_method_status,
} = new_router_data.resource_common_data;
let mut router_data = get_default_router_data(
new_router_data.tenant_id.clone(),
"payment",
new_router_data.request,
new_router_data.response,
);
router_data.merchant_id = merchant_id;
router_data.customer_id = customer_id;
router_data.connector_customer = connector_customer;
router_data.payment_id = payment_id;
router_data.attempt_id = attempt_id;
router_data.status = status;
router_data.payment_method = payment_method;
router_data.description = description;
router_data.address = address;
router_data.auth_type = auth_type;
router_data.connector_meta_data = connector_meta_data;
router_data.amount_captured = amount_captured;
router_data.minor_amount_captured = minor_amount_captured;
router_data.access_token = access_token;
router_data.session_token = session_token;
router_data.reference_id = reference_id;
router_data.payment_method_token = payment_method_token;
router_data.recurring_mandate_payment_data = recurring_mandate_payment_data;
router_data.preprocessing_id = preprocessing_id;
router_data.payment_method_balance = payment_method_balance;
router_data.connector_api_version = connector_api_version;
router_data.connector_request_reference_id = connector_request_reference_id;
router_data.test_mode = test_mode;
router_data.connector_http_status_code = connector_http_status_code;
router_data.external_latency = external_latency;
router_data.apple_pay_flow = apple_pay_flow;
router_data.connector_response = connector_response;
router_data.payment_method_status = payment_method_status;
Ok(router_data)
}
}
impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for RefundFlowData {
fn from_old_router_data(
old_router_data: &RouterData<T, Req, Resp>,
) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError>
where
Self: Sized,
{
let resource_common_data = Self {
merchant_id: old_router_data.merchant_id.clone(),
customer_id: old_router_data.customer_id.clone(),
payment_id: old_router_data.payment_id.clone(),
attempt_id: old_router_data.attempt_id.clone(),
status: old_router_data.status,
payment_method: old_router_data.payment_method,
connector_meta_data: old_router_data.connector_meta_data.clone(),
amount_captured: old_router_data.amount_captured,
minor_amount_captured: old_router_data.minor_amount_captured,
connector_request_reference_id: old_router_data.connector_request_reference_id.clone(),
refund_id: old_router_data.refund_id.clone().ok_or(
ConnectorError::MissingRequiredField {
field_name: "refund_id",
},
)?,
};
Ok(RouterDataV2 {
flow: std::marker::PhantomData,
tenant_id: old_router_data.tenant_id.clone(),
resource_common_data,
connector_auth_type: old_router_data.connector_auth_type.clone(),
request: old_router_data.request.clone(),
response: old_router_data.response.clone(),
})
}
fn to_old_router_data(
new_router_data: RouterDataV2<T, Self, Req, Resp>,
) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError>
where
Self: Sized,
{
let Self {
merchant_id,
customer_id,
payment_id,
attempt_id,
status,
payment_method,
connector_meta_data,
amount_captured,
minor_amount_captured,
connector_request_reference_id,
refund_id,
} = new_router_data.resource_common_data;
let mut router_data = get_default_router_data(
new_router_data.tenant_id.clone(),
"refund",
new_router_data.request,
new_router_data.response,
);
router_data.merchant_id = merchant_id;
router_data.customer_id = customer_id;
router_data.payment_id = payment_id;
router_data.attempt_id = attempt_id;
router_data.status = status;
router_data.payment_method = payment_method;
router_data.connector_meta_data = connector_meta_data;
router_data.amount_captured = amount_captured;
router_data.minor_amount_captured = minor_amount_captured;
router_data.connector_request_reference_id = connector_request_reference_id;
router_data.refund_id = Some(refund_id);
Ok(router_data)
}
}
impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for DisputesFlowData {
fn from_old_router_data(
old_router_data: &RouterData<T, Req, Resp>,
) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError>
where
Self: Sized,
{
let resource_common_data = Self {
merchant_id: old_router_data.merchant_id.clone(),
payment_id: old_router_data.payment_id.clone(),
attempt_id: old_router_data.attempt_id.clone(),
payment_method: old_router_data.payment_method,
connector_meta_data: old_router_data.connector_meta_data.clone(),
amount_captured: old_router_data.amount_captured,
minor_amount_captured: old_router_data.minor_amount_captured,
connector_request_reference_id: old_router_data.connector_request_reference_id.clone(),
dispute_id: old_router_data.dispute_id.clone().ok_or(
ConnectorError::MissingRequiredField {
field_name: "dispute_id",
},
)?,
};
Ok(RouterDataV2 {
flow: std::marker::PhantomData,
tenant_id: old_router_data.tenant_id.clone(),
resource_common_data,
connector_auth_type: old_router_data.connector_auth_type.clone(),
request: old_router_data.request.clone(),
response: old_router_data.response.clone(),
})
}
fn to_old_router_data(
new_router_data: RouterDataV2<T, Self, Req, Resp>,
) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError>
where
Self: Sized,
{
let Self {
merchant_id,
payment_id,
attempt_id,
payment_method,
connector_meta_data,
amount_captured,
minor_amount_captured,
connector_request_reference_id,
dispute_id,
} = new_router_data.resource_common_data;
let mut router_data = get_default_router_data(
new_router_data.tenant_id.clone(),
"Disputes",
new_router_data.request,
new_router_data.response,
);
router_data.merchant_id = merchant_id;
router_data.payment_id = payment_id;
router_data.attempt_id = attempt_id;
router_data.payment_method = payment_method;
router_data.connector_meta_data = connector_meta_data;
router_data.amount_captured = amount_captured;
router_data.minor_amount_captured = minor_amount_captured;
router_data.connector_request_reference_id = connector_request_reference_id;
router_data.dispute_id = Some(dispute_id);
Ok(router_data)
}
}
#[cfg(feature = "frm")]
impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for FrmFlowData {
fn from_old_router_data(
old_router_data: &RouterData<T, Req, Resp>,
) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError>
where
Self: Sized,
{
let resource_common_data = Self {
merchant_id: old_router_data.merchant_id.clone(),
payment_id: old_router_data.payment_id.clone(),
attempt_id: old_router_data.attempt_id.clone(),
payment_method: old_router_data.payment_method,
connector_request_reference_id: old_router_data.connector_request_reference_id.clone(),
auth_type: old_router_data.auth_type,
connector_wallets_details: old_router_data.connector_wallets_details.clone(),
connector_meta_data: old_router_data.connector_meta_data.clone(),
amount_captured: old_router_data.amount_captured,
minor_amount_captured: old_router_data.minor_amount_captured,
};
Ok(RouterDataV2 {
tenant_id: old_router_data.tenant_id.clone(),
flow: std::marker::PhantomData,
resource_common_data,
connector_auth_type: old_router_data.connector_auth_type.clone(),
request: old_router_data.request.clone(),
response: old_router_data.response.clone(),
})
}
fn to_old_router_data(
new_router_data: RouterDataV2<T, Self, Req, Resp>,
) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError>
where
Self: Sized,
{
let Self {
merchant_id,
payment_id,
attempt_id,
payment_method,
connector_request_reference_id,
auth_type,
connector_wallets_details,
connector_meta_data,
amount_captured,
minor_amount_captured,
} = new_router_data.resource_common_data;
let mut router_data = get_default_router_data(
new_router_data.tenant_id.clone(),
"frm",
new_router_data.request,
new_router_data.response,
);
router_data.merchant_id = merchant_id;
router_data.payment_id = payment_id;
router_data.attempt_id = attempt_id;
router_data.payment_method = payment_method;
router_data.connector_request_reference_id = connector_request_reference_id;
router_data.auth_type = auth_type;
router_data.connector_wallets_details = connector_wallets_details;
router_data.connector_meta_data = connector_meta_data;
router_data.amount_captured = amount_captured;
router_data.minor_amount_captured = minor_amount_captured;
Ok(router_data)
}
}
impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for FilesFlowData {
fn from_old_router_data(
old_router_data: &RouterData<T, Req, Resp>,
) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError>
where
Self: Sized,
{
let resource_common_data = Self {
merchant_id: old_router_data.merchant_id.clone(),
payment_id: old_router_data.payment_id.clone(),
attempt_id: old_router_data.attempt_id.clone(),
connector_meta_data: old_router_data.connector_meta_data.clone(),
connector_request_reference_id: old_router_data.connector_request_reference_id.clone(),
};
Ok(RouterDataV2 {
flow: std::marker::PhantomData,
tenant_id: old_router_data.tenant_id.clone(),
resource_common_data,
connector_auth_type: old_router_data.connector_auth_type.clone(),
request: old_router_data.request.clone(),
response: old_router_data.response.clone(),
})
}
fn to_old_router_data(
new_router_data: RouterDataV2<T, Self, Req, Resp>,
) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError>
where
Self: Sized,
{
let Self {
merchant_id,
payment_id,
attempt_id,
connector_meta_data,
connector_request_reference_id,
} = new_router_data.resource_common_data;
let mut router_data = get_default_router_data(
new_router_data.tenant_id.clone(),
"files",
new_router_data.request,
new_router_data.response,
);
router_data.merchant_id = merchant_id;
router_data.payment_id = payment_id;
router_data.attempt_id = attempt_id;
router_data.connector_meta_data = connector_meta_data;
router_data.connector_request_reference_id = connector_request_reference_id;
Ok(router_data)
}
}
impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for WebhookSourceVerifyData {
fn from_old_router_data(
old_router_data: &RouterData<T, Req, Resp>,
) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError>
where
Self: Sized,
{
let resource_common_data = Self {
merchant_id: old_router_data.merchant_id.clone(),
};
Ok(RouterDataV2 {
tenant_id: old_router_data.tenant_id.clone(),
flow: std::marker::PhantomData,
resource_common_data,
connector_auth_type: old_router_data.connector_auth_type.clone(),
request: old_router_data.request.clone(),
response: old_router_data.response.clone(),
})
}
fn to_old_router_data(
new_router_data: RouterDataV2<T, Self, Req, Resp>,
) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError>
where
Self: Sized,
{
let Self { merchant_id } = new_router_data.resource_common_data;
let mut router_data = get_default_router_data(
new_router_data.tenant_id.clone(),
"webhook source verify",
new_router_data.request,
new_router_data.response,
);
router_data.merchant_id = merchant_id;
Ok(router_data)
}
}
impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for MandateRevokeFlowData {
fn from_old_router_data(
old_router_data: &RouterData<T, Req, Resp>,
) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError>
where
Self: Sized,
{
let resource_common_data = Self {
merchant_id: old_router_data.merchant_id.clone(),
customer_id: old_router_data.customer_id.clone().ok_or(
ConnectorError::MissingRequiredField {
field_name: "customer_id",
},
)?,
payment_id: Some(old_router_data.payment_id.clone()),
};
Ok(RouterDataV2 {
flow: std::marker::PhantomData,
tenant_id: old_router_data.tenant_id.clone(),
resource_common_data,
connector_auth_type: old_router_data.connector_auth_type.clone(),
request: old_router_data.request.clone(),
response: old_router_data.response.clone(),
})
}
fn to_old_router_data(
new_router_data: RouterDataV2<T, Self, Req, Resp>,
) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError>
where
Self: Sized,
{
let Self {
merchant_id,
customer_id,
payment_id,
} = new_router_data.resource_common_data;
let mut router_data = get_default_router_data(
new_router_data.tenant_id.clone(),
"mandate revoke",
new_router_data.request,
new_router_data.response,
);
router_data.merchant_id = merchant_id;
router_data.customer_id = Some(customer_id);
router_data.payment_id = payment_id
.unwrap_or_else(|| {
id_type::PaymentId::get_irrelevant_id("mandate revoke")
.get_string_repr()
.to_owned()
})
.to_owned();
Ok(router_data)
}
}
#[cfg(feature = "payouts")]
impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for PayoutFlowData {
fn from_old_router_data(
old_router_data: &RouterData<T, Req, Resp>,
) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError>
where
Self: Sized,
{
let resource_common_data = Self {
merchant_id: old_router_data.merchant_id.clone(),
customer_id: old_router_data.customer_id.clone(),
connector_customer: old_router_data.connector_customer.clone(),
address: old_router_data.address.clone(),
connector_meta_data: old_router_data.connector_meta_data.clone(),
connector_wallets_details: old_router_data.connector_wallets_details.clone(),
connector_request_reference_id: old_router_data.connector_request_reference_id.clone(),
payout_method_data: old_router_data.payout_method_data.clone(),
quote_id: old_router_data.quote_id.clone(),
};
Ok(RouterDataV2 {
tenant_id: old_router_data.tenant_id.clone(),
flow: std::marker::PhantomData,
resource_common_data,
connector_auth_type: old_router_data.connector_auth_type.clone(),
request: old_router_data.request.clone(),
response: old_router_data.response.clone(),
})
}
fn to_old_router_data(
new_router_data: RouterDataV2<T, Self, Req, Resp>,
) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError>
where
Self: Sized,
{
let Self {
merchant_id,
customer_id,
connector_customer,
address,
connector_meta_data,
connector_wallets_details,
connector_request_reference_id,
payout_method_data,
quote_id,
} = new_router_data.resource_common_data;
let mut router_data = get_default_router_data(
new_router_data.tenant_id.clone(),
"payout",
new_router_data.request,
new_router_data.response,
);
router_data.merchant_id = merchant_id;
router_data.customer_id = customer_id;
router_data.connector_customer = connector_customer;
router_data.address = address;
router_data.connector_meta_data = connector_meta_data;
router_data.connector_wallets_details = connector_wallets_details;
router_data.connector_request_reference_id = connector_request_reference_id;
router_data.payout_method_data = payout_method_data;
router_data.quote_id = quote_id;
Ok(router_data)
}
}
impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp>
for ExternalAuthenticationFlowData
{
fn from_old_router_data(
old_router_data: &RouterData<T, Req, Resp>,
) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError>
where
Self: Sized,
{
let resource_common_data = Self {
merchant_id: old_router_data.merchant_id.clone(),
connector_meta_data: old_router_data.connector_meta_data.clone(),
address: old_router_data.address.clone(),
};
Ok(RouterDataV2 {
tenant_id: old_router_data.tenant_id.clone(),
flow: std::marker::PhantomData,
resource_common_data,
connector_auth_type: old_router_data.connector_auth_type.clone(),
request: old_router_data.request.clone(),
response: old_router_data.response.clone(),
})
}
fn to_old_router_data(
new_router_data: RouterDataV2<T, Self, Req, Resp>,
) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError>
where
Self: Sized,
{
let Self {
merchant_id,
connector_meta_data,
address,
} = new_router_data.resource_common_data;
let mut router_data = get_default_router_data(
new_router_data.tenant_id.clone(),
"external authentication",
new_router_data.request,
new_router_data.response,
);
router_data.merchant_id = merchant_id;
router_data.connector_meta_data = connector_meta_data;
router_data.address = address;
Ok(router_data)
}
}
impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp>
for RevenueRecoveryRecordBackData
{
fn from_old_router_data(
old_router_data: &RouterData<T, Req, Resp>,
) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError>
where
Self: Sized,
{
let resource_common_data = Self {};
Ok(RouterDataV2 {
flow: std::marker::PhantomData,
tenant_id: old_router_data.tenant_id.clone(),
resource_common_data,
connector_auth_type: old_router_data.connector_auth_type.clone(),
request: old_router_data.request.clone(),
response: old_router_data.response.clone(),
})
}
fn to_old_router_data(
new_router_data: RouterDataV2<T, Self, Req, Resp>,
) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError>
where
Self: Sized,
{
let router_data = get_default_router_data(
new_router_data.tenant_id.clone(),
"recovery_record_back",
new_router_data.request,
new_router_data.response,
);
Ok(router_data)
}
}
impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp> for UasFlowData {
fn from_old_router_data(
old_router_data: &RouterData<T, Req, Resp>,
) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError>
where
Self: Sized,
{
let resource_common_data = Self {
authenticate_by: old_router_data.connector.clone(),
source_authentication_id: old_router_data
.authentication_id
.clone()
.ok_or(ConnectorError::MissingRequiredField {
field_name: "source_authentication_id",
})
.attach_printable("missing authentication id for uas")?,
};
Ok(RouterDataV2 {
flow: std::marker::PhantomData,
tenant_id: old_router_data.tenant_id.clone(),
resource_common_data,
connector_auth_type: old_router_data.connector_auth_type.clone(),
request: old_router_data.request.clone(),
response: old_router_data.response.clone(),
})
}
fn to_old_router_data(
new_router_data: RouterDataV2<T, Self, Req, Resp>,
) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError>
where
Self: Sized,
{
let Self {
authenticate_by,
source_authentication_id,
} = new_router_data.resource_common_data;
let mut router_data = get_default_router_data(
new_router_data.tenant_id.clone(),
"uas",
new_router_data.request,
new_router_data.response,
);
router_data.connector = authenticate_by;
router_data.authentication_id = Some(source_authentication_id);
Ok(router_data)
}
}
impl<T, Req: Clone, Resp: Clone> RouterDataConversion<T, Req, Resp>
for BillingConnectorPaymentsSyncFlowData
{
fn from_old_router_data(
old_router_data: &RouterData<T, Req, Resp>,
) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, ConnectorError>
where
Self: Sized,
{
let resource_common_data = Self {};
Ok(RouterDataV2 {
flow: std::marker::PhantomData,
tenant_id: old_router_data.tenant_id.clone(),
resource_common_data,
connector_auth_type: old_router_data.connector_auth_type.clone(),
request: old_router_data.request.clone(),
response: old_router_data.response.clone(),
})
}
fn to_old_router_data(
new_router_data: RouterDataV2<T, Self, Req, Resp>,
) -> CustomResult<RouterData<T, Req, Resp>, ConnectorError>
where
Self: Sized,
{
let router_data = get_default_router_data(
new_router_data.tenant_id.clone(),
"BillingConnectorPaymentsSync",
new_router_data.request,
new_router_data.response,
);
Ok(RouterData {
connector_auth_type: new_router_data.connector_auth_type.clone(),
..router_data
})
}
}
| 6,607 | 994 |
hyperswitch | crates/hyperswitch_interfaces/src/types.rs | .rs | //! Types interface
use hyperswitch_domain_models::{
router_data::AccessToken,
router_flow_types::{
access_token_auth::AccessTokenAuth,
dispute::{Accept, Defend, Evidence},
files::{Retrieve, Upload},
mandate_revoke::MandateRevoke,
payments::{
Authorize, AuthorizeSessionToken, Balance, CalculateTax, Capture, CompleteAuthorize,
CreateConnectorCustomer, IncrementalAuthorization, InitPayment, PSync,
PaymentMethodToken, PostProcessing, PostSessionTokens, PreProcessing, SdkSessionUpdate,
Session, SetupMandate, Void,
},
refunds::{Execute, RSync},
revenue_recovery::{BillingConnectorPaymentsSync, RecoveryRecordBack},
unified_authentication_service::{
Authenticate, AuthenticationConfirmation, PostAuthenticate, PreAuthenticate,
},
webhooks::VerifyWebhookSource,
},
router_request_types::{
revenue_recovery::{BillingConnectorPaymentsSyncRequest, RevenueRecoveryRecordBackRequest},
unified_authentication_service::{
UasAuthenticationRequestData, UasAuthenticationResponseData,
UasConfirmationRequestData, UasPostAuthenticationRequestData,
UasPreAuthenticationRequestData,
},
AcceptDisputeRequestData, AccessTokenRequestData, AuthorizeSessionTokenData,
CompleteAuthorizeData, ConnectorCustomerData, DefendDisputeRequestData,
MandateRevokeRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData,
PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreProcessingData,
PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, RefundsData,
RetrieveFileRequestData, SdkPaymentsSessionUpdateData, SetupMandateRequestData,
SubmitEvidenceRequestData, UploadFileRequestData, VerifyWebhookSourceRequestData,
},
router_response_types::{
revenue_recovery::{
BillingConnectorPaymentsSyncResponse, RevenueRecoveryRecordBackResponse,
},
AcceptDisputeResponse, DefendDisputeResponse, MandateRevokeResponseData,
PaymentsResponseData, RefundsResponseData, RetrieveFileResponse, SubmitEvidenceResponse,
TaxCalculationResponseData, UploadFileResponse, VerifyWebhookSourceResponseData,
},
};
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::{
router_flow_types::payouts::{
PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount,
PoSync,
},
router_request_types::PayoutsData,
router_response_types::PayoutsResponseData,
};
use crate::api::ConnectorIntegration;
/// struct Response
#[derive(Clone, Debug)]
pub struct Response {
/// headers
pub headers: Option<http::HeaderMap>,
/// response
pub response: bytes::Bytes,
/// status code
pub status_code: u16,
}
/// Type alias for `ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData>`
pub type PaymentsAuthorizeType =
dyn ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData>;
/// Type alias for `ConnectorIntegration<CalculateTax, PaymentsTaxCalculationData, TaxCalculationResponseData>`
pub type PaymentsTaxCalculationType =
dyn ConnectorIntegration<CalculateTax, PaymentsTaxCalculationData, TaxCalculationResponseData>;
/// Type alias for `ConnectorIntegration<PostSessionTokens, PaymentsPostSessionTokensData, PaymentsResponseData>`
pub type PaymentsPostSessionTokensType = dyn ConnectorIntegration<
PostSessionTokens,
PaymentsPostSessionTokensData,
PaymentsResponseData,
>;
/// Type alias for `ConnectorIntegration<SdkSessionUpdate, SdkPaymentsSessionUpdateData, PaymentsResponseData>`
pub type SdkSessionUpdateType =
dyn ConnectorIntegration<SdkSessionUpdate, SdkPaymentsSessionUpdateData, PaymentsResponseData>;
/// Type alias for `ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>`
pub type SetupMandateType =
dyn ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>;
/// Type alias for `ConnectorIntegration<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>`
pub type MandateRevokeType =
dyn ConnectorIntegration<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>;
/// Type alias for `ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>`
pub type PaymentsPreProcessingType =
dyn ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>;
/// Type alias for `ConnectorIntegration<PostProcessing, PaymentsPostProcessingData, PaymentsResponseData>`
pub type PaymentsPostProcessingType =
dyn ConnectorIntegration<PostProcessing, PaymentsPostProcessingData, PaymentsResponseData>;
/// Type alias for `ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>`
pub type PaymentsCompleteAuthorizeType =
dyn ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>;
/// Type alias for `ConnectorIntegration<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData>`
pub type PaymentsPreAuthorizeType = dyn ConnectorIntegration<
AuthorizeSessionToken,
AuthorizeSessionTokenData,
PaymentsResponseData,
>;
/// Type alias for `ConnectorIntegration<InitPayment, PaymentsAuthorizeData, PaymentsResponseData>`
pub type PaymentsInitType =
dyn ConnectorIntegration<InitPayment, PaymentsAuthorizeData, PaymentsResponseData>;
/// Type alias for `ConnectorIntegration<Balance, PaymentsAuthorizeData, PaymentsResponseData`
pub type PaymentsBalanceType =
dyn ConnectorIntegration<Balance, PaymentsAuthorizeData, PaymentsResponseData>;
/// Type alias for `PaymentsSyncType = dyn ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData>`
pub type PaymentsSyncType = dyn ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData>;
/// Type alias for `ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData>`
pub type PaymentsCaptureType =
dyn ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData>;
/// Type alias for `ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData>`
pub type PaymentsSessionType =
dyn ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData>;
/// Type alias for `ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData>`
pub type PaymentsVoidType =
dyn ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData>;
/// Type alias for `ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>`
pub type TokenizationType = dyn ConnectorIntegration<
PaymentMethodToken,
PaymentMethodTokenizationData,
PaymentsResponseData,
>;
/// Type alias for `ConnectorIntegration<IncrementalAuthorization, PaymentsIncrementalAuthorizationData, PaymentsResponseData>`
pub type IncrementalAuthorizationType = dyn ConnectorIntegration<
IncrementalAuthorization,
PaymentsIncrementalAuthorizationData,
PaymentsResponseData,
>;
/// Type alias for `ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>`
pub type ConnectorCustomerType =
dyn ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>;
/// Type alias for `ConnectorIntegration<Execute, RefundsData, RefundsResponseData>`
pub type RefundExecuteType = dyn ConnectorIntegration<Execute, RefundsData, RefundsResponseData>;
/// Type alias for `ConnectorIntegration<RSync, RefundsData, RefundsResponseData>`
pub type RefundSyncType = dyn ConnectorIntegration<RSync, RefundsData, RefundsResponseData>;
/// Type alias for `ConnectorIntegration<PoCancel, PayoutsData, PayoutsResponseData>`
#[cfg(feature = "payouts")]
pub type PayoutCancelType = dyn ConnectorIntegration<PoCancel, PayoutsData, PayoutsResponseData>;
/// Type alias for `ConnectorIntegration<PoCreate, PayoutsData, PayoutsResponseData>`
#[cfg(feature = "payouts")]
pub type PayoutCreateType = dyn ConnectorIntegration<PoCreate, PayoutsData, PayoutsResponseData>;
/// Type alias for `ConnectorIntegration<PoEligibility, PayoutsData, PayoutsResponseData>`
#[cfg(feature = "payouts")]
pub type PayoutEligibilityType =
dyn ConnectorIntegration<PoEligibility, PayoutsData, PayoutsResponseData>;
/// Type alias for `ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData>`
#[cfg(feature = "payouts")]
pub type PayoutFulfillType = dyn ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData>;
/// Type alias for `ConnectorIntegration<PoRecipient, PayoutsData, PayoutsResponseData>`
#[cfg(feature = "payouts")]
pub type PayoutRecipientType =
dyn ConnectorIntegration<PoRecipient, PayoutsData, PayoutsResponseData>;
/// Type alias for `ConnectorIntegration<PoRecipientAccount, PayoutsData, PayoutsResponseData>`
#[cfg(feature = "payouts")]
pub type PayoutRecipientAccountType =
dyn ConnectorIntegration<PoRecipientAccount, PayoutsData, PayoutsResponseData>;
/// Type alias for `ConnectorIntegration<PoQuote, PayoutsData, PayoutsResponseData>`
#[cfg(feature = "payouts")]
pub type PayoutQuoteType = dyn ConnectorIntegration<PoQuote, PayoutsData, PayoutsResponseData>;
/// Type alias for `ConnectorIntegration<PoSync, PayoutsData, PayoutsResponseData>`
#[cfg(feature = "payouts")]
pub type PayoutSyncType = dyn ConnectorIntegration<PoSync, PayoutsData, PayoutsResponseData>;
/// Type alias for `ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken>`
pub type RefreshTokenType =
dyn ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken>;
/// Type alias for `ConnectorIntegration<Accept, AcceptDisputeRequestData, AcceptDisputeResponse>`
pub type AcceptDisputeType =
dyn ConnectorIntegration<Accept, AcceptDisputeRequestData, AcceptDisputeResponse>;
/// Type alias for `ConnectorIntegration<VerifyWebhookSource, VerifyWebhookSourceRequestData, VerifyWebhookSourceResponseData>`
pub type VerifyWebhookSourceType = dyn ConnectorIntegration<
VerifyWebhookSource,
VerifyWebhookSourceRequestData,
VerifyWebhookSourceResponseData,
>;
/// Type alias for `ConnectorIntegration<Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse>`
pub type SubmitEvidenceType =
dyn ConnectorIntegration<Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse>;
/// Type alias for `ConnectorIntegration<Upload, UploadFileRequestData, UploadFileResponse>`
pub type UploadFileType =
dyn ConnectorIntegration<Upload, UploadFileRequestData, UploadFileResponse>;
/// Type alias for `ConnectorIntegration<Retrieve, RetrieveFileRequestData, RetrieveFileResponse>`
pub type RetrieveFileType =
dyn ConnectorIntegration<Retrieve, RetrieveFileRequestData, RetrieveFileResponse>;
/// Type alias for `ConnectorIntegration<Defend, DefendDisputeRequestData, DefendDisputeResponse>`
pub type DefendDisputeType =
dyn ConnectorIntegration<Defend, DefendDisputeRequestData, DefendDisputeResponse>;
/// Type alias for `ConnectorIntegration<PreAuthenticate, UasPreAuthenticationRequestData, UasAuthenticationResponseData>`
pub type UasPreAuthenticationType = dyn ConnectorIntegration<
PreAuthenticate,
UasPreAuthenticationRequestData,
UasAuthenticationResponseData,
>;
/// Type alias for `ConnectorIntegration<PostAuthenticate, UasPostAuthenticationRequestData, UasAuthenticationResponseData>`
pub type UasPostAuthenticationType = dyn ConnectorIntegration<
PostAuthenticate,
UasPostAuthenticationRequestData,
UasAuthenticationResponseData,
>;
/// Type alias for `ConnectorIntegration<Confirmation, UasConfirmationRequestData, UasAuthenticationResponseData>`
pub type UasAuthenticationConfirmationType = dyn ConnectorIntegration<
AuthenticationConfirmation,
UasConfirmationRequestData,
UasAuthenticationResponseData,
>;
/// Type alias for `ConnectorIntegration<Authenticate, UasAuthenticationRequestData, UasAuthenticationResponseData>`
pub type UasAuthenticationType = dyn ConnectorIntegration<
Authenticate,
UasAuthenticationRequestData,
UasAuthenticationResponseData,
>;
/// Type alias for `ConnectorIntegration<RecoveryRecordBack, RevenueRecoveryRecordBackRequest, RevenueRecoveryRecordBackResponse>`
pub type RevenueRecoveryRecordBackType = dyn ConnectorIntegration<
RecoveryRecordBack,
RevenueRecoveryRecordBackRequest,
RevenueRecoveryRecordBackResponse,
>;
/// Type alias for `ConnectorIntegration<BillingConnectorPaymentsSync, BillingConnectorPaymentsSyncRequest, BillingConnectorPaymentsSyncResponse>`
pub type BillingConnectorPaymentsSyncType = dyn ConnectorIntegration<
BillingConnectorPaymentsSync,
BillingConnectorPaymentsSyncRequest,
BillingConnectorPaymentsSyncResponse,
>;
| 2,675 | 995 |
hyperswitch | crates/hyperswitch_interfaces/src/secrets_interface.rs | .rs | //! Secrets management interface
pub mod secret_handler;
pub mod secret_state;
use common_utils::errors::CustomResult;
use masking::Secret;
/// Trait defining the interface for managing application secrets
#[async_trait::async_trait]
pub trait SecretManagementInterface: Send + Sync {
/*
/// Given an input, encrypt/store the secret
async fn store_secret(
&self,
input: Secret<String>,
) -> CustomResult<String, SecretsManagementError>;
*/
/// Given an input, decrypt/retrieve the secret
async fn get_secret(
&self,
input: Secret<String>,
) -> CustomResult<Secret<String>, SecretsManagementError>;
}
/// Errors that may occur during secret management
#[derive(Debug, thiserror::Error)]
pub enum SecretsManagementError {
/// An error occurred when retrieving raw data.
#[error("Failed to fetch the raw data")]
FetchSecretFailed,
/// Failed while creating kms client
#[error("Failed while creating a secrets management client")]
ClientCreationFailed,
}
| 216 | 996 |
hyperswitch | crates/hyperswitch_interfaces/src/connector_integration_interface.rs | .rs | use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId};
use common_enums::PaymentAction;
use common_utils::{crypto, errors::CustomResult, request::Request};
use hyperswitch_domain_models::{
api::ApplicationResponse,
configs::Connectors,
errors::api_error_response::ApiErrorResponse,
payment_method_data::PaymentMethodData,
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_data_v2::RouterDataV2,
router_response_types::{ConnectorInfo, SupportedPaymentMethods},
};
use crate::{
api,
api::{
BoxedConnectorIntegration, CaptureSyncMethod, Connector, ConnectorCommon,
ConnectorIntegration, ConnectorRedirectResponse, ConnectorSpecifications,
ConnectorValidation, CurrencyUnit,
},
authentication::ExternalAuthenticationPayload,
connector_integration_v2::{BoxedConnectorIntegrationV2, ConnectorIntegrationV2, ConnectorV2},
disputes, errors,
events::connector_api_logs::ConnectorEvent,
types,
webhooks::{IncomingWebhook, IncomingWebhookFlowError, IncomingWebhookRequestDetails},
};
/// RouterDataConversion trait
///
/// This trait must be implemented for conversion between Router data and RouterDataV2
pub trait RouterDataConversion<T, Req: Clone, Resp: Clone> {
/// Convert RouterData to RouterDataV2
///
/// # Arguments
///
/// * `old_router_data` - A reference to the old RouterData
///
/// # Returns
///
/// A `CustomResult` containing the new RouterDataV2 or a ConnectorError
fn from_old_router_data(
old_router_data: &RouterData<T, Req, Resp>,
) -> CustomResult<RouterDataV2<T, Self, Req, Resp>, errors::ConnectorError>
where
Self: Sized;
/// Convert RouterDataV2 back to RouterData
///
/// # Arguments
///
/// * `new_router_data` - The new RouterDataV2
///
/// # Returns
///
/// A `CustomResult` containing the old RouterData or a ConnectorError
fn to_old_router_data(
new_router_data: RouterDataV2<T, Self, Req, Resp>,
) -> CustomResult<RouterData<T, Req, Resp>, errors::ConnectorError>
where
Self: Sized;
}
/// Alias for Box<&'static (dyn Connector + Sync)>
pub type BoxedConnector = Box<&'static (dyn Connector + Sync)>;
/// Alias for Box<&'static (dyn ConnectorV2 + Sync)>
pub type BoxedConnectorV2 = Box<&'static (dyn ConnectorV2 + Sync)>;
/// Enum representing the Connector
#[derive(Clone)]
pub enum ConnectorEnum {
/// Old connector type
Old(BoxedConnector),
/// New connector type
New(BoxedConnectorV2),
}
impl std::fmt::Debug for ConnectorEnum {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Old(_) => f
.debug_tuple("Old")
.field(&std::any::type_name::<BoxedConnector>().to_string())
.finish(),
Self::New(_) => f
.debug_tuple("New")
.field(&std::any::type_name::<BoxedConnectorV2>().to_string())
.finish(),
}
}
}
#[allow(missing_debug_implementations)]
/// Enum representing the Connector Integration
#[derive(Clone)]
pub enum ConnectorIntegrationEnum<'a, F, ResourceCommonData, Req, Resp> {
/// Old connector integration type
Old(BoxedConnectorIntegration<'a, F, Req, Resp>),
/// New connector integration type
New(BoxedConnectorIntegrationV2<'a, F, ResourceCommonData, Req, Resp>),
}
/// Alias for Box<dyn ConnectorIntegrationInterface>
pub type BoxedConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp> =
Box<dyn ConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp> + Send + Sync>;
impl ConnectorEnum {
/// Get the connector integration
///
/// # Returns
///
/// A `BoxedConnectorIntegrationInterface` containing the connector integration
pub fn get_connector_integration<F, ResourceCommonData, Req, Resp>(
&self,
) -> BoxedConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp>
where
dyn Connector + Sync: ConnectorIntegration<F, Req, Resp>,
dyn ConnectorV2 + Sync: ConnectorIntegrationV2<F, ResourceCommonData, Req, Resp>,
ResourceCommonData: RouterDataConversion<F, Req, Resp> + Clone + 'static,
F: Clone + 'static,
Req: Clone + 'static,
Resp: Clone + 'static,
{
match self {
Self::Old(old_integration) => Box::new(ConnectorIntegrationEnum::Old(
old_integration.get_connector_integration(),
)),
Self::New(new_integration) => Box::new(ConnectorIntegrationEnum::New(
new_integration.get_connector_integration_v2(),
)),
}
}
/// validates the file upload
pub fn validate_file_upload(
&self,
purpose: api::files::FilePurpose,
file_size: i32,
file_type: mime::Mime,
) -> CustomResult<(), errors::ConnectorError> {
match self {
Self::Old(connector) => connector.validate_file_upload(purpose, file_size, file_type),
Self::New(connector) => {
connector.validate_file_upload_v2(purpose, file_size, file_type)
}
}
}
}
#[async_trait::async_trait]
impl IncomingWebhook for ConnectorEnum {
fn get_webhook_body_decoding_algorithm(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::DecodeMessage + Send>, errors::ConnectorError> {
match self {
Self::Old(connector) => connector.get_webhook_body_decoding_algorithm(request),
Self::New(connector) => connector.get_webhook_body_decoding_algorithm(request),
}
}
fn get_webhook_body_decoding_message(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
match self {
Self::Old(connector) => connector.get_webhook_body_decoding_message(request),
Self::New(connector) => connector.get_webhook_body_decoding_message(request),
}
}
async fn decode_webhook_body(
&self,
request: &IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
connector_name: &str,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
match self {
Self::Old(connector) => {
connector
.decode_webhook_body(
request,
merchant_id,
connector_webhook_details,
connector_name,
)
.await
}
Self::New(connector) => {
connector
.decode_webhook_body(
request,
merchant_id,
connector_webhook_details,
connector_name,
)
.await
}
}
}
fn get_webhook_source_verification_algorithm(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
match self {
Self::Old(connector) => connector.get_webhook_source_verification_algorithm(request),
Self::New(connector) => connector.get_webhook_source_verification_algorithm(request),
}
}
async fn get_webhook_source_verification_merchant_secret(
&self,
merchant_id: &common_utils::id_type::MerchantId,
connector_name: &str,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<api_models::webhooks::ConnectorWebhookSecrets, errors::ConnectorError> {
match self {
Self::Old(connector) => {
connector
.get_webhook_source_verification_merchant_secret(
merchant_id,
connector_name,
connector_webhook_details,
)
.await
}
Self::New(connector) => {
connector
.get_webhook_source_verification_merchant_secret(
merchant_id,
connector_name,
connector_webhook_details,
)
.await
}
}
}
fn get_webhook_source_verification_signature(
&self,
request: &IncomingWebhookRequestDetails<'_>,
connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
match self {
Self::Old(connector) => connector
.get_webhook_source_verification_signature(request, connector_webhook_secrets),
Self::New(connector) => connector
.get_webhook_source_verification_signature(request, connector_webhook_secrets),
}
}
fn get_webhook_source_verification_message(
&self,
request: &IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
match self {
Self::Old(connector) => connector.get_webhook_source_verification_message(
request,
merchant_id,
connector_webhook_secrets,
),
Self::New(connector) => connector.get_webhook_source_verification_message(
request,
merchant_id,
connector_webhook_secrets,
),
}
}
async fn verify_webhook_source(
&self,
request: &IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
connector_account_details: crypto::Encryptable<masking::Secret<serde_json::Value>>,
connector_name: &str,
) -> CustomResult<bool, errors::ConnectorError> {
match self {
Self::Old(connector) => {
connector
.verify_webhook_source(
request,
merchant_id,
connector_webhook_details,
connector_account_details,
connector_name,
)
.await
}
Self::New(connector) => {
connector
.verify_webhook_source(
request,
merchant_id,
connector_webhook_details,
connector_account_details,
connector_name,
)
.await
}
}
}
fn get_webhook_object_reference_id(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<ObjectReferenceId, errors::ConnectorError> {
match self {
Self::Old(connector) => connector.get_webhook_object_reference_id(request),
Self::New(connector) => connector.get_webhook_object_reference_id(request),
}
}
fn get_webhook_event_type(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
match self {
Self::Old(connector) => connector.get_webhook_event_type(request),
Self::New(connector) => connector.get_webhook_event_type(request),
}
}
fn get_webhook_resource_object(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
match self {
Self::Old(connector) => connector.get_webhook_resource_object(request),
Self::New(connector) => connector.get_webhook_resource_object(request),
}
}
fn get_webhook_api_response(
&self,
request: &IncomingWebhookRequestDetails<'_>,
error_kind: Option<IncomingWebhookFlowError>,
) -> CustomResult<ApplicationResponse<serde_json::Value>, errors::ConnectorError> {
match self {
Self::Old(connector) => connector.get_webhook_api_response(request, error_kind),
Self::New(connector) => connector.get_webhook_api_response(request, error_kind),
}
}
fn get_dispute_details(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<disputes::DisputePayload, errors::ConnectorError> {
match self {
Self::Old(connector) => connector.get_dispute_details(request),
Self::New(connector) => connector.get_dispute_details(request),
}
}
fn get_external_authentication_details(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<ExternalAuthenticationPayload, errors::ConnectorError> {
match self {
Self::Old(connector) => connector.get_external_authentication_details(request),
Self::New(connector) => connector.get_external_authentication_details(request),
}
}
fn get_mandate_details(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<
Option<hyperswitch_domain_models::router_flow_types::ConnectorMandateDetails>,
errors::ConnectorError,
> {
match self {
Self::Old(connector) => connector.get_mandate_details(request),
Self::New(connector) => connector.get_mandate_details(request),
}
}
fn get_network_txn_id(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<
Option<hyperswitch_domain_models::router_flow_types::ConnectorNetworkTxnId>,
errors::ConnectorError,
> {
match self {
Self::Old(connector) => connector.get_network_txn_id(request),
Self::New(connector) => connector.get_network_txn_id(request),
}
}
}
impl ConnectorRedirectResponse for ConnectorEnum {
fn get_flow_type(
&self,
query_params: &str,
json_payload: Option<serde_json::Value>,
action: PaymentAction,
) -> CustomResult<common_enums::CallConnectorAction, errors::ConnectorError> {
match self {
Self::Old(connector) => connector.get_flow_type(query_params, json_payload, action),
Self::New(connector) => connector.get_flow_type(query_params, json_payload, action),
}
}
}
impl ConnectorValidation for ConnectorEnum {
fn validate_connector_against_payment_request(
&self,
capture_method: Option<common_enums::CaptureMethod>,
payment_method: common_enums::PaymentMethod,
pmt: Option<common_enums::PaymentMethodType>,
) -> CustomResult<(), errors::ConnectorError> {
match self {
Self::Old(connector) => connector.validate_connector_against_payment_request(
capture_method,
payment_method,
pmt,
),
Self::New(connector) => connector.validate_connector_against_payment_request(
capture_method,
payment_method,
pmt,
),
}
}
fn validate_mandate_payment(
&self,
pm_type: Option<common_enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
match self {
Self::Old(connector) => connector.validate_mandate_payment(pm_type, pm_data),
Self::New(connector) => connector.validate_mandate_payment(pm_type, pm_data),
}
}
fn validate_psync_reference_id(
&self,
data: &hyperswitch_domain_models::router_request_types::PaymentsSyncData,
is_three_ds: bool,
status: common_enums::enums::AttemptStatus,
connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<(), errors::ConnectorError> {
match self {
Self::Old(connector) => connector.validate_psync_reference_id(
data,
is_three_ds,
status,
connector_meta_data,
),
Self::New(connector) => connector.validate_psync_reference_id(
data,
is_three_ds,
status,
connector_meta_data,
),
}
}
fn is_webhook_source_verification_mandatory(&self) -> bool {
match self {
Self::Old(connector) => connector.is_webhook_source_verification_mandatory(),
Self::New(connector) => connector.is_webhook_source_verification_mandatory(),
}
}
}
impl ConnectorSpecifications for ConnectorEnum {
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
match self {
Self::Old(connector) => connector.get_supported_payment_methods(),
Self::New(connector) => connector.get_supported_payment_methods(),
}
}
/// Supported webhooks flows
fn get_supported_webhook_flows(&self) -> Option<&'static [common_enums::EventClass]> {
match self {
Self::Old(connector) => connector.get_supported_webhook_flows(),
Self::New(connector) => connector.get_supported_webhook_flows(),
}
}
/// Details related to connector
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
match self {
Self::Old(connector) => connector.get_connector_about(),
Self::New(connector) => connector.get_connector_about(),
}
}
}
impl ConnectorCommon for ConnectorEnum {
fn id(&self) -> &'static str {
match self {
Self::Old(connector) => connector.id(),
Self::New(connector) => connector.id(),
}
}
fn get_currency_unit(&self) -> CurrencyUnit {
match self {
Self::Old(connector) => connector.get_currency_unit(),
Self::New(connector) => connector.get_currency_unit(),
}
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
match self {
Self::Old(connector) => connector.get_auth_header(auth_type),
Self::New(connector) => connector.get_auth_header(auth_type),
}
}
fn common_get_content_type(&self) -> &'static str {
match self {
Self::Old(connector) => connector.common_get_content_type(),
Self::New(connector) => connector.common_get_content_type(),
}
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
match self {
Self::Old(connector) => connector.base_url(connectors),
Self::New(connector) => connector.base_url(connectors),
}
}
fn build_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
match self {
Self::Old(connector) => connector.build_error_response(res, event_builder),
Self::New(connector) => connector.build_error_response(res, event_builder),
}
}
}
/// Trait representing the connector integration interface
///
/// This trait defines the methods required for a connector integration interface.
pub trait ConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp>: Send + Sync {
/// Clone the connector integration interface
///
/// # Returns
///
/// A `Box` containing the cloned connector integration interface
fn clone_box(
&self,
) -> Box<dyn ConnectorIntegrationInterface<F, ResourceCommonData, Req, Resp> + Send + Sync>;
/// Get the multiple capture sync method
///
/// # Returns
///
/// A `CustomResult` containing the `CaptureSyncMethod` or a `ConnectorError`
fn get_multiple_capture_sync_method(
&self,
) -> CustomResult<CaptureSyncMethod, errors::ConnectorError>;
/// Build a request for the connector integration
///
/// # Arguments
///
/// * `req` - A reference to the RouterData
/// # Returns
///
/// A `CustomResult` containing an optional Request or a ConnectorError
fn build_request(
&self,
req: &RouterData<F, Req, Resp>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError>;
/// handles response from the connector
fn handle_response(
&self,
data: &RouterData<F, Req, Resp>,
event_builder: Option<&mut ConnectorEvent>,
_res: types::Response,
) -> CustomResult<RouterData<F, Req, Resp>, errors::ConnectorError>
where
F: Clone,
Req: Clone,
Resp: Clone;
/// Get the error response
///
/// # Arguments
///
/// * `res` - The response
/// * `event_builder` - An optional event builder
///
/// # Returns
///
/// A `CustomResult` containing the `ErrorResponse` or a `ConnectorError`
fn get_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError>;
/// Get the 5xx error response
///
/// # Arguments
///
/// * `res` - The response
/// * `event_builder` - An optional event builder
///
/// # Returns
///
/// A `CustomResult` containing the `ErrorResponse` or a `ConnectorError`
fn get_5xx_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError>;
}
impl<T: 'static, ResourceCommonData: 'static, Req: 'static, Resp: 'static>
ConnectorIntegrationInterface<T, ResourceCommonData, Req, Resp>
for ConnectorIntegrationEnum<'static, T, ResourceCommonData, Req, Resp>
where
ResourceCommonData: RouterDataConversion<T, Req, Resp> + Clone,
T: Clone,
Req: Clone,
Resp: Clone,
{
fn get_multiple_capture_sync_method(
&self,
) -> CustomResult<CaptureSyncMethod, errors::ConnectorError> {
match self {
ConnectorIntegrationEnum::Old(old_integration) => {
old_integration.get_multiple_capture_sync_method()
}
ConnectorIntegrationEnum::New(new_integration) => {
new_integration.get_multiple_capture_sync_method()
}
}
}
fn build_request(
&self,
req: &RouterData<T, Req, Resp>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
match self {
ConnectorIntegrationEnum::Old(old_integration) => {
old_integration.build_request(req, connectors)
}
ConnectorIntegrationEnum::New(new_integration) => {
let new_router_data = ResourceCommonData::from_old_router_data(req)?;
new_integration.build_request_v2(&new_router_data)
}
}
}
fn handle_response(
&self,
data: &RouterData<T, Req, Resp>,
event_builder: Option<&mut ConnectorEvent>,
res: types::Response,
) -> CustomResult<RouterData<T, Req, Resp>, errors::ConnectorError>
where
T: Clone,
Req: Clone,
Resp: Clone,
{
match self {
ConnectorIntegrationEnum::Old(old_integration) => {
old_integration.handle_response(data, event_builder, res)
}
ConnectorIntegrationEnum::New(new_integration) => {
let new_router_data = ResourceCommonData::from_old_router_data(data)?;
new_integration
.handle_response_v2(&new_router_data, event_builder, res)
.map(ResourceCommonData::to_old_router_data)?
}
}
}
fn get_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
match self {
ConnectorIntegrationEnum::Old(old_integration) => {
old_integration.get_error_response(res, event_builder)
}
ConnectorIntegrationEnum::New(new_integration) => {
new_integration.get_error_response_v2(res, event_builder)
}
}
}
fn get_5xx_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
match self {
ConnectorIntegrationEnum::Old(old_integration) => {
old_integration.get_5xx_error_response(res, event_builder)
}
ConnectorIntegrationEnum::New(new_integration) => {
new_integration.get_5xx_error_response(res, event_builder)
}
}
}
fn clone_box(
&self,
) -> Box<dyn ConnectorIntegrationInterface<T, ResourceCommonData, Req, Resp> + Send + Sync>
{
Box::new(self.clone())
}
}
impl api::ConnectorTransactionId for ConnectorEnum {
/// Get the connector transaction ID
///
/// # Arguments
///
/// * `payment_attempt` - The payment attempt
///
/// # Returns
///
/// A `Result` containing an optional transaction ID or an ApiErrorResponse
fn connector_transaction_id(
&self,
payment_attempt: hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
) -> Result<Option<String>, ApiErrorResponse> {
match self {
Self::Old(connector) => connector.connector_transaction_id(payment_attempt),
Self::New(connector) => connector.connector_transaction_id(payment_attempt),
}
}
}
| 5,523 | 997 |
hyperswitch | crates/hyperswitch_interfaces/src/lib.rs | .rs | //! Hyperswitch interface
#![warn(missing_docs, missing_debug_implementations)]
pub mod api;
pub mod authentication;
/// Configuration related functionalities
pub mod configs;
/// Connector integration interface module
pub mod connector_integration_interface;
/// definition of the new connector integration trait
pub mod connector_integration_v2;
/// Constants used throughout the application
pub mod consts;
/// Conversion implementations
pub mod conversion_impls;
pub mod disputes;
pub mod encryption_interface;
pub mod errors;
pub mod events;
/// connector integrity check interface
pub mod integrity;
pub mod metrics;
pub mod secrets_interface;
pub mod types;
pub mod webhooks;
| 129 | 998 |
hyperswitch | crates/hyperswitch_interfaces/src/errors.rs | .rs | //! Errors interface
use common_utils::errors::ErrorSwitch;
use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse;
/// Connector Errors
#[allow(missing_docs, missing_debug_implementations)]
#[derive(Debug, thiserror::Error, PartialEq)]
pub enum ConnectorError {
#[error("Error while obtaining URL for the integration")]
FailedToObtainIntegrationUrl,
#[error("Failed to encode connector request")]
RequestEncodingFailed,
#[error("Request encoding failed : {0}")]
RequestEncodingFailedWithReason(String),
#[error("Parsing failed")]
ParsingFailed,
#[error("Failed to deserialize connector response")]
ResponseDeserializationFailed,
#[error("Failed to execute a processing step: {0:?}")]
ProcessingStepFailed(Option<bytes::Bytes>),
#[error("The connector returned an unexpected response: {0:?}")]
UnexpectedResponseError(bytes::Bytes),
#[error("Failed to parse custom routing rules from merchant account")]
RoutingRulesParsingError,
#[error("Failed to obtain preferred connector from merchant account")]
FailedToObtainPreferredConnector,
#[error("An invalid connector name was provided")]
InvalidConnectorName,
#[error("An invalid Wallet was used")]
InvalidWallet,
#[error("Failed to handle connector response")]
ResponseHandlingFailed,
#[error("Missing required field: {field_name}")]
MissingRequiredField { field_name: &'static str },
#[error("Missing required fields: {field_names:?}")]
MissingRequiredFields { field_names: Vec<&'static str> },
#[error("Failed to obtain authentication type")]
FailedToObtainAuthType,
#[error("Failed to obtain certificate")]
FailedToObtainCertificate,
#[error("Connector meta data not found")]
NoConnectorMetaData,
#[error("Connector wallet details not found")]
NoConnectorWalletDetails,
#[error("Failed to obtain certificate key")]
FailedToObtainCertificateKey,
#[error("This step has not been implemented for: {0}")]
NotImplemented(String),
#[error("{message} is not supported by {connector}")]
NotSupported {
message: String,
connector: &'static str,
},
#[error("{flow} flow not supported by {connector} connector")]
FlowNotSupported { flow: String, connector: String },
#[error("Capture method not supported")]
CaptureMethodNotSupported,
#[error("Missing connector mandate ID")]
MissingConnectorMandateID,
#[error("Missing connector mandate metadata")]
MissingConnectorMandateMetadata,
#[error("Missing connector transaction ID")]
MissingConnectorTransactionID,
#[error("Missing connector refund ID")]
MissingConnectorRefundID,
#[error("Missing apple pay tokenization data")]
MissingApplePayTokenData,
#[error("Webhooks not implemented for this connector")]
WebhooksNotImplemented,
#[error("Failed to decode webhook event body")]
WebhookBodyDecodingFailed,
#[error("Signature not found for incoming webhook")]
WebhookSignatureNotFound,
#[error("Failed to verify webhook source")]
WebhookSourceVerificationFailed,
#[error("Could not find merchant secret in DB for incoming webhook source verification")]
WebhookVerificationSecretNotFound,
#[error("Merchant secret found for incoming webhook source verification is invalid")]
WebhookVerificationSecretInvalid,
#[error("Incoming webhook object reference ID not found")]
WebhookReferenceIdNotFound,
#[error("Incoming webhook event type not found")]
WebhookEventTypeNotFound,
#[error("Incoming webhook event resource object not found")]
WebhookResourceObjectNotFound,
#[error("Could not respond to the incoming webhook event")]
WebhookResponseEncodingFailed,
#[error("Invalid Date/time format")]
InvalidDateFormat,
#[error("Date Formatting Failed")]
DateFormattingFailed,
#[error("Invalid Data format")]
InvalidDataFormat { field_name: &'static str },
#[error("Payment Method data / Payment Method Type / Payment Experience Mismatch ")]
MismatchedPaymentData,
#[error("Failed to parse {wallet_name} wallet token")]
InvalidWalletToken { wallet_name: String },
#[error("Missing Connector Related Transaction ID")]
MissingConnectorRelatedTransactionID { id: String },
#[error("File Validation failed")]
FileValidationFailed { reason: String },
#[error("Missing 3DS redirection payload: {field_name}")]
MissingConnectorRedirectionPayload { field_name: &'static str },
#[error("Failed at connector's end with code '{code}'")]
FailedAtConnector { message: String, code: String },
#[error("Payment Method Type not found")]
MissingPaymentMethodType,
#[error("Balance in the payment method is low")]
InSufficientBalanceInPaymentMethod,
#[error("Server responded with Request Timeout")]
RequestTimeoutReceived,
#[error("The given currency method is not configured with the given connector")]
CurrencyNotSupported {
message: String,
connector: &'static str,
},
#[error("Invalid Configuration")]
InvalidConnectorConfig { config: &'static str },
#[error("Failed to convert amount to required type")]
AmountConversionFailed,
#[error("Generic Error")]
GenericError {
error_message: String,
error_object: serde_json::Value,
},
}
impl ConnectorError {
/// fn is_connector_timeout
pub fn is_connector_timeout(&self) -> bool {
self == &Self::RequestTimeoutReceived
}
}
impl ErrorSwitch<ConnectorError> for common_utils::errors::ParsingError {
fn switch(&self) -> ConnectorError {
ConnectorError::ParsingFailed
}
}
impl ErrorSwitch<ApiErrorResponse> for ConnectorError {
fn switch(&self) -> ApiErrorResponse {
match self {
Self::WebhookSourceVerificationFailed => ApiErrorResponse::WebhookAuthenticationFailed,
Self::WebhookSignatureNotFound
| Self::WebhookReferenceIdNotFound
| Self::WebhookResourceObjectNotFound
| Self::WebhookBodyDecodingFailed
| Self::WebhooksNotImplemented => ApiErrorResponse::WebhookBadRequest,
Self::WebhookEventTypeNotFound => ApiErrorResponse::WebhookUnprocessableEntity,
Self::WebhookVerificationSecretInvalid => {
ApiErrorResponse::WebhookInvalidMerchantSecret
}
_ => ApiErrorResponse::InternalServerError,
}
}
}
| 1,342 | 999 |
hyperswitch | crates/hyperswitch_interfaces/src/events.rs | .rs | //! Events interface
pub mod connector_api_logs;
| 10 | 1,000 |
hyperswitch | crates/hyperswitch_interfaces/src/configs.rs | .rs | pub use hyperswitch_domain_models::configs::Connectors;
| 12 | 1,001 |
hyperswitch | crates/hyperswitch_interfaces/src/connector_integration_v2.rs | .rs | //! definition of the new connector integration trait
use common_utils::{
errors::CustomResult,
request::{Method, Request, RequestBuilder, RequestContent},
};
use hyperswitch_domain_models::{router_data::ErrorResponse, router_data_v2::RouterDataV2};
use masking::Maskable;
use serde_json::json;
use crate::{
api::{self, CaptureSyncMethod},
errors,
events::connector_api_logs::ConnectorEvent,
metrics, types, webhooks,
};
/// ConnectorV2 trait
pub trait ConnectorV2:
Send
+ api::refunds_v2::RefundV2
+ api::payments_v2::PaymentV2
+ api::ConnectorRedirectResponse
+ webhooks::IncomingWebhook
+ api::ConnectorAccessTokenV2
+ api::disputes_v2::DisputeV2
+ api::files_v2::FileUploadV2
+ api::ConnectorTransactionId
+ api::PayoutsV2
+ api::ConnectorVerifyWebhookSourceV2
+ api::FraudCheckV2
+ api::ConnectorMandateRevokeV2
+ api::authentication_v2::ExternalAuthenticationV2
+ api::UnifiedAuthenticationServiceV2
+ api::revenue_recovery_v2::RevenueRecoveryV2
{
}
impl<
T: api::refunds_v2::RefundV2
+ api::payments_v2::PaymentV2
+ api::ConnectorRedirectResponse
+ Send
+ webhooks::IncomingWebhook
+ api::ConnectorAccessTokenV2
+ api::disputes_v2::DisputeV2
+ api::files_v2::FileUploadV2
+ api::ConnectorTransactionId
+ api::PayoutsV2
+ api::ConnectorVerifyWebhookSourceV2
+ api::FraudCheckV2
+ api::ConnectorMandateRevokeV2
+ api::authentication_v2::ExternalAuthenticationV2
+ api::UnifiedAuthenticationServiceV2
+ api::revenue_recovery_v2::RevenueRecoveryV2,
> ConnectorV2 for T
{
}
/// Alias for Box<&'static (dyn ConnectorV2 + Sync)>
pub type BoxedConnectorV2 = Box<&'static (dyn ConnectorV2 + Sync)>;
/// alias for Box of a type that implements trait ConnectorIntegrationV2
pub type BoxedConnectorIntegrationV2<'a, Flow, ResourceCommonData, Req, Resp> =
Box<&'a (dyn ConnectorIntegrationV2<Flow, ResourceCommonData, Req, Resp> + Send + Sync)>;
/// trait with a function that returns BoxedConnectorIntegrationV2
pub trait ConnectorIntegrationAnyV2<Flow, ResourceCommonData, Req, Resp>:
Send + Sync + 'static
{
/// function what returns BoxedConnectorIntegrationV2
fn get_connector_integration_v2(
&self,
) -> BoxedConnectorIntegrationV2<'_, Flow, ResourceCommonData, Req, Resp>;
}
impl<S, Flow, ResourceCommonData, Req, Resp>
ConnectorIntegrationAnyV2<Flow, ResourceCommonData, Req, Resp> for S
where
S: ConnectorIntegrationV2<Flow, ResourceCommonData, Req, Resp> + Send + Sync,
{
fn get_connector_integration_v2(
&self,
) -> BoxedConnectorIntegrationV2<'_, Flow, ResourceCommonData, Req, Resp> {
Box::new(self)
}
}
/// The new connector integration trait with an additional ResourceCommonData generic parameter
pub trait ConnectorIntegrationV2<Flow, ResourceCommonData, Req, Resp>:
ConnectorIntegrationAnyV2<Flow, ResourceCommonData, Req, Resp> + Sync + api::ConnectorCommon
{
/// returns a vec of tuple of header key and value
fn get_headers(
&self,
_req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
Ok(vec![])
}
/// returns content type
fn get_content_type(&self) -> &'static str {
mime::APPLICATION_JSON.essence_str()
}
/// primarily used when creating signature based on request method of payment flow
fn get_http_method(&self) -> Method {
Method::Post
}
/// returns url
fn get_url(
&self,
_req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>,
) -> CustomResult<String, errors::ConnectorError> {
metrics::UNIMPLEMENTED_FLOW
.add(1, router_env::metric_attributes!(("connector", self.id())));
Ok(String::new())
}
/// returns request body
fn get_request_body(
&self,
_req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>,
) -> CustomResult<Option<RequestContent>, errors::ConnectorError> {
Ok(None)
}
/// returns form data
fn get_request_form_data(
&self,
_req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>,
) -> CustomResult<Option<reqwest::multipart::Form>, errors::ConnectorError> {
Ok(None)
}
/// builds the request and returns it
fn build_request_v2(
&self,
req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(self.get_http_method())
.url(self.get_url(req)?.as_str())
.attach_default_headers()
.headers(self.get_headers(req)?)
.set_optional_body(self.get_request_body(req)?)
.add_certificate(self.get_certificate(req)?)
.add_certificate_key(self.get_certificate_key(req)?)
.build(),
))
}
/// accepts the raw api response and decodes it
fn handle_response_v2(
&self,
data: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>,
event_builder: Option<&mut ConnectorEvent>,
_res: types::Response,
) -> CustomResult<RouterDataV2<Flow, ResourceCommonData, Req, Resp>, errors::ConnectorError>
where
Flow: Clone,
ResourceCommonData: Clone,
Req: Clone,
Resp: Clone,
{
event_builder.map(|e| e.set_error(json!({"error": "Not Implemented"})));
Ok(data.clone())
}
/// accepts the raw api error response and decodes it
fn get_error_response_v2(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
event_builder.map(|event| event.set_error(json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
Ok(ErrorResponse::get_not_implemented())
}
/// accepts the raw 5xx error response and decodes it
fn get_5xx_error_response(
&self,
res: types::Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
event_builder.map(|event| event.set_error(json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
let error_message = match res.status_code {
500 => "internal_server_error",
501 => "not_implemented",
502 => "bad_gateway",
503 => "service_unavailable",
504 => "gateway_timeout",
505 => "http_version_not_supported",
506 => "variant_also_negotiates",
507 => "insufficient_storage",
508 => "loop_detected",
510 => "not_extended",
511 => "network_authentication_required",
_ => "unknown_error",
};
Ok(ErrorResponse {
code: res.status_code.to_string(),
message: error_message.to_string(),
reason: String::from_utf8(res.response.to_vec()).ok(),
status_code: res.status_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
})
}
// whenever capture sync is implemented at the connector side, this method should be overridden
/// retunes the capture sync method
fn get_multiple_capture_sync_method(
&self,
) -> CustomResult<CaptureSyncMethod, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("multiple capture sync".into()).into())
}
/// returns certificate string
fn get_certificate(
&self,
_req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>,
) -> CustomResult<Option<masking::Secret<String>>, errors::ConnectorError> {
Ok(None)
}
/// returns private key string
fn get_certificate_key(
&self,
_req: &RouterDataV2<Flow, ResourceCommonData, Req, Resp>,
) -> CustomResult<Option<masking::Secret<String>>, errors::ConnectorError> {
Ok(None)
}
}
| 2,057 | 1,002 |
hyperswitch | crates/hyperswitch_interfaces/src/events/connector_api_logs.rs | .rs | //! Connector API logs interface
use common_utils::request::Method;
use router_env::tracing_actix_web::RequestId;
use serde::Serialize;
use serde_json::json;
use time::OffsetDateTime;
/// struct ConnectorEvent
#[derive(Debug, Serialize)]
pub struct ConnectorEvent {
tenant_id: common_utils::id_type::TenantId,
connector_name: String,
flow: String,
request: String,
masked_response: Option<String>,
error: Option<String>,
url: String,
method: String,
payment_id: String,
merchant_id: common_utils::id_type::MerchantId,
created_at: i128,
/// Connector Event Request ID
pub request_id: String,
latency: u128,
refund_id: Option<String>,
dispute_id: Option<String>,
status_code: u16,
}
impl ConnectorEvent {
/// fn new ConnectorEvent
#[allow(clippy::too_many_arguments)]
pub fn new(
tenant_id: common_utils::id_type::TenantId,
connector_name: String,
flow: &str,
request: serde_json::Value,
url: String,
method: Method,
payment_id: String,
merchant_id: common_utils::id_type::MerchantId,
request_id: Option<&RequestId>,
latency: u128,
refund_id: Option<String>,
dispute_id: Option<String>,
status_code: u16,
) -> Self {
Self {
tenant_id,
connector_name,
flow: flow
.rsplit_once("::")
.map(|(_, s)| s)
.unwrap_or(flow)
.to_string(),
request: request.to_string(),
masked_response: None,
error: None,
url,
method: method.to_string(),
payment_id,
merchant_id,
created_at: OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000,
request_id: request_id
.map(|i| i.as_hyphenated().to_string())
.unwrap_or("NO_REQUEST_ID".to_string()),
latency,
refund_id,
dispute_id,
status_code,
}
}
/// fn set_response_body
pub fn set_response_body<T: Serialize>(&mut self, response: &T) {
match masking::masked_serialize(response) {
Ok(masked) => {
self.masked_response = Some(masked.to_string());
}
Err(er) => self.set_error(json!({"error": er.to_string()})),
}
}
/// fn set_error_response_body
pub fn set_error_response_body<T: Serialize>(&mut self, response: &T) {
match masking::masked_serialize(response) {
Ok(masked) => {
self.error = Some(masked.to_string());
}
Err(er) => self.set_error(json!({"error": er.to_string()})),
}
}
/// fn set_error
pub fn set_error(&mut self, error: serde_json::Value) {
self.error = Some(error.to_string());
}
}
| 667 | 1,003 |
hyperswitch | crates/hyperswitch_interfaces/src/api/revenue_recovery_v2.rs | .rs | //! Revenue Recovery Interface V2
use hyperswitch_domain_models::{
router_data_v2::flow_common_types::{
BillingConnectorPaymentsSyncFlowData, RevenueRecoveryRecordBackData,
},
router_flow_types::{BillingConnectorPaymentsSync, RecoveryRecordBack},
router_request_types::revenue_recovery::{
BillingConnectorPaymentsSyncRequest, RevenueRecoveryRecordBackRequest,
},
router_response_types::revenue_recovery::{
BillingConnectorPaymentsSyncResponse, RevenueRecoveryRecordBackResponse,
},
};
use crate::connector_integration_v2::ConnectorIntegrationV2;
/// trait RevenueRecoveryV2
pub trait RevenueRecoveryV2:
BillingConnectorPaymentsSyncIntegrationV2 + RevenueRecoveryRecordBackV2
{
}
/// trait BillingConnectorPaymentsSyncIntegrationV2
pub trait BillingConnectorPaymentsSyncIntegrationV2:
ConnectorIntegrationV2<
BillingConnectorPaymentsSync,
BillingConnectorPaymentsSyncFlowData,
BillingConnectorPaymentsSyncRequest,
BillingConnectorPaymentsSyncResponse,
>
{
}
/// trait RevenueRecoveryRecordBackV2
pub trait RevenueRecoveryRecordBackV2:
ConnectorIntegrationV2<
RecoveryRecordBack,
RevenueRecoveryRecordBackData,
RevenueRecoveryRecordBackRequest,
RevenueRecoveryRecordBackResponse,
>
{
}
| 268 | 1,004 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.