relay_event_normalization/
event.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
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
//! Event normalization.
//!
//! This module provides a function to normalize events.

use std::collections::hash_map::DefaultHasher;

use std::hash::{Hash, Hasher};
use std::mem;
use std::sync::OnceLock;

use itertools::Itertools;
use regex::Regex;
use relay_base_schema::metrics::{
    can_be_valid_metric_name, DurationUnit, FractionUnit, MetricUnit,
};
use relay_event_schema::processor::{self, ProcessingAction, ProcessingState, Processor};
use relay_event_schema::protocol::{
    AsPair, ClientSdkInfo, Context, ContextInner, Contexts, DebugImage, DeviceClass, Event,
    EventId, EventType, Exception, Headers, IpAddr, Level, LogEntry, Measurement, Measurements,
    NelContext, PerformanceScoreContext, ReplayContext, Request, Span, SpanStatus, Tags, Timestamp,
    TraceContext, User, VALID_PLATFORMS,
};
use relay_protocol::{
    Annotated, Empty, Error, ErrorKind, FromValue, Getter, Meta, Object, Remark, RemarkType, Value,
};
use smallvec::SmallVec;
use uuid::Uuid;

use crate::normalize::request;
use crate::span::ai::normalize_ai_measurements;
use crate::span::tag_extraction::extract_span_tags_from_event;
use crate::utils::{self, get_event_user_tag, MAX_DURATION_MOBILE_MS};
use crate::{
    breakdowns, event_error, legacy, mechanism, remove_other, schema, span, stacktrace,
    transactions, trimming, user_agent, BorrowedSpanOpDefaults, BreakdownsConfig,
    CombinedMeasurementsConfig, GeoIpLookup, MaxChars, ModelCosts, PerformanceScoreConfig,
    RawUserAgentInfo, SpanDescriptionRule, TransactionNameConfig,
};

/// Configuration for [`normalize_event`].
#[derive(Clone, Debug)]
pub struct NormalizationConfig<'a> {
    /// The identifier of the target project, which gets added to the payload.
    pub project_id: Option<u64>,

    /// The name and version of the SDK that sent the event.
    pub client: Option<String>,

    /// The internal identifier of the DSN, which gets added to the payload.
    ///
    /// Note that this is different from the DSN's public key. The ID is usually numeric.
    pub key_id: Option<String>,

    /// The version of the protocol.
    ///
    /// This is a deprecated field, as there is no more versioning of Relay event payloads.
    pub protocol_version: Option<String>,

    /// Configuration for issue grouping.
    ///
    /// This configuration is persisted into the event payload to achieve idempotency in the
    /// processing pipeline and for reprocessing.
    pub grouping_config: Option<serde_json::Value>,

    /// The IP address of the SDK that sent the event.
    ///
    /// When `{{auto}}` is specified and there is no other IP address in the payload, such as in the
    /// `request` context, this IP address gets added to the `user` context.
    pub client_ip: Option<&'a IpAddr>,

    /// The SDK's sample rate as communicated via envelope headers.
    ///
    /// It is persisted into the event payload.
    pub client_sample_rate: Option<f64>,

    /// The user-agent and client hints obtained from the submission request headers.
    ///
    /// Client hints are the preferred way to infer device, operating system, and browser
    /// information should the event payload contain no such data. If no client hints are present,
    /// normalization falls back to the user agent.
    pub user_agent: RawUserAgentInfo<&'a str>,

    /// The maximum length for names of custom measurements.
    ///
    /// Measurements with longer names are removed from the transaction event and replaced with a
    /// metadata entry.
    pub max_name_and_unit_len: Option<usize>,

    /// Configuration for measurement normalization in transaction events.
    ///
    /// Has an optional [`crate::MeasurementsConfig`] from both the project and the global level.
    /// If at least one is provided, then normalization will truncate custom measurements
    /// and add units of known built-in measurements.
    pub measurements: Option<CombinedMeasurementsConfig<'a>>,

    /// Emit breakdowns based on given configuration.
    pub breakdowns_config: Option<&'a BreakdownsConfig>,

    /// When `Some(true)`, context information is extracted from the user agent.
    pub normalize_user_agent: Option<bool>,

    /// Configuration to apply to transaction names, especially around sanitizing.
    pub transaction_name_config: TransactionNameConfig<'a>,

    /// When `true`, it is assumed that the event has been normalized before.
    ///
    /// This disables certain normalizations, especially all that are not idempotent. The
    /// renormalize mode is intended for the use in the processing pipeline, so an event modified
    /// during ingestion can be validated against the schema and large data can be trimmed. However,
    /// advanced normalizations such as inferring contexts or clock drift correction are disabled.
    pub is_renormalize: bool,

    /// Overrides the default flag for other removal.
    pub remove_other: bool,

    /// When enabled, adds errors in the meta to the event's errors.
    pub emit_event_errors: bool,

    /// When `true`, infers the device class from CPU and model.
    pub device_class_synthesis_config: bool,

    /// When `true`, extracts tags from event and spans and materializes them into `span.data`.
    pub enrich_spans: bool,

    /// The maximum allowed size of tag values in bytes. Longer values will be cropped.
    pub max_tag_value_length: usize, // TODO: move span related fields into separate config.

    /// Configuration for replacing identifiers in the span description with placeholders.
    ///
    /// This is similar to `transaction_name_config`, but applies to span descriptions.
    pub span_description_rules: Option<&'a Vec<SpanDescriptionRule>>,

    /// Configuration for generating performance score measurements for web vitals
    pub performance_score: Option<&'a PerformanceScoreConfig>,

    /// Configuration for calculating the cost of AI model runs
    pub ai_model_costs: Option<&'a ModelCosts>,

    /// An initialized GeoIP lookup.
    pub geoip_lookup: Option<&'a GeoIpLookup>,

    /// When `Some(true)`, individual parts of the event payload is trimmed to a maximum size.
    ///
    /// See the event schema for size declarations.
    pub enable_trimming: bool,

    /// Controls whether spans should be normalized (e.g. normalizing the exclusive time).
    ///
    /// To normalize spans, `is_renormalize` must be disabled _and_ `normalize_spans` enabled.
    pub normalize_spans: bool,

    /// The identifier of the Replay running while this event was created.
    ///
    /// It is persisted into the event payload for correlation.
    pub replay_id: Option<Uuid>,

    /// Controls list of hosts to be excluded from scrubbing
    pub span_allowed_hosts: &'a [String],

    /// Rules to infer `span.op` from other span fields.
    pub span_op_defaults: BorrowedSpanOpDefaults<'a>,
}

impl Default for NormalizationConfig<'_> {
    fn default() -> Self {
        Self {
            project_id: Default::default(),
            client: Default::default(),
            key_id: Default::default(),
            protocol_version: Default::default(),
            grouping_config: Default::default(),
            client_ip: Default::default(),
            client_sample_rate: Default::default(),
            user_agent: Default::default(),
            max_name_and_unit_len: Default::default(),
            breakdowns_config: Default::default(),
            normalize_user_agent: Default::default(),
            transaction_name_config: Default::default(),
            is_renormalize: Default::default(),
            remove_other: Default::default(),
            emit_event_errors: Default::default(),
            device_class_synthesis_config: Default::default(),
            enrich_spans: Default::default(),
            max_tag_value_length: usize::MAX,
            span_description_rules: Default::default(),
            performance_score: Default::default(),
            geoip_lookup: Default::default(),
            ai_model_costs: Default::default(),
            enable_trimming: false,
            measurements: None,
            normalize_spans: true,
            replay_id: Default::default(),
            span_allowed_hosts: Default::default(),
            span_op_defaults: Default::default(),
        }
    }
}

/// Normalizes an event.
///
/// Normalization consists of applying a series of transformations on the event
/// payload based on the given configuration.
pub fn normalize_event(event: &mut Annotated<Event>, config: &NormalizationConfig) {
    let Annotated(Some(ref mut event), ref mut meta) = event else {
        return;
    };

    let is_renormalize = config.is_renormalize;

    // Convert legacy data structures to current format
    let _ = legacy::LegacyProcessor.process_event(event, meta, ProcessingState::root());

    if !is_renormalize {
        // Check for required and non-empty values
        let _ = schema::SchemaProcessor.process_event(event, meta, ProcessingState::root());

        normalize(event, meta, config);
    }

    if config.enable_trimming {
        // Trim large strings and databags down
        let _ =
            trimming::TrimmingProcessor::new().process_event(event, meta, ProcessingState::root());
    }

    if config.remove_other {
        // Remove unknown attributes at every level
        let _ =
            remove_other::RemoveOtherProcessor.process_event(event, meta, ProcessingState::root());
    }

    if config.emit_event_errors {
        // Add event errors for top-level keys
        let _ =
            event_error::EmitEventErrors::new().process_event(event, meta, ProcessingState::root());
    }
}

/// Normalizes the given event based on the given config.
fn normalize(event: &mut Event, meta: &mut Meta, config: &NormalizationConfig) {
    // Normalize the transaction.
    // (internally noops for non-transaction events).
    // TODO: Parts of this processor should probably be a filter so we
    // can revert some changes to ProcessingAction)
    let mut transactions_processor = transactions::TransactionsProcessor::new(
        config.transaction_name_config,
        config.span_op_defaults,
    );
    let _ = transactions_processor.process_event(event, meta, ProcessingState::root());

    // Process security reports first to ensure all props.
    normalize_security_report(event, config.client_ip, &config.user_agent);

    // Process NEL reports to ensure all props.
    normalize_nel_report(event, config.client_ip);

    // Insert IP addrs before recursing, since geo lookup depends on it.
    normalize_ip_addresses(
        &mut event.request,
        &mut event.user,
        event.platform.as_str(),
        config.client_ip,
    );

    if let Some(geoip_lookup) = config.geoip_lookup {
        if let Some(user) = event.user.value_mut() {
            normalize_user_geoinfo(geoip_lookup, user);
        }
    }

    // Validate the basic attributes we extract metrics from
    let _ = processor::apply(&mut event.release, |release, meta| {
        if crate::validate_release(release).is_ok() {
            Ok(())
        } else {
            meta.add_error(ErrorKind::InvalidData);
            Err(ProcessingAction::DeleteValueSoft)
        }
    });
    let _ = processor::apply(&mut event.environment, |environment, meta| {
        if crate::validate_environment(environment).is_ok() {
            Ok(())
        } else {
            meta.add_error(ErrorKind::InvalidData);
            Err(ProcessingAction::DeleteValueSoft)
        }
    });

    // Default required attributes, even if they have errors
    normalize_user(event);
    normalize_logentry(&mut event.logentry, meta);
    normalize_debug_meta(event);
    normalize_breadcrumbs(event);
    normalize_release_dist(event); // dist is a tag extracted along with other metrics from transactions
    normalize_event_tags(event); // Tags are added to every metric

    // TODO: Consider moving to store normalization
    if config.device_class_synthesis_config {
        normalize_device_class(event);
    }
    normalize_stacktraces(event);
    normalize_exceptions(event); // Browser extension filters look at the stacktrace
    normalize_user_agent(event, config.normalize_user_agent); // Legacy browsers filter
    normalize_event_measurements(
        event,
        config.measurements.clone(),
        config.max_name_and_unit_len,
    ); // Measurements are part of the metric extraction
    if let Some(version) = normalize_performance_score(event, config.performance_score) {
        event
            .contexts
            .get_or_insert_with(Contexts::new)
            .get_or_default::<PerformanceScoreContext>()
            .score_profile_version = Annotated::new(version);
    }
    normalize_ai_measurements(event, config.ai_model_costs);
    normalize_breakdowns(event, config.breakdowns_config); // Breakdowns are part of the metric extraction too
    normalize_default_attributes(event, meta, config);
    normalize_trace_context_tags(event);

    let _ = processor::apply(&mut event.request, |request, _| {
        request::normalize_request(request);
        Ok(())
    });

    // Some contexts need to be normalized before metrics extraction takes place.
    normalize_contexts(&mut event.contexts);

    if config.normalize_spans && event.ty.value() == Some(&EventType::Transaction) {
        crate::normalize::normalize_app_start_spans(event);
        span::exclusive_time::compute_span_exclusive_time(event);
    }

    if config.enrich_spans {
        extract_span_tags_from_event(
            event,
            config.max_tag_value_length,
            config.span_allowed_hosts,
        );
    }

    if let Some(context) = event.context_mut::<TraceContext>() {
        context.client_sample_rate = Annotated::from(config.client_sample_rate);
    }
    normalize_replay_context(event, config.replay_id);
}

fn normalize_replay_context(event: &mut Event, replay_id: Option<Uuid>) {
    if let Some(ref mut contexts) = event.contexts.value_mut() {
        if let Some(replay_id) = replay_id {
            contexts.add(ReplayContext {
                replay_id: Annotated::new(EventId(replay_id)),
                other: Object::default(),
            });
        }
    }
}

/// Backfills the client IP address on for the NEL reports.
fn normalize_nel_report(event: &mut Event, client_ip: Option<&IpAddr>) {
    if event.context::<NelContext>().is_none() {
        return;
    }

    if let Some(client_ip) = client_ip {
        let user = event.user.value_mut().get_or_insert_with(User::default);
        user.ip_address = Annotated::new(client_ip.to_owned());
    }
}

/// Backfills common security report attributes.
fn normalize_security_report(
    event: &mut Event,
    client_ip: Option<&IpAddr>,
    user_agent: &RawUserAgentInfo<&str>,
) {
    if !is_security_report(event) {
        // This event is not a security report, exit here.
        return;
    }

    event.logger.get_or_insert_with(|| "csp".to_string());

    if let Some(client_ip) = client_ip {
        let user = event.user.value_mut().get_or_insert_with(User::default);
        user.ip_address = Annotated::new(client_ip.to_owned());
    }

    if !user_agent.is_empty() {
        let headers = event
            .request
            .value_mut()
            .get_or_insert_with(Request::default)
            .headers
            .value_mut()
            .get_or_insert_with(Headers::default);

        user_agent.populate_event_headers(headers);
    }
}

fn is_security_report(event: &Event) -> bool {
    event.csp.value().is_some()
        || event.expectct.value().is_some()
        || event.expectstaple.value().is_some()
        || event.hpkp.value().is_some()
}

