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
use std::{pin::Pin, task::{Context, Poll, Waker}, io, fmt};

use futures::ready;
use tokio::{io::{AsyncRead, AsyncWrite, ReadBuf}, sync::watch};

use crate::Channel;

pub struct TransportChannel<TAsyncDuplex: AsyncRead + AsyncWrite + Send + Unpin + 'static> {
    id: u16,
    label: String,
    channel: Pin<Box<TAsyncDuplex>>,
    is_closed: bool,
    is_read_closed: bool,
    is_shutdown_requested: bool,
    read_waker: Option<Waker>,
    self_closed: watch::Receiver<bool>,
    remote_closed: watch::Receiver<bool>,
    local_closed: watch::Sender<bool>,
}

impl<TAsyncDuplex: AsyncRead + AsyncWrite + Send + Unpin + 'static> TransportChannel<TAsyncDuplex> {
    pub fn new_pair(
        id: u16,
        label: impl AsRef<str> + ToString,
        channels: (Box<TAsyncDuplex>, Box<TAsyncDuplex>),
    ) -> (Box<dyn Channel>, Box<dyn Channel>) {
        let (channel1, channel2) = channels;

        let (local_closed1, remote_closed1) = watch::channel(false);
        let (local_closed2, remote_closed2) = watch::channel(false);
    
        let label = label.to_string();
        let label1 = format!("{label}-1");
        let label2 = format!("{label}-2");

        let self_closed1 = remote_closed1.clone();
        let self_closed2 = remote_closed2.clone();
    
        let channel1 = Box::new(
            TransportChannel {
                id,
                label: label1,
                channel: Pin::new(channel1),
                is_closed: false,
                is_read_closed: false,
                is_shutdown_requested: false,
                read_waker: None,
                self_closed: self_closed1,
                remote_closed: remote_closed2,
                local_closed: local_closed1,
            },
        );
    
        let channel2 = Box::new(
            TransportChannel {
                id,
                label: label2,
                channel: Pin::new(channel2),
                is_closed: false,
                is_read_closed: false,
                is_shutdown_requested: false,
                read_waker: None,
                self_closed: self_closed2,
                remote_closed: remote_closed1,
                local_closed: local_closed2,
            },
        );
    
        return (channel1, channel2)
    }

    fn is_remote_closed(&self) -> bool {
        return *self.remote_closed.borrow();
    }
}

impl<TAsyncDuplex: AsyncRead + AsyncWrite + Send + Unpin + 'static> Channel for TransportChannel<TAsyncDuplex> {
    fn id(&self) -> u16 {
        return self.id;
    }
    
    fn label(&self) ->  &String {
        return &self.label;
    }

    fn is_closed(&self) ->  bool {
        return self.is_closed;
    }

    fn on_close(&self) -> watch::Receiver<bool> {
        return self.self_closed.clone();
    }
} 

impl<TAsyncDuplex: AsyncRead + AsyncWrite + Send + Unpin + 'static> AsyncRead for TransportChannel<TAsyncDuplex> {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        if self.is_shutdown_requested && !self.is_closed {
            let result = ready!(self.as_mut().poll_shutdown(cx));

            self.is_read_closed = true;

            return Poll::Ready(result);
        }

        // fully closed for reads, return EOF
        if self.is_closed && self.is_read_closed {
            return Poll::Ready(Ok(()));
        }
        
        let filled_before = buf.filled().len();
        
        // poll underlying channel
        let result = self.channel.as_mut().poll_read(cx, buf);

        let bytes_read = buf.filled().len() - filled_before;

        // allow for the last read after `shutdown`
        if self.is_closed && !self.is_read_closed {
            self.is_read_closed = true;

            return Poll::Ready(Ok(()));
        }

        // save or remove read waker
        if result.is_pending() {
            // save read waker in case we need to shutdown the channel
            // but someone called `read_to_end` before the channel was closed
            self.read_waker.replace(cx.waker().clone());
        } else {
            // remove read waker
            self.read_waker.take();

            if self.is_remote_closed() {
                self.is_shutdown_requested = true;

                // if received EOF, shutdown immediatelly
                if bytes_read == 0 {
                    return self.poll_shutdown(cx);
                }
            }
        }

        return result;
    }
}

