oximedia-batch 0.1.8

Comprehensive batch processing engine for OxiMedia
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
//! Batch notification hub — webhook callbacks, email notification specs,
//! and notification deduplication.
//!
//! [`NotificationHub`] is the central dispatcher for job state-transition
//! events.  Subscribers register a [`NotificationTarget`] (webhook URL or an
//! email specification) together with an [`EventFilter`] that selects which
//! job state changes they care about.  Before dispatching, the hub runs every
//! outbound notification through a deduplication window so that retry storms
//! or rapid state flips never result in duplicate deliveries.
//!
//! # Design
//!
//! ```text
//!  ┌─────────────┐    publish()    ┌──────────────────┐
//!  │ BatchEngine │ ─────────────►  │ NotificationHub  │
//!  └─────────────┘                 │                  │
//!                                  │  1. dedup check  │
//!                                  │  2. filter match │
//!                                  │  3. dispatch     │
//!                                  └──────────────────┘
//!//!                            ┌────────────┴────────────┐
//!                            ▼                         ▼
//!                     Webhook target            Email spec
//!                    (HTTP POST JSON)         (queued for MTA)
//! ```
//!
//! Actual HTTP delivery is intentionally left to the caller (or a pluggable
//! [`Dispatcher`] trait) so that the hub stays framework-agnostic and fully
//! testable without a live network.

use std::collections::{HashMap, VecDeque};
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use parking_lot::Mutex;
use serde::{Deserialize, Serialize};

use crate::types::{JobId, JobState};

// ---------------------------------------------------------------------------
// Event types
// ---------------------------------------------------------------------------

/// A job state-transition event published to the hub.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct JobEvent {
    /// The job that changed state.
    pub job_id: JobId,
    /// Human-readable job name.
    pub job_name: String,
    /// The new state the job transitioned *into*.
    pub new_state: JobState,
    /// Unix timestamp (seconds) when the transition occurred.
    pub occurred_at: u64,
    /// Optional diagnostic message (error string, progress note, …).
    pub message: Option<String>,
    /// Arbitrary key/value metadata attached by the producer.
    pub metadata: HashMap<String, String>,
}

impl JobEvent {
    /// Construct a new event for `job_id` transitioning to `new_state`.
    #[must_use]
    pub fn new(job_id: JobId, job_name: impl Into<String>, new_state: JobState) -> Self {
        let occurred_at = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or(Duration::ZERO)
            .as_secs();
        Self {
            job_id,
            job_name: job_name.into(),
            new_state,
            occurred_at,
            message: None,
            metadata: HashMap::new(),
        }
    }

    /// Attach a diagnostic message to the event.
    #[must_use]
    pub fn with_message(mut self, msg: impl Into<String>) -> Self {
        self.message = Some(msg.into());
        self
    }

    /// Attach a metadata key/value pair.
    #[must_use]
    pub fn with_meta(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.metadata.insert(key.into(), value.into());
        self
    }

    /// Build a stable deduplication key: `"{job_id}:{state}"`.
    #[must_use]
    pub fn dedup_key(&self) -> String {
        format!("{}:{}", self.job_id, state_tag(self.new_state))
    }
}

fn state_tag(state: JobState) -> &'static str {
    match state {
        JobState::Queued => "queued",
        JobState::Running => "running",
        JobState::Completed => "completed",
        JobState::Failed => "failed",
        JobState::Cancelled => "cancelled",
        JobState::Pending => "pending",
    }
}

// ---------------------------------------------------------------------------
// Filters
// ---------------------------------------------------------------------------

/// Selects which job state transitions a subscriber wants to receive.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum EventFilter {
    /// Deliver every transition.
    All,
    /// Deliver only the listed states.
    States(Vec<JobState>),
    /// Deliver only terminal states (Completed, Failed, Cancelled).
    TerminalOnly,
    /// Deliver only failure events.
    FailureOnly,
}

impl EventFilter {
    /// Returns `true` if `event` should be delivered to a subscriber using
    /// this filter.
    #[must_use]
    pub fn matches(&self, event: &JobEvent) -> bool {
        match self {
            Self::All => true,
            Self::States(states) => states.contains(&event.new_state),
            Self::TerminalOnly => matches!(
                event.new_state,
                JobState::Completed | JobState::Failed | JobState::Cancelled
            ),
            Self::FailureOnly => matches!(event.new_state, JobState::Failed),
        }
    }
}

