kube-runtime 5.1.0

Kubernetes controller runtime
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
//! Watches a Kubernetes Resource for changes, with error recovery
//!
//! See [`watcher`] for the primary entry point.

use crate::utils::{Backoff, ResetTimerBackoff};

use backon::BackoffBuilder;
use educe::Educe;
use futures::{Stream, StreamExt, stream::BoxStream};
use kube_client::{
    Api, Error as ClientErr,
    api::{ListParams, Resource, ResourceExt, VersionMatch, WatchEvent, WatchParams},
    core::{ObjectList, Selector, metadata::PartialObjectMeta},
    error::Status,
};
use serde::de::DeserializeOwned;
#[cfg(test)]
#[path = "stub_watcher.rs"]
mod stub_watcher;

use std::{
    clone::Clone,
    collections::VecDeque,
    fmt::{Debug, Display},
    future::{self, Future},
    time::Duration,
};
use thiserror::Error;
use tracing::{debug, error, warn};

/// Errors that a watcher can emit
///
/// These are all considered retryable from a watcher's point of view,
/// even though they may require patching of rbac/netpols in the background to fix.
///
/// To avoid constantly looping errors, make sure backoff is applied.
#[derive(Debug, Error)]
pub enum Error {
    /// Received a raw error while performing an api.list
    #[error("failed to perform initial object list: {0}")]
    InitialListFailed(#[source] kube_client::Error),

    /// Received a raw error while starting an api.watch
    #[error("failed to start watching object: {0}")]
    WatchStartFailed(#[source] kube_client::Error),

    /// Received a `WatchEvent::Error` from the apiserver
    #[error("error returned by apiserver during watch: {0}")]
    WatchError(#[source] Box<Status>),

    /// Received a raw error while watching
    #[error("watch stream failed: {0}")]
    WatchFailed(#[source] kube_client::Error),

    /// Missing resource version field from api server
    #[error("no metadata.resourceVersion in watch result (does resource support watch?)")]
    NoResourceVersion,
}

/// Type alias for Result with a `watcher::Error` as default.
pub type Result<T, E = Error> = std::result::Result<T, E>;

#[derive(Debug, Clone)]
/// Watch events returned from the [`watcher`]
pub enum Event<K> {
    /// An object was added or modified
    Apply(K),
    /// An object was deleted
    ///
    /// The object need not have `metadata.deletionTimestamp` set or a changed
    /// `metadata.generation`. After decoding with
    /// [`touched_objects`](crate::WatchStreamExt::touched_objects), predicates based on
    /// unchanged fields can suppress it. See [predicate deletion handling](crate::predicates).
    ///
    /// NOTE: This should not be used for managing persistent state elsewhere, since
    /// events may be lost if the watcher is unavailable. Use
    /// [finalizers](crate::finalizer::finalizer) instead.
    Delete(K),
    /// The watch stream was restarted.
    ///
    /// A series of `InitApply` events are expected to follow until all matching objects
    /// have been listed. This event can be used to prepare a buffer for `InitApply` events.
    Init,
    /// Received an object during `Init`.
    ///
    /// Objects returned here are either from the initial stream using the `StreamingList` strategy,
    /// or from pages using the `ListWatch` strategy.
    ///
    /// These events can be passed up if having a complete set of objects is not a concern.
    /// If you need to wait for a complete set, please buffer these events until an `InitDone`.
    InitApply(K),
    /// The initialisation is complete.
    ///
    /// This can be used as a signal to replace buffered store contents atomically.
    /// No more `InitApply` events will happen until the next `Init` event.
    ///
    /// Any objects that were previously [`Applied`](Event::Apply) but are not listed in any of
    /// the `InitApply` events should be assumed to have been [`Deleted`](Event::Delete).
    InitDone,
}

impl<K> Display for Event<K>
where
    K: ResourceExt,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let desc = match self {
            Event::Init => "Init".into(),
            Event::InitApply(obj) => format!("InitApply({})", obj.name_any()),
            Event::InitDone => "InitDone".into(),
            Event::Apply(obj) => format!("Apply({})", obj.name_any()),
            Event::Delete(obj) => format!("Delete({})", obj.name_any()),
        };
        write!(f, "{desc}")
    }
}

impl<K> Event<K> {
    /// Map each object in an event through a mutator fn
    ///
    /// This allows for memory optimizations in watch streams.
    /// If you are chaining a watch stream into a reflector as an in memory state store,
    /// you can control the space used by each object by dropping fields.
    ///
    /// ```no_run
    /// use k8s_openapi::api::core::v1::Pod;
    /// use kube::ResourceExt;
    /// # use kube::runtime::watcher::Event;
    /// # let event: Event<Pod> = todo!();
    /// event.modify(|pod| {
    ///     pod.managed_fields_mut().clear();
    ///     pod.annotations_mut().clear();
    ///     pod.status = None;
    /// });
    /// ```
    #[must_use]
    pub fn modify(mut self, mut f: impl FnMut(&mut K)) -> Self {
        match &mut self {
            Self::Apply(obj) | Self::Delete(obj) | Self::InitApply(obj) => (f)(obj),
            Self::Init | Self::InitDone => {} // markers, nothing to modify
        }
        self
    }
}

#[derive(Educe, Default)]
#[educe(Debug)]
/// The internal finite state machine driving the [`watcher`]
enum State<K> {
    /// The Watcher is empty, and the next [`poll`](Stream::poll_next) will start the initial LIST to get all existing objects
    #[default]
    Empty,
    /// The Watcher is in the process of paginating through the initial LIST
    InitPage {
        continue_token: Option<String>,
        objects: VecDeque<K>,
        last_bookmark: Option<String>,
    },
    /// Kubernetes 1.27 Streaming Lists
    /// The initial watch is in progress
    InitialWatch {
        #[educe(Debug(ignore))]
        stream: BoxStream<'static, kube_client::Result<WatchEvent<K>>>,
    },
    /// The initial LIST was successful, so we should move on to starting the actual watch.
    InitListed { resource_version: String },
    /// The watch is in progress, from this point we just return events from the server.
    ///
    /// If the connection is disrupted then we propagate the error but try to restart the watch stream by
    /// returning to the `InitListed` state.
    /// If we fall out of the K8s watch window then we propagate the error and fall back doing a re-list
    /// with `Empty`.
    Watching {
        resource_version: String,
        #[educe(Debug(ignore))]
        stream: BoxStream<'static, kube_client::Result<WatchEvent<K>>>,
    },
}

/// Used to control whether the watcher receives the full object, or only the
/// metadata
trait ApiMode: Send + Sync {
    type Value: Clone + Send + 'static;

    fn list(
        &self,
        lp: &ListParams,
    ) -> impl Future<Output = kube_client::Result<ObjectList<Self::Value>>> + Send;
    fn watch(
        &self,
        wp: &WatchParams,
        version: &str,
    ) -> impl Future<
        Output = kube_client::Result<BoxStream<'static, kube_client::Result<WatchEvent<Self::Value>>>>,
    > + Send;
}

/// A wrapper around the `Api` of a `Resource` type that when used by the
/// watcher will return the entire (full) object
struct FullObject<K> {
    api: Api<K>,
}

/// Configurable list semantics for `watcher` relists
#[derive(Clone, Default, Debug, PartialEq)]
pub enum ListSemantic {
    /// List calls perform a full quorum read for most recent results
    ///
    /// Prefer this if you have strong consistency requirements. Note that this
    /// is more taxing for the apiserver and can be less scalable for the cluster.
    ///
    /// If you are observing large resource sets (such as congested `Controller` cases),
    /// you typically have a delay between the list call completing, and all the events
    /// getting processed. In such cases, it is probably worth picking `Any` over `MostRecent`,
    /// as your events are not guaranteed to be up-to-date by the time you get to them anyway.
    #[default]
    MostRecent,

    /// List calls returns cached results from apiserver
    ///
    /// This is faster and much less taxing on the apiserver, but can result
    /// in much older results than has previously observed for `Restarted` events,
    /// particularly in HA configurations, due to partitions or stale caches.
    ///
    /// This option makes the most sense for controller usage where events have
    /// some delay between being seen by the runtime, and it being sent to the reconciler.
    Any,
}

/// Configurable watcher listwatch semantics

#[derive(Clone, Default, Debug, PartialEq)]
pub enum InitialListStrategy {
    /// List first, then watch from given resource version
    ///
    /// This is the old and default way of watching. The watcher will do a paginated list call first before watching.
    /// When using this mode, you can configure the `page_size` on the watcher.
    #[default]
    ListWatch,
    /// Kubernetes 1.27 Streaming Lists
    ///
    /// See [upstream documentation on streaming lists](https://kubernetes.io/docs/reference/using-api/api-concepts/#streaming-lists),
    /// and the [KEP](https://github.com/kubernetes/enhancements/tree/master/keps/sig-api-machinery/3157-watch-list#design-details).
    StreamingList,
}

/// Accumulates all options that can be used on the watcher invocation.
#[derive(Clone, Debug, PartialEq)]
pub struct Config {
    /// A selector to restrict the list of returned objects by their labels.
    ///
    /// Defaults to everything if `None`.
    pub label_selector: Option<String>,

    /// A selector to restrict the list of returned objects by their fields.
    ///
    /// Defaults to everything if `None`.
    pub field_selector: Option<String>,

    /// Timeout for the watch call.
    ///
    /// This limits the duration of the call, regardless of any activity or inactivity.
    /// If unset, we will use 290s.
    /// The watcher's dead-connection detection window is this value plus 5s,
    /// so larger values delay noticing a silently dropped connection.
    pub timeout: Option<u32>,

    /// Semantics for list calls.
    ///
    /// Configures re-list for performance vs. consistency.
    ///
    /// NB: This option only has an effect for [`InitialListStrategy::ListWatch`].
    pub list_semantic: ListSemantic,

    /// Control how the watcher fetches the initial list of objects.
    ///
    /// - `ListWatch`: The watcher will fetch the initial list of objects using a list call.
    /// - `StreamingList`: The watcher will fetch the initial list of objects using a watch call.
    ///
    /// `StreamingList` is more efficient than `ListWatch`, but it requires the server to support
    /// streaming list bookmarks (opt-in feature gate in Kubernetes 1.27).
    ///
    /// See [upstream documentation on streaming lists](https://kubernetes.io/docs/reference/using-api/api-concepts/#streaming-lists),
    /// and the [KEP](https://github.com/kubernetes/enhancements/tree/master/keps/sig-api-machinery/3157-watch-list#design-details).
    pub initial_list_strategy: InitialListStrategy,

    /// Maximum number of objects retrieved per list operation resyncs.
    ///
    /// This can reduce the memory consumption during resyncs, at the cost of requiring more
    /// API roundtrips to complete.
    ///
    /// Defaults to 500. Note that `None` represents unbounded.
    ///
    /// NB: This option only has an effect for [`InitialListStrategy::ListWatch`].
    pub page_size: Option<u32>,

    /// Enables watch events with type "BOOKMARK".
    ///
    /// Requests watch bookmarks from the apiserver when enabled for improved watch precision and reduced list calls.
    /// This is default enabled and should generally not be turned off.
    pub bookmarks: bool,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            bookmarks: true,
            label_selector: None,
            field_selector: None,
            timeout: None,
            list_semantic: ListSemantic::default(),
            // same default page size limit as client-go
            // https://github.com/kubernetes/client-go/blob/aed71fa5cf054e1c196d67b2e21f66fd967b8ab1/tools/pager/pager.go#L31
            page_size: Some(500),
            initial_list_strategy: InitialListStrategy::ListWatch,
        }
    }
}

