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 shutdown_timeout: Option<String>,
268 pub server_name: Option<String>,
270}
271
272#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
274pub struct Credentials {
275 pub secret_key: SecretKey,
277 pub public_key: PublicKey,
279 pub id: RelayId,
281}
282
283impl Credentials {
284 pub fn generate() -> Self {
286 relay_log::info!("generating new relay credentials");
287 let (secret_key, public_key) = generate_key_pair();
288 Self {
289 secret_key,
290 public_key,
291 id: generate_relay_id(),
292 }
293 }
294
295 pub fn to_json_string(&self) -> anyhow::Result<String> {
297 serde_json::to_string(self)
298 .with_context(|| ConfigError::new(ConfigErrorKind::CouldNotWriteFile))
299 }
300}
301
302impl ConfigObject for Credentials {
303 fn format() -> ConfigFormat {
304 ConfigFormat::Json
305 }
306 fn name() -> &'static str {
307 "credentials"
308 }
309}
310
311#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
313#[serde(rename_all = "camelCase")]
314pub struct RelayInfo {
315 pub public_key: PublicKey,
317
318 #[serde(default)]
320 pub internal: bool,
321}
322
323impl RelayInfo {
324 pub fn new(public_key: PublicKey) -> Self {
326 Self {
327 public_key,
328 internal: false,
329 }
330 }
331}
332
333#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
335#[serde(rename_all = "camelCase")]
336pub enum RelayMode {
337 Proxy,
343
344 Managed,
350}
351
352impl<'de> Deserialize<'de> for RelayMode {
353 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
354 where
355 D: Deserializer<'de>,
356 {
357 let s = String::deserialize(deserializer)?;
358 match s.as_str() {
359 "proxy" => Ok(RelayMode::Proxy),
360 "managed" => Ok(RelayMode::Managed),
361 "static" => Err(serde::de::Error::custom(
362 "Relay mode 'static' has been removed. Please use 'managed' or 'proxy' instead.",
363 )),
364 other => Err(serde::de::Error::unknown_variant(
365 other,
366 &["proxy", "managed"],
367 )),
368 }
369 }
370}
371
372impl fmt::Display for RelayMode {
373 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
374 match self {
375 RelayMode::Proxy => write!(f, "proxy"),
376 RelayMode::Managed => write!(f, "managed"),
377 }
378 }
379}
380
381#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
383#[serde(rename_all = "camelCase")]
384pub enum RelayInstance {
385 Default,
387
388 Canary,
390}
391
392impl RelayInstance {
393 pub fn is_canary(&self) -> bool {
395 matches!(self, RelayInstance::Canary)
396 }
397}
398
399impl fmt::Display for RelayInstance {
400 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
401 match self {
402 RelayInstance::Default => write!(f, "default"),
403 RelayInstance::Canary => write!(f, "canary"),
404 }
405 }
406}
407
408impl FromStr for RelayInstance {
409 type Err = fmt::Error;
410
411 fn from_str(s: &str) -> Result<Self, Self::Err> {
412 match s {
413 "canary" => Ok(RelayInstance::Canary),
414 _ => Ok(RelayInstance::Default),
415 }
416 }
417}
418
419#[derive(Clone, Copy, Debug, Eq, PartialEq)]
421pub struct ParseRelayModeError;
422
423impl fmt::Display for ParseRelayModeError {
424 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
425 write!(f, "Relay mode must be one of: managed or proxy")
426 }
427}
428
429impl Error for ParseRelayModeError {}
430
431impl FromStr for RelayMode {
432 type Err = ParseRelayModeError;
433
434 fn from_str(s: &str) -> Result<Self, Self::Err> {
435 match s {
436 "proxy" => Ok(RelayMode::Proxy),
437 "managed" => Ok(RelayMode::Managed),
438 _ => Err(ParseRelayModeError),
439 }
440 }
441}
442
443fn is_default<T: Default + PartialEq>(t: &T) -> bool {
445 *t == T::default()
446}
447
448fn is_docker() -> bool {
450 if fs::metadata("/.dockerenv").is_ok() {
451 return true;
452 }
453
454 fs::read_to_string("/proc/self/cgroup").is_ok_and(|s| s.contains("/docker"))
455}
456
457fn default_host() -> IpAddr {
459 if is_docker() {
460 "0.0.0.0".parse().unwrap()
462 } else {
463 "127.0.0.1".parse().unwrap()
464 }
465}
466
467#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
471#[serde(rename_all = "lowercase")]
472#[derive(Default)]
473pub enum ReadinessCondition {
474 #[default]
483 Authenticated,
484 Always,
486}
487
488#[derive(Serialize, Deserialize, Debug, Clone)]
490#[serde(default)]
491pub struct Relay {
492 pub mode: RelayMode,
494 pub instance: RelayInstance,
496 pub upstream: UpstreamDescriptor,
498 pub advertised_upstream: Option<UpstreamDescriptor>,
507 pub host: IpAddr,
509 pub port: u16,
511 pub internal_host: Option<IpAddr>,
525 pub internal_port: Option<u16>,
529 #[serde(skip_serializing_if = "is_default")]
534 pub override_project_ids: bool,
535 pub config_reload_interval: Option<u64>,
544}
545
546impl Default for Relay {
547 fn default() -> Self {
548 Relay {
549 mode: RelayMode::Managed,
550 instance: RelayInstance::Default,
551 upstream: "https://sentry.io/".parse().unwrap(),
552 advertised_upstream: None,
553 host: default_host(),
554 port: 3000,
555 internal_host: None,
556 internal_port: None,
557 override_project_ids: false,
558 config_reload_interval: None,
559 }
560 }
561}
562
563#[derive(Serialize, Deserialize, Debug, Clone)]
565#[serde(default)]
566pub struct Metrics {
567 pub statsd: Option<String>,
571 pub statsd_buffer_size: Option<usize>,
575 pub prefix: String,
579 pub default_tags: BTreeMap<String, String>,
581 pub hostname_tag: Option<String>,
583 pub periodic_secs: u64,
588}
589
590impl Default for Metrics {
591 fn default() -> Self {
592 Metrics {
593 statsd: None,
594 statsd_buffer_size: None,
595 prefix: "sentry.relay".into(),
596 default_tags: BTreeMap::new(),
597 hostname_tag: None,
598 periodic_secs: 5,
599 }
600 }
601}
602
603#[derive(Serialize, Deserialize, Debug, Clone)]
605#[serde(default)]
606pub struct Limits {
607 pub max_concurrent_requests: usize,
610 pub max_concurrent_queries: usize,
615 pub max_event_size: ByteSize,
617 pub max_attachment_size: ByteSize,
619 pub max_attachment_count: usize,
621 pub max_attachments_size: ByteSize,
623 pub max_upload_size: ByteSize,
628 pub max_client_reports_size: ByteSize,
630 pub max_client_reports_count: usize,
632 pub max_check_in_size: ByteSize,
634 pub max_envelope_size: ByteSize,
636 pub max_sessions_size: ByteSize,
638 pub max_session_count: usize,
640 pub max_api_payload_size: ByteSize,
642 pub max_api_file_upload_size: ByteSize,
644 pub max_api_chunk_upload_size: ByteSize,
646 pub max_profile_size: ByteSize,
648 pub max_trace_metric_size: ByteSize,
650 pub max_log_size: ByteSize,
652 pub max_expanded_log_operations: usize,
654 pub max_expanded_span_operations: usize,
656 pub max_expanded_trace_metric_operations: usize,
658 pub max_expanded_span_bytes: ByteSize,
660 pub max_expanded_logs_size: ByteSize,
662 pub max_span_size: ByteSize,
664 pub max_standalone_span_count: usize,
666 pub max_container_size: ByteSize,
668 pub max_metric_buckets_size: ByteSize,
670 pub max_replay_compressed_size: ByteSize,
672 #[serde(alias = "max_replay_size")]
674 max_replay_uncompressed_size: ByteSize,
675 pub max_replay_message_size: ByteSize,
677 pub max_removed_attribute_key_size: ByteSize,
687 pub max_thread_count: usize,
692 pub max_pool_concurrency: usize,
699 pub query_timeout: u64,
702 pub shutdown_timeout: u64,
705 pub keepalive_timeout: u64,
709 pub idle_timeout: Option<u64>,
716 pub max_connections: Option<usize>,
722 pub tcp_listen_backlog: u32,
730}
731
732impl Default for Limits {
733 fn default() -> Self {
734 Limits {
735 max_concurrent_requests: 100,
736 max_concurrent_queries: 5,
737 max_event_size: ByteSize::mebibytes(1),
738 max_attachment_size: ByteSize::mebibytes(200),
739 max_attachment_count: 30,
740 max_attachments_size: ByteSize::mebibytes(200),
741 max_upload_size: ByteSize::mebibytes(10240),
742 max_client_reports_size: ByteSize::kibibytes(100),
743 max_client_reports_count: 100,
744 max_check_in_size: ByteSize::kibibytes(100),
745 max_envelope_size: ByteSize::mebibytes(200),
746 max_sessions_size: ByteSize::mebibytes(10),
747 max_session_count: 100,
748 max_api_payload_size: ByteSize::mebibytes(20),
749 max_api_file_upload_size: ByteSize::mebibytes(40),
750 max_api_chunk_upload_size: ByteSize::mebibytes(100),
751 max_profile_size: ByteSize::mebibytes(50),
752 max_trace_metric_size: ByteSize::mebibytes(1),
753 max_log_size: ByteSize::mebibytes(2),
754 max_expanded_log_operations: 3_000_000,
755 max_expanded_span_operations: 3_000_000,
756 max_expanded_trace_metric_operations: 3_000_000,
757 max_expanded_span_bytes: ByteSize::mebibytes(20),
758 max_expanded_logs_size: ByteSize::mebibytes(100),
759 max_span_size: ByteSize::mebibytes(10),
760 max_standalone_span_count: 25,
761 max_container_size: ByteSize::mebibytes(12),
762 max_metric_buckets_size: ByteSize::mebibytes(1),
763 max_replay_compressed_size: ByteSize::mebibytes(10),
764 max_replay_uncompressed_size: ByteSize::mebibytes(100),
765 max_replay_message_size: ByteSize::mebibytes(15),
766 max_thread_count: num_cpus::get(),
767 max_pool_concurrency: 1,
768 query_timeout: 30,
769 shutdown_timeout: 10,
770 keepalive_timeout: 5,
771 idle_timeout: None,
772 max_connections: None,
773 tcp_listen_backlog: 1024,
774 max_removed_attribute_key_size: ByteSize::kibibytes(10),
775 }
776 }
777}
778
779#[derive(Debug, Default, Deserialize, Serialize, Clone)]
781#[serde(default)]
782pub struct Routing {
783 pub accept_unknown_items: Option<bool>,
793}
794
795#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
797#[serde(rename_all = "lowercase")]
798pub enum HttpEncoding {
799 #[default]
804 Identity,
805 Deflate,
811 Gzip,
818 Br,
820 Zstd,
822}
823
824impl HttpEncoding {
825 pub fn parse(str: &str) -> Self {
830 let str = str.trim();
831 if str.eq_ignore_ascii_case("zstd") {
832 Self::Zstd
833 } else if str.eq_ignore_ascii_case("br") {
834 Self::Br
835 } else if str.eq_ignore_ascii_case("gzip") || str.eq_ignore_ascii_case("x-gzip") {
836 Self::Gzip
837 } else if str.eq_ignore_ascii_case("deflate") {
838 Self::Deflate
839 } else {
840 Self::Identity
841 }
842 }
843
844 pub fn parse_strict(value: &str) -> Option<Self> {
846 match value {
847 "identity" => Some(Self::Identity),
848 "deflate" => Some(Self::Deflate),
849 "gzip" => Some(Self::Gzip),
850 "br" => Some(Self::Br),
851 "zstd" => Some(Self::Zstd),
852 _ => None,
853 }
854 }
855
856 pub fn name(&self) -> Option<&'static str> {
860 match self {
861 Self::Identity => None,
862 Self::Deflate => Some("deflate"),
863 Self::Gzip => Some("gzip"),
864 Self::Br => Some("br"),
865 Self::Zstd => Some("zstd"),
866 }
867 }
868}
869
870#[derive(Serialize, Deserialize, Debug, Clone)]
872#[serde(default)]
873pub struct Http {
874 pub timeout: u32,
880 pub connection_timeout: u32,
885 pub max_retry_interval: u32,
887 pub host_header: Option<String>,
889 pub auth_interval: Option<u64>,
897 pub outage_grace_period: u64,
903 pub retry_delay: u64,
907 pub project_failure_interval: u64,
912 pub encoding: HttpEncoding,
928 pub global_metrics: bool,
935 pub forward: bool,
942 pub dns_cache: bool,
946}
947
948impl Default for Http {
949 fn default() -> Self {
950 Http {
951 timeout: 5,
952 connection_timeout: 3,
953 max_retry_interval: 60, host_header: None,
955 auth_interval: Some(600), outage_grace_period: DEFAULT_NETWORK_OUTAGE_GRACE_PERIOD,
957 retry_delay: 1,
958 project_failure_interval: 90,
959 encoding: HttpEncoding::Zstd,
960 global_metrics: false,
961 forward: true,
962 dns_cache: true,
963 }
964 }
965}
966
967#[derive(Clone, Copy, Debug, Eq, PartialEq, Default, Deserialize, Serialize)]
969#[serde(rename_all = "snake_case")]
970pub enum EnvelopeSpoolPartitioning {
971 ProjectKeyPair,
975 #[default]
982 RoundRobin,
983}
984
985#[derive(Debug, Serialize, Deserialize, Clone)]
987#[serde(default)]
988pub struct EnvelopeSpool {
989 pub path: Option<PathBuf>,
995 pub max_disk_size: ByteSize,
1001 pub batch_size_bytes: ByteSize,
1008 pub flush_timeout_secs: Option<u64>,
1014 pub max_envelope_delay_secs: u64,
1021 pub disk_usage_refresh_frequency_ms: u64,
1026 pub max_backpressure_memory_percent: f32,
1056 pub partitions: NonZeroU8,
1063 pub partitioning: EnvelopeSpoolPartitioning,
1069 pub max_unspool_envelopes_per_second: Option<NonZeroU32>,
1075 pub ephemeral: bool,
1082}
1083
1084impl Default for EnvelopeSpool {
1085 fn default() -> Self {
1086 Self {
1087 path: None,
1088 max_disk_size: ByteSize::mebibytes(500),
1089 batch_size_bytes: ByteSize::kibibytes(10),
1090 max_envelope_delay_secs: 24 * 60 * 60,
1091 disk_usage_refresh_frequency_ms: 100,
1092 max_backpressure_memory_percent: 0.8,
1093 partitions: NonZeroU8::new(1).unwrap(),
1094 partitioning: EnvelopeSpoolPartitioning::default(),
1095 ephemeral: false,
1096 flush_timeout_secs: None,
1097 max_unspool_envelopes_per_second: None,
1098 }
1099 }
1100}
1101
1102#[derive(Debug, Serialize, Deserialize, Default, Clone)]
1104#[serde(default)]
1105pub struct Spool {
1106 pub envelopes: EnvelopeSpool,
1108}
1109
1110#[derive(Serialize, Deserialize, Debug, Clone)]
1112#[serde(default)]
1113pub struct Cache {
1114 pub project_request_full_config: bool,
1119 pub project_expiry: u32,
1121 pub project_grace_period: u32,
1126 pub project_refresh_interval: Option<u32>,
1132 pub relay_expiry: u32,
1134 pub miss_expiry: u32,
1136 pub batch_interval: u32,
1138 pub downstream_relays_batch_interval: u32,
1140 pub batch_size: usize,
1144 pub file_interval: u32,
1146 pub global_config_fetch_interval: u32,
1148}
1149
1150impl Default for Cache {
1151 fn default() -> Self {
1152 Cache {
1153 project_request_full_config: false,
1154 project_expiry: 300, project_grace_period: 120, project_refresh_interval: None,
1157 relay_expiry: 3600, miss_expiry: 60, batch_interval: 100, downstream_relays_batch_interval: 100, batch_size: 500,
1162 file_interval: 10, global_config_fetch_interval: 10, }
1165 }
1166}
1167
1168#[derive(Serialize, Deserialize, Debug, Clone)]
1170#[serde(default)]
1171pub struct Processing {
1172 pub enabled: bool,
1174 pub geoip_path: Option<PathBuf>,
1176 pub max_secs_in_future: u32,
1178 pub max_session_secs_in_past: u32,
1180 pub kafka_config: Vec<KafkaConfigParam>,
1182 pub secondary_kafka_configs: BTreeMap<String, Vec<KafkaConfigParam>>,
1202 pub topics: TopicAssignments,
1204 pub kafka_validate_topics: bool,
1206 pub reloading_producer_jitter_secs: u64,
1213 pub redis: Option<RedisConfigs>,
1215 pub attachment_chunk_size: ByteSize,
1217 pub projectconfig_cache_prefix: String,
1219 pub max_rate_limit: Option<u32>,
1221 pub quota_cache_ratio: Option<f32>,
1232 pub quota_cache_max: Option<f32>,
1239 #[serde(alias = "upload")]
1241 pub objectstore: ObjectstoreServiceConfig,
1242}
1243
1244impl Default for Processing {
1245 fn default() -> Self {
1247 Self {
1248 enabled: false,
1249 geoip_path: None,
1250 max_secs_in_future: 60, max_session_secs_in_past: 5 * 24 * 3600, kafka_config: Vec::new(),
1253 secondary_kafka_configs: BTreeMap::new(),
1254 topics: TopicAssignments::default(),
1255 kafka_validate_topics: false,
1256 reloading_producer_jitter_secs: 60,
1257 redis: None,
1258 attachment_chunk_size: ByteSize::mebibytes(1),
1259 projectconfig_cache_prefix: "relayconfig".to_owned(),
1260 max_rate_limit: Some(300), quota_cache_ratio: None,
1262 quota_cache_max: None,
1263 objectstore: ObjectstoreServiceConfig::default(),
1264 }
1265 }
1266}
1267
1268fn default_cluster_name(processing: &Processing) -> String {
1274 let mut name = String::from("default");
1275 while processing.secondary_kafka_configs.contains_key(&name) {
1276 name.push('_');
1277 }
1278 name
1279}
1280
1281#[derive(Debug, Default, Serialize, Deserialize, Clone)]
1283#[serde(default)]
1284pub struct Normalization {
1285 pub level: NormalizationLevel,
1287}
1288
1289#[derive(Copy, Clone, Debug, Default, Serialize, Deserialize, Eq, PartialEq)]
1291#[serde(rename_all = "lowercase")]
1292pub enum NormalizationLevel {
1293 #[default]
1297 Default,
1298 Full,
1303}
1304
1305#[derive(Serialize, Deserialize, Clone)]
1307pub struct ObjectstoreAuthConfig {
1308 pub key_id: String,
1311
1312 pub signing_key: String,
1314}
1315
1316impl fmt::Debug for ObjectstoreAuthConfig {
1317 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1318 f.debug_struct("ObjectstoreAuthConfig")
1319 .field("key_id", &self.key_id)
1320 .field("signing_key", &"[redacted]")
1321 .finish()
1322 }
1323}
1324
1325#[derive(Serialize, Deserialize, Debug, Clone)]
1327#[serde(default)]
1328pub struct ObjectstoreServiceConfig {
1329 pub objectstore_url: Option<String>,
1334
1335 pub max_concurrent_requests: usize,
1337
1338 pub max_backlog: usize,
1342
1343 pub timeout: u64,
1348
1349 pub stream_timeout: u64,
1354
1355 pub retry_delay: f64,
1357
1358 pub max_attempts: NonZeroU16,
1360
1361 pub auth: Option<ObjectstoreAuthConfig>,
1363}
1364
1365impl Default for ObjectstoreServiceConfig {
1366 fn default() -> Self {
1367 Self {
1368 objectstore_url: None,
1369 max_concurrent_requests: 10,
1370 max_backlog: 20,
1371 timeout: 60,
1372 stream_timeout: 5 * 60, retry_delay: 1.0,
1374 max_attempts: NonZeroU16::new(5).unwrap(),
1375 auth: None,
1376 }
1377 }
1378}
1379
1380#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1383
1384pub enum EmitOutcomes {
1385 None,
1387 AsClientReports,
1389 AsOutcomes,
1391}
1392
1393impl EmitOutcomes {
1394 pub fn any(&self) -> bool {
1396 !matches!(self, EmitOutcomes::None)
1397 }
1398}
1399
1400impl Serialize for EmitOutcomes {
1401 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1402 where
1403 S: Serializer,
1404 {
1405 match self {
1407 Self::None => serializer.serialize_bool(false),
1408 Self::AsClientReports => serializer.serialize_str("as_client_reports"),
1409 Self::AsOutcomes => serializer.serialize_bool(true),
1410 }
1411 }
1412}
1413
1414struct EmitOutcomesVisitor;
1415
1416impl Visitor<'_> for EmitOutcomesVisitor {
1417 type Value = EmitOutcomes;
1418
1419 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1420 formatter.write_str("true, false, 'as_client_reports'")
1421 }
1422
1423 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
1424 where
1425 E: serde::de::Error,
1426 {
1427 Ok(if v {
1428 EmitOutcomes::AsOutcomes
1429 } else {
1430 EmitOutcomes::None
1431 })
1432 }
1433
1434 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1435 where
1436 E: serde::de::Error,
1437 {
1438 match v {
1439 "as_client_reports" => Ok(EmitOutcomes::AsClientReports),
1440 _ => Err(E::invalid_value(Unexpected::Str(v), &self)),
1441 }
1442 }
1443}
1444
1445impl<'de> Deserialize<'de> for EmitOutcomes {
1446 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1447 where
1448 D: Deserializer<'de>,
1449 {
1450 deserializer.deserialize_any(EmitOutcomesVisitor)
1451 }
1452}
1453
1454#[derive(Serialize, Deserialize, Debug, Clone)]
1456#[serde(default)]
1457pub struct Outcomes {
1458 pub emit_outcomes: EmitOutcomes,
1462 pub source: Option<String>,
1465}
1466
1467impl Default for Outcomes {
1468 fn default() -> Self {
1469 Outcomes {
1470 emit_outcomes: EmitOutcomes::AsClientReports,
1471 source: None,
1472 }
1473 }
1474}
1475
1476#[derive(Serialize, Deserialize, Debug, Default)]
1478pub struct MinimalConfig {
1479 pub relay: Relay,
1481}
1482
1483impl MinimalConfig {
1484 pub fn save_in_folder<P: AsRef<Path>>(&self, p: P) -> anyhow::Result<()> {
1486 let path = p.as_ref();
1487 if fs::metadata(path).is_err() {
1488 fs::create_dir_all(path)
1489 .with_context(|| ConfigError::file(ConfigErrorKind::CouldNotOpenFile, path))?;
1490 }
1491 self.save(path)
1492 }
1493}
1494
1495impl ConfigObject for MinimalConfig {
1496 fn format() -> ConfigFormat {
1497 ConfigFormat::Yaml
1498 }
1499
1500 fn name() -> &'static str {
1501 "config"
1502 }
1503}
1504
1505mod config_relay_info {
1507 use serde::ser::SerializeMap;
1508
1509 use super::*;
1510
1511 #[derive(Debug, Serialize, Deserialize, Clone)]
1513 struct RelayInfoConfig {
1514 public_key: PublicKey,
1515 #[serde(default)]
1516 internal: bool,
1517 }
1518
1519 impl From<RelayInfoConfig> for RelayInfo {
1520 fn from(v: RelayInfoConfig) -> Self {
1521 RelayInfo {
1522 public_key: v.public_key,
1523 internal: v.internal,
1524 }
1525 }
1526 }
1527
1528 impl From<RelayInfo> for RelayInfoConfig {
1529 fn from(v: RelayInfo) -> Self {
1530 RelayInfoConfig {
1531 public_key: v.public_key,
1532 internal: v.internal,
1533 }
1534 }
1535 }
1536
1537 pub(super) fn deserialize<'de, D>(des: D) -> Result<HashMap<RelayId, RelayInfo>, D::Error>
1538 where
1539 D: Deserializer<'de>,
1540 {
1541 let map = HashMap::<RelayId, RelayInfoConfig>::deserialize(des)?;
1542 Ok(map.into_iter().map(|(k, v)| (k, v.into())).collect())
1543 }
1544
1545 pub(super) fn serialize<S>(elm: &HashMap<RelayId, RelayInfo>, ser: S) -> Result<S::Ok, S::Error>
1546 where
1547 S: Serializer,
1548 {
1549 let mut map = ser.serialize_map(Some(elm.len()))?;
1550
1551 for (k, v) in elm {
1552 map.serialize_entry(k, &RelayInfoConfig::from(v.clone()))?;
1553 }
1554
1555 map.end()
1556 }
1557}
1558
1559#[derive(Serialize, Deserialize, Debug, Clone)]
1561#[serde(default)]
1562pub struct AuthConfig {
1563 #[serde(skip_serializing_if = "is_default")]
1565 pub ready: ReadinessCondition,
1566
1567 #[serde(with = "config_relay_info")]
1569 pub static_relays: HashMap<RelayId, RelayInfo>,
1570
1571 pub signature_max_age: u64,
1575}
1576
1577impl Default for AuthConfig {
1578 fn default() -> Self {
1579 Self {
1580 ready: ReadinessCondition::default(),
1581 static_relays: HashMap::new(),
1582 signature_max_age: 300, }
1584 }
1585}
1586
1587#[derive(Serialize, Deserialize, Debug, Default, Clone)]
1589pub struct GeoIpConfig {
1590 pub path: Option<PathBuf>,
1592}
1593
1594#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
1599#[serde(default)]
1600pub struct Health {
1601 pub refresh_interval_ms: u64,
1608 pub max_memory_bytes: Option<ByteSize>,
1613 pub max_memory_percent: f32,
1617 pub probe_timeout_ms: u64,
1624 pub memory_stat_refresh_frequency_ms: u64,
1630}
1631
1632impl Default for Health {
1633 fn default() -> Self {
1634 Self {
1635 refresh_interval_ms: 3000,
1636 max_memory_bytes: None,
1637 max_memory_percent: 0.95,
1638 probe_timeout_ms: 900,
1639 memory_stat_refresh_frequency_ms: 100,
1640 }
1641 }
1642}
1643
1644#[derive(Serialize, Deserialize, Debug, Clone)]
1646#[serde(default)]
1647pub struct Cogs {
1648 pub max_queue_size: u64,
1654 pub relay_resource_id: String,
1660}
1661
1662impl Default for Cogs {
1663 fn default() -> Self {
1664 Self {
1665 max_queue_size: 10_000,
1666 relay_resource_id: "relay_service".to_owned(),
1667 }
1668 }
1669}
1670
1671#[derive(Debug, Clone, Serialize, Deserialize)]
1673#[serde(default)]
1674pub struct Upload {
1675 pub max_concurrent_requests: usize,
1679 pub timeout: u64,
1681 pub max_age: i64,
1685
1686 pub credentials: Option<UploadCredentials>,
1690}
1691
1692impl Default for Upload {
1693 fn default() -> Self {
1694 Self {
1695 max_concurrent_requests: 100,
1696 timeout: 5 * 60, max_age: 60 * 60, credentials: None,
1699 }
1700 }
1701}
1702
1703#[derive(Clone, Serialize, Deserialize)]
1705pub struct UploadCredentials {
1706 #[cfg(feature = "processing")]
1708 pub signing_key: SecretKey,
1709
1710 pub verification_key: PublicKey,
1712}
1713
1714impl fmt::Debug for UploadCredentials {
1715 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1716 let Self {
1717 #[cfg(feature = "processing")]
1718 signing_key: _,
1719 verification_key,
1720 } = self;
1721 let mut b = f.debug_struct("UploadCredentials");
1722 #[cfg(feature = "processing")]
1723 b.field("signing_key", &"[redacted]");
1724 b.field("verification_key", verification_key).finish()
1725 }
1726}
1727
1728#[derive(Serialize, Deserialize, Debug, Default, Clone)]
1730#[serde(default)]
1731#[allow(missing_docs)]
1732pub struct ConfigValues {
1733 pub relay: Relay,
1734 pub http: Http,
1735 pub cache: Cache,
1736 pub spool: Spool,
1737 pub limits: Limits,
1738 pub logging: relay_log::LogConfig,
1739 pub routing: Routing,
1740 pub metrics: Metrics,
1741 pub sentry: relay_log::SentryConfig,
1742 pub processing: Processing,
1743 pub outcomes: Outcomes,
1744 pub aggregator: AggregatorServiceConfig,
1745 pub secondary_aggregators: Vec<ScopedAggregatorConfig>,
1746 pub auth: AuthConfig,
1747 pub geoip: GeoIpConfig,
1748 pub normalization: Normalization,
1749 pub health: Health,
1750 pub cogs: Cogs,
1751 pub upload: Upload,
1752}
1753
1754impl ConfigObject for ConfigValues {
1755 fn format() -> ConfigFormat {
1756 ConfigFormat::Yaml
1757 }
1758
1759 fn name() -> &'static str {
1760 "config"
1761 }
1762}
1763
1764#[derive(Default, Clone)]
1765struct ConfigInner {
1766 values: ConfigValues,
1768 credentials: Option<Credentials>,
1772}
1773
1774impl ConfigInner {
1775 fn apply_overrides(&mut self, overrides: &OverridableConfig) -> anyhow::Result<()> {
1776 if let Some(log_level) = &overrides.log_level {
1777 self.values.logging.level = log_level.parse()?;
1778 }
1779
1780 if let Some(log_format) = &overrides.log_format {
1781 self.values.logging.format = log_format.parse()?;
1782 }
1783
1784 let relay = &mut self.values.relay;
1785 if let Some(mode) = &overrides.mode {
1786 relay.mode = mode
1787 .parse::<RelayMode>()
1788 .with_context(|| ConfigError::field("mode"))?;
1789 }
1790 if let Some(deployment) = &overrides.instance {
1791 relay.instance = deployment
1792 .parse::<RelayInstance>()
1793 .with_context(|| ConfigError::field("deployment"))?;
1794 }
1795 if let Some(upstream) = &overrides.upstream {
1796 relay.upstream = upstream
1797 .parse::<UpstreamDescriptor>()
1798 .with_context(|| ConfigError::field("upstream"))?;
1799 } else if let Some(upstream_dsn) = &overrides.upstream_dsn {
1800 relay.upstream = upstream_dsn
1801 .parse::<Dsn>()
1802 .map(|dsn| UpstreamDescriptor::from_dsn(&dsn))
1803 .with_context(|| ConfigError::field("upstream_dsn"))?;
1804 }
1805 if let Some(host) = &overrides.host {
1806 relay.host = host
1807 .parse::<IpAddr>()
1808 .with_context(|| ConfigError::field("host"))?;
1809 }
1810 if let Some(port) = &overrides.port {
1811 relay.port = port
1812 .as_str()
1813 .parse()
1814 .with_context(|| ConfigError::field("port"))?;
1815 }
1816
1817 let processing = &mut self.values.processing;
1818 if let Some(enabled) = &overrides.processing {
1819 match enabled.to_lowercase().as_str() {
1820 "true" | "1" => processing.enabled = true,
1821 "false" | "0" | "" => processing.enabled = false,
1822 _ => return Err(ConfigError::field("processing").into()),
1823 }
1824 }
1825 if let Some(redis) = overrides.redis_url.clone() {
1826 processing.redis = Some(RedisConfigs::Unified(RedisConfig::single(redis)))
1827 }
1828 if let Some(kafka_url) = overrides.kafka_url.clone() {
1829 let existing = processing
1830 .kafka_config
1831 .iter_mut()
1832 .find(|e| e.name == "bootstrap.servers");
1833
1834 if let Some(config_param) = existing {
1835 config_param.value = kafka_url;
1836 } else {
1837 self.values.processing.kafka_config.push(KafkaConfigParam {
1838 name: "bootstrap.servers".to_owned(),
1839 value: kafka_url,
1840 })
1841 }
1842 }
1843
1844 if overrides.outcome_source.is_some() {
1845 self.values.outcomes.source = overrides.outcome_source.clone();
1846 }
1847
1848 if let Some(shutdown_timeout) = &overrides.shutdown_timeout
1849 && let Ok(shutdown_timeout) = shutdown_timeout.parse::<u64>()
1850 {
1851 self.values.limits.shutdown_timeout = shutdown_timeout;
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 shutdown_timeout(&self) -> Duration {
2792 Duration::from_secs(self.inner.values.limits.shutdown_timeout)
2793 }
2794
2795 pub fn keepalive_timeout(&self) -> Duration {
2799 Duration::from_secs(self.inner.values.limits.keepalive_timeout)
2800 }
2801
2802 pub fn idle_timeout(&self) -> Option<Duration> {
2804 self.inner
2805 .values
2806 .limits
2807 .idle_timeout
2808 .map(Duration::from_secs)
2809 }
2810
2811 pub fn max_connections(&self) -> Option<usize> {
2813 self.inner.values.limits.max_connections
2814 }
2815
2816 pub fn tcp_listen_backlog(&self) -> u32 {
2818 self.inner.values.limits.tcp_listen_backlog
2819 }
2820
2821 pub fn cpu_concurrency(&self) -> usize {
2823 self.inner.values.limits.max_thread_count
2824 }
2825
2826 pub fn pool_concurrency(&self) -> usize {
2828 self.inner.values.limits.max_pool_concurrency
2829 }
2830
2831 pub fn query_batch_size(&self) -> usize {
2833 self.inner.values.cache.batch_size
2834 }
2835
2836 pub fn processing_enabled(&self) -> bool {
2838 self.inner.values.processing.enabled
2839 }
2840
2841 pub fn normalization_level(&self) -> NormalizationLevel {
2843 self.inner.values.normalization.level
2844 }
2845
2846 pub fn geoip_path(&self) -> Option<&Path> {
2848 self.inner.values.geoip.path.as_deref().or(self
2849 .inner
2850 .values
2851 .processing
2852 .geoip_path
2853 .as_deref())
2854 }
2855
2856 pub fn max_secs_in_future(&self) -> i64 {
2860 self.inner.values.processing.max_secs_in_future.into()
2861 }
2862
2863 pub fn max_session_secs_in_past(&self) -> i64 {
2865 self.inner.values.processing.max_session_secs_in_past.into()
2866 }
2867
2868 pub fn kafka_configs(
2870 &self,
2871 topic: KafkaTopic,
2872 ) -> Result<KafkaTopicConfig<'_>, KafkaConfigError> {
2873 self.inner
2874 .values
2875 .processing
2876 .topics
2877 .get(topic)
2878 .kafka_configs(
2879 &self.inner.values.processing.kafka_config,
2880 &self.inner.values.processing.secondary_kafka_configs,
2881 )
2882 }
2883
2884 pub fn kafka_validate_topics(&self) -> bool {
2886 self.inner.values.processing.kafka_validate_topics
2887 }
2888
2889 pub fn reloading_producer_jitter(&self) -> Duration {
2891 Duration::from_secs(self.inner.values.processing.reloading_producer_jitter_secs)
2892 }
2893
2894 pub fn kafka_config_blob(&self) -> Result<Vec<u8>, KafkaConfigError> {
2903 let mut clusters = BTreeMap::new();
2906 let mut topics = BTreeMap::new();
2907
2908 let default_cluster = default_cluster_name(&self.inner.values.processing);
2912
2913 for topic in KafkaTopic::iter() {
2914 let topic_config = self.kafka_configs(*topic)?;
2915
2916 for params in topic_config.topics() {
2917 let cluster_name = params.config_name.unwrap_or(&default_cluster);
2918
2919 let config: BTreeMap<_, _> = params
2920 .params
2921 .iter()
2922 .map(|param| (param.name.as_str(), param.value.as_str()))
2923 .collect();
2924
2925 clusters.insert(
2926 cluster_name.to_owned(),
2927 serde_json::json!({ "config": config }),
2928 );
2929
2930 let entry = serde_json::json!({ "physical_topics": [{ "cluster": cluster_name }] });
2936 match topics.entry(params.topic_name.clone()) {
2937 Entry::Vacant(vacant) => {
2938 vacant.insert(entry);
2939 }
2940 Entry::Occupied(occupied) if *occupied.get() != entry => {
2941 return Err(KafkaConfigError::AmbiguousTopic(params.topic_name.clone()));
2942 }
2943 Entry::Occupied(_) => {}
2944 }
2945 }
2946 }
2947
2948 Ok(serde_json::to_vec(&serde_json::json!({
2950 "clusters": clusters,
2951 "topics": topics,
2952 }))
2953 .expect("kafka config blob is serializable"))
2954 }
2955
2956 pub fn unused_topic_assignments(&self) -> &relay_kafka::Unused {
2958 &self.inner.values.processing.topics.unused
2959 }
2960
2961 pub fn objectstore(&self) -> &ObjectstoreServiceConfig {
2963 &self.inner.values.processing.objectstore
2964 }
2965
2966 pub fn upload(&self) -> &Upload {
2968 &self.inner.values.upload
2969 }
2970
2971 #[cfg(feature = "processing")]
2973 pub fn upload_signing_key(&self) -> Option<&SecretKey> {
2974 self.upload()
2975 .credentials
2976 .as_ref()
2977 .map(|c| &c.signing_key)
2978 .or(self.credentials().map(|c| &c.secret_key))
2979 }
2980
2981 #[cfg(feature = "processing")]
2983 pub fn upload_verification_key(&self) -> Option<&PublicKey> {
2984 self.upload()
2985 .credentials
2986 .as_ref()
2987 .map(|c| &c.verification_key)
2988 .or(self.credentials().map(|c| &c.public_key))
2989 }
2990
2991 pub fn redis(&self) -> Option<RedisConfigsRef<'_>> {
2993 let redis_configs = self.inner.values.processing.redis.as_ref()?;
2994
2995 Some(build_redis_configs(
2996 redis_configs,
2997 self.cpu_concurrency() as u32,
2998 self.pool_concurrency() as u32,
2999 ))
3000 }
3001
3002 pub fn attachment_chunk_size(&self) -> usize {
3004 self.inner
3005 .values
3006 .processing
3007 .attachment_chunk_size
3008 .as_bytes()
3009 }
3010
3011 pub fn metrics_max_batch_size_bytes(&self) -> usize {
3013 self.inner.values.aggregator.max_flush_bytes
3014 }
3015
3016 pub fn projectconfig_cache_prefix(&self) -> &str {
3019 &self.inner.values.processing.projectconfig_cache_prefix
3020 }
3021
3022 pub fn max_rate_limit(&self) -> Option<u64> {
3024 self.inner.values.processing.max_rate_limit.map(u32::into)
3025 }
3026
3027 pub fn quota_cache_ratio(&self) -> Option<f32> {
3029 self.inner.values.processing.quota_cache_ratio
3030 }
3031
3032 pub fn quota_cache_max(&self) -> Option<f32> {
3034 self.inner.values.processing.quota_cache_max
3035 }
3036
3037 pub fn health_refresh_interval(&self) -> Duration {
3039 Duration::from_millis(self.inner.values.health.refresh_interval_ms)
3040 }
3041
3042 pub fn health_max_memory_watermark_bytes(&self) -> u64 {
3044 self.inner
3045 .values
3046 .health
3047 .max_memory_bytes
3048 .as_ref()
3049 .map_or(u64::MAX, |b| b.as_bytes() as u64)
3050 }
3051
3052 pub fn health_max_memory_watermark_percent(&self) -> f32 {
3054 self.inner.values.health.max_memory_percent
3055 }
3056
3057 pub fn health_probe_timeout(&self) -> Duration {
3059 Duration::from_millis(self.inner.values.health.probe_timeout_ms)
3060 }
3061
3062 pub fn memory_stat_refresh_frequency_ms(&self) -> u64 {
3064 self.inner.values.health.memory_stat_refresh_frequency_ms
3065 }
3066
3067 pub fn cogs_max_queue_size(&self) -> u64 {
3069 self.inner.values.cogs.max_queue_size
3070 }
3071
3072 pub fn cogs_relay_resource_id(&self) -> &str {
3074 &self.inner.values.cogs.relay_resource_id
3075 }
3076
3077 pub fn default_aggregator_config(&self) -> &AggregatorServiceConfig {
3079 &self.inner.values.aggregator
3080 }
3081
3082 pub fn secondary_aggregator_configs(&self) -> &Vec<ScopedAggregatorConfig> {
3084 &self.inner.values.secondary_aggregators
3085 }
3086
3087 pub fn aggregator_config_for(&self, namespace: MetricNamespace) -> &AggregatorServiceConfig {
3089 for entry in &self.inner.values.secondary_aggregators {
3090 if entry.condition.matches(Some(namespace)) {
3091 return &entry.config;
3092 }
3093 }
3094 &self.inner.values.aggregator
3095 }
3096
3097 pub fn static_relays(&self) -> &HashMap<RelayId, RelayInfo> {
3099 &self.inner.values.auth.static_relays
3100 }
3101
3102 pub fn signature_max_age(&self) -> Duration {
3104 Duration::from_secs(self.inner.values.auth.signature_max_age)
3105 }
3106
3107 pub fn accept_unknown_items(&self) -> bool {
3109 let forward = self.inner.values.routing.accept_unknown_items;
3110 forward.unwrap_or_else(|| !self.processing_enabled())
3111 }
3112}
3113
3114impl fmt::Debug for ConfigSnapshot {
3115 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3116 f.debug_struct("ConfigSnapshot")
3117 .field("values", &self.inner.values)
3118 .finish()
3119 }
3120}
3121
3122#[cfg(test)]
3123mod tests {
3124 use super::*;
3125
3126 #[test]
3127 fn test_http_encoding_parse_strict() {
3128 for (value, expected) in [
3129 ("identity", Some(HttpEncoding::Identity)),
3130 ("gzip", Some(HttpEncoding::Gzip)),
3131 ("deflate", Some(HttpEncoding::Deflate)),
3132 ("br", Some(HttpEncoding::Br)),
3133 ("zstd", Some(HttpEncoding::Zstd)),
3134 ("", None),
3135 ("unknown", None),
3136 ("x-gzip", None),
3137 ("GZIP", None),
3138 (" gzip ", None),
3139 ("zstd, gzip", None),
3140 ] {
3141 assert_eq!(HttpEncoding::parse_strict(value), expected, "{value:?}");
3142 }
3143 }
3144
3145 #[cfg(feature = "processing")]
3146 #[test]
3147 fn test_upload_secret_key_from_file() {
3148 let path = env::temp_dir().join(Uuid::new_v4().to_string());
3149 fs::create_dir(&path).unwrap();
3150 fs::write(
3151 path.join("my_secret.txt"),
3152 "U3LSQM5NorvgnoYHW_aZpc_43nuuh3lhs3zjjcBwaks",
3153 )
3154 .unwrap();
3155 fs::write(
3156 ConfigValues::path(&path),
3157 r#"
3158 upload:
3159 credentials:
3160 signing_key: ${file:my_secret.txt}
3161 verification_key: "VNS8haF0VTnuMMDR2t-f7AgnmUcXmcdzV3SVksSk34s""#,
3162 )
3163 .unwrap();
3164
3165 let config = Config::from_path(&path).unwrap().current();
3166
3167 fs::remove_dir_all(path).unwrap();
3168
3169 let signing_key = &config.upload().credentials.as_ref().unwrap().signing_key;
3170 assert_eq!(
3171 signing_key.to_string(),
3172 "U3LSQM5NorvgnoYHW_aZpc_43nuuh3lhs3zjjcBwaks"
3173 );
3174 }
3175
3176 #[test]
3177 fn test_emit_outcomes() {
3178 for (serialized, deserialized) in &[
3179 ("true", EmitOutcomes::AsOutcomes),
3180 ("false", EmitOutcomes::None),
3181 ("\"as_client_reports\"", EmitOutcomes::AsClientReports),
3182 ] {
3183 let value: EmitOutcomes = serde_json::from_str(serialized).unwrap();
3184 assert_eq!(value, *deserialized);
3185 assert_eq!(serde_json::to_string(&value).unwrap(), *serialized);
3186 }
3187 }
3188
3189 #[test]
3190 fn test_emit_outcomes_invalid() {
3191 assert!(serde_json::from_str::<EmitOutcomes>("asdf").is_err());
3192 }
3193
3194 #[cfg(feature = "processing")]
3196 fn processing_config(yaml: &str) -> Config {
3197 let path = env::temp_dir().join(Uuid::new_v4().to_string());
3198 fs::create_dir(&path).unwrap();
3199 fs::write(ConfigValues::path(&path), yaml).unwrap();
3200 Config::from_path(&path).unwrap()
3201 }
3202
3203 #[cfg(feature = "processing")]
3205 #[test]
3206 fn test_kafka_config_blob_round_trips() {
3207 use sentry_arroyo::backends::kafka::config_blob::{ConfigBlob, ProducerSelector};
3208
3209 let config = processing_config(
3211 r#"
3212processing:
3213 enabled: true
3214 kafka_config:
3215 - {name: "bootstrap.servers", value: "primary:9092"}
3216 - {name: "compression.type", value: "lz4"}
3217 secondary_kafka_configs:
3218 default:
3219 - {name: "bootstrap.servers", value: "impostor:9092"}
3220 topics:
3221 ingest-events: ["events-1", "events-2"]
3222 ingest-metrics:
3223 name: "metrics-topic"
3224 config: "default"
3225"#,
3226 );
3227 let config = config.current();
3228
3229 let blob = config.kafka_config_blob().unwrap();
3230 let parsed = ConfigBlob::parse(&blob).unwrap();
3231
3232 let resolve = |topic: &str| {
3233 let resolved = parsed
3234 .producer_config(&ProducerSelector::new(topic, "relay"))
3235 .unwrap_or_else(|_| panic!("{topic} is missing from the blob"));
3236
3237 assert_eq!(resolved.physical_topic.as_str(), topic);
3239
3240 resolved
3241 .config
3242 .config_map()
3243 .iter()
3244 .filter(|(key, _)| !matches!(key.as_str(), "statistics.interval.ms" | "client.id"))
3246 .map(|(key, value)| (key.clone(), value.clone()))
3247 .collect::<BTreeMap<_, _>>()
3248 };
3249
3250 for (topic, physical) in [
3251 (KafkaTopic::Events, ["events-1", "events-2"].as_slice()),
3252 (KafkaTopic::MetricsSessions, ["metrics-topic"].as_slice()),
3253 ] {
3254 let params = config.kafka_configs(topic).unwrap();
3255
3256 for (shard, physical) in params.topics().iter().zip(physical) {
3257 let expected: BTreeMap<_, _> = shard
3258 .params
3259 .iter()
3260 .map(|param| (param.name.clone(), param.value.clone()))
3261 .collect();
3262
3263 assert_eq!(
3264 resolve(physical),
3265 expected,
3266 "{physical} resolved differently"
3267 );
3268 }
3269 }
3270
3271 assert_eq!(
3273 resolve("events-1").get("bootstrap.servers").unwrap(),
3274 "primary:9092"
3275 );
3276 assert_eq!(
3277 resolve("metrics-topic").get("bootstrap.servers").unwrap(),
3278 "impostor:9092"
3279 );
3280 }
3281
3282 #[cfg(feature = "processing")]
3284 #[test]
3285 fn test_topic_can_move_between_clusters() {
3286 use sentry_arroyo::backends::kafka::config_blob::{ConfigBlob, ProducerSelector};
3287
3288 let resolve = |yaml: &str| {
3289 let config = processing_config(yaml);
3290 let blob = config.current().kafka_config_blob().unwrap();
3291 ConfigBlob::parse(&blob)
3292 .unwrap()
3293 .producer_config(&ProducerSelector::new("events-topic", "relay"))
3294 .unwrap()
3295 .config
3296 .get_config_value("bootstrap.servers")
3297 .unwrap()
3298 .clone()
3299 };
3300
3301 let before = resolve(
3302 r#"
3303processing:
3304 enabled: true
3305 kafka_config:
3306 - {name: "bootstrap.servers", value: "primary:9092"}
3307 secondary_kafka_configs:
3308 other:
3309 - {name: "bootstrap.servers", value: "other:9092"}
3310 topics:
3311 ingest-events: "events-topic"
3312"#,
3313 );
3314
3315 let after = resolve(
3317 r#"
3318processing:
3319 enabled: true
3320 kafka_config:
3321 - {name: "bootstrap.servers", value: "primary:9092"}
3322 secondary_kafka_configs:
3323 other:
3324 - {name: "bootstrap.servers", value: "other:9092"}
3325 topics:
3326 ingest-events:
3327 name: "events-topic"
3328 config: "other"
3329"#,
3330 );
3331
3332 assert_eq!(before, "primary:9092");
3333 assert_eq!(after, "other:9092");
3334 }
3335
3336 #[cfg(feature = "processing")]
3339 #[test]
3340 fn test_kafka_config_blob_rejects_topic_on_two_clusters() {
3341 let config = processing_config(
3342 r#"
3343processing:
3344 enabled: true
3345 kafka_config:
3346 - {name: "bootstrap.servers", value: "primary:9092"}
3347 secondary_kafka_configs:
3348 other:
3349 - {name: "bootstrap.servers", value: "other:9092"}
3350 topics:
3351 outcomes:
3352 name: "outcomes-topic"
3353 config: "other"
3354 outcomes-billing: "outcomes-topic"
3355"#,
3356 );
3357
3358 assert!(matches!(
3359 config.current().kafka_config_blob(),
3360 Err(KafkaConfigError::AmbiguousTopic(topic)) if topic == "outcomes-topic"
3361 ));
3362 }
3363
3364 #[test]
3367 fn test_reload_takes_kafka_config_but_not_topics() {
3368 let mut current = ConfigValues::default();
3369 current.processing.kafka_config = vec![KafkaConfigParam {
3370 name: "bootstrap.servers".to_owned(),
3371 value: "old:9092".to_owned(),
3372 }];
3373 current.processing.topics.events = "old-topic".to_owned().into();
3374
3375 let mut other = ConfigValues::default();
3376 other.processing.kafka_config = vec![KafkaConfigParam {
3377 name: "bootstrap.servers".to_owned(),
3378 value: "new:9092".to_owned(),
3379 }];
3380 other.processing.topics.events = "new-topic".to_owned().into();
3381
3382 let mut current = ConfigInner {
3383 values: current,
3384 ..Default::default()
3385 };
3386 let other = ConfigInner {
3387 values: other,
3388 ..Default::default()
3389 };
3390
3391 assert!(current.reload_with(&other));
3392 assert_eq!(current.values.processing.kafka_config[0].value, "new:9092");
3393
3394 let assignment = format!("{:?}", current.values.processing.topics.events);
3395 assert!(
3396 assignment.contains("old-topic"),
3397 "topic assignment was reloaded, but the producers cannot pick it up: {assignment}"
3398 );
3399 }
3400}