peaplex 0.1.1

A profoundly minimal, zero-copy stream multiplexer for any AsyncRead + AsyncWrite connection.
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
//! End-to-end tests for the standalone peaplex over a `tokio::io::duplex`
//! pair - no real network, no extra dependencies.

use std::time::Duration;

use peaplex::{FLAG_CLOSE, FLAG_DATA, FrameCodec, Multiplexer, Side, StreamId};
use tokio::{
    io::{AsyncReadExt, AsyncWriteExt, duplex},
    time::timeout,
};

fn small_pair() -> (
    Multiplexer<tokio::io::DuplexStream>,
    Multiplexer<tokio::io::DuplexStream>,
) {
    let (a, b) = duplex(64 * 1024);
    (
        Multiplexer::new(a, Side::Initiator),
        Multiplexer::new(b, Side::Responder),
    )
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn basic_roundtrip() {
    let (a, b) = small_pair();

    let reader = tokio::spawn(async move {
        let mut s = b.accept().await.unwrap();
        let mut buf = Vec::new();
        s.read_to_end(&mut buf).await.unwrap();
        buf
    });

    let mut s = a.open_stream().unwrap();
    let payload = b"hello, peaplex!";
    s.write_all(payload).await.unwrap();
    drop(s);

    let got = timeout(Duration::from_secs(5), reader)
        .await
        .expect("reader timed out")
        .unwrap();
    assert_eq!(got, payload);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn bidirectional_streams() {
    let (a, b) = small_pair();

    // a -> b
    let b2 = b.clone();
    let b_reader = tokio::spawn(async move {
        let mut s = b2.accept().await.unwrap();
        let mut buf = Vec::new();
        s.read_to_end(&mut buf).await.unwrap();
        buf
    });
    let mut s_ab = a.open_stream().unwrap();
    s_ab.write_all(b"from a to b").await.unwrap();
    drop(s_ab);
    assert_eq!(
        timeout(Duration::from_secs(5), b_reader)
            .await
            .unwrap()
            .unwrap(),
        b"from a to b"
    );

    // b -> a
    let a2 = a.clone();
    let a_reader = tokio::spawn(async move {
        let mut s = a2.accept().await.unwrap();
        let mut buf = Vec::new();
        s.read_to_end(&mut buf).await.unwrap();
        buf
    });
    let mut s_ba = b.open_stream().unwrap();
    s_ba.write_all(b"from b to a").await.unwrap();
    drop(s_ba);
    assert_eq!(
        timeout(Duration::from_secs(5), a_reader)
            .await
            .unwrap()
            .unwrap(),
        b"from b to a"
    );
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn many_concurrent_streams() {
    let (a, b) = small_pair();

    const N: usize = 32;
    let b2 = b.clone();
    let reader = tokio::spawn(async move {
        let mut received = Vec::with_capacity(N);
        for _ in 0..N {
            let mut s = b2.accept().await.unwrap();
            let mut buf = Vec::new();
            s.read_to_end(&mut buf).await.unwrap();
            received.push(buf);
        }
        received
    });

    let mut writers = Vec::new();
    for i in 0..N {
        let a = a.clone();
        writers.push(tokio::spawn(async move {
            let mut s = a.open_stream().unwrap();
            let payload = format!("stream #{i}");
            s.write_all(payload.as_bytes()).await.unwrap();
            s.shutdown().await.unwrap();
        }));
    }
    for w in writers {
        w.await.unwrap();
    }

    let received = timeout(Duration::from_secs(10), reader)
        .await
        .unwrap()
        .unwrap();
    let mut expected: Vec<Vec<u8>> = (0..N)
        .map(|i| format!("stream #{i}").into_bytes())
        .collect();
    let mut got = received;
    expected.sort();
    got.sort();
    assert_eq!(got, expected);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn large_payload_roundtrip() {
    let (a, b) = small_pair();

    let payload: Vec<u8> = (0..(4 * 1024 * 1024)).map(|i| (i % 251) as u8).collect();

    let b2 = b.clone();
    let reader = tokio::spawn(async move {
        let mut s = b2.accept().await.unwrap();
        let mut buf = Vec::new();
        s.read_to_end(&mut buf).await.unwrap();
        buf
    });

    let mut s = a.open_stream().unwrap();
    for chunk in payload.chunks(64 * 1024) {
        s.write_all(chunk).await.unwrap();
    }
    drop(s);

    let received = timeout(Duration::from_secs(10), reader)
        .await
        .unwrap()
        .unwrap();
    assert_eq!(received.len(), payload.len());
    assert_eq!(received, payload);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn shutdown_closes_streams() {
    let (a, b) = small_pair();
    let a2 = a.clone();

    let b_reader = tokio::spawn(async move {
        let mut s = b.accept().await.unwrap();
        let mut buf = Vec::new();
        // Read until EOF.
        let _ = s.read_to_end(&mut buf).await.unwrap();
        buf
    });

    let mut s = a.open_stream().unwrap();
    s.write_all(b"before shutdown").await.unwrap();

    // Give b a moment to receive the data.
    tokio::time::sleep(Duration::from_millis(20)).await;
    a.shutdown();

    // Further writes must fail.
    let err = s.write_all(b"after shutdown").await.unwrap_err();
    assert_eq!(err.kind(), std::io::ErrorKind::BrokenPipe);

    let got = timeout(Duration::from_secs(5), b_reader)
        .await
        .unwrap()
        .unwrap();
    // b might see the full payload and then EOF, or just EOF; both are
    // valid.
    assert!(
        got == b"before shutdown" || got.is_empty(),
        "unexpected payload: {got:?}"
    );
    let _ = a2;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn stream_id_layout() {
    // Initiator mints odd IDs, Responder mints even IDs.
    let (a, b) = small_pair();
    let _ = b.clone();

    let s1 = a.open_stream().unwrap();
    let s2 = a.open_stream().unwrap();
    let s3 = b.open_stream().unwrap();
    let s4 = b.open_stream().unwrap();
    assert_eq!(s1.id(), StreamId(1));
    assert_eq!(s2.id(), StreamId(3));
    assert_eq!(s3.id(), StreamId(2));
    assert_eq!(s4.id(), StreamId(4));
    assert!(s1.id().is_initiator());
    assert!(s3.id().is_responder());
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn dropped_stream_sends_close() {
    // If a stream is dropped without ever being written to or read from,
    // the peer's read should see EOF (the Close frame is sent on Drop).
    let (a, b) = small_pair();

    let b2 = b.clone();
    let reader = tokio::spawn(async move {
        let mut s = b2.accept().await.unwrap();
        let mut buf = Vec::new();
        s.read_to_end(&mut buf).await.unwrap();
        buf
    });

    // Open and immediately drop on A. The Drop sends Close.
    {
        let _s = a.open_stream().unwrap();
    }

    let got = timeout(Duration::from_secs(5), reader)
        .await
        .expect("reader timed out")
        .unwrap();
    assert!(got.is_empty(), "expected EOF, got {} bytes", got.len());
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn goaway_marks_all_streams_closed() {
    let (a, b) = small_pair();

    // Synchronize so A doesn't goaway before B has accepted the
    // streams. Without this, the duplex can be torn down before the
    // Open frames reach B, and B's accept loop sees `closed = true`
    // with an empty `new_streams` queue.
    let (accepted_tx, accepted_rx) = tokio::sync::oneshot::channel();
    let (go_tx, go_rx) = tokio::sync::oneshot::channel();

    let b2 = b.clone();
    let reader = tokio::spawn(async move {
        let mut s1 = b2.accept().await.unwrap();
        let mut s2 = b2.accept().await.unwrap();
        accepted_tx.send(()).unwrap();
        // Wait for A to fire goaway before reading.
        go_rx.await.unwrap();
        let mut buf = Vec::new();
        s1.read_to_end(&mut buf).await.unwrap();
        let mut buf2 = Vec::new();
        let _ = s2.read_to_end(&mut buf2).await.unwrap();
        (buf, buf2)
    });

    let mut s1 = a.open_stream().unwrap();
    let mut s2 = a.open_stream().unwrap();
    s1.write_all(b"hi").await.unwrap();
    s2.write_all(b"hello").await.unwrap();
    accepted_rx.await.unwrap();
    go_tx.send(()).unwrap();
    a.goaway(0);

    let (got, got2) = timeout(Duration::from_secs(5), reader)
        .await
        .expect("reader timed out")
        .unwrap();
    assert_eq!(got, b"hi");
    assert!(got2.is_empty() || got2 == b"hello");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn goaway_frame_is_actually_delivered() {
    use tokio_util::codec::Decoder;

    // A goes away; B should receive the GoAway frame on the wire, not
    // just observe the EOF from the duplex closing.
    let (a_io, b_io) = duplex(64 * 1024);
    let _a = Multiplexer::new(a_io, Side::Initiator);
    let mut b_reader = b_io;

    // Give the drive task a moment to start, then go away.
    tokio::time::sleep(Duration::from_millis(20)).await;
    _a.goaway(42);

    let mut buf = bytes::BytesMut::with_capacity(64);
    let n = timeout(Duration::from_secs(5), b_reader.read_buf(&mut buf))
        .await
        .expect("read timed out")
        .unwrap();
    assert!(n > 0, "expected at least one frame from a, got EOF");

    let frame = FrameCodec.decode(&mut buf).unwrap().unwrap();
    assert_eq!(frame.flag, peaplex::Flag::GoAway);
    assert_eq!(frame.payload.len(), 4);
    let reason = u32::from_be_bytes(frame.payload[..].try_into().unwrap());
    assert_eq!(reason, 42);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn goaway_reason_is_readable_by_peer() {
    // When A goes away with a reason, B can recover that reason via
    // `goaway_reason()` once the frame has been dispatched.
    let (a, b) = small_pair();

    a.goaway(7);

    // Poll until B's drive task has dispatched the GoAway frame.
    let reason = timeout(Duration::from_secs(5), async {
        loop {
            if let Some(r) = b.goaway_reason() {
                break r;
            }
            tokio::time::sleep(Duration::from_millis(5)).await;
        }
    })
    .await
    .expect("never observed goaway reason");
    assert_eq!(reason, 7);

    // A initiated the shutdown locally, so it has no inbound GoAway reason.
    assert_eq!(a.goaway_reason(), None);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn debug_impls() {
    let (a, b) = small_pair();
    let _ = format!("{:?}", a);
    let s = a.open_stream().unwrap();
    let _ = format!("{:?}", s);
    let _ = b;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn frame_codec_smoke() {
    use bytes::BytesMut;
    use peaplex::Frame;
    use tokio_util::codec::{Decoder, Encoder};

    let mut codec = FrameCodec;
    let mut buf = BytesMut::new();
    let f = Frame::data(StreamId(0x42), bytes::Bytes::from_static(b"abc"));
    codec.encode(f, &mut buf).unwrap();
    assert_eq!(buf[0], FLAG_DATA);
    let got = codec.decode(&mut buf).unwrap().unwrap();
    assert_eq!(got.stream_id, StreamId(0x42));
    assert_eq!(&got.payload[..], b"abc");
    assert!(codec.decode(&mut buf).unwrap().is_none());

    let f = Frame::close(StreamId(7));
    codec.encode(f, &mut buf).unwrap();
    assert_eq!(buf[buf.len() - 9], FLAG_CLOSE);
}

// The ID space is partitioned by side and `0` is reserved (see the `frame` module docs).
// A peer that ignores either rule, or reuses a live ID, would otherwise replace the entry of
// one of our substreams in the dispatcher - leaving that substream alive but deaf, since its
// `Stream` holds its own handle. Each case must be dropped instead of honoured.
//
// The multiplexer under test is the Initiator (it mints odd IDs), so an inbound `Open` is only
// legitimate with a nonzero even ID.
async fn inbound_open_is_ignored(id: u32) {
    use tokio_util::codec::Encoder;

    let (a_io, mut b_io) = duplex(64 * 1024);
    let a = Multiplexer::new(a_io, Side::Initiator);

    // Claim the odd ID the trespass test targets, so there is a live entry to clobber.
    let mut ours = a.open_stream().unwrap();
    assert_eq!(ours.id(), StreamId(1));

    let mut buf = bytes::BytesMut::new();
    FrameCodec
        .encode(peaplex::Frame::open(StreamId(id)), &mut buf)
        .unwrap();
    b_io.write_all(&buf).await.unwrap();
    b_io.flush().await.unwrap();

    // The rejected `Open` must not surface as an accepted substream...
    assert!(
        timeout(Duration::from_millis(200), a.accept())
            .await
            .is_err(),
        "an Open with id {id} was accepted"
    );
    // ...and our own substream must still be wired to the dispatcher: a `Data` frame for its
    // ID has to reach it, which it wouldn't if the entry had been replaced.
    let mut buf = bytes::BytesMut::new();
    FrameCodec
        .encode(
            peaplex::Frame::data(StreamId(1), bytes::Bytes::from_static(b"still here")),
            &mut buf,
        )
        .unwrap();
    b_io.write_all(&buf).await.unwrap();
    b_io.flush().await.unwrap();

    let mut got = [0u8; 10];
    timeout(Duration::from_secs(5), ours.read_exact(&mut got))
        .await
        .expect("our substream went deaf")
        .unwrap();
    assert_eq!(&got, b"still here");
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn inbound_open_trespassing_our_id_space_is_ignored() {
    // odd == the Initiator's half, which is ours
    inbound_open_is_ignored(3).await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn inbound_open_on_reserved_id_is_ignored() {
    // `0` is reserved, and would otherwise pass the parity check on this side (0 is even)
    inbound_open_is_ignored(0).await;
}

#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
async fn duplicate_inbound_open_is_ignored() {
    use tokio_util::codec::Encoder;

    let (a_io, mut b_io) = duplex(64 * 1024);
    let a = Multiplexer::new(a_io, Side::Initiator);

    let open = |id| {
        let mut buf = bytes::BytesMut::new();
        FrameCodec
            .encode(peaplex::Frame::open(StreamId(id)), &mut buf)
            .unwrap();
        buf
    };

    // A legitimate inbound Open: even, nonzero. This one must be accepted - otherwise the
    // assertions below would pass vacuously.
    b_io.write_all(&open(2)).await.unwrap();
    b_io.flush().await.unwrap();
    let mut theirs = timeout(Duration::from_secs(5), a.accept())
        .await
        .expect("the legitimate Open was not accepted")
        .unwrap();
    assert_eq!(theirs.id(), StreamId(2));

    // Re-opening the same live ID must not yield a second substream...
    b_io.write_all(&open(2)).await.unwrap();
    b_io.flush().await.unwrap();
    assert!(
        timeout(Duration::from_millis(200), a.accept())
            .await
            .is_err(),
        "a duplicate Open was accepted"
    );

    // ...nor detach the original from the dispatcher.
    let mut buf = bytes::BytesMut::new();
    FrameCodec
        .encode(
            peaplex::Frame::data(StreamId(2), bytes::Bytes::from_static(b"intact")),
            &mut buf,
        )
        .unwrap();
    b_io.write_all(&buf).await.unwrap();
    b_io.flush().await.unwrap();

    let mut got = [0u8; 6];
    timeout(Duration::from_secs(5), theirs.read_exact(&mut got))
        .await
        .expect("the original substream went deaf")
        .unwrap();
    assert_eq!(&got, b"intact");
}