/// Backfills IP addresses in various places.
pub fn normalize_ip_addresses(
    request: &mut Annotated<Request>,
    user: &mut Annotated<User>,
    platform: Option<&str>,
    client_ip: Option<&IpAddr>,
) {
    // NOTE: This is highly order dependent, in the sense that both the statements within this
    // function need to be executed in a certain order, and that other normalization code
    // (geoip lookup) needs to run after this.
    //
    // After a series of regressions over the old Python spaghetti code we decided to put it
    // back into one function. If a desire to split this code up overcomes you, put this in a
    // new processor and make sure all of it runs before the rest of normalization.

    // Resolve {{auto}}
    if let Some(client_ip) = client_ip {
        if let Some(ref mut request) = request.value_mut() {
            if let Some(ref mut env) = request.env.value_mut() {
                if let Some(&mut Value::String(ref mut http_ip)) = env
                    .get_mut("REMOTE_ADDR")
                    .and_then(|annotated| annotated.value_mut().as_mut())
                {
                    if http_ip == "{{auto}}" {
                        *http_ip = client_ip.to_string();
                    }
                }
            }
        }

        if let Some(ref mut user) = user.value_mut() {
            if let Some(ref mut user_ip) = user.ip_address.value_mut() {
                if user_ip.is_auto() {
                    client_ip.clone_into(user_ip)
                }
            }
        }
    }

    // Copy IPs from request interface to user, and resolve platform-specific backfilling
    let http_ip = request
        .value()
        .and_then(|request| request.env.value())
        .and_then(|env| env.get("REMOTE_ADDR"))
        .and_then(Annotated::<Value>::as_str)
        .and_then(|ip| IpAddr::parse(ip).ok());

    if let Some(http_ip) = http_ip {
        let user = user.value_mut().get_or_insert_with(User::default);
        user.ip_address.value_mut().get_or_insert(http_ip);
    } else if let Some(client_ip) = client_ip {
        let user = user.value_mut().get_or_insert_with(User::default);
        // auto is already handled above
        if user.ip_address.value().is_none() {
            // In an ideal world all SDKs would set {{auto}} explicitly.
            if let Some("javascript") | Some("cocoa") | Some("objc") = platform {
                user.ip_address = Annotated::new(client_ip.to_owned());
            }
        }
    }
}

/// Sets the user's GeoIp info based on user's IP address.
pub fn normalize_user_geoinfo(geoip_lookup: &GeoIpLookup, user: &mut User) {
    // Infer user.geo from user.ip_address
    if user.geo.value().is_none() {
        if let Some(ip_address) = user.ip_address.value() {
            if let Ok(Some(geo)) = geoip_lookup.lookup(ip_address.as_str()) {
                user.geo.set_value(Some(geo));
            }
        }
    }
}

fn normalize_user(event: &mut Event) {
    let Annotated(Some(user), _) = &mut event.user else {
        return;
    };

    if !user.other.is_empty() {
        let data = user.data.value_mut().get_or_insert_with(Object::new);
        data.extend(std::mem::take(&mut user.other));
    }

    // We set the `sentry_user` field in the `Event` payload in order to have it ready for the extraction
    // pipeline.
    let event_user_tag = get_event_user_tag(user);
    user.sentry_user.set_value(event_user_tag);
}

fn normalize_logentry(logentry: &mut Annotated<LogEntry>, _meta: &mut Meta) {
    let _ = processor::apply(logentry, |logentry, meta| {
        crate::logentry::normalize_logentry(logentry, meta)
    });
}

/// Normalizes the debug images in the event's debug meta.
fn normalize_debug_meta(event: &mut Event) {
    let Annotated(Some(debug_meta), _) = &mut event.debug_meta else {
        return;
    };
    let Annotated(Some(debug_images), _) = &mut debug_meta.images else {
        return;
    };

    for annotated_image in debug_images {
        let _ = processor::apply(annotated_image, |image, meta| match image {
            DebugImage::Other(_) => {
                meta.add_error(Error::invalid("unsupported debug image type"));
                Err(ProcessingAction::DeleteValueSoft)
            }
            _ => Ok(()),
        });
    }
}

fn normalize_breadcrumbs(event: &mut Event) {
    let Annotated(Some(breadcrumbs), _) = &mut event.breadcrumbs else {
        return;
    };
    let Some(breadcrumbs) = breadcrumbs.values.value_mut() else {
        return;
    };

    for annotated_breadcrumb in breadcrumbs {
        let Annotated(Some(breadcrumb), _) = annotated_breadcrumb else {
            continue;
        };

        if breadcrumb.ty.value().is_empty() {
            breadcrumb.ty.set_value(Some("default".to_string()));
        }
        if breadcrumb.level.value().is_none() {
            breadcrumb.level.set_value(Some(Level::Info));
        }
    }
}

/// Ensures that the `release` and `dist` fields match up.
fn normalize_release_dist(event: &mut Event) {
    normalize_dist(&mut event.dist);
}

fn normalize_dist(distribution: &mut Annotated<String>) {
    let _ = processor::apply(distribution, |dist, meta| {
        let trimmed = dist.trim();
        if trimmed.is_empty() {
            return Err(ProcessingAction::DeleteValueHard);
        } else if bytecount::num_chars(trimmed.as_bytes()) > MaxChars::Distribution.limit() {
            meta.add_error(Error::new(ErrorKind::ValueTooLong));
            return Err(ProcessingAction::DeleteValueSoft);
        } else if trimmed != dist {
            *dist = trimmed.to_string();
        }
        Ok(())
    });
}

struct DedupCache(SmallVec<[u64; 16]>);

impl DedupCache {
    pub fn new() -> Self {
        Self(SmallVec::default())
    }

    pub fn probe<H: Hash>(&mut self, element: H) -> bool {
        let mut hasher = DefaultHasher::new();
        element.hash(&mut hasher);
        let hash = hasher.finish();

        if self.0.contains(&hash) {
            false
        } else {
            self.0.push(hash);
            true
        }
    }
}

/// Removes internal tags and adds tags for well-known attributes.
fn normalize_event_tags(event: &mut Event) {
    let tags = &mut event.tags.value_mut().get_or_insert_with(Tags::default).0;
    let environment = &mut event.environment;
    if environment.is_empty() {
        *environment = Annotated::empty();
    }

    // Fix case where legacy apps pass environment as a tag instead of a top level key
    if let Some(tag) = tags.remove("environment").and_then(Annotated::into_value) {
        environment.get_or_insert_with(|| tag);
    }

    // Remove internal tags, that are generated with a `sentry:` prefix when saving the event.
    // They are not allowed to be set by the client due to ambiguity. Also, deduplicate tags.
    let mut tag_cache = DedupCache::new();
    tags.retain(|entry| {
        match entry.value() {
            Some(tag) => match tag.key() {
                Some("release") | Some("dist") | Some("user") | Some("filename")
                | Some("function") => false,
                name => tag_cache.probe(name),
            },
            // ToValue will decide if we should skip serializing Annotated::empty()
            None => true,
        }
    });

    for tag in tags.iter_mut() {
        let _ = processor::apply(tag, |tag, _| {
            if let Some(key) = tag.key() {
                if key.is_empty() {
                    tag.0 = Annotated::from_error(Error::nonempty(), None);
                } else if bytecount::num_chars(key.as_bytes()) > MaxChars::TagKey.limit() {
                    tag.0 = Annotated::from_error(Error::new(ErrorKind::ValueTooLong), None);
                }
            }

            if let Some(value) = tag.value() {
                if value.is_empty() {
                    tag.1 = Annotated::from_error(Error::nonempty(), None);
                } else if bytecount::num_chars(value.as_bytes()) > MaxChars::TagValue.limit() {
                    tag.1 = Annotated::from_error(Error::new(ErrorKind::ValueTooLong), None);
                }
            }

            Ok(())
        });
    }

    let server_name = std::mem::take(&mut event.server_name);
    if server_name.value().is_some() {
        let tag_name = "server_name".to_string();
        tags.insert(tag_name, server_name);
    }

    let site = std::mem::take(&mut event.site);
    if site.value().is_some() {
        let tag_name = "site".to_string();
        tags.insert(tag_name, site);
    }
}

// Reads device specs (family, memory, cpu, etc) from context and sets the device.class tag to high,
// medium, or low.
fn normalize_device_class(event: &mut Event) {
    let tags = &mut event.tags.value_mut().get_or_insert_with(Tags::default).0;
    let tag_name = "device.class".to_owned();
    // Remove any existing device.class tag set by the client, since this should only be set by relay.
    tags.remove("device.class");
    if let Some(contexts) = event.contexts.value() {
        if let Some(device_class) = DeviceClass::from_contexts(contexts) {
            tags.insert(tag_name, Annotated::new(device_class.to_string()));
        }
    }
}

/// Normalizes all the stack traces in the given event.
///
/// Normalized stack traces are `event.stacktrace`, `event.exceptions.stacktrace`, and
/// `event.thread.stacktrace`. Raw stack traces are not normalized.
fn normalize_stacktraces(event: &mut Event) {
    normalize_event_stacktrace(event);
    normalize_exception_stacktraces(event);
    normalize_thread_stacktraces(event);
}

/// Normalizes an event's stack trace, in `event.stacktrace`.
fn normalize_event_stacktrace(event: &mut Event) {
    let Annotated(Some(stacktrace), meta) = &mut event.stacktrace else {
        return;
    };
    stacktrace::normalize_stacktrace(&mut stacktrace.0, meta);
}

/// Normalizes the stack traces in an event's exceptions, in `event.exceptions.stacktraces`.
///
/// Note: the raw stack traces, in `event.exceptions.raw_stacktraces` is not normalized.
fn normalize_exception_stacktraces(event: &mut Event) {
    let Some(event_exception) = event.exceptions.value_mut() else {
        return;
    };
    let Some(exceptions) = event_exception.values.value_mut() else {
        return;
    };
    for annotated_exception in exceptions {
        let Some(exception) = annotated_exception.value_mut() else {
            continue;
        };
        if let Annotated(Some(stacktrace), meta) = &mut exception.stacktrace {
            stacktrace::normalize_stacktrace(&mut stacktrace.0, meta);
        }
    }
}

/// Normalizes the stack traces in an event's threads, in `event.threads.stacktraces`.
///
/// Note: the raw stack traces, in `event.threads.raw_stacktraces`, is not normalized.
fn normalize_thread_stacktraces(event: &mut Event) {
    let Some(event_threads) = event.threads.value_mut() else {
        return;
    };
    let Some(threads) = event_threads.values.value_mut() else {
        return;
    };
    for annotated_thread in threads {
        let Some(thread) = annotated_thread.value_mut() else {
            continue;
        };
        if let Annotated(Some(stacktrace), meta) = &mut thread.stacktrace {
            stacktrace::normalize_stacktrace(&mut stacktrace.0, meta);
        }
    }
}

fn normalize_exceptions(event: &mut Event) {
    let os_hint = mechanism::OsHint::from_event(event);

    if let Some(exception_values) = event.exceptions.value_mut() {
        if let Some(exceptions) = exception_values.values.value_mut() {
            if exceptions.len() == 1 && event.stacktrace.value().is_some() {
                if let Some(exception) = exceptions.get_mut(0) {
                    if let Some(exception) = exception.value_mut() {
                        mem::swap(&mut exception.stacktrace, &mut event.stacktrace);
                        event.stacktrace = Annotated::empty();
                    }
                }
            }

            // Exception mechanism needs SDK information to resolve proper names in
            // exception meta (such as signal names). "SDK Information" really means
            // the operating system version the event was generated on. Some
            // normalization still works without sdk_info, such as mach_exception
            // names (they can only occur on macOS).
            //
            // We also want to validate some other aspects of it.
            for exception in exceptions {
                normalize_exception(exception);
                if let Some(exception) = exception.value_mut() {
                    if let Some(mechanism) = exception.mechanism.value_mut() {
                        mechanism::normalize_mechanism(mechanism, os_hint);
                    }
                }
            }
        }
    }
}

fn normalize_exception(exception: &mut Annotated<Exception>) {
    static TYPE_VALUE_RE: OnceLock<Regex> = OnceLock::new();
    let regex = TYPE_VALUE_RE.get_or_init(|| Regex::new(r"^(\w+):(.*)$").unwrap());

    let _ = processor::apply(exception, |exception, meta| {
        if exception.ty.value().is_empty() {
            if let Some(value_str) = exception.value.value_mut() {
                let new_values = regex
                    .captures(value_str)
                    .map(|cap| (cap[1].to_string(), cap[2].trim().to_string().into()));

                if let Some((new_type, new_value)) = new_values {
                    exception.ty.set_value(Some(new_type));
                    *value_str = new_value;
                }
            }
        }

        if exception.ty.value().is_empty() && exception.value.value().is_empty() {
            meta.add_error(Error::with(ErrorKind::MissingAttribute, |error| {
                error.insert("attribute", "type or value");
            }));
            return Err(ProcessingAction::DeleteValueSoft);
        }

        Ok(())
    });
}

fn normalize_user_agent(_event: &mut Event, normalize_user_agent: Option<bool>) {
    if normalize_user_agent.unwrap_or(false) {
        user_agent::normalize_user_agent(_event);
    }
}

/// Ensures measurements interface is only present for transaction events.
fn normalize_event_measurements(
    event: &mut Event,
    measurements_config: Option<CombinedMeasurementsConfig>,
    max_mri_len: Option<usize>,
) {
    if event.ty.value() != Some(&EventType::Transaction) {
        // Only transaction events may have a measurements interface
        event.measurements = Annotated::empty();
    } else if let Annotated(Some(ref mut measurements), ref mut meta) = event.measurements {
        normalize_measurements(
            measurements,
            meta,
            measurements_config,
            max_mri_len,
            event.start_timestamp.0,
            event.timestamp.0,
        );
    }
}

/// Ensure only valid measurements are ingested.
pub fn normalize_measurements(
    measurements: &mut Measurements,
    meta: &mut Meta,
    measurements_config: Option<CombinedMeasurementsConfig>,
    max_mri_len: Option<usize>,
    start_timestamp: Option<Timestamp>,
    end_timestamp: Option<Timestamp>,
) {
    normalize_mobile_measurements(measurements);
    normalize_units(measurements);

    let duration_millis = match (start_timestamp, end_timestamp) {
        (Some(start), Some(end)) => relay_common::time::chrono_to_positive_millis(end - start),
        _ => 0.0,
    };

    compute_measurements(duration_millis, measurements);
    if let Some(measurements_config) = measurements_config {
        remove_invalid_measurements(measurements, meta, measurements_config, max_mri_len);
    }
}

pub trait MutMeasurements {
    fn measurements(&mut self) -> &mut Annotated<Measurements>;
}

