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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
// Copyright Materialize, Inc. and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License in the LICENSE file at the
// root of this repository, or online at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Channel utilities and extensions.

use std::pin::Pin;
use std::task::{Context, Poll};

use async_trait::async_trait;
use futures::{Future, FutureExt};
use prometheus::core::Atomic;
use tokio::sync::mpsc::{error, unbounded_channel, UnboundedReceiver, UnboundedSender};
use tokio::sync::oneshot;

use crate::metrics::PromLabelsExt;

/// Extensions for the receiving end of asynchronous channels.
#[async_trait]
pub trait ReceiverExt<T: Send> {
    /// Receives all of the currently buffered elements on the channel, up to some max.
    ///
    /// This method returns `None` if the channel has been closed and there are no remaining
    /// messages in the channel's buffer.
    ///
    /// If there are no messages in the channel's buffer, but the channel is not yet closed, this
    /// method will sleep until a message is sent or the channel is closed. When woken it will
    /// return up to max currently buffered elements.
    ///
    /// # Cancel safety
    ///
    /// This method is cancel safe. If `recv_many` is used as the event in a `select!` statement
    /// and some other branch completes first, it is guaranteed that no messages were received on
    /// this channel.
    ///
    /// # Max Buffer Size
    ///
    /// The provided max buffer size should always be less than the total capacity of the channel.
    /// Otherwise a good value is probably a fraction of the total channel size, or however large
    /// a batch that your receiving component can handle.
    ///
    /// TODO(parkmycar): We should refactor this to use `impl Iterator` instead of `Vec` when
    /// "impl trait in trait" is supported.
    async fn recv_many(&mut self, max: usize) -> Option<Vec<T>>;
}

#[async_trait]
impl<T: Send> ReceiverExt<T> for tokio::sync::mpsc::Receiver<T> {
    async fn recv_many(&mut self, max: usize) -> Option<Vec<T>> {
        // Wait for a value to be ready.
        let first = self.recv().await?;
        let mut buffer = Vec::from([first]);

        // Note(parkmycar): It's very important for cancelation safety that we don't add any more
        // .await points other than the initial one.

        // Pull all of the remaining values off the channel.
        while let Ok(v) = self.try_recv() {
            buffer.push(v);

            // Break so we don't loop here continuously.
            if buffer.len() >= max {
                break;
            }
        }

        Some(buffer)
    }
}

#[async_trait]
impl<T: Send> ReceiverExt<T> for tokio::sync::mpsc::UnboundedReceiver<T> {
    async fn recv_many(&mut self, max: usize) -> Option<Vec<T>> {
        // Wait for a value to be ready.
        let first = self.recv().await?;
        let mut buffer = Vec::from([first]);

        // Note(parkmycar): It's very important for cancelation safety that we don't add any more
        // .await points other than the initial one.

        // Pull all of the remaining values off the channel.
        while let Ok(v) = self.try_recv() {
            buffer.push(v);

            // Break so we don't loop here continuously.
            if buffer.len() >= max {
                break;
            }
        }

        Some(buffer)
    }
}

/// A trait describing a metric that can be used with an `instrumented_unbounded_channel`.
pub trait InstrumentedChannelMetric {
    /// Bump the metric, increasing the count of operators (send or receives) that occurred.
    fn bump(&self);
}

impl<'a, P, L> InstrumentedChannelMetric for crate::metrics::DeleteOnDropCounter<'a, P, L>
where
    P: Atomic,
    L: PromLabelsExt<'a>,
{
    fn bump(&self) {
        self.inc()
    }
}

/// A wrapper around tokio's mpsc unbounded channels that connects
/// metrics that are incremented when sends or receives happen.
pub fn instrumented_unbounded_channel<T, M>(
    sender_metric: M,
    receiver_metric: M,
) -> (
    InstrumentedUnboundedSender<T, M>,
    InstrumentedUnboundedReceiver<T, M>,
)
where
    M: InstrumentedChannelMetric,
{
    let (tx, rx) = unbounded_channel();

    (
        InstrumentedUnboundedSender {
            tx,
            metric: sender_metric,
        },
        InstrumentedUnboundedReceiver {
            rx,
            metric: receiver_metric,
        },
    )
}

