mabi-knx 1.4.0

Mabinogion - KNXnet/IP simulator
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
//! Heartbeat action system for KNXnet/IP connection state simulation.
//!
//! This module provides a production-grade heartbeat response engine that
//! supports all 5 HeartbeatAction types defined by the KNXnet/IP spec:
//!
//! 1. **Continue** — Normal heartbeat response (status 0x00)
//! 2. **ImmediateReconnect** — Force client to reconnect immediately (status 0x21)
//! 3. **AbandonTunnel** — Signal unrecoverable tunnel failure (status 0x27)
//! 4. **DelayedReconnect** — Signal temporary unavailability (status 0x29)
//! 5. **NoResponse** — Simulate heartbeat timeout (no response sent)
//!
//! ## Scheduling
//!
//! The [`HeartbeatScheduler`] supports multiple scheduling strategies:
//!
//! - **Override**: Static override returning the same action for every heartbeat
//! - **Sequence**: Ordered list of actions, advancing through the list
//! - **Periodic**: Inject a fault action every N heartbeats
//! - **Probabilistic**: Random action selection with configurable probability
//! - **CountdownToFailure**: Normal for N heartbeats, then fail permanently
//!
//! ## Integration
//!
//! The heartbeat scheduler is integrated into `KnxServer::handle_connection_state_request()`.
//! When the scheduler is active, it determines the response status code instead of
//! the default behavior.

use std::fmt;
use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};

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

// ============================================================================
// HeartbeatAction — 5 action types
// ============================================================================

/// Heartbeat action determining how the server responds to connection state requests.
///
/// Maps to KNXnet/IP connection state response status codes:
/// - Continue → 0x00 (E_NO_ERROR)
/// - ImmediateReconnect → 0x21 (E_CONNECTION_ID)
/// - AbandonTunnel → 0x27 (E_KNX_CONNECTION)
/// - DelayedReconnect → 0x29 (E_TUNNELLING_LAYER)
/// - NoResponse → packet dropped (simulates timeout)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum HeartbeatAction {
    /// Normal heartbeat — respond with 0x00 (no error).
    Continue,
    /// Force immediate reconnection — respond with 0x21 (E_CONNECTION_ID).
    ImmediateReconnect,
    /// Abandon the tunnel — respond with 0x27 (E_KNX_CONNECTION).
    AbandonTunnel,
    /// Delayed reconnection — respond with 0x29 (E_TUNNELLING_LAYER).
    DelayedReconnect,
    /// Suppress the heartbeat response entirely (simulates timeout).
    NoResponse,
}

impl HeartbeatAction {
    /// Get the KNXnet/IP status code for this action.
    ///
    /// Returns `None` for `NoResponse` (no packet should be sent).
    pub fn status_code(&self) -> Option<u8> {
        match self {
            Self::Continue => Some(0x00),
            Self::ImmediateReconnect => Some(0x21),
            Self::AbandonTunnel => Some(0x27),
            Self::DelayedReconnect => Some(0x29),
            Self::NoResponse => None,
        }
    }

    /// Parse a status code into a HeartbeatAction.
    pub fn from_status_code(code: u8) -> Self {
        match code {
            0x00 => Self::Continue,
            0x21 => Self::ImmediateReconnect,
            0x27 => Self::AbandonTunnel,
            0x29 => Self::DelayedReconnect,
            _ => Self::Continue, // Unknown codes default to Continue
        }
    }

    /// Whether this action results in a response being sent.
    pub fn sends_response(&self) -> bool {
        !matches!(self, Self::NoResponse)
    }

    /// Whether this action indicates the connection should be terminated.
    pub fn is_terminal(&self) -> bool {
        matches!(self, Self::AbandonTunnel)
    }

    /// Whether this action indicates the client should reconnect.
    pub fn requires_reconnect(&self) -> bool {
        matches!(self, Self::ImmediateReconnect | Self::DelayedReconnect)
    }

    /// Whether this action indicates normal operation.
    pub fn is_normal(&self) -> bool {
        matches!(self, Self::Continue)
    }

