-
Notifications
You must be signed in to change notification settings - Fork 227
/
reliability.rs
511 lines (425 loc) · 15 KB
/
reliability.rs
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
use matches::assert_matches;
use std::time::{Duration, Instant};
use tokio::{task, time};
mod broker;
use broker::*;
use rumqttc::*;
async fn start_requests(count: u8, qos: QoS, delay: u64, client: AsyncClient) {
for i in 1..=count {
let topic = "hello/world".to_owned();
let payload = vec![i, 1, 2, 3];
let _ = client.publish(topic, qos, false, payload).await;
time::sleep(Duration::from_secs(delay)).await;
}
}
async fn run(eventloop: &mut EventLoop, reconnect: bool) -> Result<(), ConnectionError> {
'reconnect: loop {
loop {
let o = eventloop.poll().await;
println!("Polled = {:?}", o);
match o {
Ok(_) => continue,
Err(_) if reconnect => continue 'reconnect,
Err(e) => return Err(e),
}
}
}
}
async fn _tick(
eventloop: &mut EventLoop,
reconnect: bool,
count: usize,
) -> Result<(), ConnectionError> {
'reconnect: loop {
for i in 0..count {
let o = eventloop.poll().await;
println!("{}. Polled = {:?}", i, o);
match o {
Ok(_) => continue,
Err(_) if reconnect => continue 'reconnect,
Err(e) => return Err(e),
}
}
break;
}
Ok(())
}
#[tokio::test]
async fn connection_should_timeout_on_time() {
task::spawn(async move {
let _broker = Broker::new(1880, 3).await;
time::sleep(Duration::from_secs(10)).await;
});
time::sleep(Duration::from_secs(1)).await;
let options = MqttOptions::new("dummy", "127.0.0.1", 1880);
let mut eventloop = EventLoop::new(options, 5);
let start = Instant::now();
let o = eventloop.poll().await;
let elapsed = start.elapsed();
assert_matches!(o, Err(ConnectionError::Timeout(_)));
assert_eq!(elapsed.as_secs(), 5);
}
//
// All keep alive tests here
//
#[tokio::test]
async fn idle_connection_triggers_pings_on_time() {
let keep_alive = 5;
let mut options = MqttOptions::new("dummy", "127.0.0.1", 1885);
options.set_keep_alive(Duration::from_secs(keep_alive));
// Create client eventloop and poll
task::spawn(async move {
let mut eventloop = EventLoop::new(options, 5);
run(&mut eventloop, false).await.unwrap();
});
let mut broker = Broker::new(1885, 0).await;
let mut count = 0;
let mut start = Instant::now();
for _ in 0..3 {
let packet = broker.read_packet().await;
match packet {
Packet::PingReq => {
count += 1;
let elapsed = start.elapsed();
assert_eq!(elapsed.as_secs(), keep_alive as u64);
broker.pingresp().await;
start = Instant::now();
}
_ => {
panic!("Expecting ping, Received: {:?}", packet);
}
}
}
assert_eq!(count, 3);
}
#[tokio::test]
async fn some_outgoing_and_no_incoming_should_trigger_pings_on_time() {
let keep_alive = 5;
let mut options = MqttOptions::new("dummy", "127.0.0.1", 1886);
options.set_keep_alive(Duration::from_secs(keep_alive));
// start sending qos0 publishes. this makes sure that there is
// outgoing activity but no incoming activity
let (client, mut eventloop) = AsyncClient::new(options, 5);
// Start sending publishes
task::spawn(async move {
start_requests(10, QoS::AtMostOnce, 1, client).await;
});
// start the eventloop
task::spawn(async move {
run(&mut eventloop, false).await.unwrap();
});
let mut broker = Broker::new(1886, 0).await;
let mut count = 0;
let mut start = Instant::now();
loop {
let event = broker.tick().await;
if event == Event::Incoming(Incoming::PingReq) {
// wait for 3 pings
count += 1;
if count == 3 {
break;
}
assert_eq!(start.elapsed().as_secs(), keep_alive as u64);
broker.pingresp().await;
start = Instant::now();
}
}
assert_eq!(count, 3);
}
#[tokio::test]
async fn some_incoming_and_no_outgoing_should_trigger_pings_on_time() {
let keep_alive = 5;
let mut options = MqttOptions::new("dummy", "127.0.0.1", 2000);
options.set_keep_alive(Duration::from_secs(keep_alive));
task::spawn(async move {
let mut eventloop = EventLoop::new(options, 5);
run(&mut eventloop, false).await.unwrap();
});
let mut broker = Broker::new(2000, 0).await;
let mut count = 0;
// Start sending qos 0 publishes to the client. This triggers
// some incoming and no outgoing packets in the client
broker.spawn_publishes(10, QoS::AtMostOnce, 1).await;
let mut start = Instant::now();
loop {
let event = broker.tick().await;
if event == Event::Incoming(Incoming::PingReq) {
// wait for 3 pings
count += 1;
if count == 3 {
break;
}
assert_eq!(start.elapsed().as_secs(), keep_alive as u64);
broker.pingresp().await;
start = Instant::now();
}
}
assert_eq!(count, 3);
}
#[tokio::test]
async fn detects_halfopen_connections_in_the_second_ping_request() {
let mut options = MqttOptions::new("dummy", "127.0.0.1", 2001);
options.set_keep_alive(Duration::from_secs(5));
// A broker which consumes packets but doesn't reply
task::spawn(async move {
let mut broker = Broker::new(2001, 0).await;
broker.blackhole().await;
});
time::sleep(Duration::from_secs(1)).await;
let start = Instant::now();
let mut eventloop = EventLoop::new(options, 5);
loop {
if let Err(e) = eventloop.poll().await {
match e {
ConnectionError::MqttState(StateError::AwaitPingResp) => break,
v => panic!("Expecting pingresp error. Found = {:?}", v),
}
}
}
assert_eq!(start.elapsed().as_secs(), 10);
}
//
// All flow control tests here
//
#[tokio::test]
async fn requests_are_blocked_after_max_inflight_queue_size() {
let mut options = MqttOptions::new("dummy", "127.0.0.1", 1887);
options.set_inflight(5);
let inflight = options.inflight();
// start sending qos0 publishes. this makes sure that there is
// outgoing activity but no incoming activity
let (client, mut eventloop) = AsyncClient::new(options, 5);
task::spawn(async move {
start_requests(10, QoS::AtLeastOnce, 1, client).await;
});
// start the eventloop
task::spawn(async move {
run(&mut eventloop, false).await.unwrap();
});
let mut broker = Broker::new(1887, 0).await;
for i in 1..=10 {
let packet = broker.read_publish().await;
if i > inflight {
assert!(packet.is_none());
}
}
}
#[tokio::test]
async fn requests_are_recovered_after_inflight_queue_size_falls_below_max() {
let mut options = MqttOptions::new("dummy", "127.0.0.1", 1888);
options.set_inflight(3);
let (client, mut eventloop) = AsyncClient::new(options, 5);
task::spawn(async move {
start_requests(5, QoS::AtLeastOnce, 1, client).await;
time::sleep(Duration::from_secs(60)).await;
});
// start the eventloop
task::spawn(async move {
run(&mut eventloop, true).await.unwrap();
});
let mut broker = Broker::new(1888, 0).await;
// packet 1, 2, and 3
assert!(broker.read_publish().await.is_some());
assert!(broker.read_publish().await.is_some());
assert!(broker.read_publish().await.is_some());
// no packet 4. client inflight full as there aren't acks yet
assert!(broker.read_publish().await.is_none());
// ack packet 1 and client would produce packet 4
broker.ack(1).await;
assert!(broker.read_publish().await.is_some());
assert!(broker.read_publish().await.is_none());
// ack packet 2 and client would produce packet 5
broker.ack(2).await;
assert!(broker.read_publish().await.is_some());
assert!(broker.read_publish().await.is_none());
}
#[ignore]
#[tokio::test]
async fn packet_id_collisions_are_detected_and_flow_control_is_applied() {
let mut options = MqttOptions::new("dummy", "127.0.0.1", 1891);
options.set_inflight(10);
let (client, mut eventloop) = AsyncClient::new(options, 5);
task::spawn(async move {
start_requests(15, QoS::AtLeastOnce, 0, client).await;
time::sleep(Duration::from_secs(60)).await;
});
task::spawn(async move {
let mut broker = Broker::new(1891, 0).await;
// read all incoming packets first
for i in 1..=4 {
let packet = broker.read_publish().await;
assert_eq!(packet.unwrap().payload[0], i);
}
// out of order ack
broker.ack(3).await;
broker.ack(4).await;
time::sleep(Duration::from_secs(5)).await;
broker.ack(1).await;
broker.ack(2).await;
// read and ack remaining packets in order
for i in 5..=15 {
let packet = broker.read_publish().await;
let packet = packet.unwrap();
assert_eq!(packet.payload[0], i);
broker.ack(packet.pkid).await;
}
time::sleep(Duration::from_secs(10)).await;
});
time::sleep(Duration::from_secs(1)).await;
// sends 4 requests. 5th request will trigger collision
// Poll until there is collision.
loop {
match eventloop.poll().await.unwrap() {
Event::Outgoing(Outgoing::AwaitAck(1)) => break,
v => {
println!("Poll = {:?}", v);
continue;
}
}
}
loop {
let start = Instant::now();
let event = eventloop.poll().await.unwrap();
println!("Poll = {:?}", event);
match event {
Event::Outgoing(Outgoing::Publish(ack)) => {
if ack == 1 {
let elapsed = start.elapsed().as_millis() as i64;
let deviation_millis: i64 = (5000 - elapsed).abs();
assert!(deviation_millis < 100);
break;
}
}
_ => continue,
}
}
}
// #[tokio::test]
// async fn packet_id_collisions_are_timedout_on_second_ping() {
// let mut options = MqttOptions::new("dummy", "127.0.0.1", 1892);
// options.set_inflight(4).set_keep_alive(5);
//
// let mut eventloop = EventLoop::new(options, 5);
// let requests_tx = eventloop.handle();
//
// task::spawn(async move {
// start_requests(10, QoS::AtLeastOnce, 0, requests_tx).await;
// time::sleep(Duration::from_secs(60)).await;
// });
//
// task::spawn(async move {
// let mut broker = Broker::new(1892, 0).await;
// // read all incoming packets first
// for i in 1..=4 {
// let packet = broker.read_publish().await;
// assert_eq!(packet.unwrap().payload[0], i);
// }
//
// // out of order ack
// broker.ack(3).await;
// broker.ack(4).await;
// time::sleep(Duration::from_secs(15)).await;
// });
//
// time::sleep(Duration::from_secs(1)).await;
//
// // Collision error but no network disconneciton
// match run(&mut eventloop, false).await.unwrap() {
// Event::Outgoing(Outgoing::AwaitAck(1)) => (),
// o => panic!("Expecting collision error. Found = {:?}", o),
// }
//
// match run(&mut eventloop, false).await {
// Err(ConnectionError::MqttState(StateError::CollisionTimeout)) => (),
// o => panic!("Expecting collision error. Found = {:?}", o),
// }
// }
//
// All reconnection tests here
//
#[tokio::test]
async fn next_poll_after_connect_failure_reconnects() {
let options = MqttOptions::new("dummy", "127.0.0.1", 3000);
task::spawn(async move {
let _broker = Broker::new(3000, 1).await;
let _broker = Broker::new(3000, 0).await;
time::sleep(Duration::from_secs(15)).await;
});
time::sleep(Duration::from_secs(1)).await;
let mut eventloop = EventLoop::new(options, 5);
match eventloop.poll().await {
Err(ConnectionError::MqttState(StateError::Connect(
ConnectReturnCode::BadUserNamePassword,
))) => (),
v => panic!("Expected bad username password error. Found = {:?}", v),
}
match eventloop.poll().await {
Ok(Event::Incoming(Packet::ConnAck(ConnAck {
code: ConnectReturnCode::Success,
session_present: false,
}))) => (),
v => panic!("Expected ConnAck Success. Found = {:?}", v),
}
}
#[tokio::test]
async fn reconnection_resumes_from_the_previous_state() {
let mut options = MqttOptions::new("dummy", "127.0.0.1", 3001);
options.set_keep_alive(Duration::from_secs(5));
// start sending qos0 publishes. Makes sure that there is out activity but no in activity
let (client, mut eventloop) = AsyncClient::new(options, 5);
task::spawn(async move {
start_requests(10, QoS::AtLeastOnce, 1, client).await;
time::sleep(Duration::from_secs(10)).await;
});
// start the eventloop
task::spawn(async move {
run(&mut eventloop, true).await.unwrap();
});
// broker connection 1
let mut broker = Broker::new(3001, 0).await;
for i in 1..=2 {
let packet = broker.read_publish().await.unwrap();
assert_eq!(i, packet.payload[0]);
broker.ack(packet.pkid).await;
}
// NOTE: An interesting thing to notice here is that reassigning a new broker
// is behaving like a half-open connection instead of cleanly closing the socket
// and returning error immediately
// Manually dropping (`drop(broker.framed)`) the connection or adding
// a block around broker with {} is closing the connection as expected
// broker connection 2
let mut broker = Broker::new(3001, 0).await;
for i in 3..=4 {
let packet = broker.read_publish().await.unwrap();
assert_eq!(i, packet.payload[0]);
broker.ack(packet.pkid).await;
}
}
#[tokio::test]
async fn reconnection_resends_unacked_packets_from_the_previous_connection_first() {
let mut options = MqttOptions::new("dummy", "127.0.0.1", 3002);
options.set_keep_alive(Duration::from_secs(5));
// start sending qos0 publishes. this makes sure that there is
// outgoing activity but no incoming activity
let (client, mut eventloop) = AsyncClient::new(options, 5);
task::spawn(async move {
start_requests(10, QoS::AtLeastOnce, 1, client).await;
time::sleep(Duration::from_secs(10)).await;
});
// start the client eventloop
task::spawn(async move {
run(&mut eventloop, true).await.unwrap();
});
// broker connection 1. receive but don't ack
let mut broker = Broker::new(3002, 0).await;
for i in 1..=2 {
let packet = broker.read_publish().await.unwrap();
assert_eq!(i, packet.payload[0]);
}
// broker connection 2 receives from scratch
let mut broker = Broker::new(3002, 0).await;
for i in 1..=6 {
let packet = broker.read_publish().await.unwrap();
assert_eq!(i, packet.payload[0]);
}
}