diagnostics_data/
lib.rs

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
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
// Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

//! # Diagnostics data
//!
//! This library contains the Diagnostics data schema used for inspect and logs . This is
//! the data that the Archive returns on `fuchsia.diagnostics.ArchiveAccessor` reads.

use chrono::{Local, TimeZone, Utc};
use diagnostics_hierarchy::HierarchyMatcher;
use fidl_fuchsia_diagnostics::{DataType, Selector};
use fidl_fuchsia_inspect as finspect;
use flyweights::FlyStr;
use itertools::Itertools;
use moniker::EXTENDED_MONIKER_COMPONENT_MANAGER_STR;
use selectors::SelectorExt;
use serde::de::{DeserializeOwned, Deserializer};
use serde::{Deserialize, Serialize, Serializer};
use std::borrow::{Borrow, Cow};
use std::cmp::Ordering;
use std::fmt;
use std::hash::Hash;
use std::ops::Deref;
use std::str::FromStr;
use std::sync::LazyLock;
use std::time::Duration;
use termion::{color, style};
use thiserror::Error;

pub use diagnostics_hierarchy::{hierarchy, DiagnosticsHierarchy, Property};
pub use diagnostics_log_types_serde::Severity;
pub use moniker::ExtendedMoniker;

#[cfg(target_os = "fuchsia")]
mod logs_legacy;

const SCHEMA_VERSION: u64 = 1;
const MICROS_IN_SEC: u128 = 1000000;
const ROOT_MONIKER_REPR: &str = "<root>";

static DEFAULT_TREE_NAME: LazyLock<FlyStr> =
    LazyLock::new(|| FlyStr::new(finspect::DEFAULT_TREE_NAME));

/// The possible name for a handle to inspect data. It could be a filename (being deprecated) or a
/// name published using `fuchsia.inspect.InspectSink`.
#[derive(Deserialize, Serialize, Clone, Debug, PartialEq, Hash, Eq)]
#[serde(rename_all = "lowercase")]
pub enum InspectHandleName {
    /// The name of an `InspectHandle`. This comes from the `name` argument
    /// in `InspectSink`.
    Name(FlyStr),

    /// The name of the file source when reading a file source of Inspect
    /// (eg an inspect VMO file or fuchsia.inspect.Tree in out/diagnostics)
    Filename(FlyStr),
}

impl InspectHandleName {
    /// Construct an InspectHandleName::Name
    pub fn name(n: impl Into<FlyStr>) -> Self {
        Self::Name(n.into())
    }

    /// Construct an InspectHandleName::Filename
    pub fn filename(n: impl Into<FlyStr>) -> Self {
        Self::Filename(n.into())
    }

    /// If variant is Name, get the underlying value.
    pub fn as_name(&self) -> Option<&str> {
        if let Self::Name(n) = self {
            Some(n.as_str())
        } else {
            None
        }
    }

    /// If variant is Filename, get the underlying value
    pub fn as_filename(&self) -> Option<&str> {
        if let Self::Filename(f) = self {
            Some(f.as_str())
        } else {
            None
        }
    }
}

impl AsRef<str> for InspectHandleName {
    fn as_ref(&self) -> &str {
        match self {
            Self::Filename(f) => f.as_str(),
            Self::Name(n) => n.as_str(),
        }
    }
}

/// The source of diagnostics data
#[derive(Default, Deserialize, Serialize, Clone, Debug, PartialEq, Eq)]
pub enum DataSource {
    #[default]
    Unknown,
    Inspect,
    Logs,
}

pub trait MetadataError {
    fn dropped_payload() -> Self;
    fn message(&self) -> Option<&str>;
}

pub trait Metadata: DeserializeOwned + Serialize + Clone + Send {
    /// The type of error returned in this metadata.
    type Error: Clone + MetadataError;

    /// Returns the timestamp at which this value was recorded.
    fn timestamp(&self) -> Timestamp;

    /// Returns the errors recorded with this value, if any.
    fn errors(&self) -> Option<&[Self::Error]>;

    /// Overrides the errors associated with this value.
    fn set_errors(&mut self, errors: Vec<Self::Error>);

    /// Returns whether any errors are recorded on this value.
    fn has_errors(&self) -> bool {
        self.errors().map(|e| !e.is_empty()).unwrap_or_default()
    }
}

/// A trait implemented by marker types which denote "kinds" of diagnostics data.
pub trait DiagnosticsData {
    /// The type of metadata included in results of this type.
    type Metadata: Metadata;

    /// The type of key used for indexing node hierarchies in the payload.
    type Key: AsRef<str> + Clone + DeserializeOwned + Eq + FromStr + Hash + Send + 'static;

    /// Used to query for this kind of metadata in the ArchiveAccessor.
    const DATA_TYPE: DataType;
}

/// Inspect carries snapshots of data trees hosted by components.
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
pub struct Inspect;

impl DiagnosticsData for Inspect {
    type Metadata = InspectMetadata;
    type Key = String;
    const DATA_TYPE: DataType = DataType::Inspect;
}

impl Metadata for InspectMetadata {
    type Error = InspectError;

    fn timestamp(&self) -> Timestamp {
        self.timestamp
    }

    fn errors(&self) -> Option<&[Self::Error]> {
        self.errors.as_deref()
    }

    fn set_errors(&mut self, errors: Vec<Self::Error>) {
        self.errors = Some(errors);
    }
}

/// Logs carry streams of structured events from components.
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
pub struct Logs;

impl DiagnosticsData for Logs {
    type Metadata = LogsMetadata;
    type Key = LogsField;
    const DATA_TYPE: DataType = DataType::Logs;
}

impl Metadata for LogsMetadata {
    type Error = LogError;

    fn timestamp(&self) -> Timestamp {
        self.timestamp
    }

    fn errors(&self) -> Option<&[Self::Error]> {
        self.errors.as_deref()
    }

    fn set_errors(&mut self, errors: Vec<Self::Error>) {
        self.errors = Some(errors);
    }
}

pub fn serialize_timestamp<S>(timestamp: &Timestamp, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    serializer.serialize_i64(timestamp.into_nanos())
}

pub fn deserialize_timestamp<'de, D>(deserializer: D) -> Result<Timestamp, D::Error>
where
    D: Deserializer<'de>,
{
    let nanos = i64::deserialize(deserializer)?;
    Ok(Timestamp::from_nanos(nanos))
}

#[cfg(target_os = "fuchsia")]
mod zircon {
    pub type Timestamp = zx::BootInstant;
}
#[cfg(target_os = "fuchsia")]
pub use zircon::Timestamp;

#[cfg(not(target_os = "fuchsia"))]
mod host {
    use serde::{Deserialize, Serialize};
    use std::fmt;
    use std::ops::Add;
    use std::time::Duration;

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

    impl Timestamp {
        /// Returns the number of nanoseconds associated with this timestamp.
        pub fn into_nanos(self) -> i64 {
            self.0
        }

        /// Constructs a timestamp from the given nanoseconds.
        pub fn from_nanos(nanos: i64) -> Self {
            Self(nanos)
        }
    }

    impl Add<Duration> for Timestamp {
        type Output = Timestamp;
        fn add(self, rhs: Duration) -> Self::Output {
            Timestamp(self.0 + rhs.as_nanos() as i64)
        }
    }

    impl fmt::Display for Timestamp {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            write!(f, "{}", self.0)
        }
    }
}
#[cfg(not(target_os = "fuchsia"))]
pub use host::Timestamp;

/// The metadata contained in a `DiagnosticsData` object where the data source is
/// `DataSource::Inspect`.
#[derive(Deserialize, Serialize, Clone, Debug, PartialEq)]
pub struct InspectMetadata {
    /// Optional vector of errors encountered by platform.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub errors: Option<Vec<InspectError>>,

    /// Name of diagnostics source producing data.
    #[serde(flatten)]
    pub name: InspectHandleName,

    /// The url with which the component was launched.
    pub component_url: FlyStr,

    /// Boot time in nanos.
    #[serde(serialize_with = "serialize_timestamp", deserialize_with = "deserialize_timestamp")]
    pub timestamp: Timestamp,

    /// When set to true, the data was escrowed. Otherwise, the data was fetched live from the
    /// source component at runtime. When absent, it means the value is false.
    #[serde(skip_serializing_if = "std::ops::Not::not")]
    #[serde(default)]
    pub escrowed: bool,
}

impl InspectMetadata {
    /// Returns the component URL with which the component that emitted the associated Inspect data
    /// was launched.
    pub fn component_url(&self) -> &str {
        self.component_url.as_str()
    }
}

