tubes 0.6.3

Host/Client protocol based on pipenet
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
use std::{collections::HashSet, fmt::Debug, string::FromUtf8Error, thread::sleep, time::Duration};
use tubes::ClientId;
use tubes::prelude::*;

#[derive(Clone, Debug, PartialEq)]
pub struct Msg(pub String);

impl From<String> for Msg {
    fn from(value: String) -> Self {
        Self(value)
    }
}

impl TryFrom<&[u8]> for Msg {
    type Error = FromUtf8Error;

    fn try_from(value: &[u8]) -> std::result::Result<Self, Self::Error> {
        Ok(Msg(String::from_utf8(value.to_vec())?))
    }
}

impl TryFrom<Msg> for Vec<u8> {
    type Error = ();

    fn try_from(value: Msg) -> std::result::Result<Self, Self::Error> {
        Ok(value.0.into())
    }
}

pub struct TestSession {
    server: Session,
    nodes: Vec<Session>,
    promoting: Option<ClientId>,
}

impl TestSession {
    pub fn new_pair(port: u16) -> Self {
        let mut res = Self {
            server: Self::new_server(port),
            nodes: vec![Self::new_client(port)],
            promoting: None,
        };
        res.connect();
        res
    }

    pub fn new_triple(port: u16) -> Self {
        let mut res = Self {
            server: Self::new_server(port),
            nodes: vec![Self::new_client(port), Self::new_client(port)],
            promoting: None,
        };
        res.connect();
        res
    }

    pub fn new_quad(port: u16) -> Self {
        let mut res = Self {
            server: Self::new_server(port),
            nodes: vec![
                Self::new_client(port),
                Self::new_client(port),
                Self::new_client(port),
            ],
            promoting: None,
        };
        res.connect();
        res
    }

    #[cfg(all(feature = "encryption", feature = "compression"))]
    pub fn new_pair_pack(port: u16) -> Self {
        let mut res = Self {
            server: Self::new_server_pack(port),
            nodes: vec![Self::new_client_pack(port)],
            promoting: None,
        };
        res.connect();
        res
    }

    #[cfg(all(feature = "encryption", feature = "compression"))]
    pub fn new_triple_pack(port: u16) -> Self {
        let mut res = Self {
            server: Self::new_server_pack(port),
            nodes: vec![Self::new_client_pack(port), Self::new_client_pack(port)],
            promoting: None,
        };
        res.connect();
        res
    }

    #[cfg(all(feature = "encryption", feature = "compression"))]
    pub fn new_quad_pack(port: u16) -> Self {
        let mut res = Self {
            server: Self::new_server_pack(port),
            nodes: vec![
                Self::new_client_pack(port),
                Self::new_client_pack(port),
                Self::new_client_pack(port),
            ],
            promoting: None,
        };
        res.connect();
        res
    }

    pub fn stop(&mut self) {
        for c in self.nodes.iter_mut() {
            c.stop();
        }
        self.server.stop();
    }

    pub fn server_uuid(&self) -> ClientId {
        self.server.uuid()
    }

    pub fn clients(&self) -> HashSet<ClientId> {
        self.server.clients()
    }

    pub fn client_leave(&mut self, uuid: ClientId) {
        // Dropping the client will also close it.
        self.nodes.retain(|c| c.uuid() != uuid);
    }

    // Clean out any receiving queue from all the nodes, allowing for a clear
    // test trigger of a specific message without pending scenarios.
    pub fn exhaust(&mut self) {
        // TODO: this is time sensitive
        sleep(Duration::from_millis(100));
        // During promotion always exhaust the promoting client first
        if let Some(p) = self.promoting {
            for c in self.nodes.iter_mut() {
                if p == c.uuid() {
                    while c.read().unwrap().is_some() {}
                    self.promoting = None;
                }
            }
        }
        while self.server.read().unwrap().is_some() {}
        for c in self.nodes.iter_mut() {
            while c.read().unwrap().is_some() {}
        }
    }

    pub fn server_broadcast(&mut self, m: Msg) {
        self.server.broadcast(m.try_into().unwrap()).unwrap();
    }

    pub fn server_send_to(&mut self, uuid: ClientId, m: Msg) {
        self.server.send_to(uuid, m.try_into().unwrap()).unwrap();
    }

