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
use std::time::{Duration, Instant};

use crate::snapshot::{ItemKind, Snapshot};
use crate::util;
use crate::{Descriptive, HandlesObservations, Observation, PutsSnapshot};

use super::*;

/// The panel shows recorded
/// observations with the same label
/// in different representations.
///
/// Let's say you want to monitor the successful requests
/// of a specific endpoint of your REST API.
/// You would then create a panel for this and might
/// want to add a counter and a meter and a histogram
/// to track latencies.
///
/// # Example
///
/// ```
/// use std::time::Instant;
/// use metrix::instruments::*;
/// use metrix::{HandlesObservations, Observation};
///
/// #[derive(Clone, PartialEq, Eq)]
/// struct SuccessfulRequests;
///
/// let counter = Counter::new_with_defaults("count");
/// let gauge = Gauge::new_with_defaults("last_latency");
/// let meter = Meter::new_with_defaults("per_second");
/// let histogram = Histogram::new_with_defaults("latencies");
///
/// assert_eq!(0, counter.get());
/// assert_eq!(None, gauge.get());
///
/// let mut panel = Panel::named(SuccessfulRequests, "successful_requests");
/// panel.add_counter(counter);
/// panel.add_gauge(gauge);
/// panel.add_meter(meter);
/// panel.add_histogram(histogram);
///
/// let observation = Observation::ObservedOneValue {
///        label: SuccessfulRequests,
///        value: 12.into(),
///        timestamp: Instant::now(),
/// };
/// panel.handle_observation(&observation);
/// ```
pub struct Panel<L> {
    label_filter: LabelFilter<L>,
    name: Option<String>,
    title: Option<String>,
    description: Option<String>,
    counter: Option<InstrumentAdapter<L, Counter>>,
    gauge: Option<GaugeAdapter<L>>,
    meter: Option<InstrumentAdapter<L, Meter>>,
    histogram: Option<InstrumentAdapter<L, Histogram>>,
    panels: Vec<Panel<L>>,
    handlers: Vec<Box<dyn HandlesObservations<Label = L>>>,
    snapshooters: Vec<Box<dyn PutsSnapshot>>,
    last_update: Instant,
    max_inactivity_duration: Option<Duration>,
    show_activity_state: bool,
}

