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
use std::{
    pin::Pin,
    future::Future,
};
use anyhow::*;
use metrix::{
    TelemetryTransmitter,
    instruments::{Panel, Cockpit},
    processor::{TelemetryProcessor, AggregatesProcessors},
instruments::Meter, TransmitsTelemetryData, instruments::Histogram, TimeUnit, instruments::Gauge};
use tokio::{
    task::JoinHandle,
    time::{self, *},
};

pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;

pub struct Jackhammer {
    interval: Interval,
    actions_per_interval: u32,
    action_factory: Box<dyn ActionFactory>,
    timeout: Option<Duration>,
    metrics: Metrics,
}

impl Jackhammer {
    pub fn builder() -> JackhammerBuilder {
        JackhammerBuilder::new()
    }

    async fn run(mut self) -> Result<()> {
        loop {
            self.interval.tick().await;

            for _ in 0..self.actions_per_interval {
                let action = self.action_factory.next_action();
                let action = timeout(self.timeout, action);
                let metrics = self.metrics.clone();

                tokio::spawn(async move {
                    let start = Instant::now();

                    match action.await {
                        Ok(Ok(_)) => metrics.observed_successful_action(start.elapsed()),
                        Ok(Err(_)) =>  metrics.observed_failed_action(start.elapsed()),
                        Err(_) => metrics.observed_timed_out_action(start.elapsed()),
                    }

                    metrics.observed_finished_action(start.elapsed());
                });

                self.metrics.observed_spawned_action();
            }
        }
    }
}

pub struct JackhammerBuilder {
    actions_per_interval: u32,
    interval: Duration,
    action_factory: Box<dyn ActionFactory>,
    metrics: Metrics,
    timeout: Option<Duration>,
}

impl JackhammerBuilder {
    pub fn new() -> Self {
        Self {
            actions_per_interval: 1,
            interval: Duration::from_secs(1),
            action_factory: Box::new(|| Box::pin(async { Ok(()) })),
            metrics: Metrics::default(),
            timeout: None,
        }
    }

    pub fn actions_per_interval(mut self, actions_per_interval: u32) -> Self {
        self.actions_per_interval = actions_per_interval;
        self
    }

    pub fn interval(mut self, interval: Duration) -> Self {
        self.interval = interval;
        self
    }

    pub fn action_factory<AF>(mut self, action_factory: AF) -> Self
    where
        AF: ActionFactory + Send + Sync,
    {
        self.action_factory = Box::new(action_factory);
        self
    }

    pub fn timeout(mut self, timeout: impl Into<Option<Duration>>) -> Self {
        self.timeout = timeout.into();
        self
    }

    /// Should be called at most once
    pub fn instrumentation<AP>(mut self, aggregator: &mut AP) -> Self
    where
        AP: AggregatesProcessors,
    {
        self.metrics = Metrics::new(aggregator);
        self
    }

    pub fn start(self) -> JackhammerHandle {
        let jackhammer = Jackhammer {
            interval: time::interval(self.interval),
            actions_per_interval: self.actions_per_interval,
            action_factory: self.action_factory,
            metrics: self.metrics,
            timeout: self.timeout,
        };

        let join_handle = tokio::spawn(jackhammer.run());

        JackhammerHandle {
            join_handle
        }
    }
}

pub trait ActionFactory: Send + 'static {
    fn next_action(&mut self) -> BoxFuture<'static, Result<()>>;
}

impl dyn ActionFactory {
    pub fn from_fn<F, Fut>(factory_fn: F) -> impl ActionFactory
    where
        F: FnMut() -> Fut + Send + Sync + 'static,
        Fut: Future<Output = Result<()>> + Send + 'static,
    {
        factory_fn
    }
}

impl<F, Fut> ActionFactory for F
where
    F: FnMut() -> Fut + Send + Sync + 'static,
    Fut: Future<Output = Result<()>> + Send + 'static,
{
    fn next_action(&mut self) -> BoxFuture<'static, Result<()>> {
        Box::pin(self())
    }
}

pub struct JackhammerHandle {
    join_handle: JoinHandle<Result<()>>,
}

impl JackhammerHandle {
    pub async fn join(self) -> Result<()> {
        self.join_handle.await??;
        Ok(())
    }
}