    pub fn first_client_send_to_server(&mut self, m: Msg) -> Option<ClientId> {
        let c = self.nodes.iter_mut().next()?;
        c.send_to(self.server.uuid(), m.try_into().unwrap())
            .unwrap();
        Some(c.uuid())
    }

    pub fn first_client_broadcast(&mut self, m: Msg) -> Option<ClientId> {
        let c = self.nodes.iter_mut().next()?;
        c.broadcast(m.try_into().unwrap()).unwrap();
        Some(c.uuid())
    }

    pub fn promote_to_host(&mut self, client: ClientId, port: u16) {
        println!(
            "TEST /// Before migration, server={}, clients={:?}",
            self.server.uuid(),
            self.server.clients()
        );
        self.promoting = Some(client);
        self.server.promote_to_host(client, Some(port));
        // By using the session first, the reconnection is being triggered.
        // The reconnection does not trigger until at least one interaction from
        // the user happens.
        self.exhaust();
        self.assert_is_server(client);

        // Swap the promoted client with the server position or the testing
        // will not work afterwards.
        let promoted_client = self.nodes.iter_mut().find(|c| c.uuid() == client).unwrap();
        std::mem::swap(&mut self.server, promoted_client);

        // TODO: time sensitive
        std::thread::sleep(Duration::from_millis(100));

        println!(
            "TEST /// After migration, server={}, clients={:?}",
            self.server.uuid(),
            self.server.clients()
        );
    }

    pub fn assert_server_received_broacast(&mut self, from: ClientId, m: Msg) {
        let m = MessageData::Broadcast {
            from,
            data: m.try_into().unwrap(),
        };
        retry(move || Self::assert_received_message(&mut self.server, &m)).unwrap();
    }

    pub fn assert_all_clients_received_broacast(&mut self, from: ClientId, m: Msg) {
        let m = MessageData::Broadcast {
            from,
            data: m.try_into().unwrap(),
        };
        for c in self.nodes.iter_mut() {
            retry(|| Self::assert_received_message(c, &m)).unwrap();
        }
    }

    pub fn assert_only_client_received(&mut self, from: ClientId, uuid: ClientId, m: Msg) {
        let m = MessageData::Send {
            from,
            to: uuid,
            data: m.try_into().unwrap(),
        };
        for c in self.nodes.iter_mut() {
            if c.uuid() == uuid {
                retry(|| Self::assert_received_message(c, &m)).unwrap();
            }
        }
        // Iterate again: checking when a message does not exist has to be done
        // in a single shot, so make sure to do it only after the positive case
        // above has been already checked and wait a little for the other
        // clients to catch up. (TODO: This is time sensitive)
        sleep(Duration::from_millis(100));
        for c in self.nodes.iter_mut() {
            if c.uuid() != uuid {
                assert!(c.read().unwrap().is_none());
            }
        }
    }

    pub fn assert_only_server_received(&mut self, from: ClientId, m: Msg) {
        let m = MessageData::Send {
            from,
            to: self.server.uuid(),
            data: m.try_into().unwrap(),
        };
        retry(|| Self::assert_received_message(&mut self.server, &m)).unwrap();
        // Iterate again: checking when a message does not exist has to be done
        // in a single shot, so make sure to do it only after the positive case
        // above has been already checked and wait a little for the other
        // clients to catch up. (TODO: This is time sensitive)
        sleep(Duration::from_millis(100));
        for c in self.nodes.iter_mut() {
            assert!(c.read().unwrap().is_none());
        }
    }

    pub fn assert_client_left(&mut self, uuid: ClientId) {
        let m = MessageData::ClientLeft(uuid);
        retry(|| Self::assert_received_message(&mut self.server, &m)).unwrap();
        for c in self.nodes.iter_mut() {
            retry(|| Self::assert_received_message(c, &m)).unwrap();
        }
        retry(|| {
            if self.server.clients().contains(&uuid) {
                return Err(format!("Client has not left {}", uuid));
            }
            Ok(())
        })
        .unwrap();
    }

    pub fn assert_is_server(&self, uuid: ClientId) {
        retry(|| {
            let client_is_server = self
                .nodes
                .iter()
                .find(|c| c.uuid() == uuid)
                .map(|c| c.is_server())
                .unwrap_or(false);
            let server_is_server = uuid == self.server.uuid();
            if !server_is_server && !client_is_server {
                return Err(format!("{} is not server", uuid));
            }
            Ok(())
        })
        .unwrap();
    }

