pagegraph 0.1.3

Rust library for analyzing PageGraph files
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
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
use std::fs::File;
use std::io::BufReader;
use std::collections::HashMap;
use std::convert::TryFrom;

use xml::reader::{ EventReader, XmlEvent };
use petgraph::graphmap::DiGraphMap;

use crate::{ graph, types };

/// Reads a PageGraph from a GraphML-formatted file.
pub fn read_from_file(file: &str) -> graph::PageGraph {
    let file = File::open(file).unwrap();
    let file = BufReader::new(file);

    let mut parser = EventReader::new(file);

    if let Ok(XmlEvent::StartDocument { .. }) = parser.next() {
        return parse_xml_document(&mut parser);
    } else {
        panic!("couldn't find start of document");
    }
}

fn parse_xml_document<R: std::io::Read>(parser: &mut EventReader<R>) -> graph::PageGraph {
    if let Ok(XmlEvent::StartElement { name, .. }) = parser.next() {
        if name.local_name == "graphml" {
            return parse_graphml(parser);
        } else {
            panic!("expected graphml element");
        }
    } else {
        panic!("could not find graphml element");
    }
}

/// For simple data items of the form `<local_name>This is the return value</local_name>`
fn parse_str_data<R: std::io::Read>(
    parser: &mut EventReader<R>,
    _attributes: Vec<xml::attribute::OwnedAttribute>,
    local_name: &str,
) -> String {
    let mut result = None;

    while let Ok(e) = parser.next() {
        match e {
            XmlEvent::EndElement { name } => {
                if name.local_name == local_name {
                    break
                }
            }
            XmlEvent::Characters(chars) => result = Some(chars),
            XmlEvent::Whitespace(_) => (),
            o => {panic!("Unexpected {:?} in `{}`", o, local_name)}
        }
    }

    return result.unwrap();
}

fn build_desc<R: std::io::Read>(
    parser: &mut EventReader<R>,
    _attributes: Vec<xml::attribute::OwnedAttribute>
) -> graph::PageGraphDescriptor {
    const STR_REP: &'static str = "desc";

    let mut version = None;
    let mut about = None;
    let mut url = None;
    let mut is_root = None;
    let mut frame_id = None;
    let mut time = None;

    while let Ok(e) = parser.next() {
        match e {
            XmlEvent::EndElement { name } => {
                if name.local_name == STR_REP {
                    break
                }
            }
            XmlEvent::StartElement { name, attributes, namespace: _ } => {
                let local_name = &name.local_name[..];
                match local_name {
                    "version" => version = Some(parse_str_data(parser, attributes, local_name)),
                    "about" => about = Some(parse_str_data(parser, attributes, local_name)),
                    "url" => url = Some(parse_str_data(parser, attributes, local_name)),
                    "is_root" => is_root = Some(parse_str_data(parser, attributes, local_name)),
                    "frame_id" => frame_id = Some(parse_str_data(parser, attributes, local_name)),
                    "time" => time = Some(build_time(parser, attributes)),
                    o => panic!("unexpected {:?} in `{}`", o, STR_REP),
                }
            }
            XmlEvent::Whitespace(_) => (),
            o => {panic!("Unexpected {:?} in `{}`", o, STR_REP)}
        }
    }

    graph::PageGraphDescriptor {
        version: version.unwrap(),
        about: about.unwrap(),
        url: url.unwrap(),
        is_root: is_root.unwrap().parse::<bool>().unwrap(),
        frame_id: graph::FrameId::try_from(frame_id.unwrap().as_str()).unwrap(),
        time: time.unwrap(),
    }
}

/// For the `time` element within `desc`.
fn build_time<R: std::io::Read>(
    parser: &mut EventReader<R>,
    _attributes: Vec<xml::attribute::OwnedAttribute>
) -> graph::PageGraphTime {
    const STR_REP: &str = "time";

    let mut start = None;
    let mut end = None;

    while let Ok(e) = parser.next() {
        match e {
            XmlEvent::EndElement { name } => {
                if name.local_name == STR_REP {
                    break
                }
            }
            XmlEvent::StartElement { name, attributes, namespace: _ } => {
                let local_name = &name.local_name[..];
                match local_name {
                    "start" => start = Some(parse_str_data(parser, attributes, local_name)),
                    "end" => end = Some(parse_str_data(parser, attributes, local_name)),
                    o => panic!("unexpected {:?} in `{}`", o, STR_REP),
                }
            }
            XmlEvent::Whitespace(_) => (),
            o => {panic!("Unexpected {:?} in `{}`", o, STR_REP)}
        }
    }

    graph::PageGraphTime {
        start: start.unwrap().parse::<u64>().unwrap(),
        end: end.unwrap().parse::<u64>().unwrap(),
    }
}

