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
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
//! Application-level WebSocket heartbeat support.
//!
//! WebSocket control Ping/Pong frames are handled by the transport heartbeat.
//! This module provides a separate, bounded loop for exchanges that require a
//! text or binary heartbeat message at the application protocol level.
//!
//! These are ordinary data messages: they share application queue admission and
//! wait for an already-started fragmented message to finish. They do not have
//! the interleaving privileges of RFC 6455 Ping/Pong control frames. If the
//! application protocol needs scheduling opportunities within a large payload,
//! it must define multiple complete messages or use a separate connection; SDK
//! frame fragmentation preserves the original logical message.

use super::{
    DisconnectedPolicy, IncomingMessage, Message, MessageReceiver, ReceiveOptions, ReceiveOverflow,
    SendOptions, Sender,
};
use crate::error::{ErrorKind, ErrorStage, ReceiveError};
use crate::module::ws_client::session_runtime::SessionRuntime;
use crate::{NetError, Result};
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::{Duration, Instant as StdInstant, SystemTime};
use tokio::task::JoinHandle;
use tokio::time::{self, Instant};
use tokio_util::sync::CancellationToken;

/// Callback used to recognize an application-level heartbeat response.
///
/// The callback must only inspect the immutable message. A callback panic is
/// converted to [`ErrorKind::CallbackPanicked`] and never escapes the task.
/// Matching is message-level and connection-scoped; protocols that can deliver
/// delayed or repeated responses should include a request nonce in the payload
/// and verify it in this callback.
pub type ApplicationHeartbeatMatcher =
    Arc<dyn Fn(&IncomingMessage) -> bool + Send + Sync + 'static>;

/// Action to take after an application heartbeat send or response failure.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ApplicationHeartbeatFailureAction {
    /// Record the failure and continue with the next scheduled heartbeat.
    Continue,
    /// Record the failure and stop the application heartbeat loop.
    Stop,
}

/// Configuration for a fixed-interval application heartbeat loop.
#[derive(Clone)]
pub struct ApplicationHeartbeatConfig {
    /// Delay between heartbeat attempts. The first heartbeat is sent after this delay.
    pub interval: Duration,
    /// Text or binary payload sent on every heartbeat attempt.
    pub payload: Message,
    /// Maximum time allowed for queue admission and the local write.
    pub send_timeout: Duration,
    /// How long to wait for a matching response after a successful write.
    /// `None` disables response matching and timeout accounting.
    pub response_timeout: Option<Duration>,
    /// Number of consecutive missed responses tolerated before `Stop` takes effect.
    pub max_missed_responses: u32,
    /// Optional application response matcher. When absent, writes are observed only.
    pub matcher: Option<ApplicationHeartbeatMatcher>,
    /// Receive queue used exclusively by the heartbeat loop when a matcher is set.
    /// The default is [`ReceiveOverflow::DropOldest`] so unrelated business
    /// traffic cannot close the session; selecting `Disconnect` makes queue
    /// overflow a heartbeat receiver failure by design.
    pub receive_options: ReceiveOptions,
    /// Failure handling policy for writes, receiver failures, and response timeouts.
    pub failure_action: ApplicationHeartbeatFailureAction,
}

impl ApplicationHeartbeatConfig {
    /// Creates a fixed-interval heartbeat configuration with no response matching.
    pub fn new(interval: Duration, payload: impl Into<Message>) -> Self {
        Self {
            interval,
            payload: payload.into(),
            send_timeout: Duration::from_secs(10),
            response_timeout: None,
            max_missed_responses: 1,
            matcher: None,
            receive_options: ReceiveOptions {
                overflow: ReceiveOverflow::DropOldest,
                ..ReceiveOptions::default()
            },
            failure_action: ApplicationHeartbeatFailureAction::Continue,
        }
    }

    /// Sets the timeout used for queue admission and local WebSocket writing.
    pub fn with_send_timeout(mut self, timeout: Duration) -> Self {
        self.send_timeout = timeout;
        self
    }

    /// Enables response matching with the supplied timeout and matcher.
    pub fn with_response_matcher(
        mut self,
        timeout: Duration,
        matcher: impl Fn(&IncomingMessage) -> bool + Send + Sync + 'static,
    ) -> Self {
        self.response_timeout = Some(timeout);
        self.matcher = Some(Arc::new(matcher));
        self
    }