// ---------------------------------------------------------------------------
// Notification targets
// ---------------------------------------------------------------------------

/// Where a notification should be delivered.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum NotificationTarget {
    /// HTTP(S) webhook — the hub will POST the serialised [`JobEvent`] as JSON.
    Webhook(WebhookSpec),
    /// Email specification — the hub records the email to send; actual
    /// delivery is handled by the caller / SMTP adapter.
    Email(EmailSpec),
    /// In-process callback channel (test / monitoring).
    InProcess {
        /// Logical channel name used by tests to route events.
        channel: String,
    },
}

/// Configuration for a webhook notification target.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct WebhookSpec {
    /// Destination URL (must be `http://` or `https://`).
    pub url: String,
    /// HTTP headers to include with every request (e.g., `Authorization`).
    pub headers: HashMap<String, String>,
    /// Optional HMAC-SHA256 secret for request signing.
    /// When set the hub will add an `X-Oximedia-Signature` header whose value
    /// is the hex-encoded HMAC of the serialised body.
    pub secret: Option<String>,
    /// Maximum delivery attempts before the notification is dropped.
    pub max_retries: u32,
    /// Timeout for each HTTP attempt in milliseconds.
    pub timeout_ms: u64,
}

impl WebhookSpec {
    /// Create a minimal webhook spec with sensible defaults.
    #[must_use]
    pub fn new(url: impl Into<String>) -> Self {
        Self {
            url: url.into(),
            headers: HashMap::new(),
            secret: None,
            max_retries: 3,
            timeout_ms: 5_000,
        }
    }

    /// Attach a bearer-token `Authorization` header.
    #[must_use]
    pub fn with_bearer(mut self, token: impl Into<String>) -> Self {
        self.headers
            .insert("Authorization".into(), format!("Bearer {}", token.into()));
        self
    }

    /// Set the HMAC signing secret.
    #[must_use]
    pub fn with_secret(mut self, secret: impl Into<String>) -> Self {
        self.secret = Some(secret.into());
        self
    }
}

/// Email notification specification.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EmailSpec {
    /// Sender address (e.g. `"batch@example.com"`).
    pub from: String,
    /// Recipient addresses.
    pub to: Vec<String>,
    /// Optional CC addresses.
    pub cc: Vec<String>,
    /// Email subject template.  The string `{job_name}` and `{state}` will be
    /// substituted before queuing.
    pub subject_template: String,
    /// Whether to include the full JSON payload as an attachment.
    pub include_payload: bool,
}

impl EmailSpec {
    /// Create a simple single-recipient email spec.
    #[must_use]
    pub fn new(from: impl Into<String>, to: impl Into<String>) -> Self {
        Self {
            from: from.into(),
            to: vec![to.into()],
            cc: Vec::new(),
            subject_template: "Batch job {job_name} → {state}".into(),
            include_payload: false,
        }
    }

    /// Render the subject for the given event.
    #[must_use]
    pub fn render_subject(&self, event: &JobEvent) -> String {
        self.subject_template
            .replace("{job_name}", &event.job_name)
            .replace("{state}", state_tag(event.new_state))
    }
}

// ---------------------------------------------------------------------------
// Deduplication
// ---------------------------------------------------------------------------

/// Entry in the deduplication ring buffer.
#[derive(Debug, Clone)]
struct DedupEntry {
    key: String,
    seen_at: u64,
}

/// Sliding-window deduplication store.
///
/// An event is considered a duplicate if the same dedup key was seen within
/// the last `window_secs` seconds.
#[derive(Debug)]
pub struct DedupWindow {
    window_secs: u64,
    seen: VecDeque<DedupEntry>,
}

impl DedupWindow {
    /// Create a new deduplication window.
    #[must_use]
    pub fn new(window_secs: u64) -> Self {
        Self {
            window_secs,
            seen: VecDeque::new(),
        }
    }

