open-net 0.3.5

A cross-platform async networking library for Rust with HTTP and WebSocket clients, network status monitoring, configurable retries, WebSocket reconnection and heartbeats, and managed client lifecycles. Reuse common networking infrastructure across applications to avoid repeated implementation and debugging, helping save development time and AI coding tokens.
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
use crate::common::log::log_def::LogType;
use bytes::Bytes;
use std::sync::Mutex;
use std::time::Duration;
use tokio::time::Instant;

/// A heartbeat decision made when the writer observes an interval tick.
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) enum HeartbeatTick {
    /// No probe is outstanding, so the writer should send this payload as Ping.
    SendProbe(Bytes),
    /// A probe is currently being written or is awaiting its matching Pong.
    Waiting,
    /// A successfully written probe has exceeded its Pong deadline.
    TimedOut,
}

/// Per-connection heartbeat correlation state shared by the read and write halves.
///
/// At most one Ping probe is outstanding. A probe first enters `Sending`, which
/// deliberately has no Pong deadline: the bounded control-frame write owns that
/// phase. Only after the send succeeds does `sent_at` start the Pong timeout.
/// The reader clears a probe only when the Pong payload exactly matches it.
pub(crate) struct HeartbeatState {
    #[cfg(feature = "quality-doctor")]
    quality: std::sync::OnceLock<(crate::module::quality::QualityContext, u64, u64)>,
    generation: u64,
    inner: Mutex<HeartbeatStateInner>,
}

struct HeartbeatStateInner {
    next_sequence: u64,
    outstanding: Option<OutstandingProbe>,
}

struct OutstandingProbe {
    #[cfg(feature = "quality-doctor")]
    quality: Option<crate::module::quality::QualityProbe>,
    payload: Bytes,
    pong_timeout: Duration,
    phase: ProbePhase,
}

enum ProbePhase {
    Sending,
    AwaitingPong { sent_at: Instant },
}

impl HeartbeatState {
    /// Creates an idle state scoped to one physical connection generation.
    pub(crate) fn new(generation: u64) -> Self {
        crate::log_t!(LogType::WSC; "new", "generation", generation);
        Self {
            #[cfg(feature = "quality-doctor")]
            quality: std::sync::OnceLock::new(),
            generation,
            inner: Mutex::new(HeartbeatStateInner {
                next_sequence: 1,
                outstanding: None,
            }),
        }
    }
    #[cfg(feature = "quality-doctor")]
    pub(crate) fn bind_quality(
        &self,
        context: crate::module::quality::QualityContext,
        client: u64,
        session: u64,
    ) {
        let _ = self.quality.set((context, client, session));
    }
    #[cfg(feature = "quality-doctor")]
    fn observe_probe(&self, payload: &[u8], schedule_delay: Option<Duration>) {
        let Some((context, client, session)) = self.quality.get() else {
            return;
        };
        let Some(probe) = context.begin(
            crate::api::quality::QualityProtocol::WebSocket,
            crate::api::quality::QualityOperationKind::WsHeartbeat,
            *client,
        ) else {
            return;
        };
        probe.session(*session);
        probe.connection(self.generation);
        probe.mark(crate::api::quality::PhaseKind::HeartbeatObserved);
        if let Some(delay) = schedule_delay {
            probe.heartbeat_schedule_delay(delay);
        }
        // Do not contend with Pong handling merely to attach diagnostics.
        let installed = match self.inner.try_lock() {
            Ok(mut inner) => match inner.outstanding.as_mut() {
                Some(outstanding) if outstanding.payload.as_ref() == payload => {
                    outstanding.quality = Some(probe.clone());
                    true
                }
                _ => false,
            },
            Err(_) => false,
        };
        if !installed {
            probe.result(crate::api::quality::QualityOutcome::Unknown);
            probe.finish();
        }
    }

