datum-net 0.9.0

Network sources and sinks for Datum streams, built on datum-core
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
use datum::{
    Keep, Sink, Source, StreamError,
    io::{Compression, Framing},
    testkit::TestSink,
};
use datum_net::quic::{
    crypto::rustls::{QuicClientConfig, QuicServerConfig},
    quinn,
    rustls::{
        ClientConfig as QuicRustlsClientConfig, RootCertStore as QuicRootCertStore,
        ServerConfig as QuicRustlsServerConfig,
        pki_types::{
            CertificateDer as QuicCertificateDer, PrivateKeyDer as QuicPrivateKeyDer,
            PrivatePkcs8KeyDer as QuicPrivatePkcs8KeyDer,
        },
    },
};
use datum_net::tls::rustls::{
    ClientConfig, RootCertStore, ServerConfig,
    pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer, ServerName},
};
use datum_net::{ConnectionSettings, RetryPolicy, TokioQuic, TokioTls, TokioUdp};
use rcgen::{CertifiedKey, generate_simple_self_signed};
use std::net::{SocketAddr, TcpListener, TcpStream, UdpSocket as StdUdpSocket};
use std::sync::{Arc, mpsc};
use std::thread;
use std::time::{Duration, Instant};

const SMALL_CHUNK: usize = 3;
const UDP_DATAGRAM_SIZE: usize = 2048;
const UDP_RECEIVE_BUFFER: usize = 8;

fn wait_until(timeout: Duration, condition: impl Fn() -> bool) -> bool {
    let deadline = Instant::now() + timeout;
    while Instant::now() < deadline {
        if condition() {
            return true;
        }
        thread::sleep(Duration::from_millis(5));
    }
    condition()
}

fn assert_failed(error: StreamError) {
    assert!(
        matches!(
            error,
            StreamError::Failed(_) | StreamError::AbruptTermination | StreamError::Cancelled
        ),
        "expected failure-shaped stream error, got {error:?}"
    );
}

fn tls_configs() -> (Arc<ServerConfig>, Arc<ClientConfig>, ServerName<'static>) {
    let CertifiedKey { cert, key_pair } =
        generate_simple_self_signed(["localhost".to_owned()]).expect("self-signed cert");
    let cert_der: CertificateDer<'static> = cert.der().clone();
    let key_der = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key_pair.serialize_der()));

    let server_config = ServerConfig::builder()
        .with_no_client_auth()
        .with_single_cert(vec![cert_der.clone()], key_der)
        .expect("server config");

    let mut roots = RootCertStore::empty();
    roots.add(cert_der).expect("trust self-signed cert");
    let client_config = ClientConfig::builder()
        .with_root_certificates(roots)
        .with_no_client_auth();

    (
        Arc::new(server_config),
        Arc::new(client_config),
        ServerName::try_from("localhost")
            .expect("server name")
            .to_owned(),
    )
}

fn quic_configs() -> (quinn::ServerConfig, quinn::ClientConfig) {
    let CertifiedKey { cert, key_pair } =
        generate_simple_self_signed(["localhost".to_owned()]).expect("self-signed cert");
    let cert_der: QuicCertificateDer<'static> = cert.der().clone();
    let key_der = QuicPrivateKeyDer::Pkcs8(QuicPrivatePkcs8KeyDer::from(key_pair.serialize_der()));
    let server_crypto = QuicRustlsServerConfig::builder()
        .with_no_client_auth()
        .with_single_cert(vec![cert_der.clone()], key_der)
        .expect("server config");

    let mut roots = QuicRootCertStore::empty();
    roots.add(cert_der).expect("trust self-signed cert");
    let client_crypto = QuicRustlsClientConfig::builder()
        .with_root_certificates(roots)
        .with_no_client_auth();

    (
        quinn::ServerConfig::with_crypto(Arc::new(
            QuicServerConfig::try_from(server_crypto).expect("QUIC server config"),
        )),
        quinn::ClientConfig::new(Arc::new(
            QuicClientConfig::try_from(client_crypto).expect("QUIC client config"),
        )),
    )
}