impl<TAsyncDuplex: AsyncRead + AsyncWrite + Send + Unpin + 'static> AsyncWrite for TransportChannel<TAsyncDuplex> {
    fn poll_write(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        if self.is_remote_closed() {
            return Poll::Ready(Ok(0));
        }

        let result = self.channel.as_mut()
            .poll_write(cx, buf);

        return result;
    }

    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        return self.channel.as_mut()
            .poll_flush(cx);
    }

    fn poll_shutdown(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> {
        if self.is_closed {
            return Poll::Ready(Ok(()));
        }

        // wait until shut
        let result = ready!(self.channel.as_mut().poll_shutdown(cx));

        self.is_closed = true;

        // notify remote part about shutdown
        let _res = self.local_closed.send(true);

        // in some cases, if `read_to_end` was called and yielded a `Poll::Pending` result,
        // we need wake the `poll_read` again, otherwise the `read_to_end` might never return
        if let Some(waker) = self.read_waker.take() {
            waker.wake();
        }


        return Poll::Ready(result);
    }
}

impl<TAsyncDuplex: AsyncRead + AsyncWrite + Send + Unpin + 'static> fmt::Debug for TransportChannel<TAsyncDuplex> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        return self.debug("TransportChannel", f);
    }
}

#[cfg(test)]
mod tests {
    use rstest::rstest;
    use futures::{SinkExt, StreamExt};
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use cs_utils::{traits::Random, futures::wait_random, test::random_vec, random_number, random_str_rg};

    use super::TransportChannel;
    use crate::create_framed_stream;
    use crate::mocks::{channel_mock_pair, ChannelMockOptions};
    use crate::test::{test_framed_stream, test_async_stream, TestOptions, TestStreamMessage};

    #[rstest]
    #[case(128)]
    #[case(256)]
    #[case(512)]
    #[case(1_024)]
    #[case(2_048)]
    #[case(4_096)]
    #[case(8_192)]
    #[case(16_384)]
    #[case(32_768)]
    #[tokio::test]
    async fn transfers_binary_data(
        #[case] test_data_size: usize,
    ) {
        let (channel1, channel2) = channel_mock_pair(
            ChannelMockOptions::random(),
            ChannelMockOptions::random(),
        );

        let (channel1, channel2) = TransportChannel::new_pair(
            1,
            "in-memory-channel-1",
            (Box::new(channel1), Box::new(channel2)),
        );

        test_async_stream(
            channel1,
            channel2,
            TestOptions::random()
                .with_data_len(test_data_size),
        ).await;
    }

    #[rstest]
    #[case(random_number(6..=8))]
    #[case(random_number(12..=16))]
    #[case(random_number(25..=32))]
    #[case(random_number(53..=64))]
    #[case(random_number(100..=128))]
    #[case(random_number(200..=256))]
    #[tokio::test]
    async fn transfers_stream_data(
        #[case] items_count: usize,
    ) {
        let (channel1, channel2) = channel_mock_pair(
            ChannelMockOptions::random(),
            ChannelMockOptions::random(),
        );

        let (channel1, channel2) = TransportChannel::new_pair(
            1,
            "in-memory-channel-1",
            (Box::new(channel1), Box::new(channel2)),
        );

        let channel1 = create_framed_stream::<TestStreamMessage, _>(channel1);
        let channel2 = create_framed_stream::<TestStreamMessage, _>(channel2);

        test_framed_stream(
            channel1,
            channel2,
            TestOptions::random()
                .with_data_len(items_count),
        ).await;
    }