    /// Sets the maximum number of consecutive response timeouts.
    pub fn with_max_missed_responses(mut self, max_missed_responses: u32) -> Self {
        self.max_missed_responses = max_missed_responses;
        self
    }

    /// Sets the receive queue options used by the heartbeat loop.
    pub fn with_receive_options(mut self, receive_options: ReceiveOptions) -> Self {
        self.receive_options = receive_options;
        self
    }

    /// Sets whether failures stop or leave the loop running.
    pub fn with_failure_action(
        mut self,
        failure_action: ApplicationHeartbeatFailureAction,
    ) -> Self {
        self.failure_action = failure_action;
        self
    }

    /// Validates values that would otherwise create a busy loop or an unbounded wait.
    pub fn validate(&self) -> Result<()> {
        if self.interval.is_zero() {
            return Err(NetError::config(
                "application_heartbeat.interval",
                "must be greater than zero",
            ));
        }
        if Instant::now().checked_add(self.interval).is_none() {
            return Err(NetError::config(
                "application_heartbeat.interval",
                "cannot be represented as a timer deadline",
            ));
        }
        if self.send_timeout.is_zero() {
            return Err(NetError::config(
                "application_heartbeat.send_timeout",
                "must be greater than zero",
            ));
        }
        if StdInstant::now().checked_add(self.send_timeout).is_none() {
            return Err(NetError::config(
                "application_heartbeat.send_timeout",
                "cannot be represented as a deadline",
            ));
        }
        if self.max_missed_responses == 0 {
            return Err(NetError::config(
                "application_heartbeat.max_missed_responses",
                "must be greater than zero",
            ));
        }
        if self.matcher.is_some() && self.receive_options.include_control_frames {
            return Err(NetError::config(
                "application_heartbeat.receive_options.include_control_frames",
                "must be false so control Pong frames cannot acknowledge application heartbeats",
            ));
        }
        if self.matcher.is_some() && self.response_timeout.is_none() {
            return Err(NetError::config(
                "application_heartbeat.response_timeout",
                "is required when matcher is set",
            ));
        }
        if let Some(timeout) = self.response_timeout {
            if StdInstant::now().checked_add(timeout).is_none() {
                return Err(NetError::config(
                    "application_heartbeat.response_timeout",
                    "must fit an absolute deadline",
                ));
            }
            if timeout.is_zero() {
                return Err(NetError::config(
                    "application_heartbeat.response_timeout",
                    "must be greater than zero",
                ));
            }
            if Instant::now().checked_add(timeout).is_none() {
                return Err(NetError::config(
                    "application_heartbeat.response_timeout",
                    "cannot be represented as a deadline",
                ));
            }
            if self.matcher.is_none() {
                return Err(NetError::config(
                    "application_heartbeat.matcher",
                    "is required when response_timeout is set",
                ));
            }
        }
        if self.matcher.is_some() {
            self.receive_options.validate()?;
        }
        Ok(())
    }
}

impl std::fmt::Debug for ApplicationHeartbeatConfig {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("ApplicationHeartbeatConfig")
            .field("interval", &self.interval)
            .field("payload_bytes", &self.payload.len())
            .field("send_timeout", &self.send_timeout)
            .field("response_timeout", &self.response_timeout)
            .field("max_missed_responses", &self.max_missed_responses)
            .field("has_matcher", &self.matcher.is_some())
            .field("receive_options", &self.receive_options)
            .field("failure_action", &self.failure_action)
            .finish()
    }
}

/// Current state of an application heartbeat loop.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ApplicationHeartbeatState {
    /// The loop is waiting for its next scheduled send.
    Running,
    /// A heartbeat was written and a response is being matched.
    WaitingForResponse,
    /// The loop has stopped because its handle was stopped, its session ended, or policy stopped it.
    Stopped,
}

/// Immutable counters and last-error classification for an application heartbeat.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct ApplicationHeartbeatSnapshot {
    /// Current loop state.
    pub state: ApplicationHeartbeatState,
    /// Number of successful local writes.
    pub sent: u64,
    /// Number of matched application responses.
    pub matched_responses: u64,
    /// Number of response deadlines reached without a match.
    pub missed_responses: u64,
    /// Number of send, receive, matcher, or response failures.
    pub failures: u64,
    /// Classification of the most recent failure, if any.
    pub last_error: Option<ErrorKind>,
}

impl Default for ApplicationHeartbeatSnapshot {
    fn default() -> Self {
        Self {
            state: ApplicationHeartbeatState::Running,
            sent: 0,
            matched_responses: 0,
            missed_responses: 0,
            failures: 0,
            last_error: None,
        }
    }
}