/// The metadata contained in a `DiagnosticsData` object where the data source is
/// `DataSource::Logs`.
#[derive(Deserialize, Serialize, Clone, Debug, PartialEq)]
pub struct LogsMetadata {
    // TODO(https://fxbug.dev/42136318) figure out exact spelling of pid/tid context and severity
    /// Optional vector of errors encountered by platform.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub errors: Option<Vec<LogError>>,

    /// The url with which the component was launched.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub component_url: Option<FlyStr>,

    /// Boot time in nanos.
    #[serde(serialize_with = "serialize_timestamp", deserialize_with = "deserialize_timestamp")]
    pub timestamp: Timestamp,

    /// Severity of the message.
    #[serde(with = "diagnostics_log_types_serde::severity")]
    pub severity: Severity,

    /// Raw severity if any. This will typically be unset unless the log message carries a severity
    /// that differs from the standard values of each severity.
    #[serde(skip_serializing_if = "Option::is_none")]
    raw_severity: Option<u8>,

    /// Tags to add at the beginning of the message
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tags: Option<Vec<String>>,

    /// The process ID
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pid: Option<u64>,

    /// The thread ID
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tid: Option<u64>,

    /// The file name
    #[serde(skip_serializing_if = "Option::is_none")]
    pub file: Option<String>,

    /// The line number
    #[serde(skip_serializing_if = "Option::is_none")]
    pub line: Option<u64>,

    /// Number of dropped messages
    /// DEPRECATED: do not set. Left for backwards compatibility with older serialized metadatas
    /// that contain this field.
    #[serde(skip)]
    dropped: Option<u64>,

    /// Size of the original message on the wire, in bytes.
    /// DEPRECATED: do not set. Left for backwards compatibility with older serialized metadatas
    /// that contain this field.
    #[serde(skip)]
    size_bytes: Option<usize>,
}

impl LogsMetadata {
    /// Returns the component URL which generated this value.
    pub fn component_url(&self) -> Option<&str> {
        self.component_url.as_ref().map(|s| s.as_str())
    }

    /// Returns the raw severity of this log.
    pub fn raw_severity(&self) -> u8 {
        match self.raw_severity {
            Some(s) => s,
            None => self.severity as u8,
        }
    }
}

/// An instance of diagnostics data with typed metadata and an optional nested payload.
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
pub struct Data<D: DiagnosticsData> {
    /// The source of the data.
    #[serde(default)]
    // TODO(https://fxbug.dev/42135946) remove this once the Metadata enum is gone everywhere
    pub data_source: DataSource,

    /// The metadata for the diagnostics payload.
    #[serde(bound(
        deserialize = "D::Metadata: DeserializeOwned",
        serialize = "D::Metadata: Serialize"
    ))]
    pub metadata: D::Metadata,

    /// Moniker of the component that generated the payload.
    #[serde(deserialize_with = "moniker_deserialize", serialize_with = "moniker_serialize")]
    pub moniker: ExtendedMoniker,

    /// Payload containing diagnostics data, if the payload exists, else None.
    pub payload: Option<DiagnosticsHierarchy<D::Key>>,

    /// Schema version.
    #[serde(default)]
    pub version: u64,
}

fn moniker_deserialize<'de, D>(deserializer: D) -> Result<ExtendedMoniker, D::Error>
where
    D: serde::Deserializer<'de>,
{
    let moniker_str = String::deserialize(deserializer)?;
    ExtendedMoniker::parse_str(&moniker_str).map_err(serde::de::Error::custom)
}

fn moniker_serialize<S>(moniker: &ExtendedMoniker, s: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    s.collect_str(moniker)
}

impl<D> Data<D>
where
    D: DiagnosticsData,
{
    /// Returns a [`Data`] with an error indicating that the payload was dropped.
    pub fn drop_payload(&mut self) {
        self.metadata.set_errors(vec![
            <<D as DiagnosticsData>::Metadata as Metadata>::Error::dropped_payload(),
        ]);
        self.payload = None;
    }

    /// Sorts this [`Data`]'s payload if one is present.
    pub fn sort_payload(&mut self) {
        if let Some(payload) = &mut self.payload {
            payload.sort();
        }
    }

    /// Uses a set of Selectors to filter self's payload and returns the resulting
    /// Data. If the resulting payload is empty, it returns Ok(None).
    pub fn filter(mut self, selectors: &[Selector]) -> Result<Option<Self>, Error> {
        let Some(hierarchy) = self.payload else {
            return Ok(None);
        };
        let matching_selectors =
            match self.moniker.match_against_selectors(selectors).collect::<Result<Vec<_>, _>>() {
                Ok(selectors) if selectors.is_empty() => return Ok(None),
                Ok(selectors) => selectors,
                Err(e) => {
                    return Err(Error::Internal(e));
                }
            };

        // TODO(https://fxbug.dev/300319116): Cache the `HierarchyMatcher`s
        let matcher: HierarchyMatcher = match matching_selectors.try_into() {
            Ok(hierarchy_matcher) => hierarchy_matcher,
            Err(e) => {
                return Err(Error::Internal(e.into()));
            }
        };

        self.payload = match diagnostics_hierarchy::filter_hierarchy(hierarchy, &matcher) {
            Some(hierarchy) => Some(hierarchy),
            None => return Ok(None),
        };
        Ok(Some(self))
    }
}

/// Errors that can happen in this library.
#[derive(Debug, Error)]
pub enum Error {
    #[error(transparent)]
    Internal(#[from] anyhow::Error),
}

/// A diagnostics data object containing inspect data.
pub type InspectData = Data<Inspect>;

/// A diagnostics data object containing logs data.
pub type LogsData = Data<Logs>;

/// A diagnostics data payload containing logs data.
pub type LogsHierarchy = DiagnosticsHierarchy<LogsField>;

/// A diagnostics hierarchy property keyed by `LogsField`.
pub type LogsProperty = Property<LogsField>;

impl Data<Inspect> {
    /// Access the name or filename within `self.metadata`.
    pub fn name(&self) -> &str {
        self.metadata.name.as_ref()
    }
}

pub struct InspectDataBuilder {
    data: Data<Inspect>,
}

impl InspectDataBuilder {
    pub fn new(
        moniker: ExtendedMoniker,
        component_url: impl Into<FlyStr>,
        timestamp: impl Into<Timestamp>,
    ) -> Self {
        Self {
            data: Data {
                data_source: DataSource::Inspect,
                moniker,
                payload: None,
                version: 1,
                metadata: InspectMetadata {
                    errors: None,
                    name: InspectHandleName::name(DEFAULT_TREE_NAME.clone()),
                    component_url: component_url.into(),
                    timestamp: timestamp.into(),
                    escrowed: false,
                },
            },
        }
    }

    pub fn escrowed(mut self, escrowed: bool) -> Self {
        self.data.metadata.escrowed = escrowed;
        self
    }

    pub fn with_hierarchy(
        mut self,
        hierarchy: DiagnosticsHierarchy<<Inspect as DiagnosticsData>::Key>,
    ) -> Self {
        self.data.payload = Some(hierarchy);
        self
    }

    pub fn with_errors(mut self, errors: Vec<InspectError>) -> Self {
        self.data.metadata.errors = Some(errors);
        self
    }

    pub fn with_name(mut self, name: InspectHandleName) -> Self {
        self.data.metadata.name = name;
        self
    }

    pub fn build(self) -> Data<Inspect> {
        self.data
    }
}

/// Internal state of the LogsDataBuilder impl
/// External customers should not directly access these fields.
pub struct LogsDataBuilder {
    /// List of errors
    errors: Vec<LogError>,
    /// Message in log
    msg: Option<String>,
    /// List of tags
    tags: Vec<String>,
    /// Process ID
    pid: Option<u64>,
    /// Thread ID
    tid: Option<u64>,
    /// File name
    file: Option<String>,
    /// Line number
    line: Option<u64>,
    /// BuilderArgs that was passed in at construction time
    args: BuilderArgs,
    /// List of KVPs from the user
    keys: Vec<Property<LogsField>>,
    /// Raw severity.
    raw_severity: Option<u8>,
}

/// Arguments used to create a new [`LogsDataBuilder`].
pub struct BuilderArgs {
    /// The moniker for the component
    pub moniker: ExtendedMoniker,
    /// The timestamp of the message in nanoseconds
    pub timestamp: Timestamp,
    /// The component URL
    pub component_url: Option<FlyStr>,
    /// The message severity
    pub severity: Severity,
}

impl LogsDataBuilder {
    /// Constructs a new LogsDataBuilder
    pub fn new(args: BuilderArgs) -> Self {
        LogsDataBuilder {
            args,
            errors: vec![],
            msg: None,
            file: None,
            line: None,
            pid: None,
            tags: vec![],
            tid: None,
            keys: vec![],
            raw_severity: None,
        }
    }

