flamelens 0.4.0

Flamegraph viewer in the terminal
Documentation
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
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
use std::collections::{HashMap, HashSet};

use serde::Serialize;

pub type StackIdentifier = usize;
pub static ROOT: &str = "all";
pub static ROOT_ID: usize = 0;

#[derive(Serialize, Debug, Clone, PartialEq)]
pub struct StackInfo {
    pub id: StackIdentifier,
    pub line_index: usize,
    pub start_index: usize,
    pub end_index: usize,
    pub total_count: u64,
    pub self_count: u64,
    pub parent: Option<StackIdentifier>,
    pub children: Vec<StackIdentifier>,
    pub level: usize,
    pub width_factor: f64,
    pub hit: bool,
}

#[derive(Debug, Clone)]
pub struct SearchPattern {
    pub pattern: String,
    pub is_regex: bool,
    pub re: regex::Regex,
    pub is_manual: bool,
}

impl SearchPattern {
    pub fn new(pattern: &str, is_regex: bool, is_manual: bool) -> Result<Self, regex::Error> {
        let _pattern = if is_regex {
            pattern.to_string()
        } else {
            format!("^{}$", regex::escape(pattern))
        };
        let re = regex::Regex::new(&_pattern)?;
        Ok(Self {
            pattern: pattern.to_string(),
            is_regex,
            re,
            is_manual,
        })
    }
}

#[derive(Debug, Clone)]
pub struct Hits {
    coverage_count: u64,
    ids: Vec<StackIdentifier>,
}

#[derive(Serialize, Debug, Clone, Default)]
pub struct Count {
    pub total: u64,
    pub own: u64,
}

#[derive(Serialize, Debug, Clone)]
pub struct CountEntry {
    pub name: String,
    pub count: Count,
    pub visible: bool,
}

#[derive(Serialize, Debug, Clone, Eq, PartialEq, Copy)]
pub enum SortColumn {
    Total,
    Own,
}

#[derive(Serialize, Debug, Clone)]
pub struct Ordered {
    pub entries: Vec<CountEntry>,
    pub num_rows: usize,
    pub sorted_column: SortColumn,
    pub search_pattern_ignored_because_of_no_match: bool,
}

impl Ordered {
    pub fn set_search_pattern(&mut self, p: &SearchPattern) {
        if p.is_manual {
            self.entries.iter_mut().for_each(|entry| {
                entry.visible = p.re.is_match(&entry.name);
            });
            self.num_rows = self.entries.iter().filter(|entry| entry.visible).count();
            if self.num_rows == 0 {
                self.clear_search_pattern();
                self.search_pattern_ignored_because_of_no_match = true;
            }
        } else {
            self.clear_search_pattern();
        }
    }

    pub fn clear_search_pattern(&mut self) {
        self.entries.iter_mut().for_each(|entry| {
            entry.visible = true;
        });
        self.num_rows = self.entries.len();
        self.search_pattern_ignored_because_of_no_match = false;
    }

    pub fn set_sort_column(&mut self, column: SortColumn) {
        if column == self.sorted_column {
            return;
        }
        self.sorted_column = column;
        match column {
            SortColumn::Total => {
                self.entries
                    .sort_by_key(|entry| (entry.count.total, entry.name.clone()));
            }
            SortColumn::Own => {
                self.entries
                    .sort_by_key(|entry| (entry.count.own, entry.name.clone()));
            }
        }
        self.entries.reverse();
    }
}

#[derive(Debug, Clone)]
pub struct FlameGraph {
    data: String,
    stacks: Vec<StackInfo>,
    levels: Vec<Vec<StackIdentifier>>,
    pub ordered_stacks: Ordered,
    hits: Option<Hits>,
    sorted: bool,
}

