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
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
|
//! Paths: one address space over any number of transports, below the identity layer
//! (`transport::identity`). An address is `<scheme>:<target>`: the transport by its
//! scheme (`mycelium`, `libp2p`, …), and on it a transport identity (Mycelium's public
//! key, libp2p's peer ID) or a location (`Transport::locate`), e.g. a multiaddr.
//! Addresses as paths keeps them are `<scheme>:<transport identity>` (`canonical`).
//!
//! Every transport carries the same messages (`wire`); paths routes each send to the
//! transport of its address, hands every transport's messages to one handler under the
//! sender's address, and puts together what the transports say about themselves
//! (addresses, seeds they found, figures). The transports are in order of preference,
//! as configured (`--transport-order`).
//!
//! A message to a node with several addresses goes to the first of them that takes it
//! (`send_first`), in the order `rank` gives. A send that fails is tried at once at the
//! next address, the message encoded for its transport: when one transport fails, the
//! next carries on within the same send.
//!
//! Paths measures the addresses of such nodes itself (and every path the node's
//! keepalive PINGs go over, below): every `PROBE_EVERY`, or every keepalive interval if
//! that is longer, each address it had a choice of
//! within `ACTIVE_FOR` gets a PING with a random nonce, which the
//! other side's paths answers at once with a PONG, over the same path. Answers give each
//! path's round-trip time (smoothed); `UNANSWERED_DOWN` PINGs in a row unanswered, or a
//! send that failed within `DOWN_FOR`, make a path down. `rank` puts paths that are up
//! first, the one in use first among them, and the rest by round-trip time; it changes
//! the one in use when another is faster by `SWITCH_GAIN` (a quarter) and at least
//! `SWITCH_MIN` (both measured), so it doesn't flap. Until both are measured, the
//! configured order decides.
//!
//! PINGs and PONGs then go up as other messages do: they tell the node the peer is
//! alive. The node's keepalive is a PING too (`swarm::peer::keepalive`), which paths
//! sends like any message, and notes as the probe of the path it went over.
//!
//! Every message on every transport passes here, so this is where messages are logged
//! (debug): `Sent message` once a transport took one, `Received message` as one
//! arrives, each with its address and what it says. Failed sends are logged by those who
//! sent them, with what they do about it.
//!
//! The debug firewall (`transport::firewall`) works here, below everything else, through
//! a `Gate`: messages from an address it blocks are dropped as they arrive, and sends to
//! one are dropped silently, as by a lossy network.
use std::collections::HashMap;
use std::sync::{Arc, Mutex, Weak};
use std::time::Duration;
use anyhow::{Context, Result, anyhow};
use tokio::time::Instant;
use tracing::{debug, info};
use crate::clock::{Clock, UnixMillis};
use crate::locks::MutexExt;
use crate::transport::stats::{PathCounts, PathInfo, PathsStats, TransportStats};
use crate::transport::traffic::Traffic;
use crate::transport::{Connection, EncodedMessage, ParsedMessage, Transport};
/// Whether to drop what comes from or goes to an address (the debug firewall,
/// `transport::firewall`; the identity layer knows which node is where).
pub(crate) trait Gate: Send + Sync {
fn blocks_inbound(&self, address: &str) -> bool;
fn blocks_outbound(&self, address: &str) -> bool;
}
/// Called with the sender's address, the message and its `payload_len`.
pub(crate) type PathHandler = dyn Fn(String, ParsedMessage, usize) -> std::pin::Pin<Box<dyn Future<Output = Result<()>> + Send>>
+ Send
+ Sync
+ 'static;
/// One of the node's transports.
struct Link {
scheme: &'static str,
inner: Arc<dyn Transport>,
}
impl Link {
fn address(&self, target: &str) -> String {
format!("{}:{target}", self.scheme)
}
fn own_address(&self) -> String {
self.address(self.inner.local_id())
}
}
/// The scheme of `address`.
pub(crate) fn scheme_of(address: &str) -> &str {
address.split_once(':').map_or("", |(scheme, _)| scheme)
}
/// A path whose send failed is down for this long (unless it answers a PING, or a
/// send there works again).
const DOWN_FOR: Duration = Duration::from_secs(60);
/// How often a path in use is pinged at most (every keepalive interval, if that is
/// longer: `Table::probe_every`), how long an answer may take, and how many PINGs in a
/// row unanswered make it down.
const PROBE_EVERY: Duration = Duration::from_secs(30);
const PROBE_TIMEOUT: Duration = Duration::from_secs(15);
const UNANSWERED_DOWN: u32 = 3;
/// How often the probe task looks for paths due.
const PROBE_TICK: Duration = Duration::from_secs(5);
/// Paths this node had a choice of, or sent over, within this long are probed; ones it
/// didn't use for twice as long are forgotten.
const ACTIVE_FOR: Duration = Duration::from_secs(300);
/// The path in use is changed for one this much faster (a fraction of its round-trip
/// time), and at least `SWITCH_MIN`.
const SWITCH_GAIN: f64 = 0.25;
const SWITCH_MIN: Duration = Duration::from_millis(5);
/// Paths kept at most: they are of peers this node chose among, but bounded anyway.
const MAX_PATHS: usize = 4096;
/// A path's clock sample with the narrowest bound is kept this long at most; then the
/// next one takes its place. (A clock set anew shows at once: `Table::clock`.)
const CLOCK_KEPT: Duration = Duration::from_secs(300);
/// How far a peer's clock is ahead of ours (behind if negative), from a PING and its
/// PONG: `offset_ms`, give or take `within_ms`. The PONG says its sender's time when it
/// answered, which was after our PING went and before the PONG came: within half the
/// round trip of its middle, however differently long the two ways took.
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub(crate) struct ClockOffset {
pub(crate) offset_ms: i64,
pub(crate) within_ms: u64,
}
impl ClockOffset {
/// From a PONG stamped `at` by its sender, which came at `heard` by our clock, `rtt`
/// after its PING went.
pub(crate) fn of(at: UnixMillis, heard: UnixMillis, rtt: Duration) -> Self {
let half_us = rtt.as_micros() / 2;
let middle_us = i128::from(heard.as_u64()) * 1000 - half_us as i128;
let offset_us = i128::from(at.as_u64()) * 1000 - middle_us;
Self {
offset_ms: i64::try_from(offset_us / 1000).unwrap_or(i64::MAX),
// And a millisecond for the stamps' resolution.
within_ms: u64::try_from(half_us.div_ceil(1000)).unwrap_or(u64::MAX) + 1,
}
}
}
/// What paths knows about one path (an address as paths keep it).
#[derive(Debug, Default)]
struct PathState {
/// When it was last among several to choose from (`rank`).
used: Option<Instant>,
/// When a message last went over it: a peer's only path is measured too, if its
/// keepalives don't (a busy pair has none: `PeerState::take_keepalive_due`).
carried: Option<Instant>,
/// Smoothed round-trip time of its PINGs.
rtt: Option<Duration>,
/// Where the transport went when `rtt` was measured (`Paths::location`).
measured_at: Option<String>,
/// The PING out, by nonce, and when it went.
probe: Option<(u64, Instant)>,
last_probe: Option<Instant>,
/// PINGs in a row unanswered.
unanswered: u32,
/// When a send there last failed.
failed_at: Option<Instant>,
/// The peer's clock as its PONGs on this path say (the narrowest bound lately), and
/// when that sample came.
clock: Option<(ClockOffset, Instant)>,
}
impl PathState {
fn is_down(&self, now: Instant) -> bool {
self.unanswered >= UNANSWERED_DOWN
|| self
.failed_at
.is_some_and(|at| now.saturating_duration_since(at) < DOWN_FOR)
}
}
/// Every path's state, and which one is in use for each set to choose from.
#[derive(Debug)]
struct Table {
paths: HashMap<String, PathState>,
/// By the set's addresses (sorted, joined): the one in use.
chosen: HashMap<String, String>,
counts: PathCounts,
/// How often a path in use is pinged: `PROBE_EVERY`, or the node's keepalive
/// interval if that is longer, so that the probes don't add to the keepalives a
/// long interval is chosen to spare. A busy pair, whose keepalives don't go, still
/// gets its paths measured this often.
probe_every: Duration,
}
impl Default for Table {
fn default() -> Self {
Self::new(PROBE_EVERY)
}
}
impl Table {
fn new(keepalive: Duration) -> Self {
Self {
paths: HashMap::new(),
chosen: HashMap::new(),
counts: PathCounts::default(),
probe_every: PROBE_EVERY.max(keepalive),
}
}
/// `usable`, with each one's place in the configured order, best first (as
/// `Paths::rank` says). With `sending`, for a message about to go: they count as
/// used (`ACTIVE_FOR`), and the one in use may change for a faster one. Without, a
/// look at the choice as it stands, changing nothing (`/peers`, figures, LINKS).
fn rank(
&mut self,
mut usable: Vec<(String, usize)>,
now: Instant,
sending: bool,
) -> Vec<String> {
usable.sort_by_key(|(_, preference)| *preference);
usable.dedup_by(|a, b| a.0 == b.0);
if usable.len() < 2 {
return usable.into_iter().map(|(address, _)| address).collect();
}
if sending {
if self.paths.len() >= MAX_PATHS {
self.forget_unused(now);
}
for (address, _) in &usable {
if self.paths.len() < MAX_PATHS || self.paths.contains_key(address) {
self.paths.entry(address.clone()).or_default().used = Some(now);
}
}
}
let rtt = |table: &Self, address: &str| table.paths.get(address).and_then(|path| path.rtt);
let (up, down): (Vec<_>, Vec<_>) = usable.into_iter().partition(|(address, _)| {
!self
.paths
.get(address)
.is_some_and(|path| path.is_down(now))
});
let mut set: Vec<&str> = up
.iter()
.chain(down.iter())
.map(|(address, _)| address.as_str())
.collect();
set.sort_unstable();
let key = set.join(" ");
let mut ranked: Vec<String> = Vec::new();
if !up.is_empty() {
let mut current = self
.chosen
.get(&key)
.filter(|chosen| up.iter().any(|(address, _)| address == *chosen))
.cloned()
.unwrap_or_else(|| up[0].0.clone());
let fastest = up
.iter()
.filter_map(|(address, _)| Some((address, rtt(self, address)?)))
.min_by_key(|(_, rtt)| *rtt);
if let (Some((fastest, fastest_rtt)), Some(current_rtt)) =
(fastest, rtt(self, ¤t))
&& sending
&& *fastest != current
&& current_rtt.saturating_sub(fastest_rtt)
>= SWITCH_MIN.max(current_rtt.mul_f64(SWITCH_GAIN))
{
info!(
from = %current,
to = %fastest,
from_rtt = ?current_rtt,
to_rtt = ?fastest_rtt,
"Switching to a faster path"
);
self.counts.switches += 1;
current = fastest.clone();
}
if sending && (self.chosen.len() < MAX_PATHS || self.chosen.contains_key(&key)) {
self.chosen.insert(key, current.clone());
}
// The rest: measured ones by round-trip time, then unmeasured ones in the
// configured order.
let mut rest: Vec<&(String, usize)> = up
.iter()
.filter(|(address, _)| *address != current)
.collect();
rest.sort_by_key(|(address, preference)| {
(
rtt(self, address).is_none(),
rtt(self, address),
*preference,
)
});
ranked.push(current);
ranked.extend(rest.into_iter().map(|(address, _)| address.clone()));
}
ranked.extend(down.into_iter().map(|(address, _)| address));
ranked
}
/// A send to `address` failed.
fn failed(&mut self, address: &str, now: Instant) {
self.counts.send_failures += 1;
if let Some(path) = self.paths.get_mut(address) {
path.failed_at = Some(now);
// A PING that didn't go out gets no answer; it is no unanswered one.
path.probe = None;
}
}
/// A send to `address` worked.
fn sent(&mut self, address: &str, now: Instant) {
if self.paths.len() >= MAX_PATHS && !self.paths.contains_key(address) {
self.forget_unused(now);
if self.paths.len() >= MAX_PATHS {
return;
}
}
let path = self.paths.entry(address.to_owned()).or_default();
path.failed_at = None;
path.carried = Some(now);
}
/// The PINGs due now, with their nonces (from `nonce`): to every path chosen among
/// others or sent over within `ACTIVE_FOR` that wasn't pinged (by us, or by a
/// keepalive) within `probe_every` and has no PING out. A PING out for
/// `PROBE_TIMEOUT` counts as unanswered.
fn due(&mut self, now: Instant, mut nonce: impl FnMut() -> u64) -> Vec<(String, u64)> {
self.forget_unused(now);
let mut due = Vec::new();
for (address, path) in &mut self.paths {
if let Some((_, sent)) = path.probe
&& now.saturating_duration_since(sent) >= PROBE_TIMEOUT
{
path.probe = None;
path.unanswered += 1;
self.counts.probes_unanswered += 1;
if path.unanswered == UNANSWERED_DOWN {
info!(address = %address, "A path stopped answering PINGs; using others");
}
}
let lately = |at: Option<Instant>| {
at.is_some_and(|at| now.saturating_duration_since(at) < ACTIVE_FOR)
};
let active = lately(path.used) || lately(path.carried);
let rested = path
.last_probe
.is_none_or(|last| now.saturating_duration_since(last) >= self.probe_every);
if active && rested && path.probe.is_none() {
let nonce = nonce();
path.probe = Some((nonce, now));
path.last_probe = Some(now);
self.counts.probes_sent += 1;
due.push((address.clone(), nonce));
}
}
due
}
/// The node sent a PING with `nonce` to `address` (its keepalive): the probe of that
/// path, which its PONG measures, even if it is a peer's only path; `due` then
/// doesn't ping it again within `probe_every`.
fn pinged(&mut self, address: &str, nonce: u64, now: Instant) {
if self.paths.len() >= MAX_PATHS && !self.paths.contains_key(address) {
self.forget_unused(now);
if self.paths.len() >= MAX_PATHS {
return;
}
}
let path = self.paths.entry(address.to_owned()).or_default();
path.probe = Some((nonce, now));
path.last_probe = Some(now);
self.counts.probes_sent += 1;
}
/// The PING with `nonce` to `address` (from `due`) goes now: its round trip counts
/// from here, not from when it was found due.
fn sending(&mut self, address: &str, nonce: u64, now: Instant) {
if let Some(path) = self.paths.get_mut(address)
&& let Some((expected, sent)) = &mut path.probe
&& *expected == nonce
{
*sent = now;
}
}
/// The transport of `address` now goes to `location` (a libp2p peer over another
/// connection: through a relay before, directly now): round trips measured before
/// were of another way, and would weigh on the next ones for minutes (`pong`
/// smooths), so they are dropped.
fn located(&mut self, address: &str, location: &str) {
let Some(path) = self.paths.get_mut(address) else {
return;
};
if path.measured_at.as_deref() != Some(location) {
if path.measured_at.is_some() {
path.rtt = None;
}
path.measured_at = Some(location.to_owned());
}
}
/// A PONG with `nonce` from `address`: its round trip, if it answers our PING out.
fn pong(&mut self, address: &str, nonce: u64, now: Instant) -> Option<Duration> {
let path = self.paths.get_mut(address)?;
let (expected, sent) = path.probe?;
if expected != nonce {
return None;
}
let sample = now.saturating_duration_since(sent);
path.probe = None;
if path.unanswered >= UNANSWERED_DOWN {
info!(address = %address, "A path answers PINGs again");
}
path.unanswered = 0;
path.failed_at = None;
path.rtt = Some(match path.rtt {
Some(rtt) => (rtt * 3 + sample) / 4,
None => sample,
});
self.counts.probes_answered += 1;
Some(sample)
}
/// A clock sample from a PONG over `address`: kept if its bound is as narrow as the
/// one kept, or that one is older than `CLOCK_KEPT`, or the two can't both be right
/// (their bounds don't overlap: a clock was set anew). The narrowest bound is the
/// round trip least delayed by queues and relays.
fn clock(&mut self, address: &str, offset: ClockOffset, now: Instant) {
let Some(path) = self.paths.get_mut(address) else {
return;
};
let replaces = path.clock.is_none_or(|(kept, at)| {
offset.within_ms <= kept.within_ms
|| now.saturating_duration_since(at) >= CLOCK_KEPT
|| offset.offset_ms.abs_diff(kept.offset_ms)
> offset.within_ms.saturating_add(kept.within_ms)
});
if replaces {
path.clock = Some((offset, now));
}
}
/// Forgets the paths neither used nor pinged for twice `ACTIVE_FOR`, and choices
/// among them.
fn forget_unused(&mut self, now: Instant) {
let recent = |at: Option<Instant>| {
at.is_some_and(|at| now.saturating_duration_since(at) < ACTIVE_FOR * 2)
};
self.paths
.retain(|_, path| recent(path.used) || recent(path.carried) || recent(path.last_probe));
let paths = &self.paths;
self.chosen
.retain(|key, _| key.split(' ').all(|address| paths.contains_key(address)));
}
fn info(&self, address: &str, now: Instant) -> PathInfo {
let path = self.paths.get(address);
PathInfo {
address: address.to_owned(),
rtt_ms: path
.and_then(|path| path.rtt)
.map(|rtt| rtt.as_secs_f64() * 1000.0),
down: path.is_some_and(|path| path.is_down(now)),
connection: None,
}
}
}
pub(crate) struct Paths {
/// In order of preference.
links: Vec<Link>,
/// Its own PINGs and PONGs are counted here, under the address (`traffic`).
traffic: Option<Arc<Traffic>>,
/// The debug firewall, if any.
gate: Option<Weak<dyn Gate>>,
/// The node's wall clock, which its PONGs say the time by.
clock: Arc<Clock>,
/// A std mutex: never held across an await.
table: Mutex<Table>,
}
impl Paths {
/// Over `transports`, by scheme, in order of preference; its own PINGs and PONGs
/// counted in `traffic`, the firewall through `gate`, PONGs stamped by `clock`;
/// paths pinged every `keepalive` at least (`Table::probe_every`).
pub(crate) fn new(
transports: Vec<(&'static str, Arc<dyn Transport>)>,
traffic: Option<Arc<Traffic>>,
gate: Option<Weak<dyn Gate>>,
clock: Arc<Clock>,
keepalive: Duration,
) -> Self {
Self {
links: transports
.into_iter()
.map(|(scheme, inner)| Link { scheme, inner })
.collect(),
traffic,
gate,
clock,
table: Mutex::new(Table::new(keepalive)),
}
}
fn gate(&self) -> Option<Arc<dyn Gate>> {
self.gate.as_ref()?.upgrade()
}
/// The transport `address` is on, and the transport identity at it
/// (`Transport::locate`, which notes where that is if the address says); None if no
/// transport of ours has its scheme, or it isn't one of that transport's.
fn split(&self, address: &str) -> Option<(&Link, String)> {
let (scheme, target) = address.split_once(':')?;
let link = self.links.iter().find(|link| link.scheme == scheme)?;
let target = link.inner.locate(target)?;
Some((link, target))
}
/// Whether one of our transports can use `address`.
pub(crate) fn usable(&self, address: &str) -> bool {
self.split(address).is_some()
}
/// `address` as paths keep it: `<scheme>:<transport identity>`.
pub(crate) fn canonical(&self, address: &str) -> Option<String> {
self.split(address)
.map(|(link, target)| link.address(&target))
}
/// Where the node at `address` (as paths keep it) is, as others can use it
/// (`Transport::locations`).
pub(crate) fn locations(&self, address: &str) -> Vec<String> {
let Some((link, target)) = self.split(address) else {
return Vec::new();
};
link.inner
.locations(&target)
.iter()
.map(|location| link.address(location))
.collect()
}
/// Where `address`'s transport is in the order of preference (none of ours: last).
pub(crate) fn preference(&self, address: &str) -> usize {
let scheme = scheme_of(address);
self.links
.iter()
.position(|link| link.scheme == scheme)
.unwrap_or(usize::MAX)
}
/// The usable ones of `addresses` (as paths keep them), best first: paths that are
/// up before those down, the one in use first, then by round-trip time, then in
/// the configured order (module docs). For a send (`sending`): several addresses
/// are paths to measure, and the one in use may change; else only a look
/// (`Table::rank`).
pub(crate) fn rank(&self, addresses: &[String], sending: bool) -> Vec<String> {
let usable: Vec<(String, usize)> = addresses
.iter()
.filter(|address| self.usable(address))
.map(|address| (address.clone(), self.preference(address)))
.collect();
self.table
.lock_or_recover()
.rank(usable, Instant::now(), sending)
}
/// The smoothed round-trip time of the path to `address`, if measured.
pub(crate) fn rtt(&self, address: &str) -> Option<Duration> {
self.table.lock_or_recover().paths.get(address)?.rtt
}
/// The peer's clock at `address`, as its PONGs there say (`ClockOffset`).
pub(crate) fn clock_offset(&self, address: &str) -> Option<ClockOffset> {
let table = self.table.lock_or_recover();
table.paths.get(address)?.clock.map(|(offset, _)| offset)
}
/// What paths knows about each of `addresses`.
pub(crate) fn info(&self, addresses: &[String]) -> Vec<PathInfo> {
let now = Instant::now();
let infos = {
let table = self.table.lock_or_recover();
addresses
.iter()
.map(|address| table.info(address, now))
.collect()
};
self.located(infos)
}
/// `infos` with where each path goes (`located`) and the transport's connection
/// there; asked outside the table's lock.
fn located(&self, mut infos: Vec<PathInfo>) -> Vec<PathInfo> {
for info in &mut infos {
info.connection = self.connection(&info.address);
info.address = self.location(&info.address);
}
infos
}
/// `address` (as paths keep it) as where it goes now, where the transport knows
/// more (`Transport::location`: libp2p, its connection's remote address); else
/// `address` itself. For showing: paths go by `address`.
pub(crate) fn location(&self, address: &str) -> String {
self.split(address)
.and_then(|(link, target)| Some(link.address(&link.inner.location(&target)?)))
.unwrap_or_else(|| address.to_owned())
}
/// Whether `address` is one of ours.
pub(crate) fn is_own(&self, address: &str) -> bool {
self.links.iter().any(|link| link.own_address() == address)
}
/// Our address on the transport of `address`, as `address` names it there.
pub(crate) fn own_address(&self, address: &str) -> Option<String> {
let scheme = scheme_of(address);
self.links
.iter()
.find(|link| link.scheme == scheme)
.map(Link::own_address)
}
/// Relays listed for the swarm (`Transport::learn_relays`): to each transport the
/// addresses with its scheme, without it.
pub(crate) fn learn_relays(&self, addresses: &[String]) {
for link in &self.links {
let targets: Vec<String> = addresses
.iter()
.filter_map(|address| address.strip_prefix(link.scheme)?.strip_prefix(':'))
.map(str::to_owned)
.collect();
link.inner.learn_relays(&targets);
}
}
/// This node's own addresses, one per transport: `<scheme>:<its identity there>`.
pub(crate) fn own_addresses(&self) -> Vec<String> {
self.links.iter().map(Link::own_address).collect()
}
/// The longest of the transports': until then, something may still be on its way.
pub(crate) fn delivery_limit(&self) -> Duration {
self.links
.iter()
.map(|link| link.inner.delivery_limit())
.max()
.unwrap_or_default()
}
/// The longest of the transports' (`Transport::sync_reply_timeout`): an answer may
/// come over any of them.
pub(crate) fn sync_reply_timeout(&self) -> Duration {
self.links
.iter()
.map(|link| link.inner.sync_reply_timeout())
.max()
.unwrap_or(crate::state::SYNC_REPLY_TIMEOUT)
}
/// Each transport's (`Transport::local_addresses`), with its scheme: taken in turns,
/// each transport's first in the configured order, then each one's second, and so on,
/// so a list cut short (`members::MAX_ADDRESSES`) still has every transport's best.
pub(crate) fn local_addresses(&self) -> Vec<String> {
let mut each: Vec<std::vec::IntoIter<String>> = self
.links
.iter()
.map(|link| {
link.inner
.local_addresses()
.into_iter()
.map(|target| link.address(&target))
.collect::<Vec<_>>()
.into_iter()
})
.collect();
let mut addresses = Vec::new();
loop {
let before = addresses.len();
addresses.extend(each.iter_mut().filter_map(Iterator::next));
if addresses.len() == before {
return addresses;
}
}
}
/// The schemes of the transports, in order of preference.
pub(crate) fn transports(&self) -> Vec<String> {
self.links
.iter()
.map(|link| link.scheme.to_owned())
.collect()
}
/// Each transport's, with its scheme.
pub(crate) fn discovered_seeds(&self) -> Vec<String> {
self.links
.iter()
.flat_map(|link| {
link.inner
.discovered_seeds()
.into_iter()
.map(|seed| link.address(&seed))
})
.collect()
}
/// Each transport's (`Transport::on_seeds_found`).
pub(crate) fn on_seeds_found(&self, found: std::sync::Arc<tokio::sync::Notify>) {
for link in &self.links {
link.inner.on_seeds_found(found.clone());
}
}
/// Each transport's (`Transport::on_reachable`).
pub(crate) fn on_reachable(&self, reachable: std::sync::Arc<tokio::sync::Notify>) {
for link in &self.links {
link.inner.on_reachable(reachable.clone());
}
}
/// The address of the node a seed leads to, as paths keep it: an address of ours
/// (`<scheme>:...`) whose transport reads it at once; with a scheme of ours, what
/// that transport resolves the rest to (an address the transport can't read as an
/// identity, e.g. a libp2p multiaddr without its peer ID, still resolves); without
/// one, what the first transport that can resolves it to.
pub(crate) async fn resolve(&self, seed: &str) -> Result<String> {
if let Some(address) = self.canonical(seed) {
return Ok(address);
}
let scheme_and_rest = seed.split_once(':').and_then(|(scheme, rest)| {
let link = self.links.iter().find(|link| link.scheme == scheme)?;
Some((link, rest))
});
if let Some((link, rest)) = scheme_and_rest {
let target = link
.inner
.resolve_seed(rest)
.await
.with_context(|| format!("{}: {seed}", link.scheme))?;
return Ok(link.address(&target));
}
let mut failures = Vec::new();
for link in &self.links {
match link.inner.resolve_seed(seed).await {
Ok(target) => return Ok(link.address(&target)),
Err(error) => failures.push(format!("{}: {error:#}", link.scheme)),
}
}
Err(anyhow!("{}", failures.join("; ")))
}
/// `message` encoded for `address`: `peer` and `address` of the result are
/// `address`, and it keeps the message (to encode it for another address).
pub(crate) fn encode(&self, address: &str, message: &ParsedMessage) -> Result<EncodedMessage> {
let (link, target) = self
.split(address)
.with_context(|| format!("no transport for {address}"))?;
let mut encoded = link.inner.encode(&target, message)?;
encoded.peer = address.to_owned();
encoded.address = address.to_owned();
encoded.message = Some(Arc::new(message.clone()));
Ok(encoded)
}
/// Sends `message` to the first of `addresses` (`rank`ed) that takes it: to its own
/// `address` as encoded, to others encoded again for their transport (if it keeps
/// the message). Returns the address it went to; an error with every address's if
/// none took it.
pub(crate) async fn send_first(
&self,
message: &EncodedMessage,
addresses: &[String],
) -> Result<String> {
let mut failures: Vec<(String, anyhow::Error)> = Vec::new();
for address in addresses {
let encoded = if *address == message.address {
message.clone()
} else {
let Some(parsed) = &message.message else {
continue;
};
match self.encode(address, parsed) {
Ok(mut encoded) => {
encoded.peer = message.peer.clone();
encoded
}
Err(error) => {
failures.push((address.clone(), error));
continue;
}
}
};
// A PING is noted before it goes: on a fast link, its PONG may be back
// before the send returns.
if let Some(ParsedMessage::Ping(nonce)) = message.message.as_deref() {
self.table
.lock_or_recover()
.pinged(address, *nonce, Instant::now());
}
match self.send(&encoded).await {
Ok(()) => {
let mut table = self.table.lock_or_recover();
table.sent(address, Instant::now());
if !failures.is_empty() {
table.counts.failovers += 1;
drop(table);
debug!(
peer = %message.peer,
address = %address,
failed = %describe(&failures),
"Sent at another address after a send failed"
);
}
return Ok(address.clone());
}
Err(error) => {
self.table.lock_or_recover().failed(address, Instant::now());
failures.push((address.clone(), error));
}
}
}
match failures.len() {
0 => Err(anyhow!("no address to send to")),
// The transport's error as it is.
1 => Err(failures.pop().expect("one").1),
_ => Err(anyhow!("{}", describe(&failures))),
}
}
/// Sends `message` to its `address` (dropped silently if the firewall blocks it).
pub(crate) async fn send(&self, message: &EncodedMessage) -> Result<()> {
if self
.gate()
.is_some_and(|gate| gate.blocks_outbound(&message.address))
{
tracing::trace!(to = %message.address, "Firewall dropped outbound message");
return Ok(());
}
let (link, target) = self
.split(&message.address)
.with_context(|| format!("no transport for {}", message.address))?;
let mut inner = message.clone();
inner.peer = target.clone();
inner.address = target;
link.inner.send_encoded(&inner).await?;
match &message.message {
Some(parsed) => {
debug!(to = %message.address, bytes = message.payload_len, message = ?parsed, "Sent message");
}
None => {
debug!(to = %message.address, bytes = message.payload_len, kind = ?message.kind, "Sent message");
}
}
Ok(())
}
/// How the transport of `address` is connected there (`Transport::connection`).
pub(crate) fn connection(&self, address: &str) -> Option<Connection> {
let (link, target) = self.split(address)?;
link.inner.connection(&target)
}
/// How hole punching to `address` went (`Transport::punching`).
pub(crate) fn punching(&self, address: &str) -> Option<crate::transport::Punching> {
let (link, target) = self.split(address)?;
link.inner.punching(&target)
}
/// Paths' own figures, and every transport's.
pub(crate) fn stats(&self) -> TransportStats {
let mut stats = TransportStats::default();
for link in &self.links {
stats.merge(link.inner.stats());
}
let now = Instant::now();
let (paths, counts) = {
let table = self.table.lock_or_recover();
let paths: Vec<PathInfo> = table
.paths
.keys()
.map(|address| table.info(address, now))
.collect();
(paths, table.counts)
};
let mut paths = self.located(paths);
paths.sort_by(|a, b| a.address.cmp(&b.address));
stats.paths = Some(PathsStats { paths, counts });
stats
}
/// Sends a PING (or with `pong`, a PONG) with `nonce` to `address`, counted and
/// logged (`traffic`).
async fn send_probe(&self, address: &str, pong: bool, nonce: u64) -> Result<()> {
let message = if pong {
ParsedMessage::Pong {
nonce,
at: self.clock.now_millis(),
}
} else {
ParsedMessage::Ping(nonce)
};
let encoded = self.encode(address, &message)?;
let sent = self.send(&encoded).await;
if let Some(traffic) = &self.traffic {
match &sent {
Ok(()) => traffic.sent(address, encoded.kind, encoded.payload_len),
Err(_) => traffic.refused(address, encoded.kind, encoded.payload_len),
}
// Logged too, under the address: the PINGs and PONGs that come back go up to
// the node and are logged there, and an exchange is seen whole.
let way = if sent.is_ok() { "sent" } else { "refused" };
traffic
.log
.note(way, address, &message, encoded.payload_len);
}
sent
}
/// Pings the paths due (`Table::due`), every `PROBE_TICK`, until dropped. Each PING
/// goes on its own, timed from when it goes: a send that takes long (a dial) neither
/// holds up the others nor counts in their round trips.
async fn probe(self: Arc<Self>) {
let mut tick = tokio::time::interval(PROBE_TICK);
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay);
loop {
tick.tick().await;
let due = self
.table
.lock_or_recover()
.due(Instant::now(), random_nonce);
for (address, nonce) in due {
let paths = Arc::clone(&self);
tokio::spawn(async move {
paths
.table
.lock_or_recover()
.sending(&address, nonce, Instant::now());
if let Err(error) = paths.send_probe(&address, false, nonce).await {
debug!(to = %address, error = %format!("{error:#}"), "Couldn't send a PING");
paths
.table
.lock_or_recover()
.failed(&address, Instant::now());
}
});
}
}
}
/// A message from `address`, handed on to `handler`: a PING answered and a PONG
/// noted first; dropped if the firewall blocks it.
async fn receive(
self: Arc<Self>,
address: String,
message: ParsedMessage,
payload_len: usize,
handler: &PathHandler,
) -> Result<()> {
if self
.gate()
.is_some_and(|gate| gate.blocks_inbound(&address))
{
tracing::trace!(from = %address, "Firewall dropped inbound message");
return Ok(());
}
debug!(from = %address, bytes = payload_len, message = ?message, "Received message");
match message {
ParsedMessage::Ping(nonce) => {
let paths = Arc::clone(&self);
let to = address.clone();
tokio::spawn(async move {
if let Err(error) = paths.send_probe(&to, true, nonce).await {
debug!(to = %to, error = %format!("{error:#}"), "Couldn't answer a PING");
}
});
}
ParsedMessage::Pong { nonce, at } => {
let heard = self.clock.now_millis();
let location = self.location(&address);
let now = Instant::now();
let mut table = self.table.lock_or_recover();
table.located(&address, &location);
if let Some(rtt) = table.pong(&address, nonce, now) {
table.clock(&address, ClockOffset::of(at, heard, rtt), now);
}
}
_ => {}
}
handler(address, message, payload_len).await
}
/// Every transport's consumer, each message handed to `handler` under the sender's
/// address (PINGs and PONGs end here), and the probe task; returns when the first
/// consumer does.
pub(crate) async fn start_consumer(self: &Arc<Self>, handler: Arc<PathHandler>) -> Result<()> {
let probing = tokio::spawn(Arc::clone(self).probe());
let mut consumers: Vec<std::pin::Pin<Box<dyn Future<Output = Result<()>> + Send>>> =
Vec::new();
for link in &self.links {
let inner = Arc::clone(&link.inner);
let scheme = link.scheme;
let handler = Arc::clone(&handler);
let paths = Arc::clone(self);
consumers.push(Box::pin(async move {
inner
.start_consumer(Box::new(move |sender, message, payload_len| {
let paths = Arc::clone(&paths);
let handler = Arc::clone(&handler);
Box::pin(async move {
paths
.receive(
format!("{scheme}:{sender}"),
message,
payload_len,
&*handler,
)
.await
})
}))
.await
}));
}
let result = first(consumers)
.await
.unwrap_or_else(|| Err(anyhow!("no transports")));
probing.abort();
result
}
/// When the first transport exits.
pub(crate) async fn wait_for_exit(&self) -> std::io::Result<std::process::ExitStatus> {
let waits = self
.links
.iter()
.map(|link| {
let inner = Arc::clone(&link.inner);
Box::pin(async move { inner.wait_for_exit().await })
as std::pin::Pin<Box<dyn Future<Output = _> + Send>>
})
.collect();
first(waits)
.await
.unwrap_or_else(|| Err(std::io::Error::other("no transports")))
}
}
/// A PING's nonce: random, so a PONG can't be made up for a PING not seen.
pub(crate) fn random_nonce() -> u64 {
let mut bytes = [0u8; 8];
if getrandom::fill(&mut bytes).is_err() {
// No randomness: a nonce still tells answers apart, if not unguessably.
return std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |since| since.as_nanos() as u64);
}
u64::from_le_bytes(bytes)
}
/// `address: error; …` for each failed send.
fn describe(failures: &[(String, anyhow::Error)]) -> String {
failures
.iter()
.map(|(address, error)| format!("{address}: {error:#}"))
.collect::<Vec<_>>()
.join("; ")
}
/// The first of the `results` to arrive, from tasks that run until they end.
async fn first<T: Send + 'static>(
tasks: Vec<std::pin::Pin<Box<dyn Future<Output = T> + Send>>>,
) -> Option<T> {
let (sender, mut receiver) = tokio::sync::mpsc::channel(1);
for task in tasks {
let sender = sender.clone();
tokio::spawn(async move {
let _ = sender.send(task.await).await;
});
}
drop(sender);
receiver.recv().await
}
#[cfg(test)]
mod tests {
use super::*;
use crate::document::replica::Epoch;
use crate::transport::sim::SimNet;
use crate::transport::{HeadsSummary, Status};
/// "a" on two sim nets, as `sim` (preferred) and `other`; "b" on both too.
fn two_nets() -> (Arc<Paths>, Arc<Paths>) {
let (first, second) = (SimNet::new(1), SimNet::new(2));
let on_both = |id: &str| {
Arc::new(Paths::new(
vec![
("sim", first.transport(id) as Arc<dyn Transport>),
("other", second.transport(id) as Arc<dyn Transport>),
],
None,
None,
Arc::default(),
Duration::ZERO,
))
};
(on_both("a"), on_both("b"))
}
#[test]
fn addresses_by_scheme() {
let (a, _b) = two_nets();
assert_eq!(a.local_addresses(), ["sim:a", "other:a"]);
assert_eq!(a.transports(), ["sim", "other"]);
assert_eq!(a.canonical("other:b").as_deref(), Some("other:b"));
assert_eq!(a.canonical("pigeon:b"), None);
assert_eq!(a.canonical("b"), None); // No scheme.
assert!(a.preference("sim:b") < a.preference("other:b"));
assert_eq!(a.preference("pigeon:b"), usize::MAX);
assert!(a.is_own("other:a") && !a.is_own("other:b"));
assert_eq!(a.own_address("other:b").as_deref(), Some("other:a"));
assert_eq!(a.own_address("pigeon:b"), None);
}
#[tokio::test]
async fn seeds_resolve_to_addresses() {
let (a, _b) = two_nets();
assert_eq!(a.resolve("other:b").await.unwrap(), "other:b");
// Without a scheme: the first transport that resolves it.
assert_eq!(a.resolve("b").await.unwrap(), "sim:b");
assert!(a.resolve("nobody").await.is_err());
}
fn paths(addresses: &[&str]) -> Vec<(String, usize)> {
addresses
.iter()
.enumerate()
.map(|(preference, address)| (address.to_string(), preference))
.collect()
}
/// Answers every PING due `rtt` later, as from the path it went to (`rtts`).
fn answer(table: &mut Table, now: Instant, rtts: &[(&str, u64)]) -> Instant {
let mut nonces = 0;
let due = table.due(now, || {
nonces += 1;
nonces
});
for (address, nonce) in due {
let rtt = rtts
.iter()
.find(|(to, _)| *to == address)
.map(|(_, ms)| *ms);
if let Some(ms) = rtt {
table.pong(&address, nonce, now + Duration::from_millis(ms));
}
}
now + PROBE_EVERY
}
#[test]
fn the_configured_order_until_measured_then_the_faster_path() {
let mut table = Table::default();
let mut now = Instant::now();
let set = paths(&["libp2p:x", "mycelium:x"]);
assert_eq!(
table.rank(set.clone(), now, true),
["libp2p:x", "mycelium:x"]
);
// libp2p a bit slower: not enough to switch.
for _ in 0..8 {
now = answer(&mut table, now, &[("libp2p:x", 110), ("mycelium:x", 100)]);
}
assert_eq!(
table.rank(set.clone(), now, true),
["libp2p:x", "mycelium:x"]
);
assert_eq!(table.counts.switches, 0);
// Much slower: switched, and it stays switched while that holds.
for _ in 0..8 {
now = answer(&mut table, now, &[("libp2p:x", 300), ("mycelium:x", 100)]);
}
assert_eq!(
table.rank(set.clone(), now, true),
["mycelium:x", "libp2p:x"]
);
assert_eq!(
table.rank(set.clone(), now, true),
["mycelium:x", "libp2p:x"]
);
assert_eq!(table.counts.switches, 1);
// Small differences under SWITCH_MIN never switch.
let lan = paths(&["libp2p:y", "mycelium:y"]);
table.rank(lan.clone(), now, true);
for _ in 0..8 {
now = answer(&mut table, now, &[("libp2p:y", 4), ("mycelium:y", 1)]);
}
assert_eq!(table.rank(lan, now, true), ["libp2p:y", "mycelium:y"]);
}
#[test]
fn unanswered_or_failing_paths_are_down() {
let mut table = Table::default();
let mut now = Instant::now();
let set = paths(&["libp2p:x", "mycelium:x"]);
table.rank(set.clone(), now, true);
// libp2p stops answering: down after UNANSWERED_DOWN PINGs, then last.
for _ in 0..=UNANSWERED_DOWN {
now = answer(&mut table, now, &[("mycelium:x", 100)]);
table.rank(set.clone(), now, true);
}
assert!(table.info("libp2p:x", now).down);
assert_eq!(
table.rank(set.clone(), now, true),
["mycelium:x", "libp2p:x"]
);
// It answers again: up, and measured.
now = answer(&mut table, now, &[("libp2p:x", 50), ("mycelium:x", 100)]);
assert!(!table.info("libp2p:x", now).down);
// A failed send: down for DOWN_FOR, unless a send there works.
table.failed("mycelium:x", now);
assert!(table.info("mycelium:x", now).down);
assert!(!table.info("mycelium:x", now + DOWN_FOR).down);
table.sent("mycelium:x", now);
assert!(!table.info("mycelium:x", now).down);
}
/// A look at the choice (`/peers`, figures) changes nothing: no path counts as
/// used, and no faster one is switched to.
#[test]
fn a_look_changes_nothing() {
let mut table = Table::default();
let mut now = Instant::now();
let set = paths(&["libp2p:x", "mycelium:x"]);
assert_eq!(
table.rank(set.clone(), now, false),
["libp2p:x", "mycelium:x"]
);
assert!(table.paths.is_empty() && table.chosen.is_empty());
table.rank(set.clone(), now, true);
for _ in 0..4 {
now = answer(&mut table, now, &[("libp2p:x", 500), ("mycelium:x", 10)]);
}
// Much faster, but only looked at: still the one in use.
assert_eq!(
table.rank(set.clone(), now, false),
["libp2p:x", "mycelium:x"]
);
assert_eq!(table.counts.switches, 0);
assert_eq!(table.rank(set, now, true), ["mycelium:x", "libp2p:x"]);
assert_eq!(table.counts.switches, 1);
}
#[test]
fn only_paths_in_use_are_pinged() {
let mut table = Table::default();
let now = Instant::now();
let mut nonce = 0;
let mut next = || {
nonce += 1;
nonce
};
// One address: nothing to choose, nothing to measure.
table.rank(paths(&["libp2p:z"]), now, true);
assert!(table.due(now, &mut next).is_empty());
table.rank(paths(&["libp2p:x", "mycelium:x"]), now, true);
assert_eq!(table.due(now, &mut next).len(), 2);
// Not again within PROBE_EVERY; a stale answer is ignored.
assert!(table.due(now + PROBE_TIMEOUT, &mut next).is_empty());
assert_eq!(table.pong("libp2p:x", 99, now), None);
// Unused for ACTIVE_FOR: no more PINGs; for twice as long: forgotten.
assert!(table.due(now + ACTIVE_FOR, &mut next).is_empty());
table.due(now + ACTIVE_FOR * 2, &mut next);
assert!(table.paths.is_empty() && table.chosen.is_empty());
}
/// A PONG's time against the middle of its round trip: the peer's clock, give or
/// take half the round trip; the narrowest bound kept, until it is old.
#[test]
fn clocks_compare_by_the_middle_of_the_round_trip() {
let rtt = Duration::from_millis(200);
let heard = UnixMillis(10_000);
let ahead = ClockOffset::of(UnixMillis(14_900), heard, rtt);
assert_eq!((ahead.offset_ms, ahead.within_ms), (5_000, 101));
let behind = ClockOffset::of(UnixMillis(6_900), heard, rtt);
assert_eq!(behind.offset_ms, -3_000);
let mut table = Table::default();
let now = Instant::now();
table.sent("libp2p:z", now);
table.clock("libp2p:z", ahead, now);
let wider = ClockOffset::of(UnixMillis(15_000), heard, rtt * 4);
table.clock("libp2p:z", wider, now);
assert_eq!(
table.paths["libp2p:z"].clock.map(|(kept, _)| kept),
Some(ahead)
);
table.clock("libp2p:z", wider, now + CLOCK_KEPT);
assert_eq!(
table.paths["libp2p:z"].clock.map(|(kept, _)| kept),
Some(wider)
);
// A clock set anew: a sample the kept one contradicts takes its place at once,
// its bound wider or not.
let set_anew = ClockOffset::of(UnixMillis(25_000), heard, rtt * 8);
table.clock("libp2p:z", set_anew, now + CLOCK_KEPT);
assert_eq!(
table.paths["libp2p:z"].clock.map(|(kept, _)| kept),
Some(set_anew)
);
}
/// A peer's only path is measured too once messages go over it, unless its
/// keepalives just did.
#[test]
fn a_path_sent_over_is_pinged() {
let mut table = Table::default();
let now = Instant::now();
table.sent("libp2p:z", now);
assert_eq!(table.due(now, || 1), [("libp2p:z".to_owned(), 1)]);
table.pong("libp2p:z", 1, now + Duration::from_millis(20));
assert!(table.info("libp2p:z", now).rtt_ms.is_some());
// A keepalive's PING within PROBE_EVERY: none of ours.
let later = now + PROBE_EVERY;
table.pinged("libp2p:z", 2, later);
table.sent("libp2p:z", later);
assert!(table.due(later, || 3).is_empty());
}
/// A PING's round trip counts from when it goes, not from when it was found due.
#[test]
fn round_trips_count_from_the_send() {
let mut table = Table::default();
let now = Instant::now();
table.rank(paths(&["libp2p:x", "mycelium:x"]), now, true);
let due = table.due(now, || 7);
assert_eq!(due.len(), 2);
// Sent a second late (after another path's slow send).
let sent = now + Duration::from_secs(1);
table.sending("libp2p:x", 7, sent);
table.sending("libp2p:x", 8, sent + Duration::from_secs(1)); // not its PING
table.pong("libp2p:x", 7, sent + Duration::from_millis(100));
let rtt = table.info("libp2p:x", now).rtt_ms.unwrap();
assert!((rtt - 100.0).abs() < 1e-6, "{rtt}");
}
/// Round trips of another way to the peer (through a relay, then directly) don't
/// weigh on those of the new one.
#[test]
fn a_path_that_goes_elsewhere_is_measured_anew() {
let mut table = Table::default();
let now = Instant::now();
table.rank(paths(&["libp2p:x", "mycelium:x"]), now, true);
let ping = |table: &mut Table, nonce: u64, at: Instant, ms: u64| {
table.pinged("libp2p:x", nonce, at);
table.pong("libp2p:x", nonce, at + Duration::from_millis(ms));
};
table.located("libp2p:x", "libp2p:/relayed");
ping(&mut table, 1, now, 120);
table.located("libp2p:x", "libp2p:/relayed");
ping(&mut table, 2, now + Duration::from_secs(30), 120);
table.located("libp2p:x", "libp2p:/lan");
ping(&mut table, 3, now + Duration::from_secs(60), 2);
let rtt = table.info("libp2p:x", now).rtt_ms.unwrap();
assert!((rtt - 2.0).abs() < 1e-6, "{rtt}");
}
/// The node's keepalive PING on a path is its probe: paths doesn't ping it too, and
/// the PONG measures it.
#[test]
fn keepalive_pings_are_probes() {
let mut table = Table::default();
let now = Instant::now();
let mut nonce = 100;
let mut next = || {
nonce += 1;
nonce
};
table.rank(paths(&["libp2p:x", "mycelium:x"]), now, true);
table.pinged("libp2p:x", 7, now);
let due = table.due(now, &mut next);
assert_eq!(due.len(), 1);
assert_eq!(due[0].0, "mycelium:x");
assert!(
table
.pong("libp2p:x", 7, now + Duration::from_millis(20))
.is_some()
);
assert_eq!(table.counts.probes_sent, 2);
// A peer's only path is measured by its keepalives, and not pinged otherwise.
table.pinged("libp2p:z", 8, now);
assert!(
table
.pong("libp2p:z", 8, now + Duration::from_millis(30))
.is_some()
);
let rtt = table.info("libp2p:z", now).rtt_ms.unwrap();
assert!((rtt - 30.0).abs() < 1e-6, "{rtt}");
let later = now + PROBE_EVERY;
assert!(
table
.due(later, &mut next)
.iter()
.all(|(address, _)| address != "libp2p:z")
);
// Forgotten once the keepalives stop.
table.due(now + ACTIVE_FOR * 2, &mut next);
assert!(!table.paths.contains_key("libp2p:z"));
}
/// Blocks one address, both ways.
struct Blocking(&'static str);
impl Gate for Blocking {
fn blocks_inbound(&self, address: &str) -> bool {
address == self.0
}
fn blocks_outbound(&self, address: &str) -> bool {
address == self.0
}
}
/// The firewall drops what comes from a blocked address before anything sees it
/// (a PING isn't answered), and sends to one silently.
#[tokio::test]
async fn the_firewall_drops_both_ways() {
let net = SimNet::new(4);
let gate: Arc<dyn Gate> = Arc::new(Blocking("sim:a"));
let b = Arc::new(Paths::new(
vec![("sim", net.transport("b") as Arc<dyn Transport>)],
None,
Some(Arc::downgrade(&gate)),
Arc::default(),
Duration::ZERO,
));
let a = Arc::new(Paths::new(
vec![("sim", net.transport("a") as Arc<dyn Transport>)],
None,
None,
Arc::default(),
Duration::ZERO,
));
let received = |paths: &Arc<Paths>| {
let (sender, received) = tokio::sync::mpsc::unbounded_channel();
let handler: Arc<PathHandler> = Arc::new(move |from, message, _| {
let sender = sender.clone();
Box::pin(async move {
let _ = sender.send((from, message.kind()));
Ok(())
})
});
let paths = Arc::clone(paths);
tokio::spawn(async move { paths.start_consumer(handler).await });
received
};
let (mut at_a, mut at_b) = (received(&a), received(&b));
// a's PING never reaches b, so nothing answers it.
let ping = a.encode("sim:b", &ParsedMessage::Ping(5)).unwrap();
a.send(&ping).await.unwrap();
// b's send to a "works", and goes nowhere.
let status = b.encode("sim:a", &some_status()).unwrap();
b.send(&status).await.unwrap();
tokio::time::sleep(Duration::from_millis(200)).await;
assert!(at_b.try_recv().is_err());
assert!(at_a.try_recv().is_err());
// Without the gate: a PING is answered by b's paths, and goes on up there.
drop(gate);
a.send(&ping).await.unwrap();
assert_eq!(
at_b.recv().await.unwrap(),
("sim:a".to_owned(), crate::transport::MessageKind::Ping)
);
assert_eq!(
at_a.recv().await.unwrap(),
("sim:b".to_owned(), crate::transport::MessageKind::Pong)
);
}
/// A transport whose sends all fail.
struct Broken;
#[async_trait::async_trait]
impl Transport for Broken {
fn local_id(&self) -> &str {
"us"
}
fn is_peer_id(&self, id: &str) -> bool {
!id.is_empty()
}
fn delivery_limit(&self) -> Duration {
Duration::from_secs(1)
}
async fn resolve_seed(&self, seed: &str) -> Result<String> {
Ok(seed.to_owned())
}
fn encode(&self, peer: &str, message: &ParsedMessage) -> Result<EncodedMessage> {
(crate::transport::sim::WIRE.encode)(peer, message)
}
async fn send_encoded(&self, _message: &EncodedMessage) -> Result<()> {
Err(anyhow!("broken"))
}
async fn start_consumer(&self, _handler: crate::transport::MessageHandler) -> Result<()> {
std::future::pending().await
}
async fn wait_for_exit(&self) -> std::io::Result<std::process::ExitStatus> {
std::future::pending().await
}
}
fn some_status() -> ParsedMessage {
ParsedMessage::Status(Status {
heads: HeadsSummary::of(Vec::new()),
epoch: Epoch::GENESIS,
epoch_seq: 0,
ready: false,
syncs_with_you: false,
leaving: false,
})
}
/// When the preferred transport fails, the same send goes over the next one, and
/// the failed address is ranked last for a while.
#[tokio::test]
async fn a_failed_send_goes_to_the_next_address() {
let net = SimNet::new(3);
let a = Paths::new(
vec![
("broken", Arc::new(Broken) as Arc<dyn Transport>),
("sim", net.transport("a") as Arc<dyn Transport>),
],
None,
None,
Arc::default(),
Duration::ZERO,
);
let b = Arc::new(Paths::new(
vec![("sim", net.transport("b") as Arc<dyn Transport>)],
None,
None,
Arc::default(),
Duration::ZERO,
));
let (sender, mut received) = tokio::sync::mpsc::unbounded_channel();
let handler: Arc<PathHandler> = Arc::new(move |from, _, _| {
let sender = sender.clone();
Box::pin(async move {
let _ = sender.send(from);
Ok(())
})
});
tokio::spawn(async move { b.start_consumer(handler).await });
let addresses = vec!["sim:b".to_owned(), "broken:b".to_owned()];
let ranked = a.rank(&addresses, true);
assert_eq!(ranked, ["broken:b", "sim:b"]); // The configured order.
let mut encoded = a.encode(&ranked[0], &some_status()).unwrap();
encoded.peer = "node-b".to_owned();
assert_eq!(a.send_first(&encoded, &ranked).await.unwrap(), "sim:b");
assert_eq!(received.recv().await.unwrap(), "sim:a");
assert_eq!(a.rank(&addresses, true), ["sim:b", "broken:b"]);
// Without the message kept, nothing else can be tried: the transport's error.
encoded.message = None;
let error = a
.send_first(&encoded, &["broken:b".to_owned()])
.await
.unwrap_err();
assert_eq!(error.to_string(), "broken");
assert!(a.send_first(&encoded, &[]).await.is_err());
}
/// A message sent to an address arrives under the sender's address on that
/// transport.
#[tokio::test]
async fn messages_arrive_under_the_senders_address() {
let (a, b) = two_nets();
let (sender, mut received) = tokio::sync::mpsc::unbounded_channel();
let handler: Arc<PathHandler> = Arc::new(move |from, message, _| {
let sender = sender.clone();
Box::pin(async move {
let _ = sender.send((from, message.kind()));
Ok(())
})
});
tokio::spawn(async move { b.start_consumer(handler).await });
let status = some_status();
for to in ["other:b", "sim:b"] {
let encoded = a.encode(to, &status).unwrap();
assert_eq!(encoded.address, to);
a.send(&encoded).await.unwrap();
}
let mut from: Vec<String> = Vec::new();
for _ in 0..2 {
from.push(received.recv().await.unwrap().0);
}
from.sort();
assert_eq!(from, ["other:a", "sim:a"]);
assert!(a.encode("pigeon:b", &status).is_err());
}
}
|