relay_server/services/
processor.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
use std::borrow::Cow;
use std::collections::{BTreeSet, HashMap};
use std::error::Error;
use std::fmt::{Debug, Display};
use std::future::Future;
use std::io::Write;
use std::pin::Pin;
use std::sync::{Arc, Once};
use std::time::Duration;

use anyhow::Context;
use brotli::CompressorWriter as BrotliEncoder;
use bytes::Bytes;
use chrono::{DateTime, Utc};
use flate2::write::{GzEncoder, ZlibEncoder};
use flate2::Compression;
use relay_base_schema::project::{ProjectId, ProjectKey};
use relay_cogs::{AppFeature, Cogs, FeatureWeights, ResourceId, Token};
use relay_common::time::UnixTimestamp;
use relay_config::{Config, HttpEncoding, NormalizationLevel, RelayMode};
use relay_dynamic_config::{CombinedMetricExtractionConfig, ErrorBoundary, Feature};
use relay_event_normalization::{
    normalize_event, validate_event, ClockDriftProcessor, CombinedMeasurementsConfig,
    EventValidationConfig, GeoIpLookup, MeasurementsConfig, NormalizationConfig, RawUserAgentInfo,
    TransactionNameConfig,
};
use relay_event_schema::processor::ProcessingAction;
use relay_event_schema::protocol::{
    ClientReport, Event, EventId, EventType, IpAddr, Metrics, NetworkReportError,
};
use relay_filter::FilterStatKey;
use relay_metrics::{Bucket, BucketMetadata, BucketView, BucketsView, MetricNamespace};
use relay_pii::PiiConfigError;
use relay_protocol::{Annotated, Empty};
use relay_quotas::{DataCategory, RateLimits, Scoping};
use relay_sampling::evaluation::{ReservoirCounters, ReservoirEvaluator, SamplingDecision};
use relay_statsd::metric;
use relay_system::{Addr, FromMessage, NoResponse, Service};
use reqwest::header;
use smallvec::{smallvec, SmallVec};
use zstd::stream::Encoder as ZstdEncoder;

use crate::constants::DEFAULT_EVENT_RETENTION;
use crate::envelope::{self, ContentType, Envelope, EnvelopeError, Item, ItemType};
use crate::extractors::{PartialDsn, RequestMeta};
use crate::http;
use crate::metrics::{MetricOutcomes, MetricsLimiter, MinimalTrackableBucket};
use crate::metrics_extraction::transactions::types::ExtractMetricsError;
use crate::metrics_extraction::transactions::{ExtractedMetrics, TransactionExtractor};
use crate::service::ServiceError;
use crate::services::global_config::GlobalConfigHandle;
use crate::services::metrics::{Aggregator, FlushBuckets, MergeBuckets, ProjectBuckets};
use crate::services::outcome::{DiscardReason, Outcome, TrackOutcome};
use crate::services::processor::event::FiltersStatus;
use crate::services::projects::cache::ProjectCacheHandle;
use crate::services::projects::project::{ProjectInfo, ProjectState};
use crate::services::test_store::{Capture, TestStore};
use crate::services::upstream::{
    SendRequest, UpstreamRelay, UpstreamRequest, UpstreamRequestError,
};
use crate::statsd::{RelayCounters, RelayHistograms, RelayTimers};
use crate::utils::{
    self, InvalidProcessingGroupType, ManagedEnvelope, SamplingResult, ThreadPool, TypedEnvelope,
    WorkerGroup,
};
use relay_base_schema::organization::OrganizationId;
#[cfg(feature = "processing")]
use {
    crate::services::store::{Store, StoreEnvelope},
    crate::utils::{CheckLimits, Enforcement, EnvelopeLimiter, ItemAction},
    itertools::Itertools,
    relay_cardinality::{
        CardinalityLimit, CardinalityLimiter, CardinalityLimitsSplit, RedisSetLimiter,
        RedisSetLimiterOptions,
    },
    relay_dynamic_config::{CardinalityLimiterMode, GlobalConfig, MetricExtractionGroups},
    relay_quotas::{Quota, RateLimitingError, RedisRateLimiter},
    relay_redis::{RedisPool, RedisPools},
    std::iter::Chain,
    std::slice::Iter,
    std::time::Instant,
    symbolic_unreal::{Unreal4Error, Unreal4ErrorKind},
};

mod attachment;
mod dynamic_sampling;
mod event;
mod metrics;
mod profile;
mod profile_chunk;
mod replay;
mod report;
mod session;
mod span;
pub use span::extract_transaction_span;

#[cfg(feature = "processing")]
mod unreal;

/// Creates the block only if used with `processing` feature.
///
/// Provided code block will be executed only if the provided config has `processing_enabled` set.
macro_rules! if_processing {
    ($config:expr, $if_true:block) => {
        #[cfg(feature = "processing")] {
            if $config.processing_enabled() $if_true
        }
    };
    ($config:expr, $if_true:block else $if_false:block) => {
        {
            #[cfg(feature = "processing")] {
                if $config.processing_enabled() $if_true else $if_false
            }
            #[cfg(not(feature = "processing"))] {
                $if_false
            }
        }
    };
}

/// The minimum clock drift for correction to apply.
const MINIMUM_CLOCK_DRIFT: Duration = Duration::from_secs(55 * 60);

#[derive(Debug)]
pub struct GroupTypeError;

impl Display for GroupTypeError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("failed to convert processing group into corresponding type")
    }
}

impl std::error::Error for GroupTypeError {}

macro_rules! processing_group {
    ($ty:ident, $variant:ident) => {
        #[derive(Clone, Copy, Debug)]
        pub struct $ty;

        impl From<$ty> for ProcessingGroup {
            fn from(_: $ty) -> Self {
                ProcessingGroup::$variant
            }
        }

        impl TryFrom<ProcessingGroup> for $ty {
            type Error = GroupTypeError;

            fn try_from(value: ProcessingGroup) -> Result<Self, Self::Error> {
                if matches!(value, ProcessingGroup::$variant) {
                    return Ok($ty);
                }
                return Err(GroupTypeError);
            }
        }
    };
}

/// A marker trait.
///
/// Should be used only with groups which are responsible for processing envelopes with events.
pub trait EventProcessing {}

/// A trait for processing groups that can be dynamically sampled.
pub trait Sampling {
    /// Whether dynamic sampling should run under the given project's conditions.
    fn supports_sampling(project_info: &ProjectInfo) -> bool;

    /// Whether reservoir sampling applies to this processing group (a.k.a. data type).
    fn supports_reservoir_sampling() -> bool;
}

processing_group!(TransactionGroup, Transaction);
impl EventProcessing for TransactionGroup {}

impl Sampling for TransactionGroup {
    fn supports_sampling(project_info: &ProjectInfo) -> bool {
        // For transactions, we require transaction metrics to be enabled before sampling.
        matches!(&project_info.config.transaction_metrics, Some(ErrorBoundary::Ok(c)) if c.is_enabled())
    }

    fn supports_reservoir_sampling() -> bool {
        true
    }
}

processing_group!(ErrorGroup, Error);
impl EventProcessing for ErrorGroup {}

processing_group!(SessionGroup, Session);
processing_group!(StandaloneGroup, Standalone);
processing_group!(ClientReportGroup, ClientReport);
processing_group!(ReplayGroup, Replay);
processing_group!(CheckInGroup, CheckIn);
processing_group!(SpanGroup, Span);

impl Sampling for SpanGroup {
    fn supports_sampling(project_info: &ProjectInfo) -> bool {
        // If no metrics could be extracted, do not sample anything.
        matches!(&project_info.config().metric_extraction, ErrorBoundary::Ok(c) if c.is_supported())
    }

    fn supports_reservoir_sampling() -> bool {
        false
    }
}

processing_group!(ProfileChunkGroup, ProfileChunk);
processing_group!(MetricsGroup, Metrics);
processing_group!(ForwardUnknownGroup, ForwardUnknown);
processing_group!(Ungrouped, Ungrouped);

/// Processed group type marker.
///
/// Marks the envelopes which passed through the processing pipeline.
#[derive(Clone, Copy, Debug)]
pub struct Processed;

/// Describes the groups of the processable items.
#[derive(Clone, Copy, Debug)]
pub enum ProcessingGroup {
    /// All the transaction related items.
    ///
    /// Includes transactions, related attachments, profiles.
    Transaction,
    /// All the items which require (have or create) events.
    ///
    /// This includes: errors, NEL, security reports, user reports, some of the
    /// attachments.
    Error,
    /// Session events.
    Session,
    /// Standalone items which can be sent alone without any event attached to it in the current
    /// envelope e.g. some attachments, user reports.
    Standalone,
    /// Outcomes.
    ClientReport,
    /// Replays and ReplayRecordings.
    Replay,
    /// Crons.
    CheckIn,
    /// Spans.
    Span,
    /// Metrics.
    Metrics,
    /// ProfileChunk.
    ProfileChunk,
    /// Unknown item types will be forwarded upstream (to processing Relay), where we will
    /// decide what to do with them.
    ForwardUnknown,
    /// All the items in the envelope that could not be grouped.
    Ungrouped,
}

impl ProcessingGroup {
    /// Splits provided envelope into list of tuples of groups with associated envelopes.
    pub fn split_envelope(mut envelope: Envelope) -> SmallVec<[(Self, Box<Envelope>); 3]> {
        let headers = envelope.headers().clone();
        let mut grouped_envelopes = smallvec![];

        // Each NEL item *must* have a dedicated envelope.
        let nel_envelopes = envelope
            .take_items_by(|item| matches!(item.ty(), &ItemType::Nel))
            .into_iter()
            .map(|item| {
                let headers = headers.clone();
                let items: SmallVec<[Item; 3]> = smallvec![item.clone()];
                let mut envelope = Envelope::from_parts(headers, items);
                envelope.set_event_id(EventId::new());
                (ProcessingGroup::Error, envelope)
            });
        grouped_envelopes.extend(nel_envelopes);

        // Extract replays.
        let replay_items = envelope.take_items_by(|item| {
            matches!(
                item.ty(),
                &ItemType::ReplayEvent | &ItemType::ReplayRecording | &ItemType::ReplayVideo
            )
        });
        if !replay_items.is_empty() {
            grouped_envelopes.push((
                ProcessingGroup::Replay,
                Envelope::from_parts(headers.clone(), replay_items),
            ))
        }

        // Keep all the sessions together in one envelope.
        let session_items = envelope
            .take_items_by(|item| matches!(item.ty(), &ItemType::Session | &ItemType::Sessions));
        if !session_items.is_empty() {
            grouped_envelopes.push((
                ProcessingGroup::Session,
                Envelope::from_parts(headers.clone(), session_items),
            ))
        }

        // Extract spans.
        let span_items = envelope.take_items_by(|item| {
            matches!(
                item.ty(),
                &ItemType::Span | &ItemType::OtelSpan | &ItemType::OtelTracesData
            )
        });
        if !span_items.is_empty() {
            grouped_envelopes.push((
                ProcessingGroup::Span,
                Envelope::from_parts(headers.clone(), span_items),
            ))
        }

        // Exract all metric items.
        //
        // Note: Should only be relevant in proxy mode. In other modes we send metrics through
        // a separate pipeline.
        let metric_items = envelope.take_items_by(|i| i.ty().is_metrics());
        if !metric_items.is_empty() {
            grouped_envelopes.push((
                ProcessingGroup::Metrics,
                Envelope::from_parts(headers.clone(), metric_items),
            ))
        }

        // Extract profile chunks.
        let profile_chunk_items =
            envelope.take_items_by(|item| matches!(item.ty(), &ItemType::ProfileChunk));
        if !profile_chunk_items.is_empty() {
            grouped_envelopes.push((
                ProcessingGroup::ProfileChunk,
                Envelope::from_parts(headers.clone(), profile_chunk_items),
            ))
        }

        // Extract all standalone items.
        //
        // Note: only if there are no items in the envelope which can create events, otherwise they
        // will be in the same envelope with all require event items.
        if !envelope.items().any(Item::creates_event) {
            let standalone_items = envelope.take_items_by(Item::requires_event);
            if !standalone_items.is_empty() {
                grouped_envelopes.push((
                    ProcessingGroup::Standalone,
                    Envelope::from_parts(headers.clone(), standalone_items),
                ))
            }
        };

        // Make sure we create separate envelopes for each `RawSecurity` report.
        let security_reports_items = envelope
            .take_items_by(|i| matches!(i.ty(), &ItemType::RawSecurity))
            .into_iter()
            .map(|item| {
                let headers = headers.clone();
                let items: SmallVec<[Item; 3]> = smallvec![item.clone()];
                let mut envelope = Envelope::from_parts(headers, items);
                envelope.set_event_id(EventId::new());
                (ProcessingGroup::Error, envelope)
            });
        grouped_envelopes.extend(security_reports_items);

        // Extract all the items which require an event into separate envelope.
        let require_event_items = envelope.take_items_by(Item::requires_event);
        if !require_event_items.is_empty() {
            let group = if require_event_items
                .iter()
                .any(|item| matches!(item.ty(), &ItemType::Transaction | &ItemType::Profile))
            {
                ProcessingGroup::Transaction
            } else {
                ProcessingGroup::Error
            };

            grouped_envelopes.push((
                group,
                Envelope::from_parts(headers.clone(), require_event_items),
            ))
        }

        // Get the rest of the envelopes, one per item.
        let envelopes = envelope.items_mut().map(|item| {
            let headers = headers.clone();
            let items: SmallVec<[Item; 3]> = smallvec![item.clone()];
            let envelope = Envelope::from_parts(headers, items);
            let item_type = item.ty();
            let group = if matches!(item_type, &ItemType::CheckIn) {
                ProcessingGroup::CheckIn
            } else if matches!(item.ty(), &ItemType::ClientReport) {
                ProcessingGroup::ClientReport
            } else if matches!(item_type, &ItemType::Unknown(_)) {
                ProcessingGroup::ForwardUnknown
            } else {
                // Cannot group this item type.
                ProcessingGroup::Ungrouped
            };

            (group, envelope)
        });
        grouped_envelopes.extend(envelopes);

        grouped_envelopes
    }

    /// Returns the name of the group.
    pub fn variant(&self) -> &'static str {
        match self {
            ProcessingGroup::Transaction => "transaction",
            ProcessingGroup::Error => "error",
            ProcessingGroup::Session => "session",
            ProcessingGroup::Standalone => "standalone",
            ProcessingGroup::ClientReport => "client_report",
            ProcessingGroup::Replay => "replay",
            ProcessingGroup::CheckIn => "check_in",
            ProcessingGroup::Span => "span",
            ProcessingGroup::Metrics => "metrics",
            ProcessingGroup::ProfileChunk => "profile_chunk",
            ProcessingGroup::ForwardUnknown => "forward_unknown",
            ProcessingGroup::Ungrouped => "ungrouped",
        }
    }
}

impl From<ProcessingGroup> for AppFeature {
    fn from(value: ProcessingGroup) -> Self {
        match value {
            ProcessingGroup::Transaction => AppFeature::Transactions,
            ProcessingGroup::Error => AppFeature::Errors,
            ProcessingGroup::Session => AppFeature::Sessions,
            ProcessingGroup::Standalone => AppFeature::UnattributedEnvelope,
            ProcessingGroup::ClientReport => AppFeature::ClientReports,
            ProcessingGroup::Replay => AppFeature::Replays,
            ProcessingGroup::CheckIn => AppFeature::CheckIns,
            ProcessingGroup::Span => AppFeature::Spans,
            ProcessingGroup::Metrics => AppFeature::UnattributedMetrics,
            ProcessingGroup::ProfileChunk => AppFeature::Profiles,
            ProcessingGroup::ForwardUnknown => AppFeature::UnattributedEnvelope,
            ProcessingGroup::Ungrouped => AppFeature::UnattributedEnvelope,
        }
    }
}

