throttle_stream/
lib.rs

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
use std::time::Duration;
use std::sync::Arc;
use futures::Stream;
use futures::stream::StreamExt;
use tokio::sync::{Mutex, mpsc};
use tokio::task::JoinHandle;
use tokio::time::sleep;

pub struct ThrottleStream<T> {
    duration: Duration,
    buffer: Arc<Mutex<Vec<T>>>,
    task: Arc<Mutex<Option<JoinHandle<()>>>>,
    sender: mpsc::Sender<Vec<T>>,
}

impl<T: Send + 'static> ThrottleStream<T> {
    pub fn clone(&self) -> Self {
        Self {
            duration: self.duration,
            buffer: self.buffer.clone(),
            task: self.task.clone(),
            sender: self.sender.clone(),
        }
    }

    pub fn new(duration: Duration) -> (Self, mpsc::Receiver<Vec<T>>) {
        let (sender, receiver) = mpsc::channel(1);
        let buffer = Arc::new(Mutex::new(Vec::new()));
        let task = Arc::new(Mutex::new(None));
        (
            Self {
                duration,
                buffer,
                task,
                sender,
            },
            receiver,
        )
    }

    async fn send_data(&self, data: Vec<T>, task_guard: &mut Option<JoinHandle<()>>) {
        if let Err(e) = self.sender.send(data).await {
            eprintln!("Failed to send data: {}", e);
            return;
        }
        *task_guard = Some(self.schedule_task());
    }

    fn schedule_task(&self) -> JoinHandle<()> {
        let this = self.clone();
        tokio::spawn(async move {
            sleep(this.duration).await;

            let mut buffer_guard = this.buffer.lock().await;
            let mut task_guard = this.task.lock().await;
            if buffer_guard.is_empty() {
                *task_guard = None;
                return;
            }

            let data = buffer_guard.drain(..).collect::<Vec<_>>();
            this.send_data(data, &mut task_guard).await;
        })
    }

    pub async fn push(&self, item: T) {
        let mut task_guard = self.task.lock().await;
        if task_guard.is_some() {
            let mut buffer_guard = self.buffer.lock().await;
            buffer_guard.push(item);
        } else {
            self.send_data(vec![item], &mut task_guard).await;
        }
    }

    pub async fn drain(&self) {
        let mut buffer_guard = self.buffer.lock().await;
        let mut task_guard = self.task.lock().await;
        if buffer_guard.is_empty() {
            return;
        }

        let data = buffer_guard.drain(..).collect::<Vec<_>>();
        self.send_data(data, &mut task_guard).await;
    }
}

/// 将输入流转换为节流后的输出流
pub fn throttle_stream<S, T>(
    input_stream: S,
    duration: Duration,
) -> impl Stream<Item = Vec<T>>
where
    S: Stream<Item = T> + Send + 'static,
    T: Send + 'static,
{
    let (throttle, mut receiver) = ThrottleStream::new(duration);
    tokio::spawn(async move {
        let mut input_stream = Box::pin(input_stream);
        while let Some(item) = input_stream.next().await {
            throttle.push(item).await;
        }
    });
    async_stream::stream! {
        while let Some(data) = receiver.recv().await {
            yield data;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_throttle_stream() {
        let (throttle, mut receiver) = ThrottleStream::new(Duration::from_millis(100));

        throttle.push(1).await;
        // time: 0ms
        assert_eq!(receiver.try_recv(), Ok(vec![1]));

        throttle.push(2).await;
        throttle.push(3).await;
        // time: 0ms
        assert!(receiver.try_recv().is_err());

        sleep(Duration::from_millis(120)).await;
        // time: 120ms
        assert_eq!(receiver.try_recv(), Ok(vec![2, 3]));

        throttle.push(4).await;
        throttle.push(5).await;
        // time: 120ms
        assert!(receiver.try_recv().is_err());

        sleep(Duration::from_millis(120)).await;
        // time: 240ms
        assert_eq!(receiver.recv().await, Some(vec![4, 5]));
    }

    #[tokio::test]
    async fn test_throttle_stream_flush() {
        let (throttle, mut receiver) = ThrottleStream::new(Duration::from_millis(100));

        throttle.push(1).await;
        // time: 0ms
        assert_eq!(receiver.try_recv(), Ok(vec![1]));

        throttle.push(2).await;
        throttle.push(3).await;
        // time: 0ms
        assert!(receiver.try_recv().is_err());

        throttle.drain().await;
        // time: 0ms
        assert_eq!(receiver.try_recv(), Ok(vec![2, 3]));

        throttle.drain().await;
        // time: 0ms
        assert!(receiver.try_recv().is_err());

        throttle.push(4).await;
        throttle.push(5).await;
        // time: 0ms
        assert!(receiver.try_recv().is_err());

        throttle.drain().await;
        // time: 0ms
        assert_eq!(receiver.try_recv(), Ok(vec![4, 5]));
    }
}