legion_prof_viewer 0.8.1

Profiler UI frontend component for Legion Prof
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
use std::collections::BTreeMap;
use std::fmt;

pub use egui::{Color32, Rgba};
use serde::{Deserialize, Serialize};
use std::collections::BTreeSet;

use crate::timestamp::{Interval, Timestamp};

// We encode EntryID as i64 because it allows us to pack Summary into the
// value -1. Users shouldn't need to know about this and interact through the
// methods below, or via EntryIndex.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
pub struct EntryID(Vec<i64>);

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)]
pub enum EntryIndex {
    Summary,
    Slot(u64),
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DataSourceInfo {
    pub entry_info: EntryInfo,
    pub interval: Interval,
    pub tile_set: TileSet,
    pub field_schema: FieldSchema,

    #[serde(default)]
    pub warning_message: Option<String>,

    // Track the set of non-empty tiles in static profiles, so if a tile is
    // empty we can skip fetching it entirely. Users should leave this empty
    // and the archiver will fill it automatically.
    #[serde(default)]
    pub nonempty_tiles: NonemptyTiles,

    #[serde(default = "SampleFormat::center")]
    pub sample_format: SampleFormat,
}

impl DataSourceInfo {
    pub fn is_empty_tile(&self, entry_id: &EntryID, tile_id: TileID) -> bool {
        self.nonempty_tiles.is_empty_tile(entry_id, tile_id)
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub enum EntryInfo {
    Panel {
        short_name: String,
        long_name: String,
        summary: Option<Box<EntryInfo>>,
        slots: Vec<EntryInfo>,
    },
    Slot {
        short_name: String,
        long_name: String,
        max_rows: u64,
    },
    Summary {
        color: Color32,
    },
}

#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct NonemptyTiles(BTreeMap<EntryID, BTreeSet<TileID>>);

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

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

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    pub fn append(&mut self, other: &mut NonemptyTiles) {
        self.0.append(&mut other.0);
    }

    pub fn is_empty_tile(&self, entry_id: &EntryID, tile_id: TileID) -> bool {
        !self
            .0
            .get(entry_id)
            .is_none_or(|tiles| tiles.contains(&tile_id))
    }

    pub fn mark_nonempty(&mut self, entry_id: &EntryID, tile_id: TileID) {
        self.0
            .entry(entry_id.to_owned())
            .or_default()
            .insert(tile_id);
    }
}

#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Deserialize, Serialize)]
pub enum SampleFormat {
    Start,
    Center,
}

impl SampleFormat {
    // Required to make serde(default) happy, see: https://github.com/serde-rs/serde/issues/368
    pub(crate) const fn center() -> Self {
        Self::Center
    }
}

#[derive(Debug, Copy, Clone, PartialEq, PartialOrd, Default, Deserialize, Serialize)]
pub struct UtilPoint {
    pub time: Timestamp,
    pub util: f32,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ItemLink {
    pub item_uid: ItemUID,

    // Text to display for the item
    pub title: String,

    // Required to enable zoom/scroll-to-item
    pub interval: Interval,
    pub entry_id: EntryID,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)]
pub struct FieldID(usize);

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)]
pub struct FieldSchema {
    // Field names that may potentially exist on a given item. They are not
    // necessarily all present on any given item
    field_ids: BTreeMap<String, FieldID>,
    field_names: BTreeMap<FieldID, String>,
    searchable: BTreeSet<FieldID>,
}

impl FieldSchema {
    pub fn new() -> Self {
        Self {
            field_ids: BTreeMap::new(),
            field_names: BTreeMap::new(),
            searchable: BTreeSet::new(),
        }
    }

    pub fn insert(&mut self, field_name: String, searchable: bool) -> FieldID {
        if let Some(field_id) = self.field_ids.get(&field_name) {
            return *field_id;
        }

        let next_id = FieldID(
            self.field_names
                .last_key_value()
                .map(|(v, _)| v.0 + 1)
                .unwrap_or(0),
        );
        self.field_ids.insert(field_name.clone(), next_id);
        self.field_names.insert(next_id, field_name);
        if searchable {
            self.searchable.insert(next_id);
        }
        next_id
    }

    pub fn get_id(&self, field_name: &str) -> Option<FieldID> {
        self.field_ids.get(field_name).copied()
    }

    pub fn get_name(&self, field_id: FieldID) -> Option<&str> {
        self.field_names.get(&field_id).map(|x| x.as_str())
    }