/// An error returned when handling [`ProcessEnvelope`].
#[derive(Debug, thiserror::Error)]
pub enum ProcessingError {
    #[error("invalid json in event")]
    InvalidJson(#[source] serde_json::Error),

    #[error("invalid message pack event payload")]
    InvalidMsgpack(#[from] rmp_serde::decode::Error),

    #[cfg(feature = "processing")]
    #[error("invalid unreal crash report")]
    InvalidUnrealReport(#[source] Unreal4Error),

    #[error("event payload too large")]
    PayloadTooLarge,

    #[error("invalid transaction event")]
    InvalidTransaction,

    #[error("envelope processor failed")]
    ProcessingFailed(#[from] ProcessingAction),

    #[error("duplicate {0} in event")]
    DuplicateItem(ItemType),

    #[error("failed to extract event payload")]
    NoEventPayload,

    #[error("missing project id in DSN")]
    MissingProjectId,

    #[error("invalid security report type: {0:?}")]
    InvalidSecurityType(Bytes),

    #[error("unsupported security report type")]
    UnsupportedSecurityType,

    #[error("invalid security report")]
    InvalidSecurityReport(#[source] serde_json::Error),

    #[error("invalid nel report")]
    InvalidNelReport(#[source] NetworkReportError),

    #[error("event filtered with reason: {0:?}")]
    EventFiltered(FilterStatKey),

    #[error("missing or invalid required event timestamp")]
    InvalidTimestamp,

    #[error("could not serialize event payload")]
    SerializeFailed(#[source] serde_json::Error),

    #[cfg(feature = "processing")]
    #[error("failed to apply quotas")]
    QuotasFailed(#[from] RateLimitingError),

    #[error("invalid pii config")]
    PiiConfigError(PiiConfigError),

    #[error("invalid processing group type")]
    InvalidProcessingGroup(#[from] InvalidProcessingGroupType),

    #[error("invalid replay")]
    InvalidReplay(DiscardReason),

    #[error("replay filtered with reason: {0:?}")]
    ReplayFiltered(FilterStatKey),
}

impl ProcessingError {
    fn to_outcome(&self) -> Option<Outcome> {
        match self {
            // General outcomes for invalid events
            Self::PayloadTooLarge => Some(Outcome::Invalid(DiscardReason::TooLarge)),
            Self::InvalidJson(_) => Some(Outcome::Invalid(DiscardReason::InvalidJson)),
            Self::InvalidMsgpack(_) => Some(Outcome::Invalid(DiscardReason::InvalidMsgpack)),
            Self::InvalidSecurityType(_) => {
                Some(Outcome::Invalid(DiscardReason::SecurityReportType))
            }
            Self::InvalidSecurityReport(_) => Some(Outcome::Invalid(DiscardReason::SecurityReport)),
            Self::UnsupportedSecurityType => Some(Outcome::Filtered(FilterStatKey::InvalidCsp)),
            Self::InvalidNelReport(_) => Some(Outcome::Invalid(DiscardReason::InvalidJson)),
            Self::InvalidTransaction => Some(Outcome::Invalid(DiscardReason::InvalidTransaction)),
            Self::InvalidTimestamp => Some(Outcome::Invalid(DiscardReason::Timestamp)),
            Self::DuplicateItem(_) => Some(Outcome::Invalid(DiscardReason::DuplicateItem)),
            Self::NoEventPayload => Some(Outcome::Invalid(DiscardReason::NoEventPayload)),

            // Processing-only outcomes (Sentry-internal Relays)
            #[cfg(feature = "processing")]
            Self::InvalidUnrealReport(ref err)
                if err.kind() == Unreal4ErrorKind::BadCompression =>
            {
                Some(Outcome::Invalid(DiscardReason::InvalidCompression))
            }
            #[cfg(feature = "processing")]
            Self::InvalidUnrealReport(_) => Some(Outcome::Invalid(DiscardReason::ProcessUnreal)),

            // Internal errors
            Self::SerializeFailed(_) | Self::ProcessingFailed(_) => {
                Some(Outcome::Invalid(DiscardReason::Internal))
            }
            #[cfg(feature = "processing")]
            Self::QuotasFailed(_) => Some(Outcome::Invalid(DiscardReason::Internal)),
            Self::PiiConfigError(_) => Some(Outcome::Invalid(DiscardReason::ProjectStatePii)),

            // These outcomes are emitted at the source.
            Self::MissingProjectId => None,
            Self::EventFiltered(_) => None,
            Self::InvalidProcessingGroup(_) => None,

            Self::InvalidReplay(reason) => Some(Outcome::Invalid(*reason)),
            Self::ReplayFiltered(key) => Some(Outcome::Filtered(key.clone())),
        }
    }

    fn is_unexpected(&self) -> bool {
        self.to_outcome()
            .map_or(false, |outcome| outcome.is_unexpected())
    }
}

#[cfg(feature = "processing")]
impl From<Unreal4Error> for ProcessingError {
    fn from(err: Unreal4Error) -> Self {
        match err.kind() {
            Unreal4ErrorKind::TooLarge => Self::PayloadTooLarge,
            _ => ProcessingError::InvalidUnrealReport(err),
        }
    }
}

impl From<ExtractMetricsError> for ProcessingError {
    fn from(error: ExtractMetricsError) -> Self {
        match error {
            ExtractMetricsError::MissingTimestamp | ExtractMetricsError::InvalidTimestamp => {
                Self::InvalidTimestamp
            }
        }
    }
}

type ExtractedEvent = (Annotated<Event>, usize);

/// A container for extracted metrics during processing.
///
/// The container enforces that the extracted metrics are correctly tagged
/// with the dynamic sampling decision.
#[derive(Debug)]
pub struct ProcessingExtractedMetrics {
    metrics: ExtractedMetrics,
}

impl ProcessingExtractedMetrics {
    pub fn new() -> Self {
        Self {
            metrics: ExtractedMetrics::default(),
        }
    }

    /// Extends the contained metrics with [`ExtractedMetrics`].
    pub fn extend(
        &mut self,
        extracted: ExtractedMetrics,
        sampling_decision: Option<SamplingDecision>,
    ) {
        self.extend_project_metrics(extracted.project_metrics, sampling_decision);
        self.extend_sampling_metrics(extracted.sampling_metrics, sampling_decision);
    }

    /// Extends the contained project metrics.
    pub fn extend_project_metrics<I>(
        &mut self,
        buckets: I,
        sampling_decision: Option<SamplingDecision>,
    ) where
        I: IntoIterator<Item = Bucket>,
    {
        self.metrics
            .project_metrics
            .extend(buckets.into_iter().map(|mut bucket| {
                bucket.metadata.extracted_from_indexed =
                    sampling_decision == Some(SamplingDecision::Keep);
                bucket
            }));
    }

    /// Extends the contained sampling metrics.
    pub fn extend_sampling_metrics<I>(
        &mut self,
        buckets: I,
        sampling_decision: Option<SamplingDecision>,
    ) where
        I: IntoIterator<Item = Bucket>,
    {
        self.metrics
            .sampling_metrics
            .extend(buckets.into_iter().map(|mut bucket| {
                bucket.metadata.extracted_from_indexed =
                    sampling_decision == Some(SamplingDecision::Keep);
                bucket
            }));
    }

    /// Applies rate limits to the contained metrics.
    ///
    /// This is used to apply rate limits which have been enforced on sampled items of an envelope
    /// to also consistently apply to the metrics extracted from these items.
    #[cfg(feature = "processing")]
    fn apply_enforcement(&mut self, enforcement: &Enforcement, enforced_consistently: bool) {
        // Metric namespaces which need to be dropped.
        let mut drop_namespaces: SmallVec<[_; 2]> = smallvec![];
        // Metrics belonging to this metric namespace need to have the `extracted_from_indexed`
        // flag reset to `false`.
        let mut reset_extracted_from_indexed: SmallVec<[_; 2]> = smallvec![];

        for (namespace, limit, indexed) in [
            (
                MetricNamespace::Transactions,
                &enforcement.event,
                &enforcement.event_indexed,
            ),
            (
                MetricNamespace::Spans,
                &enforcement.spans,
                &enforcement.spans_indexed,
            ),
        ] {
            if limit.is_active() {
                drop_namespaces.push(namespace);
            } else if indexed.is_active() && !enforced_consistently {
                // If the enforcement was not computed by consistently checking the limits,
                // the quota for the metrics has not yet been incremented.
                // In this case we have a dropped indexed payload but a metric which still needs to
                // be accounted for, make sure the metric will still be rate limited.
                reset_extracted_from_indexed.push(namespace);
            }
        }

        if !drop_namespaces.is_empty() || !reset_extracted_from_indexed.is_empty() {
            self.retain_mut(|bucket| {
                let Some(namespace) = bucket.name.try_namespace() else {
                    return true;
                };

                if drop_namespaces.contains(&namespace) {
                    return false;
                }

                if reset_extracted_from_indexed.contains(&namespace) {
                    bucket.metadata.extracted_from_indexed = false;
                }

                true
            });
        }
    }

    #[cfg(feature = "processing")]
    fn retain_mut(&mut self, mut f: impl FnMut(&mut Bucket) -> bool) {
        self.metrics.project_metrics.retain_mut(&mut f);
        self.metrics.sampling_metrics.retain_mut(&mut f);
    }
}

fn send_metrics(metrics: ExtractedMetrics, envelope: &Envelope, aggregator: &Addr<Aggregator>) {
    let project_key = envelope.meta().public_key();

    let ExtractedMetrics {
        project_metrics,
        sampling_metrics,
    } = metrics;

    if !project_metrics.is_empty() {
        aggregator.send(MergeBuckets {
            project_key,
            buckets: project_metrics,
        });
    }

    if !sampling_metrics.is_empty() {
        // If no sampling project state is available, we associate the sampling
        // metrics with the current project.
        //
        // project_without_tracing         -> metrics goes to self
        // dependent_project_with_tracing  -> metrics goes to root
        // root_project_with_tracing       -> metrics goes to root == self
        let sampling_project_key = envelope.sampling_key().unwrap_or(project_key);
        aggregator.send(MergeBuckets {
            project_key: sampling_project_key,
            buckets: sampling_metrics,
        });
    }
}

/// Returns the data category if there is an event.
///
/// The data category is computed from the event type. Both `Default` and `Error` events map to
/// the `Error` data category. If there is no Event, `None` is returned.
fn event_category(event: &Annotated<Event>) -> Option<DataCategory> {
    event_type(event).map(DataCategory::from)
}

/// Returns the event type if there is an event.
///
/// If the event does not have a type, `Some(EventType::Default)` is assumed. If, in contrast, there
/// is no event, `None` is returned.
fn event_type(event: &Annotated<Event>) -> Option<EventType> {
    event
        .value()
        .map(|event| event.ty.value().copied().unwrap_or_default())
}

/// Function for on-off switches that filter specific item types (profiles, spans)
/// based on a feature flag.
///
/// If the project config did not come from the upstream, we keep the items.
fn should_filter(config: &Config, project_info: &ProjectInfo, feature: Feature) -> bool {
    match config.relay_mode() {
        RelayMode::Proxy | RelayMode::Static | RelayMode::Capture => false,
        RelayMode::Managed => !project_info.has_feature(feature),
    }
}

/// New type representing the normalization state of the event.
#[derive(Copy, Clone)]
struct EventFullyNormalized(bool);

impl EventFullyNormalized {
    /// Returns `true` if the event is fully normalized, `false` otherwise.
    pub fn new(envelope: &Envelope) -> Self {
        let event_fully_normalized = envelope.meta().is_from_internal_relay()
            && envelope
                .items()
                .any(|item| item.creates_event() && item.fully_normalized());

        Self(event_fully_normalized)
    }
}

/// New type representing whether metrics were extracted from transactions/spans.
#[derive(Debug, Copy, Clone)]
struct EventMetricsExtracted(bool);

/// New type representing whether spans were extracted.
#[derive(Debug, Copy, Clone)]
struct SpansExtracted(bool);

/// The result of the envelope processing containing the processed envelope along with the partial
/// result.
#[derive(Debug)]
struct ProcessingResult {
    managed_envelope: TypedEnvelope<Processed>,
    extracted_metrics: ProcessingExtractedMetrics,
}

impl ProcessingResult {
    /// Creates a [`ProcessingResult`] with no metrics.
    fn no_metrics(managed_envelope: TypedEnvelope<Processed>) -> Self {
        Self {
            managed_envelope,
            extracted_metrics: ProcessingExtractedMetrics::new(),
        }
    }

    /// Returns the components of the [`ProcessingResult`].
    fn into_inner(self) -> (TypedEnvelope<Processed>, ExtractedMetrics) {
        (self.managed_envelope, self.extracted_metrics.metrics)
    }
}

/// Response of the [`ProcessEnvelope`] message.
#[cfg_attr(not(feature = "processing"), allow(dead_code))]
pub struct ProcessEnvelopeResponse {
    /// The processed envelope.
    ///
    /// This is `Some` if the envelope passed inbound filtering and rate limiting. Invalid items are
    /// removed from the envelope. Otherwise, if the envelope is empty or the entire envelope needs
    /// to be dropped, this is `None`.
    pub envelope: Option<TypedEnvelope<Processed>>,
}

/// Applies processing to all contents of the given envelope.
///
/// Depending on the contents of the envelope and Relay's mode, this includes:
///
///  - Basic normalization and validation for all item types.
///  - Clock drift correction if the required `sent_at` header is present.
///  - Expansion of certain item types (e.g. unreal).
///  - Store normalization for event payloads in processing mode.
///  - Rate limiters and inbound filters on events in processing mode.
#[derive(Debug)]
pub struct ProcessEnvelope {
    /// Envelope to process.
    pub envelope: ManagedEnvelope,
    /// The project info.
    pub project_info: Arc<ProjectInfo>,
    /// Currently active cached rate limits for this project.
    pub rate_limits: Arc<RateLimits>,
    /// Root sampling project info.
    pub sampling_project_info: Option<Arc<ProjectInfo>>,
    /// Sampling reservoir counters.
    pub reservoir_counters: ReservoirCounters,
}

/// Parses a list of metrics or metric buckets and pushes them to the project's aggregator.
///
/// This parses and validates the metrics:
///  - For [`Metrics`](ItemType::Statsd), each metric is parsed separately, and invalid metrics are
///    ignored independently.
///  - For [`MetricBuckets`](ItemType::MetricBuckets), the entire list of buckets is parsed and
///    dropped together on parsing failure.
///  - Other envelope items will be ignored with an error message.
///
/// Additionally, processing applies clock drift correction using the system clock of this Relay, if
/// the Envelope specifies the [`sent_at`](Envelope::sent_at) header.
#[derive(Debug)]
pub struct ProcessMetrics {
    /// A list of metric items.
    pub data: MetricData,
    /// The target project.
    pub project_key: ProjectKey,
    /// Whether to keep or reset the metric metadata.
    pub source: BucketSource,
    /// The wall clock time at which the request was received.
    pub received_at: DateTime<Utc>,
    /// The value of the Envelope's [`sent_at`](Envelope::sent_at) header for clock drift
    /// correction.
    pub sent_at: Option<DateTime<Utc>>,
}

/// Raw unparsed metric data.
#[derive(Debug)]
pub enum MetricData {
    /// Raw data, unparsed envelope items.
    Raw(Vec<Item>),
    /// Already parsed buckets but unprocessed.
    Parsed(Vec<Bucket>),
}

impl MetricData {
    /// Consumes the metric data and parses the contained buckets.
    ///
    /// If the contained data is already parsed the buckets are returned unchanged.
    /// Raw buckets are parsed and created with the passed `timestamp`.
    fn into_buckets(self, timestamp: UnixTimestamp) -> Vec<Bucket> {
        let items = match self {
            Self::Parsed(buckets) => return buckets,
            Self::Raw(items) => items,
        };

        let mut buckets = Vec::new();
        for item in items {
            let payload = item.payload();
            if item.ty() == &ItemType::Statsd {
                for bucket_result in Bucket::parse_all(&payload, timestamp) {
                    match bucket_result {
                        Ok(bucket) => buckets.push(bucket),
                        Err(error) => relay_log::debug!(
                            error = &error as &dyn Error,
                            "failed to parse metric bucket from statsd format",
                        ),
                    }
                }
            } else if item.ty() == &ItemType::MetricBuckets {
                match serde_json::from_slice::<Vec<Bucket>>(&payload) {
                    Ok(parsed_buckets) => {
                        // Re-use the allocation of `b` if possible.
                        if buckets.is_empty() {
                            buckets = parsed_buckets;
                        } else {
                            buckets.extend(parsed_buckets);
                        }
                    }
                    Err(error) => {
                        relay_log::debug!(
                            error = &error as &dyn Error,
                            "failed to parse metric bucket",
                        );
                        metric!(counter(RelayCounters::MetricBucketsParsingFailed) += 1);
                    }
                }
            } else {
                relay_log::error!(
                    "invalid item of type {} passed to ProcessMetrics",
                    item.ty()
                );
            }
        }
        buckets
    }
}

#[derive(Debug)]
pub struct ProcessBatchedMetrics {
    /// Metrics payload in JSON format.
    pub payload: Bytes,
    /// Whether to keep or reset the metric metadata.
    pub source: BucketSource,
    /// The wall clock time at which the request was received.
    pub received_at: DateTime<Utc>,
    /// The wall clock time at which the request was received.
    pub sent_at: Option<DateTime<Utc>>,
}

/// Source information where a metric bucket originates from.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub enum BucketSource {
    /// The metric bucket originated from an internal Relay use case.
    ///
    /// The metric bucket originates either from within the same Relay
    /// or was accepted coming from another Relay which is registered as
    /// an internal Relay via Relay's configuration.
    Internal,
    /// The bucket source originated from an untrusted source.
    ///
    /// Managed Relays sending extracted metrics are considered external,
    /// it's a project use case but it comes from an untrusted source.
    External,
}

impl BucketSource {
    /// Infers the bucket source from [`RequestMeta::is_from_internal_relay`].
    pub fn from_meta(meta: &RequestMeta) -> Self {
        match meta.is_from_internal_relay() {
            true => Self::Internal,
            false => Self::External,
        }
    }
}

/// Sends an envelope to the upstream or Kafka.
#[derive(Debug)]
pub struct SubmitEnvelope {
    pub envelope: TypedEnvelope<Processed>,
}

/// Sends a client report to the upstream.
#[derive(Debug)]
pub struct SubmitClientReports {
    /// The client report to be sent.
    pub client_reports: Vec<ClientReport>,
    /// Scoping information for the client report.
    pub scoping: Scoping,
}

/// CPU-intensive processing tasks for envelopes.
#[derive(Debug)]
pub enum EnvelopeProcessor {
    ProcessEnvelope(Box<ProcessEnvelope>),
    ProcessProjectMetrics(Box<ProcessMetrics>),
    ProcessBatchedMetrics(Box<ProcessBatchedMetrics>),
    FlushBuckets(Box<FlushBuckets>),
    SubmitEnvelope(Box<SubmitEnvelope>),
    SubmitClientReports(Box<SubmitClientReports>),
}

impl EnvelopeProcessor {
    /// Returns the name of the message variant.
    pub fn variant(&self) -> &'static str {
        match self {
            EnvelopeProcessor::ProcessEnvelope(_) => "ProcessEnvelope",
            EnvelopeProcessor::ProcessProjectMetrics(_) => "ProcessProjectMetrics",
            EnvelopeProcessor::ProcessBatchedMetrics(_) => "ProcessBatchedMetrics",
            EnvelopeProcessor::FlushBuckets(_) => "FlushBuckets",
            EnvelopeProcessor::SubmitEnvelope(_) => "SubmitEnvelope",
            EnvelopeProcessor::SubmitClientReports(_) => "SubmitClientReports",
        }
    }
}

impl relay_system::Interface for EnvelopeProcessor {}

impl FromMessage<ProcessEnvelope> for EnvelopeProcessor {
    type Response = relay_system::NoResponse;

    fn from_message(message: ProcessEnvelope, _sender: ()) -> Self {
        Self::ProcessEnvelope(Box::new(message))
    }
}

impl FromMessage<ProcessMetrics> for EnvelopeProcessor {
    type Response = NoResponse;

    fn from_message(message: ProcessMetrics, _: ()) -> Self {
        Self::ProcessProjectMetrics(Box::new(message))
    }
}

impl FromMessage<ProcessBatchedMetrics> for EnvelopeProcessor {
    type Response = NoResponse;

    fn from_message(message: ProcessBatchedMetrics, _: ()) -> Self {
        Self::ProcessBatchedMetrics(Box::new(message))
    }
}

impl FromMessage<FlushBuckets> for EnvelopeProcessor {
    type Response = NoResponse;

    fn from_message(message: FlushBuckets, _: ()) -> Self {
        Self::FlushBuckets(Box::new(message))
    }
}

impl FromMessage<SubmitEnvelope> for EnvelopeProcessor {
    type Response = NoResponse;

    fn from_message(message: SubmitEnvelope, _: ()) -> Self {
        Self::SubmitEnvelope(Box::new(message))
    }
}

impl FromMessage<SubmitClientReports> for EnvelopeProcessor {
    type Response = NoResponse;

    fn from_message(message: SubmitClientReports, _: ()) -> Self {
        Self::SubmitClientReports(Box::new(message))
    }
}

/// Service implementing the [`EnvelopeProcessor`] interface.
///
/// This service handles messages in a worker pool with configurable concurrency.
#[derive(Clone)]
pub struct EnvelopeProcessorService {
    inner: Arc<InnerProcessor>,
}

/// Contains the addresses of services that the processor publishes to.
pub struct Addrs {
    pub outcome_aggregator: Addr<TrackOutcome>,
    pub upstream_relay: Addr<UpstreamRelay>,
    pub test_store: Addr<TestStore>,
    #[cfg(feature = "processing")]
    pub store_forwarder: Option<Addr<Store>>,
    pub aggregator: Addr<Aggregator>,
}

impl Default for Addrs {
    fn default() -> Self {
        Addrs {
            outcome_aggregator: Addr::dummy(),
            upstream_relay: Addr::dummy(),
            test_store: Addr::dummy(),
            #[cfg(feature = "processing")]
            store_forwarder: None,
            aggregator: Addr::dummy(),
        }
    }
}

struct InnerProcessor {
    workers: WorkerGroup,
    config: Arc<Config>,
    global_config: GlobalConfigHandle,
    project_cache: ProjectCacheHandle,
    cogs: Cogs,
    #[cfg(feature = "processing")]
    quotas_pool: Option<RedisPool>,
    addrs: Addrs,
    #[cfg(feature = "processing")]
    rate_limiter: Option<RedisRateLimiter>,
    geoip_lookup: Option<GeoIpLookup>,
    #[cfg(feature = "processing")]
    cardinality_limiter: Option<CardinalityLimiter>,
    metric_outcomes: MetricOutcomes,
}

impl EnvelopeProcessorService {
    /// Creates a multi-threaded envelope processor.
    #[cfg_attr(feature = "processing", expect(clippy::too_many_arguments))]
    pub fn new(
        pool: ThreadPool,
        config: Arc<Config>,
        global_config: GlobalConfigHandle,
        project_cache: ProjectCacheHandle,
        cogs: Cogs,
        #[cfg(feature = "processing")] redis: Option<RedisPools>,
        addrs: Addrs,
        metric_outcomes: MetricOutcomes,
    ) -> Self {
        let geoip_lookup = config.geoip_path().and_then(|p| {
            match GeoIpLookup::open(p).context(ServiceError::GeoIp) {
                Ok(geoip) => Some(geoip),
                Err(err) => {
                    relay_log::error!("failed to open GeoIP db {p:?}: {err:?}");
                    None
                }
            }
        });

        #[cfg(feature = "processing")]
        let (cardinality, quotas) = match redis {
            Some(RedisPools {
                cardinality,
                quotas,
                ..
            }) => (Some(cardinality), Some(quotas)),
            None => (None, None),
        };

        let inner = InnerProcessor {
            workers: WorkerGroup::new(pool),
            global_config,
            project_cache,
            cogs,
            #[cfg(feature = "processing")]
            quotas_pool: quotas.clone(),
            #[cfg(feature = "processing")]
            rate_limiter: quotas
                .map(|quotas| RedisRateLimiter::new(quotas).max_limit(config.max_rate_limit())),
            addrs,
            geoip_lookup,
            #[cfg(feature = "processing")]
            cardinality_limiter: cardinality
                .map(|cardinality| {
                    RedisSetLimiter::new(
                        RedisSetLimiterOptions {
                            cache_vacuum_interval: config
                                .cardinality_limiter_cache_vacuum_interval(),
                        },
                        cardinality,
                    )
                })
                .map(CardinalityLimiter::new),
            metric_outcomes,
            config,
        };

        Self {
            inner: Arc::new(inner),
        }
    }

    /// Normalize monitor check-ins and remove invalid ones.
    #[cfg(feature = "processing")]
    fn normalize_checkins(
        &self,
        managed_envelope: &mut TypedEnvelope<CheckInGroup>,
        project_id: ProjectId,
    ) {
        managed_envelope.retain_items(|item| {
            if item.ty() != &ItemType::CheckIn {
                return ItemAction::Keep;
            }

            match relay_monitors::process_check_in(&item.payload(), project_id) {
                Ok(result) => {
                    item.set_routing_hint(result.routing_hint);
                    item.set_payload(ContentType::Json, result.payload);
                    ItemAction::Keep
                }
                Err(error) => {
                    // TODO: Track an outcome.
                    relay_log::debug!(
                        error = &error as &dyn Error,
                        "dropped invalid monitor check-in"
                    );
                    ItemAction::DropSilently
                }
            }
        })
    }

    #[cfg(feature = "processing")]
    fn enforce_quotas<Group>(
        &self,
        managed_envelope: &mut TypedEnvelope<Group>,
        event: Annotated<Event>,
        extracted_metrics: &mut ProcessingExtractedMetrics,
        project_info: Arc<ProjectInfo>,
        rate_limits: Arc<RateLimits>,
    ) -> Result<Annotated<Event>, ProcessingError> {
        let global_config = self.inner.global_config.current();
        let rate_limiter = match self.inner.rate_limiter.as_ref() {
            Some(rate_limiter) => rate_limiter,
            None => return Ok(event),
        };

        // Cached quotas first, they are quick to evaluate and some quotas (indexed) are not
        // applied in the fast path, all cached quotas can be applied here.
        let cached_result = RateLimiter::Cached.enforce(
            managed_envelope,
            event,
            extracted_metrics,
            &global_config,
            project_info.clone(),
            rate_limits.clone(),
        )?;

        // Enforce all quotas consistently with Redis.
        let consistent_result = RateLimiter::Consistent(rate_limiter).enforce(
            managed_envelope,
            cached_result.event,
            extracted_metrics,
            &global_config,
            project_info,
            rate_limits,
        )?;

        // Update cached rate limits with the freshly computed ones.
        if !consistent_result.rate_limits.is_empty() {
            self.inner
                .project_cache
                .get(managed_envelope.scoping().project_key)
                .rate_limits()
                .merge(consistent_result.rate_limits);
        }

        Ok(consistent_result.event)
    }

    /// Extract transaction metrics.
    #[allow(clippy::too_many_arguments)]
    fn extract_transaction_metrics(
        &self,
        managed_envelope: &mut TypedEnvelope<TransactionGroup>,
        event: &mut Annotated<Event>,
        extracted_metrics: &mut ProcessingExtractedMetrics,
        project_id: ProjectId,
        project_info: Arc<ProjectInfo>,
        sampling_decision: SamplingDecision,
        event_metrics_extracted: EventMetricsExtracted,
        spans_extracted: SpansExtracted,
    ) -> Result<EventMetricsExtracted, ProcessingError> {
        if event_metrics_extracted.0 {
            return Ok(event_metrics_extracted);
        }
        let Some(event) = event.value_mut() else {
            return Ok(event_metrics_extracted);
        };

        // NOTE: This function requires a `metric_extraction` in the project config. Legacy configs
        // will upsert this configuration from transaction and conditional tagging fields, even if
        // it is not present in the actual project config payload.
        let global = self.inner.global_config.current();
        let combined_config = {
            let config = match &project_info.config.metric_extraction {
                ErrorBoundary::Ok(ref config) if config.is_supported() => config,
                _ => return Ok(event_metrics_extracted),
            };
            let global_config = match &global.metric_extraction {
                ErrorBoundary::Ok(global_config) => global_config,
                #[allow(unused_variables)]
                ErrorBoundary::Err(e) => {
                    if_processing!(self.inner.config, {
                        // Config is invalid, but we will try to extract what we can with just the
                        // project config.
                        relay_log::error!("Failed to parse global extraction config {e}");
                        MetricExtractionGroups::EMPTY
                    } else {
                        // If there's an error with global metrics extraction, it is safe to assume that this
                        // Relay instance is not up-to-date, and we should skip extraction.
                        relay_log::debug!("Failed to parse global extraction config: {e}");
                        return Ok(event_metrics_extracted);
                    })
                }
            };
            CombinedMetricExtractionConfig::new(global_config, config)
        };

        // Require a valid transaction metrics config.
        let tx_config = match &project_info.config.transaction_metrics {
            Some(ErrorBoundary::Ok(tx_config)) => tx_config,
            Some(ErrorBoundary::Err(e)) => {
                relay_log::debug!("Failed to parse legacy transaction metrics config: {e}");
                return Ok(event_metrics_extracted);
            }
            None => {
                relay_log::debug!("Legacy transaction metrics config is missing");
                return Ok(event_metrics_extracted);
            }
        };

        if !tx_config.is_enabled() {
            static TX_CONFIG_ERROR: Once = Once::new();
            TX_CONFIG_ERROR.call_once(|| {
                if self.inner.config.processing_enabled() {
                    relay_log::error!(
                        "Processing Relay outdated, received tx config in version {}, which is not supported",
                        tx_config.version
                    );
                }
            });

            return Ok(event_metrics_extracted);
        }

        // If spans were already extracted for an event, we rely on span processing to extract metrics.
        let extract_spans = !spans_extracted.0
            && project_info.config.features.produces_spans()
            && utils::sample(global.options.span_extraction_sample_rate.unwrap_or(1.0));

        let metrics = crate::metrics_extraction::event::extract_metrics(
            event,
            combined_config,
            sampling_decision,
            project_id,
            self.inner
                .config
                .aggregator_config_for(MetricNamespace::Spans)
                .max_tag_value_length,
            extract_spans,
        );

        extracted_metrics.extend(metrics, Some(sampling_decision));

        if !project_info.has_feature(Feature::DiscardTransaction) {
            let transaction_from_dsc = managed_envelope
                .envelope()
                .dsc()
                .and_then(|dsc| dsc.transaction.as_deref());

            let extractor = TransactionExtractor {
                config: tx_config,
                generic_config: Some(combined_config),
                transaction_from_dsc,
                sampling_decision,
                target_project_id: project_id,
            };

            extracted_metrics.extend(extractor.extract(event)?, Some(sampling_decision));
        }

        Ok(EventMetricsExtracted(true))
    }

    fn normalize_event<Group: EventProcessing>(
        &self,
        managed_envelope: &mut TypedEnvelope<Group>,
        event: &mut Annotated<Event>,
        project_id: ProjectId,
        project_info: Arc<ProjectInfo>,
        mut event_fully_normalized: EventFullyNormalized,
    ) -> Result<EventFullyNormalized, ProcessingError> {
        if event.value().is_empty() {
            // NOTE(iker): only processing relays create events from
            // attachments, so these events won't be normalized in
            // non-processing relays even if the config is set to run full
            // normalization.
            return Ok(event_fully_normalized);
        }

        let full_normalization = match self.inner.config.normalization_level() {
            NormalizationLevel::Full => true,
            NormalizationLevel::Default => {
                if self.inner.config.processing_enabled() && event_fully_normalized.0 {
                    return Ok(event_fully_normalized);
                }

                self.inner.config.processing_enabled()
            }
        };

        let request_meta = managed_envelope.envelope().meta();
        let client_ipaddr = request_meta.client_addr().map(IpAddr::from);

        let transaction_aggregator_config = self
            .inner
            .config
            .aggregator_config_for(MetricNamespace::Transactions);

        let global_config = self.inner.global_config.current();
        let ai_model_costs = global_config.ai_model_costs.clone().ok();
        let http_span_allowed_hosts = global_config.options.http_span_allowed_hosts.as_slice();

        let retention_days: i64 = project_info
            .config
            .event_retention
            .unwrap_or(DEFAULT_EVENT_RETENTION)
            .into();

        utils::log_transaction_name_metrics(event, |event| {
            let event_validation_config = EventValidationConfig {
                received_at: Some(managed_envelope.received_at()),
                max_secs_in_past: Some(retention_days * 24 * 3600),
                max_secs_in_future: Some(self.inner.config.max_secs_in_future()),
                transaction_timestamp_range: Some(transaction_aggregator_config.timestamp_range()),
                is_validated: false,
            };

            let key_id = project_info
                .get_public_key_config()
                .and_then(|key| Some(key.numeric_id?.to_string()));
            if full_normalization && key_id.is_none() {
                relay_log::error!(
                    "project state for key {} is missing key id",
                    managed_envelope.envelope().meta().public_key()
                );
            }

            let normalization_config = NormalizationConfig {
                project_id: Some(project_id.value()),
                client: request_meta.client().map(str::to_owned),
                key_id,
                protocol_version: Some(request_meta.version().to_string()),
                grouping_config: project_info.config.grouping_config.clone(),
                client_ip: client_ipaddr.as_ref(),
                client_sample_rate: managed_envelope
                    .envelope()
                    .dsc()
                    .and_then(|ctx| ctx.sample_rate),
                user_agent: RawUserAgentInfo {
                    user_agent: request_meta.user_agent(),
                    client_hints: request_meta.client_hints().as_deref(),
                },
                max_name_and_unit_len: Some(
                    transaction_aggregator_config
                        .max_name_length
                        .saturating_sub(MeasurementsConfig::MEASUREMENT_MRI_OVERHEAD),
                ),
                breakdowns_config: project_info.config.breakdowns_v2.as_ref(),
                performance_score: project_info.config.performance_score.as_ref(),
                normalize_user_agent: Some(true),
                transaction_name_config: TransactionNameConfig {
                    rules: &project_info.config.tx_name_rules,
                },
                device_class_synthesis_config: project_info
                    .has_feature(Feature::DeviceClassSynthesis),
                enrich_spans: project_info.has_feature(Feature::ExtractSpansFromEvent)
                    || project_info.has_feature(Feature::ExtractCommonSpanMetricsFromEvent),
                max_tag_value_length: self
                    .inner
                    .config
                    .aggregator_config_for(MetricNamespace::Spans)
                    .max_tag_value_length,
                is_renormalize: false,
                remove_other: full_normalization,
                emit_event_errors: full_normalization,
                span_description_rules: project_info.config.span_description_rules.as_ref(),
                geoip_lookup: self.inner.geoip_lookup.as_ref(),
                ai_model_costs: ai_model_costs.as_ref(),
                enable_trimming: true,
                measurements: Some(CombinedMeasurementsConfig::new(
                    project_info.config().measurements.as_ref(),
                    global_config.measurements.as_ref(),
                )),
                normalize_spans: true,
                replay_id: managed_envelope
                    .envelope()
                    .dsc()
                    .and_then(|ctx| ctx.replay_id),
                span_allowed_hosts: http_span_allowed_hosts,
                span_op_defaults: global_config.span_op_defaults.borrow(),
            };

            metric!(timer(RelayTimers::EventProcessingNormalization), {
                validate_event(event, &event_validation_config)
                    .map_err(|_| ProcessingError::InvalidTransaction)?;
                normalize_event(event, &normalization_config);
                if full_normalization && event::has_unprintable_fields(event) {
                    metric!(counter(RelayCounters::EventCorrupted) += 1);
                }
                Result::<(), ProcessingError>::Ok(())
            })
        })?;

        event_fully_normalized.0 |= full_normalization;

        Ok(event_fully_normalized)
    }

    /// Processes the general errors, and the items which require or create the events.
    fn process_errors(
        &self,
        managed_envelope: &mut TypedEnvelope<ErrorGroup>,
        project_id: ProjectId,
        project_info: Arc<ProjectInfo>,
        sampling_project_info: Option<Arc<ProjectInfo>>,
        #[allow(unused_variables)] rate_limits: Arc<RateLimits>,
    ) -> Result<Option<ProcessingExtractedMetrics>, ProcessingError> {
        let mut event_fully_normalized = EventFullyNormalized::new(managed_envelope.envelope());
        let mut metrics = Metrics::default();
        #[allow(unused_mut)]
        let mut extracted_metrics = ProcessingExtractedMetrics::new();

        // Events can also contain user reports.
        report::process_user_reports(managed_envelope);

        if_processing!(self.inner.config, {
            unreal::expand(managed_envelope, &self.inner.config)?;
        });

        let extraction_result = event::extract(
            managed_envelope,
            &mut metrics,
            event_fully_normalized,
            &self.inner.config,
        )?;
        let mut event = extraction_result.event;

        if_processing!(self.inner.config, {
            if let Some(inner_event_fully_normalized) =
                unreal::process(managed_envelope, &mut event)?
            {
                event_fully_normalized = inner_event_fully_normalized;
            }
            if let Some(inner_event_fully_normalized) =
                attachment::create_placeholders(managed_envelope, &mut event, &mut metrics)
            {
                event_fully_normalized = inner_event_fully_normalized;
            }
        });

        event::finalize(
            managed_envelope,
            &mut event,
            &mut metrics,
            &self.inner.config,
        )?;
        event_fully_normalized = self.normalize_event(
            managed_envelope,
            &mut event,
            project_id,
            project_info.clone(),
            event_fully_normalized,
        )?;
        let filter_run = event::filter(
            managed_envelope,
            &mut event,
            project_info.clone(),
            &self.inner.global_config.current(),
        )?;

        if self.inner.config.processing_enabled() || matches!(filter_run, FiltersStatus::Ok) {
            dynamic_sampling::tag_error_with_sampling_decision(
                managed_envelope,
                &mut event,
                sampling_project_info,
                &self.inner.config,
            );
        }

        if_processing!(self.inner.config, {
            event = self.enforce_quotas(
                managed_envelope,
                event,
                &mut extracted_metrics,
                project_info.clone(),
                rate_limits,
            )?;
        });

        if event.value().is_some() {
            event::scrub(&mut event, project_info.clone())?;
            event::serialize(
                managed_envelope,
                &mut event,
                event_fully_normalized,
                EventMetricsExtracted(false),
                SpansExtracted(false),
            )?;
            event::emit_feedback_metrics(managed_envelope.envelope());
        }

        attachment::scrub(managed_envelope, project_info);

        if self.inner.config.processing_enabled() && !event_fully_normalized.0 {
            relay_log::error!(
                tags.project = %project_id,
                tags.ty = event_type(&event).map(|e| e.to_string()).unwrap_or("none".to_owned()),
                "ingested event without normalizing"
            );
        }

        Ok(Some(extracted_metrics))
    }

    /// Processes only transactions and transaction-related items.
    #[allow(unused_assignments)]
    #[allow(clippy::too_many_arguments)]
    fn process_transactions(
        &self,
        managed_envelope: &mut TypedEnvelope<TransactionGroup>,
        config: Arc<Config>,
        project_id: ProjectId,
        project_info: Arc<ProjectInfo>,
        mut sampling_project_info: Option<Arc<ProjectInfo>>,
        #[allow(unused_variables)] rate_limits: Arc<RateLimits>,
        reservoir_counters: ReservoirCounters,
    ) -> Result<Option<ProcessingExtractedMetrics>, ProcessingError> {
        let mut event_fully_normalized = EventFullyNormalized::new(managed_envelope.envelope());
        let mut event_metrics_extracted = EventMetricsExtracted(false);
        let mut spans_extracted = SpansExtracted(false);
        let mut metrics = Metrics::default();
        let mut extracted_metrics = ProcessingExtractedMetrics::new();

        let global_config = self.inner.global_config.current();

        // We extract the main event from the envelope.
        let extraction_result = event::extract(
            managed_envelope,
            &mut metrics,
            event_fully_normalized,
            &self.inner.config,
        )?;

        // If metrics were extracted we mark that.
        if let Some(inner_event_metrics_extracted) = extraction_result.event_metrics_extracted {
            event_metrics_extracted = inner_event_metrics_extracted;
        }
        if let Some(inner_spans_extracted) = extraction_result.spans_extracted {
            spans_extracted = inner_spans_extracted;
        };

        // We take the main event out of the result.
        let mut event = extraction_result.event;

        let profile_id = profile::filter(
            managed_envelope,
            &event,
            config.clone(),
            project_id,
            project_info.clone(),
        );
        profile::transfer_id(&mut event, profile_id);

        event::finalize(
            managed_envelope,
            &mut event,
            &mut metrics,
            &self.inner.config,
        )?;
        event_fully_normalized = self.normalize_event(
            managed_envelope,
            &mut event,
            project_id,
            project_info.clone(),
            event_fully_normalized,
        )?;

        sampling_project_info = dynamic_sampling::validate_and_set_dsc(
            managed_envelope,
            &mut event,
            project_info.clone(),
            sampling_project_info.clone(),
        );

        let filter_run = event::filter(
            managed_envelope,
            &mut event,
            project_info.clone(),
            &self.inner.global_config.current(),
        )?;

        // Always run dynamic sampling on processing Relays,
        // but delay decision until inbound filters have been fully processed.
        let run_dynamic_sampling =
            matches!(filter_run, FiltersStatus::Ok) || self.inner.config.processing_enabled();

        let reservoir = self.new_reservoir_evaluator(
            managed_envelope.scoping().organization_id,
            reservoir_counters,
        );

        let sampling_result = match run_dynamic_sampling {
            true => dynamic_sampling::run(
                managed_envelope,
                &mut event,
                config.clone(),
                project_info.clone(),
                sampling_project_info,
                &reservoir,
            ),
            false => SamplingResult::Pending,
        };

        #[cfg(feature = "processing")]
        let server_sample_rate = match sampling_result {
            SamplingResult::Match(ref sampling_match) => Some(sampling_match.sample_rate()),
            SamplingResult::NoMatch | SamplingResult::Pending => None,
        };

        if let Some(outcome) = sampling_result.into_dropped_outcome() {
            // Process profiles before dropping the transaction, if necessary.
            // Before metric extraction to make sure the profile count is reflected correctly.
            profile::process(
                managed_envelope,
                &mut event,
                &global_config,
                config.clone(),
                project_info.clone(),
            );
            // Extract metrics here, we're about to drop the event/transaction.
            event_metrics_extracted = self.extract_transaction_metrics(
                managed_envelope,
                &mut event,
                &mut extracted_metrics,
                project_id,
                project_info.clone(),
                SamplingDecision::Drop,
                event_metrics_extracted,
                spans_extracted,
            )?;

            dynamic_sampling::drop_unsampled_items(managed_envelope, event, outcome);

            // At this point we have:
            //  - An empty envelope.
            //  - An envelope containing only processed profiles.
            // We need to make sure there are enough quotas for these profiles.
            if_processing!(self.inner.config, {
                event = self.enforce_quotas(
                    managed_envelope,
                    Annotated::empty(),
                    &mut extracted_metrics,
                    project_info.clone(),
                    rate_limits,
                )?;
            });

            return Ok(Some(extracted_metrics));
        }

        // Need to scrub the transaction before extracting spans.
        //
        // Unconditionally scrub to make sure PII is removed as early as possible.
        event::scrub(&mut event, project_info.clone())?;
        attachment::scrub(managed_envelope, project_info.clone());

        if_processing!(self.inner.config, {
            // Process profiles before extracting metrics, to make sure they are removed if they are invalid.
            let profile_id = profile::process(
                managed_envelope,
                &mut event,
                &global_config,
                config.clone(),
                project_info.clone(),
            );
            profile::transfer_id(&mut event, profile_id);

            // Always extract metrics in processing Relays for sampled items.
            event_metrics_extracted = self.extract_transaction_metrics(
                managed_envelope,
                &mut event,
                &mut extracted_metrics,
                project_id,
                project_info.clone(),
                SamplingDecision::Keep,
                event_metrics_extracted,
                spans_extracted,
            )?;

            if project_info.has_feature(Feature::ExtractSpansFromEvent) {
                spans_extracted = span::extract_from_event(
                    managed_envelope,
                    &event,
                    &global_config,
                    config,
                    project_info.clone(),
                    server_sample_rate,
                    event_metrics_extracted,
                    spans_extracted,
                );
            }

            event = self.enforce_quotas(
                managed_envelope,
                event,
                &mut extracted_metrics,
                project_info.clone(),
                rate_limits,
            )?;

            event = span::maybe_discard_transaction(managed_envelope, event, project_info);
        });

        // Event may have been dropped because of a quota and the envelope can be empty.
        if event.value().is_some() {
            event::serialize(
                managed_envelope,
                &mut event,
                event_fully_normalized,
                event_metrics_extracted,
                spans_extracted,
            )?;
        }

        if self.inner.config.processing_enabled() && !event_fully_normalized.0 {
            relay_log::error!(
                tags.project = %project_id,
                tags.ty = event_type(&event).map(|e| e.to_string()).unwrap_or("none".to_owned()),
                "ingested event without normalizing"
            );
        };

        Ok(Some(extracted_metrics))
    }

    fn process_profile_chunks(
        &self,
        managed_envelope: &mut TypedEnvelope<ProfileChunkGroup>,
        project_info: Arc<ProjectInfo>,
    ) -> Result<Option<ProcessingExtractedMetrics>, ProcessingError> {
        profile_chunk::filter(managed_envelope, project_info.clone());
        if_processing!(self.inner.config, {
            profile_chunk::process(
                managed_envelope,
                project_info,
                &self.inner.global_config.current(),
                &self.inner.config,
            );
        });

        Ok(None)
    }

    /// Processes standalone items that require an event ID, but do not have an event on the same envelope.
    fn process_standalone(
        &self,
        managed_envelope: &mut TypedEnvelope<StandaloneGroup>,
        config: Arc<Config>,
        project_id: ProjectId,
        project_info: Arc<ProjectInfo>,
        #[allow(unused_variables)] rate_limits: Arc<RateLimits>,
    ) -> Result<Option<ProcessingExtractedMetrics>, ProcessingError> {
        #[allow(unused_mut)]
        let mut extracted_metrics = ProcessingExtractedMetrics::new();

        profile::filter(
            managed_envelope,
            &Annotated::empty(),
            config,
            project_id,
            project_info.clone(),
        );

        if_processing!(self.inner.config, {
            self.enforce_quotas(
                managed_envelope,
                Annotated::empty(),
                &mut extracted_metrics,
                project_info.clone(),
                rate_limits,
            )?;
        });

        report::process_user_reports(managed_envelope);
        attachment::scrub(managed_envelope, project_info);

        Ok(Some(extracted_metrics))
    }

    /// Processes user sessions.
    fn process_sessions(
        &self,
        managed_envelope: &mut TypedEnvelope<SessionGroup>,
        project_info: Arc<ProjectInfo>,
        #[allow(unused_variables)] rate_limits: Arc<RateLimits>,
    ) -> Result<Option<ProcessingExtractedMetrics>, ProcessingError> {
        let mut extracted_metrics = ProcessingExtractedMetrics::new();

        session::process(
            managed_envelope,
            &mut extracted_metrics,
            project_info.clone(),
            &self.inner.config,
        );
        if_processing!(self.inner.config, {
            self.enforce_quotas(
                managed_envelope,
                Annotated::empty(),
                &mut extracted_metrics,
                project_info,
                rate_limits,
            )?;
        });

        Ok(Some(extracted_metrics))
    }

    /// Processes user and client reports.
    fn process_client_reports(
        &self,
        managed_envelope: &mut TypedEnvelope<ClientReportGroup>,
        config: Arc<Config>,
        project_info: Arc<ProjectInfo>,
        #[allow(unused_variables)] rate_limits: Arc<RateLimits>,
    ) -> Result<Option<ProcessingExtractedMetrics>, ProcessingError> {
        #[allow(unused_mut)]
        let mut extracted_metrics = ProcessingExtractedMetrics::new();

        if_processing!(self.inner.config, {
            self.enforce_quotas(
                managed_envelope,
                Annotated::empty(),
                &mut extracted_metrics,
                project_info.clone(),
                rate_limits,
            )?;
        });

        report::process_client_reports(
            managed_envelope,
            config,
            project_info,
            self.inner.addrs.outcome_aggregator.clone(),
        );

        Ok(Some(extracted_metrics))
    }

    /// Processes replays.
    fn process_replays(
        &self,
        managed_envelope: &mut TypedEnvelope<ReplayGroup>,
        config: Arc<Config>,
        project_info: Arc<ProjectInfo>,
        #[allow(unused_variables)] rate_limits: Arc<RateLimits>,
    ) -> Result<Option<ProcessingExtractedMetrics>, ProcessingError> {
        #[allow(unused_mut)]
        let mut extracted_metrics = ProcessingExtractedMetrics::new();

        replay::process(
            managed_envelope,
            &self.inner.global_config.current(),
            config,
            project_info.clone(),
            self.inner.geoip_lookup.as_ref(),
        )?;

        if_processing!(self.inner.config, {
            self.enforce_quotas(
                managed_envelope,
                Annotated::empty(),
                &mut extracted_metrics,
                project_info,
                rate_limits,
            )?;
        });

        Ok(Some(extracted_metrics))
    }

    /// Processes cron check-ins.
    fn process_checkins(
        &self,
        #[allow(unused_variables)] managed_envelope: &mut TypedEnvelope<CheckInGroup>,
        #[allow(unused_variables)] project_id: ProjectId,
        #[allow(unused_variables)] project_info: Arc<ProjectInfo>,
        #[allow(unused_variables)] rate_limits: Arc<RateLimits>,
    ) -> Result<Option<ProcessingExtractedMetrics>, ProcessingError> {
        #[allow(unused_mut)]
        let mut extracted_metrics = ProcessingExtractedMetrics::new();

        if_processing!(self.inner.config, {
            self.enforce_quotas(
                managed_envelope,
                Annotated::empty(),
                &mut extracted_metrics,
                project_info,
                rate_limits,
            )?;
            self.normalize_checkins(managed_envelope, project_id);
        });

        Ok(Some(extracted_metrics))
    }

    /// Processes standalone spans.
    ///
    /// This function does *not* run for spans extracted from transactions.
    #[allow(clippy::too_many_arguments)]
    fn process_standalone_spans(
        &self,
        managed_envelope: &mut TypedEnvelope<SpanGroup>,
        config: Arc<Config>,
        #[allow(unused_variables)] project_id: ProjectId,
        project_info: Arc<ProjectInfo>,
        #[allow(unused_variables)] sampling_project_info: Option<Arc<ProjectInfo>>,
        #[allow(unused_variables)] rate_limits: Arc<RateLimits>,
        #[allow(unused_variables)] reservoir_counters: ReservoirCounters,
    ) -> Result<Option<ProcessingExtractedMetrics>, ProcessingError> {
        #[allow(unused_mut)]
        let mut extracted_metrics = ProcessingExtractedMetrics::new();

        span::filter(managed_envelope, config.clone(), project_info.clone());
        span::convert_otel_traces_data(managed_envelope);

        if_processing!(self.inner.config, {
            let global_config = self.inner.global_config.current();
            let reservoir = self.new_reservoir_evaluator(
                managed_envelope.scoping().organization_id,
                reservoir_counters,
            );

            span::process(
                managed_envelope,
                &mut Annotated::empty(),
                &mut extracted_metrics,
                &global_config,
                config,
                project_id,
                project_info.clone(),
                sampling_project_info,
                self.inner.geoip_lookup.as_ref(),
                &reservoir,
            );

            self.enforce_quotas(
                managed_envelope,
                Annotated::empty(),
                &mut extracted_metrics,
                project_info,
                rate_limits,
            )?;
        });

        Ok(Some(extracted_metrics))
    }

    fn process_envelope(
        &self,
        mut managed_envelope: ManagedEnvelope,
        project_id: ProjectId,
        project_info: Arc<ProjectInfo>,
        rate_limits: Arc<RateLimits>,
        sampling_project_info: Option<Arc<ProjectInfo>>,
        reservoir_counters: ReservoirCounters,
    ) -> Result<ProcessingResult, ProcessingError> {
        // Get the group from the managed envelope context, and if it's not set, try to guess it
        // from the contents of the envelope.
        let group = managed_envelope.group();

        // Pre-process the envelope headers.
        if let Some(sampling_state) = sampling_project_info.as_ref() {
            // Both transactions and standalone span envelopes need a normalized DSC header
            // to make sampling rules based on the segment/transaction name work correctly.
            managed_envelope
                .envelope_mut()
                .parametrize_dsc_transaction(&sampling_state.config.tx_name_rules);
        }

        // Set the event retention. Effectively, this value will only be available in processing
        // mode when the full project config is queried from the upstream.
        if let Some(retention) = project_info.config.event_retention {
            managed_envelope.envelope_mut().set_retention(retention);
        }

        // Ensure the project ID is updated to the stored instance for this project cache. This can
        // differ in two cases:
        //  1. The envelope was sent to the legacy `/store/` endpoint without a project ID.
        //  2. The DSN was moved and the envelope sent to the old project ID.
        managed_envelope
            .envelope_mut()
            .meta_mut()
            .set_project_id(project_id);

        macro_rules! run {
            ($fn_name:ident $(, $args:expr)*) => {{
                let mut managed_envelope = managed_envelope.try_into()?;
                match self.$fn_name(&mut managed_envelope, $($args),*) {
                    Ok(extracted_metrics) => Ok(ProcessingResult {
                        managed_envelope: managed_envelope.into_processed(),
                        extracted_metrics: extracted_metrics.map_or(ProcessingExtractedMetrics::new(), |e| e)
                    }),
                    Err(error) => {
                        if let Some(outcome) = error.to_outcome() {
                            managed_envelope.reject(outcome);
                        }

                        return Err(error);
                    }
                }

            }};
        }

        relay_log::trace!("Processing {group} group", group = group.variant());

        match group {
            ProcessingGroup::Error => run!(
                process_errors,
                project_id,
                project_info,
                sampling_project_info,
                rate_limits
            ),
            ProcessingGroup::Transaction => {
                run!(
                    process_transactions,
                    self.inner.config.clone(),
                    project_id,
                    project_info,
                    sampling_project_info,
                    rate_limits,
                    reservoir_counters
                )
            }
            ProcessingGroup::Session => run!(process_sessions, project_info, rate_limits),
            ProcessingGroup::Standalone => run!(
                process_standalone,
                self.inner.config.clone(),
                project_id,
                project_info,
                rate_limits
            ),
            ProcessingGroup::ClientReport => run!(
                process_client_reports,
                self.inner.config.clone(),
                project_info,
                rate_limits
            ),
            ProcessingGroup::Replay => {
                run!(
                    process_replays,
                    self.inner.config.clone(),
                    project_info,
                    rate_limits
                )
            }
            ProcessingGroup::CheckIn => {
                run!(process_checkins, project_id, project_info, rate_limits)
            }
            ProcessingGroup::Span => run!(
                process_standalone_spans,
                self.inner.config.clone(),
                project_id,
                project_info,
                sampling_project_info,
                rate_limits,
                reservoir_counters
            ),
            ProcessingGroup::ProfileChunk => run!(process_profile_chunks, project_info),
            // Currently is not used.
            ProcessingGroup::Metrics => {
                // In proxy mode we simply forward the metrics.
                // This group shouldn't be used outside of proxy mode.
                if self.inner.config.relay_mode() != RelayMode::Proxy {
                    relay_log::error!(
                        tags.project = %project_id,
                        items = ?managed_envelope.envelope().items().next().map(Item::ty),
                        "received metrics in the process_state"
                    );
                }

                Ok(ProcessingResult::no_metrics(
                    managed_envelope.into_processed(),
                ))
            }
            // Fallback to the legacy process_state implementation for Ungrouped events.
            ProcessingGroup::Ungrouped => {
                relay_log::error!(
                    tags.project = %project_id,
                    items = ?managed_envelope.envelope().items().next().map(Item::ty),
                    "could not identify the processing group based on the envelope's items"
                );

                Ok(ProcessingResult::no_metrics(
                    managed_envelope.into_processed(),
                ))
            }
            // Leave this group unchanged.
            //
            // This will later be forwarded to upstream.
            ProcessingGroup::ForwardUnknown => Ok(ProcessingResult::no_metrics(
                managed_envelope.into_processed(),
            )),
        }
    }

    fn process(
        &self,
        message: ProcessEnvelope,
    ) -> Result<ProcessEnvelopeResponse, ProcessingError> {
        let ProcessEnvelope {
            envelope: mut managed_envelope,
            project_info,
            rate_limits,
            sampling_project_info,
            reservoir_counters,
        } = message;

        // Prefer the project's project ID, and fall back to the stated project id from the
        // envelope. The project ID is available in all modes, other than in proxy mode, where
        // envelopes for unknown projects are forwarded blindly.
        //
        // Neither ID can be available in proxy mode on the /store/ endpoint. This is not supported,
        // since we cannot process an envelope without project ID, so drop it.
        let project_id = match project_info
            .project_id
            .or_else(|| managed_envelope.envelope().meta().project_id())
        {
            Some(project_id) => project_id,
            None => {
                managed_envelope.reject(Outcome::Invalid(DiscardReason::Internal));
                return Err(ProcessingError::MissingProjectId);
            }
        };

        let client = managed_envelope
            .envelope()
            .meta()
            .client()
            .map(str::to_owned);

        let user_agent = managed_envelope
            .envelope()
            .meta()
            .user_agent()
            .map(str::to_owned);

        relay_log::with_scope(
            |scope| {
                scope.set_tag("project", project_id);
                if let Some(client) = client {
                    scope.set_tag("sdk", client);
                }
                if let Some(user_agent) = user_agent {
                    scope.set_extra("user_agent", user_agent.into());
                }
            },
            || {
                match self.process_envelope(
                    managed_envelope,
                    project_id,
                    project_info,
                    rate_limits,
                    sampling_project_info,
                    reservoir_counters,
                ) {
                    Ok(result) => {
                        let (mut managed_envelope, extracted_metrics) = result.into_inner();

                        // The envelope could be modified or even emptied during processing, which
                        // requires re-computation of the context.
                        managed_envelope.update();

                        let has_metrics = !extracted_metrics.project_metrics.is_empty();
                        if has_metrics {
                            send_metrics(
                                extracted_metrics,
                                managed_envelope.envelope(),
                                &self.inner.addrs.aggregator,
                            );
                        }

                        let envelope_response = if managed_envelope.envelope().is_empty() {
                            if !has_metrics {
                                // Individual rate limits have already been issued
                                managed_envelope.reject(Outcome::RateLimited(None));
                            } else {
                                managed_envelope.accept();
                            }

                            None
                        } else {
                            Some(managed_envelope)
                        };

                        Ok(ProcessEnvelopeResponse {
                            envelope: envelope_response,
                        })
                    }
                    Err(err) => Err(err),
                }
            },
        )
    }

    fn handle_process_envelope(&self, message: ProcessEnvelope) {
        let project_key = message.envelope.envelope().meta().public_key();
        let wait_time = message.envelope.age();
        metric!(timer(RelayTimers::EnvelopeWaitTime) = wait_time);

        let group = message.envelope.group().variant();
        let result = metric!(timer(RelayTimers::EnvelopeProcessingTime), group = group, {
            self.process(message)
        });
        match result {
            Ok(response) => {
                if let Some(envelope) = response.envelope {
                    self.handle_submit_envelope(SubmitEnvelope { envelope });
                };
            }
            Err(error) => {
                // Errors are only logged for what we consider infrastructure or implementation
                // bugs. In other cases, we "expect" errors and log them as debug level.
                if error.is_unexpected() {
                    relay_log::error!(
                        tags.project_key = %project_key,
                        error = &error as &dyn Error,
                        "error processing envelope"
                    );
                }
            }
        }
    }

    fn handle_process_metrics(&self, cogs: &mut Token, message: ProcessMetrics) {
        let ProcessMetrics {
            data,
            project_key,
            received_at,
            sent_at,
            source,
        } = message;

        let received_timestamp =
            UnixTimestamp::from_datetime(received_at).unwrap_or(UnixTimestamp::now());

        let mut buckets = data.into_buckets(received_timestamp);
        if buckets.is_empty() {
            return;
        };
        cogs.update(relay_metrics::cogs::BySize(&buckets));

        let clock_drift_processor =
            ClockDriftProcessor::new(sent_at, received_at).at_least(MINIMUM_CLOCK_DRIFT);

        buckets.retain_mut(|bucket| {
            if let Err(error) = relay_metrics::normalize_bucket(bucket) {
                relay_log::debug!(error = &error as &dyn Error, "dropping bucket {bucket:?}");
                return false;
            }

            if !self::metrics::is_valid_namespace(bucket, source) {
                return false;
            }

            clock_drift_processor.process_timestamp(&mut bucket.timestamp);

            if !matches!(source, BucketSource::Internal) {
                bucket.metadata = BucketMetadata::new(received_timestamp);
            }

            true
        });

        let project = self.inner.project_cache.get(project_key);

        // Best effort check to filter and rate limit buckets, if there is no project state
        // available at the current time, we will check again after flushing.
        let buckets = match project.state() {
            ProjectState::Enabled(project_info) => {
                let rate_limits = project.rate_limits().current_limits();
                self.check_buckets(project_key, project_info, &rate_limits, buckets)
            }
            _ => buckets,
        };

        relay_log::trace!("merging metric buckets into the aggregator");
        self.inner
            .addrs
            .aggregator
            .send(MergeBuckets::new(project_key, buckets));
    }

    fn handle_process_batched_metrics(&self, cogs: &mut Token, message: ProcessBatchedMetrics) {
        let ProcessBatchedMetrics {
            payload,
            source,
            received_at,
            sent_at,
        } = message;

        #[derive(serde::Deserialize)]
        struct Wrapper {
            buckets: HashMap<ProjectKey, Vec<Bucket>>,
        }

        let buckets = match serde_json::from_slice(&payload) {
            Ok(Wrapper { buckets }) => buckets,
            Err(error) => {
                relay_log::debug!(
                    error = &error as &dyn Error,
                    "failed to parse batched metrics",
                );
                metric!(counter(RelayCounters::MetricBucketsParsingFailed) += 1);
                return;
            }
        };

        for (project_key, buckets) in buckets {
            self.handle_process_metrics(
                cogs,
                ProcessMetrics {
                    data: MetricData::Parsed(buckets),
                    project_key,
                    source,
                    received_at,
                    sent_at,
                },
            )
        }
    }

    fn handle_submit_envelope(&self, message: SubmitEnvelope) {
        let SubmitEnvelope { mut envelope } = message;

        #[cfg(feature = "processing")]
        if self.inner.config.processing_enabled() {
            if let Some(store_forwarder) = self.inner.addrs.store_forwarder.clone() {
                relay_log::trace!("sending envelope to kafka");
                store_forwarder.send(StoreEnvelope { envelope });
                return;
            }
        }

        // If we are in capture mode, we stash away the event instead of forwarding it.
        if Capture::should_capture(&self.inner.config) {
            relay_log::trace!("capturing envelope in memory");
            self.inner
                .addrs
                .test_store
                .send(Capture::accepted(envelope));
            return;
        }

        // Override the `sent_at` timestamp. Since the envelope went through basic
        // normalization, all timestamps have been corrected. We propagate the new
        // `sent_at` to allow the next Relay to double-check this timestamp and
        // potentially apply correction again. This is done as close to sending as
        // possible so that we avoid internal delays.
        envelope.envelope_mut().set_sent_at(Utc::now());

        relay_log::trace!("sending envelope to sentry endpoint");
        let http_encoding = self.inner.config.http_encoding();
        let result = envelope.envelope().to_vec().and_then(|v| {
            encode_payload(&v.into(), http_encoding).map_err(EnvelopeError::PayloadIoFailed)
        });

        match result {
            Ok(body) => {
                self.inner
                    .addrs
                    .upstream_relay
                    .send(SendRequest(SendEnvelope {
                        envelope,
                        body,
                        http_encoding,
                        project_cache: self.inner.project_cache.clone(),
                    }));
            }
            Err(error) => {
                // Errors are only logged for what we consider an internal discard reason. These
                // indicate errors in the infrastructure or implementation bugs.
                relay_log::error!(
                    error = &error as &dyn Error,
                    tags.project_key = %envelope.scoping().project_key,
                    "failed to serialize envelope payload"
                );

                envelope.reject(Outcome::Invalid(DiscardReason::Internal));
            }
        }
    }

    fn handle_submit_client_reports(&self, message: SubmitClientReports) {
        let SubmitClientReports {
            client_reports,
            scoping,
        } = message;

        let upstream = self.inner.config.upstream_descriptor();
        let dsn = PartialDsn::outbound(&scoping, upstream);

        let mut envelope = Envelope::from_request(None, RequestMeta::outbound(dsn));
        for client_report in client_reports {
            let mut item = Item::new(ItemType::ClientReport);
            item.set_payload(ContentType::Json, client_report.serialize().unwrap()); // TODO: unwrap OK?
            envelope.add_item(item);
        }

        let envelope = ManagedEnvelope::new(
            envelope,
            self.inner.addrs.outcome_aggregator.clone(),
            self.inner.addrs.test_store.clone(),
            ProcessingGroup::ClientReport,
        );
        self.handle_submit_envelope(SubmitEnvelope {
            envelope: envelope.into_processed(),
        });
    }

    fn check_buckets(
        &self,
        project_key: ProjectKey,
        project_info: &ProjectInfo,
        rate_limits: &RateLimits,
        buckets: Vec<Bucket>,
    ) -> Vec<Bucket> {
        let Some(scoping) = project_info.scoping(project_key) else {
            relay_log::error!(
                tags.project_key = project_key.as_str(),
                "there is no scoping: dropping {} buckets",
                buckets.len(),
            );
            return Vec::new();
        };

        let mut buckets = self::metrics::apply_project_info(
            buckets,
            &self.inner.metric_outcomes,
            project_info,
            scoping,
        );

        let namespaces: BTreeSet<MetricNamespace> = buckets
            .iter()
            .filter_map(|bucket| bucket.name.try_namespace())
            .collect();

        for namespace in namespaces {
            let limits = rate_limits.check_with_quotas(
                project_info.get_quotas(),
                scoping.item(DataCategory::MetricBucket),
            );

            if limits.is_limited() {
                let rejected;
                (buckets, rejected) = utils::split_off(buckets, |bucket| {
                    bucket.name.try_namespace() == Some(namespace)
                });

                let reason_code = limits.longest().and_then(|limit| limit.reason_code.clone());
                self.inner.metric_outcomes.track(
                    scoping,
                    &rejected,
                    Outcome::RateLimited(reason_code),
                );
            }
        }

        let quotas = project_info.config.quotas.clone();
        match MetricsLimiter::create(buckets, quotas, scoping) {
            Ok(mut bucket_limiter) => {
                bucket_limiter.enforce_limits(rate_limits, &self.inner.metric_outcomes);
                bucket_limiter.into_buckets()
            }
            Err(buckets) => buckets,
        }
    }

    #[cfg(feature = "processing")]
    fn rate_limit_buckets(
        &self,
        scoping: Scoping,
        project_info: &ProjectInfo,
        mut buckets: Vec<Bucket>,
    ) -> Vec<Bucket> {
        let Some(rate_limiter) = self.inner.rate_limiter.as_ref() else {
            return buckets;
        };

        let global_config = self.inner.global_config.current();
        let namespaces = buckets
            .iter()
            .filter_map(|bucket| bucket.name.try_namespace())
            .counts();

        let quotas = CombinedQuotas::new(&global_config, project_info.get_quotas());

        for (namespace, quantity) in namespaces {
            let item_scoping = scoping.metric_bucket(namespace);

            let limits = match rate_limiter.is_rate_limited(quotas, item_scoping, quantity, false) {
                Ok(limits) => limits,
                Err(err) => {
                    relay_log::error!(
                        error = &err as &dyn std::error::Error,
                        "failed to check redis rate limits"
                    );
                    break;
                }
            };

            if limits.is_limited() {
                let rejected;
                (buckets, rejected) = utils::split_off(buckets, |bucket| {
                    bucket.name.try_namespace() == Some(namespace)
                });

                let reason_code = limits.longest().and_then(|limit| limit.reason_code.clone());
                self.inner.metric_outcomes.track(
                    scoping,
                    &rejected,
                    Outcome::RateLimited(reason_code),
                );

                self.inner
                    .project_cache
                    .get(item_scoping.scoping.project_key)
                    .rate_limits()
                    .merge(limits);
            }
        }

        match MetricsLimiter::create(buckets, project_info.config.quotas.clone(), scoping) {
            Err(buckets) => buckets,
            Ok(bucket_limiter) => self.apply_other_rate_limits(bucket_limiter),
        }
    }

    /// Check and apply rate limits to metrics buckets for transactions and spans.
    #[cfg(feature = "processing")]
    fn apply_other_rate_limits(&self, mut bucket_limiter: MetricsLimiter) -> Vec<Bucket> {
        relay_log::trace!("handle_rate_limit_buckets");

        let scoping = *bucket_limiter.scoping();

        if let Some(rate_limiter) = self.inner.rate_limiter.as_ref() {
            let global_config = self.inner.global_config.current();
            let quotas = CombinedQuotas::new(&global_config, bucket_limiter.quotas());

            // We set over_accept_once such that the limit is actually reached, which allows subsequent
            // calls with quantity=0 to be rate limited.
            let over_accept_once = true;
            let mut rate_limits = RateLimits::new();

            for category in [DataCategory::Transaction, DataCategory::Span] {
                let count = bucket_limiter.count(category);

                let timer = Instant::now();
                let mut is_limited = false;

                if let Some(count) = count {
                    match rate_limiter.is_rate_limited(
                        quotas,
                        scoping.item(category),
                        count,
                        over_accept_once,
                    ) {
                        Ok(limits) => {
                            is_limited = limits.is_limited();
                            rate_limits.merge(limits)
                        }
                        Err(e) => relay_log::error!(error = &e as &dyn Error),
                    }
                }

                relay_statsd::metric!(
                    timer(RelayTimers::RateLimitBucketsDuration) = timer.elapsed(),
                    category = category.name(),
                    limited = if is_limited { "true" } else { "false" },
                    count = match count {
                        None => "none",
                        Some(0) => "0",
                        Some(1) => "1",
                        Some(1..=10) => "10",
                        Some(1..=25) => "25",
                        Some(1..=50) => "50",
                        Some(51..=100) => "100",
                        Some(101..=500) => "500",
                        _ => "> 500",
                    },
                );
            }

            if rate_limits.is_limited() {
                let was_enforced =
                    bucket_limiter.enforce_limits(&rate_limits, &self.inner.metric_outcomes);

                if was_enforced {
                    // Update the rate limits in the project cache.
                    self.inner
                        .project_cache
                        .get(scoping.project_key)
                        .rate_limits()
                        .merge(rate_limits);
                }
            }
        }

        bucket_limiter.into_buckets()
    }

    /// Cardinality limits the passed buckets and returns a filtered vector of only accepted buckets.
    #[cfg(feature = "processing")]
    fn cardinality_limit_buckets(
        &self,
        scoping: Scoping,
        limits: &[CardinalityLimit],
        buckets: Vec<Bucket>,
    ) -> Vec<Bucket> {
        let global_config = self.inner.global_config.current();
        let cardinality_limiter_mode = global_config.options.cardinality_limiter_mode;

        if matches!(cardinality_limiter_mode, CardinalityLimiterMode::Disabled) {
            return buckets;
        }

        let Some(ref limiter) = self.inner.cardinality_limiter else {
            return buckets;
        };

        let scope = relay_cardinality::Scoping {
            organization_id: scoping.organization_id,
            project_id: scoping.project_id,
        };

        let limits = match limiter.check_cardinality_limits(scope, limits, buckets) {
            Ok(limits) => limits,
            Err((buckets, error)) => {
                relay_log::error!(
                    error = &error as &dyn std::error::Error,
                    "cardinality limiter failed"
                );
                return buckets;
            }
        };

        let error_sample_rate = global_config.options.cardinality_limiter_error_sample_rate;
        if !limits.exceeded_limits().is_empty() && utils::sample(error_sample_rate) {
            for limit in limits.exceeded_limits() {
                relay_log::with_scope(
                    |scope| {
                        // Set the organization as user so we can alert on distinct org_ids.
                        scope.set_user(Some(relay_log::sentry::User {
                            id: Some(scoping.organization_id.to_string()),
                            ..Default::default()
                        }));
                    },
                    || {
                        relay_log::error!(
                            tags.organization_id = scoping.organization_id.value(),
                            tags.limit_id = limit.id,
                            tags.passive = limit.passive,
                            "Cardinality Limit"
                        );
                    },
                );
            }
        }

        for (limit, reports) in limits.cardinality_reports() {
            for report in reports {
                self.inner
                    .metric_outcomes
                    .cardinality(scoping, limit, report);
            }
        }

        if matches!(cardinality_limiter_mode, CardinalityLimiterMode::Passive) {
            return limits.into_source();
        }

        let CardinalityLimitsSplit { accepted, rejected } = limits.into_split();

        for (bucket, exceeded) in rejected {
            self.inner.metric_outcomes.track(
                scoping,
                &[bucket],
                Outcome::CardinalityLimited(exceeded.id.clone()),
            );
        }
        accepted
    }

    /// Processes metric buckets and sends them to kafka.
    ///
    /// This function runs the following steps:
    ///  - cardinality limiting
    ///  - rate limiting
    ///  - submit to `StoreForwarder`
    #[cfg(feature = "processing")]
    fn encode_metrics_processing(&self, message: FlushBuckets, store_forwarder: &Addr<Store>) {
        use crate::constants::DEFAULT_EVENT_RETENTION;
        use crate::services::store::StoreMetrics;

        for ProjectBuckets {
            buckets,
            scoping,
            project_info,
            ..
        } in message.buckets.into_values()
        {
            let buckets = self.rate_limit_buckets(scoping, &project_info, buckets);

            let limits = project_info.get_cardinality_limits();
            let buckets = self.cardinality_limit_buckets(scoping, limits, buckets);

            if buckets.is_empty() {
                continue;
            }

            let retention = project_info
                .config
                .event_retention
                .unwrap_or(DEFAULT_EVENT_RETENTION);

            // The store forwarder takes care of bucket splitting internally, so we can submit the
            // entire list of buckets. There is no batching needed here.
            store_forwarder.send(StoreMetrics {
                buckets,
                scoping,
                retention,
            });
        }
    }

    /// Serializes metric buckets to JSON and sends them to the upstream.
    ///
    /// This function runs the following steps:
    ///  - partitioning
    ///  - batching by configured size limit
    ///  - serialize to JSON and pack in an envelope
    ///  - submit the envelope to upstream or kafka depending on configuration
    ///
    /// Cardinality limiting and rate limiting run only in processing Relays as they both require
    /// access to the central Redis instance. Cached rate limits are applied in the project cache
    /// already.
    fn encode_metrics_envelope(&self, message: FlushBuckets) {
        let FlushBuckets {
            partition_key,
            buckets,
        } = message;

        let batch_size = self.inner.config.metrics_max_batch_size_bytes();
        let upstream = self.inner.config.upstream_descriptor();

        for ProjectBuckets {
            buckets, scoping, ..
        } in buckets.values()
        {
            let dsn = PartialDsn::outbound(scoping, upstream);

            relay_statsd::metric!(
                histogram(RelayHistograms::PartitionKeys) = u64::from(partition_key)
            );

            let mut num_batches = 0;
            for batch in BucketsView::from(buckets).by_size(batch_size) {
                let mut envelope = Envelope::from_request(None, RequestMeta::outbound(dsn.clone()));

                let mut item = Item::new(ItemType::MetricBuckets);
                item.set_source_quantities(crate::metrics::extract_quantities(batch));
                item.set_payload(ContentType::Json, serde_json::to_vec(&buckets).unwrap());
                envelope.add_item(item);

                let mut envelope = ManagedEnvelope::new(
                    envelope,
                    self.inner.addrs.outcome_aggregator.clone(),
                    self.inner.addrs.test_store.clone(),
                    ProcessingGroup::Metrics,
                );
                envelope
                    .set_partition_key(Some(partition_key))
                    .scope(*scoping);

                relay_statsd::metric!(
                    histogram(RelayHistograms::BucketsPerBatch) = batch.len() as u64
                );

                self.handle_submit_envelope(SubmitEnvelope {
                    envelope: envelope.into_processed(),
                });
                num_batches += 1;
            }

            relay_statsd::metric!(histogram(RelayHistograms::BatchesPerPartition) = num_batches);
        }
    }

    /// Creates a [`SendMetricsRequest`] and sends it to the upstream relay.
    fn send_global_partition(&self, partition_key: u32, partition: &mut Partition<'_>) {
        if partition.is_empty() {
            return;
        }

        let (unencoded, project_info) = partition.take();
        let http_encoding = self.inner.config.http_encoding();
        let encoded = match encode_payload(&unencoded, http_encoding) {
            Ok(payload) => payload,
            Err(error) => {
                let error = &error as &dyn std::error::Error;
                relay_log::error!(error, "failed to encode metrics payload");
                return;
            }
        };

        let request = SendMetricsRequest {
            partition_key: partition_key.to_string(),
            unencoded,
            encoded,
            project_info,
            http_encoding,
            metric_outcomes: self.inner.metric_outcomes.clone(),
        };

        self.inner.addrs.upstream_relay.send(SendRequest(request));
    }

    /// Serializes metric buckets to JSON and sends them to the upstream via the global endpoint.
    ///
    /// This function is similar to [`Self::encode_metrics_envelope`], but sends a global batched
    /// payload directly instead of per-project Envelopes.
    ///
    /// This function runs the following steps:
    ///  - partitioning
    ///  - batching by configured size limit
    ///  - serialize to JSON
    ///  - submit directly to the upstream
    ///
    /// Cardinality limiting and rate limiting run only in processing Relays as they both require
    /// access to the central Redis instance. Cached rate limits are applied in the project cache
    /// already.
    fn encode_metrics_global(&self, message: FlushBuckets) {
        let FlushBuckets {
            partition_key,
            buckets,
        } = message;

        let batch_size = self.inner.config.metrics_max_batch_size_bytes();
        let mut partition = Partition::new(batch_size);
        let mut partition_splits = 0;

        for ProjectBuckets {
            buckets, scoping, ..
        } in buckets.values()
        {
            for bucket in buckets {
                let mut remaining = Some(BucketView::new(bucket));

                while let Some(bucket) = remaining.take() {
                    if let Some(next) = partition.insert(bucket, *scoping) {
                        // A part of the bucket could not be inserted. Take the partition and submit
                        // it immediately. Repeat until the final part was inserted. This should
                        // always result in a request, otherwise we would enter an endless loop.
                        self.send_global_partition(partition_key, &mut partition);
                        remaining = Some(next);
                        partition_splits += 1;
                    }
                }
            }
        }

        if partition_splits > 0 {
            metric!(histogram(RelayHistograms::PartitionSplits) = partition_splits);
        }

        self.send_global_partition(partition_key, &mut partition);
    }

    fn handle_flush_buckets(&self, mut message: FlushBuckets) {
        for (project_key, pb) in message.buckets.iter_mut() {
            let buckets = std::mem::take(&mut pb.buckets);
            pb.buckets =
                self.check_buckets(*project_key, &pb.project_info, &pb.rate_limits, buckets);
        }

        #[cfg(feature = "processing")]
        if self.inner.config.processing_enabled() {
            if let Some(ref store_forwarder) = self.inner.addrs.store_forwarder {
                return self.encode_metrics_processing(message, store_forwarder);
            }
        }

        if self.inner.config.http_global_metrics() {
            self.encode_metrics_global(message)
        } else {
            self.encode_metrics_envelope(message)
        }
    }

    #[cfg(all(test, feature = "processing"))]
    fn redis_rate_limiter_enabled(&self) -> bool {
        self.inner.rate_limiter.is_some()
    }

    fn handle_message(&self, message: EnvelopeProcessor) {
        let ty = message.variant();
        let feature_weights = self.feature_weights(&message);

        metric!(timer(RelayTimers::ProcessMessageDuration), message = ty, {
            let mut cogs = self.inner.cogs.timed(ResourceId::Relay, feature_weights);

            match message {
                EnvelopeProcessor::ProcessEnvelope(m) => self.handle_process_envelope(*m),
                EnvelopeProcessor::ProcessProjectMetrics(m) => {
                    self.handle_process_metrics(&mut cogs, *m)
                }
                EnvelopeProcessor::ProcessBatchedMetrics(m) => {
                    self.handle_process_batched_metrics(&mut cogs, *m)
                }
                EnvelopeProcessor::FlushBuckets(m) => self.handle_flush_buckets(*m),
                EnvelopeProcessor::SubmitEnvelope(m) => self.handle_submit_envelope(*m),
                EnvelopeProcessor::SubmitClientReports(m) => self.handle_submit_client_reports(*m),
            }
        });
    }

    fn feature_weights(&self, message: &EnvelopeProcessor) -> FeatureWeights {
        match message {
            EnvelopeProcessor::ProcessEnvelope(v) => AppFeature::from(v.envelope.group()).into(),
            EnvelopeProcessor::ProcessProjectMetrics(_) => AppFeature::Unattributed.into(),
            EnvelopeProcessor::ProcessBatchedMetrics(_) => AppFeature::Unattributed.into(),
            EnvelopeProcessor::FlushBuckets(v) => v
                .buckets
                .values()
                .map(|s| {
                    if self.inner.config.processing_enabled() {
                        // Processing does not encode the metrics but instead rate and cardinality
                        // limits the metrics, which scales by count and not size.
                        relay_metrics::cogs::ByCount(&s.buckets).into()
                    } else {
                        relay_metrics::cogs::BySize(&s.buckets).into()
                    }
                })
                .fold(FeatureWeights::none(), FeatureWeights::merge),
            EnvelopeProcessor::SubmitEnvelope(v) => AppFeature::from(v.envelope.group()).into(),
            EnvelopeProcessor::SubmitClientReports(_) => AppFeature::ClientReports.into(),
        }
    }

    fn new_reservoir_evaluator(
        &self,
        #[allow(unused_variables)] organization_id: OrganizationId,
        reservoir_counters: ReservoirCounters,
    ) -> ReservoirEvaluator {
        #[allow(unused_mut)]
        let mut reservoir = ReservoirEvaluator::new(reservoir_counters);
        #[cfg(feature = "processing")]
        if let Some(quotas_pool) = self.inner.quotas_pool.as_ref() {
            reservoir.set_redis(organization_id, quotas_pool);
        }

        reservoir
    }
}

impl Service for EnvelopeProcessorService {
    type Interface = EnvelopeProcessor;

    async fn run(self, mut rx: relay_system::Receiver<Self::Interface>) {
        while let Some(message) = rx.recv().await {
            let service = self.clone();
            self.inner
                .workers
                .spawn(move || service.handle_message(message))
                .await;
        }
    }
}

/// Result of the enforcement of rate limiting.
///
/// If the event is already `None` or it's rate limited, it will be `None`
/// within the [`Annotated`].
#[cfg(feature = "processing")]
struct EnforcementResult {
    event: Annotated<Event>,
    rate_limits: RateLimits,
}

#[cfg(feature = "processing")]
impl EnforcementResult {
    /// Creates a new [`EnforcementResult`].
    pub fn new(event: Annotated<Event>, rate_limits: RateLimits) -> Self {
        Self { event, rate_limits }
    }
}

#[cfg(feature = "processing")]
enum RateLimiter<'a> {
    Cached,
    Consistent(&'a RedisRateLimiter),
}

#[cfg(feature = "processing")]
impl RateLimiter<'_> {
    fn enforce<Group>(
        &self,
        managed_envelope: &mut TypedEnvelope<Group>,
        event: Annotated<Event>,
        extracted_metrics: &mut ProcessingExtractedMetrics,
        global_config: &GlobalConfig,
        project_info: Arc<ProjectInfo>,
        rate_limits: Arc<RateLimits>,
    ) -> Result<EnforcementResult, ProcessingError> {
        if managed_envelope.envelope().is_empty() && event.value().is_none() {
            return Ok(EnforcementResult::new(event, RateLimits::default()));
        }

        let quotas = CombinedQuotas::new(global_config, project_info.get_quotas());
        if quotas.is_empty() {
            return Ok(EnforcementResult::new(event, RateLimits::default()));
        }

        let event_category = event_category(&event);

        // When invoking the rate limiter, capture if the event item has been rate limited to also
        // remove it from the processing state eventually.
        let mut envelope_limiter =
            EnvelopeLimiter::new(CheckLimits::All, |item_scope, quantity| match self {
                RateLimiter::Cached => Ok(rate_limits.check_with_quotas(quotas, item_scope)),
                RateLimiter::Consistent(rl) => Ok::<_, ProcessingError>(
                    rl.is_rate_limited(quotas, item_scope, quantity, false)?,
                ),
            });

        // Tell the envelope limiter about the event, since it has been removed from the Envelope at
        // this stage in processing.
        if let Some(category) = event_category {
            envelope_limiter.assume_event(category);
        }

        let scoping = managed_envelope.scoping();
        let (enforcement, rate_limits) =
            metric!(timer(RelayTimers::EventProcessingRateLimiting), {
                envelope_limiter.compute(managed_envelope.envelope_mut(), &scoping)?
            });
        let event_active = enforcement.is_event_active();

        // Use the same rate limits as used for the envelope on the metrics.
        // Those rate limits should not be checked for expiry or similar to ensure a consistent
        // limiting of envelope items and metrics.
        extracted_metrics.apply_enforcement(&enforcement, matches!(self, Self::Consistent(_)));
        enforcement.apply_with_outcomes(managed_envelope);

        if event_active {
            debug_assert!(managed_envelope.envelope().is_empty());
            return Ok(EnforcementResult::new(Annotated::empty(), rate_limits));
        }

        Ok(EnforcementResult::new(event, rate_limits))
    }
}

fn encode_payload(body: &Bytes, http_encoding: HttpEncoding) -> Result<Bytes, std::io::Error> {
    let envelope_body: Vec<u8> = match http_encoding {
        HttpEncoding::Identity => return Ok(body.clone()),
        HttpEncoding::Deflate => {
            let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
            encoder.write_all(body.as_ref())?;
            encoder.finish()?
        }
        HttpEncoding::Gzip => {
            let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
            encoder.write_all(body.as_ref())?;
            encoder.finish()?
        }
        HttpEncoding::Br => {
            // Use default buffer size (via 0), medium quality (5), and the default lgwin (22).
            let mut encoder = BrotliEncoder::new(Vec::new(), 0, 5, 22);
            encoder.write_all(body.as_ref())?;
            encoder.into_inner()
        }
        HttpEncoding::Zstd => {
            // Use the fastest compression level, our main objective here is to get the best
            // compression ratio for least amount of time spent.
            let mut encoder = ZstdEncoder::new(Vec::new(), 1)?;
            encoder.write_all(body.as_ref())?;
            encoder.finish()?
        }
    };

    Ok(envelope_body.into())
}

/// An upstream request that submits an envelope via HTTP.
#[derive(Debug)]
pub struct SendEnvelope {
    envelope: TypedEnvelope<Processed>,
    body: Bytes,
    http_encoding: HttpEncoding,
    project_cache: ProjectCacheHandle,
}

impl UpstreamRequest for SendEnvelope {
    fn method(&self) -> reqwest::Method {
        reqwest::Method::POST
    }

    fn path(&self) -> Cow<'_, str> {
        format!("/api/{}/envelope/", self.envelope.scoping().project_id).into()
    }

    fn route(&self) -> &'static str {
        "envelope"
    }

    fn build(&mut self, builder: &mut http::RequestBuilder) -> Result<(), http::HttpError> {
        let envelope_body = self.body.clone();
        metric!(histogram(RelayHistograms::UpstreamEnvelopeBodySize) = envelope_body.len() as u64);

        let meta = &self.envelope.meta();
        let shard = self.envelope.partition_key().map(|p| p.to_string());
        builder
            .content_encoding(self.http_encoding)
            .header_opt("Origin", meta.origin().map(|url| url.as_str()))
            .header_opt("User-Agent", meta.user_agent())
            .header("X-Sentry-Auth", meta.auth_header())
            .header("X-Forwarded-For", meta.forwarded_for())
            .header("Content-Type", envelope::CONTENT_TYPE)
            .header_opt("X-Sentry-Relay-Shard", shard)
            .body(envelope_body);

        Ok(())
    }

    fn respond(
        self: Box<Self>,
        result: Result<http::Response, UpstreamRequestError>,
    ) -> Pin<Box<dyn Future<Output = ()> + Send + Sync>> {
        Box::pin(async move {
            let result = match result {
                Ok(mut response) => response.consume().await.map_err(UpstreamRequestError::Http),
                Err(error) => Err(error),
            };

            match result {
                Ok(()) => self.envelope.accept(),
                Err(error) if error.is_received() => {
                    let scoping = self.envelope.scoping();
                    self.envelope.accept();

                    if let UpstreamRequestError::RateLimited(limits) = error {
                        self.project_cache
                            .get(scoping.project_key)
                            .rate_limits()
                            .merge(limits.scope(&scoping));
                    }
                }
                Err(error) => {
                    // Errors are only logged for what we consider an internal discard reason. These
                    // indicate errors in the infrastructure or implementation bugs.
                    let mut envelope = self.envelope;
                    envelope.reject(Outcome::Invalid(DiscardReason::Internal));
                    relay_log::error!(
                        error = &error as &dyn Error,
                        tags.project_key = %envelope.scoping().project_key,
                        "error sending envelope"
                    );
                }
            }
        })
    }
}

/// A container for metric buckets from multiple projects.
///
/// This container is used to send metrics to the upstream in global batches as part of the
/// [`FlushBuckets`] message if the `http.global_metrics` option is enabled. The container monitors
/// the size of all metrics and allows to split them into multiple batches. See
/// [`insert`](Self::insert) for more information.
#[derive(Debug)]
struct Partition<'a> {
    max_size: usize,
    remaining: usize,
    views: HashMap<ProjectKey, Vec<BucketView<'a>>>,
    project_info: HashMap<ProjectKey, Scoping>,
}

impl<'a> Partition<'a> {
    /// Creates a new partition with the given maximum size in bytes.
    pub fn new(size: usize) -> Self {
        Self {
            max_size: size,
            remaining: size,
            views: HashMap::new(),
            project_info: HashMap::new(),
        }
    }

    /// Inserts a bucket into the partition, splitting it if necessary.
    ///
    /// This function attempts to add the bucket to this partition. If the bucket does not fit
    /// entirely into the partition given its maximum size, the remaining part of the bucket is
    /// returned from this function call.
    ///
    /// If this function returns `Some(_)`, the partition is full and should be submitted to the
    /// upstream immediately. Use [`Self::take`] to retrieve the contents of the
    /// partition. Afterwards, the caller is responsible to call this function again with the
    /// remaining bucket until it is fully inserted.
    pub fn insert(&mut self, bucket: BucketView<'a>, scoping: Scoping) -> Option<BucketView<'a>> {
        let (current, next) = bucket.split(self.remaining, Some(self.max_size));

        if let Some(current) = current {
            self.remaining = self.remaining.saturating_sub(current.estimated_size());
            self.views
                .entry(scoping.project_key)
                .or_default()
                .push(current);

            self.project_info
                .entry(scoping.project_key)
                .or_insert(scoping);
        }

        next
    }

    /// Returns `true` if the partition does not hold any data.
    fn is_empty(&self) -> bool {
        self.views.is_empty()
    }

    /// Returns the serialized buckets for this partition.
    ///
    /// This empties the partition, so that it can be reused.
    fn take(&mut self) -> (Bytes, HashMap<ProjectKey, Scoping>) {
        #[derive(serde::Serialize)]
        struct Wrapper<'a> {
            buckets: &'a HashMap<ProjectKey, Vec<BucketView<'a>>>,
        }

        let buckets = &self.views;
        let payload = serde_json::to_vec(&Wrapper { buckets }).unwrap().into();

        let scopings = self.project_info.clone();
        self.project_info.clear();

        self.views.clear();
        self.remaining = self.max_size;

        (payload, scopings)
    }
}

/// An upstream request that submits metric buckets via HTTP.
///
/// This request is not awaited. It automatically tracks outcomes if the request is not received.
#[derive(Debug)]
struct SendMetricsRequest {
    /// If the partition key is set, the request is marked with `X-Sentry-Relay-Shard`.
    partition_key: String,
    /// Serialized metric buckets without encoding applied, used for signing.
    unencoded: Bytes,
    /// Serialized metric buckets with the stated HTTP encoding applied.
    encoded: Bytes,
    /// Mapping of all contained project keys to their scoping and extraction mode.
    ///
    /// Used to track outcomes for transmission failures.
    project_info: HashMap<ProjectKey, Scoping>,
    /// Encoding (compression) of the payload.
    http_encoding: HttpEncoding,
    /// Metric outcomes instance to send outcomes on error.
    metric_outcomes: MetricOutcomes,
}

impl SendMetricsRequest {
    fn create_error_outcomes(self) {
        #[derive(serde::Deserialize)]
        struct Wrapper {
            buckets: HashMap<ProjectKey, Vec<MinimalTrackableBucket>>,
        }

        let buckets = match serde_json::from_slice(&self.unencoded) {
            Ok(Wrapper { buckets }) => buckets,
            Err(err) => {
                relay_log::error!(
                    error = &err as &dyn std::error::Error,
                    "failed to parse buckets from failed transmission"
                );
                return;
            }
        };

        for (key, buckets) in buckets {
            let Some(&scoping) = self.project_info.get(&key) else {
                relay_log::error!("missing scoping for project key");
                continue;
            };

            self.metric_outcomes.track(
                scoping,
                &buckets,
                Outcome::Invalid(DiscardReason::Internal),
            );
        }
    }
}

impl UpstreamRequest for SendMetricsRequest {
    fn set_relay_id(&self) -> bool {
        true
    }

    fn sign(&mut self) -> Option<Bytes> {
        Some(self.unencoded.clone())
    }

    fn method(&self) -> reqwest::Method {
        reqwest::Method::POST
    }

    fn path(&self) -> Cow<'_, str> {
        "/api/0/relays/metrics/".into()
    }

    fn route(&self) -> &'static str {
        "global_metrics"
    }

    fn build(&mut self, builder: &mut http::RequestBuilder) -> Result<(), http::HttpError> {
        metric!(histogram(RelayHistograms::UpstreamMetricsBodySize) = self.encoded.len() as u64);

        builder
            .content_encoding(self.http_encoding)
            .header("X-Sentry-Relay-Shard", self.partition_key.as_bytes())
            .header(header::CONTENT_TYPE, b"application/json")
            .body(self.encoded.clone());

        Ok(())
    }

    fn respond(
        self: Box<Self>,
        result: Result<http::Response, UpstreamRequestError>,
    ) -> Pin<Box<dyn Future<Output = ()> + Send + Sync>> {
        Box::pin(async {
            match result {
                Ok(mut response) => {
                    response.consume().await.ok();
                }
                Err(error) => {
                    relay_log::error!(error = &error as &dyn Error, "Failed to send metrics batch");

                    // If the request did not arrive at the upstream, we are responsible for outcomes.
                    // Otherwise, the upstream is responsible to log outcomes.
                    if error.is_received() {
                        return;
                    }

                    self.create_error_outcomes()
                }
            }
        })
    }
}

/// Container for global and project level [`Quota`].
#[cfg(feature = "processing")]
#[derive(Copy, Clone)]
struct CombinedQuotas<'a> {
    global_quotas: &'a [Quota],
    project_quotas: &'a [Quota],
}