    /// Evaluates a heartbeat tick without ever creating a second outstanding Ping.
    #[cfg(any(test, not(feature = "quality-doctor")))]
    pub(crate) fn on_tick(&self, now: Instant, pong_timeout: Duration) -> HeartbeatTick {
        self.on_tick_inner(
            now,
            pong_timeout,
            #[cfg(feature = "quality-doctor")]
            None,
        )
    }

    #[cfg(feature = "quality-doctor")]
    pub(crate) fn on_scheduled_tick(
        &self,
        now: Instant,
        pong_timeout: Duration,
        scheduled_at: Option<Instant>,
    ) -> HeartbeatTick {
        self.on_tick_inner(now, pong_timeout, scheduled_at)
    }

    fn on_tick_inner(
        &self,
        now: Instant,
        pong_timeout: Duration,
        #[cfg(feature = "quality-doctor")] scheduled_at: Option<Instant>,
    ) -> HeartbeatTick {
        crate::log_t!(LogType::WSC; "on_tick", "now|pong_timeout", format!("{:?}", now), format!("{:?}", pong_timeout));
        let mut inner = self.lock_inner();
        let tick = match inner.outstanding.as_ref() {
            Some(OutstandingProbe {
                phase: ProbePhase::Sending,
                ..
            }) => HeartbeatTick::Waiting,
            Some(OutstandingProbe {
                pong_timeout,
                phase: ProbePhase::AwaitingPong { sent_at },
                ..
            }) if now.saturating_duration_since(*sent_at) >= *pong_timeout => {
                HeartbeatTick::TimedOut
            }
            Some(_) => HeartbeatTick::Waiting,
            None => {
                let sequence = inner.next_sequence;
                inner.next_sequence = inner.next_sequence.wrapping_add(1).max(1);
                let payload = heartbeat_payload(self.generation, sequence);
                inner.outstanding = Some(OutstandingProbe {
                    #[cfg(feature = "quality-doctor")]
                    quality: None,
                    payload: payload.clone(),
                    pong_timeout,
                    phase: ProbePhase::Sending,
                });
                HeartbeatTick::SendProbe(payload)
            }
        };
        #[cfg(feature = "quality-doctor")]
        let expired_quality = if tick == HeartbeatTick::TimedOut {
            inner
                .outstanding
                .as_mut()
                .and_then(|outstanding| outstanding.quality.take())
        } else {
            None
        };
        drop(inner);
        #[cfg(feature = "quality-doctor")]
        {
            if let Some(probe) = expired_quality {
                probe.failure(
                    crate::error::ErrorKind::TimedOut,
                    Some(crate::error::ErrorStage::Heartbeat),
                );
                probe.finish();
            }
            if let HeartbeatTick::SendProbe(payload) = &tick {
                self.observe_probe(
                    payload,
                    scheduled_at.map(|due| now.saturating_duration_since(due)),
                );
            }
        }
        match &tick {
            HeartbeatTick::SendProbe(payload) => {
                crate::log_s!(LogType::WSC; "on_tick", "generation|state|payload_bytes", self.generation, "Sending", payload.len())
            }
            HeartbeatTick::Waiting => {
                crate::log_s!(LogType::WSC; "on_tick", "generation|state", self.generation, "probe_outstanding")
            }
            HeartbeatTick::TimedOut => {
                crate::log_e!(LogType::WSC; "on_tick", "generation|error", self.generation, "PongTimeout")
            }
        }
        tick
    }

