relay_server/services/
store.rs

1//! This module contains the service that forwards events and attachments to the Sentry store.
2//! The service uses Kafka topics to forward data to Sentry
3
4use std::borrow::Cow;
5use std::collections::BTreeMap;
6use std::error::Error;
7use std::sync::Arc;
8
9use bytes::Bytes;
10use chrono::{DateTime, Utc};
11use futures::FutureExt;
12use futures::future::BoxFuture;
13use prost::Message as _;
14use sentry_protos::snuba::v1::{TraceItem, TraceItemType};
15use serde::{Deserialize, Serialize};
16use serde_json::value::RawValue;
17use uuid::Uuid;
18
19use relay_base_schema::data_category::DataCategory;
20use relay_base_schema::organization::OrganizationId;
21use relay_base_schema::project::ProjectId;
22use relay_common::time::UnixTimestamp;
23use relay_config::Config;
24use relay_event_schema::protocol::{EventId, SpanV2, datetime_to_timestamp};
25use relay_kafka::{ClientError, KafkaClient, KafkaTopic, Message, SerializationOutput};
26use relay_metrics::{
27    Bucket, BucketView, BucketViewValue, BucketsView, ByNamespace, GaugeValue, MetricName,
28    MetricNamespace, SetView,
29};
30use relay_protocol::{Annotated, FiniteF64, SerializableAnnotated};
31use relay_quotas::Scoping;
32use relay_statsd::metric;
33use relay_system::{Addr, FromMessage, Interface, NoResponse, Service};
34use relay_threading::AsyncPool;
35
36use crate::envelope::{AttachmentType, ContentType, Item, ItemType};
37use crate::managed::{Counted, Managed, ManagedEnvelope, OutcomeError, Quantities, TypedEnvelope};
38use crate::metrics::{ArrayEncoding, BucketEncoder, MetricOutcomes};
39use crate::service::ServiceError;
40use crate::services::global_config::GlobalConfigHandle;
41use crate::services::outcome::{DiscardItemType, DiscardReason, Outcome, TrackOutcome};
42use crate::services::processor::Processed;
43use crate::statsd::{RelayCounters, RelayGauges, RelayTimers};
44use crate::utils::{self, FormDataIter};
45
46/// Fallback name used for attachment items without a `filename` header.
47const UNNAMED_ATTACHMENT: &str = "Unnamed Attachment";
48
49#[derive(Debug, thiserror::Error)]
50pub enum StoreError {
51    #[error("failed to send the message to kafka: {0}")]
52    SendFailed(#[from] ClientError),
53    #[error("failed to encode data: {0}")]
54    EncodingFailed(std::io::Error),
55    #[error("failed to store event because event id was missing")]
56    NoEventId,
57}
58
59impl OutcomeError for StoreError {
60    type Error = Self;
61
62    fn consume(self) -> (Option<Outcome>, Self::Error) {
63        (Some(Outcome::Invalid(DiscardReason::Internal)), self)
64    }
65}
66
67struct Producer {
68    client: KafkaClient,
69}
70
71impl Producer {
72    pub fn create(config: &Config) -> anyhow::Result<Self> {
73        let mut client_builder = KafkaClient::builder();
74
75        for topic in KafkaTopic::iter().filter(|t| {
76            // Outcomes should not be sent from the store forwarder.
77            // See `KafkaOutcomesProducer`.
78            **t != KafkaTopic::Outcomes && **t != KafkaTopic::OutcomesBilling
79        }) {
80            let kafka_configs = config.kafka_configs(*topic)?;
81            client_builder = client_builder
82                .add_kafka_topic_config(*topic, &kafka_configs, config.kafka_validate_topics())
83                .map_err(|e| ServiceError::Kafka(e.to_string()))?;
84        }
85
86        Ok(Self {
87            client: client_builder.build(),
88        })
89    }
90}
91
92/// Publishes an [`Envelope`](crate::envelope::Envelope) to the Sentry core application through Kafka topics.
93#[derive(Debug)]
94pub struct StoreEnvelope {
95    pub envelope: TypedEnvelope<Processed>,
96}
97
98/// Publishes a list of [`Bucket`]s to the Sentry core application through Kafka topics.
99#[derive(Clone, Debug)]
100pub struct StoreMetrics {
101    pub buckets: Vec<Bucket>,
102    pub scoping: Scoping,
103    pub retention: u16,
104}
105
106/// Publishes a log item to the Sentry core application through Kafka.
107#[derive(Debug)]
108pub struct StoreTraceItem {
109    /// The final trace item which will be produced to Kafka.
110    pub trace_item: TraceItem,
111    /// Outcomes to be emitted when successfully producing the item to Kafka.
112    ///
113    /// Note: this is only a temporary measure, long term these outcomes will be part of the trace
114    /// item and emitted by Snuba to guarantee a delivery to storage.
115    pub quantities: Quantities,
116}
117
118impl Counted for StoreTraceItem {
119    fn quantities(&self) -> Quantities {
120        self.quantities.clone()
121    }
122}
123
124/// Publishes a span item to the Sentry core application through Kafka.
125#[derive(Debug)]
126pub struct StoreSpanV2 {
127    /// Routing key to assign a Kafka partition.
128    pub routing_key: Option<Uuid>,
129    /// Default retention of the span.
130    pub retention_days: u16,
131    /// Downsampled retention of the span.
132    pub downsampled_retention_days: u16,
133    /// The final Sentry compatible span item.
134    pub item: SpanV2,
135}
136
137impl Counted for StoreSpanV2 {
138    fn quantities(&self) -> Quantities {
139        smallvec::smallvec![(DataCategory::SpanIndexed, 1)]
140    }
141}
142
143/// The asynchronous thread pool used for scheduling storing tasks in the envelope store.
144pub type StoreServicePool = AsyncPool<BoxFuture<'static, ()>>;
145
146/// Service interface for the [`StoreEnvelope`] message.
147#[derive(Debug)]
148pub enum Store {
149    /// An envelope containing a mixture of items.
150    ///
151    /// Note: Some envelope items are not supported to be submitted at all or through an envelope,
152    /// for example logs must be submitted via [`Self::TraceItem`] instead.
153    ///
154    /// Long term this variant is going to be replaced with fully typed variants of items which can
155    /// be stored instead.
156    Envelope(StoreEnvelope),
157    /// Aggregated generic metrics.
158    Metrics(StoreMetrics),
159    /// A singular [`TraceItem`].
160    TraceItem(Managed<StoreTraceItem>),
161    /// A singular Span.
162    Span(Managed<Box<StoreSpanV2>>),
163}
164
165impl Store {
166    /// Returns the name of the message variant.
167    fn variant(&self) -> &'static str {
168        match self {
169            Store::Envelope(_) => "envelope",
170            Store::Metrics(_) => "metrics",
171            Store::TraceItem(_) => "log",
172            Store::Span(_) => "span",
173        }
174    }
175}
176
177impl Interface for Store {}
178
179impl FromMessage<StoreEnvelope> for Store {
180    type Response = NoResponse;
181
182    fn from_message(message: StoreEnvelope, _: ()) -> Self {
183        Self::Envelope(message)
184    }
185}
186
187impl FromMessage<StoreMetrics> for Store {
188    type Response = NoResponse;
189
190    fn from_message(message: StoreMetrics, _: ()) -> Self {
191        Self::Metrics(message)
192    }
193}
194
195impl FromMessage<Managed<StoreTraceItem>> for Store {
196    type Response = NoResponse;
197
198    fn from_message(message: Managed<StoreTraceItem>, _: ()) -> Self {
199        Self::TraceItem(message)
200    }
201}
202
203impl FromMessage<Managed<Box<StoreSpanV2>>> for Store {
204    type Response = NoResponse;
205
206    fn from_message(message: Managed<Box<StoreSpanV2>>, _: ()) -> Self {
207        Self::Span(message)
208    }
209}
210
211/// Service implementing the [`Store`] interface.
212pub struct StoreService {
213    pool: StoreServicePool,
214    config: Arc<Config>,
215    global_config: GlobalConfigHandle,
216    outcome_aggregator: Addr<TrackOutcome>,
217    metric_outcomes: MetricOutcomes,
218    producer: Producer,
219}
220
221impl StoreService {
222    pub fn create(
223        pool: StoreServicePool,
224        config: Arc<Config>,
225        global_config: GlobalConfigHandle,
226        outcome_aggregator: Addr<TrackOutcome>,
227        metric_outcomes: MetricOutcomes,
228    ) -> anyhow::Result<Self> {
229        let producer = Producer::create(&config)?;
230        Ok(Self {
231            pool,
232            config,
233            global_config,
234            outcome_aggregator,
235            metric_outcomes,
236            producer,
237        })
238    }
239
240    fn handle_message(&self, message: Store) {
241        let ty = message.variant();
242        relay_statsd::metric!(timer(RelayTimers::StoreServiceDuration), message = ty, {
243            match message {
244                Store::Envelope(message) => self.handle_store_envelope(message),
245                Store::Metrics(message) => self.handle_store_metrics(message),
246                Store::TraceItem(message) => self.handle_store_trace_item(message),
247                Store::Span(message) => self.handle_store_span(message),
248            }
249        })
250    }
251
252    fn handle_store_envelope(&self, message: StoreEnvelope) {
253        let StoreEnvelope {
254            envelope: mut managed,
255        } = message;
256
257        let scoping = managed.scoping();
258
259        match self.store_envelope(&mut managed) {
260            Ok(()) => managed.accept(),
261            Err(error) => {
262                managed.reject(Outcome::Invalid(DiscardReason::Internal));
263                relay_log::error!(
264                    error = &error as &dyn Error,
265                    tags.project_key = %scoping.project_key,
266                    "failed to store envelope"
267                );
268            }
269        }
270    }
271
272    fn store_envelope(&self, managed_envelope: &mut ManagedEnvelope) -> Result<(), StoreError> {
273        let mut envelope = managed_envelope.take_envelope();
274        let received_at = managed_envelope.received_at();
275        let scoping = managed_envelope.scoping();
276
277        let retention = envelope.retention();
278        let downsampled_retention = envelope.downsampled_retention();
279
280        let event_id = envelope.event_id();
281        let event_item = envelope.as_mut().take_item_by(|item| {
282            matches!(
283                item.ty(),
284                ItemType::Event | ItemType::Transaction | ItemType::Security
285            )
286        });
287        let event_type = event_item.as_ref().map(|item| item.ty());
288
289        // Some error events like minidumps need all attachment chunks to be processed _before_
290        // the event payload on the consumer side. Transaction attachments do not require this ordering
291        // guarantee, so they do not have to go to the same topic as their event payload.
292        let event_topic = if event_item.as_ref().map(|x| x.ty()) == Some(&ItemType::Transaction) {
293            KafkaTopic::Transactions
294        } else if envelope.get_item_by(is_slow_item).is_some() {
295            KafkaTopic::Attachments
296        } else {
297            KafkaTopic::Events
298        };
299
300        let send_individual_attachments = matches!(event_type, None | Some(&ItemType::Transaction));
301
302        let mut attachments = Vec::new();
303        let mut replay_event = None;
304        let mut replay_recording = None;
305
306        let options = &self.global_config.current().options;
307
308        // Whether Relay will submit the replay-event to snuba or not.
309        let replay_relay_snuba_publish_disabled =
310            utils::sample(options.replay_relay_snuba_publish_disabled_sample_rate).is_keep();
311
312        for item in envelope.items() {
313            let content_type = item.content_type();
314            match item.ty() {
315                ItemType::Attachment => {
316                    if let Some(attachment) = self.produce_attachment(
317                        event_id.ok_or(StoreError::NoEventId)?,
318                        scoping.project_id,
319                        item,
320                        send_individual_attachments,
321                    )? {
322                        attachments.push(attachment);
323                    }
324                }
325                ItemType::UserReport => {
326                    debug_assert!(event_topic == KafkaTopic::Attachments);
327                    self.produce_user_report(
328                        event_id.ok_or(StoreError::NoEventId)?,
329                        scoping.project_id,
330                        received_at,
331                        item,
332                    )?;
333                }
334                ItemType::UserReportV2 => {
335                    let remote_addr = envelope.meta().client_addr().map(|addr| addr.to_string());
336                    self.produce_user_report_v2(
337                        event_id.ok_or(StoreError::NoEventId)?,
338                        scoping.project_id,
339                        received_at,
340                        item,
341                        remote_addr,
342                    )?;
343                }
344                ItemType::Profile => self.produce_profile(
345                    scoping.organization_id,
346                    scoping.project_id,
347                    scoping.key_id,
348                    received_at,
349                    retention,
350                    item,
351                )?,
352                ItemType::ReplayVideo => {
353                    self.produce_replay_video(
354                        event_id,
355                        scoping,
356                        item.payload(),
357                        received_at,
358                        retention,
359                        replay_relay_snuba_publish_disabled,
360                    )?;
361                }
362                ItemType::ReplayRecording => {
363                    replay_recording = Some(item);
364                }
365                ItemType::ReplayEvent => {
366                    replay_event = Some(item);
367                    self.produce_replay_event(
368                        event_id.ok_or(StoreError::NoEventId)?,
369                        scoping.project_id,
370                        received_at,
371                        retention,
372                        &item.payload(),
373                        replay_relay_snuba_publish_disabled,
374                    )?;
375                }
376                ItemType::CheckIn => {
377                    let client = envelope.meta().client();
378                    self.produce_check_in(scoping.project_id, received_at, client, retention, item)?
379                }
380                ItemType::Span if content_type == Some(&ContentType::Json) => self.produce_span(
381                    scoping,
382                    received_at,
383                    event_id,
384                    retention,
385                    downsampled_retention,
386                    item,
387                )?,
388                ty @ ItemType::Log => {
389                    debug_assert!(
390                        false,
391                        "received {ty} through an envelope, \
392                        this item must be submitted via a specific store message instead"
393                    );
394                    relay_log::error!(
395                        tags.project_key = %scoping.project_key,
396                        "StoreService received unsupported item type '{ty}' in envelope"
397                    );
398                }
399                ItemType::ProfileChunk => self.produce_profile_chunk(
400                    scoping.organization_id,
401                    scoping.project_id,
402                    received_at,
403                    retention,
404                    item,
405                )?,
406                other => {
407                    let event_type = event_item.as_ref().map(|item| item.ty().as_str());
408                    let item_types = envelope
409                        .items()
410                        .map(|item| item.ty().as_str())
411                        .collect::<Vec<_>>();
412                    let attachment_types = envelope
413                        .items()
414                        .map(|item| {
415                            item.attachment_type()
416                                .map(|t| t.to_string())
417                                .unwrap_or_default()
418                        })
419                        .collect::<Vec<_>>();
420
421                    relay_log::with_scope(
422                        |scope| {
423                            scope.set_extra("item_types", item_types.into());
424                            scope.set_extra("attachment_types", attachment_types.into());
425                            if other == &ItemType::FormData {
426                                let payload = item.payload();
427                                let form_data_keys = FormDataIter::new(&payload)
428                                    .map(|entry| entry.key())
429                                    .collect::<Vec<_>>();
430                                scope.set_extra("form_data_keys", form_data_keys.into());
431                            }
432                        },
433                        || {
434                            relay_log::error!(
435                                tags.project_key = %scoping.project_key,
436                                tags.event_type = event_type.unwrap_or("none"),
437                                "StoreService received unexpected item type: {other}"
438                            )
439                        },
440                    )
441                }
442            }
443        }
444
445        if let Some(recording) = replay_recording {
446            // If a recording item type was seen we produce it to Kafka with the replay-event
447            // payload (should it have been provided).
448            //
449            // The replay_video value is always specified as `None`. We do not allow separate
450            // item types for `ReplayVideo` events.
451            let replay_event = replay_event.map(|rv| rv.payload());
452            self.produce_replay_recording(
453                event_id,
454                scoping,
455                &recording.payload(),
456                replay_event.as_deref(),
457                None,
458                received_at,
459                retention,
460                replay_relay_snuba_publish_disabled,
461            )?;
462        }
463
464        if let Some(event_item) = event_item {
465            let event_id = event_id.ok_or(StoreError::NoEventId)?;
466            let project_id = scoping.project_id;
467            let remote_addr = envelope.meta().client_addr().map(|addr| addr.to_string());
468
469            self.produce(
470                event_topic,
471                KafkaMessage::Event(EventKafkaMessage {
472                    payload: event_item.payload(),
473                    start_time: safe_timestamp(received_at),
474                    event_id,
475                    project_id,
476                    remote_addr,
477                    attachments,
478                }),
479            )?;
480        } else {
481            debug_assert!(attachments.is_empty());
482        }
483
484        Ok(())
485    }
486
487    fn handle_store_metrics(&self, message: StoreMetrics) {
488        let StoreMetrics {
489            buckets,
490            scoping,
491            retention,
492        } = message;
493
494        let batch_size = self.config.metrics_max_batch_size_bytes();
495        let mut error = None;
496
497        let global_config = self.global_config.current();
498        let mut encoder = BucketEncoder::new(&global_config);
499
500        let now = UnixTimestamp::now();
501        let mut delay_stats = ByNamespace::<(u64, u64, u64)>::default();
502
503        for mut bucket in buckets {
504            let namespace = encoder.prepare(&mut bucket);
505
506            if let Some(received_at) = bucket.metadata.received_at {
507                let delay = now.as_secs().saturating_sub(received_at.as_secs());
508                let (total, count, max) = delay_stats.get_mut(namespace);
509                *total += delay;
510                *count += 1;
511                *max = (*max).max(delay);
512            }
513
514            // Create a local bucket view to avoid splitting buckets unnecessarily. Since we produce
515            // each bucket separately, we only need to split buckets that exceed the size, but not
516            // batches.
517            for view in BucketsView::new(std::slice::from_ref(&bucket))
518                .by_size(batch_size)
519                .flatten()
520            {
521                let message = self.create_metric_message(
522                    scoping.organization_id,
523                    scoping.project_id,
524                    &mut encoder,
525                    namespace,
526                    &view,
527                    retention,
528                );
529
530                let result =
531                    message.and_then(|message| self.send_metric_message(namespace, message));
532
533                let outcome = match result {
534                    Ok(()) => Outcome::Accepted,
535                    Err(e) => {
536                        error.get_or_insert(e);
537                        Outcome::Invalid(DiscardReason::Internal)
538                    }
539                };
540
541                self.metric_outcomes.track(scoping, &[view], outcome);
542            }
543        }
544
545        if let Some(error) = error {
546            relay_log::error!(
547                error = &error as &dyn std::error::Error,
548                "failed to produce metric buckets: {error}"
549            );
550        }
551
552        for (namespace, (total, count, max)) in delay_stats {
553            if count == 0 {
554                continue;
555            }
556            metric!(
557                counter(RelayCounters::MetricDelaySum) += total,
558                namespace = namespace.as_str()
559            );
560            metric!(
561                counter(RelayCounters::MetricDelayCount) += count,
562                namespace = namespace.as_str()
563            );
564            metric!(
565                gauge(RelayGauges::MetricDelayMax) = max,
566                namespace = namespace.as_str()
567            );
568        }
569    }
570
571    fn handle_store_trace_item(&self, message: Managed<StoreTraceItem>) {
572        let scoping = message.scoping();
573        let received_at = message.received_at();
574
575        let quantities = message.try_accept(|item| {
576            let item_type = item.trace_item.item_type();
577            let message = KafkaMessage::Item {
578                headers: BTreeMap::from([
579                    ("project_id".to_owned(), scoping.project_id.to_string()),
580                    ("item_type".to_owned(), (item_type as i32).to_string()),
581                ]),
582                message: item.trace_item,
583                item_type,
584            };
585
586            self.produce(KafkaTopic::Items, message)
587                .map(|()| item.quantities)
588        });
589
590        // Accepted outcomes when items have been successfully produced to rdkafka.
591        //
592        // This is only a temporary measure, long term these outcomes will be part of the trace
593        // item and emitted by Snuba to guarantee a delivery to storage.
594        if let Ok(quantities) = quantities {
595            for (category, quantity) in quantities {
596                self.outcome_aggregator.send(TrackOutcome {
597                    category,
598                    event_id: None,
599                    outcome: Outcome::Accepted,
600                    quantity: u32::try_from(quantity).unwrap_or(u32::MAX),
601                    remote_addr: None,
602                    scoping,
603                    timestamp: received_at,
604                });
605            }
606        }
607    }
608
609    fn handle_store_span(&self, message: Managed<Box<StoreSpanV2>>) {
610        let scoping = message.scoping();
611        let received_at = message.received_at();
612
613        let meta = SpanMeta {
614            organization_id: scoping.organization_id,
615            project_id: scoping.project_id,
616            key_id: scoping.key_id,
617            event_id: None,
618            retention_days: message.retention_days,
619            downsampled_retention_days: message.downsampled_retention_days,
620            received: datetime_to_timestamp(received_at),
621        };
622
623        let result = message.try_accept(|span| {
624            let item = Annotated::new(span.item);
625            let message = KafkaMessage::SpanV2 {
626                routing_key: span.routing_key,
627                headers: BTreeMap::from([(
628                    "project_id".to_owned(),
629                    scoping.project_id.to_string(),
630                )]),
631                message: SpanKafkaMessage {
632                    meta,
633                    span: SerializableAnnotated(&item),
634                },
635            };
636
637            self.produce(KafkaTopic::Spans, message)
638        });
639
640        match result {
641            Ok(()) => {
642                relay_statsd::metric!(
643                    counter(RelayCounters::SpanV2Produced) += 1,
644                    via = "processing"
645                );
646
647                // XXX: Temporarily produce span outcomes. Keep in sync with either EAP
648                // or the segments consumer, depending on which will produce outcomes later.
649                self.outcome_aggregator.send(TrackOutcome {
650                    category: DataCategory::SpanIndexed,
651                    event_id: None,
652                    outcome: Outcome::Accepted,
653                    quantity: 1,
654                    remote_addr: None,
655                    scoping,
656                    timestamp: received_at,
657                });
658            }
659            Err(error) => {
660                relay_log::error!(
661                    error = &error as &dyn Error,
662                    tags.project_key = %scoping.project_key,
663                    "failed to store span"
664                );
665            }
666        }
667    }
668
669    fn create_metric_message<'a>(
670        &self,
671        organization_id: OrganizationId,
672        project_id: ProjectId,
673        encoder: &'a mut BucketEncoder,
674        namespace: MetricNamespace,
675        view: &BucketView<'a>,
676        retention_days: u16,
677    ) -> Result<MetricKafkaMessage<'a>, StoreError> {
678        let value = match view.value() {
679            BucketViewValue::Counter(c) => MetricValue::Counter(c),
680            BucketViewValue::Distribution(data) => MetricValue::Distribution(
681                encoder
682                    .encode_distribution(namespace, data)
683                    .map_err(StoreError::EncodingFailed)?,
684            ),
685            BucketViewValue::Set(data) => MetricValue::Set(
686                encoder
687                    .encode_set(namespace, data)
688                    .map_err(StoreError::EncodingFailed)?,
689            ),
690            BucketViewValue::Gauge(g) => MetricValue::Gauge(g),
691        };
692
693        Ok(MetricKafkaMessage {
694            org_id: organization_id,
695            project_id,
696            name: view.name(),
697            value,
698            timestamp: view.timestamp(),
699            tags: view.tags(),
700            retention_days,
701            received_at: view.metadata().received_at,
702        })
703    }
704
705    fn produce(
706        &self,
707        topic: KafkaTopic,
708        // Takes message by value to ensure it is not being produced twice.
709        message: KafkaMessage,
710    ) -> Result<(), StoreError> {
711        relay_log::trace!("Sending kafka message of type {}", message.variant());
712
713        let topic_name = self.producer.client.send_message(topic, &message)?;
714
715        match &message {
716            KafkaMessage::Metric {
717                message: metric, ..
718            } => {
719                metric!(
720                    counter(RelayCounters::ProcessingMessageProduced) += 1,
721                    event_type = message.variant(),
722                    topic = topic_name,
723                    metric_type = metric.value.variant(),
724                    metric_encoding = metric.value.encoding().unwrap_or(""),
725                );
726            }
727            KafkaMessage::ReplayRecordingNotChunked(replay) => {
728                let has_video = replay.replay_video.is_some();
729
730                metric!(
731                    counter(RelayCounters::ProcessingMessageProduced) += 1,
732                    event_type = message.variant(),
733                    topic = topic_name,
734                    has_video = bool_to_str(has_video),
735                );
736            }
737            message => {
738                metric!(
739                    counter(RelayCounters::ProcessingMessageProduced) += 1,
740                    event_type = message.variant(),
741                    topic = topic_name,
742                );
743            }
744        }
745
746        Ok(())
747    }
748
749    /// Produces Kafka messages for the content and metadata of an attachment item.
750    ///
751    /// The `send_individual_attachments` controls whether the metadata of an attachment
752    /// is produced directly as an individual `attachment` message, or returned from this function
753    /// to be later sent as part of an `event` message.
754    ///
755    /// Attachment contents are chunked and sent as multiple `attachment_chunk` messages,
756    /// unless the `send_individual_attachments` flag is set, and the content is small enough
757    /// to fit inside a message.
758    /// In that case, no `attachment_chunk` is produced, but the content is sent as part
759    /// of the `attachment` message instead.
760    fn produce_attachment(
761        &self,
762        event_id: EventId,
763        project_id: ProjectId,
764        item: &Item,
765        send_individual_attachments: bool,
766    ) -> Result<Option<ChunkedAttachment>, StoreError> {
767        let id = Uuid::new_v4().to_string();
768
769        let payload = item.payload();
770        let size = item.len();
771        let max_chunk_size = self.config.attachment_chunk_size();
772
773        let payload = if size == 0 {
774            AttachmentPayload::Chunked(0)
775        } else if let Some(stored_key) = item.stored_key() {
776            AttachmentPayload::Stored(stored_key.into())
777        } else if send_individual_attachments && size < max_chunk_size {
778            // When sending individual attachments, and we have a single chunk, we want to send the
779            // `data` inline in the `attachment` message.
780            // This avoids a needless roundtrip through the attachments cache on the Sentry side.
781            AttachmentPayload::Inline(payload)
782        } else {
783            let mut chunk_index = 0;
784            let mut offset = 0;
785            // This skips chunks for empty attachments. The consumer does not require chunks for
786            // empty attachments. `chunks` will be `0` in this case.
787            while offset < size {
788                let chunk_size = std::cmp::min(max_chunk_size, size - offset);
789                let chunk_message = AttachmentChunkKafkaMessage {
790                    payload: payload.slice(offset..offset + chunk_size),
791                    event_id,
792                    project_id,
793                    id: id.clone(),
794                    chunk_index,
795                };
796
797                self.produce(
798                    KafkaTopic::Attachments,
799                    KafkaMessage::AttachmentChunk(chunk_message),
800                )?;
801                offset += chunk_size;
802                chunk_index += 1;
803            }
804
805            // The chunk_index is incremented after every loop iteration. After we exit the loop, it
806            // is one larger than the last chunk, so it is equal to the number of chunks.
807            AttachmentPayload::Chunked(chunk_index)
808        };
809
810        let attachment = ChunkedAttachment {
811            id,
812            name: match item.filename() {
813                Some(name) => name.to_owned(),
814                None => UNNAMED_ATTACHMENT.to_owned(),
815            },
816            rate_limited: item.rate_limited(),
817            content_type: item
818                .content_type()
819                .map(|content_type| content_type.as_str().to_owned()),
820            attachment_type: item.attachment_type().cloned().unwrap_or_default(),
821            size,
822            payload,
823        };
824
825        if send_individual_attachments {
826            let message = KafkaMessage::Attachment(AttachmentKafkaMessage {
827                event_id,
828                project_id,
829                attachment,
830            });
831            self.produce(KafkaTopic::Attachments, message)?;
832            Ok(None)
833        } else {
834            Ok(Some(attachment))
835        }
836    }
837
838    fn produce_user_report(
839        &self,
840        event_id: EventId,
841        project_id: ProjectId,
842        received_at: DateTime<Utc>,
843        item: &Item,
844    ) -> Result<(), StoreError> {
845        let message = KafkaMessage::UserReport(UserReportKafkaMessage {
846            project_id,
847            event_id,
848            start_time: safe_timestamp(received_at),
849            payload: item.payload(),
850        });
851
852        self.produce(KafkaTopic::Attachments, message)
853    }
854
855    fn produce_user_report_v2(
856        &self,
857        event_id: EventId,
858        project_id: ProjectId,
859        received_at: DateTime<Utc>,
860        item: &Item,
861        remote_addr: Option<String>,
862    ) -> Result<(), StoreError> {
863        let message = KafkaMessage::Event(EventKafkaMessage {
864            project_id,
865            event_id,
866            payload: item.payload(),
867            start_time: safe_timestamp(received_at),
868            remote_addr,
869            attachments: vec![],
870        });
871        self.produce(KafkaTopic::Feedback, message)
872    }
873
874    fn send_metric_message(
875        &self,
876        namespace: MetricNamespace,
877        message: MetricKafkaMessage,
878    ) -> Result<(), StoreError> {
879        let topic = match namespace {
880            MetricNamespace::Sessions => KafkaTopic::MetricsSessions,
881            MetricNamespace::Unsupported => {
882                relay_log::with_scope(
883                    |scope| scope.set_extra("metric_message.name", message.name.as_ref().into()),
884                    || relay_log::error!("store service dropping unknown metric usecase"),
885                );
886                return Ok(());
887            }
888            _ => KafkaTopic::MetricsGeneric,
889        };
890        let headers = BTreeMap::from([("namespace".to_owned(), namespace.to_string())]);
891
892        self.produce(topic, KafkaMessage::Metric { headers, message })?;
893        Ok(())
894    }
895
896    fn produce_profile(
897        &self,
898        organization_id: OrganizationId,
899        project_id: ProjectId,
900        key_id: Option<u64>,
901        received_at: DateTime<Utc>,
902        retention_days: u16,
903        item: &Item,
904    ) -> Result<(), StoreError> {
905        let message = ProfileKafkaMessage {
906            organization_id,
907            project_id,
908            key_id,
909            received: safe_timestamp(received_at),
910            retention_days,
911            headers: BTreeMap::from([
912                (
913                    "sampled".to_owned(),
914                    if item.sampled() { "true" } else { "false" }.to_owned(),
915                ),
916                ("project_id".to_owned(), project_id.to_string()),
917            ]),
918            payload: item.payload(),
919        };
920        self.produce(KafkaTopic::Profiles, KafkaMessage::Profile(message))?;
921        Ok(())
922    }
923
924    fn produce_replay_event(
925        &self,
926        replay_id: EventId,
927        project_id: ProjectId,
928        received_at: DateTime<Utc>,
929        retention_days: u16,
930        payload: &[u8],
931        relay_snuba_publish_disabled: bool,
932    ) -> Result<(), StoreError> {
933        if relay_snuba_publish_disabled {
934            return Ok(());
935        }
936
937        let message = ReplayEventKafkaMessage {
938            replay_id,
939            project_id,
940            retention_days,
941            start_time: safe_timestamp(received_at),
942            payload,
943        };
944        self.produce(KafkaTopic::ReplayEvents, KafkaMessage::ReplayEvent(message))?;
945        Ok(())
946    }
947
948    #[allow(clippy::too_many_arguments)]
949    fn produce_replay_recording(
950        &self,
951        event_id: Option<EventId>,
952        scoping: Scoping,
953        payload: &[u8],
954        replay_event: Option<&[u8]>,
955        replay_video: Option<&[u8]>,
956        received_at: DateTime<Utc>,
957        retention: u16,
958        relay_snuba_publish_disabled: bool,
959    ) -> Result<(), StoreError> {
960        // Maximum number of bytes accepted by the consumer.
961        let max_payload_size = self.config.max_replay_message_size();
962
963        // Size of the consumer message. We can be reasonably sure this won't overflow because
964        // of the request size validation provided by Nginx and Relay.
965        let mut payload_size = 2000; // Reserve 2KB for the message metadata.
966        payload_size += replay_event.as_ref().map_or(0, |b| b.len());
967        payload_size += replay_video.as_ref().map_or(0, |b| b.len());
968        payload_size += payload.len();
969
970        // If the recording payload can not fit in to the message do not produce and quit early.
971        if payload_size >= max_payload_size {
972            relay_log::debug!("replay_recording over maximum size.");
973            self.outcome_aggregator.send(TrackOutcome {
974                category: DataCategory::Replay,
975                event_id,
976                outcome: Outcome::Invalid(DiscardReason::TooLarge(
977                    DiscardItemType::ReplayRecording,
978                )),
979                quantity: 1,
980                remote_addr: None,
981                scoping,
982                timestamp: received_at,
983            });
984            return Ok(());
985        }
986
987        let message =
988            KafkaMessage::ReplayRecordingNotChunked(ReplayRecordingNotChunkedKafkaMessage {
989                replay_id: event_id.ok_or(StoreError::NoEventId)?,
990                project_id: scoping.project_id,
991                key_id: scoping.key_id,
992                org_id: scoping.organization_id,
993                received: safe_timestamp(received_at),
994                retention_days: retention,
995                payload,
996                replay_event,
997                replay_video,
998                relay_snuba_publish_disabled,
999            });
1000
1001        self.produce(KafkaTopic::ReplayRecordings, message)?;
1002
1003        Ok(())
1004    }
1005
1006    fn produce_replay_video(
1007        &self,
1008        event_id: Option<EventId>,
1009        scoping: Scoping,
1010        payload: Bytes,
1011        received_at: DateTime<Utc>,
1012        retention: u16,
1013        relay_snuba_publish_disabled: bool,
1014    ) -> Result<(), StoreError> {
1015        #[derive(Deserialize)]
1016        struct VideoEvent<'a> {
1017            replay_event: &'a [u8],
1018            replay_recording: &'a [u8],
1019            replay_video: &'a [u8],
1020        }
1021
1022        let Ok(VideoEvent {
1023            replay_video,
1024            replay_event,
1025            replay_recording,
1026        }) = rmp_serde::from_slice::<VideoEvent>(&payload)
1027        else {
1028            self.outcome_aggregator.send(TrackOutcome {
1029                category: DataCategory::Replay,
1030                event_id,
1031                outcome: Outcome::Invalid(DiscardReason::InvalidReplayEvent),
1032                quantity: 1,
1033                remote_addr: None,
1034                scoping,
1035                timestamp: received_at,
1036            });
1037            return Ok(());
1038        };
1039
1040        self.produce_replay_event(
1041            event_id.ok_or(StoreError::NoEventId)?,
1042            scoping.project_id,
1043            received_at,
1044            retention,
1045            replay_event,
1046            relay_snuba_publish_disabled,
1047        )?;
1048
1049        self.produce_replay_recording(
1050            event_id,
1051            scoping,
1052            replay_recording,
1053            Some(replay_event),
1054            Some(replay_video),
1055            received_at,
1056            retention,
1057            relay_snuba_publish_disabled,
1058        )
1059    }
1060
1061    fn produce_check_in(
1062        &self,
1063        project_id: ProjectId,
1064        received_at: DateTime<Utc>,
1065        client: Option<&str>,
1066        retention_days: u16,
1067        item: &Item,
1068    ) -> Result<(), StoreError> {
1069        let message = KafkaMessage::CheckIn(CheckInKafkaMessage {
1070            message_type: CheckInMessageType::CheckIn,
1071            project_id,
1072            retention_days,
1073            start_time: safe_timestamp(received_at),
1074            sdk: client.map(str::to_owned),
1075            payload: item.payload(),
1076            routing_key_hint: item.routing_hint(),
1077        });
1078
1079        self.produce(KafkaTopic::Monitors, message)?;
1080
1081        Ok(())
1082    }
1083
1084    fn produce_span(
1085        &self,
1086        scoping: Scoping,
1087        received_at: DateTime<Utc>,
1088        event_id: Option<EventId>,
1089        retention_days: u16,
1090        downsampled_retention_days: u16,
1091        item: &Item,
1092    ) -> Result<(), StoreError> {
1093        debug_assert_eq!(item.ty(), &ItemType::Span);
1094        debug_assert_eq!(item.content_type(), Some(&ContentType::Json));
1095
1096        let Scoping {
1097            organization_id,
1098            project_id,
1099            project_key: _,
1100            key_id,
1101        } = scoping;
1102
1103        let payload = item.payload();
1104        let message = SpanKafkaMessageRaw {
1105            meta: SpanMeta {
1106                organization_id,
1107                project_id,
1108                key_id,
1109                event_id,
1110                retention_days,
1111                downsampled_retention_days,
1112                received: datetime_to_timestamp(received_at),
1113            },
1114            span: serde_json::from_slice(&payload)
1115                .map_err(|e| StoreError::EncodingFailed(e.into()))?,
1116        };
1117
1118        // Verify that this is a V2 span:
1119        debug_assert!(message.span.contains_key("attributes"));
1120        relay_statsd::metric!(
1121            counter(RelayCounters::SpanV2Produced) += 1,
1122            via = "envelope"
1123        );
1124
1125        self.produce(
1126            KafkaTopic::Spans,
1127            KafkaMessage::SpanRaw {
1128                routing_key: item.routing_hint(),
1129                headers: BTreeMap::from([(
1130                    "project_id".to_owned(),
1131                    scoping.project_id.to_string(),
1132                )]),
1133                message,
1134            },
1135        )?;
1136
1137        // XXX: Temporarily produce span outcomes. Keep in sync with either EAP
1138        // or the segments consumer, depending on which will produce outcomes later.
1139        self.outcome_aggregator.send(TrackOutcome {
1140            category: DataCategory::SpanIndexed,
1141            event_id: None,
1142            outcome: Outcome::Accepted,
1143            quantity: 1,
1144            remote_addr: None,
1145            scoping,
1146            timestamp: received_at,
1147        });
1148
1149        Ok(())
1150    }
1151
1152    fn produce_profile_chunk(
1153        &self,
1154        organization_id: OrganizationId,
1155        project_id: ProjectId,
1156        received_at: DateTime<Utc>,
1157        retention_days: u16,
1158        item: &Item,
1159    ) -> Result<(), StoreError> {
1160        let message = ProfileChunkKafkaMessage {
1161            organization_id,
1162            project_id,
1163            received: safe_timestamp(received_at),
1164            retention_days,
1165            headers: BTreeMap::from([("project_id".to_owned(), project_id.to_string())]),
1166            payload: item.payload(),
1167        };
1168        self.produce(KafkaTopic::Profiles, KafkaMessage::ProfileChunk(message))?;
1169        Ok(())
1170    }
1171}
1172
1173impl Service for StoreService {
1174    type Interface = Store;
1175
1176    async fn run(self, mut rx: relay_system::Receiver<Self::Interface>) {
1177        let this = Arc::new(self);
1178
1179        relay_log::info!("store forwarder started");
1180
1181        while let Some(message) = rx.recv().await {
1182            let service = Arc::clone(&this);
1183            // For now, we run each task synchronously, in the future we might explore how to make
1184            // the store async.
1185            this.pool
1186                .spawn_async(async move { service.handle_message(message) }.boxed())
1187                .await;
1188        }
1189
1190        relay_log::info!("store forwarder stopped");
1191    }
1192}
1193
1194/// This signifies how the attachment payload is being transfered.
1195#[derive(Debug, Serialize)]
1196enum AttachmentPayload {
1197    /// The payload has been split into multiple chunks.
1198    ///
1199    /// The individual chunks are being sent as separate [`AttachmentChunkKafkaMessage`] messages.
1200    /// If the payload `size == 0`, the number of chunks will also be `0`.
1201    #[serde(rename = "chunks")]
1202    Chunked(usize),
1203
1204    /// The payload is inlined here directly, and thus into the [`ChunkedAttachment`].
1205    #[serde(rename = "data")]
1206    Inline(Bytes),
1207
1208    /// The attachment has already been stored into the objectstore, with the given Id.
1209    #[serde(rename = "stored_id")]
1210    Stored(String),
1211}
1212
1213/// Common attributes for both standalone attachments and processing-relevant attachments.
1214#[derive(Debug, Serialize)]
1215struct ChunkedAttachment {
1216    /// The attachment ID within the event.
1217    ///
1218    /// The triple `(project_id, event_id, id)` identifies an attachment uniquely.
1219    id: String,
1220
1221    /// File name of the attachment file.
1222    name: String,
1223
1224    /// Whether this attachment was rate limited and should be removed after processing.
1225    ///
1226    /// By default, rate limited attachments are immediately removed from Envelopes. For processing,
1227    /// native crash reports still need to be retained. These attachments are marked with the
1228    /// `rate_limited` header, which signals to the processing pipeline that the attachment should
1229    /// not be persisted after processing.
1230    rate_limited: bool,
1231
1232    /// Content type of the attachment payload.
1233    #[serde(skip_serializing_if = "Option::is_none")]
1234    content_type: Option<String>,
1235
1236    /// The Sentry-internal attachment type used in the processing pipeline.
1237    #[serde(serialize_with = "serialize_attachment_type")]
1238    attachment_type: AttachmentType,
1239
1240    /// The size of the attachment in bytes.
1241    size: usize,
1242
1243    /// The attachment payload, chunked, inlined, or already stored.
1244    #[serde(flatten)]
1245    payload: AttachmentPayload,
1246}
1247
1248/// A hack to make rmp-serde behave more like serde-json when serializing enums.
1249///
1250/// Cannot serialize bytes.
1251///
1252/// See <https://github.com/3Hren/msgpack-rust/pull/214>
1253fn serialize_attachment_type<S, T>(t: &T, serializer: S) -> Result<S::Ok, S::Error>
1254where
1255    S: serde::Serializer,
1256    T: serde::Serialize,
1257{
1258    serde_json::to_value(t)
1259        .map_err(|e| serde::ser::Error::custom(e.to_string()))?
1260        .serialize(serializer)
1261}
1262
1263/// Container payload for event messages.
1264#[derive(Debug, Serialize)]
1265struct EventKafkaMessage {
1266    /// Raw event payload.
1267    payload: Bytes,
1268    /// Time at which the event was received by Relay.
1269    start_time: u64,
1270    /// The event id.
1271    event_id: EventId,
1272    /// The project id for the current event.
1273    project_id: ProjectId,
1274    /// The client ip address.
1275    remote_addr: Option<String>,
1276    /// Attachments that are potentially relevant for processing.
1277    attachments: Vec<ChunkedAttachment>,
1278}
1279
1280#[derive(Debug, Serialize)]
1281struct ReplayEventKafkaMessage<'a> {
1282    /// Raw event payload.
1283    payload: &'a [u8],
1284    /// Time at which the event was received by Relay.
1285    start_time: u64,
1286    /// The event id.
1287    replay_id: EventId,
1288    /// The project id for the current event.
1289    project_id: ProjectId,
1290    // Number of days to retain.
1291    retention_days: u16,
1292}
1293
1294/// Container payload for chunks of attachments.
1295#[derive(Debug, Serialize)]
1296struct AttachmentChunkKafkaMessage {
1297    /// Chunk payload of the attachment.
1298    payload: Bytes,
1299    /// The event id.
1300    event_id: EventId,
1301    /// The project id for the current event.
1302    project_id: ProjectId,
1303    /// The attachment ID within the event.
1304    ///
1305    /// The triple `(project_id, event_id, id)` identifies an attachment uniquely.
1306    id: String,
1307    /// Sequence number of chunk. Starts at 0 and ends at `AttachmentKafkaMessage.num_chunks - 1`.
1308    chunk_index: usize,
1309}
1310
1311/// A "standalone" attachment.
1312///
1313/// Still belongs to an event but can be sent independently (like UserReport) and is not
1314/// considered in processing.
1315#[derive(Debug, Serialize)]
1316struct AttachmentKafkaMessage {
1317    /// The event id.
1318    event_id: EventId,
1319    /// The project id for the current event.
1320    project_id: ProjectId,
1321    /// The attachment.
1322    attachment: ChunkedAttachment,
1323}
1324
1325#[derive(Debug, Serialize)]
1326struct ReplayRecordingNotChunkedKafkaMessage<'a> {
1327    replay_id: EventId,
1328    key_id: Option<u64>,
1329    org_id: OrganizationId,
1330    project_id: ProjectId,
1331    received: u64,
1332    retention_days: u16,
1333    #[serde(with = "serde_bytes")]
1334    payload: &'a [u8],
1335    #[serde(with = "serde_bytes")]
1336    replay_event: Option<&'a [u8]>,
1337    #[serde(with = "serde_bytes")]
1338    replay_video: Option<&'a [u8]>,
1339    relay_snuba_publish_disabled: bool,
1340}
1341
1342/// User report for an event wrapped up in a message ready for consumption in Kafka.
1343///
1344/// Is always independent of an event and can be sent as part of any envelope.
1345#[derive(Debug, Serialize)]
1346struct UserReportKafkaMessage {
1347    /// The project id for the current event.
1348    project_id: ProjectId,
1349    start_time: u64,
1350    payload: Bytes,
1351
1352    // Used for KafkaMessage::key
1353    #[serde(skip)]
1354    event_id: EventId,
1355}
1356
1357#[derive(Clone, Debug, Serialize)]
1358struct MetricKafkaMessage<'a> {
1359    org_id: OrganizationId,
1360    project_id: ProjectId,
1361    name: &'a MetricName,
1362    #[serde(flatten)]
1363    value: MetricValue<'a>,
1364    timestamp: UnixTimestamp,
1365    tags: &'a BTreeMap<String, String>,
1366    retention_days: u16,
1367    #[serde(skip_serializing_if = "Option::is_none")]
1368    received_at: Option<UnixTimestamp>,
1369}
1370
1371#[derive(Clone, Debug, Serialize)]
1372#[serde(tag = "type", content = "value")]
1373enum MetricValue<'a> {
1374    #[serde(rename = "c")]
1375    Counter(FiniteF64),
1376    #[serde(rename = "d")]
1377    Distribution(ArrayEncoding<'a, &'a [FiniteF64]>),
1378    #[serde(rename = "s")]
1379    Set(ArrayEncoding<'a, SetView<'a>>),
1380    #[serde(rename = "g")]
1381    Gauge(GaugeValue),
1382}
1383
1384impl MetricValue<'_> {
1385    fn variant(&self) -> &'static str {
1386        match self {
1387            Self::Counter(_) => "counter",
1388            Self::Distribution(_) => "distribution",
1389            Self::Set(_) => "set",
1390            Self::Gauge(_) => "gauge",
1391        }
1392    }
1393
1394    fn encoding(&self) -> Option<&'static str> {
1395        match self {
1396            Self::Distribution(ae) => Some(ae.name()),
1397            Self::Set(ae) => Some(ae.name()),
1398            _ => None,
1399        }
1400    }
1401}
1402
1403#[derive(Clone, Debug, Serialize)]
1404struct ProfileKafkaMessage {
1405    organization_id: OrganizationId,
1406    project_id: ProjectId,
1407    key_id: Option<u64>,
1408    received: u64,
1409    retention_days: u16,
1410    #[serde(skip)]
1411    headers: BTreeMap<String, String>,
1412    payload: Bytes,
1413}
1414
1415/// Used to discriminate cron monitor ingestion messages.
1416///
1417/// There are two types of messages that end up in the ingest-monitors kafka topic, "check_in" (the
1418/// ones produced here in relay) and "clock_pulse" messages, which are produced externally and are
1419/// intended to ensure the clock continues to run even when ingestion volume drops.
1420#[allow(dead_code)]
1421#[derive(Debug, Serialize)]
1422#[serde(rename_all = "snake_case")]
1423enum CheckInMessageType {
1424    ClockPulse,
1425    CheckIn,
1426}
1427
1428#[derive(Debug, Serialize)]
1429struct CheckInKafkaMessage {
1430    #[serde(skip)]
1431    routing_key_hint: Option<Uuid>,
1432
1433    /// Used by the consumer to discrinminate the message.
1434    message_type: CheckInMessageType,
1435    /// Raw event payload.
1436    payload: Bytes,
1437    /// Time at which the event was received by Relay.
1438    start_time: u64,
1439    /// The SDK client which produced the event.
1440    sdk: Option<String>,
1441    /// The project id for the current event.
1442    project_id: ProjectId,
1443    /// Number of days to retain.
1444    retention_days: u16,
1445}
1446
1447#[derive(Debug, Serialize)]
1448struct SpanKafkaMessageRaw<'a> {
1449    #[serde(flatten)]
1450    meta: SpanMeta,
1451    #[serde(flatten)]
1452    span: BTreeMap<&'a str, &'a RawValue>,
1453}
1454
1455#[derive(Debug, Serialize)]
1456struct SpanKafkaMessage<'a> {
1457    #[serde(flatten)]
1458    meta: SpanMeta,
1459    #[serde(flatten)]
1460    span: SerializableAnnotated<'a, SpanV2>,
1461}
1462
1463#[derive(Debug, Serialize)]
1464struct SpanMeta {
1465    organization_id: OrganizationId,
1466    project_id: ProjectId,
1467    // Required for the buffer to emit outcomes scoped to the DSN.
1468    #[serde(skip_serializing_if = "Option::is_none")]
1469    key_id: Option<u64>,
1470    #[serde(skip_serializing_if = "Option::is_none")]
1471    event_id: Option<EventId>,
1472    /// Time at which the event was received by Relay. Not to be confused with `start_timestamp_ms`.
1473    received: f64,
1474    /// Number of days until these data should be deleted.
1475    retention_days: u16,
1476    /// Number of days until the downsampled version of this data should be deleted.
1477    downsampled_retention_days: u16,
1478}
1479
1480#[derive(Clone, Debug, Serialize)]
1481struct ProfileChunkKafkaMessage {
1482    organization_id: OrganizationId,
1483    project_id: ProjectId,
1484    received: u64,
1485    retention_days: u16,
1486    #[serde(skip)]
1487    headers: BTreeMap<String, String>,
1488    payload: Bytes,
1489}
1490
1491/// An enum over all possible ingest messages.
1492#[derive(Debug, Serialize)]
1493#[serde(tag = "type", rename_all = "snake_case")]
1494#[allow(clippy::large_enum_variant)]
1495enum KafkaMessage<'a> {
1496    Event(EventKafkaMessage),
1497    UserReport(UserReportKafkaMessage),
1498    Metric {
1499        #[serde(skip)]
1500        headers: BTreeMap<String, String>,
1501        #[serde(flatten)]
1502        message: MetricKafkaMessage<'a>,
1503    },
1504    CheckIn(CheckInKafkaMessage),
1505    Item {
1506        #[serde(skip)]
1507        headers: BTreeMap<String, String>,
1508        #[serde(skip)]
1509        item_type: TraceItemType,
1510        #[serde(skip)]
1511        message: TraceItem,
1512    },
1513    SpanRaw {
1514        #[serde(skip)]
1515        routing_key: Option<Uuid>,
1516        #[serde(skip)]
1517        headers: BTreeMap<String, String>,
1518        #[serde(flatten)]
1519        message: SpanKafkaMessageRaw<'a>,
1520    },
1521    SpanV2 {
1522        #[serde(skip)]
1523        routing_key: Option<Uuid>,
1524        #[serde(skip)]
1525        headers: BTreeMap<String, String>,
1526        #[serde(flatten)]
1527        message: SpanKafkaMessage<'a>,
1528    },
1529
1530    Attachment(AttachmentKafkaMessage),
1531    AttachmentChunk(AttachmentChunkKafkaMessage),
1532
1533    Profile(ProfileKafkaMessage),
1534    ProfileChunk(ProfileChunkKafkaMessage),
1535
1536    ReplayEvent(ReplayEventKafkaMessage<'a>),
1537    ReplayRecordingNotChunked(ReplayRecordingNotChunkedKafkaMessage<'a>),
1538}
1539
1540impl Message for KafkaMessage<'_> {
1541    fn variant(&self) -> &'static str {
1542        match self {
1543            KafkaMessage::Event(_) => "event",
1544            KafkaMessage::UserReport(_) => "user_report",
1545            KafkaMessage::Metric { message, .. } => match message.name.namespace() {
1546                MetricNamespace::Sessions => "metric_sessions",
1547                MetricNamespace::Transactions => "metric_transactions",
1548                MetricNamespace::Spans => "metric_spans",
1549                MetricNamespace::Custom => "metric_custom",
1550                MetricNamespace::Unsupported => "metric_unsupported",
1551            },
1552            KafkaMessage::CheckIn(_) => "check_in",
1553            KafkaMessage::SpanRaw { .. } | KafkaMessage::SpanV2 { .. } => "span",
1554            KafkaMessage::Item { item_type, .. } => item_type.as_str_name(),
1555
1556            KafkaMessage::Attachment(_) => "attachment",
1557            KafkaMessage::AttachmentChunk(_) => "attachment_chunk",
1558
1559            KafkaMessage::Profile(_) => "profile",
1560            KafkaMessage::ProfileChunk(_) => "profile_chunk",
1561
1562            KafkaMessage::ReplayEvent(_) => "replay_event",
1563            KafkaMessage::ReplayRecordingNotChunked(_) => "replay_recording_not_chunked",
1564        }
1565    }
1566
1567    /// Returns the partitioning key for this Kafka message determining.
1568    fn key(&self) -> Option<relay_kafka::Key> {
1569        match self {
1570            Self::Event(message) => Some(message.event_id.0),
1571            Self::UserReport(message) => Some(message.event_id.0),
1572            Self::SpanRaw { routing_key, .. } | Self::SpanV2 { routing_key, .. } => *routing_key,
1573
1574            // Monitor check-ins use the hinted UUID passed through from the Envelope.
1575            //
1576            // XXX(epurkhiser): In the future it would be better if all KafkaMessage's would
1577            // recieve the routing_key_hint form their envelopes.
1578            Self::CheckIn(message) => message.routing_key_hint,
1579
1580            Self::Attachment(message) => Some(message.event_id.0),
1581            Self::AttachmentChunk(message) => Some(message.event_id.0),
1582            Self::ReplayEvent(message) => Some(message.replay_id.0),
1583
1584            // Random partitioning
1585            Self::Metric { .. }
1586            | Self::Item { .. }
1587            | Self::Profile(_)
1588            | Self::ProfileChunk(_)
1589            | Self::ReplayRecordingNotChunked(_) => None,
1590        }
1591        .filter(|uuid| !uuid.is_nil())
1592        .map(|uuid| uuid.as_u128())
1593    }
1594
1595    fn headers(&self) -> Option<&BTreeMap<String, String>> {
1596        match &self {
1597            KafkaMessage::Metric { headers, .. }
1598            | KafkaMessage::SpanRaw { headers, .. }
1599            | KafkaMessage::SpanV2 { headers, .. }
1600            | KafkaMessage::Item { headers, .. }
1601            | KafkaMessage::Profile(ProfileKafkaMessage { headers, .. })
1602            | KafkaMessage::ProfileChunk(ProfileChunkKafkaMessage { headers, .. }) => Some(headers),
1603
1604            KafkaMessage::Event(_)
1605            | KafkaMessage::UserReport(_)
1606            | KafkaMessage::CheckIn(_)
1607            | KafkaMessage::Attachment(_)
1608            | KafkaMessage::AttachmentChunk(_)
1609            | KafkaMessage::ReplayEvent(_)
1610            | KafkaMessage::ReplayRecordingNotChunked(_) => None,
1611        }
1612    }
1613
1614    fn serialize(&self) -> Result<SerializationOutput<'_>, ClientError> {
1615        match self {
1616            KafkaMessage::Metric { message, .. } => serialize_as_json(message),
1617            KafkaMessage::ReplayEvent(message) => serialize_as_json(message),
1618            KafkaMessage::SpanRaw { message, .. } => serialize_as_json(message),
1619            KafkaMessage::SpanV2 { message, .. } => serialize_as_json(message),
1620            KafkaMessage::Item { message, .. } => {
1621                let mut payload = Vec::new();
1622                match message.encode(&mut payload) {
1623                    Ok(_) => Ok(SerializationOutput::Protobuf(Cow::Owned(payload))),
1624                    Err(_) => Err(ClientError::ProtobufEncodingFailed),
1625                }
1626            }
1627            KafkaMessage::Event(_)
1628            | KafkaMessage::UserReport(_)
1629            | KafkaMessage::CheckIn(_)
1630            | KafkaMessage::Attachment(_)
1631            | KafkaMessage::AttachmentChunk(_)
1632            | KafkaMessage::Profile(_)
1633            | KafkaMessage::ProfileChunk(_)
1634            | KafkaMessage::ReplayRecordingNotChunked(_) => match rmp_serde::to_vec_named(&self) {
1635                Ok(x) => Ok(SerializationOutput::MsgPack(Cow::Owned(x))),
1636                Err(err) => Err(ClientError::InvalidMsgPack(err)),
1637            },
1638        }
1639    }
1640}
1641
1642fn serialize_as_json<T: serde::Serialize>(
1643    value: &T,
1644) -> Result<SerializationOutput<'_>, ClientError> {
1645    match serde_json::to_vec(value) {
1646        Ok(vec) => Ok(SerializationOutput::Json(Cow::Owned(vec))),
1647        Err(err) => Err(ClientError::InvalidJson(err)),
1648    }
1649}
1650
1651/// Determines if the given item is considered slow.
1652///
1653/// Slow items must be routed to the `Attachments` topic.
1654fn is_slow_item(item: &Item) -> bool {
1655    item.ty() == &ItemType::Attachment || item.ty() == &ItemType::UserReport
1656}
1657
1658fn bool_to_str(value: bool) -> &'static str {
1659    if value { "true" } else { "false" }
1660}
1661
1662/// Returns a safe timestamp for Kafka.
1663///
1664/// Kafka expects timestamps to be in UTC and in seconds since epoch.
1665fn safe_timestamp(timestamp: DateTime<Utc>) -> u64 {
1666    let ts = timestamp.timestamp();
1667    if ts >= 0 {
1668        return ts as u64;
1669    }
1670
1671    // We assume this call can't return < 0.
1672    Utc::now().timestamp() as u64
1673}
1674
1675#[cfg(test)]
1676mod tests {
1677
1678    use super::*;
1679
1680    #[test]
1681    fn disallow_outcomes() {
1682        let config = Config::default();
1683        let producer = Producer::create(&config).unwrap();
1684
1685        for topic in [KafkaTopic::Outcomes, KafkaTopic::OutcomesBilling] {
1686            let res = producer
1687                .client
1688                .send(topic, Some(0x0123456789abcdef), None, "foo", b"");
1689
1690            assert!(matches!(res, Err(ClientError::InvalidTopicName)));
1691        }
1692    }
1693}