fn parse_graphml<R: std::io::Read>(parser: &mut EventReader<R>) -> graph::PageGraph {
    let mut desc = None;
    let mut node_items = HashMap::new();
    let mut edge_items = HashMap::new();
    while let Ok(e) = parser.next() {
        match e {
            XmlEvent::StartElement { name, attributes, namespace: _ } => {
                match &name.local_name[..] {
                    "key" => {
                        let (for_type, id, key) = build_key(parser, attributes);
                        match for_type {
                            KeyItemFor::Node => node_items.insert(id, key),
                            KeyItemFor::Edge => edge_items.insert(id, key),
                        };
                    }
                    "desc" => desc = Some(build_desc(parser, attributes)),
                    "graph" => {
                        break;
                    }
                    _ => println!("Unhandled local name: {}", name.local_name),
                }
            }
            XmlEvent::EndElement { name } => {
                if name.local_name == "graphml" {
                    panic!("graphml ended without graph definition");
                } else {
                    panic!("unexpected end of element {}", name);
                }
            }
            XmlEvent::Whitespace(_) => (),
            o => {panic!("unexpected {:?} in `graphml`", o)}
        }
    }

    let key = KeyModel { node_items, edge_items };
    let graph = Some(build_graph(parser, &key, desc.expect("could not find desc")));

    while let Ok(e) = parser.next() {
        match e {
            XmlEvent::StartElement { name, attributes: _, namespace: _ } => {
                match &name.local_name[..] {
                    "key" => {
                        panic!("key item located after graph");
                    }
                    "graph" => {
                        panic!("more than one graph item not supported");
                    }
                    _ => println!("Unhandled local name: {}", name.local_name),
                }
            }
            XmlEvent::EndElement { name } => {
                if name.local_name == "graphml" {
                    break
                }
            }
            XmlEvent::Whitespace(_) => (),
            o => {panic!("Unexpected {:?} in `graphml`", o)}
        }
    }

    graph.expect("could not find graph")
}

struct KeyModel {
    node_items: HashMap<String, KeyItem>,
    edge_items: HashMap<String, KeyItem>,
}

struct KeyItem {
    id: String,
    _attr_type: String,
}

enum KeyItemFor {
    Node,
    Edge,
}

impl TryFrom<&str> for KeyItemFor {
    type Error = ();

    fn try_from(v: &str) -> Result<Self, ()> {
        match v {
            "node" => Ok(Self::Node),
            "edge" => Ok(Self::Edge),
            _ => Err(())
        }
    }
}

fn build_key<R: std::io::Read>(
    parser: &mut EventReader<R>,
    attributes: Vec<xml::attribute::OwnedAttribute>
) -> (KeyItemFor, String, KeyItem) {
    let mut id = None;
    let mut for_type = None;
    let mut attr_name = None;
    let mut attr_type = None;
    for attribute in attributes {
        let name = attribute.name.local_name;
        match &name[..] {
            "id" => id = Some(attribute.value),
            "for" => for_type = Some(attribute.value),
            "attr.name" => attr_name = Some(attribute.value),
            "attr.type" => attr_type = Some(attribute.value),
            _ => panic!("Unexpected value in key: {}", &name),
        }
    }
    let key_item = KeyItem {
        id: id.expect("couldn't find `id` value on key"),
        _attr_type: attr_type.expect("couldn't find `attr.type` value on key"),
    };

    if let Ok(XmlEvent::EndElement { name }) = parser.next() {
        if &name.local_name != "key" {
            panic!("expected end of key element");
        }
    } else {
        panic!("could not find end of key element");
    }

    (
        KeyItemFor::try_from(&for_type.expect("couldn't find `for` value on key")[..])
            .expect("unexpected `for` value on key"),
        attr_name.expect("couldn't find `attr.name` value on key"),
        key_item,
    )
}

