open-net 0.4.0

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
use super::*;
use crate::error::ErrorKind;
use crate::ws::Message;
use std::time::Duration;

type TestResult = std::result::Result<(), crate::BoxError>;

#[test]
fn heartbeat_diagnostics_bound_alternating_failures_and_preserve_first_after_subscription(
) -> TestResult {
    let send = HeartbeatFailure {
        phase: HeartbeatPhase::Send,
        kind: ErrorKind::Io,
        stage: Some(ErrorStage::Write),
    };
    let matcher = HeartbeatFailure {
        phase: HeartbeatPhase::Matcher,
        kind: ErrorKind::CallbackPanicked,
        stage: Some(ErrorStage::Receive),
    };
    let mut first = HeartbeatDiagnostics::default();
    let mut second = HeartbeatDiagnostics::default();
    check(
        !first.should_report(send, false),
        "unsubscribed failure emitted",
    )?;
    check(
        first.should_report(send, true),
        "unsubscribed failure consumed first diagnostic",
    )?;
    check(
        first.should_report(matcher, true),
        "new reason was suppressed",
    )?;
    let queue_timeout = HeartbeatFailure {
        phase: HeartbeatPhase::Send,
        kind: ErrorKind::TimedOut,
        stage: Some(ErrorStage::Queue),
    };
    let write_timeout = HeartbeatFailure {
        stage: Some(ErrorStage::Write),
        ..queue_timeout
    };
    let unstaged_timeout = HeartbeatFailure {
        stage: None,
        ..queue_timeout
    };
    check(
        first.should_report(queue_timeout, true),
        "queue timeout was suppressed",
    )?;
    check(
        first.should_report(write_timeout, true),
        "same kind at a different stage was suppressed",
    )?;
    check(
        first.should_report(unstaged_timeout, true),
        "unstaged reason shared a stage slot",
    )?;
    for _ in 0..1_000 {
        check(
            !first.should_report(send, true),
            "alternating send failure emitted again",
        )?;
        check(
            !first.should_report(matcher, true),
            "alternating matcher failure emitted again",
        )?;
        check(
            !first.should_report(queue_timeout, true),
            "alternating queue timeout emitted again",
        )?;
        check(
            !first.should_report(write_timeout, true),
            "alternating write timeout emitted again",
        )?;
        check(
            !first.should_report(unstaged_timeout, true),
            "alternating unstaged timeout emitted again",
        )?;
    }
    check(
        second.should_report(send, true),
        "one heartbeat suppressed another",
    )?;
    first.recovered(98_101);
    check(
        first.should_report(send, true),
        "recovery did not reset fault cycle",
    )?;
    check(
        !first.should_report(send, false),
        "disabled interval emitted",
    )?;
    check(
        first.should_report(send, true),
        "re-enabled subscription missed failure",
    )?;
    first.failures = u64::MAX;
    check(
        !first.should_report(send, true) && first.failures == u64::MAX,
        "failure counter wrapped",
    )?;
    check(
        !first.should_report(
            HeartbeatFailure {
                kind: ErrorKind::Cancelled,
                ..send
            },
            true,
        ),
        "normal cancellation logged as error",
    )
}