/// Builder interface to Config
///
/// Usage:
/// ```
/// use kube::runtime::watcher::Config;
/// let wc = Config::default()
///     .timeout(60)
///     .labels("kubernetes.io/lifecycle=spot");
/// ```
impl Config {
    /// Configure the timeout for watch calls
    ///
    /// This limits the duration of the call, regardless of any activity or inactivity.
    /// Defaults to 290s
    #[must_use]
    pub fn timeout(mut self, timeout_secs: u32) -> Self {
        self.timeout = Some(timeout_secs);
        self
    }

    /// Configure the selector to restrict the list of returned objects by their fields.
    ///
    /// Defaults to everything.
    /// Supports `=`, `==`, `!=`, and can be comma separated: `key1=value1,key2=value2`.
    /// The server only supports a limited number of field queries per type.
    #[must_use]
    pub fn fields(mut self, field_selector: &str) -> Self {
        self.field_selector = Some(field_selector.to_string());
        self
    }

    /// Configure the selector to restrict the list of returned objects by their labels.
    ///
    /// Defaults to everything.
    /// Supports `=`, `==`, `!=`, and can be comma separated: `key1=value1,key2=value2`.
    #[must_use]
    pub fn labels(mut self, label_selector: &str) -> Self {
        self.label_selector = Some(label_selector.to_string());
        self
    }

    /// Configure typed label selectors
    ///
    /// Configure typed selectors from [`Selector`](kube_client::core::Selector) and [`Expression`](kube_client::core::Expression) lists.
    ///
    /// ```
    /// use kube_runtime::watcher::Config;
    /// use kube_client::core::{Expression, Selector, ParseExpressionError};
    /// use k8s_openapi::apimachinery::pkg::apis::meta::v1::LabelSelector;
    /// let selector: Selector = Expression::In("env".into(), ["development".into(), "sandbox".into()].into()).into();
    /// let cfg = Config::default().labels_from(&selector);
    /// let cfg = Config::default().labels_from(&Expression::Exists("foo".into()).into());
    /// let selector: Selector = LabelSelector::default().try_into()?;
    /// let cfg = Config::default().labels_from(&selector);
    /// # Ok::<(), ParseExpressionError>(())
    ///```
    #[must_use]
    pub fn labels_from(mut self, selector: &Selector) -> Self {
        self.label_selector = Some(selector.to_string());
        self
    }

    /// Sets list semantic to configure re-list performance and consistency
    ///
    /// NB: This option only has an effect for [`InitialListStrategy::ListWatch`].
    #[must_use]
    pub fn list_semantic(mut self, semantic: ListSemantic) -> Self {
        self.list_semantic = semantic;
        self
    }

    /// Sets list semantic to `Any` to improve list performance
    ///
    /// NB: This option only has an effect for [`InitialListStrategy::ListWatch`].
    #[must_use]
    pub fn any_semantic(self) -> Self {
        self.list_semantic(ListSemantic::Any)
    }

    /// Disables watch bookmarks to simplify watch handling
    ///
    /// This is not recommended to use with production watchers as it can cause desyncs.
    /// See [#219](https://github.com/kube-rs/kube/issues/219) for details.
    #[must_use]
    pub fn disable_bookmarks(mut self) -> Self {
        self.bookmarks = false;
        self
    }

    /// Limits the number of objects retrieved in each list operation during resync.
    ///
    /// This can reduce the memory consumption during resyncs, at the cost of requiring more
    /// API roundtrips to complete.
    ///
    /// NB: This option only has an effect for [`InitialListStrategy::ListWatch`].
    #[must_use]
    pub fn page_size(mut self, page_size: u32) -> Self {
        self.page_size = Some(page_size);
        self
    }

    /// Kubernetes 1.27 Streaming Lists
    /// Sets list semantic to `Stream` to make use of watch bookmarks
    #[must_use]
    pub fn streaming_lists(mut self) -> Self {
        self.initial_list_strategy = InitialListStrategy::StreamingList;
        self
    }

    /// Converts generic `watcher::Config` structure to the instance of `ListParams` used for list requests.
    fn to_list_params(&self) -> ListParams {
        let (resource_version, version_match) = match self.list_semantic {
            ListSemantic::Any => (Some("0".into()), Some(VersionMatch::NotOlderThan)),
            ListSemantic::MostRecent => (None, None),
        };
        ListParams {
            label_selector: self.label_selector.clone(),
            field_selector: self.field_selector.clone(),
            version_match,
            resource_version,
            // The watcher handles pagination internally.
            limit: self.page_size,
            continue_token: None,
            ..Default::default()
        }
    }

    /// Converts generic `watcher::Config` structure to the instance of `WatchParams` used for watch requests.
    fn to_watch_params(&self, phase: WatchPhase) -> WatchParams {
        WatchParams {
            label_selector: self.label_selector.clone(),
            field_selector: self.field_selector.clone(),
            timeout: self.timeout,
            bookmarks: self.bookmarks,
            send_initial_events: phase == WatchPhase::Initial
                && self.initial_list_strategy == InitialListStrategy::StreamingList,
        }
    }
}