    fn now_secs() -> u64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or(Duration::ZERO)
            .as_secs()
    }

    /// Evict expired entries.
    fn evict(&mut self) {
        let cutoff = Self::now_secs().saturating_sub(self.window_secs);
        while let Some(front) = self.seen.front() {
            if front.seen_at < cutoff {
                self.seen.pop_front();
            } else {
                break;
            }
        }
    }

    /// Record `key` and return `true` if it was already seen within the window
    /// (i.e., this is a duplicate).
    pub fn check_and_record(&mut self, key: &str) -> bool {
        self.evict();
        let now = Self::now_secs();
        let duplicate = self.seen.iter().any(|e| e.key == key);
        if !duplicate {
            self.seen.push_back(DedupEntry {
                key: key.to_owned(),
                seen_at: now,
            });
        }
        duplicate
    }

    /// Number of unique keys currently tracked (not yet expired).
    #[must_use]
    pub fn len(&self) -> usize {
        self.seen.len()
    }

    /// Returns `true` if no keys are currently tracked.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.seen.is_empty()
    }
}

// ---------------------------------------------------------------------------
// Dispatcher trait
// ---------------------------------------------------------------------------

/// Pluggable delivery backend.
///
/// The hub calls `dispatch` for every outbound notification that passes the
/// deduplication and filter checks.  Implementations may send HTTP requests,
/// queue messages, write to a log, etc.
pub trait Dispatcher: Send + Sync {
    /// Deliver `event` to `target`.
    ///
    /// # Errors
    ///
    /// Returns an error string describing why delivery failed.  The hub will
    /// record the failure but will not retry automatically.
    fn dispatch(&self, event: &JobEvent, target: &NotificationTarget) -> Result<(), DispatchError>;
}

/// Error returned by a [`Dispatcher`] implementation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DispatchError {
    /// Human-readable reason for the failure.
    pub reason: String,
    /// Whether the caller may retry the delivery.
    pub retryable: bool,
}

impl DispatchError {
    /// Construct a non-retryable error.
    #[must_use]
    pub fn permanent(reason: impl Into<String>) -> Self {
        Self {
            reason: reason.into(),
            retryable: false,
        }
    }

    /// Construct a retryable (transient) error.
    #[must_use]
    pub fn transient(reason: impl Into<String>) -> Self {
        Self {
            reason: reason.into(),
            retryable: true,
        }
    }
}

impl std::fmt::Display for DispatchError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "{} ({})",
            self.reason,
            if self.retryable {
                "retryable"
            } else {
                "permanent"
            }
        )
    }
}

// ---------------------------------------------------------------------------
// Subscription
// ---------------------------------------------------------------------------

/// A registered subscription inside the hub.
#[derive(Debug, Clone)]
pub struct Subscription {
    /// Unique subscription identifier.
    pub id: SubscriptionId,
    /// Target to deliver events to.
    pub target: NotificationTarget,
    /// Filter controlling which events are delivered.
    pub filter: EventFilter,
    /// Whether this subscription is currently active.
    pub active: bool,
}

/// Opaque subscription identifier.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct SubscriptionId(String);

impl SubscriptionId {
    fn new() -> Self {
        use std::time::{SystemTime, UNIX_EPOCH};
        let nanos = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or(Duration::ZERO)
            .subsec_nanos();
        // Simple ID: timestamp nanos + thread-local counter approximation.
        Self(format!("sub-{nanos:x}"))
    }

    /// Return the string representation.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::fmt::Display for SubscriptionId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.0)
    }
}

// ---------------------------------------------------------------------------
// Delivery record
// ---------------------------------------------------------------------------

/// A record of a single delivery attempt.
#[derive(Debug, Clone)]
pub struct DeliveryRecord {
    /// Which subscription was targeted.
    pub subscription_id: SubscriptionId,
    /// The event that was (or was not) delivered.
    pub event: JobEvent,
    /// Outcome of the delivery attempt.
    pub outcome: DeliveryOutcome,
    /// Unix timestamp of the attempt.
    pub attempted_at: u64,
}