#[test]
fn heartbeat_diagnostics_emit_safe_phases_and_one_recovery() -> TestResult {
    let (tx, rx) = std::sync::mpsc::channel();
    let _subscription = crate::OpenNetLogger::register_log_listener(
        Box::new(move |record| {
            if record.tag.starts_with("ws.heartbeat.") && record.content.contains("98102") {
                let _ = tx.send(record);
            }
        }),
        &[crate::LogType::WSC],
    )?;
    let mut diagnostics = HeartbeatDiagnostics {
        client_id: 98_102,
        ..Default::default()
    };
    let error = NetError::with_source(
        ErrorKind::Io,
        std::io::Error::other("SECRET_heartbeat_source"),
    )
    .with_stage(ErrorStage::Write);
    for _ in 0..100 {
        diagnostics.error(98_102, HeartbeatPhase::Send, &error);
    }
    diagnostics.recovered(98_102);
    diagnostics.recovered(98_102);
    diagnostics.failed(
        98_102,
        HeartbeatFailure {
            phase: HeartbeatPhase::Matcher,
            kind: ErrorKind::CallbackPanicked,
            stage: Some(ErrorStage::Receive),
        },
    );
    diagnostics.stopped(98_102);
    crate::log_s!(crate::LogType::WSC, crate::LogLevel::Key; "ws.heartbeat.test_barrier", "client_id", 98_102);
    let mut records = Vec::new();
    loop {
        let record = rx.recv_timeout(Duration::from_secs(3))?;
        if record.tag == "ws.heartbeat.test_barrier" {
            break;
        }
        check(
            !record.content.contains("SECRET_"),
            "heartbeat log exposed source",
        )?;
        records.push(record);
    }
    check(
        records.len() == 4,
        "heartbeat emitted duplicate or missing lifecycle logs",
    )?;
    check(
        records[0].level == crate::LogLevel::Error && records[0].content.contains("send"),
        "send phase absent",
    )?;
    check(
        records[1].tag == "ws.heartbeat.recovered" && records[1].content.contains("100"),
        "recovery did not summarize failures",
    )?;
    check(
        records[2].content.contains("matcher") && records[3].tag == "ws.heartbeat.stopped",
        "matcher or stop phase absent",
    )
}

fn check(condition: bool, message: &str) -> TestResult {
    if condition {
        Ok(())
    } else {
        Err(message.into())
    }
}

#[test]
fn timeout_streak_starts_over_on_a_different_writer() -> TestResult {
    let first = Some(ConnectionId::from_allocated(1));
    let second = Some(ConnectionId::from_allocated(2));
    let mut misses = MissedResponses::default();
    check(misses.record(first) == 1, "first timeout was lost")?;
    check(misses.record(first) == 2, "second timeout was lost")?;
    check(
        misses.record(second) == 1,
        "previous writer's misses leaked",
    )?;
    check(misses.record(second) == 2, "new writer's streak was lost")
}

#[tokio::test(start_paused = true)]
async fn reconnecting_heartbeat_matches_its_actual_writer_after_connection_replacement(
) -> TestResult {
    use crate::module::ws_client::v2_test_support as fixture;
    use crate::ws::{ResponseRouting, TerminationReason, WebSocketClientConfig};

    let runtime = fixture::runtime(
        WebSocketClientConfig::default(),
        ResponseRouting::Disabled,
        true,
    )
    .await?;
    let first = ConnectionId::from_allocated(1);
    let second = ConnectionId::from_allocated(2);
    let config = ApplicationHeartbeatConfig::new(Duration::from_secs(1), "probe")
        .with_response_matcher(Duration::from_secs(5), |message| {
            message.message().and_then(Message::as_text) == Some("reply")
        });
    let receiver = runtime.messages.subscribe(config.receive_options.clone())?;
    let stop = CancellationToken::new();
    let snapshot = Arc::new(Mutex::new(ApplicationHeartbeatSnapshot::default()));
    let heartbeat = run_heartbeat(
        fixture::sender(&runtime),
        Some(receiver),
        config,
        stop.clone(),
        snapshot.clone(),
        runtime.clone(),
        Some(Weak::new()),
    );
    tokio::pin!(heartbeat);
    check(
        futures_util::poll!(heartbeat.as_mut()).is_pending(),
        "heartbeat did not start",
    )?;
    time::advance(Duration::from_secs(1)).await;
    check(
        futures_util::poll!(heartbeat.as_mut()).is_pending(),
        "heartbeat did not await write",
    )?;
    let item = runtime.queue.try_next().ok_or("missing probe")?;
    check(
        item.dispatch_phase.mark_writing(first),
        "probe was not admitted for writing",
    )?;
    item.complete(Ok(()));

    // The heartbeat task has not polled its receipt yet. Retire A and establish B.
    runtime.lifecycle.connection_terminated_with_details(
        TerminationReason::IoFailure,
        None,
        Default::default(),
        Some(2),
    )?;
    runtime.connection_ended(first, NetError::from(ErrorKind::Io))?;
    let reservation = runtime.lifecycle.reserve_attempt().await?;
    runtime
        .lifecycle
        .begin_attempt(runtime.lifecycle.handshake_attempt(2, 0), reservation)?;
    runtime
        .lifecycle
        .set_attempt_credential_version(2, 0, None)?;
    runtime.lifecycle.prepare_established(2, 0)?;
    runtime.activate_connection(second)?;
    runtime.lifecycle.commit_established(2, 0)?;

    check(
        runtime.current_connection_id()? == Some(second),
        "replacement did not become current",
    )?;
    runtime.messages.publish(fixture::incoming(2, "reply"))?;
    check(
        futures_util::poll!(heartbeat.as_mut()).is_pending(),
        "heartbeat stopped on replacement",
    )?;
    let waiting = snapshot_copy(&snapshot);
    check(
        waiting.sent == 1 && waiting.state == ApplicationHeartbeatState::WaitingForResponse,
        "heartbeat did not keep waiting for its written probe",
    )?;
    check(
        waiting.matched_responses == 0,
        "B's reply completed A's probe",
    )?;
    stop.cancel();
    heartbeat.await;
    Ok(())
}