    #[rstest]
    #[case(128)]
    #[case(256)]
    #[case(512)]
    #[case(1_024)]
    #[case(2_048)]
    #[tokio::test]
    async fn reads_to_end_if_self_shutdown(
        #[case] test_data_size: usize,
    ) {

        let (channel1, channel2) = channel_mock_pair(
            ChannelMockOptions::random(),
            ChannelMockOptions::random(),
        );

        let (channel1, channel2) = TransportChannel::new_pair(
            1,
            "in-memory-channel-1",
            (Box::new(channel1), Box::new(channel2)),
        );

        let (channel1, mut channel2) = test_async_stream(
            channel1,
            channel2,
            TestOptions::random()
                .with_data_len(test_data_size),
        ).await;

        wait_random(25..=50).await;

        let test_data = random_str_rg(8..=32);

        channel2.write(test_data.as_bytes()).await.unwrap();

        let (mut source, mut sink) = tokio::io::split(channel1);

        tokio::join!(
            Box::pin(async move {
                wait_random(0..=5).await;

                let mut buf = vec![];

                let bytes_read = source.read_to_end(&mut buf).await
                    .expect("Cannot read to end.");

                assert_eq!(
                    bytes_read,
                    test_data.len(),
                    "Closed channel must read {} bytes.",
                    test_data.len(),
                );
            }),
            Box::pin(async move {
                wait_random(0..=5).await;

                sink.shutdown().await.unwrap();
            }),
        );

        assert!(!channel2.is_closed(), "Channel2 must not be closed.");
    }

    #[rstest]
    #[case(128)]
    #[case(256)]
    #[case(512)]
    #[case(1_024)]
    #[case(2_048)]
    #[tokio::test]
    async fn reads_if_self_shutdown(
        #[case] test_data_size: usize,
    ) {

        let (channel1, channel2) = channel_mock_pair(
            ChannelMockOptions::random(),
            ChannelMockOptions::random(),
        );

        let (channel1, channel2) = TransportChannel::new_pair(
            1,
            "in-memory-channel-1",
            (Box::new(channel1), Box::new(channel2)),
        );

        let (channel1, mut channel2) = test_async_stream(
            channel1,
            channel2,
            TestOptions::random()
                .with_data_len(test_data_size),
        ).await;

        wait_random(25..=50).await;

        let test_data = random_str_rg(8..=32);

        channel2.write(test_data.as_bytes()).await.unwrap();

        let (mut source, mut sink) = tokio::io::split(channel1);

        tokio::join!(
            Box::pin(async move {
                wait_random(0..=5).await;

                let mut buf = [0; 1024];

                let bytes_read = source.read(&mut buf).await
                    .expect("Cannot read to end.");

                assert_eq!(
                    bytes_read,
                    test_data.len(),
                    "Closed channel must read {} bytes.",
                    test_data.len(),
                );
            }),
            Box::pin(async move {
                wait_random(0..=5).await;

                sink.shutdown().await.unwrap();
            }),
        );

        assert!(!channel2.is_closed(), "Channel2 must not be closed.");
    }

    #[rstest]
    #[case(random_number(6..=8))]
    #[case(random_number(12..=16))]
    #[case(random_number(25..=32))]
    #[case(random_number(53..=64))]
    #[case(random_number(100..=128))]
    #[case(random_number(200..=256))]
    #[tokio::test]
    async fn closes_stream_if_self_is_closed(
        #[case] items_count: u32,
    ) {
        let (channel1, channel2) = channel_mock_pair(
            ChannelMockOptions::random(),
            ChannelMockOptions::random(),
        );

        let (channel1, channel2) = TransportChannel::new_pair(
            1,
            "in-memory-channel-1",
            (Box::new(channel1), Box::new(channel2)),
        );

        let channel1 = create_framed_stream::<TestStreamMessage, _>(channel1);
        let channel2 = create_framed_stream::<TestStreamMessage, _>(channel2);

        let (channel1, mut channel2) = test_framed_stream(
            channel1,
            channel2,
            TestOptions::random()
                .with_data_len(10),
        ).await;

        let (mut sink, mut source) = channel1.split();

        let test_messages = random_vec::<TestStreamMessage>(items_count);
        let messages_to_send = test_messages.clone();
        let mut received_messages = vec![];

        tokio::join!(
            Box::pin(async move {
                while let Some(message) = source.next().await {
                    received_messages.push(message);
                }
            }),
            Box::pin(async move {
                for message in messages_to_send {
                    channel2.send(message).await.unwrap();
                }

                sink.close().await.unwrap();
            }),
        );
    }

