forge_core/webhook/
context.rs1use std::collections::HashMap;
2use std::sync::Arc;
3
4use uuid::Uuid;
5
6use crate::env::{EnvAccess, EnvProvider, RealEnvProvider};
7use crate::function::JobDispatch;
8
9pub struct WebhookContext {
11 pub webhook_name: String,
13 pub request_id: String,
15 pub idempotency_key: Option<String>,
17 headers: HashMap<String, String>,
19 db_pool: sqlx::PgPool,
21 http_client: reqwest::Client,
23 job_dispatch: Option<Arc<dyn JobDispatch>>,
25 env_provider: Arc<dyn EnvProvider>,
27}
28
29impl WebhookContext {
30 pub fn new(
32 webhook_name: String,
33 request_id: String,
34 headers: HashMap<String, String>,
35 db_pool: sqlx::PgPool,
36 http_client: reqwest::Client,
37 ) -> Self {
38 Self {
39 webhook_name,
40 request_id,
41 idempotency_key: None,
42 headers,
43 db_pool,
44 http_client,
45 job_dispatch: None,
46 env_provider: Arc::new(RealEnvProvider::new()),
47 }
48 }
49
50 pub fn with_idempotency_key(mut self, key: Option<String>) -> Self {
52 self.idempotency_key = key;
53 self
54 }
55
56 pub fn with_job_dispatch(mut self, dispatcher: Arc<dyn JobDispatch>) -> Self {
58 self.job_dispatch = Some(dispatcher);
59 self
60 }
61
62 pub fn with_env_provider(mut self, provider: Arc<dyn EnvProvider>) -> Self {
64 self.env_provider = provider;
65 self
66 }
67
68 pub fn db(&self) -> &sqlx::PgPool {
70 &self.db_pool
71 }
72
73 pub fn db_conn(&self) -> crate::function::DbConn<'_> {
75 crate::function::DbConn::Pool(&self.db_pool)
76 }
77
78 pub fn http(&self) -> &reqwest::Client {
80 &self.http_client
81 }
82
83 pub fn header(&self, name: &str) -> Option<&str> {
87 self.headers.get(&name.to_lowercase()).map(|s| s.as_str())
88 }
89
90 pub fn headers(&self) -> &HashMap<String, String> {
92 &self.headers
93 }
94
95 pub async fn dispatch_job<T: serde::Serialize>(
109 &self,
110 job_type: &str,
111 args: T,
112 ) -> crate::error::Result<Uuid> {
113 let dispatcher = self.job_dispatch.as_ref().ok_or_else(|| {
114 crate::error::ForgeError::Internal("Job dispatch not available".into())
115 })?;
116 let args_json = serde_json::to_value(args)?;
117 dispatcher.dispatch_by_name(job_type, args_json, None).await
118 }
119
120 pub async fn cancel_job(
122 &self,
123 job_id: Uuid,
124 reason: Option<String>,
125 ) -> crate::error::Result<bool> {
126 let dispatcher = self.job_dispatch.as_ref().ok_or_else(|| {
127 crate::error::ForgeError::Internal("Job dispatch not available".into())
128 })?;
129 dispatcher.cancel(job_id, reason).await
130 }
131}
132
133impl EnvAccess for WebhookContext {
134 fn env_provider(&self) -> &dyn EnvProvider {
135 self.env_provider.as_ref()
136 }
137}
138
139#[cfg(test)]
140#[allow(clippy::unwrap_used, clippy::indexing_slicing)]
141mod tests {
142 use super::*;
143
144 #[tokio::test]
145 async fn test_webhook_context_creation() {
146 let pool = sqlx::postgres::PgPoolOptions::new()
147 .max_connections(1)
148 .connect_lazy("postgres://localhost/nonexistent")
149 .expect("Failed to create mock pool");
150
151 let mut headers = HashMap::new();
152 headers.insert("x-github-event".to_string(), "push".to_string());
153 headers.insert("x-github-delivery".to_string(), "abc-123".to_string());
154
155 let ctx = WebhookContext::new(
156 "github_webhook".to_string(),
157 "req-123".to_string(),
158 headers,
159 pool,
160 reqwest::Client::new(),
161 )
162 .with_idempotency_key(Some("abc-123".to_string()));
163
164 assert_eq!(ctx.webhook_name, "github_webhook");
165 assert_eq!(ctx.request_id, "req-123");
166 assert_eq!(ctx.idempotency_key, Some("abc-123".to_string()));
167 assert_eq!(ctx.header("X-GitHub-Event"), Some("push"));
168 assert_eq!(ctx.header("x-github-event"), Some("push")); assert!(ctx.header("nonexistent").is_none());
170 }
171}