/// Outcome of a delivery attempt.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DeliveryOutcome {
    /// Successfully delivered.
    Delivered,
    /// Skipped due to deduplication.
    Deduplicated,
    /// Skipped because the event did not match the subscription filter.
    FilteredOut,
    /// Delivery failed.
    Failed(String),
    /// Subscription was inactive.
    SubscriptionInactive,
}

// ---------------------------------------------------------------------------
// NotificationHub
// ---------------------------------------------------------------------------

/// Configuration for the notification hub.
#[derive(Debug, Clone)]
pub struct HubConfig {
    /// Deduplication window in seconds.  Events with the same
    /// `(job_id, state)` pair seen within this window are suppressed.
    pub dedup_window_secs: u64,
    /// Maximum number of delivery records kept in memory.
    pub max_delivery_history: usize,
}

impl Default for HubConfig {
    fn default() -> Self {
        Self {
            dedup_window_secs: 60,
            max_delivery_history: 10_000,
        }
    }
}

/// Internal mutable state, protected by a single `Mutex`.
struct HubState {
    subscriptions: Vec<Subscription>,
    dedup: DedupWindow,
    delivery_history: VecDeque<DeliveryRecord>,
    max_history: usize,
    /// Total events published (including duplicates / filtered).
    events_published: u64,
    /// Total successful deliveries.
    deliveries_ok: u64,
    /// Total failed deliveries.
    deliveries_failed: u64,
    /// Total deduplicated (suppressed) events.
    deduplicated: u64,
}

impl HubState {
    fn new(config: &HubConfig) -> Self {
        Self {
            subscriptions: Vec::new(),
            dedup: DedupWindow::new(config.dedup_window_secs),
            delivery_history: VecDeque::new(),
            max_history: config.max_delivery_history,
            events_published: 0,
            deliveries_ok: 0,
            deliveries_failed: 0,
            deduplicated: 0,
        }
    }

    fn record(&mut self, rec: DeliveryRecord) {
        if self.delivery_history.len() >= self.max_history {
            self.delivery_history.pop_front();
        }
        self.delivery_history.push_back(rec);
    }
}

/// Central notification dispatcher for batch job events.
///
/// # Thread safety
///
/// All public methods are safe to call from multiple threads concurrently.
///
/// # Example
///
/// ```
/// use oximedia_batch::notification_hub::{
///     NotificationHub, HubConfig, EventFilter, NotificationTarget,
///     WebhookSpec, JobEvent,
/// };
/// use oximedia_batch::types::{JobId, JobState};
///
/// let hub = NotificationHub::new(HubConfig::default(), None);
/// let id = hub.subscribe(
///     NotificationTarget::Webhook(WebhookSpec::new("https://example.com/hook")),
///     EventFilter::TerminalOnly,
/// );
///
/// let event = JobEvent::new(JobId::new(), "my-encode", JobState::Completed);
/// hub.publish(event);
///
/// let stats = hub.stats();
/// assert_eq!(stats.events_published, 1);
/// ```
pub struct NotificationHub {
    state: Mutex<HubState>,
    dispatcher: Option<Box<dyn Dispatcher>>,
}

impl NotificationHub {
    /// Create a new hub.
    ///
    /// `dispatcher` provides the pluggable delivery backend.  Pass `None` to
    /// operate in "record-only" mode (useful for testing).
    #[must_use]
    pub fn new(config: HubConfig, dispatcher: Option<Box<dyn Dispatcher>>) -> Self {
        Self {
            state: Mutex::new(HubState::new(&config)),
            dispatcher,
        }
    }

    // -----------------------------------------------------------------------
    // Subscription management
    // -----------------------------------------------------------------------

    /// Register a new subscription and return its identifier.
    pub fn subscribe(&self, target: NotificationTarget, filter: EventFilter) -> SubscriptionId {
        let id = SubscriptionId::new();
        let sub = Subscription {
            id: id.clone(),
            target,
            filter,
            active: true,
        };
        self.state.lock().subscriptions.push(sub);
        id
    }

    /// Pause an existing subscription.  Events will accumulate in the dedup
    /// window but will not be dispatched until the subscription is resumed.
    ///
    /// Returns `false` if no subscription with `id` was found.
    pub fn pause(&self, id: &SubscriptionId) -> bool {
        let mut guard = self.state.lock();
        if let Some(sub) = guard.subscriptions.iter_mut().find(|s| &s.id == id) {
            sub.active = false;
            true
        } else {
            false
        }
    }