    /// All possible actions.
    pub fn all() -> &'static [HeartbeatAction] {
        &[
            Self::Continue,
            Self::ImmediateReconnect,
            Self::AbandonTunnel,
            Self::DelayedReconnect,
            Self::NoResponse,
        ]
    }

    /// Human-readable name.
    pub fn name(&self) -> &'static str {
        match self {
            Self::Continue => "Continue",
            Self::ImmediateReconnect => "ImmediateReconnect",
            Self::AbandonTunnel => "AbandonTunnel",
            Self::DelayedReconnect => "DelayedReconnect",
            Self::NoResponse => "NoResponse",
        }
    }
}

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

// ============================================================================
// HeartbeatSchedule — scheduling strategies
// ============================================================================

/// Scheduling strategy for heartbeat actions.
///
/// Controls how the server determines the heartbeat response for each
/// incoming connection state request.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum HeartbeatSchedule {
    /// Always return the default action (Continue).
    Normal,

    /// Static override — always return the specified action.
    Override { action: HeartbeatAction },

    /// Ordered sequence of actions — advances through the list, repeating
    /// the last action when exhausted.
    Sequence { actions: Vec<HeartbeatAction> },

    /// Inject a fault action every N heartbeats.
    /// Normal heartbeats return Continue, every `interval`th returns the fault action.
    Periodic {
        /// Fault action to inject.
        action: HeartbeatAction,
        /// Inject fault every N heartbeats (1-based).
        interval: u32,
    },

    /// Probabilistic fault injection.
    /// Each heartbeat has `probability` chance of returning the fault action.
    Probabilistic {
        /// Fault action to inject.
        action: HeartbeatAction,
        /// Probability of fault (0.0 - 1.0).
        probability: f64,
    },

    /// Normal for the first N heartbeats, then fail permanently.
    CountdownToFailure {
        /// Failure action.
        action: HeartbeatAction,
        /// Number of normal heartbeats before failure.
        countdown: u32,
    },
}

impl Default for HeartbeatSchedule {
    fn default() -> Self {
        Self::Normal
    }
}

impl HeartbeatSchedule {
    /// Validate the schedule configuration.
    pub fn validate(&self) -> Result<(), String> {
        match self {
            Self::Normal | Self::Override { .. } => Ok(()),
            Self::Sequence { actions } => {
                if actions.is_empty() {
                    Err("HeartbeatSchedule::Sequence requires at least one action".to_string())
                } else {
                    Ok(())
                }
            }
            Self::Periodic { interval, .. } => {
                if *interval == 0 {
                    Err("HeartbeatSchedule::Periodic interval must be > 0".to_string())
                } else {
                    Ok(())
                }
            }
            Self::Probabilistic { probability, .. } => {
                if *probability < 0.0 || *probability > 1.0 {
                    Err(format!(
                        "HeartbeatSchedule::Probabilistic probability must be 0.0-1.0, got {}",
                        probability
                    ))
                } else {
                    Ok(())
                }
            }
            Self::CountdownToFailure { countdown, .. } => {
                if *countdown == 0 {
                    Err("HeartbeatSchedule::CountdownToFailure countdown must be > 0".to_string())
                } else {
                    Ok(())
                }
            }
        }
    }
}

// ============================================================================
// HeartbeatScheduler — runtime scheduler
// ============================================================================

/// Runtime heartbeat scheduler that determines the response action for each
/// incoming connection state request.
///
/// Thread-safe — uses atomic counters and a read-write lock for schedule updates.
pub struct HeartbeatScheduler {
    /// Current schedule.
    schedule: RwLock<HeartbeatSchedule>,
    /// Heartbeat counter (total requests processed).
    counter: AtomicU32,
    /// Per-channel heartbeat counter for sequence advancement.
    /// Packed as: (channel_id << 24) | counter
    /// For simplicity, we use a global sequence index.
    sequence_index: AtomicU32,
    /// Statistics.
    stats: HeartbeatStats,
}

