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    /// All other unknown options.
169    #[serde(flatten)]
170    other: HashMap<String, Value>,
171}
172
173/// Configuration container to control [`BucketEncoding`] per namespace.
174#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]
175#[serde(default)]
176pub struct BucketEncodings {
177    spans: BucketEncoding,
178    transactions: BucketEncoding,
179    profiles: BucketEncoding,
180    custom: BucketEncoding,
181}
182
183impl BucketEncodings {
184    /// Returns the configured encoding for a specific namespace.
185    pub fn for_namespace(&self, namespace: MetricNamespace) -> BucketEncoding {
186        match namespace {
187            MetricNamespace::Spans => self.spans,
188            MetricNamespace::Transactions => self.transactions,
189            MetricNamespace::Custom => self.custom,
190            // Always force the legacy encoding for sessions,
191            // sessions are not part of the generic metrics platform with different
192            // consumer which are not (yet) updated to support the new data.
193            MetricNamespace::Sessions => BucketEncoding::Legacy,
194            _ => BucketEncoding::Legacy,
195        }
196    }
197}
198
199/// Deserializes individual metric encodings or all from a string.
200///
201/// Returns a default when failing to deserialize.
202fn de_metric_bucket_encodings<'de, D>(deserializer: D) -> Result<BucketEncodings, D::Error>
203where
204    D: serde::de::Deserializer<'de>,
205{
206    struct Visitor;
207
208    impl<'de> de::Visitor<'de> for Visitor {
209        type Value = BucketEncodings;
210
211        fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
212            formatter.write_str("metric bucket encodings")
213        }
214
215        fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
216        where
217            E: de::Error,
218        {
219            let encoding = BucketEncoding::deserialize(de::value::StrDeserializer::new(v))?;
220            Ok(BucketEncodings {
221                spans: encoding,
222                transactions: encoding,
223                profiles: encoding,
224                custom: encoding,
225            })
226        }
227
228        fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
229        where
230            A: de::MapAccess<'de>,
231        {
232            BucketEncodings::deserialize(de::value::MapAccessDeserializer::new(map))
233        }
234    }
235
236    match deserializer.deserialize_any(Visitor) {
237        Ok(value) => Ok(value),
238        Err(error) => {
239            relay_log::error!(
240                error = %error,
241                "Error deserializing metric bucket encodings",
242            );
243            Ok(BucketEncodings::default())
244        }
245    }
246}
247
248/// All supported metric bucket encodings.
249#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]
250#[serde(rename_all = "lowercase")]
251pub enum BucketEncoding {
252    /// The default legacy encoding.
253    ///
254    /// A simple JSON array of numbers.
255    #[default]
256    Legacy,
257    /// The array encoding.
258    ///
259    /// Uses already the dynamic value format but still encodes
260    /// all values as a JSON number array.
261    Array,
262    /// Base64 encoding.
263    ///
264    /// Encodes all values as Base64.
265    Base64,
266    /// Zstd.
267    ///
268    /// Compresses all values with zstd.
269    Zstd,
270}
271
272/// Returns `true` if this value is equal to `Default::default()`.
273fn is_default<T: Default + PartialEq>(t: &T) -> bool {
274    t == &T::default()
275}
276
277fn default_on_error<'de, D, T>(deserializer: D) -> Result<T, D::Error>
278where
279    D: serde::de::Deserializer<'de>,
280    T: Default + serde::de::DeserializeOwned,
281{
282    match T::deserialize(deserializer) {
283        Ok(value) => Ok(value),
284        Err(error) => {
285            relay_log::error!(
286                error = %error,
287                "Error deserializing global config option: {}",
288                std::any::type_name::<T>(),
289            );
290            Ok(T::default())
291        }
292    }
293}
294
295fn is_ok_and_empty(value: &ErrorBoundary<MetricExtractionGroups>) -> bool {
296    matches!(
297        value,
298        &ErrorBoundary::Ok(MetricExtractionGroups { ref groups }) if groups.is_empty()
299    )
300}
301
302fn is_model_metadata_empty(value: &ErrorBoundary<ModelMetadata>) -> bool {
303    matches!(value, ErrorBoundary::Ok(metadata) if metadata.is_empty())
304}
305
306#[cfg(test)]
307mod tests {
308    use super::*;
309
310    #[test]
311    fn test_global_config_roundtrip() {
312        let json = r#"{
313  "measurements": {
314    "builtinMeasurements": [
315      {
316        "name": "foo",
317        "unit": "none"
318      },
319      {
320        "name": "bar",
321        "unit": "none"
322      },
323      {
324        "name": "baz",
325        "unit": "none"
326      }
327    ],
328    "maxCustomMeasurements": 5
329  },
330  "quotas": [
331    {
332      "id": "foo",
333      "categories": [
334        "metric_bucket"
335      ],
336      "scope": "organization",
337      "limit": 0,
338      "namespace": null
339    },
340    {
341      "id": "bar",
342      "categories": [
343        "metric_bucket"
344      ],
345      "scope": "organization",
346      "limit": 0,
347      "namespace": null
348    }
349  ],
350  "filters": {
351    "version": 1,
352    "filters": [
353      {
354        "id": "myError",
355        "isEnabled": true,
356        "condition": {
357          "op": "eq",
358          "name": "event.exceptions",
359          "value": "myError"
360        }
361      }
362    ]
363  }
364}"#;
365
366        let deserialized = serde_json::from_str::<GlobalConfig>(json).unwrap();
367        let serialized = serde_json::to_string_pretty(&deserialized).unwrap();
368        assert_eq!(json, serialized.as_str());
369    }
370
371    #[test]
372    fn test_minimal_serialization() {
373        let config = r#"{"options":{"foo":"bar"}}"#;
374        let deserialized: GlobalConfig = serde_json::from_str(config).unwrap();
375        let serialized = serde_json::to_string(&deserialized).unwrap();
376        assert_eq!(config, &serialized);
377    }
378
379    #[test]
380    fn test_metric_bucket_encodings_de_from_str() {
381        let o: Options = serde_json::from_str(
382            r#"{
383                "relay.metric-bucket-set-encodings": "legacy",
384                "relay.metric-bucket-distribution-encodings": "zstd"
385        }"#,
386        )
387        .unwrap();
388
389        assert_eq!(
390            o.metric_bucket_set_encodings,
391            BucketEncodings {
392                spans: BucketEncoding::Legacy,
393                transactions: BucketEncoding::Legacy,
394                profiles: BucketEncoding::Legacy,
395                custom: BucketEncoding::Legacy,
396            }
397        );
398        assert_eq!(
399            o.metric_bucket_dist_encodings,
400            BucketEncodings {
401                spans: BucketEncoding::Zstd,
402                transactions: BucketEncoding::Zstd,
403                profiles: BucketEncoding::Zstd,
404                custom: BucketEncoding::Zstd,
405            }
406        );
407    }
408
409    #[test]
410    fn test_metric_bucket_encodings_de_from_obj() {
411        let original = BucketEncodings {
412            spans: BucketEncoding::Zstd,
413            transactions: BucketEncoding::Zstd,
414            profiles: BucketEncoding::Base64,
415            custom: BucketEncoding::Zstd,
416        };
417        let s = serde_json::to_string(&original).unwrap();
418        let s = format!(
419            r#"{{
420            "relay.metric-bucket-set-encodings": {s},
421            "relay.metric-bucket-distribution-encodings": {s}
422        }}"#
423        );
424
425        let o: Options = serde_json::from_str(&s).unwrap();
426        assert_eq!(o.metric_bucket_set_encodings, original);
427        assert_eq!(o.metric_bucket_dist_encodings, original);
428    }
429}