#[test]
fn default_configuration_is_fixed_interval_and_write_only() -> TestResult {
    let config = ApplicationHeartbeatConfig::new(Duration::from_secs(20), Message::text("ping"));
    config.validate()?;
    check(
        config.interval == Duration::from_secs(20),
        "interval changed",
    )?;
    check(
        config.response_timeout.is_none(),
        "default unexpectedly waits for response",
    )?;
    check(config.matcher.is_none(), "default unexpectedly has matcher")?;
    check(
        config.receive_options.overflow == crate::ws::ReceiveOverflow::DropOldest,
        "matcher queue default must not disconnect the session",
    )?;
    check(
        config.failure_action == ApplicationHeartbeatFailureAction::Continue,
        "default failure action changed",
    )
}

#[test]
fn zero_interval_and_send_timeout_are_rejected() -> TestResult {
    let interval = ApplicationHeartbeatConfig::new(Duration::ZERO, "ping");
    let interval_error = interval
        .validate()
        .err()
        .ok_or("zero interval was accepted")?;
    check(
        interval_error.kind() == ErrorKind::InvalidConfig,
        "zero interval error kind changed",
    )?;

    let send = ApplicationHeartbeatConfig::new(Duration::from_secs(1), "ping")
        .with_send_timeout(Duration::ZERO);
    let send_error = send
        .validate()
        .err()
        .ok_or("zero send timeout was accepted")?;
    check(
        send_error.kind() == ErrorKind::InvalidConfig,
        "zero send timeout error kind changed",
    )
}

#[test]
fn unrepresentable_interval_is_rejected() -> TestResult {
    let config = ApplicationHeartbeatConfig::new(Duration::MAX, "ping");
    let error = config
        .validate()
        .err()
        .ok_or("unrepresentable interval was accepted")?;
    check(
        error.kind() == ErrorKind::InvalidConfig,
        "unrepresentable interval returned the wrong error kind",
    )
}

#[test]
fn write_only_heartbeat_does_not_validate_unused_receive_limits() -> TestResult {
    let config = ApplicationHeartbeatConfig {
        receive_options: crate::ws::ReceiveOptions {
            max_messages: 0,
            ..crate::ws::ReceiveOptions::default()
        },
        ..ApplicationHeartbeatConfig::new(Duration::from_secs(1), "ping")
    };
    check(
        config.validate().is_ok(),
        "write-only heartbeat validated an unused receive queue",
    )
}

