kube_runtime/utils/
event_decode.rs1use crate::watcher::{Error, Event};
2use core::{
3 pin::Pin,
4 task::{ready, Context, Poll},
5};
6use futures::{Stream, TryStream};
7use pin_project::pin_project;
8
9#[pin_project]
10#[must_use = "streams do nothing unless polled"]
12pub struct EventDecode<St> {
13 #[pin]
14 stream: St,
15 emit_deleted: bool,
16}
17impl<St: TryStream<Ok = Event<K>>, K> EventDecode<St> {
18 pub(super) fn new(stream: St, emit_deleted: bool) -> Self {
19 Self { stream, emit_deleted }
20 }
21}
22impl<St, K> Stream for EventDecode<St>
23where
24 St: Stream<Item = Result<Event<K>, Error>>,
25{
26 type Item = Result<K, Error>;
27
28 fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
29 let mut me = self.project();
30 Poll::Ready(loop {
31 let var_name = match ready!(me.stream.as_mut().poll_next(cx)) {
32 Some(Ok(Event::Apply(obj) | Event::InitApply(obj))) => Some(Ok(obj)),
33 Some(Ok(Event::Delete(obj))) => {
34 if *me.emit_deleted {
35 Some(Ok(obj))
36 } else {
37 continue;
38 }
39 }
40 Some(Ok(Event::Init | Event::InitDone)) => continue,
41 Some(Err(err)) => Some(Err(err)),
42 None => return Poll::Ready(None),
43 };
44 break var_name;
45 })
46 }
47}
48
49#[cfg(test)]
50pub(crate) mod tests {
51 use std::{pin::pin, task::Poll};
52
53 use super::{Error, Event, EventDecode};
54 use futures::{poll, stream, StreamExt};
55
56 #[tokio::test]
57 async fn watches_applies_uses_correct_stream() {
58 let data = stream::iter([
59 Ok(Event::Apply(0)),
60 Ok(Event::Apply(1)),
61 Ok(Event::Delete(0)),
62 Ok(Event::Apply(2)),
63 Ok(Event::InitApply(1)),
64 Ok(Event::InitApply(2)),
65 Err(Error::NoResourceVersion),
66 Ok(Event::Apply(2)),
67 ]);
68 let mut rx = pin!(EventDecode::new(data, false));
69 assert!(matches!(poll!(rx.next()), Poll::Ready(Some(Ok(0)))));
70 assert!(matches!(poll!(rx.next()), Poll::Ready(Some(Ok(1)))));
71 assert!(matches!(poll!(rx.next()), Poll::Ready(Some(Ok(2)))));
73 assert!(matches!(poll!(rx.next()), Poll::Ready(Some(Ok(1)))));
77 assert!(matches!(poll!(rx.next()), Poll::Ready(Some(Ok(2)))));
78 assert!(matches!(
80 poll!(rx.next()),
81 Poll::Ready(Some(Err(Error::NoResourceVersion)))
82 ));
83 assert!(matches!(poll!(rx.next()), Poll::Ready(Some(Ok(2)))));
84 assert!(matches!(poll!(rx.next()), Poll::Ready(None)));
85 }
86}