openraft 0.10.2

Advanced Raft consensus
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
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
//! Public Raft interface and data types.
//!
//! [`Raft`] serves as the primary interface to a Raft node,
//! facilitating all interactions with the underlying RaftCore.
//!
//! While `RaftCore` operates as a singleton within an application, [`Raft`] instances are designed
//! to be cheaply cloneable.
//! This allows multiple components within the application that require interaction with `RaftCore`
//! to efficiently share access.

pub(crate) mod api;
#[cfg(test)]
mod declare_raft_types_test;
mod impl_raft_blocking_write;
pub mod linearizable_read;
pub(crate) mod message;
mod raft_inner;
pub mod responder;
mod runtime_config_handle;
pub(crate) mod stream_append;
pub mod trigger;
mod watch_handle;

pub(crate) use api::app::AppApi;
pub(crate) use api::management::ManagementApi;
pub(crate) use api::protocol::ProtocolApi;

pub(in crate::raft) mod core_state;
mod leader;

use std::fmt::Debug;
use std::future::Future;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;

use core_state::CoreState;
use derive_more::Display;
use futures_util::FutureExt;
use linearizable_read::Linearizer;
use linearizable_read::LinearizerOption;
use linearizable_read::ReadLogId;
pub use message::AppendEntriesRequest;
#[allow(deprecated)]
pub use message::AppendEntriesResponse;
pub use message::AppendError;
pub use message::AppendResult;
pub use message::ChangeMembershipOutcome;
pub use message::ChangeMembershipRequest;
pub use message::ClientWriteResponse;
pub use message::ClientWriteResult;
pub use message::ConflictHint;
#[allow(deprecated)]
pub use message::InstallSnapshotRequest;
#[allow(deprecated)]
pub use message::InstallSnapshotResponse;
pub use message::LogSegment;
pub use message::Precondition;
pub use message::SnapshotResponse;
pub use message::StreamAppendError;
pub use message::TransferLeaderError;
pub use message::TransferLeaderRequest;
pub use message::TransferLeaderResponse;
pub use message::VoteRequest;
pub use message::VoteResponse;
pub use message::WriteManyRequest;
pub use message::WriteOption;
pub use message::WriteRequest;
pub use message::WriteResponse;
pub use message::WriteResult;
use openraft_macros::since;
pub use stream_append::StreamAppendResult;
use tracing::Instrument;
use tracing::Level;
use tracing::trace_span;

pub use self::leader::Leader;
pub use self::watch_handle::WatchChangeHandle;
use crate::Extensions;
use crate::LogIdOptionExt;
use crate::OptionalSend;
use crate::RaftNetworkFactory;
use crate::RaftState;
pub use crate::RaftTypeConfig;
use crate::StorageError;
use crate::StorageHelper;
use crate::async_runtime::Mpsc;
use crate::async_runtime::MpscWeakSender;
use crate::async_runtime::OneshotSender;
use crate::async_runtime::Select2;
use crate::async_runtime::mpsc::MpscSender;
use crate::async_runtime::watch::WatchReceiver;
use crate::base::BoxFuture;
use crate::base::BoxOnce;
use crate::base::BoxStream;
use crate::config::Config;
use crate::config::ConfigError;
use crate::config::RuntimeConfig;
use crate::core::ClientResponderQueue;
use crate::core::DeadlineNotifier;
use crate::core::IoBroadcast;
use crate::core::LeaseReadStatePublisher;
use crate::core::MetricsChannels;
use crate::core::PendingReadQueue;
use crate::core::RaftCore;
use crate::core::SharedReplicateBatch;
use crate::core::StepDownWatcher;
use crate::core::heartbeat::handle::HeartbeatWorkersHandle;
pub use crate::core::io_flush_tracking::AppliedProgress;
pub use crate::core::io_flush_tracking::CommitProgress;
pub use crate::core::io_flush_tracking::FlushPoint;
use crate::core::io_flush_tracking::IoProgressWatcher;
pub use crate::core::io_flush_tracking::LogProgress;
pub use crate::core::io_flush_tracking::SnapshotProgress;
pub use crate::core::io_flush_tracking::VoteProgress;
use crate::core::merged_raft_msg_receiver::BatchRaftMsgReceiver;
use crate::core::notification::Notification;
use crate::core::notification_channel::NotificationChannel;
use crate::core::raft_msg::RaftMsg;
use crate::core::raft_msg::external_command::ExternalCommand;
use crate::core::raft_msg::install_full_snapshot_request::InstallFullSnapshotRequest;
use crate::core::runtime_stats::RuntimeStats;
use crate::core::sm;
use crate::core::sm::worker;
use crate::engine::Engine;
use crate::engine::EngineConfig;
use crate::entry::RaftPayload;
use crate::errors::ClientWriteError;
use crate::errors::Fatal;
use crate::errors::ForwardReason;
use crate::errors::ForwardToLeader;
use crate::errors::InitializeError;
use crate::errors::LinearizableReadError;
use crate::errors::RaftError;
use crate::errors::ShutdownError;
use crate::errors::into_raft_result::IntoRaftResult;
use crate::membership::RaftMembership;
use crate::membership::RaftMembershipExt;
use crate::metrics::MetricsRecorder;
use crate::metrics::RaftDataMetrics;
use crate::metrics::RaftMetrics;
use crate::metrics::RaftServerMetrics;
use crate::metrics::Wait;
use crate::metrics::WaitError;
use crate::network::NetSnapshot;
use crate::raft::raft_inner::RaftInner;
pub use crate::raft::runtime_config_handle::RuntimeConfigHandle;
use crate::raft::trigger::Trigger;
use crate::raft_state::IOId;
use crate::storage::RaftLogStorage;
use crate::storage::RaftStateMachine;
use crate::type_config::TypeConfigExt;
use crate::type_config::alias::JoinErrorOf;
use crate::type_config::alias::LogIdOf;
use crate::type_config::alias::MpscOf;
use crate::type_config::alias::MpscSenderOf;
use crate::type_config::alias::MpscWeakSenderOf;
use crate::type_config::alias::NodeIdOf;
use crate::type_config::alias::SnapshotOf;
use crate::type_config::alias::VoteOf;
use crate::type_config::alias::WatchReceiverOf;
use crate::type_config::alias::WriteResponderOf;
use crate::vote::Vote;
use crate::vote::leader_id::raft_leader_id::RaftLeaderId;
use crate::vote::leader_id::raft_leader_id::RaftLeaderIdExt;
use crate::vote::non_committed::UncommittedVote;
use crate::vote::raft_vote::RaftVote;
use crate::vote::raft_vote::RaftVoteExt;