#[derive(Clone, Default)]
struct Metrics {
    telemetry_transmitter: Option<TelemetryTransmitter<Metric>>,
}

impl Metrics {
    fn new<AP>(aggregator: &mut AP) -> Self
    where
        AP: AggregatesProcessors,
    {
        let mut cockpit = Cockpit::new("jackhammer");

        let panel = Panel::named(Metric::SuccessfulActions, "successful_actions")
            .meter(Meter::new_with_defaults("per_second"))
            .histogram(
                Histogram::new_with_defaults("latency_us")
                .display_time_unit(TimeUnit::Microseconds)
            )
            .histogram(
                Histogram::new_with_defaults("latency_ms")
                .display_time_unit(TimeUnit::Milliseconds)
            );
        cockpit.add_panel(panel);

        let panel = Panel::named(Metric::FailedActions, "failed_actions")
            .meter(Meter::new_with_defaults("per_second"))
            .histogram(
                Histogram::new_with_defaults("latency_us")
                .display_time_unit(TimeUnit::Microseconds)
            )
            .histogram(
                Histogram::new_with_defaults("latency_ms")
                .display_time_unit(TimeUnit::Milliseconds)
            );
        cockpit.add_panel(panel);

        let mut panel = Panel::named(Metric::FinishedActions, "finished_actions")
            .meter(Meter::new_with_defaults("per_second"))
            .histogram(
                Histogram::new_with_defaults("latency_us")
                .display_time_unit(TimeUnit::Microseconds)
            )
            .histogram(
                Histogram::new_with_defaults("latency_ms")
                .display_time_unit(TimeUnit::Milliseconds)
            );
        panel.set_description("Actions that succeeded, failed or timed out");
        cockpit.add_panel(panel);

        let panel = Panel::named(Metric::TimedOutActions, "timed_out_actions")
            .meter(Meter::new_with_defaults("per_second"))
            .histogram(
                Histogram::new_with_defaults("latency_us")
                .display_time_unit(TimeUnit::Microseconds)
            )
            .histogram(
                Histogram::new_with_defaults("latency_ms")
                .display_time_unit(TimeUnit::Milliseconds)
            );
        cockpit.add_panel(panel);

        let panel = Panel::named(Metric::SpawnedActions, "spawned_actions")
            .gauge(Gauge::new_with_defaults("count"));
        cockpit.add_panel(panel);

        let (tx, mut rx) = TelemetryProcessor::new_pair_without_name();
        rx.add_cockpit(cockpit);
        aggregator.add_processor(rx);

        Self { telemetry_transmitter: Some(tx) }
    }

    fn observed_successful_action(&self, duration: Duration) {
        if let Some(tx) = &self.telemetry_transmitter {
            tx.observed_one_duration_now(Metric::SuccessfulActions, duration);
        }
    }

    fn observed_failed_action(&self, duration: Duration) {
        if let Some(tx) = &self.telemetry_transmitter {
            tx.observed_one_duration_now(Metric::FailedActions, duration);
        }
    }

    fn observed_finished_action(&self, duration: Duration) {
        let now = std::time::Instant::now();

        if let Some(tx) = &self.telemetry_transmitter {
            tx.observed_duration(Metric::FinishedActions, duration, now);
            tx.observed_one_value(Metric::SpawnedActions, metrix::Decrement, now);
        }
    }

    fn observed_timed_out_action(&self, duration: Duration) {
        if let Some(tx) = &self.telemetry_transmitter {
            tx.observed_one_duration_now(Metric::TimedOutActions, duration);
        }
    }

    fn observed_spawned_action(&self) {
        if let Some(tx) = &self.telemetry_transmitter {
            tx.observed_one_value_now(Metric::SpawnedActions, metrix::Increment);
        }
    }
}

#[derive(PartialEq, Eq, Copy, Clone)]
enum Metric {
    SuccessfulActions,
    FailedActions,
    FinishedActions,
    TimedOutActions,
    SpawnedActions,
}

async fn timeout<T>(duration: Option<Duration>, future: impl Future<Output = T>) -> Result<T, time::Elapsed> {
    match duration {
        Some(duration) => time::timeout(duration, future).await,
        None => Ok(future.await),
    }
}