relay_dynamic_config/
global.rs

1use std::collections::btree_map::Entry;
2use std::collections::HashMap;
3use std::fs::File;
4use std::io::BufReader;
5use std::path::Path;
6
7use relay_base_schema::metrics::MetricNamespace;
8use relay_event_normalization::{MeasurementsConfig, ModelCosts, SpanOpDefaults};
9use relay_filter::GenericFiltersConfig;
10use relay_quotas::Quota;
11use serde::{de, Deserialize, Serialize};
12use serde_json::Value;
13
14use crate::{defaults, ErrorBoundary, MetricExtractionGroup, MetricExtractionGroups};
15
16/// A dynamic configuration for all Relays passed down from Sentry.
17///
18/// Values shared across all projects may also be included here, to keep
19/// [`ProjectConfig`](crate::ProjectConfig)s small.
20#[derive(Default, Clone, Debug, Serialize, Deserialize)]
21#[serde(default, rename_all = "camelCase")]
22pub struct GlobalConfig {
23    /// Configuration for measurements normalization.
24    #[serde(skip_serializing_if = "Option::is_none")]
25    pub measurements: Option<MeasurementsConfig>,
26    /// Quotas that apply to all projects.
27    #[serde(skip_serializing_if = "Vec::is_empty")]
28    pub quotas: Vec<Quota>,
29    /// Configuration for global inbound filters.
30    ///
31    /// These filters are merged with generic filters in project configs before
32    /// applying.
33    #[serde(skip_serializing_if = "is_err_or_empty")]
34    pub filters: ErrorBoundary<GenericFiltersConfig>,
35    /// Sentry options passed down to Relay.
36    #[serde(
37        deserialize_with = "default_on_error",
38        skip_serializing_if = "is_default"
39    )]
40    pub options: Options,
41
42    /// Configuration for global metrics extraction rules.
43    ///
44    /// These are merged with rules in project configs before
45    /// applying.
46    #[serde(skip_serializing_if = "is_ok_and_empty")]
47    pub metric_extraction: ErrorBoundary<MetricExtractionGroups>,
48
49    /// Configuration for AI span measurements.
50    #[serde(skip_serializing_if = "is_missing")]
51    pub ai_model_costs: ErrorBoundary<ModelCosts>,
52
53    /// Configuration to derive the `span.op` from other span fields.
54    #[serde(
55        deserialize_with = "default_on_error",
56        skip_serializing_if = "is_default"
57    )]
58    pub span_op_defaults: SpanOpDefaults,
59}
60
61impl GlobalConfig {
62    /// Loads the [`GlobalConfig`] from a file if it's provided.
63    ///
64    /// The folder_path argument should be the path to the folder where the Relay config and
65    /// credentials are stored.
66    pub fn load(folder_path: &Path) -> anyhow::Result<Option<Self>> {
67        let path = folder_path.join("global_config.json");
68
69        if path.exists() {
70            let file = BufReader::new(File::open(path)?);
71            Ok(Some(serde_json::from_reader(file)?))
72        } else {
73            Ok(None)
74        }
75    }
76
77    /// Returns the generic inbound filters.
78    pub fn filters(&self) -> Option<&GenericFiltersConfig> {
79        match &self.filters {
80            ErrorBoundary::Err(_) => None,
81            ErrorBoundary::Ok(f) => Some(f),
82        }
83    }
84
85    /// Modifies the global config after deserialization.
86    ///
87    /// - Adds hard-coded groups to metrics extraction configs.
88    pub fn normalize(&mut self) {
89        if let ErrorBoundary::Ok(config) = &mut self.metric_extraction {
90            for (group_name, metrics, tags) in defaults::hardcoded_span_metrics() {
91                // We only define these groups if they haven't been defined by the upstream yet.
92                // This ensures that the innermost Relay always defines the metrics.
93                if let Entry::Vacant(entry) = config.groups.entry(group_name) {
94                    entry.insert(MetricExtractionGroup {
95                        is_enabled: false, // must be enabled via project config
96                        metrics,
97                        tags,
98                    });
99                }
100            }
101        }
102    }
103}
104
105fn is_err_or_empty(filters_config: &ErrorBoundary<GenericFiltersConfig>) -> bool {
106    match filters_config {
107        ErrorBoundary::Err(_) => true,
108        ErrorBoundary::Ok(config) => config.version == 0 && config.filters.is_empty(),
109    }
110}
111
112/// All options passed down from Sentry to Relay.
113#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)]
114#[serde(default)]
115pub struct Options {
116    /// Kill switch for controlling the cardinality limiter.
117    #[serde(
118        rename = "relay.cardinality-limiter.mode",
119        deserialize_with = "default_on_error",
120        skip_serializing_if = "is_default"
121    )]
122    pub cardinality_limiter_mode: CardinalityLimiterMode,
123
124    /// Sample rate for Cardinality Limiter Sentry errors.
125    ///
126    /// Rate needs to be between `0.0` and `1.0`.
127    /// If set to `1.0` all cardinality limiter rejections will be logged as a Sentry error.
128    #[serde(
129        rename = "relay.cardinality-limiter.error-sample-rate",
130        deserialize_with = "default_on_error",
131        skip_serializing_if = "is_default"
132    )]
133    pub cardinality_limiter_error_sample_rate: f32,
134
135    /// Metric bucket encoding configuration for sets by metric namespace.
136    #[serde(
137        rename = "relay.metric-bucket-set-encodings",
138        deserialize_with = "de_metric_bucket_encodings",
139        skip_serializing_if = "is_default"
140    )]
141    pub metric_bucket_set_encodings: BucketEncodings,
142    /// Metric bucket encoding configuration for distributions by metric namespace.
143    #[serde(
144        rename = "relay.metric-bucket-distribution-encodings",
145        deserialize_with = "de_metric_bucket_encodings",
146        skip_serializing_if = "is_default"
147    )]
148    pub metric_bucket_dist_encodings: BucketEncodings,
149
150    /// Rollout rate for metric stats.
151    ///
152    /// Rate needs to be between `0.0` and `1.0`.
153    /// If set to `1.0` all organizations will have metric stats enabled.
154    #[serde(
155        rename = "relay.metric-stats.rollout-rate",
156        deserialize_with = "default_on_error",
157        skip_serializing_if = "is_default"
158    )]
159    pub metric_stats_rollout_rate: f32,
160
161    /// Overall sampling of span extraction.
162    ///
163    /// This number represents the fraction of transactions for which
164    /// spans are extracted. It applies on top of [`crate::Feature::ExtractCommonSpanMetricsFromEvent`],
165    /// so both feature flag and sample rate need to be enabled to get any spans extracted.
166    ///
167    /// `None` is the default and interpreted as a value of 1.0 (extract everything).
168    ///
169    /// Note: Any value below 1.0 will cause the product to break, so use with caution.
170    #[serde(
171        rename = "relay.span-extraction.sample-rate",
172        deserialize_with = "default_on_error",
173        skip_serializing_if = "is_default"
174    )]
175    pub span_extraction_sample_rate: Option<f32>,
176
177    /// Sample rate at which to ingest logs.
178    ///
179    /// This number represents the fraction of received logs that are processed. It only applies if
180    /// [`crate::Feature::OurLogsIngestion`] is enabled.
181    ///
182    /// `None` is the default and interpreted as a value of 1.0 (ingest everything).
183    ///
184    /// Note: Any value below 1.0 will cause the product to not show all the users data, so use with caution.
185    #[serde(
186        rename = "relay.ourlogs-ingestion.sample-rate",
187        deserialize_with = "default_on_error",
188        skip_serializing_if = "is_default"
189    )]
190    pub ourlogs_ingestion_sample_rate: Option<f32>,
191
192    /// List of values on span description that are allowed to be sent to Sentry without being scrubbed.
193    ///
194    /// At this point, it doesn't accept IP addresses in CIDR format.. yet.
195    #[serde(
196        rename = "relay.span-normalization.allowed_hosts",
197        deserialize_with = "default_on_error",
198        skip_serializing_if = "Vec::is_empty"
199    )]
200    pub http_span_allowed_hosts: Vec<String>,
201
202    /// Whether or not relay should drop attachments submitted with transactions.
203    #[serde(
204        rename = "relay.drop-transaction-attachments",
205        deserialize_with = "default_on_error",
206        skip_serializing_if = "is_default"
207    )]
208    pub drop_transaction_attachments: bool,
209
210    /// Deprecated, still forwarded for older downstream Relays.
211    #[doc(hidden)]
212    #[serde(
213        rename = "profiling.profile_metrics.unsampled_profiles.platforms",
214        deserialize_with = "default_on_error",
215        skip_serializing_if = "Vec::is_empty"
216    )]
217    pub deprecated1: Vec<String>,
218
219    /// Deprecated, still forwarded for older downstream Relays.
220    #[doc(hidden)]
221    #[serde(
222        rename = "profiling.profile_metrics.unsampled_profiles.sample_rate",
223        deserialize_with = "default_on_error",
224        skip_serializing_if = "is_default"
225    )]
226    pub deprecated2: f32,
227
228    /// All other unknown options.
229    #[serde(flatten)]
230    other: HashMap<String, Value>,
231}
232
233/// Kill switch for controlling the cardinality limiter.
234#[derive(Default, Clone, Copy, Debug, Serialize, Deserialize, PartialEq)]
235#[serde(rename_all = "lowercase")]
236pub enum CardinalityLimiterMode {
237    /// Cardinality limiter is enabled.
238    #[default]
239    // De-serialize from the empty string, because the option was added to
240    // Sentry incorrectly which makes Sentry send the empty string as a default.
241    #[serde(alias = "")]
242    Enabled,
243    /// Cardinality limiter is enabled but cardinality limits are not enforced.
244    Passive,
245    /// Cardinality limiter is disabled.
246    Disabled,
247}
248
249/// Configuration container to control [`BucketEncoding`] per namespace.
250#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]
251#[serde(default)]
252pub struct BucketEncodings {
253    transactions: BucketEncoding,
254    spans: BucketEncoding,
255    profiles: BucketEncoding,
256    custom: BucketEncoding,
257    metric_stats: BucketEncoding,
258}
259
260impl BucketEncodings {
261    /// Returns the configured encoding for a specific namespace.
262    pub fn for_namespace(&self, namespace: MetricNamespace) -> BucketEncoding {
263        match namespace {
264            MetricNamespace::Transactions => self.transactions,
265            MetricNamespace::Spans => self.spans,
266            MetricNamespace::Custom => self.custom,
267            MetricNamespace::Stats => self.metric_stats,
268            // Always force the legacy encoding for sessions,
269            // sessions are not part of the generic metrics platform with different
270            // consumer which are not (yet) updated to support the new data.
271            MetricNamespace::Sessions => BucketEncoding::Legacy,
272            _ => BucketEncoding::Legacy,
273        }
274    }
275}
276
277/// Deserializes individual metric encodings or all from a string.
278///
279/// Returns a default when failing to deserialize.
280fn de_metric_bucket_encodings<'de, D>(deserializer: D) -> Result<BucketEncodings, D::Error>
281where
282    D: serde::de::Deserializer<'de>,
283{
284    struct Visitor;
285
286    impl<'de> de::Visitor<'de> for Visitor {
287        type Value = BucketEncodings;
288
289        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
290            formatter.write_str("metric bucket encodings")
291        }
292
293        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
294        where
295            E: de::Error,
296        {
297            let encoding = BucketEncoding::deserialize(de::value::StrDeserializer::new(v))?;
298            Ok(BucketEncodings {
299                transactions: encoding,
300                spans: encoding,
301                profiles: encoding,
302                custom: encoding,
303                metric_stats: encoding,
304            })
305        }
306
307        fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
308        where
309            A: de::MapAccess<'de>,
310        {
311            BucketEncodings::deserialize(de::value::MapAccessDeserializer::new(map))
312        }
313    }
314
315    match deserializer.deserialize_any(Visitor) {
316        Ok(value) => Ok(value),
317        Err(error) => {
318            relay_log::error!(
319                error = %error,
320                "Error deserializing metric bucket encodings",
321            );
322            Ok(BucketEncodings::default())
323        }
324    }
325}
326
327/// All supported metric bucket encodings.
328#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]
329#[serde(rename_all = "lowercase")]
330pub enum BucketEncoding {
331    /// The default legacy encoding.
332    ///
333    /// A simple JSON array of numbers.
334    #[default]
335    Legacy,
336    /// The array encoding.
337    ///
338    /// Uses already the dynamic value format but still encodes
339    /// all values as a JSON number array.
340    Array,
341    /// Base64 encoding.
342    ///
343    /// Encodes all values as Base64.
344    Base64,
345    /// Zstd.
346    ///
347    /// Compresses all values with zstd.
348    Zstd,
349}
350
351/// Returns `true` if this value is equal to `Default::default()`.
352fn is_default<T: Default + PartialEq>(t: &T) -> bool {
353    t == &T::default()
354}
355
356fn default_on_error<'de, D, T>(deserializer: D) -> Result<T, D::Error>
357where
358    D: serde::de::Deserializer<'de>,
359    T: Default + serde::de::DeserializeOwned,
360{
361    match T::deserialize(deserializer) {
362        Ok(value) => Ok(value),
363        Err(error) => {
364            relay_log::error!(
365                error = %error,
366                "Error deserializing global config option: {}",
367                std::any::type_name::<T>(),
368            );
369            Ok(T::default())
370        }
371    }
372}
373
374fn is_ok_and_empty(value: &ErrorBoundary<MetricExtractionGroups>) -> bool {
375    matches!(
376        value,
377        &ErrorBoundary::Ok(MetricExtractionGroups { ref groups }) if groups.is_empty()
378    )
379}
380
381fn is_missing(value: &ErrorBoundary<ModelCosts>) -> bool {
382    matches!(
383        value,
384        &ErrorBoundary::Ok(ModelCosts{ version, ref costs }) if version == 0 && costs.is_empty()
385    )
386}
387
388#[cfg(test)]
389mod tests {
390    use super::*;
391
392    #[test]
393    fn test_global_config_roundtrip() {
394        let json = r#"{
395  "measurements": {
396    "builtinMeasurements": [
397      {
398        "name": "foo",
399        "unit": "none"
400      },
401      {
402        "name": "bar",
403        "unit": "none"
404      },
405      {
406        "name": "baz",
407        "unit": "none"
408      }
409    ],
410    "maxCustomMeasurements": 5
411  },
412  "quotas": [
413    {
414      "id": "foo",
415      "categories": [
416        "metric_bucket"
417      ],
418      "scope": "organization",
419      "limit": 0,
420      "namespace": null
421    },
422    {
423      "id": "bar",
424      "categories": [
425        "metric_bucket"
426      ],
427      "scope": "organization",
428      "limit": 0,
429      "namespace": null
430    }
431  ],
432  "filters": {
433    "version": 1,
434    "filters": [
435      {
436        "id": "myError",
437        "isEnabled": true,
438        "condition": {
439          "op": "eq",
440          "name": "event.exceptions",
441          "value": "myError"
442        }
443      }
444    ]
445  }
446}"#;
447
448        let deserialized = serde_json::from_str::<GlobalConfig>(json).unwrap();
449        let serialized = serde_json::to_string_pretty(&deserialized).unwrap();
450        assert_eq!(json, serialized.as_str());
451    }
452
453    #[test]
454    fn test_global_config_invalid_value_is_default() {
455        let options: Options = serde_json::from_str(
456            r#"{
457                "relay.cardinality-limiter.mode": "passive"
458            }"#,
459        )
460        .unwrap();
461
462        let expected = Options {
463            cardinality_limiter_mode: CardinalityLimiterMode::Passive,
464            ..Default::default()
465        };
466
467        assert_eq!(options, expected);
468    }
469
470    #[test]
471    fn test_cardinality_limiter_mode_de_serialize() {
472        let m: CardinalityLimiterMode = serde_json::from_str("\"\"").unwrap();
473        assert_eq!(m, CardinalityLimiterMode::Enabled);
474        let m: CardinalityLimiterMode = serde_json::from_str("\"enabled\"").unwrap();
475        assert_eq!(m, CardinalityLimiterMode::Enabled);
476        let m: CardinalityLimiterMode = serde_json::from_str("\"disabled\"").unwrap();
477        assert_eq!(m, CardinalityLimiterMode::Disabled);
478        let m: CardinalityLimiterMode = serde_json::from_str("\"passive\"").unwrap();
479        assert_eq!(m, CardinalityLimiterMode::Passive);
480
481        let m = serde_json::to_string(&CardinalityLimiterMode::Enabled).unwrap();
482        assert_eq!(m, "\"enabled\"");
483    }
484
485    #[test]
486    fn test_minimal_serialization() {
487        let config = r#"{"options":{"foo":"bar"}}"#;
488        let deserialized: GlobalConfig = serde_json::from_str(config).unwrap();
489        let serialized = serde_json::to_string(&deserialized).unwrap();
490        assert_eq!(config, &serialized);
491    }
492
493    #[test]
494    fn test_metric_bucket_encodings_de_from_str() {
495        let o: Options = serde_json::from_str(
496            r#"{
497                "relay.metric-bucket-set-encodings": "legacy",
498                "relay.metric-bucket-distribution-encodings": "zstd"
499        }"#,
500        )
501        .unwrap();
502
503        assert_eq!(
504            o.metric_bucket_set_encodings,
505            BucketEncodings {
506                transactions: BucketEncoding::Legacy,
507                spans: BucketEncoding::Legacy,
508                profiles: BucketEncoding::Legacy,
509                custom: BucketEncoding::Legacy,
510                metric_stats: BucketEncoding::Legacy,
511            }
512        );
513        assert_eq!(
514            o.metric_bucket_dist_encodings,
515            BucketEncodings {
516                transactions: BucketEncoding::Zstd,
517                spans: BucketEncoding::Zstd,
518                profiles: BucketEncoding::Zstd,
519                custom: BucketEncoding::Zstd,
520                metric_stats: BucketEncoding::Zstd,
521            }
522        );
523    }
524
525    #[test]
526    fn test_metric_bucket_encodings_de_from_obj() {
527        let original = BucketEncodings {
528            transactions: BucketEncoding::Base64,
529            spans: BucketEncoding::Zstd,
530            profiles: BucketEncoding::Base64,
531            custom: BucketEncoding::Zstd,
532            metric_stats: BucketEncoding::Base64,
533        };
534        let s = serde_json::to_string(&original).unwrap();
535        let s = format!(
536            r#"{{
537            "relay.metric-bucket-set-encodings": {s},
538            "relay.metric-bucket-distribution-encodings": {s}
539        }}"#
540        );
541
542        let o: Options = serde_json::from_str(&s).unwrap();
543        assert_eq!(o.metric_bucket_set_encodings, original);
544        assert_eq!(o.metric_bucket_dist_encodings, original);
545    }
546}