dnet 0.1.4

Message passing infrastructure.
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
//! Transport for communication over [Quinn](https://github.com/quinn-rs/quinn)
//! QUIC implementation.

use std::{
    pin::Pin,
    task::{Context, Poll},
};

use dnet_base::{Decode, Encode};
use futures::{stream::FusedStream, Sink, Stream};
use pin_project::pin_project;
use quinn::{RecvStream, SendStream};
use serde::{Deserialize, Serialize};
use tokio::io::{AsyncRead, AsyncWrite, Join};

use crate::io::{
    length_delimited::{self, DEFAULT_MAX_MESSAGE_LENGTH},
    Buffered, Pending, Void,
};

pub mod framed;
pub use framed::QuicFramedTransport;

pub mod unreliable;
pub use unreliable::QuicUnreliableTransport;

/// Length-delimited QUIC transport error.
pub type Error<Codec> = length_delimited::Error<<Codec as Encode>::Error, <Codec as Decode>::Error>;

/// Unidirectional receiving transport.
///
/// This transport can only receive messages.
/// Sending messages will succeed but will not have any effect - they will be sent into the void.
pub type UnidirectionalReceive = Join<RecvStream, Void>;

/// Unidirectional sending transport.
///
/// This transport can only send messages.
/// Note: attempt to receive a message will never complete.
pub type UnidirectionalSend = Join<Pending, SendStream>;

/// Bidirectional transport.
pub type Bidirectional = Join<RecvStream, SendStream>;

/// Wrapper for messages sent over QUIC transport.
#[derive(Debug, Serialize, Deserialize)]
pub enum Wrapper<T> {
    /// Open message - sent when a new transport is created to signal
    /// the other side that the transport is ready to be used.
    Open,

    /// Regular message.
    Message(T),
}

/// Length-delimited QUIC transport.
///
/// See [length_delimited] module for more details on the used framing method.
#[pin_project]
pub struct QuicTransport<T, Codec, Incoming, Outgoing>
where
    T: AsyncRead + AsyncWrite,
    Codec: crate::Codec,
    for<'de> Incoming: serde::de::Deserialize<'de>,
    Outgoing: Serialize,
{
    #[pin]
    inner: QuicFramedTransport<T, length_delimited::Codec<Codec>, Incoming, Outgoing>,
}

impl<Codec, Incoming, Outgoing> QuicTransport<Bidirectional, Codec, Incoming, Outgoing>
where
    Codec: crate::Codec,
    for<'de> Incoming: serde::de::Deserialize<'de>,
    Outgoing: Serialize,
{
    /// Create new length-delimited QUIC transport wrapping a provided [RecvStream] and [SendStream].
    ///
    /// **NOTE**: By default serialized message size is limited to [DEFAULT_MAX_MESSAGE_LENGTH].<br>
    /// Sending or receiving messages of larger size will result in [Error::MessageTooLong].
    pub async fn new(
        send_stream: SendStream,
        recv_stream: RecvStream,
        codec: Codec,
    ) -> Result<Self, crate::Error<Error<Codec>>> {
        QuicTransport::new_with_max_message_length(
            send_stream,
            recv_stream,
            codec,
            DEFAULT_MAX_MESSAGE_LENGTH,
        )
        .await
    }

    /// Create new length-delimited QUIC transport wrapping a provided [RecvStream] and [SendStream].
    ///
    /// Serialized message size will be limited to `max_message_length`.<br>
    /// Sending or receiving messages of larger size will result in [Error::MessageTooLong].
    pub async fn new_with_max_message_length(
        send_stream: SendStream,
        recv_stream: RecvStream,
        codec: Codec,
        max_message_length: u32,
    ) -> Result<Self, crate::Error<Error<Codec>>> {
        let inner = QuicFramedTransport::new(
            send_stream,
            recv_stream,
            length_delimited::Codec::new(codec, max_message_length),
        )
        .await
        .map_err(length_delimited::map_error)?;
        Ok(QuicTransport { inner })
    }
}