/// Heartbeat scheduler statistics.
pub struct HeartbeatStats {
    /// Total heartbeat requests processed.
    pub total_requests: AtomicU64,
    /// Normal (Continue) responses.
    pub continue_count: AtomicU64,
    /// ImmediateReconnect responses.
    pub immediate_reconnect_count: AtomicU64,
    /// AbandonTunnel responses.
    pub abandon_tunnel_count: AtomicU64,
    /// DelayedReconnect responses.
    pub delayed_reconnect_count: AtomicU64,
    /// NoResponse (timeout) count.
    pub no_response_count: AtomicU64,
}

impl HeartbeatStats {
    fn new() -> Self {
        Self {
            total_requests: AtomicU64::new(0),
            continue_count: AtomicU64::new(0),
            immediate_reconnect_count: AtomicU64::new(0),
            abandon_tunnel_count: AtomicU64::new(0),
            delayed_reconnect_count: AtomicU64::new(0),
            no_response_count: AtomicU64::new(0),
        }
    }

    fn record(&self, action: HeartbeatAction) {
        self.total_requests.fetch_add(1, Ordering::Relaxed);
        match action {
            HeartbeatAction::Continue => {
                self.continue_count.fetch_add(1, Ordering::Relaxed);
            }
            HeartbeatAction::ImmediateReconnect => {
                self.immediate_reconnect_count
                    .fetch_add(1, Ordering::Relaxed);
            }
            HeartbeatAction::AbandonTunnel => {
                self.abandon_tunnel_count.fetch_add(1, Ordering::Relaxed);
            }
            HeartbeatAction::DelayedReconnect => {
                self.delayed_reconnect_count.fetch_add(1, Ordering::Relaxed);
            }
            HeartbeatAction::NoResponse => {
                self.no_response_count.fetch_add(1, Ordering::Relaxed);
            }
        }
    }

    /// Take a snapshot of the statistics.
    pub fn snapshot(&self) -> HeartbeatStatsSnapshot {
        HeartbeatStatsSnapshot {
            total_requests: self.total_requests.load(Ordering::Relaxed),
            continue_count: self.continue_count.load(Ordering::Relaxed),
            immediate_reconnect_count: self.immediate_reconnect_count.load(Ordering::Relaxed),
            abandon_tunnel_count: self.abandon_tunnel_count.load(Ordering::Relaxed),
            delayed_reconnect_count: self.delayed_reconnect_count.load(Ordering::Relaxed),
            no_response_count: self.no_response_count.load(Ordering::Relaxed),
        }
    }
}

/// Immutable snapshot of heartbeat statistics.
#[derive(Debug, Clone)]
pub struct HeartbeatStatsSnapshot {
    pub total_requests: u64,
    pub continue_count: u64,
    pub immediate_reconnect_count: u64,
    pub abandon_tunnel_count: u64,
    pub delayed_reconnect_count: u64,
    pub no_response_count: u64,
}

impl HeartbeatStatsSnapshot {
    /// Fault rate (non-Continue / total).
    pub fn fault_rate(&self) -> f64 {
        if self.total_requests == 0 {
            return 0.0;
        }
        let faults = self.total_requests - self.continue_count;
        faults as f64 / self.total_requests as f64
    }
}

impl HeartbeatScheduler {
    /// Create a new scheduler with the given schedule.
    pub fn new(schedule: HeartbeatSchedule) -> Self {
        Self {
            schedule: RwLock::new(schedule),
            counter: AtomicU32::new(0),
            sequence_index: AtomicU32::new(0),
            stats: HeartbeatStats::new(),
        }
    }

    /// Create a scheduler with default (Normal) schedule.
    pub fn normal() -> Self {
        Self::new(HeartbeatSchedule::Normal)
    }

    /// Update the schedule at runtime.
    pub fn set_schedule(&self, schedule: HeartbeatSchedule) {
        *self.schedule.write() = schedule;
        self.counter.store(0, Ordering::Relaxed);
        self.sequence_index.store(0, Ordering::Relaxed);
    }

    /// Get the current schedule (clone).
    pub fn schedule(&self) -> HeartbeatSchedule {
        self.schedule.read().clone()
    }

    /// Get statistics snapshot.
    pub fn stats_snapshot(&self) -> HeartbeatStatsSnapshot {
        self.stats.snapshot()
    }

