1use serde::{Deserialize, Serialize};
2use std::collections::HashMap;
3
4#[derive(Debug, Clone, Serialize, Deserialize)]
5pub struct HandlerContext {
6 pub handler_name: String,
7
8 pub payload: serde_json::Value,
9
10 pub query_params: HashMap<String, String>,
11
12 pub metadata: HashMap<String, String>,
13
14 pub timestamp: String,
15}
16
17impl HandlerContext {
18 pub fn new(handler_name: impl Into<String>, payload: serde_json::Value) -> Self {
19 Self {
20 handler_name: handler_name.into(),
21 payload,
22 query_params: HashMap::new(),
23 metadata: HashMap::new(),
24 timestamp: chrono::Utc::now().to_rfc3339(),
25 }
26 }
27
28 pub fn with_metadata(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
29 self.metadata.insert(key.into(), value.into());
30 self
31 }
32
33 pub fn with_query_param(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
34 self.query_params.insert(key.into(), value.into());
35 self
36 }
37}
38
39#[derive(Debug, Clone, Serialize, Deserialize)]
40pub struct TriggeredEvent {
41 pub event_name: String,
42 pub payload: serde_json::Value,
43}
44
45#[derive(Debug, Clone, Serialize, Deserialize)]
46pub struct HandlerResult {
47 pub success: bool,
48
49 pub data: Option<serde_json::Value>,
50
51 pub error: Option<String>,
52
53 pub execution_time_ms: u64,
54
55 #[serde(default)]
56 pub triggers: Vec<TriggeredEvent>,
57
58 #[serde(default)]
59 pub auto_trigger_payloads: std::collections::HashMap<String, serde_json::Value>,
60}
61
62impl HandlerResult {
63 pub fn success(data: serde_json::Value, execution_time_ms: u64) -> Self {
64 Self {
65 success: true,
66 data: Some(data),
67 error: None,
68 execution_time_ms,
69 triggers: Vec::new(),
70 auto_trigger_payloads: std::collections::HashMap::new(),
71 }
72 }
73
74 pub fn error(error: impl Into<String>, execution_time_ms: u64) -> Self {
75 Self {
76 success: false,
77 data: None,
78 error: Some(error.into()),
79 execution_time_ms,
80 triggers: Vec::new(),
81 auto_trigger_payloads: std::collections::HashMap::new(),
82 }
83 }
84
85 pub fn with_trigger(
86 mut self,
87 event_name: impl Into<String>,
88 payload: serde_json::Value,
89 ) -> Self {
90 self.triggers.push(TriggeredEvent {
91 event_name: event_name.into(),
92 payload,
93 });
94 self
95 }
96
97 pub fn with_auto_trigger_payload(
98 mut self,
99 event_name: impl Into<String>,
100 payload: serde_json::Value,
101 ) -> Self {
102 self.auto_trigger_payloads
103 .insert(event_name.into(), payload);
104 self
105 }
106}
107
108#[async_trait::async_trait]
109pub trait Handler: Send + Sync {
110 async fn execute(&self, context: HandlerContext) -> crate::Result<HandlerResult>;
111
112 fn name(&self) -> &str;
113}