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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
//! Heatmap provides a time-series of Histograms, which is useful for
//! recording distributions over time and reporting percentiles over time
//!
//!
//! # Goals
//! * pre-allocated datastructure
//! * report time-series percentiles
//! * auto-slicing by record time
//!
//! # Future work
//! * more efficient serialization format
//!
//! # Usage
//! Create a heatmap. Insert values over time. Profit.
//!
//! ```
//!
//! use heatmap::*;

#![crate_type = "lib"]

#![crate_name = "heatmap"]

extern crate histogram;

use std::time::{Duration, Instant};
use histogram::Histogram;
use std::fs::File;
use std::io::prelude::Write;
//use std::io::BufReader;
//use std::io::BufRead;

/// A configuration struct for building custom `Heatmap`s.
#[derive(Clone, Copy)]
pub struct Config {
    precision: u32,
    max_memory: u32,
    max_value: u64,
    slice_duration: Duration,
    num_slices: usize,
    start: Instant,
}

impl Default for Config {
    fn default() -> Config {
        Config {
            precision: 3,
            max_memory: 0,
            max_value: 1_000_000_000,
            slice_duration: Duration::new(60, 0),
            num_slices: 60,
            start: Instant::now(),
        }
    }
}

impl Config {
    /// create a new Config with the defaults
    ///
    /// # Defaults
    /// * precision => 3
    /// * max_memory => 0 (unlimited)
    /// * max_value => 1_000_000_000 (1 second in nanoseconds)
    /// * slice_duration => 60_000_000_000 (1 minute in nanoseconds)
    /// * num_slices => 60 (1 hour of heatmap)
    /// * start => 0 (start from time 0)
    pub fn new() -> Config {
        Default::default()
    }

    /// set the number of significant figures to mantain for values
    pub fn precision(mut self, precision: u32) -> Self {
        self.precision = precision;
        self
    }

    /// set a bound on memory usage of `Heatmap`
    pub fn max_memory(mut self, bytes: u32) -> Self {
        self.max_memory = bytes;
        self
    }

    /// set the max value to store within the `Heatmap`
    pub fn max_value(mut self, value: u64) -> Self {
        self.max_value = value;
        self
    }

    /// set the duration of each `Slice` within the `Heatmap`
    pub fn slice_duration(mut self, duration: Duration) -> Self {
        self.slice_duration = duration;
        self
    }

    /// set the number of `Slice`s to store
    pub fn num_slices(mut self, count: usize) -> Self {
        self.num_slices = count;
        self
    }

    /// the start time of the `Heatmap`, used for `Slice` indexing
    pub fn start(mut self, time: Instant) -> Self {
        self.start = time;
        self
    }

    /// creates the `Heatmap` from the `Config`
    pub fn build(self) -> Option<Heatmap> {
        Heatmap::configured(self)
    }
}


#[derive(Clone, Copy)]
struct Counters {
    entries_total: u64,
}

impl Default for Counters {
    fn default() -> Counters {
        Counters { entries_total: 0 }
    }
}

impl Counters {
    pub fn new() -> Counters {
        Default::default()
    }

    pub fn clear(&mut self) {
        self.entries_total = 0;
    }
}

#[derive(Clone)]
struct Data {
    data: Vec<Histogram>,
    counters: Counters,
    iterator: usize,
    start: Instant,
    stop: Instant,
}

#[derive(Clone, Copy)]
struct Properties;

/// main datastructure of `Heatmap`
#[derive(Clone)]
pub struct Heatmap {
    config: Config,
    data: Data,
    properties: Properties,
}

/// a `Histogram` with time boundaries
#[derive(Clone)]
pub struct Slice {
    start: Instant,
    stop: Instant,
    histogram: Histogram,
}

impl Slice {
    /// returns the start time of the `Slice`
    pub fn start(&self) -> Instant {
        self.start
    }

    /// returns the stop time of the `Slice`
    pub fn stop(&self) -> Instant {
        self.stop
    }

    /// returns the `Histogram` for the `Slice`
    pub fn histogram(self) -> Histogram {
        self.histogram
    }
}

/// Iterator over a `Heatmap`'s `Slice`s
pub struct Iter<'a> {
    heatmap: &'a Heatmap,
    index: usize,
}

impl<'a> Iter<'a> {
    fn new(heatmap: &'a Heatmap) -> Iter<'a> {
        Iter {
            heatmap: heatmap,
            index: 0,
        }
    }
}

impl<'a> Iterator for Iter<'a> {
    type Item = Slice;

    fn next(&mut self) -> Option<Slice> {
        if self.index == (self.heatmap.config.num_slices as usize) {
            None
        } else {
            let start = self.heatmap.data.start +
                        (self.heatmap.config.slice_duration * self.index as u32);
            let current = self.index;
            self.index += 1;
            Some(Slice {
                start: start,
                stop: start + self.heatmap.config.slice_duration,
                histogram: self.heatmap.data.data[current].clone(),
            })
        }
    }
}

impl<'a> IntoIterator for &'a Heatmap {
    type Item = Slice;
    type IntoIter = Iter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        Iter::new(self)
    }
}

