1use std::collections::{BTreeMap, HashMap};
2use std::error::Error;
3use std::io::Write;
4use std::net::{IpAddr, SocketAddr};
5use std::num::{NonZeroU8, NonZeroU16};
6use std::path::{Path, PathBuf};
7use std::str::FromStr;
8use std::time::Duration;
9use std::{env, fmt, fs, io};
10
11use anyhow::Context;
12use relay_auth::{PublicKey, RelayId, SecretKey, generate_key_pair, generate_relay_id};
13use relay_common::Dsn;
14use relay_kafka::{
15 ConfigError as KafkaConfigError, KafkaConfigParam, KafkaTopic, KafkaTopicConfig,
16 TopicAssignments,
17};
18use relay_metrics::MetricNamespace;
19use serde::de::{DeserializeOwned, Unexpected, Visitor};
20use serde::{Deserialize, Deserializer, Serialize, Serializer};
21use uuid::Uuid;
22
23use crate::aggregator::{AggregatorServiceConfig, ScopedAggregatorConfig};
24use crate::byte_size::ByteSize;
25use crate::upstream::UpstreamDescriptor;
26use crate::{RedisConfig, RedisConfigs, RedisConfigsRef, build_redis_configs};
27
28const DEFAULT_NETWORK_OUTAGE_GRACE_PERIOD: u64 = 10;
29
30static CONFIG_YAML_HEADER: &str = r###"# Please see the relevant documentation.
31# Performance tuning: https://docs.sentry.io/product/relay/operating-guidelines/
32# All config options: https://docs.sentry.io/product/relay/options/
33"###;
34
35#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
37#[non_exhaustive]
38pub enum ConfigErrorKind {
39 CouldNotOpenFile,
41 CouldNotWriteFile,
43 BadYaml,
45 BadJson,
47 InvalidValue,
49 ProcessingNotAvailable,
52}
53
54impl fmt::Display for ConfigErrorKind {
55 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56 match self {
57 Self::CouldNotOpenFile => write!(f, "could not open config file"),
58 Self::CouldNotWriteFile => write!(f, "could not write config file"),
59 Self::BadYaml => write!(f, "could not parse yaml config file"),
60 Self::BadJson => write!(f, "could not parse json config file"),
61 Self::InvalidValue => write!(f, "invalid config value"),
62 Self::ProcessingNotAvailable => write!(
63 f,
64 "was not compiled with processing, cannot enable processing"
65 ),
66 }
67 }
68}
69
70#[derive(Debug, Default)]
72enum ConfigErrorSource {
73 #[default]
75 None,
76 File(PathBuf),
78 FieldOverride(String),
80}
81
82impl fmt::Display for ConfigErrorSource {
83 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84 match self {
85 ConfigErrorSource::None => Ok(()),
86 ConfigErrorSource::File(file_name) => {
87 write!(f, " (file {})", file_name.display())
88 }
89 ConfigErrorSource::FieldOverride(name) => write!(f, " (field {name})"),
90 }
91 }
92}
93
94#[derive(Debug)]
96pub struct ConfigError {
97 source: ConfigErrorSource,
98 kind: ConfigErrorKind,
99}
100
101impl ConfigError {
102 #[inline]
103 fn new(kind: ConfigErrorKind) -> Self {
104 Self {
105 source: ConfigErrorSource::None,
106 kind,
107 }
108 }
109
110 #[inline]
111 fn field(field: &'static str) -> Self {
112 Self {
113 source: ConfigErrorSource::FieldOverride(field.to_owned()),
114 kind: ConfigErrorKind::InvalidValue,
115 }
116 }
117
118 #[inline]
119 fn file(kind: ConfigErrorKind, p: impl AsRef<Path>) -> Self {
120 Self {
121 source: ConfigErrorSource::File(p.as_ref().to_path_buf()),
122 kind,
123 }
124 }
125
126 pub fn kind(&self) -> ConfigErrorKind {
128 self.kind
129 }
130}
131
132impl fmt::Display for ConfigError {
133 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
134 write!(f, "{}{}", self.kind(), self.source)
135 }
136}
137
138impl Error for ConfigError {}
139
140enum ConfigFormat {
141 Yaml,
142 Json,
143}
144
145impl ConfigFormat {
146 pub fn extension(&self) -> &'static str {
147 match self {
148 ConfigFormat::Yaml => "yml",
149 ConfigFormat::Json => "json",
150 }
151 }
152}
153
154trait ConfigObject: DeserializeOwned + Serialize {
155 fn format() -> ConfigFormat;
157
158 fn name() -> &'static str;
160
161 fn path(base: &Path) -> PathBuf {
163 base.join(format!("{}.{}", Self::name(), Self::format().extension()))
164 }
165
166 fn load(base: &Path) -> anyhow::Result<Self> {
168 let path = Self::path(base);
169
170 let f = fs::File::open(&path)
171 .with_context(|| ConfigError::file(ConfigErrorKind::CouldNotOpenFile, &path))?;
172 let f = io::BufReader::new(f);
173
174 let mut source = {
175 let file = serde_vars::FileSource::default()
176 .with_variable_prefix("${file:")
177 .with_variable_suffix("}")
178 .with_base_path(base);
179 let env = serde_vars::EnvSource::default()
180 .with_variable_prefix("${")
181 .with_variable_suffix("}");
182 (file, env)
183 };
184 match Self::format() {
185 ConfigFormat::Yaml => {
186 serde_vars::deserialize(serde_yaml::Deserializer::from_reader(f), &mut source)
187 .with_context(|| ConfigError::file(ConfigErrorKind::BadYaml, &path))
188 }
189 ConfigFormat::Json => {
190 serde_vars::deserialize(&mut serde_json::Deserializer::from_reader(f), &mut source)
191 .with_context(|| ConfigError::file(ConfigErrorKind::BadJson, &path))
192 }
193 }
194 }
195
196 fn save(&self, base: &Path) -> anyhow::Result<()> {
198 let path = Self::path(base);
199 let mut options = fs::OpenOptions::new();
200 options.write(true).truncate(true).create(true);
201
202 #[cfg(unix)]
204 {
205 use std::os::unix::fs::OpenOptionsExt;
206 options.mode(0o600);
207 }
208
209 let mut f = options
210 .open(&path)
211 .with_context(|| ConfigError::file(ConfigErrorKind::CouldNotWriteFile, &path))?;
212
213 match Self::format() {
214 ConfigFormat::Yaml => {
215 f.write_all(CONFIG_YAML_HEADER.as_bytes())?;
216 serde_yaml::to_writer(&mut f, self)
217 .with_context(|| ConfigError::file(ConfigErrorKind::CouldNotWriteFile, &path))?
218 }
219 ConfigFormat::Json => serde_json::to_writer_pretty(&mut f, self)
220 .with_context(|| ConfigError::file(ConfigErrorKind::CouldNotWriteFile, &path))?,
221 }
222
223 f.write_all(b"\n").ok();
224
225 Ok(())
226 }
227}
228
229#[derive(Debug, Default)]
232pub struct OverridableConfig {
233 pub mode: Option<String>,
235 pub instance: Option<String>,
237 pub log_level: Option<String>,
239 pub log_format: Option<String>,
241 pub upstream: Option<String>,
243 pub upstream_dsn: Option<String>,
245 pub host: Option<String>,
247 pub port: Option<String>,
249 pub processing: Option<String>,
251 pub kafka_url: Option<String>,
253 pub redis_url: Option<String>,
255 pub id: Option<String>,
257 pub secret_key: Option<String>,
259 pub public_key: Option<String>,
261 pub outcome_source: Option<String>,
263 pub shutdown_timeout: Option<String>,
265 pub server_name: Option<String>,
267}
268
269#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
271pub struct Credentials {
272 pub secret_key: SecretKey,
274 pub public_key: PublicKey,
276 pub id: RelayId,
278}
279
280impl Credentials {
281 pub fn generate() -> Self {
283 relay_log::info!("generating new relay credentials");
284 let (secret_key, public_key) = generate_key_pair();
285 Self {
286 secret_key,
287 public_key,
288 id: generate_relay_id(),
289 }
290 }
291
292 pub fn to_json_string(&self) -> anyhow::Result<String> {
294 serde_json::to_string(self)
295 .with_context(|| ConfigError::new(ConfigErrorKind::CouldNotWriteFile))
296 }
297}
298
299impl ConfigObject for Credentials {
300 fn format() -> ConfigFormat {
301 ConfigFormat::Json
302 }
303 fn name() -> &'static str {
304 "credentials"
305 }
306}
307
308#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
310#[serde(rename_all = "camelCase")]
311pub struct RelayInfo {
312 pub public_key: PublicKey,
314
315 #[serde(default)]
317 pub internal: bool,
318}
319
320impl RelayInfo {
321 pub fn new(public_key: PublicKey) -> Self {
323 Self {
324 public_key,
325 internal: false,
326 }
327 }
328}
329
330#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
332#[serde(rename_all = "camelCase")]
333pub enum RelayMode {
334 Proxy,
340
341 Managed,
347}
348
349impl<'de> Deserialize<'de> for RelayMode {
350 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
351 where
352 D: Deserializer<'de>,
353 {
354 let s = String::deserialize(deserializer)?;
355 match s.as_str() {
356 "proxy" => Ok(RelayMode::Proxy),
357 "managed" => Ok(RelayMode::Managed),
358 "static" => Err(serde::de::Error::custom(
359 "Relay mode 'static' has been removed. Please use 'managed' or 'proxy' instead.",
360 )),
361 other => Err(serde::de::Error::unknown_variant(
362 other,
363 &["proxy", "managed"],
364 )),
365 }
366 }
367}
368
369impl fmt::Display for RelayMode {
370 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
371 match self {
372 RelayMode::Proxy => write!(f, "proxy"),
373 RelayMode::Managed => write!(f, "managed"),
374 }
375 }
376}
377
378#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
380#[serde(rename_all = "camelCase")]
381pub enum RelayInstance {
382 Default,
384
385 Canary,
387}
388
389impl RelayInstance {
390 pub fn is_canary(&self) -> bool {
392 matches!(self, RelayInstance::Canary)
393 }
394}
395
396impl fmt::Display for RelayInstance {
397 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
398 match self {
399 RelayInstance::Default => write!(f, "default"),
400 RelayInstance::Canary => write!(f, "canary"),
401 }
402 }
403}
404
405impl FromStr for RelayInstance {
406 type Err = fmt::Error;
407
408 fn from_str(s: &str) -> Result<Self, Self::Err> {
409 match s {
410 "canary" => Ok(RelayInstance::Canary),
411 _ => Ok(RelayInstance::Default),
412 }
413 }
414}
415
416#[derive(Clone, Copy, Debug, Eq, PartialEq)]
418pub struct ParseRelayModeError;
419
420impl fmt::Display for ParseRelayModeError {
421 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
422 write!(f, "Relay mode must be one of: managed or proxy")
423 }
424}
425
426impl Error for ParseRelayModeError {}
427
428impl FromStr for RelayMode {
429 type Err = ParseRelayModeError;
430
431 fn from_str(s: &str) -> Result<Self, Self::Err> {
432 match s {
433 "proxy" => Ok(RelayMode::Proxy),
434 "managed" => Ok(RelayMode::Managed),
435 _ => Err(ParseRelayModeError),
436 }
437 }
438}
439
440fn is_default<T: Default + PartialEq>(t: &T) -> bool {
442 *t == T::default()
443}
444
445fn is_docker() -> bool {
447 if fs::metadata("/.dockerenv").is_ok() {
448 return true;
449 }
450
451 fs::read_to_string("/proc/self/cgroup").is_ok_and(|s| s.contains("/docker"))
452}
453
454fn default_host() -> IpAddr {
456 if is_docker() {
457 "0.0.0.0".parse().unwrap()
459 } else {
460 "127.0.0.1".parse().unwrap()
461 }
462}
463
464#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
468#[serde(rename_all = "lowercase")]
469#[derive(Default)]
470pub enum ReadinessCondition {
471 #[default]
480 Authenticated,
481 Always,
483}
484
485#[derive(Serialize, Deserialize, Debug)]
487#[serde(default)]
488pub struct Relay {
489 pub mode: RelayMode,
491 pub instance: RelayInstance,
493 pub upstream: UpstreamDescriptor,
495 pub advertised_upstream: Option<UpstreamDescriptor>,
504 pub host: IpAddr,
506 pub port: u16,
508 pub internal_host: Option<IpAddr>,
522 pub internal_port: Option<u16>,
526 #[serde(skip_serializing)]
528 pub tls_port: Option<u16>,
529 #[serde(skip_serializing)]
531 pub tls_identity_path: Option<PathBuf>,
532 #[serde(skip_serializing)]
534 pub tls_identity_password: Option<String>,
535 #[serde(skip_serializing_if = "is_default")]
540 pub override_project_ids: bool,
541}
542
543impl Default for Relay {
544 fn default() -> Self {
545 Relay {
546 mode: RelayMode::Managed,
547 instance: RelayInstance::Default,
548 upstream: "https://sentry.io/".parse().unwrap(),
549 advertised_upstream: None,
550 host: default_host(),
551 port: 3000,
552 internal_host: None,
553 internal_port: None,
554 tls_port: None,
555 tls_identity_path: None,
556 tls_identity_password: None,
557 override_project_ids: false,
558 }
559 }
560}
561
562#[derive(Serialize, Deserialize, Debug)]
564#[serde(default)]
565pub struct Metrics {
566 pub statsd: Option<String>,
570 pub statsd_buffer_size: Option<usize>,
574 pub prefix: String,
578 pub default_tags: BTreeMap<String, String>,
580 pub hostname_tag: Option<String>,
582 pub periodic_secs: u64,
587}
588
589impl Default for Metrics {
590 fn default() -> Self {
591 Metrics {
592 statsd: None,
593 statsd_buffer_size: None,
594 prefix: "sentry.relay".into(),
595 default_tags: BTreeMap::new(),
596 hostname_tag: None,
597 periodic_secs: 5,
598 }
599 }
600}
601
602#[derive(Serialize, Deserialize, Debug)]
604#[serde(default)]
605pub struct Limits {
606 pub max_concurrent_requests: usize,
609 pub max_concurrent_queries: usize,
614 pub max_event_size: ByteSize,
616 pub max_attachment_size: ByteSize,
618 pub max_upload_size: ByteSize,
620 pub max_attachments_size: ByteSize,
622 pub max_client_reports_size: ByteSize,
624 pub max_check_in_size: ByteSize,
626 pub max_envelope_size: ByteSize,
628 pub max_session_count: usize,
630 pub max_api_payload_size: ByteSize,
632 pub max_api_file_upload_size: ByteSize,
634 pub max_api_chunk_upload_size: ByteSize,
636 pub max_profile_size: ByteSize,
638 pub max_trace_metric_size: ByteSize,
640 pub max_log_size: ByteSize,
642 pub max_span_size: ByteSize,
644 pub max_container_size: ByteSize,
646 pub max_statsd_size: ByteSize,
648 pub max_metric_buckets_size: ByteSize,
650 pub max_replay_compressed_size: ByteSize,
652 #[serde(alias = "max_replay_size")]
654 max_replay_uncompressed_size: ByteSize,
655 pub max_replay_message_size: ByteSize,
657 pub max_removed_attribute_key_size: ByteSize,
667 pub max_thread_count: usize,
672 pub max_pool_concurrency: usize,
679 pub query_timeout: u64,
682 pub shutdown_timeout: u64,
685 pub keepalive_timeout: u64,
689 pub idle_timeout: Option<u64>,
696 pub max_connections: Option<usize>,
702 pub tcp_listen_backlog: u32,
710}
711
712impl Default for Limits {
713 fn default() -> Self {
714 Limits {
715 max_concurrent_requests: 100,
716 max_concurrent_queries: 5,
717 max_event_size: ByteSize::mebibytes(1),
718 max_attachment_size: ByteSize::mebibytes(200),
719 max_upload_size: ByteSize::mebibytes(1024),
720 max_attachments_size: ByteSize::mebibytes(200),
721 max_client_reports_size: ByteSize::kibibytes(4),
722 max_check_in_size: ByteSize::kibibytes(100),
723 max_envelope_size: ByteSize::mebibytes(200),
724 max_session_count: 100,
725 max_api_payload_size: ByteSize::mebibytes(20),
726 max_api_file_upload_size: ByteSize::mebibytes(40),
727 max_api_chunk_upload_size: ByteSize::mebibytes(100),
728 max_profile_size: ByteSize::mebibytes(50),
729 max_trace_metric_size: ByteSize::mebibytes(1),
730 max_log_size: ByteSize::mebibytes(1),
731 max_span_size: ByteSize::mebibytes(10),
732 max_container_size: ByteSize::mebibytes(12),
733 max_statsd_size: ByteSize::mebibytes(1),
734 max_metric_buckets_size: ByteSize::mebibytes(1),
735 max_replay_compressed_size: ByteSize::mebibytes(10),
736 max_replay_uncompressed_size: ByteSize::mebibytes(100),
737 max_replay_message_size: ByteSize::mebibytes(15),
738 max_thread_count: num_cpus::get(),
739 max_pool_concurrency: 1,
740 query_timeout: 30,
741 shutdown_timeout: 10,
742 keepalive_timeout: 5,
743 idle_timeout: None,
744 max_connections: None,
745 tcp_listen_backlog: 1024,
746 max_removed_attribute_key_size: ByteSize::kibibytes(10),
747 }
748 }
749}
750
751#[derive(Debug, Default, Deserialize, Serialize)]
753#[serde(default)]
754pub struct Routing {
755 pub accept_unknown_items: Option<bool>,
765}
766
767#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)]
769#[serde(rename_all = "lowercase")]
770pub enum HttpEncoding {
771 #[default]
776 Identity,
777 Deflate,
783 Gzip,
790 Br,
792 Zstd,
794}
795
796impl HttpEncoding {
797 pub fn parse(str: &str) -> Self {
799 let str = str.trim();
800 if str.eq_ignore_ascii_case("zstd") {
801 Self::Zstd
802 } else if str.eq_ignore_ascii_case("br") {
803 Self::Br
804 } else if str.eq_ignore_ascii_case("gzip") || str.eq_ignore_ascii_case("x-gzip") {
805 Self::Gzip
806 } else if str.eq_ignore_ascii_case("deflate") {
807 Self::Deflate
808 } else {
809 Self::Identity
810 }
811 }
812
813 pub fn name(&self) -> Option<&'static str> {
817 match self {
818 Self::Identity => None,
819 Self::Deflate => Some("deflate"),
820 Self::Gzip => Some("gzip"),
821 Self::Br => Some("br"),
822 Self::Zstd => Some("zstd"),
823 }
824 }
825}
826
827#[derive(Serialize, Deserialize, Debug)]
829#[serde(default)]
830pub struct Http {
831 pub timeout: u32,
837 pub connection_timeout: u32,
842 pub max_retry_interval: u32,
844 pub host_header: Option<String>,
846 pub auth_interval: Option<u64>,
854 pub outage_grace_period: u64,
860 pub retry_delay: u64,
864 pub project_failure_interval: u64,
869 pub encoding: HttpEncoding,
885 pub global_metrics: bool,
892 pub forward: bool,
899 pub dns_cache: bool,
903}
904
905impl Default for Http {
906 fn default() -> Self {
907 Http {
908 timeout: 5,
909 connection_timeout: 3,
910 max_retry_interval: 60, host_header: None,
912 auth_interval: Some(600), outage_grace_period: DEFAULT_NETWORK_OUTAGE_GRACE_PERIOD,
914 retry_delay: 1,
915 project_failure_interval: 90,
916 encoding: HttpEncoding::Zstd,
917 global_metrics: false,
918 forward: true,
919 dns_cache: true,
920 }
921 }
922}
923
924#[derive(Clone, Copy, Debug, Eq, PartialEq, Default, Deserialize, Serialize)]
926#[serde(rename_all = "snake_case")]
927pub enum EnvelopeSpoolPartitioning {
928 ProjectKeyPair,
932 #[default]
939 RoundRobin,
940}
941
942#[derive(Debug, Serialize, Deserialize)]
944#[serde(default)]
945pub struct EnvelopeSpool {
946 pub path: Option<PathBuf>,
952 pub max_disk_size: ByteSize,
958 pub batch_size_bytes: ByteSize,
965 pub max_envelope_delay_secs: u64,
972 pub disk_usage_refresh_frequency_ms: u64,
977 pub max_backpressure_memory_percent: f32,
1007 pub partitions: NonZeroU8,
1014 pub partitioning: EnvelopeSpoolPartitioning,
1020 pub ephemeral: bool,
1027}
1028
1029impl Default for EnvelopeSpool {
1030 fn default() -> Self {
1031 Self {
1032 path: None,
1033 max_disk_size: ByteSize::mebibytes(500),
1034 batch_size_bytes: ByteSize::kibibytes(10),
1035 max_envelope_delay_secs: 24 * 60 * 60,
1036 disk_usage_refresh_frequency_ms: 100,
1037 max_backpressure_memory_percent: 0.8,
1038 partitions: NonZeroU8::new(1).unwrap(),
1039 partitioning: EnvelopeSpoolPartitioning::default(),
1040 ephemeral: false,
1041 }
1042 }
1043}
1044
1045#[derive(Debug, Serialize, Deserialize, Default)]
1047#[serde(default)]
1048pub struct Spool {
1049 pub envelopes: EnvelopeSpool,
1051}
1052
1053#[derive(Serialize, Deserialize, Debug)]
1055#[serde(default)]
1056pub struct Cache {
1057 pub project_request_full_config: bool,
1059 pub project_expiry: u32,
1061 pub project_grace_period: u32,
1066 pub project_refresh_interval: Option<u32>,
1072 pub relay_expiry: u32,
1074 #[serde(alias = "event_expiry")]
1080 envelope_expiry: u32,
1081 #[serde(alias = "event_buffer_size")]
1083 envelope_buffer_size: u32,
1084 pub miss_expiry: u32,
1086 pub batch_interval: u32,
1088 pub downstream_relays_batch_interval: u32,
1090 pub batch_size: usize,
1094 pub file_interval: u32,
1096 pub global_config_fetch_interval: u32,
1098}
1099
1100impl Default for Cache {
1101 fn default() -> Self {
1102 Cache {
1103 project_request_full_config: false,
1104 project_expiry: 300, project_grace_period: 120, project_refresh_interval: None,
1107 relay_expiry: 3600, envelope_expiry: 600, envelope_buffer_size: 1000,
1110 miss_expiry: 60, batch_interval: 100, downstream_relays_batch_interval: 100, batch_size: 500,
1114 file_interval: 10, global_config_fetch_interval: 10, }
1117 }
1118}
1119
1120#[derive(Serialize, Deserialize, Debug)]
1122#[serde(default)]
1123pub struct Processing {
1124 pub enabled: bool,
1126 pub geoip_path: Option<PathBuf>,
1128 pub max_secs_in_future: u32,
1130 pub max_session_secs_in_past: u32,
1132 pub kafka_config: Vec<KafkaConfigParam>,
1134 pub secondary_kafka_configs: BTreeMap<String, Vec<KafkaConfigParam>>,
1154 pub topics: TopicAssignments,
1156 pub kafka_validate_topics: bool,
1158 pub redis: Option<RedisConfigs>,
1160 pub attachment_chunk_size: ByteSize,
1162 pub projectconfig_cache_prefix: String,
1164 pub max_rate_limit: Option<u32>,
1166 pub quota_cache_ratio: Option<f32>,
1177 pub quota_cache_max: Option<f32>,
1184 #[serde(alias = "upload")]
1186 pub objectstore: ObjectstoreServiceConfig,
1187}
1188
1189impl Default for Processing {
1190 fn default() -> Self {
1192 Self {
1193 enabled: false,
1194 geoip_path: None,
1195 max_secs_in_future: 60, max_session_secs_in_past: 5 * 24 * 3600, kafka_config: Vec::new(),
1198 secondary_kafka_configs: BTreeMap::new(),
1199 topics: TopicAssignments::default(),
1200 kafka_validate_topics: false,
1201 redis: None,
1202 attachment_chunk_size: ByteSize::mebibytes(1),
1203 projectconfig_cache_prefix: "relayconfig".to_owned(),
1204 max_rate_limit: Some(300), quota_cache_ratio: None,
1206 quota_cache_max: None,
1207 objectstore: ObjectstoreServiceConfig::default(),
1208 }
1209 }
1210}
1211
1212#[derive(Debug, Default, Serialize, Deserialize)]
1214#[serde(default)]
1215pub struct Normalization {
1216 pub level: NormalizationLevel,
1218}
1219
1220#[derive(Copy, Clone, Debug, Default, Serialize, Deserialize, Eq, PartialEq)]
1222#[serde(rename_all = "lowercase")]
1223pub enum NormalizationLevel {
1224 #[default]
1228 Default,
1229 Full,
1234}
1235
1236#[derive(Serialize, Deserialize)]
1238pub struct ObjectstoreAuthConfig {
1239 pub key_id: String,
1242
1243 pub signing_key: String,
1245}
1246
1247impl fmt::Debug for ObjectstoreAuthConfig {
1248 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1249 f.debug_struct("ObjectstoreAuthConfig")
1250 .field("key_id", &self.key_id)
1251 .field("signing_key", &"[redacted]")
1252 .finish()
1253 }
1254}
1255
1256#[derive(Serialize, Deserialize, Debug)]
1258#[serde(default)]
1259pub struct ObjectstoreServiceConfig {
1260 pub objectstore_url: Option<String>,
1265
1266 pub max_concurrent_requests: usize,
1268
1269 pub max_backlog: usize,
1273
1274 pub timeout: u64,
1279
1280 pub stream_timeout: u64,
1285
1286 pub retry_delay: f64,
1288
1289 pub max_attempts: NonZeroU16,
1291
1292 pub fallback_to_kafka: bool,
1297
1298 pub auth: Option<ObjectstoreAuthConfig>,
1300}
1301
1302impl Default for ObjectstoreServiceConfig {
1303 fn default() -> Self {
1304 Self {
1305 objectstore_url: None,
1306 max_concurrent_requests: 10,
1307 max_backlog: 20,
1308 timeout: 60,
1309 stream_timeout: 5 * 60, retry_delay: 1.0,
1311 max_attempts: NonZeroU16::new(5).unwrap(),
1312 fallback_to_kafka: true,
1313 auth: None,
1314 }
1315 }
1316}
1317
1318#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1321
1322pub enum EmitOutcomes {
1323 None,
1325 AsClientReports,
1327 AsOutcomes,
1329}
1330
1331impl EmitOutcomes {
1332 pub fn any(&self) -> bool {
1334 !matches!(self, EmitOutcomes::None)
1335 }
1336}
1337
1338impl Serialize for EmitOutcomes {
1339 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1340 where
1341 S: Serializer,
1342 {
1343 match self {
1345 Self::None => serializer.serialize_bool(false),
1346 Self::AsClientReports => serializer.serialize_str("as_client_reports"),
1347 Self::AsOutcomes => serializer.serialize_bool(true),
1348 }
1349 }
1350}
1351
1352struct EmitOutcomesVisitor;
1353
1354impl Visitor<'_> for EmitOutcomesVisitor {
1355 type Value = EmitOutcomes;
1356
1357 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1358 formatter.write_str("true, false, 'as_client_reports'")
1359 }
1360
1361 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
1362 where
1363 E: serde::de::Error,
1364 {
1365 Ok(if v {
1366 EmitOutcomes::AsOutcomes
1367 } else {
1368 EmitOutcomes::None
1369 })
1370 }
1371
1372 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1373 where
1374 E: serde::de::Error,
1375 {
1376 match v {
1377 "as_client_reports" => Ok(EmitOutcomes::AsClientReports),
1378 _ => Err(E::invalid_value(Unexpected::Str(v), &self)),
1379 }
1380 }
1381}
1382
1383impl<'de> Deserialize<'de> for EmitOutcomes {
1384 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1385 where
1386 D: Deserializer<'de>,
1387 {
1388 deserializer.deserialize_any(EmitOutcomesVisitor)
1389 }
1390}
1391
1392#[derive(Serialize, Deserialize, Debug)]
1394#[serde(default)]
1395pub struct Outcomes {
1396 pub emit_outcomes: EmitOutcomes,
1400 pub batch_size: usize,
1403 pub batch_interval: u64,
1406 pub source: Option<String>,
1409}
1410
1411impl Default for Outcomes {
1412 fn default() -> Self {
1413 Outcomes {
1414 emit_outcomes: EmitOutcomes::AsClientReports,
1415 batch_size: 1000,
1416 batch_interval: 500,
1417 source: None,
1418 }
1419 }
1420}
1421
1422#[derive(Serialize, Deserialize, Debug, Default)]
1424pub struct MinimalConfig {
1425 pub relay: Relay,
1427}
1428
1429impl MinimalConfig {
1430 pub fn save_in_folder<P: AsRef<Path>>(&self, p: P) -> anyhow::Result<()> {
1432 let path = p.as_ref();
1433 if fs::metadata(path).is_err() {
1434 fs::create_dir_all(path)
1435 .with_context(|| ConfigError::file(ConfigErrorKind::CouldNotOpenFile, path))?;
1436 }
1437 self.save(path)
1438 }
1439}
1440
1441impl ConfigObject for MinimalConfig {
1442 fn format() -> ConfigFormat {
1443 ConfigFormat::Yaml
1444 }
1445
1446 fn name() -> &'static str {
1447 "config"
1448 }
1449}
1450
1451mod config_relay_info {
1453 use serde::ser::SerializeMap;
1454
1455 use super::*;
1456
1457 #[derive(Debug, Serialize, Deserialize, Clone)]
1459 struct RelayInfoConfig {
1460 public_key: PublicKey,
1461 #[serde(default)]
1462 internal: bool,
1463 }
1464
1465 impl From<RelayInfoConfig> for RelayInfo {
1466 fn from(v: RelayInfoConfig) -> Self {
1467 RelayInfo {
1468 public_key: v.public_key,
1469 internal: v.internal,
1470 }
1471 }
1472 }
1473
1474 impl From<RelayInfo> for RelayInfoConfig {
1475 fn from(v: RelayInfo) -> Self {
1476 RelayInfoConfig {
1477 public_key: v.public_key,
1478 internal: v.internal,
1479 }
1480 }
1481 }
1482
1483 pub(super) fn deserialize<'de, D>(des: D) -> Result<HashMap<RelayId, RelayInfo>, D::Error>
1484 where
1485 D: Deserializer<'de>,
1486 {
1487 let map = HashMap::<RelayId, RelayInfoConfig>::deserialize(des)?;
1488 Ok(map.into_iter().map(|(k, v)| (k, v.into())).collect())
1489 }
1490
1491 pub(super) fn serialize<S>(elm: &HashMap<RelayId, RelayInfo>, ser: S) -> Result<S::Ok, S::Error>
1492 where
1493 S: Serializer,
1494 {
1495 let mut map = ser.serialize_map(Some(elm.len()))?;
1496
1497 for (k, v) in elm {
1498 map.serialize_entry(k, &RelayInfoConfig::from(v.clone()))?;
1499 }
1500
1501 map.end()
1502 }
1503}
1504
1505#[derive(Serialize, Deserialize, Debug)]
1507#[serde(default)]
1508pub struct AuthConfig {
1509 #[serde(skip_serializing_if = "is_default")]
1511 pub ready: ReadinessCondition,
1512
1513 #[serde(with = "config_relay_info")]
1515 pub static_relays: HashMap<RelayId, RelayInfo>,
1516
1517 pub signature_max_age: u64,
1521}
1522
1523impl Default for AuthConfig {
1524 fn default() -> Self {
1525 Self {
1526 ready: ReadinessCondition::default(),
1527 static_relays: HashMap::new(),
1528 signature_max_age: 300, }
1530 }
1531}
1532
1533#[derive(Serialize, Deserialize, Debug, Default)]
1535pub struct GeoIpConfig {
1536 pub path: Option<PathBuf>,
1538}
1539
1540#[derive(Serialize, Deserialize, Debug)]
1542#[serde(default)]
1543pub struct CardinalityLimiter {
1544 pub cache_vacuum_interval: u64,
1550}
1551
1552impl Default for CardinalityLimiter {
1553 fn default() -> Self {
1554 Self {
1555 cache_vacuum_interval: 180,
1556 }
1557 }
1558}
1559
1560#[derive(Serialize, Deserialize, Debug)]
1565#[serde(default)]
1566pub struct Health {
1567 pub refresh_interval_ms: u64,
1574 pub max_memory_bytes: Option<ByteSize>,
1579 pub max_memory_percent: f32,
1583 pub probe_timeout_ms: u64,
1590 pub memory_stat_refresh_frequency_ms: u64,
1596}
1597
1598impl Default for Health {
1599 fn default() -> Self {
1600 Self {
1601 refresh_interval_ms: 3000,
1602 max_memory_bytes: None,
1603 max_memory_percent: 0.95,
1604 probe_timeout_ms: 900,
1605 memory_stat_refresh_frequency_ms: 100,
1606 }
1607 }
1608}
1609
1610#[derive(Serialize, Deserialize, Debug)]
1612#[serde(default)]
1613pub struct Cogs {
1614 pub max_queue_size: u64,
1620 pub relay_resource_id: String,
1626}
1627
1628impl Default for Cogs {
1629 fn default() -> Self {
1630 Self {
1631 max_queue_size: 10_000,
1632 relay_resource_id: "relay_service".to_owned(),
1633 }
1634 }
1635}
1636
1637#[derive(Debug, Clone, Serialize, Deserialize)]
1639#[serde(default)]
1640pub struct Upload {
1641 pub max_concurrent_requests: usize,
1645 pub timeout: u64,
1647 pub max_age: i64,
1651
1652 pub credentials: Option<UploadCredentials>,
1656}
1657
1658impl Default for Upload {
1659 fn default() -> Self {
1660 Self {
1661 max_concurrent_requests: 100,
1662 timeout: 5 * 60, max_age: 60 * 60, credentials: None,
1665 }
1666 }
1667}
1668
1669#[derive(Clone, Serialize, Deserialize)]
1671pub struct UploadCredentials {
1672 #[cfg(feature = "processing")]
1674 pub signing_key: SecretKey,
1675
1676 pub verification_key: PublicKey,
1678}
1679
1680impl fmt::Debug for UploadCredentials {
1681 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1682 let Self {
1683 #[cfg(feature = "processing")]
1684 signing_key: _,
1685 verification_key,
1686 } = self;
1687 let mut b = f.debug_struct("UploadCredentials");
1688 #[cfg(feature = "processing")]
1689 b.field("signing_key", &"[redacted]");
1690 b.field("verification_key", verification_key).finish()
1691 }
1692}
1693
1694#[derive(Serialize, Deserialize, Debug, Default)]
1696#[serde(default)]
1697#[allow(missing_docs)]
1698pub struct ConfigValues {
1699 pub relay: Relay,
1700 pub http: Http,
1701 pub cache: Cache,
1702 pub spool: Spool,
1703 pub limits: Limits,
1704 pub logging: relay_log::LogConfig,
1705 pub routing: Routing,
1706 pub metrics: Metrics,
1707 pub sentry: relay_log::SentryConfig,
1708 pub processing: Processing,
1709 pub outcomes: Outcomes,
1710 pub aggregator: AggregatorServiceConfig,
1711 pub secondary_aggregators: Vec<ScopedAggregatorConfig>,
1712 pub auth: AuthConfig,
1713 pub geoip: GeoIpConfig,
1714 pub normalization: Normalization,
1715 pub cardinality_limiter: CardinalityLimiter,
1716 pub health: Health,
1717 pub cogs: Cogs,
1718 pub upload: Upload,
1719}
1720
1721impl ConfigObject for ConfigValues {
1722 fn format() -> ConfigFormat {
1723 ConfigFormat::Yaml
1724 }
1725
1726 fn name() -> &'static str {
1727 "config"
1728 }
1729}
1730
1731pub struct Config {
1733 values: ConfigValues,
1734 credentials: Option<Credentials>,
1735 path: PathBuf,
1736}
1737
1738impl fmt::Debug for Config {
1739 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1740 f.debug_struct("Config")
1741 .field("path", &self.path)
1742 .field("values", &self.values)
1743 .finish()
1744 }
1745}
1746
1747impl Config {
1748 pub fn from_path<P: AsRef<Path>>(path: P) -> anyhow::Result<Config> {
1750 let path = env::current_dir()
1751 .map(|x| x.join(path.as_ref()))
1752 .unwrap_or_else(|_| path.as_ref().to_path_buf());
1753
1754 let config = Config {
1755 values: ConfigValues::load(&path)?,
1756 credentials: if Credentials::path(&path).exists() {
1757 Some(Credentials::load(&path)?)
1758 } else {
1759 None
1760 },
1761 path: path.clone(),
1762 };
1763
1764 if cfg!(not(feature = "processing")) && config.processing_enabled() {
1765 return Err(ConfigError::file(ConfigErrorKind::ProcessingNotAvailable, &path).into());
1766 }
1767
1768 Ok(config)
1769 }
1770
1771 pub fn from_json_value(value: serde_json::Value) -> anyhow::Result<Config> {
1775 Ok(Config {
1776 values: serde_json::from_value(value)
1777 .with_context(|| ConfigError::new(ConfigErrorKind::BadJson))?,
1778 credentials: None,
1779 path: PathBuf::new(),
1780 })
1781 }
1782
1783 pub fn apply_override(
1786 &mut self,
1787 mut overrides: OverridableConfig,
1788 ) -> anyhow::Result<&mut Self> {
1789 let relay = &mut self.values.relay;
1790
1791 if let Some(mode) = overrides.mode {
1792 relay.mode = mode
1793 .parse::<RelayMode>()
1794 .with_context(|| ConfigError::field("mode"))?;
1795 }
1796
1797 if let Some(deployment) = overrides.instance {
1798 relay.instance = deployment
1799 .parse::<RelayInstance>()
1800 .with_context(|| ConfigError::field("deployment"))?;
1801 }
1802
1803 if let Some(log_level) = overrides.log_level {
1804 self.values.logging.level = log_level.parse()?;
1805 }
1806
1807 if let Some(log_format) = overrides.log_format {
1808 self.values.logging.format = log_format.parse()?;
1809 }
1810
1811 if let Some(upstream) = overrides.upstream {
1812 relay.upstream = upstream
1813 .parse::<UpstreamDescriptor>()
1814 .with_context(|| ConfigError::field("upstream"))?;
1815 } else if let Some(upstream_dsn) = overrides.upstream_dsn {
1816 relay.upstream = upstream_dsn
1817 .parse::<Dsn>()
1818 .map(|dsn| UpstreamDescriptor::from_dsn(&dsn))
1819 .with_context(|| ConfigError::field("upstream_dsn"))?;
1820 }
1821
1822 if let Some(host) = overrides.host {
1823 relay.host = host
1824 .parse::<IpAddr>()
1825 .with_context(|| ConfigError::field("host"))?;
1826 }
1827
1828 if let Some(port) = overrides.port {
1829 relay.port = port
1830 .as_str()
1831 .parse()
1832 .with_context(|| ConfigError::field("port"))?;
1833 }
1834
1835 let processing = &mut self.values.processing;
1836 if let Some(enabled) = overrides.processing {
1837 match enabled.to_lowercase().as_str() {
1838 "true" | "1" => processing.enabled = true,
1839 "false" | "0" | "" => processing.enabled = false,
1840 _ => return Err(ConfigError::field("processing").into()),
1841 }
1842 }
1843
1844 if let Some(redis) = overrides.redis_url {
1845 processing.redis = Some(RedisConfigs::Unified(RedisConfig::single(redis)))
1846 }
1847
1848 if let Some(kafka_url) = overrides.kafka_url {
1849 let existing = processing
1850 .kafka_config
1851 .iter_mut()
1852 .find(|e| e.name == "bootstrap.servers");
1853
1854 if let Some(config_param) = existing {
1855 config_param.value = kafka_url;
1856 } else {
1857 processing.kafka_config.push(KafkaConfigParam {
1858 name: "bootstrap.servers".to_owned(),
1859 value: kafka_url,
1860 })
1861 }
1862 }
1863 let id = if let Some(id) = overrides.id {
1865 let id = Uuid::parse_str(&id).with_context(|| ConfigError::field("id"))?;
1866 Some(id)
1867 } else {
1868 None
1869 };
1870 let public_key = if let Some(public_key) = overrides.public_key {
1871 let public_key = public_key
1872 .parse::<PublicKey>()
1873 .with_context(|| ConfigError::field("public_key"))?;
1874 Some(public_key)
1875 } else {
1876 None
1877 };
1878
1879 let secret_key = if let Some(secret_key) = overrides.secret_key {
1880 let secret_key = secret_key
1881 .parse::<SecretKey>()
1882 .with_context(|| ConfigError::field("secret_key"))?;
1883 Some(secret_key)
1884 } else {
1885 None
1886 };
1887 let outcomes = &mut self.values.outcomes;
1888 if overrides.outcome_source.is_some() {
1889 outcomes.source = overrides.outcome_source.take();
1890 }
1891
1892 if let Some(credentials) = &mut self.credentials {
1893 if let Some(id) = id {
1895 credentials.id = id;
1896 }
1897 if let Some(public_key) = public_key {
1898 credentials.public_key = public_key;
1899 }
1900 if let Some(secret_key) = secret_key {
1901 credentials.secret_key = secret_key
1902 }
1903 } else {
1904 match (id, public_key, secret_key) {
1906 (Some(id), Some(public_key), Some(secret_key)) => {
1907 self.credentials = Some(Credentials {
1908 secret_key,
1909 public_key,
1910 id,
1911 })
1912 }
1913 (None, None, None) => {
1914 }
1917 _ => {
1918 return Err(ConfigError::field("incomplete credentials").into());
1919 }
1920 }
1921 }
1922
1923 let limits = &mut self.values.limits;
1924 if let Some(shutdown_timeout) = overrides.shutdown_timeout
1925 && let Ok(shutdown_timeout) = shutdown_timeout.parse::<u64>()
1926 {
1927 limits.shutdown_timeout = shutdown_timeout;
1928 }
1929
1930 if let Some(server_name) = overrides.server_name {
1931 self.values.sentry.server_name = Some(server_name.into());
1932 }
1933
1934 Ok(self)
1935 }
1936
1937 pub fn config_exists<P: AsRef<Path>>(path: P) -> bool {
1939 fs::metadata(ConfigValues::path(path.as_ref())).is_ok()
1940 }
1941
1942 pub fn path(&self) -> &Path {
1944 &self.path
1945 }
1946
1947 pub fn to_yaml_string(&self) -> anyhow::Result<String> {
1949 serde_yaml::to_string(&self.values)
1950 .with_context(|| ConfigError::new(ConfigErrorKind::CouldNotWriteFile))
1951 }
1952
1953 pub fn regenerate_credentials(&mut self, save: bool) -> anyhow::Result<()> {
1957 let creds = Credentials::generate();
1958 if save {
1959 creds.save(&self.path)?;
1960 }
1961 self.credentials = Some(creds);
1962 Ok(())
1963 }
1964
1965 pub fn credentials(&self) -> Option<&Credentials> {
1967 self.credentials.as_ref()
1968 }
1969
1970 pub fn replace_credentials(
1974 &mut self,
1975 credentials: Option<Credentials>,
1976 ) -> anyhow::Result<bool> {
1977 if self.credentials == credentials {
1978 return Ok(false);
1979 }
1980
1981 match credentials {
1982 Some(ref creds) => {
1983 creds.save(&self.path)?;
1984 }
1985 None => {
1986 let path = Credentials::path(&self.path);
1987 if fs::metadata(&path).is_ok() {
1988 fs::remove_file(&path).with_context(|| {
1989 ConfigError::file(ConfigErrorKind::CouldNotWriteFile, &path)
1990 })?;
1991 }
1992 }
1993 }
1994
1995 self.credentials = credentials;
1996 Ok(true)
1997 }
1998
1999 pub fn has_credentials(&self) -> bool {
2001 self.credentials.is_some()
2002 }
2003
2004 pub fn secret_key(&self) -> Option<&SecretKey> {
2006 self.credentials.as_ref().map(|x| &x.secret_key)
2007 }
2008
2009 pub fn public_key(&self) -> Option<&PublicKey> {
2011 self.credentials.as_ref().map(|x| &x.public_key)
2012 }
2013
2014 pub fn relay_id(&self) -> Option<&RelayId> {
2016 self.credentials.as_ref().map(|x| &x.id)
2017 }
2018
2019 pub fn relay_mode(&self) -> RelayMode {
2021 self.values.relay.mode
2022 }
2023
2024 pub fn relay_instance(&self) -> RelayInstance {
2026 self.values.relay.instance
2027 }
2028
2029 pub fn upstream(&self) -> &UpstreamDescriptor {
2031 &self.values.relay.upstream
2032 }
2033
2034 pub fn advertised_upstream(&self) -> Option<&UpstreamDescriptor> {
2036 self.values.relay.advertised_upstream.as_ref()
2037 }
2038
2039 pub fn http_host_header(&self) -> Option<&str> {
2041 self.values.http.host_header.as_deref()
2042 }
2043
2044 pub fn listen_addr(&self) -> SocketAddr {
2046 (self.values.relay.host, self.values.relay.port).into()
2047 }
2048
2049 pub fn listen_addr_internal(&self) -> Option<SocketAddr> {
2057 match (
2058 self.values.relay.internal_host,
2059 self.values.relay.internal_port,
2060 ) {
2061 (Some(host), None) => Some((host, self.values.relay.port).into()),
2062 (None, Some(port)) => Some((self.values.relay.host, port).into()),
2063 (Some(host), Some(port)) => Some((host, port).into()),
2064 (None, None) => None,
2065 }
2066 }
2067
2068 pub fn tls_listen_addr(&self) -> Option<SocketAddr> {
2070 if self.values.relay.tls_identity_path.is_some() {
2071 let port = self.values.relay.tls_port.unwrap_or(3443);
2072 Some((self.values.relay.host, port).into())
2073 } else {
2074 None
2075 }
2076 }
2077
2078 pub fn tls_identity_path(&self) -> Option<&Path> {
2080 self.values.relay.tls_identity_path.as_deref()
2081 }
2082
2083 pub fn tls_identity_password(&self) -> Option<&str> {
2085 self.values.relay.tls_identity_password.as_deref()
2086 }
2087
2088 pub fn override_project_ids(&self) -> bool {
2092 self.values.relay.override_project_ids
2093 }
2094
2095 pub fn requires_auth(&self) -> bool {
2099 match self.values.auth.ready {
2100 ReadinessCondition::Authenticated => self.relay_mode() == RelayMode::Managed,
2101 ReadinessCondition::Always => false,
2102 }
2103 }
2104
2105 pub fn http_auth_interval(&self) -> Option<Duration> {
2109 if self.processing_enabled() {
2110 return None;
2111 }
2112
2113 match self.values.http.auth_interval {
2114 None | Some(0) => None,
2115 Some(secs) => Some(Duration::from_secs(secs)),
2116 }
2117 }
2118
2119 pub fn http_outage_grace_period(&self) -> Duration {
2122 Duration::from_secs(self.values.http.outage_grace_period)
2123 }
2124
2125 pub fn http_retry_delay(&self) -> Duration {
2130 Duration::from_secs(self.values.http.retry_delay)
2131 }
2132
2133 pub fn http_project_failure_interval(&self) -> Duration {
2135 Duration::from_secs(self.values.http.project_failure_interval)
2136 }
2137
2138 pub fn http_encoding(&self) -> HttpEncoding {
2140 self.values.http.encoding
2141 }
2142
2143 pub fn http_global_metrics(&self) -> bool {
2145 self.values.http.global_metrics
2146 }
2147
2148 pub fn http_forward(&self) -> bool {
2153 self.values.http.forward && !self.processing_enabled()
2154 }
2155
2156 pub fn emit_outcomes(&self) -> EmitOutcomes {
2161 if self.processing_enabled() {
2162 return EmitOutcomes::AsOutcomes;
2163 }
2164 self.values.outcomes.emit_outcomes
2165 }
2166
2167 pub fn outcome_batch_size(&self) -> usize {
2169 self.values.outcomes.batch_size
2170 }
2171
2172 pub fn outcome_batch_interval(&self) -> Duration {
2174 Duration::from_millis(self.values.outcomes.batch_interval)
2175 }
2176
2177 pub fn outcome_source(&self) -> Option<&str> {
2179 self.values.outcomes.source.as_deref()
2180 }
2181
2182 pub fn logging(&self) -> &relay_log::LogConfig {
2184 &self.values.logging
2185 }
2186
2187 pub fn sentry(&self) -> &relay_log::SentryConfig {
2189 &self.values.sentry
2190 }
2191
2192 pub fn statsd_addr(&self) -> Option<&str> {
2194 self.values.metrics.statsd.as_deref()
2195 }
2196
2197 pub fn statsd_buffer_size(&self) -> Option<usize> {
2199 self.values.metrics.statsd_buffer_size
2200 }
2201
2202 pub fn metrics_prefix(&self) -> &str {
2204 &self.values.metrics.prefix
2205 }
2206
2207 pub fn metrics_default_tags(&self) -> &BTreeMap<String, String> {
2209 &self.values.metrics.default_tags
2210 }
2211
2212 pub fn metrics_hostname_tag(&self) -> Option<&str> {
2214 self.values.metrics.hostname_tag.as_deref()
2215 }
2216
2217 pub fn metrics_periodic_interval(&self) -> Option<Duration> {
2221 match self.values.metrics.periodic_secs {
2222 0 => None,
2223 secs => Some(Duration::from_secs(secs)),
2224 }
2225 }
2226
2227 pub fn http_timeout(&self) -> Duration {
2229 Duration::from_secs(self.values.http.timeout.into())
2230 }
2231
2232 pub fn http_connection_timeout(&self) -> Duration {
2234 Duration::from_secs(self.values.http.connection_timeout.into())
2235 }
2236
2237 pub fn http_max_retry_interval(&self) -> Duration {
2239 Duration::from_secs(self.values.http.max_retry_interval.into())
2240 }
2241
2242 pub fn http_dns_cache(&self) -> bool {
2244 self.values.http.dns_cache
2245 }
2246
2247 pub fn project_cache_expiry(&self) -> Duration {
2249 Duration::from_secs(self.values.cache.project_expiry.into())
2250 }
2251
2252 pub fn request_full_project_config(&self) -> bool {
2254 self.values.cache.project_request_full_config
2255 }
2256
2257 pub fn relay_cache_expiry(&self) -> Duration {
2259 Duration::from_secs(self.values.cache.relay_expiry.into())
2260 }
2261
2262 pub fn envelope_buffer_size(&self) -> usize {
2264 self.values
2265 .cache
2266 .envelope_buffer_size
2267 .try_into()
2268 .unwrap_or(usize::MAX)
2269 }
2270
2271 pub fn cache_miss_expiry(&self) -> Duration {
2273 Duration::from_secs(self.values.cache.miss_expiry.into())
2274 }
2275
2276 pub fn project_grace_period(&self) -> Duration {
2278 Duration::from_secs(self.values.cache.project_grace_period.into())
2279 }
2280
2281 pub fn project_refresh_interval(&self) -> Option<Duration> {
2285 self.values
2286 .cache
2287 .project_refresh_interval
2288 .map(Into::into)
2289 .map(Duration::from_secs)
2290 }
2291
2292 pub fn query_batch_interval(&self) -> Duration {
2295 Duration::from_millis(self.values.cache.batch_interval.into())
2296 }
2297
2298 pub fn downstream_relays_batch_interval(&self) -> Duration {
2300 Duration::from_millis(self.values.cache.downstream_relays_batch_interval.into())
2301 }
2302
2303 pub fn local_cache_interval(&self) -> Duration {
2305 Duration::from_secs(self.values.cache.file_interval.into())
2306 }
2307
2308 pub fn global_config_fetch_interval(&self) -> Duration {
2311 Duration::from_secs(self.values.cache.global_config_fetch_interval.into())
2312 }
2313
2314 pub fn spool_envelopes_path(&self, partition_id: u8) -> Option<PathBuf> {
2319 let mut path = self
2320 .values
2321 .spool
2322 .envelopes
2323 .path
2324 .as_ref()
2325 .map(|path| path.to_owned())?;
2326
2327 if partition_id == 0 {
2328 return Some(path);
2329 }
2330
2331 let file_name = path.file_name().and_then(|f| f.to_str())?;
2332 let new_file_name = format!("{file_name}.{partition_id}");
2333 path.set_file_name(new_file_name);
2334
2335 Some(path)
2336 }
2337
2338 pub fn spool_envelopes_max_disk_size(&self) -> usize {
2340 self.values.spool.envelopes.max_disk_size.as_bytes()
2341 }
2342
2343 pub fn spool_envelopes_batch_size_bytes(&self) -> usize {
2346 self.values.spool.envelopes.batch_size_bytes.as_bytes()
2347 }
2348
2349 pub fn spool_envelopes_max_age(&self) -> Duration {
2351 Duration::from_secs(self.values.spool.envelopes.max_envelope_delay_secs)
2352 }
2353
2354 pub fn spool_disk_usage_refresh_frequency_ms(&self) -> Duration {
2356 Duration::from_millis(self.values.spool.envelopes.disk_usage_refresh_frequency_ms)
2357 }
2358
2359 pub fn spool_max_backpressure_memory_percent(&self) -> f32 {
2361 self.values.spool.envelopes.max_backpressure_memory_percent
2362 }
2363
2364 pub fn spool_partitions(&self) -> NonZeroU8 {
2366 self.values.spool.envelopes.partitions
2367 }
2368
2369 pub fn spool_partitioning(&self) -> EnvelopeSpoolPartitioning {
2371 self.values.spool.envelopes.partitioning
2372 }
2373
2374 pub fn spool_ephemeral(&self) -> bool {
2376 self.values.spool.envelopes.ephemeral
2377 }
2378
2379 pub fn max_event_size(&self) -> usize {
2381 self.values.limits.max_event_size.as_bytes()
2382 }
2383
2384 pub fn max_attachment_size(&self) -> usize {
2386 self.values.limits.max_attachment_size.as_bytes()
2387 }
2388
2389 pub fn max_upload_size(&self) -> usize {
2391 self.values.limits.max_upload_size.as_bytes()
2392 }
2393
2394 pub fn max_attachments_size(&self) -> usize {
2397 self.values.limits.max_attachments_size.as_bytes()
2398 }
2399
2400 pub fn max_client_reports_size(&self) -> usize {
2402 self.values.limits.max_client_reports_size.as_bytes()
2403 }
2404
2405 pub fn max_check_in_size(&self) -> usize {
2407 self.values.limits.max_check_in_size.as_bytes()
2408 }
2409
2410 pub fn max_log_size(&self) -> usize {
2412 self.values.limits.max_log_size.as_bytes()
2413 }
2414
2415 pub fn max_span_size(&self) -> usize {
2417 self.values.limits.max_span_size.as_bytes()
2418 }
2419
2420 pub fn max_container_size(&self) -> usize {
2422 self.values.limits.max_container_size.as_bytes()
2423 }
2424
2425 pub fn max_logs_integration_size(&self) -> usize {
2427 self.max_container_size()
2429 }
2430
2431 pub fn max_spans_integration_size(&self) -> usize {
2433 self.max_container_size()
2435 }
2436
2437 pub fn max_envelope_size(&self) -> usize {
2441 self.values.limits.max_envelope_size.as_bytes()
2442 }
2443
2444 pub fn max_session_count(&self) -> usize {
2446 self.values.limits.max_session_count
2447 }
2448
2449 pub fn max_statsd_size(&self) -> usize {
2451 self.values.limits.max_statsd_size.as_bytes()
2452 }
2453
2454 pub fn max_metric_buckets_size(&self) -> usize {
2456 self.values.limits.max_metric_buckets_size.as_bytes()
2457 }
2458
2459 pub fn max_api_payload_size(&self) -> usize {
2461 self.values.limits.max_api_payload_size.as_bytes()
2462 }
2463
2464 pub fn max_api_file_upload_size(&self) -> usize {
2466 self.values.limits.max_api_file_upload_size.as_bytes()
2467 }
2468
2469 pub fn max_api_chunk_upload_size(&self) -> usize {
2471 self.values.limits.max_api_chunk_upload_size.as_bytes()
2472 }
2473
2474 pub fn max_profile_size(&self) -> usize {
2476 self.values.limits.max_profile_size.as_bytes()
2477 }
2478
2479 pub fn max_trace_metric_size(&self) -> usize {
2481 self.values.limits.max_trace_metric_size.as_bytes()
2482 }
2483
2484 pub fn max_replay_compressed_size(&self) -> usize {
2486 self.values.limits.max_replay_compressed_size.as_bytes()
2487 }
2488
2489 pub fn max_replay_uncompressed_size(&self) -> usize {
2491 self.values.limits.max_replay_uncompressed_size.as_bytes()
2492 }
2493
2494 pub fn max_replay_message_size(&self) -> usize {
2500 self.values.limits.max_replay_message_size.as_bytes()
2501 }
2502
2503 pub fn max_concurrent_requests(&self) -> usize {
2505 self.values.limits.max_concurrent_requests
2506 }
2507
2508 pub fn max_concurrent_queries(&self) -> usize {
2510 self.values.limits.max_concurrent_queries
2511 }
2512
2513 pub fn max_removed_attribute_key_size(&self) -> usize {
2515 self.values.limits.max_removed_attribute_key_size.as_bytes()
2516 }
2517
2518 pub fn query_timeout(&self) -> Duration {
2520 Duration::from_secs(self.values.limits.query_timeout)
2521 }
2522
2523 pub fn shutdown_timeout(&self) -> Duration {
2526 Duration::from_secs(self.values.limits.shutdown_timeout)
2527 }
2528
2529 pub fn keepalive_timeout(&self) -> Duration {
2533 Duration::from_secs(self.values.limits.keepalive_timeout)
2534 }
2535
2536 pub fn idle_timeout(&self) -> Option<Duration> {
2538 self.values.limits.idle_timeout.map(Duration::from_secs)
2539 }
2540
2541 pub fn max_connections(&self) -> Option<usize> {
2543 self.values.limits.max_connections
2544 }
2545
2546 pub fn tcp_listen_backlog(&self) -> u32 {
2548 self.values.limits.tcp_listen_backlog
2549 }
2550
2551 pub fn cpu_concurrency(&self) -> usize {
2553 self.values.limits.max_thread_count
2554 }
2555
2556 pub fn pool_concurrency(&self) -> usize {
2558 self.values.limits.max_pool_concurrency
2559 }
2560
2561 pub fn query_batch_size(&self) -> usize {
2563 self.values.cache.batch_size
2564 }
2565
2566 pub fn project_configs_path(&self) -> PathBuf {
2568 self.path.join("projects")
2569 }
2570
2571 pub fn processing_enabled(&self) -> bool {
2573 self.values.processing.enabled
2574 }
2575
2576 pub fn normalization_level(&self) -> NormalizationLevel {
2578 self.values.normalization.level
2579 }
2580
2581 pub fn geoip_path(&self) -> Option<&Path> {
2583 self.values
2584 .geoip
2585 .path
2586 .as_deref()
2587 .or(self.values.processing.geoip_path.as_deref())
2588 }
2589
2590 pub fn max_secs_in_future(&self) -> i64 {
2594 self.values.processing.max_secs_in_future.into()
2595 }
2596
2597 pub fn max_session_secs_in_past(&self) -> i64 {
2599 self.values.processing.max_session_secs_in_past.into()
2600 }
2601
2602 pub fn kafka_configs(
2604 &self,
2605 topic: KafkaTopic,
2606 ) -> Result<KafkaTopicConfig<'_>, KafkaConfigError> {
2607 self.values.processing.topics.get(topic).kafka_configs(
2608 &self.values.processing.kafka_config,
2609 &self.values.processing.secondary_kafka_configs,
2610 )
2611 }
2612
2613 pub fn kafka_validate_topics(&self) -> bool {
2615 self.values.processing.kafka_validate_topics
2616 }
2617
2618 pub fn unused_topic_assignments(&self) -> &relay_kafka::Unused {
2620 &self.values.processing.topics.unused
2621 }
2622
2623 pub fn objectstore(&self) -> &ObjectstoreServiceConfig {
2625 &self.values.processing.objectstore
2626 }
2627
2628 pub fn upload(&self) -> &Upload {
2630 &self.values.upload
2631 }
2632
2633 #[cfg(feature = "processing")]
2635 pub fn upload_signing_key(&self) -> Option<&SecretKey> {
2636 self.upload()
2637 .credentials
2638 .as_ref()
2639 .map(|c| &c.signing_key)
2640 .or(self.credentials().map(|c| &c.secret_key))
2641 }
2642
2643 pub fn redis(&self) -> Option<RedisConfigsRef<'_>> {
2646 let redis_configs = self.values.processing.redis.as_ref()?;
2647
2648 Some(build_redis_configs(
2649 redis_configs,
2650 self.cpu_concurrency() as u32,
2651 self.pool_concurrency() as u32,
2652 ))
2653 }
2654
2655 pub fn attachment_chunk_size(&self) -> usize {
2657 self.values.processing.attachment_chunk_size.as_bytes()
2658 }
2659
2660 pub fn metrics_max_batch_size_bytes(&self) -> usize {
2662 self.values.aggregator.max_flush_bytes
2663 }
2664
2665 pub fn projectconfig_cache_prefix(&self) -> &str {
2668 &self.values.processing.projectconfig_cache_prefix
2669 }
2670
2671 pub fn max_rate_limit(&self) -> Option<u64> {
2673 self.values.processing.max_rate_limit.map(u32::into)
2674 }
2675
2676 pub fn quota_cache_ratio(&self) -> Option<f32> {
2678 self.values.processing.quota_cache_ratio
2679 }
2680
2681 pub fn quota_cache_max(&self) -> Option<f32> {
2683 self.values.processing.quota_cache_max
2684 }
2685
2686 pub fn cardinality_limiter_cache_vacuum_interval(&self) -> Duration {
2690 Duration::from_secs(self.values.cardinality_limiter.cache_vacuum_interval)
2691 }
2692
2693 pub fn health_refresh_interval(&self) -> Duration {
2695 Duration::from_millis(self.values.health.refresh_interval_ms)
2696 }
2697
2698 pub fn health_max_memory_watermark_bytes(&self) -> u64 {
2700 self.values
2701 .health
2702 .max_memory_bytes
2703 .as_ref()
2704 .map_or(u64::MAX, |b| b.as_bytes() as u64)
2705 }
2706
2707 pub fn health_max_memory_watermark_percent(&self) -> f32 {
2709 self.values.health.max_memory_percent
2710 }
2711
2712 pub fn health_probe_timeout(&self) -> Duration {
2714 Duration::from_millis(self.values.health.probe_timeout_ms)
2715 }
2716
2717 pub fn memory_stat_refresh_frequency_ms(&self) -> u64 {
2719 self.values.health.memory_stat_refresh_frequency_ms
2720 }
2721
2722 pub fn cogs_max_queue_size(&self) -> u64 {
2724 self.values.cogs.max_queue_size
2725 }
2726
2727 pub fn cogs_relay_resource_id(&self) -> &str {
2729 &self.values.cogs.relay_resource_id
2730 }
2731
2732 pub fn default_aggregator_config(&self) -> &AggregatorServiceConfig {
2734 &self.values.aggregator
2735 }
2736
2737 pub fn secondary_aggregator_configs(&self) -> &Vec<ScopedAggregatorConfig> {
2739 &self.values.secondary_aggregators
2740 }
2741
2742 pub fn aggregator_config_for(&self, namespace: MetricNamespace) -> &AggregatorServiceConfig {
2744 for entry in &self.values.secondary_aggregators {
2745 if entry.condition.matches(Some(namespace)) {
2746 return &entry.config;
2747 }
2748 }
2749 &self.values.aggregator
2750 }
2751
2752 pub fn static_relays(&self) -> &HashMap<RelayId, RelayInfo> {
2754 &self.values.auth.static_relays
2755 }
2756
2757 pub fn signature_max_age(&self) -> Duration {
2759 Duration::from_secs(self.values.auth.signature_max_age)
2760 }
2761
2762 pub fn accept_unknown_items(&self) -> bool {
2764 let forward = self.values.routing.accept_unknown_items;
2765 forward.unwrap_or_else(|| !self.processing_enabled())
2766 }
2767}
2768
2769impl Default for Config {
2770 fn default() -> Self {
2771 Self {
2772 values: ConfigValues::default(),
2773 credentials: None,
2774 path: PathBuf::new(),
2775 }
2776 }
2777}
2778
2779#[cfg(test)]
2780mod tests {
2781 use super::*;
2782
2783 #[test]
2785 fn test_event_buffer_size() {
2786 let yaml = r###"
2787cache:
2788 event_buffer_size: 1000000
2789 event_expiry: 1800
2790"###;
2791
2792 let values: ConfigValues = serde_yaml::from_str(yaml).unwrap();
2793 assert_eq!(values.cache.envelope_buffer_size, 1_000_000);
2794 assert_eq!(values.cache.envelope_expiry, 1800);
2795 }
2796
2797 #[cfg(feature = "processing")]
2798 #[test]
2799 fn test_upload_secret_key_from_file() {
2800 let path = env::temp_dir().join(Uuid::new_v4().to_string());
2801 fs::create_dir(&path).unwrap();
2802 fs::write(
2803 path.join("my_secret.txt"),
2804 "U3LSQM5NorvgnoYHW_aZpc_43nuuh3lhs3zjjcBwaks",
2805 )
2806 .unwrap();
2807 fs::write(
2808 ConfigValues::path(&path),
2809 r#"
2810upload:
2811 credentials:
2812 signing_key: ${file:my_secret.txt}
2813 verification_key: "VNS8haF0VTnuMMDR2t-f7AgnmUcXmcdzV3SVksSk34s""#,
2814 )
2815 .unwrap();
2816
2817 let config = Config::from_path(&path).unwrap();
2818
2819 fs::remove_dir_all(path).unwrap();
2820
2821 let signing_key = &config.upload().credentials.as_ref().unwrap().signing_key;
2822 assert_eq!(
2823 signing_key.to_string(),
2824 "U3LSQM5NorvgnoYHW_aZpc_43nuuh3lhs3zjjcBwaks"
2825 );
2826 }
2827
2828 #[test]
2829 fn test_emit_outcomes() {
2830 for (serialized, deserialized) in &[
2831 ("true", EmitOutcomes::AsOutcomes),
2832 ("false", EmitOutcomes::None),
2833 ("\"as_client_reports\"", EmitOutcomes::AsClientReports),
2834 ] {
2835 let value: EmitOutcomes = serde_json::from_str(serialized).unwrap();
2836 assert_eq!(value, *deserialized);
2837 assert_eq!(serde_json::to_string(&value).unwrap(), *serialized);
2838 }
2839 }
2840
2841 #[test]
2842 fn test_emit_outcomes_invalid() {
2843 assert!(serde_json::from_str::<EmitOutcomes>("asdf").is_err());
2844 }
2845}