zrx_stream/stream/operator/throttle.rs
1// Copyright (c) Zensical LLC <https://zensical.org>
2
3// SPDX-License-Identifier: MIT
4// Third-party contributions licensed under CLA
5
6// Permission is hereby granted, free of charge, to any person obtaining a copy
7// of this software and associated documentation files (the "Software"), to
8// deal in the Software without restriction, including without limitation the
9// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10// sell copies of the Software, and to permit persons to whom the Software is
11// furnished to do so, subject to the following conditions:
12
13// The above copyright notice and this permission notice shall be included in
14// all copies or substantial portions of the Software.
15
16// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18// FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
19// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
22// IN THE SOFTWARE.
23
24// ----------------------------------------------------------------------------
25
26//! Throttle operator.
27
28use std::marker::PhantomData;
29use zrx_scheduler::action::descriptor::Property;
30use zrx_scheduler::action::output::IntoOutputs;
31use zrx_scheduler::action::Descriptor;
32use zrx_scheduler::effect::timer::IntoDuration;
33use zrx_scheduler::effect::{Item, Timer};
34use zrx_scheduler::{outputs, Id, Value};
35
36use crate::stream::function::SelectFn;
37use crate::stream::Stream;
38
39use super::{Operator, OperatorExt};
40
41// ----------------------------------------------------------------------------
42// Structs
43// ----------------------------------------------------------------------------
44
45/// Throttle operator.
46struct Throttle<F, D> {
47 /// Operator function.
48 function: F,
49 /// Type marker.
50 marker: PhantomData<D>,
51}
52
53// ----------------------------------------------------------------------------
54// Implementations
55// ----------------------------------------------------------------------------
56
57impl<I, T> Stream<I, T>
58where
59 I: Id,
60 T: Value + Clone,
61{
62 pub fn throttle<D>(&self, duration: D) -> Stream<I, T>
63 where
64 D: IntoDuration,
65 {
66 let duration = duration.into_duration();
67 self.with_operator(Throttle {
68 function: move |_: &T| duration,
69 marker: PhantomData,
70 })
71 }
72
73 pub fn throttle_with<F, D>(&self, f: F) -> Stream<I, T>
74 where
75 F: SelectFn<I, T, D>,
76 D: IntoDuration,
77 {
78 self.with_operator(Throttle {
79 function: f,
80 marker: PhantomData,
81 })
82 }
83}
84
85// ----------------------------------------------------------------------------
86// Trait implementations
87// ----------------------------------------------------------------------------
88
89impl<I, T, F, D> Operator<I, T> for Throttle<F, D>
90where
91 I: Id,
92 T: Value + Clone,
93 F: SelectFn<I, T, D>,
94 D: IntoDuration,
95{
96 type Item<'a> = Item<&'a I, &'a T>;
97
98 /// Handles the given item.
99 ///
100 /// Throttling is implemented with the help of two timers, where the first
101 /// timer acts as a guard to ensure that the second timer is only set if the
102 /// first timer hasn't already been set. The most recent item is emitted
103 /// only if the second timer isn't active.
104 #[cfg_attr(
105 feature = "tracing",
106 tracing::instrument(level = "debug", skip_all, fields(id = %item.id))
107 )]
108 fn handle(&mut self, item: Self::Item<'_>) -> impl IntoOutputs<I> {
109 self.function.execute(item.id, item.data).map(|report| {
110 report.map(|duration| {
111 let timer = Timer::set(duration, None);
112 Timer::set(
113 0,
114 Some(outputs![timer, item.into_owned().map(Some)]),
115 )
116 })
117 })
118 }
119
120 /// Returns the descriptor.
121 #[inline]
122 fn descriptor(&self) -> Descriptor {
123 Descriptor::builder()
124 .property(Property::Pure)
125 .property(Property::Stable)
126 .property(Property::Flush)
127 .build()
128 }
129}