    /// Sets the number of dropped messages.
    /// If value is greater than zero, a DroppedLogs error
    /// will also be added to the list of errors or updated if
    /// already present.
    #[must_use = "You must call build on your builder to consume its result"]
    pub fn set_dropped(mut self, value: u64) -> Self {
        if value == 0 {
            return self;
        }
        let val = self.errors.iter_mut().find_map(|error| {
            if let LogError::DroppedLogs { count } = error {
                Some(count)
            } else {
                None
            }
        });
        if let Some(v) = val {
            *v = value;
        } else {
            self.errors.push(LogError::DroppedLogs { count: value });
        }
        self
    }

    /// Overrides the severity set through the args with a raw severity.
    pub fn set_raw_severity(mut self, severity: u8) -> Self {
        self.raw_severity = Some(severity);
        self
    }

    /// Sets the number of rolled out messages.
    /// If value is greater than zero, a RolledOutLogs error
    /// will also be added to the list of errors or updated if
    /// already present.
    #[must_use = "You must call build on your builder to consume its result"]
    pub fn set_rolled_out(mut self, value: u64) -> Self {
        if value == 0 {
            return self;
        }
        let val = self.errors.iter_mut().find_map(|error| {
            if let LogError::RolledOutLogs { count } = error {
                Some(count)
            } else {
                None
            }
        });
        if let Some(v) = val {
            *v = value;
        } else {
            self.errors.push(LogError::RolledOutLogs { count: value });
        }
        self
    }

    /// Sets the severity of the log. This will unset the raw severity.
    pub fn set_severity(mut self, severity: Severity) -> Self {
        self.args.severity = severity;
        self.raw_severity = None;
        self
    }

    /// Sets the process ID that logged the message
    #[must_use = "You must call build on your builder to consume its result"]
    pub fn set_pid(mut self, value: u64) -> Self {
        self.pid = Some(value);
        self
    }

    /// Sets the thread ID that logged the message
    #[must_use = "You must call build on your builder to consume its result"]
    pub fn set_tid(mut self, value: u64) -> Self {
        self.tid = Some(value);
        self
    }

    /// Constructs a LogsData from this builder
    pub fn build(self) -> LogsData {
        let mut args = vec![];
        if let Some(msg) = self.msg {
            args.push(LogsProperty::String(LogsField::MsgStructured, msg));
        }
        let mut payload_fields = vec![DiagnosticsHierarchy::new("message", args, vec![])];
        if !self.keys.is_empty() {
            let val = DiagnosticsHierarchy::new("keys", self.keys, vec![]);
            payload_fields.push(val);
        }
        let mut payload = LogsHierarchy::new("root", vec![], payload_fields);
        payload.sort();
        let (raw_severity, severity) =
            self.raw_severity.map(Severity::parse_exact).unwrap_or((None, self.args.severity));
        let mut ret = LogsData::for_logs(
            self.args.moniker,
            Some(payload),
            self.args.timestamp,
            self.args.component_url,
            severity,
            self.errors,
        );
        ret.metadata.raw_severity = raw_severity;
        ret.metadata.file = self.file;
        ret.metadata.line = self.line;
        ret.metadata.pid = self.pid;
        ret.metadata.tid = self.tid;
        ret.metadata.tags = Some(self.tags);
        ret
    }

    /// Adds an error
    #[must_use = "You must call build on your builder to consume its result"]
    pub fn add_error(mut self, error: LogError) -> Self {
        self.errors.push(error);
        self
    }

    /// Sets the message to be printed in the log message
    #[must_use = "You must call build on your builder to consume its result"]
    pub fn set_message(mut self, msg: impl Into<String>) -> Self {
        self.msg = Some(msg.into());
        self
    }

    /// Sets the file name that printed this message.
    #[must_use = "You must call build on your builder to consume its result"]
    pub fn set_file(mut self, file: impl Into<String>) -> Self {
        self.file = Some(file.into());
        self
    }

    /// Sets the line number that printed this message.
    #[must_use = "You must call build on your builder to consume its result"]
    pub fn set_line(mut self, line: u64) -> Self {
        self.line = Some(line);
        self
    }

    /// Adds a property to the list of key value pairs that are a part of this log message.
    #[must_use = "You must call build on your builder to consume its result"]
    pub fn add_key(mut self, kvp: Property<LogsField>) -> Self {
        self.keys.push(kvp);
        self
    }

    /// Adds a tag to the list of tags that precede this log message.
    #[must_use = "You must call build on your builder to consume its result"]
    pub fn add_tag(mut self, tag: impl Into<String>) -> Self {
        self.tags.push(tag.into());
        self
    }
}

impl Data<Logs> {
    /// Creates a new data instance for logs.
    pub fn for_logs(
        moniker: ExtendedMoniker,
        payload: Option<LogsHierarchy>,
        timestamp: impl Into<Timestamp>,
        component_url: Option<FlyStr>,
        severity: impl Into<Severity>,
        errors: Vec<LogError>,
    ) -> Self {
        let errors = if errors.is_empty() { None } else { Some(errors) };

        Data {
            moniker,
            version: SCHEMA_VERSION,
            data_source: DataSource::Logs,
            payload,
            metadata: LogsMetadata {
                timestamp: timestamp.into(),
                component_url,
                severity: severity.into(),
                raw_severity: None,
                errors,
                file: None,
                line: None,
                pid: None,
                tags: None,
                tid: None,
                dropped: None,
                size_bytes: None,
            },
        }
    }

    /// Sets the severity from a raw severity number. Overrides the severity to match the raw
    /// severity.
    pub fn set_raw_severity(&mut self, raw_severity: u8) {
        self.metadata.raw_severity = Some(raw_severity);
        self.metadata.severity = Severity::from(raw_severity);
    }

    /// Sets the severity of the log. This will unset the raw severity.
    pub fn set_severity(&mut self, severity: Severity) {
        self.metadata.severity = severity;
        self.metadata.raw_severity = None;
    }

    /// Returns the string log associated with the message, if one exists.
    pub fn msg(&self) -> Option<&str> {
        self.payload_message().as_ref().and_then(|p| {
            p.properties.iter().find_map(|property| match property {
                LogsProperty::String(LogsField::MsgStructured, msg) => Some(msg.as_str()),
                _ => None,
            })
        })
    }

    /// If the log has a message, returns a shared reference to the message contents.
    pub fn msg_mut(&mut self) -> Option<&mut String> {
        self.payload_message_mut().and_then(|p| {
            p.properties.iter_mut().find_map(|property| match property {
                LogsProperty::String(LogsField::MsgStructured, msg) => Some(msg),
                _ => None,
            })
        })
    }

    /// If the log has message, returns an exclusive reference to it.
    pub fn payload_message(&self) -> Option<&DiagnosticsHierarchy<LogsField>> {
        self.payload
            .as_ref()
            .and_then(|p| p.children.iter().find(|property| property.name.as_str() == "message"))
    }

    /// If the log has structured keys, returns an exclusive reference to them.
    pub fn payload_keys(&self) -> Option<&DiagnosticsHierarchy<LogsField>> {
        self.payload
            .as_ref()
            .and_then(|p| p.children.iter().find(|property| property.name.as_str() == "keys"))
    }

    /// Returns an iterator over the payload keys as strings with the format "key=value".
    pub fn payload_keys_strings(&self) -> Box<dyn Iterator<Item = String> + '_> {
        let maybe_iter = self.payload_keys().map(|p| {
            Box::new(p.properties.iter().filter_map(|property| match property {
                LogsProperty::String(LogsField::Tag, _tag) => None,
                LogsProperty::String(LogsField::ProcessId, _tag) => None,
                LogsProperty::String(LogsField::ThreadId, _tag) => None,
                LogsProperty::String(LogsField::Dropped, _tag) => None,
                LogsProperty::String(LogsField::Msg, _tag) => None,
                LogsProperty::String(LogsField::FilePath, _tag) => None,
                LogsProperty::String(LogsField::LineNumber, _tag) => None,
                LogsProperty::String(
                    key @ (LogsField::Other(_) | LogsField::MsgStructured),
                    value,
                ) => Some(format!("{}={}", key, value)),
                LogsProperty::Bytes(key @ (LogsField::Other(_) | LogsField::MsgStructured), _) => {
                    Some(format!("{} = <bytes>", key))
                }
                LogsProperty::Int(
                    key @ (LogsField::Other(_) | LogsField::MsgStructured),
                    value,
                ) => Some(format!("{}={}", key, value)),
                LogsProperty::Uint(
                    key @ (LogsField::Other(_) | LogsField::MsgStructured),
                    value,
                ) => Some(format!("{}={}", key, value)),
                LogsProperty::Double(
                    key @ (LogsField::Other(_) | LogsField::MsgStructured),
                    value,
                ) => Some(format!("{}={}", key, value)),
                LogsProperty::Bool(
                    key @ (LogsField::Other(_) | LogsField::MsgStructured),
                    value,
                ) => Some(format!("{}={}", key, value)),
                LogsProperty::DoubleArray(
                    key @ (LogsField::Other(_) | LogsField::MsgStructured),
                    value,
                ) => Some(format!("{}={:?}", key, value)),
                LogsProperty::IntArray(
                    key @ (LogsField::Other(_) | LogsField::MsgStructured),
                    value,
                ) => Some(format!("{}={:?}", key, value)),
                LogsProperty::UintArray(
                    key @ (LogsField::Other(_) | LogsField::MsgStructured),
                    value,
                ) => Some(format!("{}={:?}", key, value)),
                LogsProperty::StringList(
                    key @ (LogsField::Other(_) | LogsField::MsgStructured),
                    value,
                ) => Some(format!("{}={:?}", key, value)),
                _ => None,
            }))
        });
        match maybe_iter {
            Some(i) => Box::new(i),
            None => Box::new(std::iter::empty()),
        }
    }