#[cfg(feature = "processing")]
impl<'a> CombinedQuotas<'a> {
    /// Returns a new [`CombinedQuotas`].
    pub fn new(global_config: &'a GlobalConfig, project_quotas: &'a [Quota]) -> Self {
        Self {
            global_quotas: &global_config.quotas,
            project_quotas,
        }
    }

    /// Returns `true` if both global quotas and project quotas are empty.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns the number of both global and project quotas.
    pub fn len(&self) -> usize {
        self.global_quotas.len() + self.project_quotas.len()
    }
}

#[cfg(feature = "processing")]
impl<'a> IntoIterator for CombinedQuotas<'a> {
    type Item = &'a Quota;
    type IntoIter = Chain<Iter<'a, Quota>, Iter<'a, Quota>>;

    fn into_iter(self) -> Self::IntoIter {
        self.global_quotas.iter().chain(self.project_quotas.iter())
    }
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;
    use std::env;

    use insta::assert_debug_snapshot;
    use relay_base_schema::metrics::{DurationUnit, MetricUnit};
    use relay_common::glob2::LazyGlob;
    use relay_dynamic_config::ProjectConfig;
    use relay_event_normalization::{RedactionRule, TransactionNameRule};
    use relay_event_schema::protocol::TransactionSource;
    use relay_pii::DataScrubbingConfig;
    use similar_asserts::assert_eq;

