Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

refactor(webhooks): remove unnecessary clones and lazy evaluations (#3596)

Sanchith Hegdebebaf413f2ab
diff --git a/crates/diesel_models/src/events.rs b/crates/diesel_models/src/events.rs
index 2f040fc00c..817817d53d 100644
--- a/crates/diesel_models/src/events.rs
+++ b/crates/diesel_models/src/events.rs
@@ -5,9 +5,8 @@ use time::PrimitiveDateTime;
use crate::{enums as storage_enums, schema::events};
-#[derive(Clone, Debug, Deserialize, Insertable, Serialize, router_derive::DebugAsDisplay)]
+#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
#[diesel(table_name = events)]
-#[serde(deny_unknown_fields)]
pub struct EventNew {
pub event_id: String,
pub event_type: storage_enums::EventType,
diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs
index cc30146de3..1557e4bdee 100644
--- a/crates/router/src/core/webhooks.rs
+++ b/crates/router/src/core/webhooks.rs
@@ -11,7 +11,11 @@ use api_models::{
use common_utils::{errors::ReportSwitchExt, events::ApiEventsType, request::RequestContent};
use error_stack::{report, IntoReport, ResultExt};
use masking::ExposeInterface;
-use router_env::{instrument, tracing, tracing_actix_web::RequestId};
+use router_env::{
+ instrument,
+ tracing::{self, Instrument},
+ tracing_actix_web::RequestId,
+};
use super::{errors::StorageErrorExt, metrics};
#[cfg(feature = "stripe")]
@@ -214,7 +218,7 @@ pub async fn refunds_incoming_webhook_flow<W: types::OutgoingWebhookType>(
)
.await
.change_context(errors::ApiErrorResponse::WebhookResourceNotFound)
- .attach_printable_lazy(|| "Failed fetching the refund")?,
+ .attach_printable("Failed to fetch the refund")?,
api_models::webhooks::RefundIdType::ConnectorRefundId(id) => db
.find_refund_by_merchant_id_connector_refund_id_connector(
&merchant_account.merchant_id,
@@ -224,7 +228,7 @@ pub async fn refunds_incoming_webhook_flow<W: types::OutgoingWebhookType>(
)
.await
.change_context(errors::ApiErrorResponse::WebhookResourceNotFound)
- .attach_printable_lazy(|| "Failed fetching the refund")?,
+ .attach_printable("Failed to fetch the refund")?,
},
_ => Err(errors::ApiErrorResponse::WebhookProcessingFailure)
.into_report()
@@ -250,12 +254,7 @@ pub async fn refunds_incoming_webhook_flow<W: types::OutgoingWebhookType>(
)
.await
.to_not_found_response(errors::ApiErrorResponse::WebhookResourceNotFound)
- .attach_printable_lazy(|| {
- format!(
- "Failed while updating refund: refund_id: {}",
- refund_id.to_owned()
- )
- })?
+ .attach_printable_lazy(|| format!("Failed while updating refund: refund_id: {refund_id}"))?
} else {
refunds::refund_retrieve_core(
state.clone(),
@@ -268,12 +267,7 @@ pub async fn refunds_incoming_webhook_flow<W: types::OutgoingWebhookType>(
},
)
.await
- .attach_printable_lazy(|| {
- format!(
- "Failed while updating refund: refund_id: {}",
- refund_id.to_owned()
- )
- })?
+ .attach_printable_lazy(|| format!("Failed while updating refund: refund_id: {refund_id}"))?
};
let event_type: Option<enums::EventType> = updated_refund.refund_status.foreign_into();
@@ -711,7 +705,7 @@ pub async fn create_event_and_trigger_outgoing_webhook<W: types::OutgoingWebhook
primary_object_type: enums::EventObjectType,
content: api::OutgoingWebhookContent,
) -> CustomResult<(), errors::ApiErrorResponse> {
- let event_id = format!("{primary_object_id}_{}", event_type);
+ let event_id = format!("{primary_object_id}_{event_type}");
let new_event = storage::EventNew {
event_id: event_id.clone(),
event_type,
@@ -772,7 +766,6 @@ pub async fn create_event_and_trigger_outgoing_webhook<W: types::OutgoingWebhook
event.event_id.clone(),
event_type,
outgoing_webhook_event_type,
- error.is_some(),
error,
);
match webhook_event.clone().try_into() {
@@ -783,7 +776,7 @@ pub async fn create_event_and_trigger_outgoing_webhook<W: types::OutgoingWebhook
logger::error!(error=?err, event=?webhook_event, "Error Logging Outgoing Webhook Event");
}
}
- });
+ }.in_current_span());
}
Ok(())
@@ -819,7 +812,7 @@ pub async fn trigger_webhook_to_merchant<W: types::OutgoingWebhookType>(
let mut header = vec![(
reqwest::header::CONTENT_TYPE.to_string(),
- "application/json".into(),
+ mime::APPLICATION_JSON.essence_str().into(),
)];
if let Some(signature) = outgoing_webhooks_signature {
@@ -1078,7 +1071,7 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetr
logger::info!(process_webhook=?process_webhook_further);
- let flow_type: api::WebhookFlow = event_type.to_owned().into();
+ let flow_type: api::WebhookFlow = event_type.into();
let mut event_object: Box<dyn masking::ErasedMaskSerialize> = Box::new(serde_json::Value::Null);
let webhook_effect = if process_webhook_further
&& !matches!(flow_type, api::WebhookFlow::ReturnResponse)
@@ -1166,9 +1159,7 @@ pub async fn webhooks_core<W: types::OutgoingWebhookType, Ctx: PaymentMethodRetr
resource_object: serde_json::to_vec(&event_object)
.into_report()
.change_context(errors::ParsingError::EncodeError("byte-vec"))
- .attach_printable_lazy(|| {
- "Unable to convert webhook paylaod to a value".to_string()
- })
+ .attach_printable("Unable to convert webhook payload to a value")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"There was an issue when encoding the incoming webhook body to bytes",
diff --git a/crates/router/src/events/outgoing_webhook_logs.rs b/crates/router/src/events/outgoing_webhook_logs.rs
index ebf36caf70..c2b2366fac 100644
--- a/crates/router/src/events/outgoing_webhook_logs.rs
+++ b/crates/router/src/events/outgoing_webhook_logs.rs
@@ -82,7 +82,6 @@ impl OutgoingWebhookEvent {
event_id: String,
event_type: OutgoingWebhookEventType,
content: Option<OutgoingWebhookEventContent>,
- is_error: bool,
error: Option<Value>,
) -> Self {
Self {
@@ -90,7 +89,7 @@ impl OutgoingWebhookEvent {
event_id,
event_type,
content,
- is_error,
+ is_error: error.is_some(),
error,
created_at_timestamp: OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000,
}