/// Controls one application heartbeat loop.
///
/// Dropping the handle requests cancellation and aborts only the heartbeat task;
/// the owning WebSocket session remains alive.
pub struct ApplicationHeartbeatHandle {
    cancellation: CancellationToken,
    snapshot: Arc<Mutex<ApplicationHeartbeatSnapshot>>,
    task: Option<JoinHandle<()>>,
}

impl ApplicationHeartbeatHandle {
    pub(crate) fn new(
        sender: Sender,
        receiver: Option<MessageReceiver>,
        config: ApplicationHeartbeatConfig,
    ) -> Result<Self> {
        config.validate()?;
        let cancellation = CancellationToken::new();
        let snapshot = Arc::new(Mutex::new(ApplicationHeartbeatSnapshot::default()));
        let runtime = sender.runtime.clone();
        let task = runtime.clone().spawn(run_heartbeat(
            sender,
            receiver,
            config,
            cancellation.clone(),
            snapshot.clone(),
            runtime,
        ))?;
        Ok(Self {
            cancellation,
            snapshot,
            task: Some(task),
        })
    }

    /// Requests the loop to stop. The request is idempotent.
    pub fn stop(&self) {
        self.cancellation.cancel();
    }

    /// Returns a point-in-time snapshot without waiting for the loop.
    pub fn snapshot(&self) -> ApplicationHeartbeatSnapshot {
        snapshot_copy(&self.snapshot)
    }

    /// Waits for the loop task to finish and returns its final snapshot.
    pub async fn stopped(mut self) -> Result<ApplicationHeartbeatSnapshot> {
        let task = self
            .task
            .take()
            .ok_or_else(|| NetError::from(ErrorKind::Internal).with_stage(ErrorStage::Runtime))?;
        task.await.map_err(|error| {
            NetError::with_source(ErrorKind::EngineDropped, error).with_stage(ErrorStage::Runtime)
        })?;
        Ok(snapshot_copy(&self.snapshot))
    }
}