/// Distinguishes between initial watch and resumed watch for streaming lists.
///
/// This is used to determine whether to set `sendInitialEvents=true` in watch requests.
/// Only initial watches should request initial events; reconnections should not.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum WatchPhase {
    /// Initial watch from `State::Empty` - requests initial events for streaming lists
    Initial,
    /// Resumed watch from `State::InitListed` - does not request initial events
    Resumed,
}

impl<K> ApiMode for FullObject<K>
where
    K: Clone + Debug + DeserializeOwned + Send + 'static,
{
    type Value = K;

    async fn list(&self, lp: &ListParams) -> kube_client::Result<ObjectList<Self::Value>> {
        self.api.list(lp).await
    }

    async fn watch(
        &self,
        wp: &WatchParams,
        version: &str,
    ) -> kube_client::Result<BoxStream<'static, kube_client::Result<WatchEvent<Self::Value>>>> {
        self.api.watch(wp, version).await.map(StreamExt::boxed)
    }
}

/// A wrapper around the `Api` of a `Resource` type that when used by the
/// watcher will return only the metadata associated with an object
struct MetaOnly<K> {
    api: Api<K>,
}

impl<K> ApiMode for MetaOnly<K>
where
    K: Clone + Debug + DeserializeOwned + Send + 'static,
{
    type Value = PartialObjectMeta<K>;

    async fn list(&self, lp: &ListParams) -> kube_client::Result<ObjectList<Self::Value>> {
        self.api.list_metadata(lp).await
    }

    async fn watch(
        &self,
        wp: &WatchParams,
        version: &str,
    ) -> kube_client::Result<BoxStream<'static, kube_client::Result<WatchEvent<Self::Value>>>> {
        self.api.watch_metadata(wp, version).await.map(StreamExt::boxed)
    }
}

/// Client-side idle timeout margin added on top of the server-side watch timeout.
///
/// The server closes the watch stream after the configured timeout (default 290s).
/// We add a small margin so the client detects dead connections where the
/// server's close never arrives (e.g. network failure).
const WATCH_IDLE_TIMEOUT_MARGIN: Duration = Duration::from_secs(5);

/// Poll the next item from a watch stream with an idle timeout.
///
/// Returns `None` when the stream ends **or** when no item arrives within
/// `timeout + WATCH_IDLE_TIMEOUT_MARGIN`, causing the watcher to
/// treat the connection as dead and reconnect. An explicit zero timeout
/// disables this client-side idle timeout.
async fn next_with_idle_timeout<S, T>(stream: &mut S, timeout: Option<u32>) -> Option<T>
where
    S: Stream<Item = T> + Unpin,
{
    with_idle_timeout(stream.next(), timeout).await.flatten()
}

/// Await `fut` with the same idle timeout, returning `None` on expiry.
///
/// Also wraps the watch call, which can stall before a stream exists,
/// e.g. on an error response whose body never completes.
async fn with_idle_timeout<F: Future>(fut: F, timeout: Option<u32>) -> Option<F::Output> {
    if timeout == Some(0) {
        return Some(fut.await);
    }

    let idle_timeout = Duration::from_secs(u64::from(timeout.unwrap_or(290))) + WATCH_IDLE_TIMEOUT_MARGIN;
    match tokio::time::timeout(idle_timeout, fut).await {
        Ok(output) => Some(output),
        Err(_elapsed) => {
            debug!(
                timeout_secs = idle_timeout.as_secs(),
                "watch idle timeout, reconnecting"
            );
            None
        }
    }
}

/// Progresses the watcher a single step, returning (event, state)
///
/// This function should be trampolined: if event == `None`
/// then the function should be called again until it returns a Some.
#[allow(clippy::too_many_lines)] // for now
async fn step_trampolined<A>(
    api: &A,
    wc: &Config,
    state: State<A::Value>,
) -> (Option<Result<Event<A::Value>>>, State<A::Value>)
where
    A: ApiMode,
    A::Value: Resource + 'static,
{
    match state {
        State::Empty => match wc.initial_list_strategy {
            InitialListStrategy::ListWatch => (Some(Ok(Event::Init)), State::InitPage {
                continue_token: None,
                objects: VecDeque::default(),
                last_bookmark: None,
            }),
            InitialListStrategy::StreamingList => {
                match with_idle_timeout(
                    api.watch(&wc.to_watch_params(WatchPhase::Initial), "0"),
                    wc.timeout,
                )
                .await
                {
                    Some(Ok(stream)) => (Some(Ok(Event::Init)), State::InitialWatch { stream }),
                    Some(Err(err)) => {
                        if std::matches!(err, ClientErr::Api(ref status) if status.is_forbidden()) {
                            warn!("watch initlist error with 403: {err:?}");
                        } else {
                            debug!("watch initlist error: {err:?}");
                        }
                        (Some(Err(Error::WatchStartFailed(err))), State::default())
                    }
                    None => (None, State::default()),
                }
            }
        },
        State::InitPage {
            continue_token,
            mut objects,
            last_bookmark,
        } => {
            if let Some(next) = objects.pop_front() {
                return (Some(Ok(Event::InitApply(next))), State::InitPage {
                    continue_token,
                    objects,
                    last_bookmark,
                });
            }
            // check if we need to perform more pages
            if continue_token.is_none()
                && let Some(resource_version) = last_bookmark
            {
                // we have drained the last page - move on to next stage
                return (Some(Ok(Event::InitDone)), State::InitListed { resource_version });
            }
            let mut lp = wc.to_list_params();
            lp.continue_token = continue_token;
            match api.list(&lp).await {
                Ok(list) => {
                    let last_bookmark = list.metadata.resource_version.filter(|s| !s.is_empty());
                    let continue_token = list.metadata.continue_.filter(|s| !s.is_empty());
                    if last_bookmark.is_none() && continue_token.is_none() {
                        return (Some(Err(Error::NoResourceVersion)), State::Empty);
                    }
                    // Buffer page here, causing us to return to this enum branch (State::InitPage)
                    // until the objects buffer has drained
                    (None, State::InitPage {
                        continue_token,
                        objects: list.items.into_iter().collect(),
                        last_bookmark,
                    })
                }
                Err(err) => {
                    if std::matches!(err, ClientErr::Api(ref status) if status.is_forbidden()) {
                        warn!("watch list error with 403: {err:?}");
                    } else {
                        debug!("watch list error: {err:?}");
                    }
                    (Some(Err(Error::InitialListFailed(err))), State::Empty)
                }
            }
        }
        State::InitialWatch { mut stream } => {
            match next_with_idle_timeout(&mut stream, wc.timeout).await {
                Some(Ok(WatchEvent::Added(obj) | WatchEvent::Modified(obj))) => {
                    (Some(Ok(Event::InitApply(obj))), State::InitialWatch { stream })
                }
                Some(Ok(WatchEvent::Deleted(_obj))) => {
                    // Kubernetes claims these events are impossible
                    // https://kubernetes.io/docs/reference/using-api/api-concepts/#streaming-lists
                    error!("got deleted event during initial watch. this is a bug");
                    (None, State::InitialWatch { stream })
                }
                Some(Ok(WatchEvent::Bookmark(bm))) => {
                    let marks_initial_end = bm.metadata.annotations.contains_key("k8s.io/initial-events-end");
                    if marks_initial_end {
                        (Some(Ok(Event::InitDone)), State::Watching {
                            resource_version: bm.metadata.resource_version,
                            stream,
                        })
                    } else {
                        (None, State::InitialWatch { stream })
                    }
                }
                Some(Ok(WatchEvent::Error(err))) => {
                    // HTTP GONE, means we have desynced and need to start over and re-list :(
                    let new_state = if err.code == 410 {
                        State::default()
                    } else {
                        State::InitialWatch { stream }
                    };
                    if err.code == 403 {
                        warn!("watcher watchevent error 403: {err:?}");
                    } else {
                        debug!("error watchevent error: {err:?}");
                    }
                    (Some(Err(Error::WatchError(err.boxed()))), new_state)
                }
                Some(Err(err)) => {
                    if std::matches!(err, ClientErr::Api(ref status) if status.is_forbidden()) {
                        warn!("watcher error 403: {err:?}");
                    } else {
                        debug!("watcher error: {err:?}");
                    }
                    (Some(Err(Error::WatchFailed(err))), State::InitialWatch { stream })
                }
                None => (None, State::default()),
            }
        }
        State::InitListed { resource_version } => {
            match with_idle_timeout(
                api.watch(&wc.to_watch_params(WatchPhase::Resumed), &resource_version),
                wc.timeout,
            )
            .await
            {
                Some(Ok(stream)) => (None, State::Watching {
                    resource_version,
                    stream,
                }),
                Some(Err(err)) => {
                    if std::matches!(err, ClientErr::Api(ref status) if status.is_forbidden()) {
                        warn!("watch initlist error with 403: {err:?}");
                    } else {
                        debug!("watch initlist error: {err:?}");
                    }
                    (Some(Err(Error::WatchStartFailed(err))), State::InitListed {
                        resource_version,
                    })
                }
                None => (None, State::InitListed { resource_version }),
            }
        }
        State::Watching {
            resource_version,
            mut stream,
        } => match next_with_idle_timeout(&mut stream, wc.timeout).await {
            Some(Ok(WatchEvent::Added(obj) | WatchEvent::Modified(obj))) => {
                let resource_version = obj.resource_version().unwrap_or_default();
                if resource_version.is_empty() {
                    (Some(Err(Error::NoResourceVersion)), State::default())
                } else {
                    (Some(Ok(Event::Apply(obj))), State::Watching {
                        resource_version,
                        stream,
                    })
                }
            }
            Some(Ok(WatchEvent::Deleted(obj))) => {
                let resource_version = obj.resource_version().unwrap_or_default();
                if resource_version.is_empty() {
                    (Some(Err(Error::NoResourceVersion)), State::default())
                } else {
                    (Some(Ok(Event::Delete(obj))), State::Watching {
                        resource_version,
                        stream,
                    })
                }
            }
            Some(Ok(WatchEvent::Bookmark(bm))) => (None, State::Watching {
                resource_version: bm.metadata.resource_version,
                stream,
            }),
            Some(Ok(WatchEvent::Error(err))) => {
                // HTTP GONE, means we have desynced and need to start over and re-list :(
                let new_state = if err.code == 410 {
                    State::default()
                } else {
                    State::Watching {
                        resource_version,
                        stream,
                    }
                };
                if err.code == 403 {
                    warn!("watcher watchevent error 403: {err:?}");
                } else {
                    debug!("error watchevent error: {err:?}");
                }
                (Some(Err(Error::WatchError(err.boxed()))), new_state)
            }
            Some(Err(err)) => {
                if std::matches!(err, ClientErr::Api(ref status) if status.is_forbidden()) {
                    warn!("watcher error 403: {err:?}");
                } else {
                    debug!("watcher error: {err:?}");
                }
                (Some(Err(Error::WatchFailed(err))), State::Watching {
                    resource_version,
                    stream,
                })
            }
            None => (None, State::InitListed { resource_version }),
        },
    }
}