    pub fn contains_id(&self, field_id: FieldID) -> bool {
        self.field_names.contains_key(&field_id)
    }

    pub fn contains_name(&self, field_name: &str) -> bool {
        self.field_ids.contains_key(field_name)
    }

    pub fn field_names(&self) -> &BTreeMap<FieldID, String> {
        &self.field_names
    }

    pub fn searchable(&self) -> &BTreeSet<FieldID> {
        &self.searchable
    }
}

impl Default for FieldSchema {
    fn default() -> Self {
        Self::new()
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub enum Field {
    I64(i64),
    U64(u64),
    String(String),
    Interval(Interval),
    ItemLink(ItemLink),
    Vec(Vec<Field>),
    Empty,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)]
pub struct ItemUID(pub u64);

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Item {
    pub item_uid: ItemUID,
    pub interval: Interval,
    pub color: Color32,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ItemField(
    pub FieldID,
    pub Field,
    #[serde(default)] pub Option<Color32>,
);

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ItemMeta {
    pub item_uid: ItemUID,
    // As opposed to the interval in Item, which may get expanded for
    // visibility, or sliced up into multiple tiles, this interval covers the
    // entire duration of the original item, unexpanded and unsliced.
    pub original_interval: Interval,
    pub title: String,
    pub fields: Vec<ItemField>,
}

#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Deserialize, Serialize)]
pub struct TileID(pub Interval);

#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Deserialize, Serialize)]
pub struct TileSet {
    pub tiles: Vec<Vec<TileID>>,
}

#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct SummaryTileData {
    pub utilization: Vec<UtilPoint>,
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct SummaryTile {
    pub entry_id: EntryID,
    pub tile_id: TileID,
    pub data: SummaryTileData,
}

#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct SlotTileData {
    pub items: Vec<Vec<Item>>, // row -> [item]
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct SlotTile {
    pub entry_id: EntryID,
    pub tile_id: TileID,
    pub data: SlotTileData,
}

impl SlotTile {
    pub fn is_empty(&self) -> bool {
        self.data.items.iter().all(|row| row.is_empty())
    }
}

#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct SlotMetaTileData {
    pub items: Vec<Vec<ItemMeta>>, // row -> [item]
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct SlotMetaTile {
    pub entry_id: EntryID,
    pub tile_id: TileID,
    pub data: SlotMetaTileData,
}

impl SlotMetaTile {
    pub fn is_empty(&self) -> bool {
        self.data.items.iter().all(|row| row.is_empty())
    }
}

#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct DataSourceDescription {
    pub source_locator: Vec<String>,
}

pub type Result<T> = std::result::Result<T, String>;

pub trait DataSource {
    fn fetch_description(&self) -> DataSourceDescription;
    fn fetch_info(&self) -> Result<DataSourceInfo>;
    fn fetch_summary_tile(
        &self,
        entry_id: &EntryID,
        tile_id: TileID,
        full: bool,
    ) -> Result<SummaryTile>;
    fn fetch_slot_tile(&self, entry_id: &EntryID, tile_id: TileID, full: bool) -> Result<SlotTile>;
    fn fetch_slot_meta_tile(
        &self,
        entry_id: &EntryID,
        tile_id: TileID,
        full: bool,
    ) -> Result<SlotMetaTile>;
}

impl EntryID {
    pub fn root() -> Self {
        Self(Vec::new())
    }

    pub fn summary(&self) -> Self {
        let mut result = self.clone();
        result.0.push(-1);
        result
    }

    pub fn child(&self, index: u64) -> Self {
        let mut result = self.clone();
        result
            .0
            .push(index.try_into().expect("unable to fit in i64"));
        result
    }

    pub fn level(&self) -> u64 {
        self.0.len() as u64
    }

    pub fn last_slot_index(&self) -> Option<u64> {
        let last = self.0.last()?;
        (*last).try_into().ok()
    }

    pub fn slot_index(&self, level: u64) -> Option<u64> {
        let last = self.0.get(level as usize)?;
        (*last).try_into().ok()
    }

    pub fn last_index(&self) -> Option<EntryIndex> {
        let last = self.0.last()?;
        Some(
            (*last)
                .try_into()
                .map_or(EntryIndex::Summary, EntryIndex::Slot),
        )
    }