fn build_graph<R: std::io::Read>(parser: &mut EventReader<R>, key: &KeyModel, desc: graph::PageGraphDescriptor) -> graph::PageGraph {
    const STR_REP: &'static str = "graph";

    let mut edges = HashMap::new();
    let mut nodes = HashMap::new();
    let mut graph = DiGraphMap::<graph::NodeId, Vec<graph::EdgeId>>::new();

    while let Ok(e) = parser.next() {
        match e {
            XmlEvent::StartElement { name, attributes, namespace: _ } => {
                match &name.local_name[..] {
                    "node" => {
                        let node = build_node(parser, attributes, &key.node_items);
                        graph.add_node(node.id);
                        nodes.insert(node.id, node);
                    }
                    "edge" => {
                        let edge = build_edge(parser, attributes, &key.edge_items);
                        if let Some(concurrent_edges) = graph.edge_weight_mut(edge.source, edge.target) {
                            concurrent_edges.push(edge.id);
                        } else {
                            graph.add_edge(edge.source, edge.target, vec![edge.id]);
                        }
                        edges.insert(edge.id, edge);
                    }
                    _ => println!("Unhandled local name in {}: {}", STR_REP, name.local_name),
                }
            }
            XmlEvent::EndElement { name } => {
                if name.local_name == STR_REP {
                    break
                }
            }
            XmlEvent::Whitespace(_) => (),
            o => {panic!("Unexpected {:?} in `{}`", o, STR_REP)}
        }
    }

    graph::PageGraph::new(desc, edges, nodes, graph)
}

fn build_edge<R: std::io::Read>(
    parser: &mut EventReader<R>,
    attributes: Vec<xml::attribute::OwnedAttribute>,
    key: &HashMap<String, KeyItem>
) -> graph::Edge {
    const STR_REP: &'static str = "edge";

    let mut id_value = None;
    let mut source_value = None;
    let mut target_value = None;
    let mut edge_type = None;
    let mut edge_timestamp = None;
    let mut data = HashMap::new();
    for attribute in attributes {
        let name = attribute.name.local_name;
        match &name[..] {
            "id" => id_value = Some(attribute.value
                    .trim_start_matches('e')
                    .parse::<usize>()
                    .expect("Parse edge id as usize")
                    .into()
                ),
            "source" => source_value = Some(attribute.value
                    .trim_start_matches('n')
                    .parse::<usize>()
                    .expect("Parse source node id as usize")
                    .into()
                ),
            "target" => target_value = Some(attribute.value
                    .trim_start_matches('n')
                    .parse::<usize>()
                    .expect("Parse target node id as usize")
                    .into()
                ),
            _ => panic!("Unexpected attribute in {}: {}", STR_REP, name),
        }
    }

    while let Ok(e) = parser.next() {
        match e {
            XmlEvent::StartElement { name, attributes, namespace: _ } => {
                match &name.local_name[..] {
                    DataItem::STR_REP => {
                        let data_item = DataItem::build_data(parser, attributes);
                        let contained = data_item.contained;
                        if key.get("edge type").unwrap().id == data_item.key {
                            edge_type = Some(contained.to_string());
                        } else if key.get("id").unwrap().id == data_item.key {
                            let edge_id: graph::EdgeId = contained.parse::<usize>()
                                .expect("parse edge id as usize")
                                .into();
                            if edge_id != id_value.unwrap() {
                                panic!("wrong edge id");
                            }
                        } else if key.get("timestamp").unwrap().id == data_item.key {
                            edge_timestamp = Some(if contained.contains('.') {
                                contained.trim_end_matches('0')
                                    .trim_end_matches('.')
                                    .parse::<isize>()
                                    .unwrap()
                                } else {
                                    contained.parse::<isize>()
                                        .unwrap_or_default()
                                });
                        } else {
                            data.insert(data_item.key, contained);
                        }
                    }
                    _ => println!("Unhandled local name in {}: {}", STR_REP, name.local_name),
                }
            }
            XmlEvent::EndElement { name } => {
                if name.local_name == STR_REP {
                    break
                }
            }
            XmlEvent::Whitespace(_) => (),
            o => {panic!("Unexpected {:?} in `{}`", o, STR_REP)}
        }
    }

    let edge_type_attr = &edge_type.as_ref().expect("couldn't find `edge type` attr on node")[..];

    let edge_type = types::EdgeType::construct(edge_type_attr, &mut data, key);
    assert!(data.is_empty(), "extra data on edge {:?}: {:?}", edge_type, data);

    let id = id_value.expect("couldn't find `id` value on edge");
    let source = source_value.expect("couldn't find `source` value on edge");
    let target = target_value.expect("couldn't find `target` value on edge");

    graph::Edge {
        id,
        edge_type,
        edge_timestamp,
        source,
        target,
    }
}

