-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathprocessor.rs
More file actions
3780 lines (3350 loc) · 134 KB
/
processor.rs
File metadata and controls
3780 lines (3350 loc) · 134 KB
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
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;
use std::time::Duration;
use anyhow::Context;
use brotli::CompressorWriter as BrotliEncoder;
use bytes::Bytes;
use chrono::{DateTime, Utc};
use flate2::Compression;
use flate2::write::{GzEncoder, ZlibEncoder};
use futures::FutureExt;
use futures::future::BoxFuture;
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, RelayMode};
use relay_dynamic_config::{Feature, GlobalConfig};
use relay_event_normalization::{ClockDriftProcessor, GeoIpLookup};
use relay_event_schema::processor::ProcessingAction;
use relay_event_schema::protocol::{
ClientReport, Event, EventId, Metrics, NetworkReportError, SpanV2,
};
use relay_filter::FilterStatKey;
use relay_metrics::{Bucket, BucketMetadata, BucketView, BucketsView, MetricNamespace};
use relay_protocol::Annotated;
use relay_quotas::{DataCategory, Quota, RateLimits, Scoping};
use relay_sampling::evaluation::{ReservoirCounters, 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::envelope::{
self, AttachmentType, ContentType, Envelope, EnvelopeError, Item, ItemContainer, ItemType,
};
use crate::extractors::{PartialDsn, RequestMeta, RequestTrust};
use crate::integrations::Integration;
use crate::managed::{InvalidProcessingGroupType, ManagedEnvelope, TypedEnvelope};
use crate::metrics::{MetricOutcomes, MetricsLimiter, MinimalTrackableBucket};
use crate::metrics_extraction::transactions::ExtractedMetrics;
use crate::metrics_extraction::transactions::types::ExtractMetricsError;
use crate::processing::check_ins::CheckInsProcessor;
use crate::processing::client_reports::ClientReportsProcessor;
use crate::processing::errors::{ErrorsProcessor, SwitchProcessingError};
use crate::processing::logs::LogsProcessor;
use crate::processing::profile_chunks::ProfileChunksProcessor;
use crate::processing::replays::ReplaysProcessor;
use crate::processing::sessions::SessionsProcessor;
use crate::processing::spans::SpansProcessor;
use crate::processing::trace_attachments::TraceAttachmentsProcessor;
use crate::processing::trace_metrics::TraceMetricsProcessor;
use crate::processing::transactions::TransactionProcessor;
use crate::processing::utils::event::{
EventFullyNormalized, EventMetricsExtracted, FiltersStatus, SpansExtracted, event_category,
event_type,
};
use crate::processing::{Forward as _, Output, Outputs, QuotaRateLimiter};
use crate::service::ServiceError;
use crate::services::global_config::GlobalConfigHandle;
use crate::services::metrics::{Aggregator, FlushBuckets, MergeBuckets, ProjectBuckets};
use crate::services::outcome::{DiscardItemType, DiscardReason, Outcome, TrackOutcome};
use crate::services::projects::cache::ProjectCacheHandle;
use crate::services::projects::project::{ProjectInfo, ProjectState};
use crate::services::upstream::{
SendRequest, Sign, SignatureType, UpstreamRelay, UpstreamRequest, UpstreamRequestError,
};
use crate::statsd::{RelayCounters, RelayDistributions, RelayTimers};
use crate::utils::{self, CheckLimits, EnvelopeLimiter};
use crate::{http, processing};
use relay_threading::AsyncPool;
#[cfg(feature = "processing")]
use {
crate::services::objectstore::Objectstore,
crate::services::store::Store,
crate::utils::Enforcement,
itertools::Itertools,
relay_cardinality::{
CardinalityLimit, CardinalityLimiter, CardinalityLimitsSplit, RedisSetLimiter,
RedisSetLimiterOptions,
},
relay_dynamic_config::CardinalityLimiterMode,
relay_quotas::{RateLimitingError, RedisRateLimiter},
relay_redis::RedisClients,
std::time::Instant,
symbolic_unreal::{Unreal4Error, Unreal4ErrorKind},
};
mod attachment;
mod dynamic_sampling;
pub mod event;
mod metrics;
mod nel;
mod profile;
mod report;
mod span;
#[cfg(all(sentry, feature = "processing"))]
pub mod playstation;
mod standalone;
#[cfg(feature = "processing")]
mod unreal;
#[cfg(feature = "processing")]
mod nnswitch;
/// 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.
pub 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$(, $($other: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);
}
$($(
if matches!(value, ProcessingGroup::$other) {
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 {}
processing_group!(TransactionGroup, Transaction);
impl EventProcessing for TransactionGroup {}
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!(LogGroup, Log, Nel);
processing_group!(TraceMetricGroup, TraceMetric);
processing_group!(SpanGroup, Span);
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,
/// NEL reports.
Nel,
/// Logs.
Log,
/// Trace metrics.
TraceMetric,
/// Spans.
Span,
/// Span V2 spans.
SpanV2,
/// Metrics.
Metrics,
/// ProfileChunk.
ProfileChunk,
/// V2 attachments without span / log association.
TraceAttachment,
/// 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.
fn split_envelope(
mut envelope: Envelope,
project_info: &ProjectInfo,
) -> SmallVec<[(Self, Box<Envelope>); 3]> {
let headers = envelope.headers().clone();
let mut grouped_envelopes = smallvec![];
// 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),
))
}
let span_v2_items = envelope.take_items_by(|item| {
let exp_feature = project_info.has_feature(Feature::SpanV2ExperimentalProcessing);
ItemContainer::<SpanV2>::is_container(item)
|| matches!(item.integration(), Some(Integration::Spans(_)))
// Process standalone spans (v1) via the v2 pipeline
|| (exp_feature && matches!(item.ty(), &ItemType::Span))
|| (exp_feature && item.is_span_attachment())
});
if !span_v2_items.is_empty() {
grouped_envelopes.push((
ProcessingGroup::SpanV2,
Envelope::from_parts(headers.clone(), span_v2_items),
))
}
// Extract spans.
let span_items = envelope.take_items_by(|item| matches!(item.ty(), &ItemType::Span));
if !span_items.is_empty() {
grouped_envelopes.push((
ProcessingGroup::Span,
Envelope::from_parts(headers.clone(), span_items),
))
}
// Extract logs.
let logs_items = envelope.take_items_by(|item| {
matches!(item.ty(), &ItemType::Log)
|| matches!(item.integration(), Some(Integration::Logs(_)))
});
if !logs_items.is_empty() {
grouped_envelopes.push((
ProcessingGroup::Log,
Envelope::from_parts(headers.clone(), logs_items),
))
}
// Extract trace metrics.
let trace_metric_items =
envelope.take_items_by(|item| matches!(item.ty(), &ItemType::TraceMetric));
if !trace_metric_items.is_empty() {
grouped_envelopes.push((
ProcessingGroup::TraceMetric,
Envelope::from_parts(headers.clone(), trace_metric_items),
))
}
// NEL items are transformed into logs in their own processing step.
let nel_items = envelope.take_items_by(|item| matches!(item.ty(), &ItemType::Nel));
if !nel_items.is_empty() {
grouped_envelopes.push((
ProcessingGroup::Nel,
Envelope::from_parts(headers.clone(), nel_items),
))
}
// Extract 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),
))
}
let trace_attachment_items = envelope.take_items_by(Item::is_trace_attachment);
if !trace_attachment_items.is_empty() {
grouped_envelopes.push((
ProcessingGroup::TraceAttachment,
Envelope::from_parts(headers.clone(), trace_attachment_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::Log => "log",
ProcessingGroup::TraceMetric => "trace_metric",
ProcessingGroup::Nel => "nel",
ProcessingGroup::Span => "span",
ProcessingGroup::SpanV2 => "span_v2",
ProcessingGroup::Metrics => "metrics",
ProcessingGroup::ProfileChunk => "profile_chunk",
ProcessingGroup::TraceAttachment => "trace_attachment",
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::Log => AppFeature::Logs,
ProcessingGroup::TraceMetric => AppFeature::TraceMetrics,
ProcessingGroup::Nel => AppFeature::Logs,
ProcessingGroup::Span => AppFeature::Spans,
ProcessingGroup::SpanV2 => AppFeature::Spans,
ProcessingGroup::Metrics => AppFeature::UnattributedMetrics,
ProcessingGroup::ProfileChunk => AppFeature::Profiles,
ProcessingGroup::ForwardUnknown => AppFeature::UnattributedEnvelope,
ProcessingGroup::Ungrouped => AppFeature::UnattributedEnvelope,
ProcessingGroup::TraceAttachment => AppFeature::TraceAttachments,
}
}
}
/// 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(DiscardItemType),
#[error("invalid transaction event")]
InvalidTransaction,
#[error("the item is not allowed/supported in this envelope")]
UnsupportedItem,
#[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 processing group type")]
InvalidProcessingGroup(Box<InvalidProcessingGroupType>),
#[error("nintendo switch dying message processing failed {0:?}")]
InvalidNintendoDyingMessage(#[source] SwitchProcessingError),
#[cfg(all(sentry, feature = "processing"))]
#[error("playstation dump processing failed: {0}")]
InvalidPlaystationDump(String),
#[error("processing group does not match specific processor")]
ProcessingGroupMismatch,
#[error("new processing pipeline failed")]
ProcessingFailure,
}
impl ProcessingError {
pub fn to_outcome(&self) -> Option<Outcome> {
match self {
Self::PayloadTooLarge(payload_type) => {
Some(Outcome::Invalid(DiscardReason::TooLarge(*payload_type)))
}
Self::InvalidJson(_) => Some(Outcome::Invalid(DiscardReason::InvalidJson)),
Self::InvalidMsgpack(_) => Some(Outcome::Invalid(DiscardReason::InvalidMsgpack)),
Self::InvalidSecurityType(_) => {
Some(Outcome::Invalid(DiscardReason::SecurityReportType))
}
Self::UnsupportedItem => Some(Outcome::Invalid(DiscardReason::InvalidEnvelope)),
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)),
Self::InvalidNintendoDyingMessage(_) => Some(Outcome::Invalid(DiscardReason::Payload)),
#[cfg(all(sentry, feature = "processing"))]
Self::InvalidPlaystationDump(_) => Some(Outcome::Invalid(DiscardReason::Payload)),
#[cfg(feature = "processing")]
Self::InvalidUnrealReport(err) if err.kind() == Unreal4ErrorKind::BadCompression => {
Some(Outcome::Invalid(DiscardReason::InvalidCompression))
}
#[cfg(feature = "processing")]
Self::InvalidUnrealReport(_) => Some(Outcome::Invalid(DiscardReason::ProcessUnreal)),
Self::SerializeFailed(_) | Self::ProcessingFailed(_) => {
Some(Outcome::Invalid(DiscardReason::Internal))
}
#[cfg(feature = "processing")]
Self::QuotasFailed(_) => Some(Outcome::Invalid(DiscardReason::Internal)),
Self::MissingProjectId => None,
Self::EventFiltered(key) => Some(Outcome::Filtered(key.clone())),
Self::InvalidProcessingGroup(_) => None,
Self::ProcessingGroupMismatch => Some(Outcome::Invalid(DiscardReason::Internal)),
// Outcomes are emitted in the new processing pipeline already.
Self::ProcessingFailure => None,
}
}
fn is_unexpected(&self) -> bool {
self.to_outcome()
.is_some_and(|outcome| outcome.is_unexpected())
}
}
#[cfg(feature = "processing")]
impl From<Unreal4Error> for ProcessingError {
fn from(err: Unreal4Error) -> Self {
match err.kind() {
Unreal4ErrorKind::TooLarge => Self::PayloadTooLarge(ItemType::UnrealReport.into()),
_ => ProcessingError::InvalidUnrealReport(err),
}
}
}
impl From<ExtractMetricsError> for ProcessingError {
fn from(error: ExtractMetricsError) -> Self {
match error {
ExtractMetricsError::MissingTimestamp | ExtractMetricsError::InvalidTimestamp => {
Self::InvalidTimestamp
}
}
}
}
impl From<InvalidProcessingGroupType> for ProcessingError {
fn from(value: InvalidProcessingGroupType) -> Self {
Self::InvalidProcessingGroup(Box::new(value))
}
}
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(),
}
}
pub fn into_inner(self) -> ExtractedMetrics {
self.metrics
}
/// 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,
project_key: ProjectKey,
sampling_key: Option<ProjectKey>,
aggregator: &Addr<Aggregator>,
) {
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 = sampling_key.unwrap_or(project_key);
aggregator.send(MergeBuckets {
project_key: sampling_project_key,
buckets: sampling_metrics,
});
}
}
/// 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 => false,
RelayMode::Managed => !project_info.has_feature(feature),
}
}
/// The result of the envelope processing containing the processed envelope along with the partial
/// result.
#[derive(Debug)]
#[expect(
clippy::large_enum_variant,
reason = "until we have a better solution to combat the excessive growth of Item, see #4819"
)]
enum ProcessingResult {
Envelope {
managed_envelope: TypedEnvelope<Processed>,
extracted_metrics: ProcessingExtractedMetrics,
},
Output(Output<Outputs>),
}
impl ProcessingResult {
/// Creates a [`ProcessingResult`] with no metrics.
fn no_metrics(managed_envelope: TypedEnvelope<Processed>) -> Self {
Self::Envelope {
managed_envelope,
extracted_metrics: ProcessingExtractedMetrics::new(),
}
}
}
/// All items which can be submitted upstream.
#[derive(Debug)]
#[expect(
clippy::large_enum_variant,
reason = "until we have a better solution to combat the excessive growth of Item, see #4819"
)]
enum Submit<'a> {
/// A processed envelope.
Envelope(TypedEnvelope<Processed>),
/// The output of a [`processing::Processor`].
Output {
output: Outputs,
ctx: processing::ForwardContext<'a>,
},
}
/// 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,
}
/// Like a [`ProcessEnvelope`], but with an envelope which has been grouped.
#[derive(Debug)]
struct ProcessEnvelopeGrouped<'a> {
/// The group the envelope belongs to.
pub group: ProcessingGroup,
/// Envelope to process.
pub envelope: ManagedEnvelope,
/// The processing context.
pub ctx: processing::Context<'a>,
}
/// 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,