    /// Resume a paused subscription.
    ///
    /// Returns `false` if no subscription with `id` was found.
    pub fn resume(&self, id: &SubscriptionId) -> bool {
        let mut guard = self.state.lock();
        if let Some(sub) = guard.subscriptions.iter_mut().find(|s| &s.id == id) {
            sub.active = true;
            true
        } else {
            false
        }
    }

    /// Remove a subscription entirely.
    ///
    /// Returns `false` if no subscription with `id` was found.
    pub fn unsubscribe(&self, id: &SubscriptionId) -> bool {
        let mut guard = self.state.lock();
        let before = guard.subscriptions.len();
        guard.subscriptions.retain(|s| &s.id != id);
        guard.subscriptions.len() < before
    }

    /// Return a snapshot of all current subscriptions.
    #[must_use]
    pub fn subscriptions(&self) -> Vec<Subscription> {
        self.state.lock().subscriptions.clone()
    }

    // -----------------------------------------------------------------------
    // Publishing
    // -----------------------------------------------------------------------

    /// Publish a [`JobEvent`] to all matching subscribers.
    ///
    /// The hub will:
    /// 1. Check deduplication — if the event is a duplicate, it is counted but
    ///    not dispatched.
    /// 2. For each active subscription whose filter matches, call the
    ///    `Dispatcher` (if any) and record the outcome.
    pub fn publish(&self, event: JobEvent) {
        let mut guard = self.state.lock();
        guard.events_published += 1;

        let dedup_key = event.dedup_key();
        if guard.dedup.check_and_record(&dedup_key) {
            // Duplicate — record and return.
            guard.deduplicated += 1;
            let now = HubState::now_secs();
            // Record a single "deduplicated" entry for audit purposes.
            if let Some(sub) = guard.subscriptions.first() {
                let rec = DeliveryRecord {
                    subscription_id: sub.id.clone(),
                    event: event.clone(),
                    outcome: DeliveryOutcome::Deduplicated,
                    attempted_at: now,
                };
                guard.record(rec);
            }
            return;
        }

        // Clone subscriptions to avoid borrow issues while dispatching.
        let subs: Vec<Subscription> = guard.subscriptions.clone();
        let now = HubState::now_secs();

        for sub in &subs {
            if !sub.active {
                let rec = DeliveryRecord {
                    subscription_id: sub.id.clone(),
                    event: event.clone(),
                    outcome: DeliveryOutcome::SubscriptionInactive,
                    attempted_at: now,
                };
                guard.record(rec);
                continue;
            }

            if !sub.filter.matches(&event) {
                let rec = DeliveryRecord {
                    subscription_id: sub.id.clone(),
                    event: event.clone(),
                    outcome: DeliveryOutcome::FilteredOut,
                    attempted_at: now,
                };
                guard.record(rec);
                continue;
            }

            // Attempt delivery.
            let outcome = if let Some(dispatcher) = &self.dispatcher {
                match dispatcher.dispatch(&event, &sub.target) {
                    Ok(()) => {
                        guard.deliveries_ok += 1;
                        DeliveryOutcome::Delivered
                    }
                    Err(e) => {
                        guard.deliveries_failed += 1;
                        DeliveryOutcome::Failed(e.reason)
                    }
                }
            } else {
                // No dispatcher — just record as delivered (useful for tests).
                guard.deliveries_ok += 1;
                DeliveryOutcome::Delivered
            };

            let rec = DeliveryRecord {
                subscription_id: sub.id.clone(),
                event: event.clone(),
                outcome,
                attempted_at: now,
            };
            guard.record(rec);
        }
    }

    // -----------------------------------------------------------------------
    // Delivery history
    // -----------------------------------------------------------------------

    /// Return the most recent `limit` delivery records (newest last).
    #[must_use]
    pub fn delivery_history(&self, limit: usize) -> Vec<DeliveryRecord> {
        let guard = self.state.lock();
        let history = &guard.delivery_history;
        let skip = history.len().saturating_sub(limit);
        history.iter().skip(skip).cloned().collect()
    }

