rs_store/
channel.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
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
use crate::metrics::Metrics;
use crate::ActionOp;
use crossbeam::channel::{self, Receiver, Sender, TrySendError};
use std::marker::PhantomData;
use std::sync::Arc;

/// the Backpressure policy
#[derive(Clone, Default)]
pub enum BackpressurePolicy {
    /// Block the sender when the queue is full
    #[default]
    BlockOnFull,
    /// Drop the oldest item when the queue is full
    DropOldest,
    /// Drop the latest item when the queue is full
    DropLatest,
}

#[derive(thiserror::Error, Debug)]
pub(crate) enum SenderError<T> {
    #[error("Failed to send: {0}")]
    SendError(T),
    #[error("Failed to try_send: {0}")]
    TrySendError(TrySendError<T>),
}

/// Channel to hold the sender with backpressure policy
#[derive(Clone)]
pub(crate) struct SenderChannel<Action>
where
    Action: Send + Sync + Clone + 'static,
{
    _name: String,
    sender: Sender<ActionOp<Action>>,
    receiver: Receiver<ActionOp<Action>>,
    policy: BackpressurePolicy,
    metrics: Option<Arc<dyn Metrics + Send + Sync>>,
}

#[cfg(any(dev))]
impl<Action> Drop for SenderChannel<Action>
where
    Action: Send + Sync + Clone + 'static,
{
    fn drop(&mut self) {
        eprintln!("store: drop '{}' sender channel", self._name);
    }
}

impl<Action> SenderChannel<Action>
where
    Action: Send + Sync + Clone + 'static,
{
    pub fn send(&self, item: ActionOp<Action>) -> Result<i64, SenderError<ActionOp<Action>>> {
        let r = match self.policy {
            BackpressurePolicy::BlockOnFull => {
                match self.sender.send(item).map_err(|e| SenderError::SendError(e.0)) {
                    Ok(_) => Ok(self.receiver.len() as i64),
                    Err(e) => Err(e),
                }
            }
            BackpressurePolicy::DropOldest => {
                if let Err(TrySendError::Full(item)) = self.sender.try_send(item) {
                    // Drop the oldest item and try sending again
                    #[cfg(dev)]
                    eprintln!("store: dropping the oldest item in channel");
                    // Remove the oldest item
                    let _old = self.receiver.try_recv();
                    if let Some(metrics) = &self.metrics {
                        if let Ok(ActionOp::Action(action)) = _old.as_ref() {
                            metrics.action_dropped(Some(action));
                        }
                    }
                    match self.sender.try_send(item).map_err(SenderError::TrySendError) {
                        Ok(_) => Ok(self.receiver.len() as i64),
                        Err(e) => Err(e),
                    }
                } else {
                    Ok(0)
                }
            }
            BackpressurePolicy::DropLatest => {
                // Try to send the item, if the queue is full, just ignore the item (drop the latest)
                match self.sender.try_send(item).map_err(SenderError::TrySendError) {
                    Ok(_) => Ok(self.receiver.len() as i64),
                    Err(err) => {
                        #[cfg(dev)]
                        eprintln!("store: dropping the latest item in channel");
                        if let Some(metrics) = &self.metrics {
                            if let SenderError::TrySendError(TrySendError::Full(
                                ActionOp::Action(action_drop),
                            )) = &err
                            {
                                metrics.action_dropped(Some(action_drop));
                            }
                        }
                        Err(err)
                    }
                }
            }
        };

        if let Some(metrics) = &self.metrics {
            metrics.queue_size(self.receiver.len());
        }
        r
    }
}

#[allow(dead_code)]
pub(crate) struct ReceiverChannel<Action>
where
    Action: Send + Sync + Clone + 'static,
{
    name: String,
    receiver: Receiver<ActionOp<Action>>,
    metrics: Option<Arc<dyn Metrics + Send + Sync>>,
}

#[cfg(any(dev))]
impl<Action> Drop for ReceiverChannel<Action>
where
    Action: Send + Sync + Clone + 'static,
{
    fn drop(&mut self) {
        eprintln!("store: drop '{}' receiver channel", self.name);
    }
}

impl<Action> ReceiverChannel<Action>
where
    Action: Send + Sync + Clone + 'static,
{
    pub fn recv(&self) -> Option<ActionOp<Action>> {
        self.receiver.recv().ok()
    }

    #[allow(dead_code)]
    pub fn try_recv(&self) -> Option<ActionOp<Action>> {
        self.receiver.try_recv().ok()
    }
}

/// Channel with back pressure
pub(crate) struct BackpressureChannel<Action>
where
    Action: Send + Sync + Clone + 'static,
{
    phantom_data: PhantomData<Action>,
}