impl<L> Panel<L>
where
    L: Eq + Send + 'static,
{
    /// Create a new `Panel` without a name which dispatches observations
    /// with the given label
    pub fn new<F: Into<LabelFilter<L>>>(accept: F) -> Panel<L> {
        Panel {
            label_filter: accept.into(),
            name: None,
            title: None,
            description: None,
            counter: None,
            gauge: None,
            meter: None,
            histogram: None,
            panels: Vec::new(),
            handlers: Vec::new(),
            snapshooters: Vec::new(),
            last_update: Instant::now(),
            max_inactivity_duration: None,
            show_activity_state: true,
        }
    }

    /// Create a new `Panel` with the given name which dispatches observations
    /// with the given label
    pub fn named<T: Into<String>, F: Into<LabelFilter<L>>>(accept: F, name: T) -> Panel<L> {
        let mut panel = Self::new(accept);
        panel.name = Some(name.into());
        panel
    }

    /// Create a new `Panel` without a name which dispatches observations
    /// with the given labels
    pub fn accept<F: Into<LabelFilter<L>>>(accept: F) -> Self {
        Self::new(accept)
    }

    /// Create a new `Panel` with the given name which dispatches observations
    /// with the given labels
    pub fn accept_named<T: Into<String>, F: Into<LabelFilter<L>>>(accept: F, name: T) -> Self {
        Self::named(accept, name)
    }

    /// Create a new `Panel` with the given name which dispatches all
    /// observations
    pub fn accept_all_named<T: Into<String>>(name: T) -> Panel<L> {
        Self::named(AcceptAllLabels, name)
    }

    /// Create a new `Panel` without a name which dispatches all
    /// observations
    pub fn accept_all() -> Panel<L> {
        Self::new(AcceptAllLabels)
    }

    pub fn add_counter<I: Into<InstrumentAdapter<L, Counter>>>(&mut self, counter: I) {
        if self.counter.is_none() {
            self.counter = Some(counter.into());
        } else {
            self.add_handler(counter.into())
        }
    }

    pub fn counter<I: Into<InstrumentAdapter<L, Counter>>>(mut self, counter: I) -> Self {
        self.add_counter(counter);
        self
    }

    pub fn gauge<I: Into<GaugeAdapter<L>>>(mut self, gauge: I) -> Self {
        self.add_gauge(gauge);
        self
    }

    pub fn add_gauge<I: Into<GaugeAdapter<L>>>(&mut self, gauge: I) {
        if self.gauge.is_none() {
            self.gauge = Some(gauge.into());
        } else {
            self.add_handler(gauge.into())
        }
    }

    pub fn meter<I: Into<InstrumentAdapter<L, Meter>>>(mut self, meter: I) -> Self {
        self.add_meter(meter);
        self
    }

    pub fn add_meter<I: Into<InstrumentAdapter<L, Meter>>>(&mut self, meter: I) {
        if self.meter.is_none() {
            self.meter = Some(meter.into());
        } else {
            self.add_handler(meter.into())
        }
    }

    pub fn add_histogram<I: Into<InstrumentAdapter<L, Histogram>>>(&mut self, histogram: I) {
        if self.histogram.is_none() {
            self.histogram = Some(histogram.into());
        } else {
            self.add_handler(histogram.into())
        }
    }

    pub fn histogram<I: Into<InstrumentAdapter<L, Histogram>>>(mut self, histogram: I) -> Self {
        self.add_histogram(histogram);
        self
    }

    pub fn add_snapshooter<T: PutsSnapshot>(&mut self, snapshooter: T) {
        self.snapshooters.push(Box::new(snapshooter));
    }

    pub fn snapshooter<T: PutsSnapshot>(mut self, snapshooter: T) -> Self {
        self.add_snapshooter(snapshooter);
        self
    }

    pub fn add_instrument<I: Instrument>(&mut self, instrument: I) {
        self.handlers
            .push(Box::new(InstrumentAdapter::new(instrument)));
    }

    pub fn instrument<T: Instrument>(mut self, instrument: T) -> Self {
        self.add_instrument(instrument);
        self
    }

    pub fn add_panel(&mut self, panel: Panel<L>) {
        self.panels.push(panel);
    }

    pub fn panel(mut self, panel: Panel<L>) -> Self {
        self.add_panel(panel);
        self
    }

    pub fn add_handler<H: HandlesObservations<Label = L>>(&mut self, handler: H) {
        self.handlers.push(Box::new(handler));
    }

    pub fn handler<H: HandlesObservations<Label = L>>(mut self, handler: H) -> Self {
        self.add_handler(handler);
        self
    }

    /// Gets the name of this `Panel`
    pub fn name(&self) -> Option<&str> {
        self.name.as_deref()
    }

    /// Set the name if this `Panel`.
    ///
    /// The name is a path segment within a `Snapshot`
    pub fn set_name<T: Into<String>>(&mut self, name: T) {
        self.name = Some(name.into());
    }

    /// Sets the `title` of this `Panel`.
    ///
    /// A title can be part of a descriptive `Snapshot`
    pub fn set_title<T: Into<String>>(&mut self, title: T) {
        self.title = Some(title.into())
    }

    /// Sets the `description` of this `Panel`.
    ///
    /// A description can be part of a descriptive `Snapshot`
    pub fn set_description<T: Into<String>>(&mut self, description: T) {
        self.description = Some(description.into())
    }

    /// Sets the maximum amount of time this panel may be
    /// inactive until no more snapshots are taken
    ///
    /// Default is no inactivity tracking.
    pub fn inactivity_limit(mut self, limit: Duration) -> Self {
        self.set_inactivity_limit(limit);
        self
    }

    /// Set whether to show if the panel is inactive or not
    /// if `inactivity_limit` is set.
    ///
    /// The default is `true`. Only has an effect if a `inactivity_limit`
    /// is set.
    pub fn set_inactivity_limit(&mut self, limit: Duration) {
        self.max_inactivity_duration = Some(limit);
    }

    /// Set whether to show if the panel is inactive or not
    /// if `inactivity_limit` is set.
    ///
    /// The default is `true`. Only has an effect if a `inactivity_limit`
    /// is set.
    pub fn set_show_activity_state(&mut self, show: bool) {
        self.show_activity_state = show;
    }

    /// Set whether to show if the instrument is inactive are not
    /// if `inactivity_limit` is set.
    ///
    /// The default is `true`. Only has an effect if a `inactivity_limit`
    /// is set.
    pub fn show_activity_state(mut self, show: bool) -> Self {
        self.set_show_activity_state(show);
        self
    }

    pub fn accepts_label(&self, label: &L) -> bool {
        self.label_filter.accepts(label)
    }

    fn put_values_into_snapshot(&self, into: &mut Snapshot, descriptive: bool) {
        util::put_default_descriptives(self, into, descriptive);
        if let Some(d) = self.max_inactivity_duration {
            if self.show_activity_state {
                if self.last_update.elapsed() > d {
                    into.items
                        .push(("_inactive".to_string(), ItemKind::Boolean(true)));
                    into.items
                        .push(("_active".to_string(), ItemKind::Boolean(false)));
                    return;
                } else {
                    into.items
                        .push(("_inactive".to_string(), ItemKind::Boolean(false)));
                    into.items
                        .push(("_active".to_string(), ItemKind::Boolean(true)));
                }
            }
        };
        self.counter
            .as_ref()
            .iter()
            .for_each(|x| x.put_snapshot(into, descriptive));
        self.gauge
            .as_ref()
            .iter()
            .for_each(|x| x.put_snapshot(into, descriptive));
        self.meter
            .as_ref()
            .iter()
            .for_each(|x| x.put_snapshot(into, descriptive));
        self.histogram
            .as_ref()
            .iter()
            .for_each(|x| x.put_snapshot(into, descriptive));
        self.panels
            .iter()
            .for_each(|p| p.put_snapshot(into, descriptive));
        self.snapshooters
            .iter()
            .for_each(|p| p.put_snapshot(into, descriptive));
        self.handlers
            .iter()
            .for_each(|p| p.put_snapshot(into, descriptive));
    }
}

