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