open-net 0.3.2

A cross-platform async networking library with WebSocket clients and network status monitoring.
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
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 {
    generation: u64,
    inner: Mutex<HeartbeatStateInner>,
}

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

struct OutstandingProbe {
    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 {
            generation,
            inner: Mutex::new(HeartbeatStateInner {
                next_sequence: 1,
                outstanding: None,
            }),
        }
    }

    /// Evaluates a heartbeat tick without ever creating a second outstanding Ping.
    pub(crate) fn on_tick(&self, now: Instant, pong_timeout: Duration) -> 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 {
                    payload: payload.clone(),
                    pong_timeout,
                    phase: ProbePhase::Sending,
                });
                HeartbeatTick::SendProbe(payload)
            }
        };
        drop(inner);
        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);
        inner.outstanding = Some(OutstandingProbe {
            payload: payload.clone(),
            pong_timeout,
            phase: ProbePhase::Sending,
        });
        drop(inner);
        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()
    }

    /// 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 };
        drop(inner);
        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),
                }
        });
        if matches {
            inner.outstanding = None;
        }
        drop(inner);
        crate::log_s!(LogType::WSC; "acknowledge_pong", "generation|accepted", self.generation, matches);
        matches
    }

    /// Removes a probe whose Ping write failed or was cancelled.
    pub(crate) fn abandon_probe(&self, payload: &[u8]) {
        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)
        {
            inner.outstanding = None;
            drop(inner);
            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();
        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 creating a new heartbeat probe.
    pub(crate) fn is_timed_out(&self, now: Instant) -> bool {
        crate::log_t!(LogType::WSC; "is_timed_out", "now", format!("{:?}", now));
        let timed_out = self.pong_deadline().is_some_and(|deadline| now >= deadline);
        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(())
    }
}