1use crate::utils::{Backoff, ResetTimerBackoff};
6
7use backon::BackoffBuilder;
8use educe::Educe;
9use futures::{Stream, StreamExt, stream::BoxStream};
10use kube_client::{
11 Api, Error as ClientErr,
12 api::{ListParams, Resource, ResourceExt, VersionMatch, WatchEvent, WatchParams},
13 core::{ObjectList, Selector, metadata::PartialObjectMeta},
14 error::Status,
15};
16use serde::de::DeserializeOwned;
17#[cfg(test)]
18#[path = "stub_watcher.rs"]
19mod stub_watcher;
20
21use std::{
22 clone::Clone,
23 collections::VecDeque,
24 fmt::{Debug, Display},
25 future::{self, Future},
26 time::Duration,
27};
28use thiserror::Error;
29use tracing::{debug, error, warn};
30
31#[derive(Debug, Error)]
38pub enum Error {
39 #[error("failed to perform initial object list: {0}")]
41 InitialListFailed(#[source] kube_client::Error),
42
43 #[error("failed to start watching object: {0}")]
45 WatchStartFailed(#[source] kube_client::Error),
46
47 #[error("error returned by apiserver during watch: {0}")]
49 WatchError(#[source] Box<Status>),
50
51 #[error("watch stream failed: {0}")]
53 WatchFailed(#[source] kube_client::Error),
54
55 #[error("no metadata.resourceVersion in watch result (does resource support watch?)")]
57 NoResourceVersion,
58}
59
60pub type Result<T, E = Error> = std::result::Result<T, E>;
62
63#[derive(Debug, Clone)]
64pub enum Event<K> {
66 Apply(K),
68 Delete(K),
79 Init,
84 InitApply(K),
92 InitDone,
100}
101
102impl<K> Display for Event<K>
103where
104 K: ResourceExt,
105{
106 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
107 let desc = match self {
108 Event::Init => "Init".into(),
109 Event::InitApply(obj) => format!("InitApply({})", obj.name_any()),
110 Event::InitDone => "InitDone".into(),
111 Event::Apply(obj) => format!("Apply({})", obj.name_any()),
112 Event::Delete(obj) => format!("Delete({})", obj.name_any()),
113 };
114 write!(f, "{desc}")
115 }
116}
117
118impl<K> Event<K> {
119 #[must_use]
137 pub fn modify(mut self, mut f: impl FnMut(&mut K)) -> Self {
138 match &mut self {
139 Self::Apply(obj) | Self::Delete(obj) | Self::InitApply(obj) => (f)(obj),
140 Self::Init | Self::InitDone => {} }
142 self
143 }
144}
145
146#[derive(Educe, Default)]
147#[educe(Debug)]
148enum State<K> {
150 #[default]
152 Empty,
153 InitPage {
155 continue_token: Option<String>,
156 objects: VecDeque<K>,
157 last_bookmark: Option<String>,
158 },
159 InitialWatch {
162 #[educe(Debug(ignore))]
163 stream: BoxStream<'static, kube_client::Result<WatchEvent<K>>>,
164 },
165 InitListed { resource_version: String },
167 Watching {
174 resource_version: String,
175 #[educe(Debug(ignore))]
176 stream: BoxStream<'static, kube_client::Result<WatchEvent<K>>>,
177 },
178}
179
180trait ApiMode: Send + Sync {
183 type Value: Clone + Send + 'static;
184
185 fn list(
186 &self,
187 lp: &ListParams,
188 ) -> impl Future<Output = kube_client::Result<ObjectList<Self::Value>>> + Send;
189 fn watch(
190 &self,
191 wp: &WatchParams,
192 version: &str,
193 ) -> impl Future<
194 Output = kube_client::Result<BoxStream<'static, kube_client::Result<WatchEvent<Self::Value>>>>,
195 > + Send;
196}
197
198struct FullObject<K> {
201 api: Api<K>,
202}
203
204#[derive(Clone, Default, Debug, PartialEq)]
206pub enum ListSemantic {
207 #[default]
217 MostRecent,
218
219 Any,
228}
229
230#[derive(Clone, Default, Debug, PartialEq)]
233pub enum InitialListStrategy {
234 #[default]
239 ListWatch,
240 StreamingList,
245}
246
247#[derive(Clone, Debug, PartialEq)]
249pub struct Config {
250 pub label_selector: Option<String>,
254
255 pub field_selector: Option<String>,
259
260 pub timeout: Option<u32>,
267
268 pub list_semantic: ListSemantic,
274
275 pub initial_list_strategy: InitialListStrategy,
286
287 pub page_size: Option<u32>,
296
297 pub bookmarks: bool,
302}
303
304impl Default for Config {
305 fn default() -> Self {
306 Self {
307 bookmarks: true,
308 label_selector: None,
309 field_selector: None,
310 timeout: None,
311 list_semantic: ListSemantic::default(),
312 page_size: Some(500),
315 initial_list_strategy: InitialListStrategy::ListWatch,
316 }
317 }
318}
319
320impl Config {
330 #[must_use]
335 pub fn timeout(mut self, timeout_secs: u32) -> Self {
336 self.timeout = Some(timeout_secs);
337 self
338 }
339
340 #[must_use]
346 pub fn fields(mut self, field_selector: &str) -> Self {
347 self.field_selector = Some(field_selector.to_string());
348 self
349 }
350
351 #[must_use]
356 pub fn labels(mut self, label_selector: &str) -> Self {
357 self.label_selector = Some(label_selector.to_string());
358 self
359 }
360
361 #[must_use]
377 pub fn labels_from(mut self, selector: &Selector) -> Self {
378 self.label_selector = Some(selector.to_string());
379 self
380 }
381
382 #[must_use]
386 pub fn list_semantic(mut self, semantic: ListSemantic) -> Self {
387 self.list_semantic = semantic;
388 self
389 }
390
391 #[must_use]
395 pub fn any_semantic(self) -> Self {
396 self.list_semantic(ListSemantic::Any)
397 }
398
399 #[must_use]
404 pub fn disable_bookmarks(mut self) -> Self {
405 self.bookmarks = false;
406 self
407 }
408
409 #[must_use]
416 pub fn page_size(mut self, page_size: u32) -> Self {
417 self.page_size = Some(page_size);
418 self
419 }
420
421 #[must_use]
424 pub fn streaming_lists(mut self) -> Self {
425 self.initial_list_strategy = InitialListStrategy::StreamingList;
426 self
427 }
428
429 fn to_list_params(&self) -> ListParams {
431 let (resource_version, version_match) = match self.list_semantic {
432 ListSemantic::Any => (Some("0".into()), Some(VersionMatch::NotOlderThan)),
433 ListSemantic::MostRecent => (None, None),
434 };
435 ListParams {
436 label_selector: self.label_selector.clone(),
437 field_selector: self.field_selector.clone(),
438 version_match,
439 resource_version,
440 limit: self.page_size,
442 continue_token: None,
443 ..Default::default()
444 }
445 }
446
447 fn to_watch_params(&self, phase: WatchPhase) -> WatchParams {
449 WatchParams {
450 label_selector: self.label_selector.clone(),
451 field_selector: self.field_selector.clone(),
452 timeout: self.timeout,
453 bookmarks: self.bookmarks,
454 send_initial_events: phase == WatchPhase::Initial
455 && self.initial_list_strategy == InitialListStrategy::StreamingList,
456 }
457 }
458}
459
460#[derive(Clone, Copy, Debug, PartialEq, Eq)]
465enum WatchPhase {
466 Initial,
468 Resumed,
470}
471
472impl<K> ApiMode for FullObject<K>
473where
474 K: Clone + Debug + DeserializeOwned + Send + 'static,
475{
476 type Value = K;
477
478 async fn list(&self, lp: &ListParams) -> kube_client::Result<ObjectList<Self::Value>> {
479 self.api.list(lp).await
480 }
481
482 async fn watch(
483 &self,
484 wp: &WatchParams,
485 version: &str,
486 ) -> kube_client::Result<BoxStream<'static, kube_client::Result<WatchEvent<Self::Value>>>> {
487 self.api.watch(wp, version).await.map(StreamExt::boxed)
488 }
489}
490
491struct MetaOnly<K> {
494 api: Api<K>,
495}
496
497impl<K> ApiMode for MetaOnly<K>
498where
499 K: Clone + Debug + DeserializeOwned + Send + 'static,
500{
501 type Value = PartialObjectMeta<K>;
502
503 async fn list(&self, lp: &ListParams) -> kube_client::Result<ObjectList<Self::Value>> {
504 self.api.list_metadata(lp).await
505 }
506
507 async fn watch(
508 &self,
509 wp: &WatchParams,
510 version: &str,
511 ) -> kube_client::Result<BoxStream<'static, kube_client::Result<WatchEvent<Self::Value>>>> {
512 self.api.watch_metadata(wp, version).await.map(StreamExt::boxed)
513 }
514}
515
516const WATCH_IDLE_TIMEOUT_MARGIN: Duration = Duration::from_secs(5);
522
523async fn next_with_idle_timeout<S, T>(stream: &mut S, timeout: Option<u32>) -> Option<T>
530where
531 S: Stream<Item = T> + Unpin,
532{
533 with_idle_timeout(stream.next(), timeout).await.flatten()
534}
535
536async fn with_idle_timeout<F: Future>(fut: F, timeout: Option<u32>) -> Option<F::Output> {
541 if timeout == Some(0) {
542 return Some(fut.await);
543 }
544
545 let idle_timeout = Duration::from_secs(u64::from(timeout.unwrap_or(290))) + WATCH_IDLE_TIMEOUT_MARGIN;
546 match tokio::time::timeout(idle_timeout, fut).await {
547 Ok(output) => Some(output),
548 Err(_elapsed) => {
549 debug!(
550 timeout_secs = idle_timeout.as_secs(),
551 "watch idle timeout, reconnecting"
552 );
553 None
554 }
555 }
556}
557
558#[allow(clippy::too_many_lines)] async fn step_trampolined<A>(
564 api: &A,
565 wc: &Config,
566 state: State<A::Value>,
567) -> (Option<Result<Event<A::Value>>>, State<A::Value>)
568where
569 A: ApiMode,
570 A::Value: Resource + 'static,
571{
572 match state {
573 State::Empty => match wc.initial_list_strategy {
574 InitialListStrategy::ListWatch => (Some(Ok(Event::Init)), State::InitPage {
575 continue_token: None,
576 objects: VecDeque::default(),
577 last_bookmark: None,
578 }),
579 InitialListStrategy::StreamingList => {
580 match with_idle_timeout(
581 api.watch(&wc.to_watch_params(WatchPhase::Initial), "0"),
582 wc.timeout,
583 )
584 .await
585 {
586 Some(Ok(stream)) => (Some(Ok(Event::Init)), State::InitialWatch { stream }),
587 Some(Err(err)) => {
588 if std::matches!(err, ClientErr::Api(ref status) if status.is_forbidden()) {
589 warn!("watch initlist error with 403: {err:?}");
590 } else {
591 debug!("watch initlist error: {err:?}");
592 }
593 (Some(Err(Error::WatchStartFailed(err))), State::default())
594 }
595 None => (None, State::default()),
596 }
597 }
598 },
599 State::InitPage {
600 continue_token,
601 mut objects,
602 last_bookmark,
603 } => {
604 if let Some(next) = objects.pop_front() {
605 return (Some(Ok(Event::InitApply(next))), State::InitPage {
606 continue_token,
607 objects,
608 last_bookmark,
609 });
610 }
611 if continue_token.is_none()
613 && let Some(resource_version) = last_bookmark
614 {
615 return (Some(Ok(Event::InitDone)), State::InitListed { resource_version });
617 }
618 let mut lp = wc.to_list_params();
619 lp.continue_token = continue_token;
620 match api.list(&lp).await {
621 Ok(list) => {
622 let last_bookmark = list.metadata.resource_version.filter(|s| !s.is_empty());
623 let continue_token = list.metadata.continue_.filter(|s| !s.is_empty());
624 if last_bookmark.is_none() && continue_token.is_none() {
625 return (Some(Err(Error::NoResourceVersion)), State::Empty);
626 }
627 (None, State::InitPage {
630 continue_token,
631 objects: list.items.into_iter().collect(),
632 last_bookmark,
633 })
634 }
635 Err(err) => {
636 if std::matches!(err, ClientErr::Api(ref status) if status.is_forbidden()) {
637 warn!("watch list error with 403: {err:?}");
638 } else {
639 debug!("watch list error: {err:?}");
640 }
641 (Some(Err(Error::InitialListFailed(err))), State::Empty)
642 }
643 }
644 }
645 State::InitialWatch { mut stream } => {
646 match next_with_idle_timeout(&mut stream, wc.timeout).await {
647 Some(Ok(WatchEvent::Added(obj) | WatchEvent::Modified(obj))) => {
648 (Some(Ok(Event::InitApply(obj))), State::InitialWatch { stream })
649 }
650 Some(Ok(WatchEvent::Deleted(_obj))) => {
651 error!("got deleted event during initial watch. this is a bug");
654 (None, State::InitialWatch { stream })
655 }
656 Some(Ok(WatchEvent::Bookmark(bm))) => {
657 let marks_initial_end = bm.metadata.annotations.contains_key("k8s.io/initial-events-end");
658 if marks_initial_end {
659 (Some(Ok(Event::InitDone)), State::Watching {
660 resource_version: bm.metadata.resource_version,
661 stream,
662 })
663 } else {
664 (None, State::InitialWatch { stream })
665 }
666 }
667 Some(Ok(WatchEvent::Error(err))) => {
668 let new_state = if err.code == 410 {
670 State::default()
671 } else {
672 State::InitialWatch { stream }
673 };
674 if err.code == 403 {
675 warn!("watcher watchevent error 403: {err:?}");
676 } else {
677 debug!("error watchevent error: {err:?}");
678 }
679 (Some(Err(Error::WatchError(err.boxed()))), new_state)
680 }
681 Some(Err(err)) => {
682 if std::matches!(err, ClientErr::Api(ref status) if status.is_forbidden()) {
683 warn!("watcher error 403: {err:?}");
684 } else {
685 debug!("watcher error: {err:?}");
686 }
687 (Some(Err(Error::WatchFailed(err))), State::InitialWatch { stream })
688 }
689 None => (None, State::default()),
690 }
691 }
692 State::InitListed { resource_version } => {
693 match with_idle_timeout(
694 api.watch(&wc.to_watch_params(WatchPhase::Resumed), &resource_version),
695 wc.timeout,
696 )
697 .await
698 {
699 Some(Ok(stream)) => (None, State::Watching {
700 resource_version,
701 stream,
702 }),
703 Some(Err(err)) => {
704 if std::matches!(err, ClientErr::Api(ref status) if status.is_forbidden()) {
705 warn!("watch initlist error with 403: {err:?}");
706 } else {
707 debug!("watch initlist error: {err:?}");
708 }
709 (Some(Err(Error::WatchStartFailed(err))), State::InitListed {
710 resource_version,
711 })
712 }
713 None => (None, State::InitListed { resource_version }),
714 }
715 }
716 State::Watching {
717 resource_version,
718 mut stream,
719 } => match next_with_idle_timeout(&mut stream, wc.timeout).await {
720 Some(Ok(WatchEvent::Added(obj) | WatchEvent::Modified(obj))) => {
721 let resource_version = obj.resource_version().unwrap_or_default();
722 if resource_version.is_empty() {
723 (Some(Err(Error::NoResourceVersion)), State::default())
724 } else {
725 (Some(Ok(Event::Apply(obj))), State::Watching {
726 resource_version,
727 stream,
728 })
729 }
730 }
731 Some(Ok(WatchEvent::Deleted(obj))) => {
732 let resource_version = obj.resource_version().unwrap_or_default();
733 if resource_version.is_empty() {
734 (Some(Err(Error::NoResourceVersion)), State::default())
735 } else {
736 (Some(Ok(Event::Delete(obj))), State::Watching {
737 resource_version,
738 stream,
739 })
740 }
741 }
742 Some(Ok(WatchEvent::Bookmark(bm))) => (None, State::Watching {
743 resource_version: bm.metadata.resource_version,
744 stream,
745 }),
746 Some(Ok(WatchEvent::Error(err))) => {
747 let new_state = if err.code == 410 {
749 State::default()
750 } else {
751 State::Watching {
752 resource_version,
753 stream,
754 }
755 };
756 if err.code == 403 {
757 warn!("watcher watchevent error 403: {err:?}");
758 } else {
759 debug!("error watchevent error: {err:?}");
760 }
761 (Some(Err(Error::WatchError(err.boxed()))), new_state)
762 }
763 Some(Err(err)) => {
764 if std::matches!(err, ClientErr::Api(ref status) if status.is_forbidden()) {
765 warn!("watcher error 403: {err:?}");
766 } else {
767 debug!("watcher error: {err:?}");
768 }
769 (Some(Err(Error::WatchFailed(err))), State::Watching {
770 resource_version,
771 stream,
772 })
773 }
774 None => (None, State::InitListed { resource_version }),
775 },
776 }
777}
778
779async fn step<A>(
781 api: &A,
782 config: &Config,
783 mut state: State<A::Value>,
784) -> (Result<Event<A::Value>>, State<A::Value>)
785where
786 A: ApiMode,
787 A::Value: Resource + 'static,
788{
789 loop {
790 match step_trampolined(api, config, state).await {
791 (Some(result), new_state) => return (result, new_state),
792 (None, new_state) => state = new_state,
793 }
794 }
795}
796
797#[doc(alias = "informer")]
847pub fn watcher<K: Resource + Clone + DeserializeOwned + Debug + Send + 'static>(
848 api: Api<K>,
849 watcher_config: Config,
850) -> impl Stream<Item = Result<Event<K>>> + Send {
851 watcher_inner(FullObject { api }, watcher_config)
852}
853
854fn watcher_inner<A>(api: A, watcher_config: Config) -> impl Stream<Item = Result<Event<A::Value>>> + Send
857where
858 A: ApiMode,
859 A::Value: Resource,
860{
861 futures::stream::unfold(
862 (api, watcher_config, State::default()),
863 |(api, watcher_config, state)| async {
864 let (event, state) = step(&api, &watcher_config, state).await;
865 Some((event, (api, watcher_config, state)))
866 },
867 )
868}
869
870#[deprecated(
921 since = "3.1.0",
922 note = "Use `watcher(Api::<PartialObjectMeta<K>>::all(client), config)` instead. \
923 `Api<PartialObjectMeta<K>>` now automatically uses metadata-only requests."
924)]
925pub fn metadata_watcher<K: Resource + Clone + DeserializeOwned + Debug + Send + 'static>(
926 api: Api<K>,
927 watcher_config: Config,
928) -> impl Stream<Item = Result<Event<PartialObjectMeta<K>>>> + Send {
929 watcher_inner(MetaOnly { api }, watcher_config)
930}
931
932pub fn watch_object<K: Resource + Clone + DeserializeOwned + Debug + Send + 'static>(
944 api: Api<K>,
945 name: &str,
946) -> impl Stream<Item = Result<Option<K>>> + Send + use<K> {
947 let fields = format!("metadata.name={name}");
950 watcher(api, Config::default().fields(&fields))
951 .scan(false, |obj_seen, event| {
959 if matches!(event, Ok(Event::Init)) {
960 *obj_seen = false;
961 } else if matches!(event, Ok(Event::InitApply(_))) {
962 *obj_seen = true;
963 }
964 future::ready(Some((*obj_seen, event)))
965 })
966 .filter_map(|(obj_seen, event)| async move {
967 match event {
968 Ok(Event::Apply(obj) | Event::InitApply(obj)) => Some(Ok(Some(obj))),
970 Ok(Event::Delete(_)) => Some(Ok(None)),
972 Ok(Event::InitDone) if !obj_seen => Some(Ok(None)),
974 Ok(Event::Init | Event::InitDone) => None,
976 Err(err) => Some(Err(err)),
978 }
979 })
980}
981
982pub struct ExponentialBackoff {
984 inner: backon::ExponentialBackoff,
985 builder: backon::ExponentialBuilder,
986}
987
988impl ExponentialBackoff {
989 fn new(min_delay: Duration, max_delay: Duration, factor: f32, enable_jitter: bool) -> Self {
990 let builder = backon::ExponentialBuilder::default()
991 .with_min_delay(min_delay)
992 .with_max_delay(max_delay)
993 .with_factor(factor)
994 .without_max_times();
995
996 let builder = if enable_jitter {
997 builder.with_jitter()
998 } else {
999 builder
1000 };
1001
1002 Self {
1003 inner: builder.build(),
1004 builder,
1005 }
1006 }
1007}
1008
1009impl Backoff for ExponentialBackoff {
1010 fn reset(&mut self) {
1011 self.inner = self.builder.build();
1012 }
1013}
1014
1015impl Iterator for ExponentialBackoff {
1016 type Item = Duration;
1017
1018 fn next(&mut self) -> Option<Self::Item> {
1019 self.inner.next()
1020 }
1021}
1022
1023impl From<backon::ExponentialBuilder> for ExponentialBackoff {
1024 fn from(builder: backon::ExponentialBuilder) -> Self {
1025 Self {
1026 inner: builder.build(),
1027 builder,
1028 }
1029 }
1030}
1031
1032pub struct DefaultBackoff(Strategy);
1043type Strategy = ResetTimerBackoff<ExponentialBackoff>;
1044
1045impl Default for DefaultBackoff {
1046 fn default() -> Self {
1047 Self(ResetTimerBackoff::new(
1048 ExponentialBackoff::new(Duration::from_millis(800), Duration::from_secs(30), 2.0, true),
1049 Duration::from_secs(120),
1050 ))
1051 }
1052}
1053
1054impl Iterator for DefaultBackoff {
1055 type Item = Duration;
1056
1057 fn next(&mut self) -> Option<Self::Item> {
1058 self.0.next()
1059 }
1060}
1061
1062impl Backoff for DefaultBackoff {
1063 fn reset(&mut self) {
1064 self.0.reset();
1065 }
1066}
1067
1068#[cfg(test)]
1069mod tests {
1070 use std::{collections::BTreeMap, time::Duration};
1071
1072 use futures::{StreamExt, TryStreamExt, stream::BoxStream};
1073 use http::{Request, Response, StatusCode, header::CONTENT_LENGTH};
1074 use http_body_util::{BodyExt, StreamBody};
1075 use k8s_openapi::{api::core::v1::ConfigMap, apimachinery::pkg::apis::meta::v1::ObjectMeta};
1076 use kube_client::{
1077 Api, Client,
1078 api::{ListParams, TypeMeta, WatchEvent, WatchParams},
1079 client::Body,
1080 core::{
1081 ObjectList, Status,
1082 watch::{Bookmark, BookmarkMeta},
1083 },
1084 };
1085
1086 use crate::{
1087 WatchStreamExt,
1088 watcher::{
1089 ApiMode, Config, Error, ExponentialBackoff, State, WatchPhase, next_with_idle_timeout, step,
1090 step_trampolined,
1091 stub_watcher::{
1092 Recording, Sequence, SequenceStep, TestMode, error_indicates_graceful_watch_seq_exhaustion,
1093 },
1094 watcher, watcher_inner,
1095 },
1096 };
1097
1098 use super::stub_watcher::ResultPage;
1099
1100 fn config_map(name: &str, resource_version: &str) -> ConfigMap {
1101 ConfigMap {
1102 metadata: ObjectMeta {
1103 name: Some(name.to_string()),
1104 resource_version: Some(resource_version.to_string()),
1105 ..ObjectMeta::default()
1106 },
1107 ..ConfigMap::default()
1108 }
1109 }
1110
1111 #[tokio::test(start_paused = true)]
1112 async fn test_mode_watch_waits_before_returning_next_event() {
1113 let api = TestMode::new(vec![], vec![Sequence::new(vec![
1114 SequenceStep::Wait(Duration::from_millis(50)),
1115 SequenceStep::List(vec![Ok(WatchEvent::Added(config_map("a", "1")))].into()),
1116 ])]);
1117 let mut stream = api.watch(&WatchParams::default(), "0").await.unwrap();
1118
1119 assert!(futures::poll!(stream.next()).is_pending());
1120 tokio::time::advance(Duration::from_millis(49)).await;
1121 assert!(futures::poll!(stream.next()).is_pending());
1122 tokio::time::advance(Duration::from_millis(1)).await;
1123
1124 assert!(matches!(
1125 stream.next().await,
1126 Some(Ok(WatchEvent::Added(config_map))) if config_map.metadata.name.as_deref() == Some("a")
1127 ));
1128 }
1129
1130 #[allow(clippy::too_many_lines)]
1131 #[tokio::test]
1132 async fn streaming_list_resync() {
1133 const LAST_VALID_RESOURCE_VERSION: &str = "5";
1134 let mut recoverable_err = Box::new(Status::default());
1135 recoverable_err.code = 502;
1136 recoverable_err.message = "some err".to_string();
1137 recoverable_err.reason = "Something went wrong".to_string();
1138 let api = TestMode::new(vec![], vec![
1139 Sequence::new(vec![
1140 SequenceStep::List(
1141 vec![
1142 Ok(WatchEvent::Added(config_map("a", "2"))),
1143 Ok(WatchEvent::Added(config_map("b", "3"))),
1144 Ok(WatchEvent::Added(config_map("c", "4"))),
1145 Ok(WatchEvent::Bookmark(Bookmark {
1151 types: TypeMeta::resource::<ConfigMap>(),
1152 metadata: BookmarkMeta {
1153 resource_version: "4".to_string(),
1154 annotations: BTreeMap::from_iter(vec![(
1155 "k8s.io/initial-events-end".into(),
1156 "true".into(),
1157 )]),
1158 },
1159 })),
1160 ]
1161 .into(),
1162 ),
1163 SequenceStep::List(
1164 vec![
1165 Ok(WatchEvent::Modified(config_map("a", LAST_VALID_RESOURCE_VERSION))),
1166 Ok(WatchEvent::Error(recoverable_err)),
1167 ]
1168 .into(),
1169 ),
1170 SequenceStep::List(
1173 vec![Ok(WatchEvent::Modified(config_map(
1174 "a",
1175 LAST_VALID_RESOURCE_VERSION,
1176 )))]
1177 .into(),
1178 ),
1179 ]),
1180 Sequence::new(vec![SequenceStep::List(
1183 vec![
1184 Ok(WatchEvent::Added(config_map("a", "5"))),
1185 Ok(WatchEvent::Bookmark(Bookmark {
1186 types: TypeMeta::resource::<ConfigMap>(),
1187 metadata: BookmarkMeta {
1188 resource_version: "5".to_string(),
1189 annotations: BTreeMap::from_iter(vec![(
1190 "k8s.io/initial-events-end".into(),
1191 "true".into(),
1192 )]),
1193 },
1194 })),
1195 ]
1196 .into(),
1197 )]),
1198 ]);
1199
1200 let config = Config::default()
1201 .timeout(1)
1202 .streaming_lists()
1203 .labels("app=test")
1204 .fields("metadata.name!=ignored");
1205 let mut stream = std::pin::pin!(watcher_inner(api.clone(), config));
1208
1209 for expected in [
1210 "Init",
1211 "InitApply(a)",
1212 "InitApply(b)",
1213 "InitApply(c)",
1214 "InitDone",
1215 "Apply(a)",
1216 "error returned by apiserver during watch: some err: Something went wrong",
1217 "Apply(a)",
1218 "Apply(a)",
1219 ] {
1220 let event = stream.next().await.expect("watcher stream should not end");
1221 let repr = match event {
1222 Ok(event) => event.to_string(),
1223 Err(err) => err.to_string(),
1224 };
1225 assert_eq!(repr, expected);
1226 }
1227
1228 let event = tokio::time::timeout(Duration::from_millis(100), stream.next())
1229 .await
1230 .expect("watcher should return when the TestMode sequence is exhausted")
1231 .expect("watcher stream should not end");
1232 dbg!(&event);
1236 assert!(event.is_err_and(|err| error_indicates_graceful_watch_seq_exhaustion(&err)),);
1237
1238 let records = api.get_recordings();
1239 match &records[..] {
1240 [
1241 Recording::Watch(initial_params, initial_version),
1242 Recording::Watch(resumed_params, resumed_version),
1243 Recording::Watch(exhausted_params, exhausted_version),
1244 ] => {
1245 assert_eq!(initial_version, "0");
1246 assert_eq!(initial_params.label_selector.as_deref(), Some("app=test"));
1247 assert_eq!(
1248 initial_params.field_selector.as_deref(),
1249 Some("metadata.name!=ignored")
1250 );
1251 assert!(initial_params.send_initial_events);
1252
1253 for (watch_params, watch_version) in [
1254 (resumed_params, resumed_version),
1255 (exhausted_params, exhausted_version),
1256 ] {
1257 assert_eq!(watch_version, LAST_VALID_RESOURCE_VERSION);
1258 assert_eq!(watch_params.label_selector.as_deref(), Some("app=test"));
1259 assert_eq!(
1260 watch_params.field_selector.as_deref(),
1261 Some("metadata.name!=ignored")
1262 );
1263 assert!(!watch_params.send_initial_events);
1264 }
1265 }
1266 _ => panic!("unexpected API call sequence {records:?}"),
1267 }
1268 }
1269
1270 #[tokio::test]
1271 async fn streaming_list_init() {
1272 let api = TestMode::new(vec![], vec![Sequence::new(vec![
1273 SequenceStep::List(
1274 vec![
1275 Ok(WatchEvent::Added(config_map("a", "2"))),
1276 Ok(WatchEvent::Added(config_map("b", "3"))),
1277 Ok(WatchEvent::Added(config_map("c", "4"))),
1278 Ok(WatchEvent::Bookmark(Bookmark {
1284 types: TypeMeta::resource::<ConfigMap>(),
1285 metadata: BookmarkMeta {
1286 resource_version: "145".to_string(),
1287 annotations: BTreeMap::from_iter(vec![(
1288 "k8s.io/initial-events-end".into(),
1289 "true".into(),
1290 )]),
1291 },
1292 })),
1293 ]
1294 .into(),
1295 ),
1296 SequenceStep::List(
1297 vec![
1298 Ok(WatchEvent::Modified(config_map("a", "5"))),
1299 Ok(WatchEvent::Deleted(config_map("b", "7"))),
1300 Ok(WatchEvent::Modified(config_map("c", "9"))),
1301 ]
1302 .into(),
1303 ),
1304 ])]);
1305
1306 let config = Config::default()
1307 .timeout(1)
1308 .streaming_lists()
1309 .labels("app=test")
1310 .fields("metadata.name!=ignored");
1311 let mut state = State::default();
1312 for expected in [
1313 "Init",
1314 "InitApply(a)",
1315 "InitApply(b)",
1316 "InitApply(c)",
1317 "InitDone",
1318 "Apply(a)",
1319 "Delete(b)",
1320 "Apply(c)",
1321 ] {
1322 let (event, next) = step(&api, &config, state).await;
1323 state = next;
1324 assert_eq!(event.unwrap().to_string(), expected);
1325 }
1326
1327 let (event, _) = tokio::time::timeout(Duration::from_millis(100), step(&api, &config, state))
1328 .await
1329 .expect("step should return when the TestMode sequence is exhausted");
1330 assert!(event.is_err_and(|err| error_indicates_graceful_watch_seq_exhaustion(&err)));
1334
1335 let records = api.get_recordings();
1336 match &records[..] {
1337 [
1338 Recording::Watch(initial_params, initial_version),
1339 Recording::Watch(resumed_params, resumed_version),
1340 ] => {
1341 assert_eq!(initial_version, "0");
1342 assert_eq!(initial_params.label_selector.as_deref(), Some("app=test"));
1343 assert_eq!(
1344 initial_params.field_selector.as_deref(),
1345 Some("metadata.name!=ignored")
1346 );
1347 assert!(initial_params.send_initial_events);
1348
1349 assert_eq!(resumed_version, "9");
1350 assert_eq!(resumed_params.label_selector.as_deref(), Some("app=test"));
1351 assert_eq!(
1352 resumed_params.field_selector.as_deref(),
1353 Some("metadata.name!=ignored")
1354 );
1355 assert!(!resumed_params.send_initial_events);
1356 }
1357 _ => panic!("unexpected API call sequence {records:?}"),
1358 }
1359 }
1360
1361 #[tokio::test]
1362 async fn streaming_list_initial_stream_eof_before_bookmark_drops_partial_objects() {
1363 let api = TestMode::new(vec![], vec![
1364 Sequence::new(vec![SequenceStep::List(
1365 vec![
1366 Ok(WatchEvent::Added(config_map("a", "1"))),
1367 Ok(WatchEvent::Added(config_map("b", "2"))),
1368 ]
1369 .into(),
1370 )]),
1371 Sequence::new(vec![SequenceStep::List(
1372 vec![
1373 Ok(WatchEvent::Added(config_map("a", "1"))),
1374 Ok(WatchEvent::Bookmark(Bookmark {
1375 types: TypeMeta::resource::<ConfigMap>(),
1376 metadata: BookmarkMeta {
1377 resource_version: "1".to_string(),
1378 annotations: BTreeMap::from_iter(vec![(
1379 "k8s.io/initial-events-end".into(),
1380 "true".into(),
1381 )]),
1382 },
1383 })),
1384 ]
1385 .into(),
1386 )]),
1387 ]);
1388
1389 let config = Config::default().streaming_lists();
1390 let (reader, mut writer) = crate::reflector::store::<ConfigMap>();
1391 let mut state = State::default();
1392 for expected in [
1393 "Init",
1394 "InitApply(a)",
1395 "InitApply(b)",
1396 "Init",
1397 "InitApply(a)",
1398 "InitDone",
1399 ] {
1400 let (event, next) = step(&api, &config, state).await;
1401 state = next;
1402 let event = event.unwrap();
1403 assert_eq!(event.to_string(), expected);
1404 writer.apply_watcher_event(&event);
1405 }
1406
1407 let mut names: Vec<_> = reader
1408 .state()
1409 .iter()
1410 .filter_map(|cm| cm.metadata.name.clone())
1411 .collect();
1412 names.sort();
1413 assert_eq!(names, ["a".to_string()]);
1414
1415 let records = api.get_recordings();
1416 match &records[..] {
1417 [
1418 Recording::Watch(first, first_version),
1419 Recording::Watch(second, second_version),
1420 ] => {
1421 assert_eq!(first_version, "0");
1422 assert!(first.send_initial_events);
1423 assert_eq!(second_version, "0");
1424 assert!(second.send_initial_events);
1425 }
1426 _ => panic!("unexpected API call sequence {records:?}"),
1427 }
1428 }
1429
1430 #[tokio::test]
1431 async fn streaming_list_initial_watch_410_before_bookmark_drops_partial_objects() {
1432 let mut gone = Box::new(Status::default());
1433 gone.code = 410;
1434 gone.message = "expired".to_string();
1435 gone.reason = "Expired".to_string();
1436 let api = TestMode::new(vec![], vec![
1437 Sequence::new(vec![SequenceStep::List(
1438 vec![
1439 Ok(WatchEvent::Added(config_map("a", "1"))),
1440 Ok(WatchEvent::Added(config_map("b", "2"))),
1441 Ok(WatchEvent::Error(gone)),
1442 ]
1443 .into(),
1444 )]),
1445 Sequence::new(vec![SequenceStep::List(
1446 vec![
1447 Ok(WatchEvent::Added(config_map("a", "1"))),
1448 Ok(WatchEvent::Bookmark(Bookmark {
1449 types: TypeMeta::resource::<ConfigMap>(),
1450 metadata: BookmarkMeta {
1451 resource_version: "1".to_string(),
1452 annotations: BTreeMap::from_iter(vec![(
1453 "k8s.io/initial-events-end".into(),
1454 "true".into(),
1455 )]),
1456 },
1457 })),
1458 ]
1459 .into(),
1460 )]),
1461 ]);
1462
1463 let config = Config::default().streaming_lists();
1464 let (reader, mut writer) = crate::reflector::store::<ConfigMap>();
1465 let mut state = State::default();
1466 for expected in [
1467 "Init",
1468 "InitApply(a)",
1469 "InitApply(b)",
1470 "error returned by apiserver during watch: expired: Expired",
1471 "Init",
1472 "InitApply(a)",
1473 "InitDone",
1474 ] {
1475 let (event, next) = step(&api, &config, state).await;
1476 state = next;
1477 let repr = match &event {
1478 Ok(event) => event.to_string(),
1479 Err(err) => err.to_string(),
1480 };
1481 assert_eq!(repr, expected);
1482 if let Ok(event) = &event {
1483 writer.apply_watcher_event(event);
1484 }
1485 }
1486
1487 let mut names: Vec<_> = reader
1488 .state()
1489 .iter()
1490 .filter_map(|cm| cm.metadata.name.clone())
1491 .collect();
1492 names.sort();
1493 assert_eq!(names, ["a".to_string()]);
1494
1495 let records = api.get_recordings();
1496 match &records[..] {
1497 [
1498 Recording::Watch(first, first_version),
1499 Recording::Watch(second, second_version),
1500 ] => {
1501 assert_eq!(first_version, "0");
1502 assert!(first.send_initial_events);
1503 assert_eq!(second_version, "0");
1504 assert!(second.send_initial_events);
1505 }
1506 _ => panic!("unexpected API call sequence {records:?}"),
1507 }
1508 }
1509
1510 #[tokio::test]
1511 async fn listwatch_paginates_initial_list_before_starting_watch() {
1512 let api = TestMode::new(
1513 vec![
1514 Ok(ResultPage::empty()
1515 .items(vec![config_map("a", "1")])
1516 .continue_token("first".into())
1517 .into()),
1518 Ok(ResultPage::empty()
1519 .items(vec![config_map("b", "2")])
1520 .resource_version("2".into())
1521 .continue_token("second".into())
1522 .into()),
1523 Ok(ResultPage::empty()
1524 .items(vec![config_map("c", "3")])
1525 .resource_version("3".into())
1526 .into()),
1527 ],
1528 vec![Sequence::new(vec![SequenceStep::List(
1529 vec![Ok(WatchEvent::Added(config_map("d", "4")))].into(),
1530 )])],
1531 );
1532
1533 let config = Config::default()
1534 .page_size(1)
1535 .labels("app=test")
1536 .fields("metadata.name!=ignored");
1537 let mut state = State::default();
1538
1539 let (event, next) = step(&api, &config, state).await;
1540 state = next;
1541 assert_eq!(event.unwrap().to_string(), "Init");
1542
1543 let (event, next) = step(&api, &config, state).await;
1544 state = next;
1545 assert_eq!(event.unwrap().to_string(), "InitApply(a)");
1546
1547 let (event, next) = step(&api, &config, state).await;
1548 state = next;
1549 assert_eq!(event.unwrap().to_string(), "InitApply(b)");
1550
1551 let (event, next) = step(&api, &config, state).await;
1552 state = next;
1553 assert_eq!(event.unwrap().to_string(), "InitApply(c)");
1554
1555 let (event, next) = step(&api, &config, state).await;
1556 state = next;
1557 assert_eq!(event.unwrap().to_string(), "InitDone");
1558
1559 let (event, _) = step(&api, &config, state).await;
1560 assert_eq!(event.unwrap().to_string(), "Apply(d)");
1561
1562 let records = api.get_recordings();
1563 match &records[..] {
1564 [
1565 Recording::List(first),
1566 Recording::List(second),
1567 Recording::List(third),
1568 Recording::Watch(watch_params, watch_version),
1569 ] => {
1570 assert_eq!(first.continue_token.as_deref(), None);
1571 assert_eq!(second.continue_token.as_deref(), Some("first"));
1572 assert_eq!(third.continue_token.as_deref(), Some("second"));
1573
1574 assert_eq!(first.limit, Some(1));
1575 assert_eq!(first.label_selector.as_deref(), Some("app=test"));
1576 assert_eq!(first.field_selector.as_deref(), Some("metadata.name!=ignored"));
1577
1578 assert_eq!(watch_version, "3");
1579 assert_eq!(watch_params.label_selector.as_deref(), Some("app=test"));
1580 assert_eq!(
1581 watch_params.field_selector.as_deref(),
1582 Some("metadata.name!=ignored")
1583 );
1584 assert!(!watch_params.send_initial_events);
1585 }
1586 _ => panic!("unexpected API call sequence"),
1587 }
1588 }
1589
1590 #[test]
1591 fn to_watch_params_initial_phase_with_streaming_list_sets_send_initial_events() {
1592 let config = Config::default().streaming_lists();
1593 let params = config.to_watch_params(WatchPhase::Initial);
1594 assert!(params.send_initial_events);
1595 }
1596
1597 #[test]
1598 fn to_watch_params_resumed_phase_with_streaming_list_does_not_set_send_initial_events() {
1599 let config = Config::default().streaming_lists();
1600 let params = config.to_watch_params(WatchPhase::Resumed);
1601 assert!(!params.send_initial_events);
1602 }
1603
1604 #[test]
1605 fn to_watch_params_listwatch_mode_does_not_set_send_initial_events() {
1606 let config = Config::default(); let params_initial = config.to_watch_params(WatchPhase::Initial);
1608 let params_resumed = config.to_watch_params(WatchPhase::Resumed);
1609 assert!(!params_initial.send_initial_events);
1610 assert!(!params_resumed.send_initial_events);
1611 }
1612
1613 fn approx_eq(a: Duration, b: Duration) -> bool {
1614 a.abs_diff(b) < Duration::from_micros(100)
1615 }
1616
1617 #[test]
1618 fn exponential_backoff_without_jitter() {
1619 let mut backoff =
1620 ExponentialBackoff::new(Duration::from_millis(100), Duration::from_secs(1), 2.0, false);
1621
1622 assert!(approx_eq(backoff.next().unwrap(), Duration::from_millis(100)));
1623 assert!(approx_eq(backoff.next().unwrap(), Duration::from_millis(200)));
1624 assert!(approx_eq(backoff.next().unwrap(), Duration::from_millis(400)));
1625 }
1626
1627 #[test]
1628 fn exponential_backoff_with_jitter_applies_randomness() {
1629 let mut backoff =
1630 ExponentialBackoff::new(Duration::from_millis(100), Duration::from_secs(1), 2.0, true);
1631
1632 let delays: Vec<_> = (0..5).filter_map(|_| backoff.next()).collect();
1633
1634 for d in &delays {
1636 assert!(*d > Duration::ZERO);
1637 }
1638
1639 let exact_values = [
1641 Duration::from_millis(100),
1642 Duration::from_millis(200),
1643 Duration::from_millis(400),
1644 Duration::from_millis(800),
1645 Duration::from_secs(1),
1646 ];
1647
1648 let all_exact = delays
1649 .iter()
1650 .zip(exact_values.iter())
1651 .all(|(d, e)| approx_eq(*d, *e));
1652
1653 assert!(
1654 !all_exact,
1655 "With jitter enabled, delays should not all match exact exponential values"
1656 );
1657 }
1658
1659 #[tokio::test(start_paused = true)]
1660 async fn idle_timeout_returns_item_when_stream_has_data() {
1661 let mut stream = futures::stream::iter(vec![1, 2, 3]);
1662 let result = next_with_idle_timeout(&mut stream, Some(290)).await;
1663 assert_eq!(result, Some(1));
1664 }
1665
1666 #[tokio::test(start_paused = true)]
1667 async fn zero_timeout_does_not_trigger_idle_timeout() {
1668 let mut stream = futures::stream::once(async {
1669 tokio::time::sleep(Duration::from_secs(6)).await;
1670 42
1671 })
1672 .boxed();
1673
1674 let result = next_with_idle_timeout(&mut stream, Some(0)).await;
1675 assert_eq!(result, Some(42));
1676 }
1677
1678 #[tokio::test(start_paused = true)]
1679 async fn idle_timeout_returns_none_on_dead_connection() {
1680 let mut stream = futures::stream::pending::<i32>();
1681 let result = next_with_idle_timeout(&mut stream, Some(290)).await;
1683 assert_eq!(result, None);
1684 }
1685
1686 #[tokio::test(start_paused = true)]
1687 async fn idle_timeout_returns_none_when_stream_ends() {
1688 let mut stream = futures::stream::empty::<i32>();
1689 let result = next_with_idle_timeout(&mut stream, Some(290)).await;
1690 assert_eq!(result, None);
1691 }
1692
1693 struct StalledWatchCall;
1695
1696 impl ApiMode for StalledWatchCall {
1697 type Value = ConfigMap;
1698
1699 async fn list(&self, _lp: &ListParams) -> kube_client::Result<ObjectList<ConfigMap>> {
1700 futures::future::pending().await
1701 }
1702
1703 async fn watch(
1704 &self,
1705 _wp: &WatchParams,
1706 _version: &str,
1707 ) -> kube_client::Result<BoxStream<'static, kube_client::Result<WatchEvent<ConfigMap>>>> {
1708 futures::future::pending().await
1709 }
1710 }
1711
1712 #[tokio::test(start_paused = true)]
1713 async fn idle_timeout_retries_stalled_watch_call() {
1714 let config = Config::default().timeout(1);
1716 let limit = Duration::from_secs(7);
1717 let state = State::InitListed {
1718 resource_version: "1".into(),
1719 };
1720 let start = tokio::time::Instant::now();
1721 let (event, state) = tokio::time::timeout(limit, step_trampolined(&StalledWatchCall, &config, state))
1722 .await
1723 .expect("stalled resumed watch call should hit the idle timeout");
1724 assert_eq!(start.elapsed(), Duration::from_secs(6));
1725 assert!(event.is_none());
1726 assert!(matches!(state, State::InitListed { resource_version } if resource_version == "1"));
1727
1728 let config = config.streaming_lists();
1729 let start = tokio::time::Instant::now();
1730 let (event, state) =
1731 tokio::time::timeout(limit, step_trampolined(&StalledWatchCall, &config, State::Empty))
1732 .await
1733 .expect("stalled initial watch call should hit the idle timeout");
1734 assert_eq!(start.elapsed(), Duration::from_secs(6));
1735 assert!(event.is_none());
1736 assert!(matches!(state, State::Empty));
1737 }
1738
1739 fn stalled_error_client(error_body_delay: Option<Duration>) -> Client {
1742 let mut watches = 0;
1743 let service = tower::service_fn(move |request: Request<Body>| {
1744 let (status, body) = if request.uri().query().unwrap_or_default().contains("watch=true") {
1745 watches += 1;
1746 if watches == 1 {
1747 let rejection = serde_json::json!({
1748 "kind": "Status",
1749 "apiVersion": "v1",
1750 "status": "Failure",
1751 "message": "watch rejected",
1752 "reason": "InternalError",
1753 "code": 500,
1754 });
1755 (
1756 StatusCode::INTERNAL_SERVER_ERROR,
1757 serde_json::to_vec_pretty(&rejection).unwrap(),
1758 )
1759 } else {
1760 let event = WatchEvent::Added(config_map("a", "11"));
1761 (StatusCode::OK, serde_json::to_vec(&event).unwrap())
1762 }
1763 } else {
1764 let list = serde_json::json!({
1765 "kind": "ConfigMapList",
1766 "apiVersion": "v1",
1767 "metadata": { "resourceVersion": "10" },
1768 "items": [],
1769 });
1770 (StatusCode::OK, serde_json::to_vec(&list).unwrap())
1771 };
1772 let stall = status.is_server_error();
1773 let length = body.len();
1774 let frames = Body::from(body).into_stream().then(move |frame| async move {
1775 if stall {
1776 match error_body_delay {
1777 Some(delay) => tokio::time::sleep(delay).await,
1778 None => futures::future::pending().await,
1779 }
1780 }
1781 frame
1782 });
1783 std::future::ready(Ok::<_, std::convert::Infallible>(
1784 Response::builder()
1785 .status(status)
1786 .header(CONTENT_LENGTH, length)
1787 .body(StreamBody::new(frames))
1788 .unwrap(),
1789 ))
1790 });
1791 Client::new(service, "default")
1792 }
1793
1794 #[tokio::test(start_paused = true)]
1795 async fn watcher_recovers_from_stalled_error_body() {
1796 let api = Api::<ConfigMap>::default_namespaced(stalled_error_client(None));
1797 let start = tokio::time::Instant::now();
1798 let applied = watcher(api, Config::default().timeout(1))
1800 .applied_objects()
1801 .default_backoff()
1802 .take(1)
1803 .try_collect::<Vec<_>>();
1804 let applied = tokio::time::timeout(Duration::from_secs(7), applied)
1805 .await
1806 .expect("stalled error body should hit the 6s idle timeout")
1807 .expect("watcher should reconnect without surfacing an error");
1808 assert_eq!(applied[0].metadata.name.as_deref(), Some("a"));
1809 assert_eq!(start.elapsed(), Duration::from_secs(6));
1810 }
1811
1812 #[tokio::test(start_paused = true)]
1813 async fn watcher_keeps_slow_error_body_as_api_error() {
1814 for (timeout, delay) in [(1, 1), (0, 7)] {
1816 let delay = Duration::from_secs(delay);
1817 let api = Api::<ConfigMap>::default_namespaced(stalled_error_client(Some(delay)));
1818 let start = tokio::time::Instant::now();
1819 let collected = watcher(api, Config::default().timeout(timeout))
1820 .applied_objects()
1821 .take(1)
1822 .try_collect::<Vec<_>>();
1823 let err = tokio::time::timeout(delay + Duration::from_secs(1), collected)
1824 .await
1825 .expect("error body should arrive after its delay")
1826 .unwrap_err();
1827 assert!(
1828 matches!(&err, Error::WatchStartFailed(kube_client::Error::Api(status))
1829 if status.code == 500 && status.message == "watch rejected"),
1830 "got {err:?}"
1831 );
1832 assert_eq!(start.elapsed(), delay);
1833 }
1834 }
1835}