Skip to main content

relay_server/services/
processor.rs

1use std::borrow::Cow;
2use std::collections::{BTreeMap, BTreeSet, HashMap};
3use std::error::Error;
4use std::fmt::Debug;
5use std::future::Future;
6use std::io::Write;
7use std::pin::Pin;
8use std::sync::Arc;
9use std::time::Duration;
10
11use anyhow::Context;
12use brotli::CompressorWriter as BrotliEncoder;
13use bytes::Bytes;
14use chrono::{DateTime, Utc};
15use flate2::Compression;
16use flate2::write::{GzEncoder, ZlibEncoder};
17use futures::FutureExt;
18use futures::future::BoxFuture;
19use relay_base_schema::project::{ProjectId, ProjectKey};
20use relay_cogs::{AppFeature, Cogs, FeatureWeights, ResourceId, Token};
21use relay_common::time::UnixTimestamp;
22use relay_config::{Config, HttpEncoding, UpstreamDescriptor};
23use relay_event_normalization::{ClockDriftProcessor, GeoIpLookup};
24use relay_event_schema::processor::ProcessingAction;
25use relay_event_schema::protocol::ClientReport;
26use relay_filter::FilterStatKey;
27use relay_metrics::{Bucket, BucketMetadata, BucketView, BucketsView, MetricNamespace};
28use relay_quotas::{DataCategory, RateLimits, Scoping};
29use relay_sampling::evaluation::SamplingDecision;
30use relay_statsd::metric;
31use relay_system::{Addr, FromMessage, NoResponse, Service};
32use reqwest::header;
33use zstd::stream::Encoder as ZstdEncoder;
34
35use crate::envelope::{self, ContentType, Envelope, EnvelopeError, Item, ItemType};
36use crate::extractors::{PartialDsn, RequestMeta, RequestTrust};
37use crate::managed::ManagedEnvelope;
38use crate::metrics::{MetricOutcomes, MetricsLimiter, MinimalTrackableBucket};
39use crate::metrics_extraction::ExtractedMetrics;
40use crate::processing::errors::SwitchProcessingError;
41use crate::processing::relay::RelayProcessor;
42use crate::processing::{Forward as _, Output, Outputs, QuotaRateLimiter};
43use crate::service::ServiceError;
44use crate::services::global_config::GlobalConfigHandle;
45use crate::services::metrics::{Aggregator, FlushBuckets, MergeBuckets, ProjectBuckets};
46use crate::services::outcome::{DiscardItemType, DiscardReason, Outcome, TrackOutcome};
47use crate::services::projects::cache::ProjectCacheHandle;
48use crate::services::projects::project::{ProjectInfo, ProjectState};
49use crate::services::upstream::{
50    SendRequest, Sign, SignatureType, UpstreamRelay, UpstreamRequest, UpstreamRequestError,
51};
52use crate::statsd::{RelayCounters, RelayDistributions, RelayTimers};
53use crate::utils;
54use crate::{http, processing};
55use relay_threading::AsyncPool;
56use symbolic_unreal::{Unreal4Error, Unreal4ErrorKind};
57#[cfg(feature = "processing")]
58use {
59    crate::services::objectstore::Objectstore,
60    crate::services::store::Store,
61    itertools::Itertools,
62    relay_dynamic_config::GlobalConfig,
63    relay_quotas::{Quota, RateLimitingError, RedisRateLimiter},
64    relay_redis::RedisClients,
65    std::time::Instant,
66};
67
68mod metrics;
69
70/// The minimum clock drift for correction to apply.
71pub const MINIMUM_CLOCK_DRIFT: Duration = Duration::from_secs(55 * 60);
72
73/// An error returned when handling [`ProcessEnvelope`].
74#[derive(Debug, thiserror::Error)]
75pub enum ProcessingError {
76    #[error("invalid json in event")]
77    InvalidJson(#[source] serde_json::Error),
78
79    #[error("invalid message pack event payload")]
80    InvalidMsgpack(#[from] rmp_serde::decode::Error),
81
82    #[error("invalid unreal crash report")]
83    InvalidUnrealReport(#[source] Unreal4Error),
84
85    #[error("event payload too large")]
86    PayloadTooLarge(DiscardItemType),
87
88    #[error("invalid transaction event")]
89    InvalidTransaction,
90
91    #[error("the item is not allowed/supported in this envelope")]
92    UnsupportedItem,
93
94    #[error("envelope processor failed")]
95    ProcessingFailed(#[from] ProcessingAction),
96
97    #[error("duplicate {0} in event")]
98    DuplicateItem(ItemType),
99
100    #[error("failed to extract event payload")]
101    NoEventPayload,
102
103    #[error("invalid security report type: {0:?}")]
104    InvalidSecurityType(Bytes),
105
106    #[error("unsupported security report type")]
107    UnsupportedSecurityType,
108
109    #[error("invalid security report")]
110    InvalidSecurityReport(#[source] serde_json::Error),
111
112    #[error("event filtered with reason: {0:?}")]
113    EventFiltered(FilterStatKey),
114
115    #[error("could not serialize event payload")]
116    SerializeFailed(#[source] serde_json::Error),
117
118    #[cfg(feature = "processing")]
119    #[error("failed to apply quotas")]
120    QuotasFailed(#[from] RateLimitingError),
121
122    #[error("nintendo switch dying message processing failed {0:?}")]
123    InvalidNintendoDyingMessage(#[source] SwitchProcessingError),
124
125    #[cfg(all(sentry, feature = "processing"))]
126    #[error("playstation dump processing failed: {0}")]
127    InvalidPlaystationDump(String),
128
129    #[cfg(feature = "processing")]
130    #[error("invalid attachment reference")]
131    InvalidAttachmentRef,
132}
133
134impl ProcessingError {
135    pub fn to_outcome(&self) -> Option<Outcome> {
136        match self {
137            Self::PayloadTooLarge(payload_type) => {
138                Some(Outcome::Invalid(DiscardReason::ItemTooLarge(*payload_type)))
139            }
140            Self::InvalidJson(_) => Some(Outcome::Invalid(DiscardReason::InvalidJson)),
141            Self::InvalidMsgpack(_) => Some(Outcome::Invalid(DiscardReason::InvalidMsgpack)),
142            Self::InvalidSecurityType(_) => {
143                Some(Outcome::Invalid(DiscardReason::SecurityReportType))
144            }
145            Self::UnsupportedItem => Some(Outcome::Invalid(DiscardReason::InvalidEnvelope)),
146            Self::InvalidSecurityReport(_) => Some(Outcome::Invalid(DiscardReason::SecurityReport)),
147            Self::UnsupportedSecurityType => Some(Outcome::Filtered(FilterStatKey::InvalidCsp)),
148            Self::InvalidTransaction => Some(Outcome::Invalid(DiscardReason::InvalidTransaction)),
149            Self::DuplicateItem(_) => Some(Outcome::Invalid(DiscardReason::DuplicateItem)),
150            Self::NoEventPayload => Some(Outcome::Invalid(DiscardReason::NoEventPayload)),
151            Self::InvalidNintendoDyingMessage(_) => Some(Outcome::Invalid(DiscardReason::Payload)),
152            #[cfg(all(sentry, feature = "processing"))]
153            Self::InvalidPlaystationDump(_) => Some(Outcome::Invalid(DiscardReason::Payload)),
154            Self::InvalidUnrealReport(err) if err.kind() == Unreal4ErrorKind::BadCompression => {
155                Some(Outcome::Invalid(DiscardReason::InvalidCompression))
156            }
157            Self::InvalidUnrealReport(_) => Some(Outcome::Invalid(DiscardReason::ProcessUnreal)),
158            Self::SerializeFailed(_) | Self::ProcessingFailed(_) => {
159                Some(Outcome::Invalid(DiscardReason::Internal))
160            }
161            #[cfg(feature = "processing")]
162            Self::QuotasFailed(_) => Some(Outcome::Invalid(DiscardReason::Internal)),
163            Self::EventFiltered(key) => Some(Outcome::Filtered(key.clone())),
164
165            #[cfg(feature = "processing")]
166            Self::InvalidAttachmentRef => {
167                Some(Outcome::Invalid(DiscardReason::InvalidAttachmentRef))
168            }
169        }
170    }
171}
172
173impl From<Unreal4Error> for ProcessingError {
174    fn from(err: Unreal4Error) -> Self {
175        match err.kind() {
176            Unreal4ErrorKind::TooLarge => Self::PayloadTooLarge(ItemType::UnrealReport.into()),
177            _ => ProcessingError::InvalidUnrealReport(err),
178        }
179    }
180}
181
182/// A container for extracted metrics during processing.
183///
184/// The container enforces that the extracted metrics are correctly tagged
185/// with the dynamic sampling decision.
186#[derive(Debug)]
187pub struct ProcessingExtractedMetrics {
188    metrics: ExtractedMetrics,
189}
190
191impl ProcessingExtractedMetrics {
192    pub fn new() -> Self {
193        Self {
194            metrics: ExtractedMetrics::default(),
195        }
196    }
197
198    pub fn into_inner(self) -> ExtractedMetrics {
199        self.metrics
200    }
201
202    /// Extends the contained metrics with [`ExtractedMetrics`].
203    pub fn extend(
204        &mut self,
205        extracted: ExtractedMetrics,
206        sampling_decision: Option<SamplingDecision>,
207    ) {
208        self.extend_project_metrics(extracted.project_metrics, sampling_decision);
209        self.extend_sampling_metrics(extracted.sampling_metrics, sampling_decision);
210    }
211
212    /// Extends the contained project metrics.
213    pub fn extend_project_metrics<I>(
214        &mut self,
215        buckets: I,
216        sampling_decision: Option<SamplingDecision>,
217    ) where
218        I: IntoIterator<Item = Bucket>,
219    {
220        self.metrics
221            .project_metrics
222            .extend(buckets.into_iter().map(|mut bucket| {
223                bucket.metadata.extracted_from_indexed =
224                    sampling_decision == Some(SamplingDecision::Keep);
225                bucket
226            }));
227    }
228
229    /// Extends the contained sampling metrics.
230    pub fn extend_sampling_metrics<I>(
231        &mut self,
232        buckets: I,
233        sampling_decision: Option<SamplingDecision>,
234    ) where
235        I: IntoIterator<Item = Bucket>,
236    {
237        self.metrics
238            .sampling_metrics
239            .extend(buckets.into_iter().map(|mut bucket| {
240                bucket.metadata.extracted_from_indexed =
241                    sampling_decision == Some(SamplingDecision::Keep);
242                bucket
243            }));
244    }
245}
246
247fn send_metrics(
248    metrics: ExtractedMetrics,
249    project_key: ProjectKey,
250    sampling_key: Option<ProjectKey>,
251    aggregator: &Addr<Aggregator>,
252) {
253    let ExtractedMetrics {
254        project_metrics,
255        sampling_metrics,
256    } = metrics;
257
258    if !project_metrics.is_empty() {
259        aggregator.send(MergeBuckets {
260            project_key,
261            buckets: project_metrics,
262        });
263    }
264
265    if !sampling_metrics.is_empty() {
266        // If no sampling project state is available, we associate the sampling
267        // metrics with the current project.
268        //
269        // project_without_tracing         -> metrics goes to self
270        // dependent_project_with_tracing  -> metrics goes to root
271        // root_project_with_tracing       -> metrics goes to root == self
272        let sampling_project_key = sampling_key.unwrap_or(project_key);
273        aggregator.send(MergeBuckets {
274            project_key: sampling_project_key,
275            buckets: sampling_metrics,
276        });
277    }
278}
279
280/// Applies processing to all contents of the given envelope.
281///
282/// Depending on the contents of the envelope and Relay's mode, this includes:
283///
284///  - Basic normalization and validation for all item types.
285///  - Clock drift correction if the required `sent_at` header is present.
286///  - Expansion of certain item types (e.g. unreal).
287///  - Store normalization for event payloads in processing mode.
288///  - Rate limiters and inbound filters on events in processing mode.
289#[derive(Debug)]
290pub struct ProcessEnvelope {
291    /// Envelope to process.
292    pub envelope: ManagedEnvelope,
293    /// The project info.
294    pub project_info: Arc<ProjectInfo>,
295    /// Currently active cached rate limits for this project.
296    pub rate_limits: Arc<RateLimits>,
297    /// Root sampling project info.
298    pub sampling_project_info: Option<Arc<ProjectInfo>>,
299}
300
301/// Parses a list of metrics or metric buckets and pushes them to the project's aggregator.
302///
303/// This parses and validates the metrics:
304///  - For [`Metrics`](ItemType::Statsd), each metric is parsed separately, and invalid metrics are
305///    ignored independently.
306///  - For [`MetricBuckets`](ItemType::MetricBuckets), the entire list of buckets is parsed and
307///    dropped together on parsing failure.
308///  - Other envelope items will be ignored with an error message.
309///
310/// Additionally, processing applies clock drift correction using the system clock of this Relay, if
311/// the Envelope specifies the [`sent_at`](Envelope::sent_at) header.
312#[derive(Debug)]
313pub struct ProcessMetrics {
314    /// A list of metric items.
315    pub data: MetricData,
316    /// The target project.
317    pub project_key: ProjectKey,
318    /// Whether to keep or reset the metric metadata.
319    pub source: BucketSource,
320    /// The wall clock time at which the request was received.
321    pub received_at: DateTime<Utc>,
322    /// The value of the Envelope's [`sent_at`](Envelope::sent_at) header for clock drift
323    /// correction.
324    pub sent_at: Option<DateTime<Utc>>,
325}
326
327/// Raw unparsed metric data.
328#[derive(Debug)]
329pub enum MetricData {
330    /// Raw data, unparsed envelope items.
331    Raw(Vec<Item>),
332    /// Already parsed buckets but unprocessed.
333    Parsed(Vec<Bucket>),
334}
335
336impl MetricData {
337    /// Consumes the metric data and parses the contained buckets.
338    ///
339    /// If the contained data is already parsed the buckets are returned unchanged.
340    /// Raw buckets are parsed and created with the passed `timestamp`.
341    fn into_buckets(self, timestamp: UnixTimestamp) -> Vec<Bucket> {
342        let items = match self {
343            Self::Parsed(buckets) => return buckets,
344            Self::Raw(items) => items,
345        };
346
347        let mut buckets = Vec::new();
348        for item in items {
349            let payload = item.payload();
350            if item.ty() == &ItemType::Statsd {
351                for bucket_result in Bucket::parse_all(&payload, timestamp) {
352                    match bucket_result {
353                        Ok(bucket) => buckets.push(bucket),
354                        Err(error) => relay_log::debug!(
355                            error = &error as &dyn Error,
356                            "failed to parse metric bucket from statsd format",
357                        ),
358                    }
359                }
360            } else if item.ty() == &ItemType::MetricBuckets {
361                match serde_json::from_slice::<Vec<Bucket>>(&payload) {
362                    Ok(parsed_buckets) => {
363                        // Re-use the allocation of `b` if possible.
364                        if buckets.is_empty() {
365                            buckets = parsed_buckets;
366                        } else {
367                            buckets.extend(parsed_buckets);
368                        }
369                    }
370                    Err(error) => {
371                        relay_log::debug!(
372                            error = &error as &dyn Error,
373                            "failed to parse metric bucket",
374                        );
375                        metric!(counter(RelayCounters::MetricBucketsParsingFailed) += 1);
376                    }
377                }
378            } else {
379                relay_log::error!(
380                    "invalid item of type {} passed to ProcessMetrics",
381                    item.ty()
382                );
383            }
384        }
385        buckets
386    }
387}
388
389#[derive(Debug)]
390pub struct ProcessBatchedMetrics {
391    /// Metrics payload in JSON format.
392    pub payload: Bytes,
393    /// Whether to keep or reset the metric metadata.
394    pub source: BucketSource,
395    /// The wall clock time at which the request was received.
396    pub received_at: DateTime<Utc>,
397    /// The wall clock time at which the request was received.
398    pub sent_at: Option<DateTime<Utc>>,
399}
400
401/// Source information where a metric bucket originates from.
402#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
403pub enum BucketSource {
404    /// The metric bucket originated from an internal Relay use case.
405    ///
406    /// The metric bucket originates either from within the same Relay
407    /// or was accepted coming from another Relay which is registered as
408    /// an internal Relay via Relay's configuration.
409    Internal,
410    /// The bucket source originated from an untrusted source.
411    ///
412    /// Managed Relays sending extracted metrics are considered external,
413    /// it's a project use case but it comes from an untrusted source.
414    External,
415}
416
417impl BucketSource {
418    /// Infers the bucket source from [`RequestMeta::request_trust`].
419    pub fn from_meta(meta: &RequestMeta) -> Self {
420        match meta.request_trust() {
421            RequestTrust::Trusted => Self::Internal,
422            RequestTrust::Untrusted => Self::External,
423        }
424    }
425}
426
427/// Sends a client report to the upstream.
428#[derive(Debug)]
429pub struct SubmitClientReports {
430    /// The client report to be sent.
431    pub client_reports: Vec<ClientReport>,
432    /// Scoping information for the client report.
433    pub scoping: Scoping,
434}
435
436/// CPU-intensive processing tasks for envelopes.
437#[derive(Debug)]
438pub enum EnvelopeProcessor {
439    ProcessEnvelope(Box<ProcessEnvelope>),
440    ProcessProjectMetrics(Box<ProcessMetrics>),
441    ProcessBatchedMetrics(Box<ProcessBatchedMetrics>),
442    FlushBuckets(Box<FlushBuckets>),
443    SubmitClientReports(Box<SubmitClientReports>),
444}
445
446impl EnvelopeProcessor {
447    /// Returns the name of the message variant.
448    pub fn variant(&self) -> &'static str {
449        match self {
450            EnvelopeProcessor::ProcessEnvelope(_) => "ProcessEnvelope",
451            EnvelopeProcessor::ProcessProjectMetrics(_) => "ProcessProjectMetrics",
452            EnvelopeProcessor::ProcessBatchedMetrics(_) => "ProcessBatchedMetrics",
453            EnvelopeProcessor::FlushBuckets(_) => "FlushBuckets",
454            EnvelopeProcessor::SubmitClientReports(_) => "SubmitClientReports",
455        }
456    }
457}
458
459impl relay_system::Interface for EnvelopeProcessor {}
460
461impl FromMessage<ProcessEnvelope> for EnvelopeProcessor {
462    type Response = relay_system::NoResponse;
463
464    fn from_message(message: ProcessEnvelope, _sender: ()) -> Self {
465        Self::ProcessEnvelope(Box::new(message))
466    }
467}
468
469impl FromMessage<ProcessMetrics> for EnvelopeProcessor {
470    type Response = NoResponse;
471
472    fn from_message(message: ProcessMetrics, _: ()) -> Self {
473        Self::ProcessProjectMetrics(Box::new(message))
474    }
475}
476
477impl FromMessage<ProcessBatchedMetrics> for EnvelopeProcessor {
478    type Response = NoResponse;
479
480    fn from_message(message: ProcessBatchedMetrics, _: ()) -> Self {
481        Self::ProcessBatchedMetrics(Box::new(message))
482    }
483}
484
485impl FromMessage<FlushBuckets> for EnvelopeProcessor {
486    type Response = NoResponse;
487
488    fn from_message(message: FlushBuckets, _: ()) -> Self {
489        Self::FlushBuckets(Box::new(message))
490    }
491}
492
493impl FromMessage<SubmitClientReports> for EnvelopeProcessor {
494    type Response = NoResponse;
495
496    fn from_message(message: SubmitClientReports, _: ()) -> Self {
497        Self::SubmitClientReports(Box::new(message))
498    }
499}
500
501/// The asynchronous thread pool used for scheduling processing tasks in the processor.
502pub type EnvelopeProcessorServicePool = AsyncPool<BoxFuture<'static, ()>>;
503
504/// Service implementing the [`EnvelopeProcessor`] interface.
505///
506/// This service handles messages in a worker pool with configurable concurrency.
507#[derive(Clone)]
508pub struct EnvelopeProcessorService {
509    inner: Arc<InnerProcessor>,
510}
511
512/// Contains the addresses of services that the processor publishes to.
513pub struct Addrs {
514    pub outcome_aggregator: Addr<TrackOutcome>,
515    pub upstream_relay: Addr<UpstreamRelay>,
516    #[cfg(feature = "processing")]
517    pub objectstore: Option<Addr<Objectstore>>,
518    #[cfg(feature = "processing")]
519    pub store_forwarder: Option<Addr<Store>>,
520    pub aggregator: Addr<Aggregator>,
521}
522
523impl Default for Addrs {
524    fn default() -> Self {
525        Addrs {
526            outcome_aggregator: Addr::dummy(),
527            upstream_relay: Addr::dummy(),
528            #[cfg(feature = "processing")]
529            objectstore: None,
530            #[cfg(feature = "processing")]
531            store_forwarder: None,
532            aggregator: Addr::dummy(),
533        }
534    }
535}
536
537struct InnerProcessor {
538    pool: EnvelopeProcessorServicePool,
539    config: Arc<Config>,
540    global_config: GlobalConfigHandle,
541    project_cache: ProjectCacheHandle,
542    cogs: Cogs,
543    addrs: Addrs,
544    #[cfg(feature = "processing")]
545    rate_limiter: Option<Arc<RedisRateLimiter>>,
546    metric_outcomes: MetricOutcomes,
547    processor: RelayProcessor,
548}
549
550impl EnvelopeProcessorService {
551    /// Creates a multi-threaded envelope processor.
552    #[cfg_attr(feature = "processing", expect(clippy::too_many_arguments))]
553    pub fn new(
554        pool: EnvelopeProcessorServicePool,
555        config: Arc<Config>,
556        global_config: GlobalConfigHandle,
557        project_cache: ProjectCacheHandle,
558        cogs: Cogs,
559        #[cfg(feature = "processing")] redis: Option<RedisClients>,
560        addrs: Addrs,
561        metric_outcomes: MetricOutcomes,
562    ) -> Self {
563        let geoip_lookup = config
564            .geoip_path()
565            .and_then(
566                |p| match GeoIpLookup::open(p).context(ServiceError::GeoIp) {
567                    Ok(geoip) => Some(geoip),
568                    Err(err) => {
569                        relay_log::error!("failed to open GeoIP db {p:?}: {err:?}");
570                        None
571                    }
572                },
573            )
574            .unwrap_or_else(GeoIpLookup::empty);
575
576        if let Some(build_epoch) = geoip_lookup.build_epoch() {
577            relay_log::info!("Loaded GeoIP database (build: {build_epoch})");
578        }
579
580        #[cfg(feature = "processing")]
581        let rate_limiter = redis.map(|redis| {
582            RedisRateLimiter::new(redis.quotas)
583                .max_limit(config.max_rate_limit())
584                .cache(config.quota_cache_ratio(), config.quota_cache_max())
585        });
586
587        let quota_limiter = Arc::new(QuotaRateLimiter::new(
588            #[cfg(feature = "processing")]
589            project_cache.clone(),
590            #[cfg(feature = "processing")]
591            rate_limiter.clone(),
592        ));
593        #[cfg(feature = "processing")]
594        let rate_limiter = rate_limiter.map(Arc::new);
595        let inner = InnerProcessor {
596            pool,
597            global_config,
598            project_cache,
599            #[cfg(feature = "processing")]
600            rate_limiter,
601            processor: RelayProcessor::new(
602                cogs.clone(),
603                &quota_limiter,
604                &geoip_lookup,
605                addrs.outcome_aggregator.clone(),
606            ),
607            cogs,
608            addrs,
609            metric_outcomes,
610            config,
611        };
612
613        Self {
614            inner: Arc::new(inner),
615        }
616    }
617
618    async fn process_envelope(
619        &self,
620        project_id: ProjectId,
621        mut envelope: ManagedEnvelope,
622        ctx: processing::Context<'_>,
623    ) -> Vec<Output<Outputs>> {
624        // Pre-process the envelope headers.
625        if let Some(sampling_state) = ctx.sampling_project_info {
626            // Both transactions and standalone span envelopes need a normalized DSC header
627            // to make sampling rules based on the segment/transaction name work correctly.
628            envelope
629                .envelope_mut()
630                .parametrize_dsc_transaction(&sampling_state.config.tx_name_rules);
631        }
632
633        // Set the event retention. Effectively, this value will only be available in processing
634        // mode when the full project config is queried from the upstream.
635        if let Some(retention) = ctx.project_info.config.event_retention {
636            envelope.envelope_mut().set_retention(retention);
637        }
638
639        // Ensure the project ID is updated to the stored instance for this project cache. This can
640        // differ in two cases:
641        //  1. The envelope was sent to the legacy `/store/` endpoint without a project ID.
642        //  2. The DSN was moved and the envelope sent to the old project ID.
643        envelope
644            .envelope_mut()
645            .meta_mut()
646            .set_project_id(project_id);
647
648        self.inner.processor.run(envelope, ctx).await
649    }
650
651    /// Processes the envelope and returns the processed envelope back.
652    ///
653    /// Returns `Some` if the envelope passed inbound filtering and rate limiting. Invalid items are
654    /// removed from the envelope. Otherwise, if the envelope is empty or the entire envelope needs
655    /// to be dropped, this is `None`.
656    async fn process<'a>(
657        &self,
658        mut envelope: ManagedEnvelope,
659        ctx: processing::Context<'a>,
660    ) -> Vec<Output<Outputs>> {
661        // Prefer the project's project ID, and fall back to the stated project id from the
662        // envelope. The project ID is available in all modes, other than in proxy mode, where
663        // envelopes for unknown projects are forwarded blindly.
664        //
665        // Neither ID can be available in proxy mode on the /store/ endpoint. This is not supported,
666        // since we cannot process an envelope without project ID, so drop it.
667        let Some(project_id) = ctx
668            .project_info
669            .project_id
670            .or_else(|| envelope.envelope().meta().project_id())
671        else {
672            relay_log::error!(
673                tags.project_key = %envelope.envelope().meta().public_key(),
674                "project info does not contain project id"
675            );
676            envelope.reject(Outcome::Invalid(DiscardReason::Internal));
677            return Vec::new();
678        };
679
680        let client = envelope.envelope().meta().client().map(str::to_owned);
681        let user_agent = envelope.envelope().meta().user_agent().map(str::to_owned);
682
683        // We set additional information on the scope, which will be removed after processing the
684        // envelope.
685        relay_log::configure_scope(|scope| {
686            scope.set_tag("project", project_id);
687            if let Some(client) = client {
688                scope.set_tag("sdk", client);
689            }
690            if let Some(user_agent) = user_agent {
691                scope.set_extra("user_agent", user_agent.into());
692            }
693        });
694
695        let result = self.process_envelope(project_id, envelope, ctx).await;
696
697        relay_log::configure_scope(|scope| {
698            scope.remove_tag("project");
699            scope.remove_tag("sdk");
700            scope.remove_tag("user_agent");
701        });
702
703        result
704    }
705
706    async fn handle_process_envelope(&self, cogs: &mut Token, message: ProcessEnvelope) {
707        let wait_time = message.envelope.age();
708        metric!(timer(RelayTimers::EnvelopeWaitTime) = wait_time);
709
710        // This COGS handling may need an overhaul in the future:
711        // Cancel the passed in token, to start individual measurements per processor instead.
712        cogs.cancel();
713
714        let global_config = self.inner.global_config.current().unwrap_or_default();
715
716        let ctx = processing::Context {
717            config: &self.inner.config,
718            global_config: &global_config,
719            project_info: &message.project_info,
720            sampling_project_info: message.sampling_project_info.as_deref(),
721            rate_limits: &message.rate_limits,
722        };
723
724        let project_key = message.envelope.meta().public_key();
725        // Only allow sending to the sampling key, if we successfully loaded a sampling project
726        // info relating to it. This filters out unknown/invalid project keys as well as project
727        // keys from different organizations.
728        let sampling_key = ctx
729            .sampling_project_info
730            .and_then(|p| p.get_public_key_config())
731            .map(|pkc| pkc.public_key);
732
733        let outputs = metric!(timer(RelayTimers::EnvelopeProcessingTime), {
734            self.process(message.envelope, ctx).await
735        });
736
737        let ctx = ctx.to_forward();
738        for Output { main, metrics } in outputs {
739            if let Some(metrics) = metrics {
740                let agg = &self.inner.addrs.aggregator;
741                metrics.accept(|metrics| {
742                    send_metrics(metrics, project_key, sampling_key, agg);
743                });
744            }
745
746            if let Some(output) = main {
747                // Only counting processing time for COGS at the moment.
748                self.submit_upstream(&mut Token::noop(), output, ctx);
749            }
750        }
751    }
752
753    fn handle_process_metrics(&self, cogs: &mut Token, message: ProcessMetrics) {
754        let ProcessMetrics {
755            data,
756            project_key,
757            received_at,
758            sent_at,
759            source,
760        } = message;
761
762        let received_timestamp =
763            UnixTimestamp::from_datetime(received_at).unwrap_or(UnixTimestamp::now());
764
765        let mut buckets = data.into_buckets(received_timestamp);
766        if buckets.is_empty() {
767            return;
768        };
769        cogs.update(relay_metrics::cogs::BySize(&buckets));
770
771        let clock_drift_processor =
772            ClockDriftProcessor::new(sent_at, received_at).at_least(MINIMUM_CLOCK_DRIFT);
773
774        buckets.retain_mut(|bucket| {
775            if let Err(error) = relay_metrics::normalize_bucket(bucket) {
776                relay_log::debug!(error = &error as &dyn Error, "dropping bucket {bucket:?}");
777                return false;
778            }
779
780            if !self::metrics::is_valid_namespace(bucket) {
781                return false;
782            }
783
784            clock_drift_processor.process_timestamp(&mut bucket.timestamp);
785
786            if !matches!(source, BucketSource::Internal) {
787                bucket.metadata = BucketMetadata::new(received_timestamp);
788            }
789
790            true
791        });
792
793        let project = self.inner.project_cache.get(project_key);
794
795        // Best effort check to filter and rate limit buckets, if there is no project state
796        // available at the current time, we will check again after flushing.
797        let buckets = match project.state() {
798            ProjectState::Enabled(project_info) => {
799                let rate_limits = project.rate_limits().current_limits();
800                self.check_buckets(project_key, project_info, &rate_limits, buckets)
801            }
802            _ => buckets,
803        };
804
805        relay_log::trace!("merging metric buckets into the aggregator");
806        self.inner
807            .addrs
808            .aggregator
809            .send(MergeBuckets::new(project_key, buckets));
810    }
811
812    fn handle_process_batched_metrics(&self, cogs: &mut Token, message: ProcessBatchedMetrics) {
813        let ProcessBatchedMetrics {
814            payload,
815            source,
816            received_at,
817            sent_at,
818        } = message;
819
820        #[derive(serde::Deserialize)]
821        struct Wrapper {
822            buckets: HashMap<ProjectKey, Vec<Bucket>>,
823        }
824
825        let buckets = match serde_json::from_slice(&payload) {
826            Ok(Wrapper { buckets }) => buckets,
827            Err(error) => {
828                relay_log::debug!(
829                    error = &error as &dyn Error,
830                    "failed to parse batched metrics",
831                );
832                metric!(counter(RelayCounters::MetricBucketsParsingFailed) += 1);
833                return;
834            }
835        };
836
837        for (project_key, buckets) in buckets {
838            self.handle_process_metrics(
839                cogs,
840                ProcessMetrics {
841                    data: MetricData::Parsed(buckets),
842                    project_key,
843                    source,
844                    received_at,
845                    sent_at,
846                },
847            )
848        }
849    }
850
851    /// Submits a processor [`Output`] to the appropriate upstream.
852    ///
853    /// If processing is enabled, the upstream is Kafka.
854    fn submit_upstream(
855        &self,
856        cogs: &mut Token,
857        output: Outputs,
858        ctx: processing::ForwardContext<'_>,
859    ) {
860        let _submit = cogs.start_category("submit");
861
862        #[cfg(feature = "processing")]
863        if ctx.config.processing_enabled()
864            && let Some(store_forwarder) = &self.inner.addrs.store_forwarder
865        {
866            use crate::processing::StoreHandle;
867
868            let objectstore = self.inner.addrs.objectstore.as_ref();
869            let handle = StoreHandle::new(store_forwarder, objectstore, ctx.global_config);
870
871            output
872                .forward_store(handle, ctx)
873                .unwrap_or_else(|err| err.into_inner());
874
875            return;
876        }
877
878        match output.serialize_envelope(ctx) {
879            Ok(envelope) => {
880                let envelope = ManagedEnvelope::from(envelope);
881                self.submit_envelope_upstream(envelope, ctx.project_info.upstream.clone());
882            }
883            Err(_) => relay_log::error!("failed to serialize output to an envelope"),
884        };
885    }
886
887    fn submit_envelope_upstream(
888        &self,
889        mut envelope: ManagedEnvelope,
890        // Currently allowed to be optional as code is migrated to respect the upstream override
891        // provided from the project config. Eventually must be available and is required.
892        upstream: Option<UpstreamDescriptor>,
893    ) {
894        if envelope.envelope_mut().is_empty() {
895            envelope.accept();
896            return;
897        }
898
899        // No code path should hit this.
900        //
901        // Any item which is produced by processing is handled in `submit_upstream`,
902        // metrics are sent to the store directly and outcomes must be produced to Kafka
903        // instead of being sent onward as client report.
904        if self.inner.config.processing_enabled() {
905            relay_log::error!(
906                "attempt to forward envelope to http upstream when processing is enabled"
907            );
908            return;
909        }
910
911        // Override the `sent_at` timestamp. Since the envelope went through basic
912        // normalization, all timestamps have been corrected. We propagate the new
913        // `sent_at` to allow the next Relay to double-check this timestamp and
914        // potentially apply correction again. This is done as close to sending as
915        // possible so that we avoid internal delays.
916        envelope.envelope_mut().set_sent_at(Utc::now());
917
918        relay_log::trace!("sending envelope to sentry endpoint");
919        let http_encoding = self.inner.config.http_encoding();
920        let result = envelope.envelope().to_vec().and_then(|v| {
921            encode_payload(&v.into(), http_encoding).map_err(EnvelopeError::PayloadIoFailed)
922        });
923
924        match result {
925            Ok(body) => {
926                self.inner
927                    .addrs
928                    .upstream_relay
929                    .send(SendRequest(SendEnvelope {
930                        upstream,
931                        envelope,
932                        body,
933                        http_encoding,
934                        project_cache: self.inner.project_cache.clone(),
935                    }));
936            }
937            Err(error) => {
938                // Errors are only logged for what we consider an internal discard reason. These
939                // indicate errors in the infrastructure or implementation bugs.
940                relay_log::error!(
941                    error = &error as &dyn Error,
942                    tags.project_key = %envelope.scoping().project_key,
943                    "failed to serialize envelope payload"
944                );
945
946                envelope.reject(Outcome::Invalid(DiscardReason::Internal));
947            }
948        }
949    }
950
951    fn handle_submit_client_reports(&self, message: SubmitClientReports) {
952        let SubmitClientReports {
953            client_reports,
954            scoping,
955        } = message;
956
957        let upstream = self.inner.config.upstream();
958        let dsn = PartialDsn::outbound(&scoping, upstream);
959
960        let mut envelope = Envelope::from_request(None, RequestMeta::outbound(dsn));
961        for client_report in client_reports {
962            match client_report.serialize() {
963                Ok(payload) => {
964                    let mut item = Item::new(ItemType::ClientReport);
965                    item.set_payload(ContentType::Json, payload);
966                    envelope.add_item(item);
967                }
968                Err(error) => {
969                    relay_log::error!(
970                        error = &error as &dyn std::error::Error,
971                        "failed to serialize client report"
972                    );
973                }
974            }
975        }
976
977        let envelope = ManagedEnvelope::new(envelope, self.inner.addrs.outcome_aggregator.clone());
978        self.submit_envelope_upstream(envelope, None);
979    }
980
981    fn check_buckets(
982        &self,
983        project_key: ProjectKey,
984        project_info: &ProjectInfo,
985        rate_limits: &RateLimits,
986        buckets: Vec<Bucket>,
987    ) -> Vec<Bucket> {
988        let Some(scoping) = project_info.scoping(project_key) else {
989            relay_log::error!(
990                tags.project_key = project_key.as_str(),
991                "there is no scoping: dropping {} buckets",
992                buckets.len(),
993            );
994            return Vec::new();
995        };
996
997        let mut buckets = self::metrics::apply_project_info(
998            buckets,
999            &self.inner.metric_outcomes,
1000            project_info,
1001            scoping,
1002        );
1003
1004        let namespaces: BTreeSet<MetricNamespace> = buckets
1005            .iter()
1006            .filter_map(|bucket| bucket.name.try_namespace())
1007            .collect();
1008
1009        for namespace in namespaces {
1010            let limits = rate_limits.check_with_quotas(
1011                project_info.get_quotas(),
1012                scoping.item(DataCategory::MetricBucket),
1013            );
1014
1015            if limits.is_limited() {
1016                let rejected;
1017                (buckets, rejected) = utils::split_off(buckets, |bucket| {
1018                    bucket.name.try_namespace() == Some(namespace)
1019                });
1020
1021                let reason_code = limits.longest().and_then(|limit| limit.reason_code.clone());
1022                self.inner.metric_outcomes.track(
1023                    scoping,
1024                    &rejected,
1025                    Outcome::RateLimited(reason_code),
1026                );
1027            }
1028        }
1029
1030        let quotas = project_info.config.quotas.clone();
1031        match MetricsLimiter::create(buckets, quotas, scoping) {
1032            Ok(mut bucket_limiter) => {
1033                bucket_limiter.enforce_limits(rate_limits, &self.inner.metric_outcomes);
1034                bucket_limiter.into_buckets()
1035            }
1036            Err(buckets) => buckets,
1037        }
1038    }
1039
1040    #[cfg(feature = "processing")]
1041    async fn rate_limit_buckets(
1042        &self,
1043        scoping: Scoping,
1044        project_info: &ProjectInfo,
1045        mut buckets: Vec<Bucket>,
1046    ) -> Vec<Bucket> {
1047        let Some(rate_limiter) = &self.inner.rate_limiter else {
1048            return buckets;
1049        };
1050
1051        let global_config = self.inner.global_config.current().unwrap_or_default();
1052        let namespaces = buckets
1053            .iter()
1054            .filter_map(|bucket| bucket.name.try_namespace())
1055            .counts();
1056
1057        let quotas = CombinedQuotas::new(&global_config, project_info.get_quotas());
1058
1059        for (namespace, quantity) in namespaces {
1060            let item_scoping = scoping.metric_bucket(namespace);
1061
1062            let limits = match rate_limiter
1063                .is_rate_limited(quotas, item_scoping, quantity, false)
1064                .await
1065            {
1066                Ok(limits) => limits,
1067                Err(err) => {
1068                    relay_log::error!(
1069                        error = &err as &dyn std::error::Error,
1070                        "failed to check redis rate limits"
1071                    );
1072                    break;
1073                }
1074            };
1075
1076            if limits.is_limited() {
1077                let rejected;
1078                (buckets, rejected) = utils::split_off(buckets, |bucket| {
1079                    bucket.name.try_namespace() == Some(namespace)
1080                });
1081
1082                let reason_code = limits.longest().and_then(|limit| limit.reason_code.clone());
1083                self.inner.metric_outcomes.track(
1084                    scoping,
1085                    &rejected,
1086                    Outcome::RateLimited(reason_code),
1087                );
1088
1089                self.inner
1090                    .project_cache
1091                    .get(item_scoping.scoping.project_key)
1092                    .rate_limits()
1093                    .merge(limits);
1094            }
1095        }
1096
1097        match MetricsLimiter::create(buckets, project_info.config.quotas.clone(), scoping) {
1098            Err(buckets) => buckets,
1099            Ok(bucket_limiter) => self.apply_other_rate_limits(bucket_limiter).await,
1100        }
1101    }
1102
1103    /// Check and apply rate limits to metrics buckets for transactions and spans.
1104    #[cfg(feature = "processing")]
1105    async fn apply_other_rate_limits(&self, mut bucket_limiter: MetricsLimiter) -> Vec<Bucket> {
1106        relay_log::trace!("handle_rate_limit_buckets");
1107
1108        let scoping = *bucket_limiter.scoping();
1109
1110        if let Some(rate_limiter) = self.inner.rate_limiter.as_ref() {
1111            let global_config = self.inner.global_config.current().unwrap_or_default();
1112            let quotas = CombinedQuotas::new(&global_config, bucket_limiter.quotas());
1113
1114            // We set over_accept_once such that the limit is actually reached, which allows subsequent
1115            // calls with quantity=0 to be rate limited.
1116            let over_accept_once = true;
1117            let mut rate_limits = RateLimits::new();
1118
1119            let (category, count) = bucket_limiter.count();
1120
1121            let timer = Instant::now();
1122            let mut is_limited = false;
1123
1124            if let Some(count) = count {
1125                match rate_limiter
1126                    .is_rate_limited(quotas, scoping.item(category), count, over_accept_once)
1127                    .await
1128                {
1129                    Ok(limits) => {
1130                        is_limited = limits.is_limited();
1131                        rate_limits.merge(limits)
1132                    }
1133                    Err(e) => {
1134                        relay_log::error!(error = &e as &dyn Error, "rate limiting error")
1135                    }
1136                }
1137            }
1138
1139            relay_statsd::metric!(
1140                timer(RelayTimers::RateLimitBucketsDuration) = timer.elapsed(),
1141                category = category.name(),
1142                limited = if is_limited { "true" } else { "false" },
1143                count = match count {
1144                    None => "none",
1145                    Some(0) => "0",
1146                    Some(1) => "1",
1147                    Some(1..=10) => "10",
1148                    Some(1..=25) => "25",
1149                    Some(1..=50) => "50",
1150                    Some(51..=100) => "100",
1151                    Some(101..=500) => "500",
1152                    _ => "> 500",
1153                },
1154            );
1155
1156            if rate_limits.is_limited() {
1157                let was_enforced =
1158                    bucket_limiter.enforce_limits(&rate_limits, &self.inner.metric_outcomes);
1159
1160                if was_enforced {
1161                    // Update the rate limits in the project cache.
1162                    self.inner
1163                        .project_cache
1164                        .get(scoping.project_key)
1165                        .rate_limits()
1166                        .merge(rate_limits);
1167                }
1168            }
1169        }
1170
1171        bucket_limiter.into_buckets()
1172    }
1173
1174    /// Processes metric buckets and sends them to Kafka.
1175    ///
1176    /// This function runs the following steps:
1177    ///  - rate limiting
1178    ///  - submit to `StoreForwarder`
1179    #[cfg(feature = "processing")]
1180    async fn encode_metrics_processing(
1181        &self,
1182        message: FlushBuckets,
1183        store_forwarder: &Addr<Store>,
1184    ) {
1185        use crate::constants::DEFAULT_EVENT_RETENTION;
1186        use crate::services::store::StoreMetrics;
1187
1188        for ProjectBuckets {
1189            buckets,
1190            scoping,
1191            project_info,
1192            ..
1193        } in message.buckets.into_values()
1194        {
1195            let buckets = self
1196                .rate_limit_buckets(scoping, &project_info, buckets)
1197                .await;
1198
1199            if buckets.is_empty() {
1200                continue;
1201            }
1202
1203            let retention = project_info
1204                .config
1205                .event_retention
1206                .unwrap_or(DEFAULT_EVENT_RETENTION);
1207
1208            // The store forwarder takes care of bucket splitting internally, so we can submit the
1209            // entire list of buckets. There is no batching needed here.
1210            store_forwarder.send(StoreMetrics {
1211                buckets,
1212                scoping,
1213                retention,
1214            });
1215        }
1216    }
1217
1218    /// Serializes metric buckets to JSON and sends them to the upstream.
1219    ///
1220    /// This function runs the following steps:
1221    ///  - partitioning
1222    ///  - batching by configured size limit
1223    ///  - serialize to JSON and pack in an envelope
1224    ///
1225    /// Rate limiting runs only in processing Relays as it requires access to the central Redis instance.
1226    /// Cached rate limits are applied in the project cache already.
1227    fn encode_metrics_envelope(&self, message: FlushBuckets) {
1228        let FlushBuckets {
1229            partition_key,
1230            buckets,
1231        } = message;
1232
1233        let batch_size = self.inner.config.metrics_max_batch_size_bytes();
1234        let upstream = self.inner.config.upstream();
1235
1236        for ProjectBuckets {
1237            buckets,
1238            scoping,
1239            project_info,
1240            ..
1241        } in buckets.values()
1242        {
1243            let dsn = PartialDsn::outbound(scoping, upstream);
1244
1245            relay_statsd::metric!(
1246                distribution(RelayDistributions::PartitionKeys) = u64::from(partition_key)
1247            );
1248
1249            let mut num_batches = 0;
1250            for batch in BucketsView::from(buckets).by_size(batch_size) {
1251                let mut envelope = Envelope::from_request(None, RequestMeta::outbound(dsn.clone()));
1252
1253                let mut item = Item::new(ItemType::MetricBuckets);
1254                item.set_source_quantities(crate::metrics::extract_quantities(batch));
1255                item.set_payload(ContentType::Json, serde_json::to_vec(&buckets).unwrap());
1256                envelope.add_item(item);
1257
1258                let mut envelope =
1259                    ManagedEnvelope::new(envelope, self.inner.addrs.outcome_aggregator.clone());
1260                envelope
1261                    .set_partition_key(Some(partition_key))
1262                    .scope(*scoping);
1263
1264                relay_statsd::metric!(
1265                    distribution(RelayDistributions::BucketsPerBatch) = batch.len() as u64
1266                );
1267
1268                self.submit_envelope_upstream(envelope, project_info.upstream.clone());
1269                num_batches += 1;
1270            }
1271
1272            relay_statsd::metric!(
1273                distribution(RelayDistributions::BatchesPerPartition) = num_batches
1274            );
1275        }
1276    }
1277
1278    /// Creates a [`SendMetricsRequest`] and sends it to the upstream relay.
1279    fn send_global_partition(
1280        &self,
1281        upstream: Option<UpstreamDescriptor>,
1282        partition_key: u32,
1283        partition: &mut Partition<'_>,
1284    ) {
1285        if partition.is_empty() {
1286            return;
1287        }
1288
1289        let (unencoded, project_info) = partition.take();
1290        let http_encoding = self.inner.config.http_encoding();
1291        let encoded = match encode_payload(&unencoded, http_encoding) {
1292            Ok(payload) => payload,
1293            Err(error) => {
1294                let error = &error as &dyn std::error::Error;
1295                relay_log::error!(error, "failed to encode metrics payload");
1296                return;
1297            }
1298        };
1299
1300        let request = SendMetricsRequest {
1301            upstream,
1302            partition_key: partition_key.to_string(),
1303            unencoded,
1304            encoded,
1305            project_info,
1306            http_encoding,
1307            metric_outcomes: self.inner.metric_outcomes.clone(),
1308        };
1309
1310        self.inner.addrs.upstream_relay.send(SendRequest(request));
1311    }
1312
1313    /// Serializes metric buckets to JSON and sends them to the upstream via the global endpoint.
1314    ///
1315    /// This function is similar to [`Self::encode_metrics_envelope`], but sends a global batched
1316    /// payload directly instead of per-project Envelopes.
1317    ///
1318    /// This function runs the following steps:
1319    ///  - partitioning
1320    ///  - batching by configured size limit
1321    ///  - serialize to JSON
1322    ///  - submit directly to the upstream
1323    fn encode_metrics_global(&self, message: FlushBuckets) {
1324        let FlushBuckets {
1325            partition_key,
1326            buckets,
1327        } = message;
1328
1329        let batch_size = self.inner.config.metrics_max_batch_size_bytes();
1330        let mut partitions = BTreeMap::new();
1331        let mut partition_splits = 0;
1332
1333        for ProjectBuckets {
1334            buckets,
1335            scoping,
1336            project_info,
1337            ..
1338        } in buckets.values()
1339        {
1340            let partition = match partitions.get_mut(&project_info.upstream) {
1341                Some(partition) => partition,
1342                None => partitions
1343                    .entry(project_info.upstream.clone())
1344                    .or_insert_with(|| Partition::new(batch_size)),
1345            };
1346
1347            for bucket in buckets {
1348                let mut remaining = Some(BucketView::new(bucket));
1349
1350                while let Some(bucket) = remaining.take() {
1351                    if let Some(next) = partition.insert(bucket, *scoping) {
1352                        // A part of the bucket could not be inserted. Take the partition and submit
1353                        // it immediately. Repeat until the final part was inserted. This should
1354                        // always result in a request, otherwise we would enter an endless loop.
1355                        self.send_global_partition(
1356                            project_info.upstream.clone(),
1357                            partition_key,
1358                            partition,
1359                        );
1360                        remaining = Some(next);
1361                        partition_splits += 1;
1362                    }
1363                }
1364            }
1365        }
1366
1367        if partition_splits > 0 {
1368            metric!(distribution(RelayDistributions::PartitionSplits) = partition_splits);
1369        }
1370
1371        for (upstream, mut partition) in partitions {
1372            self.send_global_partition(upstream, partition_key, &mut partition);
1373        }
1374    }
1375
1376    async fn handle_flush_buckets(&self, mut message: FlushBuckets) {
1377        for (project_key, pb) in message.buckets.iter_mut() {
1378            let buckets = std::mem::take(&mut pb.buckets);
1379            pb.buckets =
1380                self.check_buckets(*project_key, &pb.project_info, &pb.rate_limits, buckets);
1381        }
1382
1383        #[cfg(feature = "processing")]
1384        if self.inner.config.processing_enabled()
1385            && let Some(ref store_forwarder) = self.inner.addrs.store_forwarder
1386        {
1387            return self
1388                .encode_metrics_processing(message, store_forwarder)
1389                .await;
1390        }
1391
1392        if self.inner.config.http_global_metrics() {
1393            self.encode_metrics_global(message)
1394        } else {
1395            self.encode_metrics_envelope(message)
1396        }
1397    }
1398
1399    #[cfg(all(test, feature = "processing"))]
1400    fn redis_rate_limiter_enabled(&self) -> bool {
1401        self.inner.rate_limiter.is_some()
1402    }
1403
1404    async fn handle_message(&self, message: EnvelopeProcessor) {
1405        let ty = message.variant();
1406        let feature_weights = self.feature_weights(&message);
1407
1408        metric!(timer(RelayTimers::ProcessMessageDuration), message = ty, {
1409            let mut cogs = self.inner.cogs.timed(ResourceId::Relay, feature_weights);
1410
1411            match message {
1412                EnvelopeProcessor::ProcessEnvelope(m) => {
1413                    self.handle_process_envelope(&mut cogs, *m).await
1414                }
1415                EnvelopeProcessor::ProcessProjectMetrics(m) => {
1416                    self.handle_process_metrics(&mut cogs, *m)
1417                }
1418                EnvelopeProcessor::ProcessBatchedMetrics(m) => {
1419                    self.handle_process_batched_metrics(&mut cogs, *m)
1420                }
1421                EnvelopeProcessor::FlushBuckets(m) => self.handle_flush_buckets(*m).await,
1422                EnvelopeProcessor::SubmitClientReports(m) => self.handle_submit_client_reports(*m),
1423            }
1424        });
1425    }
1426
1427    fn feature_weights(&self, message: &EnvelopeProcessor) -> FeatureWeights {
1428        match message {
1429            // Envelope is split later and tokens are attributed then.
1430            EnvelopeProcessor::ProcessEnvelope(_) => AppFeature::Unattributed.into(),
1431            EnvelopeProcessor::ProcessProjectMetrics(_) => AppFeature::Unattributed.into(),
1432            EnvelopeProcessor::ProcessBatchedMetrics(_) => AppFeature::Unattributed.into(),
1433            EnvelopeProcessor::FlushBuckets(v) => v
1434                .buckets
1435                .values()
1436                .map(|s| {
1437                    if self.inner.config.processing_enabled() {
1438                        // Processing does not encode the metrics but instead rate limit the metrics,
1439                        // which scales by count and not size.
1440                        relay_metrics::cogs::ByCount(&s.buckets).into()
1441                    } else {
1442                        relay_metrics::cogs::BySize(&s.buckets).into()
1443                    }
1444                })
1445                .fold(FeatureWeights::none(), FeatureWeights::merge),
1446            EnvelopeProcessor::SubmitClientReports(_) => AppFeature::ClientReports.into(),
1447        }
1448    }
1449}
1450
1451impl Service for EnvelopeProcessorService {
1452    type Interface = EnvelopeProcessor;
1453
1454    async fn run(self, mut rx: relay_system::Receiver<Self::Interface>) {
1455        while let Some(message) = rx.recv().await {
1456            let service = self.clone();
1457            self.inner
1458                .pool
1459                .spawn_async(
1460                    async move {
1461                        service.handle_message(message).await;
1462                    }
1463                    .boxed(),
1464                )
1465                .await;
1466        }
1467    }
1468}
1469
1470pub fn encode_payload(body: &Bytes, http_encoding: HttpEncoding) -> Result<Bytes, std::io::Error> {
1471    let envelope_body: Vec<u8> = match http_encoding {
1472        HttpEncoding::Identity => return Ok(body.clone()),
1473        HttpEncoding::Deflate => {
1474            let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
1475            encoder.write_all(body.as_ref())?;
1476            encoder.finish()?
1477        }
1478        HttpEncoding::Gzip => {
1479            let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
1480            encoder.write_all(body.as_ref())?;
1481            encoder.finish()?
1482        }
1483        HttpEncoding::Br => {
1484            // Use default buffer size (via 0), medium quality (5), and the default lgwin (22).
1485            let mut encoder = BrotliEncoder::new(Vec::new(), 0, 5, 22);
1486            encoder.write_all(body.as_ref())?;
1487            encoder.into_inner()
1488        }
1489        HttpEncoding::Zstd => {
1490            // Use the fastest compression level, our main objective here is to get the best
1491            // compression ratio for least amount of time spent.
1492            let mut encoder = ZstdEncoder::new(Vec::new(), 1)?;
1493            encoder.write_all(body.as_ref())?;
1494            encoder.finish()?
1495        }
1496    };
1497
1498    Ok(envelope_body.into())
1499}
1500
1501/// An upstream request that submits an envelope via HTTP.
1502#[derive(Debug)]
1503pub struct SendEnvelope {
1504    pub upstream: Option<UpstreamDescriptor>,
1505    pub envelope: ManagedEnvelope,
1506    pub body: Bytes,
1507    pub http_encoding: HttpEncoding,
1508    pub project_cache: ProjectCacheHandle,
1509}
1510
1511impl UpstreamRequest for SendEnvelope {
1512    fn upstream(&self) -> Option<&UpstreamDescriptor> {
1513        self.upstream.as_ref()
1514    }
1515
1516    fn method(&self) -> reqwest::Method {
1517        reqwest::Method::POST
1518    }
1519
1520    fn path(&self) -> Cow<'_, str> {
1521        format!("/api/{}/envelope/", self.envelope.scoping().project_id).into()
1522    }
1523
1524    fn route(&self) -> &'static str {
1525        "envelope"
1526    }
1527
1528    fn build(&mut self, builder: &mut http::RequestBuilder) -> Result<(), http::HttpError> {
1529        let envelope_body = self.body.clone();
1530        metric!(
1531            distribution(RelayDistributions::UpstreamEnvelopeBodySize) = envelope_body.len() as u64
1532        );
1533
1534        let meta = &self.envelope.meta();
1535        let shard = self.envelope.partition_key().map(|p| p.to_string());
1536        builder
1537            .content_encoding(self.http_encoding)
1538            .header_opt("Origin", meta.origin().map(|url| url.as_str()))
1539            .header_opt("User-Agent", meta.user_agent())
1540            .header("X-Sentry-Auth", meta.auth_header())
1541            .header("X-Forwarded-For", meta.forwarded_for())
1542            .header("Content-Type", envelope::CONTENT_TYPE)
1543            .header_opt("X-Sentry-Relay-Shard", shard)
1544            .body(envelope_body);
1545
1546        Ok(())
1547    }
1548
1549    fn sign(&mut self) -> Option<Sign> {
1550        Some(Sign::Optional(SignatureType::RequestSign))
1551    }
1552
1553    fn respond(
1554        self: Box<Self>,
1555        result: Result<http::Response, UpstreamRequestError>,
1556    ) -> Pin<Box<dyn Future<Output = ()> + Send + Sync>> {
1557        Box::pin(async move {
1558            let result = match result {
1559                Ok(mut response) => response.consume().await.map_err(UpstreamRequestError::Http),
1560                Err(error) => Err(error),
1561            };
1562
1563            match result {
1564                Ok(()) => self.envelope.accept(),
1565                Err(error) if error.is_received() => {
1566                    let scoping = self.envelope.scoping();
1567                    self.envelope.accept();
1568
1569                    if let UpstreamRequestError::RateLimited(limits) = error {
1570                        self.project_cache
1571                            .get(scoping.project_key)
1572                            .rate_limits()
1573                            .merge(limits.scope(&scoping));
1574                    }
1575                }
1576                Err(error) => {
1577                    // Errors are only logged for what we consider an internal discard reason. These
1578                    // indicate errors in the infrastructure or implementation bugs.
1579                    let mut envelope = self.envelope;
1580                    envelope.reject(Outcome::Invalid(DiscardReason::Internal));
1581                    relay_log::error!(
1582                        error = &error as &dyn Error,
1583                        tags.project_key = %envelope.scoping().project_key,
1584                        "error sending envelope"
1585                    );
1586                }
1587            }
1588        })
1589    }
1590}
1591
1592/// A container for metric buckets from multiple projects.
1593///
1594/// This container is used to send metrics to the upstream in global batches as part of the
1595/// [`FlushBuckets`] message if the `http.global_metrics` option is enabled. The container monitors
1596/// the size of all metrics and allows to split them into multiple batches. See
1597/// [`insert`](Self::insert) for more information.
1598#[derive(Debug)]
1599struct Partition<'a> {
1600    max_size: usize,
1601    remaining: usize,
1602    views: HashMap<ProjectKey, Vec<BucketView<'a>>>,
1603    project_info: HashMap<ProjectKey, Scoping>,
1604}
1605
1606impl<'a> Partition<'a> {
1607    /// Creates a new partition with the given maximum size in bytes.
1608    pub fn new(size: usize) -> Self {
1609        Self {
1610            max_size: size,
1611            remaining: size,
1612            views: HashMap::new(),
1613            project_info: HashMap::new(),
1614        }
1615    }
1616
1617    /// Inserts a bucket into the partition, splitting it if necessary.
1618    ///
1619    /// This function attempts to add the bucket to this partition. If the bucket does not fit
1620    /// entirely into the partition given its maximum size, the remaining part of the bucket is
1621    /// returned from this function call.
1622    ///
1623    /// If this function returns `Some(_)`, the partition is full and should be submitted to the
1624    /// upstream immediately. Use [`Self::take`] to retrieve the contents of the
1625    /// partition. Afterwards, the caller is responsible to call this function again with the
1626    /// remaining bucket until it is fully inserted.
1627    pub fn insert(&mut self, bucket: BucketView<'a>, scoping: Scoping) -> Option<BucketView<'a>> {
1628        let (current, next) = bucket.split(self.remaining, Some(self.max_size));
1629
1630        if let Some(current) = current {
1631            self.remaining = self.remaining.saturating_sub(current.estimated_size());
1632            self.views
1633                .entry(scoping.project_key)
1634                .or_default()
1635                .push(current);
1636
1637            self.project_info
1638                .entry(scoping.project_key)
1639                .or_insert(scoping);
1640        }
1641
1642        next
1643    }
1644
1645    /// Returns `true` if the partition does not hold any data.
1646    fn is_empty(&self) -> bool {
1647        self.views.is_empty()
1648    }
1649
1650    /// Returns the serialized buckets for this partition.
1651    ///
1652    /// This empties the partition, so that it can be reused.
1653    fn take(&mut self) -> (Bytes, HashMap<ProjectKey, Scoping>) {
1654        #[derive(serde::Serialize)]
1655        struct Wrapper<'a> {
1656            buckets: &'a HashMap<ProjectKey, Vec<BucketView<'a>>>,
1657        }
1658
1659        let buckets = &self.views;
1660        let payload = serde_json::to_vec(&Wrapper { buckets }).unwrap().into();
1661
1662        let scopings = std::mem::take(&mut self.project_info);
1663
1664        self.views.clear();
1665        self.remaining = self.max_size;
1666
1667        (payload, scopings)
1668    }
1669}
1670
1671/// An upstream request that submits metric buckets via HTTP.
1672///
1673/// This request is not awaited. It automatically tracks outcomes if the request is not received.
1674#[derive(Debug)]
1675struct SendMetricsRequest {
1676    /// Optional upstream override where the request will be sent to.
1677    upstream: Option<UpstreamDescriptor>,
1678    /// If the partition key is set, the request is marked with `X-Sentry-Relay-Shard`.
1679    partition_key: String,
1680    /// Serialized metric buckets without encoding applied, used for signing.
1681    unencoded: Bytes,
1682    /// Serialized metric buckets with the stated HTTP encoding applied.
1683    encoded: Bytes,
1684    /// Mapping of all contained project keys to their scoping and extraction mode.
1685    ///
1686    /// Used to track outcomes for transmission failures.
1687    project_info: HashMap<ProjectKey, Scoping>,
1688    /// Encoding (compression) of the payload.
1689    http_encoding: HttpEncoding,
1690    /// Metric outcomes instance to send outcomes on error.
1691    metric_outcomes: MetricOutcomes,
1692}
1693
1694impl SendMetricsRequest {
1695    fn create_error_outcomes(self) {
1696        #[derive(serde::Deserialize)]
1697        struct Wrapper {
1698            buckets: HashMap<ProjectKey, Vec<MinimalTrackableBucket>>,
1699        }
1700
1701        let buckets = match serde_json::from_slice(&self.unencoded) {
1702            Ok(Wrapper { buckets }) => buckets,
1703            Err(err) => {
1704                relay_log::error!(
1705                    error = &err as &dyn std::error::Error,
1706                    "failed to parse buckets from failed transmission"
1707                );
1708                return;
1709            }
1710        };
1711
1712        for (key, buckets) in buckets {
1713            let Some(&scoping) = self.project_info.get(&key) else {
1714                relay_log::error!("missing scoping for project key");
1715                continue;
1716            };
1717
1718            self.metric_outcomes.track(
1719                scoping,
1720                &buckets,
1721                Outcome::Invalid(DiscardReason::Internal),
1722            );
1723        }
1724    }
1725}
1726
1727impl UpstreamRequest for SendMetricsRequest {
1728    fn upstream(&self) -> Option<&UpstreamDescriptor> {
1729        self.upstream.as_ref()
1730    }
1731
1732    fn set_relay_id(&self) -> bool {
1733        true
1734    }
1735
1736    fn sign(&mut self) -> Option<Sign> {
1737        Some(Sign::Required(SignatureType::Body(self.unencoded.clone())))
1738    }
1739
1740    fn method(&self) -> reqwest::Method {
1741        reqwest::Method::POST
1742    }
1743
1744    fn path(&self) -> Cow<'_, str> {
1745        "/api/0/relays/metrics/".into()
1746    }
1747
1748    fn route(&self) -> &'static str {
1749        "global_metrics"
1750    }
1751
1752    fn build(&mut self, builder: &mut http::RequestBuilder) -> Result<(), http::HttpError> {
1753        metric!(
1754            distribution(RelayDistributions::UpstreamMetricsBodySize) = self.encoded.len() as u64
1755        );
1756
1757        builder
1758            .content_encoding(self.http_encoding)
1759            .header("X-Sentry-Relay-Shard", self.partition_key.as_bytes())
1760            .header(header::CONTENT_TYPE, b"application/json")
1761            .body(self.encoded.clone());
1762
1763        Ok(())
1764    }
1765
1766    fn respond(
1767        self: Box<Self>,
1768        result: Result<http::Response, UpstreamRequestError>,
1769    ) -> Pin<Box<dyn Future<Output = ()> + Send + Sync>> {
1770        Box::pin(async {
1771            match result {
1772                Ok(mut response) => {
1773                    response.consume().await.ok();
1774                }
1775                Err(error) => {
1776                    relay_log::error!(error = &error as &dyn Error, "Failed to send metrics batch");
1777
1778                    // If the request did not arrive at the upstream, we are responsible for outcomes.
1779                    // Otherwise, the upstream is responsible to log outcomes.
1780                    if error.is_received() {
1781                        return;
1782                    }
1783
1784                    self.create_error_outcomes()
1785                }
1786            }
1787        })
1788    }
1789}
1790
1791/// Container for global and project level [`Quota`].
1792#[derive(Copy, Clone, Debug)]
1793#[cfg(feature = "processing")]
1794struct CombinedQuotas<'a> {
1795    global_quotas: &'a [Quota],
1796    project_quotas: &'a [Quota],
1797}
1798
1799#[cfg(feature = "processing")]
1800impl<'a> CombinedQuotas<'a> {
1801    /// Returns a new [`CombinedQuotas`].
1802    pub fn new(global_config: &'a GlobalConfig, project_quotas: &'a [Quota]) -> Self {
1803        Self {
1804            global_quotas: &global_config.quotas,
1805            project_quotas,
1806        }
1807    }
1808}
1809
1810#[cfg(feature = "processing")]
1811impl<'a> IntoIterator for CombinedQuotas<'a> {
1812    type Item = &'a Quota;
1813    type IntoIter = std::iter::Chain<std::slice::Iter<'a, Quota>, std::slice::Iter<'a, Quota>>;
1814
1815    fn into_iter(self) -> Self::IntoIter {
1816        self.global_quotas.iter().chain(self.project_quotas.iter())
1817    }
1818}
1819
1820#[cfg(test)]
1821mod tests {
1822    use insta::assert_debug_snapshot;
1823    use relay_common::glob2::LazyGlob;
1824    use relay_dynamic_config::ProjectConfig;
1825    use relay_event_normalization::{
1826        NormalizationConfig, RedactionRule, TransactionNameConfig, TransactionNameRule,
1827    };
1828    use relay_event_schema::protocol::{Event, EventId, TransactionSource};
1829    use relay_pii::DataScrubbingConfig;
1830    use relay_protocol::Annotated;
1831    use similar_asserts::assert_eq;
1832
1833    use crate::testutils::{create_test_processor, create_test_processor_with_addrs};
1834
1835    #[cfg(feature = "processing")]
1836    use {
1837        relay_metrics::BucketValue,
1838        relay_quotas::{QuotaScope, ReasonCode},
1839        relay_test::mock_service,
1840    };
1841
1842    use super::*;
1843
1844    async fn process_to_single_envelope<'a>(
1845        processor: &EnvelopeProcessorService,
1846        envelope: ManagedEnvelope,
1847        ctx: processing::Context<'a>,
1848    ) -> Box<Envelope> {
1849        let mut outputs = processor.process(envelope, ctx).await;
1850        assert_eq!(outputs.len(), 1);
1851
1852        let Output { main, metrics } = outputs.pop().unwrap();
1853
1854        if let Some(metrics) = metrics {
1855            metrics.accept(drop);
1856        }
1857
1858        main.unwrap()
1859            .serialize_envelope(ctx.to_forward())
1860            .unwrap()
1861            .accept(|envelope| envelope)
1862    }
1863
1864    #[cfg(feature = "processing")]
1865    fn mock_quota(id: &str) -> Quota {
1866        Quota {
1867            id: Some(id.into()),
1868            categories: [DataCategory::MetricBucket].into(),
1869            scope: QuotaScope::Organization,
1870            scope_id: None,
1871            limit: Some(0),
1872            window: None,
1873            reason_code: None,
1874            namespace: None,
1875        }
1876    }
1877
1878    #[cfg(feature = "processing")]
1879    #[test]
1880    fn test_dynamic_quotas() {
1881        let global_config = relay_dynamic_config::GlobalConfig {
1882            quotas: vec![mock_quota("foo"), mock_quota("bar")],
1883            ..Default::default()
1884        };
1885
1886        let project_quotas = vec![mock_quota("baz"), mock_quota("qux")];
1887
1888        let dynamic_quotas = CombinedQuotas::new(&global_config, &project_quotas);
1889
1890        let quota_ids = dynamic_quotas.into_iter().filter_map(|q| q.id.as_deref());
1891        assert!(quota_ids.eq(["foo", "bar", "baz", "qux"]));
1892    }
1893
1894    /// Ensures that if we ratelimit one batch of buckets in [`FlushBuckets`] message, it won't
1895    /// also ratelimit the next batches in the same message automatically.
1896    #[cfg(feature = "processing")]
1897    #[tokio::test]
1898    async fn test_ratelimit_per_batch() {
1899        use relay_base_schema::organization::OrganizationId;
1900        use relay_protocol::FiniteF64;
1901
1902        let rate_limited_org = Scoping {
1903            organization_id: OrganizationId::new(1),
1904            project_id: ProjectId::new(21),
1905            project_key: ProjectKey::parse("00000000000000000000000000000000").unwrap(),
1906            key_id: Some(17),
1907        };
1908
1909        let not_rate_limited_org = Scoping {
1910            organization_id: OrganizationId::new(2),
1911            project_id: ProjectId::new(21),
1912            project_key: ProjectKey::parse("11111111111111111111111111111111").unwrap(),
1913            key_id: Some(17),
1914        };
1915
1916        let message = {
1917            let project_info = {
1918                let quota = Quota {
1919                    id: Some("testing".into()),
1920                    categories: [DataCategory::MetricBucket].into(),
1921                    scope: relay_quotas::QuotaScope::Organization,
1922                    scope_id: Some(rate_limited_org.organization_id.to_string().into()),
1923                    limit: Some(0),
1924                    window: None,
1925                    reason_code: Some(ReasonCode::new("test")),
1926                    namespace: None,
1927                };
1928
1929                let mut config = ProjectConfig::default();
1930                config.quotas.push(quota);
1931
1932                Arc::new(ProjectInfo {
1933                    config,
1934                    ..Default::default()
1935                })
1936            };
1937
1938            let project_metrics = |scoping| ProjectBuckets {
1939                buckets: vec![Bucket {
1940                    name: "d:spans/bar".into(),
1941                    value: BucketValue::Counter(FiniteF64::new(1.0).unwrap()),
1942                    timestamp: UnixTimestamp::now(),
1943                    tags: Default::default(),
1944                    width: 10,
1945                    metadata: BucketMetadata::default(),
1946                }],
1947                rate_limits: Default::default(),
1948                project_info: project_info.clone(),
1949                scoping,
1950            };
1951
1952            let buckets = hashbrown::HashMap::from([
1953                (
1954                    rate_limited_org.project_key,
1955                    project_metrics(rate_limited_org),
1956                ),
1957                (
1958                    not_rate_limited_org.project_key,
1959                    project_metrics(not_rate_limited_org),
1960                ),
1961            ]);
1962
1963            FlushBuckets {
1964                partition_key: 0,
1965                buckets,
1966            }
1967        };
1968
1969        // ensure the order of the map while iterating is as expected.
1970        assert_eq!(message.buckets.keys().count(), 2);
1971
1972        let config = {
1973            let config_json = serde_json::json!({
1974                "processing": {
1975                    "enabled": true,
1976                    "kafka_config": [],
1977                    "redis": {
1978                        "server": std::env::var("RELAY_REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379".to_owned()),
1979                    }
1980                }
1981            });
1982            Config::from_json_value(config_json).unwrap()
1983        };
1984
1985        let (store, handle) = {
1986            let f = |org_ids: &mut Vec<OrganizationId>, msg: Store| {
1987                let org_id = match msg {
1988                    Store::Metrics(x) => x.scoping.organization_id,
1989                    _ => panic!("received envelope when expecting only metrics"),
1990                };
1991                org_ids.push(org_id);
1992            };
1993
1994            mock_service("store_forwarder", vec![], f)
1995        };
1996
1997        let processor = create_test_processor(config).await;
1998        assert!(processor.redis_rate_limiter_enabled());
1999
2000        processor.encode_metrics_processing(message, &store).await;
2001
2002        drop(store);
2003        let orgs_not_ratelimited = handle.await.unwrap();
2004
2005        assert_eq!(
2006            orgs_not_ratelimited,
2007            vec![not_rate_limited_org.organization_id]
2008        );
2009    }
2010
2011    #[tokio::test]
2012    async fn test_browser_version_extraction_with_pii_like_data() {
2013        let processor = create_test_processor(Default::default()).await;
2014        let outcome_aggregator = Addr::dummy();
2015        let event_id = EventId::new();
2016
2017        let dsn = "https://e12d836b15bb49d7bbf99e64295d995b:@sentry.io/42"
2018            .parse()
2019            .unwrap();
2020
2021        let request_meta = RequestMeta::new(dsn);
2022        let mut envelope = Envelope::from_request(Some(event_id), request_meta);
2023
2024        envelope.add_item({
2025                let mut item = Item::new(ItemType::Event);
2026                item.set_payload(
2027                    ContentType::Json,
2028                    r#"
2029                    {
2030                        "request": {
2031                            "headers": [
2032                                ["User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36"]
2033                            ]
2034                        }
2035                    }
2036                "#,
2037                );
2038                item
2039            });
2040
2041        let mut datascrubbing_settings = DataScrubbingConfig::default();
2042        // enable all the default scrubbing
2043        datascrubbing_settings.scrub_data = true;
2044        datascrubbing_settings.scrub_defaults = true;
2045        datascrubbing_settings.scrub_ip_addresses = true;
2046
2047        // Make sure to mask any IP-like looking data
2048        let pii_config = serde_json::from_str(r#"{"applications": {"**": ["@ip:mask"]}}"#).unwrap();
2049
2050        let config = ProjectConfig {
2051            datascrubbing_settings,
2052            pii_config: Some(pii_config),
2053            ..Default::default()
2054        };
2055
2056        let project_info = ProjectInfo {
2057            config,
2058            ..Default::default()
2059        };
2060
2061        let envelope = ManagedEnvelope::new(envelope, outcome_aggregator);
2062
2063        let ctx = processing::Context {
2064            project_info: &project_info,
2065            ..processing::Context::for_test()
2066        };
2067
2068        let new_envelope = process_to_single_envelope(&processor, envelope, ctx).await;
2069
2070        let event_item = new_envelope.items().last().unwrap();
2071        let annotated_event: Annotated<Event> =
2072            Annotated::from_json_bytes(&event_item.payload()).unwrap();
2073        let event = annotated_event.into_value().unwrap();
2074        let headers = event
2075            .request
2076            .into_value()
2077            .unwrap()
2078            .headers
2079            .into_value()
2080            .unwrap();
2081
2082        // IP-like data must be masked
2083        assert_eq!(
2084            Some(
2085                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/********* Safari/537.36"
2086            ),
2087            headers.get_header("User-Agent")
2088        );
2089        // But we still get correct browser and version number
2090        let contexts = event.contexts.into_value().unwrap();
2091        let browser = contexts.0.get("browser").unwrap();
2092        assert_eq!(
2093            r#"{"browser":"Chrome 103.0.0","name":"Chrome","version":"103.0.0","type":"browser"}"#,
2094            browser.to_json().unwrap()
2095        );
2096    }
2097
2098    #[tokio::test]
2099    #[cfg(feature = "processing")]
2100    async fn test_materialize_dsc() {
2101        use crate::services::projects::project::PublicKeyConfig;
2102
2103        let dsn = "https://e12d836b15bb49d7bbf99e64295d995b:@sentry.io/42"
2104            .parse()
2105            .unwrap();
2106        let request_meta = RequestMeta::new(dsn);
2107        let mut envelope = Envelope::from_request(None, request_meta);
2108
2109        let dsc = r#"{
2110            "trace_id": "00000000-0000-0000-0000-000000000000",
2111            "public_key": "e12d836b15bb49d7bbf99e64295d995b",
2112            "sample_rate": "0.2"
2113        }"#;
2114        envelope.set_dsc(serde_json::from_str(dsc).unwrap());
2115
2116        let mut item = Item::new(ItemType::Event);
2117        item.set_payload(ContentType::Json, r#"{}"#);
2118        envelope.add_item(item);
2119
2120        let outcome_aggregator = Addr::dummy();
2121        let managed_envelope = ManagedEnvelope::new(envelope, outcome_aggregator);
2122
2123        let mut project_info = ProjectInfo::default();
2124        project_info.public_keys.push(PublicKeyConfig {
2125            public_key: ProjectKey::parse("e12d836b15bb49d7bbf99e64295d995b").unwrap(),
2126            numeric_id: Some(1),
2127        });
2128
2129        let config = serde_json::json!({
2130            "processing": {
2131                "enabled": true,
2132                "kafka_config": [],
2133            }
2134        });
2135
2136        let processor =
2137            create_test_processor(Config::from_json_value(config.clone()).unwrap()).await;
2138        let config = Config::from_json_value(config).unwrap();
2139        let ctx = processing::Context {
2140            config: &config,
2141            project_info: &project_info,
2142            sampling_project_info: Some(&project_info),
2143            ..processing::Context::for_test()
2144        };
2145
2146        let envelope = process_to_single_envelope(&processor, managed_envelope, ctx).await;
2147        let event = envelope
2148            .get_item_by(|item| item.ty() == &ItemType::Event)
2149            .unwrap();
2150
2151        let event = Annotated::<Event>::from_json_bytes(&event.payload()).unwrap();
2152        insta::assert_debug_snapshot!(event.value().unwrap()._dsc, @r###"
2153        Object(
2154            {
2155                "environment": ~,
2156                "public_key": String(
2157                    "e12d836b15bb49d7bbf99e64295d995b",
2158                ),
2159                "release": ~,
2160                "replay_id": ~,
2161                "sample_rate": String(
2162                    "0.2",
2163                ),
2164                "trace_id": String(
2165                    "00000000000000000000000000000000",
2166                ),
2167                "transaction": ~,
2168            },
2169        )
2170        "###);
2171    }
2172
2173    fn capture_test_event(transaction_name: &str, source: TransactionSource) -> Vec<String> {
2174        let mut event = Annotated::<Event>::from_json(
2175            r#"
2176            {
2177                "type": "transaction",
2178                "transaction": "/foo/",
2179                "timestamp": 946684810.0,
2180                "start_timestamp": 946684800.0,
2181                "contexts": {
2182                    "trace": {
2183                        "trace_id": "4c79f60c11214eb38604f4ae0781bfb2",
2184                        "span_id": "fa90fdead5f74053",
2185                        "op": "http.server",
2186                        "type": "trace"
2187                    }
2188                },
2189                "transaction_info": {
2190                    "source": "url"
2191                }
2192            }
2193            "#,
2194        )
2195        .unwrap();
2196        let e = event.value_mut().as_mut().unwrap();
2197        e.transaction.set_value(Some(transaction_name.into()));
2198
2199        e.transaction_info
2200            .value_mut()
2201            .as_mut()
2202            .unwrap()
2203            .source
2204            .set_value(Some(source));
2205
2206        relay_statsd::with_capturing_test_client(|| {
2207            utils::log_transaction_name_metrics(&mut event, |event| {
2208                let config = NormalizationConfig {
2209                    transaction_name_config: TransactionNameConfig {
2210                        rules: &[TransactionNameRule {
2211                            pattern: LazyGlob::new("/foo/*/**".to_owned()),
2212                            expiry: DateTime::<Utc>::MAX_UTC,
2213                            redaction: RedactionRule::Replace {
2214                                substitution: "*".to_owned(),
2215                            },
2216                        }],
2217                    },
2218                    ..Default::default()
2219                };
2220                relay_event_normalization::normalize_event(event, &config)
2221            });
2222        })
2223    }
2224
2225    #[test]
2226    fn test_log_transaction_metrics_none() {
2227        let captures = capture_test_event("/nothing", TransactionSource::Url);
2228        insta::assert_debug_snapshot!(captures, @r###"
2229        [
2230            "event.transaction_name_changes:1|c|#source_in:url,changes:none,source_out:sanitized,is_404:false",
2231        ]
2232        "###);
2233    }
2234
2235    #[test]
2236    fn test_log_transaction_metrics_rule() {
2237        let captures = capture_test_event("/foo/john/denver", TransactionSource::Url);
2238        insta::assert_debug_snapshot!(captures, @r###"
2239        [
2240            "event.transaction_name_changes:1|c|#source_in:url,changes:rule,source_out:sanitized,is_404:false",
2241        ]
2242        "###);
2243    }
2244
2245    #[test]
2246    fn test_log_transaction_metrics_pattern() {
2247        let captures = capture_test_event("/something/12345", TransactionSource::Url);
2248        insta::assert_debug_snapshot!(captures, @r###"
2249        [
2250            "event.transaction_name_changes:1|c|#source_in:url,changes:pattern,source_out:sanitized,is_404:false",
2251        ]
2252        "###);
2253    }
2254
2255    #[test]
2256    fn test_log_transaction_metrics_both() {
2257        let captures = capture_test_event("/foo/john/12345", TransactionSource::Url);
2258        insta::assert_debug_snapshot!(captures, @r###"
2259        [
2260            "event.transaction_name_changes:1|c|#source_in:url,changes:both,source_out:sanitized,is_404:false",
2261        ]
2262        "###);
2263    }
2264
2265    #[test]
2266    fn test_log_transaction_metrics_no_match() {
2267        let captures = capture_test_event("/foo/john/12345", TransactionSource::Route);
2268        insta::assert_debug_snapshot!(captures, @r###"
2269        [
2270            "event.transaction_name_changes:1|c|#source_in:route,changes:none,source_out:route,is_404:false",
2271        ]
2272        "###);
2273    }
2274
2275    #[tokio::test]
2276    async fn test_process_metrics_bucket_metadata() {
2277        let mut token = Cogs::noop().timed(ResourceId::Relay, AppFeature::Unattributed);
2278        let project_key = ProjectKey::parse("a94ae32be2584e0bbd7a4cbb95971fee").unwrap();
2279        let received_at = Utc::now();
2280        let config = Config::default();
2281
2282        let (aggregator, mut aggregator_rx) = Addr::custom();
2283        let processor = create_test_processor_with_addrs(
2284            config,
2285            Addrs {
2286                aggregator,
2287                ..Default::default()
2288            },
2289        )
2290        .await;
2291
2292        let mut item = Item::new(ItemType::Statsd);
2293        item.set_payload(ContentType::Text, "spans/foo:3182887624:4267882815|s");
2294        for (source, expected_received_at) in [
2295            (
2296                BucketSource::External,
2297                Some(UnixTimestamp::from_datetime(received_at).unwrap()),
2298            ),
2299            (BucketSource::Internal, None),
2300        ] {
2301            let message = ProcessMetrics {
2302                data: MetricData::Raw(vec![item.clone()]),
2303                project_key,
2304                source,
2305                received_at,
2306                sent_at: Some(Utc::now()),
2307            };
2308            processor.handle_process_metrics(&mut token, message);
2309
2310            let Aggregator::MergeBuckets(merge_buckets) = aggregator_rx.recv().await.unwrap();
2311            let buckets = merge_buckets.buckets;
2312            assert_eq!(buckets.len(), 1);
2313            assert_eq!(buckets[0].metadata.received_at, expected_received_at);
2314        }
2315    }
2316
2317    #[tokio::test]
2318    async fn test_process_batched_metrics() {
2319        let mut token = Cogs::noop().timed(ResourceId::Relay, AppFeature::Unattributed);
2320        let received_at = Utc::now();
2321        let config = Config::default();
2322
2323        let (aggregator, mut aggregator_rx) = Addr::custom();
2324        let processor = create_test_processor_with_addrs(
2325            config,
2326            Addrs {
2327                aggregator,
2328                ..Default::default()
2329            },
2330        )
2331        .await;
2332
2333        let payload = r#"{
2334    "buckets": {
2335        "11111111111111111111111111111111": [
2336            {
2337                "timestamp": 1615889440,
2338                "width": 0,
2339                "name": "d:custom/endpoint.response_time@millisecond",
2340                "type": "d",
2341                "value": [
2342                  68.0
2343                ],
2344                "tags": {
2345                  "route": "user_index"
2346                }
2347            }
2348        ],
2349        "22222222222222222222222222222222": [
2350            {
2351                "timestamp": 1615889440,
2352                "width": 0,
2353                "name": "d:custom/endpoint.cache_rate@none",
2354                "type": "d",
2355                "value": [
2356                  36.0
2357                ]
2358            }
2359        ]
2360    }
2361}
2362"#;
2363        let message = ProcessBatchedMetrics {
2364            payload: Bytes::from(payload),
2365            source: BucketSource::Internal,
2366            received_at,
2367            sent_at: Some(Utc::now()),
2368        };
2369        processor.handle_process_batched_metrics(&mut token, message);
2370
2371        let Aggregator::MergeBuckets(mb1) = aggregator_rx.recv().await.unwrap();
2372        let Aggregator::MergeBuckets(mb2) = aggregator_rx.recv().await.unwrap();
2373
2374        let mut messages = vec![mb1, mb2];
2375        messages.sort_by_key(|mb| mb.project_key);
2376
2377        let actual = messages
2378            .into_iter()
2379            .map(|mb| (mb.project_key, mb.buckets))
2380            .collect::<Vec<_>>();
2381
2382        assert_debug_snapshot!(actual, @r###"
2383        [
2384            (
2385                ProjectKey("11111111111111111111111111111111"),
2386                [
2387                    Bucket {
2388                        timestamp: UnixTimestamp(1615889440),
2389                        width: 0,
2390                        name: MetricName(
2391                            "d:custom/endpoint.response_time@millisecond",
2392                        ),
2393                        value: Distribution(
2394                            [
2395                                68.0,
2396                            ],
2397                        ),
2398                        tags: {
2399                            "route": "user_index",
2400                        },
2401                        metadata: BucketMetadata {
2402                            merges: 1,
2403                            received_at: None,
2404                            extracted_from_indexed: false,
2405                        },
2406                    },
2407                ],
2408            ),
2409            (
2410                ProjectKey("22222222222222222222222222222222"),
2411                [
2412                    Bucket {
2413                        timestamp: UnixTimestamp(1615889440),
2414                        width: 0,
2415                        name: MetricName(
2416                            "d:custom/endpoint.cache_rate@none",
2417                        ),
2418                        value: Distribution(
2419                            [
2420                                36.0,
2421                            ],
2422                        ),
2423                        tags: {},
2424                        metadata: BucketMetadata {
2425                            merges: 1,
2426                            received_at: None,
2427                            extracted_from_indexed: false,
2428                        },
2429                    },
2430                ],
2431            ),
2432        ]
2433        "###);
2434    }
2435}