-
Notifications
You must be signed in to change notification settings - Fork 123
Expand file tree
/
Copy pathstore.rs
More file actions
1669 lines (1487 loc) · 56.2 KB
/
Copy pathstore.rs
File metadata and controls
1669 lines (1487 loc) · 56.2 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
//! This module contains the service that forwards events and attachments to the Sentry store.
//! The service uses Kafka topics to forward data to Sentry
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::error::Error;
use std::sync::Arc;
use bytes::Bytes;
use chrono::{DateTime, Utc};
use futures::FutureExt;
use futures::future::BoxFuture;
use prost::Message as _;
use sentry_protos::snuba::v1::{TraceItem, TraceItemType};
use serde::Serialize;
use serde_json::value::RawValue;
use uuid::Uuid;
use relay_base_schema::data_category::DataCategory;
use relay_base_schema::organization::OrganizationId;
use relay_base_schema::project::ProjectId;
use relay_common::time::UnixTimestamp;
use relay_config::Config;
use relay_event_schema::protocol::{EventId, SpanV2, datetime_to_timestamp};
use relay_kafka::{ClientError, KafkaClient, KafkaTopic, Message, SerializationOutput};
use relay_metrics::{
Bucket, BucketView, BucketViewValue, BucketsView, ByNamespace, GaugeValue, MetricName,
MetricNamespace, SetView,
};
use relay_protocol::{Annotated, FiniteF64, SerializableAnnotated};
use relay_quotas::Scoping;
use relay_statsd::metric;
use relay_system::{Addr, FromMessage, Interface, NoResponse, Service};
use relay_threading::AsyncPool;
use crate::envelope::{AttachmentType, ContentType, Item, ItemType};
use crate::managed::{Counted, Managed, ManagedEnvelope, OutcomeError, Quantities};
use crate::metrics::{ArrayEncoding, BucketEncoder, MetricOutcomes};
use crate::service::ServiceError;
use crate::services::global_config::GlobalConfigHandle;
use crate::services::outcome::{DiscardReason, Outcome, TrackOutcome};
use crate::statsd::{RelayCounters, RelayGauges, RelayTimers};
use crate::utils::{self, FormDataIter};
mod sessions;
/// Fallback name used for attachment items without a `filename` header.
const UNNAMED_ATTACHMENT: &str = "Unnamed Attachment";
#[derive(Debug, thiserror::Error)]
pub enum StoreError {
#[error("failed to send the message to kafka: {0}")]
SendFailed(#[from] ClientError),
#[error("failed to encode data: {0}")]
EncodingFailed(std::io::Error),
#[error("failed to store event because event id was missing")]
NoEventId,
}
impl OutcomeError for StoreError {
type Error = Self;
fn consume(self) -> (Option<Outcome>, Self::Error) {
(Some(Outcome::Invalid(DiscardReason::Internal)), self)
}
}
struct Producer {
client: KafkaClient,
}
impl Producer {
pub fn create(config: &Config) -> anyhow::Result<Self> {
let mut client_builder = KafkaClient::builder();
for topic in KafkaTopic::iter().filter(|t| {
// Outcomes should not be sent from the store forwarder.
// See `KafkaOutcomesProducer`.
**t != KafkaTopic::Outcomes && **t != KafkaTopic::OutcomesBilling
}) {
let kafka_configs = config.kafka_configs(*topic)?;
client_builder = client_builder
.add_kafka_topic_config(*topic, &kafka_configs, config.kafka_validate_topics())
.map_err(|e| ServiceError::Kafka(e.to_string()))?;
}
Ok(Self {
client: client_builder.build(),
})
}
}
/// Publishes an [`Envelope`](crate::envelope::Envelope) to the Sentry core application through Kafka topics.
#[derive(Debug)]
pub struct StoreEnvelope {
pub envelope: ManagedEnvelope,
}
/// Publishes a list of [`Bucket`]s to the Sentry core application through Kafka topics.
#[derive(Clone, Debug)]
pub struct StoreMetrics {
pub buckets: Vec<Bucket>,
pub scoping: Scoping,
pub retention: u16,
}
/// Publishes a log item to the Sentry core application through Kafka.
#[derive(Debug)]
pub struct StoreTraceItem {
/// The final trace item which will be produced to Kafka.
pub trace_item: TraceItem,
}
impl Counted for StoreTraceItem {
fn quantities(&self) -> Quantities {
self.trace_item.quantities()
}
}
/// Publishes a span item to the Sentry core application through Kafka.
#[derive(Debug)]
pub struct StoreSpanV2 {
/// Routing key to assign a Kafka partition.
pub routing_key: Option<Uuid>,
/// Default retention of the span.
pub retention_days: u16,
/// Downsampled retention of the span.
pub downsampled_retention_days: u16,
/// The final Sentry compatible span item.
pub item: SpanV2,
}
impl Counted for StoreSpanV2 {
fn quantities(&self) -> Quantities {
smallvec::smallvec![(DataCategory::SpanIndexed, 1)]
}
}
/// Publishes a singular profile chunk to Kafka.
#[derive(Debug)]
pub struct StoreProfileChunk {
/// Default retention of the span.
pub retention_days: u16,
/// The serialized profile chunk payload.
pub payload: Bytes,
/// Outcome quantities associated with this profile.
///
/// Quantities are different for backend and ui profile chunks.
pub quantities: Quantities,
}
impl Counted for StoreProfileChunk {
fn quantities(&self) -> Quantities {
self.quantities.clone()
}
}
/// A replay to be stored to Kafka.
#[derive(Debug)]
pub struct StoreReplay {
/// The event ID.
pub event_id: EventId,
/// Number of days to retain.
pub retention_days: u16,
/// The recording payload (rrweb data).
pub recording: Bytes,
/// Optional replay event payload (JSON).
pub event: Option<Bytes>,
/// Optional replay video.
pub video: Option<Bytes>,
/// Outcome quantities associated with this replay.
///
/// Quantities are different for web and native replays.
pub quantities: Quantities,
}
impl Counted for StoreReplay {
fn quantities(&self) -> Quantities {
self.quantities.clone()
}
}
/// An attachment to be stored to Kafka.
#[derive(Debug)]
pub struct StoreAttachment {
/// The event ID.
pub event_id: EventId,
/// That attachment item.
pub attachment: Item,
/// Outcome quantities associated with this attachment.
pub quantities: Quantities,
}
impl Counted for StoreAttachment {
fn quantities(&self) -> Quantities {
self.quantities.clone()
}
}
/// The asynchronous thread pool used for scheduling storing tasks in the envelope store.
pub type StoreServicePool = AsyncPool<BoxFuture<'static, ()>>;
/// Service interface for the [`StoreEnvelope`] message.
#[derive(Debug)]
pub enum Store {
/// An envelope containing a mixture of items.
///
/// Note: Some envelope items are not supported to be submitted at all or through an envelope,
/// for example logs must be submitted via [`Self::TraceItem`] instead.
///
/// Long term this variant is going to be replaced with fully typed variants of items which can
/// be stored instead.
Envelope(StoreEnvelope),
/// Aggregated generic metrics.
Metrics(StoreMetrics),
/// A singular [`TraceItem`].
TraceItem(Managed<StoreTraceItem>),
/// A singular Span.
Span(Managed<Box<StoreSpanV2>>),
/// A singular profile chunk.
ProfileChunk(Managed<StoreProfileChunk>),
/// A singular replay.
Replay(Managed<StoreReplay>),
/// A singular attachment.
Attachment(Managed<StoreAttachment>),
}
impl Store {
/// Returns the name of the message variant.
fn variant(&self) -> &'static str {
match self {
Store::Envelope(_) => "envelope",
Store::Metrics(_) => "metrics",
Store::TraceItem(_) => "trace_item",
Store::Span(_) => "span",
Store::ProfileChunk(_) => "profile_chunk",
Store::Replay(_) => "replay",
Store::Attachment(_) => "attachment",
}
}
}
impl Interface for Store {}
impl FromMessage<StoreEnvelope> for Store {
type Response = NoResponse;
fn from_message(message: StoreEnvelope, _: ()) -> Self {
Self::Envelope(message)
}
}
impl FromMessage<StoreMetrics> for Store {
type Response = NoResponse;
fn from_message(message: StoreMetrics, _: ()) -> Self {
Self::Metrics(message)
}
}
impl FromMessage<Managed<StoreTraceItem>> for Store {
type Response = NoResponse;
fn from_message(message: Managed<StoreTraceItem>, _: ()) -> Self {
Self::TraceItem(message)
}
}
impl FromMessage<Managed<Box<StoreSpanV2>>> for Store {
type Response = NoResponse;
fn from_message(message: Managed<Box<StoreSpanV2>>, _: ()) -> Self {
Self::Span(message)
}
}
impl FromMessage<Managed<StoreProfileChunk>> for Store {
type Response = NoResponse;
fn from_message(message: Managed<StoreProfileChunk>, _: ()) -> Self {
Self::ProfileChunk(message)
}
}
impl FromMessage<Managed<StoreReplay>> for Store {
type Response = NoResponse;
fn from_message(message: Managed<StoreReplay>, _: ()) -> Self {
Self::Replay(message)
}
}
impl FromMessage<Managed<StoreAttachment>> for Store {
type Response = NoResponse;
fn from_message(message: Managed<StoreAttachment>, _: ()) -> Self {
Self::Attachment(message)
}
}
/// Service implementing the [`Store`] interface.
pub struct StoreService {
pool: StoreServicePool,
config: Arc<Config>,
global_config: GlobalConfigHandle,
outcome_aggregator: Addr<TrackOutcome>,
metric_outcomes: MetricOutcomes,
producer: Producer,
}
impl StoreService {
pub fn create(
pool: StoreServicePool,
config: Arc<Config>,
global_config: GlobalConfigHandle,
outcome_aggregator: Addr<TrackOutcome>,
metric_outcomes: MetricOutcomes,
) -> anyhow::Result<Self> {
let producer = Producer::create(&config)?;
Ok(Self {
pool,
config,
global_config,
outcome_aggregator,
metric_outcomes,
producer,
})
}
fn handle_message(&self, message: Store) {
let ty = message.variant();
relay_statsd::metric!(timer(RelayTimers::StoreServiceDuration), message = ty, {
match message {
Store::Envelope(message) => self.handle_store_envelope(message),
Store::Metrics(message) => self.handle_store_metrics(message),
Store::TraceItem(message) => self.handle_store_trace_item(message),
Store::Span(message) => self.handle_store_span(message),
Store::ProfileChunk(message) => self.handle_store_profile_chunk(message),
Store::Replay(message) => self.handle_store_replay(message),
Store::Attachment(message) => self.handle_store_attachment(message),
}
})
}
fn handle_store_envelope(&self, message: StoreEnvelope) {
let StoreEnvelope { mut envelope } = message;
let scoping = envelope.scoping();
match self.store_envelope(&mut envelope) {
Ok(()) => envelope.accept(),
Err(error) => {
envelope.reject(Outcome::Invalid(DiscardReason::Internal));
relay_log::error!(
error = &error as &dyn Error,
tags.project_key = %scoping.project_key,
"failed to store envelope"
);
}
}
}
fn store_envelope(&self, managed_envelope: &mut ManagedEnvelope) -> Result<(), StoreError> {
let mut envelope = managed_envelope.take_envelope();
let received_at = managed_envelope.received_at();
let scoping = managed_envelope.scoping();
let retention = envelope.retention();
let downsampled_retention = envelope.downsampled_retention();
let event_id = envelope.event_id();
let event_item = envelope.as_mut().take_item_by(|item| {
matches!(
item.ty(),
ItemType::Event | ItemType::Transaction | ItemType::Security
)
});
let event_type = event_item.as_ref().map(|item| item.ty());
// Some error events like minidumps need all attachment chunks to be processed _before_
// the event payload on the consumer side. Transaction attachments do not require this ordering
// guarantee, so they do not have to go to the same topic as their event payload.
let event_topic = if event_item.as_ref().map(|x| x.ty()) == Some(&ItemType::Transaction) {
KafkaTopic::Transactions
} else if envelope.get_item_by(is_slow_item).is_some() {
KafkaTopic::Attachments
} else {
KafkaTopic::Events
};
let send_individual_attachments = matches!(event_type, None | Some(&ItemType::Transaction));
let mut attachments = Vec::new();
for item in envelope.items() {
let content_type = item.content_type();
match item.ty() {
ItemType::Attachment => {
if let Some(attachment) = self.produce_attachment(
event_id.ok_or(StoreError::NoEventId)?,
scoping.project_id,
item,
send_individual_attachments,
)? {
attachments.push(attachment);
}
}
ItemType::UserReport => {
debug_assert!(event_topic == KafkaTopic::Attachments);
self.produce_user_report(
event_id.ok_or(StoreError::NoEventId)?,
scoping.project_id,
received_at,
item,
)?;
}
ItemType::UserReportV2 => {
let remote_addr = envelope.meta().client_addr().map(|addr| addr.to_string());
self.produce_user_report_v2(
event_id.ok_or(StoreError::NoEventId)?,
scoping.project_id,
received_at,
item,
remote_addr,
)?;
}
ItemType::Profile => self.produce_profile(
scoping.organization_id,
scoping.project_id,
scoping.key_id,
received_at,
retention,
item,
)?,
ItemType::CheckIn => {
let client = envelope.meta().client();
self.produce_check_in(scoping.project_id, received_at, client, retention, item)?
}
ItemType::Span if content_type == Some(ContentType::Json) => self.produce_span(
scoping,
received_at,
event_id,
retention,
downsampled_retention,
item,
)?,
ty @ ItemType::Log => {
debug_assert!(
false,
"received {ty} through an envelope, \
this item must be submitted via a specific store message instead"
);
relay_log::error!(
tags.project_key = %scoping.project_key,
"StoreService received unsupported item type '{ty}' in envelope"
);
}
other => {
let event_type = event_item.as_ref().map(|item| item.ty().as_str());
let item_types = envelope
.items()
.map(|item| item.ty().as_str())
.collect::<Vec<_>>();
let attachment_types = envelope
.items()
.map(|item| {
item.attachment_type()
.map(|t| t.to_string())
.unwrap_or_default()
})
.collect::<Vec<_>>();
relay_log::with_scope(
|scope| {
scope.set_extra("item_types", item_types.into());
scope.set_extra("attachment_types", attachment_types.into());
if other == &ItemType::FormData {
let payload = item.payload();
let form_data_keys = FormDataIter::new(&payload)
.map(|entry| entry.key())
.collect::<Vec<_>>();
scope.set_extra("form_data_keys", form_data_keys.into());
}
},
|| {
relay_log::error!(
tags.project_key = %scoping.project_key,
tags.event_type = event_type.unwrap_or("none"),
"StoreService received unexpected item type: {other}"
)
},
)
}
}
}
if let Some(event_item) = event_item {
let event_id = event_id.ok_or(StoreError::NoEventId)?;
let project_id = scoping.project_id;
let remote_addr = envelope.meta().client_addr().map(|addr| addr.to_string());
self.produce(
event_topic,
KafkaMessage::Event(EventKafkaMessage {
payload: event_item.payload(),
start_time: safe_timestamp(received_at),
event_id,
project_id,
remote_addr,
attachments,
}),
)?;
} else {
debug_assert!(attachments.is_empty());
}
Ok(())
}
fn handle_store_metrics(&self, message: StoreMetrics) {
let StoreMetrics {
buckets,
scoping,
retention,
} = message;
let batch_size = self.config.metrics_max_batch_size_bytes();
let mut error = None;
let global_config = self.global_config.current();
let mut encoder = BucketEncoder::new(&global_config);
let emit_sessions_to_eap = utils::is_rolled_out(
scoping.organization_id.value(),
global_config.options.sessions_eap_rollout_rate,
)
.is_keep();
let now = UnixTimestamp::now();
let mut delay_stats = ByNamespace::<(u64, u64, u64)>::default();
for mut bucket in buckets {
let namespace = encoder.prepare(&mut bucket);
if let Some(received_at) = bucket.metadata.received_at {
let delay = now.as_secs().saturating_sub(received_at.as_secs());
let (total, count, max) = delay_stats.get_mut(namespace);
*total += delay;
*count += 1;
*max = (*max).max(delay);
}
// Create a local bucket view to avoid splitting buckets unnecessarily. Since we produce
// each bucket separately, we only need to split buckets that exceed the size, but not
// batches.
for view in BucketsView::new(std::slice::from_ref(&bucket))
.by_size(batch_size)
.flatten()
{
let message = self.create_metric_message(
scoping.organization_id,
scoping.project_id,
&mut encoder,
namespace,
&view,
retention,
);
let result =
message.and_then(|message| self.send_metric_message(namespace, message));
let outcome = match result {
Ok(()) => Outcome::Accepted,
Err(e) => {
error.get_or_insert(e);
Outcome::Invalid(DiscardReason::Internal)
}
};
self.metric_outcomes.track(scoping, &[view], outcome);
}
if emit_sessions_to_eap
&& let Some(trace_item) = sessions::to_trace_item(scoping, bucket, retention)
{
let message = KafkaMessage::for_item(scoping, trace_item);
let _ = self.produce(KafkaTopic::Items, message);
}
}
if let Some(error) = error {
relay_log::error!(
error = &error as &dyn std::error::Error,
"failed to produce metric buckets: {error}"
);
}
for (namespace, (total, count, max)) in delay_stats {
if count == 0 {
continue;
}
metric!(
counter(RelayCounters::MetricDelaySum) += total,
namespace = namespace.as_str()
);
metric!(
counter(RelayCounters::MetricDelayCount) += count,
namespace = namespace.as_str()
);
metric!(
gauge(RelayGauges::MetricDelayMax) = max,
namespace = namespace.as_str()
);
}
}
fn handle_store_trace_item(&self, message: Managed<StoreTraceItem>) {
let scoping = message.scoping();
let received_at = message.received_at();
let eap_emits_outcomes = utils::is_rolled_out(
scoping.organization_id.value(),
self.global_config
.current()
.options
.eap_outcomes_rollout_rate,
)
.is_keep();
let outcomes = message.try_accept(|mut item| {
let outcomes = match eap_emits_outcomes {
true => None,
false => item.trace_item.outcomes.take(),
};
let message = KafkaMessage::for_item(scoping, item.trace_item);
self.produce(KafkaTopic::Items, message).map(|()| outcomes)
});
// Accepted outcomes when items have been successfully produced to rdkafka.
//
// This is only a temporary measure, long term these outcomes will be part of the trace
// item and emitted by Snuba to guarantee a delivery to storage.
if let Ok(Some(outcomes)) = outcomes {
for (category, quantity) in outcomes.quantities() {
self.outcome_aggregator.send(TrackOutcome {
category,
event_id: None,
outcome: Outcome::Accepted,
quantity: u32::try_from(quantity).unwrap_or(u32::MAX),
remote_addr: None,
scoping,
timestamp: received_at,
});
}
}
}
fn handle_store_span(&self, message: Managed<Box<StoreSpanV2>>) {
let scoping = message.scoping();
let received_at = message.received_at();
let relay_emits_accepted_outcome = !utils::is_rolled_out(
scoping.organization_id.value(),
self.global_config
.current()
.options
.eap_span_outcomes_rollout_rate,
)
.is_keep();
let meta = SpanMeta {
organization_id: scoping.organization_id,
project_id: scoping.project_id,
key_id: scoping.key_id,
event_id: None,
retention_days: message.retention_days,
downsampled_retention_days: message.downsampled_retention_days,
received: datetime_to_timestamp(received_at),
accepted_outcome_emitted: relay_emits_accepted_outcome,
};
let result = message.try_accept(|span| {
let item = Annotated::new(span.item);
let message = KafkaMessage::SpanV2 {
routing_key: span.routing_key,
headers: BTreeMap::from([(
"project_id".to_owned(),
scoping.project_id.to_string(),
)]),
message: SpanKafkaMessage {
meta,
span: SerializableAnnotated(&item),
},
};
self.produce(KafkaTopic::Spans, message)
});
if result.is_ok() {
relay_statsd::metric!(
counter(RelayCounters::SpanV2Produced) += 1,
via = "processing"
);
if relay_emits_accepted_outcome {
// XXX: Temporarily produce span outcomes. Keep in sync with either EAP
// or the segments consumer, depending on which will produce outcomes later.
self.outcome_aggregator.send(TrackOutcome {
category: DataCategory::SpanIndexed,
event_id: None,
outcome: Outcome::Accepted,
quantity: 1,
remote_addr: None,
scoping,
timestamp: received_at,
});
}
}
}
fn handle_store_profile_chunk(&self, message: Managed<StoreProfileChunk>) {
let scoping = message.scoping();
let received_at = message.received_at();
let _ = message.try_accept(|message| {
let message = ProfileChunkKafkaMessage {
organization_id: scoping.organization_id,
project_id: scoping.project_id,
received: safe_timestamp(received_at),
retention_days: message.retention_days,
headers: BTreeMap::from([(
"project_id".to_owned(),
scoping.project_id.to_string(),
)]),
payload: message.payload,
};
self.produce(KafkaTopic::Profiles, KafkaMessage::ProfileChunk(message))
});
}
fn handle_store_replay(&self, message: Managed<StoreReplay>) {
let scoping = message.scoping();
let received_at = message.received_at();
let _ = message.try_accept(|replay| {
let kafka_msg =
KafkaMessage::ReplayRecordingNotChunked(ReplayRecordingNotChunkedKafkaMessage {
replay_id: replay.event_id,
key_id: scoping.key_id,
org_id: scoping.organization_id,
project_id: scoping.project_id,
received: safe_timestamp(received_at),
retention_days: replay.retention_days,
payload: &replay.recording,
replay_event: replay.event.as_deref(),
replay_video: replay.video.as_deref(),
// Hardcoded to `true` to indicate to the consumer that it should always publish the
// replay_event as relay no longer does it.
relay_snuba_publish_disabled: true,
});
self.produce(KafkaTopic::ReplayRecordings, kafka_msg)
});
}
fn handle_store_attachment(&self, message: Managed<StoreAttachment>) {
let scoping = message.scoping();
let _ = message.try_accept(|attachment| {
let result = self.produce_attachment(
attachment.event_id,
scoping.project_id,
&attachment.attachment,
// Hardcoded to `true` since standalone attachments are 'individual attachments'.
true,
);
// Since we are sending an 'individual attachment' this function should never return a
// `ChunkedAttachment`.
debug_assert!(!matches!(result, Ok(Some(_))));
result
});
}
fn create_metric_message<'a>(
&self,
organization_id: OrganizationId,
project_id: ProjectId,
encoder: &'a mut BucketEncoder,
namespace: MetricNamespace,
view: &BucketView<'a>,
retention_days: u16,
) -> Result<MetricKafkaMessage<'a>, StoreError> {
let value = match view.value() {
BucketViewValue::Counter(c) => MetricValue::Counter(c),
BucketViewValue::Distribution(data) => MetricValue::Distribution(
encoder
.encode_distribution(namespace, data)
.map_err(StoreError::EncodingFailed)?,
),
BucketViewValue::Set(data) => MetricValue::Set(
encoder
.encode_set(namespace, data)
.map_err(StoreError::EncodingFailed)?,
),
BucketViewValue::Gauge(g) => MetricValue::Gauge(g),
};
Ok(MetricKafkaMessage {
org_id: organization_id,
project_id,
name: view.name(),
value,
timestamp: view.timestamp(),
tags: view.tags(),
retention_days,
received_at: view.metadata().received_at,
})
}
fn produce(
&self,
topic: KafkaTopic,
// Takes message by value to ensure it is not being produced twice.
message: KafkaMessage,
) -> Result<(), StoreError> {
relay_log::trace!("Sending kafka message of type {}", message.variant());
let topic_name = self
.producer
.client
.send_message(topic, &message)
.inspect_err(|err| {
relay_log::error!(
error = err as &dyn Error,
tags.topic = ?topic,
tags.message = message.variant(),
"failed to produce to Kafka"
)
})?;
match &message {
KafkaMessage::Metric {
message: metric, ..
} => {
metric!(
counter(RelayCounters::ProcessingMessageProduced) += 1,
event_type = message.variant(),
topic = topic_name,
metric_type = metric.value.variant(),
metric_encoding = metric.value.encoding().unwrap_or(""),
);
}
KafkaMessage::ReplayRecordingNotChunked(replay) => {
let has_video = replay.replay_video.is_some();
metric!(
counter(RelayCounters::ProcessingMessageProduced) += 1,
event_type = message.variant(),
topic = topic_name,
has_video = bool_to_str(has_video),
);
}
message => {
metric!(
counter(RelayCounters::ProcessingMessageProduced) += 1,
event_type = message.variant(),
topic = topic_name,
);
}
}
Ok(())
}
/// Produces Kafka messages for the content and metadata of an attachment item.
///
/// The `send_individual_attachments` controls whether the metadata of an attachment
/// is produced directly as an individual `attachment` message, or returned from this function
/// to be later sent as part of an `event` message.
///
/// Attachment contents are chunked and sent as multiple `attachment_chunk` messages,
/// unless the `send_individual_attachments` flag is set, and the content is small enough
/// to fit inside a message.
/// In that case, no `attachment_chunk` is produced, but the content is sent as part
/// of the `attachment` message instead.
fn produce_attachment(
&self,
event_id: EventId,
project_id: ProjectId,
item: &Item,
send_individual_attachments: bool,
) -> Result<Option<ChunkedAttachment>, StoreError> {
let id = Uuid::new_v4().to_string();
let payload = item.payload();
let size = item.len();
let max_chunk_size = self.config.attachment_chunk_size();
let payload = if size == 0 {
AttachmentPayload::Chunked(0)
} else if let Some(stored_key) = item.stored_key() {
AttachmentPayload::Stored(stored_key.into())
} else if send_individual_attachments && size < max_chunk_size {
// When sending individual attachments, and we have a single chunk, we want to send the
// `data` inline in the `attachment` message.
// This avoids a needless roundtrip through the attachments cache on the Sentry side.
AttachmentPayload::Inline(payload)
} else {
let mut chunk_index = 0;
let mut offset = 0;
// This skips chunks for empty attachments. The consumer does not require chunks for
// empty attachments. `chunks` will be `0` in this case.
while offset < size {
let chunk_size = std::cmp::min(max_chunk_size, size - offset);
let chunk_message = AttachmentChunkKafkaMessage {
payload: payload.slice(offset..offset + chunk_size),
event_id,
project_id,
id: id.clone(),
chunk_index,
};
self.produce(
KafkaTopic::Attachments,
KafkaMessage::AttachmentChunk(chunk_message),
)?;
offset += chunk_size;
chunk_index += 1;
}
// The chunk_index is incremented after every loop iteration. After we exit the loop, it
// is one larger than the last chunk, so it is equal to the number of chunks.
AttachmentPayload::Chunked(chunk_index)
};
let attachment = ChunkedAttachment {
id,
name: match item.filename() {
Some(name) => name.to_owned(),
None => UNNAMED_ATTACHMENT.to_owned(),
},
rate_limited: item.rate_limited(),
content_type: item.raw_content_type().map(|s| s.to_ascii_lowercase()),
attachment_type: item.attachment_type().unwrap_or_default(),
size,
payload,
};
if send_individual_attachments {
let message = KafkaMessage::Attachment(AttachmentKafkaMessage {
event_id,
project_id,
attachment,
});
self.produce(KafkaTopic::Attachments, message)?;
Ok(None)
} else {
Ok(Some(attachment))
}
}
fn produce_user_report(
&self,
event_id: EventId,
project_id: ProjectId,
received_at: DateTime<Utc>,
item: &Item,
) -> Result<(), StoreError> {
let message = KafkaMessage::UserReport(UserReportKafkaMessage {
project_id,
event_id,
start_time: safe_timestamp(received_at),
payload: item.payload(),
});
self.produce(KafkaTopic::Attachments, message)
}
fn produce_user_report_v2(
&self,
event_id: EventId,
project_id: ProjectId,
received_at: DateTime<Utc>,
item: &Item,
remote_addr: Option<String>,
) -> Result<(), StoreError> {
let message = KafkaMessage::Event(EventKafkaMessage {
project_id,
event_id,
payload: item.payload(),
start_time: safe_timestamp(received_at),
remote_addr,
attachments: vec![],
});
self.produce(KafkaTopic::Feedback, message)
}
fn send_metric_message(
&self,
namespace: MetricNamespace,
message: MetricKafkaMessage,