1use std::collections::{BTreeMap, HashMap};
2use std::error::Error;
3use std::io::Write;
4use std::net::{IpAddr, SocketAddr};
5use std::num::NonZeroU8;
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 (sk, pk) = generate_key_pair();
285 Self {
286 secret_key: sk,
287 public_key: pk,
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<'static>,
495 pub host: IpAddr,
497 pub port: u16,
499 pub internal_host: Option<IpAddr>,
513 pub internal_port: Option<u16>,
517 #[serde(skip_serializing)]
519 pub tls_port: Option<u16>,
520 #[serde(skip_serializing)]
522 pub tls_identity_path: Option<PathBuf>,
523 #[serde(skip_serializing)]
525 pub tls_identity_password: Option<String>,
526 #[serde(skip_serializing_if = "is_default")]
531 pub override_project_ids: bool,
532}
533
534impl Default for Relay {
535 fn default() -> Self {
536 Relay {
537 mode: RelayMode::Managed,
538 instance: RelayInstance::Default,
539 upstream: "https://sentry.io/".parse().unwrap(),
540 host: default_host(),
541 port: 3000,
542 internal_host: None,
543 internal_port: None,
544 tls_port: None,
545 tls_identity_path: None,
546 tls_identity_password: None,
547 override_project_ids: false,
548 }
549 }
550}
551
552#[derive(Serialize, Deserialize, Debug)]
554#[serde(default)]
555pub struct Metrics {
556 pub statsd: Option<String>,
560 pub statsd_buffer_size: Option<usize>,
564 pub prefix: String,
568 pub default_tags: BTreeMap<String, String>,
570 pub hostname_tag: Option<String>,
572 pub periodic_secs: u64,
577}
578
579impl Default for Metrics {
580 fn default() -> Self {
581 Metrics {
582 statsd: None,
583 statsd_buffer_size: None,
584 prefix: "sentry.relay".into(),
585 default_tags: BTreeMap::new(),
586 hostname_tag: None,
587 periodic_secs: 5,
588 }
589 }
590}
591
592#[derive(Serialize, Deserialize, Debug)]
594#[serde(default)]
595pub struct Limits {
596 pub max_concurrent_requests: usize,
599 pub max_concurrent_queries: usize,
604 pub max_event_size: ByteSize,
606 pub max_attachment_size: ByteSize,
608 pub max_upload_size: ByteSize,
610 pub max_attachments_size: ByteSize,
612 pub max_client_reports_size: ByteSize,
614 pub max_check_in_size: ByteSize,
616 pub max_envelope_size: ByteSize,
618 pub max_session_count: usize,
620 pub max_api_payload_size: ByteSize,
622 pub max_api_file_upload_size: ByteSize,
624 pub max_api_chunk_upload_size: ByteSize,
626 pub max_profile_size: ByteSize,
628 pub max_trace_metric_size: ByteSize,
630 pub max_log_size: ByteSize,
632 pub max_span_size: ByteSize,
634 pub max_container_size: ByteSize,
636 pub max_statsd_size: ByteSize,
638 pub max_metric_buckets_size: ByteSize,
640 pub max_replay_compressed_size: ByteSize,
642 #[serde(alias = "max_replay_size")]
644 max_replay_uncompressed_size: ByteSize,
645 pub max_replay_message_size: ByteSize,
647 pub max_removed_attribute_key_size: ByteSize,
657 pub max_thread_count: usize,
662 pub max_pool_concurrency: usize,
669 pub query_timeout: u64,
672 pub shutdown_timeout: u64,
675 pub keepalive_timeout: u64,
679 pub idle_timeout: Option<u64>,
686 pub max_connections: Option<usize>,
692 pub tcp_listen_backlog: u32,
700}
701
702impl Default for Limits {
703 fn default() -> Self {
704 Limits {
705 max_concurrent_requests: 100,
706 max_concurrent_queries: 5,
707 max_event_size: ByteSize::mebibytes(1),
708 max_attachment_size: ByteSize::mebibytes(200),
709 max_upload_size: ByteSize::mebibytes(1024),
710 max_attachments_size: ByteSize::mebibytes(200),
711 max_client_reports_size: ByteSize::kibibytes(4),
712 max_check_in_size: ByteSize::kibibytes(100),
713 max_envelope_size: ByteSize::mebibytes(200),
714 max_session_count: 100,
715 max_api_payload_size: ByteSize::mebibytes(20),
716 max_api_file_upload_size: ByteSize::mebibytes(40),
717 max_api_chunk_upload_size: ByteSize::mebibytes(100),
718 max_profile_size: ByteSize::mebibytes(50),
719 max_trace_metric_size: ByteSize::kibibytes(2),
720 max_log_size: ByteSize::mebibytes(1),
721 max_span_size: ByteSize::mebibytes(1),
722 max_container_size: ByteSize::mebibytes(12),
723 max_statsd_size: ByteSize::mebibytes(1),
724 max_metric_buckets_size: ByteSize::mebibytes(1),
725 max_replay_compressed_size: ByteSize::mebibytes(10),
726 max_replay_uncompressed_size: ByteSize::mebibytes(100),
727 max_replay_message_size: ByteSize::mebibytes(15),
728 max_thread_count: num_cpus::get(),
729 max_pool_concurrency: 1,
730 query_timeout: 30,
731 shutdown_timeout: 10,
732 keepalive_timeout: 5,
733 idle_timeout: None,
734 max_connections: None,
735 tcp_listen_backlog: 1024,
736 max_removed_attribute_key_size: ByteSize::kibibytes(10),
737 }
738 }
739}
740
741#[derive(Debug, Default, Deserialize, Serialize)]
743#[serde(default)]
744pub struct Routing {
745 pub accept_unknown_items: Option<bool>,
755}
756
757#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)]
759#[serde(rename_all = "lowercase")]
760pub enum HttpEncoding {
761 #[default]
766 Identity,
767 Deflate,
773 Gzip,
780 Br,
782 Zstd,
784}
785
786impl HttpEncoding {
787 pub fn parse(str: &str) -> Self {
789 let str = str.trim();
790 if str.eq_ignore_ascii_case("zstd") {
791 Self::Zstd
792 } else if str.eq_ignore_ascii_case("br") {
793 Self::Br
794 } else if str.eq_ignore_ascii_case("gzip") || str.eq_ignore_ascii_case("x-gzip") {
795 Self::Gzip
796 } else if str.eq_ignore_ascii_case("deflate") {
797 Self::Deflate
798 } else {
799 Self::Identity
800 }
801 }
802
803 pub fn name(&self) -> Option<&'static str> {
807 match self {
808 Self::Identity => None,
809 Self::Deflate => Some("deflate"),
810 Self::Gzip => Some("gzip"),
811 Self::Br => Some("br"),
812 Self::Zstd => Some("zstd"),
813 }
814 }
815}
816
817#[derive(Serialize, Deserialize, Debug)]
819#[serde(default)]
820pub struct Http {
821 pub timeout: u32,
827 pub connection_timeout: u32,
832 pub max_retry_interval: u32,
834 pub host_header: Option<String>,
836 pub auth_interval: Option<u64>,
844 pub outage_grace_period: u64,
850 pub retry_delay: u64,
854 pub project_failure_interval: u64,
859 pub encoding: HttpEncoding,
875 pub global_metrics: bool,
882 pub forward: bool,
886 pub dns_cache: bool,
890}
891
892impl Default for Http {
893 fn default() -> Self {
894 Http {
895 timeout: 5,
896 connection_timeout: 3,
897 max_retry_interval: 60, host_header: None,
899 auth_interval: Some(600), outage_grace_period: DEFAULT_NETWORK_OUTAGE_GRACE_PERIOD,
901 retry_delay: default_retry_delay(),
902 project_failure_interval: default_project_failure_interval(),
903 encoding: HttpEncoding::Zstd,
904 global_metrics: false,
905 forward: true,
906 dns_cache: true,
907 }
908 }
909}
910
911fn default_retry_delay() -> u64 {
913 1
914}
915
916fn default_project_failure_interval() -> u64 {
918 90
919}
920
921fn spool_envelopes_max_disk_size() -> ByteSize {
923 ByteSize::mebibytes(500)
924}
925
926fn spool_envelopes_batch_size_bytes() -> ByteSize {
928 ByteSize::kibibytes(10)
929}
930
931fn spool_envelopes_max_envelope_delay_secs() -> u64 {
932 24 * 60 * 60
933}
934
935fn spool_disk_usage_refresh_frequency_ms() -> u64 {
937 100
938}
939
940fn spool_max_backpressure_memory_percent() -> f32 {
942 0.8
943}
944
945fn spool_envelopes_partitions() -> NonZeroU8 {
947 NonZeroU8::new(1).unwrap()
948}
949
950#[derive(Debug, Serialize, Deserialize)]
952pub struct EnvelopeSpool {
953 pub path: Option<PathBuf>,
959 #[serde(default = "spool_envelopes_max_disk_size")]
965 pub max_disk_size: ByteSize,
966 #[serde(default = "spool_envelopes_batch_size_bytes")]
973 pub batch_size_bytes: ByteSize,
974 #[serde(default = "spool_envelopes_max_envelope_delay_secs")]
981 pub max_envelope_delay_secs: u64,
982 #[serde(default = "spool_disk_usage_refresh_frequency_ms")]
987 pub disk_usage_refresh_frequency_ms: u64,
988 #[serde(default = "spool_max_backpressure_memory_percent")]
1018 pub max_backpressure_memory_percent: f32,
1019 #[serde(default = "spool_envelopes_partitions")]
1026 pub partitions: NonZeroU8,
1027 #[serde(default)]
1034 pub ephemeral: bool,
1035}
1036
1037impl Default for EnvelopeSpool {
1038 fn default() -> Self {
1039 Self {
1040 path: None,
1041 max_disk_size: spool_envelopes_max_disk_size(),
1042 batch_size_bytes: spool_envelopes_batch_size_bytes(),
1043 max_envelope_delay_secs: spool_envelopes_max_envelope_delay_secs(),
1044 disk_usage_refresh_frequency_ms: spool_disk_usage_refresh_frequency_ms(),
1045 max_backpressure_memory_percent: spool_max_backpressure_memory_percent(),
1046 partitions: spool_envelopes_partitions(),
1047 ephemeral: false,
1048 }
1049 }
1050}
1051
1052#[derive(Debug, Serialize, Deserialize, Default)]
1054pub struct Spool {
1055 #[serde(default)]
1057 pub envelopes: EnvelopeSpool,
1058}
1059
1060#[derive(Serialize, Deserialize, Debug)]
1062#[serde(default)]
1063pub struct Cache {
1064 pub project_request_full_config: bool,
1066 pub project_expiry: u32,
1068 pub project_grace_period: u32,
1073 pub project_refresh_interval: Option<u32>,
1079 pub relay_expiry: u32,
1081 #[serde(alias = "event_expiry")]
1087 envelope_expiry: u32,
1088 #[serde(alias = "event_buffer_size")]
1090 envelope_buffer_size: u32,
1091 pub miss_expiry: u32,
1093 pub batch_interval: u32,
1095 pub downstream_relays_batch_interval: u32,
1097 pub batch_size: usize,
1101 pub file_interval: u32,
1103 pub global_config_fetch_interval: u32,
1105}
1106
1107impl Default for Cache {
1108 fn default() -> Self {
1109 Cache {
1110 project_request_full_config: false,
1111 project_expiry: 300, project_grace_period: 120, project_refresh_interval: None,
1114 relay_expiry: 3600, envelope_expiry: 600, envelope_buffer_size: 1000,
1117 miss_expiry: 60, batch_interval: 100, downstream_relays_batch_interval: 100, batch_size: 500,
1121 file_interval: 10, global_config_fetch_interval: 10, }
1124 }
1125}
1126
1127fn default_max_secs_in_future() -> u32 {
1128 60 }
1130
1131fn default_max_session_secs_in_past() -> u32 {
1132 5 * 24 * 3600 }
1134
1135fn default_chunk_size() -> ByteSize {
1136 ByteSize::mebibytes(1)
1137}
1138
1139fn default_projectconfig_cache_prefix() -> String {
1140 "relayconfig".to_owned()
1141}
1142
1143#[allow(clippy::unnecessary_wraps)]
1144fn default_max_rate_limit() -> Option<u32> {
1145 Some(300) }
1147
1148#[derive(Serialize, Deserialize, Debug)]
1150pub struct Processing {
1151 pub enabled: bool,
1153 #[serde(default)]
1155 pub geoip_path: Option<PathBuf>,
1156 #[serde(default = "default_max_secs_in_future")]
1158 pub max_secs_in_future: u32,
1159 #[serde(default = "default_max_session_secs_in_past")]
1161 pub max_session_secs_in_past: u32,
1162 pub kafka_config: Vec<KafkaConfigParam>,
1164 #[serde(default)]
1184 pub secondary_kafka_configs: BTreeMap<String, Vec<KafkaConfigParam>>,
1185 #[serde(default)]
1187 pub topics: TopicAssignments,
1188 #[serde(default)]
1190 pub kafka_validate_topics: bool,
1191 #[serde(default)]
1193 pub redis: Option<RedisConfigs>,
1194 #[serde(default = "default_chunk_size")]
1196 pub attachment_chunk_size: ByteSize,
1197 #[serde(default = "default_projectconfig_cache_prefix")]
1199 pub projectconfig_cache_prefix: String,
1200 #[serde(default = "default_max_rate_limit")]
1202 pub max_rate_limit: Option<u32>,
1203 pub quota_cache_ratio: Option<f32>,
1214 pub quota_cache_max: Option<f32>,
1221 #[serde(default, alias = "upload")]
1223 pub objectstore: ObjectstoreServiceConfig,
1224}
1225
1226impl Default for Processing {
1227 fn default() -> Self {
1229 Self {
1230 enabled: false,
1231 geoip_path: None,
1232 max_secs_in_future: default_max_secs_in_future(),
1233 max_session_secs_in_past: default_max_session_secs_in_past(),
1234 kafka_config: Vec::new(),
1235 secondary_kafka_configs: BTreeMap::new(),
1236 topics: TopicAssignments::default(),
1237 kafka_validate_topics: false,
1238 redis: None,
1239 attachment_chunk_size: default_chunk_size(),
1240 projectconfig_cache_prefix: default_projectconfig_cache_prefix(),
1241 max_rate_limit: default_max_rate_limit(),
1242 quota_cache_ratio: None,
1243 quota_cache_max: None,
1244 objectstore: ObjectstoreServiceConfig::default(),
1245 }
1246 }
1247}
1248
1249#[derive(Debug, Default, Serialize, Deserialize)]
1251#[serde(default)]
1252pub struct Normalization {
1253 #[serde(default)]
1255 pub level: NormalizationLevel,
1256}
1257
1258#[derive(Copy, Clone, Debug, Default, Serialize, Deserialize, Eq, PartialEq)]
1260#[serde(rename_all = "lowercase")]
1261pub enum NormalizationLevel {
1262 #[default]
1266 Default,
1267 Full,
1272}
1273
1274#[derive(Serialize, Deserialize, Debug)]
1276#[serde(default)]
1277pub struct OutcomeAggregatorConfig {
1278 pub bucket_interval: u64,
1280 pub flush_interval: u64,
1282}
1283
1284impl Default for OutcomeAggregatorConfig {
1285 fn default() -> Self {
1286 Self {
1287 bucket_interval: 60,
1288 flush_interval: 120,
1289 }
1290 }
1291}
1292
1293#[derive(Serialize, Deserialize, Debug)]
1295#[serde(default)]
1296pub struct ObjectstoreServiceConfig {
1297 pub objectstore_url: Option<String>,
1302
1303 pub max_concurrent_requests: usize,
1305
1306 pub max_backlog: usize,
1310
1311 pub timeout: u64,
1313}
1314
1315impl Default for ObjectstoreServiceConfig {
1316 fn default() -> Self {
1317 Self {
1318 objectstore_url: None,
1319 max_concurrent_requests: 10,
1320 max_backlog: 20,
1321 timeout: 60,
1322 }
1323 }
1324}
1325
1326#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1329
1330pub enum EmitOutcomes {
1331 None,
1333 AsClientReports,
1335 AsOutcomes,
1337}
1338
1339impl EmitOutcomes {
1340 pub fn any(&self) -> bool {
1342 !matches!(self, EmitOutcomes::None)
1343 }
1344}
1345
1346impl Serialize for EmitOutcomes {
1347 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1348 where
1349 S: Serializer,
1350 {
1351 match self {
1353 Self::None => serializer.serialize_bool(false),
1354 Self::AsClientReports => serializer.serialize_str("as_client_reports"),
1355 Self::AsOutcomes => serializer.serialize_bool(true),
1356 }
1357 }
1358}
1359
1360struct EmitOutcomesVisitor;
1361
1362impl Visitor<'_> for EmitOutcomesVisitor {
1363 type Value = EmitOutcomes;
1364
1365 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1366 formatter.write_str("true, false, or 'as_client_reports'")
1367 }
1368
1369 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
1370 where
1371 E: serde::de::Error,
1372 {
1373 Ok(if v {
1374 EmitOutcomes::AsOutcomes
1375 } else {
1376 EmitOutcomes::None
1377 })
1378 }
1379
1380 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1381 where
1382 E: serde::de::Error,
1383 {
1384 if v == "as_client_reports" {
1385 Ok(EmitOutcomes::AsClientReports)
1386 } else {
1387 Err(E::invalid_value(Unexpected::Str(v), &"as_client_reports"))
1388 }
1389 }
1390}
1391
1392impl<'de> Deserialize<'de> for EmitOutcomes {
1393 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1394 where
1395 D: Deserializer<'de>,
1396 {
1397 deserializer.deserialize_any(EmitOutcomesVisitor)
1398 }
1399}
1400
1401#[derive(Serialize, Deserialize, Debug)]
1403#[serde(default)]
1404pub struct Outcomes {
1405 pub emit_outcomes: EmitOutcomes,
1409 pub batch_size: usize,
1412 pub batch_interval: u64,
1415 pub source: Option<String>,
1418 pub aggregator: OutcomeAggregatorConfig,
1420}
1421
1422impl Default for Outcomes {
1423 fn default() -> Self {
1424 Outcomes {
1425 emit_outcomes: EmitOutcomes::AsClientReports,
1426 batch_size: 1000,
1427 batch_interval: 500,
1428 source: None,
1429 aggregator: OutcomeAggregatorConfig::default(),
1430 }
1431 }
1432}
1433
1434#[derive(Serialize, Deserialize, Debug, Default)]
1436pub struct MinimalConfig {
1437 pub relay: Relay,
1439}
1440
1441impl MinimalConfig {
1442 pub fn save_in_folder<P: AsRef<Path>>(&self, p: P) -> anyhow::Result<()> {
1444 let path = p.as_ref();
1445 if fs::metadata(path).is_err() {
1446 fs::create_dir_all(path)
1447 .with_context(|| ConfigError::file(ConfigErrorKind::CouldNotOpenFile, path))?;
1448 }
1449 self.save(path)
1450 }
1451}
1452
1453impl ConfigObject for MinimalConfig {
1454 fn format() -> ConfigFormat {
1455 ConfigFormat::Yaml
1456 }
1457
1458 fn name() -> &'static str {
1459 "config"
1460 }
1461}
1462
1463mod config_relay_info {
1465 use serde::ser::SerializeMap;
1466
1467 use super::*;
1468
1469 #[derive(Debug, Serialize, Deserialize, Clone)]
1471 struct RelayInfoConfig {
1472 public_key: PublicKey,
1473 #[serde(default)]
1474 internal: bool,
1475 }
1476
1477 impl From<RelayInfoConfig> for RelayInfo {
1478 fn from(v: RelayInfoConfig) -> Self {
1479 RelayInfo {
1480 public_key: v.public_key,
1481 internal: v.internal,
1482 }
1483 }
1484 }
1485
1486 impl From<RelayInfo> for RelayInfoConfig {
1487 fn from(v: RelayInfo) -> Self {
1488 RelayInfoConfig {
1489 public_key: v.public_key,
1490 internal: v.internal,
1491 }
1492 }
1493 }
1494
1495 pub(super) fn deserialize<'de, D>(des: D) -> Result<HashMap<RelayId, RelayInfo>, D::Error>
1496 where
1497 D: Deserializer<'de>,
1498 {
1499 let map = HashMap::<RelayId, RelayInfoConfig>::deserialize(des)?;
1500 Ok(map.into_iter().map(|(k, v)| (k, v.into())).collect())
1501 }
1502
1503 pub(super) fn serialize<S>(elm: &HashMap<RelayId, RelayInfo>, ser: S) -> Result<S::Ok, S::Error>
1504 where
1505 S: Serializer,
1506 {
1507 let mut map = ser.serialize_map(Some(elm.len()))?;
1508
1509 for (k, v) in elm {
1510 map.serialize_entry(k, &RelayInfoConfig::from(v.clone()))?;
1511 }
1512
1513 map.end()
1514 }
1515}
1516
1517#[derive(Serialize, Deserialize, Debug, Default)]
1519pub struct AuthConfig {
1520 #[serde(default, skip_serializing_if = "is_default")]
1522 pub ready: ReadinessCondition,
1523
1524 #[serde(default, with = "config_relay_info")]
1526 pub static_relays: HashMap<RelayId, RelayInfo>,
1527
1528 #[serde(default = "default_max_age")]
1532 pub signature_max_age: u64,
1533}
1534
1535fn default_max_age() -> u64 {
1536 300
1537}
1538
1539#[derive(Serialize, Deserialize, Debug, Default)]
1541pub struct GeoIpConfig {
1542 pub path: Option<PathBuf>,
1544}
1545
1546#[derive(Serialize, Deserialize, Debug)]
1548#[serde(default)]
1549pub struct CardinalityLimiter {
1550 pub cache_vacuum_interval: u64,
1556}
1557
1558impl Default for CardinalityLimiter {
1559 fn default() -> Self {
1560 Self {
1561 cache_vacuum_interval: 180,
1562 }
1563 }
1564}
1565
1566#[derive(Serialize, Deserialize, Debug)]
1571#[serde(default)]
1572pub struct Health {
1573 pub refresh_interval_ms: u64,
1580 pub max_memory_bytes: Option<ByteSize>,
1585 pub max_memory_percent: f32,
1589 pub probe_timeout_ms: u64,
1596 pub memory_stat_refresh_frequency_ms: u64,
1602}
1603
1604impl Default for Health {
1605 fn default() -> Self {
1606 Self {
1607 refresh_interval_ms: 3000,
1608 max_memory_bytes: None,
1609 max_memory_percent: 0.95,
1610 probe_timeout_ms: 900,
1611 memory_stat_refresh_frequency_ms: 100,
1612 }
1613 }
1614}
1615
1616#[derive(Serialize, Deserialize, Debug)]
1618#[serde(default)]
1619pub struct Cogs {
1620 pub max_queue_size: u64,
1626 pub relay_resource_id: String,
1632}
1633
1634impl Default for Cogs {
1635 fn default() -> Self {
1636 Self {
1637 max_queue_size: 10_000,
1638 relay_resource_id: "relay_service".to_owned(),
1639 }
1640 }
1641}
1642
1643#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
1645#[serde(default)]
1646pub struct Upload {
1647 pub max_concurrent_requests: usize,
1651 pub timeout: u64,
1654 pub max_age: i64,
1658}
1659
1660impl Default for Upload {
1661 fn default() -> Self {
1662 Self {
1663 max_concurrent_requests: 10,
1664 timeout: 5 * 60, max_age: 60 * 60, }
1667 }
1668}
1669
1670#[derive(Serialize, Deserialize, Debug, Default)]
1671struct ConfigValues {
1672 #[serde(default)]
1673 relay: Relay,
1674 #[serde(default)]
1675 http: Http,
1676 #[serde(default)]
1677 cache: Cache,
1678 #[serde(default)]
1679 spool: Spool,
1680 #[serde(default)]
1681 limits: Limits,
1682 #[serde(default)]
1683 logging: relay_log::LogConfig,
1684 #[serde(default)]
1685 routing: Routing,
1686 #[serde(default)]
1687 metrics: Metrics,
1688 #[serde(default)]
1689 sentry: relay_log::SentryConfig,
1690 #[serde(default)]
1691 processing: Processing,
1692 #[serde(default)]
1693 outcomes: Outcomes,
1694 #[serde(default)]
1695 aggregator: AggregatorServiceConfig,
1696 #[serde(default)]
1697 secondary_aggregators: Vec<ScopedAggregatorConfig>,
1698 #[serde(default)]
1699 auth: AuthConfig,
1700 #[serde(default)]
1701 geoip: GeoIpConfig,
1702 #[serde(default)]
1703 normalization: Normalization,
1704 #[serde(default)]
1705 cardinality_limiter: CardinalityLimiter,
1706 #[serde(default)]
1707 health: Health,
1708 #[serde(default)]
1709 cogs: Cogs,
1710 #[serde(default)]
1711 upload: Upload,
1712}
1713
1714impl ConfigObject for ConfigValues {
1715 fn format() -> ConfigFormat {
1716 ConfigFormat::Yaml
1717 }
1718
1719 fn name() -> &'static str {
1720 "config"
1721 }
1722}
1723
1724pub struct Config {
1726 values: ConfigValues,
1727 credentials: Option<Credentials>,
1728 path: PathBuf,
1729}
1730
1731impl fmt::Debug for Config {
1732 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1733 f.debug_struct("Config")
1734 .field("path", &self.path)
1735 .field("values", &self.values)
1736 .finish()
1737 }
1738}
1739
1740impl Config {
1741 pub fn from_path<P: AsRef<Path>>(path: P) -> anyhow::Result<Config> {
1743 let path = env::current_dir()
1744 .map(|x| x.join(path.as_ref()))
1745 .unwrap_or_else(|_| path.as_ref().to_path_buf());
1746
1747 let config = Config {
1748 values: ConfigValues::load(&path)?,
1749 credentials: if Credentials::path(&path).exists() {
1750 Some(Credentials::load(&path)?)
1751 } else {
1752 None
1753 },
1754 path: path.clone(),
1755 };
1756
1757 if cfg!(not(feature = "processing")) && config.processing_enabled() {
1758 return Err(ConfigError::file(ConfigErrorKind::ProcessingNotAvailable, &path).into());
1759 }
1760
1761 Ok(config)
1762 }
1763
1764 pub fn from_json_value(value: serde_json::Value) -> anyhow::Result<Config> {
1768 Ok(Config {
1769 values: serde_json::from_value(value)
1770 .with_context(|| ConfigError::new(ConfigErrorKind::BadJson))?,
1771 credentials: None,
1772 path: PathBuf::new(),
1773 })
1774 }
1775
1776 pub fn apply_override(
1779 &mut self,
1780 mut overrides: OverridableConfig,
1781 ) -> anyhow::Result<&mut Self> {
1782 let relay = &mut self.values.relay;
1783
1784 if let Some(mode) = overrides.mode {
1785 relay.mode = mode
1786 .parse::<RelayMode>()
1787 .with_context(|| ConfigError::field("mode"))?;
1788 }
1789
1790 if let Some(deployment) = overrides.instance {
1791 relay.instance = deployment
1792 .parse::<RelayInstance>()
1793 .with_context(|| ConfigError::field("deployment"))?;
1794 }
1795
1796 if let Some(log_level) = overrides.log_level {
1797 self.values.logging.level = log_level.parse()?;
1798 }
1799
1800 if let Some(log_format) = overrides.log_format {
1801 self.values.logging.format = log_format.parse()?;
1802 }
1803
1804 if let Some(upstream) = overrides.upstream {
1805 relay.upstream = upstream
1806 .parse::<UpstreamDescriptor>()
1807 .with_context(|| ConfigError::field("upstream"))?;
1808 } else if let Some(upstream_dsn) = overrides.upstream_dsn {
1809 relay.upstream = upstream_dsn
1810 .parse::<Dsn>()
1811 .map(|dsn| UpstreamDescriptor::from_dsn(&dsn).into_owned())
1812 .with_context(|| ConfigError::field("upstream_dsn"))?;
1813 }
1814
1815 if let Some(host) = overrides.host {
1816 relay.host = host
1817 .parse::<IpAddr>()
1818 .with_context(|| ConfigError::field("host"))?;
1819 }
1820
1821 if let Some(port) = overrides.port {
1822 relay.port = port
1823 .as_str()
1824 .parse()
1825 .with_context(|| ConfigError::field("port"))?;
1826 }
1827
1828 let processing = &mut self.values.processing;
1829 if let Some(enabled) = overrides.processing {
1830 match enabled.to_lowercase().as_str() {
1831 "true" | "1" => processing.enabled = true,
1832 "false" | "0" | "" => processing.enabled = false,
1833 _ => return Err(ConfigError::field("processing").into()),
1834 }
1835 }
1836
1837 if let Some(redis) = overrides.redis_url {
1838 processing.redis = Some(RedisConfigs::Unified(RedisConfig::single(redis)))
1839 }
1840
1841 if let Some(kafka_url) = overrides.kafka_url {
1842 let existing = processing
1843 .kafka_config
1844 .iter_mut()
1845 .find(|e| e.name == "bootstrap.servers");
1846
1847 if let Some(config_param) = existing {
1848 config_param.value = kafka_url;
1849 } else {
1850 processing.kafka_config.push(KafkaConfigParam {
1851 name: "bootstrap.servers".to_owned(),
1852 value: kafka_url,
1853 })
1854 }
1855 }
1856 let id = if let Some(id) = overrides.id {
1858 let id = Uuid::parse_str(&id).with_context(|| ConfigError::field("id"))?;
1859 Some(id)
1860 } else {
1861 None
1862 };
1863 let public_key = if let Some(public_key) = overrides.public_key {
1864 let public_key = public_key
1865 .parse::<PublicKey>()
1866 .with_context(|| ConfigError::field("public_key"))?;
1867 Some(public_key)
1868 } else {
1869 None
1870 };
1871
1872 let secret_key = if let Some(secret_key) = overrides.secret_key {
1873 let secret_key = secret_key
1874 .parse::<SecretKey>()
1875 .with_context(|| ConfigError::field("secret_key"))?;
1876 Some(secret_key)
1877 } else {
1878 None
1879 };
1880 let outcomes = &mut self.values.outcomes;
1881 if overrides.outcome_source.is_some() {
1882 outcomes.source = overrides.outcome_source.take();
1883 }
1884
1885 if let Some(credentials) = &mut self.credentials {
1886 if let Some(id) = id {
1888 credentials.id = id;
1889 }
1890 if let Some(public_key) = public_key {
1891 credentials.public_key = public_key;
1892 }
1893 if let Some(secret_key) = secret_key {
1894 credentials.secret_key = secret_key
1895 }
1896 } else {
1897 match (id, public_key, secret_key) {
1899 (Some(id), Some(public_key), Some(secret_key)) => {
1900 self.credentials = Some(Credentials {
1901 secret_key,
1902 public_key,
1903 id,
1904 })
1905 }
1906 (None, None, None) => {
1907 }
1910 _ => {
1911 return Err(ConfigError::field("incomplete credentials").into());
1912 }
1913 }
1914 }
1915
1916 let limits = &mut self.values.limits;
1917 if let Some(shutdown_timeout) = overrides.shutdown_timeout
1918 && let Ok(shutdown_timeout) = shutdown_timeout.parse::<u64>()
1919 {
1920 limits.shutdown_timeout = shutdown_timeout;
1921 }
1922
1923 if let Some(server_name) = overrides.server_name {
1924 self.values.sentry.server_name = Some(server_name.into());
1925 }
1926
1927 Ok(self)
1928 }
1929
1930 pub fn config_exists<P: AsRef<Path>>(path: P) -> bool {
1932 fs::metadata(ConfigValues::path(path.as_ref())).is_ok()
1933 }
1934
1935 pub fn path(&self) -> &Path {
1937 &self.path
1938 }
1939
1940 pub fn to_yaml_string(&self) -> anyhow::Result<String> {
1942 serde_yaml::to_string(&self.values)
1943 .with_context(|| ConfigError::new(ConfigErrorKind::CouldNotWriteFile))
1944 }
1945
1946 pub fn regenerate_credentials(&mut self, save: bool) -> anyhow::Result<()> {
1950 let creds = Credentials::generate();
1951 if save {
1952 creds.save(&self.path)?;
1953 }
1954 self.credentials = Some(creds);
1955 Ok(())
1956 }
1957
1958 pub fn credentials(&self) -> Option<&Credentials> {
1960 self.credentials.as_ref()
1961 }
1962
1963 pub fn replace_credentials(
1967 &mut self,
1968 credentials: Option<Credentials>,
1969 ) -> anyhow::Result<bool> {
1970 if self.credentials == credentials {
1971 return Ok(false);
1972 }
1973
1974 match credentials {
1975 Some(ref creds) => {
1976 creds.save(&self.path)?;
1977 }
1978 None => {
1979 let path = Credentials::path(&self.path);
1980 if fs::metadata(&path).is_ok() {
1981 fs::remove_file(&path).with_context(|| {
1982 ConfigError::file(ConfigErrorKind::CouldNotWriteFile, &path)
1983 })?;
1984 }
1985 }
1986 }
1987
1988 self.credentials = credentials;
1989 Ok(true)
1990 }
1991
1992 pub fn has_credentials(&self) -> bool {
1994 self.credentials.is_some()
1995 }
1996
1997 pub fn secret_key(&self) -> Option<&SecretKey> {
1999 self.credentials.as_ref().map(|x| &x.secret_key)
2000 }
2001
2002 pub fn public_key(&self) -> Option<&PublicKey> {
2004 self.credentials.as_ref().map(|x| &x.public_key)
2005 }
2006
2007 pub fn relay_id(&self) -> Option<&RelayId> {
2009 self.credentials.as_ref().map(|x| &x.id)
2010 }
2011
2012 pub fn relay_mode(&self) -> RelayMode {
2014 self.values.relay.mode
2015 }
2016
2017 pub fn relay_instance(&self) -> RelayInstance {
2019 self.values.relay.instance
2020 }
2021
2022 pub fn upstream_descriptor(&self) -> &UpstreamDescriptor<'_> {
2024 &self.values.relay.upstream
2025 }
2026
2027 pub fn http_host_header(&self) -> Option<&str> {
2029 self.values.http.host_header.as_deref()
2030 }
2031
2032 pub fn listen_addr(&self) -> SocketAddr {
2034 (self.values.relay.host, self.values.relay.port).into()
2035 }
2036
2037 pub fn listen_addr_internal(&self) -> Option<SocketAddr> {
2045 match (
2046 self.values.relay.internal_host,
2047 self.values.relay.internal_port,
2048 ) {
2049 (Some(host), None) => Some((host, self.values.relay.port).into()),
2050 (None, Some(port)) => Some((self.values.relay.host, port).into()),
2051 (Some(host), Some(port)) => Some((host, port).into()),
2052 (None, None) => None,
2053 }
2054 }
2055
2056 pub fn tls_listen_addr(&self) -> Option<SocketAddr> {
2058 if self.values.relay.tls_identity_path.is_some() {
2059 let port = self.values.relay.tls_port.unwrap_or(3443);
2060 Some((self.values.relay.host, port).into())
2061 } else {
2062 None
2063 }
2064 }
2065
2066 pub fn tls_identity_path(&self) -> Option<&Path> {
2068 self.values.relay.tls_identity_path.as_deref()
2069 }
2070
2071 pub fn tls_identity_password(&self) -> Option<&str> {
2073 self.values.relay.tls_identity_password.as_deref()
2074 }
2075
2076 pub fn override_project_ids(&self) -> bool {
2080 self.values.relay.override_project_ids
2081 }
2082
2083 pub fn requires_auth(&self) -> bool {
2087 match self.values.auth.ready {
2088 ReadinessCondition::Authenticated => self.relay_mode() == RelayMode::Managed,
2089 ReadinessCondition::Always => false,
2090 }
2091 }
2092
2093 pub fn http_auth_interval(&self) -> Option<Duration> {
2097 if self.processing_enabled() {
2098 return None;
2099 }
2100
2101 match self.values.http.auth_interval {
2102 None | Some(0) => None,
2103 Some(secs) => Some(Duration::from_secs(secs)),
2104 }
2105 }
2106
2107 pub fn http_outage_grace_period(&self) -> Duration {
2110 Duration::from_secs(self.values.http.outage_grace_period)
2111 }
2112
2113 pub fn http_retry_delay(&self) -> Duration {
2118 Duration::from_secs(self.values.http.retry_delay)
2119 }
2120
2121 pub fn http_project_failure_interval(&self) -> Duration {
2123 Duration::from_secs(self.values.http.project_failure_interval)
2124 }
2125
2126 pub fn http_encoding(&self) -> HttpEncoding {
2128 self.values.http.encoding
2129 }
2130
2131 pub fn http_global_metrics(&self) -> bool {
2133 self.values.http.global_metrics
2134 }
2135
2136 pub fn http_forward(&self) -> bool {
2138 self.values.http.forward
2139 }
2140
2141 pub fn emit_outcomes(&self) -> EmitOutcomes {
2146 if self.processing_enabled() {
2147 return EmitOutcomes::AsOutcomes;
2148 }
2149 self.values.outcomes.emit_outcomes
2150 }
2151
2152 pub fn outcome_batch_size(&self) -> usize {
2154 self.values.outcomes.batch_size
2155 }
2156
2157 pub fn outcome_batch_interval(&self) -> Duration {
2159 Duration::from_millis(self.values.outcomes.batch_interval)
2160 }
2161
2162 pub fn outcome_source(&self) -> Option<&str> {
2164 self.values.outcomes.source.as_deref()
2165 }
2166
2167 pub fn outcome_aggregator(&self) -> &OutcomeAggregatorConfig {
2169 &self.values.outcomes.aggregator
2170 }
2171
2172 pub fn logging(&self) -> &relay_log::LogConfig {
2174 &self.values.logging
2175 }
2176
2177 pub fn sentry(&self) -> &relay_log::SentryConfig {
2179 &self.values.sentry
2180 }
2181
2182 pub fn statsd_addr(&self) -> Option<&str> {
2184 self.values.metrics.statsd.as_deref()
2185 }
2186
2187 pub fn statsd_buffer_size(&self) -> Option<usize> {
2189 self.values.metrics.statsd_buffer_size
2190 }
2191
2192 pub fn metrics_prefix(&self) -> &str {
2194 &self.values.metrics.prefix
2195 }
2196
2197 pub fn metrics_default_tags(&self) -> &BTreeMap<String, String> {
2199 &self.values.metrics.default_tags
2200 }
2201
2202 pub fn metrics_hostname_tag(&self) -> Option<&str> {
2204 self.values.metrics.hostname_tag.as_deref()
2205 }
2206
2207 pub fn metrics_periodic_interval(&self) -> Option<Duration> {
2211 match self.values.metrics.periodic_secs {
2212 0 => None,
2213 secs => Some(Duration::from_secs(secs)),
2214 }
2215 }
2216
2217 pub fn http_timeout(&self) -> Duration {
2219 Duration::from_secs(self.values.http.timeout.into())
2220 }
2221
2222 pub fn http_connection_timeout(&self) -> Duration {
2224 Duration::from_secs(self.values.http.connection_timeout.into())
2225 }
2226
2227 pub fn http_max_retry_interval(&self) -> Duration {
2229 Duration::from_secs(self.values.http.max_retry_interval.into())
2230 }
2231
2232 pub fn http_dns_cache(&self) -> bool {
2234 self.values.http.dns_cache
2235 }
2236
2237 pub fn project_cache_expiry(&self) -> Duration {
2239 Duration::from_secs(self.values.cache.project_expiry.into())
2240 }
2241
2242 pub fn request_full_project_config(&self) -> bool {
2244 self.values.cache.project_request_full_config
2245 }
2246
2247 pub fn relay_cache_expiry(&self) -> Duration {
2249 Duration::from_secs(self.values.cache.relay_expiry.into())
2250 }
2251
2252 pub fn envelope_buffer_size(&self) -> usize {
2254 self.values
2255 .cache
2256 .envelope_buffer_size
2257 .try_into()
2258 .unwrap_or(usize::MAX)
2259 }
2260
2261 pub fn cache_miss_expiry(&self) -> Duration {
2263 Duration::from_secs(self.values.cache.miss_expiry.into())
2264 }
2265
2266 pub fn project_grace_period(&self) -> Duration {
2268 Duration::from_secs(self.values.cache.project_grace_period.into())
2269 }
2270
2271 pub fn project_refresh_interval(&self) -> Option<Duration> {
2275 self.values
2276 .cache
2277 .project_refresh_interval
2278 .map(Into::into)
2279 .map(Duration::from_secs)
2280 }
2281
2282 pub fn query_batch_interval(&self) -> Duration {
2285 Duration::from_millis(self.values.cache.batch_interval.into())
2286 }
2287
2288 pub fn downstream_relays_batch_interval(&self) -> Duration {
2290 Duration::from_millis(self.values.cache.downstream_relays_batch_interval.into())
2291 }
2292
2293 pub fn local_cache_interval(&self) -> Duration {
2295 Duration::from_secs(self.values.cache.file_interval.into())
2296 }
2297
2298 pub fn global_config_fetch_interval(&self) -> Duration {
2301 Duration::from_secs(self.values.cache.global_config_fetch_interval.into())
2302 }
2303
2304 pub fn spool_envelopes_path(&self, partition_id: u8) -> Option<PathBuf> {
2309 let mut path = self
2310 .values
2311 .spool
2312 .envelopes
2313 .path
2314 .as_ref()
2315 .map(|path| path.to_owned())?;
2316
2317 if partition_id == 0 {
2318 return Some(path);
2319 }
2320
2321 let file_name = path.file_name().and_then(|f| f.to_str())?;
2322 let new_file_name = format!("{file_name}.{partition_id}");
2323 path.set_file_name(new_file_name);
2324
2325 Some(path)
2326 }
2327
2328 pub fn spool_envelopes_max_disk_size(&self) -> usize {
2330 self.values.spool.envelopes.max_disk_size.as_bytes()
2331 }
2332
2333 pub fn spool_envelopes_batch_size_bytes(&self) -> usize {
2336 self.values.spool.envelopes.batch_size_bytes.as_bytes()
2337 }
2338
2339 pub fn spool_envelopes_max_age(&self) -> Duration {
2341 Duration::from_secs(self.values.spool.envelopes.max_envelope_delay_secs)
2342 }
2343
2344 pub fn spool_disk_usage_refresh_frequency_ms(&self) -> Duration {
2346 Duration::from_millis(self.values.spool.envelopes.disk_usage_refresh_frequency_ms)
2347 }
2348
2349 pub fn spool_max_backpressure_memory_percent(&self) -> f32 {
2351 self.values.spool.envelopes.max_backpressure_memory_percent
2352 }
2353
2354 pub fn spool_partitions(&self) -> NonZeroU8 {
2356 self.values.spool.envelopes.partitions
2357 }
2358
2359 pub fn spool_ephemeral(&self) -> bool {
2361 self.values.spool.envelopes.ephemeral
2362 }
2363
2364 pub fn max_event_size(&self) -> usize {
2366 self.values.limits.max_event_size.as_bytes()
2367 }
2368
2369 pub fn max_attachment_size(&self) -> usize {
2371 self.values.limits.max_attachment_size.as_bytes()
2372 }
2373
2374 pub fn max_upload_size(&self) -> usize {
2376 self.values.limits.max_upload_size.as_bytes()
2377 }
2378
2379 pub fn max_attachments_size(&self) -> usize {
2382 self.values.limits.max_attachments_size.as_bytes()
2383 }
2384
2385 pub fn max_client_reports_size(&self) -> usize {
2387 self.values.limits.max_client_reports_size.as_bytes()
2388 }
2389
2390 pub fn max_check_in_size(&self) -> usize {
2392 self.values.limits.max_check_in_size.as_bytes()
2393 }
2394
2395 pub fn max_log_size(&self) -> usize {
2397 self.values.limits.max_log_size.as_bytes()
2398 }
2399
2400 pub fn max_span_size(&self) -> usize {
2402 self.values.limits.max_span_size.as_bytes()
2403 }
2404
2405 pub fn max_container_size(&self) -> usize {
2407 self.values.limits.max_container_size.as_bytes()
2408 }
2409
2410 pub fn max_logs_integration_size(&self) -> usize {
2412 self.max_container_size()
2414 }
2415
2416 pub fn max_spans_integration_size(&self) -> usize {
2418 self.max_container_size()
2420 }
2421
2422 pub fn max_envelope_size(&self) -> usize {
2426 self.values.limits.max_envelope_size.as_bytes()
2427 }
2428
2429 pub fn max_session_count(&self) -> usize {
2431 self.values.limits.max_session_count
2432 }
2433
2434 pub fn max_statsd_size(&self) -> usize {
2436 self.values.limits.max_statsd_size.as_bytes()
2437 }
2438
2439 pub fn max_metric_buckets_size(&self) -> usize {
2441 self.values.limits.max_metric_buckets_size.as_bytes()
2442 }
2443
2444 pub fn max_api_payload_size(&self) -> usize {
2446 self.values.limits.max_api_payload_size.as_bytes()
2447 }
2448
2449 pub fn max_api_file_upload_size(&self) -> usize {
2451 self.values.limits.max_api_file_upload_size.as_bytes()
2452 }
2453
2454 pub fn max_api_chunk_upload_size(&self) -> usize {
2456 self.values.limits.max_api_chunk_upload_size.as_bytes()
2457 }
2458
2459 pub fn max_profile_size(&self) -> usize {
2461 self.values.limits.max_profile_size.as_bytes()
2462 }
2463
2464 pub fn max_trace_metric_size(&self) -> usize {
2466 self.values.limits.max_trace_metric_size.as_bytes()
2467 }
2468
2469 pub fn max_replay_compressed_size(&self) -> usize {
2471 self.values.limits.max_replay_compressed_size.as_bytes()
2472 }
2473
2474 pub fn max_replay_uncompressed_size(&self) -> usize {
2476 self.values.limits.max_replay_uncompressed_size.as_bytes()
2477 }
2478
2479 pub fn max_replay_message_size(&self) -> usize {
2485 self.values.limits.max_replay_message_size.as_bytes()
2486 }
2487
2488 pub fn max_concurrent_requests(&self) -> usize {
2490 self.values.limits.max_concurrent_requests
2491 }
2492
2493 pub fn max_concurrent_queries(&self) -> usize {
2495 self.values.limits.max_concurrent_queries
2496 }
2497
2498 pub fn max_removed_attribute_key_size(&self) -> usize {
2500 self.values.limits.max_removed_attribute_key_size.as_bytes()
2501 }
2502
2503 pub fn query_timeout(&self) -> Duration {
2505 Duration::from_secs(self.values.limits.query_timeout)
2506 }
2507
2508 pub fn shutdown_timeout(&self) -> Duration {
2511 Duration::from_secs(self.values.limits.shutdown_timeout)
2512 }
2513
2514 pub fn keepalive_timeout(&self) -> Duration {
2518 Duration::from_secs(self.values.limits.keepalive_timeout)
2519 }
2520
2521 pub fn idle_timeout(&self) -> Option<Duration> {
2523 self.values.limits.idle_timeout.map(Duration::from_secs)
2524 }
2525
2526 pub fn max_connections(&self) -> Option<usize> {
2528 self.values.limits.max_connections
2529 }
2530
2531 pub fn tcp_listen_backlog(&self) -> u32 {
2533 self.values.limits.tcp_listen_backlog
2534 }
2535
2536 pub fn cpu_concurrency(&self) -> usize {
2538 self.values.limits.max_thread_count
2539 }
2540
2541 pub fn pool_concurrency(&self) -> usize {
2543 self.values.limits.max_pool_concurrency
2544 }
2545
2546 pub fn query_batch_size(&self) -> usize {
2548 self.values.cache.batch_size
2549 }
2550
2551 pub fn project_configs_path(&self) -> PathBuf {
2553 self.path.join("projects")
2554 }
2555
2556 pub fn processing_enabled(&self) -> bool {
2558 self.values.processing.enabled
2559 }
2560
2561 pub fn normalization_level(&self) -> NormalizationLevel {
2563 self.values.normalization.level
2564 }
2565
2566 pub fn geoip_path(&self) -> Option<&Path> {
2568 self.values
2569 .geoip
2570 .path
2571 .as_deref()
2572 .or(self.values.processing.geoip_path.as_deref())
2573 }
2574
2575 pub fn max_secs_in_future(&self) -> i64 {
2579 self.values.processing.max_secs_in_future.into()
2580 }
2581
2582 pub fn max_session_secs_in_past(&self) -> i64 {
2584 self.values.processing.max_session_secs_in_past.into()
2585 }
2586
2587 pub fn kafka_configs(
2589 &self,
2590 topic: KafkaTopic,
2591 ) -> Result<KafkaTopicConfig<'_>, KafkaConfigError> {
2592 self.values.processing.topics.get(topic).kafka_configs(
2593 &self.values.processing.kafka_config,
2594 &self.values.processing.secondary_kafka_configs,
2595 )
2596 }
2597
2598 pub fn kafka_validate_topics(&self) -> bool {
2600 self.values.processing.kafka_validate_topics
2601 }
2602
2603 pub fn unused_topic_assignments(&self) -> &relay_kafka::Unused {
2605 &self.values.processing.topics.unused
2606 }
2607
2608 pub fn objectstore(&self) -> &ObjectstoreServiceConfig {
2610 &self.values.processing.objectstore
2611 }
2612
2613 pub fn upload(&self) -> &Upload {
2615 &self.values.upload
2616 }
2617
2618 pub fn redis(&self) -> Option<RedisConfigsRef<'_>> {
2621 let redis_configs = self.values.processing.redis.as_ref()?;
2622
2623 Some(build_redis_configs(
2624 redis_configs,
2625 self.cpu_concurrency() as u32,
2626 self.pool_concurrency() as u32,
2627 ))
2628 }
2629
2630 pub fn attachment_chunk_size(&self) -> usize {
2632 self.values.processing.attachment_chunk_size.as_bytes()
2633 }
2634
2635 pub fn metrics_max_batch_size_bytes(&self) -> usize {
2637 self.values.aggregator.max_flush_bytes
2638 }
2639
2640 pub fn projectconfig_cache_prefix(&self) -> &str {
2643 &self.values.processing.projectconfig_cache_prefix
2644 }
2645
2646 pub fn max_rate_limit(&self) -> Option<u64> {
2648 self.values.processing.max_rate_limit.map(u32::into)
2649 }
2650
2651 pub fn quota_cache_ratio(&self) -> Option<f32> {
2653 self.values.processing.quota_cache_ratio
2654 }
2655
2656 pub fn quota_cache_max(&self) -> Option<f32> {
2658 self.values.processing.quota_cache_max
2659 }
2660
2661 pub fn cardinality_limiter_cache_vacuum_interval(&self) -> Duration {
2665 Duration::from_secs(self.values.cardinality_limiter.cache_vacuum_interval)
2666 }
2667
2668 pub fn health_refresh_interval(&self) -> Duration {
2670 Duration::from_millis(self.values.health.refresh_interval_ms)
2671 }
2672
2673 pub fn health_max_memory_watermark_bytes(&self) -> u64 {
2675 self.values
2676 .health
2677 .max_memory_bytes
2678 .as_ref()
2679 .map_or(u64::MAX, |b| b.as_bytes() as u64)
2680 }
2681
2682 pub fn health_max_memory_watermark_percent(&self) -> f32 {
2684 self.values.health.max_memory_percent
2685 }
2686
2687 pub fn health_probe_timeout(&self) -> Duration {
2689 Duration::from_millis(self.values.health.probe_timeout_ms)
2690 }
2691
2692 pub fn memory_stat_refresh_frequency_ms(&self) -> u64 {
2694 self.values.health.memory_stat_refresh_frequency_ms
2695 }
2696
2697 pub fn cogs_max_queue_size(&self) -> u64 {
2699 self.values.cogs.max_queue_size
2700 }
2701
2702 pub fn cogs_relay_resource_id(&self) -> &str {
2704 &self.values.cogs.relay_resource_id
2705 }
2706
2707 pub fn default_aggregator_config(&self) -> &AggregatorServiceConfig {
2709 &self.values.aggregator
2710 }
2711
2712 pub fn secondary_aggregator_configs(&self) -> &Vec<ScopedAggregatorConfig> {
2714 &self.values.secondary_aggregators
2715 }
2716
2717 pub fn aggregator_config_for(&self, namespace: MetricNamespace) -> &AggregatorServiceConfig {
2719 for entry in &self.values.secondary_aggregators {
2720 if entry.condition.matches(Some(namespace)) {
2721 return &entry.config;
2722 }
2723 }
2724 &self.values.aggregator
2725 }
2726
2727 pub fn static_relays(&self) -> &HashMap<RelayId, RelayInfo> {
2729 &self.values.auth.static_relays
2730 }
2731
2732 pub fn signature_max_age(&self) -> Duration {
2734 Duration::from_secs(self.values.auth.signature_max_age)
2735 }
2736
2737 pub fn accept_unknown_items(&self) -> bool {
2739 let forward = self.values.routing.accept_unknown_items;
2740 forward.unwrap_or_else(|| !self.processing_enabled())
2741 }
2742}
2743
2744impl Default for Config {
2745 fn default() -> Self {
2746 Self {
2747 values: ConfigValues::default(),
2748 credentials: None,
2749 path: PathBuf::new(),
2750 }
2751 }
2752}
2753
2754#[cfg(test)]
2755mod tests {
2756
2757 use super::*;
2758
2759 #[test]
2761 fn test_event_buffer_size() {
2762 let yaml = r###"
2763cache:
2764 event_buffer_size: 1000000
2765 event_expiry: 1800
2766"###;
2767
2768 let values: ConfigValues = serde_yaml::from_str(yaml).unwrap();
2769 assert_eq!(values.cache.envelope_buffer_size, 1_000_000);
2770 assert_eq!(values.cache.envelope_expiry, 1800);
2771 }
2772
2773 #[test]
2774 fn test_emit_outcomes() {
2775 for (serialized, deserialized) in &[
2776 ("true", EmitOutcomes::AsOutcomes),
2777 ("false", EmitOutcomes::None),
2778 ("\"as_client_reports\"", EmitOutcomes::AsClientReports),
2779 ] {
2780 let value: EmitOutcomes = serde_json::from_str(serialized).unwrap();
2781 assert_eq!(value, *deserialized);
2782 assert_eq!(serde_json::to_string(&value).unwrap(), *serialized);
2783 }
2784 }
2785
2786 #[test]
2787 fn test_emit_outcomes_invalid() {
2788 assert!(serde_json::from_str::<EmitOutcomes>("asdf").is_err());
2789 }
2790}