impl Default for Heatmap {
    fn default() -> Heatmap {
        Heatmap::configured(Config::new()).unwrap()
    }
}

impl Heatmap {
    /// create a new Heatmap with defaults
    ///
    /// # Example
    /// ```
    /// # use heatmap::Heatmap;
    /// let mut h = Heatmap::new();
    /// ```
    pub fn new() -> Heatmap {
        Default::default()
    }

    /// configure and build a new Heatmap
    ///
    /// # Example
    /// ```
    /// # use heatmap::Heatmap;
    /// let mut heatmap = Heatmap::configure()
    ///     .precision(4) // set precision to 4 digits
    ///     .max_value(1_000_000_000) // store values up to 1 Million
    ///     .slice_duration(std::time::Duration::new(1, 0)) // 1 second slices
    ///     .num_slices(300) // 300 slices => 5 minutes of records
    ///     .build() // create the Heatmap
    ///     .unwrap();
    /// ```
    pub fn configure() -> Config {
        Config::default()
    }

    // internal function to build a configured `Heatmap`
    fn configured(config: Config) -> Option<Heatmap> {
        let mut data = Vec::new();

        for _ in 0..config.num_slices {
            data.push(Histogram::configure()
                .max_value(config.max_value)
                .precision(config.precision)
                .max_memory(config.max_memory / config.num_slices as u32)
                .build()
                .unwrap());
        }

        let start = config.start;

        Some(Heatmap {
            config: config,
            data: Data {
                data: data,
                counters: Counters::new(),
                iterator: 0,
                start: start,
                stop: start + (config.slice_duration * config.num_slices as u32),
            },
            properties: Properties,
        })
    }

    /// clear the heatmap data
    ///
    /// # Example
    /// ```
    /// # use heatmap::Heatmap;
    /// let mut h = Heatmap::new();
    ///
    /// h.increment(std::time::Instant::now(), 1);
    /// assert_eq!(h.entries(), 1);
    /// h.clear();
    /// assert_eq!(h.entries(), 0);
    /// ```
    pub fn clear(&mut self) {
        for i in 0..self.config.num_slices {
            self.data.data[i].clear();
        }

        self.data.counters.clear();
        self.data.start = Instant::now();
        self.data.stop = self.data.start +
                         (self.config.slice_duration * self.config.num_slices as u32);
    }