    /// Starts a recovery probe when idle or after an expired Pong wait.
    pub(crate) fn start_recovery_probe(
        &self,
        now: Instant,
        pong_timeout: Duration,
    ) -> Option<Bytes> {
        let mut inner = self.lock_inner();
        let can_start = match inner.outstanding.as_ref() {
            None => true,
            Some(probe) => match probe.phase {
                ProbePhase::Sending => false,
                ProbePhase::AwaitingPong { sent_at } => sent_at
                    .checked_add(probe.pong_timeout)
                    .is_some_and(|deadline| now >= deadline),
            },
        };
        if !can_start {
            return None;
        }
        let sequence = inner.next_sequence;
        inner.next_sequence = inner.next_sequence.wrapping_add(1).max(1);
        let payload = heartbeat_payload(self.generation, sequence);
        #[cfg(feature = "quality-doctor")]
        let expired_quality = inner
            .outstanding
            .as_mut()
            .and_then(|outstanding| outstanding.quality.take());
        inner.outstanding = Some(OutstandingProbe {
            #[cfg(feature = "quality-doctor")]
            quality: None,
            payload: payload.clone(),
            pong_timeout,
            phase: ProbePhase::Sending,
        });
        drop(inner);
        #[cfg(feature = "quality-doctor")]
        {
            if let Some(probe) = expired_quality {
                probe.failure(
                    crate::error::ErrorKind::TimedOut,
                    Some(crate::error::ErrorStage::Heartbeat),
                );
                probe.finish();
            }
            self.observe_probe(&payload, None);
        }
        crate::log_s!(LogType::WSC; "ws.heartbeat_state.start_recovery_probe", "now|pong_timeout|generation|payload_bytes", format!("{now:?}"), pong_timeout, self.generation, payload.len());
        Some(payload)
    }

    pub(crate) fn has_outstanding_probe(&self) -> bool {
        self.lock_inner().outstanding.is_some()
    }

    /// Records the beginning of a Ping write attempt without affecting heartbeat state.
    /// A safe retry records another milestone on the same probe. Contended diagnostics
    /// never delay the transport reader/writer; missing facts remain missing evidence.
    #[cfg(feature = "quality-doctor")]
    pub(crate) fn observe_write_started(&self, payload: &[u8]) {
        let quality = match self.inner.try_lock() {
            Ok(inner) => inner
                .outstanding
                .as_ref()
                .filter(|outstanding| outstanding.payload.as_ref() == payload)
                .and_then(|outstanding| outstanding.quality.clone()),
            Err(_) => None,
        };
        if let Some(probe) = quality {
            probe.mark(crate::api::quality::PhaseKind::HeartbeatWriteStarted);
        }
    }

    /// Starts the Pong deadline if `payload` is still the probe being written.
    ///
    /// A matching Pong can arrive while `SinkExt::send` is completing. In that
    /// case the reader has already cleared the probe and this method returns
    /// `false` instead of resurrecting it as outstanding.
    pub(crate) fn mark_sent(&self, payload: &[u8], sent_at: Instant) -> bool {
        crate::log_t!(LogType::WSC; "mark_sent", "payload_bytes|sent_at", payload.len(), format!("{:?}", sent_at));
        let mut inner = self.lock_inner();
        let Some(outstanding) = inner.outstanding.as_mut() else {
            crate::log_s!(LogType::WSC; "mark_sent", "generation|state", self.generation, "probe_already_cleared");
            return false;
        };
        if outstanding.payload.as_ref() != payload
            || !matches!(outstanding.phase, ProbePhase::Sending)
        {
            crate::log_s!(LogType::WSC; "mark_sent", "generation|state", self.generation, "probe_or_phase_mismatch");
            return false;
        }
        outstanding.phase = ProbePhase::AwaitingPong { sent_at };
        #[cfg(feature = "quality-doctor")]
        let quality = outstanding.quality.clone();
        drop(inner);
        #[cfg(feature = "quality-doctor")]
        if let Some(probe) = quality {
            probe.mark(crate::api::quality::PhaseKind::Written);
        }
        crate::log_s!(LogType::WSC; "mark_sent", "generation|state", self.generation, "AwaitingPong");
        true
    }

