-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathprocessor.rs
2869 lines (2469 loc) · 109 KB
/
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
use std::collections::BTreeMap;
use std::convert::TryFrom;
use std::io::Write;
use std::net;
use std::sync::Arc;
use std::time::{Duration, Instant};
use actix::SystemService;
use brotli2::write::BrotliEncoder;
use chrono::{DateTime, Duration as SignedDuration, Utc};
use flate2::write::{GzEncoder, ZlibEncoder};
use flate2::Compression;
use once_cell::sync::OnceCell;
use serde_json::Value as SerdeValue;
use tokio::sync::Semaphore;
use relay_auth::RelayVersion;
use relay_common::{ProjectId, ProjectKey, UnixTimestamp};
use relay_config::{Config, HttpEncoding};
use relay_filter::FilterStatKey;
use relay_general::pii::PiiConfigError;
use relay_general::pii::{PiiAttachmentsProcessor, PiiProcessor};
use relay_general::processor::{process_value, ProcessingState};
use relay_general::protocol::{
self, Breadcrumb, ClientReport, Csp, Event, EventType, ExpectCt, ExpectStaple, Hpkp, IpAddr,
LenientString, Metrics, RelayInfo, SecurityReportType, SessionAggregates, SessionAttributes,
SessionUpdate, Timestamp, UserReport, Values,
};
use relay_general::store::{ClockDriftProcessor, LightNormalizationConfig};
use relay_general::types::{Annotated, Array, FromValue, Object, ProcessingAction, Value};
use relay_log::LogError;
use relay_metrics::{Bucket, InsertMetrics, MergeBuckets, Metric};
use relay_quotas::{DataCategory, ReasonCode};
use relay_redis::RedisPool;
use relay_sampling::{DynamicSamplingContext, RuleId};
use relay_statsd::metric;
use relay_system::{Addr, FromMessage, NoResponse, Service};
use crate::actors::envelopes::{EnvelopeManager, SendEnvelope, SendEnvelopeError, SubmitEnvelope};
use crate::actors::outcome::{DiscardReason, Outcome, TrackOutcome};
use crate::actors::project::{Feature, ProjectState};
use crate::actors::project_cache::ProjectCache;
use crate::actors::upstream::{SendRequest, UpstreamRelay};
use crate::envelope::{AttachmentType, ContentType, Envelope, Item, ItemType};
use crate::metrics_extraction::sessions::{extract_session_metrics, SessionMetricsConfig};
use crate::metrics_extraction::transactions::{extract_transaction_metrics, ExtractMetricsError};
use crate::service::REGISTRY;
use crate::statsd::{RelayCounters, RelayTimers};
use crate::utils::{
self, ChunkedFormDataAggregator, EnvelopeContext, ErrorBoundary, FormDataIter, SamplingResult,
};
#[cfg(feature = "processing")]
use {
crate::actors::envelopes::SendMetrics,
crate::actors::project_cache::UpdateRateLimits,
crate::service::ServerError,
crate::utils::{EnvelopeLimiter, MetricsLimiter},
anyhow::Context,
relay_general::store::{GeoIpLookup, StoreConfig, StoreProcessor},
relay_quotas::ItemScoping,
relay_quotas::{RateLimitingError, RedisRateLimiter},
symbolic_unreal::{Unreal4Error, Unreal4ErrorKind},
};
/// The minimum clock drift for correction to apply.
const MINIMUM_CLOCK_DRIFT: Duration = Duration::from_secs(55 * 60);
/// 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")]
InvalidSecurityType,
#[error("invalid security report")]
InvalidSecurityReport(#[source] serde_json::Error),
#[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("event dropped by sampling rule {0}")]
Sampled(RuleId),
#[error("invalid pii config")]
PiiConfigError(PiiConfigError),
}
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::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::Sampled(_) => None,
}
}
fn is_unexpected(&self) -> bool {
self.to_outcome()
.map_or(false, |outcome| outcome.is_unexpected())
}
fn should_keep_metrics(&self) -> bool {
matches!(self, Self::Sampled(_))
}
}
#[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);
/// Checks if the Event includes unprintable fields.
#[cfg(feature = "processing")]
fn has_unprintable_fields(event: &Annotated<Event>) -> bool {
fn is_unprintable(value: &&str) -> bool {
value.chars().any(|c| {
c == '\u{fffd}' // unicode replacement character
|| (c.is_control() && !c.is_whitespace()) // non-whitespace control characters
})
}
if let Some(event) = event.value() {
let env = event.environment.as_str().filter(is_unprintable);
let release = event.release.as_str().filter(is_unprintable);
env.is_some() || release.is_some()
} else {
false
}
}
/// A state container for envelope processing.
#[derive(Debug)]
struct ProcessEnvelopeState {
/// The envelope.
///
/// The pipeline can mutate the envelope and remove or add items. In particular, event items are
/// removed at the beginning of processing and re-added in the end.
envelope: Envelope,
/// The extracted event payload.
///
/// For Envelopes without event payloads, this contains `Annotated::empty`. If a single item has
/// `creates_event`, the event is required and the pipeline errors if no payload can be
/// extracted.
event: Annotated<Event>,
/// Track whether transaction metrics were already extracted.
transaction_metrics_extracted: bool,
/// Partial metrics of the Event during construction.
///
/// The pipeline stages can add to this metrics objects. In `finalize_event`, the metrics are
/// persisted into the Event. All modifications afterwards will have no effect.
metrics: Metrics,
/// A list of cumulative sample rates applied to this event.
///
/// This element is obtained from the event or transaction item and re-serialized into the
/// resulting item.
sample_rates: Option<Value>,
/// Metrics extracted from items in the envelope.
///
/// Relay can extract metrics for sessions and transactions, which is controlled by
/// configuration objects in the project config.
extracted_metrics: Vec<Metric>,
/// The state of the project that this envelope belongs to.
project_state: Arc<ProjectState>,
/// The state of the project that initiated the current trace.
/// This is the config used for trace-based dynamic sampling.
sampling_project_state: Option<Arc<ProjectState>>,
/// The id of the project that this envelope is ingested into.
///
/// This identifier can differ from the one stated in the Envelope's DSN if the key was moved to
/// a new project or on the legacy endpoint. In that case, normalization will update the project
/// ID.
project_id: ProjectId,
/// The envelope context before processing.
envelope_context: EnvelopeContext,
}
impl ProcessEnvelopeState {
/// Returns whether any item in the envelope creates an event in any relay.
///
/// This is used to branch into the processing pipeline. If this function returns false, only
/// rate limits are executed. If this function returns true, an event is created either in the
/// current relay or in an upstream processing relay.
fn creates_event(&self) -> bool {
self.envelope.items().any(Item::creates_event)
}
/// Returns true if there is an event in the processing state.
///
/// The event was previously removed from the Envelope. This returns false if there was an
/// invalid event item.
fn has_event(&self) -> bool {
self.event.value().is_some()
}
/// 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(&self) -> Option<EventType> {
self.event
.value()
.map(|event| event.ty.value().copied().unwrap_or_default())
}
/// 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(&self) -> Option<DataCategory> {
self.event_type().map(DataCategory::from)
}
/// Removes the event payload from this processing state.
#[cfg(feature = "processing")]
fn remove_event(&mut self) {
self.event = Annotated::empty();
}
}
/// Fields of client reports that map to specific [`Outcome`]s without content.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
enum ClientReportField {
/// The event has been filtered by an inbound data filter.
Filtered,
/// The event has been filtered by a sampling rule.
FilteredSampling,
/// The event has been rate limited.
RateLimited,
/// The event has already been discarded on the client side.
ClientDiscard,
}
/// Parse an outcome from an outcome ID and a reason string.
///
/// Currently only used to reconstruct outcomes encoded in client reports.
fn outcome_from_parts(field: ClientReportField, reason: &str) -> Result<Outcome, ()> {
match field {
ClientReportField::FilteredSampling => match reason.strip_prefix("Sampled:") {
Some(rule_id) => rule_id
.parse()
.map(|id| Outcome::FilteredSampling(RuleId(id)))
.map_err(|_| ()),
None => Err(()),
},
ClientReportField::ClientDiscard => Ok(Outcome::ClientDiscard(reason.into())),
ClientReportField::Filtered => Ok(Outcome::Filtered(
FilterStatKey::try_from(reason).map_err(|_| ())?,
)),
ClientReportField::RateLimited => Ok(Outcome::RateLimited(match reason {
"" => None,
other => Some(ReasonCode::new(other)),
})),
}
}
/// 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<(Envelope, EnvelopeContext)>,
}
/// 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 {
pub envelope: Envelope,
pub envelope_context: EnvelopeContext,
pub project_state: Arc<ProjectState>,
pub sampling_project_state: Option<Arc<ProjectState>>,
}
/// 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::Metrics), 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 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 items: Vec<Item>,
/// The target project.
pub project_key: ProjectKey,
/// The instant at which the request was received.
pub start_time: Instant,
/// The value of the Envelope's [`sent_at`](Envelope::sent_at) header for clock drift
/// correction.
pub sent_at: Option<DateTime<Utc>>,
}
/// Applies HTTP content encoding to an envelope's payload.
///
/// This message is a workaround for a single-threaded upstream actor.
#[derive(Debug)]
pub struct EncodeEnvelope {
request: SendEnvelope,
}
impl EncodeEnvelope {
/// Creates a new `EncodeEnvelope` message from `SendEnvelope` request.
pub fn new(request: SendEnvelope) -> Self {
Self { request }
}
}
/// Applies rate limits to metrics buckets and forwards them to the envelope manager.
#[cfg(feature = "processing")]
#[derive(Debug)]
pub struct RateLimitFlushBuckets {
pub bucket_limiter: MetricsLimiter<Bucket>,
pub partition_key: Option<u64>,
}
/// CPU-intensive processing tasks for envelopes.
#[derive(Debug)]
pub enum EnvelopeProcessor {
ProcessEnvelope(Box<ProcessEnvelope>),
ProcessMetrics(Box<ProcessMetrics>),
EncodeEnvelope(Box<EncodeEnvelope>),
#[cfg(feature = "processing")]
RateLimitFlushBuckets(RateLimitFlushBuckets),
}
impl EnvelopeProcessor {
pub fn from_registry() -> Addr<Self> {
REGISTRY.get().unwrap().processor.clone()
}
}
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::ProcessMetrics(Box::new(message))
}
}
impl FromMessage<EncodeEnvelope> for EnvelopeProcessor {
type Response = NoResponse;
fn from_message(message: EncodeEnvelope, _: ()) -> Self {
Self::EncodeEnvelope(Box::new(message))
}
}
#[cfg(feature = "processing")]
impl FromMessage<RateLimitFlushBuckets> for EnvelopeProcessor {
type Response = NoResponse;
fn from_message(message: RateLimitFlushBuckets, _: ()) -> Self {
Self::RateLimitFlushBuckets(message)
}
}
/// Service implementing the [`EnvelopeProcessor`] interface.
///
/// This service handles messages in a worker pool with configurable concurrency.
pub struct EnvelopeProcessorService {
config: Arc<Config>,
#[cfg(feature = "processing")]
rate_limiter: Option<RedisRateLimiter>,
#[cfg(feature = "processing")]
geoip_lookup: Option<GeoIpLookup>,
}
impl EnvelopeProcessorService {
/// Creates a multi-threaded envelope processor.
pub fn new(config: Arc<Config>, _redis: Option<RedisPool>) -> anyhow::Result<Self> {
#[cfg(feature = "processing")]
{
let geoip_lookup = match config.geoip_path() {
Some(p) => Some(GeoIpLookup::open(p).context(ServerError::GeoIpError)?),
None => None,
};
let rate_limiter =
_redis.map(|pool| RedisRateLimiter::new(pool).max_limit(config.max_rate_limit()));
Ok(Self {
config,
rate_limiter,
geoip_lookup,
})
}
#[cfg(not(feature = "processing"))]
Ok(Self { config })
}
/// Returns Ok(true) if attributes were modified.
/// Returns Err if the session should be dropped.
fn validate_attributes(
&self,
client_addr: &Option<net::IpAddr>,
attributes: &mut SessionAttributes,
) -> Result<bool, ()> {
let mut changed = false;
let release = &attributes.release;
if let Err(e) = protocol::validate_release(release) {
relay_log::trace!("skipping session with invalid release '{}': {}", release, e);
return Err(());
}
if let Some(ref env) = attributes.environment {
if let Err(e) = protocol::validate_environment(env) {
relay_log::trace!("removing invalid environment '{}': {}", env, e);
attributes.environment = None;
changed = true;
}
}
if let Some(ref ip_address) = attributes.ip_address {
if ip_address.is_auto() {
attributes.ip_address = client_addr.map(IpAddr::from);
changed = true;
}
}
Ok(changed)
}
fn is_valid_session_timestamp(
&self,
received: DateTime<Utc>,
timestamp: DateTime<Utc>,
) -> bool {
let max_age = SignedDuration::seconds(self.config.max_session_secs_in_past());
if (received - timestamp) > max_age {
relay_log::trace!("skipping session older than {} days", max_age.num_days());
return false;
}
let max_future = SignedDuration::seconds(self.config.max_secs_in_future());
if (timestamp - received) > max_future {
relay_log::trace!(
"skipping session more than {}s in the future",
max_future.num_seconds()
);
return false;
}
true
}
/// Returns true if the item should be kept.
#[allow(clippy::too_many_arguments)]
fn process_session(
&self,
item: &mut Item,
received: DateTime<Utc>,
client: Option<&str>,
client_addr: Option<net::IpAddr>,
metrics_config: SessionMetricsConfig,
clock_drift_processor: &ClockDriftProcessor,
extracted_metrics: &mut Vec<Metric>,
) -> bool {
let mut changed = false;
let payload = item.payload();
let mut session = match SessionUpdate::parse(&payload) {
Ok(session) => session,
Err(error) => {
relay_log::trace!("skipping invalid session payload: {}", LogError(&error));
return false;
}
};
if session.sequence == u64::MAX {
relay_log::trace!("skipping session due to sequence overflow");
return false;
}
if clock_drift_processor.is_drifted() {
relay_log::trace!("applying clock drift correction to session");
clock_drift_processor.process_datetime(&mut session.started);
clock_drift_processor.process_datetime(&mut session.timestamp);
changed = true;
}
if session.timestamp < session.started {
relay_log::trace!("fixing session timestamp to {}", session.timestamp);
session.timestamp = session.started;
changed = true;
}
// Log the timestamp delay for all sessions after clock drift correction.
let session_delay = received - session.timestamp;
if session_delay > SignedDuration::minutes(1) {
metric!(
timer(RelayTimers::TimestampDelay) = session_delay.to_std().unwrap(),
category = "session",
);
}
// Validate timestamps
for t in [session.timestamp, session.started] {
if !self.is_valid_session_timestamp(received, t) {
return false;
}
}
// Validate attributes
match self.validate_attributes(&client_addr, &mut session.attributes) {
Err(_) => return false,
Ok(changed_attributes) => {
changed |= changed_attributes;
}
}
// Extract metrics if they haven't been extracted by a prior Relay
if metrics_config.is_enabled() && !item.metrics_extracted() {
extract_session_metrics(&session.attributes, &session, client, extracted_metrics);
item.set_metrics_extracted(true);
}
// Drop the session if metrics have been extracted in this or a prior Relay
if metrics_config.should_drop() && item.metrics_extracted() {
return false;
}
if changed {
let json_string = match serde_json::to_string(&session) {
Ok(json) => json,
Err(err) => {
relay_log::error!("failed to serialize session: {}", LogError(&err));
return false;
}
};
item.set_payload(ContentType::Json, json_string);
}
true
}
#[allow(clippy::too_many_arguments)]
fn process_session_aggregates(
&self,
item: &mut Item,
received: DateTime<Utc>,
client: Option<&str>,
client_addr: Option<net::IpAddr>,
metrics_config: SessionMetricsConfig,
clock_drift_processor: &ClockDriftProcessor,
extracted_metrics: &mut Vec<Metric>,
) -> bool {
let mut changed = false;
let payload = item.payload();
let mut session = match SessionAggregates::parse(&payload) {
Ok(session) => session,
Err(error) => {
relay_log::trace!("skipping invalid sessions payload: {}", LogError(&error));
return false;
}
};
if clock_drift_processor.is_drifted() {
relay_log::trace!("applying clock drift correction to session");
for aggregate in &mut session.aggregates {
clock_drift_processor.process_datetime(&mut aggregate.started);
}
changed = true;
}
// Validate timestamps
session
.aggregates
.retain(|aggregate| self.is_valid_session_timestamp(received, aggregate.started));
// Aftter timestamp validation, aggregates could now be empty
if session.aggregates.is_empty() {
return false;
}
// Validate attributes
match self.validate_attributes(&client_addr, &mut session.attributes) {
Err(_) => return false,
Ok(changed_attributes) => {
changed |= changed_attributes;
}
}
// Extract metrics if they haven't been extracted by a prior Relay
if metrics_config.is_enabled() && !item.metrics_extracted() {
for aggregate in &session.aggregates {
extract_session_metrics(&session.attributes, aggregate, client, extracted_metrics);
item.set_metrics_extracted(true);
}
}
// Drop the aggregate if metrics have been extracted in this or a prior Relay
if metrics_config.should_drop() && item.metrics_extracted() {
return false;
}
if changed {
let json_string = match serde_json::to_string(&session) {
Ok(json) => json,
Err(err) => {
relay_log::error!("failed to serialize session: {}", LogError(&err));
return false;
}
};
item.set_payload(ContentType::Json, json_string);
}
true
}
/// Validates all sessions and session aggregates in the envelope, if any.
///
/// Both are removed from the envelope if they contain invalid JSON or if their timestamps
/// are out of range after clock drift correction.
fn process_sessions(&self, state: &mut ProcessEnvelopeState) {
let received = state.envelope_context.received_at();
let extracted_metrics = &mut state.extracted_metrics;
let metrics_config = state.project_state.config().session_metrics;
let envelope = &mut state.envelope;
let client = envelope.meta().client().map(|x| x.to_owned());
let client_addr = envelope.meta().client_addr();
let clock_drift_processor =
ClockDriftProcessor::new(envelope.sent_at(), received).at_least(MINIMUM_CLOCK_DRIFT);
envelope.retain_items(|item| {
match item.ty() {
ItemType::Session => self.process_session(
item,
received,
client.as_deref(),
client_addr,
metrics_config,
&clock_drift_processor,
extracted_metrics,
),
ItemType::Sessions => self.process_session_aggregates(
item,
received,
client.as_deref(),
client_addr,
metrics_config,
&clock_drift_processor,
extracted_metrics,
),
_ => true, // Keep all other item types
}
});
}
/// Validates and normalizes all user report items in the envelope.
///
/// User feedback items are removed from the envelope if they contain invalid JSON or if the
/// JSON violates the schema (basic type validation). Otherwise, their normalized representation
/// is written back into the item.
fn process_user_reports(&self, state: &mut ProcessEnvelopeState) {
state.envelope.retain_items(|item| {
if item.ty() != &ItemType::UserReport {
return true;
};
let report = match serde_json::from_slice::<UserReport>(&item.payload()) {
Ok(session) => session,
Err(error) => {
relay_log::error!("failed to store user report: {}", LogError(&error));
return false;
}
};
let json_string = match serde_json::to_string(&report) {
Ok(json) => json,
Err(err) => {
relay_log::error!("failed to serialize user report: {}", LogError(&err));
return false;
}
};
item.set_payload(ContentType::Json, json_string);
true
});
}
/// Validates and extracts client reports.
///
/// At the moment client reports are primarily used to transfer outcomes from
/// client SDKs. The outcomes are removed here and sent directly to the outcomes
/// system.
fn process_client_reports(&self, state: &mut ProcessEnvelopeState) {
// if client outcomes are disabled we leave the the client reports unprocessed
// and pass them on.
if !self.config.emit_outcomes().any() || !self.config.emit_client_outcomes() {
// if a processing relay has client outcomes disabled we drop them.
if self.config.processing_enabled() {
state
.envelope
.retain_items(|item| item.ty() != &ItemType::ClientReport);
}
return;
}
let mut timestamp = None;
let mut output_events = BTreeMap::new();
let received = state.envelope_context.received_at();
let clock_drift_processor = ClockDriftProcessor::new(state.envelope.sent_at(), received)
.at_least(MINIMUM_CLOCK_DRIFT);
// we're going through all client reports but we're effectively just merging
// them into the first one.
state.envelope.retain_items(|item| {
if item.ty() != &ItemType::ClientReport {
return true;
};
match ClientReport::parse(&item.payload()) {
Ok(ClientReport {
timestamp: report_timestamp,
discarded_events,
rate_limited_events,
filtered_events,
filtered_sampling_events,
}) => {
// Glue all discarded events together and give them the appropriate outcome type
let input_events = discarded_events
.into_iter()
.map(|discarded_event| (ClientReportField::ClientDiscard, discarded_event))
.chain(
filtered_events.into_iter().map(|discarded_event| {
(ClientReportField::Filtered, discarded_event)
}),
)
.chain(filtered_sampling_events.into_iter().map(|discarded_event| {
(ClientReportField::FilteredSampling, discarded_event)
}))
.chain(rate_limited_events.into_iter().map(|discarded_event| {
(ClientReportField::RateLimited, discarded_event)
}));
for (outcome_type, discarded_event) in input_events {
if discarded_event.reason.len() > 200 {
relay_log::trace!("ignored client outcome with an overlong reason");
continue;
}
*output_events
.entry((
outcome_type,
discarded_event.reason,
discarded_event.category,
))
.or_insert(0) += discarded_event.quantity;
}
if let Some(ts) = report_timestamp {
timestamp.get_or_insert(ts);
}
}
Err(err) => relay_log::trace!("invalid client report received: {}", LogError(&err)),
}
false
});
if output_events.is_empty() {
return;
}
let timestamp =
timestamp.get_or_insert_with(|| UnixTimestamp::from_secs(received.timestamp() as u64));
if clock_drift_processor.is_drifted() {
relay_log::trace!("applying clock drift correction to client report");
clock_drift_processor.process_timestamp(timestamp);
}
let max_age = SignedDuration::seconds(self.config.max_secs_in_past());
if (received - timestamp.as_datetime()) > max_age {
relay_log::trace!(
"skipping client outcomes older than {} days",
max_age.num_days()
);
return;
}
let max_future = SignedDuration::seconds(self.config.max_secs_in_future());
if (timestamp.as_datetime() - received) > max_future {
relay_log::trace!(
"skipping client outcomes more than {}s in the future",
max_future.num_seconds()
);
return;
}
let producer = TrackOutcome::from_registry();
for ((outcome_type, reason, category), quantity) in output_events.into_iter() {
let outcome = match outcome_from_parts(outcome_type, &reason) {
Ok(outcome) => outcome,
Err(_) => {
relay_log::trace!(
"Invalid outcome_type / reason: ({:?}, {})",
outcome_type,
reason
);
continue;
}
};
producer.send(TrackOutcome {
timestamp: timestamp.as_datetime(),
scoping: state.envelope_context.scoping(),
outcome,
event_id: None,
remote_addr: None, // omitting the client address allows for better aggregation
category,
quantity,
});
}
}
/// Remove profiles if the feature flag is not enabled
fn process_profiles(&self, state: &mut ProcessEnvelopeState) {
let profiling_enabled = state.project_state.has_feature(Feature::Profiling);
let envelope = &mut state.envelope;
envelope.retain_items(|item| match item.ty() {
ItemType::Profile => profiling_enabled,
_ => true,
});
if !self.config.processing_enabled() {
return;
}
let context = &state.envelope_context;
let mut new_profiles = Vec::new();
while let Some(item) = envelope.take_item_by(|item| item.ty() == &ItemType::Profile) {
match relay_profiling::expand_profile(&item.payload()[..]) {
Ok(payloads) => new_profiles.extend(payloads),
Err(err) => {
match err {
relay_profiling::ProfileError::InvalidJson(_) => {
relay_log::warn!("invalid profile: {}", LogError(&err));
}
_ => relay_log::debug!("invalid profile: {}", err),
};
context.track_outcome(
Outcome::Invalid(DiscardReason::Profiling(
relay_profiling::discard_reason(err),
)),
DataCategory::Profile,
1,
);
}
}
}
for payload in new_profiles {
let mut item = Item::new(ItemType::Profile);
item.set_payload(ContentType::Json, &payload[..]);
envelope.add_item(item);
}
}
/// Remove replays if the feature flag is not enabled
fn process_replays(&self, state: &mut ProcessEnvelopeState) {
let replays_enabled = state.project_state.has_feature(Feature::Replays);
let context = &state.envelope_context;
let envelope = &mut state.envelope;
let client_addr = envelope.meta().client_addr();
state.envelope.retain_items(|item| match item.ty() {
ItemType::ReplayEvent => {
if !replays_enabled {
return false;
}