    /// If the log has a message, returns a mutable reference to it.
    pub fn payload_message_mut(&mut self) -> Option<&mut DiagnosticsHierarchy<LogsField>> {
        self.payload.as_mut().and_then(|p| {
            p.children.iter_mut().find(|property| property.name.as_str() == "message")
        })
    }

    /// Returns the file path associated with the message, if one exists.
    pub fn file_path(&self) -> Option<&str> {
        self.metadata.file.as_deref()
    }

    /// Returns the line number associated with the message, if one exists.
    pub fn line_number(&self) -> Option<&u64> {
        self.metadata.line.as_ref()
    }

    /// Returns the pid associated with the message, if one exists.
    pub fn pid(&self) -> Option<u64> {
        self.metadata.pid
    }

    /// Returns the tid associated with the message, if one exists.
    pub fn tid(&self) -> Option<u64> {
        self.metadata.tid
    }

    /// Returns the tags associated with the message, if any exist.
    pub fn tags(&self) -> Option<&Vec<String>> {
        self.metadata.tags.as_ref()
    }

    /// Returns the severity level of this log.
    pub fn severity(&self) -> Severity {
        self.metadata.severity
    }

    /// Returns number of dropped logs if reported in the message.
    pub fn dropped_logs(&self) -> Option<u64> {
        self.metadata.errors.as_ref().and_then(|errors| {
            errors.iter().find_map(|e| match e {
                LogError::DroppedLogs { count } => Some(*count),
                _ => None,
            })
        })
    }

    /// Returns number of rolled out logs if reported in the message.
    pub fn rolled_out_logs(&self) -> Option<u64> {
        self.metadata.errors.as_ref().and_then(|errors| {
            errors.iter().find_map(|e| match e {
                LogError::RolledOutLogs { count } => Some(*count),
                _ => None,
            })
        })
    }

    /// Returns the component nam. This only makes sense for v1 components.
    pub fn component_name(&self) -> Cow<'_, str> {
        match &self.moniker {
            ExtendedMoniker::ComponentManager => {
                Cow::Borrowed(EXTENDED_MONIKER_COMPONENT_MANAGER_STR)
            }
            ExtendedMoniker::ComponentInstance(moniker) => {
                if moniker.is_root() {
                    Cow::Borrowed(ROOT_MONIKER_REPR)
                } else {
                    Cow::Owned(moniker.path().iter().last().unwrap().to_string())
                }
            }
        }
    }
}

/// Display options for unstructured logs.
#[derive(Clone, Copy, Debug)]
pub struct LogTextDisplayOptions {
    /// Whether or not to display the full moniker.
    pub show_full_moniker: bool,

    /// Whether or not to display metadata like PID & TID.
    pub show_metadata: bool,

    /// Whether or not to display tags provided by the log producer.
    pub show_tags: bool,

    /// Whether or not to display the source location which produced the log.
    pub show_file: bool,

    /// Whether to include ANSI color codes in the output.
    pub color: LogTextColor,

    /// How to print timestamps for this log message.
    pub time_format: LogTimeDisplayFormat,
}

impl Default for LogTextDisplayOptions {
    fn default() -> Self {
        Self {
            show_full_moniker: true,
            show_metadata: true,
            show_tags: true,
            show_file: true,
            color: Default::default(),
            time_format: Default::default(),
        }
    }
}

/// Configuration for the color of a log line that is displayed in tools using [`LogTextPresenter`].
#[derive(Clone, Copy, Debug, Default)]
pub enum LogTextColor {
    /// Do not print this log with ANSI colors.
    #[default]
    None,

    /// Display color codes according to log severity and presence of dropped or rolled out logs.
    BySeverity,

    /// Highlight this message as noteworthy regardless of severity, e.g. for known spam messages.
    Highlight,
}

impl LogTextColor {
    fn begin_record(&self, f: &mut fmt::Formatter<'_>, severity: Severity) -> fmt::Result {
        match self {
            LogTextColor::BySeverity => match severity {
                Severity::Fatal => {
                    write!(f, "{}{}", color::Bg(color::Red), color::Fg(color::White))?
                }
                Severity::Error => write!(f, "{}", color::Fg(color::Red))?,
                Severity::Warn => write!(f, "{}", color::Fg(color::Yellow))?,
                Severity::Info => (),
                Severity::Debug => write!(f, "{}", color::Fg(color::LightBlue))?,
                Severity::Trace => write!(f, "{}", color::Fg(color::LightMagenta))?,
            },
            LogTextColor::Highlight => write!(f, "{}", color::Fg(color::LightYellow))?,
            LogTextColor::None => {}
        }
        Ok(())
    }

    fn begin_lost_message_counts(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let LogTextColor::BySeverity = self {
            // This will be reset below before the next line.
            write!(f, "{}", color::Fg(color::Yellow))?;
        }
        Ok(())
    }

    fn end_record(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            LogTextColor::BySeverity | LogTextColor::Highlight => write!(f, "{}", style::Reset)?,
            LogTextColor::None => {}
        };
        Ok(())
    }
}

/// Options for the timezone associated to the timestamp of a log line.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Timezone {
    /// Display a timestamp in terms of the local timezone as reported by the operating system.
    Local,

    /// Display a timestamp in terms of UTC.
    Utc,
}

impl Timezone {
    fn format(&self, seconds: i64, rem_nanos: u32) -> impl std::fmt::Display {
        const TIMESTAMP_FORMAT: &str = "%Y-%m-%d %H:%M:%S.%3f";
        match self {
            Timezone::Local => {
                Local.timestamp_opt(seconds, rem_nanos).unwrap().format(TIMESTAMP_FORMAT)
            }
            Timezone::Utc => {
                Utc.timestamp_opt(seconds, rem_nanos).unwrap().format(TIMESTAMP_FORMAT)
            }
        }
    }
}

/// Configuration for how to display the timestamp associated to a log line.
#[derive(Clone, Copy, Debug, Default)]
pub enum LogTimeDisplayFormat {
    /// Display the log message's timestamp as monotonic nanoseconds since boot.
    #[default]
    Original,

    /// Display the log's timestamp as a human-readable string in ISO 8601 format.
    WallTime {
        /// The format for displaying a timestamp as a string.
        tz: Timezone,

        /// The offset to apply to the original device-monotonic time before printing it as a
        /// human-readable timestamp.
        offset: i64,
    },
}

impl LogTimeDisplayFormat {
    fn write_timestamp(&self, f: &mut fmt::Formatter<'_>, time: Timestamp) -> fmt::Result {
        const NANOS_IN_SECOND: i64 = 1_000_000_000;

        match self {
            // Don't try to print a human readable string if it's going to be in 1970, fall back
            // to monotonic.
            Self::Original | Self::WallTime { offset: 0, .. } => {
                let time: Duration =
                    Duration::from_nanos(time.into_nanos().try_into().unwrap_or(0));
                write!(f, "[{:05}.{:06}]", time.as_secs(), time.as_micros() % MICROS_IN_SEC)?;
            }
            Self::WallTime { tz, offset } => {
                let adjusted = time.into_nanos() + offset;
                let seconds = adjusted / NANOS_IN_SECOND;
                let rem_nanos = (adjusted % NANOS_IN_SECOND) as u32;
                let formatted = tz.format(seconds, rem_nanos);
                write!(f, "[{}]", formatted)?;
            }
        }
        Ok(())
    }
}

/// Used to control stringification options of Data<Logs>
pub struct LogTextPresenter<'a> {
    /// The log to parameterize
    log: &'a Data<Logs>,

    /// Options for stringifying the log
    options: LogTextDisplayOptions,
}