impl<Codec, Incoming, Outgoing> QuicTransport<UnidirectionalSend, Codec, Incoming, Outgoing>
where
    Codec: crate::Codec,
    for<'de> Incoming: serde::de::Deserialize<'de>,
    Outgoing: Serialize,
{
    /// Create new [unidirectional](UnidirectionalSend) length-delimited QUIC transport wrapping a provided [SendStream].
    ///
    /// **NOTE**: By default serialized message size is limited to [DEFAULT_MAX_MESSAGE_LENGTH].<br>
    /// Sending messages of larger size will result in [Error::MessageTooLong].
    pub async fn unidirectional_send(
        send_stream: SendStream,
        codec: Codec,
    ) -> Result<Self, crate::Error<Error<Codec>>> {
        QuicTransport::unidirectional_send_with_max_message_length(
            send_stream,
            codec,
            DEFAULT_MAX_MESSAGE_LENGTH,
        )
        .await
    }

    /// Create new [unidirectional](UnidirectionalSend) length-delimited QUIC transport wrapping a provided [SendStream].
    ///
    /// Serialized message size will be limited to `max_message_length`.<br>
    /// Sending messages of larger size will result in [Error::MessageTooLong].
    pub async fn unidirectional_send_with_max_message_length(
        send_stream: SendStream,
        codec: Codec,
        max_message_length: u32,
    ) -> Result<Self, crate::Error<Error<Codec>>> {
        let inner = QuicFramedTransport::unidirectional_send(
            send_stream,
            length_delimited::Codec::new(codec, max_message_length),
        )
        .await
        .map_err(length_delimited::map_error)?;
        Ok(QuicTransport { inner })
    }
}

impl<Codec, Incoming, Outgoing> QuicTransport<UnidirectionalReceive, Codec, Incoming, Outgoing>
where
    Codec: crate::Codec,
    for<'de> Incoming: serde::de::Deserialize<'de>,
    Outgoing: Serialize,
{
    /// Create new [unidirectional](UnidirectionalReceive) length-delimited QUIC transport wrapping a provided [RecvStream].
    ///
    /// **NOTE**: By default serialized message size is limited to [DEFAULT_MAX_MESSAGE_LENGTH].
    /// Receiving messages of larger size will result in [Error::MessageTooLong].
    pub async fn unidirectional_receive(
        recv_stream: RecvStream,
        codec: Codec,
    ) -> Result<Self, crate::Error<Error<Codec>>> {
        QuicTransport::unidirectional_receive_with_max_message_length(
            recv_stream,
            codec,
            DEFAULT_MAX_MESSAGE_LENGTH,
        )
        .await
    }

    /// Create new [unidirectional](UnidirectionalReceive) length-delimited QUIC transport wrapping a provided [RecvStream].
    ///
    /// Serialized message size will be limited to `max_message_length`.<br>
    /// Receiving messages of larger size will result in [Error::MessageTooLong].
    pub async fn unidirectional_receive_with_max_message_length(
        recv_stream: RecvStream,
        codec: Codec,
        max_message_length: u32,
    ) -> Result<Self, crate::Error<Error<Codec>>> {
        let inner = QuicFramedTransport::unidirectional_receive(
            recv_stream,
            length_delimited::Codec::new(codec, max_message_length),
        )
        .await
        .map_err(length_delimited::map_error)?;
        Ok(QuicTransport { inner })
    }
}

impl<Codec, Incoming, Outgoing> QuicTransport<Buffered<Bidirectional>, Codec, Incoming, Outgoing>
where
    Codec: crate::Codec,
    for<'de> Incoming: serde::de::Deserialize<'de>,
    Outgoing: Serialize,
{
    /// Create new buffered length-delimited QUIC transport wrapping a provided [RecvStream] and [SendStream].
    ///
    /// **NOTE**: By default serialized message size is limited to [DEFAULT_MAX_MESSAGE_LENGTH].<br>
    /// Sending or receiving messages of larger size will result in [Error::MessageTooLong].
    pub async fn buffered(
        send_stream: SendStream,
        recv_stream: RecvStream,
        codec: Codec,
    ) -> Result<Self, crate::Error<Error<Codec>>> {
        QuicTransport::buffered_with_max_message_length(
            send_stream,
            recv_stream,
            codec,
            DEFAULT_MAX_MESSAGE_LENGTH,
        )
        .await
    }

    /// Create new buffered length-delimited QUIC transport wrapping a provided [RecvStream] and [SendStream].
    ///
    /// Serialized message size will be limited to `max_message_length`.<br>
    /// Sending or receiving messages of larger size will result in [Error::MessageTooLong].
    pub async fn buffered_with_max_message_length(
        send_stream: SendStream,
        recv_stream: RecvStream,
        codec: Codec,
        max_message_length: u32,
    ) -> Result<Self, crate::Error<Error<Codec>>> {
        let inner = QuicFramedTransport::buffered(
            send_stream,
            recv_stream,
            length_delimited::Codec::new(codec, max_message_length),
        )
        .await
        .map_err(length_delimited::map_error)?;
        Ok(QuicTransport { inner })
    }
}

impl<Codec, Incoming, Outgoing>
    QuicTransport<Buffered<UnidirectionalSend>, Codec, Incoming, Outgoing>