/// Computes performance score measurements for an event.
///
/// This computes score from vital measurements, using config options to define how it is
/// calculated.
pub fn normalize_performance_score(
    event: &mut (impl Getter + MutMeasurements),
    performance_score: Option<&PerformanceScoreConfig>,
) -> Option<String> {
    let mut version = None;
    let Some(performance_score) = performance_score else {
        return version;
    };
    for profile in &performance_score.profiles {
        if let Some(condition) = &profile.condition {
            if !condition.matches(event) {
                continue;
            }
            if let Some(measurements) = event.measurements().value_mut() {
                let mut should_add_total = false;
                if profile.score_components.iter().any(|c| {
                    !measurements.contains_key(c.measurement.as_str())
                        && c.weight.abs() >= f64::EPSILON
                        && !c.optional
                }) {
                    // All non-optional measurements with a profile weight greater than 0 are
                    // required to exist on the event. Skip this profile if
                    // a measurement with weight is missing.
                    continue;
                }
                let mut score_total = 0.0f64;
                let mut weight_total = 0.0f64;
                for component in &profile.score_components {
                    // Skip optional components if they are not present on the event.
                    if component.optional
                        && !measurements.contains_key(component.measurement.as_str())
                    {
                        continue;
                    }
                    weight_total += component.weight;
                }
                if weight_total.abs() < f64::EPSILON {
                    // All components are optional or have a weight of `0`. We cannot compute
                    // component weights, so we bail.
                    continue;
                }
                for component in &profile.score_components {
                    // Optional measurements that are not present are given a weight of 0.
                    let mut normalized_component_weight = 0.0;
                    if let Some(value) = measurements.get_value(component.measurement.as_str()) {
                        normalized_component_weight = component.weight / weight_total;
                        let cdf = utils::calculate_cdf_score(
                            value.max(0.0), // Webvitals can't be negative, but we need to clamp in case of bad data.
                            component.p10,
                            component.p50,
                        );
                        let component_score = cdf * normalized_component_weight;
                        score_total += component_score;
                        should_add_total = true;

                        measurements.insert(
                            format!("score.{}", component.measurement),
                            Measurement {
                                value: component_score.into(),
                                unit: (MetricUnit::Fraction(FractionUnit::Ratio)).into(),
                            }
                            .into(),
                        );
                    }
                    measurements.insert(
                        format!("score.weight.{}", component.measurement),
                        Measurement {
                            value: normalized_component_weight.into(),
                            unit: (MetricUnit::Fraction(FractionUnit::Ratio)).into(),
                        }
                        .into(),
                    );
                }
                if should_add_total {
                    version.clone_from(&profile.version);
                    measurements.insert(
                        "score.total".to_owned(),
                        Measurement {
                            value: score_total.into(),
                            unit: (MetricUnit::Fraction(FractionUnit::Ratio)).into(),
                        }
                        .into(),
                    );
                }
            }
            break; // Stop after the first matching profile.
        }
    }
    version
}

// Extracts lcp related tags from the trace context.
fn normalize_trace_context_tags(event: &mut Event) {
    let tags = &mut event.tags.value_mut().get_or_insert_with(Tags::default).0;
    if let Some(contexts) = event.contexts.value() {
        if let Some(trace_context) = contexts.get::<TraceContext>() {
            if let Some(data) = trace_context.data.value() {
                if let Some(lcp_element) = data.lcp_element.value() {
                    if !tags.contains("lcp.element") {
                        let tag_name = "lcp.element".to_string();
                        tags.insert(tag_name, Annotated::new(lcp_element.clone()));
                    }
                }
                if let Some(lcp_size) = data.lcp_size.value() {
                    if !tags.contains("lcp.size") {
                        let tag_name = "lcp.size".to_string();
                        tags.insert(tag_name, Annotated::new(lcp_size.to_string()));
                    }
                }
                if let Some(lcp_id) = data.lcp_id.value() {
                    let tag_name = "lcp.id".to_string();
                    if !tags.contains("lcp.id") {
                        tags.insert(tag_name, Annotated::new(lcp_id.clone()));
                    }
                }
                if let Some(lcp_url) = data.lcp_url.value() {
                    let tag_name = "lcp.url".to_string();
                    if !tags.contains("lcp.url") {
                        tags.insert(tag_name, Annotated::new(lcp_url.clone()));
                    }
                }
            }
        }
    }
}

impl MutMeasurements for Event {
    fn measurements(&mut self) -> &mut Annotated<Measurements> {
        &mut self.measurements
    }
}

impl MutMeasurements for Span {
    fn measurements(&mut self) -> &mut Annotated<Measurements> {
        &mut self.measurements
    }
}

/// Compute additional measurements derived from existing ones.
///
/// The added measurements are:
///
/// ```text
/// frames_slow_rate := measurements.frames_slow / measurements.frames_total
/// frames_frozen_rate := measurements.frames_frozen / measurements.frames_total
/// stall_percentage := measurements.stall_total_time / transaction.duration
/// ```
fn compute_measurements(transaction_duration_ms: f64, measurements: &mut Measurements) {
    if let Some(frames_total) = measurements.get_value("frames_total") {
        if frames_total > 0.0 {
            if let Some(frames_frozen) = measurements.get_value("frames_frozen") {
                let frames_frozen_rate = Measurement {
                    value: (frames_frozen / frames_total).into(),
                    unit: (MetricUnit::Fraction(FractionUnit::Ratio)).into(),
                };
                measurements.insert("frames_frozen_rate".to_owned(), frames_frozen_rate.into());
            }
            if let Some(frames_slow) = measurements.get_value("frames_slow") {
                let frames_slow_rate = Measurement {
                    value: (frames_slow / frames_total).into(),
                    unit: MetricUnit::Fraction(FractionUnit::Ratio).into(),
                };
                measurements.insert("frames_slow_rate".to_owned(), frames_slow_rate.into());
            }
        }
    }

    // Get stall_percentage
    if transaction_duration_ms > 0.0 {
        if let Some(stall_total_time) = measurements
            .get("stall_total_time")
            .and_then(Annotated::value)
        {
            if matches!(
                stall_total_time.unit.value(),
                // Accept milliseconds or None, but not other units
                Some(&MetricUnit::Duration(DurationUnit::MilliSecond) | &MetricUnit::None) | None
            ) {
                if let Some(stall_total_time) = stall_total_time.value.0 {
                    let stall_percentage = Measurement {
                        value: (stall_total_time / transaction_duration_ms).into(),
                        unit: (MetricUnit::Fraction(FractionUnit::Ratio)).into(),
                    };
                    measurements.insert("stall_percentage".to_owned(), stall_percentage.into());
                }
            }
        }
    }
}

/// Emit any breakdowns
fn normalize_breakdowns(event: &mut Event, breakdowns_config: Option<&BreakdownsConfig>) {
    match breakdowns_config {
        None => {}
        Some(config) => breakdowns::normalize_breakdowns(event, config),
    }
}

fn normalize_default_attributes(event: &mut Event, meta: &mut Meta, config: &NormalizationConfig) {
    let event_type = infer_event_type(event);
    event.ty = Annotated::from(event_type);
    event.project = Annotated::from(config.project_id);
    event.key_id = Annotated::from(config.key_id.clone());
    event.version = Annotated::from(config.protocol_version.clone());
    event.grouping_config = config
        .grouping_config
        .clone()
        .map_or(Annotated::empty(), |x| {
            FromValue::from_value(Annotated::<Value>::from(x))
        });

    let _ = relay_event_schema::processor::apply(&mut event.platform, |platform, _| {
        if is_valid_platform(platform) {
            Ok(())
        } else {
            Err(ProcessingAction::DeleteValueSoft)
        }
    });

    // Default required attributes, even if they have errors
    event.errors.get_or_insert_with(Vec::new);
    event.id.get_or_insert_with(EventId::new);
    event.platform.get_or_insert_with(|| "other".to_string());
    event.logger.get_or_insert_with(String::new);
    event.extra.get_or_insert_with(Object::new);
    event.level.get_or_insert_with(|| match event_type {
        EventType::Transaction => Level::Info,
        _ => Level::Error,
    });
    if event.client_sdk.value().is_none() {
        event.client_sdk.set_value(get_sdk_info(config));
    }

    if event.platform.as_str() == Some("java") {
        if let Some(event_logger) = event.logger.value_mut().take() {
            let shortened = shorten_logger(event_logger, meta);
            event.logger.set_value(Some(shortened));
        }
    }
}

/// Returns `true` if the given platform string is a known platform identifier.
///
/// See [`VALID_PLATFORMS`] for a list of all known platforms.
pub fn is_valid_platform(platform: &str) -> bool {
    VALID_PLATFORMS.contains(&platform)
}

/// Infers the `EventType` from the event's interfaces.
fn infer_event_type(event: &Event) -> EventType {
    // The event type may be set explicitly when constructing the event items from specific
    // items. This is DEPRECATED, and each distinct event type may get its own base class. For
    // the time being, this is only implemented for transactions, so be specific:
    if event.ty.value() == Some(&EventType::Transaction) {
        return EventType::Transaction;
    }
    if event.ty.value() == Some(&EventType::UserReportV2) {
        return EventType::UserReportV2;
    }

    // The SDKs do not describe event types, and we must infer them from available attributes.
    let has_exceptions = event
        .exceptions
        .value()
        .and_then(|exceptions| exceptions.values.value())
        .filter(|values| !values.is_empty())
        .is_some();

    if has_exceptions {
        EventType::Error
    } else if event.csp.value().is_some() {
        EventType::Csp
    } else if event.hpkp.value().is_some() {
        EventType::Hpkp
    } else if event.expectct.value().is_some() {
        EventType::ExpectCt
    } else if event.expectstaple.value().is_some() {
        EventType::ExpectStaple
    } else if event.context::<NelContext>().is_some() {
        EventType::Nel
    } else {
        EventType::Default
    }
}

/// Returns the SDK info from the config.
fn get_sdk_info(config: &NormalizationConfig) -> Option<ClientSdkInfo> {
    config.client.as_ref().and_then(|client| {
        client
            .splitn(2, '/')
            .collect_tuple()
            .or_else(|| client.splitn(2, ' ').collect_tuple())
            .map(|(name, version)| ClientSdkInfo {
                name: Annotated::new(name.to_owned()),
                version: Annotated::new(version.to_owned()),
                ..Default::default()
            })
    })
}

/// If the logger is longer than [`MaxChars::Logger`], it returns a String with
/// a shortened version of the logger. If not, the same logger is returned as a
/// String. The resulting logger is always trimmed.
///
/// To shorten the logger, all extra chars that don't fit into the maximum limit
/// are removed, from the beginning of the logger.  Then, if the remaining
/// substring contains a `.` somewhere but in the end, all chars until `.`
/// (exclusive) are removed.
///
/// Additionally, the new logger is prefixed with `*`, to indicate it was
/// shortened.
fn shorten_logger(logger: String, meta: &mut Meta) -> String {
    let original_len = bytecount::num_chars(logger.as_bytes());
    let trimmed = logger.trim();
    let logger_len = bytecount::num_chars(trimmed.as_bytes());
    if logger_len <= MaxChars::Logger.limit() {
        if trimmed == logger {
            return logger;
        } else {
            if trimmed.is_empty() {
                meta.add_remark(Remark {
                    ty: RemarkType::Removed,
                    rule_id: "@logger:remove".to_owned(),
                    range: Some((0, original_len)),
                });
            } else {
                meta.add_remark(Remark {
                    ty: RemarkType::Substituted,
                    rule_id: "@logger:trim".to_owned(),
                    range: None,
                });
            }
            meta.set_original_length(Some(original_len));
            return trimmed.to_string();
        };
    }

    let mut tokens = trimmed.split("").collect_vec();
    // Remove empty str tokens from the beginning and end.
    tokens.pop();
    tokens.reverse(); // Prioritize chars from the end of the string.
    tokens.pop();

    let word_cut = remove_logger_extra_chars(&mut tokens);
    if word_cut {
        remove_logger_word(&mut tokens);
    }

    tokens.reverse();
    meta.add_remark(Remark {
        ty: RemarkType::Substituted,
        rule_id: "@logger:replace".to_owned(),
        range: Some((0, logger_len - tokens.len())),
    });
    meta.set_original_length(Some(original_len));

    format!("*{}", tokens.join(""))
}

/// Remove as many tokens as needed to match the maximum char limit defined in
/// [`MaxChars::Logger`], and an extra token for the logger prefix. Returns
/// whether a word has been cut.
///
/// A word is considered any non-empty substring that doesn't contain a `.`.
fn remove_logger_extra_chars(tokens: &mut Vec<&str>) -> bool {
    // Leave one slot of space for the prefix
    let mut remove_chars = tokens.len() - MaxChars::Logger.limit() + 1;
    let mut word_cut = false;
    while remove_chars > 0 {
        if let Some(c) = tokens.pop() {
            if !word_cut && c != "." {
                word_cut = true;
            } else if word_cut && c == "." {
                word_cut = false;
            }
        }
        remove_chars -= 1;
    }
    word_cut
}

/// If the `.` token is present, removes all tokens from the end of the vector
/// until `.`. If it isn't present, nothing is removed.
fn remove_logger_word(tokens: &mut Vec<&str>) {
    let mut delimiter_found = false;
    for token in tokens.iter() {
        if *token == "." {
            delimiter_found = true;
            break;
        }
    }
    if !delimiter_found {
        return;
    }
    while let Some(i) = tokens.last() {
        if *i == "." {
            break;
        }
        tokens.pop();
    }
}

/// Normalizes incoming contexts for the downstream metric extraction.
fn normalize_contexts(contexts: &mut Annotated<Contexts>) {
    let _ = processor::apply(contexts, |contexts, _meta| {
        // Reprocessing context sent from SDKs must not be accepted, it is a Sentry-internal
        // construct.
        // [`normalize`] does not run on renormalization anyway.
        contexts.0.remove("reprocessing");

        for annotated in &mut contexts.0.values_mut() {
            if let Some(ContextInner(Context::Trace(context))) = annotated.value_mut() {
                context.status.get_or_insert_with(|| SpanStatus::Unknown);
            }
            if let Some(context_inner) = annotated.value_mut() {
                crate::normalize::contexts::normalize_context(&mut context_inner.0);
            }
        }

        Ok(())
    });
}

/// New SDKs do not send measurements when they exceed 180 seconds.
///
/// Drop those outlier measurements for older SDKs.
fn filter_mobile_outliers(measurements: &mut Measurements) {
    for key in [
        "app_start_cold",
        "app_start_warm",
        "time_to_initial_display",
        "time_to_full_display",
    ] {
        if let Some(value) = measurements.get_value(key) {
            if value > MAX_DURATION_MOBILE_MS {
                measurements.remove(key);
            }
        }
    }
}