    use crate::metrics_extraction::transactions::types::{
        CommonTags, TransactionMeasurementTags, TransactionMetric,
    };
    use crate::metrics_extraction::IntoMetric;
    use crate::testutils::{self, create_test_processor, create_test_processor_with_addrs};

    #[cfg(feature = "processing")]
    use {
        relay_metrics::BucketValue,
        relay_quotas::{QuotaScope, ReasonCode},
        relay_test::mock_service,
    };

    use super::*;

    #[cfg(feature = "processing")]
    fn mock_quota(id: &str) -> Quota {
        Quota {
            id: Some(id.into()),
            categories: smallvec::smallvec![DataCategory::MetricBucket],
            scope: QuotaScope::Organization,
            scope_id: None,
            limit: Some(0),
            window: None,
            reason_code: None,
            namespace: None,
        }
    }

    #[cfg(feature = "processing")]
    #[test]
    fn test_dynamic_quotas() {
        let global_config = GlobalConfig {
            quotas: vec![mock_quota("foo"), mock_quota("bar")],
            ..Default::default()
        };

        let project_quotas = vec![mock_quota("baz"), mock_quota("qux")];

        let dynamic_quotas = CombinedQuotas::new(&global_config, &project_quotas);

        assert_eq!(dynamic_quotas.len(), 4);
        assert!(!dynamic_quotas.is_empty());

        let quota_ids = dynamic_quotas.into_iter().filter_map(|q| q.id.as_deref());
        assert!(quota_ids.eq(["foo", "bar", "baz", "qux"]));
    }