where
    Codec: crate::Codec,
    for<'de> Incoming: serde::de::Deserialize<'de>,
    Outgoing: Serialize,
{
    /// Create new buffered [unidirectional](UnidirectionalSend) length-delimited QUIC transport wrapping a provided [SendStream].
    ///
    /// **NOTE**: By default serialized message size is limited to [DEFAULT_MAX_MESSAGE_LENGTH].<br>
    /// Sending messages of larger size will result in [Error::MessageTooLong].
    pub async fn buffered_unidirectional_send(
        send_stream: SendStream,
        codec: Codec,
    ) -> Result<Self, crate::Error<Error<Codec>>> {
        QuicTransport::buffered_unidirectional_send_with_max_message_length(
            send_stream,
            codec,
            DEFAULT_MAX_MESSAGE_LENGTH,
        )
        .await
    }

    /// Create new buffered [unidirectional](UnidirectionalSend) length-delimited QUIC transport wrapping a provided [SendStream].
    ///
    /// Serialized message size will be limited to `max_message_length`.<br>
    /// Sending messages of larger size will result in [Error::MessageTooLong].
    pub async fn buffered_unidirectional_send_with_max_message_length(
        send_stream: SendStream,
        codec: Codec,
        max_message_length: u32,
    ) -> Result<Self, crate::Error<Error<Codec>>> {
        let inner = QuicFramedTransport::buffered_unidirectional_send(
            send_stream,
            length_delimited::Codec::new(codec, max_message_length),
        )
        .await
        .map_err(length_delimited::map_error)?;
        Ok(QuicTransport { inner })
    }
}

impl<Codec, Incoming, Outgoing>
    QuicTransport<Buffered<UnidirectionalReceive>, Codec, Incoming, Outgoing>
where
    Codec: crate::Codec,
    for<'de> Incoming: serde::de::Deserialize<'de>,
    Outgoing: Serialize,
{
    /// Create new buffered [unidirectional](UnidirectionalReceive) length-delimited QUIC transport wrapping a provided [RecvStream].
    ///
    /// **NOTE**: By default serialized message size is limited to [DEFAULT_MAX_MESSAGE_LENGTH].<br>
    /// Receiving messages of larger size will result in [Error::MessageTooLong].
    pub async fn buffered_unidirectional_receive(
        recv_stream: RecvStream,
        codec: Codec,
    ) -> Result<Self, crate::Error<Error<Codec>>> {
        QuicTransport::buffered_unidirectional_receive_with_max_message_length(
            recv_stream,
            codec,
            DEFAULT_MAX_MESSAGE_LENGTH,
        )
        .await
    }

    /// Create new buffered [unidirectional](UnidirectionalReceive) length-delimited QUIC transport wrapping a provided [RecvStream].
    ///
    /// Serialized message size will be limited to `max_message_length`.<br>
    /// Receiving messages of larger size will result in [Error::MessageTooLong].
    pub async fn buffered_unidirectional_receive_with_max_message_length(
        recv_stream: RecvStream,
        codec: Codec,
        max_message_length: u32,
    ) -> Result<Self, crate::Error<Error<Codec>>> {
        let inner = QuicFramedTransport::buffered_unidirectional_receive(
            recv_stream,
            length_delimited::Codec::new(codec, max_message_length),
        )
        .await
        .map_err(length_delimited::map_error)?;
        Ok(QuicTransport { inner })
    }
}

impl<T, Codec, Incoming, Outgoing> Sink<Outgoing> for QuicTransport<T, Codec, Incoming, Outgoing>
where
    T: AsyncRead + AsyncWrite,
    Codec: crate::Codec,
    for<'de> Incoming: serde::de::Deserialize<'de>,
    Outgoing: Serialize,
{
    type Error = crate::Error<Error<Codec>>;

    fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.project()
            .inner
            .poll_ready(cx)
            .map_err(length_delimited::map_error)
    }

    fn start_send(self: Pin<&mut Self>, item: Outgoing) -> Result<(), Self::Error> {
        self.project()
            .inner
            .start_send(item)
            .map_err(length_delimited::map_error)
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.project()
            .inner
            .poll_flush(cx)
            .map_err(length_delimited::map_error)
    }

    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.project()
            .inner
            .poll_close(cx)
            .map_err(length_delimited::map_error)
    }
}

impl<T, Codec, Incoming, Outgoing> Stream for QuicTransport<T, Codec, Incoming, Outgoing>
where
    T: AsyncRead + AsyncWrite,
    Codec: crate::Codec,
    for<'de> Incoming: serde::de::Deserialize<'de>,
    Outgoing: Serialize,
{
    type Item = Result<
        Incoming,
        length_delimited::Error<<Codec as Encode>::Error, <Codec as Decode>::Error>,
    >;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.project()
            .inner
            .poll_next(cx)
            .map_err(length_delimited::map_error_inner)
    }
}