/// Trampoline helper for `step_trampolined`
async fn step<A>(
    api: &A,
    config: &Config,
    mut state: State<A::Value>,
) -> (Result<Event<A::Value>>, State<A::Value>)
where
    A: ApiMode,
    A::Value: Resource + 'static,
{
    loop {
        match step_trampolined(api, config, state).await {
            (Some(result), new_state) => return (result, new_state),
            (None, new_state) => state = new_state,
        }
    }
}

/// Watches a Kubernetes Resource for changes continuously
///
/// Compared to [`Api::watch`], this automatically tries to recover the stream upon errors.
///
/// Errors from the underlying watch are propagated, after which the stream will go into recovery mode on the next poll.
/// You can apply your own backoff by not polling the stream for a duration after errors.
/// Keep in mind that some [`TryStream`](futures::TryStream) combinators (such as
/// [`try_for_each`](futures::TryStreamExt::try_for_each) and [`try_concat`](futures::TryStreamExt::try_concat))
/// will terminate eagerly as soon as they receive an [`Err`].
///
/// The events are intended to provide a safe input interface for a state store like a [`reflector`].
/// Direct users may want to use [`WatchStreamExt`] for higher-level constructs.
///
/// ```
/// use kube::{
///   api::{Api, ResourceExt}, Client,
///   runtime::{watcher, WatchStreamExt}
/// };
/// use k8s_openapi::api::core::v1::Pod;
/// use futures::TryStreamExt;
///
/// # async fn wrapper() -> Result<(), watcher::Error> {
/// #   let client: Client = todo!();
/// let pods: Api<Pod> = Api::namespaced(client, "apps");
///
/// watcher(pods, watcher::Config::default()).applied_objects()
///     .try_for_each(|p| async move {
///         println!("Applied: {}", p.name_any());
///        Ok(())
///     })
///     .await?;
/// # Ok(())
/// # }
/// ```
/// [`WatchStreamExt`]: super::WatchStreamExt
/// [`reflector`]: super::reflector::reflector
/// [`Api::watch`]: kube_client::Api::watch
///
/// # Recovery
///
/// The stream will attempt to be recovered on the next poll after an [`Err`] is returned.
/// This will normally happen immediately, but you can use [`StreamBackoff`](crate::utils::StreamBackoff)
/// to introduce an artificial delay. [`DefaultBackoff::default`] returns a suitable default set of parameters.
///
/// If the watch connection is interrupted, then `watcher` will attempt to restart the watch using the last
/// [resource version](https://kubernetes.io/docs/reference/using-api/api-concepts/#efficient-detection-of-changes)
/// that we have seen on the stream. If this is successful then the stream is simply resumed from where it left off.
/// If this fails because the resource version is no longer valid then we start over with a new stream, starting with
/// an [`Event::Init`]. The internals mechanics of recovery should be considered an implementation detail.
#[doc(alias = "informer")]
pub fn watcher<K: Resource + Clone + DeserializeOwned + Debug + Send + 'static>(
    api: Api<K>,
    watcher_config: Config,
) -> impl Stream<Item = Result<Event<K>>> + Send {
    watcher_inner(FullObject { api }, watcher_config)
}

/// [`ApiMode`] compatibility helper. Introduced later so that the core logic of [`watcher`] can be tested without
/// having to modify its pre-existing signature.
fn watcher_inner<A>(api: A, watcher_config: Config) -> impl Stream<Item = Result<Event<A::Value>>> + Send
where
    A: ApiMode,
    A::Value: Resource,
{
    futures::stream::unfold(
        (api, watcher_config, State::default()),
        |(api, watcher_config, state)| async {
            let (event, state) = step(&api, &watcher_config, state).await;
            Some((event, (api, watcher_config, state)))
        },
    )
}

/// Watches a Kubernetes Resource for changes continuously and receives only the
/// metadata
///
/// Compared to [`Api::watch_metadata`], this automatically tries to recover the stream upon errors.
///
/// Errors from the underlying watch are propagated, after which the stream will go into recovery mode on the next poll.
/// You can apply your own backoff by not polling the stream for a duration after errors.
/// Keep in mind that some [`TryStream`](futures::TryStream) combinators (such as
/// [`try_for_each`](futures::TryStreamExt::try_for_each) and [`try_concat`](futures::TryStreamExt::try_concat))
/// will terminate eagerly as soon as they receive an [`Err`].
///
/// The events are intended to provide a safe input interface for a state store like a [`reflector`].
/// Direct users may want to use [`WatchStreamExt`] for higher-level constructs.
///
/// ```
/// use kube::{
///   api::{Api, ResourceExt}, Client,
///   runtime::{watcher, metadata_watcher, WatchStreamExt}
/// };
/// use k8s_openapi::api::core::v1::Pod;
/// use futures::TryStreamExt;
///
/// # async fn wrapper() -> Result<(), watcher::Error> {
/// #   let client: Client = todo!();
/// let pods: Api<Pod> = Api::namespaced(client, "apps");
///
/// metadata_watcher(pods, watcher::Config::default()).applied_objects()
///         .try_for_each(|p| async move {
///          println!("Applied: {}", p.name_any());
///             Ok(())
///         })
///         .await?;
/// #   Ok(())
/// # }
/// ```
/// [`WatchStreamExt`]: super::WatchStreamExt
/// [`reflector`]: super::reflector::reflector
/// [`Api::watch`]: kube_client::Api::watch
///
/// # Recovery
///
/// The stream will attempt to be recovered on the next poll after an [`Err`] is returned.
/// This will normally happen immediately, but you can use [`StreamBackoff`](crate::utils::StreamBackoff)
/// to introduce an artificial delay. [`DefaultBackoff::default`] returns a suitable default set of parameters.
///
/// If the watch connection is interrupted, then `watcher` will attempt to restart the watch using the last
/// [resource version](https://kubernetes.io/docs/reference/using-api/api-concepts/#efficient-detection-of-changes)
/// that we have seen on the stream. If this is successful then the stream is simply resumed from where it left off.
/// If this fails because the resource version is no longer valid then we start over with a new stream, starting with
/// an [`Event::Init`]. The internals mechanics of recovery should be considered an implementation detail.
#[deprecated(
    since = "3.1.0",
    note = "Use `watcher(Api::<PartialObjectMeta<K>>::all(client), config)` instead. \
            `Api<PartialObjectMeta<K>>` now automatically uses metadata-only requests."
)]
pub fn metadata_watcher<K: Resource + Clone + DeserializeOwned + Debug + Send + 'static>(
    api: Api<K>,
    watcher_config: Config,
) -> impl Stream<Item = Result<Event<PartialObjectMeta<K>>>> + Send {
    watcher_inner(MetaOnly { api }, watcher_config)
}

