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