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::future::BoxFuture;
18use relay_base_schema::project::{ProjectId, ProjectKey};
19use relay_cogs::{AppFeature, Cogs, FeatureWeights, ResourceId, Token};
20use relay_common::time::UnixTimestamp;
21use relay_config::{Config, HttpEncoding, UpstreamDescriptor};
22use relay_event_normalization::{ClockDriftProcessor, GeoIpLookup};
23use relay_event_schema::processor::ProcessingAction;
24use relay_event_schema::protocol::ClientReport;
25use relay_filter::FilterStatKey;
26use relay_log::sentry::SentryFutureExt;
27use relay_metrics::{Bucket, BucketMetadata, BucketView, BucketsView, MetricNamespace};
28use relay_quotas::{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        relay_log::configure_scope(|scope| {
681            scope.set_tag("project_id", project_id);
682        });
683
684        self.process_envelope(project_id, envelope, ctx).await
685    }
686
687    async fn handle_process_envelope(&self, cogs: &mut Token, message: ProcessEnvelope) {
688        let wait_time = message.envelope.age();
689        metric!(timer(RelayTimers::EnvelopeWaitTime) = wait_time);
690
691        // This COGS handling may need an overhaul in the future:
692        // Cancel the passed in token, to start individual measurements per processor instead.
693        cogs.cancel();
694
695        let global_config = self.inner.global_config.current().unwrap_or_default();
696
697        let ctx = processing::Context {
698            config: &self.inner.config,
699            global_config: &global_config,
700            project_info: &message.project_info,
701            sampling_project_info: message.sampling_project_info.as_deref(),
702            rate_limits: &message.rate_limits,
703        };
704
705        let project_key = message.envelope.meta().public_key();
706        // Only allow sending to the sampling key, if we successfully loaded a sampling project
707        // info relating to it. This filters out unknown/invalid project keys as well as project
708        // keys from different organizations.
709        let sampling_key = ctx
710            .sampling_project_info
711            .and_then(|p| p.get_public_key_config())
712            .map(|pkc| pkc.public_key);
713
714        relay_log::configure_scope(|scope| {
715            scope.set_tag("project_key", project_key);
716            if let Some(sampling_key) = sampling_key {
717                scope.set_tag("sampling_key", sampling_key);
718            }
719            let meta = message.envelope.envelope().meta();
720            scope.set_tag("sdk_name", meta.client_name());
721            if let Some(client) = meta.client() {
722                scope.set_tag("sdk", client);
723            }
724            if let Some(user_agent) = meta.user_agent() {
725                scope.set_extra("user_agent", user_agent.into());
726            }
727        });
728
729        let outputs = metric!(timer(RelayTimers::EnvelopeProcessingTime), {
730            self.process(message.envelope, ctx).await
731        });
732
733        let ctx = ctx.to_forward();
734        for Output { main, metrics } in outputs {
735            if let Some(metrics) = metrics {
736                let agg = &self.inner.addrs.aggregator;
737                metrics.accept(|metrics| {
738                    send_metrics(metrics, project_key, sampling_key, agg);
739                });
740            }
741
742            if let Some(output) = main {
743                // Only counting processing time for COGS at the moment.
744                self.submit_upstream(&mut Token::noop(), output, ctx);
745            }
746        }
747    }
748
749    fn handle_process_metrics(&self, cogs: &mut Token, message: ProcessMetrics) {
750        let ProcessMetrics {
751            data,
752            project_key,
753            received_at,
754            sent_at,
755            source,
756        } = message;
757
758        let received_timestamp =
759            UnixTimestamp::from_datetime(received_at).unwrap_or(UnixTimestamp::now());
760
761        let mut buckets = data.into_buckets(received_timestamp);
762        if buckets.is_empty() {
763            return;
764        };
765        cogs.update(relay_metrics::cogs::BySize(&buckets));
766
767        let clock_drift_processor =
768            ClockDriftProcessor::new(sent_at, received_at).at_least(MINIMUM_CLOCK_DRIFT);
769
770        buckets.retain_mut(|bucket| {
771            if let Err(error) = relay_metrics::normalize_bucket(bucket) {
772                relay_log::debug!(error = &error as &dyn Error, "dropping bucket {bucket:?}");
773                return false;
774            }
775
776            if !self::metrics::is_valid_namespace(bucket, source) {
777                relay_log::debug!("dropping bucket in invalid namespace {bucket:?}");
778                return false;
779            }
780
781            clock_drift_processor.process_timestamp(&mut bucket.timestamp);
782
783            if !matches!(source, BucketSource::Internal) {
784                bucket.metadata = BucketMetadata::new(received_timestamp);
785            }
786
787            true
788        });
789
790        let project = self.inner.project_cache.get(project_key);
791
792        // Best effort check to filter and rate limit buckets, if there is no project state
793        // available at the current time, we will check again after flushing.
794        let buckets = match project.state() {
795            ProjectState::Enabled(project_info) => {
796                let rate_limits = project.rate_limits().current_limits();
797                self.check_buckets(project_key, project_info, &rate_limits, buckets)
798            }
799            _ => buckets,
800        };
801
802        relay_log::trace!("merging metric buckets into the aggregator");
803        self.inner
804            .addrs
805            .aggregator
806            .send(MergeBuckets::new(project_key, buckets));
807    }
808
809    fn handle_process_batched_metrics(&self, cogs: &mut Token, message: ProcessBatchedMetrics) {
810        let ProcessBatchedMetrics {
811            payload,
812            source,
813            received_at,
814            sent_at,
815        } = message;
816
817        #[derive(serde::Deserialize)]
818        struct Wrapper {
819            buckets: HashMap<ProjectKey, Vec<Bucket>>,
820        }
821
822        let buckets = match serde_json::from_slice(&payload) {
823            Ok(Wrapper { buckets }) => buckets,
824            Err(error) => {
825                relay_log::debug!(
826                    error = &error as &dyn Error,
827                    "failed to parse batched metrics",
828                );
829                metric!(counter(RelayCounters::MetricBucketsParsingFailed) += 1);
830                return;
831            }
832        };
833
834        for (project_key, buckets) in buckets {
835            self.handle_process_metrics(
836                cogs,
837                ProcessMetrics {
838                    data: MetricData::Parsed(buckets),
839                    project_key,
840                    source,
841                    received_at,
842                    sent_at,
843                },
844            )
845        }
846    }
847
848    /// Submits a processor [`Output`] to the appropriate upstream.
849    ///
850    /// If processing is enabled, the upstream is Kafka.
851    fn submit_upstream(
852        &self,
853        cogs: &mut Token,
854        output: Outputs,
855        ctx: processing::ForwardContext<'_>,
856    ) {
857        let _submit = cogs.start_category("submit");
858
859        #[cfg(feature = "processing")]
860        if ctx.config.processing_enabled()
861            && let Some(store_forwarder) = &self.inner.addrs.store_forwarder
862        {
863            use crate::processing::StoreHandle;
864
865            let objectstore = self.inner.addrs.objectstore.as_ref();
866            let handle = StoreHandle::new(store_forwarder, objectstore, ctx.global_config);
867
868            output
869                .forward_store(handle, ctx)
870                .unwrap_or_else(|err| err.into_inner());
871
872            return;
873        }
874
875        match output.serialize_envelope(ctx) {
876            Ok(envelope) => {
877                let envelope = ManagedEnvelope::from(envelope);
878                self.submit_envelope_upstream(envelope, ctx.project_info.upstream.clone());
879            }
880            Err(_) => relay_log::error!("failed to serialize output to an envelope"),
881        };
882    }
883
884    fn submit_envelope_upstream(
885        &self,
886        mut envelope: ManagedEnvelope,
887        // Currently allowed to be optional as code is migrated to respect the upstream override
888        // provided from the project config. Eventually must be available and is required.
889        upstream: Option<UpstreamDescriptor>,
890    ) {
891        if envelope.envelope_mut().is_empty() {
892            envelope.accept();
893            return;
894        }
895
896        // No code path should hit this.
897        //
898        // Any item which is produced by processing is handled in `submit_upstream`,
899        // metrics are sent to the store directly and outcomes must be produced to Kafka
900        // instead of being sent onward as client report.
901        if self.inner.config.processing_enabled() {
902            relay_log::error!(
903                "attempt to forward envelope to http upstream when processing is enabled"
904            );
905            return;
906        }
907
908        // Override the `sent_at` timestamp. Since the envelope went through basic
909        // normalization, all timestamps have been corrected. We propagate the new
910        // `sent_at` to allow the next Relay to double-check this timestamp and
911        // potentially apply correction again. This is done as close to sending as
912        // possible so that we avoid internal delays.
913        envelope.envelope_mut().set_sent_at(Utc::now());
914
915        relay_log::trace!("sending envelope to sentry endpoint");
916        let http_encoding = self.inner.config.http_encoding();
917        let result = envelope.envelope().to_vec().and_then(|v| {
918            encode_payload(&v.into(), http_encoding).map_err(EnvelopeError::PayloadIoFailed)
919        });
920
921        match result {
922            Ok(body) => {
923                self.inner
924                    .addrs
925                    .upstream_relay
926                    .send(SendRequest(SendEnvelope {
927                        upstream,
928                        envelope,
929                        body,
930                        http_encoding,
931                        project_cache: self.inner.project_cache.clone(),
932                    }));
933            }
934            Err(error) => {
935                // Errors are only logged for what we consider an internal discard reason. These
936                // indicate errors in the infrastructure or implementation bugs.
937                relay_log::error!(
938                    error = &error as &dyn Error,
939                    tags.project_key = %envelope.scoping().project_key,
940                    "failed to serialize envelope payload"
941                );
942
943                envelope.reject(Outcome::Invalid(DiscardReason::Internal));
944            }
945        }
946    }
947
948    fn handle_submit_client_reports(&self, message: SubmitClientReports) {
949        let SubmitClientReports {
950            client_reports,
951            scoping,
952        } = message;
953
954        let upstream = self.inner.config.upstream();
955        let dsn = PartialDsn::outbound(&scoping, upstream);
956
957        let mut envelope = Envelope::from_request(None, RequestMeta::outbound(dsn));
958        for client_report in client_reports {
959            match client_report.serialize() {
960                Ok(payload) => {
961                    let mut item = Item::new(ItemType::ClientReport);
962                    item.set_payload(ContentType::Json, payload);
963                    envelope.add_item(item);
964                }
965                Err(error) => {
966                    relay_log::error!(
967                        error = &error as &dyn std::error::Error,
968                        "failed to serialize client report"
969                    );
970                }
971            }
972        }
973
974        let envelope = ManagedEnvelope::new(envelope, self.inner.addrs.outcome_aggregator.clone());
975        self.submit_envelope_upstream(envelope, None);
976    }
977
978    fn check_buckets(
979        &self,
980        project_key: ProjectKey,
981        project_info: &ProjectInfo,
982        rate_limits: &RateLimits,
983        buckets: Vec<Bucket>,
984    ) -> Vec<Bucket> {
985        let Some(scoping) = project_info.scoping(project_key) else {
986            relay_log::error!(
987                tags.project_key = project_key.as_str(),
988                "there is no scoping: dropping {} buckets",
989                buckets.len(),
990            );
991            return Vec::new();
992        };
993
994        let mut buckets = self::metrics::apply_project_info(
995            buckets,
996            &self.inner.metric_outcomes,
997            project_info,
998            scoping,
999        );
1000
1001        let mut namespaces: BTreeSet<MetricNamespace> = buckets
1002            .iter()
1003            .filter_map(|bucket| bucket.name.try_namespace())
1004            .collect();
1005
1006        // Never rate limit outcomes.
1007        namespaces.remove(&MetricNamespace::Outcomes);
1008
1009        for namespace in namespaces {
1010            let limits = rate_limits
1011                .check_with_quotas(project_info.get_quotas(), scoping.metric_bucket(namespace));
1012
1013            if limits.is_limited() {
1014                let rejected;
1015                (buckets, rejected) = utils::split_off(buckets, |bucket| {
1016                    bucket.name.try_namespace() == Some(namespace)
1017                });
1018
1019                let reason_code = limits.longest().and_then(|limit| limit.reason_code.clone());
1020                self.inner.metric_outcomes.track(
1021                    scoping,
1022                    &rejected,
1023                    Outcome::RateLimited(reason_code),
1024                );
1025            }
1026        }
1027
1028        let quotas = project_info.config.quotas.clone();
1029        match MetricsLimiter::create(buckets, quotas, scoping) {
1030            Ok(mut bucket_limiter) => {
1031                bucket_limiter.enforce_limits(rate_limits, &self.inner.metric_outcomes);
1032                bucket_limiter.into_buckets()
1033            }
1034            Err(buckets) => buckets,
1035        }
1036    }
1037
1038    #[cfg(feature = "processing")]
1039    async fn rate_limit_buckets(
1040        &self,
1041        scoping: Scoping,
1042        project_info: &ProjectInfo,
1043        mut buckets: Vec<Bucket>,
1044    ) -> Vec<Bucket> {
1045        let Some(rate_limiter) = &self.inner.rate_limiter else {
1046            return buckets;
1047        };
1048
1049        let global_config = self.inner.global_config.current().unwrap_or_default();
1050        let mut namespaces = buckets
1051            .iter()
1052            .filter_map(|bucket| bucket.name.try_namespace())
1053            .counts();
1054
1055        // Never rate limit outcomes.
1056        namespaces.remove(&MetricNamespace::Outcomes);
1057
1058        let quotas = CombinedQuotas::new(&global_config, project_info.get_quotas());
1059
1060        for (namespace, quantity) in namespaces {
1061            let item_scoping = scoping.metric_bucket(namespace);
1062
1063            let limits = match rate_limiter
1064                .is_rate_limited(quotas, item_scoping, quantity, false)
1065                .await
1066            {
1067                Ok(limits) => limits,
1068                Err(err) => {
1069                    relay_log::error!(
1070                        error = &err as &dyn std::error::Error,
1071                        "failed to check redis rate limits"
1072                    );
1073                    break;
1074                }
1075            };
1076
1077            if limits.is_limited() {
1078                let rejected;
1079                (buckets, rejected) = utils::split_off(buckets, |bucket| {
1080                    bucket.name.try_namespace() == Some(namespace)
1081                });
1082
1083                let reason_code = limits.longest().and_then(|limit| limit.reason_code.clone());
1084                self.inner.metric_outcomes.track(
1085                    scoping,
1086                    &rejected,
1087                    Outcome::RateLimited(reason_code),
1088                );
1089
1090                self.inner
1091                    .project_cache
1092                    .get(item_scoping.scoping.project_key)
1093                    .rate_limits()
1094                    .merge(limits);
1095            }
1096        }
1097
1098        match MetricsLimiter::create(buckets, project_info.config.quotas.clone(), scoping) {
1099            Err(buckets) => buckets,
1100            Ok(bucket_limiter) => self.apply_other_rate_limits(bucket_limiter).await,
1101        }
1102    }
1103
1104    /// Check and apply rate limits to metrics buckets for transactions and spans.
1105    #[cfg(feature = "processing")]
1106    async fn apply_other_rate_limits(&self, mut bucket_limiter: MetricsLimiter) -> Vec<Bucket> {
1107        relay_log::trace!("handle_rate_limit_buckets");
1108
1109        let scoping = *bucket_limiter.scoping();
1110
1111        if let Some(rate_limiter) = self.inner.rate_limiter.as_ref() {
1112            let global_config = self.inner.global_config.current().unwrap_or_default();
1113            let quotas = CombinedQuotas::new(&global_config, bucket_limiter.quotas());
1114
1115            // We set over_accept_once such that the limit is actually reached, which allows subsequent
1116            // calls with quantity=0 to be rate limited.
1117            let over_accept_once = true;
1118            let mut rate_limits = RateLimits::new();
1119
1120            let (category, count) = bucket_limiter.count();
1121
1122            let timer = Instant::now();
1123            let mut is_limited = false;
1124
1125            if let Some(count) = count {
1126                match rate_limiter
1127                    .is_rate_limited(quotas, scoping.item(category), count, over_accept_once)
1128                    .await
1129                {
1130                    Ok(limits) => {
1131                        is_limited = limits.is_limited();
1132                        rate_limits.merge(limits)
1133                    }
1134                    Err(e) => {
1135                        relay_log::error!(error = &e as &dyn Error, "rate limiting error")
1136                    }
1137                }
1138            }
1139
1140            relay_statsd::metric!(
1141                timer(RelayTimers::RateLimitBucketsDuration) = timer.elapsed(),
1142                category = category.name(),
1143                limited = if is_limited { "true" } else { "false" },
1144                count = match count {
1145                    None => "none",
1146                    Some(0) => "0",
1147                    Some(1) => "1",
1148                    Some(1..=10) => "10",
1149                    Some(1..=25) => "25",
1150                    Some(1..=50) => "50",
1151                    Some(51..=100) => "100",
1152                    Some(101..=500) => "500",
1153                    _ => "> 500",
1154                },
1155            );
1156
1157            if rate_limits.is_limited() {
1158                let was_enforced =
1159                    bucket_limiter.enforce_limits(&rate_limits, &self.inner.metric_outcomes);
1160
1161                if was_enforced {
1162                    // Update the rate limits in the project cache.
1163                    self.inner
1164                        .project_cache
1165                        .get(scoping.project_key)
1166                        .rate_limits()
1167                        .merge(rate_limits);
1168                }
1169            }
1170        }
1171
1172        bucket_limiter.into_buckets()
1173    }
1174
1175    /// Processes metric buckets and sends them to Kafka.
1176    ///
1177    /// This function runs the following steps:
1178    ///  - rate limiting
1179    ///  - emit billing outcomes
1180    ///  - submit to `StoreForwarder`
1181    #[cfg(feature = "processing")]
1182    async fn encode_metrics_processing(
1183        &self,
1184        message: FlushBuckets,
1185        store_forwarder: &Addr<Store>,
1186    ) {
1187        use crate::constants::DEFAULT_EVENT_RETENTION;
1188        use crate::services::store::StoreMetrics;
1189        use relay_dynamic_config::Feature;
1190
1191        for ProjectBuckets {
1192            buckets,
1193            scoping,
1194            project_info,
1195            ..
1196        } in message.buckets.into_values()
1197        {
1198            let mut buckets = self
1199                .rate_limit_buckets(scoping, &project_info, buckets)
1200                .await;
1201
1202            if buckets.is_empty() {
1203                continue;
1204            }
1205
1206            if project_info
1207                .config
1208                .features
1209                .has(Feature::GenerateBillingOutcome)
1210            {
1211                // Emit metric billing outcomes.
1212                self.inner
1213                    .metric_outcomes
1214                    .track_accepted_outcome(scoping, &mut buckets);
1215            }
1216
1217            let retention = project_info
1218                .config
1219                .event_retention
1220                .unwrap_or(DEFAULT_EVENT_RETENTION);
1221
1222            // The store forwarder takes care of bucket splitting internally, so we can submit the
1223            // entire list of buckets. There is no batching needed here.
1224            store_forwarder.send(StoreMetrics {
1225                buckets,
1226                scoping,
1227                retention,
1228            });
1229        }
1230    }
1231
1232    /// Serializes metric buckets to JSON and sends them to the upstream.
1233    ///
1234    /// This function runs the following steps:
1235    ///  - partitioning
1236    ///  - batching by configured size limit
1237    ///  - serialize to JSON and pack in an envelope
1238    ///
1239    /// Rate limiting runs only in processing Relays as it requires access to the central Redis instance.
1240    /// Cached rate limits are applied in the project cache already.
1241    fn encode_metrics_envelope(&self, message: FlushBuckets) {
1242        let FlushBuckets {
1243            partition_key,
1244            buckets,
1245        } = message;
1246
1247        let batch_size = self.inner.config.metrics_max_batch_size_bytes();
1248        let upstream = self.inner.config.upstream();
1249
1250        for ProjectBuckets {
1251            buckets,
1252            scoping,
1253            project_info,
1254            ..
1255        } in buckets.values()
1256        {
1257            let dsn = PartialDsn::outbound(scoping, upstream);
1258
1259            relay_statsd::metric!(
1260                distribution(RelayDistributions::PartitionKeys) = u64::from(partition_key)
1261            );
1262
1263            let mut num_batches = 0;
1264            for batch in BucketsView::from(buckets).by_size(batch_size) {
1265                let mut envelope = Envelope::from_request(None, RequestMeta::outbound(dsn.clone()));
1266
1267                let mut item = Item::new(ItemType::MetricBuckets);
1268                item.set_source_quantities(crate::metrics::extract_quantities(batch));
1269                item.set_payload(ContentType::Json, serde_json::to_vec(&buckets).unwrap());
1270                envelope.add_item(item);
1271
1272                let mut envelope =
1273                    ManagedEnvelope::new(envelope, self.inner.addrs.outcome_aggregator.clone());
1274                envelope
1275                    .set_partition_key(Some(partition_key))
1276                    .scope(*scoping);
1277
1278                relay_statsd::metric!(
1279                    distribution(RelayDistributions::BucketsPerBatch) = batch.len() as u64
1280                );
1281
1282                self.submit_envelope_upstream(envelope, project_info.upstream.clone());
1283                num_batches += 1;
1284            }
1285
1286            relay_statsd::metric!(
1287                distribution(RelayDistributions::BatchesPerPartition) = num_batches
1288            );
1289        }
1290    }
1291
1292    /// Creates a [`SendMetricsRequest`] and sends it to the upstream relay.
1293    fn send_global_partition(
1294        &self,
1295        upstream: Option<UpstreamDescriptor>,
1296        partition_key: u32,
1297        partition: &mut Partition<'_>,
1298    ) {
1299        if partition.is_empty() {
1300            return;
1301        }
1302
1303        let (unencoded, project_info) = partition.take();
1304        let http_encoding = self.inner.config.http_encoding();
1305        let encoded = match encode_payload(&unencoded, http_encoding) {
1306            Ok(payload) => payload,
1307            Err(error) => {
1308                let error = &error as &dyn std::error::Error;
1309                relay_log::error!(error, "failed to encode metrics payload");
1310                return;
1311            }
1312        };
1313
1314        let request = SendMetricsRequest {
1315            upstream,
1316            partition_key: partition_key.to_string(),
1317            unencoded,
1318            encoded,
1319            project_info,
1320            http_encoding,
1321            metric_outcomes: self.inner.metric_outcomes.clone(),
1322        };
1323
1324        self.inner.addrs.upstream_relay.send(SendRequest(request));
1325    }
1326
1327    /// Serializes metric buckets to JSON and sends them to the upstream via the global endpoint.
1328    ///
1329    /// This function is similar to [`Self::encode_metrics_envelope`], but sends a global batched
1330    /// payload directly instead of per-project Envelopes.
1331    ///
1332    /// This function runs the following steps:
1333    ///  - partitioning
1334    ///  - batching by configured size limit
1335    ///  - serialize to JSON
1336    ///  - submit directly to the upstream
1337    fn encode_metrics_global(&self, message: FlushBuckets) {
1338        let FlushBuckets {
1339            partition_key,
1340            buckets,
1341        } = message;
1342
1343        let batch_size = self.inner.config.metrics_max_batch_size_bytes();
1344        let mut partitions = BTreeMap::new();
1345        let mut partition_splits = 0;
1346
1347        for ProjectBuckets {
1348            buckets,
1349            scoping,
1350            project_info,
1351            ..
1352        } in buckets.values()
1353        {
1354            let partition = match partitions.get_mut(&project_info.upstream) {
1355                Some(partition) => partition,
1356                None => partitions
1357                    .entry(project_info.upstream.clone())
1358                    .or_insert_with(|| Partition::new(batch_size)),
1359            };
1360
1361            for bucket in buckets {
1362                let mut remaining = Some(BucketView::new(bucket));
1363
1364                while let Some(bucket) = remaining.take() {
1365                    if let Some(next) = partition.insert(bucket, *scoping) {
1366                        // A part of the bucket could not be inserted. Take the partition and submit
1367                        // it immediately. Repeat until the final part was inserted. This should
1368                        // always result in a request, otherwise we would enter an endless loop.
1369                        self.send_global_partition(
1370                            project_info.upstream.clone(),
1371                            partition_key,
1372                            partition,
1373                        );
1374                        remaining = Some(next);
1375                        partition_splits += 1;
1376                    }
1377                }
1378            }
1379        }
1380
1381        if partition_splits > 0 {
1382            metric!(distribution(RelayDistributions::PartitionSplits) = partition_splits);
1383        }
1384
1385        for (upstream, mut partition) in partitions {
1386            self.send_global_partition(upstream, partition_key, &mut partition);
1387        }
1388    }
1389
1390    async fn handle_flush_buckets(&self, mut message: FlushBuckets) {
1391        for (project_key, pb) in message.buckets.iter_mut() {
1392            let buckets = std::mem::take(&mut pb.buckets);
1393            pb.buckets =
1394                self.check_buckets(*project_key, &pb.project_info, &pb.rate_limits, buckets);
1395        }
1396
1397        #[cfg(feature = "processing")]
1398        if self.inner.config.processing_enabled()
1399            && let Some(ref store_forwarder) = self.inner.addrs.store_forwarder
1400        {
1401            return self
1402                .encode_metrics_processing(message, store_forwarder)
1403                .await;
1404        }
1405
1406        if self.inner.config.http_global_metrics() {
1407            self.encode_metrics_global(message)
1408        } else {
1409            self.encode_metrics_envelope(message)
1410        }
1411    }
1412
1413    #[cfg(all(test, feature = "processing"))]
1414    fn redis_rate_limiter_enabled(&self) -> bool {
1415        self.inner.rate_limiter.is_some()
1416    }
1417
1418    async fn handle_message(self, message: EnvelopeProcessor) {
1419        let ty = message.variant();
1420        let feature_weights = self.feature_weights(&message);
1421
1422        metric!(timer(RelayTimers::ProcessMessageDuration), message = ty, {
1423            let mut cogs = self.inner.cogs.timed(ResourceId::Relay, feature_weights);
1424
1425            match message {
1426                EnvelopeProcessor::ProcessEnvelope(m) => {
1427                    self.handle_process_envelope(&mut cogs, *m).await
1428                }
1429                EnvelopeProcessor::ProcessProjectMetrics(m) => {
1430                    self.handle_process_metrics(&mut cogs, *m)
1431                }
1432                EnvelopeProcessor::ProcessBatchedMetrics(m) => {
1433                    self.handle_process_batched_metrics(&mut cogs, *m)
1434                }
1435                EnvelopeProcessor::FlushBuckets(m) => self.handle_flush_buckets(*m).await,
1436                EnvelopeProcessor::SubmitClientReports(m) => self.handle_submit_client_reports(*m),
1437            }
1438        });
1439    }
1440
1441    fn feature_weights(&self, message: &EnvelopeProcessor) -> FeatureWeights {
1442        match message {
1443            // Envelope is split later and tokens are attributed then.
1444            EnvelopeProcessor::ProcessEnvelope(_) => AppFeature::Unattributed.into(),
1445            EnvelopeProcessor::ProcessProjectMetrics(_) => AppFeature::Unattributed.into(),
1446            EnvelopeProcessor::ProcessBatchedMetrics(_) => AppFeature::Unattributed.into(),
1447            EnvelopeProcessor::FlushBuckets(v) => v
1448                .buckets
1449                .values()
1450                .map(|s| {
1451                    if self.inner.config.processing_enabled() {
1452                        // Processing does not encode the metrics but instead rate limit the metrics,
1453                        // which scales by count and not size.
1454                        relay_metrics::cogs::ByCount(&s.buckets).into()
1455                    } else {
1456                        relay_metrics::cogs::BySize(&s.buckets).into()
1457                    }
1458                })
1459                .fold(FeatureWeights::none(), FeatureWeights::merge),
1460            EnvelopeProcessor::SubmitClientReports(_) => AppFeature::ClientReports.into(),
1461        }
1462    }
1463}
1464
1465impl Service for EnvelopeProcessorService {
1466    type Interface = EnvelopeProcessor;
1467
1468    async fn run(self, mut rx: relay_system::Receiver<Self::Interface>) {
1469        while let Some(message) = rx.recv().await {
1470            let service = self.clone();
1471            // Create a new hub to prevent sentry scopes from bleeding to other tasks.
1472            let hub = relay_log::Hub::with(|h| relay_log::Hub::new_from_top(h));
1473
1474            self.inner
1475                .pool
1476                .spawn_async(Box::pin(service.handle_message(message).bind_hub(hub)))
1477                .await;
1478        }
1479    }
1480}
1481
1482pub fn encode_payload(body: &Bytes, http_encoding: HttpEncoding) -> Result<Bytes, std::io::Error> {
1483    let envelope_body: Vec<u8> = match http_encoding {
1484        HttpEncoding::Identity => return Ok(body.clone()),
1485        HttpEncoding::Deflate => {
1486            let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
1487            encoder.write_all(body.as_ref())?;
1488            encoder.finish()?
1489        }
1490        HttpEncoding::Gzip => {
1491            let mut encoder = GzEncoder::new(Vec::new(), Compression::default());
1492            encoder.write_all(body.as_ref())?;
1493            encoder.finish()?
1494        }
1495        HttpEncoding::Br => {
1496            // Use default buffer size (via 0), medium quality (5), and the default lgwin (22).
1497            let mut encoder = BrotliEncoder::new(Vec::new(), 0, 5, 22);
1498            encoder.write_all(body.as_ref())?;
1499            encoder.into_inner()
1500        }
1501        HttpEncoding::Zstd => {
1502            // Use the fastest compression level, our main objective here is to get the best
1503            // compression ratio for least amount of time spent.
1504            let mut encoder = ZstdEncoder::new(Vec::new(), 1)?;
1505            encoder.write_all(body.as_ref())?;
1506            encoder.finish()?
1507        }
1508    };
1509
1510    Ok(envelope_body.into())
1511}
1512
1513/// An upstream request that submits an envelope via HTTP.
1514#[derive(Debug)]
1515pub struct SendEnvelope {
1516    pub upstream: Option<UpstreamDescriptor>,
1517    pub envelope: ManagedEnvelope,
1518    pub body: Bytes,
1519    pub http_encoding: HttpEncoding,
1520    pub project_cache: ProjectCacheHandle,
1521}
1522
1523impl UpstreamRequest for SendEnvelope {
1524    fn upstream(&self) -> Option<&UpstreamDescriptor> {
1525        self.upstream.as_ref()
1526    }
1527
1528    fn method(&self) -> reqwest::Method {
1529        reqwest::Method::POST
1530    }
1531
1532    fn path(&self) -> Cow<'_, str> {
1533        format!("/api/{}/envelope/", self.envelope.scoping().project_id).into()
1534    }
1535
1536    fn route(&self) -> &'static str {
1537        "envelope"
1538    }
1539
1540    fn build(&mut self, builder: &mut http::RequestBuilder) -> Result<(), http::HttpError> {
1541        let envelope_body = self.body.clone();
1542        metric!(
1543            distribution(RelayDistributions::UpstreamEnvelopeBodySize) = envelope_body.len() as u64
1544        );
1545
1546        let meta = &self.envelope.meta();
1547        let shard = self.envelope.partition_key().map(|p| p.to_string());
1548        builder
1549            .content_encoding(self.http_encoding)
1550            .header_opt("Origin", meta.origin().map(|url| url.as_str()))
1551            .header_opt("User-Agent", meta.user_agent())
1552            .header("X-Sentry-Auth", meta.auth_header())
1553            .header("X-Forwarded-For", meta.forwarded_for())
1554            .header("Content-Type", envelope::CONTENT_TYPE)
1555            .header_opt("X-Sentry-Relay-Shard", shard)
1556            .body(envelope_body);
1557
1558        Ok(())
1559    }
1560
1561    fn sign(&mut self) -> Option<Sign> {
1562        Some(Sign::Optional(SignatureType::RequestSign))
1563    }
1564
1565    fn respond(
1566        self: Box<Self>,
1567        result: Result<http::Response, UpstreamRequestError>,
1568    ) -> Pin<Box<dyn Future<Output = ()> + Send + Sync>> {
1569        Box::pin(async move {
1570            let result = match result {
1571                Ok(mut response) => response.consume().await.map_err(UpstreamRequestError::Http),
1572                Err(error) => Err(error),
1573            };
1574
1575            match result {
1576                Ok(()) => self.envelope.accept(),
1577                Err(error) if error.is_received() => {
1578                    let scoping = self.envelope.scoping();
1579                    self.envelope.accept();
1580
1581                    if let UpstreamRequestError::RateLimited(limits) = error {
1582                        self.project_cache
1583                            .get(scoping.project_key)
1584                            .rate_limits()
1585                            .merge(limits.scope(&scoping));
1586                    }
1587                }
1588                Err(error) => {
1589                    // Errors are only logged for what we consider an internal discard reason. These
1590                    // indicate errors in the infrastructure or implementation bugs.
1591                    let mut envelope = self.envelope;
1592                    envelope.reject(Outcome::Invalid(DiscardReason::Internal));
1593                    relay_log::error!(
1594                        error = &error as &dyn Error,
1595                        tags.project_key = %envelope.scoping().project_key,
1596                        "error sending envelope"
1597                    );
1598                }
1599            }
1600        })
1601    }
1602}
1603
1604/// A container for metric buckets from multiple projects.
1605///
1606/// This container is used to send metrics to the upstream in global batches as part of the
1607/// [`FlushBuckets`] message if the `http.global_metrics` option is enabled. The container monitors
1608/// the size of all metrics and allows to split them into multiple batches. See
1609/// [`insert`](Self::insert) for more information.
1610#[derive(Debug)]
1611struct Partition<'a> {
1612    max_size: usize,
1613    remaining: usize,
1614    views: HashMap<ProjectKey, Vec<BucketView<'a>>>,
1615    project_info: HashMap<ProjectKey, Scoping>,
1616}
1617
1618impl<'a> Partition<'a> {
1619    /// Creates a new partition with the given maximum size in bytes.
1620    pub fn new(size: usize) -> Self {
1621        Self {
1622            max_size: size,
1623            remaining: size,
1624            views: HashMap::new(),
1625            project_info: HashMap::new(),
1626        }
1627    }
1628
1629    /// Inserts a bucket into the partition, splitting it if necessary.
1630    ///
1631    /// This function attempts to add the bucket to this partition. If the bucket does not fit
1632    /// entirely into the partition given its maximum size, the remaining part of the bucket is
1633    /// returned from this function call.
1634    ///
1635    /// If this function returns `Some(_)`, the partition is full and should be submitted to the
1636    /// upstream immediately. Use [`Self::take`] to retrieve the contents of the
1637    /// partition. Afterwards, the caller is responsible to call this function again with the
1638    /// remaining bucket until it is fully inserted.
1639    pub fn insert(&mut self, bucket: BucketView<'a>, scoping: Scoping) -> Option<BucketView<'a>> {
1640        let (current, next) = bucket.split(self.remaining, Some(self.max_size));
1641
1642        if let Some(current) = current {
1643            self.remaining = self.remaining.saturating_sub(current.estimated_size());
1644            self.views
1645                .entry(scoping.project_key)
1646                .or_default()
1647                .push(current);
1648
1649            self.project_info
1650                .entry(scoping.project_key)
1651                .or_insert(scoping);
1652        }
1653
1654        next
1655    }
1656
1657    /// Returns `true` if the partition does not hold any data.
1658    fn is_empty(&self) -> bool {
1659        self.views.is_empty()
1660    }
1661
1662    /// Returns the serialized buckets for this partition.
1663    ///
1664    /// This empties the partition, so that it can be reused.
1665    fn take(&mut self) -> (Bytes, HashMap<ProjectKey, Scoping>) {
1666        #[derive(serde::Serialize)]
1667        struct Wrapper<'a> {
1668            buckets: &'a HashMap<ProjectKey, Vec<BucketView<'a>>>,
1669        }
1670
1671        let buckets = &self.views;
1672        let payload = serde_json::to_vec(&Wrapper { buckets }).unwrap().into();
1673
1674        let scopings = std::mem::take(&mut self.project_info);
1675
1676        self.views.clear();
1677        self.remaining = self.max_size;
1678
1679        (payload, scopings)
1680    }
1681}
1682
1683/// An upstream request that submits metric buckets via HTTP.
1684///
1685/// This request is not awaited. It automatically tracks outcomes if the request is not received.
1686#[derive(Debug)]
1687struct SendMetricsRequest {
1688    /// Optional upstream override where the request will be sent to.
1689    upstream: Option<UpstreamDescriptor>,
1690    /// If the partition key is set, the request is marked with `X-Sentry-Relay-Shard`.
1691    partition_key: String,
1692    /// Serialized metric buckets without encoding applied, used for signing.
1693    unencoded: Bytes,
1694    /// Serialized metric buckets with the stated HTTP encoding applied.
1695    encoded: Bytes,
1696    /// Mapping of all contained project keys to their scoping and extraction mode.
1697    ///
1698    /// Used to track outcomes for transmission failures.
1699    project_info: HashMap<ProjectKey, Scoping>,
1700    /// Encoding (compression) of the payload.
1701    http_encoding: HttpEncoding,
1702    /// Metric outcomes instance to send outcomes on error.
1703    metric_outcomes: MetricOutcomes,
1704}
1705
1706impl SendMetricsRequest {
1707    fn create_error_outcomes(self) {
1708        #[derive(serde::Deserialize)]
1709        struct Wrapper {
1710            buckets: HashMap<ProjectKey, Vec<MinimalTrackableBucket>>,
1711        }
1712
1713        let buckets = match serde_json::from_slice(&self.unencoded) {
1714            Ok(Wrapper { buckets }) => buckets,
1715            Err(err) => {
1716                relay_log::error!(
1717                    error = &err as &dyn std::error::Error,
1718                    "failed to parse buckets from failed transmission"
1719                );
1720                return;
1721            }
1722        };
1723
1724        for (key, buckets) in buckets {
1725            let Some(&scoping) = self.project_info.get(&key) else {
1726                relay_log::error!("missing scoping for project key");
1727                continue;
1728            };
1729
1730            self.metric_outcomes.track(
1731                scoping,
1732                &buckets,
1733                Outcome::Invalid(DiscardReason::Internal),
1734            );
1735        }
1736    }
1737}
1738
1739impl UpstreamRequest for SendMetricsRequest {
1740    fn upstream(&self) -> Option<&UpstreamDescriptor> {
1741        self.upstream.as_ref()
1742    }
1743
1744    fn set_relay_id(&self) -> bool {
1745        true
1746    }
1747
1748    fn sign(&mut self) -> Option<Sign> {
1749        Some(Sign::Required(SignatureType::Body(self.unencoded.clone())))
1750    }
1751
1752    fn method(&self) -> reqwest::Method {
1753        reqwest::Method::POST
1754    }
1755
1756    fn path(&self) -> Cow<'_, str> {
1757        "/api/0/relays/metrics/".into()
1758    }
1759
1760    fn route(&self) -> &'static str {
1761        "global_metrics"
1762    }
1763
1764    fn build(&mut self, builder: &mut http::RequestBuilder) -> Result<(), http::HttpError> {
1765        metric!(
1766            distribution(RelayDistributions::UpstreamMetricsBodySize) = self.encoded.len() as u64
1767        );
1768
1769        builder
1770            .content_encoding(self.http_encoding)
1771            .header("X-Sentry-Relay-Shard", self.partition_key.as_bytes())
1772            .header(header::CONTENT_TYPE, b"application/json")
1773            .body(self.encoded.clone());
1774
1775        Ok(())
1776    }
1777
1778    fn respond(
1779        self: Box<Self>,
1780        result: Result<http::Response, UpstreamRequestError>,
1781    ) -> Pin<Box<dyn Future<Output = ()> + Send + Sync>> {
1782        Box::pin(async {
1783            match result {
1784                Ok(mut response) => {
1785                    response.consume().await.ok();
1786                }
1787                Err(error) => {
1788                    relay_log::error!(error = &error as &dyn Error, "Failed to send metrics batch");
1789
1790                    // If the request did not arrive at the upstream, we are responsible for outcomes.
1791                    // Otherwise, the upstream is responsible to log outcomes.
1792                    if error.is_received() {
1793                        return;
1794                    }
1795
1796                    self.create_error_outcomes()
1797                }
1798            }
1799        })
1800    }
1801}
1802
1803/// Container for global and project level [`Quota`].
1804#[derive(Copy, Clone, Debug)]
1805#[cfg(feature = "processing")]
1806struct CombinedQuotas<'a> {
1807    global_quotas: &'a [Quota],
1808    project_quotas: &'a [Quota],
1809}
1810
1811#[cfg(feature = "processing")]
1812impl<'a> CombinedQuotas<'a> {
1813    /// Returns a new [`CombinedQuotas`].
1814    pub fn new(global_config: &'a GlobalConfig, project_quotas: &'a [Quota]) -> Self {
1815        Self {
1816            global_quotas: &global_config.quotas,
1817            project_quotas,
1818        }
1819    }
1820}
1821
1822#[cfg(feature = "processing")]
1823impl<'a> IntoIterator for CombinedQuotas<'a> {
1824    type Item = &'a Quota;
1825    type IntoIter = std::iter::Chain<std::slice::Iter<'a, Quota>, std::slice::Iter<'a, Quota>>;
1826
1827    fn into_iter(self) -> Self::IntoIter {
1828        self.global_quotas.iter().chain(self.project_quotas.iter())
1829    }
1830}
1831
1832#[cfg(test)]
1833mod tests {
1834    use insta::assert_debug_snapshot;
1835    use relay_common::glob2::LazyGlob;
1836    use relay_dynamic_config::ProjectConfig;
1837    use relay_event_normalization::{
1838        NormalizationConfig, RedactionRule, TransactionNameConfig, TransactionNameRule,
1839    };
1840    use relay_event_schema::protocol::{Event, EventId, TransactionSource};
1841    use relay_pii::DataScrubbingConfig;
1842    use relay_protocol::Annotated;
1843    #[cfg(feature = "processing")]
1844    use relay_quotas::DataCategory;
1845    use similar_asserts::assert_eq;
1846
1847    use crate::testutils::{create_test_processor, create_test_processor_with_addrs};
1848
1849    #[cfg(feature = "processing")]
1850    use {
1851        relay_metrics::BucketValue,
1852        relay_quotas::{QuotaScope, ReasonCode},
1853        relay_test::mock_service,
1854    };
1855
1856    use super::*;
1857
1858    async fn process_to_single_envelope<'a>(
1859        processor: &EnvelopeProcessorService,
1860        envelope: ManagedEnvelope,
1861        ctx: processing::Context<'a>,
1862    ) -> Box<Envelope> {
1863        let mut outputs = processor.process(envelope, ctx).await;
1864        assert_eq!(outputs.len(), 1);
1865
1866        let Output { main, metrics } = outputs.pop().unwrap();
1867
1868        if let Some(metrics) = metrics {
1869            metrics.accept(drop);
1870        }
1871
1872        main.unwrap()
1873            .serialize_envelope(ctx.to_forward())
1874            .unwrap()
1875            .accept(|envelope| envelope)
1876    }
1877
1878    #[cfg(feature = "processing")]
1879    fn mock_quota(id: &str) -> Quota {
1880        Quota {
1881            id: Some(id.into()),
1882            categories: [DataCategory::MetricBucket].into(),
1883            scope: QuotaScope::Organization,
1884            scope_id: None,
1885            limit: Some(0),
1886            window: None,
1887            reason_code: None,
1888            namespace: None,
1889        }
1890    }
1891
1892    #[cfg(feature = "processing")]
1893    #[test]
1894    fn test_dynamic_quotas() {
1895        let global_config = relay_dynamic_config::GlobalConfig {
1896            quotas: vec![mock_quota("foo"), mock_quota("bar")],
1897            ..Default::default()
1898        };
1899
1900        let project_quotas = vec![mock_quota("baz"), mock_quota("qux")];
1901
1902        let dynamic_quotas = CombinedQuotas::new(&global_config, &project_quotas);
1903
1904        let quota_ids = dynamic_quotas.into_iter().filter_map(|q| q.id.as_deref());
1905        assert!(quota_ids.eq(["foo", "bar", "baz", "qux"]));
1906    }
1907
1908    /// Ensures that if we ratelimit one batch of buckets in [`FlushBuckets`] message, it won't
1909    /// also ratelimit the next batches in the same message automatically.
1910    #[cfg(feature = "processing")]
1911    #[tokio::test]
1912    async fn test_ratelimit_per_batch() {
1913        use relay_base_schema::organization::OrganizationId;
1914        use relay_protocol::FiniteF64;
1915
1916        let rate_limited_org = Scoping {
1917            organization_id: OrganizationId::new(1),
1918            project_id: ProjectId::new(21),
1919            project_key: ProjectKey::parse("00000000000000000000000000000000").unwrap(),
1920            key_id: Some(17),
1921        };
1922
1923        let not_rate_limited_org = Scoping {
1924            organization_id: OrganizationId::new(2),
1925            project_id: ProjectId::new(21),
1926            project_key: ProjectKey::parse("11111111111111111111111111111111").unwrap(),
1927            key_id: Some(17),
1928        };
1929
1930        let message = {
1931            let project_info = {
1932                let quota = Quota {
1933                    id: Some("testing".into()),
1934                    categories: [DataCategory::MetricBucket].into(),
1935                    scope: relay_quotas::QuotaScope::Organization,
1936                    scope_id: Some(rate_limited_org.organization_id.to_string().into()),
1937                    limit: Some(0),
1938                    window: None,
1939                    reason_code: Some(ReasonCode::new("test")),
1940                    namespace: None,
1941                };
1942
1943                let mut config = ProjectConfig::default();
1944                config.quotas.push(quota);
1945
1946                Arc::new(ProjectInfo {
1947                    config,
1948                    ..Default::default()
1949                })
1950            };
1951
1952            let project_metrics = |scoping| ProjectBuckets {
1953                buckets: vec![Bucket {
1954                    name: "d:spans/bar".into(),
1955                    value: BucketValue::Counter(FiniteF64::new(1.0).unwrap()),
1956                    timestamp: UnixTimestamp::now(),
1957                    tags: Default::default(),
1958                    width: 10,
1959                    metadata: BucketMetadata::default(),
1960                }],
1961                rate_limits: Default::default(),
1962                project_info: project_info.clone(),
1963                scoping,
1964            };
1965
1966            let buckets = hashbrown::HashMap::from([
1967                (
1968                    rate_limited_org.project_key,
1969                    project_metrics(rate_limited_org),
1970                ),
1971                (
1972                    not_rate_limited_org.project_key,
1973                    project_metrics(not_rate_limited_org),
1974                ),
1975            ]);
1976
1977            FlushBuckets {
1978                partition_key: 0,
1979                buckets,
1980            }
1981        };
1982
1983        // ensure the order of the map while iterating is as expected.
1984        assert_eq!(message.buckets.keys().count(), 2);
1985
1986        let config = {
1987            let config_json = serde_json::json!({
1988                "processing": {
1989                    "enabled": true,
1990                    "kafka_config": [],
1991                    "redis": {
1992                        "server": std::env::var("RELAY_REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379".to_owned()),
1993                    }
1994                }
1995            });
1996            Config::from_json_value(config_json).unwrap()
1997        };
1998
1999        let (store, handle) = {
2000            let f = |org_ids: &mut Vec<OrganizationId>, msg: Store| {
2001                let org_id = match msg {
2002                    Store::Metrics(x) => x.scoping.organization_id,
2003                    _ => panic!("received envelope when expecting only metrics"),
2004                };
2005                org_ids.push(org_id);
2006            };
2007
2008            mock_service("store_forwarder", vec![], f)
2009        };
2010
2011        let processor = create_test_processor(config).await;
2012        assert!(processor.redis_rate_limiter_enabled());
2013
2014        processor.encode_metrics_processing(message, &store).await;
2015
2016        drop(store);
2017        let orgs_not_ratelimited = handle.await.unwrap();
2018
2019        assert_eq!(
2020            orgs_not_ratelimited,
2021            vec![not_rate_limited_org.organization_id]
2022        );
2023    }
2024
2025    #[tokio::test]
2026    async fn test_browser_version_extraction_with_pii_like_data() {
2027        let processor = create_test_processor(Default::default()).await;
2028        let outcome_aggregator = Addr::dummy();
2029        let event_id = EventId::new();
2030
2031        let dsn = "https://e12d836b15bb49d7bbf99e64295d995b:@sentry.io/42"
2032            .parse()
2033            .unwrap();
2034
2035        let request_meta = RequestMeta::new(dsn);
2036        let mut envelope = Envelope::from_request(Some(event_id), request_meta);
2037
2038        envelope.add_item({
2039                let mut item = Item::new(ItemType::Event);
2040                item.set_payload(
2041                    ContentType::Json,
2042                    r#"
2043                    {
2044                        "request": {
2045                            "headers": [
2046                                ["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"]
2047                            ]
2048                        }
2049                    }
2050                "#,
2051                );
2052                item
2053            });
2054
2055        let mut datascrubbing_settings = DataScrubbingConfig::default();
2056        // enable all the default scrubbing
2057        datascrubbing_settings.scrub_data = true;
2058        datascrubbing_settings.scrub_defaults = true;
2059        datascrubbing_settings.scrub_ip_addresses = true;
2060
2061        // Make sure to mask any IP-like looking data
2062        let pii_config = serde_json::from_str(r#"{"applications": {"**": ["@ip:mask"]}}"#).unwrap();
2063
2064        let config = ProjectConfig {
2065            datascrubbing_settings,
2066            pii_config: Some(pii_config),
2067            ..Default::default()
2068        };
2069
2070        let project_info = ProjectInfo {
2071            config,
2072            ..Default::default()
2073        };
2074
2075        let envelope = ManagedEnvelope::new(envelope, outcome_aggregator);
2076
2077        let ctx = processing::Context {
2078            project_info: &project_info,
2079            ..processing::Context::for_test()
2080        };
2081
2082        let new_envelope = process_to_single_envelope(&processor, envelope, ctx).await;
2083
2084        let event_item = new_envelope.items().last().unwrap();
2085        let annotated_event: Annotated<Event> =
2086            Annotated::from_json_bytes(&event_item.payload()).unwrap();
2087        let event = annotated_event.into_value().unwrap();
2088        let headers = event
2089            .request
2090            .into_value()
2091            .unwrap()
2092            .headers
2093            .into_value()
2094            .unwrap();
2095
2096        // IP-like data must be masked
2097        assert_eq!(
2098            Some(
2099                "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/********* Safari/537.36"
2100            ),
2101            headers.get_header("User-Agent")
2102        );
2103        // But we still get correct browser and version number
2104        let contexts = event.contexts.into_value().unwrap();
2105        let browser = contexts.0.get("browser").unwrap();
2106        assert_eq!(
2107            r#"{"browser":"Chrome 103.0.0","name":"Chrome","version":"103.0.0","type":"browser"}"#,
2108            browser.to_json().unwrap()
2109        );
2110    }
2111
2112    #[tokio::test]
2113    #[cfg(feature = "processing")]
2114    async fn test_materialize_dsc() {
2115        use crate::services::projects::project::PublicKeyConfig;
2116
2117        let dsn = "https://e12d836b15bb49d7bbf99e64295d995b:@sentry.io/42"
2118            .parse()
2119            .unwrap();
2120        let request_meta = RequestMeta::new(dsn);
2121        let mut envelope = Envelope::from_request(None, request_meta);
2122
2123        let dsc = r#"{
2124            "trace_id": "00000000-0000-0000-0000-000000000001",
2125            "public_key": "e12d836b15bb49d7bbf99e64295d995b",
2126            "sample_rate": "0.2"
2127        }"#;
2128        envelope.set_dsc(serde_json::from_str(dsc).unwrap());
2129
2130        let mut item = Item::new(ItemType::Event);
2131        item.set_payload(ContentType::Json, r#"{}"#);
2132        envelope.add_item(item);
2133
2134        let outcome_aggregator = Addr::dummy();
2135        let managed_envelope = ManagedEnvelope::new(envelope, outcome_aggregator);
2136
2137        let mut project_info = ProjectInfo::default();
2138        project_info.public_keys.push(PublicKeyConfig {
2139            public_key: ProjectKey::parse("e12d836b15bb49d7bbf99e64295d995b").unwrap(),
2140            numeric_id: Some(1),
2141        });
2142
2143        let config = serde_json::json!({
2144            "processing": {
2145                "enabled": true,
2146                "kafka_config": [],
2147            }
2148        });
2149
2150        let processor =
2151            create_test_processor(Config::from_json_value(config.clone()).unwrap()).await;
2152        let config = Config::from_json_value(config).unwrap();
2153        let ctx = processing::Context {
2154            config: &config,
2155            project_info: &project_info,
2156            sampling_project_info: Some(&project_info),
2157            ..processing::Context::for_test()
2158        };
2159
2160        let envelope = process_to_single_envelope(&processor, managed_envelope, ctx).await;
2161        let event = envelope
2162            .get_item_by(|item| item.ty() == &ItemType::Event)
2163            .unwrap();
2164
2165        let event = Annotated::<Event>::from_json_bytes(&event.payload()).unwrap();
2166        insta::assert_debug_snapshot!(event.value().unwrap()._dsc, @r###"
2167        Object(
2168            {
2169                "environment": ~,
2170                "public_key": String(
2171                    "e12d836b15bb49d7bbf99e64295d995b",
2172                ),
2173                "release": ~,
2174                "replay_id": ~,
2175                "sample_rate": String(
2176                    "0.2",
2177                ),
2178                "trace_id": String(
2179                    "00000000000000000000000000000001",
2180                ),
2181                "transaction": ~,
2182            },
2183        )
2184        "###);
2185    }
2186
2187    fn capture_test_event(transaction_name: &str, source: TransactionSource) -> Vec<String> {
2188        let mut event = Annotated::<Event>::from_json(
2189            r#"
2190            {
2191                "type": "transaction",
2192                "transaction": "/foo/",
2193                "timestamp": 946684810.0,
2194                "start_timestamp": 946684800.0,
2195                "contexts": {
2196                    "trace": {
2197                        "trace_id": "4c79f60c11214eb38604f4ae0781bfb2",
2198                        "span_id": "fa90fdead5f74053",
2199                        "op": "http.server",
2200                        "type": "trace"
2201                    }
2202                },
2203                "transaction_info": {
2204                    "source": "url"
2205                }
2206            }
2207            "#,
2208        )
2209        .unwrap();
2210        let e = event.value_mut().as_mut().unwrap();
2211        e.transaction.set_value(Some(transaction_name.into()));
2212
2213        e.transaction_info
2214            .value_mut()
2215            .as_mut()
2216            .unwrap()
2217            .source
2218            .set_value(Some(source));
2219
2220        relay_statsd::with_capturing_test_client(|| {
2221            utils::log_transaction_name_metrics(&mut event, |event| {
2222                let config = NormalizationConfig {
2223                    transaction_name_config: TransactionNameConfig {
2224                        rules: &[TransactionNameRule {
2225                            pattern: LazyGlob::new("/foo/*/**".to_owned()),
2226                            expiry: DateTime::<Utc>::MAX_UTC,
2227                            redaction: RedactionRule::Replace {
2228                                substitution: "*".to_owned(),
2229                            },
2230                        }],
2231                    },
2232                    ..Default::default()
2233                };
2234                relay_event_normalization::normalize_event(event, &config)
2235            });
2236        })
2237    }
2238
2239    #[test]
2240    fn test_log_transaction_metrics_none() {
2241        let captures = capture_test_event("/nothing", TransactionSource::Url);
2242        insta::assert_debug_snapshot!(captures, @r###"
2243        [
2244            "event.transaction_name_changes:1|c|#source_in:url,changes:none,source_out:sanitized,is_404:false",
2245        ]
2246        "###);
2247    }
2248
2249    #[test]
2250    fn test_log_transaction_metrics_rule() {
2251        let captures = capture_test_event("/foo/john/denver", TransactionSource::Url);
2252        insta::assert_debug_snapshot!(captures, @r###"
2253        [
2254            "event.transaction_name_changes:1|c|#source_in:url,changes:rule,source_out:sanitized,is_404:false",
2255        ]
2256        "###);
2257    }
2258
2259    #[test]
2260    fn test_log_transaction_metrics_pattern() {
2261        let captures = capture_test_event("/something/12345", TransactionSource::Url);
2262        insta::assert_debug_snapshot!(captures, @r###"
2263        [
2264            "event.transaction_name_changes:1|c|#source_in:url,changes:pattern,source_out:sanitized,is_404:false",
2265        ]
2266        "###);
2267    }
2268
2269    #[test]
2270    fn test_log_transaction_metrics_both() {
2271        let captures = capture_test_event("/foo/john/12345", TransactionSource::Url);
2272        insta::assert_debug_snapshot!(captures, @r###"
2273        [
2274            "event.transaction_name_changes:1|c|#source_in:url,changes:both,source_out:sanitized,is_404:false",
2275        ]
2276        "###);
2277    }
2278
2279    #[test]
2280    fn test_log_transaction_metrics_no_match() {
2281        let captures = capture_test_event("/foo/john/12345", TransactionSource::Route);
2282        insta::assert_debug_snapshot!(captures, @r###"
2283        [
2284            "event.transaction_name_changes:1|c|#source_in:route,changes:none,source_out:route,is_404:false",
2285        ]
2286        "###);
2287    }
2288
2289    #[tokio::test]
2290    async fn test_process_metrics_bucket_metadata() {
2291        let mut token = Cogs::noop().timed(ResourceId::Relay, AppFeature::Unattributed);
2292        let project_key = ProjectKey::parse("a94ae32be2584e0bbd7a4cbb95971fee").unwrap();
2293        let received_at = Utc::now();
2294        let config = Config::default();
2295
2296        let (aggregator, mut aggregator_rx) = Addr::custom();
2297        let processor = create_test_processor_with_addrs(
2298            config,
2299            Addrs {
2300                aggregator,
2301                ..Default::default()
2302            },
2303        )
2304        .await;
2305
2306        let mut item = Item::new(ItemType::Statsd);
2307        item.set_payload(ContentType::Text, "spans/foo:3182887624:4267882815|s");
2308        for (source, expected_received_at) in [
2309            (
2310                BucketSource::External,
2311                Some(UnixTimestamp::from_datetime(received_at).unwrap()),
2312            ),
2313            (BucketSource::Internal, None),
2314        ] {
2315            let message = ProcessMetrics {
2316                data: MetricData::Raw(vec![item.clone()]),
2317                project_key,
2318                source,
2319                received_at,
2320                sent_at: Some(Utc::now()),
2321            };
2322            processor.handle_process_metrics(&mut token, message);
2323
2324            let Aggregator::MergeBuckets(merge_buckets) = aggregator_rx.recv().await.unwrap();
2325            let buckets = merge_buckets.buckets;
2326            assert_eq!(buckets.len(), 1);
2327            assert_eq!(buckets[0].metadata.received_at, expected_received_at);
2328        }
2329    }
2330
2331    #[tokio::test]
2332    async fn test_process_batched_metrics() {
2333        let mut token = Cogs::noop().timed(ResourceId::Relay, AppFeature::Unattributed);
2334        let received_at = Utc::now();
2335        let config = Config::default();
2336
2337        let (aggregator, mut aggregator_rx) = Addr::custom();
2338        let processor = create_test_processor_with_addrs(
2339            config,
2340            Addrs {
2341                aggregator,
2342                ..Default::default()
2343            },
2344        )
2345        .await;
2346
2347        let payload = r#"{
2348    "buckets": {
2349        "11111111111111111111111111111111": [
2350            {
2351                "timestamp": 1615889440,
2352                "width": 0,
2353                "name": "d:custom/endpoint.response_time@millisecond",
2354                "type": "d",
2355                "value": [
2356                  68.0
2357                ],
2358                "tags": {
2359                  "route": "user_index"
2360                }
2361            }
2362        ],
2363        "22222222222222222222222222222222": [
2364            {
2365                "timestamp": 1615889440,
2366                "width": 0,
2367                "name": "d:custom/endpoint.cache_rate@none",
2368                "type": "d",
2369                "value": [
2370                  36.0
2371                ]
2372            }
2373        ]
2374    }
2375}
2376"#;
2377        let message = ProcessBatchedMetrics {
2378            payload: Bytes::from(payload),
2379            source: BucketSource::Internal,
2380            received_at,
2381            sent_at: Some(Utc::now()),
2382        };
2383        processor.handle_process_batched_metrics(&mut token, message);
2384
2385        let Aggregator::MergeBuckets(mb1) = aggregator_rx.recv().await.unwrap();
2386        let Aggregator::MergeBuckets(mb2) = aggregator_rx.recv().await.unwrap();
2387
2388        let mut messages = vec![mb1, mb2];
2389        messages.sort_by_key(|mb| mb.project_key);
2390
2391        let actual = messages
2392            .into_iter()
2393            .map(|mb| (mb.project_key, mb.buckets))
2394            .collect::<Vec<_>>();
2395
2396        assert_debug_snapshot!(actual, @r###"
2397        [
2398            (
2399                ProjectKey("11111111111111111111111111111111"),
2400                [
2401                    Bucket {
2402                        timestamp: UnixTimestamp(1615889440),
2403                        width: 0,
2404                        name: MetricName(
2405                            "d:custom/endpoint.response_time@millisecond",
2406                        ),
2407                        value: Distribution(
2408                            [
2409                                68.0,
2410                            ],
2411                        ),
2412                        tags: {
2413                            "route": "user_index",
2414                        },
2415                        metadata: BucketMetadata {
2416                            merges: 1,
2417                            received_at: None,
2418                            extracted_from_indexed: false,
2419                        },
2420                    },
2421                ],
2422            ),
2423            (
2424                ProjectKey("22222222222222222222222222222222"),
2425                [
2426                    Bucket {
2427                        timestamp: UnixTimestamp(1615889440),
2428                        width: 0,
2429                        name: MetricName(
2430                            "d:custom/endpoint.cache_rate@none",
2431                        ),
2432                        value: Distribution(
2433                            [
2434                                36.0,
2435                            ],
2436                        ),
2437                        tags: {},
2438                        metadata: BucketMetadata {
2439                            merges: 1,
2440                            received_at: None,
2441                            extracted_from_indexed: false,
2442                        },
2443                    },
2444                ],
2445            ),
2446        ]
2447        "###);
2448    }
2449}