/// Watch a single named object for updates
///
/// Emits `None` if the object is deleted (or not found), and `Some` if an object is updated (or created/found).
///
/// Often invoked indirectly via [`await_condition`](crate::wait::await_condition()).
///
/// ## Scope Warning
///
/// When using this with an `Api::all` on namespaced resources there is a chance of duplicated names.
/// To avoid getting confusing / wrong answers for this, use `Api::namespaced` bound to a specific namespace
/// when watching for transitions to namespaced objects.
pub fn watch_object<K: Resource + Clone + DeserializeOwned + Debug + Send + 'static>(
    api: Api<K>,
    name: &str,
) -> impl Stream<Item = Result<Option<K>>> + Send + use<K> {
    // filtering by object name in given scope, so there's at most one matching object
    // footgun: Api::all may generate events from namespaced objects with the same name in different namespaces
    let fields = format!("metadata.name={name}");
    watcher(api, Config::default().fields(&fields))
        // The `obj_seen` state is used to track whether the object exists in each Init / InitApply / InitDone
        // sequence of events. If the object wasn't seen in any particular sequence it is treated as deleted and
        // `None` is emitted when the InitDone event is received.
        //
        // The first check ensures `None` is emitted if the object was already gone (or not found), subsequent
        // checks ensure `None` is emitted even if for some reason the Delete event wasn't received, which
        // could happen given K8S events aren't guaranteed delivery.
        .scan(false, |obj_seen, event| {
            if matches!(event, Ok(Event::Init)) {
                *obj_seen = false;
            } else if matches!(event, Ok(Event::InitApply(_))) {
                *obj_seen = true;
            }
            future::ready(Some((*obj_seen, event)))
        })
        .filter_map(|(obj_seen, event)| async move {
            match event {
                // Pass up `Some` for Found / Updated
                Ok(Event::Apply(obj) | Event::InitApply(obj)) => Some(Ok(Some(obj))),
                // Pass up `None` for Deleted
                Ok(Event::Delete(_)) => Some(Ok(None)),
                // Pass up `None` if the object wasn't seen in the initial list
                Ok(Event::InitDone) if !obj_seen => Some(Ok(None)),
                // Ignore marker events
                Ok(Event::Init | Event::InitDone) => None,
                // Bubble up errors
                Err(err) => Some(Err(err)),
            }
        })
}

/// A struct with a manually configured exponential backoff
pub struct ExponentialBackoff {
    inner: backon::ExponentialBackoff,
    builder: backon::ExponentialBuilder,
}

impl ExponentialBackoff {
    fn new(min_delay: Duration, max_delay: Duration, factor: f32, enable_jitter: bool) -> Self {
        let builder = backon::ExponentialBuilder::default()
            .with_min_delay(min_delay)
            .with_max_delay(max_delay)
            .with_factor(factor)
            .without_max_times();

        let builder = if enable_jitter {
            builder.with_jitter()
        } else {
            builder
        };

        Self {
            inner: builder.build(),
            builder,
        }
    }
}

impl Backoff for ExponentialBackoff {
    fn reset(&mut self) {
        self.inner = self.builder.build();
    }
}

impl Iterator for ExponentialBackoff {
    type Item = Duration;

    fn next(&mut self) -> Option<Self::Item> {
        self.inner.next()
    }
}

impl From<backon::ExponentialBuilder> for ExponentialBackoff {
    fn from(builder: backon::ExponentialBuilder) -> Self {
        Self {
            inner: builder.build(),
            builder,
        }
    }
}

/// Default watcher backoff inspired by Kubernetes' client-go.
///
/// The parameters currently optimize for being kind to struggling apiservers.
/// The exact parameters are taken from
/// [client-go's reflector source](https://github.com/kubernetes/client-go/blob/980663e185ab6fc79163b1c2565034f6d58368db/tools/cache/reflector.go#L177-L181)
/// and should not be considered stable.
///
/// This struct implements [`Backoff`] and is the default strategy used
/// when calling `WatchStreamExt::default_backoff`. If you need to create
/// this manually then [`DefaultBackoff::default`] can be used.
pub struct DefaultBackoff(Strategy);
type Strategy = ResetTimerBackoff<ExponentialBackoff>;

impl Default for DefaultBackoff {
    fn default() -> Self {
        Self(ResetTimerBackoff::new(
            ExponentialBackoff::new(Duration::from_millis(800), Duration::from_secs(30), 2.0, true),
            Duration::from_secs(120),
        ))
    }
}

impl Iterator for DefaultBackoff {
    type Item = Duration;

    fn next(&mut self) -> Option<Self::Item> {
        self.0.next()
    }
}

impl Backoff for DefaultBackoff {
    fn reset(&mut self) {
        self.0.reset();
    }
}

#[cfg(test)]
mod tests {
    use std::{collections::BTreeMap, time::Duration};

    use futures::{StreamExt, TryStreamExt, stream::BoxStream};
    use http::{Request, Response, StatusCode, header::CONTENT_LENGTH};
    use http_body_util::{BodyExt, StreamBody};
    use k8s_openapi::{api::core::v1::ConfigMap, apimachinery::pkg::apis::meta::v1::ObjectMeta};
    use kube_client::{
        Api, Client,
        api::{ListParams, TypeMeta, WatchEvent, WatchParams},
        client::Body,
        core::{
            ObjectList, Status,
            watch::{Bookmark, BookmarkMeta},
        },
    };

    use crate::{
        WatchStreamExt,
        watcher::{
            ApiMode, Config, Error, ExponentialBackoff, State, WatchPhase, next_with_idle_timeout, step,
            step_trampolined,
            stub_watcher::{
                Recording, Sequence, SequenceStep, TestMode, error_indicates_graceful_watch_seq_exhaustion,
            },
            watcher, watcher_inner,
        },
    };

    use super::stub_watcher::ResultPage;

    fn config_map(name: &str, resource_version: &str) -> ConfigMap {
        ConfigMap {
            metadata: ObjectMeta {
                name: Some(name.to_string()),
                resource_version: Some(resource_version.to_string()),
                ..ObjectMeta::default()
            },
            ..ConfigMap::default()
        }
    }

    #[tokio::test(start_paused = true)]
    async fn test_mode_watch_waits_before_returning_next_event() {
        let api = TestMode::new(vec![], vec![Sequence::new(vec![
            SequenceStep::Wait(Duration::from_millis(50)),
            SequenceStep::List(vec![Ok(WatchEvent::Added(config_map("a", "1")))].into()),
        ])]);
        let mut stream = api.watch(&WatchParams::default(), "0").await.unwrap();

        assert!(futures::poll!(stream.next()).is_pending());
        tokio::time::advance(Duration::from_millis(49)).await;
        assert!(futures::poll!(stream.next()).is_pending());
        tokio::time::advance(Duration::from_millis(1)).await;

        assert!(matches!(
            stream.next().await,
            Some(Ok(WatchEvent::Added(config_map))) if config_map.metadata.name.as_deref() == Some("a")
        ));
    }

