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