fn build_node<R: std::io::Read>(
    parser: &mut EventReader<R>,
    attributes: Vec<xml::attribute::OwnedAttribute>,
    key: &HashMap<String, KeyItem>
) -> graph::Node {
    const STR_REP: &'static str = "node";

    let mut id_value = None;
    let mut node_type = None;
    let mut node_timestamp = None;
    let mut data = HashMap::new();
    for attribute in attributes {
        let name = attribute.name.local_name;
        match &name[..] {
            "id" => id_value = Some(attribute.value
                    .trim_start_matches('n')
                    .parse::<usize>()
                    .expect("Parse node id as usize")
                    .into()
                ),
            _ => panic!("Unexpected attribute in {}: {}", STR_REP, name),
        }
    }

    while let Ok(e) = parser.next() {
        match e {
            XmlEvent::StartElement { name, attributes, namespace: _ } => {
                match &name.local_name[..] {
                    DataItem::STR_REP => {
                        let data_item = DataItem::build_data(parser, attributes);
                        let contained = data_item.contained;
                        if key.get("node type").unwrap().id == data_item.key {
                            node_type = Some(contained.to_string());
                        } else if key.get("id").unwrap().id == data_item.key {
                            let node_id: graph::NodeId = contained.parse::<usize>()
                                .expect("parse node id as usize")
                                .into();
                            if node_id != id_value.unwrap() {
                                panic!("wrong node id");
                            }
                        } else if key.get("timestamp").unwrap().id == data_item.key {
                            node_timestamp = Some(if contained.contains('.') {
                                contained.trim_end_matches('0')
                                    .trim_end_matches('.')
                                    .parse::<isize>()
                                    .unwrap()
                                } else {
                                    contained.parse::<isize>()
                                        .unwrap_or_default()
                                });
                        } else {
                            data.insert(data_item.key, contained);
                        }
                    }
                    _ => println!("Unhandled local name in {}: {}", STR_REP, name.local_name),
                }
            }
            XmlEvent::EndElement { name } => {
                if name.local_name == STR_REP {
                    break
                }
            }
            XmlEvent::Whitespace(_) => (),
            o => {panic!("Unexpected {:?} in `{}`", o, STR_REP)}
        }
    }

    let node_type_attr = &node_type.as_ref().expect("couldn't find `node type` attr on node")[..];

    let node_type = types::NodeType::construct(node_type_attr, &mut data, key);
    assert!(data.is_empty(), "extra data on node {:?}: {:?}", node_type, data);

    let id = id_value.expect("couldn't find `id` value on node");
    let node_timestamp = node_timestamp.expect("couldn't find `timestamp` attr on node");

    graph::Node {
        id,
        node_type,
        node_timestamp,
    }
}

/// Represents a `data` GraphML node, which provides attributes associated with a particular node
/// or edge.
#[derive(Debug, PartialEq)]
struct DataItem {
    key: String,
    contained: String,
}

impl DataItem {
    const STR_REP: &'static str = "data";

    fn build_data<R: std::io::Read>(
        parser: &mut EventReader<R>,
        attributes: Vec<xml::attribute::OwnedAttribute>
    ) -> Self {
        let mut key_value = None;
        let mut contained_value = None;

        for attribute in attributes {
            let name = attribute.name.local_name;
            match &name[..] {
                "key" => key_value = Some(attribute.value),
                _ => panic!("Unexpected attribute in {}: {}", Self::STR_REP, name),
            }
        }

        while let Ok(e) = parser.next() {
            match e {
                XmlEvent::EndElement { name } => {
                    if name.local_name == Self::STR_REP {
                        break
                    }
                }
                XmlEvent::Characters(c) => {
                    contained_value = Some(c);
                }
                XmlEvent::Whitespace(_) => (),
                o => {panic!("Unexpected {:?} in `{}`", o, Self::STR_REP)}
            }
        }

        Self {
            key: key_value.expect("couldn't find `key` value on data"),
            contained: contained_value.unwrap_or_default(),
        }
    }
}