    #[allow(clippy::too_many_lines)]
    #[tokio::test]
    async fn streaming_list_resync() {
        const LAST_VALID_RESOURCE_VERSION: &str = "5";
        let mut recoverable_err = Box::new(Status::default());
        recoverable_err.code = 502;
        recoverable_err.message = "some err".to_string();
        recoverable_err.reason = "Something went wrong".to_string();
        let api = TestMode::new(vec![], vec![
            Sequence::new(vec![
                SequenceStep::List(
                    vec![
                        Ok(WatchEvent::Added(config_map("a", "2"))),
                        Ok(WatchEvent::Added(config_map("b", "3"))),
                        Ok(WatchEvent::Added(config_map("c", "4"))),
                        // Details here: https://kubernetes.io/docs/reference/using-api/api-concepts/#streaming-lists
                        // Should only be sent when requested via allowWatchBookmarks=true
                        // Since TestMode does not contain any real logic and  is not dynamically
                        // progammable, this is up to the test
                        // author to return or not for now.
                        Ok(WatchEvent::Bookmark(Bookmark {
                            types: TypeMeta::resource::<ConfigMap>(),
                            metadata: BookmarkMeta {
                                resource_version: "4".to_string(),
                                annotations: BTreeMap::from_iter(vec![(
                                    "k8s.io/initial-events-end".into(),
                                    "true".into(),
                                )]),
                            },
                        })),
                    ]
                    .into(),
                ),
                SequenceStep::List(
                    vec![
                        Ok(WatchEvent::Modified(config_map("a", LAST_VALID_RESOURCE_VERSION))),
                        Ok(WatchEvent::Error(recoverable_err)),
                    ]
                    .into(),
                ),
                // After an error we expect the watcher to request its last(latest) known
                // resource version to be queried again.
                SequenceStep::List(
                    vec![Ok(WatchEvent::Modified(config_map(
                        "a",
                        LAST_VALID_RESOURCE_VERSION,
                    )))]
                    .into(),
                ),
            ]),
            // After an error we expect the watcher to request its last(latest) known
            // resource version to be queried again.
            Sequence::new(vec![SequenceStep::List(
                vec![
                    Ok(WatchEvent::Added(config_map("a", "5"))),
                    Ok(WatchEvent::Bookmark(Bookmark {
                        types: TypeMeta::resource::<ConfigMap>(),
                        metadata: BookmarkMeta {
                            resource_version: "5".to_string(),
                            annotations: BTreeMap::from_iter(vec![(
                                "k8s.io/initial-events-end".into(),
                                "true".into(),
                            )]),
                        },
                    })),
                ]
                .into(),
            )]),
        ]);

        let config = Config::default()
            .timeout(1)
            .streaming_lists()
            .labels("app=test")
            .fields("metadata.name!=ignored");
        // NOTE(juf): The stream which is returned here is not the same stream that an individual `watch` result produces.
        // That stream is wrapped and hidden behind the inner state [`kube_runtime::watcher::State`] of the watcher implementation.
        let mut stream = std::pin::pin!(watcher_inner(api.clone(), config));

        for expected in [
            "Init",
            "InitApply(a)",
            "InitApply(b)",
            "InitApply(c)",
            "InitDone",
            "Apply(a)",
            "error returned by apiserver during watch: some err: Something went wrong",
            "Apply(a)",
            "Apply(a)",
        ] {
            let event = stream.next().await.expect("watcher stream should not end");
            let repr = match event {
                Ok(event) => event.to_string(),
                Err(err) => err.to_string(),
            };
            assert_eq!(repr, expected);
        }

        let event = tokio::time::timeout(Duration::from_millis(100), stream.next())
            .await
            .expect("watcher should return when the TestMode sequence is exhausted")
            .expect("watcher stream should not end");
        // See function docs for more context, we expect this error, when we want to check whether
        // the whole watch sequence has been consumed and as breaker to avoid consuming an infinite
        // async stream that returns None.
        dbg!(&event);
        assert!(event.is_err_and(|err| error_indicates_graceful_watch_seq_exhaustion(&err)),);

        let records = api.get_recordings();
        match &records[..] {
            [
                Recording::Watch(initial_params, initial_version),
                Recording::Watch(resumed_params, resumed_version),
                Recording::Watch(exhausted_params, exhausted_version),
            ] => {
                assert_eq!(initial_version, "0");
                assert_eq!(initial_params.label_selector.as_deref(), Some("app=test"));
                assert_eq!(
                    initial_params.field_selector.as_deref(),
                    Some("metadata.name!=ignored")
                );
                assert!(initial_params.send_initial_events);

                for (watch_params, watch_version) in [
                    (resumed_params, resumed_version),
                    (exhausted_params, exhausted_version),
                ] {
                    assert_eq!(watch_version, LAST_VALID_RESOURCE_VERSION);
                    assert_eq!(watch_params.label_selector.as_deref(), Some("app=test"));
                    assert_eq!(
                        watch_params.field_selector.as_deref(),
                        Some("metadata.name!=ignored")
                    );
                    assert!(!watch_params.send_initial_events);
                }
            }
            _ => panic!("unexpected API call sequence {records:?}"),
        }
    }

    #[tokio::test]
    async fn streaming_list_init() {
        let api = TestMode::new(vec![], vec![Sequence::new(vec![
            SequenceStep::List(
                vec![
                    Ok(WatchEvent::Added(config_map("a", "2"))),
                    Ok(WatchEvent::Added(config_map("b", "3"))),
                    Ok(WatchEvent::Added(config_map("c", "4"))),
                    // Details here: https://kubernetes.io/docs/reference/using-api/api-concepts/#streaming-lists
                    // Should only be sent when requested via allowWatchBookmarks=true
                    // Since TestMode does not contain any real logic and  is not dynamically
                    // progammable, this is up to the test
                    // author to return or not for now.
                    Ok(WatchEvent::Bookmark(Bookmark {
                        types: TypeMeta::resource::<ConfigMap>(),
                        metadata: BookmarkMeta {
                            resource_version: "145".to_string(),
                            annotations: BTreeMap::from_iter(vec![(
                                "k8s.io/initial-events-end".into(),
                                "true".into(),
                            )]),
                        },
                    })),
                ]
                .into(),
            ),
            SequenceStep::List(
                vec![
                    Ok(WatchEvent::Modified(config_map("a", "5"))),
                    Ok(WatchEvent::Deleted(config_map("b", "7"))),
                    Ok(WatchEvent::Modified(config_map("c", "9"))),
                ]
                .into(),
            ),
        ])]);

        let config = Config::default()
            .timeout(1)
            .streaming_lists()
            .labels("app=test")
            .fields("metadata.name!=ignored");
        let mut state = State::default();
        for expected in [
            "Init",
            "InitApply(a)",
            "InitApply(b)",
            "InitApply(c)",
            "InitDone",
            "Apply(a)",
            "Delete(b)",
            "Apply(c)",
        ] {
            let (event, next) = step(&api, &config, state).await;
            state = next;
            assert_eq!(event.unwrap().to_string(), expected);
        }

        let (event, _) = tokio::time::timeout(Duration::from_millis(100), step(&api, &config, state))
            .await
            .expect("step should return when the TestMode sequence is exhausted");
        // See function docs for more context, we expect this error, when we want to check whether
        // the whole watch sequence has been consumed and as breaker to avoid consuming an infinite
        // async stream that returns None.
        assert!(event.is_err_and(|err| error_indicates_graceful_watch_seq_exhaustion(&err)));

        let records = api.get_recordings();
        match &records[..] {
            [
                Recording::Watch(initial_params, initial_version),
                Recording::Watch(resumed_params, resumed_version),
            ] => {
                assert_eq!(initial_version, "0");
                assert_eq!(initial_params.label_selector.as_deref(), Some("app=test"));
                assert_eq!(
                    initial_params.field_selector.as_deref(),
                    Some("metadata.name!=ignored")
                );
                assert!(initial_params.send_initial_events);

                assert_eq!(resumed_version, "9");
                assert_eq!(resumed_params.label_selector.as_deref(), Some("app=test"));
                assert_eq!(
                    resumed_params.field_selector.as_deref(),
                    Some("metadata.name!=ignored")
                );
                assert!(!resumed_params.send_initial_events);
            }
            _ => panic!("unexpected API call sequence {records:?}"),
        }
    }