    /// Clears the current probe only for an exact payload match.
    pub(crate) fn acknowledge_pong(&self, payload: &[u8]) -> bool {
        crate::log_t!(LogType::WSC; "acknowledge_pong", "payload_bytes", payload.len());
        let now = Instant::now();
        let mut inner = self.lock_inner();
        let matches = inner.outstanding.as_ref().is_some_and(|probe| {
            probe.payload.as_ref() == payload
                && match probe.phase {
                    ProbePhase::Sending => true,
                    ProbePhase::AwaitingPong { sent_at } => sent_at
                        .checked_add(probe.pong_timeout)
                        .is_some_and(|deadline| now < deadline),
                }
        });
        #[cfg(feature = "quality-doctor")]
        let quality = if matches {
            inner
                .outstanding
                .as_mut()
                .and_then(|outstanding| outstanding.quality.take())
        } else {
            None
        };
        if matches {
            inner.outstanding = None;
        }
        drop(inner);
        #[cfg(feature = "quality-doctor")]
        if let Some(probe) = quality {
            probe.mark(crate::api::quality::PhaseKind::Heartbeat);
            probe.result(crate::api::quality::QualityOutcome::Success);
            probe.finish();
        }
        crate::log_s!(LogType::WSC; "acknowledge_pong", "generation|accepted", self.generation, matches);
        matches
    }

    /// Removes a probe without an observed write failure.
    #[cfg(test)]
    pub(crate) fn abandon_probe(&self, payload: &[u8]) {
        self.abandon_probe_inner(payload, None);
    }

    /// Preserve the actual control-write failure in diagnostics without changing its
    /// transport classification or the existing probe-abandonment transition.
    pub(crate) fn fail_probe(&self, payload: &[u8], error: &crate::error::NetError) {
        self.abandon_probe_inner(payload, Some(error));
    }

    fn abandon_probe_inner(&self, payload: &[u8], error: Option<&crate::error::NetError>) {
        #[cfg(not(feature = "quality-doctor"))]
        let _ = error;
        crate::log_t!(LogType::WSC; "abandon_probe", "payload_bytes", payload.len());
        let mut inner = self.lock_inner();
        if inner
            .outstanding
            .as_ref()
            .is_some_and(|probe| probe.payload.as_ref() == payload)
        {
            #[cfg(feature = "quality-doctor")]
            let quality = inner
                .outstanding
                .as_mut()
                .and_then(|outstanding| outstanding.quality.take());
            inner.outstanding = None;
            drop(inner);
            #[cfg(feature = "quality-doctor")]
            if let Some(probe) = quality {
                match error {
                    Some(error) => probe.error(error),
                    None => probe.result(crate::api::quality::QualityOutcome::Unknown),
                }
                probe.finish();
            }
            crate::log_s!(LogType::WSC; "abandon_probe", "generation|state", self.generation, "probe_abandoned");
        }
    }

    /// Returns the deadline of the probe that is currently awaiting its Pong.
    ///
    /// A probe in `Sending` has no Pong deadline yet; its write is bounded by
    /// `control_write_timeout` instead.
    pub(crate) fn pong_deadline(&self) -> Option<Instant> {
        crate::log_t!(LogType::WSC; "pong_deadline");
        let inner = self.lock_inner();
        self.pong_deadline_locked(&inner)
    }

    fn pong_deadline_locked(&self, inner: &HeartbeatStateInner) -> Option<Instant> {
        inner
            .outstanding
            .as_ref()
            .and_then(|probe| match probe.phase {
                ProbePhase::Sending => None,
                ProbePhase::AwaitingPong { sent_at } => {
                    // Public configuration rejects unrepresentable durations. Falling back to
                    // `sent_at` keeps a corrupted/internal value fail-closed instead of either
                    // panicking the writer or silently disabling heartbeat expiry.
                    match sent_at.checked_add(probe.pong_timeout) {
                        Some(deadline) => Some(deadline),
                        None => {
                            crate::log_e!(LogType::WSC; "pong_deadline", "error", "pong_deadline_overflow");
                            Some(sent_at)
                        }
                    }
                }
            })
    }