    #[rstest]
    #[case(random_number(6..=8))]
    #[case(random_number(12..=16))]
    #[case(random_number(25..=32))]
    #[case(random_number(53..=64))]
    #[case(random_number(100..=128))]
    #[case(random_number(200..=256))]
    #[tokio::test]
    async fn closes_stream_if_remote_counterpart_is_closed(
        #[case] items_count: u32,
    ) {
        let (channel1, channel2) = channel_mock_pair(
            ChannelMockOptions::random(),
            ChannelMockOptions::random(),
        );

        let (channel1, channel2) = TransportChannel::new_pair(
            1,
            "in-memory-channel-1",
            (Box::new(channel1), Box::new(channel2)),
        );

        let channel1 = create_framed_stream::<TestStreamMessage, _>(channel1);
        let channel2 = create_framed_stream::<TestStreamMessage, _>(channel2);

        let (mut channel1, mut channel2) = test_framed_stream(
            channel1,
            channel2,
            TestOptions::random()
                .with_data_len(10),
        ).await;

        let test_messages = random_vec::<TestStreamMessage>(items_count);
        let messages_to_send = test_messages.clone();
        let mut received_messages = vec![];

        tokio::join!(
            Box::pin(async move {
                while let Some(message) = channel1.next().await {
                    received_messages.push(message);
                }

                assert!(channel1.get_ref().is_closed(), "Channel must be closed.");
            }),
            Box::pin(async move {
                for message in messages_to_send {
                    channel2.send(message).await.unwrap();
                }

                channel2.close().await.unwrap();
            }),
        );
    }

    #[rstest]
    #[case(128)]
    #[case(256)]
    #[case(512)]
    #[case(1_024)]
    #[case(2_048)]
    #[tokio::test]
    async fn reads_to_end_if_remote_counterpart_is_closed(
        #[case] test_data_size: usize,
    ) {

        let (channel1, channel2) = channel_mock_pair(
            ChannelMockOptions::random(),
            ChannelMockOptions::random(),
        );

        let (channel1, channel2) = TransportChannel::new_pair(
            1,
            "in-memory-channel-1",
            (Box::new(channel1), Box::new(channel2)),
        );

        let (mut channel1, mut channel2) = test_async_stream(
            channel1,
            channel2,
            TestOptions::random()
                .with_data_len(test_data_size),
        ).await;

        let test_data = random_str_rg(8..=32);

        channel2.write(test_data.as_bytes()).await.unwrap();

        tokio::join!(
            Box::pin(async move {
                wait_random(0..=5).await;

                let mut buf = vec![];

                let bytes_read = channel1.read_to_end(&mut buf).await
                    .expect("Cannot read to end.");

                assert_eq!(
                    bytes_read,
                    test_data.len(),
                    "Closed channel must read {} bytes.",
                    test_data.len(),
                );

                assert!(
                    channel1.is_closed(),
                    "Channel must be closed after remote counterpart is closed.",
                );
            }),
            Box::pin(async move {
                wait_random(0..=5).await;

                channel2.shutdown().await.unwrap();
            }),
        );
    }