/// Remove and return an attribute from an attribute map according to the key, if present
macro_rules! drain_opt_string_from {
    ( $attrs:ident, $key:ident, $attr:expr ) => {
        $attrs.remove(&$key.get($attr).expect(&format!("could not find `{}` in key", $attr)).id)
    };
}
/// Panic if the attribute string does not exist in the map
macro_rules! drain_string_from {
    ( $attrs:ident, $key:ident, $attr:expr ) => {
        drain_opt_string_from!($attrs, $key, $attr)
            .expect(&format!("attribute `{}` was not present", $attr))
    };
}
/// Panic if the attribute string cannot be parsed as a boolean value
macro_rules! drain_bool_from {
    ( $attrs:ident, $key:ident, $attr:expr ) => {
        drain_string_from!($attrs, $key, $attr)
            .to_ascii_lowercase()
            .parse::<bool>()
            .expect(&format!("could not parse attribute `{}` as bool", $attr))
    };
}
/// Panic if the optional attribute string cannot be parsed as an unsigned numeric value
macro_rules! drain_opt_usize_from {
    ( $attrs:ident, $key:ident, $attr:expr ) => {
        drain_opt_string_from!($attrs, $key, $attr)
            .map(|inner_data| inner_data
                .parse::<usize>()
                .expect(&format!("could not parse attribute `{}` as usize", $attr))
            )
    };
}
/// Panic if the attribute string cannot be parsed as an unsigned numeric value
macro_rules! drain_usize_from {
    ( $attrs:ident, $key:ident, $attr:expr ) => {
        {
            let value = drain_string_from!($attrs, $key, $attr);
            value
                .parse::<usize>()
                .expect(&format!("could not parse attribute `{}` as usize: `{}`", $attr, value))
        }
    };
}

/// Allows building this type from a type string and a set of associated attributes, each of which
/// correspond to intelligible string representations through a key.
///
/// Any attributes used will be drained from `attrs`.
trait KeyedAttrs {
    fn construct(type_str: &str, attrs: &mut HashMap<String, String>, key: &HashMap<String, KeyItem>) -> Self;
}

impl KeyedAttrs for types::NodeType {
    fn construct(type_str: &str, attrs: &mut HashMap<String, String>, key: &HashMap<String, KeyItem>) -> Self {
        macro_rules! drain_opt_string {
            ( $attr:expr ) => { drain_opt_string_from!(attrs, key, $attr) }
        }
        macro_rules! drain_string {
            ( $attr:expr ) => { drain_string_from!(attrs, key, $attr) }
        }
        macro_rules! drain_bool {
            ( $attr:expr ) => { drain_bool_from!(attrs, key, $attr) }
        }
        macro_rules! drain_usize {
            ( $attr:expr ) => { drain_usize_from!(attrs, key, $attr) }
        }

        match type_str {
            "extensions" => Self::Extensions {},
            "remote frame" => Self::RemoteFrame {
                frame_id: graph::FrameId::try_from(&drain_string!("frame id") as &str).unwrap()
            },
            "resource" => Self::Resource {
                url: drain_string!("url")
            },
            "ad filter" => Self::AdFilter {
                rule: drain_string!("rule")
            },
            "tracker filter" => Self::TrackerFilter,
            "fingerprinting filter" => Self::FingerprintingFilter,
            "web API" => Self::WebApi {
                method: drain_string!("method")
            },
            "JS builtin" => Self::JsBuiltin {
                method: drain_string!("method")
            },
            "HTML element" => Self::HtmlElement {
                tag_name: drain_string!("tag name"),
                is_deleted: drain_bool!("is deleted"),
                node_id: drain_usize!("node id"),
            },
            "text node" => Self::TextNode{
                text: drain_opt_string!("text"),
                is_deleted: drain_bool!("is deleted"),
                node_id: drain_usize!("node id"),
            },
            "DOM root" => Self::DomRoot {
                url: drain_opt_string!("url"),
                tag_name: drain_string!("tag name"),
                is_deleted: drain_bool!("is deleted"),
                node_id: drain_usize!("node id"),
            },
            "frame owner" => Self::FrameOwner {
                tag_name: drain_string!("tag name"),
                is_deleted: drain_bool!("is deleted"),
                node_id: drain_usize!("node id"),
            },
            "storage" => Self::Storage {},
            "local storage" => Self::LocalStorage {},
            "session storage" => Self::SessionStorage {},
            "cookie jar" => Self::CookieJar {},
            "script" => Self::Script {
                url: drain_opt_string!("url"),
                script_type: drain_string!("script type"),
                script_id: drain_usize!("script id"),
                source: drain_string!("source"),
            },
            "parser" => Self::Parser {},
            "Brave Shields" => Self::BraveShields {},
            "shieldsAds shield" => Self::AdsShield {},
            "trackers shield" => Self::TrackersShield {},
            "javascript shield" => Self::JavascriptShield {},
            "fingerprinting shield" => Self::FingerprintingShield {},
            "fingerprintingV2 shield" => Self::FingerprintingV2Shield {},
            "binding" => Self::Binding {
                binding: drain_string!("binding"),
                binding_type: drain_string!("binding type"),
            },
            "binding event" => Self::BindingEvent {
                binding_event: drain_string!("binding event"),
            },
            _ => panic!("Unknown node type `{}`", type_str),
        }
    }
}