impl Drop for ApplicationHeartbeatHandle {
    fn drop(&mut self) {
        self.cancellation.cancel();
        if let Some(task) = self.task.take() {
            task.abort();
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum ResponseWait {
    Matched,
    TimedOut,
    Closed,
    Cancelled,
    Failed(HeartbeatFailure),
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum HeartbeatPhase {
    SendOptions,
    Send,
    Connection,
    ResponseWait,
    Matcher,
    Receive,
}

impl HeartbeatPhase {
    fn name(self) -> &'static str {
        match self {
            Self::SendOptions => "send_options",
            Self::Send => "send",
            Self::Connection => "connection",
            Self::ResponseWait => "response_wait",
            Self::Matcher => "matcher",
            Self::Receive => "receive",
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct HeartbeatFailure {
    phase: HeartbeatPhase,
    kind: ErrorKind,
    stage: Option<ErrorStage>,
}

const HEARTBEAT_STAGE_SLOTS: usize = ErrorStage::Runtime as usize + 2;

#[derive(Default)]
struct HeartbeatDiagnostics {
    client_id: u64,
    last: Option<HeartbeatFailure>,
    failures: u64,
    // One bit per SDK ErrorKind for each fixed phase/stage, including no stage.
    // None of these slots are keyed by user-controlled data.
    reported: [[u64; HEARTBEAT_STAGE_SLOTS]; 6],
}

impl HeartbeatDiagnostics {
    fn should_report(&mut self, failure: HeartbeatFailure, enabled: bool) -> bool {
        if matches!(failure.kind, ErrorKind::Cancelled | ErrorKind::Closed) {
            self.last = None;
            self.failures = 0;
            self.reported = [[0; HEARTBEAT_STAGE_SLOTS]; 6];
            return false;
        }
        self.last = Some(failure);
        self.failures = self.failures.saturating_add(1);
        if !enabled {
            // An unobserved failure does not spend a later subscriber's first
            // diagnostic. Queue rejection retains the logger's drop semantics.
            self.reported = [[0; HEARTBEAT_STAGE_SLOTS]; 6];
            return false;
        }
        // ErrorKind currently has 40 data-free variants. Keep future out-of-range
        // classifications bounded as well, without risking a diagnostic panic.
        let bit = 1_u64
            .checked_shl(failure.kind as u32)
            .unwrap_or(1_u64 << 63);
        let stage = failure
            .stage
            .map_or(0, |stage| stage as usize + 1)
            .min(HEARTBEAT_STAGE_SLOTS - 1);
        let reported = &mut self.reported[failure.phase as usize][stage];
        let first = *reported & bit == 0;
        *reported |= bit;
        first
    }

    fn failed(&mut self, session_id: u64, failure: HeartbeatFailure) {
        if self.should_report(
            failure,
            crate::OpenNetLogger::is_enabled_for(crate::LogType::WSC, crate::LogLevel::Error),
        ) {
            crate::log_e!(crate::LogType::WSC; "ws.heartbeat.failed",
                "client_id|session_id|phase|kind|stage|failures", self.client_id, session_id, failure.phase.name(),
                format!("{:?}", failure.kind), failure.stage.map(|stage| format!("{stage:?}")), self.failures);
        }
    }

    fn error(&mut self, session_id: u64, phase: HeartbeatPhase, error: &NetError) {
        self.failed(
            session_id,
            HeartbeatFailure {
                phase,
                kind: error.kind(),
                stage: error.context().stage,
            },
        );
    }

    fn recovered(&mut self, session_id: u64) {
        if let Some(failure) = self.last.take() {
            crate::log_s!(crate::LogType::WSC, crate::LogLevel::Key; "ws.heartbeat.recovered",
                "client_id|session_id|phase|failures", self.client_id, session_id, failure.phase.name(), self.failures);
        }
        self.failures = 0;
        self.reported = [[0; HEARTBEAT_STAGE_SLOTS]; 6];
    }

    fn stopped(&self, session_id: u64) {
        if let Some(failure) = self.last {
            crate::log_s!(crate::LogType::WSC, crate::LogLevel::Key; "ws.heartbeat.stopped",
                "client_id|session_id|phase|kind|failures", self.client_id, session_id, failure.phase.name(), format!("{:?}", failure.kind), self.failures);
        }
    }
}

async fn run_heartbeat(
    sender: Sender,
    mut receiver: Option<MessageReceiver>,
    config: ApplicationHeartbeatConfig,
    cancellation: CancellationToken,
    snapshot: Arc<Mutex<ApplicationHeartbeatSnapshot>>,
    runtime: Arc<SessionRuntime>,
) {
    let now = Instant::now();
    let first_tick = match now.checked_add(config.interval) {
        Some(deadline) => deadline,
        None => now,
    };
    let mut ticker = time::interval_at(first_tick, config.interval);
    ticker.set_missed_tick_behavior(time::MissedTickBehavior::Skip);
    let mut consecutive_missed = 0_u32;
    let mut stopped_by_policy = false;
    let session_closed = runtime.closed_token();
    let session_id = runtime.id.as_u64();
    let mut diagnostics = HeartbeatDiagnostics {
        client_id: runtime.client_id.as_u64(),
        ..Default::default()
    };

    'heartbeat: loop {
        tokio::select! {
            _ = cancellation.cancelled() => break 'heartbeat,
            _ = session_closed.cancelled() => break 'heartbeat,
            _ = ticker.tick() => {
                snapshot_update(&snapshot, |current| {
                    current.state = ApplicationHeartbeatState::Running;
                });
                let options = match send_options(config.send_timeout) {
                    Ok(options) => options,
                    Err(error) => {
                        diagnostics.error(session_id, HeartbeatPhase::SendOptions, &error);
                        // A configuration/deadline failure is not a missed
                        // response. Keep the response-timeout streak scoped to
                        // actual response deadlines.
                        consecutive_missed = 0;
                        let should_stop = record_failure(
                            &snapshot,
                            &error,
                            config.failure_action,
                        );
                        if should_stop {
                            stopped_by_policy = true;
                            break 'heartbeat;
                        }
                        continue;
                    }
                };
                let sent_at = SystemTime::now();
                let send = sender
                    .message(config.payload.clone())
                    .options(options)
                    .send();
                let send_result = tokio::select! {
                    _ = cancellation.cancelled() => break 'heartbeat,
                    _ = session_closed.cancelled() => break 'heartbeat,
                    result = send => result,
                };
                if let Err(error) = send_result {
                    diagnostics.error(session_id, HeartbeatPhase::Send, &error);
                    // A write failure breaks the response-timeout streak; the
                    // next successful write starts a new response sequence.
                    consecutive_missed = 0;
                    let should_stop = record_failure(
                        &snapshot,
                        &error,
                        config.failure_action,
                    );
                    if should_stop {
                        stopped_by_policy = true;
                        break 'heartbeat;
                    }
                    continue;
                }
                snapshot_update(&snapshot, |current| {
                    increment(&mut current.sent);
                });
                let (Some(matcher), Some(receiver)) =
                    (config.matcher.as_ref(), receiver.as_mut())
                else {
                    diagnostics.recovered(session_id);
                    continue;
                };
                let connection_id = match runtime.current_connection_id() {
                    Ok(Some(connection_id)) => connection_id,
                    Ok(None) => {
                        // The write completed while the physical connection
                        // was being retired or replaced. Do not turn this
                        // lifecycle race into a response timeout for the new
                        // connection; retry on the next interval instead.
                        consecutive_missed = 0;
                        let error = NetError::from(ErrorKind::NotConnected)
                            .with_stage(ErrorStage::Runtime);
                        let should_stop = record_failure(
                            &snapshot,
                            &error,
                            config.failure_action,
                        );
                        if should_stop {
                            // The retirement race is expected, but a policy stop
                            // still names its actual cause instead of an older fault.
                            diagnostics.last = Some(HeartbeatFailure {
                                phase: HeartbeatPhase::Connection,
                                kind: ErrorKind::NotConnected,
                                stage: Some(ErrorStage::Runtime),
                            });
                            diagnostics.failures = diagnostics.failures.saturating_add(1);
                            stopped_by_policy = true;
                            break 'heartbeat;
                        }
                        continue;
                    }
                    Err(error) => {
                        diagnostics.error(session_id, HeartbeatPhase::Connection, &error);
                        // A connection/lifecycle lookup failure is not a
                        // response timeout and must not carry a stale streak
                        // into the next heartbeat.
                        consecutive_missed = 0;
                        let should_stop = record_failure(
                            &snapshot,
                            &error,
                            config.failure_action,
                        );
                        if should_stop {
                            stopped_by_policy = true;
                            break 'heartbeat;
                        }
                        continue;
                    }
                };
                snapshot_update(&snapshot, |current| {
                    current.state = ApplicationHeartbeatState::WaitingForResponse;
                });
                let timeout = match config.response_timeout {
                    Some(timeout) => timeout,
                    None => continue,
                };
                match wait_for_response(
                    receiver,
                    matcher,
                    timeout,
                    &cancellation,
                    &session_closed,
                    Some(connection_id),
                    sent_at,
                ).await {
                    ResponseWait::Matched => {
                        consecutive_missed = 0;
                        snapshot_update(&snapshot, |current| {
                            increment(&mut current.matched_responses);
                            current.state = ApplicationHeartbeatState::Running;
                        });
                        diagnostics.recovered(session_id);
                    }
                    ResponseWait::TimedOut => {
                        diagnostics.failed(session_id, HeartbeatFailure {
                            phase: HeartbeatPhase::ResponseWait, kind: ErrorKind::TimedOut, stage: Some(ErrorStage::Receive),
                        });
                        consecutive_missed = consecutive_missed.saturating_add(1);
                        snapshot_update(&snapshot, |current| {
                            increment(&mut current.missed_responses);
                            current.last_error = Some(ErrorKind::TimedOut);
                            increment(&mut current.failures);
                            current.state = ApplicationHeartbeatState::Running;
                        });
                        if config.failure_action == ApplicationHeartbeatFailureAction::Stop
                            && consecutive_missed >= config.max_missed_responses
                        {
                            stopped_by_policy = true;
                            break 'heartbeat;
                        }
                    }
                    ResponseWait::Closed | ResponseWait::Cancelled => break 'heartbeat,
                    ResponseWait::Failed(failure) => {
                        diagnostics.failed(session_id, failure);
                        // Receiver and matcher failures are distinct from a
                        // response deadline, so they reset consecutive misses.
                        consecutive_missed = 0;
                        let should_stop = record_failure_kind(
                            &snapshot,
                            failure.kind,
                            config.failure_action,
                        );
                        if should_stop {
                            stopped_by_policy = true;
                            break 'heartbeat;
                        }
                    }
                }
            }
        }
    }
    if let Some(receiver) = receiver.as_ref() {
        receiver.unsubscribe();
    }
    snapshot_update(&snapshot, |current| {
        current.state = ApplicationHeartbeatState::Stopped;
    });
    if stopped_by_policy {
        diagnostics.stopped(session_id);
    }
}

async fn wait_for_response(
    receiver: &mut MessageReceiver,
    matcher: &ApplicationHeartbeatMatcher,
    timeout: Duration,
    cancellation: &CancellationToken,
    session_closed: &CancellationToken,
    connection_id: Option<crate::ws::ConnectionId>,
    sent_at: SystemTime,
) -> ResponseWait {
    let deadline = time::sleep(timeout);
    tokio::pin!(deadline);
    loop {
        tokio::select! {
            _ = cancellation.cancelled() => return ResponseWait::Cancelled,
            _ = session_closed.cancelled() => return ResponseWait::Closed,
            _ = &mut deadline => return ResponseWait::TimedOut,
            result = receiver.recv() => {
                match result {
                    Ok(Some(message)) => {
                        if connection_id != Some(message.connection_id()) {
                            continue;
                        }
                        if message.received_at().duration_since(sent_at).is_err() {
                            continue;
                        }
                        let matches = match catch_unwind(AssertUnwindSafe(|| matcher(&message))) {
                            Ok(matches) => matches,
                            Err(_) => return ResponseWait::Failed(HeartbeatFailure {
                                phase: HeartbeatPhase::Matcher, kind: ErrorKind::CallbackPanicked, stage: Some(ErrorStage::Receive),
                            }),
                        };
                        if matches {
                            return ResponseWait::Matched;
                        }
                    }
                    Ok(None) => return ResponseWait::Closed,
                    // DropOldest is the safe default for a matcher queue. A
                    // lag means unrelated messages were discarded; keep
                    // waiting for the current connection's matching response
                    // instead of turning normal market-data pressure into a
                    // socket failure.
                    Err(ReceiveError::Lagged { .. }) => continue,
                    Err(ReceiveError::Failed(error)) => {
                        return ResponseWait::Failed(HeartbeatFailure {
                            phase: HeartbeatPhase::Receive, kind: error.kind(), stage: error.context().stage,
                        });
                    }
                }
            }
        }
    }
}

fn send_options(timeout: Duration) -> Result<SendOptions> {
    let deadline = StdInstant::now().checked_add(timeout).ok_or_else(|| {
        NetError::config(
            "application_heartbeat.send_timeout",
            "cannot be represented as a deadline",
        )
    })?;
    Ok(SendOptions {
        disconnected: DisconnectedPolicy::WaitForReconnect,
        enqueue_timeout: Some(timeout),
        write_timeout: timeout,
        deadline: Some(deadline),
        ..SendOptions::default()
    })
}

fn record_failure(
    snapshot: &Arc<Mutex<ApplicationHeartbeatSnapshot>>,
    error: &NetError,
    action: ApplicationHeartbeatFailureAction,
) -> bool {
    record_failure_kind(snapshot, error.kind(), action)
}

fn record_failure_kind(
    snapshot: &Arc<Mutex<ApplicationHeartbeatSnapshot>>,
    kind: ErrorKind,
    action: ApplicationHeartbeatFailureAction,
) -> bool {
    snapshot_update(snapshot, |current| {
        increment(&mut current.failures);
        current.last_error = Some(kind);
        current.state = ApplicationHeartbeatState::Running;
    });
    action == ApplicationHeartbeatFailureAction::Stop
}

fn increment(value: &mut u64) {
    if let Some(next) = value.checked_add(1) {
        *value = next;
    }
}

fn snapshot_copy(
    snapshot: &Arc<Mutex<ApplicationHeartbeatSnapshot>>,
) -> ApplicationHeartbeatSnapshot {
    *lock_snapshot(snapshot)
}

fn snapshot_update<F>(snapshot: &Arc<Mutex<ApplicationHeartbeatSnapshot>>, update: F)
where
    F: FnOnce(&mut ApplicationHeartbeatSnapshot),
{
    let mut current = lock_snapshot(snapshot);
    update(&mut current);
}

fn lock_snapshot<'a>(
    snapshot: &'a Arc<Mutex<ApplicationHeartbeatSnapshot>>,
) -> MutexGuard<'a, ApplicationHeartbeatSnapshot> {
    match snapshot.lock() {
        Ok(guard) => guard,
        Err(poisoned) => {
            crate::log_e!(crate::common::log::log_def::LogType::WSC;
                "ws.heartbeat.lock_snapshot", "arg_snapshot_present|error", true, "lock_poisoned_recovered");
            poisoned.into_inner()
        }
    }
}

#[cfg(test)]
#[path = "application_heartbeat_tests.rs"]
mod tests;