Skip to main content

relay_server/services/
processor.rs

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