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
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
//! A contract is PUT within a location distance, this entails that all nodes within
//! a given radius will cache a copy of the contract and it's current value,
//! as well as will broadcast updates to the contract value to all subscribers.
pub(crate) mod op_ctx_task;
use std::collections::HashSet;
use std::future::Future;
use std::pin::Pin;
pub(crate) use self::messages::{PutMsg, PutStreamingPayload};
use super::orphan_streams::{OrphanStreamError, STREAM_CLAIM_TIMEOUT};
use freenet_stdlib::{
client_api::{ErrorKind, HostResponse},
prelude::*,
};
use super::{
OpEnum, OpError, OpInitialization, OpOutcome, Operation, OperationResult, VisitedPeers, put,
should_use_streaming,
};
/// Minimum HTL to use when retrying — prevents retries from being too shallow.
const MIN_RETRY_HTL: usize = 3;
use crate::node::IsOperationCompleted;
use crate::transport::peer_connection::StreamId;
use crate::{
client_events::HostResult,
contract::ContractHandlerEvent,
message::{InnerMessage, NetMessage, Transaction},
node::{NetworkBridge, OpManager},
ring::{KnownPeerKeyLocation, Location, PeerKeyLocation},
tracing::{NetEventLog, OperationFailure, state_hash_full},
};
use either::Either;
/// Routing stats for put operations, used to report success/failure to the router.
struct PutStats {
target_peer: PeerKeyLocation,
contract_location: Location,
}
pub(crate) struct PutOp {
pub id: Transaction,
state: Option<PutState>,
/// The address we received this operation's message from.
/// Used for connection-based routing: responses are sent back to this address.
upstream_addr: Option<std::net::SocketAddr>,
/// Routing stats for reporting outcomes to the router.
stats: Option<PutStats>,
/// True when a downstream relay has acknowledged forwarding this request.
/// Used by the GC task to distinguish "peer is dead" from "peer is working on it".
pub(crate) ack_received: bool,
/// Number of speculative parallel paths launched by the originator's GC task.
/// Capped at MAX_SPECULATIVE_PATHS to bound network overhead.
pub(crate) speculative_paths: u8,
}
impl PutOp {
pub(super) fn outcome(&self) -> OpOutcome<'_> {
if self.finalized() {
if let Some(ref stats) = self.stats {
return OpOutcome::ContractOpSuccessUntimed {
target_peer: &stats.target_peer,
contract_location: stats.contract_location,
};
}
return OpOutcome::Irrelevant;
}
// Not completed — if we have stats, report as failure
if let Some(ref stats) = self.stats {
OpOutcome::ContractOpFailure {
target_peer: &stats.target_peer,
contract_location: stats.contract_location,
}
} else {
OpOutcome::Incomplete
}
}
/// Returns true if this PUT was initiated by a local client (not forwarded from a peer).
pub(crate) fn is_client_initiated(&self) -> bool {
self.upstream_addr.is_none()
}
/// Extract routing failure info for timeout reporting.
pub(crate) fn failure_routing_info(&self) -> Option<(PeerKeyLocation, Location)> {
self.stats
.as_ref()
.map(|s| (s.target_peer.clone(), s.contract_location))
}
pub(super) fn finalized(&self) -> bool {
self.state.is_none() || matches!(self.state, Some(PutState::Finished(_)))
}
pub(super) fn to_host_result(&self) -> HostResult {
if let Some(PutState::Finished(data)) = &self.state {
let key = &data.key;
Ok(HostResponse::ContractResponse(
freenet_stdlib::client_api::ContractResponse::PutResponse { key: *key },
))
} else {
Err(ErrorKind::OperationError {
cause: "put didn't finish successfully".into(),
}
.into())
}
}
/// Get the next hop address if this operation is in a state that needs to send
/// an outbound message to a downstream peer.
pub(crate) fn get_next_hop_addr(&self) -> Option<std::net::SocketAddr> {
match &self.state {
Some(PutState::AwaitingResponse(data)) => data.next_hop,
_ => None,
}
}
/// Get the current HTL (remaining hops) for this operation.
/// Returns None if the operation is not in AwaitingResponse state.
pub(crate) fn get_current_htl(&self) -> Option<usize> {
match &self.state {
Some(PutState::AwaitingResponse(data)) => Some(data.current_htl),
_ => None,
}
}
/// Try the next alternative peer for a timed-out PUT operation.
///
/// Returns `Ok((new_op, msg))` with the re-routed operation and message to send,
/// or `Err(self)` if no alternatives remain or no retry payload is available.
///
/// Follows the same pattern as `GetOp::retry_with_next_alternative`:
/// 1. Inject fallback peers if local alternatives exhausted
/// 2. Pick next alternative, mark in tried_peers + bloom filter
/// 3. Reduce HTL on each retry to limit blast radius
/// 4. Build a new PutMsg::Request from the retained payload
pub(crate) fn retry_with_next_alternative(
mut self,
max_hops_to_live: usize,
fallback_peers: &[PeerKeyLocation],
) -> Result<(PutOp, PutMsg), Box<PutOp>> {
let state = match self.state.take() {
Some(s) => s,
None => return Err(Box::new(self)),
};
match state {
PutState::AwaitingResponse(mut data) => {
// Can't retry without the contract data
if data.retry_payload.is_none() {
self.state = Some(PutState::AwaitingResponse(data));
return Err(Box::new(self));
}
// If local alternatives exhausted, inject fallback peers we haven't tried.
if data.alternatives.is_empty() && !fallback_peers.is_empty() {
for peer in fallback_peers {
if let Some(addr) = peer.socket_addr() {
if !data.tried_peers.contains(&addr)
&& !data.visited.probably_visited(addr)
{
data.alternatives.push(peer.clone());
}
}
}
if !data.alternatives.is_empty() {
tracing::info!(
tx = %self.id,
contract = %data.contract_key,
new_candidates = data.alternatives.len(),
"PUT broadening search to all connected peers (DBF fallback)"
);
}
}
if data.alternatives.is_empty() {
self.state = Some(PutState::AwaitingResponse(data));
return Err(Box::new(self));
}
let next_target = data.alternatives.remove(0);
let contract_key = data.contract_key;
if let Some(addr) = next_target.socket_addr() {
data.tried_peers.insert(addr);
data.visited.mark_visited(addr);
}
tracing::info!(
tx = %self.id,
contract = %contract_key,
target = %next_target,
remaining_alternatives = data.alternatives.len(),
"PUT retrying with alternative peer after timeout"
);
data.next_hop = next_target.socket_addr();
data.attempts_at_hop += 1;
// Update stats to point to the new target so timeouts/failures
// are reported against the correct peer (#3527).
if let Some(ref mut s) = self.stats {
s.target_peer = next_target.clone();
}
// Reduce HTL on each retry to avoid full-depth traversal storms.
let retry_htl = (max_hops_to_live / (data.attempts_at_hop.max(1)))
.max(MIN_RETRY_HTL)
.min(max_hops_to_live);
let payload = data.retry_payload.as_ref().unwrap();
// The skip_list in PutMsg::Request is a HashSet<SocketAddr>, which is
// more limited than GET's VisitedPeers bloom filter. We include all
// tried_peers so relay nodes won't route back to peers the originator
// already attempted. The `visited` bloom filter provides the primary
// defense at the originator (preventing re-selection of the same peers
// in `closest_to_location`), but it can't be serialized into the
// skip_list since bloom filters aren't convertible to address sets.
let skip_list = data.tried_peers.clone();
// Retry always uses non-streaming PutMsg::Request, even if the
// original was streamed. The transport layer fragments large messages
// into UDP packets regardless, so there's no message size limit.
// Streaming is an optimization (avoids holding the full payload in
// memory at relay hops), but for originator retry the payload is
// already in memory in retry_payload.
let msg = PutMsg::Request {
id: self.id,
contract: payload.contract.clone(),
related_contracts: payload.related_contracts.clone(),
value: payload.value.clone(),
htl: retry_htl,
skip_list,
};
self.state = Some(PutState::AwaitingResponse(data));
Ok((self, msg))
}
state @ (PutState::PrepareRequest(_) | PutState::Finished(_)) => {
self.state = Some(state);
Err(Box::new(self))
}
}
}
/// Handle aborted connections.
///
/// If speculative retry paths are in flight, the abort of the original path
/// is non-terminal — we log and return Ok, letting the speculative path
/// deliver the result (or the GC task will timeout if all paths fail).
///
/// If no speculative paths remain, we fail immediately and notify the client.
/// Retry with alternative peers is handled by the GC task's speculative
/// retry mechanism (see `retry_with_next_alternative`).
pub(crate) async fn handle_abort(self, op_manager: &OpManager) -> Result<(), OpError> {
if self.speculative_paths > 0 {
tracing::warn!(
tx = %self.id,
speculative_paths = self.speculative_paths,
"Put operation original path aborted, but {} speculative path(s) still active — \
not failing the operation",
self.speculative_paths
);
// Mark completed so GC doesn't re-process this operation entry,
// but don't notify the client — the speculative path will do that.
op_manager.completed(self.id);
return Ok(());
}
tracing::warn!(
tx = %self.id,
"Put operation aborted due to connection failure"
);
// Extract key and current_htl from state if available
let (key, current_htl) = match &self.state {
Some(PutState::PrepareRequest(data)) => (Some(data.contract.key()), Some(data.htl)),
Some(PutState::AwaitingResponse(data)) => (None, Some(data.current_htl)),
Some(PutState::Finished(data)) => (Some(data.key), None),
None => (None, None),
};
// Calculate hop_count: max_htl - current_htl
let hop_count = current_htl.map(|htl| op_manager.ring.max_hops_to_live.saturating_sub(htl));
// Emit failure event if we have the key
if let Some(key) = key {
if let Some(event) = NetEventLog::put_failure(
&self.id,
&op_manager.ring,
key,
OperationFailure::ConnectionDropped,
hop_count,
) {
op_manager.ring.register_events(Either::Left(event)).await;
}
}
// Create an error result to notify the client
let error_result: crate::client_events::HostResult =
Err(freenet_stdlib::client_api::ErrorKind::OperationError {
cause: "Put operation failed: peer connection dropped".into(),
}
.into());
// Send the error to the client via the result router.
// Use try_send to avoid blocking the event loop (see channel-safety.md).
if let Err(err) = op_manager
.result_router_tx
.try_send((self.id, error_result))
{
tracing::error!(
tx = %self.id,
error = %err,
"Failed to send abort notification to client \
(result router channel full or closed)"
);
}
// Mark the operation as completed so it's removed from tracking
op_manager.completed(self.id);
Ok(())
}
}
impl IsOperationCompleted for PutOp {
fn is_completed(&self) -> bool {
matches!(self.state, Some(put::PutState::Finished(_)))
}
}
pub(crate) struct PutResult {}
impl Operation for PutOp {
type Message = PutMsg;
type Result = PutResult;
async fn load_or_init<'a>(
op_manager: &'a OpManager,
msg: &'a Self::Message,
source_addr: Option<std::net::SocketAddr>,
) -> Result<OpInitialization<Self>, OpError> {
let tx = *msg.id();
tracing::debug!(
tx = %tx,
msg_type = %msg,
phase = "load_or_init",
"Attempting to load or initialize PUT operation"
);
match op_manager.pop(msg.id()) {
Ok(Some(OpEnum::Put(put_op))) => {
// was an existing operation, the other peer messaged back
tracing::debug!(
tx = %tx,
state = %put_op.state.as_ref().map(|s| format!("{:?}", s)).unwrap_or_else(|| "None".to_string()),
phase = "load_or_init",
"Found existing PUT operation"
);
Ok(OpInitialization {
op: put_op,
source_addr,
})
}
Ok(Some(op)) => {
tracing::warn!(
tx = %tx,
phase = "load_or_init",
"Found operation with wrong type, pushing back"
);
if let Err(e) = op_manager.push(tx, op).await {
tracing::warn!(tx = %tx, error = %e, "failed to push mismatched op back");
}
Err(OpError::OpNotPresent(tx))
}
Ok(None) => {
// Check if this is a response message - if so, the operation was likely
// cleaned up due to timeout and we should not create a new operation
if matches!(
msg,
PutMsg::Response { .. }
| PutMsg::ResponseStreaming { .. }
| PutMsg::ForwardingAck { .. }
) {
tracing::debug!(
tx = %tx,
phase = "load_or_init",
"PUT response arrived for non-existent operation (likely timed out)"
);
return Err(OpError::OpNotPresent(tx));
}
// New incoming request - we're a forwarder or final node.
// We don't need persistent state, just track upstream_addr for response routing.
tracing::debug!(
tx = %tx,
source = ?source_addr,
phase = "load_or_init",
"New incoming request"
);
Ok(OpInitialization {
op: Self {
state: None, // No state needed for forwarding nodes
id: tx,
upstream_addr: source_addr, // Remember who to send response to
stats: None,
ack_received: false,
speculative_paths: 0,
},
source_addr,
})
}
Err(err) => {
// Already-completed is a benign race under task-per-tx retries
// (multiple NotFound retries against the same tx routinely hit
// it). Logging at ERROR here was producing 350k+ events/sec in
// ci-fault-loss, enough allocator churn to OOM the runner.
// Running is also expected (another task is mid-process).
// Keep ERROR for genuinely unexpected failures only.
match &err {
crate::node::OpNotAvailable::Completed
| crate::node::OpNotAvailable::Running => {
tracing::debug!(
tx = %tx,
error = %err,
phase = "load_or_init",
"pop returned expected not-available state"
);
}
}
Err(err.into())
}
}
}
fn id(&self) -> &Transaction {
&self.id
}
fn process_message<'a, NB: NetworkBridge>(
self,
conn_manager: &'a mut NB,
op_manager: &'a OpManager,
input: &'a Self::Message,
source_addr: Option<std::net::SocketAddr>,
) -> Pin<Box<dyn Future<Output = Result<OperationResult, OpError>> + Send + 'a>> {
Box::pin(async move {
let id = self.id;
let upstream_addr = self.upstream_addr;
let mut stats = self.stats;
let is_originator = upstream_addr.is_none();
// Look up sender's PeerKeyLocation from source address for telemetry
let sender_from_addr = source_addr.and_then(|addr| {
op_manager
.ring
.connection_manager
.get_peer_location_by_addr(addr)
});
// Extract subscribe flags from state (only relevant for originator)
let subscribe = match &self.state {
Some(PutState::PrepareRequest(data)) => data.subscribe,
Some(PutState::AwaitingResponse(data)) => data.subscribe,
_ => false,
};
let blocking_subscribe = match &self.state {
Some(PutState::PrepareRequest(data)) => data.blocking_subscribe,
Some(PutState::AwaitingResponse(data)) => data.blocking_subscribe,
_ => false,
};
match input {
PutMsg::Request {
id: _msg_id,
contract,
related_contracts,
value,
htl,
skip_list,
} => {
let key = contract.key();
let htl = *htl;
tracing::info!(
tx = %id,
contract = %key,
htl,
is_originator,
subscribe,
phase = "request",
"Processing PUT Request"
);
// Check if we're already subscribed to this contract BEFORE storing
let was_hosting = op_manager.ring.is_hosting_contract(&key);
// Step 1: Store contract locally (all nodes cache)
// put_contract returns (merged_value, state_changed) where state_changed
// is true if the stored state actually changed (old != new).
let (merged_value, _state_changed) = match put_contract(
op_manager,
key,
value.clone(),
related_contracts.clone(),
contract,
)
.await
{
Ok(result) => result,
Err(err) => {
// Emit put_failure telemetry so we can diagnose
// why PUTs fail on the network. Without this event,
// put_contract errors are invisible in telemetry.
tracing::error!(
tx = %id,
contract = %key,
error = %err,
htl,
is_originator,
"put_contract failed"
);
if let Some(event) = NetEventLog::put_failure(
&id,
&op_manager.ring,
key,
OperationFailure::ContractError(err.to_string()),
Some(op_manager.ring.max_hops_to_live.saturating_sub(htl)),
) {
op_manager.ring.register_events(Either::Left(event)).await;
}
return Err(err);
}
};
// Mark as hosting if not already
if !was_hosting {
let evicted = op_manager
.ring
.host_contract(key, value.size() as u64, crate::ring::AccessType::Put)
.evicted;
if is_originator {
op_manager.ring.mark_local_client_access(&key);
}
super::announce_contract_hosted(op_manager, &key).await;
// Clean up interest tracking for evicted contracts
let mut removed_contracts = Vec::new();
for evicted_key in evicted {
if op_manager
.interest_manager
.unregister_local_hosting(&evicted_key)
{
removed_contracts.push(evicted_key);
}
}
// Register local interest for delta-based sync
let became_interested =
op_manager.interest_manager.register_local_hosting(&key);
// Broadcast interest changes to peers
let added = if became_interested { vec![key] } else { vec![] };
if !added.is_empty() || !removed_contracts.is_empty() {
super::broadcast_change_interests(op_manager, added, removed_contracts)
.await;
}
}
// Invariant: after storing and hosting, the contract MUST be in the hosting list.
debug_assert!(
op_manager.ring.is_hosting_contract(&key),
"PUT Request: contract {key} must be in hosting list after put_contract + host_contract"
);
// Network peer notification is now automatic via BroadcastStateChange
// event emitted by the executor when state changes. No manual triggering needed.
// Phase 3a (#1454): originator early-response removed;
// task-per-tx driver delivers via send_client_result.
// Step 2: Determine if we should forward or respond
// Build skip list: include sender (upstream) and already-tried peers
let mut new_skip_list = skip_list.clone();
if let Some(addr) = upstream_addr {
new_skip_list.insert(addr);
}
// Add our own address to skip list
if let Some(own_addr) = op_manager.ring.connection_manager.get_own_addr() {
new_skip_list.insert(own_addr);
}
// Find next hop toward contract location
let next_hop = if htl > 0 {
op_manager
.ring
.closest_potentially_hosting(&key, &new_skip_list)
} else {
None
};
// Convert to KnownPeerKeyLocation for compile-time address guarantee
let next_peer_known =
next_hop.and_then(|p| KnownPeerKeyLocation::try_from(p).ok());
if let Some(next_peer) = next_peer_known {
// Forward to next hop
let next_addr = next_peer.socket_addr();
tracing::debug!(
tx = %id,
contract = %key,
peer_addr = %next_addr,
htl = htl - 1,
phase = "forward",
"Forwarding PUT to next hop"
);
// Emit put_request telemetry when forwarding
if let Some(event) = NetEventLog::put_request(
&id,
&op_manager.ring,
key,
PeerKeyLocation::from(next_peer.clone()),
htl.saturating_sub(1),
) {
op_manager.ring.register_events(Either::Left(event)).await;
}
let new_htl = htl.saturating_sub(1);
// Clone merged_value before it's moved into the streaming payload,
// so the originator can retain it for retry.
let merged_value_for_retry = is_originator.then(|| merged_value.clone());
// Check if we should use streaming for the forward
let payload = PutStreamingPayload {
contract: contract.clone(),
related_contracts: related_contracts.clone(),
value: merged_value,
};
let payload_bytes = bincode::serialize(&payload).map_err(|e| {
OpError::NotificationChannelError(format!(
"Failed to serialize streaming payload: {e}"
))
})?;
let payload_size = payload_bytes.len();
let (forward_msg, stream_data) =
if should_use_streaming(op_manager.streaming_threshold, payload_size) {
let sid = StreamId::next_operations();
tracing::info!(
tx = %id,
stream_id = %sid,
payload_size,
"PUT request using operations-level streaming"
);
(
PutMsg::RequestStreaming {
id,
stream_id: sid,
contract_key: key,
total_size: payload_size as u64,
htl: new_htl,
skip_list: new_skip_list,
subscribe,
},
Some((sid, bytes::Bytes::from(payload_bytes))),
)
} else {
(
PutMsg::Request {
id,
contract: payload.contract,
related_contracts: payload.related_contracts,
value: payload.value,
htl: new_htl,
skip_list: new_skip_list,
},
None,
)
};
// Transition to AwaitingResponse, preserving subscribe flags for originator
// Store next_hop so handle_notification_msg can route the message
let new_state = Some(PutState::AwaitingResponse(AwaitingResponseData {
subscribe,
blocking_subscribe,
next_hop: Some(next_addr),
current_htl: htl,
contract_key: key,
tried_peers: {
let mut s = HashSet::new();
s.insert(next_addr);
s
},
alternatives: vec![],
attempts_at_hop: 1,
visited: VisitedPeers::default(),
// Originator retains merged payload for retry; relay peers don't need it.
// Uses merged_value (post put_contract) not the original input value,
// so retries propagate the same state as the primary path.
retry_payload: merged_value_for_retry.map(|val| PutRetryPayload {
contract: contract.clone(),
related_contracts: related_contracts.clone(),
value: val,
}),
}));
stats = Some(PutStats {
target_peer: PeerKeyLocation::from(next_peer.clone()),
contract_location: Location::from(&key),
});
// Send ForwardingAck upstream before forwarding (fire-and-forget).
// Tells the upstream "I received the data, processing it" so the
// GC task can distinguish dead peers from slow multi-hop chains.
//
// The ACK is sent before the actual forward (SendAndContinue) completes
// because the forward happens outside process_message. This is intentional
// and matches GET's pattern (get.rs ForwardingAck). The ACK is advisory
// ("I'm processing this request") not a delivery guarantee ("I successfully
// forwarded it"). If the forward subsequently fails, the GC task's timeout
// will catch it.
if let Some(upstream) = upstream_addr {
let ack = NetMessage::from(PutMsg::ForwardingAck {
id,
contract_key: key,
});
drop(conn_manager.send(upstream, ack).await);
}
Ok(OperationResult::SendAndContinue {
msg: NetMessage::from(forward_msg),
next_hop: Some(next_addr),
state: OpEnum::Put(PutOp {
id,
state: new_state,
upstream_addr,
stats,
ack_received: false,
speculative_paths: 0,
}),
stream_data,
})
} else {
// No next hop - we're the final destination (or htl exhausted)
tracing::info!(
tx = %id,
contract = %key,
phase = "complete",
"PUT complete at this node, sending response"
);
if is_originator {
// We're both originator and final destination
// Emit put_success telemetry with our own location as target
// hop_count is 0 since we stored locally
let own_location = op_manager.ring.connection_manager.own_location();
let hash = Some(state_hash_full(&merged_value));
let size = Some(merged_value.len());
if let Some(event) = NetEventLog::put_success(
&id,
&op_manager.ring,
key,
own_location,
Some(0), // Stored locally, 0 hops
hash,
size,
) {
op_manager.ring.register_events(Either::Left(event)).await;
}
// Start subscription if requested
if subscribe {
start_subscription_after_put(
op_manager,
id,
key,
blocking_subscribe,
)
.await;
}
Ok(OperationResult::ContinueOp(OpEnum::Put(PutOp {
id,
state: Some(PutState::Finished(FinishedData { key })),
upstream_addr: None,
stats,
ack_received: false,
speculative_paths: 0,
})))
} else {
// Non-originator target peer - emit put_success for convergence checking
// Without this event, the target peer's stored state won't be tracked,
// causing convergence checks to fail (they need contracts replicated
// across multiple peers). See issue #2680.
let own_location = op_manager.ring.connection_manager.own_location();
let hash = Some(state_hash_full(&merged_value));
let size = Some(merged_value.len());
if let Some(event) = NetEventLog::put_success(
&id,
&op_manager.ring,
key,
own_location,
None, // hop_count unknown without initial HTL
hash,
size,
) {
op_manager.ring.register_events(Either::Left(event)).await;
}
// Send response back to upstream
let response = PutMsg::Response { id, key };
let upstream =
upstream_addr.expect("non-originator must have upstream");
Ok(OperationResult::SendAndComplete {
msg: NetMessage::from(response),
next_hop: Some(upstream),
stream_data: None,
})
}
}
}
PutMsg::Response { id: _msg_id, key } => {
tracing::info!(
tx = %id,
contract = %key,
is_originator,
subscribe,
phase = "response",
"PUT Response received"
);
if is_originator {
// We're the originator - operation complete!
tracing::info!(
tx = %id,
contract = %key,
elapsed_ms = id.elapsed().as_millis(),
phase = "complete",
"PUT operation completed successfully"
);
let current_htl = match &self.state {
Some(PutState::AwaitingResponse(data)) => Some(data.current_htl),
_ => None,
};
let hop_count = current_htl
.map(|htl| op_manager.ring.max_hops_to_live.saturating_sub(htl));
if let Some(sender) = sender_from_addr.clone() {
finalize_put_at_originator(
op_manager,
id,
*key,
PutFinalizationData {
sender,
hop_count,
state_hash: None,
state_size: None,
},
subscribe,
blocking_subscribe,
)
.await;
}
Ok(OperationResult::ContinueOp(OpEnum::Put(PutOp {
id,
state: Some(PutState::Finished(FinishedData { key: *key })),
upstream_addr: None,
stats,
ack_received: false,
speculative_paths: 0,
})))
} else {
// Forward response to our upstream
let upstream = upstream_addr.expect("non-originator must have upstream");
tracing::debug!(
tx = %id,
contract = %key,
peer_addr = %upstream,
phase = "response",
"Forwarding PUT Response to upstream"
);
let response = PutMsg::Response { id, key: *key };
Ok(OperationResult::SendAndComplete {
msg: NetMessage::from(response),
next_hop: Some(upstream),
stream_data: None,
})
}
}
// Streaming PUT request handler
PutMsg::RequestStreaming {
id: _msg_id,
stream_id,
contract_key,
total_size,
htl,
skip_list,
subscribe: msg_subscribe,
} => {
tracing::info!(
tx = %id,
contract = %contract_key,
stream_id = %stream_id,
total_size,
htl,
is_originator,
phase = "streaming_request",
"Processing PUT RequestStreaming"
);
// Step 1: Claim the stream from orphan registry (atomic dedup)
let peer_addr = match source_addr {
Some(addr) => addr,
None => {
tracing::error!(tx = %id, "source_addr missing for streaming PUT request");
return Err(OpError::UnexpectedOpState);
}
};
let stream_handle = match op_manager
.orphan_stream_registry()
.claim_or_wait(peer_addr, *stream_id, STREAM_CLAIM_TIMEOUT)
.await
{
Ok(handle) => handle,
Err(OrphanStreamError::AlreadyClaimed) => {
tracing::debug!(
tx = %id,
stream_id = %stream_id,
"PUT RequestStreaming skipped — stream already claimed (dedup)"
);
// Push the operation state back since load_or_init popped it.
// Without this, duplicate metadata messages (from embedded fragment #1)
// permanently lose the operation state, preventing ResponseStreaming
// from being matched to the operation.
if self.state.is_some() {
if let Err(e) = op_manager
.push(
id,
OpEnum::Put(PutOp {
id,
state: self.state,
upstream_addr,
stats,
ack_received: false,
speculative_paths: 0,
}),
)
.await
{
tracing::warn!(tx = %id, error = %e, "failed to push PUT op state back after dedup");
}
}
return Err(OpError::OpNotPresent(id));
}
Err(e) => {
tracing::error!(
tx = %id,
stream_id = %stream_id,
error = %e,
"Failed to claim stream from orphan registry"
);
// Push the operation state back to prevent loss
if self.state.is_some() {
if let Err(e) = op_manager
.push(
id,
OpEnum::Put(PutOp {
id,
state: self.state,
upstream_addr,
stats,
ack_received: false,
speculative_paths: 0,
}),
)
.await
{
tracing::warn!(tx = %id, error = %e, "failed to push PUT op state back after orphan claim failure");
}
}
return Err(OpError::OrphanStreamClaimFailed);
}
};
// Step 2: Compute next hop BEFORE assembly (enables piped forwarding)
// Build skip list for routing
let htl = *htl;
let mut routing_skip_list = skip_list.clone();
if let Some(addr) = upstream_addr {
routing_skip_list.insert(addr);
}
if let Some(own_addr) = op_manager.ring.connection_manager.get_own_addr() {
routing_skip_list.insert(own_addr);
}
let next_hop = if htl > 0 {
op_manager
.ring
.closest_potentially_hosting(contract_key, &routing_skip_list)
} else {
None
};
let next_peer_known =
next_hop.and_then(|p| KnownPeerKeyLocation::try_from(p).ok());
// Step 3: Start piping if we have a next hop and streaming is appropriate
// Fork the handle and start forwarding BEFORE we assemble locally
let piping_started = if let Some(ref next_peer) = next_peer_known {
let next_addr = next_peer.socket_addr();
// Check if streaming should be used based on the original stream size
if should_use_streaming(
op_manager.streaming_threshold,
*total_size as usize,
) {
let outbound_sid = StreamId::next_operations();
let forked_handle = stream_handle.fork();
tracing::info!(
tx = %id,
inbound_stream_id = %stream_id,
outbound_stream_id = %outbound_sid,
total_size,
peer_addr = %next_addr,
"Starting piped stream forwarding to next hop"
);
// Send metadata message first
let pipe_metadata = PutMsg::RequestStreaming {
id,
stream_id: outbound_sid,
contract_key: *contract_key,
total_size: *total_size,
htl: htl.saturating_sub(1),
skip_list: routing_skip_list.clone(),
subscribe: *msg_subscribe,
};
let pipe_metadata_net: NetMessage = pipe_metadata.into();
// Serialize metadata for embedding in fragment #1 (fix #2757)
let embedded_metadata = match bincode::serialize(&pipe_metadata_net) {
Ok(bytes) => Some(bytes::Bytes::from(bytes)),
Err(e) => {
tracing::warn!(
tx = %id,
error = %e,
"Failed to serialize piped stream metadata for embedding"
);
None
}
};
conn_manager.send(next_addr, pipe_metadata_net).await?;
// Start piping (runs asynchronously in background)
conn_manager
.pipe_stream(
next_addr,
outbound_sid,
forked_handle,
embedded_metadata,
)
.await?;
// Send ForwardingAck upstream AFTER downstream handoff succeeds.
// If the downstream send failed (returned Err above), we don't
// ACK — so the upstream's GC task will retry after ACK_TIMEOUT
// instead of waiting PROGRESS_TIMEOUT for a stalled chain.
if let Some(upstream) = upstream_addr {
let ack = NetMessage::from(PutMsg::ForwardingAck {
id,
contract_key: *contract_key,
});
drop(conn_manager.send(upstream, ack).await);
}
if let Some(event) = NetEventLog::put_request(
&id,
&op_manager.ring,
*contract_key,
PeerKeyLocation::from(next_peer.clone()),
htl.saturating_sub(1),
) {
op_manager.ring.register_events(Either::Left(event)).await;
}
true
} else {
false
}
} else {
false
};
// Step 4: Wait for stream to complete and assemble data (for local storage)
let stream_data = match stream_handle.assemble().await {
Ok(data) => data,
Err(e) => {
tracing::error!(
tx = %id,
stream_id = %stream_id,
error = %e,
"Failed to assemble stream data"
);
return Err(OpError::StreamCancelled);
}
};
tracing::debug!(
tx = %id,
stream_id = %stream_id,
received_size = stream_data.len(),
expected_size = total_size,
"Stream data assembled"
);
// Step 3: Deserialize the streaming payload
let payload: PutStreamingPayload = match bincode::deserialize(&stream_data) {
Ok(p) => p,
Err(e) => {
tracing::error!(
tx = %id,
stream_id = %stream_id,
error = %e,
"Failed to deserialize streaming payload"
);
return Err(OpError::invalid_transition(id));
}
};
let contract = &payload.contract;
let value = payload.value;
let related_contracts = payload.related_contracts;
let key = contract.key();
// Verify contract key matches
if key != *contract_key {
tracing::error!(
tx = %id,
expected = %contract_key,
actual = %key,
"Contract key mismatch in streaming payload"
);
return Err(OpError::invalid_transition(id));
}
// Step 4: Store contract locally (same as regular Request)
let was_hosting = op_manager.ring.is_hosting_contract(&key);
let (merged_value, _state_changed) = match put_contract(
op_manager,
key,
value.clone(),
related_contracts.clone(),
contract,
)
.await
{
Ok(result) => result,
Err(err) => {
tracing::error!(
tx = %id,
contract = %key,
error = %err,
htl,
is_originator,
"put_contract failed (streaming path)"
);
if let Some(event) = NetEventLog::put_failure(
&id,
&op_manager.ring,
key,
OperationFailure::ContractError(err.to_string()),
Some(op_manager.ring.max_hops_to_live.saturating_sub(htl)),
) {
op_manager.ring.register_events(Either::Left(event)).await;
}
return Err(err);
}
};
// Mark as hosting if not already
if !was_hosting {
let evicted = op_manager
.ring
.host_contract(key, value.size() as u64, crate::ring::AccessType::Put)
.evicted;
if is_originator {
op_manager.ring.mark_local_client_access(&key);
}
super::announce_contract_hosted(op_manager, &key).await;
let mut removed_contracts = Vec::new();
for evicted_key in evicted {
if op_manager
.interest_manager
.unregister_local_hosting(&evicted_key)
{
removed_contracts.push(evicted_key);
}
}
let became_interested =
op_manager.interest_manager.register_local_hosting(&key);
let added = if became_interested { vec![key] } else { vec![] };
if !added.is_empty() || !removed_contracts.is_empty() {
super::broadcast_change_interests(op_manager, added, removed_contracts)
.await;
}
}
// Invariant: after storing and hosting, the contract MUST be in the hosting list.
debug_assert!(
op_manager.ring.is_hosting_contract(&key),
"PUT Streaming: contract {key} must be in hosting list after put_contract + host_contract"
);
// Step 5: Handle forwarding or final destination
if piping_started {
// Piping is already underway - just track state, no need to forward via return
let next_addr = next_peer_known
.as_ref()
.expect("piping_started implies next_peer_known")
.socket_addr();
tracing::debug!(
tx = %id,
contract = %key,
peer_addr = %next_addr,
htl = htl.saturating_sub(1),
phase = "forward",
"PUT piping in progress to next hop"
);
// Forwarding nodes always use non-blocking subscriptions:
// blocking_subscribe is a client-side preference that only
// applies to the originator node.
let new_state = Some(PutState::AwaitingResponse(AwaitingResponseData {
subscribe: *msg_subscribe,
blocking_subscribe: false,
next_hop: Some(next_addr),
current_htl: htl,
contract_key: key,
tried_peers: {
let mut s = HashSet::new();
s.insert(next_addr);
s
},
alternatives: vec![],
attempts_at_hop: 1,
visited: VisitedPeers::default(),
retry_payload: None,
}));
stats = Some(PutStats {
target_peer: PeerKeyLocation::from(
next_peer_known
.as_ref()
.expect("piping_started implies next_peer_known")
.clone(),
),
contract_location: Location::from(&key),
});
// No msg or stream_data needed - piping handles forwarding
Ok(OperationResult::ContinueOp(OpEnum::Put(PutOp {
id,
state: new_state,
upstream_addr,
stats,
ack_received: false,
speculative_paths: 0,
})))
} else if let Some(next_peer) = next_peer_known {
// Next hop exists but piping didn't start (streaming not appropriate for size)
// Forward as non-streaming message
let next_addr = next_peer.socket_addr();
tracing::debug!(
tx = %id,
contract = %key,
peer_addr = %next_addr,
htl = htl - 1,
phase = "forward",
"Forwarding PUT (from streaming) as non-streaming to next hop"
);
if let Some(event) = NetEventLog::put_request(
&id,
&op_manager.ring,
key,
PeerKeyLocation::from(next_peer.clone()),
htl.saturating_sub(1),
) {
op_manager.ring.register_events(Either::Left(event)).await;
}
let new_htl = htl.saturating_sub(1);
let forward_msg = PutMsg::Request {
id,
contract: contract.clone(),
related_contracts,
value: merged_value,
htl: new_htl,
skip_list: routing_skip_list,
};
// Forwarding nodes always use non-blocking subscriptions:
// blocking_subscribe is a client-side preference that only
// applies to the originator node.
let new_state = Some(PutState::AwaitingResponse(AwaitingResponseData {
subscribe: *msg_subscribe,
blocking_subscribe: false,
next_hop: Some(next_addr),
current_htl: htl,
contract_key: key,
tried_peers: {
let mut s = HashSet::new();
s.insert(next_addr);
s
},
alternatives: vec![],
attempts_at_hop: 1,
visited: VisitedPeers::default(),
retry_payload: None,
}));
stats = Some(PutStats {
target_peer: PeerKeyLocation::from(next_peer.clone()),
contract_location: Location::from(&key),
});
// Send ForwardingAck upstream before forwarding (fire-and-forget).
if let Some(upstream) = upstream_addr {
let ack = NetMessage::from(PutMsg::ForwardingAck {
id,
contract_key: key,
});
drop(conn_manager.send(upstream, ack).await);
}
Ok(OperationResult::SendAndContinue {
msg: NetMessage::from(forward_msg),
next_hop: Some(next_addr),
state: OpEnum::Put(PutOp {
id,
state: new_state,
upstream_addr,
stats,
ack_received: false,
speculative_paths: 0,
}),
stream_data: None,
})
} else {
// No next hop - we're the final destination
tracing::info!(
tx = %id,
contract = %key,
phase = "complete",
"Streaming PUT complete at this node"
);
if is_originator {
let own_location = op_manager.ring.connection_manager.own_location();
let hash = Some(state_hash_full(&merged_value));
let size = Some(merged_value.len());
finalize_put_at_originator(
op_manager,
id,
key,
PutFinalizationData {
sender: own_location,
hop_count: Some(0),
state_hash: hash,
state_size: size,
},
*msg_subscribe,
blocking_subscribe,
)
.await;
Ok(OperationResult::ContinueOp(OpEnum::Put(PutOp {
id,
state: Some(PutState::Finished(FinishedData { key })),
upstream_addr: None,
stats,
ack_received: false,
speculative_paths: 0,
})))
} else {
// Send ResponseStreaming back to upstream
let own_location = op_manager.ring.connection_manager.own_location();
let hash = Some(state_hash_full(&merged_value));
let size = Some(merged_value.len());
if let Some(event) = NetEventLog::put_success(
&id,
&op_manager.ring,
key,
own_location,
None,
hash,
size,
) {
op_manager.ring.register_events(Either::Left(event)).await;
}
let upstream =
upstream_addr.expect("non-originator must have upstream");
let response = PutMsg::ResponseStreaming {
id,
key,
continue_forwarding: false,
};
Ok(OperationResult::SendAndComplete {
msg: NetMessage::from(response),
next_hop: Some(upstream),
stream_data: None,
})
}
}
}
// Streaming PUT response handler
PutMsg::ResponseStreaming {
id: _msg_id,
key,
continue_forwarding,
} => {
tracing::info!(
tx = %id,
contract = %key,
continue_forwarding,
is_originator,
phase = "streaming_response",
"Processing PUT ResponseStreaming"
);
// Extract current HTL for telemetry
let current_htl = match &self.state {
Some(PutState::AwaitingResponse(data)) => Some(data.current_htl),
_ => None,
};
if is_originator {
// We initiated the streaming PUT - operation complete
let hop_count = current_htl
.map(|htl| op_manager.ring.max_hops_to_live.saturating_sub(htl));
finalize_put_at_originator(
op_manager,
id,
*key,
PutFinalizationData {
sender: op_manager.ring.connection_manager.own_location(),
hop_count,
state_hash: None,
state_size: None,
},
subscribe,
blocking_subscribe,
)
.await;
tracing::info!(
tx = %id,
contract = %key,
phase = "complete",
"Streaming PUT operation complete (originator)"
);
Ok(OperationResult::ContinueOp(OpEnum::Put(PutOp {
id,
state: Some(PutState::Finished(FinishedData { key: *key })),
upstream_addr: None,
stats,
ack_received: false,
speculative_paths: 0,
})))
} else {
// Forward response to upstream
let upstream = upstream_addr.expect("non-originator must have upstream");
tracing::debug!(
tx = %id,
contract = %key,
peer_addr = %upstream,
phase = "response",
"Forwarding PUT ResponseStreaming to upstream"
);
// Forward as regular Response for simplicity
// (streaming is only needed for large payloads, responses are small)
let response = PutMsg::Response { id, key: *key };
Ok(OperationResult::SendAndComplete {
msg: NetMessage::from(response),
next_hop: Some(upstream),
stream_data: None,
})
}
}
PutMsg::ForwardingAck { id, contract_key } => {
// A downstream relay acknowledged forwarding our PUT request.
// Mark the operation so the GC task knows the peer is alive.
tracing::debug!(
tx = %id,
contract = %contract_key,
phase = "ack",
"Received ForwardingAck from downstream"
);
// Continue waiting for the actual Response
Ok(OperationResult::ContinueOp(OpEnum::Put(PutOp {
id: *id,
state: self.state,
upstream_addr,
stats,
ack_received: true,
speculative_paths: self.speculative_paths,
})))
}
}
})
}
}
/// Telemetry data for originator-side PUT finalization.
pub(super) struct PutFinalizationData {
pub sender: PeerKeyLocation,
pub hop_count: Option<usize>,
pub state_hash: Option<String>,
pub state_size: Option<usize>,
}
/// Originator-side finalization after a PUT has been accepted by the network.
///
/// Emits `put_success` telemetry and, if `subscribe` is true, starts a
/// post-PUT subscription. Called by both the legacy `process_message`
/// originator branches and the task-per-tx driver (Phase 3a).
///
/// The caller is responsible for constructing and delivering the client
/// result (`OperationResult::ContinueOp` on the legacy path,
/// `DriverOutcome::Publish` on the task-per-tx path).
pub(super) async fn finalize_put_at_originator(
op_manager: &OpManager,
id: Transaction,
key: ContractKey,
telemetry: PutFinalizationData,
subscribe: bool,
blocking_subscribe: bool,
) {
if let Some(event) = NetEventLog::put_success(
&id,
&op_manager.ring,
key,
telemetry.sender,
telemetry.hop_count,
telemetry.state_hash,
telemetry.state_size,
) {
op_manager.ring.register_events(Either::Left(event)).await;
}
if subscribe {
start_subscription_after_put(op_manager, id, key, blocking_subscribe).await;
}
}
/// The `blocking_subscription` parameter controls subscription behavior:
/// - When false (default): subscription completes asynchronously and PUT response
/// is sent immediately
/// - When true: PUT response waits for subscription to complete
///
/// This value comes from the client request's `blocking_subscribe` field
/// (`ContractRequest::Put`).
async fn start_subscription_after_put(
op_manager: &OpManager,
parent_tx: Transaction,
key: ContractKey,
blocking_subscription: bool,
) {
// Note: This failed_parents check may be unnecessary since we only spawn the subscription
// at PUT completion, so there's no earlier child operation that could have failed.
// Keeping it as defensive check in case of race conditions not currently understood.
if !op_manager.failed_parents().contains(&parent_tx) {
let child_tx =
super::start_subscription_request(op_manager, parent_tx, key, blocking_subscription);
tracing::debug!(
tx = %parent_tx,
child_tx = %child_tx,
contract = %key,
blocking = blocking_subscription,
phase = "subscribe",
"Started subscription after PUT"
);
} else {
tracing::warn!(
tx = %parent_tx,
contract = %key,
phase = "subscribe",
"Not starting subscription for failed parent PUT operation"
);
}
}
#[allow(dead_code)] // Used in tests; Phase 6 cleanup
pub(crate) fn start_op(
contract: ContractContainer,
related_contracts: RelatedContracts<'static>,
value: WrappedState,
htl: usize,
subscribe: bool,
blocking_subscribe: bool,
) -> PutOp {
let key = contract.key();
let contract_location = Location::from(&key);
tracing::debug!(contract_location = %contract_location, contract = %key, phase = "request", "Requesting put");
let id = Transaction::new::<PutMsg>();
let state = Some(PutState::PrepareRequest(PrepareRequestData {
contract,
related_contracts,
value,
htl,
subscribe,
blocking_subscribe,
}));
PutOp {
id,
state,
upstream_addr: None, // Local operation, no upstream peer
stats: None,
ack_received: false,
speculative_paths: 0,
}
}
/// Create a PUT operation with a specific transaction ID (for operation deduplication)
#[allow(dead_code)] // Used in tests; Phase 6 cleanup
pub(crate) fn start_op_with_id(
contract: ContractContainer,
related_contracts: RelatedContracts<'static>,
value: WrappedState,
htl: usize,
subscribe: bool,
blocking_subscribe: bool,
id: Transaction,
) -> PutOp {
let key = contract.key();
let contract_location = Location::from(&key);
tracing::debug!(contract_location = %contract_location, contract = %key, tx = %id, phase = "request", "Requesting put with existing transaction ID");
let state = Some(PutState::PrepareRequest(PrepareRequestData {
contract,
related_contracts,
value,
htl,
subscribe,
blocking_subscribe,
}));
PutOp {
id,
state,
upstream_addr: None, // Local operation, no upstream peer
stats: None,
ack_received: false,
speculative_paths: 0,
}
}
// State machine for PUT operations.
//
// State transitions:
// - Originator: PrepareRequest → AwaitingResponse → Finished
// - Forwarder: (receives Request) → AwaitingResponse → (receives Response) → done
// - Final node: (receives Request) → stores contract → sends Response → done
//
// ── Type-state data structs ──────────────────────────────────────────────
//
// Each state in the PUT state machine is a named struct with typed
// transition methods. This gives compile-time guarantees:
//
// PrepareRequest ── into_awaiting_response() ──► AwaitingResponse
// AwaitingResponse ── into_finished() ──► Finished
//
// Invalid transitions (e.g. Finished → PrepareRequest) are unrepresentable
// because the target type simply has no such method.
/// Data for the PrepareRequest state: originator preparing initial PUT request.
#[derive(Debug, Clone)]
#[allow(dead_code)] // Phase 6 cleanup: only constructed by now-dead start_op/start_op_with_id
pub struct PrepareRequestData {
pub contract: ContractContainer,
pub related_contracts: RelatedContracts<'static>,
pub value: WrappedState,
pub htl: usize,
/// If true, start a subscription after PUT completes
pub subscribe: bool,
/// If true, the PUT response waits for the subscription to complete
pub blocking_subscribe: bool,
}
impl PrepareRequestData {
/// Transition to AwaitingResponse after sending the PUT request.
///
/// Encodes valid transition: PrepareRequest → AwaitingResponse.
/// The subscribe/blocking_subscribe flags are carried forward.
#[allow(dead_code)] // Documents valid transition; see type-state pattern
pub fn into_awaiting_response(
self,
next_hop: Option<std::net::SocketAddr>,
contract_key: ContractKey,
alternatives: Vec<PeerKeyLocation>,
visited: VisitedPeers,
) -> AwaitingResponseData {
let mut tried_peers = HashSet::new();
if let Some(addr) = next_hop {
tried_peers.insert(addr);
}
AwaitingResponseData {
subscribe: self.subscribe,
blocking_subscribe: self.blocking_subscribe,
next_hop,
current_htl: self.htl,
contract_key,
tried_peers,
alternatives,
attempts_at_hop: 1,
visited,
retry_payload: None,
}
}
}
/// Data for the AwaitingResponse state: waiting for downstream node's response.
#[derive(Debug, Clone)]
pub struct AwaitingResponseData {
/// If true, start a subscription after PUT completes (originator only)
pub subscribe: bool,
/// If true, the PUT response waits for the subscription to complete
pub blocking_subscribe: bool,
/// Next hop address for routing the outbound message
pub next_hop: Option<std::net::SocketAddr>,
/// Current HTL (remaining hops) for hop_count calculation.
pub current_htl: usize,
/// Contract key for retry routing.
pub contract_key: ContractKey,
/// Peers already tried at this hop level.
pub tried_peers: HashSet<std::net::SocketAddr>,
/// Fallback peers at the current hop, ranked by proximity.
pub alternatives: Vec<PeerKeyLocation>,
/// How many peers have been tried at this hop (for HTL reduction on retry).
pub attempts_at_hop: usize,
/// Bloom filter tracking peers visited across all hops (prevents re-routing).
pub visited: VisitedPeers,
/// Retained contract data for retry (originator only).
/// None for relay peers since they don't need to retry with the full payload.
pub retry_payload: Option<PutRetryPayload>,
}
/// Contract data retained by the originator for retry.
#[derive(Debug, Clone)]
pub struct PutRetryPayload {
pub contract: ContractContainer,
pub related_contracts: RelatedContracts<'static>,
pub value: WrappedState,
}
impl AwaitingResponseData {
/// Transition to Finished on successful PUT response.
///
/// Encodes valid transition: AwaitingResponse → Finished.
#[allow(dead_code)] // Documents valid transition; see type-state pattern
pub fn into_finished(self, key: ContractKey) -> FinishedData {
FinishedData { key }
}
}
/// Data for the Finished state: PUT operation completed successfully.
#[derive(Debug, Clone, Copy)]
pub struct FinishedData {
pub key: ContractKey,
}
// ── State enum (wraps the typed structs) ─────────────────────────────────
/// Streaming flow (when enabled and payload > threshold):
/// State machine for PUT operations.
/// - Originator: PrepareRequest → AwaitingResponse → Finished
/// - Forwarder: ReceivedRequest → stores → sends Response → done
#[derive(Debug, Clone)]
#[allow(clippy::large_enum_variant)]
pub enum PutState {
/// Local originator preparing to send initial request.
#[allow(dead_code)]
// Phase 6 cleanup: only constructed by now-dead start_op/start_op_with_id
PrepareRequest(PrepareRequestData),
/// Waiting for response from downstream node.
AwaitingResponse(AwaitingResponseData),
/// Operation completed successfully.
Finished(FinishedData),
}
/// Stores the contract state and returns (new_state, state_changed).
/// `state_changed` is true if the stored state was actually modified
/// (old state != new state), which is needed to trigger UPDATE propagation.
pub(super) async fn put_contract(
op_manager: &OpManager,
key: ContractKey,
state: WrappedState,
related_contracts: RelatedContracts<'static>,
contract: &ContractContainer,
) -> Result<(WrappedState, bool), OpError> {
// after the contract has been cached, push the update query
match op_manager
.notify_contract_handler(ContractHandlerEvent::PutQuery {
key,
state,
related_contracts,
contract: Some(contract.clone()),
})
.await
{
Ok(ContractHandlerEvent::PutResponse {
new_value: Ok(new_val),
state_changed,
}) => {
// Notify any waiters that this contract has been stored
op_manager.notify_contract_stored(&key);
// Invariant: after a successful PUT, the stored state must be non-empty.
// A successful PutResponse with an empty value indicates a contract handler bug.
debug_assert!(
new_val.size() > 0,
"put_contract: stored state must be non-empty after successful PUT for contract {key}"
);
Ok((new_val, state_changed))
}
Ok(ContractHandlerEvent::PutResponse {
new_value: Err(err),
..
}) => {
tracing::error!(contract = %key, error = %err, phase = "error", "Failed to update contract value");
Err(OpError::from(err))
// TODO: not a valid value update, notify back to requester
}
Err(err) => Err(err.into()),
Ok(_) => Err(OpError::UnexpectedOpState),
}
}
mod messages {
use std::{collections::HashSet, fmt::Display};
use freenet_stdlib::prelude::*;
use serde::{Deserialize, Serialize};
use crate::message::{InnerMessage, Transaction};
use crate::ring::Location;
use crate::transport::peer_connection::StreamId;
/// Payload for streaming PUT requests.
/// This struct is serialized and sent via the stream, while the metadata
/// is sent via the RequestStreaming message.
#[derive(Debug, Serialize, Deserialize)]
pub(crate) struct PutStreamingPayload {
pub contract: ContractContainer,
#[serde(deserialize_with = "RelatedContracts::deser_related_contracts")]
pub related_contracts: RelatedContracts<'static>,
pub value: WrappedState,
}
/// PUT operation messages.
///
/// The PUT operation stores a contract and its initial state in the network.
/// It uses hop-by-hop routing: each node forwards toward the contract location
/// and remembers where the request came from to route the response back.
///
/// If a PUT reaches a node that is already subscribed to the contract and the
/// merged state differs from the input, an Update operation is triggered to
/// propagate the change to other subscribers.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub(crate) enum PutMsg {
/// Request to store a contract. Forwarded hop-by-hop toward contract location.
/// Each receiving node:
/// 1. Stores the contract locally (caching)
/// 2. Forwards to the next hop closer to contract location
/// 3. Remembers upstream_addr to route the response back
Request {
id: Transaction,
contract: ContractContainer,
#[serde(deserialize_with = "RelatedContracts::deser_related_contracts")]
related_contracts: RelatedContracts<'static>,
value: WrappedState,
/// Hops to live - decremented at each hop, request fails if reaches 0
htl: usize,
/// Addresses to skip when selecting next hop (prevents loops)
skip_list: HashSet<std::net::SocketAddr>,
},
/// Response indicating the PUT completed. Routed hop-by-hop back to originator
/// using each node's stored upstream_addr.
Response { id: Transaction, key: ContractKey },
/// Streaming request to store a large contract. Used when payload exceeds
/// streaming_threshold (default 64KB). The actual data is sent via a separate
/// stream identified by stream_id.
///
/// This variant is only used when streaming is enabled in config.
RequestStreaming {
id: Transaction,
/// Identifies the stream carrying the contract and state data
stream_id: StreamId,
/// Key of the contract being stored
contract_key: ContractKey,
/// Total size of the streamed payload in bytes
total_size: u64,
/// Hops to live - decremented at each hop
htl: usize,
/// Addresses to skip when selecting next hop
skip_list: HashSet<std::net::SocketAddr>,
/// Whether to subscribe to updates after storing
subscribe: bool,
},
/// Streaming response indicating PUT completed for a streaming request.
/// Sent back to the originator after the stream has been fully received
/// and the contract stored.
ResponseStreaming {
id: Transaction,
key: ContractKey,
/// Whether the receiving node should continue forwarding to other peers
continue_forwarding: bool,
},
/// Lightweight ACK sent by a relay peer back to its upstream when it forwards
/// a PUT request to the next hop. Tells the upstream "I received the data and
/// am processing it" so the GC task can distinguish dead peers from slow
/// multi-hop chains. Fire-and-forget — no response expected.
ForwardingAck {
id: Transaction,
contract_key: ContractKey,
},
}
impl InnerMessage for PutMsg {
fn id(&self) -> &Transaction {
match self {
Self::Request { id, .. }
| Self::Response { id, .. }
| Self::RequestStreaming { id, .. }
| Self::ResponseStreaming { id, .. }
| Self::ForwardingAck { id, .. } => id,
}
}
fn requested_location(&self) -> Option<Location> {
match self {
Self::Request { contract, .. } => Some(Location::from(contract.id())),
Self::Response { key, .. } => Some(Location::from(key.id())),
Self::RequestStreaming { contract_key, .. } => {
Some(Location::from(contract_key.id()))
}
Self::ResponseStreaming { key, .. } => Some(Location::from(key.id())),
Self::ForwardingAck { contract_key, .. } => Some(Location::from(contract_key.id())),
}
}
}
impl Display for PutMsg {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Request {
id, contract, htl, ..
} => {
write!(
f,
"PutRequest(id: {}, key: {}, htl: {})",
id,
contract.key(),
htl
)
}
Self::Response { id, key } => {
write!(f, "PutResponse(id: {}, key: {})", id, key)
}
Self::RequestStreaming {
id,
stream_id,
contract_key,
total_size,
htl,
..
} => {
write!(
f,
"PutRequestStreaming(id: {}, key: {}, stream: {}, size: {}, htl: {})",
id, contract_key, stream_id, total_size, htl
)
}
Self::ResponseStreaming {
id,
key,
continue_forwarding,
} => {
write!(
f,
"PutResponseStreaming(id: {}, key: {}, continue: {})",
id, key, continue_forwarding
)
}
Self::ForwardingAck { id, contract_key } => {
write!(f, "PutForwardingAck(id: {}, key: {})", id, contract_key)
}
}
}
}
}
#[cfg(test)]
#[allow(clippy::wildcard_enum_match_arm)]
mod tests {
use super::*;
use crate::message::Transaction;
use crate::operations::test_utils::{make_contract_key, make_test_contract};
fn make_put_op(state: Option<PutState>) -> PutOp {
PutOp {
id: Transaction::new::<PutMsg>(),
state,
upstream_addr: None,
stats: None,
ack_received: false,
speculative_paths: 0,
}
}
// Tests for finalized() method
#[test]
fn put_op_finalized_when_state_is_none() {
let op = make_put_op(None);
assert!(
op.finalized(),
"PutOp should be finalized when state is None"
);
}
#[test]
fn put_op_finalized_when_state_is_finished() {
let op = make_put_op(Some(PutState::Finished(FinishedData {
key: make_contract_key(1),
})));
assert!(
op.finalized(),
"PutOp should be finalized when state is Finished"
);
}
#[test]
fn put_op_not_finalized_when_awaiting_response() {
let op = make_put_op(Some(PutState::AwaitingResponse(AwaitingResponseData {
subscribe: false,
blocking_subscribe: false,
next_hop: None,
current_htl: 10,
contract_key: make_contract_key(0),
tried_peers: HashSet::new(),
alternatives: vec![],
attempts_at_hop: 1,
visited: VisitedPeers::default(),
retry_payload: None,
})));
assert!(
!op.finalized(),
"PutOp should not be finalized in AwaitingResponse state"
);
}
// Tests for to_host_result() method
#[test]
fn put_op_to_host_result_success_when_finished() {
let key = make_contract_key(1);
let op = make_put_op(Some(PutState::Finished(FinishedData { key })));
let result = op.to_host_result();
assert!(
result.is_ok(),
"to_host_result should return Ok for Finished state"
);
if let Ok(HostResponse::ContractResponse(
freenet_stdlib::client_api::ContractResponse::PutResponse { key: returned_key },
)) = result
{
assert_eq!(returned_key, key, "Returned key should match");
} else {
panic!("Expected PutResponse");
}
}
#[test]
fn put_op_to_host_result_error_when_not_finished() {
let op = make_put_op(Some(PutState::AwaitingResponse(AwaitingResponseData {
subscribe: false,
blocking_subscribe: false,
next_hop: None,
current_htl: 10,
contract_key: make_contract_key(0),
tried_peers: HashSet::new(),
alternatives: vec![],
attempts_at_hop: 1,
visited: VisitedPeers::default(),
retry_payload: None,
})));
let result = op.to_host_result();
assert!(
result.is_err(),
"to_host_result should return Err for non-Finished state"
);
}
#[test]
fn put_op_to_host_result_error_when_none() {
let op = make_put_op(None);
let result = op.to_host_result();
assert!(
result.is_err(),
"to_host_result should return Err when state is None"
);
}
// Tests for is_completed() trait method
#[test]
fn put_op_is_completed_when_finished() {
let op = make_put_op(Some(PutState::Finished(FinishedData {
key: make_contract_key(1),
})));
assert!(
op.is_completed(),
"is_completed should return true for Finished state"
);
}
#[test]
fn put_op_is_not_completed_when_in_progress() {
let op = make_put_op(Some(PutState::AwaitingResponse(AwaitingResponseData {
subscribe: false,
blocking_subscribe: false,
next_hop: None,
current_htl: 10,
contract_key: make_contract_key(0),
tried_peers: HashSet::new(),
alternatives: vec![],
attempts_at_hop: 1,
visited: VisitedPeers::default(),
retry_payload: None,
})));
assert!(
!op.is_completed(),
"is_completed should return false for AwaitingResponse state"
);
}
// Tests for PutMsg helper methods
#[test]
fn put_msg_id_returns_transaction() {
let tx = Transaction::new::<PutMsg>();
let msg = PutMsg::Response {
id: tx,
key: make_contract_key(1),
};
assert_eq!(*msg.id(), tx, "id() should return the transaction ID");
}
#[test]
fn put_msg_display_formats_correctly() {
let tx = Transaction::new::<PutMsg>();
let msg = PutMsg::Response {
id: tx,
key: make_contract_key(1),
};
let display = format!("{}", msg);
assert!(
display.contains("PutResponse"),
"Display should contain message type name"
);
}
// Tests for blocking_subscribe propagation
#[test]
fn start_op_propagates_blocking_subscribe_true() {
let contract = make_test_contract(&[1u8]);
let op = start_op(
contract,
RelatedContracts::default(),
WrappedState::new(vec![]),
10,
true, // subscribe
true, // blocking_subscribe
);
match op.state {
Some(PutState::PrepareRequest(data)) => {
let blocking_subscribe = data.blocking_subscribe;
assert!(
blocking_subscribe,
"blocking_subscribe should be true in PrepareRequest"
);
}
other => panic!("Expected PrepareRequest state, got {:?}", other),
}
}
#[test]
fn start_op_with_id_propagates_blocking_subscribe_true() {
let contract = make_test_contract(&[1u8]);
let tx = Transaction::new::<PutMsg>();
let op = start_op_with_id(
contract,
RelatedContracts::default(),
WrappedState::new(vec![]),
10,
true, // subscribe
true, // blocking_subscribe
tx,
);
match op.state {
Some(PutState::PrepareRequest(data)) => {
let blocking_subscribe = data.blocking_subscribe;
assert!(
blocking_subscribe,
"blocking_subscribe should be true in PrepareRequest via start_op_with_id"
);
}
other => panic!("Expected PrepareRequest state, got {:?}", other),
}
}
// Tests for outcome() method
#[test]
fn put_op_outcome_success_untimed_when_finalized_with_stats() {
use crate::operations::OpOutcome;
use crate::ring::{Location, PeerKeyLocation};
let target_peer = PeerKeyLocation::random();
let contract_location = Location::random();
let op = PutOp {
id: Transaction::new::<PutMsg>(),
state: Some(PutState::Finished(FinishedData {
key: make_contract_key(1),
})),
upstream_addr: None,
stats: Some(PutStats {
target_peer: target_peer.clone(),
contract_location,
}),
ack_received: false,
speculative_paths: 0,
};
match op.outcome() {
OpOutcome::ContractOpSuccessUntimed {
target_peer: peer,
contract_location: loc,
} => {
assert_eq!(*peer, target_peer);
assert_eq!(loc, contract_location);
}
OpOutcome::ContractOpSuccess { .. }
| OpOutcome::ContractOpFailure { .. }
| OpOutcome::Incomplete
| OpOutcome::Irrelevant => {
panic!("Expected ContractOpSuccessUntimed for finalized put with stats")
}
}
}
#[test]
fn put_op_outcome_irrelevant_when_finalized_without_stats() {
use crate::operations::OpOutcome;
let op = PutOp {
id: Transaction::new::<PutMsg>(),
state: Some(PutState::Finished(FinishedData {
key: make_contract_key(1),
})),
upstream_addr: None,
stats: None,
ack_received: false,
speculative_paths: 0,
};
assert!(matches!(op.outcome(), OpOutcome::Irrelevant));
}
#[test]
fn put_op_outcome_failure_when_not_finalized_with_stats() {
use crate::operations::OpOutcome;
use crate::ring::{Location, PeerKeyLocation};
let target_peer = PeerKeyLocation::random();
let contract_location = Location::random();
let op = PutOp {
id: Transaction::new::<PutMsg>(),
state: Some(PutState::AwaitingResponse(AwaitingResponseData {
subscribe: false,
blocking_subscribe: false,
next_hop: None,
current_htl: 10,
contract_key: make_contract_key(0),
tried_peers: HashSet::new(),
alternatives: vec![],
attempts_at_hop: 1,
visited: VisitedPeers::default(),
retry_payload: None,
})),
upstream_addr: None,
stats: Some(PutStats {
target_peer: target_peer.clone(),
contract_location,
}),
ack_received: false,
speculative_paths: 0,
};
match op.outcome() {
OpOutcome::ContractOpFailure {
target_peer: peer,
contract_location: loc,
} => {
assert_eq!(*peer, target_peer);
assert_eq!(loc, contract_location);
}
OpOutcome::ContractOpSuccess { .. }
| OpOutcome::ContractOpSuccessUntimed { .. }
| OpOutcome::Incomplete
| OpOutcome::Irrelevant => {
panic!("Expected ContractOpFailure for non-finalized put with stats")
}
}
}
#[test]
fn put_op_outcome_incomplete_when_not_finalized_without_stats() {
use crate::operations::OpOutcome;
let op = make_put_op(Some(PutState::AwaitingResponse(AwaitingResponseData {
subscribe: false,
blocking_subscribe: false,
next_hop: None,
current_htl: 10,
contract_key: make_contract_key(0),
tried_peers: HashSet::new(),
alternatives: vec![],
attempts_at_hop: 1,
visited: VisitedPeers::default(),
retry_payload: None,
})));
assert!(matches!(op.outcome(), OpOutcome::Incomplete));
}
#[test]
fn put_op_failure_routing_info_with_stats() {
use crate::ring::{Location, PeerKeyLocation};
let target_peer = PeerKeyLocation::random();
let contract_location = Location::random();
let op = PutOp {
id: Transaction::new::<PutMsg>(),
state: None,
upstream_addr: None,
stats: Some(PutStats {
target_peer: target_peer.clone(),
contract_location,
}),
ack_received: false,
speculative_paths: 0,
};
let info = op.failure_routing_info().expect("should have routing info");
assert_eq!(info.0, target_peer);
assert_eq!(info.1, contract_location);
}
#[test]
fn put_op_failure_routing_info_without_stats() {
let op = make_put_op(None);
assert!(op.failure_routing_info().is_none());
}
#[test]
fn start_op_defaults_blocking_subscribe_false() {
let contract = make_test_contract(&[1u8]);
let op = start_op(
contract,
RelatedContracts::default(),
WrappedState::new(vec![]),
10,
true, // subscribe
false, // blocking_subscribe
);
match op.state {
Some(PutState::PrepareRequest(data)) => {
let blocking_subscribe = data.blocking_subscribe;
assert!(
!blocking_subscribe,
"blocking_subscribe should be false by default"
);
}
other => panic!("Expected PrepareRequest state, got {:?}", other),
}
}
/// Verify that start_op creates a PutOp with stats=None initially.
/// Stats should only be populated when a target peer is chosen during forwarding.
#[test]
fn start_op_creates_put_with_no_stats() {
let contract = make_test_contract(&[1u8]);
let op = start_op(
contract,
RelatedContracts::default(),
WrappedState::new(vec![]),
10,
false,
false,
);
assert!(
op.stats.is_none(),
"start_op should create PutOp with stats=None"
);
// Without stats, outcome should be Incomplete (not finalized, no stats)
assert!(matches!(op.outcome(), OpOutcome::Incomplete));
}
/// Simulate a put operation lifecycle: initially no stats, then stats are set
/// when forwarding, then state is Finished → outcome should be SuccessUntimed.
#[test]
fn put_op_stats_lifecycle_from_initial_to_finished() {
use crate::ring::{Location, PeerKeyLocation};
let target_peer = PeerKeyLocation::random();
let contract_location = Location::random();
// Step 1: Initial state - no stats, PrepareRequest
let mut op = PutOp {
id: Transaction::new::<PutMsg>(),
state: Some(PutState::PrepareRequest(PrepareRequestData {
contract: make_test_contract(&[1u8]),
related_contracts: RelatedContracts::default(),
value: WrappedState::new(vec![]),
htl: 10,
subscribe: false,
blocking_subscribe: false,
})),
upstream_addr: None,
stats: None,
ack_received: false,
speculative_paths: 0,
};
assert!(matches!(op.outcome(), OpOutcome::Incomplete));
assert!(op.failure_routing_info().is_none());
// Step 2: Stats are set when forwarding to next peer
op.stats = Some(PutStats {
target_peer: target_peer.clone(),
contract_location,
});
op.state = Some(PutState::AwaitingResponse(AwaitingResponseData {
subscribe: false,
blocking_subscribe: false,
next_hop: None,
current_htl: 9,
contract_key: make_contract_key(0),
tried_peers: HashSet::new(),
alternatives: vec![],
attempts_at_hop: 1,
visited: VisitedPeers::default(),
retry_payload: None,
}));
// Not finalized yet, but has stats → failure
match op.outcome() {
OpOutcome::ContractOpFailure {
target_peer: peer, ..
} => assert_eq!(*peer, target_peer),
OpOutcome::ContractOpSuccess { .. }
| OpOutcome::ContractOpSuccessUntimed { .. }
| OpOutcome::Incomplete
| OpOutcome::Irrelevant => {
panic!("Expected ContractOpFailure for in-progress put with stats")
}
}
assert!(op.failure_routing_info().is_some());
// Step 3: Operation finishes successfully
op.state = Some(PutState::Finished(FinishedData {
key: make_contract_key(1),
}));
match op.outcome() {
OpOutcome::ContractOpSuccessUntimed {
target_peer: peer,
contract_location: loc,
} => {
assert_eq!(*peer, target_peer);
assert_eq!(loc, contract_location);
}
OpOutcome::ContractOpSuccess { .. }
| OpOutcome::ContractOpFailure { .. }
| OpOutcome::Incomplete
| OpOutcome::Irrelevant => {
panic!("Expected ContractOpSuccessUntimed for finished put with stats")
}
}
}
/// Verify that a forwarding node (state=None, stats=None) returns Irrelevant
/// since it is finalized (state is None) but has no routing decision to report.
#[test]
fn put_op_forwarding_node_outcome_is_irrelevant() {
let op = PutOp {
id: Transaction::new::<PutMsg>(),
state: None,
upstream_addr: Some("127.0.0.1:12345".parse().unwrap()),
stats: None,
ack_received: false,
speculative_paths: 0,
};
// state=None → finalized, stats=None → Irrelevant
assert!(op.finalized());
assert!(matches!(op.outcome(), OpOutcome::Irrelevant));
}
#[test]
fn is_client_initiated_true_when_no_upstream() {
let op = make_put_op(None);
assert!(op.is_client_initiated());
}
#[test]
fn is_client_initiated_false_when_forwarded() {
let op = PutOp {
id: Transaction::new::<PutMsg>(),
state: None,
upstream_addr: Some("127.0.0.1:12345".parse().unwrap()),
stats: None,
ack_received: false,
speculative_paths: 0,
};
assert!(!op.is_client_initiated());
}
// === Tests for retry_with_next_alternative ===
use crate::operations::test_utils::make_peer;
fn make_awaiting_put_op(
alternatives: Vec<PeerKeyLocation>,
tried: &[PeerKeyLocation],
retry_payload: Option<PutRetryPayload>,
) -> PutOp {
let id = Transaction::new::<PutMsg>();
let mut tried_peers = HashSet::new();
for p in tried {
if let Some(addr) = p.socket_addr() {
tried_peers.insert(addr);
}
}
PutOp {
id,
state: Some(PutState::AwaitingResponse(AwaitingResponseData {
subscribe: false,
blocking_subscribe: false,
next_hop: None,
current_htl: 7,
contract_key: make_contract_key(0),
tried_peers,
alternatives,
attempts_at_hop: 1,
visited: VisitedPeers::default(),
retry_payload,
})),
upstream_addr: None,
stats: None,
ack_received: false,
speculative_paths: 0,
}
}
fn make_retry_payload() -> PutRetryPayload {
PutRetryPayload {
contract: make_test_contract(&[1u8]),
related_contracts: RelatedContracts::default(),
value: WrappedState::new(vec![42u8]),
}
}
#[test]
fn test_retry_with_next_alternative_uses_local_alternatives() {
let alt1 = make_peer(5001);
let alt2 = make_peer(5002);
let op = make_awaiting_put_op(vec![alt1.clone(), alt2], &[], Some(make_retry_payload()));
let result = op.retry_with_next_alternative(10, &[]);
assert!(result.is_ok(), "Should succeed with local alternatives");
let (new_op, msg) = match result {
Ok(v) => v,
Err(_) => panic!("Should succeed with local alternatives"),
};
match &msg {
PutMsg::Request { htl, .. } => {
assert!(*htl <= 10);
}
other => panic!("Expected PutMsg::Request, got {other}"),
}
if let Some(PutState::AwaitingResponse(data)) = &new_op.state {
assert_eq!(data.alternatives.len(), 1);
assert!(data.tried_peers.contains(&alt1.socket_addr().unwrap()));
} else {
panic!("Expected AwaitingResponse state");
}
}
#[test]
fn test_retry_with_next_alternative_no_alternatives_returns_err() {
let op = make_awaiting_put_op(vec![], &[], Some(make_retry_payload()));
let result = op.retry_with_next_alternative(10, &[]);
assert!(
result.is_err(),
"Should fail with no alternatives and no fallback"
);
}
#[test]
fn test_retry_with_next_alternative_no_retry_payload_returns_err() {
let alt = make_peer(5010);
let op = make_awaiting_put_op(vec![alt], &[], None);
let result = op.retry_with_next_alternative(10, &[]);
assert!(
result.is_err(),
"Should fail without retry payload (relay peer)"
);
// Verify state is preserved
let returned = match result {
Err(op) => op,
Ok(_) => panic!("Expected Err"),
};
assert!(matches!(
&returned.state,
Some(PutState::AwaitingResponse(_))
));
}
#[test]
fn test_retry_with_next_alternative_dbf_fallback() {
let fallback1 = make_peer(5020);
let fallback2 = make_peer(5021);
let op = make_awaiting_put_op(vec![], &[], Some(make_retry_payload()));
let result = op.retry_with_next_alternative(10, &[fallback1.clone(), fallback2]);
assert!(result.is_ok(), "Should succeed with DBF fallback peers");
let (new_op, _msg) = match result {
Ok(v) => v,
Err(_) => panic!("Should succeed with DBF fallback"),
};
if let Some(PutState::AwaitingResponse(data)) = &new_op.state {
assert_eq!(data.alternatives.len(), 1);
assert!(data.tried_peers.contains(&fallback1.socket_addr().unwrap()));
} else {
panic!("Expected AwaitingResponse state");
}
}
#[test]
fn test_retry_with_next_alternative_htl_reduction() {
let alt1 = make_peer(5030);
let alt2 = make_peer(5031);
let alt3 = make_peer(5032);
let op = make_awaiting_put_op(vec![alt1, alt2, alt3], &[], Some(make_retry_payload()));
// attempts_at_hop starts at 1, retry increments to 2 → 10/2 = 5
let (op, msg) = match op.retry_with_next_alternative(10, &[]) {
Ok(v) => v,
Err(_) => panic!("retry 1 failed"),
};
match &msg {
PutMsg::Request { htl, .. } => {
assert_eq!(*htl, 5, "First retry: 10/2=5");
}
other => panic!("Expected Request, got {other}"),
}
// attempts_at_hop becomes 3 → 10/3 = 3 (MIN_RETRY_HTL)
let (op, msg) = match op.retry_with_next_alternative(10, &[]) {
Ok(v) => v,
Err(_) => panic!("retry 2 failed"),
};
match &msg {
PutMsg::Request { htl, .. } => {
assert_eq!(*htl, MIN_RETRY_HTL, "Second retry: 10/3=3");
}
other => panic!("Expected Request, got {other}"),
}
// attempts_at_hop becomes 4 → 10/4 = 2 → clamped to MIN_RETRY_HTL=3
let (_op, msg) = match op.retry_with_next_alternative(10, &[]) {
Ok(v) => v,
Err(_) => panic!("retry 3 failed"),
};
match &msg {
PutMsg::Request { htl, .. } => {
assert_eq!(*htl, MIN_RETRY_HTL, "Third retry: clamped to MIN_RETRY_HTL");
}
other => panic!("Expected Request, got {other}"),
}
}
#[test]
fn test_retry_with_next_alternative_wrong_state_returns_err() {
let op = PutOp {
id: Transaction::new::<PutMsg>(),
state: Some(PutState::Finished(FinishedData {
key: make_contract_key(1),
})),
upstream_addr: None,
stats: None,
ack_received: false,
speculative_paths: 0,
};
let result = op.retry_with_next_alternative(10, &[]);
assert!(result.is_err(), "Finished state should return Err");
}
#[test]
fn test_forwarding_ack_serde_roundtrip() {
let tx = Transaction::new::<PutMsg>();
let key = make_contract_key(42);
let msg = PutMsg::ForwardingAck {
id: tx,
contract_key: key,
};
let serialized = bincode::serialize(&msg).expect("serialize");
let deserialized: PutMsg = bincode::deserialize(&serialized).expect("deserialize");
match deserialized {
PutMsg::ForwardingAck { id, contract_key } => {
assert_eq!(id, tx);
assert_eq!(contract_key, key);
}
other => panic!("Expected ForwardingAck, got {other}"),
}
}
// ── Intermediate node stats tracking tests (#3527) ─────────────────────
/// Non-finalized PUT with stats reports ContractOpFailure on timeout.
#[test]
fn test_put_failure_outcome_with_stats() {
let target = make_peer(9001);
let contract_key = make_contract_key(42);
let contract_location = Location::from(&contract_key);
let op = PutOp {
id: Transaction::new::<PutMsg>(),
state: Some(PutState::AwaitingResponse(AwaitingResponseData {
subscribe: false,
blocking_subscribe: false,
current_htl: 10,
contract_key,
next_hop: target.socket_addr(),
alternatives: vec![],
tried_peers: HashSet::new(),
attempts_at_hop: 1,
visited: VisitedPeers::default(),
retry_payload: None,
})),
upstream_addr: Some("127.0.0.1:12345".parse().unwrap()),
stats: Some(PutStats {
target_peer: target.clone(),
contract_location,
}),
ack_received: false,
speculative_paths: 0,
};
assert!(!op.finalized());
match op.outcome() {
OpOutcome::ContractOpFailure {
target_peer,
contract_location: loc,
} => {
assert_eq!(target_peer, &target);
assert_eq!(loc, contract_location);
}
other => panic!("Expected ContractOpFailure, got {:?}", other),
}
}
/// Non-finalized PUT without stats reports Incomplete.
#[test]
fn test_put_failure_outcome_without_stats() {
let contract_key = make_contract_key(42);
let op = PutOp {
id: Transaction::new::<PutMsg>(),
state: Some(PutState::AwaitingResponse(AwaitingResponseData {
subscribe: false,
blocking_subscribe: false,
current_htl: 10,
contract_key,
next_hop: None,
alternatives: vec![],
tried_peers: HashSet::new(),
attempts_at_hop: 1,
visited: VisitedPeers::default(),
retry_payload: None,
})),
upstream_addr: Some("127.0.0.1:12345".parse().unwrap()),
stats: None,
ack_received: false,
speculative_paths: 0,
};
assert!(!op.finalized());
assert!(
matches!(op.outcome(), OpOutcome::Incomplete),
"PUT without stats should return Incomplete"
);
}
/// retry_with_next_alternative updates stats.target_peer to the new target.
#[test]
fn test_put_retry_updates_stats_target() {
let original_target = make_peer(9001);
let alternative = make_peer(9002);
let contract_key = make_contract_key(42);
let contract_location = Location::from(&contract_key);
let op = PutOp {
id: Transaction::new::<PutMsg>(),
state: Some(PutState::AwaitingResponse(AwaitingResponseData {
subscribe: false,
blocking_subscribe: false,
current_htl: 10,
contract_key,
next_hop: original_target.socket_addr(),
alternatives: vec![alternative.clone()],
tried_peers: HashSet::new(),
attempts_at_hop: 1,
visited: VisitedPeers::default(),
retry_payload: Some(PutRetryPayload {
contract: make_test_contract(&[0u8]),
related_contracts: RelatedContracts::new(),
value: WrappedState::new(vec![1, 2, 3]),
}),
})),
upstream_addr: None,
stats: Some(PutStats {
target_peer: original_target,
contract_location,
}),
ack_received: false,
speculative_paths: 0,
};
let (new_op, _msg) = match op.retry_with_next_alternative(10, &[]) {
Ok(result) => result,
Err(_) => panic!("retry should succeed with available alternative"),
};
let stats = new_op.stats.expect("stats should be present after retry");
assert_eq!(
stats.target_peer.socket_addr(),
alternative.socket_addr(),
"Stats target_peer should be updated to the alternative peer"
);
}
}