fn normalize_mobile_measurements(measurements: &mut Measurements) {
    normalize_app_start_measurements(measurements);
    filter_mobile_outliers(measurements);
}

fn normalize_units(measurements: &mut Measurements) {
    for (name, measurement) in measurements.iter_mut() {
        let measurement = match measurement.value_mut() {
            Some(m) => m,
            None => continue,
        };

        let stated_unit = measurement.unit.value().copied();
        let default_unit = get_metric_measurement_unit(name);
        measurement
            .unit
            .set_value(Some(stated_unit.or(default_unit).unwrap_or_default()))
    }
}

/// Remove measurements that do not conform to the given config.
///
/// Built-in measurements are accepted if their unit is correct, dropped otherwise.
/// Custom measurements are accepted up to a limit.
///
/// Note that [`Measurements`] is a BTreeMap, which means its keys are sorted.
/// This ensures that for two events with the same measurement keys, the same set of custom
/// measurements is retained.
fn remove_invalid_measurements(
    measurements: &mut Measurements,
    meta: &mut Meta,
    measurements_config: CombinedMeasurementsConfig,
    max_name_and_unit_len: Option<usize>,
) {
    let max_custom_measurements = measurements_config.max_custom_measurements().unwrap_or(0);

    let mut custom_measurements_count = 0;
    let mut removed_measurements = Object::new();

    measurements.retain(|name, value| {
        let measurement = match value.value_mut() {
            Some(m) => m,
            None => return false,
        };

        if !can_be_valid_metric_name(name) {
            meta.add_error(Error::invalid(format!(
                "Metric name contains invalid characters: \"{name}\""
            )));
            removed_measurements.insert(name.clone(), Annotated::new(std::mem::take(measurement)));
            return false;
        }

        // TODO(jjbayer): Should we actually normalize the unit into the event?
        let unit = measurement.unit.value().unwrap_or(&MetricUnit::None);

        if let Some(max_name_and_unit_len) = max_name_and_unit_len {
            let max_name_len = max_name_and_unit_len - unit.to_string().len();

            if name.len() > max_name_len {
                meta.add_error(Error::invalid(format!(
                    "Metric name too long {}/{max_name_len}: \"{name}\"",
                    name.len(),
                )));
                removed_measurements
                    .insert(name.clone(), Annotated::new(std::mem::take(measurement)));
                return false;
            }
        }

        // Check if this is a builtin measurement:
        for builtin_measurement in measurements_config.builtin_measurement_keys() {
            if builtin_measurement.name() == name {
                let value = measurement.value.value().unwrap_or(&0.0);
                // Drop negative values if the builtin measurement does not allow them.
                if !builtin_measurement.allow_negative() && *value < 0.0 {
                    meta.add_error(Error::invalid(format!(
                        "Negative value for measurement {name} not allowed: {value}",
                    )));
                    removed_measurements
                        .insert(name.clone(), Annotated::new(std::mem::take(measurement)));
                    return false;
                }
                // If the unit matches a built-in measurement, we allow it.
                // If the name matches but the unit is wrong, we do not even accept it as a custom measurement,
                // and just drop it instead.
                return builtin_measurement.unit() == unit;
            }
        }

        // For custom measurements, check the budget:
        if custom_measurements_count < max_custom_measurements {
            custom_measurements_count += 1;
            return true;
        }

        meta.add_error(Error::invalid(format!("Too many measurements: {name}")));
        removed_measurements.insert(name.clone(), Annotated::new(std::mem::take(measurement)));

        false
    });

    if !removed_measurements.is_empty() {
        meta.set_original_value(Some(removed_measurements));
    }
}

/// Returns the unit of the provided metric.
///
/// For known measurements, this returns `Some(MetricUnit)`, which can also include
/// `Some(MetricUnit::None)`. For unknown measurement names, this returns `None`.
fn get_metric_measurement_unit(measurement_name: &str) -> Option<MetricUnit> {
    match measurement_name {
        // Web
        "fcp" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
        "lcp" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
        "fid" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
        "fp" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
        "inp" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
        "ttfb" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
        "ttfb.requesttime" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
        "cls" => Some(MetricUnit::None),

        // Mobile
        "app_start_cold" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
        "app_start_warm" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
        "frames_total" => Some(MetricUnit::None),
        "frames_slow" => Some(MetricUnit::None),
        "frames_slow_rate" => Some(MetricUnit::Fraction(FractionUnit::Ratio)),
        "frames_frozen" => Some(MetricUnit::None),
        "frames_frozen_rate" => Some(MetricUnit::Fraction(FractionUnit::Ratio)),
        "time_to_initial_display" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
        "time_to_full_display" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),

        // React-Native
        "stall_count" => Some(MetricUnit::None),
        "stall_total_time" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
        "stall_longest_time" => Some(MetricUnit::Duration(DurationUnit::MilliSecond)),
        "stall_percentage" => Some(MetricUnit::Fraction(FractionUnit::Ratio)),

        // Default
        _ => None,
    }
}

/// Replaces dot.case app start measurements keys with snake_case keys.
///
/// The dot.case app start measurements keys are treated as custom measurements.
/// The snake_case is the key expected by the Sentry UI to aggregate and display in graphs.
fn normalize_app_start_measurements(measurements: &mut Measurements) {
    if let Some(app_start_cold_value) = measurements.remove("app.start.cold") {
        measurements.insert("app_start_cold".to_string(), app_start_cold_value);
    }
    if let Some(app_start_warm_value) = measurements.remove("app.start.warm") {
        measurements.insert("app_start_warm".to_string(), app_start_warm_value);
    }
}

#[cfg(test)]
mod tests {

    use std::collections::BTreeMap;

    use insta::assert_debug_snapshot;
    use itertools::Itertools;
    use relay_common::glob2::LazyGlob;
    use relay_event_schema::protocol::{Breadcrumb, Csp, DebugMeta, DeviceContext, Values};
    use relay_protocol::{get_value, SerializableAnnotated};
    use serde_json::json;

    use super::*;
    use crate::{ClientHints, MeasurementsConfig, ModelCost};

    const IOS_MOBILE_EVENT: &str = r#"
        {
            "sdk": {"name": "sentry.cocoa"},
            "contexts": {
                "trace": {
                    "op": "ui.load"
                }
            },
            "measurements": {
                "app_start_warm": {
                    "value": 8049.345970153808,
                    "unit": "millisecond"
                },
                "time_to_full_display": {
                    "value": 8240.571022033691,
                    "unit": "millisecond"
                },
                "time_to_initial_display": {
                    "value": 8049.345970153808,
                    "unit": "millisecond"
                }
            }
        }
        "#;

    const ANDROID_MOBILE_EVENT: &str = r#"
        {
            "sdk": {"name": "sentry.java.android"},
            "contexts": {
                "trace": {
                    "op": "ui.load"
                }
            },
            "measurements": {
                "app_start_cold": {
                    "value": 22648,
                    "unit": "millisecond"
                },
                "time_to_full_display": {
                    "value": 22647,
                    "unit": "millisecond"
                },
                "time_to_initial_display": {
                    "value": 22647,
                    "unit": "millisecond"
                }
            }
        }
        "#;

    #[test]
    fn test_normalize_dist_none() {
        let mut dist = Annotated::default();
        normalize_dist(&mut dist);
        assert_eq!(dist.value(), None);
    }

    #[test]
    fn test_normalize_dist_empty() {
        let mut dist = Annotated::new("".to_string());
        normalize_dist(&mut dist);
        assert_eq!(dist.value(), None);
    }

    #[test]
    fn test_normalize_dist_trim() {
        let mut dist = Annotated::new(" foo  ".to_string());
        normalize_dist(&mut dist);
        assert_eq!(dist.value(), Some(&"foo".to_string()));
    }

    #[test]
    fn test_normalize_dist_whitespace() {
        let mut dist = Annotated::new(" ".to_owned());
        normalize_dist(&mut dist);
        assert_eq!(dist.value(), None);
    }

    #[test]
    fn test_normalize_platform_and_level_with_transaction_event() {
        let json = r#"
        {
            "type": "transaction"
        }
        "#;

        let Annotated(Some(mut event), mut meta) = Annotated::<Event>::from_json(json).unwrap()
        else {
            panic!("Invalid transaction json");
        };

        normalize_default_attributes(&mut event, &mut meta, &NormalizationConfig::default());

        assert_eq!(event.level.value().unwrap().to_string(), "info");
        assert_eq!(event.ty.value().unwrap().to_string(), "transaction");
        assert_eq!(event.platform.as_str().unwrap(), "other");
    }

    #[test]
    fn test_normalize_platform_and_level_with_error_event() {
        let json = r#"
        {
            "type": "error",
            "exception": {
                "values": [{"type": "ValueError", "value": "Should not happen"}]
            }
        }
        "#;

        let Annotated(Some(mut event), mut meta) = Annotated::<Event>::from_json(json).unwrap()
        else {
            panic!("Invalid error json");
        };

        normalize_default_attributes(&mut event, &mut meta, &NormalizationConfig::default());

        assert_eq!(event.level.value().unwrap().to_string(), "error");
        assert_eq!(event.ty.value().unwrap().to_string(), "error");
        assert_eq!(event.platform.value().unwrap().to_owned(), "other");
    }

    #[test]
    fn test_computed_measurements() {
        let json = r#"
        {
            "type": "transaction",
            "timestamp": "2021-04-26T08:00:05+0100",
            "start_timestamp": "2021-04-26T08:00:00+0100",
            "measurements": {
                "frames_slow": {"value": 1},
                "frames_frozen": {"value": 2},
                "frames_total": {"value": 4},
                "stall_total_time": {"value": 4000, "unit": "millisecond"}
            }
        }
        "#;

        let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();

        normalize_event_measurements(&mut event, None, None);

        insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {}, @r#"
        {
          "type": "transaction",
          "timestamp": 1619420405.0,
          "start_timestamp": 1619420400.0,
          "measurements": {
            "frames_frozen": {
              "value": 2.0,
              "unit": "none",
            },
            "frames_frozen_rate": {
              "value": 0.5,
              "unit": "ratio",
            },
            "frames_slow": {
              "value": 1.0,
              "unit": "none",
            },
            "frames_slow_rate": {
              "value": 0.25,
              "unit": "ratio",
            },
            "frames_total": {
              "value": 4.0,
              "unit": "none",
            },
            "stall_percentage": {
              "value": 0.8,
              "unit": "ratio",
            },
            "stall_total_time": {
              "value": 4000.0,
              "unit": "millisecond",
            },
          },
        }
        "#);
    }

    #[test]
    fn test_filter_custom_measurements() {
        let json = r#"
        {
            "type": "transaction",
            "timestamp": "2021-04-26T08:00:05+0100",
            "start_timestamp": "2021-04-26T08:00:00+0100",
            "measurements": {
                "my_custom_measurement_1": {"value": 123},
                "frames_frozen": {"value": 666, "unit": "invalid_unit"},
                "frames_slow": {"value": 1},
                "my_custom_measurement_3": {"value": 456},
                "my_custom_measurement_2": {"value": 789}
            }
        }
        "#;
        let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();

        let project_measurement_config: MeasurementsConfig = serde_json::from_value(json!({
            "builtinMeasurements": [
                {"name": "frames_frozen", "unit": "none"},
                {"name": "frames_slow", "unit": "none"}
            ],
            "maxCustomMeasurements": 2,
            "stray_key": "zzz"
        }))
        .unwrap();

        let dynamic_measurement_config =
            CombinedMeasurementsConfig::new(Some(&project_measurement_config), None);

        normalize_event_measurements(&mut event, Some(dynamic_measurement_config), None);

        // Only two custom measurements are retained, in alphabetic order (1 and 2)
        insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {}, @r#"
        {
          "type": "transaction",
          "timestamp": 1619420405.0,
          "start_timestamp": 1619420400.0,
          "measurements": {
            "frames_slow": {
              "value": 1.0,
              "unit": "none",
            },
            "my_custom_measurement_1": {
              "value": 123.0,
              "unit": "none",
            },
            "my_custom_measurement_2": {
              "value": 789.0,
              "unit": "none",
            },
          },
          "_meta": {
            "measurements": {
              "": Meta(Some(MetaInner(
                err: [
                  [
                    "invalid_data",
                    {
                      "reason": "Too many measurements: my_custom_measurement_3",
                    },
                  ],
                ],
                val: Some({
                  "my_custom_measurement_3": {
                    "unit": "none",
                    "value": 456.0,
                  },
                }),
              ))),
            },
          },
        }
        "#);
    }

