-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathevents.rs
1758 lines (1482 loc) · 68.8 KB
/
events.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::cell::RefCell;
use std::collections::BTreeMap;
use std::rc::Rc;
use std::sync::Arc;
use std::time::{Duration, Instant};
use actix::prelude::*;
use actix_web::http::ContentEncoding;
use chrono::{DateTime, Duration as SignedDuration, Utc};
use failure::Fail;
use futures::prelude::*;
use parking_lot::RwLock;
use serde_json::Value as SerdeValue;
use relay_common::{clone, metric, LogError, ProjectId};
use relay_config::{Config, HttpEncoding, RelayMode};
use relay_general::pii::{PiiAttachmentsProcessor, PiiProcessor};
use relay_general::processor::{process_value, ProcessingState};
use relay_general::protocol::{
Breadcrumb, Csp, Event, EventId, EventType, ExpectCt, ExpectStaple, Hpkp, LenientString,
Metrics, SecurityReportType, SessionUpdate, Timestamp, Values,
};
use relay_general::store::ClockDriftProcessor;
use relay_general::types::{Annotated, Array, Object, ProcessingAction, Value};
use relay_quotas::RateLimits;
use relay_redis::RedisPool;
use crate::actors::outcome::{DiscardReason, Outcome, OutcomeProducer, TrackOutcome};
use crate::actors::project::{
CheckEnvelope, GetProjectState, Project, ProjectState, UpdateRateLimits,
};
use crate::actors::project_cache::ProjectError;
use crate::actors::upstream::{SendRequest, UpstreamRelay, UpstreamRequestError};
use crate::envelope::{self, AttachmentType, ContentType, Envelope, Item, ItemType};
use crate::metrics::{RelayCounters, RelayHistograms, RelaySets, RelayTimers};
use crate::service::ServerError;
use crate::utils::{self, ChunkedFormDataAggregator, FormDataIter, FutureExt};
#[cfg(feature = "processing")]
use {
crate::actors::store::{StoreEnvelope, StoreError, StoreForwarder},
crate::service::ServerErrorKind,
crate::utils::EnvelopeLimiter,
chrono::TimeZone,
failure::ResultExt,
minidump::Minidump,
relay_filter::FilterStatKey,
relay_general::protocol::IpAddr,
relay_general::store::{GeoIpLookup, StoreConfig, StoreProcessor},
relay_quotas::{DataCategory, RateLimitingError, RedisRateLimiter},
};
/// The minimum clock drift for correction to apply.
const MINIMUM_CLOCK_DRIFT: Duration = Duration::from_secs(55 * 60);
#[derive(Debug, Fail)]
pub enum QueueEnvelopeError {
#[fail(display = "Too many events (event_buffer_size reached)")]
TooManyEvents,
}
#[derive(Debug, Fail)]
enum ProcessingError {
#[fail(display = "invalid json in event")]
InvalidJson(#[cause] serde_json::Error),
#[fail(display = "invalid message pack event payload")]
InvalidMsgpack(#[cause] rmp_serde::decode::Error),
#[cfg(feature = "processing")]
#[fail(display = "invalid unreal crash report")]
InvalidUnrealReport(#[cause] symbolic::unreal::Unreal4Error),
#[fail(display = "event payload too large")]
PayloadTooLarge,
#[fail(display = "invalid transaction event")]
InvalidTransaction,
#[fail(display = "event processor failed")]
ProcessingFailed(#[cause] ProcessingAction),
#[fail(display = "duplicate {} in event", _0)]
DuplicateItem(ItemType),
#[fail(display = "failed to extract event payload")]
NoEventPayload,
#[fail(display = "could not schedule project fetch")]
ScheduleFailed(#[cause] MailboxError),
#[fail(display = "failed to resolve project information")]
ProjectFailed(#[cause] ProjectError),
#[fail(display = "missing project id in DSN")]
MissingProjectId,
#[fail(display = "invalid security report type")]
InvalidSecurityType,
#[fail(display = "invalid security report")]
InvalidSecurityReport(#[cause] serde_json::Error),
#[fail(display = "event submission rejected with reason: {:?}", _0)]
EventRejected(DiscardReason),
#[cfg(feature = "processing")]
#[fail(display = "event filtered with reason: {:?}", _0)]
EventFiltered(FilterStatKey),
#[fail(display = "could not serialize event payload")]
SerializeFailed(#[cause] serde_json::Error),
#[fail(display = "could not send event to upstream")]
SendFailed(#[cause] UpstreamRequestError),
#[cfg(feature = "processing")]
#[fail(display = "could not store event")]
StoreFailed(#[cause] StoreError),
#[fail(display = "event rate limited")]
RateLimited(RateLimits),
#[cfg(feature = "processing")]
#[fail(display = "failed to apply quotas")]
QuotasFailed(#[cause] RateLimitingError),
#[fail(display = "event exceeded its configured lifetime")]
Timeout,
}
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::EventRejected(reason) => Some(Outcome::Invalid(reason)),
Self::InvalidSecurityType => Some(Outcome::Invalid(DiscardReason::SecurityReportType)),
Self::InvalidSecurityReport(_) => Some(Outcome::Invalid(DiscardReason::SecurityReport)),
Self::InvalidTransaction => Some(Outcome::Invalid(DiscardReason::InvalidTransaction)),
Self::DuplicateItem(_) => Some(Outcome::Invalid(DiscardReason::DuplicateItem)),
Self::NoEventPayload => Some(Outcome::Invalid(DiscardReason::NoEventPayload)),
Self::RateLimited(ref rate_limits) => rate_limits
.longest_error()
.map(|r| Outcome::RateLimited(r.reason_code.clone())),
// Processing-only outcomes (Sentry-internal Relays)
#[cfg(feature = "processing")]
Self::InvalidUnrealReport(_) => Some(Outcome::Invalid(DiscardReason::ProcessUnreal)),
#[cfg(feature = "processing")]
Self::EventFiltered(ref filter_stat_key) => Some(Outcome::Filtered(*filter_stat_key)),
// Internal errors
Self::SerializeFailed(_)
| Self::ScheduleFailed(_)
| Self::ProjectFailed(_)
| Self::Timeout
| Self::ProcessingFailed(_)
| Self::MissingProjectId => Some(Outcome::Invalid(DiscardReason::Internal)),
#[cfg(feature = "processing")]
Self::StoreFailed(_) | Self::QuotasFailed(_) => {
Some(Outcome::Invalid(DiscardReason::Internal))
}
// If we send to an upstream, we don't emit outcomes.
Self::SendFailed(_) => None,
}
}
}
type ExtractedEvent = (Annotated<Event>, usize);
/// 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 event 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>,
/// 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,
/// Rate limits returned in processing mode.
///
/// The rate limiter is invoked in processing mode, after which the resulting limits are stored
/// in this field. Note that there can be rate limits even if the envelope still carries items.
///
/// These are always empty in non-processing mode, since the rate limiter is not invoked.
rate_limits: RateLimits,
/// The state of the project that this envelope belongs to.
project_state: 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,
/// UTC date time converted from the `start_time` instant.
received_at: DateTime<Utc>,
}
impl ProcessEnvelopeState {
/// Returns whether any item in the envelope creates an event.
///
/// This is used to branch into the event processing pipeline. If this function returns false,
/// only rate limits are executed.
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.
#[cfg(feature = "processing")]
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();
}
}
/// Synchronous service for processing envelopes.
pub struct EventProcessor {
config: Arc<Config>,
#[cfg(feature = "processing")]
rate_limiter: Option<RedisRateLimiter>,
#[cfg(feature = "processing")]
geoip_lookup: Option<Arc<GeoIpLookup>>,
}
impl EventProcessor {
#[cfg(feature = "processing")]
pub fn new(
config: Arc<Config>,
rate_limiter: Option<RedisRateLimiter>,
geoip_lookup: Option<Arc<GeoIpLookup>>,
) -> Self {
Self {
config,
rate_limiter,
geoip_lookup,
}
}
#[cfg(not(feature = "processing"))]
pub fn new(config: Arc<Config>) -> Self {
Self { config }
}
/// Validates all sessions in the envelope, if any.
///
/// Sessions 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) -> Result<(), ProcessingError> {
let envelope = &mut state.envelope;
let received = state.received_at;
let project_id = state.project_id;
let clock_drift_processor =
ClockDriftProcessor::new(envelope.sent_at(), received).at_least(MINIMUM_CLOCK_DRIFT);
let client = envelope.meta().client().map(str::to_owned);
envelope.retain_items(|item| {
if item.ty() != ItemType::Session {
return true;
}
let mut changed = false;
let payload = item.payload();
let mut session = match SessionUpdate::parse(&payload) {
Ok(session) => session,
Err(error) => {
return sentry::with_scope(
|scope| {
scope.set_tag("project", project_id);
if let Some(ref client) = client {
scope.set_tag("sdk", client);
}
scope.set_extra("session", String::from_utf8_lossy(&payload).into());
},
|| {
// Skip gracefully here to allow sending other sessions.
log::error!("failed to store session: {}", LogError(&error));
false
},
);
}
};
if session.sequence == u64::max_value() {
log::trace!("skipping session due to sequence overflow");
return false;
}
if clock_drift_processor.is_drifted() {
log::trace!("applying clock drift correction to session");
clock_drift_processor.process_session(&mut session);
changed = true;
}
if session.timestamp < session.started {
log::trace!("fixing session timestamp to {}", session.timestamp);
session.timestamp = session.started;
changed = true;
}
let max_age = SignedDuration::seconds(self.config.max_session_secs_in_past());
if (received - session.started) > max_age || (received - session.timestamp) > max_age {
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 (session.started - received) > max_age || (session.timestamp - received) > max_age {
log::trace!(
"skipping session more than {}s in the future",
max_future.num_seconds()
);
return false;
}
if changed {
let json_string = match serde_json::to_string(&session) {
Ok(json) => json,
Err(_) => return false,
};
item.set_payload(ContentType::Json, json_string);
}
true
});
Ok(())
}
/// Creates and initializes the processing state.
///
/// This applies defaults to the envelope and initializes empty rate limits.
fn prepare_state(
&self,
message: ProcessEnvelope,
) -> Result<ProcessEnvelopeState, ProcessingError> {
let ProcessEnvelope {
mut envelope,
project_state,
start_time,
} = message;
// 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_state.config.event_retention {
envelope.set_retention(retention);
}
// 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
// events 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 event without project ID, so drop it.
let project_id = project_state
.project_id
.or_else(|| envelope.meta().project_id())
.ok_or(ProcessingError::MissingProjectId)?;
// 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.
envelope.meta_mut().set_project_id(project_id);
Ok(ProcessEnvelopeState {
envelope,
event: Annotated::empty(),
metrics: Metrics::default(),
rate_limits: RateLimits::new(),
project_state,
project_id,
received_at: relay_common::instant_to_date_time(start_time),
})
}
/// Expands Unreal 4 items inside an envelope.
///
/// If the envelope does NOT contain an `UnrealReport` item, it doesn't do anything. If the envelope
/// contains an `UnrealReport` item, it removes it from the envelope and inserts new items for each
/// of its contents.
///
/// After this, the `EventProcessor` should be able to process the envelope the same way it
/// processes any other envelopes.
#[cfg(feature = "processing")]
fn expand_unreal(&self, state: &mut ProcessEnvelopeState) -> Result<(), ProcessingError> {
let envelope = &mut state.envelope;
if let Some(item) = envelope.take_item_by(|item| item.ty() == ItemType::UnrealReport) {
utils::expand_unreal_envelope(item, envelope)
.map_err(ProcessingError::InvalidUnrealReport)?;
}
Ok(())
}
fn event_from_json_payload(
&self,
item: Item,
event_type: Option<EventType>,
) -> Result<ExtractedEvent, ProcessingError> {
let mut event = Annotated::<Event>::from_json_bytes(&item.payload())
.map_err(ProcessingError::InvalidJson)?;
if let Some(event_value) = event.value_mut() {
event_value.ty.set_value(event_type);
}
Ok((event, item.len()))
}
fn event_from_security_report(&self, item: Item) -> Result<ExtractedEvent, ProcessingError> {
let len = item.len();
let mut event = Event::default();
let data = &item.payload();
let report_type = SecurityReportType::from_json(data)
.map_err(ProcessingError::InvalidJson)?
.ok_or(ProcessingError::InvalidSecurityType)?;
match report_type {
SecurityReportType::Csp => Csp::apply_to_event(data, &mut event),
SecurityReportType::ExpectCt => ExpectCt::apply_to_event(data, &mut event),
SecurityReportType::ExpectStaple => ExpectStaple::apply_to_event(data, &mut event),
SecurityReportType::Hpkp => Hpkp::apply_to_event(data, &mut event),
}
.map_err(ProcessingError::InvalidSecurityReport)?;
if let Some(release) = item.get_header("sentry_release").and_then(Value::as_str) {
event.release = Annotated::from(LenientString(release.to_owned()));
}
if let Some(env) = item
.get_header("sentry_environment")
.and_then(Value::as_str)
{
event.environment = Annotated::from(env.to_owned());
}
// Explicitly set the event type. This is required so that a `Security` item can be created
// instead of a regular `Event` item.
event.ty = Annotated::new(match report_type {
SecurityReportType::Csp => EventType::Csp,
SecurityReportType::ExpectCt => EventType::ExpectCT,
SecurityReportType::ExpectStaple => EventType::ExpectStaple,
SecurityReportType::Hpkp => EventType::Hpkp,
});
Ok((Annotated::new(event), len))
}
fn merge_formdata(&self, target: &mut SerdeValue, item: Item) {
let payload = item.payload();
let mut aggregator = ChunkedFormDataAggregator::new();
for entry in FormDataIter::new(&payload) {
if entry.key() == "sentry" {
// Custom clients can submit longer payloads and should JSON encode event data into
// the optional `sentry` field.
match serde_json::from_str(entry.value()) {
Ok(event) => utils::merge_values(target, event),
Err(_) => log::debug!("invalid json event payload in sentry form field"),
}
} else if let Some(index) = utils::get_sentry_chunk_index(entry.key(), "sentry__") {
// Electron SDK splits up long payloads into chunks starting at sentry__1 with an
// incrementing counter. Assemble these chunks here and then decode them below.
aggregator.insert(index, entry.value());
} else if let Some(keys) = utils::get_sentry_entry_indexes(entry.key()) {
// Try to parse the nested form syntax `sentry[key][key]` This is required for the
// Breakpad client library, which only supports string values of up to 64
// characters.
utils::update_nested_value(target, &keys, entry.value());
} else {
// Merge additional form fields from the request with `extra` data from the event
// payload and set defaults for processing. This is sent by clients like Breakpad or
// Crashpad.
utils::update_nested_value(target, &["extra", entry.key()], entry.value());
}
}
if !aggregator.is_empty() {
match serde_json::from_str(&aggregator.join()) {
Ok(event) => utils::merge_values(target, event),
Err(_) => log::debug!("invalid json event payload in sentry__* form fields"),
}
}
}
fn extract_attached_event(
config: &Config,
item: Option<Item>,
) -> Result<Annotated<Event>, ProcessingError> {
let item = match item {
Some(item) if !item.is_empty() => item,
_ => return Ok(Annotated::new(Event::default())),
};
// Protect against blowing up during deserialization. Attachments can have a significantly
// larger size than regular events and may cause significant processing delays.
if item.len() > config.max_event_size() {
return Err(ProcessingError::PayloadTooLarge);
}
let payload = item.payload();
let deserializer = &mut rmp_serde::Deserializer::from_read_ref(payload.as_ref());
Annotated::deserialize_with_meta(deserializer).map_err(ProcessingError::InvalidMsgpack)
}
fn parse_msgpack_breadcrumbs(
config: &Config,
item: Option<Item>,
) -> Result<Array<Breadcrumb>, ProcessingError> {
let mut breadcrumbs = Array::new();
let item = match item {
Some(item) if !item.is_empty() => item,
_ => return Ok(breadcrumbs),
};
// Validate that we do not exceed the maximum breadcrumb payload length. Breadcrumbs are
// truncated to a maximum of 100 in event normalization, but this is to protect us from
// blowing up during deserialization. As approximation, we use the maximum event payload
// size as bound, which is roughly in the right ballpark.
if item.len() > config.max_event_size() {
return Err(ProcessingError::PayloadTooLarge);
}
let payload = item.payload();
let mut deserializer = rmp_serde::Deserializer::new(payload.as_ref());
while !deserializer.get_ref().is_empty() {
let breadcrumb = Annotated::deserialize_with_meta(&mut deserializer)
.map_err(ProcessingError::InvalidMsgpack)?;
breadcrumbs.push(breadcrumb);
}
Ok(breadcrumbs)
}
fn event_from_attachments(
config: &Config,
event_item: Option<Item>,
breadcrumbs_item1: Option<Item>,
breadcrumbs_item2: Option<Item>,
) -> Result<ExtractedEvent, ProcessingError> {
let len = event_item.as_ref().map_or(0, |item| item.len())
+ breadcrumbs_item1.as_ref().map_or(0, |item| item.len())
+ breadcrumbs_item2.as_ref().map_or(0, |item| item.len());
let mut event = Self::extract_attached_event(config, event_item)?;
let mut breadcrumbs1 = Self::parse_msgpack_breadcrumbs(config, breadcrumbs_item1)?;
let mut breadcrumbs2 = Self::parse_msgpack_breadcrumbs(config, breadcrumbs_item2)?;
let timestamp1 = breadcrumbs1
.iter()
.rev()
.find_map(|breadcrumb| breadcrumb.value().and_then(|b| b.timestamp.value()));
let timestamp2 = breadcrumbs2
.iter()
.rev()
.find_map(|breadcrumb| breadcrumb.value().and_then(|b| b.timestamp.value()));
// Sort breadcrumbs by date. We presume that last timestamp from each row gives the
// relative sequence of the whole sequence, i.e., we don't need to splice the sequences
// to get the breadrumbs sorted.
if timestamp1 > timestamp2 {
std::mem::swap(&mut breadcrumbs1, &mut breadcrumbs2);
}
// Limit the total length of the breadcrumbs. We presume that if we have both
// breadcrumbs with items one contains the maximum number of breadcrumbs allowed.
let max_length = std::cmp::max(breadcrumbs1.len(), breadcrumbs2.len());
breadcrumbs1.extend(breadcrumbs2);
if breadcrumbs1.len() > max_length {
// Keep only the last max_length elements from the vectors
breadcrumbs1.drain(0..(breadcrumbs1.len() - max_length));
}
if !breadcrumbs1.is_empty() {
event.get_or_insert_with(Event::default).breadcrumbs = Annotated::new(Values {
values: Annotated::new(breadcrumbs1),
other: Object::default(),
});
}
Ok((event, len))
}
/// Checks for duplicate items in an envelope.
///
/// An item is considered duplicate if it was not removed by sanitation in `process_event` and
/// `extract_event`. This partially depends on the `processing_enabled` flag.
fn is_duplicate(&self, item: &Item) -> bool {
match item.ty() {
// These should always be removed by `extract_event`:
ItemType::Event => true,
ItemType::Transaction => true,
ItemType::Security => true,
ItemType::FormData => true,
ItemType::RawSecurity => true,
// These should be removed conditionally:
ItemType::UnrealReport => self.config.processing_enabled(),
// These may be forwarded to upstream / store:
ItemType::Attachment => false,
ItemType::UserReport => false,
// session data is never considered as part of deduplication
ItemType::Session => false,
}
}
/// Extracts the primary event payload from an envelope.
///
/// The event is obtained from only one source in the following precedence:
/// 1. An explicit event item. This is also the case for JSON uploads.
/// 2. A security report item.
/// 3. Attachments `__sentry-event` and `__sentry-breadcrumb1/2`.
/// 4. A multipart form data body.
/// 5. If none match, `Annotated::empty()`.
fn extract_event(&self, state: &mut ProcessEnvelopeState) -> Result<(), ProcessingError> {
let envelope = &mut state.envelope;
// Remove all items first, and then process them. After this function returns, only
// attachments can remain in the envelope. The event will be added again at the end of
// `process_event`.
let event_item = envelope.take_item_by(|item| item.ty() == ItemType::Event);
let transaction_item = envelope.take_item_by(|item| item.ty() == ItemType::Transaction);
let security_item = envelope.take_item_by(|item| item.ty() == ItemType::Security);
let raw_security_item = envelope.take_item_by(|item| item.ty() == ItemType::RawSecurity);
let form_item = envelope.take_item_by(|item| item.ty() == ItemType::FormData);
let attachment_item = envelope
.take_item_by(|item| item.attachment_type() == Some(AttachmentType::EventPayload));
let breadcrumbs1 = envelope
.take_item_by(|item| item.attachment_type() == Some(AttachmentType::Breadcrumbs));
let breadcrumbs2 = envelope
.take_item_by(|item| item.attachment_type() == Some(AttachmentType::Breadcrumbs));
// Event items can never occur twice in an envelope.
if let Some(duplicate) = envelope.get_item_by(|item| self.is_duplicate(item)) {
return Err(ProcessingError::DuplicateItem(duplicate.ty()));
}
let (event, event_len) = if let Some(item) = event_item.or(security_item) {
log::trace!("processing json event");
metric!(timer(RelayTimers::EventProcessingDeserialize), {
// Event items can never include transactions, so retain the event type and let
// inference deal with this during store normalization.
self.event_from_json_payload(item, None)?
})
} else if let Some(item) = transaction_item {
log::trace!("processing json transaction");
metric!(timer(RelayTimers::EventProcessingDeserialize), {
// Transaction items can only contain transaction events. Force the event type to
// hint to normalization that we're dealing with a transaction now.
self.event_from_json_payload(item, Some(EventType::Transaction))?
})
} else if let Some(item) = raw_security_item {
log::trace!("processing security report");
self.event_from_security_report(item)?
} else if attachment_item.is_some() || breadcrumbs1.is_some() || breadcrumbs2.is_some() {
log::trace!("extracting attached event data");
Self::event_from_attachments(&self.config, attachment_item, breadcrumbs1, breadcrumbs2)?
} else if let Some(item) = form_item {
log::trace!("extracting form data");
let len = item.len();
let mut value = SerdeValue::Object(Default::default());
self.merge_formdata(&mut value, item);
let event = Annotated::deserialize_with_meta(value).unwrap_or_default();
(event, len)
} else {
log::trace!("no event in envelope");
(Annotated::empty(), 0)
};
state.event = event;
state.metrics.bytes_ingested_event = Annotated::new(event_len as u64);
Ok(())
}
/// Extracts event information from an unreal context.
///
/// If the event does not contain an unreal context, this function does not perform any action.
/// If there was no event payload prior to this function, it is created.
#[cfg(feature = "processing")]
fn process_unreal(&self, state: &mut ProcessEnvelopeState) -> Result<(), ProcessingError> {
utils::process_unreal_envelope(&mut state.event, &mut state.envelope)
.map_err(ProcessingError::InvalidUnrealReport)
}
/// Writes a placeholder to indicate that this event has an associated minidump or an apple
/// crash report.
///
/// This will indicate to the ingestion pipeline that this event will need to be processed. The
/// payload can be checked via `is_minidump_event`.
#[cfg(feature = "processing")]
fn write_native_placeholder(&self, event: &mut Event, is_minidump: bool) {
use relay_general::protocol::{Exception, JsonLenientString, Level, Mechanism};
// Events must be native platform.
let platform = event.platform.value_mut();
*platform = Some("native".to_string());
// Assume that this minidump is the result of a crash and assign the fatal
// level. Note that the use of `setdefault` here doesn't generally allow the
// user to override the minidump's level as processing will overwrite it
// later.
event.level.get_or_insert_with(|| Level::Fatal);
// Create a placeholder exception. This signals normalization that this is an
// error event and also serves as a placeholder if processing of the minidump
// fails.
let exceptions = event
.exceptions
.value_mut()
.get_or_insert_with(Values::default)
.values
.value_mut()
.get_or_insert_with(Vec::new);
exceptions.clear(); // clear previous errors if any
let (type_name, value, mechanism_type) = if is_minidump {
("Minidump", "Invalid Minidump", "minidump")
} else {
(
"AppleCrashReport",
"Invalid Apple Crash Report",
"applecrashreport",
)
};
exceptions.push(Annotated::new(Exception {
ty: Annotated::new(type_name.to_string()),
value: Annotated::new(JsonLenientString(value.to_string())),
mechanism: Annotated::new(Mechanism {
ty: Annotated::from(mechanism_type.to_string()),
handled: Annotated::from(false),
synthetic: Annotated::from(true),
..Mechanism::default()
}),
..Exception::default()
}));
}
/// Extracts the timestamp from the minidump and uses it as the event timestamp.
#[cfg(feature = "processing")]
fn write_minidump_timestamp(&self, event: &mut Event, minidump_item: &Item) {
let minidump = match Minidump::read(minidump_item.payload()) {
Ok(minidump) => minidump,
Err(err) => {
log::debug!("Failed to parse minidump: {:?}", err);
return;
}
};
let timestamp = Utc.timestamp(minidump.header.time_date_stamp.into(), 0);
event.timestamp.set_value(Some(timestamp.into()));
}
/// Adds processing placeholders for special attachments.
///
/// If special attachments are present in the envelope, this adds placeholder payloads to the
/// event. This indicates to the pipeline that the event needs special processing.
///
/// If the event payload was empty before, it is created.
#[cfg(feature = "processing")]
fn create_placeholders(&self, state: &mut ProcessEnvelopeState) -> Result<(), ProcessingError> {
let envelope = &mut state.envelope;
let minidump_attachment =
envelope.get_item_by(|item| item.attachment_type() == Some(AttachmentType::Minidump));
let apple_crash_report_attachment = envelope
.get_item_by(|item| item.attachment_type() == Some(AttachmentType::AppleCrashReport));
if let Some(item) = minidump_attachment {
let event = state.event.get_or_insert_with(Event::default);
state.metrics.bytes_ingested_event_minidump = Annotated::new(item.len() as u64);
self.write_native_placeholder(event, true);
self.write_minidump_timestamp(event, item);
} else if let Some(item) = apple_crash_report_attachment {
let event = state.event.get_or_insert_with(Event::default);
state.metrics.bytes_ingested_event_applecrashreport = Annotated::new(item.len() as u64);
self.write_native_placeholder(event, false);
}
Ok(())
}
fn finalize_event(&self, state: &mut ProcessEnvelopeState) -> Result<(), ProcessingError> {
let is_transaction = state.event_type() == Some(EventType::Transaction);
let envelope = &mut state.envelope;
let event = match state.event.value_mut() {
Some(event) => event,
None if !self.config.processing_enabled() => return Ok(()),
None => return Err(ProcessingError::NoEventPayload),
};
// Event id is set statically in the ingest path.
let event_id = envelope.event_id().unwrap_or_default();
debug_assert!(!event_id.is_nil());
// Ensure that the event id in the payload is consistent with the envelope. If an event
// id was ingested, this will already be the case. Otherwise, this will insert a new
// event id. To be defensive, we always overwrite to ensure consistency.
event.id = Annotated::new(event_id);
// In processing mode, also write metrics into the event. Most metrics have already been
// collected at this state, except for the combined size of all attachments.
if self.config.processing_enabled() {
let attachment_size = envelope
.items()
.filter(|item| item.attachment_type() == Some(AttachmentType::Attachment))
.map(|item| item.len() as u64)
.sum::<u64>();
if attachment_size > 0 {
state.metrics.bytes_ingested_event_attachment = Annotated::new(attachment_size);
}
event._metrics = Annotated::new(std::mem::take(&mut state.metrics));
}
// TODO: Temporary workaround before processing. Experimental SDKs relied on a buggy
// clock drift correction that assumes the event timestamp is the sent_at time. This
// should be removed as soon as legacy ingestion has been removed.
let sent_at = match envelope.sent_at() {
Some(sent_at) => Some(sent_at),
None if is_transaction => event.timestamp.value().copied().map(Timestamp::into_inner),
None => None,
};
let mut processor =
ClockDriftProcessor::new(sent_at, state.received_at).at_least(MINIMUM_CLOCK_DRIFT);
process_value(&mut state.event, &mut processor, ProcessingState::root())
.map_err(|_| ProcessingError::InvalidTransaction)?;
Ok(())
}
#[cfg(feature = "processing")]
fn store_process_event(&self, state: &mut ProcessEnvelopeState) -> Result<(), ProcessingError> {
let ProcessEnvelopeState {
ref envelope,
ref mut event,
ref project_state,
received_at,
..
} = *state;
let key_id = project_state
.get_public_key_config()
.and_then(|k| Some(k.numeric_id?.to_string()));
if key_id.is_none() {
log::error!(
"project state for key {} is missing key id",
envelope.meta().public_key()
);
}
let store_config = StoreConfig {
project_id: Some(state.project_id.value()),
client_ip: envelope.meta().client_addr().map(IpAddr::from),
client: envelope.meta().client().map(str::to_owned),
key_id,
protocol_version: Some(envelope.meta().version().to_string()),
grouping_config: project_state.config.grouping_config.clone(),
user_agent: envelope.meta().user_agent().map(str::to_owned),
max_secs_in_future: Some(self.config.max_secs_in_future()),
max_secs_in_past: Some(self.config.max_secs_in_past()),
enable_trimming: Some(true),
is_renormalize: Some(false),
remove_other: Some(true),
normalize_user_agent: Some(true),
sent_at: envelope.sent_at(),
received_at: Some(received_at),
};
let mut store_processor = StoreProcessor::new(store_config, self.geoip_lookup.as_deref());
metric!(timer(RelayTimers::EventProcessingProcess), {
process_value(event, &mut store_processor, ProcessingState::root())
.map_err(|_| ProcessingError::InvalidTransaction)?;
});
Ok(())
}
#[cfg(feature = "processing")]
fn filter_event(&self, state: &mut ProcessEnvelopeState) -> Result<(), ProcessingError> {
let event = match state.event.value_mut() {
Some(event) => event,
None => return Err(ProcessingError::NoEventPayload),
};
let client_ip = state.envelope.meta().client_addr();
let filter_settings = &state.project_state.config.filter_settings;
metric!(timer(RelayTimers::EventProcessingFiltering), {
relay_filter::should_filter(event, client_ip, filter_settings)
.map_err(ProcessingError::EventFiltered)
})
}
#[cfg(feature = "processing")]
fn enforce_quotas(&self, state: &mut ProcessEnvelopeState) -> Result<(), ProcessingError> {
let rate_limiter = match self.rate_limiter.as_ref() {
Some(rate_limiter) => rate_limiter,
None => return Ok(()),
};
let project_state = &state.project_state;
let quotas = project_state.config.quotas.as_slice();
if quotas.is_empty() {
return Ok(());
}
let mut remove_event = false;
let category = state.event_category();
// 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(|item_scope, quantity| {
let limits = rate_limiter.is_rate_limited(quotas, item_scope, quantity)?;
remove_event |= Some(item_scope.category) == category && limits.is_limited();
Ok(limits)
});
// Tell the envelope limiter about the event, since it has been removed from the Envelope at
// this stage in processing.
if let Some(category) = category {
envelope_limiter.assume_event(category);
}
// Fetch scoping again from the project state. This is a rather cheap operation at this
// point and it is easier than passing scoping through all layers of `process_envelope`.
let scoping = project_state.get_scoping(state.envelope.meta());
state.rate_limits = metric!(timer(RelayTimers::EventProcessingRateLimiting), {
envelope_limiter
.enforce(&mut state.envelope, &scoping)
.map_err(ProcessingError::QuotasFailed)?
});
if remove_event {
state.remove_event();