impl<T, Codec, Incoming, Outgoing> FusedStream for QuicTransport<T, Codec, Incoming, Outgoing>
where
    T: AsyncRead + AsyncWrite,
    Codec: crate::Codec,
    for<'de> Incoming: serde::de::Deserialize<'de>,
    Outgoing: Serialize,
{
    fn is_terminated(&self) -> bool {
        self.inner.is_terminated()
    }
}

#[cfg(feature = "logging")]
impl<T, Codec, Incoming, Outgoing> dnet_base::Logging
    for QuicTransport<T, Codec, Incoming, Outgoing>
where
    T: AsyncRead + AsyncWrite,
    Codec: crate::Codec,
    for<'de> Incoming: serde::de::Deserialize<'de>,
    Outgoing: Serialize,
{
    const KIND: &'static str = "QUIC";

    fn with_logger<F, R>(&self, f: F) -> R
    where
        F: FnOnce(&dnet_base::Logger) -> R,
    {
        self.inner.with_logger(f)
    }

    fn with_logger_mut<F, R>(&mut self, f: F) -> R
    where
        F: FnOnce(&mut dnet_base::Logger) -> R,
    {
        self.inner.with_logger_mut(f)
    }
}

#[cfg(test)]
mod tests {
    use std::{
        net::{IpAddr, Ipv4Addr, SocketAddr},
        sync::Arc,
    };

    use dnet_codecs::BincodeCodec;
    use futures::join;
    use quinn::{rustls::pki_types::CertificateDer, ClientConfig, Endpoint, ServerConfig};
    use rcgen::generate_simple_self_signed;
    use rustls::{pki_types::PrivatePkcs8KeyDer, RootCertStore};
    use serde::{Deserialize, Serialize};
    use tokio::spawn;

    use crate::quic::{Bidirectional, QuicTransport};

    async fn create_transports<I, O>(
        port: u16,
    ) -> (
        QuicTransport<Bidirectional, BincodeCodec, I, O>,
        QuicTransport<Bidirectional, BincodeCodec, O, I>,
    )
    where
        I: Serialize + Send + 'static,
        for<'de> I: Deserialize<'de>,
        O: Serialize + Send + 'static,
        for<'de> O: Deserialize<'de>,
    {
        let server_address = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port);

        let certificate = generate_simple_self_signed(vec!["localhost".into()]).unwrap();
        let certificate_der = CertificateDer::from(certificate.cert.clone());

        let certificate_der_clone = CertificateDer::from(certificate.cert.clone());
        let server = spawn(async move {
            let private_key = PrivatePkcs8KeyDer::from(certificate.signing_key.serialize_der());

            let mut server_config =
                ServerConfig::with_single_cert(vec![certificate_der_clone], private_key.into())
                    .unwrap();
            let transport_config = Arc::get_mut(&mut server_config.transport).unwrap();
            transport_config.max_concurrent_uni_streams(0_u8.into());

            let endpoint = Endpoint::server(server_config, server_address).unwrap();

            let incoming = endpoint.accept().await.unwrap();

            let connection = incoming.await.unwrap();

            let (send_stream, recv_stream) = connection.accept_bi().await.unwrap();

            QuicTransport::new(send_stream, recv_stream, BincodeCodec::default())
                .await
                .unwrap()
        });

        let client = spawn(async move {
            let mut certificates = RootCertStore::empty();
            certificates.add(certificate_der).unwrap();
            let config = ClientConfig::with_root_certificates(Arc::new(certificates)).unwrap();

            let mut endpoint = Endpoint::client("0.0.0.0:0".parse().unwrap()).unwrap();
            endpoint.set_default_client_config(config);

            let connecting = endpoint.connect(server_address, "localhost").unwrap();

            let connection = connecting.await.unwrap();

            let (send_stream, recv_stream) = connection.open_bi().await.unwrap();

            QuicTransport::new(send_stream, recv_stream, BincodeCodec::default())
                .await
                .unwrap()
        });

        let (left, right) = join!(server, client);
        let left = left.unwrap();
        let right = right.unwrap();

        (left, right)
    }

    #[tokio::test]
    async fn test_transport() {
        let (left, right) = create_transports(8180).await;
        dnet_tests::test_transport(left, right).await;
    }

    #[tokio::test]
    async fn test_unit_message() {
        let (left, right) = create_transports(8181).await;
        dnet_tests::test_unit_message(left, right).await;
    }

    #[tokio::test]
    async fn test_stream() {
        let (left, right) = create_transports(8182).await;
        dnet_tests::test_stream(left, right).await;
    }
}