1use std::collections::btree_map::Entry;
2use std::collections::{BTreeMap, HashMap};
3use std::error::Error;
4use std::io::Write;
5use std::net::{IpAddr, SocketAddr};
6use std::num::{NonZeroU8, NonZeroU16, NonZeroU32};
7use std::path::{Path, PathBuf};
8use std::str::FromStr;
9use std::sync::{Arc, Mutex, PoisonError};
10use std::time::Duration;
11use std::{env, fmt, fs, io};
12
13use anyhow::Context;
14use arc_swap::ArcSwap;
15use relay_auth::{PublicKey, RelayId, SecretKey, generate_key_pair, generate_relay_id};
16use relay_common::Dsn;
17use relay_kafka::{
18 ConfigError as KafkaConfigError, KafkaConfigParam, KafkaTopic, KafkaTopicConfig,
19 TopicAssignments,
20};
21use relay_metrics::MetricNamespace;
22use serde::de::{DeserializeOwned, Unexpected, Visitor};
23use serde::{Deserialize, Deserializer, Serialize, Serializer};
24use uuid::Uuid;
25
26use crate::aggregator::{AggregatorServiceConfig, ScopedAggregatorConfig};
27use crate::byte_size::ByteSize;
28use crate::upstream::UpstreamDescriptor;
29use crate::{RedisConfig, RedisConfigs, RedisConfigsRef, build_redis_configs};
30
31const DEFAULT_NETWORK_OUTAGE_GRACE_PERIOD: u64 = 10;
32
33static CONFIG_YAML_HEADER: &str = r###"# Please see the relevant documentation.
34# Performance tuning: https://docs.sentry.io/product/relay/operating-guidelines/
35# All config options: https://docs.sentry.io/product/relay/options/
36"###;
37
38#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
40#[non_exhaustive]
41pub enum ConfigErrorKind {
42 CouldNotOpenFile,
44 CouldNotWriteFile,
46 BadYaml,
48 BadJson,
50 InvalidValue,
52 ProcessingNotAvailable,
55}
56
57impl fmt::Display for ConfigErrorKind {
58 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59 match self {
60 Self::CouldNotOpenFile => write!(f, "could not open config file"),
61 Self::CouldNotWriteFile => write!(f, "could not write config file"),
62 Self::BadYaml => write!(f, "could not parse yaml config file"),
63 Self::BadJson => write!(f, "could not parse json config file"),
64 Self::InvalidValue => write!(f, "invalid config value"),
65 Self::ProcessingNotAvailable => write!(
66 f,
67 "was not compiled with processing, cannot enable processing"
68 ),
69 }
70 }
71}
72
73#[derive(Debug, Default)]
75enum ConfigErrorSource {
76 #[default]
78 None,
79 File(PathBuf),
81 FieldOverride(String),
83}
84
85impl fmt::Display for ConfigErrorSource {
86 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87 match self {
88 ConfigErrorSource::None => Ok(()),
89 ConfigErrorSource::File(file_name) => {
90 write!(f, " (file {})", file_name.display())
91 }
92 ConfigErrorSource::FieldOverride(name) => write!(f, " (field {name})"),
93 }
94 }
95}
96
97#[derive(Debug)]
99pub struct ConfigError {
100 source: ConfigErrorSource,
101 kind: ConfigErrorKind,
102}
103
104impl ConfigError {
105 #[inline]
106 fn new(kind: ConfigErrorKind) -> Self {
107 Self {
108 source: ConfigErrorSource::None,
109 kind,
110 }
111 }
112
113 #[inline]
114 fn field(field: &'static str) -> Self {
115 Self {
116 source: ConfigErrorSource::FieldOverride(field.to_owned()),
117 kind: ConfigErrorKind::InvalidValue,
118 }
119 }
120
121 #[inline]
122 fn file(kind: ConfigErrorKind, p: impl AsRef<Path>) -> Self {
123 Self {
124 source: ConfigErrorSource::File(p.as_ref().to_path_buf()),
125 kind,
126 }
127 }
128
129 pub fn kind(&self) -> ConfigErrorKind {
131 self.kind
132 }
133}
134
135impl fmt::Display for ConfigError {
136 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
137 write!(f, "{}{}", self.kind(), self.source)
138 }
139}
140
141impl Error for ConfigError {}
142
143enum ConfigFormat {
144 Yaml,
145 Json,
146}
147
148impl ConfigFormat {
149 pub fn extension(&self) -> &'static str {
150 match self {
151 ConfigFormat::Yaml => "yml",
152 ConfigFormat::Json => "json",
153 }
154 }
155}
156
157trait ConfigObject: DeserializeOwned + Serialize {
158 fn format() -> ConfigFormat;
160
161 fn name() -> &'static str;
163
164 fn path(base: &Path) -> PathBuf {
166 base.join(format!("{}.{}", Self::name(), Self::format().extension()))
167 }
168
169 fn load(base: &Path) -> anyhow::Result<Self> {
171 let path = Self::path(base);
172
173 let f = fs::File::open(&path)
174 .with_context(|| ConfigError::file(ConfigErrorKind::CouldNotOpenFile, &path))?;
175 let f = io::BufReader::new(f);
176
177 let mut source = {
178 let file = serde_vars::FileSource::default()
179 .with_variable_prefix("${file:")
180 .with_variable_suffix("}")
181 .with_base_path(base);
182 let env = serde_vars::EnvSource::default()
183 .with_variable_prefix("${")
184 .with_variable_suffix("}");
185 (file, env)
186 };
187 match Self::format() {
188 ConfigFormat::Yaml => {
189 serde_vars::deserialize(serde_yaml::Deserializer::from_reader(f), &mut source)
190 .with_context(|| ConfigError::file(ConfigErrorKind::BadYaml, &path))
191 }
192 ConfigFormat::Json => {
193 serde_vars::deserialize(&mut serde_json::Deserializer::from_reader(f), &mut source)
194 .with_context(|| ConfigError::file(ConfigErrorKind::BadJson, &path))
195 }
196 }
197 }
198
199 fn save(&self, base: &Path) -> anyhow::Result<()> {
201 let path = Self::path(base);
202 let mut options = fs::OpenOptions::new();
203 options.write(true).truncate(true).create(true);
204
205 #[cfg(unix)]
207 {
208 use std::os::unix::fs::OpenOptionsExt;
209 options.mode(0o600);
210 }
211
212 let mut f = options
213 .open(&path)
214 .with_context(|| ConfigError::file(ConfigErrorKind::CouldNotWriteFile, &path))?;
215
216 match Self::format() {
217 ConfigFormat::Yaml => {
218 f.write_all(CONFIG_YAML_HEADER.as_bytes())?;
219 serde_yaml::to_writer(&mut f, self)
220 .with_context(|| ConfigError::file(ConfigErrorKind::CouldNotWriteFile, &path))?
221 }
222 ConfigFormat::Json => serde_json::to_writer_pretty(&mut f, self)
223 .with_context(|| ConfigError::file(ConfigErrorKind::CouldNotWriteFile, &path))?,
224 }
225
226 f.write_all(b"\n").ok();
227
228 Ok(())
229 }
230}
231
232#[derive(Debug, Default, Clone)]
235pub struct OverridableConfig {
236 pub mode: Option<String>,
238 pub instance: Option<String>,
240 pub log_level: Option<String>,
242 pub log_format: Option<String>,
244 pub upstream: Option<String>,
246 pub upstream_dsn: Option<String>,
248 pub host: Option<String>,
250 pub port: Option<String>,
252 pub processing: Option<String>,
254 pub kafka_url: Option<String>,
256 pub redis_url: Option<String>,
258 pub id: Option<String>,
260 pub secret_key: Option<String>,
262 pub public_key: Option<String>,
264 pub outcome_source: Option<String>,
266 pub server_name: Option<String>,
268}
269
270#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
272pub struct Credentials {
273 pub secret_key: SecretKey,
275 pub public_key: PublicKey,
277 pub id: RelayId,
279}
280
281impl Credentials {
282 pub fn generate() -> Self {
284 relay_log::info!("generating new relay credentials");
285 let (secret_key, public_key) = generate_key_pair();
286 Self {
287 secret_key,
288 public_key,
289 id: generate_relay_id(),
290 }
291 }
292
293 pub fn to_json_string(&self) -> anyhow::Result<String> {
295 serde_json::to_string(self)
296 .with_context(|| ConfigError::new(ConfigErrorKind::CouldNotWriteFile))
297 }
298}
299
300impl ConfigObject for Credentials {
301 fn format() -> ConfigFormat {
302 ConfigFormat::Json
303 }
304 fn name() -> &'static str {
305 "credentials"
306 }
307}
308
309#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
311#[serde(rename_all = "camelCase")]
312pub struct RelayInfo {
313 pub public_key: PublicKey,
315
316 #[serde(default)]
318 pub internal: bool,
319}
320
321impl RelayInfo {
322 pub fn new(public_key: PublicKey) -> Self {
324 Self {
325 public_key,
326 internal: false,
327 }
328 }
329}
330
331#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
333#[serde(rename_all = "camelCase")]
334pub enum RelayMode {
335 Proxy,
341
342 Managed,
348}
349
350impl<'de> Deserialize<'de> for RelayMode {
351 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
352 where
353 D: Deserializer<'de>,
354 {
355 let s = String::deserialize(deserializer)?;
356 match s.as_str() {
357 "proxy" => Ok(RelayMode::Proxy),
358 "managed" => Ok(RelayMode::Managed),
359 "static" => Err(serde::de::Error::custom(
360 "Relay mode 'static' has been removed. Please use 'managed' or 'proxy' instead.",
361 )),
362 other => Err(serde::de::Error::unknown_variant(
363 other,
364 &["proxy", "managed"],
365 )),
366 }
367 }
368}
369
370impl fmt::Display for RelayMode {
371 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
372 match self {
373 RelayMode::Proxy => write!(f, "proxy"),
374 RelayMode::Managed => write!(f, "managed"),
375 }
376 }
377}
378
379#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
381#[serde(rename_all = "camelCase")]
382pub enum RelayInstance {
383 Default,
385
386 Canary,
388}
389
390impl RelayInstance {
391 pub fn is_canary(&self) -> bool {
393 matches!(self, RelayInstance::Canary)
394 }
395}
396
397impl fmt::Display for RelayInstance {
398 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
399 match self {
400 RelayInstance::Default => write!(f, "default"),
401 RelayInstance::Canary => write!(f, "canary"),
402 }
403 }
404}
405
406impl FromStr for RelayInstance {
407 type Err = fmt::Error;
408
409 fn from_str(s: &str) -> Result<Self, Self::Err> {
410 match s {
411 "canary" => Ok(RelayInstance::Canary),
412 _ => Ok(RelayInstance::Default),
413 }
414 }
415}
416
417#[derive(Clone, Copy, Debug, Eq, PartialEq)]
419pub struct ParseRelayModeError;
420
421impl fmt::Display for ParseRelayModeError {
422 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
423 write!(f, "Relay mode must be one of: managed or proxy")
424 }
425}
426
427impl Error for ParseRelayModeError {}
428
429impl FromStr for RelayMode {
430 type Err = ParseRelayModeError;
431
432 fn from_str(s: &str) -> Result<Self, Self::Err> {
433 match s {
434 "proxy" => Ok(RelayMode::Proxy),
435 "managed" => Ok(RelayMode::Managed),
436 _ => Err(ParseRelayModeError),
437 }
438 }
439}
440
441fn is_default<T: Default + PartialEq>(t: &T) -> bool {
443 *t == T::default()
444}
445
446fn is_docker() -> bool {
448 if fs::metadata("/.dockerenv").is_ok() {
449 return true;
450 }
451
452 fs::read_to_string("/proc/self/cgroup").is_ok_and(|s| s.contains("/docker"))
453}
454
455fn default_host() -> IpAddr {
457 if is_docker() {
458 "0.0.0.0".parse().unwrap()
460 } else {
461 "127.0.0.1".parse().unwrap()
462 }
463}
464
465#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
469#[serde(rename_all = "lowercase")]
470#[derive(Default)]
471pub enum ReadinessCondition {
472 #[default]
481 Authenticated,
482 Always,
484}
485
486#[derive(Serialize, Deserialize, Debug, Clone)]
488#[serde(default)]
489pub struct Relay {
490 pub mode: RelayMode,
492 pub instance: RelayInstance,
494 pub upstream: UpstreamDescriptor,
496 pub advertised_upstream: Option<UpstreamDescriptor>,
505 pub host: IpAddr,
507 pub port: u16,
509 pub internal_host: Option<IpAddr>,
523 pub internal_port: Option<u16>,
527 #[serde(skip_serializing_if = "is_default")]
532 pub override_project_ids: bool,
533 pub config_reload_interval: Option<u64>,
542}
543
544impl Default for Relay {
545 fn default() -> Self {
546 Relay {
547 mode: RelayMode::Managed,
548 instance: RelayInstance::Default,
549 upstream: "https://sentry.io/".parse().unwrap(),
550 advertised_upstream: None,
551 host: default_host(),
552 port: 3000,
553 internal_host: None,
554 internal_port: None,
555 override_project_ids: false,
556 config_reload_interval: None,
557 }
558 }
559}
560
561#[derive(Serialize, Deserialize, Debug, Clone)]
563#[serde(default)]
564pub struct Metrics {
565 pub statsd: Option<String>,
569 pub statsd_buffer_size: Option<usize>,
573 pub prefix: String,
577 pub default_tags: BTreeMap<String, String>,
579 pub hostname_tag: Option<String>,
581 pub periodic_secs: u64,
586}
587
588impl Default for Metrics {
589 fn default() -> Self {
590 Metrics {
591 statsd: None,
592 statsd_buffer_size: None,
593 prefix: "sentry.relay".into(),
594 default_tags: BTreeMap::new(),
595 hostname_tag: None,
596 periodic_secs: 5,
597 }
598 }
599}
600
601#[derive(Serialize, Deserialize, Debug, Clone)]
603#[serde(default)]
604pub struct Limits {
605 pub max_concurrent_requests: usize,
608 pub max_concurrent_queries: usize,
613 pub max_event_size: ByteSize,
615 pub max_attachment_size: ByteSize,
617 pub max_attachment_count: usize,
619 pub max_attachments_size: ByteSize,
621 pub max_upload_size: ByteSize,
626 pub max_client_reports_size: ByteSize,
628 pub max_client_reports_count: usize,
630 pub max_check_in_size: ByteSize,
632 pub max_envelope_size: ByteSize,
634 pub max_sessions_size: ByteSize,
636 pub max_session_count: usize,
638 pub max_api_payload_size: ByteSize,
640 pub max_api_file_upload_size: ByteSize,
642 pub max_api_chunk_upload_size: ByteSize,
644 pub max_profile_size: ByteSize,
646 pub max_trace_metric_size: ByteSize,
648 pub max_log_size: ByteSize,
650 pub max_expanded_log_operations: usize,
652 pub max_expanded_span_operations: usize,
654 pub max_expanded_trace_metric_operations: usize,
656 pub max_expanded_span_bytes: ByteSize,
658 pub max_expanded_logs_size: ByteSize,
660 pub max_span_size: ByteSize,
662 pub max_standalone_span_count: usize,
664 pub max_container_size: ByteSize,
666 pub max_metric_buckets_size: ByteSize,
668 pub max_replay_compressed_size: ByteSize,
670 #[serde(alias = "max_replay_size")]
672 max_replay_uncompressed_size: ByteSize,
673 pub max_replay_message_size: ByteSize,
675 pub max_removed_attribute_key_size: ByteSize,
685 pub max_thread_count: usize,
690 pub max_pool_concurrency: usize,
697 pub query_timeout: u64,
700 pub keepalive_timeout: u64,
704 pub header_read_timeout: u64,
715 pub idle_timeout: Option<u64>,
722 pub max_connections: Option<usize>,
728 pub tcp_listen_backlog: u32,
736}
737
738impl Default for Limits {
739 fn default() -> Self {
740 Limits {
741 max_concurrent_requests: 100,
742 max_concurrent_queries: 5,
743 max_event_size: ByteSize::mebibytes(1),
744 max_attachment_size: ByteSize::mebibytes(200),
745 max_attachment_count: 30,
746 max_attachments_size: ByteSize::mebibytes(200),
747 max_upload_size: ByteSize::mebibytes(10240),
748 max_client_reports_size: ByteSize::kibibytes(100),
749 max_client_reports_count: 100,
750 max_check_in_size: ByteSize::kibibytes(100),
751 max_envelope_size: ByteSize::mebibytes(200),
752 max_sessions_size: ByteSize::mebibytes(10),
753 max_session_count: 100,
754 max_api_payload_size: ByteSize::mebibytes(20),
755 max_api_file_upload_size: ByteSize::mebibytes(40),
756 max_api_chunk_upload_size: ByteSize::mebibytes(100),
757 max_profile_size: ByteSize::mebibytes(50),
758 max_trace_metric_size: ByteSize::mebibytes(1),
759 max_log_size: ByteSize::mebibytes(2),
760 max_expanded_log_operations: 3_000_000,
761 max_expanded_span_operations: 3_000_000,
762 max_expanded_trace_metric_operations: 3_000_000,
763 max_expanded_span_bytes: ByteSize::mebibytes(20),
764 max_expanded_logs_size: ByteSize::mebibytes(100),
765 max_span_size: ByteSize::mebibytes(10),
766 max_standalone_span_count: 25,
767 max_container_size: ByteSize::mebibytes(12),
768 max_metric_buckets_size: ByteSize::mebibytes(1),
769 max_replay_compressed_size: ByteSize::mebibytes(10),
770 max_replay_uncompressed_size: ByteSize::mebibytes(100),
771 max_replay_message_size: ByteSize::mebibytes(15),
772 max_thread_count: num_cpus::get(),
773 max_pool_concurrency: 1,
774 query_timeout: 30,
775 keepalive_timeout: 5,
776 header_read_timeout: 5,
777 idle_timeout: None,
778 max_connections: None,
779 tcp_listen_backlog: 1024,
780 max_removed_attribute_key_size: ByteSize::kibibytes(10),
781 }
782 }
783}
784
785#[derive(Debug, Default, Deserialize, Serialize, Clone)]
787#[serde(default)]
788pub struct Routing {
789 pub accept_unknown_items: Option<bool>,
799}
800
801#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
803#[serde(rename_all = "lowercase")]
804pub enum HttpEncoding {
805 #[default]
810 Identity,
811 Deflate,
817 Gzip,
824 Br,
826 Zstd,
828}
829
830impl HttpEncoding {
831 pub fn parse(str: &str) -> Self {
836 let str = str.trim();
837 if str.eq_ignore_ascii_case("zstd") {
838 Self::Zstd
839 } else if str.eq_ignore_ascii_case("br") {
840 Self::Br
841 } else if str.eq_ignore_ascii_case("gzip") || str.eq_ignore_ascii_case("x-gzip") {
842 Self::Gzip
843 } else if str.eq_ignore_ascii_case("deflate") {
844 Self::Deflate
845 } else {
846 Self::Identity
847 }
848 }
849
850 pub fn parse_strict(value: &str) -> Option<Self> {
852 match value {
853 "identity" => Some(Self::Identity),
854 "deflate" => Some(Self::Deflate),
855 "gzip" => Some(Self::Gzip),
856 "br" => Some(Self::Br),
857 "zstd" => Some(Self::Zstd),
858 _ => None,
859 }
860 }
861
862 pub fn name(&self) -> Option<&'static str> {
866 match self {
867 Self::Identity => None,
868 Self::Deflate => Some("deflate"),
869 Self::Gzip => Some("gzip"),
870 Self::Br => Some("br"),
871 Self::Zstd => Some("zstd"),
872 }
873 }
874}
875
876#[derive(Serialize, Deserialize, Debug, Clone)]
878#[serde(default)]
879pub struct Http {
880 pub timeout: u32,
886 pub connection_timeout: u32,
891 pub max_retry_interval: u32,
893 pub host_header: Option<String>,
895 pub auth_interval: Option<u64>,
903 pub outage_grace_period: u64,
909 pub retry_delay: u64,
913 pub project_failure_interval: u64,
918 pub encoding: HttpEncoding,
934 pub global_metrics: bool,
941 pub forward: bool,
948 pub dns_cache: bool,
952}
953
954impl Default for Http {
955 fn default() -> Self {
956 Http {
957 timeout: 5,
958 connection_timeout: 3,
959 max_retry_interval: 60, host_header: None,
961 auth_interval: Some(600), outage_grace_period: DEFAULT_NETWORK_OUTAGE_GRACE_PERIOD,
963 retry_delay: 1,
964 project_failure_interval: 90,
965 encoding: HttpEncoding::Zstd,
966 global_metrics: false,
967 forward: true,
968 dns_cache: true,
969 }
970 }
971}
972
973#[derive(Clone, Copy, Debug, Eq, PartialEq, Default, Deserialize, Serialize)]
975#[serde(rename_all = "snake_case")]
976pub enum EnvelopeSpoolPartitioning {
977 ProjectKeyPair,
981 #[default]
988 RoundRobin,
989}
990
991#[derive(Debug, Serialize, Deserialize, Clone)]
993#[serde(default)]
994pub struct EnvelopeSpool {
995 pub path: Option<PathBuf>,
1001 pub max_disk_size: ByteSize,
1007 pub batch_size_bytes: ByteSize,
1014 pub flush_timeout_secs: Option<u64>,
1020 pub max_envelope_delay_secs: u64,
1027 pub disk_usage_refresh_frequency_ms: u64,
1032 pub max_backpressure_memory_percent: f32,
1062 pub partitions: NonZeroU8,
1069 pub partitioning: EnvelopeSpoolPartitioning,
1075 pub max_unspool_envelopes_per_second: Option<NonZeroU32>,
1081 pub ephemeral: bool,
1088}
1089
1090impl Default for EnvelopeSpool {
1091 fn default() -> Self {
1092 Self {
1093 path: None,
1094 max_disk_size: ByteSize::mebibytes(500),
1095 batch_size_bytes: ByteSize::kibibytes(10),
1096 max_envelope_delay_secs: 24 * 60 * 60,
1097 disk_usage_refresh_frequency_ms: 100,
1098 max_backpressure_memory_percent: 0.8,
1099 partitions: NonZeroU8::new(1).unwrap(),
1100 partitioning: EnvelopeSpoolPartitioning::default(),
1101 ephemeral: false,
1102 flush_timeout_secs: None,
1103 max_unspool_envelopes_per_second: None,
1104 }
1105 }
1106}
1107
1108#[derive(Debug, Serialize, Deserialize, Default, Clone)]
1110#[serde(default)]
1111pub struct Spool {
1112 pub envelopes: EnvelopeSpool,
1114}
1115
1116#[derive(Serialize, Deserialize, Debug, Clone)]
1118#[serde(default)]
1119pub struct Cache {
1120 pub project_request_full_config: bool,
1125 pub project_expiry: u32,
1127 pub project_grace_period: u32,
1132 pub project_refresh_interval: Option<u32>,
1138 pub relay_expiry: u32,
1140 pub miss_expiry: u32,
1142 pub batch_interval: u32,
1144 pub downstream_relays_batch_interval: u32,
1146 pub batch_size: usize,
1150 pub file_interval: u32,
1152 pub global_config_fetch_interval: u32,
1154}
1155
1156impl Default for Cache {
1157 fn default() -> Self {
1158 Cache {
1159 project_request_full_config: false,
1160 project_expiry: 300, project_grace_period: 120, project_refresh_interval: None,
1163 relay_expiry: 3600, miss_expiry: 60, batch_interval: 100, downstream_relays_batch_interval: 100, batch_size: 500,
1168 file_interval: 10, global_config_fetch_interval: 10, }
1171 }
1172}
1173
1174#[derive(Serialize, Deserialize, Debug, Clone)]
1176#[serde(default)]
1177pub struct Processing {
1178 pub enabled: bool,
1180 pub geoip_path: Option<PathBuf>,
1182 pub max_secs_in_future: u32,
1184 pub max_session_secs_in_past: u32,
1186 pub kafka_config: Vec<KafkaConfigParam>,
1188 pub secondary_kafka_configs: BTreeMap<String, Vec<KafkaConfigParam>>,
1208 pub topics: TopicAssignments,
1210 pub kafka_validate_topics: bool,
1212 pub reloading_producer_jitter_secs: u64,
1219 pub redis: Option<RedisConfigs>,
1221 pub attachment_chunk_size: ByteSize,
1223 pub projectconfig_cache_prefix: String,
1225 pub max_rate_limit: Option<u32>,
1227 pub quota_cache_ratio: Option<f32>,
1238 pub quota_cache_max: Option<f32>,
1245 #[serde(alias = "upload")]
1247 pub objectstore: ObjectstoreServiceConfig,
1248}
1249
1250impl Default for Processing {
1251 fn default() -> Self {
1253 Self {
1254 enabled: false,
1255 geoip_path: None,
1256 max_secs_in_future: 60, max_session_secs_in_past: 5 * 24 * 3600, kafka_config: Vec::new(),
1259 secondary_kafka_configs: BTreeMap::new(),
1260 topics: TopicAssignments::default(),
1261 kafka_validate_topics: false,
1262 reloading_producer_jitter_secs: 60,
1263 redis: None,
1264 attachment_chunk_size: ByteSize::mebibytes(1),
1265 projectconfig_cache_prefix: "relayconfig".to_owned(),
1266 max_rate_limit: Some(300), quota_cache_ratio: None,
1268 quota_cache_max: None,
1269 objectstore: ObjectstoreServiceConfig::default(),
1270 }
1271 }
1272}
1273
1274fn default_cluster_name(processing: &Processing) -> String {
1280 let mut name = String::from("default");
1281 while processing.secondary_kafka_configs.contains_key(&name) {
1282 name.push('_');
1283 }
1284 name
1285}
1286
1287#[derive(Debug, Default, Serialize, Deserialize, Clone)]
1289#[serde(default)]
1290pub struct Normalization {
1291 pub level: NormalizationLevel,
1293}
1294
1295#[derive(Copy, Clone, Debug, Default, Serialize, Deserialize, Eq, PartialEq)]
1297#[serde(rename_all = "lowercase")]
1298pub enum NormalizationLevel {
1299 #[default]
1303 Default,
1304 Full,
1309}
1310
1311#[derive(Serialize, Deserialize, Clone)]
1313pub struct ObjectstoreAuthConfig {
1314 pub key_id: String,
1317
1318 pub signing_key: String,
1320}
1321
1322impl fmt::Debug for ObjectstoreAuthConfig {
1323 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1324 f.debug_struct("ObjectstoreAuthConfig")
1325 .field("key_id", &self.key_id)
1326 .field("signing_key", &"[redacted]")
1327 .finish()
1328 }
1329}
1330
1331#[derive(Serialize, Deserialize, Debug, Clone)]
1333#[serde(default)]
1334pub struct ObjectstoreServiceConfig {
1335 pub objectstore_url: Option<String>,
1340
1341 pub max_concurrent_requests: usize,
1343
1344 pub max_backlog: usize,
1348
1349 pub timeout: u64,
1354
1355 pub stream_timeout: u64,
1360
1361 pub retry_delay: f64,
1363
1364 pub max_attempts: NonZeroU16,
1366
1367 pub auth: Option<ObjectstoreAuthConfig>,
1369}
1370
1371impl Default for ObjectstoreServiceConfig {
1372 fn default() -> Self {
1373 Self {
1374 objectstore_url: None,
1375 max_concurrent_requests: 10,
1376 max_backlog: 20,
1377 timeout: 60,
1378 stream_timeout: 5 * 60, retry_delay: 1.0,
1380 max_attempts: NonZeroU16::new(5).unwrap(),
1381 auth: None,
1382 }
1383 }
1384}
1385
1386#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1389
1390pub enum EmitOutcomes {
1391 None,
1393 AsClientReports,
1395 AsOutcomes,
1397}
1398
1399impl EmitOutcomes {
1400 pub fn any(&self) -> bool {
1402 !matches!(self, EmitOutcomes::None)
1403 }
1404}
1405
1406impl Serialize for EmitOutcomes {
1407 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1408 where
1409 S: Serializer,
1410 {
1411 match self {
1413 Self::None => serializer.serialize_bool(false),
1414 Self::AsClientReports => serializer.serialize_str("as_client_reports"),
1415 Self::AsOutcomes => serializer.serialize_bool(true),
1416 }
1417 }
1418}
1419
1420struct EmitOutcomesVisitor;
1421
1422impl Visitor<'_> for EmitOutcomesVisitor {
1423 type Value = EmitOutcomes;
1424
1425 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1426 formatter.write_str("true, false, 'as_client_reports'")
1427 }
1428
1429 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
1430 where
1431 E: serde::de::Error,
1432 {
1433 Ok(if v {
1434 EmitOutcomes::AsOutcomes
1435 } else {
1436 EmitOutcomes::None
1437 })
1438 }
1439
1440 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1441 where
1442 E: serde::de::Error,
1443 {
1444 match v {
1445 "as_client_reports" => Ok(EmitOutcomes::AsClientReports),
1446 _ => Err(E::invalid_value(Unexpected::Str(v), &self)),
1447 }
1448 }
1449}
1450
1451impl<'de> Deserialize<'de> for EmitOutcomes {
1452 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1453 where
1454 D: Deserializer<'de>,
1455 {
1456 deserializer.deserialize_any(EmitOutcomesVisitor)
1457 }
1458}
1459
1460#[derive(Serialize, Deserialize, Debug, Clone)]
1462#[serde(default)]
1463pub struct Outcomes {
1464 pub emit_outcomes: EmitOutcomes,
1468 pub source: Option<String>,
1471}
1472
1473impl Default for Outcomes {
1474 fn default() -> Self {
1475 Outcomes {
1476 emit_outcomes: EmitOutcomes::AsClientReports,
1477 source: None,
1478 }
1479 }
1480}
1481
1482#[derive(Serialize, Deserialize, Debug, Default)]
1484pub struct MinimalConfig {
1485 pub relay: Relay,
1487}
1488
1489impl MinimalConfig {
1490 pub fn save_in_folder<P: AsRef<Path>>(&self, p: P) -> anyhow::Result<()> {
1492 let path = p.as_ref();
1493 if fs::metadata(path).is_err() {
1494 fs::create_dir_all(path)
1495 .with_context(|| ConfigError::file(ConfigErrorKind::CouldNotOpenFile, path))?;
1496 }
1497 self.save(path)
1498 }
1499}
1500
1501impl ConfigObject for MinimalConfig {
1502 fn format() -> ConfigFormat {
1503 ConfigFormat::Yaml
1504 }
1505
1506 fn name() -> &'static str {
1507 "config"
1508 }
1509}
1510
1511mod config_relay_info {
1513 use serde::ser::SerializeMap;
1514
1515 use super::*;
1516
1517 #[derive(Debug, Serialize, Deserialize, Clone)]
1519 struct RelayInfoConfig {
1520 public_key: PublicKey,
1521 #[serde(default)]
1522 internal: bool,
1523 }
1524
1525 impl From<RelayInfoConfig> for RelayInfo {
1526 fn from(v: RelayInfoConfig) -> Self {
1527 RelayInfo {
1528 public_key: v.public_key,
1529 internal: v.internal,
1530 }
1531 }
1532 }
1533
1534 impl From<RelayInfo> for RelayInfoConfig {
1535 fn from(v: RelayInfo) -> Self {
1536 RelayInfoConfig {
1537 public_key: v.public_key,
1538 internal: v.internal,
1539 }
1540 }
1541 }
1542
1543 pub(super) fn deserialize<'de, D>(des: D) -> Result<HashMap<RelayId, RelayInfo>, D::Error>
1544 where
1545 D: Deserializer<'de>,
1546 {
1547 let map = HashMap::<RelayId, RelayInfoConfig>::deserialize(des)?;
1548 Ok(map.into_iter().map(|(k, v)| (k, v.into())).collect())
1549 }
1550
1551 pub(super) fn serialize<S>(elm: &HashMap<RelayId, RelayInfo>, ser: S) -> Result<S::Ok, S::Error>
1552 where
1553 S: Serializer,
1554 {
1555 let mut map = ser.serialize_map(Some(elm.len()))?;
1556
1557 for (k, v) in elm {
1558 map.serialize_entry(k, &RelayInfoConfig::from(v.clone()))?;
1559 }
1560
1561 map.end()
1562 }
1563}
1564
1565#[derive(Serialize, Deserialize, Debug, Clone)]
1567#[serde(default)]
1568pub struct AuthConfig {
1569 #[serde(skip_serializing_if = "is_default")]
1571 pub ready: ReadinessCondition,
1572
1573 #[serde(with = "config_relay_info")]
1575 pub static_relays: HashMap<RelayId, RelayInfo>,
1576
1577 pub signature_max_age: u64,
1581}
1582
1583impl Default for AuthConfig {
1584 fn default() -> Self {
1585 Self {
1586 ready: ReadinessCondition::default(),
1587 static_relays: HashMap::new(),
1588 signature_max_age: 300, }
1590 }
1591}
1592
1593#[derive(Serialize, Deserialize, Debug, Default, Clone)]
1595pub struct GeoIpConfig {
1596 pub path: Option<PathBuf>,
1598}
1599
1600#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
1605#[serde(default)]
1606pub struct Health {
1607 pub refresh_interval_ms: u64,
1614 pub max_memory_bytes: Option<ByteSize>,
1619 pub max_memory_percent: f32,
1623 pub probe_timeout_ms: u64,
1630 pub memory_stat_refresh_frequency_ms: u64,
1636}
1637
1638impl Default for Health {
1639 fn default() -> Self {
1640 Self {
1641 refresh_interval_ms: 3000,
1642 max_memory_bytes: None,
1643 max_memory_percent: 0.95,
1644 probe_timeout_ms: 900,
1645 memory_stat_refresh_frequency_ms: 100,
1646 }
1647 }
1648}
1649
1650#[derive(Serialize, Deserialize, Debug, Clone)]
1652#[serde(default)]
1653pub struct Cogs {
1654 pub max_queue_size: u64,
1660 pub relay_resource_id: String,
1666}
1667
1668impl Default for Cogs {
1669 fn default() -> Self {
1670 Self {
1671 max_queue_size: 10_000,
1672 relay_resource_id: "relay_service".to_owned(),
1673 }
1674 }
1675}
1676
1677#[derive(Debug, Clone, Serialize, Deserialize)]
1679#[serde(default)]
1680pub struct Upload {
1681 pub max_concurrent_requests: usize,
1685 pub timeout: u64,
1687 pub max_age: i64,
1691
1692 pub credentials: Option<UploadCredentials>,
1696}
1697
1698impl Default for Upload {
1699 fn default() -> Self {
1700 Self {
1701 max_concurrent_requests: 100,
1702 timeout: 5 * 60, max_age: 60 * 60, credentials: None,
1705 }
1706 }
1707}
1708
1709#[derive(Clone, Serialize, Deserialize)]
1711pub struct UploadCredentials {
1712 #[cfg(feature = "processing")]
1714 pub signing_key: SecretKey,
1715
1716 pub verification_key: PublicKey,
1718}
1719
1720impl fmt::Debug for UploadCredentials {
1721 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1722 let Self {
1723 #[cfg(feature = "processing")]
1724 signing_key: _,
1725 verification_key,
1726 } = self;
1727 let mut b = f.debug_struct("UploadCredentials");
1728 #[cfg(feature = "processing")]
1729 b.field("signing_key", &"[redacted]");
1730 b.field("verification_key", verification_key).finish()
1731 }
1732}
1733
1734#[derive(Serialize, Deserialize, Debug, Default, Clone)]
1736#[serde(default)]
1737#[allow(missing_docs)]
1738pub struct ConfigValues {
1739 pub relay: Relay,
1740 pub http: Http,
1741 pub cache: Cache,
1742 pub spool: Spool,
1743 pub limits: Limits,
1744 pub logging: relay_log::LogConfig,
1745 pub routing: Routing,
1746 pub metrics: Metrics,
1747 pub sentry: relay_log::SentryConfig,
1748 pub processing: Processing,
1749 pub outcomes: Outcomes,
1750 pub aggregator: AggregatorServiceConfig,
1751 pub secondary_aggregators: Vec<ScopedAggregatorConfig>,
1752 pub auth: AuthConfig,
1753 pub geoip: GeoIpConfig,
1754 pub normalization: Normalization,
1755 pub health: Health,
1756 pub cogs: Cogs,
1757 pub upload: Upload,
1758}
1759
1760impl ConfigObject for ConfigValues {
1761 fn format() -> ConfigFormat {
1762 ConfigFormat::Yaml
1763 }
1764
1765 fn name() -> &'static str {
1766 "config"
1767 }
1768}
1769
1770#[derive(Default, Clone)]
1771struct ConfigInner {
1772 values: ConfigValues,
1774 credentials: Option<Credentials>,
1778}
1779
1780impl ConfigInner {
1781 fn apply_overrides(&mut self, overrides: &OverridableConfig) -> anyhow::Result<()> {
1782 if let Some(log_level) = &overrides.log_level {
1783 self.values.logging.level = log_level.parse()?;
1784 }
1785
1786 if let Some(log_format) = &overrides.log_format {
1787 self.values.logging.format = log_format.parse()?;
1788 }
1789
1790 let relay = &mut self.values.relay;
1791 if let Some(mode) = &overrides.mode {
1792 relay.mode = mode
1793 .parse::<RelayMode>()
1794 .with_context(|| ConfigError::field("mode"))?;
1795 }
1796 if let Some(deployment) = &overrides.instance {
1797 relay.instance = deployment
1798 .parse::<RelayInstance>()
1799 .with_context(|| ConfigError::field("deployment"))?;
1800 }
1801 if let Some(upstream) = &overrides.upstream {
1802 relay.upstream = upstream
1803 .parse::<UpstreamDescriptor>()
1804 .with_context(|| ConfigError::field("upstream"))?;
1805 } else if let Some(upstream_dsn) = &overrides.upstream_dsn {
1806 relay.upstream = upstream_dsn
1807 .parse::<Dsn>()
1808 .map(|dsn| UpstreamDescriptor::from_dsn(&dsn))
1809 .with_context(|| ConfigError::field("upstream_dsn"))?;
1810 }
1811 if let Some(host) = &overrides.host {
1812 relay.host = host
1813 .parse::<IpAddr>()
1814 .with_context(|| ConfigError::field("host"))?;
1815 }
1816 if let Some(port) = &overrides.port {
1817 relay.port = port
1818 .as_str()
1819 .parse()
1820 .with_context(|| ConfigError::field("port"))?;
1821 }
1822
1823 let processing = &mut self.values.processing;
1824 if let Some(enabled) = &overrides.processing {
1825 match enabled.to_lowercase().as_str() {
1826 "true" | "1" => processing.enabled = true,
1827 "false" | "0" | "" => processing.enabled = false,
1828 _ => return Err(ConfigError::field("processing").into()),
1829 }
1830 }
1831 if let Some(redis) = overrides.redis_url.clone() {
1832 processing.redis = Some(RedisConfigs::Unified(RedisConfig::single(redis)))
1833 }
1834 if let Some(kafka_url) = overrides.kafka_url.clone() {
1835 let existing = processing
1836 .kafka_config
1837 .iter_mut()
1838 .find(|e| e.name == "bootstrap.servers");
1839
1840 if let Some(config_param) = existing {
1841 config_param.value = kafka_url;
1842 } else {
1843 self.values.processing.kafka_config.push(KafkaConfigParam {
1844 name: "bootstrap.servers".to_owned(),
1845 value: kafka_url,
1846 })
1847 }
1848 }
1849
1850 if overrides.outcome_source.is_some() {
1851 self.values.outcomes.source = overrides.outcome_source.clone();
1852 }
1853
1854 if let Some(server_name) = overrides.server_name.clone() {
1855 self.values.sentry.server_name = Some(server_name.into());
1856 }
1857
1858 let id = if let Some(id) = &overrides.id {
1859 let id = Uuid::parse_str(id).with_context(|| ConfigError::field("id"))?;
1860 Some(id)
1861 } else {
1862 None
1863 };
1864 let public_key = if let Some(public_key) = &overrides.public_key {
1865 let public_key = public_key
1866 .parse::<PublicKey>()
1867 .with_context(|| ConfigError::field("public_key"))?;
1868 Some(public_key)
1869 } else {
1870 None
1871 };
1872
1873 let secret_key = if let Some(secret_key) = &overrides.secret_key {
1874 let secret_key = secret_key
1875 .parse::<SecretKey>()
1876 .with_context(|| ConfigError::field("secret_key"))?;
1877 Some(secret_key)
1878 } else {
1879 None
1880 };
1881
1882 if let Some(credentials) = &mut self.credentials {
1883 if let Some(id) = id {
1885 credentials.id = id;
1886 }
1887 if let Some(public_key) = public_key {
1888 credentials.public_key = public_key;
1889 }
1890 if let Some(secret_key) = secret_key {
1891 credentials.secret_key = secret_key
1892 }
1893 } else {
1894 match (id, public_key, secret_key) {
1896 (Some(id), Some(public_key), Some(secret_key)) => {
1897 self.credentials = Some(Credentials {
1898 secret_key,
1899 public_key,
1900 id,
1901 })
1902 }
1903 (None, None, None) => {
1904 }
1907 _ => {
1908 return Err(ConfigError::field("incomplete credentials").into());
1909 }
1910 }
1911 }
1912
1913 Ok(())
1914 }
1915
1916 fn reload_with(&mut self, other: &Self) -> bool {
1920 let mut changed = false;
1921
1922 if self.values.health != other.values.health {
1923 relay_log::debug!("updating health");
1924 self.values.health = other.values.health.clone();
1925 changed = true;
1926 }
1927
1928 if self.values.processing.kafka_config != other.values.processing.kafka_config
1938 || self.values.processing.secondary_kafka_configs
1939 != other.values.processing.secondary_kafka_configs
1940 {
1941 relay_log::debug!("updating kafka config");
1942 self.values.processing.kafka_config = other.values.processing.kafka_config.clone();
1943 self.values.processing.secondary_kafka_configs =
1944 other.values.processing.secondary_kafka_configs.clone();
1945 changed = true;
1946 }
1947
1948 if self.values.spool.envelopes.max_unspool_envelopes_per_second
1949 != other
1950 .values
1951 .spool
1952 .envelopes
1953 .max_unspool_envelopes_per_second
1954 {
1955 relay_log::debug!("updating spool.envelopes.max_unspool_envelopes_per_second");
1956 self.values.spool.envelopes.max_unspool_envelopes_per_second = other
1957 .values
1958 .spool
1959 .envelopes
1960 .max_unspool_envelopes_per_second;
1961 changed = true;
1962 }
1963
1964 changed
1965 }
1966}
1967
1968pub struct Config {
1970 inner_access: Mutex<()>,
1979 inner: ArcSwap<ConfigInner>,
1981 overrides: Vec<OverridableConfig>,
1986 path: PathBuf,
1990}
1991
1992impl fmt::Debug for Config {
1993 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1994 let inner = self.inner.load();
1995
1996 f.debug_struct("Config")
1997 .field("path", &self.path)
1998 .field("values", &inner.values)
2000 .finish()
2001 }
2002}
2003
2004impl Config {
2005 pub fn from_path<P: AsRef<Path>>(path: P) -> anyhow::Result<Config> {
2007 let path = env::current_dir()
2008 .map(|x| x.join(path.as_ref()))
2009 .unwrap_or_else(|_| path.as_ref().to_path_buf());
2010
2011 let inner = ConfigInner {
2012 values: ConfigValues::load(&path)?,
2013 credentials: match Credentials::path(&path).exists() {
2014 true => Some(Credentials::load(&path)?),
2015 false => None,
2016 },
2017 };
2018
2019 let config = Config {
2020 inner_access: Mutex::new(()),
2021 inner: ArcSwap::from_pointee(inner),
2022 overrides: Vec::new(),
2023 path: path.clone(),
2024 };
2025
2026 if cfg!(not(feature = "processing")) && config.current().processing_enabled() {
2027 return Err(ConfigError::file(ConfigErrorKind::ProcessingNotAvailable, &path).into());
2028 }
2029
2030 Ok(config)
2031 }
2032
2033 pub fn from_json_value(value: serde_json::Value) -> anyhow::Result<Config> {
2037 Ok(Config {
2038 inner_access: Mutex::new(()),
2039 inner: ArcSwap::from_pointee(ConfigInner {
2040 values: serde_json::from_value(value)
2041 .with_context(|| ConfigError::new(ConfigErrorKind::BadJson))?,
2042 credentials: None,
2043 }),
2044 overrides: Vec::new(),
2045 path: PathBuf::new(),
2046 })
2047 }
2048
2049 pub fn apply_override(&mut self, overrides: OverridableConfig) -> anyhow::Result<&mut Self> {
2054 crate::utils::try_rcu(&self.inner, |inner| {
2057 let mut new = ConfigInner::clone(inner);
2058 new.apply_overrides(&overrides)?;
2059 Ok::<_, anyhow::Error>(Arc::new(new))
2060 })?;
2061
2062 self.overrides.push(overrides);
2064
2065 Ok(self)
2066 }
2067
2068 pub fn config_exists<P: AsRef<Path>>(path: P) -> bool {
2070 fs::metadata(ConfigValues::path(path.as_ref())).is_ok()
2071 }
2072
2073 pub fn path(&self) -> &Path {
2075 &self.path
2076 }
2077
2078 pub fn to_yaml_string(&self) -> anyhow::Result<String> {
2080 serde_yaml::to_string(&self.inner.load().values)
2081 .with_context(|| ConfigError::new(ConfigErrorKind::CouldNotWriteFile))
2082 }
2083
2084 pub fn replace_credentials(
2088 &mut self,
2089 credentials: Option<Credentials>,
2090 ) -> anyhow::Result<bool> {
2091 if self.inner.load().credentials == credentials {
2092 return Ok(false);
2093 }
2094
2095 if !self.path.is_empty() {
2096 match &credentials {
2097 Some(creds) => {
2098 creds.save(&self.path)?;
2099 }
2100 None => {
2101 let path = Credentials::path(&self.path);
2102 if fs::metadata(&path).is_ok() {
2103 fs::remove_file(&path).with_context(|| {
2104 ConfigError::file(ConfigErrorKind::CouldNotWriteFile, &path)
2105 })?;
2106 }
2107 }
2108 }
2109 }
2110
2111 self.inner.rcu(|inner| {
2116 let mut inner = ConfigInner::clone(inner);
2117 inner.credentials = credentials.clone();
2118 Arc::new(inner)
2119 });
2120
2121 Ok(true)
2122 }
2123
2124 pub fn reload(&self) -> anyhow::Result<bool> {
2134 if self.path.is_empty() {
2135 return Ok(false);
2136 }
2137
2138 let _access = self
2139 .inner_access
2140 .lock()
2141 .unwrap_or_else(PoisonError::into_inner);
2142
2143 let mut new_config = Self::from_path(&self.path)?;
2144 for overrides in &self.overrides {
2145 new_config.apply_override(overrides.clone())?;
2146 }
2147 let new_config = new_config.current();
2148
2149 let mut changed = false;
2150
2151 self.inner.rcu(|inner| {
2153 let mut new_inner = ConfigInner::clone(inner);
2154 changed = new_inner.reload_with(&new_config.inner);
2155 match changed {
2156 true => Arc::new(new_inner),
2157 false => Arc::clone(inner),
2158 }
2159 });
2160
2161 Ok(changed)
2162 }
2163
2164 pub fn current(&self) -> ConfigSnapshot {
2169 let inner = self.inner.load();
2170 ConfigSnapshot { inner }
2171 }
2172}
2173
2174impl Default for Config {
2175 fn default() -> Self {
2176 Self {
2177 inner_access: Mutex::new(()),
2178 inner: ArcSwap::from_pointee(Default::default()),
2179 overrides: Vec::new(),
2180 path: PathBuf::new(),
2181 }
2182 }
2183}
2184
2185pub struct ConfigSnapshot {
2193 inner: arc_swap::Guard<Arc<ConfigInner>>,
2194}
2195
2196impl ConfigSnapshot {
2197 pub fn has_credentials(&self) -> bool {
2199 self.inner.credentials.is_some()
2200 }
2201
2202 pub fn credentials(&self) -> Option<&Credentials> {
2204 self.inner.credentials.as_ref()
2205 }
2206
2207 pub fn secret_key(&self) -> Option<&SecretKey> {
2209 self.inner.credentials.as_ref().map(|x| &x.secret_key)
2210 }
2211
2212 pub fn public_key(&self) -> Option<&PublicKey> {
2214 self.inner.credentials.as_ref().map(|x| &x.public_key)
2215 }
2216
2217 pub fn relay_id(&self) -> Option<&RelayId> {
2219 self.inner.credentials.as_ref().map(|x| &x.id)
2220 }
2221
2222 pub fn relay_mode(&self) -> RelayMode {
2224 self.inner.values.relay.mode
2225 }
2226
2227 pub fn relay_instance(&self) -> RelayInstance {
2229 self.inner.values.relay.instance
2230 }
2231
2232 pub fn upstream(&self) -> &UpstreamDescriptor {
2234 &self.inner.values.relay.upstream
2235 }
2236
2237 pub fn advertised_upstream(&self) -> Option<&UpstreamDescriptor> {
2239 self.inner.values.relay.advertised_upstream.as_ref()
2240 }
2241
2242 pub fn http_host_header(&self) -> Option<&str> {
2244 self.inner.values.http.host_header.as_deref()
2245 }
2246
2247 pub fn listen_addr(&self) -> SocketAddr {
2249 (self.inner.values.relay.host, self.inner.values.relay.port).into()
2250 }
2251
2252 pub fn listen_addr_internal(&self) -> Option<SocketAddr> {
2260 match (
2261 self.inner.values.relay.internal_host,
2262 self.inner.values.relay.internal_port,
2263 ) {
2264 (Some(host), None) => Some((host, self.inner.values.relay.port).into()),
2265 (None, Some(port)) => Some((self.inner.values.relay.host, port).into()),
2266 (Some(host), Some(port)) => Some((host, port).into()),
2267 (None, None) => None,
2268 }
2269 }
2270
2271 pub fn override_project_ids(&self) -> bool {
2275 self.inner.values.relay.override_project_ids
2276 }
2277
2278 pub fn config_reload_interval(&self) -> Option<Duration> {
2282 let interval = self.inner.values.relay.config_reload_interval?;
2283 Some(match interval {
2284 0 => Duration::from_millis(50),
2287 secs => Duration::from_secs(secs),
2288 })
2289 }
2290
2291 pub fn requires_auth(&self) -> bool {
2295 match self.inner.values.auth.ready {
2296 ReadinessCondition::Authenticated => self.relay_mode() == RelayMode::Managed,
2297 ReadinessCondition::Always => false,
2298 }
2299 }
2300
2301 pub fn http_auth_interval(&self) -> Option<Duration> {
2305 if self.processing_enabled() {
2306 return None;
2307 }
2308
2309 match self.inner.values.http.auth_interval {
2310 None | Some(0) => None,
2311 Some(secs) => Some(Duration::from_secs(secs)),
2312 }
2313 }
2314
2315 pub fn http_outage_grace_period(&self) -> Duration {
2318 Duration::from_secs(self.inner.values.http.outage_grace_period)
2319 }
2320
2321 pub fn http_retry_delay(&self) -> Duration {
2326 Duration::from_secs(self.inner.values.http.retry_delay)
2327 }
2328
2329 pub fn http_project_failure_interval(&self) -> Duration {
2331 Duration::from_secs(self.inner.values.http.project_failure_interval)
2332 }
2333
2334 pub fn http_encoding(&self) -> HttpEncoding {
2336 self.inner.values.http.encoding
2337 }
2338
2339 pub fn http_global_metrics(&self) -> bool {
2341 self.inner.values.http.global_metrics
2342 }
2343
2344 pub fn http_forward(&self) -> bool {
2349 self.inner.values.http.forward && !self.processing_enabled()
2350 }
2351
2352 pub fn emit_outcomes(&self) -> EmitOutcomes {
2357 if self.processing_enabled() {
2358 return EmitOutcomes::AsOutcomes;
2359 }
2360 self.inner.values.outcomes.emit_outcomes
2361 }
2362
2363 pub fn outcome_source(&self) -> Option<&str> {
2365 self.inner.values.outcomes.source.as_deref()
2366 }
2367
2368 pub fn logging(&self) -> &relay_log::LogConfig {
2370 &self.inner.values.logging
2371 }
2372
2373 pub fn sentry(&self) -> &relay_log::SentryConfig {
2375 &self.inner.values.sentry
2376 }
2377
2378 pub fn statsd_addr(&self) -> Option<&str> {
2380 self.inner.values.metrics.statsd.as_deref()
2381 }
2382
2383 pub fn statsd_buffer_size(&self) -> Option<usize> {
2385 self.inner.values.metrics.statsd_buffer_size
2386 }
2387
2388 pub fn metrics_prefix(&self) -> &str {
2390 &self.inner.values.metrics.prefix
2391 }
2392
2393 pub fn metrics_default_tags(&self) -> &BTreeMap<String, String> {
2395 &self.inner.values.metrics.default_tags
2396 }
2397
2398 pub fn metrics_hostname_tag(&self) -> Option<&str> {
2400 self.inner.values.metrics.hostname_tag.as_deref()
2401 }
2402
2403 pub fn metrics_periodic_interval(&self) -> Option<Duration> {
2407 match self.inner.values.metrics.periodic_secs {
2408 0 => None,
2409 secs => Some(Duration::from_secs(secs)),
2410 }
2411 }
2412
2413 pub fn http_timeout(&self) -> Duration {
2415 Duration::from_secs(self.inner.values.http.timeout.into())
2416 }
2417
2418 pub fn http_connection_timeout(&self) -> Duration {
2420 Duration::from_secs(self.inner.values.http.connection_timeout.into())
2421 }
2422
2423 pub fn http_max_retry_interval(&self) -> Duration {
2425 Duration::from_secs(self.inner.values.http.max_retry_interval.into())
2426 }
2427
2428 pub fn http_dns_cache(&self) -> bool {
2430 self.inner.values.http.dns_cache
2431 }
2432
2433 pub fn project_cache_expiry(&self) -> Duration {
2435 Duration::from_secs(self.inner.values.cache.project_expiry.into())
2436 }
2437
2438 pub fn request_full_project_config(&self) -> bool {
2440 self.inner.values.cache.project_request_full_config
2441 }
2442
2443 pub fn relay_cache_expiry(&self) -> Duration {
2445 Duration::from_secs(self.inner.values.cache.relay_expiry.into())
2446 }
2447
2448 pub fn cache_miss_expiry(&self) -> Duration {
2450 Duration::from_secs(self.inner.values.cache.miss_expiry.into())
2451 }
2452
2453 pub fn project_grace_period(&self) -> Duration {
2455 Duration::from_secs(self.inner.values.cache.project_grace_period.into())
2456 }
2457
2458 pub fn project_refresh_interval(&self) -> Option<Duration> {
2462 self.inner
2463 .values
2464 .cache
2465 .project_refresh_interval
2466 .map(Into::into)
2467 .map(Duration::from_secs)
2468 }
2469
2470 pub fn query_batch_interval(&self) -> Duration {
2473 Duration::from_millis(self.inner.values.cache.batch_interval.into())
2474 }
2475
2476 pub fn downstream_relays_batch_interval(&self) -> Duration {
2478 Duration::from_millis(
2479 self.inner
2480 .values
2481 .cache
2482 .downstream_relays_batch_interval
2483 .into(),
2484 )
2485 }
2486
2487 pub fn local_cache_interval(&self) -> Duration {
2489 Duration::from_secs(self.inner.values.cache.file_interval.into())
2490 }
2491
2492 pub fn global_config_fetch_interval(&self) -> Duration {
2495 Duration::from_secs(self.inner.values.cache.global_config_fetch_interval.into())
2496 }
2497
2498 pub fn spool_envelopes_path(&self, partition_id: u8) -> Option<PathBuf> {
2503 let mut path = self
2504 .inner
2505 .values
2506 .spool
2507 .envelopes
2508 .path
2509 .as_ref()
2510 .map(|path| path.to_owned())?;
2511
2512 if partition_id == 0 {
2513 return Some(path);
2514 }
2515
2516 let file_name = path.file_name().and_then(|f| f.to_str())?;
2517 let new_file_name = format!("{file_name}.{partition_id}");
2518 path.set_file_name(new_file_name);
2519
2520 Some(path)
2521 }
2522
2523 pub fn spool_envelopes_max_disk_size(&self) -> usize {
2525 self.inner.values.spool.envelopes.max_disk_size.as_bytes()
2526 }
2527
2528 pub fn spool_envelopes_batch_size_bytes(&self) -> usize {
2531 self.inner
2532 .values
2533 .spool
2534 .envelopes
2535 .batch_size_bytes
2536 .as_bytes()
2537 }
2538
2539 pub fn spool_envelopes_flush_timeout(&self) -> Option<Duration> {
2541 self.inner
2542 .values
2543 .spool
2544 .envelopes
2545 .flush_timeout_secs
2546 .map(Duration::from_secs)
2547 }
2548
2549 pub fn spool_max_unspool_envelopes_per_second(&self) -> Option<NonZeroU32> {
2551 self.inner
2552 .values
2553 .spool
2554 .envelopes
2555 .max_unspool_envelopes_per_second
2556 }
2557
2558 pub fn spool_envelopes_max_age(&self) -> Duration {
2560 Duration::from_secs(self.inner.values.spool.envelopes.max_envelope_delay_secs)
2561 }
2562
2563 pub fn spool_disk_usage_refresh_frequency_ms(&self) -> Duration {
2565 Duration::from_millis(
2566 self.inner
2567 .values
2568 .spool
2569 .envelopes
2570 .disk_usage_refresh_frequency_ms,
2571 )
2572 }
2573
2574 pub fn spool_max_backpressure_memory_percent(&self) -> f32 {
2576 self.inner
2577 .values
2578 .spool
2579 .envelopes
2580 .max_backpressure_memory_percent
2581 }
2582
2583 pub fn spool_partitions(&self) -> NonZeroU8 {
2585 self.inner.values.spool.envelopes.partitions
2586 }
2587
2588 pub fn spool_partitioning(&self) -> EnvelopeSpoolPartitioning {
2590 self.inner.values.spool.envelopes.partitioning
2591 }
2592
2593 pub fn spool_ephemeral(&self) -> bool {
2595 self.inner.values.spool.envelopes.ephemeral
2596 }
2597
2598 pub fn max_event_size(&self) -> usize {
2600 self.inner.values.limits.max_event_size.as_bytes()
2601 }
2602
2603 pub fn max_attachment_size(&self) -> usize {
2605 self.inner.values.limits.max_attachment_size.as_bytes()
2606 }
2607
2608 pub fn max_attachment_count(&self) -> usize {
2610 self.inner.values.limits.max_attachment_count
2611 }
2612
2613 pub fn max_attachments_size(&self) -> usize {
2616 self.inner.values.limits.max_attachments_size.as_bytes()
2617 }
2618
2619 pub fn max_upload_size(&self) -> usize {
2621 self.inner.values.limits.max_upload_size.as_bytes()
2622 }
2623
2624 pub fn max_client_reports_count(&self) -> usize {
2626 self.inner.values.limits.max_client_reports_count
2627 }
2628
2629 pub fn max_client_reports_size(&self) -> usize {
2631 self.inner.values.limits.max_client_reports_size.as_bytes()
2632 }
2633
2634 pub fn max_check_in_size(&self) -> usize {
2636 self.inner.values.limits.max_check_in_size.as_bytes()
2637 }
2638
2639 pub fn max_log_size(&self) -> usize {
2641 self.inner.values.limits.max_log_size.as_bytes()
2642 }
2643
2644 pub fn max_expanded_log_operations(&self) -> usize {
2646 self.inner.values.limits.max_expanded_log_operations
2647 }
2648
2649 pub fn max_expanded_span_operations(&self) -> usize {
2651 self.inner.values.limits.max_expanded_span_operations
2652 }
2653
2654 pub fn max_expanded_trace_metric_operations(&self) -> usize {
2656 self.inner
2657 .values
2658 .limits
2659 .max_expanded_trace_metric_operations
2660 }
2661
2662 pub fn max_expanded_span_bytes(&self) -> ByteSize {
2664 self.inner.values.limits.max_expanded_span_bytes
2665 }
2666
2667 pub fn max_expanded_logs_size(&self) -> ByteSize {
2669 self.inner.values.limits.max_expanded_logs_size
2670 }
2671
2672 pub fn max_span_size(&self) -> usize {
2674 self.inner.values.limits.max_span_size.as_bytes()
2675 }
2676
2677 pub fn max_standalone_span_count(&self) -> usize {
2679 self.inner.values.limits.max_standalone_span_count
2680 }
2681
2682 pub fn max_container_size(&self) -> usize {
2684 self.inner.values.limits.max_container_size.as_bytes()
2685 }
2686
2687 pub fn max_envelope_size(&self) -> usize {
2691 self.inner.values.limits.max_envelope_size.as_bytes()
2692 }
2693
2694 pub fn max_session_count(&self) -> usize {
2696 self.inner.values.limits.max_session_count
2697 }
2698
2699 pub fn max_sessions_size(&self) -> usize {
2701 self.inner.values.limits.max_sessions_size.as_bytes()
2702 }
2703
2704 pub fn max_metric_buckets_size(&self) -> usize {
2706 self.inner.values.limits.max_metric_buckets_size.as_bytes()
2707 }
2708
2709 pub fn max_api_payload_size(&self) -> usize {
2711 self.inner.values.limits.max_api_payload_size.as_bytes()
2712 }
2713
2714 pub fn max_api_file_upload_size(&self) -> usize {
2716 self.inner.values.limits.max_api_file_upload_size.as_bytes()
2717 }
2718
2719 pub fn max_api_chunk_upload_size(&self) -> usize {
2721 self.inner
2722 .values
2723 .limits
2724 .max_api_chunk_upload_size
2725 .as_bytes()
2726 }
2727
2728 pub fn max_profile_size(&self) -> usize {
2730 self.inner.values.limits.max_profile_size.as_bytes()
2731 }
2732
2733 pub fn max_trace_metric_size(&self) -> usize {
2735 self.inner.values.limits.max_trace_metric_size.as_bytes()
2736 }
2737
2738 pub fn max_replay_compressed_size(&self) -> usize {
2740 self.inner
2741 .values
2742 .limits
2743 .max_replay_compressed_size
2744 .as_bytes()
2745 }
2746
2747 pub fn max_replay_uncompressed_size(&self) -> usize {
2749 self.inner
2750 .values
2751 .limits
2752 .max_replay_uncompressed_size
2753 .as_bytes()
2754 }
2755
2756 pub fn max_replay_message_size(&self) -> usize {
2762 self.inner.values.limits.max_replay_message_size.as_bytes()
2763 }
2764
2765 pub fn max_concurrent_requests(&self) -> usize {
2767 self.inner.values.limits.max_concurrent_requests
2768 }
2769
2770 pub fn max_concurrent_queries(&self) -> usize {
2772 self.inner.values.limits.max_concurrent_queries
2773 }
2774
2775 pub fn max_removed_attribute_key_size(&self) -> usize {
2777 self.inner
2778 .values
2779 .limits
2780 .max_removed_attribute_key_size
2781 .as_bytes()
2782 }
2783
2784 pub fn query_timeout(&self) -> Duration {
2786 Duration::from_secs(self.inner.values.limits.query_timeout)
2787 }
2788
2789 pub fn keepalive_timeout(&self) -> Duration {
2793 Duration::from_secs(self.inner.values.limits.keepalive_timeout)
2794 }
2795
2796 pub fn header_read_timeout(&self) -> Duration {
2800 Duration::from_secs(self.inner.values.limits.header_read_timeout)
2801 }
2802
2803 pub fn idle_timeout(&self) -> Option<Duration> {
2805 self.inner
2806 .values
2807 .limits
2808 .idle_timeout
2809 .map(Duration::from_secs)
2810 }
2811
2812 pub fn max_connections(&self) -> Option<usize> {
2814 self.inner.values.limits.max_connections
2815 }
2816
2817 pub fn tcp_listen_backlog(&self) -> u32 {
2819 self.inner.values.limits.tcp_listen_backlog
2820 }
2821
2822 pub fn cpu_concurrency(&self) -> usize {
2824 self.inner.values.limits.max_thread_count
2825 }
2826
2827 pub fn pool_concurrency(&self) -> usize {
2829 self.inner.values.limits.max_pool_concurrency
2830 }
2831
2832 pub fn query_batch_size(&self) -> usize {
2834 self.inner.values.cache.batch_size
2835 }
2836
2837 pub fn processing_enabled(&self) -> bool {
2839 self.inner.values.processing.enabled
2840 }
2841
2842 pub fn normalization_level(&self) -> NormalizationLevel {
2844 self.inner.values.normalization.level
2845 }
2846
2847 pub fn geoip_path(&self) -> Option<&Path> {
2849 self.inner.values.geoip.path.as_deref().or(self
2850 .inner
2851 .values
2852 .processing
2853 .geoip_path
2854 .as_deref())
2855 }
2856
2857 pub fn max_secs_in_future(&self) -> i64 {
2861 self.inner.values.processing.max_secs_in_future.into()
2862 }
2863
2864 pub fn max_session_secs_in_past(&self) -> i64 {
2866 self.inner.values.processing.max_session_secs_in_past.into()
2867 }
2868
2869 pub fn kafka_configs(
2871 &self,
2872 topic: KafkaTopic,
2873 ) -> Result<KafkaTopicConfig<'_>, KafkaConfigError> {
2874 self.inner
2875 .values
2876 .processing
2877 .topics
2878 .get(topic)
2879 .kafka_configs(
2880 &self.inner.values.processing.kafka_config,
2881 &self.inner.values.processing.secondary_kafka_configs,
2882 )
2883 }
2884
2885 pub fn kafka_validate_topics(&self) -> bool {
2887 self.inner.values.processing.kafka_validate_topics
2888 }
2889
2890 pub fn reloading_producer_jitter(&self) -> Duration {
2892 Duration::from_secs(self.inner.values.processing.reloading_producer_jitter_secs)
2893 }
2894
2895 pub fn kafka_config_blob(&self) -> Result<Vec<u8>, KafkaConfigError> {
2904 let mut clusters = BTreeMap::new();
2907 let mut topics = BTreeMap::new();
2908
2909 let default_cluster = default_cluster_name(&self.inner.values.processing);
2913
2914 for topic in KafkaTopic::iter() {
2915 let topic_config = self.kafka_configs(*topic)?;
2916
2917 for params in topic_config.topics() {
2918 let cluster_name = params.config_name.unwrap_or(&default_cluster);
2919
2920 let config: BTreeMap<_, _> = params
2921 .params
2922 .iter()
2923 .map(|param| (param.name.as_str(), param.value.as_str()))
2924 .collect();
2925
2926 clusters.insert(
2927 cluster_name.to_owned(),
2928 serde_json::json!({ "config": config }),
2929 );
2930
2931 let entry = serde_json::json!({ "physical_topics": [{ "cluster": cluster_name }] });
2937 match topics.entry(params.topic_name.clone()) {
2938 Entry::Vacant(vacant) => {
2939 vacant.insert(entry);
2940 }
2941 Entry::Occupied(occupied) if *occupied.get() != entry => {
2942 return Err(KafkaConfigError::AmbiguousTopic(params.topic_name.clone()));
2943 }
2944 Entry::Occupied(_) => {}
2945 }
2946 }
2947 }
2948
2949 Ok(serde_json::to_vec(&serde_json::json!({
2951 "clusters": clusters,
2952 "topics": topics,
2953 }))
2954 .expect("kafka config blob is serializable"))
2955 }
2956
2957 pub fn unused_topic_assignments(&self) -> &relay_kafka::Unused {
2959 &self.inner.values.processing.topics.unused
2960 }
2961
2962 pub fn objectstore(&self) -> &ObjectstoreServiceConfig {
2964 &self.inner.values.processing.objectstore
2965 }
2966
2967 pub fn upload(&self) -> &Upload {
2969 &self.inner.values.upload
2970 }
2971
2972 #[cfg(feature = "processing")]
2974 pub fn upload_signing_key(&self) -> Option<&SecretKey> {
2975 self.upload()
2976 .credentials
2977 .as_ref()
2978 .map(|c| &c.signing_key)
2979 .or(self.credentials().map(|c| &c.secret_key))
2980 }
2981
2982 #[cfg(feature = "processing")]
2984 pub fn upload_verification_key(&self) -> Option<&PublicKey> {
2985 self.upload()
2986 .credentials
2987 .as_ref()
2988 .map(|c| &c.verification_key)
2989 .or(self.credentials().map(|c| &c.public_key))
2990 }
2991
2992 pub fn redis(&self) -> Option<RedisConfigsRef<'_>> {
2994 let redis_configs = self.inner.values.processing.redis.as_ref()?;
2995
2996 Some(build_redis_configs(
2997 redis_configs,
2998 self.cpu_concurrency() as u32,
2999 self.pool_concurrency() as u32,
3000 ))
3001 }
3002
3003 pub fn attachment_chunk_size(&self) -> usize {
3005 self.inner
3006 .values
3007 .processing
3008 .attachment_chunk_size
3009 .as_bytes()
3010 }
3011
3012 pub fn metrics_max_batch_size_bytes(&self) -> usize {
3014 self.inner.values.aggregator.max_flush_bytes
3015 }
3016
3017 pub fn projectconfig_cache_prefix(&self) -> &str {
3020 &self.inner.values.processing.projectconfig_cache_prefix
3021 }
3022
3023 pub fn max_rate_limit(&self) -> Option<u64> {
3025 self.inner.values.processing.max_rate_limit.map(u32::into)
3026 }
3027
3028 pub fn quota_cache_ratio(&self) -> Option<f32> {
3030 self.inner.values.processing.quota_cache_ratio
3031 }
3032
3033 pub fn quota_cache_max(&self) -> Option<f32> {
3035 self.inner.values.processing.quota_cache_max
3036 }
3037
3038 pub fn health_refresh_interval(&self) -> Duration {
3040 Duration::from_millis(self.inner.values.health.refresh_interval_ms)
3041 }
3042
3043 pub fn health_max_memory_watermark_bytes(&self) -> u64 {
3045 self.inner
3046 .values
3047 .health
3048 .max_memory_bytes
3049 .as_ref()
3050 .map_or(u64::MAX, |b| b.as_bytes() as u64)
3051 }
3052
3053 pub fn health_max_memory_watermark_percent(&self) -> f32 {
3055 self.inner.values.health.max_memory_percent
3056 }
3057
3058 pub fn health_probe_timeout(&self) -> Duration {
3060 Duration::from_millis(self.inner.values.health.probe_timeout_ms)
3061 }
3062
3063 pub fn memory_stat_refresh_frequency_ms(&self) -> u64 {
3065 self.inner.values.health.memory_stat_refresh_frequency_ms
3066 }
3067
3068 pub fn cogs_max_queue_size(&self) -> u64 {
3070 self.inner.values.cogs.max_queue_size
3071 }
3072
3073 pub fn cogs_relay_resource_id(&self) -> &str {
3075 &self.inner.values.cogs.relay_resource_id
3076 }
3077
3078 pub fn default_aggregator_config(&self) -> &AggregatorServiceConfig {
3080 &self.inner.values.aggregator
3081 }
3082
3083 pub fn secondary_aggregator_configs(&self) -> &Vec<ScopedAggregatorConfig> {
3085 &self.inner.values.secondary_aggregators
3086 }
3087
3088 pub fn aggregator_config_for(&self, namespace: MetricNamespace) -> &AggregatorServiceConfig {
3090 for entry in &self.inner.values.secondary_aggregators {
3091 if entry.condition.matches(Some(namespace)) {
3092 return &entry.config;
3093 }
3094 }
3095 &self.inner.values.aggregator
3096 }
3097
3098 pub fn static_relays(&self) -> &HashMap<RelayId, RelayInfo> {
3100 &self.inner.values.auth.static_relays
3101 }
3102
3103 pub fn signature_max_age(&self) -> Duration {
3105 Duration::from_secs(self.inner.values.auth.signature_max_age)
3106 }
3107
3108 pub fn accept_unknown_items(&self) -> bool {
3110 let forward = self.inner.values.routing.accept_unknown_items;
3111 forward.unwrap_or_else(|| !self.processing_enabled())
3112 }
3113}
3114
3115impl fmt::Debug for ConfigSnapshot {
3116 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3117 f.debug_struct("ConfigSnapshot")
3118 .field("values", &self.inner.values)
3119 .finish()
3120 }
3121}
3122
3123#[cfg(test)]
3124mod tests {
3125 use super::*;
3126
3127 #[test]
3128 fn test_http_encoding_parse_strict() {
3129 for (value, expected) in [
3130 ("identity", Some(HttpEncoding::Identity)),
3131 ("gzip", Some(HttpEncoding::Gzip)),
3132 ("deflate", Some(HttpEncoding::Deflate)),
3133 ("br", Some(HttpEncoding::Br)),
3134 ("zstd", Some(HttpEncoding::Zstd)),
3135 ("", None),
3136 ("unknown", None),
3137 ("x-gzip", None),
3138 ("GZIP", None),
3139 (" gzip ", None),
3140 ("zstd, gzip", None),
3141 ] {
3142 assert_eq!(HttpEncoding::parse_strict(value), expected, "{value:?}");
3143 }
3144 }
3145
3146 #[cfg(feature = "processing")]
3147 #[test]
3148 fn test_upload_secret_key_from_file() {
3149 let path = env::temp_dir().join(Uuid::new_v4().to_string());
3150 fs::create_dir(&path).unwrap();
3151 fs::write(
3152 path.join("my_secret.txt"),
3153 "U3LSQM5NorvgnoYHW_aZpc_43nuuh3lhs3zjjcBwaks",
3154 )
3155 .unwrap();
3156 fs::write(
3157 ConfigValues::path(&path),
3158 r#"
3159 upload:
3160 credentials:
3161 signing_key: ${file:my_secret.txt}
3162 verification_key: "VNS8haF0VTnuMMDR2t-f7AgnmUcXmcdzV3SVksSk34s""#,
3163 )
3164 .unwrap();
3165
3166 let config = Config::from_path(&path).unwrap().current();
3167
3168 fs::remove_dir_all(path).unwrap();
3169
3170 let signing_key = &config.upload().credentials.as_ref().unwrap().signing_key;
3171 assert_eq!(
3172 signing_key.to_string(),
3173 "U3LSQM5NorvgnoYHW_aZpc_43nuuh3lhs3zjjcBwaks"
3174 );
3175 }
3176
3177 #[test]
3178 fn test_emit_outcomes() {
3179 for (serialized, deserialized) in &[
3180 ("true", EmitOutcomes::AsOutcomes),
3181 ("false", EmitOutcomes::None),
3182 ("\"as_client_reports\"", EmitOutcomes::AsClientReports),
3183 ] {
3184 let value: EmitOutcomes = serde_json::from_str(serialized).unwrap();
3185 assert_eq!(value, *deserialized);
3186 assert_eq!(serde_json::to_string(&value).unwrap(), *serialized);
3187 }
3188 }
3189
3190 #[test]
3191 fn test_emit_outcomes_invalid() {
3192 assert!(serde_json::from_str::<EmitOutcomes>("asdf").is_err());
3193 }
3194
3195 #[cfg(feature = "processing")]
3197 fn processing_config(yaml: &str) -> Config {
3198 let path = env::temp_dir().join(Uuid::new_v4().to_string());
3199 fs::create_dir(&path).unwrap();
3200 fs::write(ConfigValues::path(&path), yaml).unwrap();
3201 Config::from_path(&path).unwrap()
3202 }
3203
3204 #[cfg(feature = "processing")]
3206 #[test]
3207 fn test_kafka_config_blob_round_trips() {
3208 use sentry_arroyo::backends::kafka::config_blob::{ConfigBlob, ProducerSelector};
3209
3210 let config = processing_config(
3212 r#"
3213processing:
3214 enabled: true
3215 kafka_config:
3216 - {name: "bootstrap.servers", value: "primary:9092"}
3217 - {name: "compression.type", value: "lz4"}
3218 secondary_kafka_configs:
3219 default:
3220 - {name: "bootstrap.servers", value: "impostor:9092"}
3221 topics:
3222 ingest-events: ["events-1", "events-2"]
3223 ingest-metrics:
3224 name: "metrics-topic"
3225 config: "default"
3226"#,
3227 );
3228 let config = config.current();
3229
3230 let blob = config.kafka_config_blob().unwrap();
3231 let parsed = ConfigBlob::parse(&blob).unwrap();
3232
3233 let resolve = |topic: &str| {
3234 let resolved = parsed
3235 .producer_config(&ProducerSelector::new(topic, "relay"))
3236 .unwrap_or_else(|_| panic!("{topic} is missing from the blob"));
3237
3238 assert_eq!(resolved.physical_topic.as_str(), topic);
3240
3241 resolved
3242 .config
3243 .config_map()
3244 .iter()
3245 .filter(|(key, _)| !matches!(key.as_str(), "statistics.interval.ms" | "client.id"))
3247 .map(|(key, value)| (key.clone(), value.clone()))
3248 .collect::<BTreeMap<_, _>>()
3249 };
3250
3251 for (topic, physical) in [
3252 (KafkaTopic::Events, ["events-1", "events-2"].as_slice()),
3253 (KafkaTopic::MetricsSessions, ["metrics-topic"].as_slice()),
3254 ] {
3255 let params = config.kafka_configs(topic).unwrap();
3256
3257 for (shard, physical) in params.topics().iter().zip(physical) {
3258 let expected: BTreeMap<_, _> = shard
3259 .params
3260 .iter()
3261 .map(|param| (param.name.clone(), param.value.clone()))
3262 .collect();
3263
3264 assert_eq!(
3265 resolve(physical),
3266 expected,
3267 "{physical} resolved differently"
3268 );
3269 }
3270 }
3271
3272 assert_eq!(
3274 resolve("events-1").get("bootstrap.servers").unwrap(),
3275 "primary:9092"
3276 );
3277 assert_eq!(
3278 resolve("metrics-topic").get("bootstrap.servers").unwrap(),
3279 "impostor:9092"
3280 );
3281 }
3282
3283 #[cfg(feature = "processing")]
3285 #[test]
3286 fn test_topic_can_move_between_clusters() {
3287 use sentry_arroyo::backends::kafka::config_blob::{ConfigBlob, ProducerSelector};
3288
3289 let resolve = |yaml: &str| {
3290 let config = processing_config(yaml);
3291 let blob = config.current().kafka_config_blob().unwrap();
3292 ConfigBlob::parse(&blob)
3293 .unwrap()
3294 .producer_config(&ProducerSelector::new("events-topic", "relay"))
3295 .unwrap()
3296 .config
3297 .get_config_value("bootstrap.servers")
3298 .unwrap()
3299 .clone()
3300 };
3301
3302 let before = resolve(
3303 r#"
3304processing:
3305 enabled: true
3306 kafka_config:
3307 - {name: "bootstrap.servers", value: "primary:9092"}
3308 secondary_kafka_configs:
3309 other:
3310 - {name: "bootstrap.servers", value: "other:9092"}
3311 topics:
3312 ingest-events: "events-topic"
3313"#,
3314 );
3315
3316 let after = resolve(
3318 r#"
3319processing:
3320 enabled: true
3321 kafka_config:
3322 - {name: "bootstrap.servers", value: "primary:9092"}
3323 secondary_kafka_configs:
3324 other:
3325 - {name: "bootstrap.servers", value: "other:9092"}
3326 topics:
3327 ingest-events:
3328 name: "events-topic"
3329 config: "other"
3330"#,
3331 );
3332
3333 assert_eq!(before, "primary:9092");
3334 assert_eq!(after, "other:9092");
3335 }
3336
3337 #[cfg(feature = "processing")]
3340 #[test]
3341 fn test_kafka_config_blob_rejects_topic_on_two_clusters() {
3342 let config = processing_config(
3343 r#"
3344processing:
3345 enabled: true
3346 kafka_config:
3347 - {name: "bootstrap.servers", value: "primary:9092"}
3348 secondary_kafka_configs:
3349 other:
3350 - {name: "bootstrap.servers", value: "other:9092"}
3351 topics:
3352 outcomes:
3353 name: "outcomes-topic"
3354 config: "other"
3355 outcomes-billing: "outcomes-topic"
3356"#,
3357 );
3358
3359 assert!(matches!(
3360 config.current().kafka_config_blob(),
3361 Err(KafkaConfigError::AmbiguousTopic(topic)) if topic == "outcomes-topic"
3362 ));
3363 }
3364
3365 #[test]
3368 fn test_reload_takes_kafka_config_but_not_topics() {
3369 let mut current = ConfigValues::default();
3370 current.processing.kafka_config = vec![KafkaConfigParam {
3371 name: "bootstrap.servers".to_owned(),
3372 value: "old:9092".to_owned(),
3373 }];
3374 current.processing.topics.events = "old-topic".to_owned().into();
3375
3376 let mut other = ConfigValues::default();
3377 other.processing.kafka_config = vec![KafkaConfigParam {
3378 name: "bootstrap.servers".to_owned(),
3379 value: "new:9092".to_owned(),
3380 }];
3381 other.processing.topics.events = "new-topic".to_owned().into();
3382
3383 let mut current = ConfigInner {
3384 values: current,
3385 ..Default::default()
3386 };
3387 let other = ConfigInner {
3388 values: other,
3389 ..Default::default()
3390 };
3391
3392 assert!(current.reload_with(&other));
3393 assert_eq!(current.values.processing.kafka_config[0].value, "new:9092");
3394
3395 let assignment = format!("{:?}", current.values.processing.topics.events);
3396 assert!(
3397 assignment.contains("old-topic"),
3398 "topic assignment was reloaded, but the producers cannot pick it up: {assignment}"
3399 );
3400 }
3401}