    fn connect(&mut self) {
        self.server.start().unwrap();
        assert!(self.server.is_connected());
        for c in self.nodes.iter_mut() {
            c.start().unwrap();
            assert!(c.is_connected());
        }

        retry(|| {
            let len1 = self.server.clients().len();
            let len2 = self.nodes.len();
            if len1 != len2 {
                return Err(format!("Client lengths not matching: {} != {}", len1, len2));
            }
            for uuid in self.nodes.iter().map(|n| n.uuid()) {
                if !self.server.clients().contains(&uuid) {
                    return Err(format!("Client not in server list: {}", uuid));
                }
            }
            Ok(())
        })
        .unwrap();

        let server_uuid = self.server_uuid();
        for c in self.nodes.iter_mut() {
            retry(|| {
                let Some(suuid) = c.server_uuid() else {
                    return Err(format!(
                        "Client {} did not receive the server uuid",
                        c.uuid()
                    ));
                };
                if server_uuid != suuid {
                    return Err(format!(
                        "Client {} did receive the wrong server uuid {} != {}",
                        c.uuid(),
                        server_uuid,
                        suuid
                    ));
                }
                Ok(())
            })
            .unwrap();
        }

        for uuid in self.clients().iter() {
            let m = MessageData::ClientJoined(*uuid);
            for c in self.nodes.iter_mut() {
                if c.uuid() != *uuid {
                    retry(|| Self::assert_received_message(c, &m)).unwrap();
                }
            }
        }
    }

    fn new_server(port: u16) -> Session {
        let s = Session::new_server(format!("127.0.0.1:{}", port).as_str().into());
        assert!(s.is_server());
        assert!(!s.is_connected());
        s
    }

    fn new_client(port: u16) -> Session {
        let s = Session::new_client(format!("127.0.0.1:{}", port).as_str().into());
        assert!(!s.is_server());
        assert!(!s.is_connected());
        s
    }

    #[cfg(all(feature = "encryption", feature = "compression"))]
    fn new_server_pack(port: u16) -> Session {
        let config = Config {
            address: "127.0.0.1".parse().ok(),
            port,
            versions: Default::default(),
            accept_timeout: Default::default(),
            compress: true,
            key: Some(Self::key()),
        };
        Session::new_server(config)
    }

    #[cfg(all(feature = "encryption", feature = "compression"))]
    fn new_client_pack(port: u16) -> Session {
        let config = Config {
            address: "127.0.0.1".parse().ok(),
            port,
            versions: Default::default(),
            accept_timeout: Default::default(),
            compress: true,
            key: Some(Self::key()),
        };
        Session::new_client(config)
    }

    #[cfg(feature = "encryption")]
    fn key() -> Vec<u8> {
        vec![0; 32]
    }

    fn assert_received_message(s: &mut Session, m: &MessageData) -> Result<(), String> {
        let m = Self::debug_message(m);
        let msg = s.read().unwrap().ok_or(format!(
            "No message available on {}, expected {}",
            s.uuid(),
            m
        ))?;
        let msg = Self::debug_message(&msg);
        if msg != m {
            return Err(format!(
                "Wrong message, expected: \n{}\n returned: \n{}",
                m, msg
            ));
        }
        Ok(())
    }

    fn debug_message(m: &MessageData) -> String {
        match m {
            MessageData::Broadcast { from, data: m } => format!("Broadcast({from}, {m:?})"),
            MessageData::Send {
                from,
                to: uuid,
                data: m,
            } => format!("Send({from}, {uuid}, {m:?})"),
            MessageData::ClientJoined(uuid) => format!("ClientJoined({uuid})"),
            MessageData::ClientLeft(uuid) => format!("ClientLeft({uuid})"),
        }
    }
}

impl Drop for TestSession {
    fn drop(&mut self) {
        self.stop();
    }
}

fn retry<E, F: FnMut() -> Result<(), E>>(mut f: F) -> Result<(), E> {
    let mut ct = 0;
    loop {
        if let Err(e) = f() {
            if ct >= 20 {
                return Err(e);
            }
        } else {
            return Ok(());
        }
        sleep(Duration::from_millis(100));
        ct += 1;
    }
}