impl<Action> BackpressureChannel<Action>
where
    Action: Send + Sync + Clone + 'static,
{
    #[allow(dead_code)]
    pub fn pair(
        capacity: usize,
        policy: BackpressurePolicy,
    ) -> (SenderChannel<Action>, ReceiverChannel<Action>) {
        Self::pair_with("<anon>", capacity, policy, None)
    }

    #[allow(dead_code)]
    pub fn pair_with_metrics(
        capacity: usize,
        policy: BackpressurePolicy,
        metrics: Option<Arc<dyn Metrics + Send + Sync>>,
    ) -> (SenderChannel<Action>, ReceiverChannel<Action>) {
        Self::pair_with("<anon>", capacity, policy, metrics)
    }

    #[allow(dead_code)]
    pub fn pair_with(
        name: &str,
        capacity: usize,
        policy: BackpressurePolicy,
        metrics: Option<Arc<dyn Metrics + Send + Sync>>,
    ) -> (SenderChannel<Action>, ReceiverChannel<Action>) {
        let (sender, receiver) = channel::bounded(capacity);
        (
            SenderChannel {
                _name: name.to_string(),
                sender,
                receiver: receiver.clone(),
                policy,
                metrics: metrics.clone(),
            },
            ReceiverChannel {
                name: name.to_string(),
                receiver,
                metrics: metrics.clone(),
            },
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::thread;
    use std::time::Duration;

    #[test]
    fn test_channel_backpressure_drop_old() {
        let (sender, receiver) =
            BackpressureChannel::<i32>::pair(5, BackpressurePolicy::DropOldest);

        let producer = {
            let sender_channel = sender.clone();
            thread::spawn(move || {
                for i in 0..20 {
                    // Send more messages than the channel can hold
                    println!("Sending: {}", i);
                    if let Err(err) = sender_channel.send(ActionOp::Action(i)) {
                        eprintln!("Failed to send: {:?}", err);
                    }
                    thread::sleep(Duration::from_millis(50)); // Slow down to observe full condition
                }
            })
        };

        let consumer = {
            thread::spawn(move || {
                let mut received_items = vec![];
                while let Some(value) = receiver.recv() {
                    println!("Received: {:?}", value);
                    match value {
                        ActionOp::Action(i) => received_items.push(i),
                        _ => {}
                    }
                    thread::sleep(Duration::from_millis(150)); // Slow down the consumer to create a backlog
                }
                println!("Channel closed, consumer thread exiting.");
                assert!(receiver.try_recv().is_none());

                received_items
            })
        };

        // Wait for the producer to finish
        producer.join().unwrap();
        drop(sender); // Close the channel after the producer is done

        // Collect the results from the consumer thread
        let received_items = consumer.join().unwrap();

        // Check the length of received items; it should be less than the total sent (20) due to drops
        assert!(received_items.len() < 20);
        // Ensure the last items were not dropped (based on the DropOld policy)
        assert_eq!(received_items.last(), Some(&19));
    }

    #[test]
    fn test_channel_backpressure_drop_latest() {
        let (sender, receiver) =
            BackpressureChannel::<i32>::pair(5, BackpressurePolicy::DropLatest);

        let producer = {
            let sender_channel = sender.clone();
            thread::spawn(move || {
                for i in 0..20 {
                    // Send more messages than the channel can hold
                    println!("Sending: {}", i);
                    if let Err(err) = sender_channel.send(ActionOp::Action(i)) {
                        eprintln!("Failed to send: {:?}", err);
                    }
                    thread::sleep(Duration::from_millis(50)); // Slow down to observe full condition
                }
            })
        };

        let consumer = {
            thread::spawn(move || {
                let mut received_items = vec![];
                while let Some(value) = receiver.recv() {
                    eprintln!("Received: {:?}", value);
                    match value {
                        ActionOp::Action(i) => received_items.push(i),
                        _ => {}
                    }
                    thread::sleep(Duration::from_millis(150)); // Slow down the consumer to create a backlog
                }
                println!("Channel closed, consumer thread exiting.");
                received_items
            })
        };

        // Wait for the producer to finish
        producer.join().unwrap();
        drop(sender); // Close the channel after the producer is done

        // Collect the results from the consumer thread
        let received_items = consumer.join().unwrap();

        // Check the length of received items; it should be less than the total sent (20) due to drops
        assert!(received_items.len() < 20);

        // Ensure the last item received is not necessarily the last one sent, based on the DropLatest policy
        assert!(received_items.contains(&0)); // The earliest items should be present
        assert!(received_items.last().unwrap() < &19); // The latest items might be dropped
    }
}