    /// Ensures that if we ratelimit one batch of buckets in [`FlushBuckets`] message, it won't
    /// also ratelimit the next batches in the same message automatically.
    #[cfg(feature = "processing")]
    #[tokio::test]
    async fn test_ratelimit_per_batch() {
        use relay_base_schema::organization::OrganizationId;

        let rate_limited_org = Scoping {
            organization_id: OrganizationId::new(1),
            project_id: ProjectId::new(21),
            project_key: ProjectKey::parse("00000000000000000000000000000000").unwrap(),
            key_id: Some(17),
        };

        let not_rate_limited_org = Scoping {
            organization_id: OrganizationId::new(2),
            project_id: ProjectId::new(21),
            project_key: ProjectKey::parse("11111111111111111111111111111111").unwrap(),
            key_id: Some(17),
        };

        let message = {
            let project_info = {
                let quota = Quota {
                    id: Some("testing".into()),
                    categories: vec![DataCategory::MetricBucket].into(),
                    scope: relay_quotas::QuotaScope::Organization,
                    scope_id: Some(rate_limited_org.organization_id.to_string()),
                    limit: Some(0),
                    window: None,
                    reason_code: Some(ReasonCode::new("test")),
                    namespace: None,
                };

                let mut config = ProjectConfig::default();
                config.quotas.push(quota);

                Arc::new(ProjectInfo {
                    config,
                    ..Default::default()
                })
            };

            let project_metrics = |scoping| ProjectBuckets {
                buckets: vec![Bucket {
                    name: "d:transactions/bar".into(),
                    value: BucketValue::Counter(relay_metrics::FiniteF64::new(1.0).unwrap()),
                    timestamp: UnixTimestamp::now(),
                    tags: Default::default(),
                    width: 10,
                    metadata: BucketMetadata::default(),
                }],
                rate_limits: Default::default(),
                project_info: project_info.clone(),
                scoping,
            };

            let buckets = hashbrown::HashMap::from([
                (
                    rate_limited_org.project_key,
                    project_metrics(rate_limited_org),
                ),
                (
                    not_rate_limited_org.project_key,
                    project_metrics(not_rate_limited_org),
                ),
            ]);

            FlushBuckets {
                partition_key: 0,
                buckets,
            }
        };

        // ensure the order of the map while iterating is as expected.
        assert_eq!(message.buckets.keys().count(), 2);

        let config = {
            let config_json = serde_json::json!({
                "processing": {
                    "enabled": true,
                    "kafka_config": [],
                    "redis": {
                        "server": std::env::var("RELAY_REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379".to_owned()),
                    }
                }
            });
            Config::from_json_value(config_json).unwrap()
        };

        let (store, handle) = {
            let f = |org_ids: &mut Vec<OrganizationId>, msg: Store| {
                let org_id = match msg {
                    Store::Metrics(x) => x.scoping.organization_id,
                    _ => panic!("received envelope when expecting only metrics"),
                };
                org_ids.push(org_id);
            };

            mock_service("store_forwarder", vec![], f)
        };

        let processor = create_test_processor(config).await;
        assert!(processor.redis_rate_limiter_enabled());

        processor.encode_metrics_processing(message, &store);

        drop(store);
        let orgs_not_ratelimited = handle.await.unwrap();

        assert_eq!(
            orgs_not_ratelimited,
            vec![not_rate_limited_org.organization_id]
        );
    }

