relay_dynamic_config/
global.rs

1use std::collections::HashMap;
2use std::collections::btree_map::Entry;
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::{Deserialize, Serialize, de};
12use serde_json::Value;
13
14use crate::{ErrorBoundary, MetricExtractionGroup, MetricExtractionGroups, defaults};
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_model_costs_empty")]
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    /// All other unknown options.
211    #[serde(flatten)]
212    other: HashMap<String, Value>,
213}
214
215/// Kill switch for controlling the cardinality limiter.
216#[derive(Default, Clone, Copy, Debug, Serialize, Deserialize, PartialEq)]
217#[serde(rename_all = "lowercase")]
218pub enum CardinalityLimiterMode {
219    /// Cardinality limiter is enabled.
220    #[default]
221    // De-serialize from the empty string, because the option was added to
222    // Sentry incorrectly which makes Sentry send the empty string as a default.
223    #[serde(alias = "")]
224    Enabled,
225    /// Cardinality limiter is enabled but cardinality limits are not enforced.
226    Passive,
227    /// Cardinality limiter is disabled.
228    Disabled,
229}
230
231/// Configuration container to control [`BucketEncoding`] per namespace.
232#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]
233#[serde(default)]
234pub struct BucketEncodings {
235    transactions: BucketEncoding,
236    spans: BucketEncoding,
237    profiles: BucketEncoding,
238    custom: BucketEncoding,
239    metric_stats: BucketEncoding,
240}
241
242impl BucketEncodings {
243    /// Returns the configured encoding for a specific namespace.
244    pub fn for_namespace(&self, namespace: MetricNamespace) -> BucketEncoding {
245        match namespace {
246            MetricNamespace::Transactions => self.transactions,
247            MetricNamespace::Spans => self.spans,
248            MetricNamespace::Custom => self.custom,
249            MetricNamespace::Stats => self.metric_stats,
250            // Always force the legacy encoding for sessions,
251            // sessions are not part of the generic metrics platform with different
252            // consumer which are not (yet) updated to support the new data.
253            MetricNamespace::Sessions => BucketEncoding::Legacy,
254            _ => BucketEncoding::Legacy,
255        }
256    }
257}
258
259/// Deserializes individual metric encodings or all from a string.
260///
261/// Returns a default when failing to deserialize.
262fn de_metric_bucket_encodings<'de, D>(deserializer: D) -> Result<BucketEncodings, D::Error>
263where
264    D: serde::de::Deserializer<'de>,
265{
266    struct Visitor;
267
268    impl<'de> de::Visitor<'de> for Visitor {
269        type Value = BucketEncodings;
270
271        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
272            formatter.write_str("metric bucket encodings")
273        }
274
275        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
276        where
277            E: de::Error,
278        {
279            let encoding = BucketEncoding::deserialize(de::value::StrDeserializer::new(v))?;
280            Ok(BucketEncodings {
281                transactions: encoding,
282                spans: encoding,
283                profiles: encoding,
284                custom: encoding,
285                metric_stats: encoding,
286            })
287        }
288
289        fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
290        where
291            A: de::MapAccess<'de>,
292        {
293            BucketEncodings::deserialize(de::value::MapAccessDeserializer::new(map))
294        }
295    }
296
297    match deserializer.deserialize_any(Visitor) {
298        Ok(value) => Ok(value),
299        Err(error) => {
300            relay_log::error!(
301                error = %error,
302                "Error deserializing metric bucket encodings",
303            );
304            Ok(BucketEncodings::default())
305        }
306    }
307}
308
309/// All supported metric bucket encodings.
310#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]
311#[serde(rename_all = "lowercase")]
312pub enum BucketEncoding {
313    /// The default legacy encoding.
314    ///
315    /// A simple JSON array of numbers.
316    #[default]
317    Legacy,
318    /// The array encoding.
319    ///
320    /// Uses already the dynamic value format but still encodes
321    /// all values as a JSON number array.
322    Array,
323    /// Base64 encoding.
324    ///
325    /// Encodes all values as Base64.
326    Base64,
327    /// Zstd.
328    ///
329    /// Compresses all values with zstd.
330    Zstd,
331}
332
333/// Returns `true` if this value is equal to `Default::default()`.
334fn is_default<T: Default + PartialEq>(t: &T) -> bool {
335    t == &T::default()
336}
337
338fn default_on_error<'de, D, T>(deserializer: D) -> Result<T, D::Error>
339where
340    D: serde::de::Deserializer<'de>,
341    T: Default + serde::de::DeserializeOwned,
342{
343    match T::deserialize(deserializer) {
344        Ok(value) => Ok(value),
345        Err(error) => {
346            relay_log::error!(
347                error = %error,
348                "Error deserializing global config option: {}",
349                std::any::type_name::<T>(),
350            );
351            Ok(T::default())
352        }
353    }
354}
355
356fn is_ok_and_empty(value: &ErrorBoundary<MetricExtractionGroups>) -> bool {
357    matches!(
358        value,
359        &ErrorBoundary::Ok(MetricExtractionGroups { ref groups }) if groups.is_empty()
360    )
361}
362
363fn is_model_costs_empty(value: &ErrorBoundary<ModelCosts>) -> bool {
364    matches!(value, ErrorBoundary::Ok(model_costs) if model_costs.is_empty())
365}
366
367#[cfg(test)]
368mod tests {
369    use super::*;
370
371    #[test]
372    fn test_global_config_roundtrip() {
373        let json = r#"{
374  "measurements": {
375    "builtinMeasurements": [
376      {
377        "name": "foo",
378        "unit": "none"
379      },
380      {
381        "name": "bar",
382        "unit": "none"
383      },
384      {
385        "name": "baz",
386        "unit": "none"
387      }
388    ],
389    "maxCustomMeasurements": 5
390  },
391  "quotas": [
392    {
393      "id": "foo",
394      "categories": [
395        "metric_bucket"
396      ],
397      "scope": "organization",
398      "limit": 0,
399      "namespace": null
400    },
401    {
402      "id": "bar",
403      "categories": [
404        "metric_bucket"
405      ],
406      "scope": "organization",
407      "limit": 0,
408      "namespace": null
409    }
410  ],
411  "filters": {
412    "version": 1,
413    "filters": [
414      {
415        "id": "myError",
416        "isEnabled": true,
417        "condition": {
418          "op": "eq",
419          "name": "event.exceptions",
420          "value": "myError"
421        }
422      }
423    ]
424  }
425}"#;
426
427        let deserialized = serde_json::from_str::<GlobalConfig>(json).unwrap();
428        let serialized = serde_json::to_string_pretty(&deserialized).unwrap();
429        assert_eq!(json, serialized.as_str());
430    }
431
432    #[test]
433    fn test_global_config_invalid_value_is_default() {
434        let options: Options = serde_json::from_str(
435            r#"{
436                "relay.cardinality-limiter.mode": "passive"
437            }"#,
438        )
439        .unwrap();
440
441        let expected = Options {
442            cardinality_limiter_mode: CardinalityLimiterMode::Passive,
443            ..Default::default()
444        };
445
446        assert_eq!(options, expected);
447    }
448
449    #[test]
450    fn test_cardinality_limiter_mode_de_serialize() {
451        let m: CardinalityLimiterMode = serde_json::from_str("\"\"").unwrap();
452        assert_eq!(m, CardinalityLimiterMode::Enabled);
453        let m: CardinalityLimiterMode = serde_json::from_str("\"enabled\"").unwrap();
454        assert_eq!(m, CardinalityLimiterMode::Enabled);
455        let m: CardinalityLimiterMode = serde_json::from_str("\"disabled\"").unwrap();
456        assert_eq!(m, CardinalityLimiterMode::Disabled);
457        let m: CardinalityLimiterMode = serde_json::from_str("\"passive\"").unwrap();
458        assert_eq!(m, CardinalityLimiterMode::Passive);
459
460        let m = serde_json::to_string(&CardinalityLimiterMode::Enabled).unwrap();
461        assert_eq!(m, "\"enabled\"");
462    }
463
464    #[test]
465    fn test_minimal_serialization() {
466        let config = r#"{"options":{"foo":"bar"}}"#;
467        let deserialized: GlobalConfig = serde_json::from_str(config).unwrap();
468        let serialized = serde_json::to_string(&deserialized).unwrap();
469        assert_eq!(config, &serialized);
470    }
471
472    #[test]
473    fn test_metric_bucket_encodings_de_from_str() {
474        let o: Options = serde_json::from_str(
475            r#"{
476                "relay.metric-bucket-set-encodings": "legacy",
477                "relay.metric-bucket-distribution-encodings": "zstd"
478        }"#,
479        )
480        .unwrap();
481
482        assert_eq!(
483            o.metric_bucket_set_encodings,
484            BucketEncodings {
485                transactions: BucketEncoding::Legacy,
486                spans: BucketEncoding::Legacy,
487                profiles: BucketEncoding::Legacy,
488                custom: BucketEncoding::Legacy,
489                metric_stats: BucketEncoding::Legacy,
490            }
491        );
492        assert_eq!(
493            o.metric_bucket_dist_encodings,
494            BucketEncodings {
495                transactions: BucketEncoding::Zstd,
496                spans: BucketEncoding::Zstd,
497                profiles: BucketEncoding::Zstd,
498                custom: BucketEncoding::Zstd,
499                metric_stats: BucketEncoding::Zstd,
500            }
501        );
502    }
503
504    #[test]
505    fn test_metric_bucket_encodings_de_from_obj() {
506        let original = BucketEncodings {
507            transactions: BucketEncoding::Base64,
508            spans: BucketEncoding::Zstd,
509            profiles: BucketEncoding::Base64,
510            custom: BucketEncoding::Zstd,
511            metric_stats: BucketEncoding::Base64,
512        };
513        let s = serde_json::to_string(&original).unwrap();
514        let s = format!(
515            r#"{{
516            "relay.metric-bucket-set-encodings": {s},
517            "relay.metric-bucket-distribution-encodings": {s}
518        }}"#
519        );
520
521        let o: Options = serde_json::from_str(&s).unwrap();
522        assert_eq!(o.metric_bucket_set_encodings, original);
523        assert_eq!(o.metric_bucket_dist_encodings, original);
524    }
525}