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
use crate::watcher::{Error, Event};
use core::{
pin::Pin,
task::{Context, Poll},
};
use futures::{ready, Stream, TryStream};
use pin_project::pin_project;
#[pin_project]
#[must_use = "streams do nothing unless polled"]
pub struct EventFlatten<St, K> {
#[pin]
stream: St,
emit_deleted: bool,
queue: std::vec::IntoIter<K>,
}
impl<St: TryStream<Ok = Event<K>>, K> EventFlatten<St, K> {
pub(super) fn new(stream: St, emit_deleted: bool) -> Self {
Self {
stream,
queue: vec![].into_iter(),
emit_deleted,
}
}
}
impl<St, K> Stream for EventFlatten<St, K>
where
St: Stream<Item = Result<Event<K>, Error>>,
{
type Item = Result<K, Error>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let mut me = self.project();
Poll::Ready(loop {
if let Some(item) = me.queue.next() {
break Some(Ok(item));
}
break match ready!(me.stream.as_mut().poll_next(cx)) {
Some(Ok(Event::Applied(obj))) => Some(Ok(obj)),
Some(Ok(Event::Deleted(obj))) => {
if *me.emit_deleted {
Some(Ok(obj))
} else {
continue;
}
}
Some(Ok(Event::Restarted(objs))) => {
*me.queue = objs.into_iter();
continue;
}
Some(Err(err)) => Some(Err(err)),
None => return Poll::Ready(None),
};
})
}
}
#[cfg(test)]
pub(crate) mod tests {
use std::task::Poll;
use super::{Error, Event, EventFlatten};
use futures::{pin_mut, poll, stream, StreamExt};
#[tokio::test]
async fn watches_applies_uses_correct_eventflattened_stream() {
let data = stream::iter([
Ok(Event::Applied(0)),
Ok(Event::Applied(1)),
Ok(Event::Deleted(0)),
Ok(Event::Applied(2)),
Ok(Event::Restarted(vec![1, 2])),
Err(Error::TooManyObjects),
Ok(Event::Applied(2)),
]);
let rx = EventFlatten::new(data, false);
pin_mut!(rx);
assert!(matches!(poll!(rx.next()), Poll::Ready(Some(Ok(0)))));
assert!(matches!(poll!(rx.next()), Poll::Ready(Some(Ok(1)))));
assert!(matches!(poll!(rx.next()), Poll::Ready(Some(Ok(2)))));
assert!(matches!(poll!(rx.next()), Poll::Ready(Some(Ok(1)))));
assert!(matches!(poll!(rx.next()), Poll::Ready(Some(Ok(2)))));
assert!(matches!(
poll!(rx.next()),
Poll::Ready(Some(Err(Error::TooManyObjects)))
));
assert!(matches!(poll!(rx.next()), Poll::Ready(Some(Ok(2)))));
assert!(matches!(poll!(rx.next()), Poll::Ready(None)));
}
}