impl<'a> LogTextPresenter<'a> {
    /// Creates a new LogTextPresenter with the specified options and
    /// log message. This presenter is bound to the lifetime of the
    /// underlying log message.
    pub fn new(log: &'a Data<Logs>, options: LogTextDisplayOptions) -> Self {
        Self { log, options }
    }
}

impl fmt::Display for Data<Logs> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        LogTextPresenter::new(self, Default::default()).fmt(f)
    }
}

impl Deref for LogTextPresenter<'_> {
    type Target = Data<Logs>;
    fn deref(&self) -> &Self::Target {
        self.log
    }
}

impl fmt::Display for LogTextPresenter<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.options.color.begin_record(f, self.log.severity())?;
        self.options.time_format.write_timestamp(f, self.metadata.timestamp)?;

        if self.options.show_metadata {
            match self.pid() {
                Some(pid) => write!(f, "[{pid}]")?,
                None => write!(f, "[]")?,
            }
            match self.tid() {
                Some(tid) => write!(f, "[{tid}]")?,
                None => write!(f, "[]")?,
            }
        }

        let moniker = if self.options.show_full_moniker {
            match &self.moniker {
                ExtendedMoniker::ComponentManager => {
                    Cow::Borrowed(EXTENDED_MONIKER_COMPONENT_MANAGER_STR)
                }
                ExtendedMoniker::ComponentInstance(instance) => {
                    if instance.is_root() {
                        Cow::Borrowed(ROOT_MONIKER_REPR)
                    } else {
                        Cow::Owned(instance.to_string())
                    }
                }
            }
        } else {
            self.component_name()
        };
        write!(f, "[{moniker}]")?;

        if self.options.show_tags {
            match &self.metadata.tags {
                Some(tags) if !tags.is_empty() => {
                    let mut filtered =
                        tags.iter().filter(|tag| *tag != moniker.as_ref()).peekable();
                    if filtered.peek().is_some() {
                        write!(f, "[{}]", filtered.join(","))?;
                    }
                }
                _ => {}
            }
        }

        write!(f, " {}:", self.metadata.severity)?;

        if self.options.show_file {
            match (&self.metadata.file, &self.metadata.line) {
                (Some(file), Some(line)) => write!(f, " [{file}({line})]")?,
                (Some(file), None) => write!(f, " [{file}]")?,
                _ => (),
            }
        }

        if let Some(msg) = self.msg() {
            write!(f, " {msg}")?;
        } else {
            write!(f, " <missing message>")?;
        }
        for kvp in self.payload_keys_strings() {
            write!(f, " {}", kvp)?;
        }

        let dropped = self.log.dropped_logs().unwrap_or_default();
        let rolled = self.log.rolled_out_logs().unwrap_or_default();
        if dropped != 0 || rolled != 0 {
            self.options.color.begin_lost_message_counts(f)?;
            if dropped != 0 {
                write!(f, " [dropped={dropped}]")?;
            }
            if rolled != 0 {
                write!(f, " [rolled={rolled}]")?;
            }
        }

        self.options.color.end_record(f)?;

        Ok(())
    }
}

impl Eq for Data<Logs> {}

impl PartialOrd for Data<Logs> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Data<Logs> {
    fn cmp(&self, other: &Self) -> Ordering {
        self.metadata.timestamp.cmp(&other.metadata.timestamp)
    }
}

/// An enum containing well known argument names passed through logs, as well
/// as an `Other` variant for any other argument names.
///
/// This contains the fields of logs sent as a [`LogMessage`].
///
/// [`LogMessage`]: https://fuchsia.dev/reference/fidl/fuchsia.logger#LogMessage
#[derive(Clone, Debug, Deserialize, Eq, Hash, PartialEq, PartialOrd, Ord, Serialize)]
pub enum LogsField {
    ProcessId,
    ThreadId,
    Dropped,
    Tag,
    Msg,
    MsgStructured,
    FilePath,
    LineNumber,
    Other(String),
}

impl fmt::Display for LogsField {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            LogsField::ProcessId => write!(f, "pid"),
            LogsField::ThreadId => write!(f, "tid"),
            LogsField::Dropped => write!(f, "num_dropped"),
            LogsField::Tag => write!(f, "tag"),
            LogsField::Msg => write!(f, "message"),
            LogsField::MsgStructured => write!(f, "value"),
            LogsField::FilePath => write!(f, "file_path"),
            LogsField::LineNumber => write!(f, "line_number"),
            LogsField::Other(name) => write!(f, "{}", name),
        }
    }
}

// TODO(https://fxbug.dev/42127608) - ensure that strings reported here align with naming
// decisions made for the structured log format sent by other components.
/// The label for the process koid in the log metadata.
pub const PID_LABEL: &str = "pid";
/// The label for the thread koid in the log metadata.
pub const TID_LABEL: &str = "tid";
/// The label for the number of dropped logs in the log metadata.
pub const DROPPED_LABEL: &str = "num_dropped";
/// The label for a tag in the log metadata.
pub const TAG_LABEL: &str = "tag";
/// The label for the contents of a message in the log payload.
pub const MESSAGE_LABEL_STRUCTURED: &str = "value";
/// The label for the message in the log payload.
pub const MESSAGE_LABEL: &str = "message";
/// The label for the file associated with a log line.
pub const FILE_PATH_LABEL: &str = "file";
/// The label for the line number in the file associated with a log line.
pub const LINE_NUMBER_LABEL: &str = "line";

impl AsRef<str> for LogsField {
    fn as_ref(&self) -> &str {
        match self {
            Self::ProcessId => PID_LABEL,
            Self::ThreadId => TID_LABEL,
            Self::Dropped => DROPPED_LABEL,
            Self::Tag => TAG_LABEL,
            Self::Msg => MESSAGE_LABEL,
            Self::FilePath => FILE_PATH_LABEL,
            Self::LineNumber => LINE_NUMBER_LABEL,
            Self::MsgStructured => MESSAGE_LABEL_STRUCTURED,
            Self::Other(str) => str.as_str(),
        }
    }
}

impl<T> From<T> for LogsField
where
    // Deref instead of AsRef b/c LogsField: AsRef<str> so this conflicts with concrete From<Self>
    T: Deref<Target = str>,
{
    fn from(s: T) -> Self {
        match s.as_ref() {
            PID_LABEL => Self::ProcessId,
            TID_LABEL => Self::ThreadId,
            DROPPED_LABEL => Self::Dropped,
            TAG_LABEL => Self::Tag,
            MESSAGE_LABEL => Self::Msg,
            FILE_PATH_LABEL => Self::FilePath,
            LINE_NUMBER_LABEL => Self::LineNumber,
            MESSAGE_LABEL_STRUCTURED => Self::MsgStructured,
            _ => Self::Other(s.to_string()),
        }
    }
}

impl FromStr for LogsField {
    type Err = ();
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(Self::from(s))
    }
}

/// Possible errors that can come in a `DiagnosticsData` object where the data source is
/// `DataSource::Logs`.
#[derive(Clone, Deserialize, Debug, Eq, PartialEq, Serialize)]
pub enum LogError {
    /// Represents the number of logs that were dropped by the component writing the logs due to an
    /// error writing to the socket before succeeding to write a log.
    #[serde(rename = "dropped_logs")]
    DroppedLogs { count: u64 },
    /// Represents the number of logs that were dropped for a component by the archivist due to the
    /// log buffer execeeding its maximum capacity before the current message.
    #[serde(rename = "rolled_out_logs")]
    RolledOutLogs { count: u64 },
    #[serde(rename = "parse_record")]
    FailedToParseRecord(String),
    #[serde(rename = "other")]
    Other { message: String },
}

const DROPPED_PAYLOAD_MSG: &str = "Schema failed to fit component budget.";

impl MetadataError for LogError {
    fn dropped_payload() -> Self {
        Self::Other { message: DROPPED_PAYLOAD_MSG.into() }
    }

    fn message(&self) -> Option<&str> {
        match self {
            Self::FailedToParseRecord(msg) => Some(msg.as_str()),
            Self::Other { message } => Some(message.as_str()),
            _ => None,
        }
    }
}

/// Possible error that can come in a `DiagnosticsData` object where the data source is
/// `DataSource::Inspect`..
#[derive(Debug, PartialEq, Clone, Eq)]
pub struct InspectError {
    pub message: String,
}

impl MetadataError for InspectError {
    fn dropped_payload() -> Self {
        Self { message: "Schema failed to fit component budget.".into() }
    }

    fn message(&self) -> Option<&str> {
        Some(self.message.as_str())
    }
}

impl fmt::Display for InspectError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.message)
    }
}

impl Borrow<str> for InspectError {
    fn borrow(&self) -> &str {
        &self.message
    }
}