/// A wrapper around tokio's `UnboundedSender` that increments a metric when a send occurs.
///
/// The metric is not dropped until this sender is dropped.
#[derive(Debug)]
pub struct InstrumentedUnboundedSender<T, M> {
    tx: UnboundedSender<T>,
    metric: M,
}

impl<T, M> InstrumentedUnboundedSender<T, M>
where
    M: InstrumentedChannelMetric,
{
    /// The same as `UnboundedSender::send`.
    pub fn send(&self, message: T) -> Result<(), error::SendError<T>> {
        let res = self.tx.send(message);
        self.metric.bump();
        res
    }
}

/// A wrapper around tokio's `UnboundedReceiver` that increments a metric when a recv _finishes_.
///
/// The metric is not dropped until this receiver is dropped.
#[derive(Debug)]
pub struct InstrumentedUnboundedReceiver<T, M> {
    rx: UnboundedReceiver<T>,
    metric: M,
}

impl<T, M> InstrumentedUnboundedReceiver<T, M>
where
    M: InstrumentedChannelMetric,
{
    /// The same as `UnboundedSender::recv`.
    pub async fn recv(&mut self) -> Option<T> {
        let res = self.rx.recv().await;
        self.metric.bump();
        res
    }

    /// The same as `UnboundedSender::try_recv`.
    pub fn try_recv(&mut self) -> Result<T, error::TryRecvError> {
        let res = self.rx.try_recv();

        if res.is_ok() {
            self.metric.bump();
        }
        res
    }
}

/// Extensions for oneshot channel types.
pub trait OneshotReceiverExt<T> {
    /// If the receiver is dropped without the value being observed, the provided closure will be
    /// called with the value that was left in the channel.
    ///
    /// This is useful in cases where you want to cleanup resources if the receiver of this value
    /// has gone away. If the sender and receiver are running on separate threads, it's possible
    /// for the sender to succeed, and for the receiver to be concurrently dropped, never realizing
    /// that it received a value.
    fn with_guard<F>(self, guard: F) -> GuardedReceiver<F, T>
    where
        F: FnMut(T);
}

impl<T> OneshotReceiverExt<T> for oneshot::Receiver<T> {
    fn with_guard<F>(self, guard: F) -> GuardedReceiver<F, T>
    where
        F: FnMut(T),
    {
        GuardedReceiver { guard, inner: self }
    }
}

/// A wrapper around [`oneshot::Receiver`] that will call the provided closure if there is a value
/// in the receiver when it's dropped.
#[derive(Debug)]
pub struct GuardedReceiver<F: FnMut(T), T> {
    guard: F,
    inner: oneshot::Receiver<T>,
}

// Note(parkmycar): If this Unpin requirement becomes too restrictive, we can refactor
// GuardedReceiver to use `pin_project`.
impl<F: FnMut(T) + Unpin, T> Future for GuardedReceiver<F, T> {
    type Output = Result<T, oneshot::error::RecvError>;

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        self.inner.poll_unpin(cx)
    }
}

impl<F: FnMut(T), T> Drop for GuardedReceiver<F, T> {
    fn drop(&mut self) {
        // Close the channel so the sender is guaranteed to fail.
        self.inner.close();

        // If there was some value waiting in the channel call the guard with the value.
        if let Ok(x) = self.inner.try_recv() {
            (self.guard)(x)
        }
    }
}

// allow `futures::block_on` for testing.
#[allow(clippy::disallowed_methods)]
#[cfg(test)]
mod tests {
    use futures::executor::block_on;
    use futures::FutureExt;
    use tokio::sync::mpsc;

    use super::ReceiverExt;

    #[crate::test]
    fn smoke_test_tokio_mpsc() {
        let (tx, mut rx) = mpsc::channel(16);

        // Buffer a few elements.
        tx.try_send(1).expect("enough capacity");
        tx.try_send(2).expect("enough capacity");
        tx.try_send(3).expect("enough capacity");
        tx.try_send(4).expect("enough capacity");
        tx.try_send(5).expect("enough capacity");

        // Receive a max of three elements at once.
        let elements = block_on(rx.recv_many(3)).expect("values");
        assert_eq!(elements, [1, 2, 3]);

        // Receive the remaining elements.
        let elements = block_on(rx.recv_many(8)).expect("values");
        assert_eq!(elements, [4, 5]);
    }