impl<L> PutsSnapshot for Panel<L>
where
    L: Eq + Send + 'static,
{
    fn put_snapshot(&self, into: &mut Snapshot, descriptive: bool) {
        if let Some(ref name) = self.name {
            let mut new_level = Snapshot::default();
            self.put_values_into_snapshot(&mut new_level, descriptive);
            into.items
                .push((name.clone(), ItemKind::Snapshot(new_level)));
        } else {
            self.put_values_into_snapshot(into, descriptive);
        }
    }
}

impl<L> HandlesObservations for Panel<L>
where
    L: Eq + Send + 'static,
{
    type Label = L;

    fn handle_observation(&mut self, observation: &Observation<Self::Label>) -> usize {
        if !self.label_filter.accepts(observation.label()) {
            return 0;
        }

        let mut instruments_updated = 0;

        self.counter
            .iter_mut()
            .for_each(|x| instruments_updated += x.handle_observation(&observation));
        self.gauge
            .iter_mut()
            .for_each(|x| instruments_updated += x.handle_observation(&observation));
        self.meter
            .iter_mut()
            .for_each(|x| instruments_updated += x.handle_observation(&observation));
        self.histogram
            .iter_mut()
            .for_each(|x| instruments_updated += x.handle_observation(&observation));
        self.panels
            .iter_mut()
            .for_each(|x| instruments_updated += x.handle_observation(&observation));
        self.handlers
            .iter_mut()
            .for_each(|x| instruments_updated += x.handle_observation(&observation));

        instruments_updated
    }
}

impl<L> Descriptive for Panel<L> {
    fn title(&self) -> Option<&str> {
        self.title.as_deref()
    }

    fn description(&self) -> Option<&str> {
        self.description.as_deref()
    }
}