fn accept_one(listener: TcpListener, timeout: Duration) -> TcpStream {
    listener
        .set_nonblocking(true)
        .expect("set listener nonblocking");
    let deadline = Instant::now() + timeout;
    loop {
        match listener.accept() {
            Ok((stream, _)) => return stream,
            Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
                assert!(
                    Instant::now() < deadline,
                    "timed out waiting for TCP accept"
                );
                thread::sleep(Duration::from_millis(5));
            }
            Err(error) => panic!("TCP accept failed: {error}"),
        }
    }
}

fn can_bind_udp(addr: SocketAddr) -> bool {
    StdUdpSocket::bind(addr).is_ok()
}

fn lifecycle_settings() -> ConnectionSettings {
    ConnectionSettings::default()
        .connect_timeout(Duration::from_millis(100))
        .handshake_timeout(Duration::from_millis(100))
        .retry_policy(
            RetryPolicy::default()
                .max_attempts(8)
                .initial_backoff(Duration::from_millis(10))
                .max_backoff(Duration::from_millis(40)),
        )
}

#[test]
fn tls_delimiter_framing_preserves_frames_across_tls_chunks() {
    let (server_config, client_config, server_name) = tls_configs();
    let (binding_completion, incoming_completion) =
        TokioTls::bind("127.0.0.1:0", server_config, SMALL_CHUNK)
            .to_mat(Sink::head(), Keep::both)
            .run()
            .expect("TLS bind source materializes");
    let binding = binding_completion.wait().expect("TLS binding succeeds");

    let (connection_completion, client_response) =
        Source::from_iterable([b"alp".to_vec(), b"ha\nbe".to_vec(), b"ta\ngamma\n".to_vec()])
            .via_mat(
                TokioTls::outgoing_connection(
                    binding.local_addr(),
                    server_name,
                    client_config,
                    SMALL_CHUNK,
                ),
                Keep::right,
            )
            .via(Framing::delimiter(b"\n".to_vec(), 64, false))
            .to_mat(Sink::collect(), Keep::both)
            .run()
            .expect("framed TLS client stream materializes");

    let incoming = incoming_completion
        .wait()
        .expect("server accepts TLS connection");
    connection_completion
        .wait()
        .expect("client TLS connection completes");

    let (server_source, server_sink) = incoming.into_parts();
    let frames = server_source
        .via(Framing::delimiter(b"\n".to_vec(), 64, false))
        .take(3)
        .run_with(Sink::collect())
        .expect("server framed read materializes")
        .wait()
        .expect("server reads framed request");
    assert_eq!(
        frames,
        vec![b"alpha".to_vec(), b"beta".to_vec(), b"gamma".to_vec()]
    );

    Source::from_iterable([b"ok:alpha\nok:".to_vec(), b"beta\nok:gamma\n".to_vec()])
        .run_with(server_sink)
        .expect("server framed response materializes")
        .wait()
        .expect("server writes framed response");

    assert_eq!(
        client_response
            .wait()
            .expect("client decodes framed response"),
        vec![
            b"ok:alpha".to_vec(),
            b"ok:beta".to_vec(),
            b"ok:gamma".to_vec()
        ]
    );
}

#[test]
fn tls_compression_carries_gzip_payload_to_decompressing_peer() {
    let (server_config, client_config, server_name) = tls_configs();
    let (binding_completion, incoming_completion) =
        TokioTls::bind("127.0.0.1:0", server_config, SMALL_CHUNK)
            .to_mat(Sink::head(), Keep::both)
            .run()
            .expect("TLS bind source materializes");
    let binding = binding_completion.wait().expect("TLS binding succeeds");

    let payload = b"gzip over TLS with enough bytes to cross several TLS read chunks".repeat(4);
    let (connection_completion, mut client_probe) = Source::<Vec<u8>>::empty()
        .via_mat(
            TokioTls::outgoing_connection(
                binding.local_addr(),
                server_name,
                client_config,
                SMALL_CHUNK,
            ),
            Keep::right,
        )
        .via(Compression::gunzip())
        .to_mat(TestSink::probe(), Keep::both)
        .run()
        .expect("decompressing TLS client stream materializes");
    client_probe.set_timeout(Duration::from_secs(3));
    client_probe.request(128);

    let incoming = incoming_completion
        .wait()
        .expect("server accepts TLS connection");
    connection_completion
        .wait()
        .expect("client TLS connection completes");

    let (_server_source, server_sink) = incoming.into_parts();
    Source::from_iterable([
        payload[..17].to_vec(),
        payload[17..71].to_vec(),
        payload[71..].to_vec(),
    ])
    .via(Compression::gzip())
    .run_with(server_sink)
    .expect("server gzip response materializes")
    .wait()
    .expect("server writes compressed response");

    let mut decoded = Vec::new();
    while decoded.len() < payload.len() {
        decoded.extend(client_probe.expect_next());
    }
    assert_eq!(decoded, payload);
}