    /// Get the total heartbeat count.
    pub fn heartbeat_count(&self) -> u32 {
        self.counter.load(Ordering::Relaxed)
    }

    /// Reset the scheduler state (counter, sequence index).
    pub fn reset(&self) {
        self.counter.store(0, Ordering::Relaxed);
        self.sequence_index.store(0, Ordering::Relaxed);
    }

    /// Determine the next heartbeat action.
    ///
    /// This is the core scheduling method. It reads the current schedule,
    /// advances internal counters, and returns the appropriate action.
    ///
    /// # Arguments
    /// * `channel_id` — The channel for which the heartbeat was received
    pub fn next_action(&self, _channel_id: u8) -> HeartbeatAction {
        let count = self.counter.fetch_add(1, Ordering::Relaxed);
        let schedule = self.schedule.read();

        let action = match &*schedule {
            HeartbeatSchedule::Normal => HeartbeatAction::Continue,

            HeartbeatSchedule::Override { action } => *action,

            HeartbeatSchedule::Sequence { actions } => {
                let idx = self.sequence_index.fetch_add(1, Ordering::Relaxed) as usize;
                if idx < actions.len() {
                    actions[idx]
                } else {
                    // Repeat last action when sequence is exhausted
                    *actions.last().unwrap_or(&HeartbeatAction::Continue)
                }
            }

            HeartbeatSchedule::Periodic { action, interval } => {
                // 1-based: first heartbeat is 1, inject at multiples of interval
                let one_based = count + 1;
                if one_based % *interval == 0 {
                    *action
                } else {
                    HeartbeatAction::Continue
                }
            }

            HeartbeatSchedule::Probabilistic {
                action,
                probability,
            } => {
                let random = heartbeat_rand();
                if random < *probability {
                    *action
                } else {
                    HeartbeatAction::Continue
                }
            }

            HeartbeatSchedule::CountdownToFailure { action, countdown } => {
                if count >= *countdown {
                    *action
                } else {
                    HeartbeatAction::Continue
                }
            }
        };

        self.stats.record(action);
        action
    }
}

impl fmt::Debug for HeartbeatScheduler {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("HeartbeatScheduler")
            .field("schedule", &*self.schedule.read())
            .field("counter", &self.counter.load(Ordering::Relaxed))
            .field(
                "sequence_index",
                &self.sequence_index.load(Ordering::Relaxed),
            )
            .finish()
    }
}

// ============================================================================
// HeartbeatSchedulerConfig — serde config
// ============================================================================

/// Configuration for the heartbeat scheduler.
///
/// This is used in `TunnelBehaviorConfig` and supports YAML/JSON deserialization.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HeartbeatSchedulerConfig {
    /// Whether the scheduler is enabled.
    /// When disabled, normal heartbeat behavior is used.
    #[serde(default = "default_false")]
    pub enabled: bool,

    /// The scheduling strategy.
    #[serde(default)]
    pub schedule: HeartbeatSchedule,
}

fn default_false() -> bool {
    false
}

impl Default for HeartbeatSchedulerConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            schedule: HeartbeatSchedule::default(),
        }
    }
}

impl HeartbeatSchedulerConfig {
    /// Validate the configuration.
    pub fn validate(&self) -> Result<(), String> {
        if self.enabled {
            self.schedule.validate()
        } else {
            Ok(())
        }
    }
}

// ============================================================================
// Simple PRNG for probabilistic scheduling
// ============================================================================