    /// increment the count for a value at a time
    ///
    /// # Example
    /// ```
    /// extern crate heatmap;
    ///
    /// let mut h = heatmap::Heatmap::new();
    ///
    /// h.increment(std::time::Instant::now(), 1);
    /// assert_eq!(h.entries(), 1);
    pub fn increment(&mut self, time: Instant, value: u64) -> Result<(), &'static str> {
        self.increment_by(time, value, 1_u64)
    }

    /// increment additional counts for value at a time
    ///
    /// # Example
    /// ```
    /// extern crate heatmap;
    ///
    /// let mut h = heatmap::Heatmap::new();
    ///
    /// h.increment_by(std::time::Instant::now(), 1, 1);
    /// assert_eq!(h.entries(), 1);
    ///
    /// h.increment_by(std::time::Instant::now(), 2, 2);
    /// assert_eq!(h.entries(), 3);
    ///
    /// h.increment_by(std::time::Instant::now(), 10, 10);
    /// assert_eq!(h.entries(), 13);
    /// ```
    pub fn increment_by(&mut self,
                        time: Instant,
                        value: u64,
                        count: u64)
                        -> Result<(), &'static str> {
        self.data.counters.entries_total = self.data.counters.entries_total.saturating_add(count);

        match self.histogram_index(time) {
            Ok(histogram_index) => self.data.data[histogram_index].increment_by(value, count),
            Err(e) => Err(e),
        }
    }

    /// get the count of items at a quantized time-value point
    pub fn get(&mut self, time: Instant, value: u64) -> Result<u64, &'static str> {
        match self.histogram_index(time) {
            Ok(histogram_index) => {
                match self.data.data[histogram_index].get(value) {
                    Some(count) => Ok(count),
                    None => Err("histogram didn't have"),
                }
            }
            Err(e) => Err(e),
        }
    }



    /// internal function to find the index of the histogram in the heatmap
    fn histogram_index(&mut self, time: Instant) -> Result<usize, &'static str> {
        if time < self.data.start {
            return Err("sample too early");
        } else if time > self.data.stop {
            return Err("sample too late");
        }
        let t = time.duration_since(self.data.start);
        let index: usize = cycles(t, self.config.slice_duration).floor() as usize;
        Ok(index)
    }

    /// return the number of entries in the Histogram
    ///
    /// # Example
    /// ```
    /// extern crate heatmap;
    ///
    /// let mut h = heatmap::Heatmap::new();
    ///
    /// assert_eq!(h.entries(), 0);
    /// h.increment_by(std::time::Instant::now(), 1, 1);
    /// assert_eq!(h.entries(), 1);
    /// ```
    pub fn entries(&self) -> u64 {
        self.data.counters.entries_total
    }

    /// merge one Heatmap into another Heatmap
    ///
    /// # Example
    /// ```
    /// extern crate heatmap;
    ///
    /// let mut a = heatmap::Heatmap::configure()
    ///     .num_slices(60)
    ///     .slice_duration(std::time::Duration::new(1, 0))
    ///     .build()
    ///     .unwrap();
    ///
    /// let mut b = heatmap::Heatmap::new();
    ///
    /// assert_eq!(a.entries(), 0);
    /// assert_eq!(b.entries(), 0);
    ///
    /// let t0 = std::time::Instant::now();
    /// let t1 = t0 + std::time::Duration::new(1, 0);
    ///
    /// let _ = a.increment(t0, 1);
    /// let _ = b.increment(t0, 1);
    ///
    /// assert_eq!(a.entries(), 1);
    /// assert_eq!(b.entries(), 1);
    ///
    /// a.merge(&mut b);
    ///
    /// assert_eq!(a.entries(), 2);
    /// assert_eq!(a.get(t0, 1).unwrap(), 2);
    /// assert_eq!(a.get(t0, 2).unwrap(), 0);
    /// assert_eq!(a.get(t1, 1).unwrap(), 0);
    /// ```
    pub fn merge(&mut self, other: &Heatmap) {
        for slice in other.into_iter() {
            let slice = slice.clone();
            let start = slice.start();
            for bucket in &slice.histogram {
                let _ = self.increment_by(start, bucket.value(), bucket.count());
            }
        }
    }

    /// save the `Heatmap` to disk. NOTE: format may change in future
    pub fn save(&self, file: String) {
        let mut file_handle = File::create(file.clone()).unwrap();

        let config = format!("{} {} {} {:?} {} {:?}\n",
                             self.config.precision,
                             self.config.max_memory,
                             self.config.max_value,
                             self.config.slice_duration,
                             self.config.num_slices,
                             self.config.start)
            .into_bytes();
        let _ = file_handle.write_all(&config);

        for slice in self.into_iter() {
            let histogram = slice.histogram.clone();
            for bucket in &histogram {
                if bucket.count() > 0 {
                    let line = format!("{:?} {} {}\n", slice.start, bucket.value(), bucket.count())
                        .into_bytes();
                    let _ = file_handle.write_all(&line);
                }
            }
        }
    }

    // /// load the `Heatmap` from file. NOTE: format may change in future
    // pub fn load(file: String) -> Heatmap {
    //     let file_handle = File::open(file.clone()).unwrap();

    //     let reader = BufReader::new(&file_handle);

    //     let mut lines = reader.lines();

    //     let config = lines.next().unwrap().unwrap();
    //     let config_tokens: Vec<&str> = config.split_whitespace().collect();

    //     let precision: u32 = config_tokens[0].parse().unwrap();
    //     let max_memory: u32 = config_tokens[1].parse().unwrap();
    //     let max_value: u64 = config_tokens[2].parse().unwrap();
    //     let slice_duration: u64 = config_tokens[3].parse().unwrap();
    //     let num_slices: usize = config_tokens[4].parse().unwrap();
    //     let start: u64 = config_tokens[5].parse().unwrap();

    //     let mut heatmap = Heatmap::configure()
    //         .precision(precision)
    //         .max_memory(max_memory)
    //         .max_value(max_value)
    //         .slice_duration(slice_duration)
    //         .num_slices(num_slices)
    //         .start(start)
    //         .build()
    //         .unwrap();

    //     for line in lines {
    //         if let Ok(s) = line {
    //             let tokens: Vec<&str> = s.split_whitespace().collect();
    //             if tokens.len() != 3 {
    //                 panic!("malformed heatmap file");
    //             }
    //             let start: u64 = tokens[0].parse().unwrap();
    //             let value: u64 = tokens[1].parse().unwrap();
    //             let count: u64 = tokens[2].parse().unwrap();
    //             let _ = heatmap.increment_by(start, value, count);
    //         }
    //     }

    //     heatmap
    // }

    /// returns the number of buckets per `Histogram` / `Slice`
    pub fn histogram_buckets(&self) -> u64 {
        self.data.data[0].clone().buckets_total()
    }

    /// returns the number of `Slice`s within `Heatmap`
    pub fn num_slices(&self) -> u64 {
        self.config.num_slices as u64
    }
}

fn cycles(duration: Duration, period: Duration) -> f64 {
    let d = duration.as_secs() as f64 + (duration.subsec_nanos() as f64 / 1_000_000_000.0);
    let p = period.as_secs() as f64 + (period.subsec_nanos() as f64 / 1_000_000_000.0);
    d / p
}

#[cfg(test)]
mod tests {
    use super::Heatmap;

    #[test]
    fn test_new_0() {
        let h = Heatmap::configure()
            .num_slices(60)
            .build()
            .unwrap();

        assert_eq!(h.num_slices(), 60);

        let h = Heatmap::configure()
            .num_slices(120)
            .build()
            .unwrap();

        assert_eq!(h.num_slices(), 120);
    }
}