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
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
use crate::log::{debug, error, info, trace, warn};
use core::future;
use core::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
use core::task::Poll;
use futures_util::{FutureExt, pin_mut, select_biased};
use heapless::{Deque, index_map::FnvIndexMap};
#[cfg(all(test, feature = "client-tokio"))]
use std::sync::{Arc, Mutex};
#[cfg(all(test, feature = "client-tokio"))]
use crate::e2e::E2ERegistry;
#[cfg(all(test, feature = "client-tokio"))]
use crate::tokio_transport::{
TokioBufferProvider, TokioChannels, TokioSpawner, TokioTimer, TokioTransport,
};
use crate::{
Timer,
client::{
ClientUpdate, DiscoveryMessage,
service_registry::{ServiceEndpointInfo, ServiceEndpointKey, ServiceRegistry},
session::{SessionTracker, SessionVerdict, TransportKind},
socket_manager::{ReceivedMessage, SocketManager},
},
protocol::{self, Message},
traits::PayloadWireFormat,
transport::{ChannelFactory, E2ERegistryHandle, MpscRecv, OneshotSend, UnboundedSend},
};
use super::error::Error;
/// Max depth of the internal control-message queue. Each entry is one
/// in-flight `ControlMessage`. Must be generous enough to absorb bursts
/// from `Client` callers between event-loop ticks.
const REQUEST_QUEUE_CAP: usize = 32;
/// Max number of outstanding unicast request-response pairs. Each entry is
/// a `request_id` awaiting a reply. Must be a power of two.
const PENDING_RESPONSES_CAP: usize = 64;
/// Max number of bound unicast sockets tracked by port. Must be a power of
/// two.
const UNICAST_SOCKETS_CAP: usize = 8;
pub enum ControlMessage<P: PayloadWireFormat + 'static, C: ChannelFactory> {
SetInterface(Ipv4Addr, C::OneshotSender<Result<(), Error>>),
BindDiscovery(C::OneshotSender<Result<(), Error>>),
UnbindDiscovery(C::OneshotSender<Result<(), Error>>),
SendSD(
SocketAddrV4,
P::SdHeader,
C::OneshotSender<Result<(), Error>>,
),
AddEndpoint(
ServiceEndpointKey,
u16, // instance_id
u16, // local_port
C::OneshotSender<Result<(), Error>>,
),
RemoveEndpoint(ServiceEndpointKey, C::OneshotSender<Result<(), Error>>),
SendToService {
key: ServiceEndpointKey,
message: Message<P>,
/// Fires when the UDP send completes (or errors on lookup/bind).
send_complete: C::OneshotSender<Result<(), Error>>,
/// Fires when a matching unicast response arrives.
response: C::OneshotSender<Result<P, Error>>,
},
Subscribe {
key: ServiceEndpointKey,
major_version: u8,
ttl: u32,
event_group_id: u16,
client_port: u16,
response: C::OneshotSender<Result<(), Error>>,
},
QueryRebootFlag(C::OneshotSender<Result<crate::protocol::sd::RebootFlag, Error>>),
/// Test-only: force `sd_session_has_wrapped` to simulate the state a
/// long-running client reaches after its SD session counter wraps past
/// `0xFFFF`, without actually sending 65k SD messages. Fires the
/// accompanying oneshot once the mutation is applied.
#[cfg(all(test, feature = "client-tokio"))]
ForceSdSessionWrappedForTest(bool, C::OneshotSender<Result<(), Error>>),
}
impl<P: PayloadWireFormat + 'static, C: ChannelFactory> core::fmt::Debug for ControlMessage<P, C> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::SetInterface(addr, _) => f.debug_tuple("SetInterface").field(addr).finish(),
Self::BindDiscovery(_) => f.write_str("BindDiscovery"),
Self::UnbindDiscovery(_) => f.write_str("UnbindDiscovery"),
Self::SendSD(addr, header, _) => {
f.debug_tuple("SendSD").field(addr).field(header).finish()
}
Self::AddEndpoint(key, instance_id, local_port, _) => f
.debug_tuple("AddEndpoint")
.field(key)
.field(instance_id)
.field(local_port)
.finish(),
Self::RemoveEndpoint(key, _) => f.debug_tuple("RemoveEndpoint").field(key).finish(),
Self::SendToService { key, message, .. } => f
.debug_struct("SendToService")
.field("key", key)
.field("message", message)
.finish_non_exhaustive(),
Self::Subscribe {
key,
event_group_id,
..
} => f
.debug_struct("Subscribe")
.field("key", key)
.field("event_group_id", event_group_id)
.finish_non_exhaustive(),
Self::QueryRebootFlag(_) => f.write_str("QueryRebootFlag"),
#[cfg(all(test, feature = "client-tokio"))]
Self::ForceSdSessionWrappedForTest(b, _) => f
.debug_tuple("ForceSdSessionWrappedForTest")
.field(b)
.finish(),
}
}
}
impl<P, C> ControlMessage<P, C>
where
P: PayloadWireFormat + Send + 'static,
C: ChannelFactory,
Result<(), Error>: crate::transport::OneshotPooled<C>,
Result<P, Error>: crate::transport::OneshotPooled<C>,
Result<crate::protocol::sd::RebootFlag, Error>: crate::transport::OneshotPooled<C>,
{
#[must_use]
pub fn set_interface(interface: Ipv4Addr) -> (C::OneshotReceiver<Result<(), Error>>, Self) {
let (sender, receiver) = C::oneshot();
(receiver, Self::SetInterface(interface, sender))
}
#[must_use]
pub fn bind_discovery() -> (C::OneshotReceiver<Result<(), Error>>, Self) {
let (sender, receiver) = C::oneshot();
(receiver, Self::BindDiscovery(sender))
}
#[must_use]
pub fn unbind_discovery() -> (C::OneshotReceiver<Result<(), Error>>, Self) {
let (sender, receiver) = C::oneshot();
(receiver, Self::UnbindDiscovery(sender))
}
#[must_use]
pub fn send_sd(
socket_addr: SocketAddrV4,
header: P::SdHeader,
) -> (C::OneshotReceiver<Result<(), Error>>, Self) {
let (sender, receiver) = C::oneshot();
(receiver, Self::SendSD(socket_addr, header, sender))
}
#[must_use]
pub fn add_endpoint(
key: ServiceEndpointKey,
instance_id: u16,
local_port: u16,
) -> (C::OneshotReceiver<Result<(), Error>>, Self) {
let (sender, receiver) = C::oneshot();
(
receiver,
Self::AddEndpoint(key, instance_id, local_port, sender),
)
}
#[must_use]
pub fn remove_endpoint(
key: ServiceEndpointKey,
) -> (C::OneshotReceiver<Result<(), Error>>, Self) {
let (sender, receiver) = C::oneshot();
(receiver, Self::RemoveEndpoint(key, sender))
}
#[allow(clippy::type_complexity)]
#[must_use]
pub fn send_to_service(
key: ServiceEndpointKey,
message: Message<P>,
) -> (
C::OneshotReceiver<Result<(), Error>>,
C::OneshotReceiver<Result<P, Error>>,
Self,
) {
let (send_complete_tx, send_complete_rx) = C::oneshot();
let (response_tx, response_rx) = C::oneshot();
(
send_complete_rx,
response_rx,
Self::SendToService {
key,
message,
send_complete: send_complete_tx,
response: response_tx,
},
)
}
#[must_use]
pub fn subscribe(
key: ServiceEndpointKey,
major_version: u8,
ttl: u32,
event_group_id: u16,
client_port: u16,
) -> (C::OneshotReceiver<Result<(), Error>>, Self) {
let (sender, receiver) = C::oneshot();
(
receiver,
Self::Subscribe {
key,
major_version,
ttl,
event_group_id,
client_port,
response: sender,
},
)
}
#[must_use]
pub fn query_reboot_flag() -> (
C::OneshotReceiver<Result<crate::protocol::sd::RebootFlag, Error>>,
Self,
) {
let (sender, receiver) = C::oneshot();
(receiver, Self::QueryRebootFlag(sender))
}
#[cfg(all(test, feature = "client-tokio"))]
#[must_use]
pub fn force_sd_session_wrapped_for_test(
wrapped: bool,
) -> (C::OneshotReceiver<Result<(), Error>>, Self) {
let (sender, receiver) = C::oneshot();
(
receiver,
Self::ForceSdSessionWrappedForTest(wrapped, sender),
)
}
/// Consume this message and notify its oneshot senders with
/// `Error::Capacity(structure_name)` instead of silently dropping them.
///
/// Dropping the senders would let the awaiting `oneshot::Receiver`s
/// resolve to `RecvError`, which the public APIs currently `.unwrap()`
/// — that would panic callers under load. Delivering an explicit
/// `Err(Error::Capacity(..))` turns a would-be panic into a normal
/// `Result` with a stable, descriptive error.
fn reject_with_capacity(self, structure_name: &'static str) {
match self {
Self::SetInterface(_, response)
| Self::BindDiscovery(response)
| Self::UnbindDiscovery(response)
| Self::SendSD(_, _, response)
| Self::AddEndpoint(_, _, _, response)
| Self::RemoveEndpoint(_, response)
| Self::Subscribe { response, .. } => {
let _ = response.send(Err(Error::Capacity(structure_name)));
}
Self::SendToService {
send_complete,
response,
..
} => {
let _ = send_complete.send(Err(Error::Capacity(structure_name)));
let _ = response.send(Err(Error::Capacity(structure_name)));
}
Self::QueryRebootFlag(response) => {
let _ = response.send(Err(Error::Capacity(structure_name)));
}
#[cfg(all(test, feature = "client-tokio"))]
Self::ForceSdSessionWrappedForTest(_, response) => {
let _ = response.send(Err(Error::Capacity(structure_name)));
}
}
}
}
pub(super) struct Inner<
PayloadDefinitions: PayloadWireFormat + 'static,
Tm: Timer,
R: E2ERegistryHandle,
C: ChannelFactory,
D,
> {
/// MPSC Receiver used to receive control messages from outer client
control_receiver: C::BoundedReceiver<ControlMessage<PayloadDefinitions, C>, 4>,
/// Queue of pending control messages to process
request_queue: Deque<ControlMessage<PayloadDefinitions, C>, REQUEST_QUEUE_CAP>,
/// Pending request-responses keyed by `request_id` (`client_id` << 16 | `session_counter`).
/// Set by `SendToService`, cleared when a matching unicast arrives.
pending_responses: FnvIndexMap<
u32,
C::OneshotSender<Result<PayloadDefinitions, Error>>,
PENDING_RESPONSES_CAP,
>,
/// Unbounded sender used to send updates to outer client
update_sender: C::UnboundedSender<ClientUpdate<PayloadDefinitions>>,
/// Target interface for sockets
interface: Ipv4Addr,
/// Socket manager for service discovery if bound (multicast: `INADDR_ANY`
/// + group join; also sends outgoing SD)
discovery_socket: Option<SocketManager<PayloadDefinitions, C>>,
/// Receive-only UNICAST service-discovery socket (interface-IP bound) if
/// bound. Diverts the sensor's unicast SD off `discovery_socket` so the
/// unicast and multicast SD session domains get separate `SessionTracker`
/// keys (prevents interleaved-counter false reboots).
discovery_unicast_socket: Option<SocketManager<PayloadDefinitions, C>>,
/// Socket managers for unicast messages, keyed by local port
unicast_sockets: FnvIndexMap<u16, SocketManager<PayloadDefinitions, C>, UNICAST_SOCKETS_CAP>,
/// Per-sender SD session state for reboot detection
session_tracker: SessionTracker,
/// Registry of known service endpoints (auto-populated from SD + manual)
service_registry: ServiceRegistry,
/// Internal flag to continue run loop
run: bool,
/// Client ID for SOME/IP request headers (upper 16 bits of request ID)
client_id: u16,
/// Incrementing session counter for SOME/IP request headers (lower 16 bits of request ID)
session_counter: u16,
/// SD session state persisted across discovery socket rebinds so that
/// `unbind_discovery` + `bind_discovery` does not emit a false reboot signal.
sd_session_id: u16,
sd_session_has_wrapped: bool,
/// Shared E2E registry for runtime E2E configuration
e2e_registry: R,
/// Enable multicast loopback on SD sockets for same-host testing
multicast_loopback: bool,
/// Bind dispatch — abstracts the bind-and-spawn step over either a
/// [`Spawner`](crate::transport::Spawner) (Send-required) or a
/// [`LocalSpawner`](crate::transport::LocalSpawner) (single-task)
/// path. Holds the [`TransportFactory`](crate::transport::TransportFactory)
/// and the spawner internally; see
/// [`crate::client::bind_dispatch`] for the two impls.
dispatch: D,
/// Async sleep primitive used by the run-loop's idle tick and any
/// future periodic-emission paths. On `client-tokio` builds this is
/// [`TokioTimer`] (which wraps `tokio::time::sleep`).
timer: Tm,
/// Phantom data to represent the generic message definitions
phantom: core::marker::PhantomData<PayloadDefinitions>,
}
impl<P: PayloadWireFormat, Tm: Timer, R: E2ERegistryHandle, C: ChannelFactory, D> core::fmt::Debug
for Inner<P, Tm, R, C, D>
{
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Inner")
.field("interface", &self.interface)
.field("session_tracker", &self.session_tracker)
.field("run", &self.run)
.field("client_id", &self.client_id)
.field("session_counter", &self.session_counter)
.finish_non_exhaustive()
}
}
impl<PayloadDefinitions, Tm, R, C, D> Inner<PayloadDefinitions, Tm, R, C, D>
where
PayloadDefinitions: PayloadWireFormat + Clone + core::fmt::Debug + Send + 'static,
Tm: Timer + 'static,
R: E2ERegistryHandle,
C: ChannelFactory,
D: crate::client::bind_dispatch::BindDispatch<PayloadDefinitions, C, R> + 'static,
// Channel-bound bundle (see comment in `client::mod`).
Result<(), Error>: crate::transport::OneshotPooled<C>,
Result<PayloadDefinitions, Error>: crate::transport::OneshotPooled<C>,
Result<crate::protocol::sd::RebootFlag, Error>: crate::transport::OneshotPooled<C>,
ControlMessage<PayloadDefinitions, C>: crate::transport::BoundedPooled<C, 4>,
super::socket_manager::SendMessage<PayloadDefinitions, C>:
crate::transport::BoundedPooled<C, 16>,
Result<super::socket_manager::ReceivedMessage<PayloadDefinitions>, Error>:
crate::transport::BoundedPooled<C, 16>,
super::ClientUpdate<PayloadDefinitions>: crate::transport::UnboundedPooled<C>,
{
/// Construct an `Inner` and return the control/update channels plus
/// the run-loop future.
///
/// The dispatch is one of [`SpawnerDispatch`] (Send-required) or
/// [`LocalSpawnerDispatch`] (single-task) — the
/// `Client::new_with_deps` / `Client::new_with_deps_local` public
/// constructors pick the right one. The returned future inherits
/// the dispatch's auto-trait set: `Send` if the dispatch is
/// Send-aware and all dependencies are `Send`, `!Send` otherwise.
///
/// [`SpawnerDispatch`]: super::bind_dispatch::SpawnerDispatch
/// [`LocalSpawnerDispatch`]: super::bind_dispatch::LocalSpawnerDispatch
#[allow(clippy::type_complexity)]
pub fn build(
interface: Ipv4Addr,
e2e_registry: R,
multicast_loopback: bool,
dispatch: D,
timer: Tm,
) -> (
C::BoundedSender<ControlMessage<PayloadDefinitions, C>, 4>,
C::UnboundedReceiver<ClientUpdate<PayloadDefinitions>>,
impl core::future::Future<Output = ()> + 'static,
) {
info!("Initializing SOME/IP Client");
let (control_sender, control_receiver) = C::bounded::<_, 4>();
let (update_sender, update_receiver) = C::unbounded();
let inner = Self {
control_receiver,
request_queue: Deque::new(),
pending_responses: FnvIndexMap::new(),
update_sender,
interface,
discovery_socket: None,
discovery_unicast_socket: None,
unicast_sockets: FnvIndexMap::new(),
session_tracker: SessionTracker::default(),
service_registry: ServiceRegistry::default(),
run: true,
client_id: 0x1234,
session_counter: 1,
sd_session_id: 1,
sd_session_has_wrapped: false,
e2e_registry,
multicast_loopback,
dispatch,
timer,
phantom: core::marker::PhantomData,
};
(control_sender, update_receiver, inner.run_future())
}
async fn bind_discovery(&mut self) -> Result<(), Error> {
if self.discovery_socket.is_some() {
Ok(())
} else {
let socket = self
.dispatch
.bind_discovery(
self.interface,
self.e2e_registry.clone(),
self.sd_session_id,
self.sd_session_has_wrapped,
self.multicast_loopback,
)
.await?;
self.discovery_socket = Some(socket);
// Receive-only unicast SD socket bound to the interface IP — see
// `discovery_unicast_socket`. Best-effort: if the unicast bind
// fails, multicast discovery still works (we just lose the
// unicast-domain split), so don't fail the whole bind.
match self
.dispatch
.bind_discovery_unicast(self.interface, self.e2e_registry.clone())
.await
{
Ok(unicast) => self.discovery_unicast_socket = Some(unicast),
Err(e) => error!("Failed to bind unicast discovery socket: {:?}", e),
}
Ok(())
}
}
// Dropping the receiver kills the loop
async fn unbind_discovery(&mut self) {
debug!("Unbinding Discovery socket.");
if let Some(socket) = self.discovery_socket.take() {
self.sd_session_id = socket.session_id();
self.sd_session_has_wrapped =
socket.reboot_flag() == crate::protocol::sd::RebootFlag::Continuous;
socket.shut_down().await;
}
if let Some(socket) = self.discovery_unicast_socket.take() {
socket.shut_down().await;
}
}
fn set_interface(&mut self, interface: Ipv4Addr) {
self.interface = interface;
}
async fn bind_unicast(&mut self, port: u16) -> Result<u16, Error> {
if port != 0
&& let Some(socket) = self.unicast_sockets.get(&port)
{
return Ok(socket.port());
}
// Check capacity before asking the OS for a port so we don't
// bind-then-drop a socket we can't track.
if self.unicast_sockets.len() >= UNICAST_SOCKETS_CAP {
warn!(
"unicast_sockets at capacity ({}); refusing new bind of port {}",
UNICAST_SOCKETS_CAP, port
);
return Err(Error::Capacity("unicast_sockets"));
}
let unicast_socket = self
.dispatch
.bind_unicast(port, self.e2e_registry.clone())
.await?;
let bound_port = unicast_socket.port();
// Capacity was checked above, so insert cannot report "full" here.
// A defensive check guards against a future refactor that changes
// the ordering.
if self
.unicast_sockets
.insert(bound_port, unicast_socket)
.is_err()
{
error!(
"unicast_sockets insert failed after capacity check passed — invariant violation"
);
return Err(Error::Capacity("unicast_sockets"));
}
debug!("Bound unicast socket on port {}", bound_port);
Ok(bound_port)
}
/// Tracks the caller's response channel against `request_id` so a
/// future unicast reply can be routed back. If the
/// `pending_responses` map is already at `PENDING_RESPONSES_CAP`, the
/// `response` sender is recovered from the failed `insert` and used
/// to deliver `Err(Error::Capacity("pending_responses"))` — the
/// caller's `PendingResponse::response().await` resolves cleanly
/// instead of panicking on the `RecvError` that dropping the Sender
/// would have produced. If `request_id` is reused while an older
/// pending entry still exists (e.g. after a `session_counter`
/// wrap-around), the displaced sender is likewise completed with
/// `Err(Error::Capacity("pending_responses"))` rather than being
/// silently dropped — the caller awaiting the previous request
/// sees a clean error instead of a `RecvError` panic. Any reply
/// that later arrives for a dropped `request_id` is surfaced on
/// the update stream via `ClientUpdate::Unicast` instead of
/// matching a pending entry.
fn track_or_reject_pending_response(
&mut self,
request_id: u32,
response: C::OneshotSender<Result<PayloadDefinitions, Error>>,
) {
match self.pending_responses.insert(request_id, response) {
Ok(None) => {}
Ok(Some(displaced_response)) => {
// `request_id` reuse is expected once `session_counter`
// wraps every ~65k requests on a long-lived client, and
// legitimate when the previous request is still pending.
// The displaced sender carries `Error::Capacity` to its
// awaiter; logging at `warn!` per wrap floods ops dashboards
// for a routine event, so demote to `debug!`.
debug!(
"pending_responses already contained request_id \
0x{:08X}; replacing existing pending response",
request_id
);
let _ = displaced_response.send(Err(Error::Capacity("pending_responses")));
}
Err((_req_id, response)) => {
warn!(
"pending_responses at capacity ({}); response tracking \
dropped for request_id 0x{:08X}",
PENDING_RESPONSES_CAP, request_id
);
let _ = response.send(Err(Error::Capacity("pending_responses")));
}
}
}
async fn receive_discovery(
socket_manager: &mut Option<SocketManager<PayloadDefinitions, C>>,
) -> Result<
(
SocketAddr,
protocol::Header,
<PayloadDefinitions as PayloadWireFormat>::SdHeader,
),
Error,
> {
let Some(socket) = socket_manager else {
// If we don't have a receiver, return a future that never resolves
return future::pending().await;
};
let Some(result) = socket.receive().await else {
// Socket loop has exited. Evict the dead manager so
// subsequent polls don't busy-loop on a closed receiver —
// instead they fall through to the `future::pending()`
// arm and wait until the user re-binds discovery (e.g.
// via SetInterface).
*socket_manager = None;
return Err(Error::SocketClosedUnexpectedly);
};
let received = result?;
let someip_header = received.message.header().clone();
if let Some(sd_header) = received.message.sd_header() {
Ok((received.source, someip_header, Clone::clone(sd_header)))
} else {
Err(Error::UnexpectedDiscoveryMessage(someip_header))
}
}
/// Process one received SD datagram: feed every service-instance entry to
/// the reboot [`SessionTracker`] under `transport`, refresh the service
/// registry, and emit `SenderRebooted` / `DiscoveryUpdated`. Shared by the
/// multicast and unicast discovery receive arms so each transport's SD
/// session counter is tracked on its own key — without this split the
/// sensor's interleaved multicast/unicast session counters look like
/// perpetual reboots.
///
/// [`SessionTracker`]: super::session::SessionTracker
#[allow(clippy::too_many_arguments)]
fn handle_discovery_datagram(
source: SocketAddr,
transport: TransportKind,
someip_header: protocol::Header,
sd_header: <PayloadDefinitions as PayloadWireFormat>::SdHeader,
session_tracker: &mut SessionTracker,
service_registry: &mut ServiceRegistry,
e2e_registry: &R,
update_sender: &C::UnboundedSender<ClientUpdate<PayloadDefinitions>>,
) {
// Extract session ID from SOME/IP request_id (lower 16 bits)
let session_id = (someip_header.request_id() & 0xFFFF) as u16;
let sd_payload = PayloadDefinitions::new_sd_payload(&sd_header);
// Extract reboot flag from the SD payload flags
let reboot_flag = sd_payload.sd_flags().map_or(
crate::protocol::sd::RebootFlag::Continuous,
crate::protocol::sd::Flags::reboot,
);
// Track sender session/reboot state for every SD entry that identifies
// a service instance, not only offer/stop-offer entries — keyed per
// transport so multicast and unicast domains don't collide. This
// ensures reboot detection works for all SD traffic (FindService,
// Subscribe, SubscribeAck, etc.).
let mut rebooted = false;
sd_payload.for_each_service_instance(|svc_id, inst_id| {
let verdict =
session_tracker.check(source, transport, svc_id, inst_id, session_id, reboot_flag);
if verdict == SessionVerdict::Reboot {
rebooted = true;
}
});
// Auto-populate service registry from offer/stop-offer SD entries.
sd_payload.for_each_offered_endpoint(|ep| {
// Per AUTOSAR §4.2.1.3 the wire identity of a service
// instance is the service id + the offered socket; the
// instance id is data, stored in the value for use by
// SubscribeEventgroup entries.
let Some(endpoint) = ep.endpoint else {
debug!(
"SD entry for 0x{:04X}.0x{:04X} carried no endpoint option; cannot identify the provider socket, skipping",
ep.service_id, ep.instance_id,
);
return;
};
let key = ServiceEndpointKey {
service_id: ep.service_id,
endpoint,
};
if ep.is_offer {
if service_registry
.insert(
key,
ServiceEndpointInfo {
instance_id: ep.instance_id,
local_port: 0,
major_version: ep.major_version,
minor_version: ep.minor_version,
},
)
.is_ok()
{
trace!(
"Registry: added 0x{:04X} -> {:?} (instance 0x{:04X})",
ep.service_id, endpoint, ep.instance_id,
);
} else {
warn!(
"Registry full; dropped offer for 0x{:04X} at {:?}",
ep.service_id, endpoint,
);
}
} else {
service_registry.remove(key);
trace!(
"Registry: removed 0x{:04X} at {:?}",
ep.service_id, endpoint,
);
}
});
if rebooted {
// A rebooted sender restarts its E2E counter at zero, so drop our
// stored per-source receive state for it; otherwise its first
// post-reboot frame would read as out-of-sequence.
e2e_registry.reset_source(source.ip());
let _ = update_sender.send_now(ClientUpdate::SenderRebooted(source));
}
let discovery_msg = DiscoveryMessage {
source,
someip_header,
sd_header,
};
let _ = update_sender.send_now(ClientUpdate::DiscoveryUpdated(discovery_msg));
}
/// Receive from any bound unicast socket. Returns the first message ready
/// from any socket. If no sockets are bound, returns a future that never resolves.
///
/// A unicast socket whose loop has exited (`poll_receive` returns
/// `Poll::Ready(None)`) is evicted from the map immediately rather
/// than having `Err(SocketClosedUnexpectedly)` returned once per
/// poll forever, which would CPU-pin the run-loop and flood the
/// update stream.
async fn receive_any_unicast(
unicast_sockets: &mut FnvIndexMap<
u16,
SocketManager<PayloadDefinitions, C>,
UNICAST_SOCKETS_CAP,
>,
) -> Result<ReceivedMessage<PayloadDefinitions>, Error> {
if unicast_sockets.is_empty() {
return future::pending().await;
}
core::future::poll_fn(|cx| {
// Collect ports of any sockets that report `Ready(None)`
// (loop has exited). Evict them after the iteration so we
// do not mutate the map while iterating it.
let mut dead_ports: heapless::Vec<u16, UNICAST_SOCKETS_CAP> = heapless::Vec::new();
let mut delivered: Option<Result<ReceivedMessage<PayloadDefinitions>, Error>> = None;
for (port, socket) in unicast_sockets.iter_mut() {
if let Poll::Ready(result) = socket.poll_receive(cx) {
match result {
Some(msg) => {
delivered = Some(msg);
break;
}
None => {
// Mark for eviction; keep scanning others.
let _ = dead_ports.push(*port);
}
}
}
}
for port in &dead_ports {
// Removing the `SocketManager` drops its channel ends, so the
// spawned socket-loop future returns and is dropped. That drop
// releases its `BufferLease` (#125), freeing the pool slot for
// the next bind — no explicit buffer release is needed here.
unicast_sockets.remove(port);
crate::log::warn!("Unicast socket on port {port} closed; evicted from registry");
}
if let Some(msg) = delivered {
Poll::Ready(msg)
} else if unicast_sockets.is_empty() {
// The last socket just got evicted; fall through to a
// pending state so the next bind triggers a fresh poll.
Poll::Pending
} else if !dead_ports.is_empty() {
// At least one socket got evicted but others remain;
// re-poll so the caller observes the next ready event
// promptly instead of waiting on a stale waker.
cx.waker().wake_by_ref();
Poll::Pending
} else {
Poll::Pending
}
})
.await
}
#[allow(clippy::too_many_lines)]
async fn handle_control_message(&mut self) {
if let Some(active_request) = self.request_queue.pop_front() {
match active_request {
ControlMessage::SetInterface(interface, response) => {
if self.discovery_socket.is_some() {
info!(
"Discovery socket currently bound to interface: {}, unbinding.",
self.interface
);
self.unbind_discovery().await;
// Re-enqueue after pop. The slot we popped is free,
// so `push_front` should never fail here — but if a
// future refactor breaks that invariant, reject via
// the capacity path instead of silently dropping the
// response oneshot (matches the primary `push_back`
// overflow arm in the control-channel receiver).
if let Err(rejected) = self
.request_queue
.push_front(ControlMessage::SetInterface(interface, response))
{
error!("request_queue push_front failed after pop — invariant broken");
rejected.reject_with_capacity("request_queue");
}
return;
}
if self.interface != interface {
self.set_interface(interface);
// See re-enqueue note above.
if let Err(rejected) = self
.request_queue
.push_front(ControlMessage::SetInterface(interface, response))
{
error!("request_queue push_front failed after pop — invariant broken");
rejected.reject_with_capacity("request_queue");
}
return;
}
// Reaching here: discovery is not bound AND
// `interface == self.interface`. Do nothing — the
// user expressed no change of intent. Previously
// this branch silently called `bind_discovery()`
// as a side effect, which surprised callers
// probing the current interface via
// `client.set_interface(client.interface()).await`.
debug!("SetInterface: no-op (interface unchanged, discovery not bound)");
if response.send(Ok(())).is_err() {
debug!("SetInterface: caller dropped the response receiver");
}
}
ControlMessage::BindDiscovery(response) => {
let result = self.bind_discovery().await;
if response.send(result).is_err() {
debug!("BindDiscovery: caller dropped the response receiver");
}
}
ControlMessage::UnbindDiscovery(response) => {
self.unbind_discovery().await;
if response.send(Ok(())).is_err() {
debug!("UnbindDiscovery: caller dropped the response receiver");
}
}
ControlMessage::SendSD(target, header, response) => {
// SD Message, If the discovery socket is not bound, bind it
match &mut self.discovery_socket {
None => {
match self.bind_discovery().await {
Ok(()) => {
// See re-enqueue note on SetInterface above.
if let Err(rejected) = self.request_queue.push_front(
ControlMessage::SendSD(target, header, response),
) {
error!(
"request_queue push_front failed after pop — invariant broken"
);
rejected.reject_with_capacity("request_queue");
}
}
Err(e) => {
error!(
"Failed to bind discovery socket for sending SD message: {:?}",
e
);
if response.send(Err(e)).is_err() {
debug!(
"SendSD (bind-err path): caller dropped the response receiver"
);
}
}
}
}
Some(discovery_socket) => {
let message = Message::<PayloadDefinitions>::new_sd(
u32::from(discovery_socket.session_id()),
&header,
);
debug!("Sending {:?} to {}", &message, target);
let send_result = self
.discovery_socket
.as_mut()
.unwrap()
.send(target, message)
.await;
if response.send(send_result).is_err() {
debug!("SendSD: caller dropped the response receiver");
}
}
}
}
ControlMessage::AddEndpoint(key, instance_id, local_port, response) => {
let insert_result = self.service_registry.insert(
key,
ServiceEndpointInfo {
instance_id,
local_port,
major_version: 0xFF,
minor_version: 0xFFFF_FFFF,
},
);
let outcome = if insert_result.is_ok() {
debug!(
"Added endpoint for service 0x{:04X} -> {:?}",
key.service_id, key.endpoint,
);
Ok(())
} else {
warn!(
"service_registry at capacity ({}); cannot add 0x{:04X} at {:?}",
crate::client::service_registry::SERVICE_REGISTRY_CAP,
key.service_id,
key.endpoint,
);
Err(Error::Capacity("service_registry"))
};
if response.send(outcome).is_err() {
debug!("AddEndpoint: caller dropped the response receiver");
}
}
ControlMessage::RemoveEndpoint(key, response) => {
self.service_registry.remove(key);
debug!(
"Removed endpoint for service 0x{:04X} at {:?}",
key.service_id, key.endpoint,
);
if response.send(Ok(())).is_err() {
debug!("RemoveEndpoint: caller dropped the response receiver");
}
}
ControlMessage::SendToService {
key,
mut message,
send_complete,
response,
} => {
let Some(endpoint_info) = self.service_registry.get(key) else {
let _ = send_complete.send(Err(Error::ServiceNotFound));
return;
};
let desired_port = endpoint_info.local_port;
// The send target is the key's endpoint; today's
// transports are IPv4 + UDP only.
let (SocketAddr::V4(target), crate::TransportProtocol::Udp) =
(key.endpoint.addr, key.endpoint.protocol)
else {
let _ = send_complete.send(Err(Error::UnsupportedEndpoint(key.endpoint)));
return;
};
let source_port = if desired_port == 0 {
// Ephemeral: auto-bind only if no sockets exist, then use first
if self.unicast_sockets.is_empty() {
match self.bind_unicast(0).await {
Ok(port) => {
debug!("Auto-bound unicast on port {} for SendToService", port);
port
}
Err(e) => {
let _ = send_complete.send(Err(e));
return;
}
}
} else {
*self.unicast_sockets.keys().next().unwrap()
}
} else {
// Specific port: bind if not already bound
match self.bind_unicast(desired_port).await {
Ok(port) => port,
Err(e) => {
let _ = send_complete.send(Err(e));
return;
}
}
};
let socket = self.unicast_sockets.get_mut(&source_port).unwrap();
// Stamp request ID with the CURRENT session counter,
// but only advance it on successful send. A failed
// send should not chew through the 16-bit session
// space — under transient transport failure that
// could wrap toward in-flight pending_responses
// far faster than expected.
let request_id =
(u32::from(self.client_id) << 16) | u32::from(self.session_counter);
message.set_request_id(request_id);
let send_result = socket.send(target, message).await;
match send_result {
Ok(()) => {
// Advance the counter only after a real
// wire transmission. Skip 0 on wrap.
self.session_counter = self.session_counter.wrapping_add(1);
if self.session_counter == 0 {
self.session_counter = 1;
}
let _ = send_complete.send(Ok(()));
self.track_or_reject_pending_response(request_id, response);
}
Err(e) => {
let _ = send_complete.send(Err(e));
}
}
}
#[cfg(all(test, feature = "client-tokio"))]
ControlMessage::ForceSdSessionWrappedForTest(wrapped, response) => {
self.sd_session_has_wrapped = wrapped;
let _ = response.send(Ok(()));
}
ControlMessage::QueryRebootFlag(response) => {
// Prefer the live socket's tracked flag when bound. When
// unbound, fall back to `sd_session_has_wrapped`, which
// persists wrap state across unbind/rebind (updated in
// `unbind_discovery` from the socket manager before it's
// dropped). Without this fallback, a long-running client
// that wraps past 0xFFFF and then unbinds discovery
// would erroneously revert to `RecentlyRebooted` on the
// next `reboot_flag()` call.
let flag = if let Some(socket) = self.discovery_socket.as_ref() {
socket.reboot_flag()
} else if self.sd_session_has_wrapped {
crate::protocol::sd::RebootFlag::Continuous
} else {
crate::protocol::sd::RebootFlag::RecentlyRebooted
};
if response.send(Ok(flag)).is_err() {
debug!("QueryRebootFlag: caller dropped the response receiver");
}
}
ControlMessage::Subscribe {
key,
major_version,
ttl,
event_group_id,
client_port,
response,
} => {
// Look up endpoint from service registry; the
// instance id travels in the value ([PRS_SOMEIP_00162])
// but SubscribeEventgroup entries carry it on the wire.
let Some(reg) = self.service_registry.get(key) else {
if response.send(Err(Error::ServiceNotFound)).is_err() {
debug!(
"Subscribe (ServiceNotFound): caller dropped the response receiver (expected for subscribe_no_wait)"
);
}
return;
};
let instance_id = reg.instance_id;
// Subscribes go to the provider's socket; today's
// transports are IPv4 + UDP only.
let (SocketAddr::V4(provider), crate::TransportProtocol::Udp) =
(key.endpoint.addr, key.endpoint.protocol)
else {
let _ = response.send(Err(Error::UnsupportedEndpoint(key.endpoint)));
return;
};
// Bind unicast on the requested port (0 = ephemeral)
let unicast_port = match self.bind_unicast(client_port).await {
Ok(port) => {
debug!("Bound unicast on port {} for Subscribe", port);
port
}
Err(e) => {
if response.send(Err(e)).is_err() {
debug!(
"Subscribe (bind-err): caller dropped the response receiver"
);
}
return;
}
};
// Auto-bind discovery if not bound (re-queue like SendSD does)
match &mut self.discovery_socket {
None => match self.bind_discovery().await {
Ok(()) => {
// Re-enqueue the Subscribe carrying the
// ALREADY-bound `unicast_port` so pass-2
// hits the `bind_unicast` dedupe path
// instead of allocating a second
// ephemeral socket. Carrying the
// original `client_port=0` would
// re-bind ephemerally and leak the
// original socket into
// `unicast_sockets` until the slot cap
// hit.
if let Err(rejected) =
self.request_queue.push_front(ControlMessage::Subscribe {
key,
major_version,
ttl,
event_group_id,
client_port: unicast_port,
response,
})
{
error!(
"request_queue push_front failed after pop — invariant broken"
);
rejected.reject_with_capacity("request_queue");
}
}
Err(e) => {
if response.send(Err(e)).is_err() {
debug!(
"Subscribe (discovery-bind-err): caller dropped the response receiver"
);
}
}
},
Some(discovery_socket) => {
let sd_header = PayloadDefinitions::new_subscription_sd_header(
key.service_id,
instance_id,
major_version,
ttl,
event_group_id,
self.interface,
crate::protocol::sd::TransportProtocol::Udp,
unicast_port,
discovery_socket.reboot_flag(),
);
let session_id = u32::from(discovery_socket.session_id());
let message =
Message::<PayloadDefinitions>::new_sd(session_id, &sd_header);
let target =
SocketAddrV4::new(*provider.ip(), protocol::sd::MULTICAST_PORT);
debug!("Sending Subscribe {:?} to {}", &message, target);
let send_result = self
.discovery_socket
.as_mut()
.unwrap()
.send(target, message)
.await;
if response.send(send_result).is_err() {
debug!(
"Subscribe: caller dropped the response receiver (expected for subscribe_no_wait)"
);
}
}
}
}
}
}
}
#[allow(clippy::too_many_lines)]
async fn run_future(mut self) {
info!("SOME/IP Client processing loop started");
loop {
// Scope the `&mut self` destructure + pinned per-iteration
// futures so all borrows of `self` drop before we call
// `self.handle_control_message().await` below. `pin_mut!`
// creates stack-pinned locals that outlive the select
// macro, so the inner block is required to release those
// borrows.
let should_break = {
let Self {
control_receiver,
pending_responses,
discovery_socket,
discovery_unicast_socket,
unicast_sockets,
update_sender,
request_queue,
session_tracker,
service_registry,
e2e_registry,
run,
timer,
..
} = &mut self;
// Build fresh per-iteration futures and fuse them for
// `select!`'s `FusedFuture + Unpin` bound.
// `receive_discovery` / `receive_any_unicast` are
// async fns that are not `Unpin`; the `Timer::sleep`
// future likewise. Stack-pinning via `pin_mut!`
// satisfies both.
//
// The 125ms idle tick goes through the caller-supplied
// `Timer` impl. On `client-tokio` builds this is
// `TokioTimer` (wrapping `tokio::time::sleep`); bare-metal
// builds plug in their own (e.g. an `embassy_time` shim).
let control_fut = control_receiver.recv().fuse();
let sleep_fut = timer.sleep(core::time::Duration::from_millis(125)).fuse();
let discovery_fut = Self::receive_discovery(discovery_socket).fuse();
let discovery_unicast_fut =
Self::receive_discovery(discovery_unicast_socket).fuse();
let unicast_fut = Self::receive_any_unicast(unicast_sockets).fuse();
pin_mut!(
control_fut,
sleep_fut,
discovery_fut,
discovery_unicast_fut,
unicast_fut
);
// `select_biased!` (rather than `select!`) because
// futures-util's pseudo-random `select!` requires
// `std`. Top-down arm priority is intentional here:
// `control_fut` sits first because control messages
// drive loop lifecycle (shutdown, queue submissions)
// and dropping them on the floor would deadlock the
// caller's request path. Beyond control, the order
// is `sleep_fut → discovery_fut → unicast_fut`; the
// sleep arm is a 125 ms tick so it can't drive
// sustained pressure, and discovery (multicast SD)
// is bursty enough that unicast is not at real risk
// of starvation in practice. If a future workload
// proves otherwise, the per-iteration arm-flip
// pattern used in `socket_manager`'s send/recv
// select can be lifted here too.
select_biased! {
// Receive a control message
ctrl = control_fut => {
if let Some(ctrl) = ctrl {
debug!("Received control message: {:?}", ctrl);
if let Err(rejected) = request_queue.push_back(ctrl) {
// Queue full: notify the rejected message's
// oneshot senders with `Error::Capacity` so
// callers see a typed overload error rather
// than a `RecvError` (which `client::mod`
// maps to `Error::Shutdown`, conflating
// overload with lifecycle failure).
warn!(
"request_queue at capacity ({}); rejecting control message with Capacity error",
REQUEST_QUEUE_CAP
);
rejected.reject_with_capacity("request_queue");
}
} else {
// The sender has been dropped, so we should exit
*run = false;
}
}
() = sleep_fut => {}
// Receive a discovery message
discovery = discovery_fut => {
trace!("Received discovery message: {:?}", discovery);
match discovery {
Ok((source, someip_header, sd_header)) => {
Self::handle_discovery_datagram(
source,
TransportKind::Multicast,
someip_header,
sd_header,
session_tracker,
service_registry,
e2e_registry,
update_sender,
);
}
Err(err) => {
error!("Error receiving discovery message: {:?}", err);
let _ = update_sender.send_now(ClientUpdate::Error(err));
}
}
}
// Unicast SD arrives on the interface-IP-bound socket (the
// sensor's separate unicast SD session domain).
unicast_discovery = discovery_unicast_fut => {
trace!("Received unicast discovery message: {:?}", unicast_discovery);
match unicast_discovery {
Ok((source, someip_header, sd_header)) => {
Self::handle_discovery_datagram(
source,
TransportKind::Unicast,
someip_header,
sd_header,
session_tracker,
service_registry,
e2e_registry,
update_sender,
);
}
Err(err) => {
error!("Error receiving unicast discovery message: {:?}", err);
let _ = update_sender.send_now(ClientUpdate::Error(err));
}
}
}
unicast = unicast_fut => {
trace!("Received unicast message: {:?}", unicast);
match unicast {
Ok(received) => {
let ReceivedMessage { message: received_message, e2e_status, source } = received;
// Check if this matches a pending request-response by request_id
let request_id = received_message.header().request_id();
if let Some(sender) = pending_responses.remove(&request_id) {
let _ = sender.send(Ok(received_message.payload().clone()));
continue;
}
// Not a response — forward as ClientUpdate::Unicast
let _ = update_sender.send_now(ClientUpdate::Unicast { message: received_message, e2e_status, source });
}
Err(err) => {
let _ = update_sender.send_now(ClientUpdate::Error(err));
}
}
}
}
!*run
};
if should_break {
info!("SOME/IP Client processing loop exiting");
break;
}
self.handle_control_message().await;
}
}
}
#[cfg(all(test, feature = "client-tokio"))]
mod tests {
use super::*;
use crate::protocol::sd::test_support::{TestPayload, empty_sd_header};
use crate::transport::{OneshotRecv, UnboundedRecv};
use std::format;
use tokio::sync::mpsc::Sender;
use tokio::sync::{mpsc, oneshot};
type TestControl = ControlMessage<TestPayload, TokioChannels>;
/// UDP key on `LOCALHOST:port`. The behavioral tests register their
/// endpoint at `LOCALHOST:5000`, so lookups use `lh_key(_, 5000)` to
/// hit the same socket key.
fn lh_key(service: u16, port: u16) -> ServiceEndpointKey {
ServiceEndpointKey::udp(
service,
SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, port)),
)
}
/// Type alias for the fully-spelled `Inner` flavor used throughout
/// these tests: tokio everything, default `Arc<Mutex<E2ERegistry>>`
/// and `Arc<RwLock<Ipv4Addr>>` handles.
type TestInner = Inner<
TestPayload,
crate::tokio_transport::TokioTimer,
Arc<Mutex<E2ERegistry>>,
TokioChannels,
crate::client::bind_dispatch::SpawnerDispatch<
crate::tokio_transport::TokioTransport,
TokioSpawner,
crate::tokio_transport::TokioBufferProvider,
>,
>;
#[test]
fn test_control_message_constructors() {
// Each constructor returns (oneshot::Receiver, ControlMessage)
let (_rx, msg) = TestControl::set_interface(Ipv4Addr::LOCALHOST);
assert!(matches!(msg, ControlMessage::SetInterface(..)));
let (_rx, msg) = TestControl::bind_discovery();
assert!(matches!(msg, ControlMessage::BindDiscovery(..)));
let (_rx, msg) = TestControl::unbind_discovery();
assert!(matches!(msg, ControlMessage::UnbindDiscovery(..)));
let target = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 1234);
let sd_header = empty_sd_header();
let (_rx, msg) = TestControl::send_sd(target, sd_header);
assert!(matches!(msg, ControlMessage::SendSD(..)));
let addr = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 5000);
let (_rx, msg) = TestControl::add_endpoint(
ServiceEndpointKey::udp(0x1234, SocketAddr::V4(addr)),
0x0001,
0,
);
assert!(matches!(msg, ControlMessage::AddEndpoint(..)));
let (_rx, msg) = TestControl::remove_endpoint(lh_key(0x1234, 5000));
assert!(matches!(msg, ControlMessage::RemoveEndpoint(..)));
let message = Message::<TestPayload>::new_sd(1, &empty_sd_header());
let (_send_rx, _resp_rx, msg) = TestControl::send_to_service(lh_key(0x1234, 5000), message);
assert!(matches!(msg, ControlMessage::SendToService { .. }));
let (_rx, msg) = TestControl::subscribe(lh_key(0x1234, 5000), 1, 3, 0x01, 0);
assert!(matches!(msg, ControlMessage::Subscribe { .. }));
}
/// `reject_with_capacity` must notify every oneshot sender inside a
/// rejected `ControlMessage` with `Err(Error::Capacity(..))` — for
/// `SendToService`, _both_ the `send_complete` and `response`
/// channels. Dropping either channel would let a caller's `.unwrap()`
/// (or `.expect(...)` inside `PendingResponse::response()`) panic on
/// the resulting `RecvError`, which is exactly what Copilot flagged.
#[test]
fn reject_with_capacity_notifies_every_sender() {
use crate::transport::OneshotCancelled;
use futures_util::FutureExt;
fn expect_capacity<F>(rx: F, label: &str)
where
F: core::future::Future<Output = Result<Result<(), Error>, OneshotCancelled>>,
{
match rx.now_or_never() {
Some(Ok(Err(Error::Capacity(s)))) => assert_eq!(s, "request_queue", "{label}"),
other => panic!("{label}: expected Some(Ok(Err(Capacity))), got {other:?}"),
}
}
// Variants carrying a single Result<(), Error> response sender.
let (rx, msg) = TestControl::set_interface(Ipv4Addr::LOCALHOST);
msg.reject_with_capacity("request_queue");
expect_capacity(rx.recv(), "SetInterface");
let (rx, msg) = TestControl::bind_discovery();
msg.reject_with_capacity("request_queue");
expect_capacity(rx.recv(), "BindDiscovery");
let (rx, msg) = TestControl::unbind_discovery();
msg.reject_with_capacity("request_queue");
expect_capacity(rx.recv(), "UnbindDiscovery");
let target = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 1234);
let (rx, msg) = TestControl::send_sd(target, empty_sd_header());
msg.reject_with_capacity("request_queue");
expect_capacity(rx.recv(), "SendSD");
let addr = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 5000);
let (rx, msg) = TestControl::add_endpoint(
ServiceEndpointKey::udp(0x1234, SocketAddr::V4(addr)),
0x0001,
0,
);
msg.reject_with_capacity("request_queue");
expect_capacity(rx.recv(), "AddEndpoint");
let (rx, msg) = TestControl::remove_endpoint(lh_key(0x1234, 5000));
msg.reject_with_capacity("request_queue");
expect_capacity(rx.recv(), "RemoveEndpoint");
let (rx, msg) = TestControl::subscribe(lh_key(0x1234, 5000), 1, 3, 0x01, 0);
msg.reject_with_capacity("request_queue");
expect_capacity(rx.recv(), "Subscribe");
// SendToService carries two senders — both must be notified so that
// neither `send_rx.recv().await.unwrap()?` nor `PendingResponse::response()`
// panics.
let message = Message::<TestPayload>::new_sd(1, &empty_sd_header());
let (send_rx, resp_rx, msg) = TestControl::send_to_service(lh_key(0x1234, 5000), message);
msg.reject_with_capacity("request_queue");
expect_capacity(send_rx.recv(), "SendToService.send_complete");
// resp_rx has type Result<TestPayload, Error> — check it separately
match resp_rx.recv().now_or_never() {
Some(Ok(Err(Error::Capacity(s)))) => {
assert_eq!(s, "request_queue", "SendToService.response");
}
other => {
panic!("SendToService.response: expected Some(Ok(Err(Capacity))), got {other:?}")
}
}
}
#[test]
fn test_control_message_debug() {
let (_rx, msg) = TestControl::set_interface(Ipv4Addr::LOCALHOST);
let s = format!("{msg:?}");
assert!(s.contains("SetInterface"));
let (_rx, msg) = TestControl::bind_discovery();
assert!(!format!("{msg:?}").is_empty());
let (_rx, msg) = TestControl::unbind_discovery();
assert!(format!("{msg:?}").contains("UnbindDiscovery"));
let target = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 1234);
let sd_header = empty_sd_header();
let (_rx, msg) = TestControl::send_sd(target, sd_header);
assert!(format!("{msg:?}").contains("SendSD"));
let addr = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 5000);
let (_rx, msg) = TestControl::add_endpoint(
ServiceEndpointKey::udp(0x1234, SocketAddr::V4(addr)),
0x0001,
0,
);
let s = format!("{msg:?}");
assert!(s.contains("AddEndpoint"));
let (_rx, msg) = TestControl::remove_endpoint(lh_key(0x1234, 5000));
let s = format!("{msg:?}");
assert!(s.contains("RemoveEndpoint"));
let message = Message::<TestPayload>::new_sd(1, &empty_sd_header());
let (_send_rx, _resp_rx, msg) = TestControl::send_to_service(lh_key(0x1234, 5000), message);
let s = format!("{msg:?}");
assert!(s.contains("SendToService"));
assert!(s.contains("service_id"));
assert!(s.contains("endpoint"));
let (_rx, msg) = TestControl::subscribe(lh_key(0x1234, 5000), 1, 3, 0x01, 0);
let s = format!("{msg:?}");
assert!(s.contains("Subscribe"));
assert!(s.contains("service_id"));
assert!(s.contains("event_group_id"));
}
/// Build an [`Inner`] without spawning the run loop, for direct
/// unit-testing of state-mutating methods.
fn make_inner_for_test() -> TestInner {
let (_control_sender, control_receiver) =
TokioChannels::bounded::<ControlMessage<TestPayload, TokioChannels>, 4>();
let (update_sender, _update_receiver) =
TokioChannels::unbounded::<ClientUpdate<TestPayload>>();
Inner {
control_receiver,
request_queue: Deque::new(),
pending_responses: FnvIndexMap::new(),
update_sender,
interface: Ipv4Addr::LOCALHOST,
discovery_socket: None,
discovery_unicast_socket: None,
unicast_sockets: FnvIndexMap::new(),
session_tracker: SessionTracker::default(),
service_registry: ServiceRegistry::default(),
run: true,
client_id: 0x1234,
session_counter: 1,
sd_session_id: 1,
sd_session_has_wrapped: false,
e2e_registry: Arc::new(Mutex::new(E2ERegistry::new())),
multicast_loopback: false,
dispatch: crate::client::bind_dispatch::SpawnerDispatch {
factory: TokioTransport,
spawner: TokioSpawner,
buffer_provider: TokioBufferProvider::new(),
},
timer: TokioTimer,
phantom: core::marker::PhantomData,
}
}
#[tokio::test]
async fn bind_unicast_returns_capacity_error_when_map_full() {
let mut inner = make_inner_for_test();
// Fill unicast_sockets to capacity using ephemeral binds (port 0).
// Each call with port=0 creates a fresh socket on a distinct OS-chosen
// port, so the cap is what gates — not duplicate-key collapse.
for _ in 0..UNICAST_SOCKETS_CAP {
let bound = inner
.bind_unicast(0)
.await
.expect("ephemeral bind below cap should succeed");
assert_ne!(bound, 0, "OS should assign a non-zero ephemeral port");
}
assert_eq!(inner.unicast_sockets.len(), UNICAST_SOCKETS_CAP);
// The next bind must fail with Error::Capacity and must NOT bind a
// socket (pre-bind capacity check).
let err = inner
.bind_unicast(0)
.await
.expect_err("bind past cap should fail");
match err {
Error::Capacity(name) => assert_eq!(name, "unicast_sockets"),
other => panic!("expected Error::Capacity, got {other:?}"),
}
assert_eq!(
inner.unicast_sockets.len(),
UNICAST_SOCKETS_CAP,
"map should remain at capacity, not bind-then-drop a new socket"
);
}
/// Happy path: with room in `pending_responses`, the helper tracks
/// the entry and does NOT signal the caller — the sender stays
/// alive so a future unicast reply can resolve it.
#[tokio::test]
async fn track_or_reject_pending_response_inserts_when_room_available() {
use futures_util::FutureExt;
let mut inner = make_inner_for_test();
let (tx, rx) = oneshot::channel::<Result<TestPayload, Error>>();
inner.track_or_reject_pending_response(0xDEAD_BEEF, tx);
assert_eq!(inner.pending_responses.len(), 1);
assert!(
inner.pending_responses.contains_key(&0xDEAD_BEEF),
"entry should be keyed by the provided request_id",
);
// Receiver is still waiting — helper did NOT pre-emptively
// resolve it with a capacity error on the happy path.
assert!(
rx.now_or_never().is_none(),
"receiver must still be pending when the insert succeeds",
);
}
/// Regression guard against cb1d0d1: without explicit rejection,
/// the dropped Sender would cause `PendingResponse::response()` to
/// panic on `RecvError` rather than returning a clean
/// `Err(Error::Capacity("pending_responses"))`. Exercises the
/// overflow branch in `track_or_reject_pending_response`, which is
/// the same branch the `SendToService` run-loop arm now delegates
/// to.
#[tokio::test]
async fn track_or_reject_pending_response_rejects_on_saturation() {
let mut inner = make_inner_for_test();
// Fill the map to capacity with dummy oneshot senders. The
// receivers are stashed to keep each channel open for the
// remainder of the test — on `tokio::sync::oneshot`, dropping
// the receiver does not drop the sender; it flips the sender
// into a state where `send()` fails with the value returned.
// The stash is what lets us later observe `sender.send(...)`
// succeeding against a still-open channel when the overflow
// case completes the displaced sender with a capacity error.
let mut stashed: std::vec::Vec<oneshot::Receiver<Result<TestPayload, Error>>> =
std::vec::Vec::with_capacity(PENDING_RESPONSES_CAP);
for i in 0..PENDING_RESPONSES_CAP {
let (tx, rx) = oneshot::channel::<Result<TestPayload, Error>>();
inner
.pending_responses
.insert(
u32::try_from(i).expect("PENDING_RESPONSES_CAP fits in u32"),
tx,
)
.expect("filling under cap must succeed");
stashed.push(rx);
}
assert_eq!(inner.pending_responses.len(), PENDING_RESPONSES_CAP);
// One more entry — map is full, the helper must recover the
// sender from the failed insert and deliver an explicit
// capacity error on it.
let (overflow_tx, overflow_rx) = oneshot::channel::<Result<TestPayload, Error>>();
let overflow_key: u32 = 0xFFFF_FFFE;
inner.track_or_reject_pending_response(overflow_key, overflow_tx);
// Map size unchanged — the overflow attempt was rejected, not
// silently dropping an existing entry.
assert_eq!(
inner.pending_responses.len(),
PENDING_RESPONSES_CAP,
"overflow must not evict existing entries",
);
assert!(
!inner.pending_responses.contains_key(&overflow_key),
"overflowed key must not be in the map",
);
// The caller's receiver resolves to Err(Capacity), not a
// panicking RecvError — this is the invariant cb1d0d1 fixes.
let result = overflow_rx
.await
.expect("receiver should get the explicit Err, not RecvError from dropped Sender");
match result {
Err(Error::Capacity(tag)) => assert_eq!(tag, "pending_responses"),
other => panic!("expected Err(Error::Capacity(\"pending_responses\")), got {other:?}"),
}
}
/// If a `request_id` is reused while an older pending entry is still
/// live (e.g. `session_counter` wrap-around), `insert` returns
/// `Ok(Some(old_sender))`. Without handling that case, the displaced
/// sender is dropped and the caller awaiting the original request
/// hits `RecvError` (which `PendingResponse::response()` treats as a
/// fatal panic). This test guards against that: the displaced
/// sender must be completed with
/// `Err(Error::Capacity("pending_responses"))` so the original
/// caller gets a clean `Result` instead of a panicking `RecvError`.
#[tokio::test]
async fn track_or_reject_pending_response_completes_displaced_sender() {
use futures_util::FutureExt;
let mut inner = make_inner_for_test();
let key: u32 = 0xCAFE_F00D;
// First tracking: the sender lives in the map.
let (first_tx, first_rx) = oneshot::channel::<Result<TestPayload, Error>>();
inner.track_or_reject_pending_response(key, first_tx);
assert_eq!(inner.pending_responses.len(), 1);
// Second tracking with the same key: displaces the first sender.
let (second_tx, second_rx) = oneshot::channel::<Result<TestPayload, Error>>();
inner.track_or_reject_pending_response(key, second_tx);
// Map still has one entry — the second one replaced the first.
assert_eq!(inner.pending_responses.len(), 1);
assert!(inner.pending_responses.contains_key(&key));
// The original caller's receiver resolves to Err(Capacity) — not
// a dropped-sender RecvError.
let displaced_result = first_rx.await.expect(
"displaced sender must be completed with a real Err, \
not dropped (which would produce RecvError)",
);
match displaced_result {
Err(Error::Capacity(tag)) => assert_eq!(tag, "pending_responses"),
other => {
panic!("expected Err(Error::Capacity(\\\"pending_responses\\\")), got {other:?}")
}
}
// The new sender is still live and pending.
assert!(
second_rx.now_or_never().is_none(),
"replacement sender must still be pending in the map",
);
}
/// Sibling to `client_new_with_spawner_routes_socket_spawns_through_it`
/// in `mod.rs`, which covers the `bind_discovery` path. This one
/// covers `bind_unicast`: each successful ephemeral unicast bind
/// must submit exactly one future through the injected `Spawner`.
/// Without this test, a future refactor could silently revert the
/// unicast bind path to direct `tokio::spawn` and only the
/// discovery path's test would fail to catch it.
#[tokio::test]
async fn bind_unicast_routes_through_injected_spawner() {
use core::sync::atomic::{AtomicUsize, Ordering};
#[derive(Clone)]
struct CountingSpawner {
count: Arc<AtomicUsize>,
}
impl crate::transport::Spawner for CountingSpawner {
fn spawn(&self, future: impl core::future::Future<Output = ()> + Send + 'static) {
self.count.fetch_add(1, Ordering::SeqCst);
// Delegate so the socket loop actually runs — matters
// if the caller later issues a send that awaits the
// loop's oneshot ack. For the pure-spawn-count
// assertion below it would also work to drop the
// future; we delegate to keep the Inner in a healthy
// state in case assertion ordering changes.
drop(tokio::spawn(future));
}
}
let count = Arc::new(AtomicUsize::new(0));
let spawner = CountingSpawner {
count: Arc::clone(&count),
};
// Build Inner directly with the counting spawner — same pattern
// as `make_inner_for_test`, but parameterized on S.
let (_control_sender, control_receiver) = mpsc::channel(4);
let (update_sender, _update_receiver) = mpsc::unbounded_channel();
let mut inner: Inner<
TestPayload,
TokioTimer,
Arc<Mutex<E2ERegistry>>,
TokioChannels,
crate::client::bind_dispatch::SpawnerDispatch<
TokioTransport,
CountingSpawner,
TokioBufferProvider,
>,
> = Inner {
control_receiver,
request_queue: Deque::new(),
pending_responses: FnvIndexMap::new(),
update_sender,
interface: Ipv4Addr::LOCALHOST,
discovery_socket: None,
discovery_unicast_socket: None,
unicast_sockets: FnvIndexMap::new(),
session_tracker: SessionTracker::default(),
service_registry: ServiceRegistry::default(),
run: true,
client_id: 0x1234,
session_counter: 1,
sd_session_id: 1,
sd_session_has_wrapped: false,
e2e_registry: Arc::new(Mutex::new(E2ERegistry::new())),
multicast_loopback: false,
dispatch: crate::client::bind_dispatch::SpawnerDispatch {
factory: TokioTransport,
spawner,
buffer_provider: TokioBufferProvider::new(),
},
timer: TokioTimer,
phantom: core::marker::PhantomData,
};
// Three ephemeral binds → three distinct socket loops spawned.
for i in 0..3 {
let bound = inner
.bind_unicast(0)
.await
.expect("ephemeral bind should succeed");
assert_ne!(bound, 0, "iteration {i}: OS should assign a port");
}
assert_eq!(
count.load(Ordering::SeqCst),
3,
"expected exactly three spawns (one per bind_unicast call), got {}",
count.load(Ordering::SeqCst)
);
}
#[tokio::test]
async fn test_inner_build_and_shutdown() {
let (control_sender, mut update_receiver, run_fut) = TestInner::build(
Ipv4Addr::LOCALHOST,
Arc::new(Mutex::new(E2ERegistry::new())),
false,
crate::client::bind_dispatch::SpawnerDispatch {
factory: TokioTransport,
spawner: TokioSpawner,
buffer_provider: TokioBufferProvider::new(),
},
TokioTimer,
);
let _run_handle = tokio::spawn(run_fut);
// Drop control sender to trigger loop exit
drop(control_sender);
// The update receiver should eventually return None when the inner loop exits
let result = tokio::time::timeout(
std::time::Duration::from_secs(2),
UnboundedRecv::recv(&mut update_receiver),
)
.await;
assert!(result.is_ok());
assert!(result.unwrap().is_none());
}
/// Helper: verify inner loop is still alive by sending an `AddEndpoint` and
/// checking that a response arrives within 2 seconds.
async fn assert_inner_alive(
control_sender: &Sender<ControlMessage<TestPayload, TokioChannels>>,
) {
let addr = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 9999);
let (rx, msg) = TestControl::add_endpoint(
ServiceEndpointKey::udp(0xFFFE, SocketAddr::V4(addr)),
0xFFFE,
0,
);
control_sender.send(msg).await.unwrap();
let result = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
.await
.expect("Timed out — inner loop appears dead")
.expect("Oneshot closed — inner loop appears dead");
assert!(result.is_ok());
}
// -- Dropped-receiver robustness tests --
// These verify that dropping the oneshot receiver before the inner loop
// sends its response does NOT kill the processing loop (the `warn!`
// paths that replaced `self.run = false`).
#[tokio::test]
async fn test_dropped_receiver_bind_discovery_continues() {
let (control_sender, _update_receiver, run_fut) = TestInner::build(
Ipv4Addr::LOCALHOST,
Arc::new(Mutex::new(E2ERegistry::new())),
false,
crate::client::bind_dispatch::SpawnerDispatch {
factory: TokioTransport,
spawner: TokioSpawner,
buffer_provider: TokioBufferProvider::new(),
},
TokioTimer,
);
let _run_handle = tokio::spawn(run_fut);
let (rx, msg) = TestControl::bind_discovery();
drop(rx);
control_sender.send(msg).await.unwrap();
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
assert_inner_alive(&control_sender).await;
}
#[tokio::test]
async fn test_dropped_receiver_unbind_discovery_continues() {
let (control_sender, _update_receiver, run_fut) = TestInner::build(
Ipv4Addr::LOCALHOST,
Arc::new(Mutex::new(E2ERegistry::new())),
false,
crate::client::bind_dispatch::SpawnerDispatch {
factory: TokioTransport,
spawner: TokioSpawner,
buffer_provider: TokioBufferProvider::new(),
},
TokioTimer,
);
let _run_handle = tokio::spawn(run_fut);
let (rx, msg) = TestControl::unbind_discovery();
drop(rx);
control_sender.send(msg).await.unwrap();
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
assert_inner_alive(&control_sender).await;
}
#[tokio::test]
async fn test_dropped_receiver_set_interface_continues() {
let (control_sender, _update_receiver, run_fut) = TestInner::build(
Ipv4Addr::LOCALHOST,
Arc::new(Mutex::new(E2ERegistry::new())),
false,
crate::client::bind_dispatch::SpawnerDispatch {
factory: TokioTransport,
spawner: TokioSpawner,
buffer_provider: TokioBufferProvider::new(),
},
TokioTimer,
);
let _run_handle = tokio::spawn(run_fut);
// SetInterface(LOCALHOST) on a fresh inner goes straight to
// bind_discovery + send response (interface already matches).
let (rx, msg) = TestControl::set_interface(Ipv4Addr::LOCALHOST);
drop(rx);
control_sender.send(msg).await.unwrap();
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
assert_inner_alive(&control_sender).await;
}
#[tokio::test]
async fn test_dropped_receiver_send_sd_continues() {
let (control_sender, _update_receiver, run_fut) = TestInner::build(
Ipv4Addr::LOCALHOST,
Arc::new(Mutex::new(E2ERegistry::new())),
false,
crate::client::bind_dispatch::SpawnerDispatch {
factory: TokioTransport,
spawner: TokioSpawner,
buffer_provider: TokioBufferProvider::new(),
},
TokioTimer,
);
let _run_handle = tokio::spawn(run_fut);
// Bind discovery first so the SendSD path has a socket to use
let (rx, msg) = TestControl::bind_discovery();
control_sender.send(msg).await.unwrap();
rx.recv().await.unwrap().unwrap();
// Send SD with a dropped receiver
let target = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 30490);
let sd_header = empty_sd_header();
let (rx, msg) = TestControl::send_sd(target, sd_header);
drop(rx);
control_sender.send(msg).await.unwrap();
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
assert_inner_alive(&control_sender).await;
}
// -- Request queue test --
// Verifies that when a new control message arrives while a multi-step
// operation (SetInterface) is mid-way through processing, the new message
// is queued and both complete successfully.
#[tokio::test]
async fn test_queued_messages_all_complete() {
let (control_sender, _update_receiver, run_fut) = TestInner::build(
Ipv4Addr::LOCALHOST,
Arc::new(Mutex::new(E2ERegistry::new())),
false,
crate::client::bind_dispatch::SpawnerDispatch {
factory: TokioTransport,
spawner: TokioSpawner,
buffer_provider: TokioBufferProvider::new(),
},
TokioTimer,
);
let _run_handle = tokio::spawn(run_fut);
// Bind discovery so SetInterface will take the multi-step path:
// iteration 1: unbind discovery, re-queue SetInterface
// iteration 2: interface matches, bind discovery, send response
let (rx, msg) = TestControl::bind_discovery();
control_sender.send(msg).await.unwrap();
rx.recv().await.unwrap().unwrap();
// Queue both messages into the channel buffer before the inner loop
// processes either. mpsc sends on a non-full buffer complete without
// yielding, so both land before the spawned task runs.
//
// 1) SetInterface(LOCALHOST) — will unbind discovery, re-queue itself
// 2) AddEndpoint — queued behind SetInterface, processed after it
let (rx_set, msg_set) = TestControl::set_interface(Ipv4Addr::LOCALHOST);
let addr = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 9999);
let (rx_add, msg_add) = TestControl::add_endpoint(
ServiceEndpointKey::udp(0x1234, SocketAddr::V4(addr)),
0x0001,
0,
);
control_sender.send(msg_set).await.unwrap();
control_sender.send(msg_add).await.unwrap();
// Both should complete successfully
let set_result = tokio::time::timeout(std::time::Duration::from_secs(3), rx_set.recv())
.await
.expect("Timed out waiting for SetInterface")
.expect("SetInterface oneshot closed");
assert!(set_result.is_ok());
let add_result = tokio::time::timeout(std::time::Duration::from_secs(3), rx_add.recv())
.await
.expect("Timed out waiting for AddEndpoint")
.expect("AddEndpoint oneshot closed");
assert!(add_result.is_ok());
// Verify inner loop is still alive
assert_inner_alive(&control_sender).await;
}
#[tokio::test]
async fn test_send_to_service_constructor_returns_two_receivers() {
let message = Message::<TestPayload>::new_sd(1, &empty_sd_header());
let (send_rx, resp_rx, msg) = TestControl::send_to_service(lh_key(0x1234, 5000), message);
// Extract the senders from the control message
if let ControlMessage::SendToService {
send_complete,
response,
..
} = msg
{
// Both channels are independent — sending on one doesn't affect the other
send_complete.send(Ok(())).unwrap();
assert!(send_rx.recv().await.unwrap().is_ok());
let payload = TestPayload {
header: empty_sd_header(),
};
response.send(Ok(payload.clone())).unwrap();
assert_eq!(resp_rx.recv().await.unwrap().unwrap(), payload);
} else {
panic!("expected SendToService variant");
}
}
#[tokio::test]
async fn test_dropped_receiver_add_endpoint_continues() {
let (control_sender, _update_receiver, run_fut) = TestInner::build(
Ipv4Addr::LOCALHOST,
Arc::new(Mutex::new(E2ERegistry::new())),
false,
crate::client::bind_dispatch::SpawnerDispatch {
factory: TokioTransport,
spawner: TokioSpawner,
buffer_provider: TokioBufferProvider::new(),
},
TokioTimer,
);
let _run_handle = tokio::spawn(run_fut);
let addr = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 5000);
let (rx, msg) = TestControl::add_endpoint(
ServiceEndpointKey::udp(0x1234, SocketAddr::V4(addr)),
0x0001,
0,
);
drop(rx);
control_sender.send(msg).await.unwrap();
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
assert_inner_alive(&control_sender).await;
}
#[tokio::test]
async fn test_dropped_receiver_remove_endpoint_continues() {
let (control_sender, _update_receiver, run_fut) = TestInner::build(
Ipv4Addr::LOCALHOST,
Arc::new(Mutex::new(E2ERegistry::new())),
false,
crate::client::bind_dispatch::SpawnerDispatch {
factory: TokioTransport,
spawner: TokioSpawner,
buffer_provider: TokioBufferProvider::new(),
},
TokioTimer,
);
let _run_handle = tokio::spawn(run_fut);
let (rx, msg) = TestControl::remove_endpoint(lh_key(0x1234, 5000));
drop(rx);
control_sender.send(msg).await.unwrap();
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
assert_inner_alive(&control_sender).await;
}
#[tokio::test]
async fn test_dropped_receiver_send_to_service_send_complete_continues() {
let (control_sender, _update_receiver, run_fut) = TestInner::build(
Ipv4Addr::LOCALHOST,
Arc::new(Mutex::new(E2ERegistry::new())),
false,
crate::client::bind_dispatch::SpawnerDispatch {
factory: TokioTransport,
spawner: TokioSpawner,
buffer_provider: TokioBufferProvider::new(),
},
TokioTimer,
);
let _run_handle = tokio::spawn(run_fut);
// Add an endpoint first so SendToService doesn't fail with ServiceNotFound
let addr = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 5000);
let (rx, msg) = TestControl::add_endpoint(
ServiceEndpointKey::udp(0x1234, SocketAddr::V4(addr)),
0x0001,
0,
);
control_sender.send(msg).await.unwrap();
rx.recv().await.unwrap().unwrap();
// Send SendToService with the send_complete receiver dropped
let message = Message::<TestPayload>::new_sd(1, &empty_sd_header());
let (send_rx, _resp_rx, msg) = TestControl::send_to_service(lh_key(0x1234, 5000), message);
drop(send_rx);
control_sender.send(msg).await.unwrap();
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
assert_inner_alive(&control_sender).await;
}
#[tokio::test]
async fn test_bind_discovery_with_loopback() {
// Spawn inner with multicast_loopback=true so bind_discovery exercises
// the loopback-enabled branch of SocketManager::bind_discovery.
let (control_sender, _update_receiver, run_fut) = TestInner::build(
Ipv4Addr::LOCALHOST,
Arc::new(Mutex::new(E2ERegistry::new())),
true,
crate::client::bind_dispatch::SpawnerDispatch {
factory: TokioTransport,
spawner: TokioSpawner,
buffer_provider: TokioBufferProvider::new(),
},
TokioTimer,
);
let _run_handle = tokio::spawn(run_fut);
let (rx, msg) = TestControl::bind_discovery();
control_sender.send(msg).await.unwrap();
rx.recv().await.unwrap().unwrap();
}
#[tokio::test]
async fn test_bind_discovery_idempotent() {
// Binding discovery twice should succeed (early return on already-bound)
let (control_sender, _update_receiver, run_fut) = TestInner::build(
Ipv4Addr::LOCALHOST,
Arc::new(Mutex::new(E2ERegistry::new())),
false,
crate::client::bind_dispatch::SpawnerDispatch {
factory: TokioTransport,
spawner: TokioSpawner,
buffer_provider: TokioBufferProvider::new(),
},
TokioTimer,
);
let _run_handle = tokio::spawn(run_fut);
let (rx, msg) = TestControl::bind_discovery();
control_sender.send(msg).await.unwrap();
rx.recv().await.unwrap().unwrap();
// Second bind should also succeed (idempotent path)
let (rx, msg) = TestControl::bind_discovery();
control_sender.send(msg).await.unwrap();
rx.recv().await.unwrap().unwrap();
}
#[tokio::test]
async fn test_send_sd_auto_binds_discovery() {
// SendSD without a bound discovery socket should auto-bind and succeed
let (control_sender, _update_receiver, run_fut) = TestInner::build(
Ipv4Addr::LOCALHOST,
Arc::new(Mutex::new(E2ERegistry::new())),
false,
crate::client::bind_dispatch::SpawnerDispatch {
factory: TokioTransport,
spawner: TokioSpawner,
buffer_provider: TokioBufferProvider::new(),
},
TokioTimer,
);
let _run_handle = tokio::spawn(run_fut);
let target = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 30490);
let sd_header = empty_sd_header();
let (rx, msg) = TestControl::send_sd(target, sd_header);
control_sender.send(msg).await.unwrap();
let result = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
.await
.expect("Timed out waiting for SendSD")
.expect("SendSD oneshot closed");
assert!(result.is_ok());
}
#[tokio::test]
async fn test_send_to_service_auto_binds_unicast() {
// SendToService with no unicast sockets should auto-bind ephemeral
let (control_sender, _update_receiver, run_fut) = TestInner::build(
Ipv4Addr::LOCALHOST,
Arc::new(Mutex::new(E2ERegistry::new())),
false,
crate::client::bind_dispatch::SpawnerDispatch {
factory: TokioTransport,
spawner: TokioSpawner,
buffer_provider: TokioBufferProvider::new(),
},
TokioTimer,
);
let _run_handle = tokio::spawn(run_fut);
let addr = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 5000);
let (rx, msg) = TestControl::add_endpoint(
ServiceEndpointKey::udp(0x1234, SocketAddr::V4(addr)),
0x0001,
0,
);
control_sender.send(msg).await.unwrap();
rx.recv().await.unwrap().unwrap();
let message = Message::<TestPayload>::new_sd(1, &empty_sd_header());
let (send_rx, _resp_rx, msg) = TestControl::send_to_service(lh_key(0x1234, 5000), message);
control_sender.send(msg).await.unwrap();
let result = tokio::time::timeout(std::time::Duration::from_secs(2), send_rx.recv())
.await
.expect("Timed out waiting for SendToService")
.expect("SendToService oneshot closed");
assert!(result.is_ok(), "send should succeed: {result:?}");
}
#[tokio::test]
async fn test_subscribe_with_endpoint_sends_sd() {
// Subscribe with a known endpoint and bound discovery should send the SD message
let (control_sender, _update_receiver, run_fut) = TestInner::build(
Ipv4Addr::LOCALHOST,
Arc::new(Mutex::new(E2ERegistry::new())),
false,
crate::client::bind_dispatch::SpawnerDispatch {
factory: TokioTransport,
spawner: TokioSpawner,
buffer_provider: TokioBufferProvider::new(),
},
TokioTimer,
);
let _run_handle = tokio::spawn(run_fut);
// Bind discovery first
let (rx, msg) = TestControl::bind_discovery();
control_sender.send(msg).await.unwrap();
rx.recv().await.unwrap().unwrap();
// Add endpoint
let addr = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 5000);
let (rx, msg) = TestControl::add_endpoint(
ServiceEndpointKey::udp(0x1234, SocketAddr::V4(addr)),
0x0001,
0,
);
control_sender.send(msg).await.unwrap();
rx.recv().await.unwrap().unwrap();
// Subscribe
let (rx, msg) = TestControl::subscribe(lh_key(0x1234, 5000), 1, 3, 0x01, 0);
control_sender.send(msg).await.unwrap();
let result = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
.await
.expect("Timed out waiting for Subscribe")
.expect("Subscribe oneshot closed");
assert!(result.is_ok(), "subscribe should succeed: {result:?}");
}
#[tokio::test]
async fn test_subscribe_auto_binds_discovery() {
// Subscribe without discovery bound should auto-bind and succeed
let (control_sender, _update_receiver, run_fut) = TestInner::build(
Ipv4Addr::LOCALHOST,
Arc::new(Mutex::new(E2ERegistry::new())),
false,
crate::client::bind_dispatch::SpawnerDispatch {
factory: TokioTransport,
spawner: TokioSpawner,
buffer_provider: TokioBufferProvider::new(),
},
TokioTimer,
);
let _run_handle = tokio::spawn(run_fut);
// Add endpoint but do NOT bind discovery
let addr = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 5000);
let (rx, msg) = TestControl::add_endpoint(
ServiceEndpointKey::udp(0x1234, SocketAddr::V4(addr)),
0x0001,
0,
);
control_sender.send(msg).await.unwrap();
rx.recv().await.unwrap().unwrap();
// Subscribe should auto-bind discovery
let (rx, msg) = TestControl::subscribe(lh_key(0x1234, 5000), 1, 3, 0x01, 0);
control_sender.send(msg).await.unwrap();
let result = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
.await
.expect("Timed out waiting for Subscribe")
.expect("Subscribe oneshot closed");
assert!(result.is_ok(), "subscribe should auto-bind: {result:?}");
}
#[tokio::test]
async fn test_subscribe_unknown_service_returns_error() {
let (control_sender, _update_receiver, run_fut) = TestInner::build(
Ipv4Addr::LOCALHOST,
Arc::new(Mutex::new(E2ERegistry::new())),
false,
crate::client::bind_dispatch::SpawnerDispatch {
factory: TokioTransport,
spawner: TokioSpawner,
buffer_provider: TokioBufferProvider::new(),
},
TokioTimer,
);
let _run_handle = tokio::spawn(run_fut);
let (rx, msg) = TestControl::subscribe(lh_key(0xFFFF, 5000), 1, 3, 0x01, 0);
control_sender.send(msg).await.unwrap();
let result = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
.await
.expect("Timed out")
.expect("oneshot closed");
assert!(matches!(result, Err(Error::ServiceNotFound)));
}
#[tokio::test]
async fn test_send_to_service_reuses_existing_unicast_socket() {
// When a unicast socket already exists, SendToService should reuse it
let (control_sender, _update_receiver, run_fut) = TestInner::build(
Ipv4Addr::LOCALHOST,
Arc::new(Mutex::new(E2ERegistry::new())),
false,
crate::client::bind_dispatch::SpawnerDispatch {
factory: TokioTransport,
spawner: TokioSpawner,
buffer_provider: TokioBufferProvider::new(),
},
TokioTimer,
);
let _run_handle = tokio::spawn(run_fut);
let addr = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 5000);
let (rx, msg) = TestControl::add_endpoint(
ServiceEndpointKey::udp(0x1234, SocketAddr::V4(addr)),
0x0001,
0,
);
control_sender.send(msg).await.unwrap();
rx.recv().await.unwrap().unwrap();
// First send auto-binds unicast
let message = Message::<TestPayload>::new_sd(1, &empty_sd_header());
let (send_rx, _resp_rx, msg) = TestControl::send_to_service(lh_key(0x1234, 5000), message);
control_sender.send(msg).await.unwrap();
send_rx.recv().await.unwrap().unwrap();
// Second send reuses the existing socket (no auto-bind needed)
let message = Message::<TestPayload>::new_sd(1, &empty_sd_header());
let (send_rx, _resp_rx, msg) = TestControl::send_to_service(lh_key(0x1234, 5000), message);
control_sender.send(msg).await.unwrap();
let result = tokio::time::timeout(std::time::Duration::from_secs(2), send_rx.recv())
.await
.expect("Timed out")
.expect("oneshot closed");
assert!(
result.is_ok(),
"second send should reuse socket: {result:?}"
);
}
#[tokio::test]
async fn test_dropped_receiver_subscribe_service_not_found_continues() {
// Subscribe with no endpoint → ServiceNotFound response is dropped
let (control_sender, _update_receiver, run_fut) = TestInner::build(
Ipv4Addr::LOCALHOST,
Arc::new(Mutex::new(E2ERegistry::new())),
false,
crate::client::bind_dispatch::SpawnerDispatch {
factory: TokioTransport,
spawner: TokioSpawner,
buffer_provider: TokioBufferProvider::new(),
},
TokioTimer,
);
let _run_handle = tokio::spawn(run_fut);
let (rx, msg) = TestControl::subscribe(lh_key(0x1234, 5000), 1, 3, 0x01, 0);
drop(rx);
control_sender.send(msg).await.unwrap();
tokio::time::sleep(std::time::Duration::from_millis(500)).await;
assert_inner_alive(&control_sender).await;
}
#[tokio::test]
async fn test_set_interface_changes_interface() {
// SetInterface to a different address exercises the interface!=current path
let (control_sender, _update_receiver, run_fut) = TestInner::build(
Ipv4Addr::LOCALHOST,
Arc::new(Mutex::new(E2ERegistry::new())),
false,
crate::client::bind_dispatch::SpawnerDispatch {
factory: TokioTransport,
spawner: TokioSpawner,
buffer_provider: TokioBufferProvider::new(),
},
TokioTimer,
);
let _run_handle = tokio::spawn(run_fut);
// Change to a different loopback-range address (127.0.0.2).
// Binding discovery on 127.0.0.2 should succeed on most systems.
let (rx, msg) = TestControl::set_interface(Ipv4Addr::new(127, 0, 0, 2));
control_sender.send(msg).await.unwrap();
let result = tokio::time::timeout(std::time::Duration::from_secs(3), rx.recv())
.await
.expect("Timed out waiting for SetInterface")
.expect("SetInterface oneshot closed");
// The result may be Ok or Err depending on whether 127.0.0.2 is bindable,
// but the important thing is that the inner loop didn't panic or deadlock.
let _ = result;
assert_inner_alive(&control_sender).await;
}
#[tokio::test]
async fn test_set_interface_with_discovery_bound_changes_interface() {
// SetInterface when discovery is already bound: unbind → change → rebind
let (control_sender, _update_receiver, run_fut) = TestInner::build(
Ipv4Addr::LOCALHOST,
Arc::new(Mutex::new(E2ERegistry::new())),
false,
crate::client::bind_dispatch::SpawnerDispatch {
factory: TokioTransport,
spawner: TokioSpawner,
buffer_provider: TokioBufferProvider::new(),
},
TokioTimer,
);
let _run_handle = tokio::spawn(run_fut);
// Bind discovery on LOCALHOST first
let (rx, msg) = TestControl::bind_discovery();
control_sender.send(msg).await.unwrap();
rx.recv().await.unwrap().unwrap();
// Change to 127.0.0.2 — this takes the multi-step path:
// 1. unbind discovery, re-queue
// 2. interface != 127.0.0.2, set_interface, re-queue
// 3. interface == 127.0.0.2, bind discovery
let (rx, msg) = TestControl::set_interface(Ipv4Addr::new(127, 0, 0, 2));
control_sender.send(msg).await.unwrap();
let result = tokio::time::timeout(std::time::Duration::from_secs(3), rx.recv())
.await
.expect("Timed out waiting for SetInterface")
.expect("SetInterface oneshot closed");
let _ = result;
assert_inner_alive(&control_sender).await;
}
#[tokio::test]
async fn test_subscribe_specific_port_reuse() {
// Subscribe twice with the same specific client_port exercises the
// bind_unicast port-reuse path (port != 0 && already bound).
let (control_sender, _update_receiver, run_fut) = TestInner::build(
Ipv4Addr::LOCALHOST,
Arc::new(Mutex::new(E2ERegistry::new())),
false,
crate::client::bind_dispatch::SpawnerDispatch {
factory: TokioTransport,
spawner: TokioSpawner,
buffer_provider: TokioBufferProvider::new(),
},
TokioTimer,
);
let _run_handle = tokio::spawn(run_fut);
// Add endpoint and bind discovery
let (rx, msg) = TestControl::bind_discovery();
control_sender.send(msg).await.unwrap();
rx.recv().await.unwrap().unwrap();
let addr = SocketAddrV4::new(Ipv4Addr::LOCALHOST, 5000);
let (rx, msg) = TestControl::add_endpoint(
ServiceEndpointKey::udp(0x1234, SocketAddr::V4(addr)),
0x0001,
0,
);
control_sender.send(msg).await.unwrap();
rx.recv().await.unwrap().unwrap();
// First subscribe with specific port — binds the port
let (rx, msg) = TestControl::subscribe(lh_key(0x1234, 5000), 1, 3, 0x01, 44444);
control_sender.send(msg).await.unwrap();
let result = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
.await
.expect("Timed out")
.expect("oneshot closed");
assert!(result.is_ok(), "first subscribe should succeed: {result:?}");
// Second subscribe with the same port — reuses the existing socket
let (rx, msg) = TestControl::subscribe(lh_key(0x1234, 5000), 1, 3, 0x02, 44444);
control_sender.send(msg).await.unwrap();
let result = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
.await
.expect("Timed out")
.expect("oneshot closed");
assert!(
result.is_ok(),
"second subscribe should reuse port: {result:?}"
);
}
#[tokio::test]
async fn test_sd_session_id_persists_across_rebind() {
// Verify that unbind_discovery + bind_discovery carries the session counter
// forward rather than resetting it to 1, which would send a false reboot signal.
use crate::protocol::MessageView;
use std::vec;
use tokio::net::UdpSocket;
let (control_sender, _update_receiver, run_fut) = TestInner::build(
Ipv4Addr::LOCALHOST,
Arc::new(Mutex::new(E2ERegistry::new())),
false,
crate::client::bind_dispatch::SpawnerDispatch {
factory: TokioTransport,
spawner: TokioSpawner,
buffer_provider: TokioBufferProvider::new(),
},
TokioTimer,
);
let _run_handle = tokio::spawn(run_fut);
let raw = UdpSocket::bind("127.0.0.1:0").await.unwrap();
let target = SocketAddrV4::new(Ipv4Addr::LOCALHOST, raw.local_addr().unwrap().port());
// Bind and send one SD message to advance the session counter.
let (rx, msg) = TestControl::bind_discovery();
control_sender.send(msg).await.unwrap();
rx.recv().await.unwrap().unwrap();
let (rx, msg) = TestControl::send_sd(target, empty_sd_header());
control_sender.send(msg).await.unwrap();
rx.recv().await.unwrap().unwrap();
let mut buf = vec![0u8; 1400];
let (len, _) =
tokio::time::timeout(std::time::Duration::from_secs(2), raw.recv_from(&mut buf))
.await
.expect("timed out waiting for first SD message")
.unwrap();
let first = MessageView::parse(&buf[..len]).unwrap();
let session_id_before = (first.header().request_id() & 0xFFFF) as u16;
let reboot_flag_before = first.sd_header().unwrap().flags().reboot();
assert!(session_id_before >= 1, "session_id must never be 0");
// Unbind, then rebind.
let (rx, msg) = TestControl::unbind_discovery();
control_sender.send(msg).await.unwrap();
rx.recv().await.unwrap().unwrap();
let (rx, msg) = TestControl::bind_discovery();
control_sender.send(msg).await.unwrap();
rx.recv().await.unwrap().unwrap();
// Send a second SD message and verify both session counter and reboot flag persisted.
let (rx, msg) = TestControl::send_sd(target, empty_sd_header());
control_sender.send(msg).await.unwrap();
rx.recv().await.unwrap().unwrap();
let (len, _) =
tokio::time::timeout(std::time::Duration::from_secs(2), raw.recv_from(&mut buf))
.await
.expect("timed out waiting for second SD message")
.unwrap();
let second = MessageView::parse(&buf[..len]).unwrap();
let session_id_after = (second.header().request_id() & 0xFFFF) as u16;
let reboot_flag_after = second.sd_header().unwrap().flags().reboot();
assert!(
session_id_after > session_id_before,
"session_id should continue after rebind (before={session_id_before}, after={session_id_after})"
);
assert_eq!(
reboot_flag_after, reboot_flag_before,
"reboot_flag should be preserved across rebind"
);
}
/// Regression for ad515c3 (source-keyed registry): drives
/// `handle_discovery_datagram` — the production auto-registration
/// path — directly with real SD `OfferService` / `StopOfferService`
/// payloads (via `RawPayload`/`VecSdHeader`, which unlike the
/// `TestPayload` used elsewhere in this module actually implements
/// `for_each_offered_endpoint`), rather than poking the registry
/// map directly. Two devices offer the identical
/// `(service_id, instance_id)` — the fixed ECU-Extract-instance-id
/// scenario — and a `StopOfferService` from one device must evict
/// only that device's entry.
#[test]
#[allow(clippy::too_many_lines)]
fn handle_discovery_datagram_keys_offers_by_device_ip() {
use crate::RawPayload;
use crate::protocol::sd::{self, Entry, Options, OptionsCount, ServiceEntry};
use crate::traits::WireFormat;
use core::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
type RawInner = Inner<
RawPayload,
TokioTimer,
Arc<Mutex<E2ERegistry>>,
TokioChannels,
crate::client::bind_dispatch::SpawnerDispatch<
TokioTransport,
TokioSpawner,
TokioBufferProvider,
>,
>;
const SERVICE_ID: u16 = 0x1234;
const INSTANCE_ID: u16 = 1;
const DEVICE_A: Ipv4Addr = Ipv4Addr::new(127, 0, 0, 10);
const DEVICE_B: Ipv4Addr = Ipv4Addr::new(127, 0, 0, 11);
const PORT_A: u16 = 30_509;
const PORT_B: u16 = 30_510;
fn offer_header(service_addr: SocketAddrV4, is_offer: bool) -> crate::VecSdHeader {
let service_entry = ServiceEntry {
index_first_options_run: 0,
index_second_options_run: 0,
options_count: OptionsCount::new(1, 0),
service_id: SERVICE_ID,
instance_id: INSTANCE_ID,
major_version: 1,
ttl: 3,
minor_version: 0,
};
let entry = if is_offer {
Entry::OfferService(service_entry)
} else {
Entry::StopOfferService(service_entry)
};
let endpoint = Options::IpV4Endpoint {
ip: *service_addr.ip(),
protocol: sd::TransportProtocol::Udp,
port: service_addr.port(),
};
crate::VecSdHeader {
flags: sd::Flags::new_sd(sd::RebootFlag::RecentlyRebooted),
entries: std::vec![entry],
options: std::vec![endpoint],
}
}
let mut session_tracker = SessionTracker::default();
let mut service_registry = ServiceRegistry::default();
let e2e_registry: Arc<Mutex<E2ERegistry>> = Arc::new(Mutex::new(E2ERegistry::new()));
let (update_sender, _update_receiver) =
TokioChannels::unbounded::<ClientUpdate<RawPayload>>();
let addr_a = SocketAddrV4::new(DEVICE_A, PORT_A);
let addr_b = SocketAddrV4::new(DEVICE_B, PORT_B);
// Two OFFERs for the identical (service_id, instance_id) from two
// distinct device IPs — each arrives as its own SD datagram, exactly
// as real per-sender SD traffic does.
for (request_id, source_ip, service_addr) in
[(1u32, DEVICE_A, addr_a), (2u32, DEVICE_B, addr_b)]
{
let sd_header = offer_header(service_addr, true);
let someip_header = protocol::Header::new_sd(request_id, sd_header.required_size());
RawInner::handle_discovery_datagram(
SocketAddr::new(source_ip.into(), sd::MULTICAST_PORT),
TransportKind::Multicast,
someip_header,
sd_header,
&mut session_tracker,
&mut service_registry,
&e2e_registry,
&update_sender,
);
}
let key_a = ServiceEndpointKey::udp(SERVICE_ID, SocketAddr::V4(addr_a));
let key_b = ServiceEndpointKey::udp(SERVICE_ID, SocketAddr::V4(addr_b));
assert_eq!(
service_registry.get(key_a).map(|info| info.instance_id),
Some(INSTANCE_ID),
"device A's offer must resolve to device A's entry"
);
assert_eq!(
service_registry.get(key_b).map(|info| info.instance_id),
Some(INSTANCE_ID),
"device A's second offer must not have shadowed device B's entry"
);
// StopOffer from device A only — device B's entry must survive.
// This is the exact "StopOffer evicts all" regression: before
// ad515c3, the registry was keyed by (service_id, instance_id)
// alone, so removing A's entry would have removed B's too.
let stop_header = offer_header(addr_a, false);
let someip_header = protocol::Header::new_sd(3, stop_header.required_size());
RawInner::handle_discovery_datagram(
SocketAddr::new(DEVICE_A.into(), sd::MULTICAST_PORT),
TransportKind::Multicast,
someip_header,
stop_header,
&mut session_tracker,
&mut service_registry,
&e2e_registry,
&update_sender,
);
assert!(
service_registry.get(key_a).is_none(),
"device A's entry must be evicted by its StopOffer"
);
assert_eq!(
service_registry.get(key_b).map(|info| info.instance_id),
Some(INSTANCE_ID),
"device B's entry must survive device A's StopOffer"
);
}
}