    #[tokio::test]
    async fn streaming_list_initial_stream_eof_before_bookmark_drops_partial_objects() {
        let api = TestMode::new(vec![], vec![
            Sequence::new(vec![SequenceStep::List(
                vec![
                    Ok(WatchEvent::Added(config_map("a", "1"))),
                    Ok(WatchEvent::Added(config_map("b", "2"))),
                ]
                .into(),
            )]),
            Sequence::new(vec![SequenceStep::List(
                vec![
                    Ok(WatchEvent::Added(config_map("a", "1"))),
                    Ok(WatchEvent::Bookmark(Bookmark {
                        types: TypeMeta::resource::<ConfigMap>(),
                        metadata: BookmarkMeta {
                            resource_version: "1".to_string(),
                            annotations: BTreeMap::from_iter(vec![(
                                "k8s.io/initial-events-end".into(),
                                "true".into(),
                            )]),
                        },
                    })),
                ]
                .into(),
            )]),
        ]);

        let config = Config::default().streaming_lists();
        let (reader, mut writer) = crate::reflector::store::<ConfigMap>();
        let mut state = State::default();
        for expected in [
            "Init",
            "InitApply(a)",
            "InitApply(b)",
            "Init",
            "InitApply(a)",
            "InitDone",
        ] {
            let (event, next) = step(&api, &config, state).await;
            state = next;
            let event = event.unwrap();
            assert_eq!(event.to_string(), expected);
            writer.apply_watcher_event(&event);
        }

        let mut names: Vec<_> = reader
            .state()
            .iter()
            .filter_map(|cm| cm.metadata.name.clone())
            .collect();
        names.sort();
        assert_eq!(names, ["a".to_string()]);

        let records = api.get_recordings();
        match &records[..] {
            [
                Recording::Watch(first, first_version),
                Recording::Watch(second, second_version),
            ] => {
                assert_eq!(first_version, "0");
                assert!(first.send_initial_events);
                assert_eq!(second_version, "0");
                assert!(second.send_initial_events);
            }
            _ => panic!("unexpected API call sequence {records:?}"),
        }
    }

    #[tokio::test]
    async fn streaming_list_initial_watch_410_before_bookmark_drops_partial_objects() {
        let mut gone = Box::new(Status::default());
        gone.code = 410;
        gone.message = "expired".to_string();
        gone.reason = "Expired".to_string();
        let api = TestMode::new(vec![], vec![
            Sequence::new(vec![SequenceStep::List(
                vec![
                    Ok(WatchEvent::Added(config_map("a", "1"))),
                    Ok(WatchEvent::Added(config_map("b", "2"))),
                    Ok(WatchEvent::Error(gone)),
                ]
                .into(),
            )]),
            Sequence::new(vec![SequenceStep::List(
                vec![
                    Ok(WatchEvent::Added(config_map("a", "1"))),
                    Ok(WatchEvent::Bookmark(Bookmark {
                        types: TypeMeta::resource::<ConfigMap>(),
                        metadata: BookmarkMeta {
                            resource_version: "1".to_string(),
                            annotations: BTreeMap::from_iter(vec![(
                                "k8s.io/initial-events-end".into(),
                                "true".into(),
                            )]),
                        },
                    })),
                ]
                .into(),
            )]),
        ]);

        let config = Config::default().streaming_lists();
        let (reader, mut writer) = crate::reflector::store::<ConfigMap>();
        let mut state = State::default();
        for expected in [
            "Init",
            "InitApply(a)",
            "InitApply(b)",
            "error returned by apiserver during watch: expired: Expired",
            "Init",
            "InitApply(a)",
            "InitDone",
        ] {
            let (event, next) = step(&api, &config, state).await;
            state = next;
            let repr = match &event {
                Ok(event) => event.to_string(),
                Err(err) => err.to_string(),
            };
            assert_eq!(repr, expected);
            if let Ok(event) = &event {
                writer.apply_watcher_event(event);
            }
        }

        let mut names: Vec<_> = reader
            .state()
            .iter()
            .filter_map(|cm| cm.metadata.name.clone())
            .collect();
        names.sort();
        assert_eq!(names, ["a".to_string()]);

        let records = api.get_recordings();
        match &records[..] {
            [
                Recording::Watch(first, first_version),
                Recording::Watch(second, second_version),
            ] => {
                assert_eq!(first_version, "0");
                assert!(first.send_initial_events);
                assert_eq!(second_version, "0");
                assert!(second.send_initial_events);
            }
            _ => panic!("unexpected API call sequence {records:?}"),
        }
    }

    #[tokio::test]
    async fn listwatch_paginates_initial_list_before_starting_watch() {
        let api = TestMode::new(
            vec![
                Ok(ResultPage::empty()
                    .items(vec![config_map("a", "1")])
                    .continue_token("first".into())
                    .into()),
                Ok(ResultPage::empty()
                    .items(vec![config_map("b", "2")])
                    .resource_version("2".into())
                    .continue_token("second".into())
                    .into()),
                Ok(ResultPage::empty()
                    .items(vec![config_map("c", "3")])
                    .resource_version("3".into())
                    .into()),
            ],
            vec![Sequence::new(vec![SequenceStep::List(
                vec![Ok(WatchEvent::Added(config_map("d", "4")))].into(),
            )])],
        );

        let config = Config::default()
            .page_size(1)
            .labels("app=test")
            .fields("metadata.name!=ignored");
        let mut state = State::default();

        let (event, next) = step(&api, &config, state).await;
        state = next;
        assert_eq!(event.unwrap().to_string(), "Init");

        let (event, next) = step(&api, &config, state).await;
        state = next;
        assert_eq!(event.unwrap().to_string(), "InitApply(a)");

        let (event, next) = step(&api, &config, state).await;
        state = next;
        assert_eq!(event.unwrap().to_string(), "InitApply(b)");

        let (event, next) = step(&api, &config, state).await;
        state = next;
        assert_eq!(event.unwrap().to_string(), "InitApply(c)");

        let (event, next) = step(&api, &config, state).await;
        state = next;
        assert_eq!(event.unwrap().to_string(), "InitDone");

        let (event, _) = step(&api, &config, state).await;
        assert_eq!(event.unwrap().to_string(), "Apply(d)");

        let records = api.get_recordings();
        match &records[..] {
            [
                Recording::List(first),
                Recording::List(second),
                Recording::List(third),
                Recording::Watch(watch_params, watch_version),
            ] => {
                assert_eq!(first.continue_token.as_deref(), None);
                assert_eq!(second.continue_token.as_deref(), Some("first"));
                assert_eq!(third.continue_token.as_deref(), Some("second"));

                assert_eq!(first.limit, Some(1));
                assert_eq!(first.label_selector.as_deref(), Some("app=test"));
                assert_eq!(first.field_selector.as_deref(), Some("metadata.name!=ignored"));

                assert_eq!(watch_version, "3");
                assert_eq!(watch_params.label_selector.as_deref(), Some("app=test"));
                assert_eq!(
                    watch_params.field_selector.as_deref(),
                    Some("metadata.name!=ignored")
                );
                assert!(!watch_params.send_initial_events);
            }
            _ => panic!("unexpected API call sequence"),
        }
    }

    #[test]
    fn to_watch_params_initial_phase_with_streaming_list_sets_send_initial_events() {
        let config = Config::default().streaming_lists();
        let params = config.to_watch_params(WatchPhase::Initial);
        assert!(params.send_initial_events);
    }

    #[test]
    fn to_watch_params_resumed_phase_with_streaming_list_does_not_set_send_initial_events() {
        let config = Config::default().streaming_lists();
        let params = config.to_watch_params(WatchPhase::Resumed);
        assert!(!params.send_initial_events);
    }

    #[test]
    fn to_watch_params_listwatch_mode_does_not_set_send_initial_events() {
        let config = Config::default(); // ListWatch mode
        let params_initial = config.to_watch_params(WatchPhase::Initial);
        let params_resumed = config.to_watch_params(WatchPhase::Resumed);
        assert!(!params_initial.send_initial_events);
        assert!(!params_resumed.send_initial_events);
    }