    #[test]
    fn test_normalize_units() {
        let mut measurements = Annotated::<Measurements>::from_json(
            r#"{
                "fcp": {"value": 1.1},
                "stall_count": {"value": 3.3},
                "foo": {"value": 8.8}
            }"#,
        )
        .unwrap()
        .into_value()
        .unwrap();
        insta::assert_debug_snapshot!(measurements, @r#"
        Measurements(
            {
                "fcp": Measurement {
                    value: 1.1,
                    unit: ~,
                },
                "foo": Measurement {
                    value: 8.8,
                    unit: ~,
                },
                "stall_count": Measurement {
                    value: 3.3,
                    unit: ~,
                },
            },
        )
        "#);
        normalize_units(&mut measurements);
        insta::assert_debug_snapshot!(measurements, @r#"
        Measurements(
            {
                "fcp": Measurement {
                    value: 1.1,
                    unit: Duration(
                        MilliSecond,
                    ),
                },
                "foo": Measurement {
                    value: 8.8,
                    unit: None,
                },
                "stall_count": Measurement {
                    value: 3.3,
                    unit: None,
                },
            },
        )
        "#);
    }

    #[test]
    fn test_normalize_security_report() {
        let mut event = Event {
            csp: Annotated::from(Csp::default()),
            ..Default::default()
        };
        let ipaddr = IpAddr("213.164.1.114".to_string());

        let client_ip = Some(&ipaddr);

        let user_agent = RawUserAgentInfo {
            user_agent: Some("Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:109.0) Gecko/20100101 Firefox/109.0"),
            client_hints: ClientHints {
                sec_ch_ua_platform: Some("macOS"),
                sec_ch_ua_platform_version: Some("13.2.0"),
                sec_ch_ua: Some(r#""Chromium";v="110", "Not A(Brand";v="24", "Google Chrome";v="110""#),
                sec_ch_ua_model: Some("some model"),
            }
        };

        // This call should fill the event headers with info from the user_agent which is
        // tested below.
        normalize_security_report(&mut event, client_ip, &user_agent);

        let headers = event
            .request
            .value_mut()
            .get_or_insert_with(Request::default)
            .headers
            .value_mut()
            .get_or_insert_with(Headers::default);

        assert_eq!(
            event.user.value().unwrap().ip_address,
            Annotated::from(ipaddr)
        );
        assert_eq!(
            headers.get_header(RawUserAgentInfo::USER_AGENT),
            user_agent.user_agent
        );
        assert_eq!(
            headers.get_header(ClientHints::SEC_CH_UA),
            user_agent.client_hints.sec_ch_ua,
        );
        assert_eq!(
            headers.get_header(ClientHints::SEC_CH_UA_MODEL),
            user_agent.client_hints.sec_ch_ua_model,
        );
        assert_eq!(
            headers.get_header(ClientHints::SEC_CH_UA_PLATFORM),
            user_agent.client_hints.sec_ch_ua_platform,
        );
        assert_eq!(
            headers.get_header(ClientHints::SEC_CH_UA_PLATFORM_VERSION),
            user_agent.client_hints.sec_ch_ua_platform_version,
        );

        assert!(
            std::mem::size_of_val(&ClientHints::<&str>::default()) == 64,
            "If you add new fields, update the test accordingly"
        );
    }

    #[test]
    fn test_no_device_class() {
        let mut event = Event {
            ..Default::default()
        };
        normalize_device_class(&mut event);
        let tags = &event.tags.value_mut().get_or_insert_with(Tags::default).0;
        assert_eq!(None, tags.get("device_class"));
    }

    #[test]
    fn test_apple_low_device_class() {
        let mut event = Event {
            contexts: {
                let mut contexts = Contexts::new();
                contexts.add(DeviceContext {
                    family: "iPhone".to_string().into(),
                    model: "iPhone8,4".to_string().into(),
                    ..Default::default()
                });
                Annotated::new(contexts)
            },
            ..Default::default()
        };
        normalize_device_class(&mut event);
        assert_debug_snapshot!(event.tags, @r#"
        Tags(
            PairList(
                [
                    TagEntry(
                        "device.class",
                        "1",
                    ),
                ],
            ),
        )
        "#);
    }

    #[test]
    fn test_apple_medium_device_class() {
        let mut event = Event {
            contexts: {
                let mut contexts = Contexts::new();
                contexts.add(DeviceContext {
                    family: "iPhone".to_string().into(),
                    model: "iPhone12,8".to_string().into(),
                    ..Default::default()
                });
                Annotated::new(contexts)
            },
            ..Default::default()
        };
        normalize_device_class(&mut event);
        assert_debug_snapshot!(event.tags, @r#"
        Tags(
            PairList(
                [
                    TagEntry(
                        "device.class",
                        "2",
                    ),
                ],
            ),
        )
        "#);
    }

    #[test]
    fn test_android_low_device_class() {
        let mut event = Event {
            contexts: {
                let mut contexts = Contexts::new();
                contexts.add(DeviceContext {
                    family: "android".to_string().into(),
                    processor_frequency: 1000.into(),
                    processor_count: 6.into(),
                    memory_size: (2 * 1024 * 1024 * 1024).into(),
                    ..Default::default()
                });
                Annotated::new(contexts)
            },
            ..Default::default()
        };
        normalize_device_class(&mut event);
        assert_debug_snapshot!(event.tags, @r#"
        Tags(
            PairList(
                [
                    TagEntry(
                        "device.class",
                        "1",
                    ),
                ],
            ),
        )
        "#);
    }

    #[test]
    fn test_android_medium_device_class() {
        let mut event = Event {
            contexts: {
                let mut contexts = Contexts::new();
                contexts.add(DeviceContext {
                    family: "android".to_string().into(),
                    processor_frequency: 2000.into(),
                    processor_count: 8.into(),
                    memory_size: (6 * 1024 * 1024 * 1024).into(),
                    ..Default::default()
                });
                Annotated::new(contexts)
            },
            ..Default::default()
        };
        normalize_device_class(&mut event);
        assert_debug_snapshot!(event.tags, @r#"
        Tags(
            PairList(
                [
                    TagEntry(
                        "device.class",
                        "2",
                    ),
                ],
            ),
        )
        "#);
    }

    #[test]
    fn test_android_high_device_class() {
        let mut event = Event {
            contexts: {
                let mut contexts = Contexts::new();
                contexts.add(DeviceContext {
                    family: "android".to_string().into(),
                    processor_frequency: 2500.into(),
                    processor_count: 8.into(),
                    memory_size: (6 * 1024 * 1024 * 1024).into(),
                    ..Default::default()
                });
                Annotated::new(contexts)
            },
            ..Default::default()
        };
        normalize_device_class(&mut event);
        assert_debug_snapshot!(event.tags, @r#"
        Tags(
            PairList(
                [
                    TagEntry(
                        "device.class",
                        "3",
                    ),
                ],
            ),
        )
        "#);
    }

    #[test]
    fn test_keeps_valid_measurement() {
        let name = "lcp";
        let measurement = Measurement {
            value: Annotated::new(420.69),
            unit: Annotated::new(MetricUnit::Duration(DurationUnit::MilliSecond)),
        };

        assert!(!is_measurement_dropped(name, measurement));
    }

    #[test]
    fn test_drops_too_long_measurement_names() {
        let name = "lcpppppppppppppppppppppppppppp";
        let measurement = Measurement {
            value: Annotated::new(420.69),
            unit: Annotated::new(MetricUnit::Duration(DurationUnit::MilliSecond)),
        };

        assert!(is_measurement_dropped(name, measurement));
    }

    #[test]
    fn test_drops_measurements_with_invalid_characters() {
        let name = "i æm frøm nørwåy";
        let measurement = Measurement {
            value: Annotated::new(420.69),
            unit: Annotated::new(MetricUnit::Duration(DurationUnit::MilliSecond)),
        };

        assert!(is_measurement_dropped(name, measurement));
    }

    fn is_measurement_dropped(name: &str, measurement: Measurement) -> bool {
        let max_name_and_unit_len = Some(30);

        let mut measurements: BTreeMap<String, Annotated<Measurement>> = Object::new();
        measurements.insert(name.to_string(), Annotated::new(measurement));

        let mut measurements = Measurements(measurements);
        let mut meta = Meta::default();
        let measurements_config = MeasurementsConfig {
            max_custom_measurements: 1,
            ..Default::default()
        };

        let dynamic_config = CombinedMeasurementsConfig::new(Some(&measurements_config), None);

        // Just for clarity.
        // Checks that there is 1 measurement before processing.
        assert_eq!(measurements.len(), 1);

        remove_invalid_measurements(
            &mut measurements,
            &mut meta,
            dynamic_config,
            max_name_and_unit_len,
        );

        // Checks whether the measurement is dropped.
        measurements.len() == 0
    }

    #[test]
    fn test_normalize_app_start_measurements_does_not_add_measurements() {
        let mut measurements = Annotated::<Measurements>::from_json(r###"{}"###)
            .unwrap()
            .into_value()
            .unwrap();
        insta::assert_debug_snapshot!(measurements, @r###"
        Measurements(
            {},
        )
        "###);
        normalize_app_start_measurements(&mut measurements);
        insta::assert_debug_snapshot!(measurements, @r###"
        Measurements(
            {},
        )
        "###);
    }

    #[test]
    fn test_normalize_app_start_cold_measurements() {
        let mut measurements =
            Annotated::<Measurements>::from_json(r#"{"app.start.cold": {"value": 1.1}}"#)
                .unwrap()
                .into_value()
                .unwrap();
        insta::assert_debug_snapshot!(measurements, @r###"
        Measurements(
            {
                "app.start.cold": Measurement {
                    value: 1.1,
                    unit: ~,
                },
            },
        )
        "###);
        normalize_app_start_measurements(&mut measurements);
        insta::assert_debug_snapshot!(measurements, @r###"
        Measurements(
            {
                "app_start_cold": Measurement {
                    value: 1.1,
                    unit: ~,
                },
            },
        )
        "###);
    }

    #[test]
    fn test_normalize_app_start_warm_measurements() {
        let mut measurements =
            Annotated::<Measurements>::from_json(r#"{"app.start.warm": {"value": 1.1}}"#)
                .unwrap()
                .into_value()
                .unwrap();
        insta::assert_debug_snapshot!(measurements, @r###"
        Measurements(
            {
                "app.start.warm": Measurement {
                    value: 1.1,
                    unit: ~,
                },
            },
        )
        "###);
        normalize_app_start_measurements(&mut measurements);
        insta::assert_debug_snapshot!(measurements, @r###"
        Measurements(
            {
                "app_start_warm": Measurement {
                    value: 1.1,
                    unit: ~,
                },
            },
        )
        "###);
    }

    #[test]
    fn test_ai_measurements() {
        let json = r#"
            {
                "spans": [
                    {
                        "timestamp": 1702474613.0495,
                        "start_timestamp": 1702474613.0175,
                        "description": "OpenAI ",
                        "op": "ai.chat_completions.openai",
                        "span_id": "9c01bd820a083e63",
                        "parent_span_id": "a1e13f3f06239d69",
                        "trace_id": "922dda2462ea4ac2b6a4b339bee90863",
                        "measurements": {
                            "ai_total_tokens_used": {
                                "value": 1230
                            }
                        },
                        "data": {
                            "ai.pipeline.name": "Autofix Pipeline",
                            "ai.model_id": "claude-2.1"
                        }
                    },
                    {
                        "timestamp": 1702474613.0495,
                        "start_timestamp": 1702474613.0175,
                        "description": "OpenAI ",
                        "op": "ai.chat_completions.openai",
                        "span_id": "ac01bd820a083e63",
                        "parent_span_id": "a1e13f3f06239d69",
                        "trace_id": "922dda2462ea4ac2b6a4b339bee90863",
                        "measurements": {
                            "ai_prompt_tokens_used": {
                                "value": 1000
                            },
                            "ai_completion_tokens_used": {
                                "value": 2000
                            }
                        },
                        "data": {
                            "ai.pipeline.name": "Autofix Pipeline",
                            "ai.model_id": "gpt4-21-04"
                        }
                    }
                ]
            }
        "#;

        let mut event = Annotated::<Event>::from_json(json).unwrap();

        normalize_event(
            &mut event,
            &NormalizationConfig {
                ai_model_costs: Some(&ModelCosts {
                    version: 1,
                    costs: vec![
                        ModelCost {
                            model_id: LazyGlob::new("claude-2*"),
                            for_completion: false,
                            cost_per_1k_tokens: 1.0,
                        },
                        ModelCost {
                            model_id: LazyGlob::new("gpt4-21*"),
                            for_completion: false,
                            cost_per_1k_tokens: 2.0,
                        },
                        ModelCost {
                            model_id: LazyGlob::new("gpt4-21*"),
                            for_completion: true,
                            cost_per_1k_tokens: 20.0,
                        },
                    ],
                }),
                ..NormalizationConfig::default()
            },
        );

        let spans = event.value().unwrap().spans.value().unwrap();
        assert_eq!(spans.len(), 2);
        assert_eq!(
            spans
                .first()
                .unwrap()
                .value()
                .unwrap()
                .measurements
                .value()
                .unwrap()
                .get_value("ai_total_cost"),
            Some(1.23)
        );
        assert_eq!(
            spans
                .get(1)
                .unwrap()
                .value()
                .unwrap()
                .measurements
                .value()
                .unwrap()
                .get_value("ai_total_cost"),
            Some(20.0 * 2.0 + 2.0)
        );
    }

    #[test]
    fn test_apple_high_device_class() {
        let mut event = Event {
            contexts: {
                let mut contexts = Contexts::new();
                contexts.add(DeviceContext {
                    family: "iPhone".to_string().into(),
                    model: "iPhone15,3".to_string().into(),
                    ..Default::default()
                });
                Annotated::new(contexts)
            },
            ..Default::default()
        };
        normalize_device_class(&mut event);
        assert_debug_snapshot!(event.tags, @r#"
        Tags(
            PairList(
                [
                    TagEntry(
                        "device.class",
                        "3",
                    ),
                ],
            ),
        )
        "#);
    }

    #[test]
    fn test_filter_mobile_outliers() {
        let mut measurements =
            Annotated::<Measurements>::from_json(r#"{"app_start_warm": {"value": 180001}}"#)
                .unwrap()
                .into_value()
                .unwrap();
        assert_eq!(measurements.len(), 1);
        filter_mobile_outliers(&mut measurements);
        assert_eq!(measurements.len(), 0);
    }

    #[test]
    fn test_computed_performance_score() {
        let json = r#"
        {
            "type": "transaction",
            "timestamp": "2021-04-26T08:00:05+0100",
            "start_timestamp": "2021-04-26T08:00:00+0100",
            "measurements": {
                "fid": {"value": 213, "unit": "millisecond"},
                "fcp": {"value": 1237, "unit": "millisecond"},
                "lcp": {"value": 6596, "unit": "millisecond"},
                "cls": {"value": 0.11}
            },
            "contexts": {
                "browser": {
                    "name": "Chrome",
                    "version": "120.1.1",
                    "type": "browser"
                }
            }
        }
        "#;

        let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();

        let performance_score: PerformanceScoreConfig = serde_json::from_value(json!({
            "profiles": [
                {
                    "name": "Desktop",
                    "scoreComponents": [
                        {
                            "measurement": "fcp",
                            "weight": 0.15,
                            "p10": 900,
                            "p50": 1600
                        },
                        {
                            "measurement": "lcp",
                            "weight": 0.30,
                            "p10": 1200,
                            "p50": 2400
                        },
                        {
                            "measurement": "fid",
                            "weight": 0.30,
                            "p10": 100,
                            "p50": 300
                        },
                        {
                            "measurement": "cls",
                            "weight": 0.25,
                            "p10": 0.1,
                            "p50": 0.25
                        },
                        {
                            "measurement": "ttfb",
                            "weight": 0.0,
                            "p10": 0.2,
                            "p50": 0.4
                        },
                    ],
                    "condition": {
                        "op":"eq",
                        "name": "event.contexts.browser.name",
                        "value": "Chrome"
                    }
                }
            ]
        }))
        .unwrap();

        normalize_performance_score(&mut event, Some(&performance_score));

        insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {}, @r###"
        {
          "type": "transaction",
          "timestamp": 1619420405.0,
          "start_timestamp": 1619420400.0,
          "contexts": {
            "browser": {
              "name": "Chrome",
              "version": "120.1.1",
              "type": "browser",
            },
          },
          "measurements": {
            "cls": {
              "value": 0.11,
            },
            "fcp": {
              "value": 1237.0,
              "unit": "millisecond",
            },
            "fid": {
              "value": 213.0,
              "unit": "millisecond",
            },
            "lcp": {
              "value": 6596.0,
              "unit": "millisecond",
            },
            "score.cls": {
              "value": 0.21864170607444863,
              "unit": "ratio",
            },
            "score.fcp": {
              "value": 0.10750855443790831,
              "unit": "ratio",
            },
            "score.fid": {
              "value": 0.19657361348282545,
              "unit": "ratio",
            },
            "score.lcp": {
              "value": 0.009238896571386584,
              "unit": "ratio",
            },
            "score.total": {
              "value": 0.531962770566569,
              "unit": "ratio",
            },
            "score.weight.cls": {
              "value": 0.25,
              "unit": "ratio",
            },
            "score.weight.fcp": {
              "value": 0.15,
              "unit": "ratio",
            },
            "score.weight.fid": {
              "value": 0.3,
              "unit": "ratio",
            },
            "score.weight.lcp": {
              "value": 0.3,
              "unit": "ratio",
            },
            "score.weight.ttfb": {
              "value": 0.0,
              "unit": "ratio",
            },
          },
        }
        "###);
    }

    // Test performance score is calculated correctly when the sum of weights is under 1.
    // The expected result should normalize the weights to a sum of 1 and scale the weight measurements accordingly.
    #[test]
    fn test_computed_performance_score_with_under_normalized_weights() {
        let json = r#"
        {
            "type": "transaction",
            "timestamp": "2021-04-26T08:00:05+0100",
            "start_timestamp": "2021-04-26T08:00:00+0100",
            "measurements": {
                "fid": {"value": 213, "unit": "millisecond"},
                "fcp": {"value": 1237, "unit": "millisecond"},
                "lcp": {"value": 6596, "unit": "millisecond"},
                "cls": {"value": 0.11}
            },
            "contexts": {
                "browser": {
                    "name": "Chrome",
                    "version": "120.1.1",
                    "type": "browser"
                }
            }
        }
        "#;

        let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();

        let performance_score: PerformanceScoreConfig = serde_json::from_value(json!({
            "profiles": [
                {
                    "name": "Desktop",
                    "scoreComponents": [
                        {
                            "measurement": "fcp",
                            "weight": 0.03,
                            "p10": 900,
                            "p50": 1600
                        },
                        {
                            "measurement": "lcp",
                            "weight": 0.06,
                            "p10": 1200,
                            "p50": 2400
                        },
                        {
                            "measurement": "fid",
                            "weight": 0.06,
                            "p10": 100,
                            "p50": 300
                        },
                        {
                            "measurement": "cls",
                            "weight": 0.05,
                            "p10": 0.1,
                            "p50": 0.25
                        },
                        {
                            "measurement": "ttfb",
                            "weight": 0.0,
                            "p10": 0.2,
                            "p50": 0.4
                        },
                    ],
                    "condition": {
                        "op":"eq",
                        "name": "event.contexts.browser.name",
                        "value": "Chrome"
                    }
                }
            ]
        }))
        .unwrap();

        normalize_performance_score(&mut event, Some(&performance_score));

        insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {}, @r###"
        {
          "type": "transaction",
          "timestamp": 1619420405.0,
          "start_timestamp": 1619420400.0,
          "contexts": {
            "browser": {
              "name": "Chrome",
              "version": "120.1.1",
              "type": "browser",
            },
          },
          "measurements": {
            "cls": {
              "value": 0.11,
            },
            "fcp": {
              "value": 1237.0,
              "unit": "millisecond",
            },
            "fid": {
              "value": 213.0,
              "unit": "millisecond",
            },
            "lcp": {
              "value": 6596.0,
              "unit": "millisecond",
            },
            "score.cls": {
              "value": 0.21864170607444863,
              "unit": "ratio",
            },
            "score.fcp": {
              "value": 0.10750855443790831,
              "unit": "ratio",
            },
            "score.fid": {
              "value": 0.19657361348282545,
              "unit": "ratio",
            },
            "score.lcp": {
              "value": 0.009238896571386584,
              "unit": "ratio",
            },
            "score.total": {
              "value": 0.531962770566569,
              "unit": "ratio",
            },
            "score.weight.cls": {
              "value": 0.25,
              "unit": "ratio",
            },
            "score.weight.fcp": {
              "value": 0.15,
              "unit": "ratio",
            },
            "score.weight.fid": {
              "value": 0.3,
              "unit": "ratio",
            },
            "score.weight.lcp": {
              "value": 0.3,
              "unit": "ratio",
            },
            "score.weight.ttfb": {
              "value": 0.0,
              "unit": "ratio",
            },
          },
        }
        "###);
    }

    // Test performance score is calculated correctly when the sum of weights is over 1.
    // The expected result should normalize the weights to a sum of 1 and scale the weight measurements accordingly.
    #[test]
    fn test_computed_performance_score_with_over_normalized_weights() {
        let json = r#"
        {
            "type": "transaction",
            "timestamp": "2021-04-26T08:00:05+0100",
            "start_timestamp": "2021-04-26T08:00:00+0100",
            "measurements": {
                "fid": {"value": 213, "unit": "millisecond"},
                "fcp": {"value": 1237, "unit": "millisecond"},
                "lcp": {"value": 6596, "unit": "millisecond"},
                "cls": {"value": 0.11}
            },
            "contexts": {
                "browser": {
                    "name": "Chrome",
                    "version": "120.1.1",
                    "type": "browser"
                }
            }
        }
        "#;

        let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();

        let performance_score: PerformanceScoreConfig = serde_json::from_value(json!({
            "profiles": [
                {
                    "name": "Desktop",
                    "scoreComponents": [
                        {
                            "measurement": "fcp",
                            "weight": 0.30,
                            "p10": 900,
                            "p50": 1600
                        },
                        {
                            "measurement": "lcp",
                            "weight": 0.60,
                            "p10": 1200,
                            "p50": 2400
                        },
                        {
                            "measurement": "fid",
                            "weight": 0.60,
                            "p10": 100,
                            "p50": 300
                        },
                        {
                            "measurement": "cls",
                            "weight": 0.50,
                            "p10": 0.1,
                            "p50": 0.25
                        },
                        {
                            "measurement": "ttfb",
                            "weight": 0.0,
                            "p10": 0.2,
                            "p50": 0.4
                        },
                    ],
                    "condition": {
                        "op":"eq",
                        "name": "event.contexts.browser.name",
                        "value": "Chrome"
                    }
                }
            ]
        }))
        .unwrap();

        normalize_performance_score(&mut event, Some(&performance_score));

        insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {}, @r###"
        {
          "type": "transaction",
          "timestamp": 1619420405.0,
          "start_timestamp": 1619420400.0,
          "contexts": {
            "browser": {
              "name": "Chrome",
              "version": "120.1.1",
              "type": "browser",
            },
          },
          "measurements": {
            "cls": {
              "value": 0.11,
            },
            "fcp": {
              "value": 1237.0,
              "unit": "millisecond",
            },
            "fid": {
              "value": 213.0,
              "unit": "millisecond",
            },
            "lcp": {
              "value": 6596.0,
              "unit": "millisecond",
            },
            "score.cls": {
              "value": 0.21864170607444863,
              "unit": "ratio",
            },
            "score.fcp": {
              "value": 0.10750855443790831,
              "unit": "ratio",
            },
            "score.fid": {
              "value": 0.19657361348282545,
              "unit": "ratio",
            },
            "score.lcp": {
              "value": 0.009238896571386584,
              "unit": "ratio",
            },
            "score.total": {
              "value": 0.531962770566569,
              "unit": "ratio",
            },
            "score.weight.cls": {
              "value": 0.25,
              "unit": "ratio",
            },
            "score.weight.fcp": {
              "value": 0.15,
              "unit": "ratio",
            },
            "score.weight.fid": {
              "value": 0.3,
              "unit": "ratio",
            },
            "score.weight.lcp": {
              "value": 0.3,
              "unit": "ratio",
            },
            "score.weight.ttfb": {
              "value": 0.0,
              "unit": "ratio",
            },
          },
        }
        "###);
    }

    #[test]
    fn test_computed_performance_score_missing_measurement() {
        let json = r#"
        {
            "type": "transaction",
            "timestamp": "2021-04-26T08:00:05+0100",
            "start_timestamp": "2021-04-26T08:00:00+0100",
            "measurements": {
                "a": {"value": 213, "unit": "millisecond"}
            },
            "contexts": {
                "browser": {
                    "name": "Chrome",
                    "version": "120.1.1",
                    "type": "browser"
                }
            }
        }
        "#;

        let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();

        let performance_score: PerformanceScoreConfig = serde_json::from_value(json!({
            "profiles": [
                {
                    "name": "Desktop",
                    "scoreComponents": [
                        {
                            "measurement": "a",
                            "weight": 0.15,
                            "p10": 900,
                            "p50": 1600
                        },
                        {
                            "measurement": "b",
                            "weight": 0.30,
                            "p10": 1200,
                            "p50": 2400
                        },
                    ],
                    "condition": {
                        "op":"eq",
                        "name": "event.contexts.browser.name",
                        "value": "Chrome"
                    }
                }
            ]
        }))
        .unwrap();

        normalize_performance_score(&mut event, Some(&performance_score));

        insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {}, @r###"
        {
          "type": "transaction",
          "timestamp": 1619420405.0,
          "start_timestamp": 1619420400.0,
          "contexts": {
            "browser": {
              "name": "Chrome",
              "version": "120.1.1",
              "type": "browser",
            },
          },
          "measurements": {
            "a": {
              "value": 213.0,
              "unit": "millisecond",
            },
          },
        }
        "###);
    }

    #[test]
    fn test_computed_performance_score_optional_measurement() {
        let json = r#"
        {
            "type": "transaction",
            "timestamp": "2021-04-26T08:00:05+0100",
            "start_timestamp": "2021-04-26T08:00:00+0100",
            "measurements": {
                "a": {"value": 213, "unit": "millisecond"},
                "b": {"value": 213, "unit": "millisecond"}
            },
            "contexts": {
                "browser": {
                    "name": "Chrome",
                    "version": "120.1.1",
                    "type": "browser"
                }
            }
        }
        "#;

        let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();

        let performance_score: PerformanceScoreConfig = serde_json::from_value(json!({
            "profiles": [
                {
                    "name": "Desktop",
                    "scoreComponents": [
                        {
                            "measurement": "a",
                            "weight": 0.15,
                            "p10": 900,
                            "p50": 1600,
                        },
                        {
                            "measurement": "b",
                            "weight": 0.30,
                            "p10": 1200,
                            "p50": 2400,
                            "optional": true
                        },
                        {
                            "measurement": "c",
                            "weight": 0.55,
                            "p10": 1200,
                            "p50": 2400,
                            "optional": true
                        },
                    ],
                    "condition": {
                        "op":"eq",
                        "name": "event.contexts.browser.name",
                        "value": "Chrome"
                    }
                }
            ]
        }))
        .unwrap();

        normalize_performance_score(&mut event, Some(&performance_score));

        insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {}, @r###"
        {
          "type": "transaction",
          "timestamp": 1619420405.0,
          "start_timestamp": 1619420400.0,
          "contexts": {
            "browser": {
              "name": "Chrome",
              "version": "120.1.1",
              "type": "browser",
            },
          },
          "measurements": {
            "a": {
              "value": 213.0,
              "unit": "millisecond",
            },
            "b": {
              "value": 213.0,
              "unit": "millisecond",
            },
            "score.a": {
              "value": 0.33333215313291975,
              "unit": "ratio",
            },
            "score.b": {
              "value": 0.66666415149198,
              "unit": "ratio",
            },
            "score.total": {
              "value": 0.9999963046248997,
              "unit": "ratio",
            },
            "score.weight.a": {
              "value": 0.33333333333333337,
              "unit": "ratio",
            },
            "score.weight.b": {
              "value": 0.6666666666666667,
              "unit": "ratio",
            },
            "score.weight.c": {
              "value": 0.0,
              "unit": "ratio",
            },
          },
        }
        "###);
    }

    #[test]
    fn test_computed_performance_score_weight_0() {
        let json = r#"
        {
            "type": "transaction",
            "timestamp": "2021-04-26T08:00:05+0100",
            "start_timestamp": "2021-04-26T08:00:00+0100",
            "measurements": {
                "cls": {"value": 0.11}
            }
        }
        "#;

        let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();

        let performance_score: PerformanceScoreConfig = serde_json::from_value(json!({
            "profiles": [
                {
                    "name": "Desktop",
                    "scoreComponents": [
                        {
                            "measurement": "cls",
                            "weight": 0,
                            "p10": 0.1,
                            "p50": 0.25
                        },
                    ],
                    "condition": {
                        "op":"and",
                        "inner": []
                    }
                }
            ]
        }))
        .unwrap();

        normalize_performance_score(&mut event, Some(&performance_score));

        insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {}, @r###"
        {
          "type": "transaction",
          "timestamp": 1619420405.0,
          "start_timestamp": 1619420400.0,
          "measurements": {
            "cls": {
              "value": 0.11,
            },
          },
        }
        "###);
    }

    #[test]
    fn test_computed_performance_score_negative_value() {
        let json = r#"
        {
            "type": "transaction",
            "timestamp": "2021-04-26T08:00:05+0100",
            "start_timestamp": "2021-04-26T08:00:00+0100",
            "measurements": {
                "ttfb": {"value": -100, "unit": "millisecond"}
            }
        }
        "#;

        let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();

        let performance_score: PerformanceScoreConfig = serde_json::from_value(json!({
            "profiles": [
                {
                    "name": "Desktop",
                    "scoreComponents": [
                        {
                            "measurement": "ttfb",
                            "weight": 1.0,
                            "p10": 100.0,
                            "p50": 250.0
                        },
                    ],
                    "condition": {
                        "op":"and",
                        "inner": []
                    }
                }
            ]
        }))
        .unwrap();

        normalize_performance_score(&mut event, Some(&performance_score));

        insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {}, @r###"
        {
          "type": "transaction",
          "timestamp": 1619420405.0,
          "start_timestamp": 1619420400.0,
          "measurements": {
            "score.total": {
              "value": 1.0,
              "unit": "ratio",
            },
            "score.ttfb": {
              "value": 1.0,
              "unit": "ratio",
            },
            "score.weight.ttfb": {
              "value": 1.0,
              "unit": "ratio",
            },
            "ttfb": {
              "value": -100.0,
              "unit": "millisecond",
            },
          },
        }
        "###);
    }

    #[test]
    fn test_filter_negative_web_vital_measurements() {
        let json = r#"
        {
            "type": "transaction",
            "timestamp": "2021-04-26T08:00:05+0100",
            "start_timestamp": "2021-04-26T08:00:00+0100",
            "measurements": {
                "ttfb": {"value": -100, "unit": "millisecond"}
            }
        }
        "#;
        let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();

        // Allow ttfb as a builtinMeasurement with allow_negative defaulted to false.
        let project_measurement_config: MeasurementsConfig = serde_json::from_value(json!({
            "builtinMeasurements": [
                {"name": "ttfb", "unit": "millisecond"},
            ],
        }))
        .unwrap();

        let dynamic_measurement_config =
            CombinedMeasurementsConfig::new(Some(&project_measurement_config), None);

        normalize_event_measurements(&mut event, Some(dynamic_measurement_config), None);

        insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {}, @r###"
        {
          "type": "transaction",
          "timestamp": 1619420405.0,
          "start_timestamp": 1619420400.0,
          "measurements": {},
          "_meta": {
            "measurements": {
              "": Meta(Some(MetaInner(
                err: [
                  [
                    "invalid_data",
                    {
                      "reason": "Negative value for measurement ttfb not allowed: -100",
                    },
                  ],
                ],
                val: Some({
                  "ttfb": {
                    "unit": "millisecond",
                    "value": -100.0,
                  },
                }),
              ))),
            },
          },
        }
        "###);
    }

    #[test]
    fn test_computed_performance_score_multiple_profiles() {
        let json = r#"
        {
            "type": "transaction",
            "timestamp": "2021-04-26T08:00:05+0100",
            "start_timestamp": "2021-04-26T08:00:00+0100",
            "measurements": {
                "cls": {"value": 0.11},
                "inp": {"value": 120.0}
            }
        }
        "#;

        let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();

        let performance_score: PerformanceScoreConfig = serde_json::from_value(json!({
            "profiles": [
                {
                    "name": "Desktop",
                    "scoreComponents": [
                        {
                            "measurement": "cls",
                            "weight": 0,
                            "p10": 0.1,
                            "p50": 0.25
                        },
                    ],
                    "condition": {
                        "op":"and",
                        "inner": []
                    }
                },
                {
                    "name": "Desktop",
                    "scoreComponents": [
                        {
                            "measurement": "inp",
                            "weight": 1.0,
                            "p10": 0.1,
                            "p50": 0.25
                        },
                    ],
                    "condition": {
                        "op":"and",
                        "inner": []
                    }
                }
            ]
        }))
        .unwrap();

        normalize_performance_score(&mut event, Some(&performance_score));

        insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {}, @r###"
        {
          "type": "transaction",
          "timestamp": 1619420405.0,
          "start_timestamp": 1619420400.0,
          "measurements": {
            "cls": {
              "value": 0.11,
            },
            "inp": {
              "value": 120.0,
            },
            "score.inp": {
              "value": 0.0,
              "unit": "ratio",
            },
            "score.total": {
              "value": 0.0,
              "unit": "ratio",
            },
            "score.weight.inp": {
              "value": 1.0,
              "unit": "ratio",
            },
          },
        }
        "###);
    }

    #[test]
    fn test_compute_performance_score_for_mobile_ios_profile() {
        let mut event = Annotated::<Event>::from_json(IOS_MOBILE_EVENT)
            .unwrap()
            .0
            .unwrap();

        let performance_score: PerformanceScoreConfig = serde_json::from_value(json!({
            "profiles": [
                {
                    "name": "Mobile",
                    "scoreComponents": [
                        {
                            "measurement": "time_to_initial_display",
                            "weight": 0.25,
                            "p10": 1800.0,
                            "p50": 3000.0,
                            "optional": true
                        },
                        {
                            "measurement": "time_to_full_display",
                            "weight": 0.25,
                            "p10": 2500.0,
                            "p50": 4000.0,
                            "optional": true
                        },
                        {
                            "measurement": "app_start_warm",
                            "weight": 0.25,
                            "p10": 200.0,
                            "p50": 500.0,
                            "optional": true
                        },
                        {
                            "measurement": "app_start_cold",
                            "weight": 0.25,
                            "p10": 200.0,
                            "p50": 500.0,
                            "optional": true
                        }
                    ],
                    "condition": {
                        "op": "and",
                        "inner": [
                            {
                                "op": "or",
                                "inner": [
                                    {
                                        "op": "eq",
                                        "name": "event.sdk.name",
                                        "value": "sentry.cocoa"
                                    },
                                    {
                                        "op": "eq",
                                        "name": "event.sdk.name",
                                        "value": "sentry.java.android"
                                    }
                                ]
                            },
                            {
                                "op": "eq",
                                "name": "event.contexts.trace.op",
                                "value": "ui.load"
                            }
                        ]
                    }
                }
            ]
        }))
        .unwrap();

        normalize_performance_score(&mut event, Some(&performance_score));

        insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {});
    }

    #[test]
    fn test_compute_performance_score_for_mobile_android_profile() {
        let mut event = Annotated::<Event>::from_json(ANDROID_MOBILE_EVENT)
            .unwrap()
            .0
            .unwrap();

        let performance_score: PerformanceScoreConfig = serde_json::from_value(json!({
            "profiles": [
                {
                    "name": "Mobile",
                    "scoreComponents": [
                        {
                            "measurement": "time_to_initial_display",
                            "weight": 0.25,
                            "p10": 1800.0,
                            "p50": 3000.0,
                            "optional": true
                        },
                        {
                            "measurement": "time_to_full_display",
                            "weight": 0.25,
                            "p10": 2500.0,
                            "p50": 4000.0,
                            "optional": true
                        },
                        {
                            "measurement": "app_start_warm",
                            "weight": 0.25,
                            "p10": 200.0,
                            "p50": 500.0,
                            "optional": true
                        },
                        {
                            "measurement": "app_start_cold",
                            "weight": 0.25,
                            "p10": 200.0,
                            "p50": 500.0,
                            "optional": true
                        }
                    ],
                    "condition": {
                        "op": "and",
                        "inner": [
                            {
                                "op": "or",
                                "inner": [
                                    {
                                        "op": "eq",
                                        "name": "event.sdk.name",
                                        "value": "sentry.cocoa"
                                    },
                                    {
                                        "op": "eq",
                                        "name": "event.sdk.name",
                                        "value": "sentry.java.android"
                                    }
                                ]
                            },
                            {
                                "op": "eq",
                                "name": "event.contexts.trace.op",
                                "value": "ui.load"
                            }
                        ]
                    }
                }
            ]
        }))
        .unwrap();

        normalize_performance_score(&mut event, Some(&performance_score));

        insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {});
    }

    #[test]
    fn test_computes_performance_score_and_tags_with_profile_version() {
        let json = r#"
        {
            "type": "transaction",
            "timestamp": "2021-04-26T08:00:05+0100",
            "start_timestamp": "2021-04-26T08:00:00+0100",
            "measurements": {
                "inp": {"value": 120.0}
            }
        }
        "#;

        let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();

        let performance_score: PerformanceScoreConfig = serde_json::from_value(json!({
            "profiles": [
                {
                    "name": "Desktop",
                    "scoreComponents": [
                        {
                            "measurement": "inp",
                            "weight": 1.0,
                            "p10": 0.1,
                            "p50": 0.25
                        },
                    ],
                    "condition": {
                        "op":"and",
                        "inner": []
                    },
                    "version": "beta"
                }
            ]
        }))
        .unwrap();

        normalize(
            &mut event,
            &mut Meta::default(),
            &NormalizationConfig {
                performance_score: Some(&performance_score),
                ..Default::default()
            },
        );

        insta::assert_ron_snapshot!(SerializableAnnotated(&event.contexts), {}, @r###"
        {
          "performance_score": {
            "score_profile_version": "beta",
            "type": "performancescore",
          },
        }
        "###);
        insta::assert_ron_snapshot!(SerializableAnnotated(&event.measurements), {}, @r###"
        {
          "inp": {
            "value": 120.0,
            "unit": "millisecond",
          },
          "score.inp": {
            "value": 0.0,
            "unit": "ratio",
          },
          "score.total": {
            "value": 0.0,
            "unit": "ratio",
          },
          "score.weight.inp": {
            "value": 1.0,
            "unit": "ratio",
          },
        }
        "###);
    }

    #[test]
    fn test_computes_standalone_cls_performance_score() {
        let json = r#"
        {
            "type": "transaction",
            "timestamp": "2021-04-26T08:00:05+0100",
            "start_timestamp": "2021-04-26T08:00:00+0100",
            "measurements": {
                "cls": {"value": 0.5}
            }
        }
        "#;

        let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();

        let performance_score: PerformanceScoreConfig = serde_json::from_value(json!({
            "profiles": [
            {
                "name": "Default",
                "scoreComponents": [
                    {
                        "measurement": "fcp",
                        "weight": 0.15,
                        "p10": 900.0,
                        "p50": 1600.0,
                        "optional": true,
                    },
                    {
                        "measurement": "lcp",
                        "weight": 0.30,
                        "p10": 1200.0,
                        "p50": 2400.0,
                        "optional": true,
                    },
                    {
                        "measurement": "cls",
                        "weight": 0.15,
                        "p10": 0.1,
                        "p50": 0.25,
                        "optional": true,
                    },
                    {
                        "measurement": "ttfb",
                        "weight": 0.10,
                        "p10": 200.0,
                        "p50": 400.0,
                        "optional": true,
                    },
                ],
                "condition": {
                    "op": "and",
                    "inner": [],
                },
            }
            ]
        }))
        .unwrap();

        normalize(
            &mut event,
            &mut Meta::default(),
            &NormalizationConfig {
                performance_score: Some(&performance_score),
                ..Default::default()
            },
        );

        insta::assert_ron_snapshot!(SerializableAnnotated(&event.measurements), {}, @r###"
        {
          "cls": {
            "value": 0.5,
            "unit": "none",
          },
          "score.cls": {
            "value": 0.16615877613713903,
            "unit": "ratio",
          },
          "score.total": {
            "value": 0.16615877613713903,
            "unit": "ratio",
          },
          "score.weight.cls": {
            "value": 1.0,
            "unit": "ratio",
          },
          "score.weight.fcp": {
            "value": 0.0,
            "unit": "ratio",
          },
          "score.weight.lcp": {
            "value": 0.0,
            "unit": "ratio",
          },
          "score.weight.ttfb": {
            "value": 0.0,
            "unit": "ratio",
          },
        }
        "###);
    }

    #[test]
    fn test_computed_performance_score_uses_first_matching_profile() {
        let json = r#"
        {
            "type": "transaction",
            "timestamp": "2021-04-26T08:00:05+0100",
            "start_timestamp": "2021-04-26T08:00:00+0100",
            "measurements": {
                "a": {"value": 213, "unit": "millisecond"},
                "b": {"value": 213, "unit": "millisecond"}
            },
            "contexts": {
                "browser": {
                    "name": "Chrome",
                    "version": "120.1.1",
                    "type": "browser"
                }
            }
        }
        "#;

        let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();

        let performance_score: PerformanceScoreConfig = serde_json::from_value(json!({
            "profiles": [
                {
                    "name": "Mobile",
                    "scoreComponents": [
                        {
                            "measurement": "a",
                            "weight": 0.15,
                            "p10": 100,
                            "p50": 200,
                        },
                        {
                            "measurement": "b",
                            "weight": 0.30,
                            "p10": 100,
                            "p50": 200,
                            "optional": true
                        },
                        {
                            "measurement": "c",
                            "weight": 0.55,
                            "p10": 100,
                            "p50": 200,
                            "optional": true
                        },
                    ],
                    "condition": {
                        "op":"eq",
                        "name": "event.contexts.browser.name",
                        "value": "Chrome Mobile"
                    }
                },
                {
                    "name": "Desktop",
                    "scoreComponents": [
                        {
                            "measurement": "a",
                            "weight": 0.15,
                            "p10": 900,
                            "p50": 1600,
                        },
                        {
                            "measurement": "b",
                            "weight": 0.30,
                            "p10": 1200,
                            "p50": 2400,
                            "optional": true
                        },
                        {
                            "measurement": "c",
                            "weight": 0.55,
                            "p10": 1200,
                            "p50": 2400,
                            "optional": true
                        },
                    ],
                    "condition": {
                        "op":"eq",
                        "name": "event.contexts.browser.name",
                        "value": "Chrome"
                    }
                },
                {
                    "name": "Default",
                    "scoreComponents": [
                        {
                            "measurement": "a",
                            "weight": 0.15,
                            "p10": 100,
                            "p50": 200,
                        },
                        {
                            "measurement": "b",
                            "weight": 0.30,
                            "p10": 100,
                            "p50": 200,
                            "optional": true
                        },
                        {
                            "measurement": "c",
                            "weight": 0.55,
                            "p10": 100,
                            "p50": 200,
                            "optional": true
                        },
                    ],
                    "condition": {
                        "op": "and",
                        "inner": [],
                    }
                }
            ]
        }))
        .unwrap();

        normalize_performance_score(&mut event, Some(&performance_score));

        insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {}, @r###"
        {
          "type": "transaction",
          "timestamp": 1619420405.0,
          "start_timestamp": 1619420400.0,
          "contexts": {
            "browser": {
              "name": "Chrome",
              "version": "120.1.1",
              "type": "browser",
            },
          },
          "measurements": {
            "a": {
              "value": 213.0,
              "unit": "millisecond",
            },
            "b": {
              "value": 213.0,
              "unit": "millisecond",
            },
            "score.a": {
              "value": 0.33333215313291975,
              "unit": "ratio",
            },
            "score.b": {
              "value": 0.66666415149198,
              "unit": "ratio",
            },
            "score.total": {
              "value": 0.9999963046248997,
              "unit": "ratio",
            },
            "score.weight.a": {
              "value": 0.33333333333333337,
              "unit": "ratio",
            },
            "score.weight.b": {
              "value": 0.6666666666666667,
              "unit": "ratio",
            },
            "score.weight.c": {
              "value": 0.0,
              "unit": "ratio",
            },
          },
        }
        "###);
    }

    #[test]
    fn test_computed_performance_score_falls_back_to_default_profile() {
        let json = r#"
        {
            "type": "transaction",
            "timestamp": "2021-04-26T08:00:05+0100",
            "start_timestamp": "2021-04-26T08:00:00+0100",
            "measurements": {
                "a": {"value": 213, "unit": "millisecond"},
                "b": {"value": 213, "unit": "millisecond"}
            },
            "contexts": {}
        }
        "#;

        let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();

        let performance_score: PerformanceScoreConfig = serde_json::from_value(json!({
            "profiles": [
                {
                    "name": "Mobile",
                    "scoreComponents": [
                        {
                            "measurement": "a",
                            "weight": 0.15,
                            "p10": 900,
                            "p50": 1600,
                            "optional": true
                        },
                        {
                            "measurement": "b",
                            "weight": 0.30,
                            "p10": 1200,
                            "p50": 2400,
                            "optional": true
                        },
                        {
                            "measurement": "c",
                            "weight": 0.55,
                            "p10": 1200,
                            "p50": 2400,
                            "optional": true
                        },
                    ],
                    "condition": {
                        "op":"eq",
                        "name": "event.contexts.browser.name",
                        "value": "Chrome Mobile"
                    }
                },
                {
                    "name": "Desktop",
                    "scoreComponents": [
                        {
                            "measurement": "a",
                            "weight": 0.15,
                            "p10": 900,
                            "p50": 1600,
                            "optional": true
                        },
                        {
                            "measurement": "b",
                            "weight": 0.30,
                            "p10": 1200,
                            "p50": 2400,
                            "optional": true
                        },
                        {
                            "measurement": "c",
                            "weight": 0.55,
                            "p10": 1200,
                            "p50": 2400,
                            "optional": true
                        },
                    ],
                    "condition": {
                        "op":"eq",
                        "name": "event.contexts.browser.name",
                        "value": "Chrome"
                    }
                },
                {
                    "name": "Default",
                    "scoreComponents": [
                        {
                            "measurement": "a",
                            "weight": 0.15,
                            "p10": 100,
                            "p50": 200,
                            "optional": true
                        },
                        {
                            "measurement": "b",
                            "weight": 0.30,
                            "p10": 100,
                            "p50": 200,
                            "optional": true
                        },
                        {
                            "measurement": "c",
                            "weight": 0.55,
                            "p10": 100,
                            "p50": 200,
                            "optional": true
                        },
                    ],
                    "condition": {
                        "op": "and",
                        "inner": [],
                    }
                }
            ]
        }))
        .unwrap();

        normalize_performance_score(&mut event, Some(&performance_score));

        insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {}, @r###"
        {
          "type": "transaction",
          "timestamp": 1619420405.0,
          "start_timestamp": 1619420400.0,
          "contexts": {},
          "measurements": {
            "a": {
              "value": 213.0,
              "unit": "millisecond",
            },
            "b": {
              "value": 213.0,
              "unit": "millisecond",
            },
            "score.a": {
              "value": 0.15121816827413334,
              "unit": "ratio",
            },
            "score.b": {
              "value": 0.3024363365482667,
              "unit": "ratio",
            },
            "score.total": {
              "value": 0.4536545048224,
              "unit": "ratio",
            },
            "score.weight.a": {
              "value": 0.33333333333333337,
              "unit": "ratio",
            },
            "score.weight.b": {
              "value": 0.6666666666666667,
              "unit": "ratio",
            },
            "score.weight.c": {
              "value": 0.0,
              "unit": "ratio",
            },
          },
        }
        "###);
    }

    #[test]
    fn test_normalization_removes_reprocessing_context() {
        let json = r#"{
            "contexts": {
                "reprocessing": {}
            }
        }"#;
        let mut event = Annotated::<Event>::from_json(json).unwrap();
        assert!(get_value!(event.contexts!).contains_key("reprocessing"));
        normalize_event(&mut event, &NormalizationConfig::default());
        assert!(!get_value!(event.contexts!).contains_key("reprocessing"));
    }

    #[test]
    fn test_renormalization_does_not_remove_reprocessing_context() {
        let json = r#"{
            "contexts": {
                "reprocessing": {}
            }
        }"#;
        let mut event = Annotated::<Event>::from_json(json).unwrap();
        assert!(get_value!(event.contexts!).contains_key("reprocessing"));
        normalize_event(
            &mut event,
            &NormalizationConfig {
                is_renormalize: true,
                ..Default::default()
            },
        );
        assert!(get_value!(event.contexts!).contains_key("reprocessing"));
    }

    #[test]
    fn test_normalize_user() {
        let json = r#"{
            "user": {
                "id": "123456",
                "username": "john",
                "other": "value"
            }
        }"#;
        let mut event = Annotated::<Event>::from_json(json).unwrap();
        normalize_user(event.value_mut().as_mut().unwrap());

        let user = event.value().unwrap().user.value().unwrap();
        assert_eq!(user.data, {
            let mut map = Object::new();
            map.insert(
                "other".to_string(),
                Annotated::new(Value::String("value".to_owned())),
            );
            Annotated::new(map)
        });
        assert_eq!(user.other, Object::new());
        assert_eq!(user.username, Annotated::new("john".to_string().into()));
        assert_eq!(user.sentry_user, Annotated::new("id:123456".to_string()));
    }

    #[test]
    fn test_handle_types_in_spaced_exception_values() {
        let mut exception = Annotated::new(Exception {
            value: Annotated::new("ValueError: unauthorized".to_string().into()),
            ..Exception::default()
        });
        normalize_exception(&mut exception);

        let exception = exception.value().unwrap();
        assert_eq!(exception.value.as_str(), Some("unauthorized"));
        assert_eq!(exception.ty.as_str(), Some("ValueError"));
    }

    #[test]
    fn test_handle_types_in_non_spaced_excepton_values() {
        let mut exception = Annotated::new(Exception {
            value: Annotated::new("ValueError:unauthorized".to_string().into()),
            ..Exception::default()
        });
        normalize_exception(&mut exception);

        let exception = exception.value().unwrap();
        assert_eq!(exception.value.as_str(), Some("unauthorized"));
        assert_eq!(exception.ty.as_str(), Some("ValueError"));
    }

    #[test]
    fn test_rejects_empty_exception_fields() {
        let mut exception = Annotated::new(Exception {
            value: Annotated::new("".to_string().into()),
            ty: Annotated::new("".to_string()),
            ..Default::default()
        });

        normalize_exception(&mut exception);

        assert!(exception.value().is_none());
        assert!(exception.meta().has_errors());
    }

    #[test]
    fn test_json_value() {
        let mut exception = Annotated::new(Exception {
            value: Annotated::new(r#"{"unauthorized":true}"#.to_string().into()),
            ..Exception::default()
        });

        normalize_exception(&mut exception);

        let exception = exception.value().unwrap();

        // Don't split a json-serialized value on the colon
        assert_eq!(exception.value.as_str(), Some(r#"{"unauthorized":true}"#));
        assert_eq!(exception.ty.value(), None);
    }

    #[test]
    fn test_exception_invalid() {
        let mut exception = Annotated::new(Exception::default());

        normalize_exception(&mut exception);

        let expected = Error::with(ErrorKind::MissingAttribute, |error| {
            error.insert("attribute", "type or value");
        });
        assert_eq!(
            exception.meta().iter_errors().collect_tuple(),
            Some((&expected,))
        );
    }

    #[test]
    fn test_normalize_exception() {
        let mut event = Annotated::new(Event {
            exceptions: Annotated::new(Values::new(vec![Annotated::new(Exception {
                // Exception with missing type and value
                ty: Annotated::empty(),
                value: Annotated::empty(),
                ..Default::default()
            })])),
            ..Default::default()
        });

        normalize_event(&mut event, &NormalizationConfig::default());

        let exception = event
            .value()
            .unwrap()
            .exceptions
            .value()
            .unwrap()
            .values
            .value()
            .unwrap()
            .first()
            .unwrap();

        assert_debug_snapshot!(exception.meta(), @r#"
        Meta {
            remarks: [],
            errors: [
                Error {
                    kind: MissingAttribute,
                    data: {
                        "attribute": String(
                            "type or value",
                        ),
                    },
                },
            ],
            original_length: None,
            original_value: Some(
                Object(
                    {
                        "mechanism": ~,
                        "module": ~,
                        "raw_stacktrace": ~,
                        "stacktrace": ~,
                        "thread_id": ~,
                        "type": ~,
                        "value": ~,
                    },
                ),
            ),
        }"#);
    }

    #[test]
    fn test_normalize_breadcrumbs() {
        let mut event = Event {
            breadcrumbs: Annotated::new(Values {
                values: Annotated::new(vec![Annotated::new(Breadcrumb::default())]),
                ..Default::default()
            }),
            ..Default::default()
        };
        normalize_breadcrumbs(&mut event);

        let breadcrumb = event
            .breadcrumbs
            .value()
            .unwrap()
            .values
            .value()
            .unwrap()
            .first()
            .unwrap()
            .value()
            .unwrap();
        assert_eq!(breadcrumb.ty.value().unwrap(), "default");
        assert_eq!(&breadcrumb.level.value().unwrap().to_string(), "info");
    }

    #[test]
    fn test_other_debug_images_have_meta_errors() {
        let mut event = Event {
            debug_meta: Annotated::new(DebugMeta {
                images: Annotated::new(vec![Annotated::new(
                    DebugImage::Other(BTreeMap::default()),
                )]),
                ..Default::default()
            }),
            ..Default::default()
        };
        normalize_debug_meta(&mut event);

        let debug_image_meta = event
            .debug_meta
            .value()
            .unwrap()
            .images
            .value()
            .unwrap()
            .first()
            .unwrap()
            .meta();
        assert_debug_snapshot!(debug_image_meta, @r#"
        Meta {
            remarks: [],
            errors: [
                Error {
                    kind: InvalidData,
                    data: {
                        "reason": String(
                            "unsupported debug image type",
                        ),
                    },
                },
            ],
            original_length: None,
            original_value: Some(
                Object(
                    {},
                ),
            ),
        }"#);
    }

    #[test]
    fn test_skip_span_normalization_when_configured() {
        let json = r#"{
            "type": "transaction",
            "start_timestamp": 1,
            "timestamp": 2,
            "contexts": {
                "trace": {
                    "trace_id": "4c79f60c11214eb38604f4ae0781bfb2",
                    "span_id": "aaaaaaaaaaaaaaaa"
                }
            },
            "spans": [
                {
                    "op": "db",
                    "description": "SELECT * FROM table;",
                    "start_timestamp": 1,
                    "timestamp": 2,
                    "trace_id": "4c79f60c11214eb38604f4ae0781bfb2",
                    "span_id": "bbbbbbbbbbbbbbbb",
                    "parent_span_id": "aaaaaaaaaaaaaaaa"
                }
            ]
        }"#;

        let mut event = Annotated::<Event>::from_json(json).unwrap();
        assert!(get_value!(event.spans[0].exclusive_time).is_none());
        normalize_event(
            &mut event,
            &NormalizationConfig {
                is_renormalize: true,
                ..Default::default()
            },
        );
        assert!(get_value!(event.spans[0].exclusive_time).is_none());
        normalize_event(
            &mut event,
            &NormalizationConfig {
                is_renormalize: false,
                ..Default::default()
            },
        );
        assert!(get_value!(event.spans[0].exclusive_time).is_some());
    }

    #[test]
    fn test_normalize_trace_context_tags_extracts_lcp_info() {
        let json = r#"{
            "type": "transaction",
            "start_timestamp": 1,
            "timestamp": 2,
            "contexts": {
                "trace": {
                    "data": {
                        "lcp.element": "body > div#app > div > h1#header",
                        "lcp.size": 24827,
                        "lcp.id": "header",
                        "lcp.url": "http://example.com/image.jpg"
                    }
                }
            },
            "measurements": {
                "lcp": { "value": 146.20000000298023, "unit": "millisecond" }
            }
        }"#;
        let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();
        normalize_trace_context_tags(&mut event);
        insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {}, @r#"
        {
          "type": "transaction",
          "timestamp": 2.0,
          "start_timestamp": 1.0,
          "contexts": {
            "trace": {
              "data": {
                "lcp.element": "body > div#app > div > h1#header",
                "lcp.size": 24827,
                "lcp.id": "header",
                "lcp.url": "http://example.com/image.jpg",
              },
              "type": "trace",
            },
          },
          "tags": [
            [
              "lcp.element",
              "body > div#app > div > h1#header",
            ],
            [
              "lcp.size",
              "24827",
            ],
            [
              "lcp.id",
              "header",
            ],
            [
              "lcp.url",
              "http://example.com/image.jpg",
            ],
          ],
          "measurements": {
            "lcp": {
              "value": 146.20000000298023,
              "unit": "millisecond",
            },
          },
        }
        "#);
    }

    #[test]
    fn test_normalize_trace_context_tags_does_not_overwrite_lcp_tags() {
        let json = r#"{
          "type": "transaction",
          "start_timestamp": 1,
          "timestamp": 2,
          "contexts": {
              "trace": {
                  "data": {
                      "lcp.element": "body > div#app > div > h1#id",
                      "lcp.size": 33333,
                      "lcp.id": "id",
                      "lcp.url": "http://example.com/another-image.jpg"
                  }
              }
          },
          "tags": {
              "lcp.element": "body > div#app > div > h1#header",
              "lcp.size": 24827,
              "lcp.id": "header",
              "lcp.url": "http://example.com/image.jpg"
          },
          "measurements": {
              "lcp": { "value": 146.20000000298023, "unit": "millisecond" }
          }
        }"#;
        let mut event = Annotated::<Event>::from_json(json).unwrap().0.unwrap();
        normalize_trace_context_tags(&mut event);
        insta::assert_ron_snapshot!(SerializableAnnotated(&Annotated::new(event)), {}, @r#"
        {
          "type": "transaction",
          "timestamp": 2.0,
          "start_timestamp": 1.0,
          "contexts": {
            "trace": {
              "data": {
                "lcp.element": "body > div#app > div > h1#id",
                "lcp.size": 33333,
                "lcp.id": "id",
                "lcp.url": "http://example.com/another-image.jpg",
              },
              "type": "trace",
            },
          },
          "tags": [
            [
              "lcp.element",
              "body > div#app > div > h1#header",
            ],
            [
              "lcp.id",
              "header",
            ],
            [
              "lcp.size",
              "24827",
            ],
            [
              "lcp.url",
              "http://example.com/image.jpg",
            ],
          ],
          "measurements": {
            "lcp": {
              "value": 146.20000000298023,
              "unit": "millisecond",
            },
          },
        }
        "#);
    }
}