Skip to main content

relay_dynamic_config/
global.rs

1use std::collections::HashMap;
2use std::fs::File;
3use std::io::BufReader;
4use std::path::Path;
5
6use relay_base_schema::metrics::MetricNamespace;
7use relay_event_normalization::{MeasurementsConfig, ModelMetadata, SpanOpDefaults};
8use relay_filter::GenericFiltersConfig;
9use relay_quotas::Quota;
10use serde::{Deserialize, Serialize, de};
11use serde_json::Value;
12
13use crate::{ErrorBoundary, MetricExtractionGroups};
14
15/// A dynamic configuration for all Relays passed down from Sentry.
16///
17/// Values shared across all projects may also be included here, to keep
18/// [`ProjectConfig`](crate::ProjectConfig)s small.
19#[derive(Default, Clone, Debug, Serialize, Deserialize)]
20#[serde(default, rename_all = "camelCase")]
21pub struct GlobalConfig {
22    /// Configuration for measurements normalization.
23    #[serde(skip_serializing_if = "Option::is_none")]
24    pub measurements: Option<MeasurementsConfig>,
25    /// Quotas that apply to all projects.
26    #[serde(skip_serializing_if = "Vec::is_empty")]
27    pub quotas: Vec<Quota>,
28    /// Configuration for global inbound filters.
29    ///
30    /// These filters are merged with generic filters in project configs before
31    /// applying.
32    #[serde(skip_serializing_if = "is_err_or_empty")]
33    pub filters: ErrorBoundary<GenericFiltersConfig>,
34    /// Sentry options passed down to Relay.
35    #[serde(
36        deserialize_with = "default_on_error",
37        skip_serializing_if = "is_default"
38    )]
39    pub options: Options,
40
41    /// Configuration for global metrics extraction rules.
42    ///
43    /// These are merged with rules in project configs before
44    /// applying.
45    #[serde(skip_serializing_if = "is_ok_and_empty")]
46    pub metric_extraction: ErrorBoundary<MetricExtractionGroups>,
47
48    /// Metadata for AI models including costs and context size.
49    #[serde(skip_serializing_if = "is_model_metadata_empty")]
50    pub ai_model_metadata: ErrorBoundary<ModelMetadata>,
51
52    /// Configuration to derive the `span.op` from other span fields.
53    #[serde(
54        deserialize_with = "default_on_error",
55        skip_serializing_if = "is_default"
56    )]
57    pub span_op_defaults: SpanOpDefaults,
58}
59
60impl GlobalConfig {
61    /// Loads the [`GlobalConfig`] from a file if it's provided.
62    ///
63    /// The folder_path argument should be the path to the folder where the Relay config and
64    /// credentials are stored.
65    pub fn load(folder_path: &Path) -> anyhow::Result<Option<Self>> {
66        let path = folder_path.join("global_config.json");
67
68        if path.exists() {
69            let file = BufReader::new(File::open(path)?);
70            Ok(Some(serde_json::from_reader(file)?))
71        } else {
72            Ok(None)
73        }
74    }
75
76    /// Returns the generic inbound filters.
77    pub fn filters(&self) -> Option<&GenericFiltersConfig> {
78        match &self.filters {
79            ErrorBoundary::Err(_) => None,
80            ErrorBoundary::Ok(f) => Some(f),
81        }
82    }
83
84    /// Returns the AI model metadata if configured and enabled.
85    pub fn ai_model_metadata(&self) -> Option<&ModelMetadata> {
86        self.ai_model_metadata
87            .as_ref()
88            .ok()
89            .filter(|m| m.is_enabled())
90    }
91}
92
93fn is_err_or_empty(filters_config: &ErrorBoundary<GenericFiltersConfig>) -> bool {
94    match filters_config {
95        ErrorBoundary::Err(_) => true,
96        ErrorBoundary::Ok(config) => config.version == 0 && config.filters.is_empty(),
97    }
98}
99
100// Temporary until we understand why we see false killswitch values sometimes appearing.
101fn default_killswitched() -> bool {
102    relay_log::info!("using default for endpoint fetch config");
103    bool::default()
104}
105
106/// All options passed down from Sentry to Relay.
107#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)]
108#[serde(default)]
109pub struct Options {
110    /// Metric bucket encoding configuration for sets by metric namespace.
111    #[serde(
112        rename = "relay.metric-bucket-set-encodings",
113        deserialize_with = "de_metric_bucket_encodings",
114        skip_serializing_if = "is_default"
115    )]
116    pub metric_bucket_set_encodings: BucketEncodings,
117    /// Metric bucket encoding configuration for distributions by metric namespace.
118    #[serde(
119        rename = "relay.metric-bucket-distribution-encodings",
120        deserialize_with = "de_metric_bucket_encodings",
121        skip_serializing_if = "is_default"
122    )]
123    pub metric_bucket_dist_encodings: BucketEncodings,
124
125    /// List of values on span description that are allowed to be sent to Sentry without being scrubbed.
126    ///
127    /// At this point, it doesn't accept IP addresses in CIDR format.. yet.
128    #[serde(
129        rename = "relay.span-normalization.allowed_hosts",
130        deserialize_with = "default_on_error",
131        skip_serializing_if = "Vec::is_empty"
132    )]
133    pub http_span_allowed_hosts: Vec<String>,
134
135    /// Instructs relay to store attachments in objectstore instead of sending chunks via kafka.
136    ///
137    /// Rate needs to be between `0.0` and `1.0`.
138    /// If set to `1.0` all attachments will be stored in objectstore.
139    #[serde(
140        rename = "relay.objectstore-attachments.sample-rate",
141        deserialize_with = "default_on_error",
142        skip_serializing_if = "is_default"
143    )]
144    pub objectstore_attachments_sample_rate: f32,
145
146    /// Rollout rate for the EAP (Event Analytics Platform) double-write for user sessions.
147    ///
148    /// When rolled out, session data is sent both through the legacy metrics pipeline
149    /// and directly to the `snuba-items` topic as `TRACE_ITEM_TYPE_USER_SESSION`.
150    ///
151    /// Rate needs to be between `0.0` and `1.0`.
152    #[serde(
153        rename = "relay.sessions-eap.rollout-rate",
154        deserialize_with = "default_on_error",
155        skip_serializing_if = "is_default"
156    )]
157    pub sessions_eap_rollout_rate: f32,
158
159    /// Kill-switch for fetching project configs in endpoints.
160    #[serde(
161        default = "default_killswitched",
162        rename = "relay.endpoint-fetch-config.enabled",
163        deserialize_with = "default_on_error",
164        skip_serializing_if = "is_default"
165    )]
166    pub endpoint_fetch_config_enabled: bool,
167
168    /// The limit under which relay in-lines attachments into the envelope even if uploading to
169    /// objectstore is enabled.
170    ///
171    /// If the attachment is smaller than the attachment reference obtained by
172    /// uploading, there is no point in uploading.
173    #[serde(
174        rename = "relay.attachment-inline.limit",
175        deserialize_with = "default_on_error",
176        skip_serializing_if = "is_default"
177    )]
178    pub attachment_inline_limit: usize,
179
180    /// Kill-switch for suppressing generic metrics.
181    #[serde(
182        rename = "relay.generic-metrics.disabled",
183        deserialize_with = "default_on_error",
184        skip_serializing_if = "is_default"
185    )]
186    pub generic_metrics_disabled: bool,
187
188    /// All other unknown options.
189    #[serde(flatten)]
190    other: HashMap<String, Value>,
191}
192
193/// Configuration container to control [`BucketEncoding`] per namespace.
194#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]
195#[serde(default)]
196pub struct BucketEncodings {
197    spans: BucketEncoding,
198    transactions: BucketEncoding,
199    profiles: BucketEncoding,
200}
201
202impl BucketEncodings {
203    /// Returns the configured encoding for a specific namespace.
204    pub fn for_namespace(&self, namespace: MetricNamespace) -> BucketEncoding {
205        match namespace {
206            MetricNamespace::Spans => self.spans,
207            MetricNamespace::Transactions => self.transactions,
208            // Always force the legacy encoding for sessions,
209            // sessions are not part of the generic metrics platform with different
210            // consumer which are not (yet) updated to support the new data.
211            MetricNamespace::Sessions => BucketEncoding::Legacy,
212            _ => BucketEncoding::Legacy,
213        }
214    }
215}
216
217/// Deserializes individual metric encodings or all from a string.
218///
219/// Returns a default when failing to deserialize.
220fn de_metric_bucket_encodings<'de, D>(deserializer: D) -> Result<BucketEncodings, D::Error>
221where
222    D: serde::de::Deserializer<'de>,
223{
224    struct Visitor;
225
226    impl<'de> de::Visitor<'de> for Visitor {
227        type Value = BucketEncodings;
228
229        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
230            formatter.write_str("metric bucket encodings")
231        }
232
233        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
234        where
235            E: de::Error,
236        {
237            let encoding = BucketEncoding::deserialize(de::value::StrDeserializer::new(v))?;
238            Ok(BucketEncodings {
239                spans: encoding,
240                transactions: encoding,
241                profiles: encoding,
242            })
243        }
244
245        fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
246        where
247            A: de::MapAccess<'de>,
248        {
249            BucketEncodings::deserialize(de::value::MapAccessDeserializer::new(map))
250        }
251    }
252
253    match deserializer.deserialize_any(Visitor) {
254        Ok(value) => Ok(value),
255        Err(error) => {
256            relay_log::error!(
257                error = %error,
258                "Error deserializing metric bucket encodings",
259            );
260            Ok(BucketEncodings::default())
261        }
262    }
263}
264
265/// All supported metric bucket encodings.
266#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]
267#[serde(rename_all = "lowercase")]
268pub enum BucketEncoding {
269    /// The default legacy encoding.
270    ///
271    /// A simple JSON array of numbers.
272    #[default]
273    Legacy,
274    /// The array encoding.
275    ///
276    /// Uses already the dynamic value format but still encodes
277    /// all values as a JSON number array.
278    Array,
279    /// Base64 encoding.
280    ///
281    /// Encodes all values as Base64.
282    Base64,
283    /// Zstd.
284    ///
285    /// Compresses all values with zstd.
286    Zstd,
287}
288
289/// Returns `true` if this value is equal to `Default::default()`.
290fn is_default<T: Default + PartialEq>(t: &T) -> bool {
291    t == &T::default()
292}
293
294fn default_on_error<'de, D, T>(deserializer: D) -> Result<T, D::Error>
295where
296    D: serde::de::Deserializer<'de>,
297    T: Default + serde::de::DeserializeOwned,
298{
299    match T::deserialize(deserializer) {
300        Ok(value) => Ok(value),
301        Err(error) => {
302            relay_log::error!(
303                error = %error,
304                "Error deserializing global config option: {}",
305                std::any::type_name::<T>(),
306            );
307            Ok(T::default())
308        }
309    }
310}
311
312fn is_ok_and_empty(value: &ErrorBoundary<MetricExtractionGroups>) -> bool {
313    matches!(
314        value,
315        &ErrorBoundary::Ok(MetricExtractionGroups { ref groups }) if groups.is_empty()
316    )
317}
318
319fn is_model_metadata_empty(value: &ErrorBoundary<ModelMetadata>) -> bool {
320    matches!(value, ErrorBoundary::Ok(metadata) if metadata.is_empty())
321}
322
323#[cfg(test)]
324mod tests {
325    use super::*;
326
327    #[test]
328    fn test_global_config_roundtrip() {
329        let json = r#"{
330  "measurements": {
331    "builtinMeasurements": [
332      {
333        "name": "foo",
334        "unit": "none"
335      },
336      {
337        "name": "bar",
338        "unit": "none"
339      },
340      {
341        "name": "baz",
342        "unit": "none"
343      }
344    ],
345    "maxCustomMeasurements": 5
346  },
347  "quotas": [
348    {
349      "id": "foo",
350      "categories": [
351        "metric_bucket"
352      ],
353      "scope": "organization",
354      "limit": 0,
355      "namespace": null
356    },
357    {
358      "id": "bar",
359      "categories": [
360        "metric_bucket"
361      ],
362      "scope": "organization",
363      "limit": 0,
364      "namespace": null
365    }
366  ],
367  "filters": {
368    "version": 1,
369    "filters": [
370      {
371        "id": "myError",
372        "isEnabled": true,
373        "condition": {
374          "op": "eq",
375          "name": "event.exceptions",
376          "value": "myError"
377        }
378      }
379    ]
380  }
381}"#;
382
383        let deserialized = serde_json::from_str::<GlobalConfig>(json).unwrap();
384        let serialized = serde_json::to_string_pretty(&deserialized).unwrap();
385        assert_eq!(json, serialized.as_str());
386    }
387
388    #[test]
389    fn test_minimal_serialization() {
390        let config = r#"{"options":{"foo":"bar"}}"#;
391        let deserialized: GlobalConfig = serde_json::from_str(config).unwrap();
392        let serialized = serde_json::to_string(&deserialized).unwrap();
393        assert_eq!(config, &serialized);
394    }
395
396    #[test]
397    fn test_metric_bucket_encodings_de_from_str() {
398        let o: Options = serde_json::from_str(
399            r#"{
400                "relay.metric-bucket-set-encodings": "legacy",
401                "relay.metric-bucket-distribution-encodings": "zstd"
402        }"#,
403        )
404        .unwrap();
405
406        assert_eq!(
407            o.metric_bucket_set_encodings,
408            BucketEncodings {
409                spans: BucketEncoding::Legacy,
410                transactions: BucketEncoding::Legacy,
411                profiles: BucketEncoding::Legacy,
412            }
413        );
414        assert_eq!(
415            o.metric_bucket_dist_encodings,
416            BucketEncodings {
417                spans: BucketEncoding::Zstd,
418                transactions: BucketEncoding::Zstd,
419                profiles: BucketEncoding::Zstd,
420            }
421        );
422    }
423
424    #[test]
425    fn test_metric_bucket_encodings_de_from_obj() {
426        let original = BucketEncodings {
427            spans: BucketEncoding::Zstd,
428            transactions: BucketEncoding::Zstd,
429            profiles: BucketEncoding::Base64,
430        };
431        let s = serde_json::to_string(&original).unwrap();
432        let s = format!(
433            r#"{{
434            "relay.metric-bucket-set-encodings": {s},
435            "relay.metric-bucket-distribution-encodings": {s}
436        }}"#
437        );
438
439        let o: Options = serde_json::from_str(&s).unwrap();
440        assert_eq!(o.metric_bucket_set_encodings, original);
441        assert_eq!(o.metric_bucket_dist_encodings, original);
442    }
443}