#[test]
fn quic_bidirectional_stream_json_framing_round_trip() {
    let (server_config, client_config) = quic_configs();
    let (binding_completion, incoming_completion) =
        TokioQuic::bind("127.0.0.1:0", server_config, SMALL_CHUNK)
            .to_mat(Sink::head(), Keep::both)
            .run()
            .expect("QUIC bind source materializes");
    let binding = binding_completion.wait().expect("QUIC binding succeeds");

    let client_connection = TokioQuic::connect(
        binding.local_addr(),
        "localhost",
        client_config,
        SMALL_CHUNK,
    )
    .run_with(Sink::head())
    .expect("QUIC client connection source materializes")
    .wait()
    .expect("QUIC client connects");
    let incoming = incoming_completion
        .wait()
        .expect("server accepts QUIC connection");

    let (stream_completion, client_response) = Source::from_iterable([
        br#"[{"id":1,"payload":"al"#.to_vec(),
        br#"pha"},{"id":2,"payload":"beta"}]"#.to_vec(),
    ])
    .via_mat(client_connection.open_bi(SMALL_CHUNK), Keep::right)
    .via(Framing::json(128))
    .to_mat(Sink::collect(), Keep::both)
    .run()
    .expect("QUIC JSON-framed stream materializes");

    let accepted_stream = incoming
        .accept_bi(SMALL_CHUNK)
        .run_with(Sink::head())
        .expect("server accept_bi source materializes")
        .wait()
        .expect("server accepts QUIC bi stream");
    let (server_source, server_sink) = accepted_stream.into_parts();
    let frames = server_source
        .via(Framing::json(128))
        .take(2)
        .run_with(Sink::collect())
        .expect("server JSON framing materializes")
        .wait()
        .expect("server reads JSON frames");
    assert_eq!(
        frames,
        vec![
            br#"{"id":1,"payload":"alpha"}"#.to_vec(),
            br#"{"id":2,"payload":"beta"}"#.to_vec()
        ]
    );

    Source::from_iterable([
        br#"{"ok":true,"id":1}"#.to_vec(),
        br#"{"ok":true,"id":2}"#.to_vec(),
    ])
    .run_with(server_sink)
    .expect("server JSON response materializes")
    .wait()
    .expect("server writes JSON response");

    assert_eq!(
        client_response.wait().expect("client receives JSON frames"),
        vec![
            br#"{"ok":true,"id":1}"#.to_vec(),
            br#"{"ok":true,"id":2}"#.to_vec()
        ]
    );
    stream_completion.wait().expect("QUIC stream opens");
}

#[test]
fn udp_payloads_flow_through_core_map_filter_and_drop_releases_socket() {
    let (binding_completion, mut probe) =
        TokioUdp::bind("127.0.0.1:0", UDP_DATAGRAM_SIZE, UDP_RECEIVE_BUFFER)
            .map(|datagram| datagram.into_payload())
            .filter(|payload| payload.starts_with(b"keep"))
            .to_mat(TestSink::probe(), Keep::both)
            .run()
            .expect("UDP bind source with core operators materializes");
    probe.set_timeout(Duration::from_secs(3));
    probe.request(2);
    let binding = binding_completion.wait().expect("UDP bind succeeds");

    let sender = StdUdpSocket::bind("127.0.0.1:0").expect("sender UDP socket");
    for payload in [b"drop-one".as_slice(), b"keep-one", b"keep-two"] {
        sender
            .send_to(payload, binding.local_addr())
            .expect("send UDP datagram");
    }

    let mut received = vec![probe.expect_next(), probe.expect_next()];
    received.sort();
    assert_eq!(received, vec![b"keep-one".to_vec(), b"keep-two".to_vec()]);

    drop(probe);
    assert!(
        wait_until(Duration::from_secs(3), || can_bind_udp(
            binding.local_addr()
        )),
        "dropping composed UDP stream should release the bound socket"
    );
}