    pub fn index(&self, level: u64) -> Option<EntryIndex> {
        let last = self.0.get(level as usize)?;
        Some(
            (*last)
                .try_into()
                .map_or(EntryIndex::Summary, EntryIndex::Slot),
        )
    }

    pub fn has_prefix(&self, prefix: &EntryID) -> bool {
        if prefix.0.len() > self.0.len() {
            return false;
        }
        for (a, b) in self.0.iter().zip(prefix.0.iter()) {
            if a != b {
                return false;
            }
        }
        true
    }

    pub fn from_slug(s: &str) -> std::result::Result<Self, std::num::ParseIntError> {
        let elts: std::result::Result<Vec<_>, _> = s.split('_').map(|x| x.parse::<i64>()).collect();
        Ok(Self(elts?))
    }
}

impl EntryInfo {
    pub fn get(&self, entry_id: &EntryID) -> Option<&EntryInfo> {
        let mut result = self;
        for i in 0..entry_id.level() {
            match (entry_id.index(i)?, result) {
                (EntryIndex::Summary, EntryInfo::Panel { summary, .. }) => {
                    return summary.as_deref();
                }
                (EntryIndex::Slot(j), EntryInfo::Panel { slots, .. }) => {
                    result = slots.get(j as usize)?;
                }
                _ => panic!("EntryID and EntryInfo do not match"),
            }
        }
        Some(result)
    }

    pub fn nodes(&self) -> u64 {
        if let EntryInfo::Panel { slots, .. } = self {
            slots.len() as u64
        } else {
            unreachable!()
        }
    }

    pub fn kinds(&self) -> Vec<String> {
        if let EntryInfo::Panel { slots: nodes, .. } = self {
            let mut result = Vec::new();
            let mut set = BTreeSet::new();
            for node in nodes {
                if let EntryInfo::Panel { slots: kinds, .. } = node {
                    for kind in kinds {
                        if let EntryInfo::Panel { short_name, .. } = kind {
                            if set.insert(short_name) {
                                result.push(short_name.clone());
                            }
                        } else {
                            unreachable!();
                        }
                    }
                } else {
                    unreachable!();
                }
            }
            return result;
        }
        unreachable!()
    }
}

#[derive(Debug)]
pub enum SlugParseError {
    ParseInt(std::num::ParseIntError),
    TooFewValues,
    TooManyValues,
}

impl fmt::Display for SlugParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            SlugParseError::ParseInt(..) => write!(f, "parse error"),
            SlugParseError::TooFewValues => write!(f, "too few values"),
            SlugParseError::TooManyValues => write!(f, "too many values"),
        }
    }
}

impl std::error::Error for SlugParseError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            SlugParseError::ParseInt(e) => Some(e),
            SlugParseError::TooFewValues => None,
            SlugParseError::TooManyValues => None,
        }
    }
}

impl From<std::num::ParseIntError> for SlugParseError {
    fn from(e: std::num::ParseIntError) -> SlugParseError {
        SlugParseError::ParseInt(e)
    }
}

impl TileID {
    pub fn from_slug(s: &str) -> std::result::Result<Self, SlugParseError> {
        let elts: std::result::Result<Vec<i64>, _> =
            s.split('_').map(|x| x.parse::<i64>()).collect();
        match elts?.as_slice() {
            [start, stop] => Ok(Self(Interval::new(Timestamp(*start), Timestamp(*stop)))),
            [_] => Err(SlugParseError::TooFewValues),
            [] => Err(SlugParseError::TooFewValues),
            _ => Err(SlugParseError::TooManyValues),
        }
    }
}

pub struct EntryIDSlug<'a>(pub &'a EntryID);

impl fmt::Display for EntryIDSlug<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        for (i, e) in self.0.0.iter().enumerate() {
            write!(f, "{}", e)?;
            if i < self.0.0.len() - 1 {
                write!(f, "_")?;
            }
        }
        Ok(())
    }
}

pub struct TileIDSlug(pub TileID);

impl fmt::Display for TileIDSlug {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0.0.start.0)?;
        write!(f, "_")?;
        write!(f, "{}", self.0.0.stop.0)
    }
}

// Private helpers for EntryID
impl EntryID {
    pub(crate) fn shift_level0(&self, level0_offset: i64) -> EntryID {
        assert!(!self.0.is_empty());
        assert_ne!(self.0[0], -1);
        let mut result = self.clone();
        result.0[0] += level0_offset;
        assert!(result.0[0] >= 0);
        result
    }
}