1use crate::{
2 domain::entities::Event,
3 infrastructure::memory::ledger::{
4 MapCharge, Owner, Tally, option_string_heap, string_heap, strings_heap,
5 },
6};
7use chrono::{DateTime, Utc};
8use dashmap::{DashMap, mapref::entry::Entry};
9use serde::{Deserialize, Serialize};
10use std::mem::size_of;
11use uuid::Uuid;
12
13#[derive(Debug, Clone, Serialize, Deserialize)]
15pub struct WebhookSubscription {
16 pub id: Uuid,
18 pub tenant_id: String,
20 pub url: String,
22 pub event_types: Vec<String>,
25 pub entity_ids: Vec<String>,
27 pub secret: String,
29 pub active: bool,
31 pub created_at: DateTime<Utc>,
33 pub updated_at: DateTime<Utc>,
35 pub description: Option<String>,
37}
38
39#[derive(Debug, Clone, Deserialize)]
41pub struct RegisterWebhookRequest {
42 pub tenant_id: String,
43 pub url: String,
44 #[serde(default)]
45 pub event_types: Vec<String>,
46 #[serde(default)]
47 pub entity_ids: Vec<String>,
48 pub secret: Option<String>,
49 pub description: Option<String>,
50}
51
52#[derive(Debug, Clone, Deserialize)]
54pub struct UpdateWebhookRequest {
55 pub url: Option<String>,
56 pub event_types: Option<Vec<String>>,
57 pub entity_ids: Option<Vec<String>>,
58 pub active: Option<bool>,
59 pub description: Option<String>,
60}
61
62#[derive(Debug, Clone, Serialize, Deserialize)]
64pub struct WebhookDelivery {
65 pub id: Uuid,
66 pub webhook_id: Uuid,
67 pub event_id: Uuid,
68 pub status: DeliveryStatus,
69 pub attempt: u32,
70 pub max_attempts: u32,
71 pub response_status: Option<u16>,
72 pub response_body: Option<String>,
73 pub error: Option<String>,
74 pub created_at: DateTime<Utc>,
75 pub next_retry_at: Option<DateTime<Utc>>,
76}
77
78#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
79#[serde(rename_all = "lowercase")]
80pub enum DeliveryStatus {
81 Pending,
82 Success,
83 Failed,
84 Retrying,
85}
86
87fn subscription_heap(webhook: &WebhookSubscription) -> u64 {
89 string_heap(&webhook.tenant_id)
90 + string_heap(&webhook.url)
91 + strings_heap(&webhook.event_types)
92 + strings_heap(&webhook.entity_ids)
93 + string_heap(&webhook.secret)
94 + option_string_heap(&webhook.description)
95}
96
97fn delivery_heap(delivery: &WebhookDelivery) -> u64 {
98 option_string_heap(&delivery.response_body) + option_string_heap(&delivery.error)
99}
100
101fn deliveries_heap(deliveries: &Vec<WebhookDelivery>) -> u64 {
103 (deliveries.capacity() * size_of::<WebhookDelivery>()) as u64
104 + deliveries.iter().map(delivery_heap).sum::<u64>()
105}
106
107pub struct WebhookRegistry {
109 webhooks: DashMap<Uuid, WebhookSubscription>,
111 webhooks_charge: MapCharge,
112 tenant_index: DashMap<String, Vec<Uuid>>,
114 tenant_index_charge: MapCharge,
115 deliveries: DashMap<Uuid, Vec<WebhookDelivery>>,
117 deliveries_charge: MapCharge,
118 vec_slots: Tally,
121}
122
123impl Default for WebhookRegistry {
124 fn default() -> Self {
125 Self::new()
126 }
127}
128
129impl WebhookRegistry {
130 pub fn new() -> Self {
131 Self {
132 webhooks: DashMap::new(),
133 webhooks_charge: MapCharge::new(Owner::Misc, size_of::<(Uuid, WebhookSubscription)>()),
134 tenant_index: DashMap::new(),
135 tenant_index_charge: MapCharge::new(Owner::Misc, size_of::<(String, Vec<Uuid>)>()),
136 deliveries: DashMap::new(),
137 deliveries_charge: MapCharge::new(
138 Owner::Misc,
139 size_of::<(Uuid, Vec<WebhookDelivery>)>(),
140 ),
141 vec_slots: Tally::new(Owner::Misc),
142 }
143 }
144
145 fn push_tenant_id(&self, tenant_id: String, id: Uuid) {
146 match self.tenant_index.entry(tenant_id) {
147 Entry::Occupied(mut slot) => self.push_id(slot.get_mut(), id),
148 Entry::Vacant(slot) => {
149 self.vec_slots.add(string_heap(slot.key()));
150 self.push_id(&mut slot.insert(Vec::new()), id);
151 }
152 }
153 self.tenant_index_charge.resize(&self.tenant_index);
154 }
155
156 fn push_id(&self, ids: &mut Vec<Uuid>, id: Uuid) {
157 let before = ids.capacity();
158 ids.push(id);
159 self.vec_slots
160 .grow(before, ids.capacity(), size_of::<Uuid>());
161 }
162
163 pub fn register(&self, req: RegisterWebhookRequest) -> WebhookSubscription {
165 let now = Utc::now();
166 let secret = req.secret.unwrap_or_else(|| {
167 format!("whsec_{}", Uuid::new_v4().to_string().replace('-', ""))
169 });
170
171 let webhook = WebhookSubscription {
172 id: Uuid::new_v4(),
173 tenant_id: req.tenant_id.clone(),
174 url: req.url,
175 event_types: req.event_types,
176 entity_ids: req.entity_ids,
177 secret,
178 active: true,
179 created_at: now,
180 updated_at: now,
181 description: req.description,
182 };
183
184 let id = webhook.id;
185 self.webhooks_charge
186 .insert(&self.webhooks, id, webhook.clone(), |_, w| {
187 subscription_heap(w)
188 });
189
190 self.push_tenant_id(req.tenant_id, id);
191
192 webhook
193 }
194
195 pub fn get(&self, id: Uuid) -> Option<WebhookSubscription> {
197 self.webhooks.get(&id).map(|w| w.clone())
198 }
199
200 pub fn list_by_tenant(&self, tenant_id: &str) -> Vec<WebhookSubscription> {
202 self.tenant_index
203 .get(tenant_id)
204 .map(|ids| {
205 ids.iter()
206 .filter_map(|id| self.webhooks.get(id).map(|w| w.clone()))
207 .collect()
208 })
209 .unwrap_or_default()
210 }
211
212 pub fn update(&self, id: Uuid, req: UpdateWebhookRequest) -> Option<WebhookSubscription> {
214 let mut webhook = self.webhooks.get_mut(&id)?;
215 let w = webhook.value_mut();
216 let heap_before = subscription_heap(w);
217
218 if let Some(url) = req.url {
219 w.url = url;
220 }
221 if let Some(event_types) = req.event_types {
222 w.event_types = event_types;
223 }
224 if let Some(entity_ids) = req.entity_ids {
225 w.entity_ids = entity_ids;
226 }
227 if let Some(active) = req.active {
228 w.active = active;
229 }
230 if let Some(description) = req.description {
231 w.description = Some(description);
232 }
233 w.updated_at = Utc::now();
234 self.webhooks_charge
235 .adjust_owned(heap_before, subscription_heap(w));
236
237 Some(w.clone())
238 }
239
240 pub fn delete(&self, id: Uuid) -> Option<WebhookSubscription> {
242 let webhook = self
243 .webhooks_charge
244 .remove_entry(&self.webhooks, &id, |_, w| subscription_heap(w))?;
245
246 if let Some(mut ids) = self.tenant_index.get_mut(&webhook.tenant_id) {
248 ids.retain(|wid| *wid != id);
249 }
250
251 if let Some((_, deliveries)) = self.deliveries.remove(&id) {
253 self.vec_slots.sub(deliveries_heap(&deliveries));
254 }
255 self.deliveries_charge.resize(&self.deliveries);
256
257 Some(webhook)
258 }
259
260 pub fn find_matching(&self, event: &Event) -> Vec<WebhookSubscription> {
262 let mut matching = Vec::new();
265
266 for entry in &self.webhooks {
267 let webhook = entry.value();
268 if !webhook.active {
269 continue;
270 }
271
272 if !webhook.event_types.is_empty()
274 && !webhook
275 .event_types
276 .iter()
277 .any(|pattern| matches_pattern(pattern, event.event_type_str()))
278 {
279 continue;
280 }
281
282 if !webhook.entity_ids.is_empty()
284 && !webhook
285 .entity_ids
286 .contains(&event.entity_id_str().to_string())
287 {
288 continue;
289 }
290
291 matching.push(webhook.clone());
292 }
293
294 matching
295 }
296
297 pub fn record_delivery(&self, delivery: WebhookDelivery) {
299 let webhook_id = delivery.webhook_id;
300 self.vec_slots.add(delivery_heap(&delivery));
301 let mut log = self.deliveries.entry(webhook_id).or_default();
302 let before = log.capacity();
303 log.push(delivery);
304 self.vec_slots
305 .grow(before, log.capacity(), size_of::<WebhookDelivery>());
306 drop(log);
307 self.deliveries_charge.resize(&self.deliveries);
308 }
309
310 pub fn get_deliveries(&self, webhook_id: Uuid, limit: usize) -> Vec<WebhookDelivery> {
312 self.deliveries
313 .get(&webhook_id)
314 .map(|deliveries| {
315 let d = deliveries.value();
316 let start = d.len().saturating_sub(limit);
317 d[start..].to_vec()
318 })
319 .unwrap_or_default()
320 }
321}
322
323fn matches_pattern(pattern: &str, value: &str) -> bool {
329 if pattern == "*" {
330 return true;
331 }
332 if let Some(prefix) = pattern.strip_suffix(".*") {
333 return value.starts_with(prefix) && value[prefix.len()..].starts_with('.');
334 }
335 pattern == value
336}
337
338#[cfg(test)]
339mod tests {
340 use super::*;
341
342 fn create_test_event(entity_id: &str, event_type: &str) -> Event {
343 Event::from_strings(
344 event_type.to_string(),
345 entity_id.to_string(),
346 "default".to_string(),
347 serde_json::json!({"test": true}),
348 None,
349 )
350 .unwrap()
351 }
352
353 #[test]
354 fn test_register_webhook() {
355 let registry = WebhookRegistry::new();
356
357 let webhook = registry.register(RegisterWebhookRequest {
358 tenant_id: "tenant-1".to_string(),
359 url: "https://example.com/webhook".to_string(),
360 event_types: vec!["user.*".to_string()],
361 entity_ids: vec![],
362 secret: Some("test-secret".to_string()),
363 description: Some("Test webhook".to_string()),
364 });
365
366 assert_eq!(webhook.url, "https://example.com/webhook");
367 assert_eq!(webhook.tenant_id, "tenant-1");
368 assert!(webhook.active);
369 assert_eq!(webhook.secret, "test-secret");
370 }
371
372 #[test]
373 fn test_get_webhook() {
374 let registry = WebhookRegistry::new();
375
376 let webhook = registry.register(RegisterWebhookRequest {
377 tenant_id: "tenant-1".to_string(),
378 url: "https://example.com/webhook".to_string(),
379 event_types: vec![],
380 entity_ids: vec![],
381 secret: None,
382 description: None,
383 });
384
385 let found = registry.get(webhook.id).unwrap();
386 assert_eq!(found.id, webhook.id);
387 assert_eq!(found.url, webhook.url);
388 }
389
390 #[test]
391 fn test_list_by_tenant() {
392 let registry = WebhookRegistry::new();
393
394 registry.register(RegisterWebhookRequest {
395 tenant_id: "tenant-1".to_string(),
396 url: "https://example.com/hook1".to_string(),
397 event_types: vec![],
398 entity_ids: vec![],
399 secret: None,
400 description: None,
401 });
402
403 registry.register(RegisterWebhookRequest {
404 tenant_id: "tenant-1".to_string(),
405 url: "https://example.com/hook2".to_string(),
406 event_types: vec![],
407 entity_ids: vec![],
408 secret: None,
409 description: None,
410 });
411
412 registry.register(RegisterWebhookRequest {
413 tenant_id: "tenant-2".to_string(),
414 url: "https://other.com/hook".to_string(),
415 event_types: vec![],
416 entity_ids: vec![],
417 secret: None,
418 description: None,
419 });
420
421 let tenant1_hooks = registry.list_by_tenant("tenant-1");
422 assert_eq!(tenant1_hooks.len(), 2);
423
424 let tenant2_hooks = registry.list_by_tenant("tenant-2");
425 assert_eq!(tenant2_hooks.len(), 1);
426 }
427
428 #[test]
429 fn test_update_webhook() {
430 let registry = WebhookRegistry::new();
431
432 let webhook = registry.register(RegisterWebhookRequest {
433 tenant_id: "tenant-1".to_string(),
434 url: "https://example.com/webhook".to_string(),
435 event_types: vec![],
436 entity_ids: vec![],
437 secret: None,
438 description: None,
439 });
440
441 let updated = registry
442 .update(
443 webhook.id,
444 UpdateWebhookRequest {
445 url: Some("https://example.com/new-url".to_string()),
446 event_types: Some(vec!["order.*".to_string()]),
447 entity_ids: None,
448 active: Some(false),
449 description: Some("Updated".to_string()),
450 },
451 )
452 .unwrap();
453
454 assert_eq!(updated.url, "https://example.com/new-url");
455 assert_eq!(updated.event_types, vec!["order.*".to_string()]);
456 assert!(!updated.active);
457 assert_eq!(updated.description, Some("Updated".to_string()));
458 }
459
460 #[test]
461 fn test_delete_webhook() {
462 let registry = WebhookRegistry::new();
463
464 let webhook = registry.register(RegisterWebhookRequest {
465 tenant_id: "tenant-1".to_string(),
466 url: "https://example.com/webhook".to_string(),
467 event_types: vec![],
468 entity_ids: vec![],
469 secret: None,
470 description: None,
471 });
472
473 let deleted = registry.delete(webhook.id);
474 assert!(deleted.is_some());
475 assert!(registry.get(webhook.id).is_none());
476 assert!(registry.list_by_tenant("tenant-1").is_empty());
477 }
478
479 #[test]
480 fn test_find_matching_all_events() {
481 let registry = WebhookRegistry::new();
482
483 registry.register(RegisterWebhookRequest {
484 tenant_id: "tenant-1".to_string(),
485 url: "https://example.com/all".to_string(),
486 event_types: vec![],
487 entity_ids: vec![],
488 secret: None,
489 description: None,
490 });
491
492 let event = create_test_event("entity-1", "user.created");
493 let matching = registry.find_matching(&event);
494 assert_eq!(matching.len(), 1);
495 }
496
497 #[test]
498 fn test_find_matching_event_type_wildcard() {
499 let registry = WebhookRegistry::new();
500
501 registry.register(RegisterWebhookRequest {
502 tenant_id: "tenant-1".to_string(),
503 url: "https://example.com/users".to_string(),
504 event_types: vec!["user.*".to_string()],
505 entity_ids: vec![],
506 secret: None,
507 description: None,
508 });
509
510 let user_event = create_test_event("entity-1", "user.created");
511 assert_eq!(registry.find_matching(&user_event).len(), 1);
512
513 let order_event = create_test_event("entity-1", "order.placed");
514 assert_eq!(registry.find_matching(&order_event).len(), 0);
515 }
516
517 #[test]
518 fn test_find_matching_entity_filter() {
519 let registry = WebhookRegistry::new();
520
521 registry.register(RegisterWebhookRequest {
522 tenant_id: "tenant-1".to_string(),
523 url: "https://example.com/entity".to_string(),
524 event_types: vec![],
525 entity_ids: vec!["entity-1".to_string()],
526 secret: None,
527 description: None,
528 });
529
530 let matching_event = create_test_event("entity-1", "user.created");
531 assert_eq!(registry.find_matching(&matching_event).len(), 1);
532
533 let non_matching = create_test_event("entity-2", "user.created");
534 assert_eq!(registry.find_matching(&non_matching).len(), 0);
535 }
536
537 #[test]
538 fn test_find_matching_inactive_skipped() {
539 let registry = WebhookRegistry::new();
540
541 let webhook = registry.register(RegisterWebhookRequest {
542 tenant_id: "tenant-1".to_string(),
543 url: "https://example.com/hook".to_string(),
544 event_types: vec![],
545 entity_ids: vec![],
546 secret: None,
547 description: None,
548 });
549
550 registry.update(
552 webhook.id,
553 UpdateWebhookRequest {
554 url: None,
555 event_types: None,
556 entity_ids: None,
557 active: Some(false),
558 description: None,
559 },
560 );
561
562 let event = create_test_event("entity-1", "user.created");
563 assert_eq!(registry.find_matching(&event).len(), 0);
564 }
565
566 #[test]
567 fn test_matches_pattern() {
568 assert!(matches_pattern("*", "anything"));
569 assert!(matches_pattern("user.created", "user.created"));
570 assert!(!matches_pattern("user.created", "user.updated"));
571 assert!(matches_pattern("user.*", "user.created"));
572 assert!(matches_pattern("user.*", "user.updated"));
573 assert!(!matches_pattern("user.*", "order.placed"));
574 assert!(!matches_pattern("user.*", "user"));
575 }
576
577 #[test]
578 fn test_record_and_get_deliveries() {
579 let registry = WebhookRegistry::new();
580 let webhook_id = Uuid::new_v4();
581
582 registry.record_delivery(WebhookDelivery {
583 id: Uuid::new_v4(),
584 webhook_id,
585 event_id: Uuid::new_v4(),
586 status: DeliveryStatus::Success,
587 attempt: 1,
588 max_attempts: 5,
589 response_status: Some(200),
590 response_body: None,
591 error: None,
592 created_at: Utc::now(),
593 next_retry_at: None,
594 });
595
596 registry.record_delivery(WebhookDelivery {
597 id: Uuid::new_v4(),
598 webhook_id,
599 event_id: Uuid::new_v4(),
600 status: DeliveryStatus::Failed,
601 attempt: 1,
602 max_attempts: 5,
603 response_status: Some(500),
604 response_body: Some("Internal error".to_string()),
605 error: None,
606 created_at: Utc::now(),
607 next_retry_at: None,
608 });
609
610 let deliveries = registry.get_deliveries(webhook_id, 10);
611 assert_eq!(deliveries.len(), 2);
612 assert_eq!(deliveries[0].status, DeliveryStatus::Success);
613 assert_eq!(deliveries[1].status, DeliveryStatus::Failed);
614 }
615
616 #[test]
617 fn test_auto_generated_secret() {
618 let registry = WebhookRegistry::new();
619
620 let webhook = registry.register(RegisterWebhookRequest {
621 tenant_id: "tenant-1".to_string(),
622 url: "https://example.com/hook".to_string(),
623 event_types: vec![],
624 entity_ids: vec![],
625 secret: None,
626 description: None,
627 });
628
629 assert!(webhook.secret.starts_with("whsec_"));
630 assert!(webhook.secret.len() > 10);
631 }
632}