/// Define types for a Raft type configuration.
///
/// Since Rust has some limitations when deriving traits for types with generic arguments
/// and most types are parameterized by [`RaftTypeConfig`], we need to add supertraits to
/// a type implementing [`RaftTypeConfig`].
///
/// This macro does exactly that.
///
/// Example:
/// ```ignore
/// openraft::declare_raft_types!(
///    pub TypeConfig:
///        D            = ClientRequest,
///        R            = ClientResponse,
///        NodeId       = u64,
///        Node         = openraft::impls::BasicNode,
///        Term         = u64,
///        LeaderId     = openraft::impls::leader_id_adv::LeaderId<Self::Term, Self::NodeId>,
///        Vote           = openraft::impls::Vote<Self::LeaderId>,
///        Membership     = openraft::impls::Membership<Self::NodeId, Self::Node>,
///        Payload        = openraft::impls::EntryPayload<Self::D, Self::Membership>,
///        Entry          = openraft::impls::Entry<
///            <Self::LeaderId as openraft::vote::RaftLeaderId>::Committed,
///            Self::Payload,
///        >,
///        Responder<T>   = openraft::impls::OneshotResponder<Self, T>,
///        AsyncRuntime   = openraft::impls::TokioRuntime,
/// );
/// ```
///
/// A generic associated type, `Responder<T>` or `Batch<T>`, is written with its type parameter, as
/// in the example above. The macro adds the `where T: OptionalSend + 'static` bound that
/// [`RaftTypeConfig`] declares for it, so an entry does not write its own `where` clause.
///
/// Attributes before the type name, such as a doc comment or `#[derive(Hash)]`, apply to the
/// generated struct. A `#[cfg(...)]` among them also applies to its [`RaftTypeConfig`]
/// implementation, so a declaration whose `cfg` is false leaves neither item. Every other
/// attribute, `#[cfg_attr(...)]` included, applies to the struct only. A macro that forwards a
/// `cfg` to this one must pass it as tokens, such as with `$(#[$($attr:tt)*])*`: a `cfg` forwarded
/// as a `meta` fragment applies to the struct only.
///
/// Types can be omitted, and the following default type will be used:
/// - `D`:              `String`
/// - `R`:              `String`
/// - `NodeId`:         `u64`
/// - `Node`:           `::openraft::impls::BasicNode`
/// - `Term`:           `u64`
/// - `LeaderId`:       `::openraft::impls::leader_id_adv::LeaderId<Self::Term, Self::NodeId>`
/// - `Vote`:           `::openraft::impls::Vote<Self::LeaderId>`
/// - `Membership`:     `::openraft::impls::Membership<Self::NodeId, Self::Node>`
/// - `MembershipEdit`: `::openraft::impls::ChangeMembers<Self::NodeId, Self::Node>`
/// - `Payload`:        `::openraft::impls::EntryPayload<Self::D, Self::Membership>`
/// - `Entry`:          `::openraft::alias::DefaultEntryOf<Self>`
/// - `Responder<T>`:   `::openraft::impls::ProgressResponder<Self, T>`
/// - `Batch<T>`:       `::openraft::impls::InlineBatch<T>`
/// - `AsyncRuntime`:   `::openraft::impls::TokioRuntime`
/// - `ErrorSource`:    `::openraft::impls::BoxedErrorSource`
///
/// For example, to declare with only `D` and `R` types:
/// ```ignore
/// openraft::declare_raft_types!(
///    pub TypeConfig:
///        D = ClientRequest,
///        R = ClientResponse,
/// );
/// ```
///
/// Or just use the default type config:
/// ```ignore
/// openraft::declare_raft_types!(pub TypeConfig);
/// ```
#[macro_export]
macro_rules! declare_raft_types {
    // Add a trailing colon to    `declare_raft_types(MyType)`,
    // Make it the standard form: `declare_raft_types(MyType:)`.
    // Attributes pass as tokens, so that the main entry still finds a `cfg` among them.
    ($(#[$($outer:tt)*])* $visibility:vis $id:ident) => {
        $crate::declare_raft_types!($(#[$($outer)*])* $visibility $id:);
    };

    // The main entry of this macro
    // Attributes are matched as tokens, not as `meta` fragments: a fragment is opaque to later
    // matching, so a `cfg` in one could not be picked out.
    ($(#[$($outer:tt)*])* $visibility:vis $id:ident: $($(#[$inner:meta])* $type_id:ident $(<$type_param:ident>)? = $type:ty),* $(,)? ) => {
        $(#[$($outer)*])*
        #[derive(Debug, Clone, Copy, Default, Eq, PartialEq, Ord, PartialOrd)]
        $visibility struct $id {}

        // The impl takes only the `cfg` attributes of the struct: a disabled struct must leave no
        // impl behind, and other attributes, such as `derive`, do not apply to an impl.
        $crate::__declare_raft_types_cfg!([$(#[$($outer)*])*] [] impl $crate::RaftTypeConfig for $id {
            // `expand!(KEYED, ...)` ignores the duplicates of a type name.
            // Thus by appending default types after user defined types,
            // the absent user defined types are filled with default types.
            // A generic type gets the bound that `RaftTypeConfig` declares for it.
            $crate::macros::expand!(
                KEYED,
                (N, P, ATTR, V) => {ATTR type N P = V;},
                $(($type_id, $(<$type_param>)?, $(#[$inner])*, $type $(where $type_param: $crate::OptionalSend + 'static)?),)*

                // Default types:
                (D              , , , String                                       ),
                (R              , , , String                                       ),
                (NodeId         , , , u64                                          ),
                (Node           , , , $crate::impls::BasicNode                     ),
                (Term           , , , u64                                          ),
                (LeaderId       , , , $crate::impls::leader_id_adv::LeaderId<Self::Term, Self::NodeId> ),
                (Vote           , , , $crate::impls::Vote<Self::LeaderId>            ),
                (Membership     , , , $crate::impls::Membership<Self::NodeId, Self::Node> ),
                (MembershipEdit , , , $crate::impls::ChangeMembers<Self::NodeId, Self::Node> ),
                (Payload        , , , $crate::impls::EntryPayload<Self::D, Self::Membership> ),
                (Entry          , , , $crate::impls::Entry<<Self::LeaderId as $crate::vote::RaftLeaderId>::Committed, Self::Payload> ),
                (Responder      , <T>, , $crate::impls::ProgressResponder<Self, T> where T: $crate::OptionalSend + 'static ),
                (Batch          , <T>, , $crate::impls::InlineBatch<T> where T: $crate::OptionalSend + 'static ),
                (AsyncRuntime   , , , $crate::impls::TokioRuntime                  ),
                (ErrorSource    , , , $crate::impls::BoxedErrorSource               ),
            );

        });
    };
}

/// Emits an item under only the `#[cfg(...)]` attributes of an attribute list.
///
/// `__declare_raft_types_cfg!([attributes] [] item)` moves each `#[cfg(...)]` of `attributes` into
/// the second list and drops every other attribute, then emits `item` under the collected ones.
/// `declare_raft_types!` gates its `RaftTypeConfig` impl with it.
#[doc(hidden)]
#[macro_export]
macro_rules! __declare_raft_types_cfg {
    ([#[cfg($($predicate:tt)*)] $($attrs:tt)*] [$($cfgs:tt)*] $($item:tt)*) => {
        $crate::__declare_raft_types_cfg!([$($attrs)*] [$($cfgs)* #[cfg($($predicate)*)]] $($item)*);
    };

    ([#[$($attr:tt)*] $($attrs:tt)*] [$($cfgs:tt)*] $($item:tt)*) => {
        $crate::__declare_raft_types_cfg!([$($attrs)*] [$($cfgs)*] $($item)*);
    };

    ([] [$($cfgs:tt)*] $($item:tt)*) => {
        $($cfgs)*
        $($item)*
    };
}

/// Policy that determines how to handle read operations in a Raft cluster.
///
/// This enum defines strategies for ensuring linearizable reads in distributed systems
/// while balancing between consistency guarantees and performance.
#[derive(Clone, Debug, Display, PartialEq, Eq)]
pub enum ReadPolicy {
    /// Uses leader lease to avoid network round-trips for read operations.
    ///
    /// With `LeaseRead`, the leader can serve reads locally without contacting followers
    /// as long as it believes its leadership lease is still valid. This provides better
    /// performance compared to `ReadIndex` but assumes clock drift between nodes is negligible.
    /// It returns an error immediately when the lease is stale.
    ///
    /// Note: This offers slightly weaker consistency guarantees than `ReadIndex` in exchange
    /// for lower latency.
    LeaseRead,

    /// Implements the ReadIndex protocol to ensure linearizable reads.
    ///
    /// With `ReadIndex`, the leader confirms its leadership status by contacting a quorum
    /// of followers before serving read requests. This ensures strong consistency but incurs
    /// the cost of network communication for each read operation.
    ///
    /// This is the safer option that provides the strongest consistency guarantees.
    ReadIndex,
}

/// Primary interface to a Raft node.
///
/// `Raft` provides the complete implementation of the Raft consensus protocol and serves as the
/// main interface for interacting with a Raft node in the cluster. Applications built on Raft use
/// this type to spawn a Raft task and communicate with it.
///
/// # Architecture
///
/// The `Raft` handle is a lightweight wrapper around an `Arc<RaftInner>`, making it cheap to clone.
/// The actual work is performed by an internal core task, which runs separately processing
/// requests through message channels.
///
/// # Lifecycle
///
/// 1. **Creation**: Use [`Raft::new`] to create and spawn a new Raft node, or use [`Raft::build`]
///    followed by [`Raft::run`] when application setup must finish before Raft starts
/// 2. **Initialization**: Call [`initialize`](Raft::initialize) on pristine nodes to form a cluster
/// 3. **Operation**: Use various methods to interact with the node:
///    - Protocol RPCs: [`append_entries`](Raft::append_entries), [`vote`](Raft::vote)
///    - Client operations: [`client_write`](Raft::client_write),
///      [`ensure_linearizable`](Raft::ensure_linearizable)
///    - Management: [`trigger`](Raft::trigger), [`metrics`](Raft::metrics)
/// 4. **Shutdown**: Call [`shutdown`](Raft::shutdown) to gracefully stop the node
///
/// # Cloning
///
/// `Raft` implements [`Clone`] with very low cost, allowing multiple components in your application
/// to hold handles to the same Raft node. All clones reference the same underlying Raft instance.
///
/// # Error Handling
///
/// Methods return [`RaftError::Fatal`] when the Raft node encounters unrecoverable errors or is
/// shutting down. Applications should monitor for fatal errors and initiate shutdown if needed.
///
/// # Examples
///
/// ```ignore
/// // Create a new Raft node
/// let raft = Raft::new(node_id, config, network, log_store, state_machine).await?;
///
/// // Initialize a new cluster
/// raft.initialize(btreeset![1, 2, 3]).await?;
///
/// // Write to the cluster
/// let response = raft.client_write(my_request).await?;
///
/// // Read linearizably
/// raft.ensure_linearizable(ReadPolicy::ReadIndex).await?;
/// let data = raft.with_state_machine(|sm| { sm.read("key") }).await?;
///
/// // Monitor metrics
/// let metrics = raft.metrics().borrow_watched();
/// println!("Current leader: {:?}", metrics.current_leader);
/// ```
///
/// # See Also
///
/// - [Raft specification](https://raft.github.io/raft.pdf) for protocol details
/// - [`Config`] for configuration options
/// - [`RaftMetrics`] for monitoring cluster state
#[since(version = "0.10.0", change = "added SM state machine type parameter")]
pub struct Raft<C, SM = ()>
where
    C: RaftTypeConfig,
    SM: RaftStateMachine<C>,
{
    inner: Arc<RaftInner<C>>,
    sm_cmd_tx: MpscWeakSenderOf<C, sm::Command<C, SM>>,

    /// Sender of the dedicated channel that delivers a full snapshot to RaftCore.
    ///
    /// The snapshot data type is defined by the state machine, thus it does not go through
    /// the [`RaftMsg`] channel, which is independent of the state machine type.
    ///
    /// [`RaftMsg`]: crate::core::raft_msg::RaftMsg
    install_snapshot_tx: MpscSenderOf<C, Box<InstallFullSnapshotRequest<C, SM>>>,
}

impl<C, SM> Clone for Raft<C, SM>
where
    C: RaftTypeConfig,
    SM: RaftStateMachine<C>,
{
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            sm_cmd_tx: self.sm_cmd_tx.clone(),
            install_snapshot_tx: self.install_snapshot_tx.clone(),
        }
    }
}

impl<C, SM> Debug for Raft<C, SM>
where
    C: RaftTypeConfig,
    SM: RaftStateMachine<C>,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Raft").field("id", &self.inner.id).finish()
    }
}

/// Forwarder task that bridges IO completion Watch channel to notification channel.
///
/// This task reads IO completion results from a Watch channel and forwards them
/// to the RaftCore notification channel, translating IOId and storage errors to notifications.
///
/// To reduce wakeup overhead, notifications are batched: at most one notification
/// is forwarded per `BATCH_INTERVAL`. When a change arrives, the forwarder waits
/// until the interval expires before reading and forwarding the latest value.
async fn io_completion_forwarder<C>(
    mut rx_io: WatchReceiverOf<C, Result<IOId<C>, StorageError<C>>>,
    weak_tx_notify: MpscWeakSenderOf<C, Notification<C>>,
) where
    C: RaftTypeConfig,
{
    const BATCH_INTERVAL: Duration = Duration::from_micros(1);

    loop {
        let deadline = C::now() + BATCH_INTERVAL;

        // Wait for IO completion notification
        if rx_io.changed().await.is_err() {
            // Watch sender dropped, exit forwarder
            tracing::debug!("IO completion watch channel closed, forwarder exiting");
            break;
        }

        let now = C::now();
        if now < deadline {
            C::sleep_until(deadline).await;

            // Drain all the changed events.
            let _ = rx_io.changed().now_or_never();
        }

        // Read the latest value after batching interval
        let result = {
            let borrowed = rx_io.borrow_watched();
            borrowed.clone()
        };

        // Try to upgrade weak sender
        let Some(tx) = weak_tx_notify.upgrade() else {
            tracing::debug!("Notification channel closed, forwarder exiting");
            break;
        };

        // Forward the result to notification channel
        let notification = match result {
            Ok(io_id) => Notification::LocalIO { io_id },
            Err(storage_error) => Notification::StorageError { error: storage_error },
        };

        if let Err(e) = tx.send(notification).await {
            tracing::warn!("failed to forward IO completion: {}", e.0);
            break;
        }
    }
}

impl<C, SM> Raft<C, SM>
where
    C: RaftTypeConfig,
    SM: RaftStateMachine<C>,
{
    /// Create and spawn a new Raft task.
    ///
    /// ### `id`
    /// The ID which the spawned Raft task will use to identify itself within the cluster.
    /// Applications must guarantee that the ID provided to this function is stable, and should be
    /// persisted in a well known location, probably alongside the Raft log and the application's
    /// state machine. This ensures that restarts of the node will yield the same ID every time.
    ///
    /// ### `config`
    /// Raft's runtime config. See the docs on the `Config` object for more details. A channel
    /// size that the runtime's channels do not accept makes this return [`RaftError::APIError`]
    /// with [`ConfigError::ChannelSizeOutOfRange`], naming the field, before any task starts. A
    /// storage error while it recovers the initial state is a [`RaftError::Fatal`].
    ///
    /// ### `network`
    /// An implementation of the [`RaftNetworkFactory`] trait which will be used by Raft for
    /// sending RPCs to peer nodes within the cluster.
    ///
    /// ### `storage`
    /// An implementation of the [`RaftLogStorage`] and [`RaftStateMachine`] trait which will be
    /// used by Raft for data storage.
    ///
    /// ### Recovering committed state on startup
    /// `new()` returns as soon as the node task is spawned, but the state machine may still lag the
    /// state it had before a restart — see [`RaftLogStorage::save_committed`]. An
    /// application that serves reads immediately (especially when `committed` is not persisted) may
    /// then observe a reverted state. To prevent that, await
    /// [`wait_for_recovery`](Self::wait_for_recovery) before serving reads:
    ///
    /// ```ignore
    /// let raft = Raft::new(id, config, network, log_store, sm).await?;
    /// raft.wait_for_recovery(Some(Duration::from_secs(5))).await?;
    /// // The state machine has recovered at least its pre-restart committed state.
    /// ```
    #[since(
        version = "0.10.2",
        change = "return `RaftError<C, ConfigError>`, with a `ConfigError` for a channel size the runtime does not accept"
    )]
    #[since(
        version = "0.10.0",
        change = "require N::Network: NetSnapshot<SnapshotData = SM::SnapshotData>"
    )]
    #[tracing::instrument(level="debug", skip_all, fields(cluster=%config.cluster_name))]
    pub async fn new<LS, N>(
        id: C::NodeId,
        config: Arc<Config>,
        network: N,
        log_store: LS,
        state_machine: SM,
    ) -> Result<Self, RaftError<C, ConfigError>>
    where
        N: RaftNetworkFactory<C>,
        N::Network: NetSnapshot<C, SnapshotData = SM::SnapshotData>,
        LS: RaftLogStorage<C>,
    {
        let raft = Self::build(id, config, network, log_store, state_machine).await?;
        raft.run();
        Ok(raft)
    }

    /// Build a Raft node without spawning its tasks.
    ///
    /// This two-phase alternative to [`new`](Self::new) lets an application construct data-serving
    /// components that depend on the [`Raft`] handle before the node can campaign for leadership.
    /// Call [`run`](Self::run) after those components are ready.
    ///
    /// Storage is inspected and the initial Raft state is recovered during this call, but
    /// No Raft background task starts until [`run`](Self::run) is called. It returns the same
    /// errors as `new`.
    ///
    /// ```ignore
    /// let raft = Raft::build(id, config, network, log_store, sm).await?;
    /// let server = DataServer::new(raft.clone());
    /// raft.run();
    /// server.serve().await?;
    /// ```
    #[since(
        version = "0.10.2",
        change = "return `RaftError<C, ConfigError>`, with a `ConfigError` for a channel size the runtime does not accept"
    )]
    #[since(version = "0.10.0")]
    #[tracing::instrument(level="debug", skip_all, fields(cluster=%config.cluster_name))]
    pub async fn build<LS, N>(
        id: C::NodeId,
        config: Arc<Config>,
        network: N,
        mut log_store: LS,
        mut state_machine: SM,
    ) -> Result<Self, RaftError<C, ConfigError>>
    where
        N: RaftNetworkFactory<C>,
        N::Network: NetSnapshot<C, SnapshotData = SM::SnapshotData>,
        LS: RaftLogStorage<C>,
    {
        // Check the channel sizes before building any channel: a runtime panics on a size that
        // its channels do not accept.
        config.validate_channel_sizes(MpscOf::<C>::buffer_size_range()).map_err(RaftError::APIError)?;

        let api_channel_size = config.api_channel_size();
        let notification_channel_size = config.notification_channel_size();

        let (tx_api, rx_api) = C::mpsc(api_channel_size);
        let (tx_install_snapshot, rx_install_snapshot) = C::mpsc(api_channel_size);
        let (tx_notify, rx_notify) = C::mpsc(notification_channel_size);
        let (tx_metrics, rx_metrics) = C::watch_channel(RaftMetrics::new_initial(id.clone()));
        let (tx_data_metrics, rx_data_metrics) = C::watch_channel(RaftDataMetrics::default());
        let (tx_server_metrics, rx_server_metrics) = C::watch_channel(RaftServerMetrics::new_initial(id.clone()));
        let (tx_lease_read_state, rx_lease_read_state) = C::watch_channel(None);
        let lease_read_state_publisher = LeaseReadStatePublisher::new(tx_lease_read_state);

        // Watch channel for IO completion notifications from storage callbacks.
        // Initial value is a dummy IOId with this node's ID.
        let leader_id = C::LeaderId::new_with_default_term(id.clone());
        let dummy_io_id = IOId::Vote(UncommittedVote::new(leader_id));
        let (tx_io_completed, rx_io_completed) = C::watch_channel(Ok(dummy_io_id));

        // Create weak sender for forwarder before moving tx_notify into RaftCore
        let weak_tx_notify = tx_notify.downgrade();

        let (tx_progress, progress_watcher) = IoProgressWatcher::new();
        let (tx_control, rx_control) = C::watch_channel(());

        let runtime_config = Arc::new(RuntimeConfig::new(&config));

        let core_span = tracing::span!(
            parent: tracing::Span::current(),
            Level::DEBUG,
            "RaftCore",
            id = display(&id),
            cluster = display(&config.cluster_name)
        );

        let eng_config = EngineConfig::new(id.clone(), config.as_ref());

        let state = {
            let mut helper = StorageHelper::new(&mut log_store, &mut state_machine).with_id(id.clone());
            helper.get_initial_state().await.map_err(Fatal::from)?
        };

        let engine = Engine::new(state, eng_config);

        // The logs applied before the core starts, such as those that `get_initial_state()`
        // re-applies, are not observed: the log stages start after them.
        let log_stage_begin = engine.state.io_state().applied().cloned().next_index();

        let sm_span = tracing::span!(parent: &core_span, Level::DEBUG, "sm_worker");

        let log_reader = log_store.get_log_reader().await;
        let (sm_cmd_tx, sm_cmd_rx) = C::mpsc(config.state_machine_channel_size());
        let weak_sm_cmd_tx = sm_cmd_tx.downgrade();

        let default_io_id = IOId::new_vote_io(UncommittedVote::new_with_default_term(id.clone()));
        let (io_accepted_tx, _io_accepted_rx) = C::watch_channel(default_io_id.clone());
        let (io_submitted_tx, _io_submitted_rx) = C::watch_channel(default_io_id);
        let (committed_tx, _committed_rx) = C::watch_channel(None);
        let (quorum_loss_probe_tx, _quorum_loss_probe_rx) = C::watch_channel(None);

        let shared_replicate_batch = SharedReplicateBatch::new();

        let start = {
            let id = id.clone();
            let config = config.clone();
            let runtime_config = runtime_config.clone();
            let tx_api = tx_api.clone();
            let tx_install_snapshot = tx_install_snapshot.clone();
            let rx_metrics = rx_metrics.clone();
            let rx_server_metrics = rx_server_metrics.clone();

            Box::new(move |_inner: &RaftInner<C>| {
                let buffered = config.enable_unbounded_state_machine_buffer();
                let sm_cmd_rx = sm::command_receiver::CommandReceiver::new(sm_cmd_rx, buffered);
                let sm_handle = worker::Worker::spawn(
                    id.clone(),
                    state_machine,
                    log_reader,
                    tx_notify.clone(),
                    (sm_cmd_tx, sm_cmd_rx),
                    sm_span,
                );
                let election_deadline_notifier =
                    DeadlineNotifier::spawn(tx_notify.clone(), |_| Notification::ElectionDeadlineReached);
                let heartbeat_deadline_notifier =
                    DeadlineNotifier::spawn(tx_notify.clone(), |i| Notification::Tick { i });

                let core: RaftCore<C, N, LS, SM> = RaftCore {
                    id: id.clone(),
                    config: config.clone(),
                    runtime_config: runtime_config.clone(),
                    core_state: Default::default(),
                    network_factory: Arc::new(C::mutex(network)),
                    log_store,
                    sm_handle,

                    engine,
                    lease_read_state_publisher,

                    // Allocates on the first client write, like the engine queues, and keeps
                    // its capacity after draining.
                    client_responders: ClientResponderQueue::new(),

                    pending_reads: PendingReadQueue::default(),
                    pending_read_deadline_notifier: DeadlineNotifier::spawn(tx_notify.clone(), |_| {
                        Notification::PendingReadDeadlineReached
                    }),
                    election_deadline_notifier,
                    heartbeat_deadline_notifier,
                    replications: Default::default(),
                    lingering_replications: Default::default(),

                    heartbeat_handle: HeartbeatWorkersHandle::new(id.clone(), config.clone()),
                    tx_api: tx_api.clone(),
                    rx_api: BatchRaftMsgReceiver::new(
                        rx_api,
                        config.api_batch_capacity(),
                        Duration::from_millis(config.api_batch_linger_ms()),
                    ),
                    tx_install_snapshot: tx_install_snapshot.clone(),
                    rx_install_snapshot,
                    rx_control,

                    notifications: NotificationChannel::new(tx_notify, rx_notify),

                    io_broadcast: IoBroadcast {
                        completed: tx_io_completed,
                        accepted: io_accepted_tx,
                        submitted: io_submitted_tx,
                        committed: committed_tx,
                    },
                    quorum_loss_probe_tx,

                    metrics: MetricsChannels {
                        all: tx_metrics,
                        data: tx_data_metrics,
                        server: tx_server_metrics,
                        progress: tx_progress,
                    },

                    runtime_stats: RuntimeStats::new(&config, log_stage_begin),
                    shared_replicate_batch,

                    metrics_recorder: None,

                    span: core_span,
                };

                // Spawn forwarder task to bridge Watch channel to notification channel
                let _forwarder_handle = C::spawn(io_completion_forwarder::<C>(rx_io_completed, weak_tx_notify));

                StepDownWatcher::<C>::spawn(
                    rx_server_metrics.clone(),
                    rx_metrics.clone(),
                    tx_api.downgrade(),
                    &config,
                );

                let core = Box::new(core);
                let core_fut = core.main().instrument(trace_span!("spawn").or_current());
                C::spawn(core_fut)
            })
        };

        let inner = RaftInner {
            id,
            config,
            runtime_config,
            tx_api,
            rx_lease_read_state,
            rx_metrics,
            rx_data_metrics,
            rx_server_metrics,
            progress_watcher,
            tx_control: Mutex::new(Some(tx_control)),
            core_state: Mutex::new(CoreState::Unstarted(Some(start))),
            extensions: Extensions::default(),
        };

        Ok(Self {
            inner: Arc::new(inner),
            sm_cmd_tx: weak_sm_cmd_tx,
            install_snapshot_tx: tx_install_snapshot,
        })
    }

    /// Start the Raft core task built by [`build`](Self::build).
    ///
    /// This method is idempotent: calling it on an already running or stopped node has no effect.
    #[since(version = "0.10.0")]
    pub fn run(&self) {
        let mut state = self.inner.core_state.lock().unwrap();
        let CoreState::Unstarted(start) = &mut *state else {
            return;
        };

        let start = start.take().expect("unstarted Raft must have a start function");
        let join_handle = start(self.inner.as_ref());
        *state = CoreState::started(join_handle);
    }
}

impl<C, SM> Raft<C, SM>
where
    C: RaftTypeConfig,
    SM: RaftStateMachine<C>,
{
    /// Return a handle to update runtime config.
    ///
    /// Such enabling/disabling heartbeat, election, etc.
    ///
    /// Example:
    /// ```ignore
    /// let raft = Raft::new(...).await?;
    /// raft.runtime_config().heartbeat(true);
    /// raft.runtime_config().tick(true);
    /// raft.runtime_config().elect(true);
    /// ```
    pub fn runtime_config(&self) -> RuntimeConfigHandle<'_, C> {
        RuntimeConfigHandle::new(self.inner.as_ref())
    }

    /// Return the config of this Raft node.
    pub fn config(&self) -> &Arc<Config> {
        &self.inner.config
    }

    /// Access the underlying extensions map.
    ///
    /// For most use cases, prefer [`extension()`](Self::extension) which provides
    /// a simpler API for getting values.
    ///
    /// This method is useful when you need direct access to the [`Extensions`] type,
    /// such as checking if a value exists with [`contains()`](Extensions::contains)
    /// or removing a value with [`remove()`](Extensions::remove).
    #[since(version = "0.10.0")]
    pub fn extensions(&self) -> &Extensions {
        &self.inner.extensions
    }

    /// Get a clone of a user-defined extension value.
    ///
    /// If no value exists, `T::default()` is inserted and a clone is returned.
    /// Values must implement `Clone` and `Default`. Use `Arc` for shared mutable state.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use std::sync::atomic::{AtomicU64, Ordering};
    /// use std::sync::Arc;
    ///
    /// #[derive(Clone, Default)]
    /// pub struct MyCounter(Arc<AtomicU64>);
    ///
    /// // Get a clone (auto-inserts default if not present)
    /// let counter = raft.extension::<MyCounter>();
    /// counter.0.fetch_add(1, Ordering::Relaxed);
    ///
    /// // Multiple calls share the same underlying data via Arc
    /// let counter2 = raft.extension::<MyCounter>();
    /// assert_eq!(counter2.0.load(Ordering::Relaxed), 1);
    /// ```
    #[since(version = "0.10.0")]
    pub fn extension<T>(&self) -> T
    where T: OptionalSend + Clone + Default + 'static {
        self.inner.extensions.get::<T>()
    }

    /// Return a copy of the runtime statistics.
    ///
    /// Sends a message to RaftCore to retrieve the current runtime statistics.
    /// This returns a snapshot of the stats at the time of the call.
    #[cfg(feature = "runtime-stats")]
    pub async fn runtime_stats(&self) -> Result<RuntimeStats<C>, Fatal<C>> {
        self.inner.call_core_oneshot(|tx| RaftMsg::GetRuntimeStats { tx }).await
    }

    /// Check if this node is the leader, as its latest metrics show.
    ///
    /// Returns `true` if the latest [`RaftMetrics`] of this node show it as
    /// [`ServerState::Leader`]. The check reads only the metrics of this node and contacts no other
    /// node, so it does not confirm that this node still leads: a leader cut off from a quorum
    /// keeps its role until it learns of a higher vote, while another node may already lead in a
    /// higher term.
    ///
    /// A `true` result also does not protect a read of application state from stale data: even a
    /// current leader may not have applied every committed entry yet, such as one that an earlier
    /// leader committed. Before such a read, call [`ensure_linearizable()`], which confirms the
    /// leadership by a quorum or a lease, then waits for the state machine to apply the entries
    /// that the read must observe. Or call [`get_read_linearizer()`], then
    /// [`Linearizer::await_ready()`] or [`Linearizer::try_await_ready()`].
    ///
    /// # Example
    ///
    /// ```ignore
    /// if raft.is_leader() {
    ///     // Perform leader-only operations
    /// }
    /// ```
    ///
    /// [`ServerState::Leader`]: crate::core::ServerState::Leader
    /// [`ensure_linearizable()`]: Self::ensure_linearizable
    /// [`get_read_linearizer()`]: Self::get_read_linearizer
    #[since(version = "0.10.0")]
    pub fn is_leader(&self) -> bool {
        self.inner.rx_metrics.borrow_watched().state.is_leader()
    }

    /// Get leader information if this node is currently a leader.
    ///
    /// Returns [`Leader`], containing the leader ID and health metadata, if the latest
    /// [`RaftMetrics`] report shows this node running as [`ServerState::Leader`], with a committed
    /// [`vote`](RaftMetrics::vote) that names this node. A leader that the membership keeps only
    /// as a learner qualifies.
    ///
    /// Otherwise it returns [`ForwardToLeader`]. If the committed vote names another node, the
    /// error holds that node's ID and, if the effective membership has the node, its node
    /// information. The error holds no leader if the vote is not committed, or if the vote names
    /// this node but this node does not run as leader. The metrics still report this node's
    /// committed vote after it restarts, shuts down, or steps down as a removed leader.
    ///
    /// # Example
    ///
    /// ```ignore
    /// match raft.as_leader() {
    ///     Ok(leader) => {
    ///         println!("This node is leader: {:?}", leader.leader_id());
    ///     }
    ///     Err(forward) => {
    ///         println!("Forward to leader: {:?}", forward.leader_id);
    ///     }
    /// }
    /// ```
    ///
    /// [`ServerState::Leader`]: crate::core::ServerState::Leader
    /// [`ForwardToLeader`]: crate::errors::ForwardToLeader
    #[since(version = "0.10.2", change = "also requires this node to run as `Leader`")]
    #[since(version = "0.10.0")]
    pub fn as_leader(&self) -> Result<Leader<C, SM>, ForwardToLeader<C>> {
        // Read the role and the vote with one metrics borrow, so that both come from the same
        // report. Calling `is_leader()` here would borrow the metrics a second time.

        let metrics = self.inner.rx_metrics.borrow_watched();

        let Some(committed_vote) = metrics.vote.try_to_committed() else {
            return Err(ForwardToLeader::empty());
        };

        let leader_id = committed_vote.leader_id();
        let node_id = leader_id.node_id();

        if node_id == &self.inner.id {
            // After a restart, a shutdown, or a step down, the committed vote still names this
            // node, so the vote alone does not show that this node leads.
            let runs_as_leader = metrics.running_state.is_ok() && metrics.state.is_leader();
            if !runs_as_leader {
                return Err(ForwardToLeader::empty());
            }

            Ok(Leader {
                raft: self.clone(),
                leader_id: leader_id.clone(),
                last_quorum_acked: metrics.last_quorum_acked.map(|s| s.into_inner()),
            })
        } else {
            let node = metrics.membership_config.get_node(node_id).cloned();

            Err(ForwardToLeader {
                leader_id: Some(node_id.clone()),
                leader_node: node,
                reason: ForwardReason::NotLeader,
            })
        }
    }

    /// Get the ID of this Raft node.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let id = raft.node_id();
    /// println!("Node ID: {:?}", id);
    /// ```
    #[since(version = "0.10.0")]
    pub fn node_id(&self) -> &C::NodeId {
        &self.inner.id
    }

    /// Get an iterator over the current voter node IDs.
    ///
    /// Returns node IDs that are voters in the effective membership. Learners are not included.
    ///
    /// # Example
    ///
    /// ```ignore
    /// for voter_id in raft.voter_ids() {
    ///     println!("Voter: {:?}", voter_id);
    /// }
    /// ```
    #[since(version = "0.10.0")]
    pub fn voter_ids(&self) -> impl Iterator<Item = C::NodeId> {
        // borrow_watched() holds a lock that blocks RaftCore.
        // Clone and collect immediately to release the lock quickly.
        let membership = self.inner.rx_metrics.borrow_watched().membership_config.clone();
        membership.voter_ids().collect::<Vec<_>>().into_iter()
    }

    /// Get an iterator over the current learner node IDs.
    ///
    /// Returns known node IDs in the effective membership with no campaign, read voter,
    /// or write voter role. These nodes receive replicated logs without counting toward either
    /// quorum.
    ///
    /// # Example
    ///
    /// ```ignore
    /// for learner_id in raft.learner_ids() {
    ///     println!("Learner: {:?}", learner_id);
    /// }
    /// ```
    #[since(version = "0.10.0")]
    pub fn learner_ids(&self) -> impl Iterator<Item = C::NodeId> {
        // borrow_watched() holds a lock that blocks RaftCore.
        // Clone and collect immediately to release the lock quickly.
        let membership = self.inner.rx_metrics.borrow_watched().membership_config.clone();
        let membership = membership.membership();
        let node_ids = membership.node_ids();
        let learners = node_ids.filter(|id| membership.is_learner(id));
        let ids = learners.collect::<Vec<_>>();
        ids.into_iter()
    }

    /// Create a new [`ProtocolApi`] to handle Raft protocol RPCs received by this Raft node.
    ///
    /// [`ProtocolApi`] provides the following protocol APIs:
    /// - [`ProtocolApi::append_entries`]
    /// - [`ProtocolApi::vote`]
    /// - [`ProtocolApi::get_snapshot`]
    /// - [`ProtocolApi::install_full_snapshot`]
    /// - [`ProtocolApi::handle_transfer_leader`]
    pub(crate) fn protocol_api(&self) -> ProtocolApi<C, SM> {
        ProtocolApi::new(
            self.inner.clone(),
            self.sm_cmd_tx.clone(),
            self.install_snapshot_tx.clone(),
        )
    }

    pub(crate) fn app_api(&self) -> AppApi<'_, C> {
        AppApi::new(&self.inner)
    }

    pub(crate) fn management_api(&self) -> ManagementApi<'_, C> {
        ManagementApi::new(self.inner.as_ref())
    }

    /// Return a [`Trigger`] handle to manually trigger raft actions, such as elect or build
    /// snapshot.
    ///
    /// Example:
    /// ```ignore
    /// let raft = Raft::new(...).await?;
    /// raft.trigger().elect(false).await?;
    /// ```
    pub fn trigger(&self) -> Trigger<'_, C> {
        Trigger::new(self.inner.as_ref())
    }

    /// Set or unset a custom metrics recorder for exporting Raft metrics.
    ///
    /// This allows applications to plug in their own metrics collection backends
    /// (e.g., OpenTelemetry, Prometheus, StatsD) at runtime. The recorder will
    /// receive metrics events from RaftCore as they occur.
    ///
    /// Pass `Some(recorder)` to enable metrics recording, or `None` to disable it.
    ///
    /// # Example
    ///
    /// `recorder` below is an `Arc<dyn MetricsRecorder>`. The [`metrics::recorder`] module shows
    /// how to implement [`MetricsRecorder`].
    ///
    /// ```no_run
    /// # use std::sync::Arc;
    /// # use openraft::Raft;
    /// # use openraft::RaftTypeConfig;
    /// # use openraft::errors::Fatal;
    /// # use openraft::metrics::MetricsRecorder;
    /// # use openraft::storage::RaftStateMachine;
    /// #
    /// # async fn example<C, SM>(raft: &Raft<C, SM>, recorder: Arc<dyn MetricsRecorder>) -> Result<(), Fatal<C>>
    /// # where
    /// #     C: RaftTypeConfig,
    /// #     SM: RaftStateMachine<C>,
    /// # {
    /// // Enable metrics recording
    /// raft.set_metrics_recorder(Some(recorder)).await?;
    ///
    /// // Disable metrics recording
    /// raft.set_metrics_recorder(None).await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`metrics::recorder`]: crate::metrics::recorder
    ///
    /// # Errors
    ///
    /// Returns [`Fatal`] error if RaftCore is shut down or has a storage error.
    pub async fn set_metrics_recorder(&self, recorder: Option<Arc<dyn MetricsRecorder>>) -> Result<(), Fatal<C>> {
        self.inner.send_external_command(ExternalCommand::SetMetricsRecorder { recorder }).await
    }

    /// Submit an AppendEntries RPC to this Raft node.
    ///
    /// These RPCs are sent by the cluster leader to replicate log entries (§5.3), and are also
    /// used as heartbeats (§5.2).
    ///
    /// The outer `Err` means this node has stopped. The inner [`AppendResult`] is the reply for
    /// the leader: the last log id this node accepted, or the [`AppendError`] that explains why it
    /// rejected the request. A conflict carries a hint that describes this node's log after it
    /// truncated the conflicting entries.
    ///
    /// [`AppendResult`] does not implement serde, so convert it to the transport's own response
    /// type. Converting it to [`StreamAppendResult`] with `result.map_err(Into::into)` gives a
    /// serializable format that keeps the log id but drops the hint.
    #[since(version = "0.10.0", change = "returns AppendResult with an optional conflict hint")]
    #[tracing::instrument(level = "debug", skip_all)]
    pub async fn append_entries(&self, rpc: AppendEntriesRequest<C>) -> Result<AppendResult<C>, RaftError<C>> {
        self.protocol_api().append_entries(rpc).await.map_err(RaftError::Fatal)
    }

    /// Submit a stream of AppendEntries RPCs to this Raft node.
    ///
    /// This is a stream-oriented version of [`Self::append_entries`] with pipelining support.
    /// It spawns a background task that reads from the input stream, sends requests to RaftCore,
    /// and forwards response receivers to the output stream. Responses are yielded in order.
    ///
    /// ## Pipelining Behavior
    ///
    /// - A background task reads from the input stream and sends to RaftCore
    /// - Uses a bounded channel (64 slots) for backpressure
    /// - Responses are yielded in order (FIFO) as they complete
    ///
    /// ## Output
    ///
    /// The output stream emits:
    /// - `Ok(log_id)` when logs are successfully flushed
    /// - `Err(e)` when an error occurs, which terminates the stream
    ///
    /// A conflict, [`AppendError::Conflict`], carries a hint that describes this node's log after
    /// it truncated the conflicting entries. [`AppendError`] does not implement serde, so convert
    /// it to the transport's own response type. Converting it to [`StreamAppendError`] keeps
    /// the existing format but drops the hint, and the leader then falls back to binary search.
    ///
    /// ## Pinning
    ///
    /// The returned stream is `!Unpin` because it uses async closures internally.
    /// You must pin the stream before calling `.next()`:
    ///
    /// ```ignore
    /// use std::pin::pin;
    ///
    /// let mut output = pin!(raft.stream_append(input));
    /// while let Some(result) = output.next().await { /* ... */ }
    /// ```
    ///
    /// Alternatively, use `Box::pin` for heap pinning if the stream needs to be stored or returned:
    ///
    /// ```ignore
    /// let mut output = Box::pin(raft.stream_append(input));
    /// ```
    ///
    /// # Example
    ///
    /// ```ignore
    /// use std::pin::pin;
    /// use futures_util::StreamExt;
    ///
    /// let input_stream = futures_util::stream::iter(vec![request1, request2, request3]);
    /// let mut output_stream = pin!(raft.stream_append(input_stream));
    ///
    /// while let Some(result) = output_stream.next().await {
    ///     match result {
    ///         Ok(Ok(log_id)) => println!("Flushed: {:?}", log_id),
    ///         Ok(Err(err)) => {
    ///             println!("Append error: {}", err);
    ///             break;
    ///         }
    ///         Err(fatal) => {
    ///             println!("Fatal: {}", fatal);
    ///             break;
    ///         }
    ///     }
    /// }
    /// ```
    #[since(
        version = "0.10.0",
        change = "stream item carries AppendError with an optional conflict hint"
    )]
    #[since(version = "0.10.0", change = "stream item contains Fatal")]
    #[since(version = "0.10.0")]
    pub fn stream_append<S>(
        &self,
        stream: S,
    ) -> impl futures_util::Stream<Item = Result<AppendResult<C>, Fatal<C>>> + OptionalSend + 'static
    where
        S: futures_util::Stream<Item = AppendEntriesRequest<C>> + OptionalSend + 'static,
    {
        self.protocol_api().stream_append(stream)
    }

    /// Submit a VoteRequest (RequestVote in the spec) RPC to this Raft node.
    ///
    /// These RPCs are sent by cluster peers which are in candidate state attempting to gather votes
    /// (§5.2).
    #[tracing::instrument(level = "debug", skip_all)]
    pub async fn vote(&self, rpc: VoteRequest<C>) -> Result<VoteResponse<C>, RaftError<C>> {
        self.protocol_api().vote(rpc).await.into_raft_result()
    }

    /// Submit a Pre-Vote RPC to this Raft node.
    ///
    /// A pre-candidate sends this before incrementing its term to ask whether peers *would* grant
    /// it a vote at `rpc.vote` (a hypothetical next term). Handling this RPC never persists a
    /// vote or changes this node's term; it only reports whether the vote would be granted,
    /// judged by the same leader-lease and last-log-id rules as [`Raft::vote()`]. Pre-Vote is
    /// only used when [`Config::enable_pre_vote`](crate::Config::enable_pre_vote) is enabled on
    /// the sender.
    #[since(version = "0.10.0", change = "added for the Pre-Vote feature")]
    #[tracing::instrument(level = "debug", skip_all)]
    pub async fn pre_vote(&self, rpc: VoteRequest<C>) -> Result<VoteResponse<C>, RaftError<C>> {
        self.protocol_api().pre_vote(rpc).await.into_raft_result()
    }

    /// Get the latest snapshot from the state machine.
    ///
    /// The request is served directly by the state-machine worker, not `RaftCore`. It returns an
    /// error only when that worker fails to serve it, e.g., encountering a storage error or having
    /// stopped (`Fatal::Stopped`), which can occur while `RaftCore` is still running.
    #[tracing::instrument(level = "debug", skip_all)]
    pub async fn get_snapshot(&self) -> Result<Option<SnapshotOf<C, SM::SnapshotData>>, RaftError<C>> {
        self.protocol_api().get_snapshot().await.into_raft_result()
    }

    /// Install a completely received snapshot to the state machine.
    ///
    /// This method is used to implement an application defined snapshot transmission.
    /// The application receives a snapshot from the leader, in chunks or a stream, and
    /// then rebuild a snapshot, then pass the snapshot to Raft to install.
    ///
    /// It returns `Ok` with a [`SnapshotResponse`] in each of these cases:
    ///
    /// - This node accepts `vote` and installs the snapshot. It returns once
    ///   [`RaftStateMachine::install_snapshot()`] has returned `Ok` for this snapshot.
    /// - This node accepts `vote`, but it has already committed every log through the snapshot's
    ///   last log id, so it does not install the snapshot. It returns only after those logs are
    ///   flushed to storage.
    /// - This node rejects `vote` and does not install the snapshot. The returned vote is then
    ///   greater than `vote`.
    ///
    /// In the first two cases the returned vote is `vote`, so the response does not tell whether
    /// this node installed the snapshot.
    ///
    /// Answer the leader's [`NetSnapshot::full_snapshot()`] with this response, unchanged. Unless
    /// the vote in it is greater, the leader takes it as proof that this node has every log through
    /// the snapshot's last log id.
    ///
    /// # Errors
    ///
    /// Returns [`Fatal`] if this node stopped before it answered, for example because
    /// [`RaftStateMachine::install_snapshot()`] returned an error. The snapshot is then not known
    /// to be installed: answer the leader with an error, not with a successful response.
    ///
    /// # Panics
    ///
    /// If `vote` is accepted, the input must be one a protocol-following cluster can produce,
    /// otherwise this method panics (also in release builds):
    /// - the snapshot's last log id must not be beyond the leadership of `vote`: no leader owns a
    ///   snapshot with a log id greater than its own vote;
    /// - a snapshot greater than the locally committed log id must be at a strictly greater index:
    ///   an equal index identifies a different entry in an already committed slot, while a smaller
    ///   index contradicts a committed suffix.
    ///
    /// Such input indicates a forged or corrupted snapshot, e.g., one built by a previous
    /// incarnation of the cluster. Installing it would corrupt the log id order.
    #[since(
        version = "0.10.0",
        change = "panic on a snapshot inconsistent with the vote or with locally committed logs"
    )]
    #[since(version = "0.9.0")]
    #[tracing::instrument(level = "debug", skip_all)]
    pub async fn install_full_snapshot(
        &self,
        vote: VoteOf<C>,
        snapshot: SnapshotOf<C, SM::SnapshotData>,
    ) -> Result<SnapshotResponse<C>, Fatal<C>> {
        self.protocol_api().install_full_snapshot(vote, snapshot).await
    }

    /// Get the ID of the current leader, as this node knows it.
    ///
    /// Returns [`RaftMetrics::current_leader`] from the latest metrics of this node, without
    /// contacting other nodes. It is the ID of the elected leader of the current term of this node,
    /// which can be this node. It is `None` until this node learns of that leader, such as during
    /// an election. The ID can be out of date: a node cut off from the cluster can keep naming the
    /// leader it knew, while another node may already lead in a higher term. It can also name this
    /// node after this node stops leading, such as when it steps down as a removed leader or shuts
    /// down.
    ///
    /// Use it to choose where to send client requests. Because the ID can be out of date, the node
    /// that receives a request can still answer with a [`ForwardToLeader`] error, which names the
    /// leader that node knows of, if any.
    ///
    /// Neither this ID nor [`is_leader()`] protects a read of application state from stale data.
    /// Before such a read, call [`ensure_linearizable()`], which confirms the leadership by a
    /// quorum or a lease, then waits for the state machine to apply the entries that the read must
    /// observe. [`get_read_linearizer()`] followed by [`Linearizer::await_ready()`] or
    /// [`Linearizer::try_await_ready()`] does the same in two steps.
    ///
    /// [`is_leader()`]: Self::is_leader
    /// [`ensure_linearizable()`]: Self::ensure_linearizable
    /// [`get_read_linearizer()`]: Self::get_read_linearizer
    #[tracing::instrument(level = "debug", skip(self))]
    pub async fn current_leader(&self) -> Option<C::NodeId> {
        self.metrics().borrow_watched().current_leader.clone()
    }

    /// Ensures reads performed after this method are linearizable across the cluster
    /// using explicitly provided options. This method is just a shorthand for calling
    /// [`get_read_log_id()`](Raft::get_read_log_id) and then calling [Raft::wait].
    ///
    /// This method is just a shorthand for combining calling
    /// [`Raft::get_read_linearizer()`](Self::get_read_linearizer) and
    /// [`Linearizer::try_await_ready()`](Linearizer::try_await_ready), i.e., it is
    /// equivalent to:
    /// ```ignore
    /// my_raft.get_read_linearizer(read_policy).await?.try_await_ready(&my_raft, None).await?;
    /// ```
    ///
    /// To support follower read, i.e., get `read_log_id` on a remote leader then read on local
    /// state machine, see [`Raft::get_read_linearizer`].
    ///
    /// The option defines how to ensure leadership. It may be a [`LinearizerOption`] or a
    /// [`ReadPolicy`], which is converted into one.
    ///
    /// Returns:
    /// - `Ok(read_log_id)` on successful confirmation that the node is the leader. `read_log_id` is
    ///   `max(noop_log_id, committed)` at authorization: the log ID a read on any node must wait
    ///   for. A standard read returns after this node has applied it. A relaxed read, see
    ///   [`LinearizerOption::with_relaxed`], returns once this node has applied the no-op, so this
    ///   node may not have applied `read_log_id` yet.
    /// - `Err(RaftError<LinearizableReadError>)` if fails to assert leadership.
    ///
    /// # Examples
    /// ```ignore
    /// // Confirm leadership with a fresh quorum acknowledgement
    /// my_raft.ensure_linearizable(ReadPolicy::ReadIndex).await?;
    ///
    /// // Or reuse a valid leader lease to avoid a quorum round trip, when the lease's
    /// // assumptions hold; see `ReadPolicy::LeaseRead`
    /// my_raft.ensure_linearizable(ReadPolicy::LeaseRead).await?;
    ///
    /// // Then proceed with the state machine read
    /// ```
    /// Read more about how it works: [Read Operation](crate::docs::protocol::read)
    #[since(
        version = "0.10.0",
        change = "accept `impl Into<LinearizerOption>` instead of `ReadPolicy`"
    )]
    #[since(version = "0.10.0", change = "return ReadLogId instead of Option<LogId>")]
    #[since(version = "0.9.0")]
    #[tracing::instrument(level = "debug", skip_all)]
    pub async fn ensure_linearizable(
        &self,
        linearizer_option: impl Into<LinearizerOption>,
    ) -> Result<ReadLogId<C>, RaftError<C, LinearizableReadError<C>>> {
        let linearizer = self.app_api().get_read_linearizer(linearizer_option.into()).await.into_raft_result()?;

        // Safe unwrap: it never times out.
        let state = linearizer.await_ready(self).await?;
        Ok(state.read_log_id())
    }

    /// Legacy method that returns read state as a tuple. Use
    /// [`Raft::get_read_linearizer`] instead.
    ///
    /// This method extracts the read log ID and applied log ID from a [`Linearizer`] and returns
    /// them as a tuple.
    ///
    /// The [`ReadLogId`] contains the current leadership and the inclusive log boundary the state
    /// machine must apply through before serving the read. The applied log ID is the last value
    /// known to have been applied when the linearizer was created. A relaxed option does not
    /// change the returned boundary, so a read that waits for it gets the standard barrier; use
    /// [`Raft::get_read_linearizer`] for relaxed reads.
    /// **For new code, use [`Raft::get_read_linearizer`]** which provides a better API.
    ///
    /// See [`Raft::get_read_linearizer`] for full documentation.
    #[since(
        version = "0.10.0",
        change = "accept `impl Into<LinearizerOption>` instead of `ReadPolicy`"
    )]
    #[since(version = "0.10.0", change = "return ReadLogId instead of Option<LogId>")]
    #[since(version = "0.9.0")]
    #[tracing::instrument(level = "debug", skip_all)]
    pub async fn get_read_log_id(
        &self,
        linearizer_option: impl Into<LinearizerOption>,
    ) -> Result<(ReadLogId<C>, Option<LogIdOf<C>>), RaftError<C, LinearizableReadError<C>>> {
        let linearizer = self.app_api().get_read_linearizer(linearizer_option.into()).await.into_raft_result()?;

        let read_log_id = linearizer.read_log_id();
        let applied = linearizer.applied();

        Ok((read_log_id, applied.cloned()))
    }

    /// Ensures this node is leader and returns a [`Linearizer`] to linearize reads.
    ///
    /// This method confirms leadership and provides the necessary information to linearize reads
    /// across the cluster. The leadership is ensured by sending heartbeats or by lease according
    /// to the specified [`LinearizerOption`]. [`ReadPolicy`] is also accepted and converted into
    /// an option.
    ///
    /// The request always enters RaftCore's API queue alongside write requests. To allow a
    /// caller-side lease check that bypasses this queue, use [`Self::get_local_read_linearizer`].
    /// Queue order governs request handling; an earlier write may still be uncommitted.
    ///
    /// Returns:
    /// - `Ok(Linearizer<C>)` on successful confirmation that the node is the leader. The
    ///   [`Linearizer`] contains the `read_log_id` up to which the state machine should apply to
    ///   linearize reads, and the last `applied` log id.
    /// - `Err(RaftError<LinearizableReadError>)` if this node fails to ensure its leadership, for
    ///   example, it detects a higher term, or fails to communicate with a quorum.
    ///
    /// Once returned, the caller should block until the state machine to apply up to `read_log_id`
    /// using [`Linearizer::try_await_ready`].
    ///
    /// # Examples
    /// ```no_run
    /// # use openraft::Raft;
    /// # use openraft::RaftTypeConfig;
    /// # use openraft::raft::ReadPolicy;
    /// # use openraft::storage::RaftStateMachine;
    /// #
    /// # trait Read {
    /// #     fn read(&self, key: &str) -> Option<String>;
    /// # }
    /// #
    /// # async fn example<C, SM>(my_raft: Raft<C, SM>) -> Result<(), Box<dyn std::error::Error>>
    /// # where
    /// #     C: RaftTypeConfig,
    /// #     SM: RaftStateMachine<C> + Read,
    /// # {
    /// let linearizer = my_raft.get_read_linearizer(ReadPolicy::ReadIndex).await?;
    /// let _ = linearizer.try_await_ready(&my_raft, None).await?.unwrap();
    ///
    /// // Following read from state machine is linearized across the cluster
    /// let val = my_raft.with_state_machine(|sm| Box::pin(async move { sm.read("foo") })).await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Follower Read
    ///
    /// For follower reads, obtain the `read_log_id` from the leader via application-defined RPC,
    /// then use [`Linearizer::try_await_ready`] to wait for local state machine to catch
    /// up.
    ///
    /// ```no_run
    /// # use openraft::Raft;
    /// # use openraft::RaftTypeConfig;
    /// # use openraft::raft::ReadPolicy;
    /// # use openraft::raft::linearizable_read::Linearizer;
    /// # use openraft::storage::RaftStateMachine;
    /// #
    /// # trait Read {
    /// #     fn read(&self, key: &str) -> Option<String>;
    /// # }
    /// #
    /// # trait AppRpc<C>
    /// # where C: RaftTypeConfig
    /// # {
    /// #     async fn get_read_linearizer(
    /// #         &self,
    /// #         leader_id: C::NodeId,
    /// #         read_policy: ReadPolicy,
    /// #     ) -> Result<Linearizer<C>, Box<dyn std::error::Error>>;
    /// # }
    /// #
    /// # async fn example<C, SM, R>(my_raft: Raft<C, SM>, my_app_rpc: R) -> Result<(), Box<dyn std::error::Error>>
    /// # where
    /// #     C: RaftTypeConfig,
    /// #     SM: RaftStateMachine<C> + Read,
    /// #     R: AppRpc<C>,
    /// # {
    /// // `current_leader()` returns `None` while no leader is known, such as during an election
    /// let leader_id = my_raft.current_leader().await.ok_or("no known leader")?;
    ///
    /// // Application defined RPC to get the `read_log_id` from the remote leader
    /// let linearizer = my_app_rpc.get_read_linearizer(leader_id, ReadPolicy::ReadIndex).await?;
    ///
    /// // Block waiting local state machine to apply up to the `read_log_id`
    /// let _ = linearizer.try_await_ready(&my_raft, None).await?.unwrap();
    ///
    /// // Following read from state machine is linearized across the cluster
    /// let val = my_raft.with_state_machine(|sm| Box::pin(async move { sm.read("foo") })).await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// See: [Read Operation](crate::docs::protocol::read)
    #[since(
        version = "0.10.0",
        change = "accept `impl Into<LinearizerOption>` instead of `ReadPolicy`"
    )]
    #[since(version = "0.10.0")]
    #[tracing::instrument(level = "debug", skip_all)]
    pub async fn get_read_linearizer(
        &self,
        linearizer_option: impl Into<LinearizerOption>,
    ) -> Result<Linearizer<C>, RaftError<C, LinearizableReadError<C>>> {
        let linearizer_option = linearizer_option.into();
        self.app_api().get_read_linearizer(linearizer_option).await.into_raft_result()
    }

    /// Returns a [`Linearizer`] using a caller-side lease check when enabled and valid.
    ///
    /// With [`Config::enable_local_lease_read`] set to `Some(true)`, a valid cached leader
    /// snapshot authorizes the read without entering RaftCore's API queue. The read can therefore
    /// overtake queued write requests and uses the published committed boundary. Both this method
    /// and [`Self::get_read_linearizer`] support linearizable reads; overlapping unfinished writes
    /// may follow the read. Await a write's completion before starting a read that must observe it.
    ///
    /// Disabled caching, a missing or expired snapshot, and zero effective acknowledgement age
    /// fall back to [`Self::get_read_linearizer`] with the same options. In particular,
    /// [`ReadPolicy::ReadIndex`] always uses RaftCore for fresh quorum confirmation.
    ///
    /// A cache hit can return immediately, but the caller must still await
    /// [`Linearizer::await_ready`] or [`Linearizer::try_await_ready`] before reading application
    /// state. This method checks leader state; follower reads still obtain a linearizer from
    /// the leader and wait for their own state machine to catch up.
    ///
    /// If known applied progress is behind the read boundary, the apply wait depends on RaftCore
    /// reporting newer metrics.
    #[since(version = "0.10.0")]
    #[tracing::instrument(level = "debug", skip_all)]
    pub async fn get_local_read_linearizer(
        &self,
        linearizer_option: impl Into<LinearizerOption>,
    ) -> Result<Linearizer<C>, RaftError<C, LinearizableReadError<C>>> {
        let linearizer_option = linearizer_option.into();
        let app_api = self.app_api();
        let result = app_api.get_local_read_linearizer(linearizer_option).await;
        result.into_raft_result()
    }

    /// Submit a mutating client request to Raft to update the state of the system (§5.1).
    ///
    /// It will be appended to the log, committed to the cluster, and then applied to the
    /// application state machine. The result of applying the request to the state machine will
    /// be returned as the response from this method.
    ///
    /// Our goal for Raft is to implement linearizable semantics. If the leader crashes after
    /// committing a log entry but before responding to the client, the client may retry the
    /// command with a new leader, causing it to be executed a second time. As such, clients
    /// should assign a unique serial number to every logical command and reuse it for every retry.
    /// The state machine should track the latest serial number processed for each client, along
    /// with the associated response. This deduplication state must be durable and included in
    /// snapshots. If the state machine receives a command whose serial number has already been
    /// executed, it responds immediately without re-executing the request (§8). The
    /// [`RaftStateMachine::apply`] method is the perfect place to implement
    /// this.
    ///
    /// These are application specific requirements, and must be implemented by the application
    /// which is being built on top of Raft.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// // Submit a write request
    /// let request = MyAppData { key: "foo".to_string(), value: "bar".to_string() };
    /// let response = raft.client_write(request).await?;
    /// println!("Applied at log index: {:?}", response.log_id);
    /// ```
    #[tracing::instrument(level = "debug", skip(self, app_data))]
    pub async fn client_write(
        &self,
        app_data: C::D,
    ) -> Result<ClientWriteResponse<C>, RaftError<C, ClientWriteError<C>>> {
        self.app_api().client_write(C::Payload::normal(app_data)).await.into_raft_result()
    }

    /// Write a blank log entry to the Raft log.
    ///
    /// A blank entry contains no application data and is typically used to:
    /// - Commit entries from previous terms when a new leader is elected
    /// - Advance the commit index without any state machine changes
    /// - Act as a barrier to ensure all previous entries are committed
    ///
    /// Returns when the blank entry has been applied to the state machine.
    #[since(version = "0.10.0")]
    #[tracing::instrument(level = "debug", skip(self))]
    pub async fn write_blank(&self) -> Result<ClientWriteResponse<C>, RaftError<C, ClientWriteError<C>>> {
        self.app_api().client_write(C::Payload::blank()).await.into_raft_result()
    }

    /// Submit a mutating client request to Raft without waiting for its result.
    ///
    /// `_ff` means fire and forget. Unlike [`Self::client_write()`], this method does not wait for
    /// the write to be applied and does not return its result. RaftCore reports the result to
    /// `responder` instead.
    ///
    /// The caller observes each stage of the write in a different place:
    ///
    /// - Submission: this method returns `Ok(())` once the write is queued for RaftCore. It means
    ///   only that the write was submitted: RaftCore may still reject it, and a write that RaftCore
    ///   admits may never be committed or applied. `Err(Fatal)` means RaftCore has stopped and the
    ///   write was not submitted.
    /// - Commit: once the log entry of the write is committed, RaftCore calls
    ///   [`Responder::on_commit()`] with its log id. The state machine may not have applied the
    ///   write yet. A rejected or discarded write gets no commit notification.
    /// - Completion: RaftCore calls [`Responder::on_complete()`] with the write's
    ///   [`ClientWriteResult`]: `Ok` with a [`ClientWriteResponse`] once the state machine has
    ///   applied the write, or `Err` with a [`ClientWriteError`] if the write fails, such as
    ///   [`ClientWriteError::ForwardToLeader`] when RaftCore rejects it without appending it, or
    ///   [`ClientWriteError::LogEntryDiscarded`] when its appended entry is discarded, which leaves
    ///   its commit status unknown.
    ///
    /// This method returns no receiver. The caller creates a responder of the type that the type
    /// config selects as [`Responder<T>`](RaftTypeConfig::Responder), keeps its receiver, and
    /// passes `Some(responder)`. The success or rejection of the write arrives at that receiver.
    /// With `None`, nothing reports whether the write was rejected, committed, or applied.
    ///
    /// [`declare_raft_types!`] selects [`ProgressResponder`] by default.
    /// [`ProgressResponder::new()`] returns a commit receiver and a complete receiver, and
    /// [`ProgressResponder::complete_only()`] returns only the complete receiver. The
    /// [`ProgressResponder`] documentation shows an example that submits a write with this method.
    /// If the responder is dropped without a result, for example because RaftCore stopped, the
    /// complete receiver of a [`ProgressResponder`] returns an error. That error does not tell
    /// whether the write was committed or applied.
    ///
    /// [`Responder::on_commit()`]: crate::raft::responder::Responder::on_commit
    /// [`Responder::on_complete()`]: crate::raft::responder::Responder::on_complete
    /// [`ClientWriteError::ForwardToLeader`]: crate::errors::ClientWriteError::ForwardToLeader
    /// [`ClientWriteError::LogEntryDiscarded`]: crate::errors::ClientWriteError::LogEntryDiscarded
    /// [`declare_raft_types!`]: crate::declare_raft_types
    /// [`ProgressResponder`]: crate::impls::ProgressResponder
    /// [`ProgressResponder::new()`]: crate::impls::ProgressResponder::new
    /// [`ProgressResponder::complete_only()`]: crate::impls::ProgressResponder::complete_only
    #[since(version = "0.10.0", date = "2025-10-27", change = "add responder arg")]
    #[since(version = "0.10.0")]
    pub async fn client_write_ff(
        &self,
        app_data: C::D,
        responder: Option<WriteResponderOf<C>>,
    ) -> Result<(), Fatal<C>> {
        self.app_api().client_write_ff(C::Payload::normal(app_data), responder).await
    }

    /// Write multiple application data payloads in a single batch.
    ///
    /// Returns a stream that yields the result of each entry in submission order, once that entry
    /// is applied. This is more efficient than calling [`client_write()`](Self::client_write)
    /// multiple times as it sends all payloads in a single message to the Raft core.
    ///
    /// `write_option` controls how RaftCore admits the batch: pass `WriteOption::default()` for an
    /// unconditional write, [`WriteOption::expect_leader()`] to admit the batch only while a
    /// given leader is established, or [`WriteOption::expect_last_log_id()`] to admit it only on
    /// top of a given log entry. To attach your own responders instead of reading a stream, use
    /// [`Self::write_many()`].
    ///
    /// `Err(Fatal)` from this method means the batch was not submitted. If RaftCore stops before
    /// the result of an entry arrives, the stream yields the error that stopped RaftCore in place
    /// of that result, as [`client_write()`](Self::client_write) returns it, and ends. The stream
    /// does not keep the node running: once every `Raft` handle is dropped, RaftCore stops, and
    /// the stream yields `Err(Fatal::Stopped)` in place of a result that has not arrived.
    ///
    /// # Admission
    ///
    /// The batch reaches RaftCore as one message, and RaftCore admits or rejects it as a whole:
    ///
    /// - If the expected leader is not the current committed leader, every entry yields
    ///   [`ClientWriteError::ForwardToLeader`] and nothing is appended.
    /// - If this node may not accept writes, for example because it is not the leader, its leader
    ///   lease has expired, or it is transferring leadership, every entry yields
    ///   [`ClientWriteError::ForwardToLeader`] and nothing is appended.
    /// - If the expected last log id is not the leader's last log id, every entry yields
    ///   [`ClientWriteError::PreconditionFailed`] and nothing is appended.
    /// - Otherwise every entry is appended to the leader's log in order, at consecutive log
    ///   indexes.
    ///
    /// # Commit
    ///
    /// Commit is not all or nothing: each entry is replicated and committed at its own log index.
    /// If leadership changes before the batch commits, the new leader may have received only the
    /// first part of the batch. It then commits that part and discards the rest, and each
    /// discarded entry yields [`ClientWriteError::LogEntryDiscarded`]. The state machine must
    /// deduplicate retried writes, as described in [`Self::client_write()`].
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use openraft::Raft;
    /// # use openraft::RaftTypeConfig;
    /// # use openraft::storage::RaftStateMachine;
    /// use futures_util::TryStreamExt;
    /// use openraft::raft::WriteOption;
    ///
    /// # async fn example<C, SM>(
    /// #     raft: &Raft<C, SM>,
    /// #     data1: C::D,
    /// #     data2: C::D,
    /// # ) -> Result<(), Box<dyn std::error::Error>>
    /// # where
    /// #     C: RaftTypeConfig,
    /// #     SM: RaftStateMachine<C>,
    /// # {
    /// // Admit the batch only while the leader that `as_leader()` returned still leads.
    /// let leader_id = raft.as_leader()?.to_committed_leader_id();
    /// let mut stream = raft.client_write_many([data1, data2], WriteOption::expect_leader(leader_id)).await?;
    ///
    /// // try_next() extracts Fatal error, result is WriteResult
    /// while let Some(result) = stream.try_next().await? {
    ///     match result {
    ///         Ok(response) => println!("Applied at log index: {:?}", response.log_id),
    ///         Err(error) => eprintln!("Write failed: {:?}", error),
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`ClientWriteError::ForwardToLeader`]: crate::errors::ClientWriteError::ForwardToLeader
    /// [`ClientWriteError::LogEntryDiscarded`]: crate::errors::ClientWriteError::LogEntryDiscarded
    /// [`ClientWriteError::PreconditionFailed`]: crate::errors::ClientWriteError::PreconditionFailed
    #[since(
        version = "0.10.2",
        change = "the stream yields the error that stopped RaftCore, not always `Fatal::Stopped`"
    )]
    #[since(version = "0.10.1", change = "add write_option argument")]
    #[since(version = "0.10.0")]
    #[tracing::instrument(level = "debug", skip_all)]
    pub async fn client_write_many(
        &self,
        app_data: impl IntoIterator<Item = C::D>,
        write_option: WriteOption<C>,
    ) -> Result<BoxStream<'static, Result<WriteResult<C>, Fatal<C>>>, Fatal<C>> {
        self.app_api().client_write_many(app_data.into_iter().map(C::Payload::normal), write_option).await
    }

    /// Submit a write request to Raft.
    ///
    /// Returns a [`WriteRequest`] builder. Fire-and-forget by default;
    /// use [`.responder()`] for results, [`.with_leader()`] or [`.with_option()`] for conditional
    /// writes.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use openraft::Raft;
    /// # use openraft::RaftTypeConfig;
    /// # use openraft::raft::ClientWriteResult;
    /// # use openraft::storage::RaftStateMachine;
    /// use openraft::impls::ProgressResponder;
    ///
    /// # async fn example<C, SM>(
    /// #     raft: &Raft<C, SM>,
    /// #     data1: C::D,
    /// #     data2: C::D,
    /// #     data3: C::D,
    /// # ) -> Result<(), Box<dyn std::error::Error>>
    /// # where
    /// #     C: RaftTypeConfig<Responder<ClientWriteResult<C>> = ProgressResponder<C, ClientWriteResult<C>>>,
    /// #     SM: RaftStateMachine<C>,
    /// # {
    /// // Fire-and-forget
    /// raft.write(data1).await?;
    ///
    /// // With responder
    /// let (responder2, rx2) = ProgressResponder::complete_only();
    /// raft.write(data2).responder(responder2).await?;
    /// let response2 = rx2.await??;
    ///
    /// // Conditional write (fails if leader changed)
    /// let (responder3, rx3) = ProgressResponder::complete_only();
    /// let leader_id = raft.as_leader()?.to_committed_leader_id();
    /// raft.write(data3)
    ///     .with_leader(leader_id)
    ///     .responder(responder3)
    ///     .await?;
    /// let response3 = rx3.await??;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`.responder()`]: WriteRequest::responder
    /// [`.with_leader()`]: WriteRequest::with_leader
    /// [`.with_option()`]: WriteRequest::with_option
    #[since(version = "0.10.0")]
    pub fn write(
        &self,
        app_data: C::D,
    ) -> WriteRequest<'_, C, impl Future<Output = Result<(), Fatal<C>>> + OptionalSend> {
        message::write_request(&self.inner, app_data)
    }

    /// Submit a batch of writes to Raft in one request.
    ///
    /// Returns a [`WriteManyRequest`] builder. Each item of `writes` is an application data and
    /// an optional responder that receives its result. Append more writes with [`.push()`] or
    /// [`.extend()`], and make the batch conditional with [`.with_leader()`] or
    /// [`.with_option()`].
    ///
    /// Awaiting the builder sends the batch to RaftCore without waiting for it to be appended or
    /// committed. Each write reports its result to its responder; a write without a responder
    /// reports nothing. `Err(Fatal)` means RaftCore has stopped and the batch was not submitted.
    ///
    /// # Admission
    ///
    /// RaftCore admits or rejects the batch as a whole:
    ///
    /// - If the expected leader set by [`.with_leader()`] is not the current committed leader,
    ///   every write fails with [`ClientWriteError::ForwardToLeader`] and nothing is appended.
    /// - If this node may not accept writes, for example because it is not the leader, its leader
    ///   lease has expired, or it is transferring leadership, every write fails with
    ///   [`ClientWriteError::ForwardToLeader`] and nothing is appended.
    /// - If the last log id expected by [`WriteOption::with_last_log_id()`] is not the leader's
    ///   last log id, every write fails with [`ClientWriteError::PreconditionFailed`] and nothing
    ///   is appended.
    /// - Otherwise every write is appended to the leader's log in order, at consecutive log
    ///   indexes.
    ///
    /// RaftCore may append the batch together with other queued writes, but it never splits the
    /// batch. A batch that expects a last log id is appended alone. Since admission is all or
    /// nothing, a responder on any one write tells whether the whole batch was admitted. An empty
    /// batch appends nothing.
    ///
    /// # Commit
    ///
    /// Commit is not all or nothing: each entry is replicated and committed at its own log index.
    /// If leadership changes before the batch commits, the new leader may have received only the
    /// first part of the batch. It then commits that part and discards the rest, and the
    /// responders of the discarded writes receive [`ClientWriteError::LogEntryDiscarded`].
    /// Retrying the whole batch then applies the committed part twice, so the state machine must
    /// deduplicate retried writes, as described in [`Self::client_write()`].
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use openraft::Raft;
    /// # use openraft::RaftTypeConfig;
    /// # use openraft::raft::ClientWriteResult;
    /// # use openraft::storage::RaftStateMachine;
    /// use openraft::impls::ProgressResponder;
    ///
    /// # async fn example<C, SM>(
    /// #     raft: &Raft<C, SM>,
    /// #     data1: C::D,
    /// #     data2: C::D,
    /// #     data3: C::D,
    /// # ) -> Result<(), Box<dyn std::error::Error>>
    /// # where
    /// #     C: RaftTypeConfig<Responder<ClientWriteResult<C>> = ProgressResponder<C, ClientWriteResult<C>>>,
    /// #     SM: RaftStateMachine<C>,
    /// # {
    /// let (responder1, rx1) = ProgressResponder::complete_only();
    /// let (responder3, rx3) = ProgressResponder::complete_only();
    ///
    /// // Admit the batch only while the leader that `as_leader()` returned still leads.
    /// let leader_id = raft.as_leader()?.to_committed_leader_id();
    /// raft.write_many([(data1, Some(responder1)), (data2, None)])
    ///     .push(data3, Some(responder3))
    ///     .with_leader(leader_id)
    ///     .await?;
    ///
    /// let response1 = rx1.await??;
    /// let response3 = rx3.await??;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`.push()`]: WriteManyRequest::push
    /// [`.extend()`]: WriteManyRequest::extend
    /// [`.with_leader()`]: WriteManyRequest::with_leader
    /// [`.with_option()`]: WriteManyRequest::with_option
    /// [`ClientWriteError::ForwardToLeader`]: crate::errors::ClientWriteError::ForwardToLeader
    /// [`ClientWriteError::LogEntryDiscarded`]: crate::errors::ClientWriteError::LogEntryDiscarded
    /// [`ClientWriteError::PreconditionFailed`]: crate::errors::ClientWriteError::PreconditionFailed
    #[since(version = "0.10.1")]
    pub fn write_many(
        &self,
        writes: impl IntoIterator<Item = (C::D, Option<WriteResponderOf<C>>)>,
    ) -> WriteManyRequest<'_, C, impl Future<Output = Result<(), Fatal<C>>> + OptionalSend> {
        self.app_api().write_many(writes)
    }

    /// Handle the LeaderTransfer request from a Leader node.
    ///
    /// If this node is the `to` node, it resets the Leader lease and triggers an election when the
    /// expected log entries are flushed.
    /// Otherwise, it just resets the Leader lease to allow the `to` node to become the Leader.
    ///
    /// It does not wait for RaftCore to act on the request: a response of `Ok(())` means only that
    /// the request is queued, and RaftCore ignores it unless this node's vote equals the request's
    /// vote when RaftCore handles it. Before queueing, the `to` node waits up to
    /// [`Config::election_timeout_min`] for the expected log entries to be flushed under the
    /// request's vote, and otherwise returns a [`TransferLeaderError`] in the response. See
    /// [`TransferLeaderResponse`] for what each response reports, and how to learn whether
    /// leadership moved.
    ///
    /// The application calls
    /// [`Raft::trigger().transfer_leader()`](crate::raft::trigger::Trigger::transfer_leader) to
    /// submit Transfer Leader command. Then, the current Leader will broadcast it to every node in
    /// the cluster via [`RaftNetworkV2::transfer_leader`] and the implementation on the remote node
    /// responds to transfer leader request by calling this method.
    ///
    /// [`RaftNetworkV2::transfer_leader`]: crate::network::RaftNetworkV2::transfer_leader
    #[since(version = "0.10.0", change = "returns TransferLeaderResponse")]
    #[since(version = "0.10.0")]
    #[tracing::instrument(level = "debug", skip_all)]
    pub async fn handle_transfer_leader(
        &self,
        req: TransferLeaderRequest<C>,
    ) -> Result<TransferLeaderResponse<C>, Fatal<C>> {
        self.protocol_api().handle_transfer_leader(req).await
    }

    /// Return `true` if this node is already initialized and cannot be initialized again with
    /// [`Raft::initialize`]
    #[since(version = "0.10.0")]
    pub async fn is_initialized(&self) -> Result<bool, Fatal<C>> {
        let initialized = self.with_raft_state(|st| st.is_initialized()).await?;

        Ok(initialized)
    }

    /// Initialize a pristine Raft node with the given config.
    ///
    /// A node is pristine when it has no log and its vote has the default term. A node that starts
    /// with empty storage is pristine. A node that has voted for a candidate is not, even if it
    /// has no log, because its vote has a greater term. [`Raft::is_initialized()`] returns `false`
    /// only while the node is pristine.
    ///
    /// On a node that is not pristine, `initialize()` changes nothing and returns
    /// `InitializeError::NotAllowed`. This error only says that the node can no longer be
    /// initialized. It does not mean that the cluster has a leader or that a quorum of its voters
    /// is reachable, and neither does a successful `initialize()`. To learn when a leader is
    /// elected, watch [`Raft::metrics()`] or wait for it with [`Raft::wait()`].
    ///
    /// ## Recommended Usage
    ///
    /// The simplest and most appropriate way to initialize a cluster is to call `initialize()`
    /// on **exactly one node**. The other nodes should remain empty and wait for the initialized
    /// node to replicate logs to them.
    ///
    /// Calling `initialize()` on multiple nodes with **identical configuration** is also
    /// acceptable and will not cause any consistency issues — the Raft voting protocol ensures
    /// that only one leader will be elected.
    ///
    /// However, calling `initialize()` with **different configurations** on different nodes
    /// may lead to a split-brain condition and must be avoided.
    ///
    /// To change the membership of an initialized cluster, such as to grow a single-node cluster,
    /// call [`Raft::add_learner()`] and [`Raft::change_membership()`] on the leader. A node that
    /// joins this way starts with empty storage and is not initialized.
    ///
    /// ## Behavior
    ///
    /// On success, this node:
    ///
    /// 1. Appends the membership config as the log at index 0. The membership takes effect on this
    ///    node at once, before the log is committed.
    /// 2. Starts an election to become the leader, and enters the Candidate state.
    /// 3. Returns `Ok(())` once the membership log is flushed to this node's storage, without
    ///    waiting for the election.
    ///
    /// The election needs the votes of a quorum of the voters: a single-node cluster elects this
    /// node by itself, while a multi-node cluster has no leader until a quorum of its voters is
    /// reachable. The elected leader then commits a blank log of its own term, which also commits
    /// the membership log.
    ///
    /// `members` converts into the first membership config. The default [`Membership`] converts
    /// from a `BTreeMap` or a `HashMap` of nodes, and from a `BTreeSet` of node ids when the node
    /// type is `()` or `EmptyNode`.
    /// Initialization fails with `InitializeError::InvalidMembership` when the read or the write
    /// quorum set has no usable quorum, when a quorum ID has no node, when a write voter does not
    /// have [`NodeRole::ReceiveLogs`], or when OpenRaft cannot prove that the read quorums
    /// intersect the write quorums.
    ///
    /// [`Membership`]: crate::Membership
    /// [`NodeRole::ReceiveLogs`]: crate::membership::NodeRole::ReceiveLogs
    ///
    /// # Examples
    ///
    /// Initialize a single-node cluster on node 1:
    ///
    /// ```no_run
    /// use std::collections::BTreeMap;
    ///
    /// use openraft::impls::BasicNode;
    /// # use openraft::Raft;
    /// # use openraft::RaftTypeConfig;
    /// # use openraft::storage::RaftStateMachine;
    /// #
    /// # async fn example<C, SM>(raft: Raft<C, SM>) -> Result<(), Box<dyn std::error::Error>>
    /// # where
    /// #     C: RaftTypeConfig<NodeId = u64, Node = BasicNode>,
    /// #     BTreeMap<u64, BasicNode>: Into<C::Membership>,
    /// #     SM: RaftStateMachine<C>,
    /// # {
    ///
    /// let mut nodes = BTreeMap::new();
    /// nodes.insert(1, BasicNode { addr: "127.0.0.1:8080".to_string() });
    /// raft.initialize(nodes).await?;
    ///
    /// // `initialize()` does not wait for the election
    /// raft.wait(None).current_leader(1, "node 1 is elected").await?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Or initialize a three-node cluster by calling `initialize()` on node 1 only. Nodes 2 and 3
    /// start with empty storage. Node 1 becomes the leader once one of them votes for it, then
    /// replicates the membership log to both:
    ///
    /// ```no_run
    /// use std::collections::BTreeMap;
    ///
    /// use openraft::impls::BasicNode;
    /// # use openraft::Raft;
    /// # use openraft::RaftTypeConfig;
    /// # use openraft::storage::RaftStateMachine;
    /// #
    /// # async fn example<C, SM>(raft: Raft<C, SM>) -> Result<(), Box<dyn std::error::Error>>
    /// # where
    /// #     C: RaftTypeConfig<NodeId = u64, Node = BasicNode>,
    /// #     BTreeMap<u64, BasicNode>: Into<C::Membership>,
    /// #     SM: RaftStateMachine<C>,
    /// # {
    ///
    /// let mut nodes = BTreeMap::new();
    /// nodes.insert(1, BasicNode { addr: "127.0.0.1:8080".to_string() });
    /// nodes.insert(2, BasicNode { addr: "127.0.0.1:8081".to_string() });
    /// nodes.insert(3, BasicNode { addr: "127.0.0.1:8082".to_string() });
    /// raft.initialize(nodes).await?;
    /// # Ok(())
    /// # }
    /// ```
    #[since(version = "0.10.0", change = "takes `Into<C::Membership>` instead of `IntoNodes`")]
    #[tracing::instrument(level = "debug", skip(self))]
    pub async fn initialize<T>(&self, members: T) -> Result<(), RaftError<C, InitializeError<C>>>
    where T: Into<C::Membership> + Debug {
        self.management_api().initialize(members).await.into_raft_result()
    }

    /// Provides read-only access to [`RaftState`] through a user-provided function.
    ///
    /// The function `func` is applied to the current [`RaftState`]. The result of this function,
    /// of type `V`, is returned wrapped in `Result<V, Fatal<C>>`. `Fatal` error will be
    /// returned if failed to receive a reply from `RaftCore`.
    ///
    /// A `Fatal` error is returned if:
    /// - Raft core task is stopped normally.
    /// - Raft core task is panicked due to programming error.
    /// - Raft core task is encountered a storage error.
    ///
    /// Example for getting the local committed log id:
    /// ```no_run
    /// # use openraft::Raft;
    /// # use openraft::RaftTypeConfig;
    /// # use openraft::errors::Fatal;
    /// # use openraft::storage::RaftStateMachine;
    /// #
    /// # async fn example<C, SM>(my_raft: &Raft<C, SM>) -> Result<(), Fatal<C>>
    /// # where
    /// #     C: RaftTypeConfig,
    /// #     SM: RaftStateMachine<C>,
    /// # {
    /// let committed = my_raft.with_raft_state(|st| st.local_committed().cloned()).await?;
    /// # Ok(())
    /// # }
    /// ```
    pub async fn with_raft_state<F, V>(&self, func: F) -> Result<V, Fatal<C>>
    where
        F: FnOnce(&RaftState<C>) -> V + OptionalSend + 'static,
        V: OptionalSend + 'static,
    {
        let (tx, rx) = C::oneshot();

        self.external_request(|st| {
            let result = func(st);
            if let Err(_err) = tx.send(result) {
                tracing::error!("{}: to-Raft tx send error", func_name!());
            }
        })
        .await?;

        match rx.await {
            Ok(res) => Ok(res),
            Err(err) => {
                tracing::error!("{}: rx recv error: {}", func_name!(), err);
                let fatal = self.inner.get_core_stop_error().await;
                Err(fatal)
            }
        }
    }

    /// Send a request to the Raft core loop in a fire-and-forget manner.
    ///
    /// This method returns immediately after sending the message to the Raft core loop,
    /// without waiting for the request to be executed. The returned `Result` indicates
    /// whether the message was successfully sent, not whether the request was executed.
    ///
    /// The request functor will be called with an immutable reference to the [`RaftState`]
    /// and serialized with other Raft core loop processing (e.g., client requests
    /// or general state changes).
    ///
    /// If a response is required, then the caller can store the sender of a one-shot channel
    /// in the closure of the request functor, which can then be used to send the response
    /// asynchronously.
    ///
    /// Returns a `Fatal` error if:
    /// - Raft core task is stopped normally.
    /// - Raft core task is panicked due to programming error.
    /// - Raft core task is encountered a storage error.
    pub async fn external_request<F>(&self, req: F) -> Result<(), Fatal<C>>
    where F: FnOnce(&RaftState<C>) + OptionalSend + 'static {
        let req: BoxOnce<'static, RaftState<C>> = Box::new(req);
        self.inner.send_msg(RaftMsg::WithRaftState { req }).await
    }

    /// Get a handle to the metrics channel.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// // Get current metrics
    /// let metrics = raft.metrics().borrow_watched().clone();
    /// println!("Current leader: {:?}", metrics.current_leader);
    /// println!("Current term: {}", metrics.current_term);
    /// ```
    pub fn metrics(&self) -> WatchReceiverOf<C, RaftMetrics<C>> {
        self.inner.rx_metrics.clone()
    }

    /// Get a handle to the data metrics channel.
    pub fn data_metrics(&self) -> WatchReceiverOf<C, RaftDataMetrics<C>> {
        self.inner.rx_data_metrics.clone()
    }

    /// Get a handle to the server metrics channel.
    ///
    /// When the node stops, the channel reports [`ServerState::Shutdown`] before it closes, as
    /// [`Self::metrics`] does.
    ///
    /// [`ServerState::Shutdown`]: crate::ServerState::Shutdown
    #[since(version = "0.10.2", change = "reports `Shutdown` when the node stops")]
    pub fn server_metrics(&self) -> WatchReceiverOf<C, RaftServerMetrics<C>> {
        self.inner.rx_server_metrics.clone()
    }

    /// Get a handle to watch log I/O flush progress.
    ///
    /// Tracks when log entries and votes are durably written to storage.
    /// Updated on every I/O completion (vote saves and log appends).
    ///
    /// # Waiting for an entry
    ///
    /// A [`FlushPoint`] holds the vote and the last log id of the latest I/O that storage flushed.
    /// Flush points compare their votes first, so `wait_until_ge()` returns either of these:
    ///
    /// - A flush point under the target's vote, with a log id at or after the target's.
    /// - A flush point under a greater vote, with any log id, or none.
    ///
    /// To wait for an entry, build the target from the entry's log id and the committed vote of
    /// the leader that proposed the entry. With the vote of a later leader, any log id of that
    /// leader would meet the target, whatever its index. With an uncommitted vote, the committed
    /// vote of the same leader ID would meet it, without a log id.
    ///
    /// Then check the vote of the returned flush point. Under the target's vote, this node flushes
    /// the entries of that leader's log in order, so a log id at or after the entry's shows that
    /// storage flushed the entry. A greater vote does not show it: the vote may have changed
    /// before storage flushed the entry, and a later leader can make this node truncate an entry
    /// that was not committed. The handle keeps only the latest flush point, so it does not show
    /// whether one under the target's vote came first.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use openraft::Raft;
    /// # use openraft::RaftTypeConfig;
    /// # use openraft::storage::RaftStateMachine;
    /// # use openraft::type_config::alias::LogIdOf;
    /// use openraft::Vote;
    /// use openraft::raft::FlushPoint;
    ///
    /// # async fn example<C, SM>(
    /// #     raft: &Raft<C, SM>,
    /// #     term: C::Term,
    /// #     node_id: C::NodeId,
    /// #     log_id: LogIdOf<C>,
    /// # ) -> Result<(), Box<dyn std::error::Error>>
    /// # where
    /// #     C: RaftTypeConfig,
    /// #     SM: RaftStateMachine<C>,
    /// # {
    /// let mut log_progress = raft.watch_log_progress();
    ///
    /// // Node `node_id` proposed the entry `log_id` as the leader of `term`.
    /// let vote = Vote::new_committed(term, node_id);
    /// let target = Some(FlushPoint::new(vote.clone(), Some(log_id.clone())));
    ///
    /// match log_progress.wait_until_ge(&target).await? {
    ///     Some(flushed) if flushed.vote == vote => {
    ///         // The wait returned under `vote`, so `flushed.last_log_id` is at or after `log_id`.
    ///         println!("storage flushed {log_id}");
    ///     }
    ///     _ => {
    ///         // A greater vote ended the wait, whatever log id it holds.
    ///         println!("the vote changed; storage may not have flushed {log_id}");
    ///     }
    /// }
    /// # Ok(())
    /// # }
    /// ```
    #[since(version = "0.10.0")]
    #[must_use = "progress handle should be stored to track I/O progress"]
    pub fn watch_log_progress(&self) -> LogProgress<C> {
        self.inner.progress_watcher.log_progress()
    }

    /// Get a handle to watch vote I/O flush progress.
    ///
    /// Tracks when votes (leadership changes) are durably written to storage.
    /// Updated only when the vote changes (new term or leader), not on every log append.
    ///
    /// Use this when you only care about leadership changes, not specific log entries.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let mut vote_progress = raft.watch_vote_progress();
    ///
    /// // Wait for term 2 to be persisted
    /// let target = Some(Vote::new_committed(2, 0));
    /// vote_progress.wait_until_ge(&target).await?;
    /// ```
    #[since(version = "0.10.0")]
    #[must_use = "progress handle should be stored to track vote progress"]
    pub fn watch_vote_progress(&self) -> VoteProgress<C> {
        self.inner.progress_watcher.vote_progress()
    }

    /// Get a handle to watch commit log progress.
    ///
    /// Tracks when committed logs advance(persisted on a quorum and the last-log is proposed by the
    /// leader). Updated whenever the committed cursor moves forward.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let mut commit_progress = raft.watch_commit_progress();
    ///
    /// // Wait until log index 42 is committed
    /// let target = Some(LogId::new(LeaderId::new(2, node_id), 42));
    /// commit_progress.wait_until_ge(&target).await?;
    /// ```
    #[since(version = "0.10.0")]
    #[must_use = "progress handle should be stored to track commit progress"]
    pub fn watch_commit_progress(&self) -> CommitProgress<C> {
        self.inner.progress_watcher.commit_progress()
    }

    /// Get a handle to watch snapshot persistence progress.
    ///
    /// Tracks when snapshots are persisted to storage.
    /// Updated whenever a snapshot is built or installed and persisted.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let mut snapshot_progress = raft.watch_snapshot_progress();
    ///
    /// // Wait until snapshot covering log index 100 is persisted
    /// let target = Some(LogId::new(LeaderId::new(2, node_id), 100));
    /// snapshot_progress.wait_until_ge(&target).await?;
    /// ```
    #[since(version = "0.10.0")]
    #[must_use = "progress handle should be stored to track snapshot progress"]
    pub fn watch_snapshot_progress(&self) -> SnapshotProgress<C> {
        self.inner.progress_watcher.snapshot_progress()
    }

    /// Get a handle to watch applied log progress.
    ///
    /// Tracks when logs are applied to the state machine.
    /// Updated whenever the last applied log id advances.
    ///
    /// # Note
    ///
    /// If the state machine does not persist the applied state immediately, the watcher
    /// may observe duplicate events when the server restarts and re-applies log entries.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let mut apply_progress = raft.watch_apply_progress();
    ///
    /// // Wait until log index 42 is applied
    /// let target = Some(LogId::new(LeaderId::new(2, node_id), 42));
    /// apply_progress.wait_until_ge(&target).await?;
    /// ```
    #[since(version = "0.10.0")]
    #[must_use = "progress handle should be stored to track applied progress"]
    pub fn watch_apply_progress(&self) -> AppliedProgress<C> {
        self.inner.progress_watcher.apply_progress()
    }

    /// Call `callback` each time the vote of this node names a new leader ID.
    ///
    /// Returns a [`WatchChangeHandle`] that must be held to keep watching.
    /// If the handle is dropped or [`WatchChangeHandle::close()`] is called,
    /// the background task will be terminated and the callback will no longer be invoked.
    ///
    /// The watch reads the votes of this node that storage has flushed, which
    /// [`watch_vote_progress()`] reports. A vote names a leader ID, of this node or of another
    /// one, and tells whether a quorum granted that leader ID. A committed vote names an elected
    /// leader. An uncommitted vote names a candidate, such as this node while it campaigns; a node
    /// that has never voted holds an uncommitted vote for itself in the default term. A leader ID
    /// includes the term, so a node elected again in a new term has a new leader ID.
    ///
    /// The callback receives:
    /// - `old`: `(leader_id, committed)` of the vote that the watch read last, or `None` on the
    ///   first callback.
    /// - `new`: `(leader_id, committed)` of the vote that names the new leader ID.
    ///
    /// # Observed changes
    ///
    /// The watch calls back only for a new leader ID, not when the vote of the same leader ID
    /// becomes committed. When `new` shows a candidate with `committed == false`, no callback
    /// follows when that candidate wins. The watch still reads the committed vote, so the next
    /// callback can get that leader ID in `old` with `committed == true`, although its own callback
    /// got `false`. To observe the commitment, use [`watch_vote_progress()`].
    ///
    /// The watch reads only the latest vote, so the votes flushed between two reads coalesce: a
    /// leader ID that is replaced before the watch reads it gets no callback, and does not show as
    /// `old`. The future that the callback returns is awaited before the watch reads the vote
    /// again.
    ///
    /// # Leader-only services
    ///
    /// The callback does not show whether this node leads. When this node campaigns, a callback
    /// can report it as a candidate, and none follows when it wins. After this node restarts, or
    /// steps down as a removed leader, its vote can still name it as committed. To start and stop
    /// services while this node leads, use [`on_leader_change()`], which follows the role of this
    /// node.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use openraft::Raft;
    /// # use openraft::RaftTypeConfig;
    /// # use openraft::storage::RaftStateMachine;
    /// use openraft::vote::RaftLeaderId;
    ///
    /// # async fn example<C, SM>(raft: &Raft<C, SM>)
    /// # where
    /// #     C: RaftTypeConfig,
    /// #     SM: RaftStateMachine<C>,
    /// # {
    /// let mut handle = raft.on_cluster_leader_change(|_old, (leader_id, committed)| {
    ///     // `committed` is how the vote stood when this leader ID showed first: a candidate is
    ///     // reported once, with `false`, and not again when it wins.
    ///     let term = leader_id.term();
    ///     let node_id = leader_id.node_id();
    ///     println!("leader ID of term {term}: node {node_id}, committed: {committed}");
    ///     async {}
    /// });
    ///
    /// // Later, stop watching
    /// handle.close().await;
    /// # }
    /// ```
    ///
    /// [`on_leader_change()`]: Self::on_leader_change
    /// [`watch_vote_progress()`]: Self::watch_vote_progress
    #[since(version = "0.10.0")]
    #[must_use = "handle must be held to keep the watch task running"]
    pub fn on_cluster_leader_change<F, Fut>(&self, mut callback: F) -> WatchChangeHandle<C>
    where
        F: FnMut(Option<(C::LeaderId, bool)>, (C::LeaderId, bool)) -> Fut + OptionalSend + 'static,
        Fut: Future<Output = ()> + OptionalSend + 'static,
    {
        let mut prev_vote: Option<Vote<C::LeaderId>> = None;

        self.watch_vote_change(move |new_vote, _my_node_id| {
            let old_leader = prev_vote.as_ref().map(|v| v.leader_id().clone());
            let new_leader = new_vote.leader_id().clone();

            // Only call callback if leader_id actually changed
            let fut = if old_leader.as_ref() != Some(&new_leader) {
                let old_state = prev_vote.as_ref().map(|v| (v.leader_id().clone(), v.is_committed()));
                let new_state = (new_vote.leader_id().clone(), new_vote.is_committed());
                Some(callback(old_state, new_state))
            } else {
                None
            };
            prev_vote = Some(new_vote);

            async move {
                if let Some(f) = fut {
                    f.await;
                }
            }
        })
    }

    /// Register callbacks for when this node starts or stops leading.
    ///
    /// Returns a [`WatchChangeHandle`] that must be held to keep watching.
    /// If the handle is dropped or [`WatchChangeHandle::close()`] is called,
    /// the background task will be terminated and the callbacks will no longer be invoked.
    ///
    /// Unlike [`on_cluster_leader_change()`] which fires on any leader change in the cluster,
    /// this method only fires when THIS node becomes or stops being the leader.
    ///
    /// The callbacks follow the [`RaftMetrics`] of this node. The metrics show this node leading
    /// when they show it running as [`ServerState::Leader`] with a committed
    /// [`vote`](RaftMetrics::vote) that names it, as [`as_leader()`](Self::as_leader) requires.
    /// The vote alone does not show it: the metrics keep the committed vote of this node after it
    /// restarts, steps down as a removed leader, or shuts down.
    ///
    /// - `start`: Called with the leader ID of the vote when the metrics show this node leading, at
    ///   once if it already leads.
    /// - `stop`: Called with the same leader ID when the metrics stop showing that leadership: this
    ///   node becomes a follower, a candidate, or a learner, leads in a new term, or stops.
    ///
    /// # Callback Guarantees
    ///
    /// The `start` and `stop` callbacks are guaranteed to be called in alternating order:
    /// `start` → `stop` → `start` → `stop` → ...
    ///
    /// Each callback is called only after the future returned by the previous one completes.
    /// Even if a node transitions directly from leader in Term 1 to leader in Term 2, `start` is
    /// called with the new `leader_id` only after the future that `stop` returned for the old one
    /// completes, so no code of `start` overlaps the cleanup of Term 1.
    ///
    /// When the node stops, by [`shutdown()`](Self::shutdown), by dropping every `Raft` handle,
    /// or on a fatal error, the watch calls `stop` if `start` was called last, then ends. Closing
    /// or dropping the [`WatchChangeHandle`] ends the watch without calling `stop`: the caller
    /// stops a service that still runs. Either takes effect once the callbacks for the current
    /// change return: closing the handle while `stop` runs for Term 1 still calls `start` for
    /// Term 2 before [`close()`](WatchChangeHandle::close) returns.
    ///
    /// # Limits
    ///
    /// The watch reads only the latest metrics, so updates between two reads coalesce: a
    /// leadership that begins and ends between them gets neither callback.
    ///
    /// The callbacks report what the local metrics showed; they do not confirm that this node
    /// still leads. A callback runs after the update it reports, and a leader cut off from a
    /// quorum keeps its role, so the services of an old and a new leader can run at the same time.
    /// Do not use the callbacks to authorize a read, which [`ensure_linearizable()`] does, or to
    /// keep an old leader from acting.
    ///
    /// # Example
    ///
    /// ```no_run
    /// # use openraft::Raft;
    /// # use openraft::RaftTypeConfig;
    /// # use openraft::storage::RaftStateMachine;
    /// #
    /// # async fn start_leader_services() {}
    /// # async fn stop_leader_services() {}
    /// #
    /// # async fn example<C, SM>(raft: &Raft<C, SM>)
    /// # where
    /// #     C: RaftTypeConfig,
    /// #     SM: RaftStateMachine<C>,
    /// # {
    /// let mut handle = raft.on_leader_change(
    ///     |leader_id| async move {
    ///         println!("Became leader: {:?}", leader_id);
    ///         start_leader_services().await;
    ///     },
    ///     |old_leader| async move {
    ///         println!("Stopped leading: {:?}", old_leader);
    ///         stop_leader_services().await;
    ///     },
    /// );
    ///
    /// // Later, stop watching
    /// handle.close().await;
    /// # }
    /// ```
    ///
    /// [`on_cluster_leader_change()`]: Self::on_cluster_leader_change
    /// [`ensure_linearizable()`]: Self::ensure_linearizable
    /// [`ServerState::Leader`]: crate::core::ServerState::Leader
    #[since(
        version = "0.10.2",
        change = "calls `start` only after the future of the preceding `stop` completes"
    )]
    #[since(
        version = "0.10.2",
        change = "follows the role of this node, and calls `stop` when the node stops"
    )]
    #[since(version = "0.10.0")]
    #[must_use = "handle must be held to keep the watch task running"]
    pub fn on_leader_change<F1, F2, Fut1, Fut2>(&self, start: F1, stop: F2) -> WatchChangeHandle<C>
    where
        F1: Fn(C::LeaderId) -> Fut1 + OptionalSend + 'static,
        F2: Fn(C::LeaderId) -> Fut2 + OptionalSend + 'static,
        Fut1: Future<Output = ()> + OptionalSend + 'static,
        Fut2: Future<Output = ()> + OptionalSend + 'static,
    {
        let my_node_id = self.inner.id().clone();
        // Hold the metrics receiver, not a `Raft`: a `Raft` handle would keep the node running
        // after the application drops its own handles.
        let mut rx_metrics = self.metrics();
        let (cancel_tx, mut cancel_rx) = C::oneshot::<()>();

        let handle = C::spawn(async move {
            // The leadership that `start` has been called for, and `stop` has not.
            let mut prev_leader_id: Option<C::LeaderId> = None;

            loop {
                // The committed vote keeps naming this node after it stops leading, so this node
                // leads only while the same metrics also show it running as leader.
                let leader_id = {
                    let metrics = rx_metrics.borrow_and_update();
                    let vote = &metrics.vote;
                    let leads = metrics.running_state.is_ok() && metrics.state.is_leader() && vote.is_committed();
                    let leader_id = vote.leader_id();
                    (leads && leader_id.node_id() == &my_node_id).then(|| leader_id.clone())
                };

                if leader_id != prev_leader_id {
                    // Finish `stop` of the old leadership before calling `start` of the new one,
                    // e.g., from leading in term 1 to leading in term 2: `start` can begin its
                    // work before it returns a future, and that work must not overlap the cleanup.
                    if let Some(old) = prev_leader_id.take() {
                        stop(old).await;
                    }
                    if let Some(new) = &leader_id {
                        start(new.clone()).await;
                    }
                    prev_leader_id = leader_id;
                }

                let selected = C::select2(&mut cancel_rx, rx_metrics.changed()).await;
                match selected {
                    // The handle is closed or dropped: the caller ends the watch, without `stop`.
                    Select2::First(_) => return,
                    Select2::Second(Ok(())) => {}
                    // The core is gone: it reported `Shutdown`, or it panicked without a report.
                    Select2::Second(Err(_)) => break,
                }
            }

            if let Some(leader_id) = prev_leader_id {
                stop(leader_id).await;
            }
        });

        WatchChangeHandle {
            cancel_tx: Some(cancel_tx),
            join_handle: Some(handle),
        }
    }

    /// Spawn a task that watches vote changes and invokes async callback on each change.
    ///
    /// This is an internal helper used by [`Self::on_cluster_leader_change()`].
    ///
    /// The callback returns a future that will be awaited before processing
    /// the next vote change.
    fn watch_vote_change<F, Fut>(&self, mut callback: F) -> WatchChangeHandle<C>
    where
        F: FnMut(Vote<C::LeaderId>, &NodeIdOf<C>) -> Fut + OptionalSend + 'static,
        Fut: Future<Output = ()> + OptionalSend + 'static,
    {
        let my_node_id = self.inner.id().clone();
        let mut vote_progress = self.watch_vote_progress();
        let (cancel_tx, mut cancel_rx) = C::oneshot::<()>();

        let handle = C::spawn(async move {
            loop {
                let selected = C::select2(&mut cancel_rx, vote_progress.changed()).await;
                match selected {
                    Select2::First(_) => break,
                    Select2::Second(res) => {
                        if res.is_err() {
                            break;
                        }
                        let Some(vote) = vote_progress.get() else {
                            continue;
                        };

                        callback(vote, &my_node_id).await;
                    }
                }
            }
        });

        WatchChangeHandle {
            cancel_tx: Some(cancel_tx),
            join_handle: Some(handle),
        }
    }

    /// Get a handle to wait for the metrics to satisfy some condition.
    ///
    /// A wait checks the metrics it observes and returns the first that satisfy its condition. It
    /// returns [`WaitError::ShuttingDown`] if the metrics channel closes first, which happens when
    /// the node stops.
    ///
    /// If `timeout` is `Some`, the wait returns [`WaitError::Timeout`] when no observed metrics
    /// satisfy the condition within that duration. If `timeout` is `None`, the wait sets no
    /// timeout: it ends only when observed metrics satisfy the condition or the metrics channel
    /// closes.
    ///
    /// ```no_run
    /// # use std::time::Duration;
    /// # use openraft::Raft;
    /// # use openraft::RaftTypeConfig;
    /// # use openraft::storage::RaftStateMachine;
    /// use openraft::ServerState;
    ///
    /// # async fn example<C, SM>(r: &Raft<C, SM>) -> Result<(), Box<dyn std::error::Error>>
    /// # where
    /// #     C: RaftTypeConfig<NodeId = u64>,
    /// #     SM: RaftStateMachine<C>,
    /// # {
    /// let timeout = Duration::from_millis(200);
    ///
    /// // wait for raft log-3 to be applied:
    /// r.wait(Some(timeout)).applied_index(Some(3), "log-3 applied").await?;
    ///
    /// // wait with no timeout for raft node's current leader to become 2:
    /// r.wait(None).current_leader(2, "wait for leader").await?;
    ///
    /// // wait for raft state to become a follower
    /// r.wait(None).state(ServerState::Follower, "state").await?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn wait(&self, timeout: Option<Duration>) -> Wait<C> {
        self.inner.wait(timeout)
    }

    /// Wait for this node's state machine to recover to at least the state it had before restart.
    ///
    /// Call this **once**, right after the node is created, before it starts serving requests. It
    /// is a one-time step for recovering across a restart, **not** a per-read primitive: it does
    /// not make later reads linearizable — use [`ensure_linearizable`](Self::ensure_linearizable)
    /// for each linearizable read instead. (Once recovered, the node stays recovered, so calling it
    /// again is a no-op that returns as soon as the current cluster commit has been applied.)
    ///
    /// The method waits in two phases, together bounded by `timeout`:
    /// 1. until `cluster_committed` is perceived as covering this node's current durable log tail
    ///    (the cluster commit is re-established for everything this node may have applied),
    /// 2. until the state machine has applied up to that cluster commit.
    ///
    /// The target is pinned to the first `cluster_committed` that covers this node's current
    /// durable log tail. If the cluster advanced while this node was down, that target may exceed
    /// the node's own pre-restart applied index — which still satisfies "at least the same state".
    ///
    /// It requires a reachable, functioning cluster: if no cluster commit is re-established (no
    /// leader, lost quorum, or this node is isolated), the method returns [`WaitError::Timeout`].
    /// If `timeout` is `None` it waits forever (see [`wait`](Self::wait)).
    ///
    /// # Why this works
    ///
    /// Perceiving a `cluster_committed` that covers this node's durable log tail means the current
    /// leader has either committed the local tail this node may have applied before restart, or has
    /// first replaced any uncommitted tail with the leader's log. Applying up to that commit
    /// restores every durable log entry that could have contributed to the pre-restart state. This
    /// is the same `read_log_id` argument that makes linearizable reads safe: see [the read
    /// protocol](crate::docs::protocol::read) for the read-safety argument and [the commit
    /// protocol](crate::docs::protocol::commit) for why `cluster_committed` is never a value
    /// restored from storage. A node that did not persist `committed` can use this in place of, or
    /// together with, saving it (see [log pointers](crate::docs::data::log_pointers)).
    ///
    /// # Limitation: a follower may still recover a stale state
    ///
    /// The soundness above is bounded by what this node made **durable**. A follower may apply an
    /// entry the cluster has committed before it flushes that entry locally — apply is gated on the
    /// cluster commit, not on the local flush (the invariant is `applied ≤ committed ≤ submitted`,
    /// not `applied ≤ flushed`; see [log pointers](crate::docs::data::log_pointers)). If the node
    /// restarts while such an entry is applied but still unflushed, and its applied state was not
    /// otherwise persisted, the restart reverts three tracking points at once: the durable log tail
    /// falls back to `flushed`, the state machine falls back to an earlier applied state, and
    /// `last_log_index` now describes the shorter log.
    ///
    /// Because the first-phase wait is `cluster_committed >= last_log_index` and `last_log_index`
    /// has itself reverted, a stale `cluster_committed` covering only the shrunken log satisfies
    /// it. `wait_for_recovery` can then return having recovered a state older than the one this
    /// node served immediately before the restart. The node is not stuck — the leader
    /// re-replicates the lost tail and it catches up — but across that window the method no
    /// longer pins recovery to the pre-restart state.
    ///
    /// This can only happen while serving reads as a follower. A leader holds every committed entry
    /// and never applies below its commit, so a read taken on the leader through
    /// [`ensure_linearizable`](Self::ensure_linearizable) cannot revert to an earlier state. When a
    /// read must be guaranteed fresh across a restart, serve it on the leader.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // On startup, block until the state machine has recovered the committed state before
    /// // serving reads:
    /// raft.wait_for_recovery(Some(Duration::from_secs(5))).await?;
    /// ```
    #[since(version = "0.10.0")]
    pub async fn wait_for_recovery(&self, timeout: Option<Duration>) -> Result<RaftMetrics<C>, WaitError> {
        let start = C::now();

        // Phase 1: wait until the cluster commit is re-established for this node's durable log
        // tail. A follower may first hear an older leader_commit, which is not enough to recover
        // everything it had applied before restart.
        let metrics = self
            .wait(timeout)
            .metrics(
                |m| {
                    let cluster_committed = m.cluster_committed.as_ref().map(|x| x.index());
                    cluster_committed.is_some() && cluster_committed >= m.last_log_index
                },
                "wait_for_recovery: cluster commit covers local log",
            )
            .await?;

        let target = metrics.cluster_committed.as_ref().map(|x| x.index());

        // Phase 2: wait until the state machine has applied up to that cluster commit, within the
        // time remaining from the original budget.
        let remaining = timeout.map(|t| t.saturating_sub(C::now() - start));
        self.wait(remaining)
            .applied_index_at_least(target, "wait_for_recovery: state machine applied cluster commit")
            .await
    }

    /// Shutdown this Raft node.
    ///
    /// It sends a shutdown signal and waits until `RaftCore` returns. If this future is cancelled
    /// while joining the core, a later call resumes that join and waits for the core to exit.
    /// Use [`Self::try_shutdown`] to check for a core task join failure.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// // Gracefully shutdown the Raft node
    /// raft.shutdown().await?;
    /// ```
    pub async fn shutdown(&self) -> Result<(), JoinErrorOf<C>> {
        let _ = self.try_shutdown().await;
        Ok(())
    }

    /// Shut down this node and return an error if the core task failed to join.
    ///
    /// The join finishes before this returns, and its result is retained across calls to this
    /// method and [`Self::shutdown`]. Concurrent callers and retries after cancellation share the
    /// join.
    ///
    /// Success describes the runtime join of a started core task, independently of its return
    /// value and other background task lifetimes. A node stopped before [`Self::run`] succeeds.
    #[since(version = "0.10.1", change = "joins only the core task: the tick task is retired")]
    #[since(version = "0.10.0")]
    pub async fn try_shutdown(&self) -> Result<(), ShutdownError> {
        // Dropping the sender closes the control channel, which stops RaftCore.
        let tx_control = self.inner.tx_control.lock().unwrap().take();
        if tx_control.is_some() {
            tracing::info!("closing the control channel to stop RaftCore");
        }
        drop(tx_control);

        let (_, core_failed) = self.inner.join_core_task().await;
        if core_failed { Err(ShutdownError) } else { Ok(()) }
    }

    /// Provides mutable access to [`RaftStateMachine`] through a user-provided function.
    ///
    /// The function `func` is applied to the current [`RaftStateMachine`]. The result of this
    /// function, of type `V`, is returned wrapped in `Result<V, Fatal<C>>`.
    ///
    /// A `Fatal` error is returned if:
    /// - Raft core task is stopped normally.
    /// - Raft core task is panicked due to programming error.
    /// - Raft core task is encountered a storage error.
    ///
    /// Example for getting the last applied log id from SM(assume there is `last_applied()` method
    /// provided):
    ///
    /// ```no_run
    /// # use std::future::Future;
    /// # use openraft::Raft;
    /// # use openraft::RaftTypeConfig;
    /// # use openraft::errors::Fatal;
    /// # use openraft::storage::RaftStateMachine;
    /// # use openraft::type_config::alias::LogIdOf;
    /// #
    /// # trait LastApplied<C>
    /// # where C: RaftTypeConfig
    /// # {
    /// #     fn last_applied(&mut self) -> impl Future<Output = Option<LogIdOf<C>>> + Send;
    /// # }
    /// #
    /// # async fn example<C, SM>(my_raft: &Raft<C, SM>) -> Result<(), Fatal<C>>
    /// # where
    /// #     C: RaftTypeConfig,
    /// #     SM: RaftStateMachine<C> + LastApplied<C>,
    /// # {
    /// let last_applied_log_id = my_raft.with_state_machine(|sm| {
    ///     Box::pin(async move { sm.last_applied().await })
    /// }).await?;
    /// # Ok(())
    /// # }
    /// ```
    #[since(version = "0.10.0")]
    pub async fn with_state_machine<F, V>(&self, func: F) -> Result<V, Fatal<C>>
    where
        SM: OptionalSend + 'static,
        F: FnOnce(&mut SM) -> BoxFuture<V> + OptionalSend + 'static,
        V: OptionalSend + 'static,
    {
        let (tx, rx) = C::oneshot();

        self.external_state_machine_request(|sm| {
            Box::pin(async move {
                let resp = func(sm).await;
                if let Err(_err) = tx.send(resp) {
                    tracing::error!("{}: failed to send response to user tx", func_name!());
                }
            })
        })
        .await?;

        // Use the bounded receive: the state-machine worker owns the responder and can die on its
        // own (e.g. a panic in `func`) while RaftCore keeps running. An unbounded join on the core
        // would then hang forever. `recv_msg` waits only up to `RECV_CORE_STOP_TIMEOUT` before
        // resolving to `Fatal::Stopped`.
        self.inner.recv_msg(rx).await
    }

    /// Send a request to the [`RaftStateMachine`] worker in a fire-and-forget manner.
    ///
    /// This method returns immediately after sending the message to the state machine worker,
    /// without waiting for the request to be executed. The returned `Result` indicates
    /// whether the message was successfully sent, not whether the request was executed.
    ///
    /// The request functor will be called with a mutable reference to the state machine.
    /// The functor returns a [`Future`] because state machine methods are `async`.
    ///
    /// Returns a `Fatal` error if:
    /// - Raft core task is stopped normally.
    /// - Raft core task is panicked due to programming error.
    /// - Raft core task is encountered a storage error.
    #[since(version = "0.10.0")]
    pub async fn external_state_machine_request<F>(&self, req: F) -> Result<(), Fatal<C>>
    where
        SM: OptionalSend + 'static,
        F: FnOnce(&mut SM) -> BoxFuture<()> + OptionalSend + 'static,
    {
        let Some(tx) = self.sm_cmd_tx.upgrade() else {
            return Err(self.inner.get_core_stop_error_bounded().await);
        };

        let sm_cmd = sm::Command::ExternalFunc {
            func: Box::new(move |sm| req(sm)),
        };
        if tx.send(sm_cmd).await.is_err() {
            return Err(self.inner.get_core_stop_error_bounded().await);
        }
        Ok(())
    }
}