    /// Checks the exact deadline without changing the outstanding transport probe.
    ///
    /// Observe expiration here as well as on interval ticks: the writer can retire
    /// the connection, or exhaust recovery, before another tick/replacement probe.
    pub(crate) fn is_timed_out(&self, now: Instant) -> bool {
        crate::log_t!(LogType::WSC; "is_timed_out", "now", format!("{:?}", now));
        #[allow(unused_mut)] // Mutable only when quality-doctor is compiled in.
        let mut inner = self.lock_inner();
        let timed_out = self
            .pong_deadline_locked(&inner)
            .is_some_and(|deadline| now >= deadline);
        // Claim the diagnostic probe under the same lock as the deadline check.
        // A matching Pong or a replacement cannot make us finish another probe,
        // and repeated deadline/tick checks cannot publish the result twice.
        #[cfg(feature = "quality-doctor")]
        let expired_quality = if timed_out {
            inner
                .outstanding
                .as_mut()
                .and_then(|outstanding| outstanding.quality.take())
        } else {
            None
        };
        drop(inner);
        #[cfg(feature = "quality-doctor")]
        if let Some(probe) = expired_quality {
            probe.failure(
                crate::error::ErrorKind::TimedOut,
                Some(crate::error::ErrorStage::Heartbeat),
            );
            probe.finish();
        }
        if timed_out {
            crate::log_e!(LogType::WSC; "is_timed_out", "generation|error", self.generation, "PongTimeout");
        }
        timed_out
    }

    fn lock_inner(&self) -> std::sync::MutexGuard<'_, HeartbeatStateInner> {
        crate::log_t!(LogType::WSC; "lock_inner");
        match self.inner.lock() {
            Ok(guard) => guard,
            Err(poisoned) => {
                crate::log_e!(LogType::WSC; "lock_inner", "error", "lock_poisoned_recovered");
                poisoned.into_inner()
            }
        }
    }
}