#[test]
fn lifecycle_tls_retry_then_carries_framed_data() {
    let (server_config, client_config, server_name) = tls_configs();
    let dummy_listener = TcpListener::bind("127.0.0.1:0").expect("dummy TCP listener");
    let addr = dummy_listener.local_addr().expect("dummy TCP addr");
    let (server_done_sender, server_done_receiver) = mpsc::channel();

    let server = thread::spawn(move || {
        let first_attempt = accept_one(dummy_listener, Duration::from_secs(3));
        drop(first_attempt);

        let (binding_completion, incoming_completion) =
            TokioTls::bind(addr, server_config, SMALL_CHUNK)
                .to_mat(Sink::head(), Keep::both)
                .run()
                .expect("real TLS server materializes");
        binding_completion
            .wait()
            .expect("real TLS server binds after first failure");

        let incoming = incoming_completion
            .wait()
            .expect("retry accepts TLS connection");
        let (source, sink) = incoming.into_parts();
        let request = source
            .via(Framing::delimiter(b"\n".to_vec(), 64, false))
            .run_with(Sink::head())
            .expect("server framed read materializes")
            .wait()
            .expect("server reads framed request");
        assert_eq!(request, b"retry-frame".to_vec());

        Source::single(b"retry-ok\n".to_vec())
            .run_with(sink)
            .expect("server framed echo materializes")
            .wait()
            .expect("server framed echo completes");
        server_done_sender.send(()).expect("send server done");
    });

    let (connection_completion, response_completion) = Source::single(b"retry-frame\n".to_vec())
        .via_mat(
            TokioTls::outgoing_connection_with_lifecycle(
                addr,
                server_name,
                client_config,
                lifecycle_settings(),
            ),
            Keep::right,
        )
        .via(Framing::delimiter(b"\n".to_vec(), 64, false))
        .to_mat(Sink::head(), Keep::both)
        .run()
        .expect("lifecycle client stream materializes");

    let connection = connection_completion
        .wait()
        .expect("client connects after retry");
    assert_eq!(connection.remote_addr(), addr);
    assert_eq!(
        response_completion
            .wait()
            .expect("client receives framed response"),
        b"retry-ok".to_vec()
    );

    server_done_receiver
        .recv_timeout(Duration::from_secs(3))
        .expect("server finishes");
    server.join().expect("server thread joins");
}

#[test]
fn peer_drop_mid_tls_framed_stream_surfaces_stream_error() {
    let (server_config, client_config, server_name) = tls_configs();
    let (binding_completion, incoming_completion) =
        TokioTls::bind("127.0.0.1:0", server_config, SMALL_CHUNK)
            .to_mat(Sink::head(), Keep::both)
            .run()
            .expect("TLS bind source materializes");
    let binding = binding_completion.wait().expect("TLS binding succeeds");

    let (connection_completion, client_response) = Source::single(b"request\n".to_vec())
        .via_mat(
            TokioTls::outgoing_connection(
                binding.local_addr(),
                server_name,
                client_config,
                SMALL_CHUNK,
            ),
            Keep::right,
        )
        .via(Framing::delimiter(b"\n".to_vec(), 64, false))
        .to_mat(Sink::head(), Keep::both)
        .run()
        .expect("framed TLS client stream materializes");

    let incoming = incoming_completion
        .wait()
        .expect("server accepts TLS connection");
    connection_completion
        .wait()
        .expect("client TLS connection completes");
    drop(incoming);

    let error = client_response
        .wait()
        .expect_err("peer drop should fail the framed response stream");
    assert_failed(error);
}