impl Serialize for InspectError {
    fn serialize<S: Serializer>(&self, ser: S) -> Result<S::Ok, S::Error> {
        self.message.serialize(ser)
    }
}

impl<'de> Deserialize<'de> for InspectError {
    fn deserialize<D>(de: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let message = String::deserialize(de)?;
        Ok(Self { message })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use diagnostics_hierarchy::hierarchy;
    use selectors::FastError;
    use serde_json::json;

    const TEST_URL: &str = "fuchsia-pkg://test";

    #[fuchsia::test]
    fn test_canonical_json_inspect_formatting() {
        let mut hierarchy = hierarchy! {
            root: {
                x: "foo",
            }
        };

        hierarchy.sort();
        let json_schema = InspectDataBuilder::new(
            "a/b/c/d".try_into().unwrap(),
            TEST_URL,
            Timestamp::from_nanos(123456i64),
        )
        .with_hierarchy(hierarchy)
        .with_name(InspectHandleName::filename("test_file_plz_ignore.inspect"))
        .build();

        let result_json =
            serde_json::to_value(&json_schema).expect("serialization should succeed.");

        let expected_json = json!({
          "moniker": "a/b/c/d",
          "version": 1,
          "data_source": "Inspect",
          "payload": {
            "root": {
              "x": "foo"
            }
          },
          "metadata": {
            "component_url": TEST_URL,
            "filename": "test_file_plz_ignore.inspect",
            "timestamp": 123456,
          }
        });

        pretty_assertions::assert_eq!(result_json, expected_json, "golden diff failed.");
    }

    #[fuchsia::test]
    fn test_errorful_json_inspect_formatting() {
        let json_schema = InspectDataBuilder::new(
            "a/b/c/d".try_into().unwrap(),
            TEST_URL,
            Timestamp::from_nanos(123456i64),
        )
        .with_name(InspectHandleName::filename("test_file_plz_ignore.inspect"))
        .with_errors(vec![InspectError { message: "too much fun being had.".to_string() }])
        .build();

        let result_json =
            serde_json::to_value(&json_schema).expect("serialization should succeed.");

        let expected_json = json!({
          "moniker": "a/b/c/d",
          "version": 1,
          "data_source": "Inspect",
          "payload": null,
          "metadata": {
            "component_url": TEST_URL,
            "errors": ["too much fun being had."],
            "filename": "test_file_plz_ignore.inspect",
            "timestamp": 123456,
          }
        });

        pretty_assertions::assert_eq!(result_json, expected_json, "golden diff failed.");
    }

    fn parse_selectors(strings: Vec<&str>) -> Vec<Selector> {
        strings
            .iter()
            .map(|s| match selectors::parse_selector::<FastError>(s) {
                Ok(selector) => selector,
                Err(e) => panic!("Couldn't parse selector {s}: {e}"),
            })
            .collect::<Vec<_>>()
    }

    #[fuchsia::test]
    fn test_filter_returns_none_on_empty_hierarchy() {
        let data = InspectDataBuilder::new(
            "a/b/c/d".try_into().unwrap(),
            TEST_URL,
            Timestamp::from_nanos(123456i64),
        )
        .build();
        let selectors = parse_selectors(vec!["a/b/c/d:foo"]);
        assert_eq!(data.filter(&selectors).expect("Filter OK"), None);
    }

    #[fuchsia::test]
    fn test_filter_returns_none_on_selector_mismatch() {
        let mut hierarchy = hierarchy! {
            root: {
                x: "foo",
            }
        };
        hierarchy.sort();
        let data = InspectDataBuilder::new(
            "b/c/d/e".try_into().unwrap(),
            TEST_URL,
            Timestamp::from_nanos(123456i64),
        )
        .with_hierarchy(hierarchy)
        .build();
        let selectors = parse_selectors(vec!["a/b/c/d:foo"]);
        assert_eq!(data.filter(&selectors).expect("Filter OK"), None);
    }

    #[fuchsia::test]
    fn test_filter_returns_none_on_data_mismatch() {
        let mut hierarchy = hierarchy! {
            root: {
                x: "foo",
            }
        };
        hierarchy.sort();
        let data = InspectDataBuilder::new(
            "a/b/c/d".try_into().unwrap(),
            TEST_URL,
            Timestamp::from_nanos(123456i64),
        )
        .with_hierarchy(hierarchy)
        .build();
        let selectors = parse_selectors(vec!["a/b/c/d:foo"]);

        assert_eq!(data.filter(&selectors).expect("FIlter OK"), None);
    }

    #[fuchsia::test]
    fn test_filter_returns_matching_data() {
        let mut hierarchy = hierarchy! {
            root: {
                x: "foo",
                y: "bar",
            }
        };
        hierarchy.sort();
        let data = InspectDataBuilder::new(
            "a/b/c/d".try_into().unwrap(),
            TEST_URL,
            Timestamp::from_nanos(123456i64),
        )
        .with_name(InspectHandleName::filename("test_file_plz_ignore.inspect"))
        .with_hierarchy(hierarchy)
        .build();
        let selectors = parse_selectors(vec!["a/b/c/d:root:x"]);

        let expected_json = json!({
          "moniker": "a/b/c/d",
          "version": 1,
          "data_source": "Inspect",
          "payload": {
            "root": {
              "x": "foo"
            }
          },
          "metadata": {
            "component_url": TEST_URL,
            "filename": "test_file_plz_ignore.inspect",
            "timestamp": 123456,
          }
        });

        let result_json = serde_json::to_value(data.filter(&selectors).expect("Filter Ok"))
            .expect("serialization should succeed.");

        pretty_assertions::assert_eq!(result_json, expected_json, "golden diff failed.");
    }

    #[fuchsia::test]
    fn default_builder_test() {
        let builder = LogsDataBuilder::new(BuilderArgs {
            component_url: Some("url".into()),
            moniker: ExtendedMoniker::parse_str("moniker").unwrap(),
            severity: Severity::Info,
            timestamp: Timestamp::from_nanos(0),
        });
        //let tree = builder.build();
        let expected_json = json!({
          "moniker": "moniker",
          "version": 1,
          "data_source": "Logs",
          "payload": {
              "root":
              {
                  "message":{}
              }
          },
          "metadata": {
            "component_url": "url",
              "severity": "INFO",
              "tags": [],

            "timestamp": 0,
          }
        });
        let result_json =
            serde_json::to_value(builder.build()).expect("serialization should succeed.");
        pretty_assertions::assert_eq!(result_json, expected_json, "golden diff failed.");
    }

    #[fuchsia::test]
    fn regular_message_test() {
        let builder = LogsDataBuilder::new(BuilderArgs {
            component_url: Some("url".into()),
            moniker: ExtendedMoniker::parse_str("moniker").unwrap(),
            severity: Severity::Info,
            timestamp: Timestamp::from_nanos(0),
        })
        .set_message("app")
        .set_file("test file.cc")
        .set_line(420)
        .set_pid(1001)
        .set_tid(200)
        .set_dropped(2)
        .add_tag("You're")
        .add_tag("IT!")
        .add_key(LogsProperty::String(LogsField::Other("key".to_string()), "value".to_string()));
        // TODO(https://fxbug.dev/42157027): Convert to our custom DSL when possible.
        let expected_json = json!({
          "moniker": "moniker",
          "version": 1,
          "data_source": "Logs",
          "payload": {
              "root":
              {
                  "keys":{
                      "key":"value"
                  },
                  "message":{
                      "value":"app"
                  }
              }
          },
          "metadata": {
            "errors": [],
            "component_url": "url",
              "errors": [{"dropped_logs":{"count":2}}],
              "file": "test file.cc",
              "line": 420,
              "pid": 1001,
              "severity": "INFO",
              "tags": ["You're", "IT!"],
              "tid": 200,

            "timestamp": 0,
          }
        });
        let result_json =
            serde_json::to_value(builder.build()).expect("serialization should succeed.");
        pretty_assertions::assert_eq!(result_json, expected_json, "golden diff failed.");
    }

    #[fuchsia::test]
    fn display_for_logs() {
        let data = LogsDataBuilder::new(BuilderArgs {
            timestamp: Timestamp::from_nanos(12345678000i64),
            component_url: Some(FlyStr::from("fake-url")),
            moniker: ExtendedMoniker::parse_str("moniker").unwrap(),
            severity: Severity::Info,
        })
        .set_pid(123)
        .set_tid(456)
        .set_message("some message".to_string())
        .set_file("some_file.cc".to_string())
        .set_line(420)
        .add_tag("foo")
        .add_tag("bar")
        .add_key(LogsProperty::String(LogsField::Other("test".to_string()), "property".to_string()))
        .add_key(LogsProperty::String(LogsField::MsgStructured, "test".to_string()))
        .build();

        assert_eq!(
            "[00012.345678][123][456][moniker][foo,bar] INFO: [some_file.cc(420)] some message test=property value=test",
            format!("{}", data)
        )
    }

    #[fuchsia::test]
    fn display_for_logs_with_duplicate_moniker() {
        let data = LogsDataBuilder::new(BuilderArgs {
            timestamp: Timestamp::from_nanos(12345678000i64),
            component_url: Some(FlyStr::from("fake-url")),
            moniker: ExtendedMoniker::parse_str("moniker").unwrap(),
            severity: Severity::Info,
        })
        .set_pid(123)
        .set_tid(456)
        .set_message("some message".to_string())
        .set_file("some_file.cc".to_string())
        .set_line(420)
        .add_tag("moniker")
        .add_tag("bar")
        .add_tag("moniker")
        .add_key(LogsProperty::String(LogsField::Other("test".to_string()), "property".to_string()))
        .add_key(LogsProperty::String(LogsField::MsgStructured, "test".to_string()))
        .build();

        assert_eq!(
            "[00012.345678][123][456][moniker][bar] INFO: [some_file.cc(420)] some message test=property value=test",
            format!("{}", data)
        )
    }

    #[fuchsia::test]
    fn display_for_logs_with_duplicate_moniker_and_no_other_tags() {
        let data = LogsDataBuilder::new(BuilderArgs {
            timestamp: Timestamp::from_nanos(12345678000i64),
            component_url: Some(FlyStr::from("fake-url")),
            moniker: ExtendedMoniker::parse_str("moniker").unwrap(),
            severity: Severity::Info,
        })
        .set_pid(123)
        .set_tid(456)
        .set_message("some message".to_string())
        .set_file("some_file.cc".to_string())
        .set_line(420)
        .add_tag("moniker")
        .add_tag("moniker")
        .add_key(LogsProperty::String(LogsField::Other("test".to_string()), "property".to_string()))
        .add_key(LogsProperty::String(LogsField::MsgStructured, "test".to_string()))
        .build();

        assert_eq!(
            "[00012.345678][123][456][moniker] INFO: [some_file.cc(420)] some message test=property value=test",
            format!("{}", data)
        )
    }

    #[fuchsia::test]
    fn display_for_logs_partial_moniker() {
        let data = LogsDataBuilder::new(BuilderArgs {
            timestamp: Timestamp::from_nanos(12345678000i64),
            component_url: Some(FlyStr::from("fake-url")),
            moniker: ExtendedMoniker::parse_str("test/moniker").unwrap(),
            severity: Severity::Info,
        })
        .set_pid(123)
        .set_tid(456)
        .set_message("some message".to_string())
        .set_file("some_file.cc".to_string())
        .set_line(420)
        .add_tag("foo")
        .add_tag("bar")
        .add_key(LogsProperty::String(LogsField::Other("test".to_string()), "property".to_string()))
        .add_key(LogsProperty::String(LogsField::MsgStructured, "test".to_string()))
        .build();

        assert_eq!(
            "[00012.345678][123][456][moniker][foo,bar] INFO: [some_file.cc(420)] some message test=property value=test",
            format!("{}", LogTextPresenter::new(&data, LogTextDisplayOptions {
                show_full_moniker: false,
                ..Default::default()
            }))
        )
    }

    #[fuchsia::test]
    fn display_for_logs_exclude_metadata() {
        let data = LogsDataBuilder::new(BuilderArgs {
            timestamp: Timestamp::from_nanos(12345678000i64),
            component_url: Some(FlyStr::from("fake-url")),
            moniker: ExtendedMoniker::parse_str("moniker").unwrap(),
            severity: Severity::Info,
        })
        .set_pid(123)
        .set_tid(456)
        .set_message("some message".to_string())
        .set_file("some_file.cc".to_string())
        .set_line(420)
        .add_tag("foo")
        .add_tag("bar")
        .add_key(LogsProperty::String(LogsField::Other("test".to_string()), "property".to_string()))
        .add_key(LogsProperty::String(LogsField::MsgStructured, "test".to_string()))
        .build();

        assert_eq!(
            "[00012.345678][moniker][foo,bar] INFO: [some_file.cc(420)] some message test=property value=test",
            format!("{}", LogTextPresenter::new(&data, LogTextDisplayOptions {
                show_metadata: false,
                ..Default::default()
            }))
        )
    }

    #[fuchsia::test]
    fn display_for_logs_exclude_tags() {
        let data = LogsDataBuilder::new(BuilderArgs {
            timestamp: Timestamp::from_nanos(12345678000i64),
            component_url: Some(FlyStr::from("fake-url")),
            moniker: ExtendedMoniker::parse_str("moniker").unwrap(),
            severity: Severity::Info,
        })
        .set_pid(123)
        .set_tid(456)
        .set_message("some message".to_string())
        .set_file("some_file.cc".to_string())
        .set_line(420)
        .add_tag("foo")
        .add_tag("bar")
        .add_key(LogsProperty::String(LogsField::Other("test".to_string()), "property".to_string()))
        .add_key(LogsProperty::String(LogsField::MsgStructured, "test".to_string()))
        .build();

        assert_eq!(
            "[00012.345678][123][456][moniker] INFO: [some_file.cc(420)] some message test=property value=test",
            format!("{}", LogTextPresenter::new(&data, LogTextDisplayOptions {
                show_tags: false,
                ..Default::default()
            }))
        )
    }

    #[fuchsia::test]
    fn display_for_logs_exclude_file() {
        let data = LogsDataBuilder::new(BuilderArgs {
            timestamp: Timestamp::from_nanos(12345678000i64),
            component_url: Some(FlyStr::from("fake-url")),
            moniker: ExtendedMoniker::parse_str("moniker").unwrap(),
            severity: Severity::Info,
        })
        .set_pid(123)
        .set_tid(456)
        .set_message("some message".to_string())
        .set_file("some_file.cc".to_string())
        .set_line(420)
        .add_tag("foo")
        .add_tag("bar")
        .add_key(LogsProperty::String(LogsField::Other("test".to_string()), "property".to_string()))
        .add_key(LogsProperty::String(LogsField::MsgStructured, "test".to_string()))
        .build();

        assert_eq!(
            "[00012.345678][123][456][moniker][foo,bar] INFO: some message test=property value=test",
            format!("{}", LogTextPresenter::new(&data, LogTextDisplayOptions {
                show_file: false,
                ..Default::default()
            }))
        )
    }

    #[fuchsia::test]
    fn display_for_logs_include_color_by_severity() {
        let data = LogsDataBuilder::new(BuilderArgs {
            timestamp: Timestamp::from_nanos(12345678000i64),
            component_url: Some(FlyStr::from("fake-url")),
            moniker: ExtendedMoniker::parse_str("moniker").unwrap(),
            severity: Severity::Error,
        })
        .set_pid(123)
        .set_tid(456)
        .set_message("some message".to_string())
        .set_file("some_file.cc".to_string())
        .set_line(420)
        .add_tag("foo")
        .add_tag("bar")
        .add_key(LogsProperty::String(LogsField::Other("test".to_string()), "property".to_string()))
        .add_key(LogsProperty::String(LogsField::MsgStructured, "test".to_string()))
        .build();

        assert_eq!(
            format!("{}[00012.345678][123][456][moniker][foo,bar] ERROR: [some_file.cc(420)] some message test=property value=test{}", color::Fg(color::Red), style::Reset),
            format!("{}", LogTextPresenter::new(&data, LogTextDisplayOptions {
                color: LogTextColor::BySeverity,
                ..Default::default()
            }))
        )
    }

    #[fuchsia::test]
    fn display_for_logs_highlight_line() {
        let data = LogsDataBuilder::new(BuilderArgs {
            timestamp: Timestamp::from_nanos(12345678000i64),
            component_url: Some(FlyStr::from("fake-url")),
            moniker: ExtendedMoniker::parse_str("moniker").unwrap(),
            severity: Severity::Info,
        })
        .set_pid(123)
        .set_tid(456)
        .set_message("some message".to_string())
        .set_file("some_file.cc".to_string())
        .set_line(420)
        .add_tag("foo")
        .add_tag("bar")
        .add_key(LogsProperty::String(LogsField::Other("test".to_string()), "property".to_string()))
        .add_key(LogsProperty::String(LogsField::MsgStructured, "test".to_string()))
        .build();

        assert_eq!(
            format!("{}[00012.345678][123][456][moniker][foo,bar] INFO: [some_file.cc(420)] some message test=property value=test{}", color::Fg(color::LightYellow), style::Reset),
            format!("{}", LogTextPresenter::new(&data, LogTextDisplayOptions {
                color: LogTextColor::Highlight,
                ..Default::default()
            }))
        )
    }

    #[fuchsia::test]
    fn display_for_logs_with_wall_time() {
        let data = LogsDataBuilder::new(BuilderArgs {
            timestamp: Timestamp::from_nanos(12345678000i64),
            component_url: Some(FlyStr::from("fake-url")),
            moniker: ExtendedMoniker::parse_str("moniker").unwrap(),
            severity: Severity::Info,
        })
        .set_pid(123)
        .set_tid(456)
        .set_message("some message".to_string())
        .set_file("some_file.cc".to_string())
        .set_line(420)
        .add_tag("foo")
        .add_tag("bar")
        .add_key(LogsProperty::String(LogsField::Other("test".to_string()), "property".to_string()))
        .add_key(LogsProperty::String(LogsField::MsgStructured, "test".to_string()))
        .build();

        assert_eq!(
            "[1970-01-01 00:00:12.345][123][456][moniker][foo,bar] INFO: [some_file.cc(420)] some message test=property value=test",
            format!("{}", LogTextPresenter::new(&data, LogTextDisplayOptions {
                time_format: LogTimeDisplayFormat::WallTime { tz: Timezone::Utc, offset: 1 },
                ..Default::default()
            }))
        );

        assert_eq!(
            "[00012.345678][123][456][moniker][foo,bar] INFO: [some_file.cc(420)] some message test=property value=test",
            format!("{}", LogTextPresenter::new(&data, LogTextDisplayOptions {
                time_format: LogTimeDisplayFormat::WallTime { tz: Timezone::Utc, offset: 0 },
                ..Default::default()
            })),
            "should fall back to monotonic if offset is 0"
        );
    }

    #[fuchsia::test]
    fn display_for_logs_with_dropped_count() {
        let data = LogsDataBuilder::new(BuilderArgs {
            timestamp: Timestamp::from_nanos(12345678000i64),
            component_url: Some(FlyStr::from("fake-url")),
            moniker: ExtendedMoniker::parse_str("moniker").unwrap(),
            severity: Severity::Info,
        })
        .set_dropped(5)
        .set_pid(123)
        .set_tid(456)
        .set_message("some message".to_string())
        .set_file("some_file.cc".to_string())
        .set_line(420)
        .add_tag("foo")
        .add_tag("bar")
        .add_key(LogsProperty::String(LogsField::Other("test".to_string()), "property".to_string()))
        .add_key(LogsProperty::String(LogsField::MsgStructured, "test".to_string()))
        .build();

        assert_eq!(
            "[00012.345678][123][456][moniker][foo,bar] INFO: [some_file.cc(420)] some message test=property value=test [dropped=5]",
            format!("{}", LogTextPresenter::new(&data, LogTextDisplayOptions::default())),
        );

        assert_eq!(
            format!("[00012.345678][123][456][moniker][foo,bar] INFO: [some_file.cc(420)] some message test=property value=test{} [dropped=5]{}", color::Fg(color::Yellow), style::Reset),
            format!("{}", LogTextPresenter::new(&data, LogTextDisplayOptions {
                color: LogTextColor::BySeverity,
                ..Default::default()
            })),
        );
    }

    #[fuchsia::test]
    fn display_for_logs_with_rolled_count() {
        let data = LogsDataBuilder::new(BuilderArgs {
            timestamp: Timestamp::from_nanos(12345678000i64),
            component_url: Some(FlyStr::from("fake-url")),
            moniker: ExtendedMoniker::parse_str("moniker").unwrap(),
            severity: Severity::Info,
        })
        .set_rolled_out(10)
        .set_pid(123)
        .set_tid(456)
        .set_message("some message".to_string())
        .set_file("some_file.cc".to_string())
        .set_line(420)
        .add_tag("foo")
        .add_tag("bar")
        .add_key(LogsProperty::String(LogsField::Other("test".to_string()), "property".to_string()))
        .add_key(LogsProperty::String(LogsField::MsgStructured, "test".to_string()))
        .build();

        assert_eq!(
            "[00012.345678][123][456][moniker][foo,bar] INFO: [some_file.cc(420)] some message test=property value=test [rolled=10]",
            format!("{}", LogTextPresenter::new(&data, LogTextDisplayOptions::default())),
        );

        assert_eq!(
            format!("[00012.345678][123][456][moniker][foo,bar] INFO: [some_file.cc(420)] some message test=property value=test{} [rolled=10]{}", color::Fg(color::Yellow), style::Reset),
            format!("{}", LogTextPresenter::new(&data, LogTextDisplayOptions {
                color: LogTextColor::BySeverity,
                ..Default::default()
            })),
        );
    }

    #[fuchsia::test]
    fn display_for_logs_with_dropped_and_rolled_counts() {
        let data = LogsDataBuilder::new(BuilderArgs {
            timestamp: Timestamp::from_nanos(12345678000i64),
            component_url: Some(FlyStr::from("fake-url")),
            moniker: ExtendedMoniker::parse_str("moniker").unwrap(),
            severity: Severity::Info,
        })
        .set_dropped(5)
        .set_rolled_out(10)
        .set_pid(123)
        .set_tid(456)
        .set_message("some message".to_string())
        .set_file("some_file.cc".to_string())
        .set_line(420)
        .add_tag("foo")
        .add_tag("bar")
        .add_key(LogsProperty::String(LogsField::Other("test".to_string()), "property".to_string()))
        .add_key(LogsProperty::String(LogsField::MsgStructured, "test".to_string()))
        .build();

        assert_eq!(
            "[00012.345678][123][456][moniker][foo,bar] INFO: [some_file.cc(420)] some message test=property value=test [dropped=5] [rolled=10]",
            format!("{}", LogTextPresenter::new(&data, LogTextDisplayOptions::default())),
        );

        assert_eq!(
            format!("[00012.345678][123][456][moniker][foo,bar] INFO: [some_file.cc(420)] some message test=property value=test{} [dropped=5] [rolled=10]{}", color::Fg(color::Yellow), style::Reset),
            format!("{}", LogTextPresenter::new(&data, LogTextDisplayOptions {
                color: LogTextColor::BySeverity,
                ..Default::default()
            })),
        );
    }

    #[fuchsia::test]
    fn display_for_logs_no_tags() {
        let data = LogsDataBuilder::new(BuilderArgs {
            timestamp: Timestamp::from_nanos(12345678000i64),
            component_url: Some(FlyStr::from("fake-url")),
            moniker: ExtendedMoniker::parse_str("moniker").unwrap(),
            severity: Severity::Info,
        })
        .set_pid(123)
        .set_tid(456)
        .set_message("some message".to_string())
        .build();

        assert_eq!("[00012.345678][123][456][moniker] INFO: some message", format!("{}", data))
    }

    #[fuchsia::test]
    fn size_bytes_deserialize_backwards_compatibility() {
        let original_json = json!({
          "moniker": "a/b",
          "version": 1,
          "data_source": "Logs",
          "payload": {
            "root": {
              "message":{}
            }
          },
          "metadata": {
            "component_url": "url",
              "severity": "INFO",
              "tags": [],

            "timestamp": 123,
          }
        });
        let expected_data = LogsDataBuilder::new(BuilderArgs {
            component_url: Some("url".into()),
            moniker: ExtendedMoniker::parse_str("a/b").unwrap(),
            severity: Severity::Info,
            timestamp: Timestamp::from_nanos(123),
        })
        .build();
        let original_data: LogsData = serde_json::from_value(original_json).unwrap();
        assert_eq!(original_data, expected_data);
        // We skip deserializing the size_bytes
        assert_eq!(original_data.metadata.size_bytes, None);
    }

    #[fuchsia::test]
    fn dropped_deserialize_backwards_compatibility() {
        let original_json = json!({
          "moniker": "a/b",
          "version": 1,
          "data_source": "Logs",
          "payload": {
            "root": {
              "message":{}
            }
          },
          "metadata": {
            "dropped": 0,
            "component_url": "url",
              "severity": "INFO",
              "tags": [],

            "timestamp": 123,
          }
        });
        let expected_data = LogsDataBuilder::new(BuilderArgs {
            component_url: Some("url".into()),
            moniker: ExtendedMoniker::parse_str("a/b").unwrap(),
            severity: Severity::Info,
            timestamp: Timestamp::from_nanos(123),
        })
        .build();
        let original_data: LogsData = serde_json::from_value(original_json).unwrap();
        assert_eq!(original_data, expected_data);
        // We skip deserializing dropped
        assert_eq!(original_data.metadata.dropped, None);
    }

    #[fuchsia::test]
    fn severity_aliases() {
        assert_eq!(Severity::from_str("warn").unwrap(), Severity::Warn);
        assert_eq!(Severity::from_str("warning").unwrap(), Severity::Warn);
    }
}