    #[rstest]
    #[case(128)]
    #[case(256)]
    #[case(512)]
    #[case(1_024)]
    #[case(2_048)]
    #[tokio::test]
    async fn reads_if_remote_counterpart_is_closed(
        #[case] test_data_size: usize,
    ) {

        let (channel1, channel2) = channel_mock_pair(
            ChannelMockOptions::random(),
            ChannelMockOptions::random(),
        );

        let (channel1, channel2) = TransportChannel::new_pair(
            1,
            "in-memory-channel-1",
            (Box::new(channel1), Box::new(channel2)),
        );

        let (mut channel1, mut channel2) = test_async_stream(
            channel1,
            channel2,
            TestOptions::random()
                .with_data_len(test_data_size),
        ).await;

        let test_data = random_str_rg(8..=32);

        channel2.write(test_data.as_bytes()).await.unwrap();

        channel2.shutdown().await.unwrap();

        assert!(
            channel2.is_closed(),
            "Channel2 must be closed.",
        );

        wait_random(3..=5).await;

        let mut buf = [0; 1024];

        let bytes_read = channel1.read(&mut buf).await
            .expect("Cannot read to end.");

        assert_eq!(
            bytes_read,
            test_data.len(),
            "Closed channel must read {} bytes.",
            test_data.len(),
        );

        let bytes_read = channel1.read(&mut buf).await
            .expect("Cannot read to end.");

        assert_eq!(
            bytes_read,
            0,
            "Closed channel must read 0 bytes.",
        );

        assert!(
            channel1.is_closed(),
            "Channel must be closed after remote counterpart is closed.",
        );
    }

    #[rstest]
    #[case(128)]
    #[case(256)]
    #[case(512)]
    #[case(1_024)]
    #[case(2_048)]
    #[tokio::test]
    async fn fails_to_write_if_remote_counterpart_is_closed(
        #[case] test_data_size: usize,
    ) {

        let (channel1, channel2) = channel_mock_pair(
            ChannelMockOptions::random(),
            ChannelMockOptions::random(),
        );

        let (channel1, channel2) = TransportChannel::new_pair(
            1,
            "in-memory-channel-1",
            (Box::new(channel1), Box::new(channel2)),
        );

        let (mut channel1, mut channel2) = test_async_stream(
            channel1,
            channel2,
            TestOptions::random()
                .with_data_len(test_data_size),
        ).await;

        channel2.shutdown().await.unwrap();

        assert!(
            channel2.write(b"anything").await.is_err(),
            "Must fail to write to closed channel.",
        );

        assert!(
            channel2.is_closed(),
            "Channel2 must be closed.",
        );

        wait_random(3..=5).await;

        let test_data = random_str_rg(24..=32);
        let bytes_written = channel1.write(test_data.as_bytes()).await
            .expect("Cannot write to channel.");

        assert_eq!(
            bytes_written,
            0,
            "Must write 0 bytes if remote channel is closed.",
        );
    }

    #[rstest]
    #[case(128)]
    #[case(256)]
    #[case(512)]
    #[case(1_024)]
    #[case(2_048)]
    #[tokio::test]
    async fn fails_to_write_if_self_is_closed(
        #[case] test_data_size: usize,
    ) {

        let (channel1, channel2) = channel_mock_pair(
            ChannelMockOptions::random(),
            ChannelMockOptions::random(),
        );

        let (channel1, channel2) = TransportChannel::new_pair(
            1,
            "in-memory-channel-1",
            (Box::new(channel1), Box::new(channel2)),
        );

        let (channel1, mut channel2) = test_async_stream(
            channel1,
            channel2,
            TestOptions::random()
                .with_data_len(test_data_size),
        ).await;

        let (mut source, mut sink) = tokio::io::split(channel1);

        let test_data = random_str_rg(24..=32);

        channel2.write(test_data.as_bytes()).await
            .expect("Cannot write data.");

        sink.shutdown().await.unwrap();

        assert!(
            sink.write(b"something").await.is_err(),
            "Must fail to write to closed channel.",
        );

        let mut buf = vec![];
        let bytes_received = source.read_to_end(&mut buf).await
            .expect("Cannot read data.");

        assert_eq!(
            bytes_received,
            test_data.len(),
            "Must be able to read to end if channel is closed.",
        );

        let channel1 = source.unsplit(sink);

        assert!(
            channel1.is_closed(),
            "Channel must be closed.",
        );
    }
}