impl FlameGraph {
    pub fn from_string(mut content: String, sorted: bool) -> Self {
        // Make sure content ends with newline to simplify parsing
        if !content.ends_with('\n') {
            content.push('\n');
        }
        let mut stacks = Vec::<StackInfo>::new();
        stacks.push(StackInfo {
            id: ROOT_ID,
            line_index: 0,
            start_index: 0,
            end_index: 0,
            total_count: 0,
            self_count: 0,
            width_factor: 0.0,
            parent: None,
            children: Vec::<StackIdentifier>::new(),
            level: 0,
            hit: false,
        });
        let mut last_line_index = 0;
        let mut counts: HashMap<String, Count> = HashMap::new();
        for line_index in content
            .char_indices()
            .filter(|(_, c)| *c == '\n')
            .map(|(i, _)| i)
        {
            let line = &content[last_line_index..line_index];
            #[allow(clippy::unnecessary_unwrap)]
            let line_and_count = match line.rsplit_once(' ') {
                Some((line, count)) => {
                    let parsed_count = count.parse::<u64>();
                    if line.is_empty() || parsed_count.is_err() {
                        None
                    } else {
                        Some((line, parsed_count.unwrap()))
                    }
                }
                _ => None,
            };
            if line_and_count.is_none() || line.starts_with('#') {
                last_line_index = line_index + 1;
                continue;
            }
            let (line, count) = line_and_count.unwrap();

            stacks[ROOT_ID].total_count += count;
            let mut parent_id = ROOT_ID;
            let mut level = 1;
            let mut last_delim_index = 0;
            let mut counted_names = HashSet::<String>::new();
            for delim_index in line
                .char_indices()
                .filter(|(_, c)| *c == ';')
                .map(|(i, _)| i)
            {
                let stack_id = FlameGraph::update_one(
                    &mut stacks,
                    &mut counts,
                    &mut counted_names,
                    &content,
                    count,
                    last_line_index,
                    last_line_index + last_delim_index,
                    last_line_index + delim_index,
                    parent_id,
                    level,
                    false,
                );
                parent_id = stack_id;
                level += 1;
                last_delim_index = delim_index + 1;
            }
            FlameGraph::update_one(
                &mut stacks,
                &mut counts,
                &mut counted_names,
                &content,
                count,
                last_line_index,
                last_line_index + last_delim_index,
                last_line_index + line.len(),
                parent_id,
                level,
                true,
            );
            last_line_index = line_index + 1;
        }

        let ordered = FlameGraph::get_ordered_stacks(&counts);
        let mut out = Self {
            data: content,
            stacks,
            levels: vec![],
            ordered_stacks: ordered,
            hits: None,
            sorted,
        };
        out.populate_levels(&ROOT_ID, 0, None);
        out
    }

    fn get_ordered_stacks(counts: &HashMap<String, Count>) -> Ordered {
        let mut counts = counts.iter().collect::<Vec<_>>();
        counts.sort_by_key(|(short_name, count)| (count.own, short_name.to_string()));
        let ordered_by_self_count = counts
            .iter()
            .rev()
            .map(|x| CountEntry {
                name: x.0.to_string(),
                count: x.1.clone(),
                visible: true,
            })
            .collect::<Vec<_>>();
        let num_rows = ordered_by_self_count.len();
        Ordered {
            entries: ordered_by_self_count,
            num_rows,
            sorted_column: SortColumn::Own,
            search_pattern_ignored_because_of_no_match: false,
        }
    }

    #[allow(clippy::too_many_arguments)]
    fn update_one(
        stacks: &mut Vec<StackInfo>,
        counts: &mut HashMap<String, Count>,
        counted_names: &mut HashSet<String>,
        content: &str,
        count: u64,
        line_index: usize,
        start_index: usize,
        end_index: usize,
        parent_id: StackIdentifier,
        level: usize,
        is_self: bool,
    ) -> StackIdentifier {
        let short_name = &content[start_index..end_index];

        // Invariant: parent always exists. We can just check the short name to
        // check if the parent already contains the child, since the prior
        // prefixes should always match (definition of a parent).
        let parent_stack = stacks.get(parent_id).unwrap();

        // Add or update the current stack
        let current_stack_id_if_exists = parent_stack
            .children
            .iter()
            .find(|child_id| {
                let child = stacks.get(**child_id).unwrap();
                &content[child.start_index..child.end_index] == short_name
            })
            .cloned();
        let stack_id = if let Some(stack_id) = current_stack_id_if_exists {
            stack_id
        } else {
            stacks.push(StackInfo {
                id: stacks.len(),
                line_index,
                start_index,
                end_index,
                total_count: 0,
                self_count: 0,
                width_factor: 0.0,
                parent: Some(parent_id),
                children: Vec::<StackIdentifier>::new(),
                level,
                hit: false,
            });
            let stack_id = stacks.len() - 1;
            stacks.get_mut(parent_id).unwrap().children.push(stack_id);
            stack_id
        };
        let info = stacks.get_mut(stack_id).unwrap();
        info.total_count += count;
        if is_self {
            info.self_count += count;
        }

        // Update summarized counts
        let summarized_count = counts.entry(short_name.to_string()).or_default();
        if !counted_names.contains(short_name) {
            counted_names.insert(short_name.to_string());
            summarized_count.total += count;
        }
        if is_self {
            summarized_count.own += count;
        }

        stack_id
    }