#[test]
fn response_timeout_requires_matcher_and_positive_miss_limit() -> TestResult {
    let timeout_without_matcher = ApplicationHeartbeatConfig::new(Duration::from_secs(1), "ping")
        .with_send_timeout(Duration::from_secs(1));
    let timeout_without_matcher = ApplicationHeartbeatConfig {
        response_timeout: Some(Duration::from_secs(1)),
        ..timeout_without_matcher
    };
    let timeout_error = timeout_without_matcher
        .validate()
        .err()
        .ok_or("response timeout without matcher was accepted")?;
    check(
        timeout_error.kind() == ErrorKind::InvalidConfig,
        "response matcher validation error kind changed",
    )?;

    let zero_misses = ApplicationHeartbeatConfig::new(Duration::from_secs(1), "ping")
        .with_max_missed_responses(0)
        .with_response_matcher(Duration::from_secs(1), |message| {
            message.message().and_then(Message::as_text) == Some("pong")
        });
    check(
        zero_misses.validate().is_err(),
        "zero missed response limit was accepted",
    )
}

#[test]
fn response_matcher_accepts_only_expected_message() -> TestResult {
    let config = ApplicationHeartbeatConfig::new(Duration::from_secs(1), "ping")
        .with_response_matcher(Duration::from_secs(1), |message| {
            message.message().and_then(Message::as_text) == Some("pong")
        });
    check(
        config.matcher.is_some(),
        "response matcher was not installed",
    )?;
    check(
        config.validate().is_ok(),
        "valid response matcher configuration was rejected",
    )
}

#[test]
fn snapshot_starts_running_with_zero_counters() -> TestResult {
    let snapshot = ApplicationHeartbeatSnapshot::default();
    check(
        snapshot.state == ApplicationHeartbeatState::Running,
        "snapshot did not start running",
    )?;
    check(snapshot.sent == 0, "snapshot sent count was not zero")?;
    check(
        snapshot.matched_responses == 0,
        "snapshot response count was not zero",
    )?;
    check(
        snapshot.missed_responses == 0,
        "snapshot misses were not zero",
    )?;
    check(snapshot.failures == 0, "snapshot failures were not zero")?;
    check(snapshot.last_error.is_none(), "snapshot retained an error")
}

#[test]
fn send_options_keep_a_finite_absolute_deadline() -> TestResult {
    let options = super::send_options(Duration::from_secs(2))?;
    check(
        options.deadline.is_some(),
        "heartbeat send options dropped the absolute deadline",
    )
}

#[test]
fn unrepresentable_deadline_is_rejected() -> TestResult {
    let config = ApplicationHeartbeatConfig::new(Duration::from_secs(1), "ping")
        .with_send_timeout(Duration::MAX);
    check(
        config.validate().is_err(),
        "unrepresentable send deadline was accepted",
    )
}

#[test]
fn control_frames_are_rejected_for_application_matching() -> TestResult {
    let config = ApplicationHeartbeatConfig::new(Duration::from_secs(1), "ping")
        .with_response_matcher(Duration::from_secs(1), |_| true)
        .with_receive_options(crate::ws::ReceiveOptions {
            include_control_frames: true,
            ..crate::ws::ReceiveOptions::default()
        });
    let error = config
        .validate()
        .err()
        .ok_or("control frames were accepted by application heartbeat")?;
    check(
        error.kind() == ErrorKind::InvalidConfig,
        "control-frame validation returned the wrong error kind",
    )
}

#[test]
fn matcher_requires_response_timeout() -> TestResult {
    let config = ApplicationHeartbeatConfig {
        matcher: Some(std::sync::Arc::new(|message| {
            message.message().and_then(Message::as_text) == Some("pong")
        })),
        ..ApplicationHeartbeatConfig::new(Duration::from_secs(1), "ping")
    };
    check(
        config.validate().is_err(),
        "matcher without response timeout was accepted",
    )
}