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