/// Simple thread-local PRNG for heartbeat scheduling.
/// No cryptographic strength needed — just reasonable distribution.
fn heartbeat_rand() -> f64 {
    use std::cell::Cell;
    thread_local! {
        static STATE: Cell<u64> = Cell::new(0xDEAD_BEEF_CAFE_BABEu64);
    }
    STATE.with(|s| {
        let mut x = s.get();
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        s.set(x);
        (x as f64) / (u64::MAX as f64)
    })
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_heartbeat_action_status_codes() {
        assert_eq!(HeartbeatAction::Continue.status_code(), Some(0x00));
        assert_eq!(
            HeartbeatAction::ImmediateReconnect.status_code(),
            Some(0x21)
        );
        assert_eq!(HeartbeatAction::AbandonTunnel.status_code(), Some(0x27));
        assert_eq!(HeartbeatAction::DelayedReconnect.status_code(), Some(0x29));
        assert_eq!(HeartbeatAction::NoResponse.status_code(), None);
    }

    #[test]
    fn test_heartbeat_action_from_status_code() {
        assert_eq!(
            HeartbeatAction::from_status_code(0x00),
            HeartbeatAction::Continue
        );
        assert_eq!(
            HeartbeatAction::from_status_code(0x21),
            HeartbeatAction::ImmediateReconnect
        );
        assert_eq!(
            HeartbeatAction::from_status_code(0x27),
            HeartbeatAction::AbandonTunnel
        );
        assert_eq!(
            HeartbeatAction::from_status_code(0x29),
            HeartbeatAction::DelayedReconnect
        );
        assert_eq!(
            HeartbeatAction::from_status_code(0xFF),
            HeartbeatAction::Continue
        );
    }

    #[test]
    fn test_heartbeat_action_properties() {
        assert!(HeartbeatAction::Continue.is_normal());
        assert!(!HeartbeatAction::Continue.is_terminal());
        assert!(!HeartbeatAction::Continue.requires_reconnect());
        assert!(HeartbeatAction::Continue.sends_response());

        assert!(HeartbeatAction::AbandonTunnel.is_terminal());
        assert!(!HeartbeatAction::AbandonTunnel.is_normal());

        assert!(HeartbeatAction::ImmediateReconnect.requires_reconnect());
        assert!(HeartbeatAction::DelayedReconnect.requires_reconnect());
        assert!(!HeartbeatAction::AbandonTunnel.requires_reconnect());

        assert!(!HeartbeatAction::NoResponse.sends_response());
    }

    #[test]
    fn test_heartbeat_action_all() {
        let all = HeartbeatAction::all();
        assert_eq!(all.len(), 5);
    }

    #[test]
    fn test_heartbeat_action_display() {
        assert_eq!(format!("{}", HeartbeatAction::Continue), "Continue");
        assert_eq!(
            format!("{}", HeartbeatAction::ImmediateReconnect),
            "ImmediateReconnect"
        );
        assert_eq!(
            format!("{}", HeartbeatAction::AbandonTunnel),
            "AbandonTunnel"
        );
        assert_eq!(
            format!("{}", HeartbeatAction::DelayedReconnect),
            "DelayedReconnect"
        );
        assert_eq!(format!("{}", HeartbeatAction::NoResponse), "NoResponse");
    }

    #[test]
    fn test_schedule_normal() {
        let scheduler = HeartbeatScheduler::normal();
        assert_eq!(scheduler.next_action(1), HeartbeatAction::Continue);
        assert_eq!(scheduler.next_action(1), HeartbeatAction::Continue);
        assert_eq!(scheduler.heartbeat_count(), 2);
    }

    #[test]
    fn test_schedule_override() {
        let scheduler = HeartbeatScheduler::new(HeartbeatSchedule::Override {
            action: HeartbeatAction::ImmediateReconnect,
        });

        assert_eq!(
            scheduler.next_action(1),
            HeartbeatAction::ImmediateReconnect
        );
        assert_eq!(
            scheduler.next_action(1),
            HeartbeatAction::ImmediateReconnect
        );
        assert_eq!(
            scheduler.next_action(2),
            HeartbeatAction::ImmediateReconnect
        );
    }

    #[test]
    fn test_schedule_sequence() {
        let scheduler = HeartbeatScheduler::new(HeartbeatSchedule::Sequence {
            actions: vec![
                HeartbeatAction::Continue,
                HeartbeatAction::ImmediateReconnect,
                HeartbeatAction::AbandonTunnel,
            ],
        });

        assert_eq!(scheduler.next_action(1), HeartbeatAction::Continue);
        assert_eq!(
            scheduler.next_action(1),
            HeartbeatAction::ImmediateReconnect
        );
        assert_eq!(scheduler.next_action(1), HeartbeatAction::AbandonTunnel);
        // Beyond sequence — repeats last
        assert_eq!(scheduler.next_action(1), HeartbeatAction::AbandonTunnel);
        assert_eq!(scheduler.next_action(1), HeartbeatAction::AbandonTunnel);
    }

    #[test]
    fn test_schedule_periodic() {
        let scheduler = HeartbeatScheduler::new(HeartbeatSchedule::Periodic {
            action: HeartbeatAction::AbandonTunnel,
            interval: 3,
        });

        // Heartbeats: 1=Continue, 2=Continue, 3=Fault, 4=Continue, 5=Continue, 6=Fault
        assert_eq!(scheduler.next_action(1), HeartbeatAction::Continue); // count=0, 1-based=1
        assert_eq!(scheduler.next_action(1), HeartbeatAction::Continue); // count=1, 1-based=2
        assert_eq!(scheduler.next_action(1), HeartbeatAction::AbandonTunnel); // count=2, 1-based=3
        assert_eq!(scheduler.next_action(1), HeartbeatAction::Continue); // count=3, 1-based=4
        assert_eq!(scheduler.next_action(1), HeartbeatAction::Continue); // count=4, 1-based=5
        assert_eq!(scheduler.next_action(1), HeartbeatAction::AbandonTunnel); // count=5, 1-based=6
    }

    #[test]
    fn test_schedule_countdown_to_failure() {
        let scheduler = HeartbeatScheduler::new(HeartbeatSchedule::CountdownToFailure {
            action: HeartbeatAction::ImmediateReconnect,
            countdown: 3,
        });

        assert_eq!(scheduler.next_action(1), HeartbeatAction::Continue); // 0 < 3
        assert_eq!(scheduler.next_action(1), HeartbeatAction::Continue); // 1 < 3
        assert_eq!(scheduler.next_action(1), HeartbeatAction::Continue); // 2 < 3
        assert_eq!(
            scheduler.next_action(1),
            HeartbeatAction::ImmediateReconnect
        ); // 3 >= 3
        assert_eq!(
            scheduler.next_action(1),
            HeartbeatAction::ImmediateReconnect
        ); // 4 >= 3
    }

    #[test]
    fn test_schedule_probabilistic() {
        let scheduler = HeartbeatScheduler::new(HeartbeatSchedule::Probabilistic {
            action: HeartbeatAction::NoResponse,
            probability: 0.0,
        });

        // probability=0.0 → always Continue
        for _ in 0..20 {
            assert_eq!(scheduler.next_action(1), HeartbeatAction::Continue);
        }

        let scheduler = HeartbeatScheduler::new(HeartbeatSchedule::Probabilistic {
            action: HeartbeatAction::NoResponse,
            probability: 1.0,
        });

        // probability=1.0 → always NoResponse
        for _ in 0..20 {
            assert_eq!(scheduler.next_action(1), HeartbeatAction::NoResponse);
        }
    }

    #[test]
    fn test_scheduler_set_schedule() {
        let scheduler = HeartbeatScheduler::normal();
        assert_eq!(scheduler.next_action(1), HeartbeatAction::Continue);

        scheduler.set_schedule(HeartbeatSchedule::Override {
            action: HeartbeatAction::AbandonTunnel,
        });
        assert_eq!(scheduler.next_action(1), HeartbeatAction::AbandonTunnel);
        assert_eq!(scheduler.heartbeat_count(), 1); // Counter was reset
    }

    #[test]
    fn test_scheduler_reset() {
        let scheduler = HeartbeatScheduler::new(HeartbeatSchedule::Sequence {
            actions: vec![
                HeartbeatAction::Continue,
                HeartbeatAction::ImmediateReconnect,
            ],
        });

        assert_eq!(scheduler.next_action(1), HeartbeatAction::Continue);
        assert_eq!(
            scheduler.next_action(1),
            HeartbeatAction::ImmediateReconnect
        );

        scheduler.reset();

        // After reset, sequence starts over
        assert_eq!(scheduler.next_action(1), HeartbeatAction::Continue);
        assert_eq!(
            scheduler.next_action(1),
            HeartbeatAction::ImmediateReconnect
        );
    }

    #[test]
    fn test_scheduler_stats() {
        let scheduler = HeartbeatScheduler::new(HeartbeatSchedule::Sequence {
            actions: vec![
                HeartbeatAction::Continue,
                HeartbeatAction::ImmediateReconnect,
                HeartbeatAction::AbandonTunnel,
                HeartbeatAction::DelayedReconnect,
                HeartbeatAction::NoResponse,
            ],
        });

        for _ in 0..5 {
            scheduler.next_action(1);
        }

        let stats = scheduler.stats_snapshot();
        assert_eq!(stats.total_requests, 5);
        assert_eq!(stats.continue_count, 1);
        assert_eq!(stats.immediate_reconnect_count, 1);
        assert_eq!(stats.abandon_tunnel_count, 1);
        assert_eq!(stats.delayed_reconnect_count, 1);
        assert_eq!(stats.no_response_count, 1);
    }

    #[test]
    fn test_stats_fault_rate() {
        let scheduler = HeartbeatScheduler::new(HeartbeatSchedule::Periodic {
            action: HeartbeatAction::ImmediateReconnect,
            interval: 2,
        });

        // 1=Continue, 2=Fault, 3=Continue, 4=Fault
        for _ in 0..4 {
            scheduler.next_action(1);
        }

        let stats = scheduler.stats_snapshot();
        assert_eq!(stats.total_requests, 4);
        assert_eq!(stats.continue_count, 2);
        assert_eq!(stats.immediate_reconnect_count, 2);
        assert!((stats.fault_rate() - 0.5).abs() < f64::EPSILON);
    }

    #[test]
    fn test_stats_fault_rate_zero() {
        let stats = HeartbeatStatsSnapshot {
            total_requests: 0,
            continue_count: 0,
            immediate_reconnect_count: 0,
            abandon_tunnel_count: 0,
            delayed_reconnect_count: 0,
            no_response_count: 0,
        };
        assert_eq!(stats.fault_rate(), 0.0);
    }

    #[test]
    fn test_schedule_validate() {
        assert!(HeartbeatSchedule::Normal.validate().is_ok());
        assert!(HeartbeatSchedule::Override {
            action: HeartbeatAction::Continue,
        }
        .validate()
        .is_ok());

        assert!(HeartbeatSchedule::Sequence {
            actions: vec![HeartbeatAction::Continue],
        }
        .validate()
        .is_ok());
        assert!(HeartbeatSchedule::Sequence { actions: vec![] }
            .validate()
            .is_err());

        assert!(HeartbeatSchedule::Periodic {
            action: HeartbeatAction::Continue,
            interval: 1,
        }
        .validate()
        .is_ok());
        assert!(HeartbeatSchedule::Periodic {
            action: HeartbeatAction::Continue,
            interval: 0,
        }
        .validate()
        .is_err());

        assert!(HeartbeatSchedule::Probabilistic {
            action: HeartbeatAction::Continue,
            probability: 0.5,
        }
        .validate()
        .is_ok());
        assert!(HeartbeatSchedule::Probabilistic {
            action: HeartbeatAction::Continue,
            probability: -0.1,
        }
        .validate()
        .is_err());
        assert!(HeartbeatSchedule::Probabilistic {
            action: HeartbeatAction::Continue,
            probability: 1.1,
        }
        .validate()
        .is_err());

        assert!(HeartbeatSchedule::CountdownToFailure {
            action: HeartbeatAction::Continue,
            countdown: 5,
        }
        .validate()
        .is_ok());
        assert!(HeartbeatSchedule::CountdownToFailure {
            action: HeartbeatAction::Continue,
            countdown: 0,
        }
        .validate()
        .is_err());
    }

    #[test]
    fn test_scheduler_config_default() {
        let config = HeartbeatSchedulerConfig::default();
        assert!(!config.enabled);
        assert!(matches!(config.schedule, HeartbeatSchedule::Normal));
        assert!(config.validate().is_ok());
    }

    #[test]
    fn test_scheduler_debug() {
        let scheduler = HeartbeatScheduler::normal();
        let debug_str = format!("{:?}", scheduler);
        assert!(debug_str.contains("HeartbeatScheduler"));
        assert!(debug_str.contains("Normal"));
    }
}