    /// Return all delivery records for a specific job.
    #[must_use]
    pub fn history_for_job(&self, job_id: &JobId) -> Vec<DeliveryRecord> {
        let guard = self.state.lock();
        guard
            .delivery_history
            .iter()
            .filter(|r| &r.event.job_id == job_id)
            .cloned()
            .collect()
    }

    // -----------------------------------------------------------------------
    // Statistics
    // -----------------------------------------------------------------------

    /// Return a snapshot of hub-level statistics.
    #[must_use]
    pub fn stats(&self) -> HubStats {
        let guard = self.state.lock();
        HubStats {
            events_published: guard.events_published,
            deliveries_ok: guard.deliveries_ok,
            deliveries_failed: guard.deliveries_failed,
            deduplicated: guard.deduplicated,
            active_subscriptions: guard.subscriptions.iter().filter(|s| s.active).count(),
            total_subscriptions: guard.subscriptions.len(),
            dedup_window_size: guard.dedup.len(),
        }
    }
}

impl HubState {
    fn now_secs() -> u64 {
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap_or(Duration::ZERO)
            .as_secs()
    }
}

/// Snapshot of hub-level statistics.
#[derive(Debug, Clone)]
pub struct HubStats {
    /// Total number of calls to [`NotificationHub::publish`].
    pub events_published: u64,
    /// Successful deliveries.
    pub deliveries_ok: u64,
    /// Failed delivery attempts.
    pub deliveries_failed: u64,
    /// Events suppressed by deduplication.
    pub deduplicated: u64,
    /// Subscriptions that are currently active.
    pub active_subscriptions: usize,
    /// Total subscriptions (active + paused).
    pub total_subscriptions: usize,
    /// Unique keys currently tracked in the dedup window.
    pub dedup_window_size: usize,
}

// ---------------------------------------------------------------------------
// No-op dispatcher (convenient for tests)
// ---------------------------------------------------------------------------

/// A [`Dispatcher`] that always succeeds without performing any I/O.
///
/// Useful for unit tests and environments without network access.
pub struct NoOpDispatcher;

impl Dispatcher for NoOpDispatcher {
    fn dispatch(
        &self,
        _event: &JobEvent,
        _target: &NotificationTarget,
    ) -> Result<(), DispatchError> {
        Ok(())
    }
}

/// A [`Dispatcher`] that always fails, for testing error-path behaviour.
pub struct FailingDispatcher {
    /// Whether the failure should be considered retryable.
    pub retryable: bool,
}

