1use std::collections::{BTreeMap, HashMap};
2use std::error::Error;
3use std::io::Write;
4use std::net::{IpAddr, SocketAddr, ToSocketAddrs};
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 = serde_vars::EnvSource::default();
175 match Self::format() {
176 ConfigFormat::Yaml => {
177 serde_vars::deserialize(serde_yaml::Deserializer::from_reader(f), &mut source)
178 .with_context(|| ConfigError::file(ConfigErrorKind::BadYaml, &path))
179 }
180 ConfigFormat::Json => {
181 serde_vars::deserialize(&mut serde_json::Deserializer::from_reader(f), &mut source)
182 .with_context(|| ConfigError::file(ConfigErrorKind::BadJson, &path))
183 }
184 }
185 }
186
187 fn save(&self, base: &Path) -> anyhow::Result<()> {
189 let path = Self::path(base);
190 let mut options = fs::OpenOptions::new();
191 options.write(true).truncate(true).create(true);
192
193 #[cfg(unix)]
195 {
196 use std::os::unix::fs::OpenOptionsExt;
197 options.mode(0o600);
198 }
199
200 let mut f = options
201 .open(&path)
202 .with_context(|| ConfigError::file(ConfigErrorKind::CouldNotWriteFile, &path))?;
203
204 match Self::format() {
205 ConfigFormat::Yaml => {
206 f.write_all(CONFIG_YAML_HEADER.as_bytes())?;
207 serde_yaml::to_writer(&mut f, self)
208 .with_context(|| ConfigError::file(ConfigErrorKind::CouldNotWriteFile, &path))?
209 }
210 ConfigFormat::Json => serde_json::to_writer_pretty(&mut f, self)
211 .with_context(|| ConfigError::file(ConfigErrorKind::CouldNotWriteFile, &path))?,
212 }
213
214 f.write_all(b"\n").ok();
215
216 Ok(())
217 }
218}
219
220#[derive(Debug, Default)]
223pub struct OverridableConfig {
224 pub mode: Option<String>,
226 pub instance: Option<String>,
228 pub log_level: Option<String>,
230 pub log_format: Option<String>,
232 pub upstream: Option<String>,
234 pub upstream_dsn: Option<String>,
236 pub host: Option<String>,
238 pub port: Option<String>,
240 pub processing: Option<String>,
242 pub kafka_url: Option<String>,
244 pub redis_url: Option<String>,
246 pub id: Option<String>,
248 pub secret_key: Option<String>,
250 pub public_key: Option<String>,
252 pub outcome_source: Option<String>,
254 pub shutdown_timeout: Option<String>,
256 pub server_name: Option<String>,
258}
259
260#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
262pub struct Credentials {
263 pub secret_key: SecretKey,
265 pub public_key: PublicKey,
267 pub id: RelayId,
269}
270
271impl Credentials {
272 pub fn generate() -> Self {
274 relay_log::info!("generating new relay credentials");
275 let (sk, pk) = generate_key_pair();
276 Self {
277 secret_key: sk,
278 public_key: pk,
279 id: generate_relay_id(),
280 }
281 }
282
283 pub fn to_json_string(&self) -> anyhow::Result<String> {
285 serde_json::to_string(self)
286 .with_context(|| ConfigError::new(ConfigErrorKind::CouldNotWriteFile))
287 }
288}
289
290impl ConfigObject for Credentials {
291 fn format() -> ConfigFormat {
292 ConfigFormat::Json
293 }
294 fn name() -> &'static str {
295 "credentials"
296 }
297}
298
299#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
301#[serde(rename_all = "camelCase")]
302pub struct RelayInfo {
303 pub public_key: PublicKey,
305
306 #[serde(default)]
308 pub internal: bool,
309}
310
311impl RelayInfo {
312 pub fn new(public_key: PublicKey) -> Self {
314 Self {
315 public_key,
316 internal: false,
317 }
318 }
319}
320
321#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
323#[serde(rename_all = "camelCase")]
324pub enum RelayMode {
325 Proxy,
331
332 Managed,
338}
339
340impl<'de> Deserialize<'de> for RelayMode {
341 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
342 where
343 D: Deserializer<'de>,
344 {
345 let s = String::deserialize(deserializer)?;
346 match s.as_str() {
347 "proxy" => Ok(RelayMode::Proxy),
348 "managed" => Ok(RelayMode::Managed),
349 "static" => Err(serde::de::Error::custom(
350 "Relay mode 'static' has been removed. Please use 'managed' or 'proxy' instead.",
351 )),
352 other => Err(serde::de::Error::unknown_variant(
353 other,
354 &["proxy", "managed"],
355 )),
356 }
357 }
358}
359
360impl fmt::Display for RelayMode {
361 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
362 match self {
363 RelayMode::Proxy => write!(f, "proxy"),
364 RelayMode::Managed => write!(f, "managed"),
365 }
366 }
367}
368
369#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
371#[serde(rename_all = "camelCase")]
372pub enum RelayInstance {
373 Default,
375
376 Canary,
378}
379
380impl RelayInstance {
381 pub fn is_canary(&self) -> bool {
383 matches!(self, RelayInstance::Canary)
384 }
385}
386
387impl fmt::Display for RelayInstance {
388 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
389 match self {
390 RelayInstance::Default => write!(f, "default"),
391 RelayInstance::Canary => write!(f, "canary"),
392 }
393 }
394}
395
396impl FromStr for RelayInstance {
397 type Err = fmt::Error;
398
399 fn from_str(s: &str) -> Result<Self, Self::Err> {
400 match s {
401 "canary" => Ok(RelayInstance::Canary),
402 _ => Ok(RelayInstance::Default),
403 }
404 }
405}
406
407#[derive(Clone, Copy, Debug, Eq, PartialEq)]
409pub struct ParseRelayModeError;
410
411impl fmt::Display for ParseRelayModeError {
412 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
413 write!(f, "Relay mode must be one of: managed or proxy")
414 }
415}
416
417impl Error for ParseRelayModeError {}
418
419impl FromStr for RelayMode {
420 type Err = ParseRelayModeError;
421
422 fn from_str(s: &str) -> Result<Self, Self::Err> {
423 match s {
424 "proxy" => Ok(RelayMode::Proxy),
425 "managed" => Ok(RelayMode::Managed),
426 _ => Err(ParseRelayModeError),
427 }
428 }
429}
430
431fn is_default<T: Default + PartialEq>(t: &T) -> bool {
433 *t == T::default()
434}
435
436fn is_docker() -> bool {
438 if fs::metadata("/.dockerenv").is_ok() {
439 return true;
440 }
441
442 fs::read_to_string("/proc/self/cgroup").is_ok_and(|s| s.contains("/docker"))
443}
444
445fn default_host() -> IpAddr {
447 if is_docker() {
448 "0.0.0.0".parse().unwrap()
450 } else {
451 "127.0.0.1".parse().unwrap()
452 }
453}
454
455#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
459#[serde(rename_all = "lowercase")]
460#[derive(Default)]
461pub enum ReadinessCondition {
462 #[default]
471 Authenticated,
472 Always,
474}
475
476#[derive(Serialize, Deserialize, Debug)]
478#[serde(default)]
479pub struct Relay {
480 pub mode: RelayMode,
482 pub instance: RelayInstance,
484 pub upstream: UpstreamDescriptor<'static>,
486 pub host: IpAddr,
488 pub port: u16,
490 pub internal_host: Option<IpAddr>,
504 pub internal_port: Option<u16>,
508 #[serde(skip_serializing)]
510 pub tls_port: Option<u16>,
511 #[serde(skip_serializing)]
513 pub tls_identity_path: Option<PathBuf>,
514 #[serde(skip_serializing)]
516 pub tls_identity_password: Option<String>,
517 #[serde(skip_serializing_if = "is_default")]
522 pub override_project_ids: bool,
523}
524
525impl Default for Relay {
526 fn default() -> Self {
527 Relay {
528 mode: RelayMode::Managed,
529 instance: RelayInstance::Default,
530 upstream: "https://sentry.io/".parse().unwrap(),
531 host: default_host(),
532 port: 3000,
533 internal_host: None,
534 internal_port: None,
535 tls_port: None,
536 tls_identity_path: None,
537 tls_identity_password: None,
538 override_project_ids: false,
539 }
540 }
541}
542
543#[derive(Serialize, Deserialize, Debug)]
545#[serde(default)]
546pub struct Metrics {
547 pub statsd: Option<String>,
551 pub prefix: String,
555 pub default_tags: BTreeMap<String, String>,
557 pub hostname_tag: Option<String>,
559 pub sample_rate: f32,
564 pub periodic_secs: u64,
569 pub aggregate: bool,
573 pub allow_high_cardinality_tags: bool,
581}
582
583impl Default for Metrics {
584 fn default() -> Self {
585 Metrics {
586 statsd: None,
587 prefix: "sentry.relay".into(),
588 default_tags: BTreeMap::new(),
589 hostname_tag: None,
590 sample_rate: 1.0,
591 periodic_secs: 5,
592 aggregate: true,
593 allow_high_cardinality_tags: false,
594 }
595 }
596}
597
598#[derive(Serialize, Deserialize, Debug)]
600#[serde(default)]
601pub struct Limits {
602 pub max_concurrent_requests: usize,
605 pub max_concurrent_queries: usize,
610 pub max_event_size: ByteSize,
612 pub max_attachment_size: ByteSize,
614 pub max_attachments_size: ByteSize,
616 pub max_client_reports_size: ByteSize,
618 pub max_check_in_size: ByteSize,
620 pub max_envelope_size: ByteSize,
622 pub max_session_count: usize,
624 pub max_span_count: usize,
626 pub max_log_count: usize,
628 pub max_trace_metric_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_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_attachments_size: ByteSize::mebibytes(200),
710 max_client_reports_size: ByteSize::kibibytes(4),
711 max_check_in_size: ByteSize::kibibytes(100),
712 max_envelope_size: ByteSize::mebibytes(200),
713 max_session_count: 100,
714 max_span_count: 1000,
715 max_log_count: 1000,
716 max_trace_metric_count: 1000,
717 max_api_payload_size: ByteSize::mebibytes(20),
718 max_api_file_upload_size: ByteSize::mebibytes(40),
719 max_api_chunk_upload_size: ByteSize::mebibytes(100),
720 max_profile_size: ByteSize::mebibytes(50),
721 max_trace_metric_size: ByteSize::kibibytes(2),
722 max_log_size: ByteSize::mebibytes(1),
723 max_span_size: ByteSize::mebibytes(1),
724 max_container_size: ByteSize::mebibytes(3),
725 max_statsd_size: ByteSize::mebibytes(1),
726 max_metric_buckets_size: ByteSize::mebibytes(1),
727 max_replay_compressed_size: ByteSize::mebibytes(10),
728 max_replay_uncompressed_size: ByteSize::mebibytes(100),
729 max_replay_message_size: ByteSize::mebibytes(15),
730 max_thread_count: num_cpus::get(),
731 max_pool_concurrency: 1,
732 query_timeout: 30,
733 shutdown_timeout: 10,
734 keepalive_timeout: 5,
735 idle_timeout: None,
736 max_connections: None,
737 tcp_listen_backlog: 1024,
738 }
739 }
740}
741
742#[derive(Debug, Default, Deserialize, Serialize)]
744#[serde(default)]
745pub struct Routing {
746 pub accept_unknown_items: Option<bool>,
756}
757
758#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)]
760#[serde(rename_all = "lowercase")]
761pub enum HttpEncoding {
762 #[default]
767 Identity,
768 Deflate,
774 Gzip,
781 Br,
783 Zstd,
785}
786
787impl HttpEncoding {
788 pub fn parse(str: &str) -> Self {
790 let str = str.trim();
791 if str.eq_ignore_ascii_case("zstd") {
792 Self::Zstd
793 } else if str.eq_ignore_ascii_case("br") {
794 Self::Br
795 } else if str.eq_ignore_ascii_case("gzip") || str.eq_ignore_ascii_case("x-gzip") {
796 Self::Gzip
797 } else if str.eq_ignore_ascii_case("deflate") {
798 Self::Deflate
799 } else {
800 Self::Identity
801 }
802 }
803
804 pub fn name(&self) -> Option<&'static str> {
808 match self {
809 Self::Identity => None,
810 Self::Deflate => Some("deflate"),
811 Self::Gzip => Some("gzip"),
812 Self::Br => Some("br"),
813 Self::Zstd => Some("zstd"),
814 }
815 }
816}
817
818#[derive(Serialize, Deserialize, Debug)]
820#[serde(default)]
821pub struct Http {
822 pub timeout: u32,
828 pub connection_timeout: u32,
833 pub max_retry_interval: u32,
835 pub host_header: Option<String>,
837 pub auth_interval: Option<u64>,
845 pub outage_grace_period: u64,
851 pub retry_delay: u64,
855 pub project_failure_interval: u64,
860 pub encoding: HttpEncoding,
876 pub global_metrics: bool,
883}
884
885impl Default for Http {
886 fn default() -> Self {
887 Http {
888 timeout: 5,
889 connection_timeout: 3,
890 max_retry_interval: 60, host_header: None,
892 auth_interval: Some(600), outage_grace_period: DEFAULT_NETWORK_OUTAGE_GRACE_PERIOD,
894 retry_delay: default_retry_delay(),
895 project_failure_interval: default_project_failure_interval(),
896 encoding: HttpEncoding::Zstd,
897 global_metrics: false,
898 }
899 }
900}
901
902fn default_retry_delay() -> u64 {
904 1
905}
906
907fn default_project_failure_interval() -> u64 {
909 90
910}
911
912fn spool_envelopes_max_disk_size() -> ByteSize {
914 ByteSize::mebibytes(500)
915}
916
917fn spool_envelopes_batch_size_bytes() -> ByteSize {
919 ByteSize::kibibytes(10)
920}
921
922fn spool_envelopes_max_envelope_delay_secs() -> u64 {
923 24 * 60 * 60
924}
925
926fn spool_disk_usage_refresh_frequency_ms() -> u64 {
928 100
929}
930
931fn spool_max_backpressure_envelopes() -> usize {
933 500
934}
935
936fn spool_max_backpressure_memory_percent() -> f32 {
938 0.9
939}
940
941fn spool_envelopes_partitions() -> NonZeroU8 {
943 NonZeroU8::new(1).unwrap()
944}
945
946#[derive(Debug, Serialize, Deserialize)]
948pub struct EnvelopeSpool {
949 pub path: Option<PathBuf>,
955 #[serde(default = "spool_envelopes_max_disk_size")]
961 pub max_disk_size: ByteSize,
962 #[serde(default = "spool_envelopes_batch_size_bytes")]
969 pub batch_size_bytes: ByteSize,
970 #[serde(default = "spool_envelopes_max_envelope_delay_secs")]
977 pub max_envelope_delay_secs: u64,
978 #[serde(default = "spool_disk_usage_refresh_frequency_ms")]
983 pub disk_usage_refresh_frequency_ms: u64,
984 #[serde(default = "spool_max_backpressure_envelopes")]
988 pub max_backpressure_envelopes: usize,
989 #[serde(default = "spool_max_backpressure_memory_percent")]
1019 pub max_backpressure_memory_percent: f32,
1020 #[serde(default = "spool_envelopes_partitions")]
1027 pub partitions: NonZeroU8,
1028}
1029
1030impl Default for EnvelopeSpool {
1031 fn default() -> Self {
1032 Self {
1033 path: None,
1034 max_disk_size: spool_envelopes_max_disk_size(),
1035 batch_size_bytes: spool_envelopes_batch_size_bytes(),
1036 max_envelope_delay_secs: spool_envelopes_max_envelope_delay_secs(),
1037 disk_usage_refresh_frequency_ms: spool_disk_usage_refresh_frequency_ms(),
1038 max_backpressure_envelopes: spool_max_backpressure_envelopes(),
1039 max_backpressure_memory_percent: spool_max_backpressure_memory_percent(),
1040 partitions: spool_envelopes_partitions(),
1041 }
1042 }
1043}
1044
1045#[derive(Debug, Serialize, Deserialize, Default)]
1047pub struct Spool {
1048 #[serde(default)]
1050 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
1120fn default_max_secs_in_future() -> u32 {
1121 60 }
1123
1124fn default_max_session_secs_in_past() -> u32 {
1125 5 * 24 * 3600 }
1127
1128fn default_chunk_size() -> ByteSize {
1129 ByteSize::mebibytes(1)
1130}
1131
1132fn default_projectconfig_cache_prefix() -> String {
1133 "relayconfig".to_owned()
1134}
1135
1136#[allow(clippy::unnecessary_wraps)]
1137fn default_max_rate_limit() -> Option<u32> {
1138 Some(300) }
1140
1141#[derive(Serialize, Deserialize, Debug)]
1143pub struct Processing {
1144 pub enabled: bool,
1146 #[serde(default)]
1148 pub geoip_path: Option<PathBuf>,
1149 #[serde(default = "default_max_secs_in_future")]
1151 pub max_secs_in_future: u32,
1152 #[serde(default = "default_max_session_secs_in_past")]
1154 pub max_session_secs_in_past: u32,
1155 pub kafka_config: Vec<KafkaConfigParam>,
1157 #[serde(default)]
1177 pub secondary_kafka_configs: BTreeMap<String, Vec<KafkaConfigParam>>,
1178 #[serde(default)]
1180 pub topics: TopicAssignments,
1181 #[serde(default)]
1183 pub kafka_validate_topics: bool,
1184 #[serde(default)]
1186 pub redis: Option<RedisConfigs>,
1187 #[serde(default = "default_chunk_size")]
1189 pub attachment_chunk_size: ByteSize,
1190 #[serde(default = "default_projectconfig_cache_prefix")]
1192 pub projectconfig_cache_prefix: String,
1193 #[serde(default = "default_max_rate_limit")]
1195 pub max_rate_limit: Option<u32>,
1196 #[serde(default)]
1198 pub upload: UploadServiceConfig,
1199}
1200
1201impl Default for Processing {
1202 fn default() -> Self {
1204 Self {
1205 enabled: false,
1206 geoip_path: None,
1207 max_secs_in_future: default_max_secs_in_future(),
1208 max_session_secs_in_past: default_max_session_secs_in_past(),
1209 kafka_config: Vec::new(),
1210 secondary_kafka_configs: BTreeMap::new(),
1211 topics: TopicAssignments::default(),
1212 kafka_validate_topics: false,
1213 redis: None,
1214 attachment_chunk_size: default_chunk_size(),
1215 projectconfig_cache_prefix: default_projectconfig_cache_prefix(),
1216 max_rate_limit: default_max_rate_limit(),
1217 upload: UploadServiceConfig::default(),
1218 }
1219 }
1220}
1221
1222#[derive(Debug, Default, Serialize, Deserialize)]
1224#[serde(default)]
1225pub struct Normalization {
1226 #[serde(default)]
1228 pub level: NormalizationLevel,
1229}
1230
1231#[derive(Copy, Clone, Debug, Default, Serialize, Deserialize, Eq, PartialEq)]
1233#[serde(rename_all = "lowercase")]
1234pub enum NormalizationLevel {
1235 #[default]
1239 Default,
1240 Full,
1245}
1246
1247#[derive(Serialize, Deserialize, Debug)]
1249#[serde(default)]
1250pub struct OutcomeAggregatorConfig {
1251 pub bucket_interval: u64,
1253 pub flush_interval: u64,
1255}
1256
1257impl Default for OutcomeAggregatorConfig {
1258 fn default() -> Self {
1259 Self {
1260 bucket_interval: 60,
1261 flush_interval: 120,
1262 }
1263 }
1264}
1265
1266#[derive(Serialize, Deserialize, Debug)]
1268#[serde(default)]
1269pub struct UploadServiceConfig {
1270 pub max_concurrent_requests: usize,
1272
1273 pub timeout: u64,
1275}
1276
1277impl Default for UploadServiceConfig {
1278 fn default() -> Self {
1279 Self {
1280 max_concurrent_requests: 100,
1281 timeout: 60,
1282 }
1283 }
1284}
1285
1286#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1289
1290pub enum EmitOutcomes {
1291 None,
1293 AsClientReports,
1295 AsOutcomes,
1297}
1298
1299impl EmitOutcomes {
1300 pub fn any(&self) -> bool {
1302 !matches!(self, EmitOutcomes::None)
1303 }
1304}
1305
1306impl Serialize for EmitOutcomes {
1307 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1308 where
1309 S: Serializer,
1310 {
1311 match self {
1313 Self::None => serializer.serialize_bool(false),
1314 Self::AsClientReports => serializer.serialize_str("as_client_reports"),
1315 Self::AsOutcomes => serializer.serialize_bool(true),
1316 }
1317 }
1318}
1319
1320struct EmitOutcomesVisitor;
1321
1322impl Visitor<'_> for EmitOutcomesVisitor {
1323 type Value = EmitOutcomes;
1324
1325 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1326 formatter.write_str("true, false, or 'as_client_reports'")
1327 }
1328
1329 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
1330 where
1331 E: serde::de::Error,
1332 {
1333 Ok(if v {
1334 EmitOutcomes::AsOutcomes
1335 } else {
1336 EmitOutcomes::None
1337 })
1338 }
1339
1340 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1341 where
1342 E: serde::de::Error,
1343 {
1344 if v == "as_client_reports" {
1345 Ok(EmitOutcomes::AsClientReports)
1346 } else {
1347 Err(E::invalid_value(Unexpected::Str(v), &"as_client_reports"))
1348 }
1349 }
1350}
1351
1352impl<'de> Deserialize<'de> for EmitOutcomes {
1353 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1354 where
1355 D: Deserializer<'de>,
1356 {
1357 deserializer.deserialize_any(EmitOutcomesVisitor)
1358 }
1359}
1360
1361#[derive(Serialize, Deserialize, Debug)]
1363#[serde(default)]
1364pub struct Outcomes {
1365 pub emit_outcomes: EmitOutcomes,
1369 pub emit_client_outcomes: bool,
1371 pub batch_size: usize,
1374 pub batch_interval: u64,
1377 pub source: Option<String>,
1380 pub aggregator: OutcomeAggregatorConfig,
1382}
1383
1384impl Default for Outcomes {
1385 fn default() -> Self {
1386 Outcomes {
1387 emit_outcomes: EmitOutcomes::AsClientReports,
1388 emit_client_outcomes: true,
1389 batch_size: 1000,
1390 batch_interval: 500,
1391 source: None,
1392 aggregator: OutcomeAggregatorConfig::default(),
1393 }
1394 }
1395}
1396
1397#[derive(Serialize, Deserialize, Debug, Default)]
1399pub struct MinimalConfig {
1400 pub relay: Relay,
1402}
1403
1404impl MinimalConfig {
1405 pub fn save_in_folder<P: AsRef<Path>>(&self, p: P) -> anyhow::Result<()> {
1407 let path = p.as_ref();
1408 if fs::metadata(path).is_err() {
1409 fs::create_dir_all(path)
1410 .with_context(|| ConfigError::file(ConfigErrorKind::CouldNotOpenFile, path))?;
1411 }
1412 self.save(path)
1413 }
1414}
1415
1416impl ConfigObject for MinimalConfig {
1417 fn format() -> ConfigFormat {
1418 ConfigFormat::Yaml
1419 }
1420
1421 fn name() -> &'static str {
1422 "config"
1423 }
1424}
1425
1426mod config_relay_info {
1428 use serde::ser::SerializeMap;
1429
1430 use super::*;
1431
1432 #[derive(Debug, Serialize, Deserialize, Clone)]
1434 struct RelayInfoConfig {
1435 public_key: PublicKey,
1436 #[serde(default)]
1437 internal: bool,
1438 }
1439
1440 impl From<RelayInfoConfig> for RelayInfo {
1441 fn from(v: RelayInfoConfig) -> Self {
1442 RelayInfo {
1443 public_key: v.public_key,
1444 internal: v.internal,
1445 }
1446 }
1447 }
1448
1449 impl From<RelayInfo> for RelayInfoConfig {
1450 fn from(v: RelayInfo) -> Self {
1451 RelayInfoConfig {
1452 public_key: v.public_key,
1453 internal: v.internal,
1454 }
1455 }
1456 }
1457
1458 pub(super) fn deserialize<'de, D>(des: D) -> Result<HashMap<RelayId, RelayInfo>, D::Error>
1459 where
1460 D: Deserializer<'de>,
1461 {
1462 let map = HashMap::<RelayId, RelayInfoConfig>::deserialize(des)?;
1463 Ok(map.into_iter().map(|(k, v)| (k, v.into())).collect())
1464 }
1465
1466 pub(super) fn serialize<S>(elm: &HashMap<RelayId, RelayInfo>, ser: S) -> Result<S::Ok, S::Error>
1467 where
1468 S: Serializer,
1469 {
1470 let mut map = ser.serialize_map(Some(elm.len()))?;
1471
1472 for (k, v) in elm {
1473 map.serialize_entry(k, &RelayInfoConfig::from(v.clone()))?;
1474 }
1475
1476 map.end()
1477 }
1478}
1479
1480#[derive(Serialize, Deserialize, Debug, Default)]
1482pub struct AuthConfig {
1483 #[serde(default, skip_serializing_if = "is_default")]
1485 pub ready: ReadinessCondition,
1486
1487 #[serde(default, with = "config_relay_info")]
1489 pub static_relays: HashMap<RelayId, RelayInfo>,
1490
1491 #[serde(default = "default_max_age")]
1495 pub signature_max_age: u64,
1496}
1497
1498fn default_max_age() -> u64 {
1499 300
1500}
1501
1502#[derive(Serialize, Deserialize, Debug, Default)]
1504pub struct GeoIpConfig {
1505 pub path: Option<PathBuf>,
1507}
1508
1509#[derive(Serialize, Deserialize, Debug)]
1511#[serde(default)]
1512pub struct CardinalityLimiter {
1513 pub cache_vacuum_interval: u64,
1519}
1520
1521impl Default for CardinalityLimiter {
1522 fn default() -> Self {
1523 Self {
1524 cache_vacuum_interval: 180,
1525 }
1526 }
1527}
1528
1529#[derive(Serialize, Deserialize, Debug)]
1534#[serde(default)]
1535pub struct Health {
1536 pub refresh_interval_ms: u64,
1543 pub max_memory_bytes: Option<ByteSize>,
1548 pub max_memory_percent: f32,
1552 pub probe_timeout_ms: u64,
1559 pub memory_stat_refresh_frequency_ms: u64,
1565}
1566
1567impl Default for Health {
1568 fn default() -> Self {
1569 Self {
1570 refresh_interval_ms: 3000,
1571 max_memory_bytes: None,
1572 max_memory_percent: 0.95,
1573 probe_timeout_ms: 900,
1574 memory_stat_refresh_frequency_ms: 100,
1575 }
1576 }
1577}
1578
1579#[derive(Serialize, Deserialize, Debug)]
1581#[serde(default)]
1582pub struct Cogs {
1583 pub max_queue_size: u64,
1589 pub relay_resource_id: String,
1595}
1596
1597impl Default for Cogs {
1598 fn default() -> Self {
1599 Self {
1600 max_queue_size: 10_000,
1601 relay_resource_id: "relay_service".to_owned(),
1602 }
1603 }
1604}
1605
1606#[derive(Serialize, Deserialize, Debug, Default)]
1607struct ConfigValues {
1608 #[serde(default)]
1609 relay: Relay,
1610 #[serde(default)]
1611 http: Http,
1612 #[serde(default)]
1613 cache: Cache,
1614 #[serde(default)]
1615 spool: Spool,
1616 #[serde(default)]
1617 limits: Limits,
1618 #[serde(default)]
1619 logging: relay_log::LogConfig,
1620 #[serde(default)]
1621 routing: Routing,
1622 #[serde(default)]
1623 metrics: Metrics,
1624 #[serde(default)]
1625 sentry: relay_log::SentryConfig,
1626 #[serde(default)]
1627 processing: Processing,
1628 #[serde(default)]
1629 outcomes: Outcomes,
1630 #[serde(default)]
1631 aggregator: AggregatorServiceConfig,
1632 #[serde(default)]
1633 secondary_aggregators: Vec<ScopedAggregatorConfig>,
1634 #[serde(default)]
1635 auth: AuthConfig,
1636 #[serde(default)]
1637 geoip: GeoIpConfig,
1638 #[serde(default)]
1639 normalization: Normalization,
1640 #[serde(default)]
1641 cardinality_limiter: CardinalityLimiter,
1642 #[serde(default)]
1643 health: Health,
1644 #[serde(default)]
1645 cogs: Cogs,
1646}
1647
1648impl ConfigObject for ConfigValues {
1649 fn format() -> ConfigFormat {
1650 ConfigFormat::Yaml
1651 }
1652
1653 fn name() -> &'static str {
1654 "config"
1655 }
1656}
1657
1658pub struct Config {
1660 values: ConfigValues,
1661 credentials: Option<Credentials>,
1662 path: PathBuf,
1663}
1664
1665impl fmt::Debug for Config {
1666 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1667 f.debug_struct("Config")
1668 .field("path", &self.path)
1669 .field("values", &self.values)
1670 .finish()
1671 }
1672}
1673
1674impl Config {
1675 pub fn from_path<P: AsRef<Path>>(path: P) -> anyhow::Result<Config> {
1677 let path = env::current_dir()
1678 .map(|x| x.join(path.as_ref()))
1679 .unwrap_or_else(|_| path.as_ref().to_path_buf());
1680
1681 let config = Config {
1682 values: ConfigValues::load(&path)?,
1683 credentials: if Credentials::path(&path).exists() {
1684 Some(Credentials::load(&path)?)
1685 } else {
1686 None
1687 },
1688 path: path.clone(),
1689 };
1690
1691 if cfg!(not(feature = "processing")) && config.processing_enabled() {
1692 return Err(ConfigError::file(ConfigErrorKind::ProcessingNotAvailable, &path).into());
1693 }
1694
1695 Ok(config)
1696 }
1697
1698 pub fn from_json_value(value: serde_json::Value) -> anyhow::Result<Config> {
1702 Ok(Config {
1703 values: serde_json::from_value(value)
1704 .with_context(|| ConfigError::new(ConfigErrorKind::BadJson))?,
1705 credentials: None,
1706 path: PathBuf::new(),
1707 })
1708 }
1709
1710 pub fn apply_override(
1713 &mut self,
1714 mut overrides: OverridableConfig,
1715 ) -> anyhow::Result<&mut Self> {
1716 let relay = &mut self.values.relay;
1717
1718 if let Some(mode) = overrides.mode {
1719 relay.mode = mode
1720 .parse::<RelayMode>()
1721 .with_context(|| ConfigError::field("mode"))?;
1722 }
1723
1724 if let Some(deployment) = overrides.instance {
1725 relay.instance = deployment
1726 .parse::<RelayInstance>()
1727 .with_context(|| ConfigError::field("deployment"))?;
1728 }
1729
1730 if let Some(log_level) = overrides.log_level {
1731 self.values.logging.level = log_level.parse()?;
1732 }
1733
1734 if let Some(log_format) = overrides.log_format {
1735 self.values.logging.format = log_format.parse()?;
1736 }
1737
1738 if let Some(upstream) = overrides.upstream {
1739 relay.upstream = upstream
1740 .parse::<UpstreamDescriptor>()
1741 .with_context(|| ConfigError::field("upstream"))?;
1742 } else if let Some(upstream_dsn) = overrides.upstream_dsn {
1743 relay.upstream = upstream_dsn
1744 .parse::<Dsn>()
1745 .map(|dsn| UpstreamDescriptor::from_dsn(&dsn).into_owned())
1746 .with_context(|| ConfigError::field("upstream_dsn"))?;
1747 }
1748
1749 if let Some(host) = overrides.host {
1750 relay.host = host
1751 .parse::<IpAddr>()
1752 .with_context(|| ConfigError::field("host"))?;
1753 }
1754
1755 if let Some(port) = overrides.port {
1756 relay.port = port
1757 .as_str()
1758 .parse()
1759 .with_context(|| ConfigError::field("port"))?;
1760 }
1761
1762 let processing = &mut self.values.processing;
1763 if let Some(enabled) = overrides.processing {
1764 match enabled.to_lowercase().as_str() {
1765 "true" | "1" => processing.enabled = true,
1766 "false" | "0" | "" => processing.enabled = false,
1767 _ => return Err(ConfigError::field("processing").into()),
1768 }
1769 }
1770
1771 if let Some(redis) = overrides.redis_url {
1772 processing.redis = Some(RedisConfigs::Unified(RedisConfig::single(redis)))
1773 }
1774
1775 if let Some(kafka_url) = overrides.kafka_url {
1776 let existing = processing
1777 .kafka_config
1778 .iter_mut()
1779 .find(|e| e.name == "bootstrap.servers");
1780
1781 if let Some(config_param) = existing {
1782 config_param.value = kafka_url;
1783 } else {
1784 processing.kafka_config.push(KafkaConfigParam {
1785 name: "bootstrap.servers".to_owned(),
1786 value: kafka_url,
1787 })
1788 }
1789 }
1790 let id = if let Some(id) = overrides.id {
1792 let id = Uuid::parse_str(&id).with_context(|| ConfigError::field("id"))?;
1793 Some(id)
1794 } else {
1795 None
1796 };
1797 let public_key = if let Some(public_key) = overrides.public_key {
1798 let public_key = public_key
1799 .parse::<PublicKey>()
1800 .with_context(|| ConfigError::field("public_key"))?;
1801 Some(public_key)
1802 } else {
1803 None
1804 };
1805
1806 let secret_key = if let Some(secret_key) = overrides.secret_key {
1807 let secret_key = secret_key
1808 .parse::<SecretKey>()
1809 .with_context(|| ConfigError::field("secret_key"))?;
1810 Some(secret_key)
1811 } else {
1812 None
1813 };
1814 let outcomes = &mut self.values.outcomes;
1815 if overrides.outcome_source.is_some() {
1816 outcomes.source = overrides.outcome_source.take();
1817 }
1818
1819 if let Some(credentials) = &mut self.credentials {
1820 if let Some(id) = id {
1822 credentials.id = id;
1823 }
1824 if let Some(public_key) = public_key {
1825 credentials.public_key = public_key;
1826 }
1827 if let Some(secret_key) = secret_key {
1828 credentials.secret_key = secret_key
1829 }
1830 } else {
1831 match (id, public_key, secret_key) {
1833 (Some(id), Some(public_key), Some(secret_key)) => {
1834 self.credentials = Some(Credentials {
1835 secret_key,
1836 public_key,
1837 id,
1838 })
1839 }
1840 (None, None, None) => {
1841 }
1844 _ => {
1845 return Err(ConfigError::field("incomplete credentials").into());
1846 }
1847 }
1848 }
1849
1850 let limits = &mut self.values.limits;
1851 if let Some(shutdown_timeout) = overrides.shutdown_timeout
1852 && let Ok(shutdown_timeout) = shutdown_timeout.parse::<u64>()
1853 {
1854 limits.shutdown_timeout = shutdown_timeout;
1855 }
1856
1857 if let Some(server_name) = overrides.server_name {
1858 self.values.sentry.server_name = Some(server_name.into());
1859 }
1860
1861 Ok(self)
1862 }
1863
1864 pub fn config_exists<P: AsRef<Path>>(path: P) -> bool {
1866 fs::metadata(ConfigValues::path(path.as_ref())).is_ok()
1867 }
1868
1869 pub fn path(&self) -> &Path {
1871 &self.path
1872 }
1873
1874 pub fn to_yaml_string(&self) -> anyhow::Result<String> {
1876 serde_yaml::to_string(&self.values)
1877 .with_context(|| ConfigError::new(ConfigErrorKind::CouldNotWriteFile))
1878 }
1879
1880 pub fn regenerate_credentials(&mut self, save: bool) -> anyhow::Result<()> {
1884 let creds = Credentials::generate();
1885 if save {
1886 creds.save(&self.path)?;
1887 }
1888 self.credentials = Some(creds);
1889 Ok(())
1890 }
1891
1892 pub fn credentials(&self) -> Option<&Credentials> {
1894 self.credentials.as_ref()
1895 }
1896
1897 pub fn replace_credentials(
1901 &mut self,
1902 credentials: Option<Credentials>,
1903 ) -> anyhow::Result<bool> {
1904 if self.credentials == credentials {
1905 return Ok(false);
1906 }
1907
1908 match credentials {
1909 Some(ref creds) => {
1910 creds.save(&self.path)?;
1911 }
1912 None => {
1913 let path = Credentials::path(&self.path);
1914 if fs::metadata(&path).is_ok() {
1915 fs::remove_file(&path).with_context(|| {
1916 ConfigError::file(ConfigErrorKind::CouldNotWriteFile, &path)
1917 })?;
1918 }
1919 }
1920 }
1921
1922 self.credentials = credentials;
1923 Ok(true)
1924 }
1925
1926 pub fn has_credentials(&self) -> bool {
1928 self.credentials.is_some()
1929 }
1930
1931 pub fn secret_key(&self) -> Option<&SecretKey> {
1933 self.credentials.as_ref().map(|x| &x.secret_key)
1934 }
1935
1936 pub fn public_key(&self) -> Option<&PublicKey> {
1938 self.credentials.as_ref().map(|x| &x.public_key)
1939 }
1940
1941 pub fn relay_id(&self) -> Option<&RelayId> {
1943 self.credentials.as_ref().map(|x| &x.id)
1944 }
1945
1946 pub fn relay_mode(&self) -> RelayMode {
1948 self.values.relay.mode
1949 }
1950
1951 pub fn relay_instance(&self) -> RelayInstance {
1953 self.values.relay.instance
1954 }
1955
1956 pub fn upstream_descriptor(&self) -> &UpstreamDescriptor<'_> {
1958 &self.values.relay.upstream
1959 }
1960
1961 pub fn http_host_header(&self) -> Option<&str> {
1963 self.values.http.host_header.as_deref()
1964 }
1965
1966 pub fn listen_addr(&self) -> SocketAddr {
1968 (self.values.relay.host, self.values.relay.port).into()
1969 }
1970
1971 pub fn listen_addr_internal(&self) -> Option<SocketAddr> {
1979 match (
1980 self.values.relay.internal_host,
1981 self.values.relay.internal_port,
1982 ) {
1983 (Some(host), None) => Some((host, self.values.relay.port).into()),
1984 (None, Some(port)) => Some((self.values.relay.host, port).into()),
1985 (Some(host), Some(port)) => Some((host, port).into()),
1986 (None, None) => None,
1987 }
1988 }
1989
1990 pub fn tls_listen_addr(&self) -> Option<SocketAddr> {
1992 if self.values.relay.tls_identity_path.is_some() {
1993 let port = self.values.relay.tls_port.unwrap_or(3443);
1994 Some((self.values.relay.host, port).into())
1995 } else {
1996 None
1997 }
1998 }
1999
2000 pub fn tls_identity_path(&self) -> Option<&Path> {
2002 self.values.relay.tls_identity_path.as_deref()
2003 }
2004
2005 pub fn tls_identity_password(&self) -> Option<&str> {
2007 self.values.relay.tls_identity_password.as_deref()
2008 }
2009
2010 pub fn override_project_ids(&self) -> bool {
2014 self.values.relay.override_project_ids
2015 }
2016
2017 pub fn requires_auth(&self) -> bool {
2021 match self.values.auth.ready {
2022 ReadinessCondition::Authenticated => self.relay_mode() == RelayMode::Managed,
2023 ReadinessCondition::Always => false,
2024 }
2025 }
2026
2027 pub fn http_auth_interval(&self) -> Option<Duration> {
2031 if self.processing_enabled() {
2032 return None;
2033 }
2034
2035 match self.values.http.auth_interval {
2036 None | Some(0) => None,
2037 Some(secs) => Some(Duration::from_secs(secs)),
2038 }
2039 }
2040
2041 pub fn http_outage_grace_period(&self) -> Duration {
2044 Duration::from_secs(self.values.http.outage_grace_period)
2045 }
2046
2047 pub fn http_retry_delay(&self) -> Duration {
2052 Duration::from_secs(self.values.http.retry_delay)
2053 }
2054
2055 pub fn http_project_failure_interval(&self) -> Duration {
2057 Duration::from_secs(self.values.http.project_failure_interval)
2058 }
2059
2060 pub fn http_encoding(&self) -> HttpEncoding {
2062 self.values.http.encoding
2063 }
2064
2065 pub fn http_global_metrics(&self) -> bool {
2067 self.values.http.global_metrics
2068 }
2069
2070 pub fn emit_outcomes(&self) -> EmitOutcomes {
2075 if self.processing_enabled() {
2076 return EmitOutcomes::AsOutcomes;
2077 }
2078 self.values.outcomes.emit_outcomes
2079 }
2080
2081 pub fn emit_client_outcomes(&self) -> bool {
2091 self.values.outcomes.emit_client_outcomes
2092 }
2093
2094 pub fn outcome_batch_size(&self) -> usize {
2096 self.values.outcomes.batch_size
2097 }
2098
2099 pub fn outcome_batch_interval(&self) -> Duration {
2101 Duration::from_millis(self.values.outcomes.batch_interval)
2102 }
2103
2104 pub fn outcome_source(&self) -> Option<&str> {
2106 self.values.outcomes.source.as_deref()
2107 }
2108
2109 pub fn outcome_aggregator(&self) -> &OutcomeAggregatorConfig {
2111 &self.values.outcomes.aggregator
2112 }
2113
2114 pub fn logging(&self) -> &relay_log::LogConfig {
2116 &self.values.logging
2117 }
2118
2119 pub fn sentry(&self) -> &relay_log::SentryConfig {
2121 &self.values.sentry
2122 }
2123
2124 pub fn statsd_addrs(&self) -> anyhow::Result<Vec<SocketAddr>> {
2128 if let Some(ref addr) = self.values.metrics.statsd {
2129 let addrs = addr
2130 .as_str()
2131 .to_socket_addrs()
2132 .with_context(|| ConfigError::file(ConfigErrorKind::InvalidValue, &self.path))?
2133 .collect();
2134 Ok(addrs)
2135 } else {
2136 Ok(vec![])
2137 }
2138 }
2139
2140 pub fn metrics_prefix(&self) -> &str {
2142 &self.values.metrics.prefix
2143 }
2144
2145 pub fn metrics_default_tags(&self) -> &BTreeMap<String, String> {
2147 &self.values.metrics.default_tags
2148 }
2149
2150 pub fn metrics_hostname_tag(&self) -> Option<&str> {
2152 self.values.metrics.hostname_tag.as_deref()
2153 }
2154
2155 pub fn metrics_sample_rate(&self) -> f32 {
2157 self.values.metrics.sample_rate
2158 }
2159
2160 pub fn metrics_aggregate(&self) -> bool {
2162 self.values.metrics.aggregate
2163 }
2164
2165 pub fn metrics_allow_high_cardinality_tags(&self) -> bool {
2167 self.values.metrics.allow_high_cardinality_tags
2168 }
2169
2170 pub fn metrics_periodic_interval(&self) -> Option<Duration> {
2174 match self.values.metrics.periodic_secs {
2175 0 => None,
2176 secs => Some(Duration::from_secs(secs)),
2177 }
2178 }
2179
2180 pub fn http_timeout(&self) -> Duration {
2182 Duration::from_secs(self.values.http.timeout.into())
2183 }
2184
2185 pub fn http_connection_timeout(&self) -> Duration {
2187 Duration::from_secs(self.values.http.connection_timeout.into())
2188 }
2189
2190 pub fn http_max_retry_interval(&self) -> Duration {
2192 Duration::from_secs(self.values.http.max_retry_interval.into())
2193 }
2194
2195 pub fn project_cache_expiry(&self) -> Duration {
2197 Duration::from_secs(self.values.cache.project_expiry.into())
2198 }
2199
2200 pub fn request_full_project_config(&self) -> bool {
2202 self.values.cache.project_request_full_config
2203 }
2204
2205 pub fn relay_cache_expiry(&self) -> Duration {
2207 Duration::from_secs(self.values.cache.relay_expiry.into())
2208 }
2209
2210 pub fn envelope_buffer_size(&self) -> usize {
2212 self.values
2213 .cache
2214 .envelope_buffer_size
2215 .try_into()
2216 .unwrap_or(usize::MAX)
2217 }
2218
2219 pub fn cache_miss_expiry(&self) -> Duration {
2221 Duration::from_secs(self.values.cache.miss_expiry.into())
2222 }
2223
2224 pub fn project_grace_period(&self) -> Duration {
2226 Duration::from_secs(self.values.cache.project_grace_period.into())
2227 }
2228
2229 pub fn project_refresh_interval(&self) -> Option<Duration> {
2233 self.values
2234 .cache
2235 .project_refresh_interval
2236 .map(Into::into)
2237 .map(Duration::from_secs)
2238 }
2239
2240 pub fn query_batch_interval(&self) -> Duration {
2243 Duration::from_millis(self.values.cache.batch_interval.into())
2244 }
2245
2246 pub fn downstream_relays_batch_interval(&self) -> Duration {
2248 Duration::from_millis(self.values.cache.downstream_relays_batch_interval.into())
2249 }
2250
2251 pub fn local_cache_interval(&self) -> Duration {
2253 Duration::from_secs(self.values.cache.file_interval.into())
2254 }
2255
2256 pub fn global_config_fetch_interval(&self) -> Duration {
2259 Duration::from_secs(self.values.cache.global_config_fetch_interval.into())
2260 }
2261
2262 pub fn spool_envelopes_path(&self, partition_id: u8) -> Option<PathBuf> {
2267 let mut path = self
2268 .values
2269 .spool
2270 .envelopes
2271 .path
2272 .as_ref()
2273 .map(|path| path.to_owned())?;
2274
2275 if partition_id == 0 {
2276 return Some(path);
2277 }
2278
2279 let file_name = path.file_name().and_then(|f| f.to_str())?;
2280 let new_file_name = format!("{file_name}.{partition_id}");
2281 path.set_file_name(new_file_name);
2282
2283 Some(path)
2284 }
2285
2286 pub fn spool_envelopes_max_disk_size(&self) -> usize {
2288 self.values.spool.envelopes.max_disk_size.as_bytes()
2289 }
2290
2291 pub fn spool_envelopes_batch_size_bytes(&self) -> usize {
2294 self.values.spool.envelopes.batch_size_bytes.as_bytes()
2295 }
2296
2297 pub fn spool_envelopes_max_age(&self) -> Duration {
2299 Duration::from_secs(self.values.spool.envelopes.max_envelope_delay_secs)
2300 }
2301
2302 pub fn spool_disk_usage_refresh_frequency_ms(&self) -> Duration {
2304 Duration::from_millis(self.values.spool.envelopes.disk_usage_refresh_frequency_ms)
2305 }
2306
2307 pub fn spool_max_backpressure_envelopes(&self) -> usize {
2309 self.values.spool.envelopes.max_backpressure_envelopes
2310 }
2311
2312 pub fn spool_max_backpressure_memory_percent(&self) -> f32 {
2314 self.values.spool.envelopes.max_backpressure_memory_percent
2315 }
2316
2317 pub fn spool_partitions(&self) -> NonZeroU8 {
2319 self.values.spool.envelopes.partitions
2320 }
2321
2322 pub fn max_event_size(&self) -> usize {
2324 self.values.limits.max_event_size.as_bytes()
2325 }
2326
2327 pub fn max_attachment_size(&self) -> usize {
2329 self.values.limits.max_attachment_size.as_bytes()
2330 }
2331
2332 pub fn max_attachments_size(&self) -> usize {
2335 self.values.limits.max_attachments_size.as_bytes()
2336 }
2337
2338 pub fn max_client_reports_size(&self) -> usize {
2340 self.values.limits.max_client_reports_size.as_bytes()
2341 }
2342
2343 pub fn max_check_in_size(&self) -> usize {
2345 self.values.limits.max_check_in_size.as_bytes()
2346 }
2347
2348 pub fn max_log_size(&self) -> usize {
2350 self.values.limits.max_log_size.as_bytes()
2351 }
2352
2353 pub fn max_span_size(&self) -> usize {
2355 self.values.limits.max_span_size.as_bytes()
2356 }
2357
2358 pub fn max_container_size(&self) -> usize {
2360 self.values.limits.max_container_size.as_bytes()
2361 }
2362
2363 pub fn max_envelope_size(&self) -> usize {
2367 self.values.limits.max_envelope_size.as_bytes()
2368 }
2369
2370 pub fn max_session_count(&self) -> usize {
2372 self.values.limits.max_session_count
2373 }
2374
2375 pub fn max_span_count(&self) -> usize {
2377 self.values.limits.max_span_count
2378 }
2379
2380 pub fn max_log_count(&self) -> usize {
2382 self.values.limits.max_log_count
2383 }
2384
2385 pub fn max_trace_metric_count(&self) -> usize {
2387 self.values.limits.max_trace_metric_count
2388 }
2389
2390 pub fn max_statsd_size(&self) -> usize {
2392 self.values.limits.max_statsd_size.as_bytes()
2393 }
2394
2395 pub fn max_metric_buckets_size(&self) -> usize {
2397 self.values.limits.max_metric_buckets_size.as_bytes()
2398 }
2399
2400 pub fn max_api_payload_size(&self) -> usize {
2402 self.values.limits.max_api_payload_size.as_bytes()
2403 }
2404
2405 pub fn max_api_file_upload_size(&self) -> usize {
2407 self.values.limits.max_api_file_upload_size.as_bytes()
2408 }
2409
2410 pub fn max_api_chunk_upload_size(&self) -> usize {
2412 self.values.limits.max_api_chunk_upload_size.as_bytes()
2413 }
2414
2415 pub fn max_profile_size(&self) -> usize {
2417 self.values.limits.max_profile_size.as_bytes()
2418 }
2419
2420 pub fn max_trace_metric_size(&self) -> usize {
2422 self.values.limits.max_trace_metric_size.as_bytes()
2423 }
2424
2425 pub fn max_replay_compressed_size(&self) -> usize {
2427 self.values.limits.max_replay_compressed_size.as_bytes()
2428 }
2429
2430 pub fn max_replay_uncompressed_size(&self) -> usize {
2432 self.values.limits.max_replay_uncompressed_size.as_bytes()
2433 }
2434
2435 pub fn max_replay_message_size(&self) -> usize {
2441 self.values.limits.max_replay_message_size.as_bytes()
2442 }
2443
2444 pub fn max_concurrent_requests(&self) -> usize {
2446 self.values.limits.max_concurrent_requests
2447 }
2448
2449 pub fn max_concurrent_queries(&self) -> usize {
2451 self.values.limits.max_concurrent_queries
2452 }
2453
2454 pub fn query_timeout(&self) -> Duration {
2456 Duration::from_secs(self.values.limits.query_timeout)
2457 }
2458
2459 pub fn shutdown_timeout(&self) -> Duration {
2462 Duration::from_secs(self.values.limits.shutdown_timeout)
2463 }
2464
2465 pub fn keepalive_timeout(&self) -> Duration {
2469 Duration::from_secs(self.values.limits.keepalive_timeout)
2470 }
2471
2472 pub fn idle_timeout(&self) -> Option<Duration> {
2474 self.values.limits.idle_timeout.map(Duration::from_secs)
2475 }
2476
2477 pub fn max_connections(&self) -> Option<usize> {
2479 self.values.limits.max_connections
2480 }
2481
2482 pub fn tcp_listen_backlog(&self) -> u32 {
2484 self.values.limits.tcp_listen_backlog
2485 }
2486
2487 pub fn cpu_concurrency(&self) -> usize {
2489 self.values.limits.max_thread_count
2490 }
2491
2492 pub fn pool_concurrency(&self) -> usize {
2494 self.values.limits.max_pool_concurrency
2495 }
2496
2497 pub fn query_batch_size(&self) -> usize {
2499 self.values.cache.batch_size
2500 }
2501
2502 pub fn project_configs_path(&self) -> PathBuf {
2504 self.path.join("projects")
2505 }
2506
2507 pub fn processing_enabled(&self) -> bool {
2509 self.values.processing.enabled
2510 }
2511
2512 pub fn normalization_level(&self) -> NormalizationLevel {
2514 self.values.normalization.level
2515 }
2516
2517 pub fn geoip_path(&self) -> Option<&Path> {
2519 self.values
2520 .geoip
2521 .path
2522 .as_deref()
2523 .or(self.values.processing.geoip_path.as_deref())
2524 }
2525
2526 pub fn max_secs_in_future(&self) -> i64 {
2530 self.values.processing.max_secs_in_future.into()
2531 }
2532
2533 pub fn max_session_secs_in_past(&self) -> i64 {
2535 self.values.processing.max_session_secs_in_past.into()
2536 }
2537
2538 pub fn kafka_configs(
2540 &self,
2541 topic: KafkaTopic,
2542 ) -> Result<KafkaTopicConfig<'_>, KafkaConfigError> {
2543 self.values.processing.topics.get(topic).kafka_configs(
2544 &self.values.processing.kafka_config,
2545 &self.values.processing.secondary_kafka_configs,
2546 )
2547 }
2548
2549 pub fn kafka_validate_topics(&self) -> bool {
2551 self.values.processing.kafka_validate_topics
2552 }
2553
2554 pub fn unused_topic_assignments(&self) -> &relay_kafka::Unused {
2556 &self.values.processing.topics.unused
2557 }
2558
2559 pub fn upload(&self) -> &UploadServiceConfig {
2561 &self.values.processing.upload
2562 }
2563
2564 pub fn redis(&self) -> Option<RedisConfigsRef<'_>> {
2567 let redis_configs = self.values.processing.redis.as_ref()?;
2568
2569 Some(build_redis_configs(
2570 redis_configs,
2571 self.cpu_concurrency() as u32,
2572 self.pool_concurrency() as u32,
2573 ))
2574 }
2575
2576 pub fn attachment_chunk_size(&self) -> usize {
2578 self.values.processing.attachment_chunk_size.as_bytes()
2579 }
2580
2581 pub fn metrics_max_batch_size_bytes(&self) -> usize {
2583 self.values.aggregator.max_flush_bytes
2584 }
2585
2586 pub fn projectconfig_cache_prefix(&self) -> &str {
2589 &self.values.processing.projectconfig_cache_prefix
2590 }
2591
2592 pub fn max_rate_limit(&self) -> Option<u64> {
2594 self.values.processing.max_rate_limit.map(u32::into)
2595 }
2596
2597 pub fn cardinality_limiter_cache_vacuum_interval(&self) -> Duration {
2601 Duration::from_secs(self.values.cardinality_limiter.cache_vacuum_interval)
2602 }
2603
2604 pub fn health_refresh_interval(&self) -> Duration {
2606 Duration::from_millis(self.values.health.refresh_interval_ms)
2607 }
2608
2609 pub fn health_max_memory_watermark_bytes(&self) -> u64 {
2611 self.values
2612 .health
2613 .max_memory_bytes
2614 .as_ref()
2615 .map_or(u64::MAX, |b| b.as_bytes() as u64)
2616 }
2617
2618 pub fn health_max_memory_watermark_percent(&self) -> f32 {
2620 self.values.health.max_memory_percent
2621 }
2622
2623 pub fn health_probe_timeout(&self) -> Duration {
2625 Duration::from_millis(self.values.health.probe_timeout_ms)
2626 }
2627
2628 pub fn memory_stat_refresh_frequency_ms(&self) -> u64 {
2630 self.values.health.memory_stat_refresh_frequency_ms
2631 }
2632
2633 pub fn cogs_max_queue_size(&self) -> u64 {
2635 self.values.cogs.max_queue_size
2636 }
2637
2638 pub fn cogs_relay_resource_id(&self) -> &str {
2640 &self.values.cogs.relay_resource_id
2641 }
2642
2643 pub fn default_aggregator_config(&self) -> &AggregatorServiceConfig {
2645 &self.values.aggregator
2646 }
2647
2648 pub fn secondary_aggregator_configs(&self) -> &Vec<ScopedAggregatorConfig> {
2650 &self.values.secondary_aggregators
2651 }
2652
2653 pub fn aggregator_config_for(&self, namespace: MetricNamespace) -> &AggregatorServiceConfig {
2655 for entry in &self.values.secondary_aggregators {
2656 if entry.condition.matches(Some(namespace)) {
2657 return &entry.config;
2658 }
2659 }
2660 &self.values.aggregator
2661 }
2662
2663 pub fn static_relays(&self) -> &HashMap<RelayId, RelayInfo> {
2665 &self.values.auth.static_relays
2666 }
2667
2668 pub fn signature_max_age(&self) -> Duration {
2670 Duration::from_secs(self.values.auth.signature_max_age)
2671 }
2672
2673 pub fn accept_unknown_items(&self) -> bool {
2675 let forward = self.values.routing.accept_unknown_items;
2676 forward.unwrap_or_else(|| !self.processing_enabled())
2677 }
2678}
2679
2680impl Default for Config {
2681 fn default() -> Self {
2682 Self {
2683 values: ConfigValues::default(),
2684 credentials: None,
2685 path: PathBuf::new(),
2686 }
2687 }
2688}
2689
2690#[cfg(test)]
2691mod tests {
2692
2693 use super::*;
2694
2695 #[test]
2697 fn test_event_buffer_size() {
2698 let yaml = r###"
2699cache:
2700 event_buffer_size: 1000000
2701 event_expiry: 1800
2702"###;
2703
2704 let values: ConfigValues = serde_yaml::from_str(yaml).unwrap();
2705 assert_eq!(values.cache.envelope_buffer_size, 1_000_000);
2706 assert_eq!(values.cache.envelope_expiry, 1800);
2707 }
2708
2709 #[test]
2710 fn test_emit_outcomes() {
2711 for (serialized, deserialized) in &[
2712 ("true", EmitOutcomes::AsOutcomes),
2713 ("false", EmitOutcomes::None),
2714 ("\"as_client_reports\"", EmitOutcomes::AsClientReports),
2715 ] {
2716 let value: EmitOutcomes = serde_json::from_str(serialized).unwrap();
2717 assert_eq!(value, *deserialized);
2718 assert_eq!(serde_json::to_string(&value).unwrap(), *serialized);
2719 }
2720 }
2721
2722 #[test]
2723 fn test_emit_outcomes_invalid() {
2724 assert!(serde_json::from_str::<EmitOutcomes>("asdf").is_err());
2725 }
2726}