diff --git a/.cargo/config.toml b/.cargo/config.toml index 1368506f4e..66da12a13b 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,2 +1,23 @@ +[target.'cfg(all())'] +rustflags = [ + "-Funsafe_code", + "-Wclippy::as_conversions", + "-Wclippy::expect_used", + "-Wclippy::missing_panics_doc", + "-Wclippy::panic_in_result_fn", + "-Wclippy::panic", + "-Wclippy::panicking_unwrap", + "-Wclippy::todo", + "-Wclippy::unimplemented", + "-Wclippy::unreachable", + "-Wclippy::unwrap_in_result", + "-Wclippy::unwrap_used", + "-Wclippy::use_self", + # "-Wmissing_debug_implementations", + # "-Wmissing_docs", + "-Wrust_2018_idioms", + "-Wunused_qualifications", +] + [alias] -gen-pg = "generate --path ../../../../connector-template -n" \ No newline at end of file +gen-pg = "generate --path ../../../../connector-template -n" diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index ab6fce7dba..32e0767576 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -30,7 +30,6 @@ concurrency: cancel-in-progress: true env: - RUSTFLAGS: "-D warnings" # Disable incremental compilation. # # Incremental compilation is useful as part of an edit-build-test-edit cycle, @@ -104,6 +103,10 @@ jobs: with: crate: cargo-hack + - name: Deny warnings + shell: bash + run: sed -i 's/rustflags = \[/rustflags = \[\n "-Dwarnings",/' .cargo/config.toml + - name: Test compilation shell: bash run: cargo hack check --workspace --each-feature --no-dev-deps @@ -176,6 +179,10 @@ jobs: # mkdir -p .cargo # curl -sL https://raw.githubusercontent.com/EmbarkStudios/rust-ecosystem/main/lints.toml >> .cargo/config.toml + - name: Deny warnings + shell: bash + run: sed -i 's/rustflags = \[/rustflags = \[\n "-Dwarnings",/' .cargo/config.toml + - name: Run clippy shell: bash run: cargo clippy --all-features --all-targets diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 791d304dca..e37de90ba7 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -501,13 +501,13 @@ pub enum Connector { impl From for IntentStatus { fn from(s: AttemptStatus) -> Self { match s { - AttemptStatus::Charged | AttemptStatus::AutoRefunded => IntentStatus::Succeeded, + AttemptStatus::Charged | AttemptStatus::AutoRefunded => Self::Succeeded, - AttemptStatus::ConfirmationAwaited => IntentStatus::RequiresConfirmation, - AttemptStatus::PaymentMethodAwaited => IntentStatus::RequiresPaymentMethod, + AttemptStatus::ConfirmationAwaited => Self::RequiresConfirmation, + AttemptStatus::PaymentMethodAwaited => Self::RequiresPaymentMethod, - AttemptStatus::Authorized => IntentStatus::RequiresCapture, - AttemptStatus::AuthenticationPending => IntentStatus::RequiresCustomerAction, + AttemptStatus::Authorized => Self::RequiresCapture, + AttemptStatus::AuthenticationPending => Self::RequiresCustomerAction, AttemptStatus::PartialCharged | AttemptStatus::Started @@ -516,15 +516,15 @@ impl From for IntentStatus { | AttemptStatus::CodInitiated | AttemptStatus::VoidInitiated | AttemptStatus::CaptureInitiated - | AttemptStatus::Pending => IntentStatus::Processing, + | AttemptStatus::Pending => Self::Processing, AttemptStatus::AuthenticationFailed | AttemptStatus::AuthorizationFailed | AttemptStatus::VoidFailed | AttemptStatus::RouterDeclined | AttemptStatus::CaptureFailed - | AttemptStatus::Failure => IntentStatus::Failed, - AttemptStatus::Voided => IntentStatus::Cancelled, + | AttemptStatus::Failure => Self::Failed, + AttemptStatus::Voided => Self::Cancelled, } } } diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index a087d67368..5db1f91f12 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -86,7 +86,7 @@ impl<'de> serde::Deserialize<'de> for ListPaymentMethodRequest { impl<'de> de::Visitor<'de> for FieldVisitor { type Value = ListPaymentMethodRequest; - fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("Failed while deserializing as map") } diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 1a884d5671..76916d7eb1 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -77,7 +77,7 @@ impl From for i64 { impl From for Amount { fn from(val: i64) -> Self { - NonZeroI64::new(val).map_or(Amount::Zero, Amount::Value) + NonZeroI64::new(val).map_or(Self::Zero, Amount::Value) } } @@ -241,10 +241,11 @@ pub enum PayLaterData { }, } -#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +#[derive(Debug, Clone, Eq, PartialEq, Default, serde::Deserialize, serde::Serialize)] pub enum PaymentMethod { #[serde(rename(deserialize = "card"))] Card(CCard), + #[default] #[serde(rename(deserialize = "bank_transfer"))] BankTransfer, #[serde(rename(deserialize = "wallet"))] @@ -279,12 +280,6 @@ pub enum PaymentMethodDataResponse { Paypal, } -impl Default for PaymentMethod { - fn default() -> Self { - PaymentMethod::BankTransfer - } -} - #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub enum PaymentIdType { PaymentIntentId(String), @@ -683,13 +678,11 @@ impl From for CCardResponse { impl From for PaymentMethodDataResponse { fn from(payment_method_data: PaymentMethod) -> Self { match payment_method_data { - PaymentMethod::Card(card) => PaymentMethodDataResponse::Card(CCardResponse::from(card)), - PaymentMethod::BankTransfer => PaymentMethodDataResponse::BankTransfer, - PaymentMethod::PayLater(pay_later_data) => { - PaymentMethodDataResponse::PayLater(pay_later_data) - } - PaymentMethod::Wallet(wallet_data) => PaymentMethodDataResponse::Wallet(wallet_data), - PaymentMethod::Paypal => PaymentMethodDataResponse::Paypal, + PaymentMethod::Card(card) => Self::Card(CCardResponse::from(card)), + PaymentMethod::BankTransfer => Self::BankTransfer, + PaymentMethod::PayLater(pay_later_data) => Self::PayLater(pay_later_data), + PaymentMethod::Wallet(wallet_data) => Self::Wallet(wallet_data), + PaymentMethod::Paypal => Self::Paypal, } } } @@ -873,7 +866,7 @@ mod payment_id_type { impl<'de> Visitor<'de> for PaymentIdVisitor { type Value = PaymentIdType; - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } @@ -888,7 +881,7 @@ mod payment_id_type { impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option; - fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { + fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } @@ -944,7 +937,7 @@ mod amount { impl<'de> de::Visitor<'de> for AmountVisitor { type Value = Amount; - fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "amount as integer") } @@ -952,13 +945,24 @@ mod amount { where E: de::Error, { - self.visit_i64(v as i64) + let v = i64::try_from(v).map_err(|_| { + E::custom(format!( + "invalid value `{v}`, expected an integer between 0 and {}", + i64::MAX + )) + })?; + self.visit_i64(v) } fn visit_i64(self, v: i64) -> Result where E: de::Error, { + if v.is_negative() { + return Err(E::custom(format!( + "invalid value `{v}`, expected a positive integer" + ))); + } Ok(Amount::from(v)) } } @@ -966,7 +970,7 @@ mod amount { impl<'de> de::Visitor<'de> for OptionalAmountVisitor { type Value = Option; - fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result { + fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "option of amount (as integer)") } @@ -1002,6 +1006,7 @@ mod amount { #[cfg(test)] mod tests { + #![allow(clippy::unwrap_used)] use super::*; #[test] diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs index 77288eccfa..14abcc9f9d 100644 --- a/crates/api_models/src/refunds.rs +++ b/crates/api_models/src/refunds.rs @@ -34,30 +34,23 @@ pub struct RefundResponse { pub error_message: Option, } -#[derive(Debug, Eq, Clone, PartialEq, Deserialize, Serialize)] +#[derive(Debug, Eq, Clone, PartialEq, Default, Deserialize, Serialize)] #[serde(rename_all = "snake_case")] pub enum RefundStatus { Succeeded, Failed, + #[default] Pending, Review, } -impl Default for RefundStatus { - fn default() -> Self { - RefundStatus::Pending - } -} - impl From for RefundStatus { fn from(status: enums::RefundStatus) -> Self { match status { - enums::RefundStatus::Failure | enums::RefundStatus::TransactionFailure => { - RefundStatus::Failed - } - enums::RefundStatus::ManualReview => RefundStatus::Review, - enums::RefundStatus::Pending => RefundStatus::Pending, - enums::RefundStatus::Success => RefundStatus::Succeeded, + enums::RefundStatus::Failure | enums::RefundStatus::TransactionFailure => Self::Failed, + enums::RefundStatus::ManualReview => Self::Review, + enums::RefundStatus::Pending => Self::Pending, + enums::RefundStatus::Success => Self::Succeeded, } } } diff --git a/crates/common_utils/src/ext_traits.rs b/crates/common_utils/src/ext_traits.rs index 808381cd3e..76162a12d7 100644 --- a/crates/common_utils/src/ext_traits.rs +++ b/crates/common_utils/src/ext_traits.rs @@ -26,7 +26,7 @@ where fn convert_and_encode(&'e self) -> CustomResult where P: TryFrom<&'e Self> + Serialize, - Result>::Error>: error_stack::ResultExt, + Result>::Error>: ResultExt, >::Error> as ResultExt>::Ok: Serialize; /// @@ -37,7 +37,7 @@ where fn convert_and_url_encode(&'e self) -> CustomResult where P: TryFrom<&'e Self> + Serialize, - Result>::Error>: error_stack::ResultExt, + Result>::Error>: ResultExt, >::Error> as ResultExt>::Ok: Serialize; /// @@ -68,7 +68,7 @@ where /// /// Functionality, for specifically encoding `Self` into `Vec` /// after serialization by using `serde::Serialize` - /// + /// fn encode_to_vec(&'e self) -> CustomResult, errors::ParsingError> where Self: Serialize; @@ -81,7 +81,7 @@ where fn convert_and_encode(&'e self) -> CustomResult where P: TryFrom<&'e Self> + Serialize, - Result>::Error>: error_stack::ResultExt, + Result>::Error>: ResultExt, >::Error> as ResultExt>::Ok: Serialize, { serde_json::to_string(&P::try_from(self).change_context(errors::ParsingError)?) @@ -93,7 +93,7 @@ where fn convert_and_url_encode(&'e self) -> CustomResult where P: TryFrom<&'e Self> + Serialize, - Result>::Error>: error_stack::ResultExt, + Result>::Error>: ResultExt, >::Error> as ResultExt>::Ok: Serialize, { serde_urlencoded::to_string(&P::try_from(self).change_context(errors::ParsingError)?) @@ -303,7 +303,7 @@ pub trait AsyncExt { } #[async_trait::async_trait] -impl AsyncExt for Result { +impl AsyncExt for Result { type WrappedSelf = Result; async fn async_and_then(self, func: F) -> Self::WrappedSelf where @@ -329,7 +329,7 @@ impl AsyncExt for Result AsyncExt for Option { +impl AsyncExt for Option { type WrappedSelf = Option; async fn async_and_then(self, func: F) -> Self::WrappedSelf where diff --git a/crates/common_utils/src/lib.rs b/crates/common_utils/src/lib.rs index 2329ddb375..8ba8aa195a 100644 --- a/crates/common_utils/src/lib.rs +++ b/crates/common_utils/src/lib.rs @@ -1,18 +1,5 @@ #![forbid(unsafe_code)] -#![warn( - missing_docs, - rust_2018_idioms, - missing_debug_implementations, - clippy::expect_used, - clippy::missing_panics_doc, - clippy::panic, - clippy::panic_in_result_fn, - clippy::panicking_unwrap, - clippy::unreachable, - clippy::unwrap_in_result, - clippy::unwrap_used, - clippy::unimplemented -)] +#![warn(missing_docs, missing_debug_implementations)] #![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR" ), "/", "README.md"))] pub mod consts; diff --git a/crates/drainer/src/connection.rs b/crates/drainer/src/connection.rs index 209c7e01c1..74d2c20596 100644 --- a/crates/drainer/src/connection.rs +++ b/crates/drainer/src/connection.rs @@ -1,4 +1,3 @@ -use async_bb8_diesel::ConnectionManager; use bb8::PooledConnection; use diesel::PgConnection; @@ -27,7 +26,9 @@ pub async fn diesel_make_pg_pool(database: &Database, _test_transaction: bool) - } #[allow(clippy::expect_used)] -pub async fn pg_connection(pool: &PgPool) -> PooledConnection> { +pub async fn pg_connection( + pool: &PgPool, +) -> PooledConnection<'_, async_bb8_diesel::ConnectionManager> { pool.get() .await .expect("Couldn't retrieve PostgreSQL connection") diff --git a/crates/drainer/src/lib.rs b/crates/drainer/src/lib.rs index a11b374d9b..23db8e4bce 100644 --- a/crates/drainer/src/lib.rs +++ b/crates/drainer/src/lib.rs @@ -100,7 +100,10 @@ async fn drainer( macro_util::handle_resp!(a.orig.update(&conn, a.update_data).await, "up", "ref") } }, - kv::DBOperation::Delete => todo!(), + kv::DBOperation::Delete => { + // TODO: Implement this + println!("Not implemented!"); + } }; } diff --git a/crates/drainer/src/main.rs b/crates/drainer/src/main.rs index 739d7c6448..4475544334 100644 --- a/crates/drainer/src/main.rs +++ b/crates/drainer/src/main.rs @@ -5,7 +5,10 @@ use structopt::StructOpt; async fn main() -> DrainerResult<()> { // Get configuration let cmd_line = settings::CmdLineConf::from_args(); - let conf = settings::Settings::with_config_path(cmd_line.config_path).unwrap(); + + #[allow(clippy::expect_used)] + let conf = settings::Settings::with_config_path(cmd_line.config_path) + .expect("Unable to construct application configuration"); let store = services::Store::new(&conf, false).await; let store = std::sync::Arc::new(store); diff --git a/crates/masking/src/lib.rs b/crates/masking/src/lib.rs index f967572766..d0452d5c5b 100644 --- a/crates/masking/src/lib.rs +++ b/crates/masking/src/lib.rs @@ -1,20 +1,7 @@ #![cfg_attr(docsrs, feature(doc_auto_cfg, doc_cfg_hide))] #![cfg_attr(docsrs, doc(cfg_hide(doc)))] #![forbid(unsafe_code)] -#![warn( - missing_docs, - rust_2018_idioms, - unused_qualifications, - clippy::expect_used, - clippy::missing_panics_doc, - clippy::panic, - clippy::panic_in_result_fn, - clippy::panicking_unwrap, - clippy::unreachable, - clippy::unwrap_in_result, - clippy::unwrap_used, - clippy::use_self -)] +#![warn(missing_docs)] //! //! Personal Identifiable Information protection. Wrapper types and traits for secret management which help ensure they aren't accidentally copied, logged, or otherwise exposed (as much as possible), and also ensure secrets are securely wiped from memory when dropped. diff --git a/crates/masking/tests/basic.rs b/crates/masking/tests/basic.rs index 32f4bbedbf..59bb2cefaa 100644 --- a/crates/masking/tests/basic.rs +++ b/crates/masking/tests/basic.rs @@ -1,4 +1,4 @@ -#![allow(dead_code)] +#![allow(dead_code, clippy::unwrap_used, clippy::panic_in_result_fn)] use masking as pii; diff --git a/crates/redis_interface/src/commands.rs b/crates/redis_interface/src/commands.rs index 7e733473df..58d6122522 100644 --- a/crates/redis_interface/src/commands.rs +++ b/crates/redis_interface/src/commands.rs @@ -75,7 +75,7 @@ impl super::RedisConnectionPool { let serialized = Encode::::encode_to_vec(&value) .change_context(errors::RedisError::JsonSerializationFailed)?; - self.set_key(key, &serialized as &[u8]).await + self.set_key(key, serialized.as_slice()).await } #[instrument(level = "DEBUG", skip(self))] @@ -242,7 +242,7 @@ impl super::RedisConnectionPool { let serialized = Encode::::encode_to_vec(&value) .change_context(errors::RedisError::JsonSerializationFailed)?; - self.set_hash_field_if_not_exist(key, field, &serialized as &[u8]) + self.set_hash_field_if_not_exist(key, field, serialized.as_slice()) .await } @@ -561,6 +561,7 @@ impl super::RedisConnectionPool { #[cfg(test)] mod tests { + #![allow(clippy::unwrap_used)] use crate::{errors::RedisError, RedisConnectionPool, RedisEntryId, RedisSettings}; diff --git a/crates/redis_interface/src/lib.rs b/crates/redis_interface/src/lib.rs index fec2f9d1e1..3a0c4164a1 100644 --- a/crates/redis_interface/src/lib.rs +++ b/crates/redis_interface/src/lib.rs @@ -38,7 +38,7 @@ impl RedisConnectionPool { /// /// Panics if a connection to Redis is not successful. #[allow(clippy::expect_used)] - pub async fn new(conf: &types::RedisSettings) -> Self { + pub async fn new(conf: &RedisSettings) -> Self { let redis_connection_url = match conf.cluster_enabled { // Fred relies on this format for specifying cluster where the host port is ignored & only query parameters are used for node addresses // redis-cluster://username:password@host:port?node=bar.com:30002&node=baz.com:30003 @@ -100,8 +100,8 @@ struct RedisConfig { default_stream_read_count: u64, } -impl From<&types::RedisSettings> for RedisConfig { - fn from(config: &types::RedisSettings) -> Self { +impl From<&RedisSettings> for RedisConfig { + fn from(config: &RedisSettings) -> Self { Self { default_ttl: config.default_ttl, default_stream_read_count: config.stream_read_count, diff --git a/crates/redis_interface/src/types.rs b/crates/redis_interface/src/types.rs index ba4b1b8455..76060d0219 100644 --- a/crates/redis_interface/src/types.rs +++ b/crates/redis_interface/src/types.rs @@ -49,36 +49,32 @@ pub enum RedisEntryId { impl From for fred::types::XID { fn from(id: RedisEntryId) -> Self { - use fred::types::XID; - match id { RedisEntryId::UserSpecifiedID { milliseconds, sequence_number, - } => XID::Manual(fred::bytes_utils::format_bytes!( + } => Self::Manual(fred::bytes_utils::format_bytes!( "{milliseconds}-{sequence_number}" )), - RedisEntryId::AutoGeneratedID => XID::Auto, - RedisEntryId::AfterLastID => XID::Max, - RedisEntryId::UndeliveredEntryID => XID::NewInGroup, + RedisEntryId::AutoGeneratedID => Self::Auto, + RedisEntryId::AfterLastID => Self::Max, + RedisEntryId::UndeliveredEntryID => Self::NewInGroup, } } } impl From<&RedisEntryId> for fred::types::XID { fn from(id: &RedisEntryId) -> Self { - use fred::types::XID; - match id { RedisEntryId::UserSpecifiedID { milliseconds, sequence_number, - } => XID::Manual(fred::bytes_utils::format_bytes!( + } => Self::Manual(fred::bytes_utils::format_bytes!( "{milliseconds}-{sequence_number}" )), - RedisEntryId::AutoGeneratedID => XID::Auto, - RedisEntryId::AfterLastID => XID::Max, - RedisEntryId::UndeliveredEntryID => XID::NewInGroup, + RedisEntryId::AutoGeneratedID => Self::Auto, + RedisEntryId::AfterLastID => Self::Max, + RedisEntryId::UndeliveredEntryID => Self::NewInGroup, } } } diff --git a/crates/router/src/bin/router.rs b/crates/router/src/bin/router.rs index 9fcecfcdb3..94b423ebd8 100644 --- a/crates/router/src/bin/router.rs +++ b/crates/router/src/bin/router.rs @@ -9,11 +9,16 @@ use structopt::StructOpt; async fn main() -> BachResult<()> { // get commandline config before initializing config let cmd_line = CmdLineConf::from_args(); - let conf = Settings::with_config_path(cmd_line.config_path).unwrap(); + + #[allow(clippy::expect_used)] + let conf = Settings::with_config_path(cmd_line.config_path) + .expect("Unable to construct application configuration"); + let _guard = logger::setup(&conf.log)?; logger::info!("Application started [{:?}] [{:?}]", conf.server, conf.log); + #[allow(clippy::expect_used)] let (server, mut state) = router::start_server(conf) .await .expect("Failed to create the server"); diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs index 7d75354244..365d922d64 100644 --- a/crates/router/src/bin/scheduler.rs +++ b/crates/router/src/bin/scheduler.rs @@ -15,7 +15,11 @@ async fn main() -> CustomResult<(), errors::ProcessTrackerError> { // console_subscriber::init(); let cmd_line = CmdLineConf::from_args(); - let conf = Settings::with_config_path(cmd_line.config_path).unwrap(); + + #[allow(clippy::expect_used)] + let conf = Settings::with_config_path(cmd_line.config_path) + .expect("Unable to construct application configuration"); + let mut state = routes::AppState::new(conf).await; let _guard = logger::setup(&state.conf.log).map_err(|_| errors::ProcessTrackerError::UnexpectedFlow)?; @@ -57,8 +61,12 @@ async fn start_scheduler( }, }; + #[allow(clippy::expect_used)] let flow = std::env::var(SCHEDULER_FLOW).expect("SCHEDULER_FLOW environment variable not set"); - let flow = scheduler::SchedulerFlow::from_str(&flow).unwrap(); + #[allow(clippy::expect_used)] + let flow = scheduler::SchedulerFlow::from_str(&flow) + .expect("Unable to parse SchedulerFlow from environment variable"); + let scheduler_settings = state .conf .scheduler diff --git a/crates/router/src/compatibility/stripe/customers/types.rs b/crates/router/src/compatibility/stripe/customers/types.rs index 86bc030334..d8d4402fa8 100644 --- a/crates/router/src/compatibility/stripe/customers/types.rs +++ b/crates/router/src/compatibility/stripe/customers/types.rs @@ -1,9 +1,10 @@ use std::{convert::From, default::Default}; +use common_utils::date_time; use masking; use serde::{Deserialize, Serialize}; -use crate::{pii, types::api}; +use crate::{logger, pii, types::api}; #[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)] pub struct CustomerAddress { @@ -90,7 +91,18 @@ impl From for CreateCustomerResponse { Self { id: cust.customer_id, object: "customer".to_owned(), - created: cust.created_at.assume_utc().unix_timestamp() as u64, + created: u64::try_from(cust.created_at.assume_utc().unix_timestamp()).unwrap_or_else( + |error| { + logger::error!( + %error, + "incorrect value for `customer.created_at` provided {}", cust.created_at + ); + // Current timestamp converted to Unix timestamp should have a positive value + // for many years to come + u64::try_from(date_time::now().assume_utc().unix_timestamp()) + .unwrap_or_default() + }, + ), description: cust.description, email: cust.email, metadata: cust.metadata, diff --git a/crates/router/src/connection.rs b/crates/router/src/connection.rs index 9a5d921f2c..12d0bb72b9 100644 --- a/crates/router/src/connection.rs +++ b/crates/router/src/connection.rs @@ -1,4 +1,4 @@ -use async_bb8_diesel::{AsyncConnection, ConnectionError, ConnectionManager}; +use async_bb8_diesel::{AsyncConnection, ConnectionError}; use bb8::{CustomizeConnection, PooledConnection}; use diesel::PgConnection; @@ -51,7 +51,9 @@ pub async fn diesel_make_pg_pool(database: &Database, test_transaction: bool) -> } #[allow(clippy::expect_used)] -pub async fn pg_connection(pool: &PgPool) -> PooledConnection> { +pub async fn pg_connection( + pool: &PgPool, +) -> PooledConnection<'_, async_bb8_diesel::ConnectionManager> { pool.get() .await .expect("Couldn't retrieve PostgreSQL connection") diff --git a/crates/router/src/connector/aci.rs b/crates/router/src/connector/aci.rs index e4cbec17f3..5b7569e9c6 100644 --- a/crates/router/src/connector/aci.rs +++ b/crates/router/src/connector/aci.rs @@ -21,7 +21,7 @@ use crate::{ #[derive(Debug, Clone)] pub struct Aci; -impl api::ConnectorCommon for Aci { +impl ConnectorCommon for Aci { fn id(&self) -> &'static str { "aci" } diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index 312231a29d..b3267138a3 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -25,7 +25,7 @@ use crate::{ #[derive(Debug, Clone)] pub struct Adyen; -impl api::ConnectorCommon for Adyen { +impl ConnectorCommon for Adyen { fn id(&self) -> &'static str { "adyen" } diff --git a/crates/router/src/connector/applepay.rs b/crates/router/src/connector/applepay.rs index 3f6bfb04ad..28ea11130d 100644 --- a/crates/router/src/connector/applepay.rs +++ b/crates/router/src/connector/applepay.rs @@ -21,7 +21,7 @@ use crate::{ #[derive(Debug, Clone)] pub struct Applepay; -impl api::ConnectorCommon for Applepay { +impl ConnectorCommon for Applepay { fn id(&self) -> &'static str { "applepay" } diff --git a/crates/router/src/connector/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs index 8be464900e..ee6c82e3ac 100644 --- a/crates/router/src/connector/authorizedotnet.rs +++ b/crates/router/src/connector/authorizedotnet.rs @@ -23,7 +23,7 @@ use crate::{ #[derive(Debug, Clone)] pub struct Authorizedotnet; -impl api::ConnectorCommon for Authorizedotnet { +impl ConnectorCommon for Authorizedotnet { fn id(&self) -> &'static str { "authorizedotnet" } diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index a76a11b85c..01a03eecdf 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -192,18 +192,29 @@ impl TryFrom<&types::PaymentsCancelRouterData> for CancelTransactionRequest { } } -#[derive( - Debug, Clone, Default, PartialEq, Eq, serde_repr::Serialize_repr, serde_repr::Deserialize_repr, -)] -#[repr(u8)] -pub enum AuthorizedotnetPaymentStatus { - Approved = 1, - Declined = 2, - Error = 3, - #[default] - HeldForReview = 4, +// Safety: Enum as u8 conversions, we are specifying discriminants which are well within the range +// of u8 +#[allow(clippy::as_conversions)] +mod status { + #[derive( + Debug, + Clone, + Default, + PartialEq, + Eq, + serde_repr::Serialize_repr, + serde_repr::Deserialize_repr, + )] + #[repr(u8)] + pub enum AuthorizedotnetPaymentStatus { + Approved = 1, + Declined = 2, + Error = 3, + #[default] + HeldForReview = 4, + } } - +pub use status::AuthorizedotnetPaymentStatus; pub type AuthorizedotnetRefundStatus = AuthorizedotnetPaymentStatus; impl From for enums::AttemptStatus { @@ -378,8 +389,8 @@ impl TryFrom<&types::RefundsRouterData> for CreateRefundRequest { } } -impl From for enums::RefundStatus { - fn from(item: self::AuthorizedotnetRefundStatus) -> Self { +impl From for enums::RefundStatus { + fn from(item: AuthorizedotnetRefundStatus) -> Self { match item { AuthorizedotnetPaymentStatus::Approved => Self::Success, AuthorizedotnetPaymentStatus::Declined | AuthorizedotnetPaymentStatus::Error => { diff --git a/crates/router/src/connector/braintree.rs b/crates/router/src/connector/braintree.rs index 28e32c6c86..6808b9a415 100644 --- a/crates/router/src/connector/braintree.rs +++ b/crates/router/src/connector/braintree.rs @@ -24,7 +24,7 @@ use crate::{ #[derive(Debug, Clone)] pub struct Braintree; -impl api::ConnectorCommon for Braintree { +impl ConnectorCommon for Braintree { fn id(&self) -> &'static str { "braintree" } diff --git a/crates/router/src/connector/checkout.rs b/crates/router/src/connector/checkout.rs index 726a6c59c8..76afcdc2d0 100644 --- a/crates/router/src/connector/checkout.rs +++ b/crates/router/src/connector/checkout.rs @@ -26,7 +26,7 @@ use crate::{ #[derive(Debug, Clone)] pub struct Checkout; -impl api::ConnectorCommon for Checkout { +impl ConnectorCommon for Checkout { fn id(&self) -> &'static str { "checkout" } diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs index 01703125aa..e400d8b386 100644 --- a/crates/router/src/connector/klarna.rs +++ b/crates/router/src/connector/klarna.rs @@ -21,7 +21,7 @@ use crate::{ #[derive(Debug, Clone)] pub struct Klarna; -impl api::ConnectorCommon for Klarna { +impl ConnectorCommon for Klarna { fn id(&self) -> &'static str { "klarna" } diff --git a/crates/router/src/connector/shift4.rs b/crates/router/src/connector/shift4.rs index 4ba448dec7..4bb8d72d8a 100644 --- a/crates/router/src/connector/shift4.rs +++ b/crates/router/src/connector/shift4.rs @@ -27,7 +27,7 @@ use crate::{ #[derive(Debug, Clone)] pub struct Shift4; -impl api::ConnectorCommonExt for Shift4 +impl ConnectorCommonExt for Shift4 where Self: ConnectorIntegration, { @@ -50,7 +50,7 @@ where Ok(headers) } } -impl api::ConnectorCommon for Shift4 { +impl ConnectorCommon for Shift4 { fn id(&self) -> &'static str { "shift4" } @@ -95,29 +95,20 @@ impl api::ConnectorCommon for Shift4 { impl api::Payment for Shift4 {} impl api::PreVerify for Shift4 {} -impl - services::ConnectorIntegration< - api::Verify, - types::VerifyRequestData, - types::PaymentsResponseData, - > for Shift4 +impl ConnectorIntegration + for Shift4 { } impl api::PaymentVoid for Shift4 {} -impl - services::ConnectorIntegration< - api::Void, - types::PaymentsCancelData, - types::PaymentsResponseData, - > for Shift4 +impl ConnectorIntegration + for Shift4 { } impl api::PaymentSync for Shift4 {} -impl - services::ConnectorIntegration +impl ConnectorIntegration for Shift4 { fn get_headers( @@ -190,12 +181,8 @@ impl impl api::PaymentCapture for Shift4 {} -impl - services::ConnectorIntegration< - api::Capture, - types::PaymentsCaptureData, - types::PaymentsResponseData, - > for Shift4 +impl ConnectorIntegration + for Shift4 { fn get_headers( &self, @@ -264,24 +251,16 @@ impl impl api::PaymentSession for Shift4 {} -impl - services::ConnectorIntegration< - api::Session, - types::PaymentsSessionData, - types::PaymentsResponseData, - > for Shift4 +impl ConnectorIntegration + for Shift4 { //TODO: implement sessions flow } impl api::PaymentAuthorize for Shift4 {} -impl - services::ConnectorIntegration< - api::Authorize, - types::PaymentsAuthorizeData, - types::PaymentsResponseData, - > for Shift4 +impl ConnectorIntegration + for Shift4 { fn get_headers( &self, @@ -358,9 +337,7 @@ impl api::Refund for Shift4 {} impl api::RefundExecute for Shift4 {} impl api::RefundSync for Shift4 {} -impl services::ConnectorIntegration - for Shift4 -{ +impl ConnectorIntegration for Shift4 { fn get_headers( &self, req: &types::RefundsRouterData, @@ -430,9 +407,7 @@ impl services::ConnectorIntegration - for Shift4 -{ +impl ConnectorIntegration for Shift4 { fn get_headers( &self, req: &types::RefundSyncRouterData, diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs index dbcd99afaf..e7d3439d38 100644 --- a/crates/router/src/connector/shift4/transformers.rs +++ b/crates/router/src/connector/shift4/transformers.rs @@ -181,8 +181,8 @@ impl TryFrom<&types::RefundsRouterData> for Shift4RefundRequest { } } -impl From for enums::RefundStatus { - fn from(item: self::Shift4RefundStatus) -> Self { +impl From for enums::RefundStatus { + fn from(item: Shift4RefundStatus) -> Self { match item { self::Shift4RefundStatus::Successful => Self::Success, self::Shift4RefundStatus::Failed => Self::Failure, diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs index 2d202bab10..5df5b323d8 100644 --- a/crates/router/src/connector/stripe.rs +++ b/crates/router/src/connector/stripe.rs @@ -26,7 +26,7 @@ use crate::{ #[derive(Debug, Clone)] pub struct Stripe; -impl api::ConnectorCommon for Stripe { +impl ConnectorCommon for Stripe { fn id(&self) -> &'static str { "stripe" } diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 204726a87e..22f711bb91 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -528,8 +528,8 @@ pub enum RefundStatus { RequiresAction, } -impl From for enums::RefundStatus { - fn from(item: self::RefundStatus) -> Self { +impl From for enums::RefundStatus { + fn from(item: RefundStatus) -> Self { match item { self::RefundStatus::Succeeded => Self::Success, self::RefundStatus::Failed => Self::Failure, diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs index 9af3f0b33c..e09e2ffd66 100644 --- a/crates/router/src/core/errors.rs +++ b/crates/router/src/core/errors.rs @@ -4,7 +4,7 @@ pub(crate) mod utils; use std::fmt::Display; -use actix_web::{body::BoxBody, http::StatusCode, HttpResponse, ResponseError}; +use actix_web::{body::BoxBody, http::StatusCode, ResponseError}; pub use common_utils::errors::{CustomResult, ParsingError, ValidationError}; use config::ConfigError; use error_stack; @@ -24,7 +24,7 @@ pub type BachResponse = BachResult>; macro_rules! impl_error_display { ($st: ident, $arg: tt) => { - impl std::fmt::Display for $st { + impl Display for $st { fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!( fmt, @@ -224,7 +224,7 @@ impl ResponseError for BachError { } } -pub fn http_not_implemented() -> HttpResponse { +pub fn http_not_implemented() -> actix_web::HttpResponse { ApiErrorResponse::NotImplemented.error_response() } diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 6634ee05a6..b10478a1ad 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -21,10 +21,7 @@ use self::{ }; use super::errors::StorageErrorExt; use crate::{ - core::{ - errors::{self, RouterResponse, RouterResult}, - payments, - }, + core::errors::{self, RouterResponse, RouterResult}, db::StorageInterface, logger, pii, routes::AppState, @@ -62,9 +59,9 @@ where // To perform router related operation for PaymentResponse PaymentResponse: Operation, - FData: std::marker::Send, + FData: Send, { - let operation: BoxedOperation = Box::new(operation); + let operation: BoxedOperation<'_, F, Req> = Box::new(operation); let (operation, validate_result) = operation .to_validate_request()? @@ -184,7 +181,7 @@ pub async fn payments_core( ) -> RouterResponse where F: Send + Clone, - FData: std::marker::Send, + FData: Send, Op: Operation + Send + Sync + Clone, Req: Debug, Res: transformers::ToResponse, Op> + From, @@ -289,7 +286,7 @@ pub async fn payments_response_for_redirection_flows<'a>( payments_core::( state, merchant_account, - payments::PaymentStatus, + PaymentStatus, req, services::api::AuthFlow::Merchant, None, @@ -488,7 +485,7 @@ pub fn if_not_create_change_operation<'a, Op, F>( status: storage_enums::IntentStatus, confirm: Option, current: &'a Op, -) -> BoxedOperation +) -> BoxedOperation<'_, F, api::PaymentsRequest> where F: Send + Clone, Op: Operation + Send + Sync, @@ -515,7 +512,7 @@ where pub fn is_confirm<'a, F: Clone + Send, R, Op>( operation: &'a Op, confirm: Option, -) -> BoxedOperation +) -> BoxedOperation<'_, F, R> where PaymentConfirm: Operation, &'a PaymentConfirm: Operation, diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 3ddf928c04..da0286498b 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -38,7 +38,7 @@ pub trait Feature { storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult where - Self: std::marker::Sized, + Self: Sized, F: Clone, dyn api::Connector: services::ConnectorIntegration; } diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs index 2d9189f81b..e36007772d 100644 --- a/crates/router/src/core/payments/flows/authorize_flow.rs +++ b/crates/router/src/core/payments/flows/authorize_flow.rs @@ -13,7 +13,6 @@ use crate::{ types::{ self, api, storage::{self, enums as storage_enums}, - PaymentsAuthorizeData, PaymentsAuthorizeRouterData, PaymentsResponseData, }, }; @@ -74,7 +73,7 @@ impl Feature for types::PaymentsAu } } -impl PaymentsAuthorizeRouterData { +impl types::PaymentsAuthorizeRouterData { pub async fn decide_flow<'a, 'b>( &'b self, state: &'a AppState, @@ -87,9 +86,10 @@ impl PaymentsAuthorizeRouterData { match confirm { Some(true) => { let connector_integration: services::BoxedConnectorIntegration< + '_, api::Authorize, - PaymentsAuthorizeData, - PaymentsResponseData, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, > = connector.connector.get_connector_integration(); let resp = services::execute_connector_processing_step( state, diff --git a/crates/router/src/core/payments/flows/cancel_flow.rs b/crates/router/src/core/payments/flows/cancel_flow.rs index ad7458e94a..e54f5a970b 100644 --- a/crates/router/src/core/payments/flows/cancel_flow.rs +++ b/crates/router/src/core/payments/flows/cancel_flow.rs @@ -11,7 +11,6 @@ use crate::{ types::{ self, api, storage::{self, enums}, - PaymentsCancelRouterData, PaymentsResponseData, }, }; @@ -24,7 +23,7 @@ impl ConstructFlowSpecificData RouterResult { + ) -> RouterResult { transformers::construct_payment_router_data::( state, self.clone(), @@ -58,7 +57,7 @@ impl Feature } } -impl PaymentsCancelRouterData { +impl types::PaymentsCancelRouterData { #[allow(clippy::too_many_arguments)] pub async fn decide_flow<'a, 'b>( &'b self, @@ -69,9 +68,10 @@ impl PaymentsCancelRouterData { call_connector_action: payments::CallConnectorAction, ) -> RouterResult { let connector_integration: services::BoxedConnectorIntegration< + '_, api::Void, types::PaymentsCancelData, - PaymentsResponseData, + types::PaymentsResponseData, > = connector.connector.get_connector_integration(); let resp = services::execute_connector_processing_step( state, diff --git a/crates/router/src/core/payments/flows/capture_flow.rs b/crates/router/src/core/payments/flows/capture_flow.rs index 469308e888..1fc736bccc 100644 --- a/crates/router/src/core/payments/flows/capture_flow.rs +++ b/crates/router/src/core/payments/flows/capture_flow.rs @@ -11,7 +11,6 @@ use crate::{ types::{ self, api, storage::{self, enums}, - PaymentsCaptureData, PaymentsCaptureRouterData, PaymentsResponseData, }, }; @@ -25,7 +24,7 @@ impl state: &AppState, connector_id: &str, merchant_account: &storage::MerchantAccount, - ) -> RouterResult { + ) -> RouterResult { transformers::construct_payment_router_data::( state, self.clone(), @@ -59,7 +58,7 @@ impl Feature } } -impl PaymentsCaptureRouterData { +impl types::PaymentsCaptureRouterData { #[allow(clippy::too_many_arguments)] pub async fn decide_flow<'a, 'b>( &'b self, @@ -70,9 +69,10 @@ impl PaymentsCaptureRouterData { call_connector_action: payments::CallConnectorAction, ) -> RouterResult { let connector_integration: services::BoxedConnectorIntegration< + '_, api::Capture, - PaymentsCaptureData, - PaymentsResponseData, + types::PaymentsCaptureData, + types::PaymentsResponseData, > = connector.connector.get_connector_integration(); let resp = services::execute_connector_processing_step( state, diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs index e8240e5326..1e471b593b 100644 --- a/crates/router/src/core/payments/flows/psync_flow.rs +++ b/crates/router/src/core/payments/flows/psync_flow.rs @@ -11,7 +11,6 @@ use crate::{ types::{ self, api, storage::{self, enums}, - PaymentsResponseData, PaymentsSyncData, PaymentsSyncRouterData, }, }; @@ -60,7 +59,7 @@ impl Feature } } -impl PaymentsSyncRouterData { +impl types::PaymentsSyncRouterData { pub async fn decide_flow<'a, 'b>( &'b self, state: &'a AppState, @@ -70,9 +69,10 @@ impl PaymentsSyncRouterData { call_connector_action: payments::CallConnectorAction, ) -> RouterResult { let connector_integration: services::BoxedConnectorIntegration< + '_, api::PSync, - PaymentsSyncData, - PaymentsResponseData, + types::PaymentsSyncData, + types::PaymentsResponseData, > = connector.connector.get_connector_integration(); let resp = services::execute_connector_processing_step( state, diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 52fea4646b..e76eb518a3 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -110,6 +110,7 @@ impl types::PaymentsSessionRouterData { api::GetToken::Metadata => create_gpay_session_token(self), api::GetToken::Connector => { let connector_integration: services::BoxedConnectorIntegration< + '_, api::Session, types::PaymentsSessionData, types::PaymentsResponseData, diff --git a/crates/router/src/core/payments/flows/verfiy_flow.rs b/crates/router/src/core/payments/flows/verfiy_flow.rs index e16caf0a4a..ef019350d4 100644 --- a/crates/router/src/core/payments/flows/verfiy_flow.rs +++ b/crates/router/src/core/payments/flows/verfiy_flow.rs @@ -70,6 +70,7 @@ impl types::VerifyRouterData { match confirm { Some(true) => { let connector_integration: services::BoxedConnectorIntegration< + '_, api::Verify, types::VerifyRequestData, types::PaymentsResponseData, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 1967fe41dc..b0e8b6c1e1 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -566,7 +566,7 @@ pub(crate) async fn call_payment_method( pub(crate) fn client_secret_auth

( payload: P, - auth_type: &services::api::MerchantAuthentication, + auth_type: &services::api::MerchantAuthentication<'_>, ) -> RouterResult

where P: services::Authenticate, @@ -1195,7 +1195,7 @@ pub fn make_url_with_signature( } pub fn hmac_sha256_sorted_query_params<'a>( - params: &mut [(Cow, Cow)], + params: &mut [(Cow<'_, str>, Cow<'_, str>)], key: &'a str, ) -> RouterResult { params.sort(); diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs index 2b6d4fa2be..fbd9e0d6ca 100644 --- a/crates/router/src/core/payments/operations.rs +++ b/crates/router/src/core/payments/operations.rs @@ -8,21 +8,18 @@ mod payment_session; mod payment_start; mod payment_status; mod payment_update; + use async_trait::async_trait; use error_stack::{report, ResultExt}; -pub use payment_cancel::PaymentCancel; -pub use payment_capture::PaymentCapture; -pub use payment_confirm::PaymentConfirm; -pub use payment_create::PaymentCreate; -pub use payment_method_validate::PaymentMethodValidate; -pub use payment_response::PaymentResponse; -pub use payment_session::PaymentSession; -pub use payment_start::PaymentStart; -pub use payment_status::PaymentStatus; -pub use payment_update::PaymentUpdate; use router_env::{instrument, tracing}; -use storage::Customer; +pub use self::{ + payment_cancel::PaymentCancel, payment_capture::PaymentCapture, + payment_confirm::PaymentConfirm, payment_create::PaymentCreate, + payment_method_validate::PaymentMethodValidate, payment_response::PaymentResponse, + payment_session::PaymentSession, payment_start::PaymentStart, payment_status::PaymentStatus, + payment_update::PaymentUpdate, +}; use super::{helpers, CustomerDetails, PaymentData}; use crate::{ core::errors::{self, CustomResult, RouterResult}, @@ -150,7 +147,7 @@ pub trait UpdateTracker: Send { db: &dyn StorageInterface, payment_id: &api::PaymentIdType, payment_data: D, - customer: Option, + customer: Option, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<(BoxedOperation<'b, F, Req>, D)> where diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs index 0c74ef8718..81620fb9e7 100644 --- a/crates/router/src/core/payments/operations/payment_capture.rs +++ b/crates/router/src/core/payments/operations/payment_capture.rs @@ -13,7 +13,7 @@ use crate::{ db::StorageInterface, routes::AppState, types::{ - api::{self, PaymentIdTypeExt, PaymentsCaptureRequest}, + api::{self, PaymentIdTypeExt}, storage::{self, enums}, transformers::ForeignInto, }, @@ -34,7 +34,7 @@ impl GetTracker, api::PaymentsCaptu state: &'a AppState, payment_id: &api::PaymentIdType, merchant_id: &str, - request: &PaymentsCaptureRequest, + request: &api::PaymentsCaptureRequest, _mandate_type: Option, storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<( diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index 239bfabef0..185889feaa 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -101,7 +101,6 @@ impl GetTracker, api::PaymentsSessionRequest> payment_intent.shipping_address_id = shipping_address.clone().map(|x| x.address_id); payment_intent.billing_address_id = billing_address.clone().map(|x| x.address_id); - let db = db as &dyn StorageInterface; let connector_response = db .find_connector_response_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index b3c12ff2bf..cf847caae4 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -16,7 +16,7 @@ use crate::{ routes::AppState, types::{ api::{self, enums as api_enums, PaymentIdTypeExt}, - storage::{self, enums, Customer}, + storage::{self, enums}, transformers::ForeignInto, }, utils::OptionExt, @@ -158,7 +158,7 @@ impl UpdateTracker, api::PaymentsStartRequest> for P _db: &dyn StorageInterface, _payment_id: &api::PaymentIdType, payment_data: PaymentData, - _customer: Option, + _customer: Option, _storage_scheme: enums::MerchantStorageScheme, ) -> RouterResult<( BoxedOperation<'b, F, api::PaymentsStartRequest>, diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index d0682df3c8..693a1f4ed8 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -109,7 +109,7 @@ impl Domain for PaymentStatus { &'a self, state: &'a AppState, payment_attempt: &storage::PaymentAttempt, - ) -> CustomResult<(), errors::ApiErrorResponse> { + ) -> CustomResult<(), ApiErrorResponse> { helpers::add_domain_task_to_pt(self, state, payment_attempt).await } @@ -118,7 +118,7 @@ impl Domain for PaymentStatus { merchant_account: &storage::MerchantAccount, state: &AppState, request_connector: Option, - ) -> CustomResult { + ) -> CustomResult { helpers::get_connector_default(merchant_account, state, request_connector).await } } diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 129ba54fe9..a9d1560b81 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -112,7 +112,6 @@ impl GetTracker, api::PaymentsRequest> for Pa payment_intent.shipping_address_id = shipping_address.clone().map(|x| x.address_id); payment_intent.billing_address_id = billing_address.clone().map(|x| x.address_id); - let db = db as &dyn StorageInterface; let connector_response = db .find_connector_response_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index eea134d453..7e96342450 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -13,8 +13,7 @@ use crate::{ routes::AppState, services::{self, RedirectForm}, types::{ - self, - api::{self, NextAction, PaymentsResponse}, + self, api, storage::{self, enums}, transformers::ForeignInto, }, @@ -32,8 +31,7 @@ where T: TryFrom>, types::RouterData: Feature, F: Clone, - error_stack::Report: - std::convert::From<>>::Error>, + error_stack::Report: From<>>::Error>, { //TODO: everytime parsing the json may have impact? @@ -260,10 +258,10 @@ where .map_err(|_| errors::ApiErrorResponse::InternalServerError)?; services::BachResponse::Form(form) } else { - let mut response: PaymentsResponse = request.into(); + let mut response: api::PaymentsResponse = request.into(); let mut next_action_response = None; if payment_intent.status == enums::IntentStatus::RequiresCustomerAction { - next_action_response = Some(NextAction { + next_action_response = Some(api::NextAction { next_action_type: api::NextActionType::RedirectToUrl, redirect_to_url: Some(helpers::create_startpay_url( server, @@ -342,7 +340,7 @@ where ) } } - None => services::BachResponse::Json(PaymentsResponse { + None => services::BachResponse::Json(api::PaymentsResponse { payment_id: Some(payment_attempt.payment_id), merchant_id: Some(payment_attempt.merchant_id), status: payment_intent.status.foreign_into(), diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index 9e7fcf55fd..8c5bd3669f 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -127,6 +127,7 @@ pub async fn trigger_refund_to_gateway( logger::debug!(?router_data); let connector_integration: services::BoxedConnectorIntegration< + '_, api::Execute, types::RefundsData, types::RefundsResponseData, @@ -268,6 +269,7 @@ pub async fn sync_refund_with_gateway( .await?; let connector_integration: services::BoxedConnectorIntegration< + '_, api::RSync, types::RefundsData, types::RefundsResponseData, diff --git a/crates/router/src/cors.rs b/crates/router/src/cors.rs index 5235d6b78f..07e12b0d3f 100644 --- a/crates/router/src/cors.rs +++ b/crates/router/src/cors.rs @@ -1,8 +1,7 @@ -use actix_cors::Cors; // use actix_web::http::header; pub fn cors() -> actix_cors::Cors { - Cors::permissive() // Warn : Never use in production + actix_cors::Cors::permissive() // FIXME : Never use in production /* .allowed_methods(vec!["GET", "POST", "PUT", "DELETE"]) diff --git a/crates/router/src/db/connector_response.rs b/crates/router/src/db/connector_response.rs index 6fe5d28205..b35e55b291 100644 --- a/crates/router/src/db/connector_response.rs +++ b/crates/router/src/db/connector_response.rs @@ -88,6 +88,7 @@ impl ConnectorResponseInterface for MockDb { ) -> CustomResult { let mut connector_response = self.connector_response.lock().await; let response = storage::ConnectorResponse { + #[allow(clippy::as_conversions)] id: connector_response.len() as i32, payment_id: new.payment_id, merchant_id: new.merchant_id, diff --git a/crates/router/src/db/customers.rs b/crates/router/src/db/customers.rs index accfc96859..234ded5b2d 100644 --- a/crates/router/src/db/customers.rs +++ b/crates/router/src/db/customers.rs @@ -153,6 +153,7 @@ impl CustomerInterface for MockDb { ) -> CustomResult { let mut customers = self.customers.lock().await; let customer = storage::Customer { + #[allow(clippy::as_conversions)] id: customers.len() as i32, customer_id: customer_data.customer_id, merchant_id: customer_data.merchant_id, diff --git a/crates/router/src/db/merchant_account.rs b/crates/router/src/db/merchant_account.rs index 750d8af5b9..d0e48d114e 100644 --- a/crates/router/src/db/merchant_account.rs +++ b/crates/router/src/db/merchant_account.rs @@ -122,6 +122,7 @@ impl MerchantAccountInterface for MockDb { ) -> CustomResult { let mut accounts = self.merchant_accounts.lock().await; let account = storage::MerchantAccount { + #[allow(clippy::as_conversions)] id: accounts.len() as i32, merchant_id: merchant_account.merchant_id, api_key: merchant_account.api_key, diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs index d422060632..347506c15d 100644 --- a/crates/router/src/db/merchant_connector_account.rs +++ b/crates/router/src/db/merchant_connector_account.rs @@ -163,6 +163,7 @@ impl MerchantConnectorAccountInterface for MockDb { ) -> CustomResult { let mut accounts = self.merchant_connector_accounts.lock().await; let account = storage::MerchantConnectorAccount { + #[allow(clippy::as_conversions)] id: accounts.len() as i32, merchant_id: t.merchant_id.unwrap_or_default(), connector_name: t.connector_name.unwrap_or_default(), diff --git a/crates/router/src/db/payment_attempt.rs b/crates/router/src/db/payment_attempt.rs index 52ae9ca32d..de6abb99ec 100644 --- a/crates/router/src/db/payment_attempt.rs +++ b/crates/router/src/db/payment_attempt.rs @@ -207,6 +207,7 @@ impl PaymentAttemptInterface for MockDb { _storage_scheme: enums::MerchantStorageScheme, ) -> CustomResult { let mut payment_attempts = self.payment_attempts.lock().await; + #[allow(clippy::as_conversions)] let id = payment_attempts.len() as i32; let time = common_utils::date_time::now(); diff --git a/crates/router/src/db/payment_intent.rs b/crates/router/src/db/payment_intent.rs index df170182a4..0149c24365 100644 --- a/crates/router/src/db/payment_intent.rs +++ b/crates/router/src/db/payment_intent.rs @@ -343,6 +343,7 @@ impl PaymentIntentInterface for MockDb { let mut payment_intents = self.payment_intents.lock().await; let time = common_utils::date_time::now(); let payment_intent = types::PaymentIntent { + #[allow(clippy::as_conversions)] id: payment_intents.len() as i32, payment_id: new.payment_id, merchant_id: new.merchant_id, diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs index abeaaff771..2cbb8cec7a 100644 --- a/crates/router/src/db/refund.rs +++ b/crates/router/src/db/refund.rs @@ -1,9 +1,8 @@ -use error_stack::Report; use storage_models::errors::DatabaseError; use super::MockDb; use crate::{ - core::errors::{self, CustomResult, StorageError}, + core::errors::{self, CustomResult}, types::storage::{self as storage_types, enums}, }; @@ -571,6 +570,7 @@ impl RefundInterface for MockDb { let current_time = common_utils::date_time::now(); let refund = storage_types::Refund { + #[allow(clippy::as_conversions)] id: refunds.len() as i32, internal_reference_id: new.internal_reference_id, refund_id: new.refund_id, @@ -638,9 +638,7 @@ impl RefundInterface for MockDb { .find(|refund| refund.merchant_id == merchant_id && refund.refund_id == refund_id) .cloned() .ok_or_else(|| { - Report::from(StorageError::DatabaseError(Report::from( - DatabaseError::NotFound, - ))) + errors::StorageError::DatabaseError(DatabaseError::NotFound.into()).into() }) } diff --git a/crates/router/src/db/temp_card.rs b/crates/router/src/db/temp_card.rs index 0b3af9cce4..15b998d283 100644 --- a/crates/router/src/db/temp_card.rs +++ b/crates/router/src/db/temp_card.rs @@ -87,6 +87,7 @@ impl TempCardInterface for MockDb { ) -> CustomResult { let mut cards = self.temp_cards.lock().await; let card = storage::TempCard { + #[allow(clippy::as_conversions)] id: cards.len() as i32, date_created: insert.date_created, txn_id: insert.txn_id, diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 5d1d8cde95..84252c835b 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -1,24 +1,4 @@ #![forbid(unsafe_code)] -// FIXME: I strongly advise to add this worning. -// #![warn(missing_docs)] - -// FIXME: I recommend to add these wornings too, although there is no harm if these wanrings will stay disabled. -// #![warn(rust_2018_idioms)] -// #![warn(missing_debug_implementations)] -#![warn( - // clippy::as_conversions, - clippy::expect_used, - // clippy::integer_arithmetic, - clippy::missing_panics_doc, - clippy::panic, - clippy::panic_in_result_fn, - clippy::panicking_unwrap, - clippy::todo, - clippy::unreachable, - clippy::unwrap_in_result, - clippy::unwrap_used, - clippy::use_self -)] #![recursion_limit = "256"] #[cfg(feature = "stripe")] diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index 868dc2fe75..dc726c654c 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -166,7 +166,7 @@ mod tests { #[test] fn test_custom_list_deserialization() { let dummy_data = "amount=120&recurring_enabled=true&installment_payment_enabled=true&accepted_countries=US&accepted_countries=IN"; - let de_query: web::Query = + let de_query: web::Query = web::Query::from_query(dummy_data).unwrap(); let de_struct = de_query.into_inner(); assert_eq!( diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs index bbc26431c0..97ba2c8fca 100644 --- a/crates/router/src/routes/refunds.rs +++ b/crates/router/src/routes/refunds.rs @@ -5,11 +5,7 @@ use router_env::{ }; use super::app::AppState; -use crate::{ - core::refunds::*, - services::api, - types::api::refunds::{self, RefundRequest}, -}; +use crate::{core::refunds::*, services::api, types::api::refunds}; #[instrument(skip_all, fields(flow = ?Flow::RefundsCreate))] // #[post("")] @@ -54,7 +50,7 @@ pub async fn refunds_retrieve( pub async fn refunds_update( state: web::Data, req: HttpRequest, - json_payload: web::Json, + json_payload: web::Json, path: web::Path, ) -> HttpResponse { let refund_id = path.into_inner(); diff --git a/crates/router/src/scheduler/producer.rs b/crates/router/src/scheduler/producer.rs index a190cf9104..791691c0bb 100644 --- a/crates/router/src/scheduler/producer.rs +++ b/crates/router/src/scheduler/producer.rs @@ -147,6 +147,9 @@ pub async fn fetch_producer_tasks( } new_tasks.append(&mut pending_tasks); + + // Safety: Assuming we won't deal with more than `u64::MAX` tasks at once + #[allow(clippy::as_conversions)] metrics::TASKS_PICKED_COUNT.add(&metrics::CONTEXT, new_tasks.len() as u64, &[]); Ok(new_tasks) } diff --git a/crates/router/src/scheduler/utils.rs b/crates/router/src/scheduler/utils.rs index e43f65ed4b..d8f409f94c 100644 --- a/crates/router/src/scheduler/utils.rs +++ b/crates/router/src/scheduler/utils.rs @@ -26,6 +26,8 @@ pub async fn divide_and_append_tasks( settings: &SchedulerSettings, ) -> CustomResult<(), errors::ProcessTrackerError> { let batches = divide(tasks, settings); + // Safety: Assuming we won't deal with more than `u64::MAX` batches at once + #[allow(clippy::as_conversions)] metrics::BATCHES_CREATED.add(&metrics::CONTEXT, batches.len() as u64, &[]); // Metrics for batch in batches { let result = update_status_and_append(state, flow, batch).await; diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 96a5c55908..52f1af5385 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -22,12 +22,12 @@ use crate::{ payments, }, db::StorageInterface, - logger, routes, + logger, routes::AppState, types::{ self, api, storage::{self, enums}, - ErrorResponse, Response, + ErrorResponse, }, utils::{self, OptionExt}, }; @@ -36,7 +36,7 @@ pub type BoxedConnectorIntegration<'a, T, Req, Resp> = Box<&'a (dyn ConnectorIntegration + Send + Sync)>; pub trait ConnectorIntegrationAny: Send + Sync + 'static { - fn get_connector_integration(&self) -> BoxedConnectorIntegration; + fn get_connector_integration(&self) -> BoxedConnectorIntegration<'_, T, Req, Resp>; } impl ConnectorIntegrationAny for S @@ -86,7 +86,7 @@ pub trait ConnectorIntegration: ConnectorIntegrationAny, - _res: Response, + _res: types::Response, ) -> CustomResult, errors::ConnectorError> where T: Clone, @@ -185,7 +185,7 @@ where pub(crate) async fn call_connector_api( state: &AppState, request: Request, -) -> CustomResult, errors::ApiClientError> { +) -> CustomResult, errors::ApiClientError> { let current_time = Instant::now(); let response = send_request(state, request).await; @@ -256,7 +256,7 @@ async fn send_request( #[instrument(skip_all)] async fn handle_response( response: CustomResult, -) -> CustomResult, errors::ApiClientError> { +) -> CustomResult, errors::ApiClientError> { response .map(|response| async { logger::info!(?response); @@ -272,7 +272,7 @@ async fn handle_response( .into_report() .change_context(errors::ApiClientError::ResponseDecodingFailed) .attach_printable("Error while waiting for response")?; - Ok(Ok(Response { + Ok(Ok(types::Response { response, status_code, })) @@ -308,7 +308,7 @@ async fn handle_response( }; Err(report!(error).attach_printable("Client error response received")) */ - Ok(Err(Response { + Ok(Err(types::Response { response: bytes, status_code, })) @@ -408,14 +408,14 @@ pub enum AuthFlow { Merchant, } -pub(crate) fn get_auth_flow(auth_type: &MerchantAuthentication) -> AuthFlow { +pub(crate) fn get_auth_flow(auth_type: &MerchantAuthentication<'_>) -> AuthFlow { match auth_type { MerchantAuthentication::ApiKey => AuthFlow::Merchant, _ => AuthFlow::Client, } } -pub(crate) fn get_auth_type(request: &HttpRequest) -> RouterResult { +pub(crate) fn get_auth_type(request: &HttpRequest) -> RouterResult> { let api_key = get_api_key(request).change_context(errors::ApiErrorResponse::Unauthorized)?; if api_key.starts_with("pk_") { Ok(MerchantAuthentication::PublishableKey) @@ -426,17 +426,17 @@ pub(crate) fn get_auth_type(request: &HttpRequest) -> RouterResult( - state: &'b routes::AppState, + state: &'b AppState, request: &'a HttpRequest, payload: T, func: F, api_authentication: ApiAuthentication<'a>, ) -> RouterResult> where - F: Fn(&'b routes::AppState, storage::MerchantAccount, T) -> Fut, + F: Fn(&'b AppState, storage::MerchantAccount, T) -> Fut, Fut: Future>, Q: Serialize + Debug + 'a, - T: std::fmt::Debug, + T: Debug, { let merchant_account = match api_authentication { ApiAuthentication::Merchant(merchant_auth) => { @@ -455,7 +455,7 @@ where fields(request_method, request_url_path) )] pub(crate) async fn server_wrap<'a, 'b, A, T, Q, F, Fut>( - state: &'b routes::AppState, + state: &'b AppState, request: &'a HttpRequest, payload: T, func: F, @@ -463,10 +463,10 @@ pub(crate) async fn server_wrap<'a, 'b, A, T, Q, F, Fut>( ) -> HttpResponse where A: Into> + Debug, - F: Fn(&'b routes::AppState, storage::MerchantAccount, T) -> Fut, + F: Fn(&'b AppState, storage::MerchantAccount, T) -> Fut, Fut: Future>>, Q: Serialize + Debug + 'a, - T: std::fmt::Debug, + T: Debug, { let api_authentication = api_authentication.into(); let request_method = request.method().as_str(); @@ -594,9 +594,9 @@ pub async fn authenticate_connector<'a>( } pub(crate) fn get_auth_type_and_check_client_secret

( - req: &actix_web::HttpRequest, + req: &HttpRequest, payload: P, -) -> RouterResult<(P, MerchantAuthentication)> +) -> RouterResult<(P, MerchantAuthentication<'_>)> where P: Authenticate, { @@ -608,7 +608,7 @@ where } pub(crate) async fn authenticate_eph_key<'a>( - req: &'a actix_web::HttpRequest, + req: &'a HttpRequest, store: &dyn StorageInterface, customer_id: String, ) -> RouterResult> { @@ -748,7 +748,7 @@ pub fn build_redirection_form(form: &RedirectForm) -> maud::Markup { } } - (maud::PreEscaped(r#""#)) + (PreEscaped(r#""#)) } } } diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index d390388b35..ff73559ad9 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -7,7 +7,7 @@ pub mod payments; pub mod refunds; pub mod webhooks; -use std::{fmt::Debug, marker, str::FromStr}; +use std::{fmt::Debug, str::FromStr}; use bytes::Bytes; use error_stack::{report, IntoReport, ResultExt}; @@ -88,7 +88,7 @@ impl; +type BoxedConnector = Box<&'static (dyn Connector + Sync)>; // Normal flow will call the connector and follow the flow specific operations (capture, authorize) // SessionTokenFromMetadata will avoid calling the connector instead create the session token ( for sdk ) diff --git a/crates/router/src/types/api/payment_methods.rs b/crates/router/src/types/api/payment_methods.rs index cc43782f9f..fb068b8a04 100644 --- a/crates/router/src/types/api/payment_methods.rs +++ b/crates/router/src/types/api/payment_methods.rs @@ -81,8 +81,8 @@ pub(crate) trait CreatePaymentMethodExt { the_subtype: Option, ) -> bool where - T: std::cmp::Eq + std::hash::Hash, - U: std::cmp::PartialEq; + T: Eq + std::hash::Hash, + U: PartialEq; } impl CreatePaymentMethodExt for CreatePaymentMethod { @@ -122,8 +122,8 @@ impl CreatePaymentMethodExt for CreatePaymentMethod { the_subtype: Option, ) -> bool where - T: std::cmp::Eq + std::hash::Hash, - U: std::cmp::PartialEq, + T: Eq + std::hash::Hash, + U: PartialEq, { let the_subtype = match the_subtype { Some(st) => st, diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs index 97975d6aca..661746e819 100644 --- a/crates/router/src/types/api/payments.rs +++ b/crates/router/src/types/api/payments.rs @@ -1,4 +1,3 @@ -use api_models::payments; pub use api_models::payments::{ AcceptanceType, Address, AddressDetails, Amount, AuthenticationForStartResponse, CCard, CustomerAcceptance, MandateData, MandateTxnType, MandateType, MandateValidationFields, @@ -115,7 +114,7 @@ impl MandateValidationFieldsExt for MandateValidationFields { impl From> for Foreign { fn from(item: Foreign) -> Self { let item = item.0; - payments::PaymentsResponse { + PaymentsResponse { payment_id: Some(item.payment_id), merchant_id: Some(item.merchant_id), status: item.status.foreign_into(), diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs index 9a63a821ae..526f1afbf3 100644 --- a/crates/router/src/utils.rs +++ b/crates/router/src/utils.rs @@ -47,7 +47,7 @@ pub mod error_parser { } impl ResponseError for CustomJsonError { - fn status_code(&self) -> reqwest::StatusCode { + fn status_code(&self) -> StatusCode { StatusCode::INTERNAL_SERVER_ERROR } diff --git a/crates/router/src/utils/storage_partitioning.rs b/crates/router/src/utils/storage_partitioning.rs index 7136b6d7cb..943b84d189 100644 --- a/crates/router/src/utils/storage_partitioning.rs +++ b/crates/router/src/utils/storage_partitioning.rs @@ -1,9 +1,9 @@ pub(crate) trait KvStorePartition { - fn partition_number(key: PartitionKey, num_partitions: u8) -> u32 { + fn partition_number(key: PartitionKey<'_>, num_partitions: u8) -> u32 { crc32fast::hash(key.to_string().as_bytes()) % u32::from(num_partitions) } - fn shard_key(key: PartitionKey, num_partitions: u8) -> String { + fn shard_key(key: PartitionKey<'_>, num_partitions: u8) -> String { format!("shard_{}", Self::partition_number(key, num_partitions)) } } diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index a8d8f85866..630107deab 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -108,6 +108,7 @@ async fn payments_create_success() { get_token: types::api::GetToken::Connector, }; let connector_integration: services::BoxedConnectorIntegration< + '_, types::api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData, @@ -140,6 +141,7 @@ async fn payments_create_failure() { get_token: types::api::GetToken::Connector, }; let connector_integration: services::BoxedConnectorIntegration< + '_, types::api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData, @@ -178,6 +180,7 @@ async fn refund_for_successful_payments() { }; let state = routes::AppState::with_storage(conf, StorageImpl::PostgresqlTest).await; let connector_integration: services::BoxedConnectorIntegration< + '_, types::api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData, @@ -196,6 +199,7 @@ async fn refund_for_successful_payments() { "The payment failed" ); let connector_integration: services::BoxedConnectorIntegration< + '_, types::api::Execute, types::RefundsData, types::RefundsResponseData, @@ -234,6 +238,7 @@ async fn refunds_create_failure() { }; let state = routes::AppState::with_storage(conf, StorageImpl::PostgresqlTest).await; let connector_integration: services::BoxedConnectorIntegration< + '_, types::api::Execute, types::RefundsData, types::RefundsResponseData, diff --git a/crates/router/tests/connectors/authorizedotnet.rs b/crates/router/tests/connectors/authorizedotnet.rs index 31feab732f..6b9fe6b67c 100644 --- a/crates/router/tests/connectors/authorizedotnet.rs +++ b/crates/router/tests/connectors/authorizedotnet.rs @@ -106,6 +106,7 @@ async fn payments_create_success() { get_token: types::api::GetToken::Connector, }; let connector_integration: services::BoxedConnectorIntegration< + '_, types::api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData, @@ -142,6 +143,7 @@ async fn payments_create_failure() { }; let state = routes::AppState::with_storage(conf, StorageImpl::PostgresqlTest).await; let connector_integration: services::BoxedConnectorIntegration< + '_, types::api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData, @@ -186,6 +188,7 @@ async fn refunds_create_success() { }; let state = routes::AppState::with_storage(conf, StorageImpl::PostgresqlTest).await; let connector_integration: services::BoxedConnectorIntegration< + '_, types::api::Execute, types::RefundsData, types::RefundsResponseData, @@ -222,6 +225,7 @@ async fn refunds_create_failure() { }; let state = routes::AppState::with_storage(conf, StorageImpl::PostgresqlTest).await; let connector_integration: services::BoxedConnectorIntegration< + '_, types::api::Execute, types::RefundsData, types::RefundsResponseData, diff --git a/crates/router/tests/connectors/checkout.rs b/crates/router/tests/connectors/checkout.rs index 0bea948fa9..cefd2e1d8a 100644 --- a/crates/router/tests/connectors/checkout.rs +++ b/crates/router/tests/connectors/checkout.rs @@ -105,6 +105,7 @@ async fn test_checkout_payment_success() { }; let state = routes::AppState::with_storage(conf, StorageImpl::PostgresqlTest).await; let connector_integration: services::BoxedConnectorIntegration< + '_, types::api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData, @@ -143,6 +144,7 @@ async fn test_checkout_refund_success() { get_token: types::api::GetToken::Connector, }; let connector_integration: services::BoxedConnectorIntegration< + '_, types::api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData, @@ -166,6 +168,7 @@ async fn test_checkout_refund_success() { ); // Successful refund let connector_integration: services::BoxedConnectorIntegration< + '_, types::api::Execute, types::RefundsData, types::RefundsResponseData, @@ -209,6 +212,7 @@ async fn test_checkout_payment_failure() { get_token: types::api::GetToken::Connector, }; let connector_integration: services::BoxedConnectorIntegration< + '_, types::api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData, @@ -241,6 +245,7 @@ async fn test_checkout_refund_failure() { get_token: types::api::GetToken::Connector, }; let connector_integration: services::BoxedConnectorIntegration< + '_, types::api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData, @@ -262,6 +267,7 @@ async fn test_checkout_refund_failure() { ); // Unsuccessful refund let connector_integration: services::BoxedConnectorIntegration< + '_, types::api::Execute, types::RefundsData, types::RefundsResponseData, diff --git a/crates/router/tests/connectors/connector_auth.rs b/crates/router/tests/connectors/connector_auth.rs index e06897d9ab..5be73e5aaa 100644 --- a/crates/router/tests/connectors/connector_auth.rs +++ b/crates/router/tests/connectors/connector_auth.rs @@ -11,6 +11,7 @@ pub(crate) struct ConnectorAuthentication { impl ConnectorAuthentication { pub(crate) fn new() -> Self { + #[allow(clippy::expect_used)] toml::de::from_slice( &std::fs::read("tests/connectors/auth.toml") .expect("connector authentication config file not found"), @@ -26,7 +27,7 @@ pub(crate) struct HeaderKey { impl From for ConnectorAuthType { fn from(key: HeaderKey) -> Self { - ConnectorAuthType::HeaderKey { + Self::HeaderKey { api_key: key.api_key, } } @@ -40,7 +41,7 @@ pub(crate) struct BodyKey { impl From for ConnectorAuthType { fn from(key: BodyKey) -> Self { - ConnectorAuthType::BodyKey { + Self::BodyKey { api_key: key.api_key, key1: key.key1, } diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index 93c55c6e58..b4ea15522d 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -1,3 +1,5 @@ +#![allow(clippy::expect_used, clippy::panic, clippy::unwrap_used)] + mod aci; mod authorizedotnet; mod checkout; diff --git a/crates/router/tests/connectors/shift4.rs b/crates/router/tests/connectors/shift4.rs index dd4f68f4e7..d7d559555c 100644 --- a/crates/router/tests/connectors/shift4.rs +++ b/crates/router/tests/connectors/shift4.rs @@ -8,7 +8,7 @@ use crate::{ }; struct Shift4; -impl utils::ConnectorActions for Shift4 {} +impl ConnectorActions for Shift4 {} impl utils::Connector for Shift4 { fn get_data(&self) -> types::api::ConnectorData { use router::connector::Shift4; diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 569a38586d..51fdfc8710 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -5,14 +5,8 @@ use masking::Secret; use router::{ core::payments, db::StorageImpl, - routes, - services::{self}, - types::{ - self, - api::{self}, - storage::enums, - PaymentAddress, RouterData, - }, + routes, services, + types::{self, api, storage::enums, PaymentAddress}, }; pub trait Connector { @@ -93,7 +87,7 @@ async fn call_connector< Req: Debug + Clone + 'static, Resp: Debug + Clone + 'static, >( - request: RouterData, + request: types::RouterData, integration: services::BoxedConnectorIntegration<'_, T, Req, Resp>, ) -> types::RouterData { use router::configs::settings::Settings; @@ -115,7 +109,7 @@ pub struct CCardType(pub api::CCard); impl Default for CCardType { fn default() -> Self { - CCardType(api::CCard { + Self(api::CCard { card_number: Secret::new("4200000000000000".to_string()), card_exp_month: Secret::new("10".to_string()), card_exp_year: Secret::new("2025".to_string()), @@ -141,7 +135,7 @@ impl Default for PaymentAuthorizeType { browser_info: None, order_details: None, }; - PaymentAuthorizeType(data) + Self(data) } } @@ -155,7 +149,7 @@ impl Default for PaymentRefundType { connector_transaction_id: String::new(), refund_amount: 100, }; - PaymentRefundType(data) + Self(data) } } diff --git a/crates/router/tests/customers.rs b/crates/router/tests/customers.rs index ce7f6b5f79..f765b9f461 100644 --- a/crates/router/tests/customers.rs +++ b/crates/router/tests/customers.rs @@ -1,3 +1,5 @@ +#![allow(clippy::unwrap_used)] + mod utils; // setting the connector in environment variables doesn't work when run in parallel. Neither does passing the paymentid diff --git a/crates/router/tests/integration_demo.rs b/crates/router/tests/integration_demo.rs index d838f8e798..1fc675ffa9 100644 --- a/crates/router/tests/integration_demo.rs +++ b/crates/router/tests/integration_demo.rs @@ -1,3 +1,5 @@ +#![allow(clippy::unwrap_used)] + mod utils; #[allow(dead_code)] diff --git a/crates/router/tests/payouts.rs b/crates/router/tests/payouts.rs index ff36fa13cf..0c208340ac 100644 --- a/crates/router/tests/payouts.rs +++ b/crates/router/tests/payouts.rs @@ -1,3 +1,5 @@ +#![allow(clippy::unwrap_used)] + mod utils; #[actix_web::test] diff --git a/crates/router/tests/refunds.rs b/crates/router/tests/refunds.rs index 7eff4f2e9b..608b16f5ca 100644 --- a/crates/router/tests/refunds.rs +++ b/crates/router/tests/refunds.rs @@ -1,3 +1,5 @@ +#![allow(clippy::unwrap_used)] + use utils::{mk_service, AppClient}; mod utils; diff --git a/crates/router/tests/utils.rs b/crates/router/tests/utils.rs index 964ae87668..6063680cb6 100644 --- a/crates/router/tests/utils.rs +++ b/crates/router/tests/utils.rs @@ -1,4 +1,10 @@ -#![allow(dead_code)] +#![allow( + dead_code, + clippy::expect_used, + clippy::missing_panics_doc, + clippy::unwrap_used +)] + use actix_http::{body::MessageBody, Request}; use actix_web::{ dev::{Service, ServiceResponse}, @@ -31,11 +37,8 @@ async fn stripemock() -> Option { None } -pub async fn mk_service() -> impl actix_web::dev::Service< - actix_http::Request, - Response = actix_web::dev::ServiceResponse, - Error = actix_web::Error, -> { +pub async fn mk_service( +) -> impl Service, Error = actix_web::Error> { let mut conf = Settings::new().unwrap(); let request_body_limit = conf.server.request_body_limit; @@ -63,8 +66,8 @@ pub struct AppClient { } impl AppClient { - pub fn guest() -> AppClient { - AppClient { state: Guest } + pub fn guest() -> Self { + Self { state: Guest } } } diff --git a/crates/router_derive/src/lib.rs b/crates/router_derive/src/lib.rs index cba0ef3012..8f9015d484 100644 --- a/crates/router_derive/src/lib.rs +++ b/crates/router_derive/src/lib.rs @@ -133,6 +133,11 @@ pub fn diesel_enum( /// ``` /// +/// # Panics +/// +/// Panics if a struct without named fields is provided as input to the macro +// FIXME: Remove allowed warnings, raise compile errors in a better manner instead of panicking +#[allow(clippy::panic, clippy::unwrap_used)] #[proc_macro_derive(Setter, attributes(auth_based))] pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = syn::parse_macro_input!(input as syn::DeriveInput); @@ -145,6 +150,7 @@ pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream { { named } else { + // FIXME: Use `compile_error!()` instead panic!("You can't use this proc-macro on structs without fields"); }; diff --git a/crates/router_derive/src/macros/api_error.rs b/crates/router_derive/src/macros/api_error.rs index 56d59317cf..8c6790a76d 100644 --- a/crates/router_derive/src/macros/api_error.rs +++ b/crates/router_derive/src/macros/api_error.rs @@ -74,11 +74,15 @@ fn implement_error_type( Fields::Unnamed(..) => quote! { (..) }, Fields::Named(..) => quote! { {..} }, }; + // Safety: Missing attributes are already checked before this function is called. + #[allow(clippy::unwrap_used)] let error_type = properties.error_type.as_ref().unwrap(); arms.push(quote! { #enum_name::#ident #params => #error_type }); } + // Safety: Missing attributes are already checked before this function is called. + #[allow(clippy::unwrap_used)] let error_type_enum = type_properties.error_type_enum.as_ref().unwrap(); quote! { pub fn error_type(&self) -> #error_type_enum { @@ -101,6 +105,8 @@ fn implement_error_code( Fields::Unnamed(..) => quote! { (..) }, Fields::Named(..) => quote! { {..} }, }; + // Safety: Missing attributes are already checked before this function is called. + #[allow(clippy::unwrap_used)] let error_code = properties.code.as_ref().unwrap(); arms.push(quote! { #enum_name::#ident #params => #error_code.to_string() }); @@ -129,11 +135,17 @@ fn implement_error_message( let fields = fields .named .iter() - .map(|f| f.ident.as_ref().unwrap()) + .map(|f| { + // Safety: Named fields are guaranteed to have an identifier. + #[allow(clippy::unwrap_used)] + f.ident.as_ref().unwrap() + }) .collect::>(); quote! { {#fields} } } }; + // Safety: Missing attributes are already checked before this function is called. + #[allow(clippy::unwrap_used)] let error_message = properties.message.as_ref().unwrap(); arms.push(quote! { #enum_name::#ident #params => format!(#error_message) }); @@ -150,7 +162,7 @@ fn implement_error_message( fn implement_serialize( enum_name: &Ident, - generics: (&ImplGenerics, &TypeGenerics, Option<&WhereClause>), + generics: (&ImplGenerics<'_>, &TypeGenerics<'_>, Option<&WhereClause>), type_properties: &ErrorTypeProperties, variants_properties_map: &HashMap<&Variant, ErrorVariantProperties>, ) -> TokenStream { @@ -165,14 +177,22 @@ fn implement_serialize( let fields = fields .named .iter() - .map(|f| f.ident.as_ref().unwrap()) + .map(|f| { + // Safety: Named fields are guaranteed to have an identifier. + #[allow(clippy::unwrap_used)] + f.ident.as_ref().unwrap() + }) .collect::>(); quote! { {#fields} } } }; + // Safety: Missing attributes are already checked before this function is called. + #[allow(clippy::unwrap_used)] let error_message = properties.message.as_ref().unwrap(); - let msg_unused_fields = get_unused_fields(&variant.fields, &error_message.value()).unwrap(); + let msg_unused_fields = get_unused_fields(&variant.fields, &error_message.value()); + // Safety: Missing attributes are already checked before this function is called. + #[allow(clippy::unwrap_used)] let error_type_enum = type_properties.error_type_enum.as_ref().unwrap(); let response_definition = if msg_unused_fields.is_empty() { quote! { @@ -188,6 +208,8 @@ fn implement_serialize( let mut extra_fields = Vec::new(); for field in &msg_unused_fields { let vis = &field.vis; + // Safety: `msq_unused_fields` is expected to contain named fields only. + #[allow(clippy::unwrap_used)] let ident = &field.ident.as_ref().unwrap(); let ty = &field.ty; extra_fields.push(quote! { #vis #ident: #ty }); @@ -204,12 +226,20 @@ fn implement_serialize( } }; + // Safety: Missing attributes are already checked before this function is called. + #[allow(clippy::unwrap_used)] let error_type = properties.error_type.as_ref().unwrap(); + // Safety: Missing attributes are already checked before this function is called. + #[allow(clippy::unwrap_used)] let code = properties.code.as_ref().unwrap(); + // Safety: Missing attributes are already checked before this function is called. + #[allow(clippy::unwrap_used)] let message = properties.message.as_ref().unwrap(); let extra_fields = msg_unused_fields .iter() .map(|field| { + // Safety: `extra_fields` is expected to contain named fields only. + #[allow(clippy::unwrap_used)] let field_name = field.ident.as_ref().unwrap(); quote! { #field_name: #field_name.to_owned() } }) diff --git a/crates/router_derive/src/macros/api_error/helpers.rs b/crates/router_derive/src/macros/api_error/helpers.rs index b299709078..8da29f485b 100644 --- a/crates/router_derive/src/macros/api_error/helpers.rs +++ b/crates/router_derive/src/macros/api_error/helpers.rs @@ -24,13 +24,13 @@ enum EnumMeta { } impl Parse for EnumMeta { - fn parse(input: syn::parse::ParseStream) -> syn::Result { + fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result { let lookahead = input.lookahead1(); if lookahead.peek(keyword::error_type_enum) { let keyword = input.parse()?; input.parse::()?; let value = input.parse()?; - Ok(EnumMeta::ErrorTypeEnum { keyword, value }) + Ok(Self::ErrorTypeEnum { keyword, value }) } else { Err(lookahead.error()) } @@ -40,7 +40,7 @@ impl Parse for EnumMeta { impl Spanned for EnumMeta { fn span(&self) -> proc_macro2::Span { match self { - EnumMeta::ErrorTypeEnum { keyword, .. } => keyword.span(), + Self::ErrorTypeEnum { keyword, .. } => keyword.span(), } } } @@ -83,6 +83,13 @@ impl HasErrorTypeProperties for DeriveInput { } } + if output.error_type_enum.is_none() { + return Err(syn::Error::new( + self.span(), + "error(error_type_enum) attribute not found", + )); + } + Ok(output) } } @@ -103,23 +110,23 @@ enum VariantMeta { } impl Parse for VariantMeta { - fn parse(input: syn::parse::ParseStream) -> syn::Result { + fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result { let lookahead = input.lookahead1(); if lookahead.peek(keyword::error_type) { let keyword = input.parse()?; let _: Token![=] = input.parse()?; let value = input.parse()?; - Ok(VariantMeta::ErrorType { keyword, value }) + Ok(Self::ErrorType { keyword, value }) } else if lookahead.peek(keyword::code) { let keyword = input.parse()?; let _: Token![=] = input.parse()?; let value = input.parse()?; - Ok(VariantMeta::Code { keyword, value }) + Ok(Self::Code { keyword, value }) } else if lookahead.peek(keyword::message) { let keyword = input.parse()?; let _: Token![=] = input.parse()?; let value = input.parse()?; - Ok(VariantMeta::Message { keyword, value }) + Ok(Self::Message { keyword, value }) } else { Err(lookahead.error()) } @@ -129,9 +136,9 @@ impl Parse for VariantMeta { impl Spanned for VariantMeta { fn span(&self) -> proc_macro2::Span { match self { - VariantMeta::ErrorType { keyword, .. } => keyword.span, - VariantMeta::Code { keyword, .. } => keyword.span, - VariantMeta::Message { keyword, .. } => keyword.span, + Self::ErrorType { keyword, .. } => keyword.span, + Self::Code { keyword, .. } => keyword.span, + Self::Message { keyword, .. } => keyword.span, } } } @@ -220,19 +227,21 @@ pub(super) fn check_missing_attributes( } /// Get all the fields not used in the error message. -pub(super) fn get_unused_fields(fields: &Fields, message: &str) -> syn::Result> { +pub(super) fn get_unused_fields(fields: &Fields, message: &str) -> Vec { let fields = match fields { syn::Fields::Unit => Vec::new(), syn::Fields::Unnamed(_) => Vec::new(), syn::Fields::Named(fields) => fields.named.iter().cloned().collect(), }; - Ok(fields + fields .iter() .filter(|&field| { + // Safety: Named fields are guaranteed to have an identifier. + #[allow(clippy::unwrap_used)] let field_name = format!("{}", field.ident.as_ref().unwrap()); !message.contains(&field_name) }) .cloned() - .collect()) + .collect() } diff --git a/crates/router_derive/src/macros/operation.rs b/crates/router_derive/src/macros/operation.rs index 798ee1525d..bee3185b44 100644 --- a/crates/router_derive/src/macros/operation.rs +++ b/crates/router_derive/src/macros/operation.rs @@ -83,7 +83,7 @@ enum Conversion { } impl From for Conversion { - fn from(s: String) -> Conversion { + fn from(s: String) -> Self { match s.as_str() { "validate_request" => Self::ValidateRequest, "get_tracker" => Self::GetTracker, @@ -91,6 +91,7 @@ impl From for Conversion { "update_tracker" => Self::UpdateTracker, "post_tracker" => Self::PostUpdateTracker, "all" => Self::All, + #[allow(clippy::panic)] // FIXME: Use `compile_error!()` instead _ => panic!("Invalid conversion identifier {}", s), } } @@ -118,36 +119,36 @@ impl Conversion { fn to_function(&self, ident: Derives) -> TokenStream { let req_type = Self::get_req_type(ident); match self { - Conversion::ValidateRequest => quote! { + Self::ValidateRequest => quote! { fn to_validate_request(&self) -> RouterResult<&(dyn ValidateRequest + Send + Sync)> { Ok(self) } }, - Conversion::GetTracker => quote! { + Self::GetTracker => quote! { fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker,#req_type> + Send + Sync)> { Ok(self) } }, - Conversion::Domain => quote! { + Self::Domain => quote! { fn to_domain(&self) -> RouterResult<&dyn Domain> { Ok(self) } }, - Conversion::UpdateTracker => quote! { + Self::UpdateTracker => quote! { fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker,#req_type> + Send + Sync)> { Ok(self) } }, - Conversion::PostUpdateTracker => quote! { + Self::PostUpdateTracker => quote! { fn to_post_update_tracker(&self) -> RouterResult<&(dyn PostUpdateTracker, #req_type> + Send + Sync)> { Ok(self) } }, - Conversion::All => { - let validate_request = Conversion::ValidateRequest.to_function(ident); - let get_tracker = Conversion::GetTracker.to_function(ident); - let domain = Conversion::Domain.to_function(ident); - let update_tracker = Conversion::UpdateTracker.to_function(ident); + Self::All => { + let validate_request = Self::ValidateRequest.to_function(ident); + let get_tracker = Self::GetTracker.to_function(ident); + let domain = Self::Domain.to_function(ident); + let update_tracker = Self::UpdateTracker.to_function(ident); quote! { #validate_request @@ -162,36 +163,36 @@ impl Conversion { fn to_ref_function(&self, ident: Derives) -> TokenStream { let req_type = Self::get_req_type(ident); match self { - Conversion::ValidateRequest => quote! { + Self::ValidateRequest => quote! { fn to_validate_request(&self) -> RouterResult<&(dyn ValidateRequest + Send + Sync)> { Ok(*self) } }, - Conversion::GetTracker => quote! { + Self::GetTracker => quote! { fn to_get_tracker(&self) -> RouterResult<&(dyn GetTracker,#req_type> + Send + Sync)> { Ok(*self) } }, - Conversion::Domain => quote! { + Self::Domain => quote! { fn to_domain(&self) -> RouterResult<&(dyn Domain)> { Ok(*self) } }, - Conversion::UpdateTracker => quote! { + Self::UpdateTracker => quote! { fn to_update_tracker(&self) -> RouterResult<&(dyn UpdateTracker,#req_type> + Send + Sync)> { Ok(*self) } }, - Conversion::PostUpdateTracker => quote! { + Self::PostUpdateTracker => quote! { fn to_post_update_tracker(&self) -> RouterResult<&(dyn PostUpdateTracker, #req_type> + Send + Sync)> { Ok(*self) } }, - Conversion::All => { - let validate_request = Conversion::ValidateRequest.to_ref_function(ident); - let get_tracker = Conversion::GetTracker.to_ref_function(ident); - let domain = Conversion::Domain.to_ref_function(ident); - let update_tracker = Conversion::UpdateTracker.to_ref_function(ident); + Self::All => { + let validate_request = Self::ValidateRequest.to_ref_function(ident); + let get_tracker = Self::GetTracker.to_ref_function(ident); + let domain = Self::Domain.to_ref_function(ident); + let update_tracker = Self::UpdateTracker.to_ref_function(ident); quote! { #validate_request @@ -205,6 +206,7 @@ impl Conversion { } fn find_operation_attr(a: &[syn::Attribute]) -> syn::Attribute { + #[allow(clippy::expect_used)] // FIXME: Use `compile_error!()` instead a.iter() .find(|a| { a.path @@ -232,6 +234,9 @@ fn find_value(v: NestedMeta) -> Option<(String, Vec)> { _ => None, } } + +// FIXME: Propagate errors in a better manner instead of `expect()`, maybe use `compile_error!()` +#[allow(clippy::unwrap_used, clippy::expect_used)] fn find_properties(attr: &syn::Attribute) -> Option>> { let meta = attr.parse_meta(); match meta { @@ -251,6 +256,8 @@ fn find_properties(attr: &syn::Attribute) -> Option> } } +// FIXME: Propagate errors in a better manner instead of `expect()`, maybe use `compile_error!()` +#[allow(clippy::expect_used)] pub fn operation_derive_inner(token: proc_macro::TokenStream) -> proc_macro::TokenStream { let input = parse_macro_input!(token as DeriveInput); let struct_name = &input.ident; diff --git a/crates/router_env/src/env.rs b/crates/router_env/src/env.rs index 518a1cac0c..701953f6b2 100644 --- a/crates/router_env/src/env.rs +++ b/crates/router_env/src/env.rs @@ -63,7 +63,7 @@ pub fn workspace_path() -> PathBuf { // for (key, value) in std::env::vars() { // println!("{key} : {value}"); // } - if let Result::Ok(manifest_dir) = std::env::var(CARGO_MANIFEST_DIR) { + if let Ok(manifest_dir) = std::env::var(CARGO_MANIFEST_DIR) { let mut path = PathBuf::from(manifest_dir); path.pop(); path.pop(); diff --git a/crates/router_env/src/lib.rs b/crates/router_env/src/lib.rs index 6c6ce4893b..4febff06f2 100644 --- a/crates/router_env/src/lib.rs +++ b/crates/router_env/src/lib.rs @@ -1,17 +1,5 @@ #![forbid(unsafe_code)] -#![warn( - missing_docs, - rust_2018_idioms, - missing_debug_implementations, - clippy::expect_used, - clippy::missing_panics_doc, - clippy::panic, - clippy::panic_in_result_fn, - clippy::panicking_unwrap, - clippy::unreachable, - clippy::unwrap_in_result, - clippy::unwrap_used -)] +#![warn(missing_docs, missing_debug_implementations)] //! //! Environment of payment router: logger, basic config, its environment awareness. diff --git a/crates/router_env/src/logger/formatter.rs b/crates/router_env/src/logger/formatter.rs index cc66fccfe4..17f4dea6ed 100644 --- a/crates/router_env/src/logger/formatter.rs +++ b/crates/router_env/src/logger/formatter.rs @@ -102,9 +102,9 @@ pub enum RecordType { impl fmt::Display for RecordType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let repr = match self { - RecordType::EnterSpan => "START", - RecordType::ExitSpan => "END", - RecordType::Event => "EVENT", + Self::EnterSpan => "START", + Self::ExitSpan => "END", + Self::Event => "EVENT", }; write!(f, "{}", repr) } diff --git a/crates/router_env/tests/logger.rs b/crates/router_env/tests/logger.rs index 5e134a8194..824f9e825b 100644 --- a/crates/router_env/tests/logger.rs +++ b/crates/router_env/tests/logger.rs @@ -1,3 +1,5 @@ +#![allow(clippy::unwrap_used)] + use router_env as env; mod test_module; use env::TelemetryGuard; diff --git a/crates/storage_models/src/lib.rs b/crates/storage_models/src/lib.rs index 98d4a68c49..7ff7845843 100644 --- a/crates/storage_models/src/lib.rs +++ b/crates/storage_models/src/lib.rs @@ -63,7 +63,7 @@ pub(crate) mod diesel_impl { type Row = Vec>; fn build(row: Self::Row) -> diesel::deserialize::Result { - Ok(DieselArray(row)) + Ok(Self(row)) } } @@ -84,7 +84,7 @@ pub(crate) mod diesel_impl { type Row = Option>>; fn build(row: Self::Row) -> diesel::deserialize::Result { - Ok(OptionalDieselArray(row)) + Ok(Self(row)) } } } diff --git a/crates/storage_models/src/payment_intent.rs b/crates/storage_models/src/payment_intent.rs index 3077c884f8..7906cbc6ce 100644 --- a/crates/storage_models/src/payment_intent.rs +++ b/crates/storage_models/src/payment_intent.rs @@ -236,7 +236,7 @@ fn make_client_secret_null_if_success( status: Option, ) -> Option> { if status == Some(storage_enums::IntentStatus::Succeeded) { - Option::>::Some(None) + Some(None) } else { None } diff --git a/crates/storage_models/src/query/connector_response.rs b/crates/storage_models/src/query/connector_response.rs index 49d66a2ed8..8dd4f06547 100644 --- a/crates/storage_models/src/query/connector_response.rs +++ b/crates/storage_models/src/query/connector_response.rs @@ -47,7 +47,7 @@ impl ConnectorResponse { payment_id: &str, merchant_id: &str, attempt_id: &str, - ) -> StorageResult { + ) -> StorageResult { generics::generic_find_one::<::Table, _, _>( conn, dsl::merchant_id.eq(merchant_id.to_owned()).and( diff --git a/crates/storage_models/src/query/process_tracker.rs b/crates/storage_models/src/query/process_tracker.rs index 8a0ecd1beb..be7891aa42 100644 --- a/crates/storage_models/src/query/process_tracker.rs +++ b/crates/storage_models/src/query/process_tracker.rs @@ -88,7 +88,7 @@ impl ProcessTracker { time_lower_limit: PrimitiveDateTime, time_upper_limit: PrimitiveDateTime, runner: &str, - limit: u64, + limit: usize, ) -> StorageResult> { let mut x: Vec = generics::generic_filter::<::Table, _, _>( conn, @@ -100,7 +100,7 @@ impl ProcessTracker { ) .await?; x.sort_by(|a, b| a.schedule_time.cmp(&b.schedule_time)); - x.truncate(limit as usize); + x.truncate(limit); Ok(x) } diff --git a/crates/storage_models/src/query/temp_card.rs b/crates/storage_models/src/query/temp_card.rs index 1ed94934c1..eb9fdc2732 100644 --- a/crates/storage_models/src/query/temp_card.rs +++ b/crates/storage_models/src/query/temp_card.rs @@ -25,7 +25,7 @@ impl TempCard { pub async fn find_by_transaction_id( conn: &PgPooledConn, transaction_id: &str, - ) -> StorageResult> { + ) -> StorageResult> { generics::generic_find_one_optional::<::Table, _, _>( conn, dsl::txn_id.eq(transaction_id.to_owned()),