impl KeyedAttrs for types::EdgeType {
    fn construct(type_str: &str, attrs: &mut HashMap<String, String>, key: &HashMap<String, KeyItem>) -> Self {
        macro_rules! drain_opt_string {
            ( $attr:expr ) => { drain_opt_string_from!(attrs, key, $attr) }
        }
        macro_rules! drain_string {
            ( $attr:expr ) => { drain_string_from!(attrs, key, $attr) }
        }
        macro_rules! drain_bool {
            ( $attr:expr ) => { drain_bool_from!(attrs, key, $attr) }
        }
        macro_rules! drain_opt_usize {
            ( $attr:expr ) => { drain_opt_usize_from!(attrs, key, $attr) }
        }
        macro_rules! drain_usize {
            ( $attr:expr ) => { drain_usize_from!(attrs, key, $attr) }
        }

        match type_str {
            "filter" => Self::Filter {},
            "structure" => Self::Structure {},
            "cross DOM" => Self::CrossDom {},
            "resource block" => Self::ResourceBlock {},
            "shield" => Self::Shield {},
            "text change" => Self::TextChange {},
            "remove node" => Self::RemoveNode {},
            "delete node" => Self::DeleteNode {},
            "insert node" => Self::InsertNode {
                parent: drain_usize!("parent"),
                before: drain_opt_usize!("before"),
            },
            "create node" => Self::CreateNode {},
            "js result" => Self::JsResult {
                value: drain_opt_string!("value"),
            },
            "js call" => Self::JsCall {
                args: drain_opt_string!("args"),
                script_position: drain_usize!("script position"),
            },
            "request complete" => Self::RequestComplete {
                resource_type: drain_string!("resource type"),
                status: drain_string!("status"),
                value: drain_opt_string!("value"),
                response_hash: drain_opt_string!("response hash"),
                request_id: drain_usize!("request id"),
                headers: drain_string!("headers"),
                size: drain_string!("size"),
            },
            "request error" => Self::RequestError {
                status: drain_string!("status"),
                request_id: drain_usize!("request id"),
                value: drain_opt_string!("value"),
                headers: drain_string!("headers"),
                size: drain_string!("size"),
            },
            "request start" => Self::RequestStart {
                request_type: crate::types::RequestType::from(&drain_string!("resource type")[..]),
                status: drain_string!("status"),
                request_id: drain_usize!("request id"),
            },
            "request response" => Self::RequestResponse,
            "add event listener" => Self::AddEventListener {
                key: drain_string!("key"),
                event_listener_id: drain_usize!("event listener id"),
                script_id: drain_usize!("script id"),
            },
            "remove event listener" => Self::RemoveEventListener {
                key: drain_string!("key"),
                event_listener_id: drain_usize!("event listener id"),
                script_id: drain_usize!("script id"),
            },
            "event listener" => Self::EventListener{
                key: drain_string!("key"),
                event_listener_id: drain_usize!("event listener id"),
            },
            "storage set" => Self::StorageSet {
                key: drain_string!("key"),
                value: drain_opt_string!("value"),
            },
            "storage read result" => Self::StorageReadResult {
                key: drain_string!("key"),
                value: drain_opt_string!("value"),
            },
            "delete storage" => Self::DeleteStorage {
                key: drain_string!("key"),
            },
            "read storage call" => Self::ReadStorageCall {
                key: drain_string!("key"),
            },
            "clear storage" => Self::ClearStorage {
                key: drain_string!("key"),
            },
            "storage bucket" => Self::StorageBucket {},
            "execute from attribute" => Self::ExecuteFromAttribute {
                attr_name: drain_string!("attr name"),
            },
            "execute" => Self::Execute {},
            "set attribute" => Self::SetAttribute {
                key: drain_string!("key"),
                value: drain_opt_string!("value"),
                is_style: drain_bool!("is style"),
            },
            "delete attribute" => Self::DeleteAttribute {
                key: drain_string!("key"),
                is_style: drain_bool!("is style"),
            },
            "binding" => Self::Binding {},
            "binding event" => Self::BindingEvent {
                script_position: drain_usize!("script position"),
            },
            _ => panic!("Unknown edge type `{}`", type_str),
        }
    }
}