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#[derive(Default, Clone, Debug, Serialize, Deserialize)]
20#[serde(default, rename_all = "camelCase")]
21pub struct GlobalConfig {
22 #[serde(skip_serializing_if = "Option::is_none")]
24 pub measurements: Option<MeasurementsConfig>,
25 #[serde(skip_serializing_if = "Vec::is_empty")]
27 pub quotas: Vec<Quota>,
28 #[serde(skip_serializing_if = "is_err_or_empty")]
33 pub filters: ErrorBoundary<GenericFiltersConfig>,
34 #[serde(
36 deserialize_with = "default_on_error",
37 skip_serializing_if = "is_default"
38 )]
39 pub options: Options,
40
41 #[serde(skip_serializing_if = "is_ok_and_empty")]
46 pub metric_extraction: ErrorBoundary<MetricExtractionGroups>,
47
48 #[serde(skip_serializing_if = "is_model_metadata_empty")]
50 pub ai_model_metadata: ErrorBoundary<ModelMetadata>,
51
52 #[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 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 pub fn filters(&self) -> Option<&GenericFiltersConfig> {
78 match &self.filters {
79 ErrorBoundary::Err(_) => None,
80 ErrorBoundary::Ok(f) => Some(f),
81 }
82 }
83
84 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
100fn default_killswitched() -> bool {
102 relay_log::info!("using default for endpoint fetch config");
103 bool::default()
104}
105
106#[derive(Default, Clone, Debug, Serialize, Deserialize, PartialEq)]
108#[serde(default)]
109pub struct Options {
110 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[serde(flatten)]
182 other: HashMap<String, Value>,
183}
184
185#[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 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 MetricNamespace::Sessions => BucketEncoding::Legacy,
206 _ => BucketEncoding::Legacy,
207 }
208 }
209}
210
211fn 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#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq)]
262#[serde(rename_all = "lowercase")]
263pub enum BucketEncoding {
264 #[default]
268 Legacy,
269 Array,
274 Base64,
278 Zstd,
282}
283
284fn 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}