    fn approx_eq(a: Duration, b: Duration) -> bool {
        a.abs_diff(b) < Duration::from_micros(100)
    }

    #[test]
    fn exponential_backoff_without_jitter() {
        let mut backoff =
            ExponentialBackoff::new(Duration::from_millis(100), Duration::from_secs(1), 2.0, false);

        assert!(approx_eq(backoff.next().unwrap(), Duration::from_millis(100)));
        assert!(approx_eq(backoff.next().unwrap(), Duration::from_millis(200)));
        assert!(approx_eq(backoff.next().unwrap(), Duration::from_millis(400)));
    }

    #[test]
    fn exponential_backoff_with_jitter_applies_randomness() {
        let mut backoff =
            ExponentialBackoff::new(Duration::from_millis(100), Duration::from_secs(1), 2.0, true);

        let delays: Vec<_> = (0..5).filter_map(|_| backoff.next()).collect();

        // All delays should be positive
        for d in &delays {
            assert!(*d > Duration::ZERO);
        }

        // With jitter, at least one delay should differ from exact values
        let exact_values = [
            Duration::from_millis(100),
            Duration::from_millis(200),
            Duration::from_millis(400),
            Duration::from_millis(800),
            Duration::from_secs(1),
        ];

        let all_exact = delays
            .iter()
            .zip(exact_values.iter())
            .all(|(d, e)| approx_eq(*d, *e));

        assert!(
            !all_exact,
            "With jitter enabled, delays should not all match exact exponential values"
        );
    }

    #[tokio::test(start_paused = true)]
    async fn idle_timeout_returns_item_when_stream_has_data() {
        let mut stream = futures::stream::iter(vec![1, 2, 3]);
        let result = next_with_idle_timeout(&mut stream, Some(290)).await;
        assert_eq!(result, Some(1));
    }

    #[tokio::test(start_paused = true)]
    async fn zero_timeout_does_not_trigger_idle_timeout() {
        let mut stream = futures::stream::once(async {
            tokio::time::sleep(Duration::from_secs(6)).await;
            42
        })
        .boxed();

        let result = next_with_idle_timeout(&mut stream, Some(0)).await;
        assert_eq!(result, Some(42));
    }

    #[tokio::test(start_paused = true)]
    async fn idle_timeout_returns_none_on_dead_connection() {
        let mut stream = futures::stream::pending::<i32>();
        // NB tokio auto-advances virtual time when the runtime is idle so next_with_idle_timeout resolves immediately
        let result = next_with_idle_timeout(&mut stream, Some(290)).await;
        assert_eq!(result, None);
    }

    #[tokio::test(start_paused = true)]
    async fn idle_timeout_returns_none_when_stream_ends() {
        let mut stream = futures::stream::empty::<i32>();
        let result = next_with_idle_timeout(&mut stream, Some(290)).await;
        assert_eq!(result, None);
    }

    /// Never answers, like an error response whose body stalls
    struct StalledWatchCall;

    impl ApiMode for StalledWatchCall {
        type Value = ConfigMap;

        async fn list(&self, _lp: &ListParams) -> kube_client::Result<ObjectList<ConfigMap>> {
            futures::future::pending().await
        }

        async fn watch(
            &self,
            _wp: &WatchParams,
            _version: &str,
        ) -> kube_client::Result<BoxStream<'static, kube_client::Result<WatchEvent<ConfigMap>>>> {
            futures::future::pending().await
        }
    }

    #[tokio::test(start_paused = true)]
    async fn idle_timeout_retries_stalled_watch_call() {
        // timeout(1) plus the 5s margin, so an unbounded watch call trips the outer 7s limit
        let config = Config::default().timeout(1);
        let limit = Duration::from_secs(7);
        let state = State::InitListed {
            resource_version: "1".into(),
        };
        let start = tokio::time::Instant::now();
        let (event, state) = tokio::time::timeout(limit, step_trampolined(&StalledWatchCall, &config, state))
            .await
            .expect("stalled resumed watch call should hit the idle timeout");
        assert_eq!(start.elapsed(), Duration::from_secs(6));
        assert!(event.is_none());
        assert!(matches!(state, State::InitListed { resource_version } if resource_version == "1"));

        let config = config.streaming_lists();
        let start = tokio::time::Instant::now();
        let (event, state) =
            tokio::time::timeout(limit, step_trampolined(&StalledWatchCall, &config, State::Empty))
                .await
                .expect("stalled initial watch call should hit the idle timeout");
        assert_eq!(start.elapsed(), Duration::from_secs(6));
        assert!(event.is_none());
        assert!(matches!(state, State::Empty));
    }

    /// Serves an empty LIST, then a watch rejected with HTTP 500 whose pretty-printed `Status`
    /// body is held back by `error_body_delay` (forever when `None`), then watches with one event.
    fn stalled_error_client(error_body_delay: Option<Duration>) -> Client {
        let mut watches = 0;
        let service = tower::service_fn(move |request: Request<Body>| {
            let (status, body) = if request.uri().query().unwrap_or_default().contains("watch=true") {
                watches += 1;
                if watches == 1 {
                    let rejection = serde_json::json!({
                        "kind": "Status",
                        "apiVersion": "v1",
                        "status": "Failure",
                        "message": "watch rejected",
                        "reason": "InternalError",
                        "code": 500,
                    });
                    (
                        StatusCode::INTERNAL_SERVER_ERROR,
                        serde_json::to_vec_pretty(&rejection).unwrap(),
                    )
                } else {
                    let event = WatchEvent::Added(config_map("a", "11"));
                    (StatusCode::OK, serde_json::to_vec(&event).unwrap())
                }
            } else {
                let list = serde_json::json!({
                    "kind": "ConfigMapList",
                    "apiVersion": "v1",
                    "metadata": { "resourceVersion": "10" },
                    "items": [],
                });
                (StatusCode::OK, serde_json::to_vec(&list).unwrap())
            };
            let stall = status.is_server_error();
            let length = body.len();
            let frames = Body::from(body).into_stream().then(move |frame| async move {
                if stall {
                    match error_body_delay {
                        Some(delay) => tokio::time::sleep(delay).await,
                        None => futures::future::pending().await,
                    }
                }
                frame
            });
            std::future::ready(Ok::<_, std::convert::Infallible>(
                Response::builder()
                    .status(status)
                    .header(CONTENT_LENGTH, length)
                    .body(StreamBody::new(frames))
                    .unwrap(),
            ))
        });
        Client::new(service, "default")
    }

    #[tokio::test(start_paused = true)]
    async fn watcher_recovers_from_stalled_error_body() {
        let api = Api::<ConfigMap>::default_namespaced(stalled_error_client(None));
        let start = tokio::time::Instant::now();
        // try_collect stops at the first Err, like the try_for_each pipelines in the docs
        let applied = watcher(api, Config::default().timeout(1))
            .applied_objects()
            .default_backoff()
            .take(1)
            .try_collect::<Vec<_>>();
        let applied = tokio::time::timeout(Duration::from_secs(7), applied)
            .await
            .expect("stalled error body should hit the 6s idle timeout")
            .expect("watcher should reconnect without surfacing an error");
        assert_eq!(applied[0].metadata.name.as_deref(), Some("a"));
        assert_eq!(start.elapsed(), Duration::from_secs(6));
    }

    #[tokio::test(start_paused = true)]
    async fn watcher_keeps_slow_error_body_as_api_error() {
        // completes inside the 6s idle timeout, and with the idle timeout disabled
        for (timeout, delay) in [(1, 1), (0, 7)] {
            let delay = Duration::from_secs(delay);
            let api = Api::<ConfigMap>::default_namespaced(stalled_error_client(Some(delay)));
            let start = tokio::time::Instant::now();
            let collected = watcher(api, Config::default().timeout(timeout))
                .applied_objects()
                .take(1)
                .try_collect::<Vec<_>>();
            let err = tokio::time::timeout(delay + Duration::from_secs(1), collected)
                .await
                .expect("error body should arrive after its delay")
                .unwrap_err();
            assert!(
                matches!(&err, Error::WatchStartFailed(kube_client::Error::Api(status))
                    if status.code == 500 && status.message == "watch rejected"),
                "got {err:?}"
            );
            assert_eq!(start.elapsed(), delay);
        }
    }
}