    fn populate_levels(
        &mut self,
        stack_id: &StackIdentifier,
        level: usize,
        parent_total_count_and_width_factor: Option<(u64, f64)>,
    ) {
        // Update levels
        if self.levels.len() <= level {
            self.levels.push(vec![]);
        }
        self.levels[level].push(*stack_id);

        // Calculate width_factor of the current stack
        let stack = self.stacks.get(*stack_id).unwrap();
        let total_count = stack.total_count;
        let width_factor = if let Some((parent_total_count, parent_width_factor)) =
            parent_total_count_and_width_factor
        {
            parent_width_factor * (total_count as f64 / parent_total_count as f64)
        } else {
            1.0
        };

        // Sort children
        let sorted_children = if self.sorted {
            let mut sorted_children = stack.children.clone();
            sorted_children.sort_by_key(|child_id| {
                self.stacks
                    .get(*child_id)
                    .map(|child| child.total_count)
                    .unwrap_or(0)
            });
            sorted_children.reverse();
            Some(sorted_children)
        } else {
            None
        };

        // Make the updates to the current stack
        let stack = self.stacks.get_mut(*stack_id).unwrap();
        stack.width_factor = width_factor;
        if let Some(sorted_children) = sorted_children {
            stack.children = sorted_children;
        }

        // Move on to children
        for child_id in stack.children.clone().iter() {
            self.populate_levels(child_id, level + 1, Some((total_count, width_factor)));
        }
    }

    pub fn get_stack(&self, stack_id: &StackIdentifier) -> Option<&StackInfo> {
        self.stacks.get(*stack_id)
    }

    pub fn get_stack_short_name(&self, stack_id: &StackIdentifier) -> Option<&str> {
        self.get_stack(stack_id)
            .map(|stack| self.get_stack_short_name_from_info(stack))
    }

    pub fn get_stack_full_name(&self, stack_id: &StackIdentifier) -> Option<&str> {
        self.get_stack(stack_id)
            .map(|stack| self.get_stack_full_name_from_info(stack))
    }

    pub fn get_stack_short_name_from_info(&self, stack: &StackInfo) -> &str {
        if stack.id == ROOT_ID {
            ROOT
        } else {
            &self.data[stack.start_index..stack.end_index]
        }
    }

    pub fn get_stack_full_name_from_info(&self, stack: &StackInfo) -> &str {
        if stack.id == ROOT_ID {
            ROOT
        } else {
            &self.data[stack.line_index..stack.end_index]
        }
    }

    pub fn get_stack_by_full_name(&self, full_name: &str) -> Option<&StackInfo> {
        self.stacks
            .iter()
            .find(|stack| self.get_stack_full_name_from_info(stack) == full_name)
    }

    pub fn get_stack_id_by_full_name(&self, full_name: &str) -> Option<StackIdentifier> {
        self.get_stack_by_full_name(full_name).map(|stack| stack.id)
    }

    pub fn get_stacks_at_level(&self, level: usize) -> Option<&Vec<StackIdentifier>> {
        self.levels.get(level)
    }

    pub fn root(&self) -> &StackInfo {
        self.get_stack(&ROOT_ID).unwrap()
    }

    pub fn total_count(&self) -> u64 {
        self.root().total_count
    }

    pub fn get_num_levels(&self) -> usize {
        self.levels.len()
    }

    pub fn get_ancestors(&self, stack_id: &StackIdentifier) -> Vec<StackIdentifier> {
        let mut ancestors = vec![];
        let mut current_id = *stack_id;
        while let Some(stack) = self.get_stack(&current_id) {
            ancestors.push(current_id);
            if let Some(parent_id) = stack.parent {
                current_id = parent_id;
            } else {
                break;
            }
        }
        ancestors
    }

    pub fn get_descendants(&self, stack_id: &StackIdentifier) -> Vec<StackIdentifier> {
        let mut descendants = vec![];
        let mut stack_ids = vec![*stack_id];
        while let Some(stack_id) = stack_ids.pop() {
            descendants.push(stack_id);
            if let Some(stack) = self.get_stack(&stack_id) {
                stack_ids.extend(stack.children.iter().copied());
            }
        }
        descendants
    }

    pub fn set_hits(&mut self, p: &SearchPattern) {
        self.stacks.iter_mut().for_each(|stack| {
            stack.hit =
                p.re.is_match(&self.data[stack.start_index..stack.end_index]);
        });
        self.hits = Some(Hits {
            coverage_count: self._count_hit_coverage(ROOT_ID),
            ids: self._collect_hit_ids(),
        });
        self.ordered_stacks.set_search_pattern(p);
    }

    pub fn clear_hits(&mut self) {
        self.stacks.iter_mut().for_each(|stack| stack.hit = false);
        self.hits = None;
        self.ordered_stacks.clear_search_pattern();
    }

    pub fn hit_coverage_count(&self) -> Option<u64> {
        self.hits.as_ref().map(|h| h.coverage_count)
    }