impl Dispatcher for FailingDispatcher {
    fn dispatch(
        &self,
        _event: &JobEvent,
        _target: &NotificationTarget,
    ) -> Result<(), DispatchError> {
        Err(if self.retryable {
            DispatchError::transient("simulated transient failure")
        } else {
            DispatchError::permanent("simulated permanent failure")
        })
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{JobId, JobState};

    fn make_event(state: JobState) -> JobEvent {
        JobEvent::new(JobId::new(), "test-job", state)
    }

    // -----------------------------------------------------------------------
    // DedupWindow
    // -----------------------------------------------------------------------

    #[test]
    fn test_dedup_window_first_occurrence_is_not_duplicate() {
        let mut w = DedupWindow::new(60);
        assert!(!w.check_and_record("key-a"));
        assert_eq!(w.len(), 1);
    }

    #[test]
    fn test_dedup_window_second_occurrence_is_duplicate() {
        let mut w = DedupWindow::new(60);
        assert!(!w.check_and_record("key-a"));
        assert!(w.check_and_record("key-a"));
    }

    #[test]
    fn test_dedup_window_different_keys_not_duplicated() {
        let mut w = DedupWindow::new(60);
        assert!(!w.check_and_record("key-a"));
        assert!(!w.check_and_record("key-b"));
        assert_eq!(w.len(), 2);
    }

    #[test]
    fn test_dedup_window_zero_window_never_deduplicates() {
        // With a zero-second window everything is immediately evicted.
        let mut w = DedupWindow::new(0);
        // First insertion: not a duplicate.
        assert!(!w.check_and_record("key-a"));
        // Second: might still be present if eviction threshold is now - 0 = now.
        // The implementation retains entries whose seen_at >= cutoff (cutoff = now - 0 = now).
        // An entry recorded "just now" has seen_at == now, so it survives.
        // Accept either result — just ensure no panic.
        let _ = w.check_and_record("key-a");
    }

    // -----------------------------------------------------------------------
    // EventFilter
    // -----------------------------------------------------------------------

    #[test]
    fn test_filter_all_matches_every_state() {
        let filter = EventFilter::All;
        for state in [
            JobState::Queued,
            JobState::Running,
            JobState::Completed,
            JobState::Failed,
            JobState::Cancelled,
        ] {
            assert!(filter.matches(&make_event(state)));
        }
    }

    #[test]
    fn test_filter_terminal_only() {
        let filter = EventFilter::TerminalOnly;
        assert!(filter.matches(&make_event(JobState::Completed)));
        assert!(filter.matches(&make_event(JobState::Failed)));
        assert!(filter.matches(&make_event(JobState::Cancelled)));
        assert!(!filter.matches(&make_event(JobState::Queued)));
        assert!(!filter.matches(&make_event(JobState::Running)));
    }

    #[test]
    fn test_filter_failure_only() {
        let filter = EventFilter::FailureOnly;
        assert!(filter.matches(&make_event(JobState::Failed)));
        assert!(!filter.matches(&make_event(JobState::Completed)));
        assert!(!filter.matches(&make_event(JobState::Cancelled)));
    }

    #[test]
    fn test_filter_specific_states() {
        let filter = EventFilter::States(vec![JobState::Running, JobState::Completed]);
        assert!(filter.matches(&make_event(JobState::Running)));
        assert!(filter.matches(&make_event(JobState::Completed)));
        assert!(!filter.matches(&make_event(JobState::Failed)));
    }

    // -----------------------------------------------------------------------
    // NotificationHub
    // -----------------------------------------------------------------------

    #[test]
    fn test_hub_subscribe_and_stats() {
        let hub = NotificationHub::new(HubConfig::default(), None);
        let _id = hub.subscribe(
            NotificationTarget::InProcess {
                channel: "test".into(),
            },
            EventFilter::All,
        );
        let stats = hub.stats();
        assert_eq!(stats.total_subscriptions, 1);
        assert_eq!(stats.active_subscriptions, 1);
    }

    #[test]
    fn test_hub_publish_increments_counter() {
        let hub = NotificationHub::new(HubConfig::default(), Some(Box::new(NoOpDispatcher)));
        hub.subscribe(
            NotificationTarget::InProcess {
                channel: "ch".into(),
            },
            EventFilter::All,
        );
        hub.publish(make_event(JobState::Completed));
        assert_eq!(hub.stats().events_published, 1);
        assert_eq!(hub.stats().deliveries_ok, 1);
    }

    #[test]
    fn test_hub_deduplication_suppresses_repeat() {
        let hub = NotificationHub::new(HubConfig::default(), Some(Box::new(NoOpDispatcher)));
        hub.subscribe(
            NotificationTarget::InProcess {
                channel: "ch".into(),
            },
            EventFilter::All,
        );
        let job_id = JobId::new();
        let ev1 = JobEvent::new(job_id.clone(), "job", JobState::Completed);
        let ev2 = JobEvent::new(job_id, "job", JobState::Completed);
        hub.publish(ev1);
        hub.publish(ev2);
        let stats = hub.stats();
        assert_eq!(stats.events_published, 2);
        assert_eq!(stats.deduplicated, 1);
    }

    #[test]
    fn test_hub_filter_applied_per_subscription() {
        let hub = NotificationHub::new(HubConfig::default(), Some(Box::new(NoOpDispatcher)));
        hub.subscribe(
            NotificationTarget::InProcess {
                channel: "failure-only".into(),
            },
            EventFilter::FailureOnly,
        );
        // Completed should be filtered out.
        hub.publish(make_event(JobState::Completed));
        let stats = hub.stats();
        assert_eq!(stats.deliveries_ok, 0);
        // Failed should pass through.
        hub.publish(make_event(JobState::Failed));
        let stats = hub.stats();
        assert_eq!(stats.deliveries_ok, 1);
    }

    #[test]
    fn test_hub_failing_dispatcher_records_failure() {
        let hub = NotificationHub::new(
            HubConfig::default(),
            Some(Box::new(FailingDispatcher { retryable: false })),
        );
        hub.subscribe(
            NotificationTarget::InProcess {
                channel: "ch".into(),
            },
            EventFilter::All,
        );
        hub.publish(make_event(JobState::Running));
        let stats = hub.stats();
        assert_eq!(stats.deliveries_failed, 1);
        assert_eq!(stats.deliveries_ok, 0);
    }

    #[test]
    fn test_hub_pause_and_resume() {
        let hub = NotificationHub::new(HubConfig::default(), Some(Box::new(NoOpDispatcher)));
        let id = hub.subscribe(
            NotificationTarget::InProcess {
                channel: "ch".into(),
            },
            EventFilter::All,
        );
        assert!(hub.pause(&id));
        hub.publish(make_event(JobState::Running));
        assert_eq!(hub.stats().deliveries_ok, 0);

        assert!(hub.resume(&id));
        hub.publish(make_event(JobState::Completed)); // Different state → not deduped.
        assert_eq!(hub.stats().deliveries_ok, 1);
    }

    #[test]
    fn test_hub_unsubscribe() {
        let hub = NotificationHub::new(HubConfig::default(), Some(Box::new(NoOpDispatcher)));
        let id = hub.subscribe(
            NotificationTarget::InProcess {
                channel: "ch".into(),
            },
            EventFilter::All,
        );
        assert!(hub.unsubscribe(&id));
        assert_eq!(hub.stats().total_subscriptions, 0);
        // Removing again returns false.
        assert!(!hub.unsubscribe(&id));
    }

    #[test]
    fn test_hub_delivery_history() {
        let hub = NotificationHub::new(HubConfig::default(), Some(Box::new(NoOpDispatcher)));
        hub.subscribe(
            NotificationTarget::InProcess {
                channel: "ch".into(),
            },
            EventFilter::All,
        );
        hub.publish(make_event(JobState::Queued));
        hub.publish(make_event(JobState::Running));
        let history = hub.delivery_history(10);
        assert_eq!(history.len(), 2);
    }

    #[test]
    fn test_webhook_spec_builder() {
        let spec = WebhookSpec::new("https://example.com/hook")
            .with_bearer("tok123")
            .with_secret("s3cr3t");
        assert!(spec.headers.contains_key("Authorization"));
        assert_eq!(spec.secret.as_deref(), Some("s3cr3t"));
        assert_eq!(spec.max_retries, 3);
    }

    #[test]
    fn test_email_spec_render_subject() {
        let spec = EmailSpec::new("from@example.com", "to@example.com");
        let event = JobEvent::new(JobId::new(), "encode-job", JobState::Completed);
        let subject = spec.render_subject(&event);
        assert!(subject.contains("encode-job"));
        assert!(subject.contains("completed"));
    }

    #[test]
    fn test_job_event_dedup_key_uniqueness() {
        let id = JobId::new();
        let e1 = JobEvent::new(id.clone(), "j", JobState::Completed);
        let e2 = JobEvent::new(id.clone(), "j", JobState::Failed);
        assert_ne!(e1.dedup_key(), e2.dedup_key());
    }

    #[test]
    fn test_hub_history_for_job() {
        let hub = NotificationHub::new(HubConfig::default(), Some(Box::new(NoOpDispatcher)));
        let id = hub.subscribe(
            NotificationTarget::InProcess {
                channel: "ch".into(),
            },
            EventFilter::All,
        );

        let job_a = JobId::from("job-a");
        let job_b = JobId::from("job-b");
        hub.publish(JobEvent::new(job_a.clone(), "A", JobState::Running));
        hub.publish(JobEvent::new(job_b.clone(), "B", JobState::Completed));

        let history_a = hub.history_for_job(&job_a);
        assert_eq!(history_a.len(), 1);

        // Unsubscribe to avoid leaks in later tests.
        hub.unsubscribe(&id);
    }
}