    #[tokio::test]
    async fn test_browser_version_extraction_with_pii_like_data() {
        let processor = create_test_processor(Default::default()).await;
        let (outcome_aggregator, test_store) = testutils::processor_services();
        let event_id = EventId::new();

        let dsn = "https://e12d836b15bb49d7bbf99e64295d995b:@sentry.io/42"
            .parse()
            .unwrap();

        let request_meta = RequestMeta::new(dsn);
        let mut envelope = Envelope::from_request(Some(event_id), request_meta);

        envelope.add_item({
                let mut item = Item::new(ItemType::Event);
                item.set_payload(
                    ContentType::Json,
                    r#"
                    {
                        "request": {
                            "headers": [
                                ["User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36"]
                            ]
                        }
                    }
                "#,
                );
                item
            });

        let mut datascrubbing_settings = DataScrubbingConfig::default();
        // enable all the default scrubbing
        datascrubbing_settings.scrub_data = true;
        datascrubbing_settings.scrub_defaults = true;
        datascrubbing_settings.scrub_ip_addresses = true;

        // Make sure to mask any IP-like looking data
        let pii_config = serde_json::from_str(r#"{"applications": {"**": ["@ip:mask"]}}"#).unwrap();

        let config = ProjectConfig {
            datascrubbing_settings,
            pii_config: Some(pii_config),
            ..Default::default()
        };

        let project_info = ProjectInfo {
            config,
            ..Default::default()
        };

        let mut envelopes = ProcessingGroup::split_envelope(*envelope);
        assert_eq!(envelopes.len(), 1);

        let (group, envelope) = envelopes.pop().unwrap();
        let envelope = ManagedEnvelope::new(envelope, outcome_aggregator, test_store, group);

        let message = ProcessEnvelope {
            envelope,
            project_info: Arc::new(project_info),
            rate_limits: Default::default(),
            sampling_project_info: None,
            reservoir_counters: ReservoirCounters::default(),
        };

        let envelope_response = processor.process(message).unwrap();
        let new_envelope = envelope_response.envelope.unwrap();
        let new_envelope = new_envelope.envelope();

        let event_item = new_envelope.items().last().unwrap();
        let annotated_event: Annotated<Event> =
            Annotated::from_json_bytes(&event_item.payload()).unwrap();
        let event = annotated_event.into_value().unwrap();
        let headers = event
            .request
            .into_value()
            .unwrap()
            .headers
            .into_value()
            .unwrap();

        // IP-like data must be masked
        assert_eq!(Some("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/********* Safari/537.36"), headers.get_header("User-Agent"));
        // But we still get correct browser and version number
        let contexts = event.contexts.into_value().unwrap();
        let browser = contexts.0.get("browser").unwrap();
        assert_eq!(
            r#"{"browser":"Chrome 103.0.0","name":"Chrome","version":"103.0.0","type":"browser"}"#,
            browser.to_json().unwrap()
        );
    }

    #[tokio::test]
    #[cfg(feature = "processing")]
    async fn test_materialize_dsc() {
        let dsn = "https://e12d836b15bb49d7bbf99e64295d995b:@sentry.io/42"
            .parse()
            .unwrap();
        let request_meta = RequestMeta::new(dsn);
        let mut envelope = Envelope::from_request(None, request_meta);

        let dsc = r#"{
            "trace_id": "00000000-0000-0000-0000-000000000000",
            "public_key": "e12d836b15bb49d7bbf99e64295d995b",
            "sample_rate": "0.2"
        }"#;
        envelope.set_dsc(serde_json::from_str(dsc).unwrap());

        let mut item = Item::new(ItemType::Event);
        item.set_payload(ContentType::Json, r#"{}"#);
        envelope.add_item(item);

        let (outcome_aggregator, test_store) = testutils::processor_services();
        let managed_envelope = ManagedEnvelope::new(
            envelope,
            outcome_aggregator,
            test_store,
            ProcessingGroup::Error,
        );

        let process_message = ProcessEnvelope {
            envelope: managed_envelope,
            project_info: Arc::new(ProjectInfo::default()),
            rate_limits: Default::default(),
            sampling_project_info: None,
            reservoir_counters: ReservoirCounters::default(),
        };

        let config = Config::from_json_value(serde_json::json!({
            "processing": {
                "enabled": true,
                "kafka_config": [],
            }
        }))
        .unwrap();

        let processor = create_test_processor(config).await;
        let response = processor.process(process_message).unwrap();
        let envelope = response.envelope.as_ref().unwrap().envelope();
        let event = envelope
            .get_item_by(|item| item.ty() == &ItemType::Event)
            .unwrap();

        let event = Annotated::<Event>::from_json_bytes(&event.payload()).unwrap();
        insta::assert_debug_snapshot!(event.value().unwrap()._dsc, @r###"
        Object(
            {
                "environment": ~,
                "public_key": String(
                    "e12d836b15bb49d7bbf99e64295d995b",
                ),
                "release": ~,
                "replay_id": ~,
                "sample_rate": String(
                    "0.2",
                ),
                "trace_id": String(
                    "00000000-0000-0000-0000-000000000000",
                ),
                "transaction": ~,
            },
        )
        "###);
    }

    fn capture_test_event(transaction_name: &str, source: TransactionSource) -> Vec<String> {
        let mut event = Annotated::<Event>::from_json(
            r#"
            {
                "type": "transaction",
                "transaction": "/foo/",
                "timestamp": 946684810.0,
                "start_timestamp": 946684800.0,
                "contexts": {
                    "trace": {
                        "trace_id": "4c79f60c11214eb38604f4ae0781bfb2",
                        "span_id": "fa90fdead5f74053",
                        "op": "http.server",
                        "type": "trace"
                    }
                },
                "transaction_info": {
                    "source": "url"
                }
            }
            "#,
        )
        .unwrap();
        let e = event.value_mut().as_mut().unwrap();
        e.transaction.set_value(Some(transaction_name.into()));

        e.transaction_info
            .value_mut()
            .as_mut()
            .unwrap()
            .source
            .set_value(Some(source));

        relay_statsd::with_capturing_test_client(|| {
            utils::log_transaction_name_metrics(&mut event, |event| {
                let config = NormalizationConfig {
                    transaction_name_config: TransactionNameConfig {
                        rules: &[TransactionNameRule {
                            pattern: LazyGlob::new("/foo/*/**".to_owned()),
                            expiry: DateTime::<Utc>::MAX_UTC,
                            redaction: RedactionRule::Replace {
                                substitution: "*".to_owned(),
                            },
                        }],
                    },
                    ..Default::default()
                };
                normalize_event(event, &config)
            });
        })
    }

    #[test]
    fn test_log_transaction_metrics_none() {
        let captures = capture_test_event("/nothing", TransactionSource::Url);
        insta::assert_debug_snapshot!(captures, @r#"
        [
            "event.transaction_name_changes:1|c|#source_in:url,changes:none,source_out:sanitized,is_404:false",
        ]
        "#);
    }

    #[test]
    fn test_log_transaction_metrics_rule() {
        let captures = capture_test_event("/foo/john/denver", TransactionSource::Url);
        insta::assert_debug_snapshot!(captures, @r#"
        [
            "event.transaction_name_changes:1|c|#source_in:url,changes:rule,source_out:sanitized,is_404:false",
        ]
        "#);
    }

    #[test]
    fn test_log_transaction_metrics_pattern() {
        let captures = capture_test_event("/something/12345", TransactionSource::Url);
        insta::assert_debug_snapshot!(captures, @r#"
        [
            "event.transaction_name_changes:1|c|#source_in:url,changes:pattern,source_out:sanitized,is_404:false",
        ]
        "#);
    }

    #[test]
    fn test_log_transaction_metrics_both() {
        let captures = capture_test_event("/foo/john/12345", TransactionSource::Url);
        insta::assert_debug_snapshot!(captures, @r#"
        [
            "event.transaction_name_changes:1|c|#source_in:url,changes:both,source_out:sanitized,is_404:false",
        ]
        "#);
    }

    #[test]
    fn test_log_transaction_metrics_no_match() {
        let captures = capture_test_event("/foo/john/12345", TransactionSource::Route);
        insta::assert_debug_snapshot!(captures, @r#"
        [
            "event.transaction_name_changes:1|c|#source_in:route,changes:none,source_out:route,is_404:false",
        ]
        "#);
    }

    /// Confirms that the hardcoded value we use for the fixed length of the measurement MRI is
    /// correct. Unit test is placed here because it has dependencies to relay-server and therefore
    /// cannot be called from relay-metrics.
    #[test]
    fn test_mri_overhead_constant() {
        let hardcoded_value = MeasurementsConfig::MEASUREMENT_MRI_OVERHEAD;

        let derived_value = {
            let name = "foobar".to_string();
            let value = 5.into(); // Arbitrary value.
            let unit = MetricUnit::Duration(DurationUnit::default());
            let tags = TransactionMeasurementTags {
                measurement_rating: None,
                universal_tags: CommonTags(BTreeMap::new()),
                score_profile_version: None,
            };

            let measurement = TransactionMetric::Measurement {
                name: name.clone(),
                value,
                unit,
                tags,
            };

            let metric: Bucket = measurement.into_metric(UnixTimestamp::now());
            metric.name.len() - unit.to_string().len() - name.len()
        };
        assert_eq!(
            hardcoded_value, derived_value,
            "Update `MEASUREMENT_MRI_OVERHEAD` if the naming scheme changed."
        );
    }

    #[tokio::test]
    async fn test_process_metrics_bucket_metadata() {
        let mut token = Cogs::noop().timed(ResourceId::Relay, AppFeature::Unattributed);
        let project_key = ProjectKey::parse("a94ae32be2584e0bbd7a4cbb95971fee").unwrap();
        let received_at = Utc::now();
        let config = Config::default();

        let (aggregator, mut aggregator_rx) = Addr::custom();
        let processor = create_test_processor_with_addrs(
            config,
            Addrs {
                aggregator,
                ..Default::default()
            },
        )
        .await;

        let mut item = Item::new(ItemType::Statsd);
        item.set_payload(
            ContentType::Text,
            "transactions/foo:3182887624:4267882815|s",
        );
        for (source, expected_received_at) in [
            (
                BucketSource::External,
                Some(UnixTimestamp::from_datetime(received_at).unwrap()),
            ),
            (BucketSource::Internal, None),
        ] {
            let message = ProcessMetrics {
                data: MetricData::Raw(vec![item.clone()]),
                project_key,
                source,
                received_at,
                sent_at: Some(Utc::now()),
            };
            processor.handle_process_metrics(&mut token, message);

            let Aggregator::MergeBuckets(merge_buckets) = aggregator_rx.recv().await.unwrap();
            let buckets = merge_buckets.buckets;
            assert_eq!(buckets.len(), 1);
            assert_eq!(buckets[0].metadata.received_at, expected_received_at);
        }
    }

    #[tokio::test]
    async fn test_process_batched_metrics() {
        let mut token = Cogs::noop().timed(ResourceId::Relay, AppFeature::Unattributed);
        let received_at = Utc::now();
        let config = Config::default();

        let (aggregator, mut aggregator_rx) = Addr::custom();
        let processor = create_test_processor_with_addrs(
            config,
            Addrs {
                aggregator,
                ..Default::default()
            },
        )
        .await;

        let payload = r#"{
    "buckets": {
        "11111111111111111111111111111111": [
            {
                "timestamp": 1615889440,
                "width": 0,
                "name": "d:custom/endpoint.response_time@millisecond",
                "type": "d",
                "value": [
                  68.0
                ],
                "tags": {
                  "route": "user_index"
                }
            }
        ],
        "22222222222222222222222222222222": [
            {
                "timestamp": 1615889440,
                "width": 0,
                "name": "d:custom/endpoint.cache_rate@none",
                "type": "d",
                "value": [
                  36.0
                ]
            }
        ]
    }
}
"#;
        let message = ProcessBatchedMetrics {
            payload: Bytes::from(payload),
            source: BucketSource::Internal,
            received_at,
            sent_at: Some(Utc::now()),
        };
        processor.handle_process_batched_metrics(&mut token, message);

        let Aggregator::MergeBuckets(mb1) = aggregator_rx.recv().await.unwrap();
        let Aggregator::MergeBuckets(mb2) = aggregator_rx.recv().await.unwrap();

        let mut messages = vec![mb1, mb2];
        messages.sort_by_key(|mb| mb.project_key);

        let actual = messages
            .into_iter()
            .map(|mb| (mb.project_key, mb.buckets))
            .collect::<Vec<_>>();

        assert_debug_snapshot!(actual, @r###"
        [
            (
                ProjectKey("11111111111111111111111111111111"),
                [
                    Bucket {
                        timestamp: UnixTimestamp(1615889440),
                        width: 0,
                        name: MetricName(
                            "d:custom/endpoint.response_time@millisecond",
                        ),
                        value: Distribution(
                            [
                                68.0,
                            ],
                        ),
                        tags: {
                            "route": "user_index",
                        },
                        metadata: BucketMetadata {
                            merges: 1,
                            received_at: None,
                            extracted_from_indexed: false,
                        },
                    },
                ],
            ),
            (
                ProjectKey("22222222222222222222222222222222"),
                [
                    Bucket {
                        timestamp: UnixTimestamp(1615889440),
                        width: 0,
                        name: MetricName(
                            "d:custom/endpoint.cache_rate@none",
                        ),
                        value: Distribution(
                            [
                                36.0,
                            ],
                        ),
                        tags: {},
                        metadata: BucketMetadata {
                            merges: 1,
                            received_at: None,
                            extracted_from_indexed: false,
                        },
                    },
                ],
            ),
        ]
        "###);
    }
}