    #[crate::test]
    fn smoke_test_tokio_unbounded() {
        let (tx, mut rx) = mpsc::unbounded_channel();

        // Buffer a few elements.
        tx.send(1).expect("enough capacity");
        tx.send(2).expect("enough capacity");
        tx.send(3).expect("enough capacity");
        tx.send(4).expect("enough capacity");
        tx.send(5).expect("enough capacity");

        // Receive a max of three elements at once.
        let elements = block_on(rx.recv_many(3)).expect("values");
        assert_eq!(elements, [1, 2, 3]);

        // Receive the remaining elements.
        let elements = block_on(rx.recv_many(8)).expect("values");
        assert_eq!(elements, [4, 5]);
    }

    #[crate::test]
    fn test_tokio_mpsc_permit() {
        let (tx, mut rx) = mpsc::channel(16);

        // Reserve space for a few elements.
        let permit1 = tx.clone().try_reserve_owned().expect("enough capacity");
        let permit2 = tx.clone().try_reserve_owned().expect("enough capacity");
        let permit3 = tx.clone().try_reserve_owned().expect("enough capacity");

        // Close the channel.
        drop(tx);

        let waker = futures::task::noop_waker();
        let mut cx = std::task::Context::from_waker(&waker);

        let mut recv_many = rx.recv_many(4);

        // The channel is closed, but there are outstanding permits, so we should return pending.
        assert!(recv_many.poll_unpin(&mut cx).is_pending());

        // Send data on the channel.
        permit1.send(1);
        permit2.send(2);
        permit3.send(3);

        // We should receive all of the data after a single poll.
        let elements = match recv_many.poll_unpin(&mut cx) {
            std::task::Poll::Ready(elements) => elements.expect("elements to be returned"),
            std::task::Poll::Pending => panic!("future didn't immediately return elements!"),
        };
        assert_eq!(elements, [1, 2, 3]);
        drop(recv_many);

        // Polling the channel one more time should return None since the channel is closed.
        let elements = match rx.recv_many(4).poll_unpin(&mut cx) {
            std::task::Poll::Ready(elements) => elements,
            std::task::Poll::Pending => panic!("future didn't immediately return"),
        };
        assert!(elements.is_none());
    }

    #[crate::test]
    fn test_empty_channel() {
        let (tx, mut rx) = mpsc::channel::<usize>(16);

        let recv_many = rx.recv_many(4);
        drop(tx);

        let elements = block_on(recv_many);
        assert!(elements.is_none());
    }

    #[crate::test]
    fn test_atleast_two_semantics() {
        let (tx, mut rx) = mpsc::channel(16);

        // Buffer a few elements.
        tx.try_send(1).expect("enough capacity");
        tx.try_send(2).expect("enough capacity");
        tx.try_send(3).expect("enough capacity");

        // Even though we specify a max of one, we'll receive at least 2.
        let elements = block_on(rx.recv_many(1)).expect("values");
        assert_eq!(elements, [1, 2]);
    }

    #[crate::test]
    fn test_cancelation_safety() {
        let (tx, mut rx) = mpsc::channel(16);

        // Buffer a few elements.
        tx.try_send(1).expect("enough capacity");
        tx.try_send(2).expect("enough capacity");
        tx.try_send(3).expect("enough capacity");

        let mut immediate_ready = Box::pin(async { 100 }).fuse();

        let mut count = 0;
        let mut result = vec![];

        loop {
            count += 1;

            block_on(async {
                futures::select_biased! {
                    single = &mut immediate_ready => result.push(single),
                    many = &mut rx.recv_many(2).fuse() => {
                        let values = many.expect("stream ended!");
                        result.extend(values);
                    },
                }
            });

            if count >= 3 {
                break;
            }
        }

        assert_eq!(result, [100, 1, 2, 3]);
    }

    #[crate::test]
    fn test_closed_channel() {
        let (tx, mut rx) = mpsc::channel(16);

        tx.try_send(1).expect("enough capacity");
        tx.try_send(2).expect("enough capacity");
        tx.try_send(3).expect("enough capacity");

        // Drop the sender to close it.
        drop(tx);

        // Make sure the buffer is larger than queued elements.
        let elements = block_on(rx.recv_many(4)).expect("elements");
        assert_eq!(elements, [1, 2, 3]);

        // Receiving again should return None.
        assert!(block_on(rx.recv_many(4)).is_none());
    }
}