/// Produces a compact RFC-control-frame-safe payload unique within a generation.
fn heartbeat_payload(generation: u64, sequence: u64) -> Bytes {
    crate::log_t!(LogType::WSC; "heartbeat_payload", "generation|sequence", generation, sequence);
    let mut payload = [0_u8; 16];
    payload[..8].copy_from_slice(&generation.to_be_bytes());
    payload[8..].copy_from_slice(&sequence.to_be_bytes());
    Bytes::copy_from_slice(&payload)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::module::ws_client::test_support::{
        check, check_eq, check_ne, test_error, TestResult,
    };

    #[tokio::test(start_paused = true)]
    async fn matched_pong_clears_only_the_current_probe() -> TestResult {
        let heartbeat = HeartbeatState::new(9);
        let now = Instant::now();
        let HeartbeatTick::SendProbe(first) = heartbeat.on_tick(now, Duration::from_secs(5)) else {
            return Err(test_error("first tick must create a probe"));
        };
        check!(!first.is_empty())?;
        check!(heartbeat.mark_sent(first.as_ref(), now))?;
        check!(!heartbeat.acknowledge_pong(b"not-the-probe"))?;
        check_eq!(
            heartbeat.on_tick(now + Duration::from_secs(1), Duration::from_secs(5)),
            HeartbeatTick::Waiting
        )?;
        check!(heartbeat.acknowledge_pong(first.as_ref()))?;

        let HeartbeatTick::SendProbe(second) =
            heartbeat.on_tick(now + Duration::from_secs(2), Duration::from_secs(5))
        else {
            return Err(test_error("matched Pong must allow the next probe"));
        };
        check!(!second.is_empty())?;
        check_ne!(first, second)?;
        Ok(())
    }

    #[tokio::test(start_paused = true)]
    async fn timeout_starts_only_after_ping_send_succeeds() -> TestResult {
        let heartbeat = HeartbeatState::new(11);
        let started = Instant::now();
        let HeartbeatTick::SendProbe(payload) = heartbeat.on_tick(started, Duration::from_secs(5))
        else {
            return Err(test_error("first tick must create a probe"));
        };

        check_eq!(
            heartbeat.on_tick(started + Duration::from_secs(30), Duration::from_secs(5),),
            HeartbeatTick::Waiting,
            "a blocked Ping write is governed by its write timeout, not Pong timeout"
        )?;

        let sent_at = started + Duration::from_secs(30);
        check!(heartbeat.mark_sent(payload.as_ref(), sent_at))?;
        check_eq!(
            heartbeat.on_tick(
                sent_at + Duration::from_millis(4_999),
                Duration::from_secs(5),
            ),
            HeartbeatTick::Waiting
        )?;
        check_eq!(
            heartbeat.on_tick(sent_at + Duration::from_secs(5), Duration::from_secs(5),),
            HeartbeatTick::TimedOut
        )?;
        check!(heartbeat.is_timed_out(sent_at + Duration::from_secs(5)))?;
        Ok(())
    }

    #[tokio::test(start_paused = true)]
    async fn matching_pong_at_or_after_deadline_cannot_revive_the_connection() -> TestResult {
        let timeout = Duration::from_secs(5);
        let heartbeat = HeartbeatState::new(13);
        let sent_at = Instant::now();
        let HeartbeatTick::SendProbe(payload) = heartbeat.on_tick(sent_at, timeout) else {
            return Err(test_error("first tick must create a probe"));
        };
        check!(heartbeat.mark_sent(payload.as_ref(), sent_at))?;

        tokio::time::advance(timeout).await;

        check!(!heartbeat.acknowledge_pong(payload.as_ref()))?;
        check!(heartbeat.is_timed_out(Instant::now()))?;
        check_eq!(
            heartbeat.on_tick(Instant::now(), timeout),
            HeartbeatTick::TimedOut
        )?;
        Ok(())
    }

    #[tokio::test(start_paused = true)]
    async fn stale_generation_and_sequence_probes_cannot_change_current_probe() -> TestResult {
        let timeout = Duration::from_secs(5);
        for stale_source in ["previous-generation", "previous-sequence"] {
            let heartbeat = HeartbeatState::new(42);
            let previous_generation = HeartbeatState::new(41);
            let now = Instant::now();
            let stale_state = if stale_source == "previous-generation" {
                &previous_generation
            } else {
                &heartbeat
            };
            let HeartbeatTick::SendProbe(stale) = stale_state.on_tick(now, timeout) else {
                return Err(test_error("stale fixture did not create a real probe"));
            };
            if stale_source == "previous-sequence" {
                check!(heartbeat.acknowledge_pong(&stale))?;
            }
            let HeartbeatTick::SendProbe(current) = heartbeat.on_tick(now, timeout) else {
                return Err(test_error("current fixture did not create a real probe"));
            };
            check!(
                !heartbeat.mark_sent(&stale, now),
                "{stale_source}: stale probe marked the current Sending probe sent"
            )?;
            check_eq!(heartbeat.pong_deadline(), None)?;
            check!(
                !heartbeat.acknowledge_pong(&stale),
                "{stale_source}: stale Pong cleared the current Sending probe"
            )?;
            check_eq!(heartbeat.on_tick(now, timeout), HeartbeatTick::Waiting)?;
            check!(heartbeat.mark_sent(&current, now))?;
            let deadline = now
                .checked_add(timeout)
                .ok_or_else(|| test_error("bounded probe deadline was not representable"))?;
            check_eq!(heartbeat.pong_deadline(), Some(deadline))?;
            check!(
                !heartbeat.acknowledge_pong(&stale),
                "{stale_source}: stale Pong cleared the current AwaitingPong probe"
            )?;
            check_eq!(heartbeat.pong_deadline(), Some(deadline))?;
            heartbeat.abandon_probe(&stale);
            check_eq!(
                heartbeat.pong_deadline(),
                Some(deadline),
                "{stale_source}: stale failure abandoned the current probe"
            )?;
            tokio::time::advance(Duration::from_secs(4)).await;
            check!(!heartbeat.is_timed_out(Instant::now()))?;
            check!(!heartbeat.mark_sent(&stale, Instant::now()))?;
            check!(!heartbeat.acknowledge_pong(&stale))?;
            check_eq!(heartbeat.pong_deadline(), Some(deadline))?;
            tokio::time::advance(Duration::from_secs(1)).await;
            check!(heartbeat.is_timed_out(Instant::now()))?;
            check!(!heartbeat.acknowledge_pong(&current))?;
            check_eq!(
                heartbeat.on_tick(Instant::now(), timeout),
                HeartbeatTick::TimedOut
            )?;
        }
        Ok(())
    }

    #[tokio::test(start_paused = true)]
    async fn abandoned_probe_allows_a_new_normal_probe() -> TestResult {
        let heartbeat = HeartbeatState::new(79);
        let now = Instant::now();
        let HeartbeatTick::SendProbe(first) = heartbeat.on_tick(now, Duration::from_secs(5)) else {
            return Err(test_error("normal probe was not created"));
        };
        heartbeat.abandon_probe(first.as_ref());
        let HeartbeatTick::SendProbe(next) =
            heartbeat.on_tick(now + Duration::from_millis(1), Duration::from_secs(5))
        else {
            return Err(test_error("abandoning a probe must allow a new probe"));
        };
        check_ne!(first, next)?;
        check!(heartbeat.mark_sent(next.as_ref(), now + Duration::from_millis(1)))?;
        check!(!heartbeat.acknowledge_pong(first.as_ref()))?;
        check!(heartbeat.acknowledge_pong(next.as_ref()))?;
        Ok(())
    }

    #[tokio::test(start_paused = true)]
    async fn recovery_probe_replaces_only_expired_probe() -> TestResult {
        let heartbeat = HeartbeatState::new(80);
        let timeout = Duration::from_secs(5);
        let now = Instant::now();
        let HeartbeatTick::SendProbe(first) = heartbeat.on_tick(now, timeout) else {
            return Err(test_error("normal probe was not created"));
        };
        check!(heartbeat.start_recovery_probe(now, timeout).is_none())?;
        check!(heartbeat.mark_sent(first.as_ref(), now))?;
        check!(heartbeat
            .start_recovery_probe(now + timeout - Duration::from_nanos(1), timeout)
            .is_none())?;
        let expired = now
            .checked_add(timeout)
            .ok_or_else(|| test_error("test deadline overflow"))?;
        let recovery = heartbeat
            .start_recovery_probe(expired, timeout)
            .ok_or_else(|| test_error("expired probe did not start recovery"))?;
        check_ne!(first, recovery)?;
        check!(!heartbeat.acknowledge_pong(first.as_ref()))?;
        check!(heartbeat.has_outstanding_probe())?;
        check!(heartbeat.mark_sent(recovery.as_ref(), expired))?;
        check!(heartbeat.acknowledge_pong(recovery.as_ref()))?;
        check!(!heartbeat.has_outstanding_probe())?;
        Ok(())
    }

    #[tokio::test(start_paused = true)]
    async fn recovery_probe_starts_from_idle_state() -> TestResult {
        let heartbeat = HeartbeatState::new(81);
        let payload = heartbeat
            .start_recovery_probe(Instant::now(), Duration::from_secs(1))
            .ok_or_else(|| test_error("idle state did not start recovery"))?;
        check!(heartbeat.has_outstanding_probe())?;
        check!(heartbeat.mark_sent(payload.as_ref(), Instant::now()))?;
        check!(heartbeat.acknowledge_pong(payload.as_ref()))?;
        Ok(())
    }
}