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

use futures::{Future, ready};
use tokio::{io::{duplex, AsyncRead, AsyncWrite, ReadBuf, DuplexStream}, sync::watch};
use cs_utils::{random_number, random_str, futures::wait_random, traits::Random};

use crate::Channel;

pub struct ChannelMock<TAsyncDuplex: AsyncRead + AsyncWrite + Send + Unpin + 'static = DuplexStream> {
    id: u16,
    label: String,
    channel: Pin<Box<TAsyncDuplex>>,
    options: ChannelMockOptions,
    read_delay_future: Option<Pin<Box<dyn Future<Output = ()> + Send>>>,
    write_delay_future: Option<Pin<Box<dyn Future<Output = ()> + Send>>>,
    is_closed: bool,
}

impl<TAsyncDuplex: AsyncRead + AsyncWrite + Send + Unpin + 'static> ChannelMock<TAsyncDuplex> {
    pub fn new(
        channel: Box<TAsyncDuplex>,
        options: ChannelMockOptions,
    ) -> Box<dyn Channel> {
        return Box::new(
            ChannelMock {
                id: options.id,
                label: options.label.clone(),
                channel: Pin::new(channel),
                options,
                read_delay_future: None,
                write_delay_future: None,
                is_closed: false,
            },
        );
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct ChannelMockOptions {
    id: u16,
    label: String,
    latency_range: RangeInclusive<u64>,
}

impl ChannelMockOptions {
    pub fn with_id(
        self,
        id: u16,
    ) -> ChannelMockOptions {
        return ChannelMockOptions {
            id,
            ..self
        };
    }

    pub fn with_label(
        self,
        label: impl AsRef<str> + ToString,
    ) -> ChannelMockOptions {
        return ChannelMockOptions {
            label: label.to_string(),
            ..self
        };
    }

    pub fn with_latency(
        self,
        latency_range: RangeInclusive<u64>,
    ) -> ChannelMockOptions {
        return ChannelMockOptions {
            latency_range,
            ..self
        };
    }
}

impl Random for ChannelMockOptions {
    fn random() -> Self {
        let min = random_number(0..5);
        let max = random_number(5..=50);

        return ChannelMockOptions::default()
            .with_latency(min..=max);
    }
}

impl Default for ChannelMockOptions {
    fn default() -> ChannelMockOptions {
        return ChannelMockOptions {
            id: random_number(0..=u16::MAX),
            label: format!("channel-mock-{}", random_str(8)),
            latency_range: (0..=0),
        };
    }
}

pub fn channel_mock_pair(
    options1: ChannelMockOptions,
    options2: ChannelMockOptions,
) -> (Box<dyn Channel>, Box<dyn Channel>) {
    let (channel1, channel2) = duplex(1024);

    return (
        ChannelMock::new(Box::new(channel1), options1),
        ChannelMock::new(Box::new(channel2), options2),
    );
}

impl<TAsyncDuplex: AsyncRead + AsyncWrite + Send + Unpin + 'static> Channel for ChannelMock<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> {
        unimplemented!();
    }
}

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

impl<TAsyncDuplex: AsyncRead + AsyncWrite + Send + Unpin + 'static> AsyncRead for ChannelMock<TAsyncDuplex> {
    fn poll_read(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &mut ReadBuf<'_>,
    ) -> Poll<io::Result<()>> {
        // if delay future present, wait until it completes
        if let Some(read_delay_future) = self.read_delay_future.as_mut() {
            ready!(read_delay_future.as_mut().poll(cx));

            self.read_delay_future.take();
        }

        // otherwise run the read future to completion
        let result = ready!(self.channel.as_mut().poll_read(cx, buf));

        self.read_delay_future = Some(Box::pin(wait_random(self.options.latency_range.clone())));

        return Poll::Ready(result);
    }
}

impl<TAsyncDuplex: AsyncRead + AsyncWrite + Send + Unpin + 'static> AsyncWrite for ChannelMock<TAsyncDuplex> {
    fn poll_write(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
        buf: &[u8],
    ) -> Poll<io::Result<usize>> {
        // if delay future present, wait until it completes
        if let Some(write_delay_future) = self.write_delay_future.as_mut() {
            ready!(write_delay_future.as_mut().poll(cx));

            self.write_delay_future.take();
        }

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

        self.write_delay_future = Some(Box::pin(wait_random(self.options.latency_range.clone())));

        return Poll::Ready(result);
    }

    fn poll_flush(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<io::Result<()>> {
        // if delay future present, wait until it completes
        if let Some(read_delay_future) = self.read_delay_future.as_mut() {
            ready!(read_delay_future.as_mut().poll(cx));

            self.read_delay_future.take();
        }

        return self.channel.as_mut()
            .poll_flush(cx);
    }

    fn poll_shutdown(
        mut self: Pin<&mut Self>,
        cx: &mut Context<'_>,
    ) -> Poll<io::Result<()>> {
        // if delay future present, wait until it completes
        if let Some(read_delay_future) = self.read_delay_future.as_mut() {
            ready!(read_delay_future.as_mut().poll(cx));

            self.read_delay_future.take();
        }

        return self.channel.as_mut()
            .poll_shutdown(cx);
    }
}

#[cfg(test)]
mod tests {
    use rstest::rstest;
    
    use cs_utils::{traits::Random, random_number};
    
    use crate::test::{TestStreamMessage, test_async_stream, test_framed_stream, TestOptions};
    use crate::utils::create_framed_stream;

    use super::channel_mock_pair;

    #[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)]
    #[case(65_536)]
    #[tokio::test]
    async fn transfers_binary_data(
        #[case] test_data_len: usize,
    ) {
        let (channel1, channel2) = channel_mock_pair(Random::random(), Random::random());

        test_async_stream(
            channel1,
            channel2,
            TestOptions::random()
                .with_data_len(test_data_len),
        ).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(Random::random(), Random::random());

        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;
    }
}