Skip to content

Commit 01410bb

Browse files
refactor(events): Allow box dyn for event handler (#2629)
Co-authored-by: Nishant Joshi <[email protected]>
1 parent 6cf8f05 commit 01410bb

File tree

5 files changed

+42
-42
lines changed

5 files changed

+42
-42
lines changed

crates/router/src/events.rs

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,15 @@ pub mod api_logs;
44
pub mod event_logger;
55

66
pub trait EventHandler: Sync + Send + dyn_clone::DynClone {
7-
fn log_event<T: Event>(&self, event: T);
7+
fn log_event(&self, event: RawEvent);
8+
}
9+
10+
dyn_clone::clone_trait_object!(EventHandler);
11+
12+
pub struct RawEvent {
13+
event_type: EventType,
14+
key: String,
15+
payload: serde_json::Value,
816
}
917

1018
#[derive(Debug, Serialize)]
@@ -15,12 +23,3 @@ pub enum EventType {
1523
Refund,
1624
ApiLogs,
1725
}
18-
19-
pub trait Event
20-
where
21-
Self: Serialize,
22-
{
23-
fn event_type() -> EventType;
24-
25-
fn key(&self) -> String;
26-
}

crates/router/src/events/api_logs.rs

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use router_env::{tracing_actix_web::RequestId, types::FlowMetric};
22
use serde::{Deserialize, Serialize};
33
use time::OffsetDateTime;
44

5-
use super::Event;
5+
use super::{EventType, RawEvent};
66

77
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
88
pub struct ApiEvent {
@@ -30,12 +30,14 @@ impl ApiEvent {
3030
}
3131
}
3232

33-
impl Event for ApiEvent {
34-
fn event_type() -> super::EventType {
35-
super::EventType::ApiLogs
36-
}
33+
impl TryFrom<ApiEvent> for RawEvent {
34+
type Error = serde_json::Error;
3735

38-
fn key(&self) -> String {
39-
self.request_id.to_string()
36+
fn try_from(value: ApiEvent) -> Result<Self, Self::Error> {
37+
Ok(Self {
38+
event_type: EventType::ApiLogs,
39+
key: value.request_id.clone(),
40+
payload: serde_json::to_value(value)?,
41+
})
4042
}
4143
}
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
use super::{Event, EventHandler};
1+
use super::{EventHandler, RawEvent};
22
use crate::services::logger;
33

44
#[derive(Clone, Debug, Default)]
55
pub struct EventLogger {}
66

77
impl EventHandler for EventLogger {
8-
fn log_event<T: Event>(&self, event: T) {
9-
logger::info!(current = ?serde_json::to_string(&event).unwrap_or(r#"{ "error": "Serialization failed" }"#.to_string()), event_type =? T::event_type(), event_id =? event.key(), log_type = "event");
8+
fn log_event(&self, event: RawEvent) {
9+
logger::info!(event = ?serde_json::to_string(&event.payload).unwrap_or(r#"{ "error": "Serialization failed" }"#.to_string()), event_type =? event.event_type, event_id =? event.key, log_type = "event");
1010
}
1111
}

crates/router/src/routes/app.rs

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -32,31 +32,28 @@ use crate::{
3232
};
3333

3434
#[derive(Clone)]
35-
pub struct AppStateBase<E: EventHandler> {
35+
pub struct AppState {
3636
pub flow_name: String,
3737
pub store: Box<dyn StorageInterface>,
3838
pub conf: Arc<settings::Settings>,
39-
pub event_handler: E,
39+
pub event_handler: Box<dyn EventHandler>,
4040
#[cfg(feature = "email")]
4141
pub email_client: Arc<dyn EmailClient>,
4242
#[cfg(feature = "kms")]
4343
pub kms_secrets: Arc<settings::ActiveKmsSecrets>,
4444
pub api_client: Box<dyn crate::services::ApiClient>,
4545
}
4646

47-
pub type AppState = AppStateBase<EventLogger>;
48-
4947
impl scheduler::SchedulerAppState for AppState {
5048
fn get_db(&self) -> Box<dyn SchedulerInterface> {
5149
self.store.get_scheduler_db()
5250
}
5351
}
5452

5553
pub trait AppStateInfo {
56-
type Event: EventHandler;
5754
fn conf(&self) -> settings::Settings;
5855
fn store(&self) -> Box<dyn StorageInterface>;
59-
fn event_handler(&self) -> &Self::Event;
56+
fn event_handler(&self) -> Box<dyn EventHandler>;
6057
#[cfg(feature = "email")]
6158
fn email_client(&self) -> Arc<dyn EmailClient>;
6259
fn add_request_id(&mut self, request_id: RequestId);
@@ -66,7 +63,6 @@ pub trait AppStateInfo {
6663
}
6764

6865
impl AppStateInfo for AppState {
69-
type Event = EventLogger;
7066
fn conf(&self) -> settings::Settings {
7167
self.conf.as_ref().to_owned()
7268
}
@@ -77,8 +73,8 @@ impl AppStateInfo for AppState {
7773
fn email_client(&self) -> Arc<dyn EmailClient> {
7874
self.email_client.to_owned()
7975
}
80-
fn event_handler(&self) -> &Self::Event {
81-
&self.event_handler
76+
fn event_handler(&self) -> Box<dyn EventHandler> {
77+
self.event_handler.to_owned()
8278
}
8379
fn add_request_id(&mut self, request_id: RequestId) {
8480
self.api_client.add_request_id(request_id);
@@ -148,7 +144,7 @@ impl AppState {
148144
#[cfg(feature = "kms")]
149145
kms_secrets: Arc::new(kms_secrets),
150146
api_client,
151-
event_handler: EventLogger::default(),
147+
event_handler: Box::<EventLogger>::default(),
152148
}
153149
}
154150

crates/router/src/services/api.rs

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ use serde_json::json;
2525
use tera::{Context, Tera};
2626

2727
use self::request::{HeaderExt, RequestBuilderExt};
28+
use super::authentication::{AuthInfo, AuthenticateAndFetch};
2829
use crate::{
2930
configs::settings::{Connectors, Settings},
3031
consts,
@@ -33,14 +34,13 @@ use crate::{
3334
errors::{self, CustomResult},
3435
payments,
3536
},
36-
events::{api_logs::ApiEvent, EventHandler},
37+
events::api_logs::ApiEvent,
3738
logger,
3839
routes::{
3940
app::AppStateInfo,
4041
metrics::{self, request as metrics_request},
4142
AppState,
4243
},
43-
services::authentication as auth,
4444
types::{
4545
self,
4646
api::{self, ConnectorCommon},
@@ -751,7 +751,7 @@ pub async fn server_wrap_util<'a, 'b, A, U, T, Q, F, Fut, E, OErr>(
751751
request: &'a HttpRequest,
752752
payload: T,
753753
func: F,
754-
api_auth: &dyn auth::AuthenticateAndFetch<U, A>,
754+
api_auth: &dyn AuthenticateAndFetch<U, A>,
755755
lock_action: api_locking::LockAction,
756756
) -> CustomResult<ApplicationResponse<Q>, OErr>
757757
where
@@ -761,7 +761,7 @@ where
761761
Q: Serialize + Debug + 'a,
762762
T: Debug,
763763
A: AppStateInfo + Clone,
764-
U: auth::AuthInfo,
764+
U: AuthInfo,
765765
E: ErrorSwitch<OErr> + error_stack::Context,
766766
OErr: ResponseError + error_stack::Context,
767767
errors::ApiErrorResponse: ErrorSwitch<OErr>,
@@ -816,12 +816,15 @@ where
816816
Ok(res) => metrics::request::track_response_status_code(res),
817817
Err(err) => err.current_context().status_code().as_u16().into(),
818818
};
819-
state.event_handler().log_event(ApiEvent::new(
820-
flow,
821-
&request_id,
822-
request_duration,
823-
status_code,
824-
));
819+
let api_event = ApiEvent::new(flow, &request_id, request_duration, status_code);
820+
match api_event.clone().try_into() {
821+
Ok(event) => {
822+
state.event_handler().log_event(event);
823+
}
824+
Err(err) => {
825+
logger::error!(error=?err, event=?api_event, "Error Logging API Event");
826+
}
827+
}
825828

826829
metrics::request::status_code_metrics(status_code, flow.to_string(), merchant_id.to_string());
827830

@@ -838,15 +841,15 @@ pub async fn server_wrap<'a, A, T, U, Q, F, Fut, E>(
838841
request: &'a HttpRequest,
839842
payload: T,
840843
func: F,
841-
api_auth: &dyn auth::AuthenticateAndFetch<U, A>,
844+
api_auth: &dyn AuthenticateAndFetch<U, A>,
842845
lock_action: api_locking::LockAction,
843846
) -> HttpResponse
844847
where
845848
F: Fn(A, U, T) -> Fut,
846849
Fut: Future<Output = CustomResult<ApplicationResponse<Q>, E>>,
847850
Q: Serialize + Debug + 'a,
848851
T: Debug,
849-
U: auth::AuthInfo,
852+
U: AuthInfo,
850853
A: AppStateInfo + Clone,
851854
ApplicationResponse<Q>: Debug,
852855
E: ErrorSwitch<api_models::errors::types::ApiErrorResponse> + error_stack::Context,

0 commit comments

Comments
 (0)