    pub fn hit_ids(&self) -> Option<&Vec<StackIdentifier>> {
        self.hits.as_ref().map(|h| &h.ids)
    }

    fn _count_hit_coverage(&self, stack_id: StackIdentifier) -> u64 {
        let stack = self.get_stack(&stack_id).unwrap();
        if stack.hit {
            return stack.total_count;
        }
        let mut count = 0;
        for child_id in stack.children.iter() {
            count += self._count_hit_coverage(*child_id);
        }
        count
    }

    fn _collect_hit_ids(&self) -> Vec<StackIdentifier> {
        let mut hits = vec![];
        for level in self.levels.iter() {
            for stacks in level.iter() {
                if let Some(stack) = self.get_stack(stacks) {
                    if stack.hit {
                        hits.push(*stacks);
                    }
                }
            }
        }
        hits
    }
}

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

    const UPDATE_FIXTURES: bool = false;

    #[derive(Serialize, Debug, Clone, PartialEq)]
    pub struct StackInfoReadable<'a> {
        pub id: StackIdentifier,
        pub line_index: usize,
        pub start_index: usize,
        pub end_index: usize,
        pub total_count: u64,
        pub self_count: u64,
        pub parent: Option<StackIdentifier>,
        pub children: Vec<StackIdentifier>,
        pub level: usize,
        pub width_factor: f64,
        pub hit: bool,
        pub short_name: &'a str,
        pub full_name: &'a str,
    }

    impl FlameGraph {
        pub fn to_readable_stacks(&self) -> Vec<StackInfoReadable<'_>> {
            self.stacks
                .iter()
                .map(|stack| StackInfoReadable {
                    id: stack.id,
                    line_index: stack.line_index,
                    start_index: stack.start_index,
                    end_index: stack.end_index,
                    total_count: stack.total_count,
                    self_count: stack.self_count,
                    parent: stack.parent,
                    children: stack.children.clone(),
                    level: stack.level,
                    width_factor: stack.width_factor,
                    hit: stack.hit,
                    short_name: self.get_stack_short_name_from_info(stack),
                    full_name: self.get_stack_full_name_from_info(stack),
                })
                .collect()
        }
    }

    fn check_result<P: AsRef<std::path::Path>>(data_filename: P) -> FlameGraph {
        let content = std::fs::read_to_string(&data_filename).unwrap();
        let fg = FlameGraph::from_string(content, true);

        // Location to store all the fixtures for this test data
        let tag = data_filename
            .as_ref()
            .file_stem()
            .unwrap()
            .to_str()
            .unwrap();
        let fixture_dir = format!("tests/fixtures/{}", tag);

        // Check expected stacks
        let serialized = serde_json::to_string_pretty(&fg.to_readable_stacks()).unwrap();
        let filename = format!("{}/expected_stacks.json", fixture_dir.as_str());
        if UPDATE_FIXTURES {
            std::fs::create_dir_all(fixture_dir.as_str()).unwrap();
            std::fs::write(&filename, serialized.clone()).unwrap();
        }
        let expected = std::fs::read_to_string(&filename).unwrap();
        assert_eq!(serialized, expected);

        // Check ordered counts
        let serialized = serde_json::to_string_pretty(&fg.ordered_stacks).unwrap();
        let filename = format!("{}/expected_ordered_counts.json", fixture_dir.as_str());
        if UPDATE_FIXTURES {
            std::fs::create_dir_all(fixture_dir).unwrap();
            std::fs::write(&filename, serialized.clone()).unwrap();
        }
        let expected = std::fs::read_to_string(&filename).unwrap();
        assert_eq!(serialized, expected);

        assert_eq!(UPDATE_FIXTURES, false, "Set UPDATE_FIXTURES to false");
        fg
    }

    #[test]
    fn test_simple() {
        let fg = check_result("tests/data/py-spy-simple.txt");
        assert_eq!(fg.total_count(), 657);
        assert_eq!(
            *fg.root(),
            StackInfo {
                id: ROOT_ID,
                line_index: 0,
                start_index: 0,
                end_index: 0,
                total_count: 657,
                self_count: 0,
                width_factor: 1.0,
                parent: None,
                children: vec![3, 1, 5],
                level: 0,
                hit: false,
            }
        );
    }

    #[test]
    fn test_no_name_count() {
        let fg = check_result("tests/data/invalid-lines.txt");
        assert_eq!(fg.total_count(), 428);
    }

    #[test]
    fn test_ignore_lines_starting_with_hash() {
        check_result("tests/data/ignore-metadata-lines.txt");
    }

    #[test]
    fn test_recursive() {
        check_result("tests/data/recursive.txt");
    }
}