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 objectstore_url: Option<String>,
1275
1276 pub max_concurrent_requests: usize,
1278
1279 pub timeout: u64,
1281}
1282
1283impl Default for UploadServiceConfig {
1284 fn default() -> Self {
1285 Self {
1286 objectstore_url: None,
1287 max_concurrent_requests: 100,
1288 timeout: 60,
1289 }
1290 }
1291}
1292
1293#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1296
1297pub enum EmitOutcomes {
1298 None,
1300 AsClientReports,
1302 AsOutcomes,
1304}
1305
1306impl EmitOutcomes {
1307 pub fn any(&self) -> bool {
1309 !matches!(self, EmitOutcomes::None)
1310 }
1311}
1312
1313impl Serialize for EmitOutcomes {
1314 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1315 where
1316 S: Serializer,
1317 {
1318 match self {
1320 Self::None => serializer.serialize_bool(false),
1321 Self::AsClientReports => serializer.serialize_str("as_client_reports"),
1322 Self::AsOutcomes => serializer.serialize_bool(true),
1323 }
1324 }
1325}
1326
1327struct EmitOutcomesVisitor;
1328
1329impl Visitor<'_> for EmitOutcomesVisitor {
1330 type Value = EmitOutcomes;
1331
1332 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1333 formatter.write_str("true, false, or 'as_client_reports'")
1334 }
1335
1336 fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
1337 where
1338 E: serde::de::Error,
1339 {
1340 Ok(if v {
1341 EmitOutcomes::AsOutcomes
1342 } else {
1343 EmitOutcomes::None
1344 })
1345 }
1346
1347 fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1348 where
1349 E: serde::de::Error,
1350 {
1351 if v == "as_client_reports" {
1352 Ok(EmitOutcomes::AsClientReports)
1353 } else {
1354 Err(E::invalid_value(Unexpected::Str(v), &"as_client_reports"))
1355 }
1356 }
1357}
1358
1359impl<'de> Deserialize<'de> for EmitOutcomes {
1360 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1361 where
1362 D: Deserializer<'de>,
1363 {
1364 deserializer.deserialize_any(EmitOutcomesVisitor)
1365 }
1366}
1367
1368#[derive(Serialize, Deserialize, Debug)]
1370#[serde(default)]
1371pub struct Outcomes {
1372 pub emit_outcomes: EmitOutcomes,
1376 pub emit_client_outcomes: bool,
1378 pub batch_size: usize,
1381 pub batch_interval: u64,
1384 pub source: Option<String>,
1387 pub aggregator: OutcomeAggregatorConfig,
1389}
1390
1391impl Default for Outcomes {
1392 fn default() -> Self {
1393 Outcomes {
1394 emit_outcomes: EmitOutcomes::AsClientReports,
1395 emit_client_outcomes: true,
1396 batch_size: 1000,
1397 batch_interval: 500,
1398 source: None,
1399 aggregator: OutcomeAggregatorConfig::default(),
1400 }
1401 }
1402}
1403
1404#[derive(Serialize, Deserialize, Debug, Default)]
1406pub struct MinimalConfig {
1407 pub relay: Relay,
1409}
1410
1411impl MinimalConfig {
1412 pub fn save_in_folder<P: AsRef<Path>>(&self, p: P) -> anyhow::Result<()> {
1414 let path = p.as_ref();
1415 if fs::metadata(path).is_err() {
1416 fs::create_dir_all(path)
1417 .with_context(|| ConfigError::file(ConfigErrorKind::CouldNotOpenFile, path))?;
1418 }
1419 self.save(path)
1420 }
1421}
1422
1423impl ConfigObject for MinimalConfig {
1424 fn format() -> ConfigFormat {
1425 ConfigFormat::Yaml
1426 }
1427
1428 fn name() -> &'static str {
1429 "config"
1430 }
1431}
1432
1433mod config_relay_info {
1435 use serde::ser::SerializeMap;
1436
1437 use super::*;
1438
1439 #[derive(Debug, Serialize, Deserialize, Clone)]
1441 struct RelayInfoConfig {
1442 public_key: PublicKey,
1443 #[serde(default)]
1444 internal: bool,
1445 }
1446
1447 impl From<RelayInfoConfig> for RelayInfo {
1448 fn from(v: RelayInfoConfig) -> Self {
1449 RelayInfo {
1450 public_key: v.public_key,
1451 internal: v.internal,
1452 }
1453 }
1454 }
1455
1456 impl From<RelayInfo> for RelayInfoConfig {
1457 fn from(v: RelayInfo) -> Self {
1458 RelayInfoConfig {
1459 public_key: v.public_key,
1460 internal: v.internal,
1461 }
1462 }
1463 }
1464
1465 pub(super) fn deserialize<'de, D>(des: D) -> Result<HashMap<RelayId, RelayInfo>, D::Error>
1466 where
1467 D: Deserializer<'de>,
1468 {
1469 let map = HashMap::<RelayId, RelayInfoConfig>::deserialize(des)?;
1470 Ok(map.into_iter().map(|(k, v)| (k, v.into())).collect())
1471 }
1472
1473 pub(super) fn serialize<S>(elm: &HashMap<RelayId, RelayInfo>, ser: S) -> Result<S::Ok, S::Error>
1474 where
1475 S: Serializer,
1476 {
1477 let mut map = ser.serialize_map(Some(elm.len()))?;
1478
1479 for (k, v) in elm {
1480 map.serialize_entry(k, &RelayInfoConfig::from(v.clone()))?;
1481 }
1482
1483 map.end()
1484 }
1485}
1486
1487#[derive(Serialize, Deserialize, Debug, Default)]
1489pub struct AuthConfig {
1490 #[serde(default, skip_serializing_if = "is_default")]
1492 pub ready: ReadinessCondition,
1493
1494 #[serde(default, with = "config_relay_info")]
1496 pub static_relays: HashMap<RelayId, RelayInfo>,
1497
1498 #[serde(default = "default_max_age")]
1502 pub signature_max_age: u64,
1503}
1504
1505fn default_max_age() -> u64 {
1506 300
1507}
1508
1509#[derive(Serialize, Deserialize, Debug, Default)]
1511pub struct GeoIpConfig {
1512 pub path: Option<PathBuf>,
1514}
1515
1516#[derive(Serialize, Deserialize, Debug)]
1518#[serde(default)]
1519pub struct CardinalityLimiter {
1520 pub cache_vacuum_interval: u64,
1526}
1527
1528impl Default for CardinalityLimiter {
1529 fn default() -> Self {
1530 Self {
1531 cache_vacuum_interval: 180,
1532 }
1533 }
1534}
1535
1536#[derive(Serialize, Deserialize, Debug)]
1541#[serde(default)]
1542pub struct Health {
1543 pub refresh_interval_ms: u64,
1550 pub max_memory_bytes: Option<ByteSize>,
1555 pub max_memory_percent: f32,
1559 pub probe_timeout_ms: u64,
1566 pub memory_stat_refresh_frequency_ms: u64,
1572}
1573
1574impl Default for Health {
1575 fn default() -> Self {
1576 Self {
1577 refresh_interval_ms: 3000,
1578 max_memory_bytes: None,
1579 max_memory_percent: 0.95,
1580 probe_timeout_ms: 900,
1581 memory_stat_refresh_frequency_ms: 100,
1582 }
1583 }
1584}
1585
1586#[derive(Serialize, Deserialize, Debug)]
1588#[serde(default)]
1589pub struct Cogs {
1590 pub max_queue_size: u64,
1596 pub relay_resource_id: String,
1602}
1603
1604impl Default for Cogs {
1605 fn default() -> Self {
1606 Self {
1607 max_queue_size: 10_000,
1608 relay_resource_id: "relay_service".to_owned(),
1609 }
1610 }
1611}
1612
1613#[derive(Serialize, Deserialize, Debug, Default)]
1614struct ConfigValues {
1615 #[serde(default)]
1616 relay: Relay,
1617 #[serde(default)]
1618 http: Http,
1619 #[serde(default)]
1620 cache: Cache,
1621 #[serde(default)]
1622 spool: Spool,
1623 #[serde(default)]
1624 limits: Limits,
1625 #[serde(default)]
1626 logging: relay_log::LogConfig,
1627 #[serde(default)]
1628 routing: Routing,
1629 #[serde(default)]
1630 metrics: Metrics,
1631 #[serde(default)]
1632 sentry: relay_log::SentryConfig,
1633 #[serde(default)]
1634 processing: Processing,
1635 #[serde(default)]
1636 outcomes: Outcomes,
1637 #[serde(default)]
1638 aggregator: AggregatorServiceConfig,
1639 #[serde(default)]
1640 secondary_aggregators: Vec<ScopedAggregatorConfig>,
1641 #[serde(default)]
1642 auth: AuthConfig,
1643 #[serde(default)]
1644 geoip: GeoIpConfig,
1645 #[serde(default)]
1646 normalization: Normalization,
1647 #[serde(default)]
1648 cardinality_limiter: CardinalityLimiter,
1649 #[serde(default)]
1650 health: Health,
1651 #[serde(default)]
1652 cogs: Cogs,
1653}
1654
1655impl ConfigObject for ConfigValues {
1656 fn format() -> ConfigFormat {
1657 ConfigFormat::Yaml
1658 }
1659
1660 fn name() -> &'static str {
1661 "config"
1662 }
1663}
1664
1665pub struct Config {
1667 values: ConfigValues,
1668 credentials: Option<Credentials>,
1669 path: PathBuf,
1670}
1671
1672impl fmt::Debug for Config {
1673 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1674 f.debug_struct("Config")
1675 .field("path", &self.path)
1676 .field("values", &self.values)
1677 .finish()
1678 }
1679}
1680
1681impl Config {
1682 pub fn from_path<P: AsRef<Path>>(path: P) -> anyhow::Result<Config> {
1684 let path = env::current_dir()
1685 .map(|x| x.join(path.as_ref()))
1686 .unwrap_or_else(|_| path.as_ref().to_path_buf());
1687
1688 let config = Config {
1689 values: ConfigValues::load(&path)?,
1690 credentials: if Credentials::path(&path).exists() {
1691 Some(Credentials::load(&path)?)
1692 } else {
1693 None
1694 },
1695 path: path.clone(),
1696 };
1697
1698 if cfg!(not(feature = "processing")) && config.processing_enabled() {
1699 return Err(ConfigError::file(ConfigErrorKind::ProcessingNotAvailable, &path).into());
1700 }
1701
1702 Ok(config)
1703 }
1704
1705 pub fn from_json_value(value: serde_json::Value) -> anyhow::Result<Config> {
1709 Ok(Config {
1710 values: serde_json::from_value(value)
1711 .with_context(|| ConfigError::new(ConfigErrorKind::BadJson))?,
1712 credentials: None,
1713 path: PathBuf::new(),
1714 })
1715 }
1716
1717 pub fn apply_override(
1720 &mut self,
1721 mut overrides: OverridableConfig,
1722 ) -> anyhow::Result<&mut Self> {
1723 let relay = &mut self.values.relay;
1724
1725 if let Some(mode) = overrides.mode {
1726 relay.mode = mode
1727 .parse::<RelayMode>()
1728 .with_context(|| ConfigError::field("mode"))?;
1729 }
1730
1731 if let Some(deployment) = overrides.instance {
1732 relay.instance = deployment
1733 .parse::<RelayInstance>()
1734 .with_context(|| ConfigError::field("deployment"))?;
1735 }
1736
1737 if let Some(log_level) = overrides.log_level {
1738 self.values.logging.level = log_level.parse()?;
1739 }
1740
1741 if let Some(log_format) = overrides.log_format {
1742 self.values.logging.format = log_format.parse()?;
1743 }
1744
1745 if let Some(upstream) = overrides.upstream {
1746 relay.upstream = upstream
1747 .parse::<UpstreamDescriptor>()
1748 .with_context(|| ConfigError::field("upstream"))?;
1749 } else if let Some(upstream_dsn) = overrides.upstream_dsn {
1750 relay.upstream = upstream_dsn
1751 .parse::<Dsn>()
1752 .map(|dsn| UpstreamDescriptor::from_dsn(&dsn).into_owned())
1753 .with_context(|| ConfigError::field("upstream_dsn"))?;
1754 }
1755
1756 if let Some(host) = overrides.host {
1757 relay.host = host
1758 .parse::<IpAddr>()
1759 .with_context(|| ConfigError::field("host"))?;
1760 }
1761
1762 if let Some(port) = overrides.port {
1763 relay.port = port
1764 .as_str()
1765 .parse()
1766 .with_context(|| ConfigError::field("port"))?;
1767 }
1768
1769 let processing = &mut self.values.processing;
1770 if let Some(enabled) = overrides.processing {
1771 match enabled.to_lowercase().as_str() {
1772 "true" | "1" => processing.enabled = true,
1773 "false" | "0" | "" => processing.enabled = false,
1774 _ => return Err(ConfigError::field("processing").into()),
1775 }
1776 }
1777
1778 if let Some(redis) = overrides.redis_url {
1779 processing.redis = Some(RedisConfigs::Unified(RedisConfig::single(redis)))
1780 }
1781
1782 if let Some(kafka_url) = overrides.kafka_url {
1783 let existing = processing
1784 .kafka_config
1785 .iter_mut()
1786 .find(|e| e.name == "bootstrap.servers");
1787
1788 if let Some(config_param) = existing {
1789 config_param.value = kafka_url;
1790 } else {
1791 processing.kafka_config.push(KafkaConfigParam {
1792 name: "bootstrap.servers".to_owned(),
1793 value: kafka_url,
1794 })
1795 }
1796 }
1797 let id = if let Some(id) = overrides.id {
1799 let id = Uuid::parse_str(&id).with_context(|| ConfigError::field("id"))?;
1800 Some(id)
1801 } else {
1802 None
1803 };
1804 let public_key = if let Some(public_key) = overrides.public_key {
1805 let public_key = public_key
1806 .parse::<PublicKey>()
1807 .with_context(|| ConfigError::field("public_key"))?;
1808 Some(public_key)
1809 } else {
1810 None
1811 };
1812
1813 let secret_key = if let Some(secret_key) = overrides.secret_key {
1814 let secret_key = secret_key
1815 .parse::<SecretKey>()
1816 .with_context(|| ConfigError::field("secret_key"))?;
1817 Some(secret_key)
1818 } else {
1819 None
1820 };
1821 let outcomes = &mut self.values.outcomes;
1822 if overrides.outcome_source.is_some() {
1823 outcomes.source = overrides.outcome_source.take();
1824 }
1825
1826 if let Some(credentials) = &mut self.credentials {
1827 if let Some(id) = id {
1829 credentials.id = id;
1830 }
1831 if let Some(public_key) = public_key {
1832 credentials.public_key = public_key;
1833 }
1834 if let Some(secret_key) = secret_key {
1835 credentials.secret_key = secret_key
1836 }
1837 } else {
1838 match (id, public_key, secret_key) {
1840 (Some(id), Some(public_key), Some(secret_key)) => {
1841 self.credentials = Some(Credentials {
1842 secret_key,
1843 public_key,
1844 id,
1845 })
1846 }
1847 (None, None, None) => {
1848 }
1851 _ => {
1852 return Err(ConfigError::field("incomplete credentials").into());
1853 }
1854 }
1855 }
1856
1857 let limits = &mut self.values.limits;
1858 if let Some(shutdown_timeout) = overrides.shutdown_timeout
1859 && let Ok(shutdown_timeout) = shutdown_timeout.parse::<u64>()
1860 {
1861 limits.shutdown_timeout = shutdown_timeout;
1862 }
1863
1864 if let Some(server_name) = overrides.server_name {
1865 self.values.sentry.server_name = Some(server_name.into());
1866 }
1867
1868 Ok(self)
1869 }
1870
1871 pub fn config_exists<P: AsRef<Path>>(path: P) -> bool {
1873 fs::metadata(ConfigValues::path(path.as_ref())).is_ok()
1874 }
1875
1876 pub fn path(&self) -> &Path {
1878 &self.path
1879 }
1880
1881 pub fn to_yaml_string(&self) -> anyhow::Result<String> {
1883 serde_yaml::to_string(&self.values)
1884 .with_context(|| ConfigError::new(ConfigErrorKind::CouldNotWriteFile))
1885 }
1886
1887 pub fn regenerate_credentials(&mut self, save: bool) -> anyhow::Result<()> {
1891 let creds = Credentials::generate();
1892 if save {
1893 creds.save(&self.path)?;
1894 }
1895 self.credentials = Some(creds);
1896 Ok(())
1897 }
1898
1899 pub fn credentials(&self) -> Option<&Credentials> {
1901 self.credentials.as_ref()
1902 }
1903
1904 pub fn replace_credentials(
1908 &mut self,
1909 credentials: Option<Credentials>,
1910 ) -> anyhow::Result<bool> {
1911 if self.credentials == credentials {
1912 return Ok(false);
1913 }
1914
1915 match credentials {
1916 Some(ref creds) => {
1917 creds.save(&self.path)?;
1918 }
1919 None => {
1920 let path = Credentials::path(&self.path);
1921 if fs::metadata(&path).is_ok() {
1922 fs::remove_file(&path).with_context(|| {
1923 ConfigError::file(ConfigErrorKind::CouldNotWriteFile, &path)
1924 })?;
1925 }
1926 }
1927 }
1928
1929 self.credentials = credentials;
1930 Ok(true)
1931 }
1932
1933 pub fn has_credentials(&self) -> bool {
1935 self.credentials.is_some()
1936 }
1937
1938 pub fn secret_key(&self) -> Option<&SecretKey> {
1940 self.credentials.as_ref().map(|x| &x.secret_key)
1941 }
1942
1943 pub fn public_key(&self) -> Option<&PublicKey> {
1945 self.credentials.as_ref().map(|x| &x.public_key)
1946 }
1947
1948 pub fn relay_id(&self) -> Option<&RelayId> {
1950 self.credentials.as_ref().map(|x| &x.id)
1951 }
1952
1953 pub fn relay_mode(&self) -> RelayMode {
1955 self.values.relay.mode
1956 }
1957
1958 pub fn relay_instance(&self) -> RelayInstance {
1960 self.values.relay.instance
1961 }
1962
1963 pub fn upstream_descriptor(&self) -> &UpstreamDescriptor<'_> {
1965 &self.values.relay.upstream
1966 }
1967
1968 pub fn http_host_header(&self) -> Option<&str> {
1970 self.values.http.host_header.as_deref()
1971 }
1972
1973 pub fn listen_addr(&self) -> SocketAddr {
1975 (self.values.relay.host, self.values.relay.port).into()
1976 }
1977
1978 pub fn listen_addr_internal(&self) -> Option<SocketAddr> {
1986 match (
1987 self.values.relay.internal_host,
1988 self.values.relay.internal_port,
1989 ) {
1990 (Some(host), None) => Some((host, self.values.relay.port).into()),
1991 (None, Some(port)) => Some((self.values.relay.host, port).into()),
1992 (Some(host), Some(port)) => Some((host, port).into()),
1993 (None, None) => None,
1994 }
1995 }
1996
1997 pub fn tls_listen_addr(&self) -> Option<SocketAddr> {
1999 if self.values.relay.tls_identity_path.is_some() {
2000 let port = self.values.relay.tls_port.unwrap_or(3443);
2001 Some((self.values.relay.host, port).into())
2002 } else {
2003 None
2004 }
2005 }
2006
2007 pub fn tls_identity_path(&self) -> Option<&Path> {
2009 self.values.relay.tls_identity_path.as_deref()
2010 }
2011
2012 pub fn tls_identity_password(&self) -> Option<&str> {
2014 self.values.relay.tls_identity_password.as_deref()
2015 }
2016
2017 pub fn override_project_ids(&self) -> bool {
2021 self.values.relay.override_project_ids
2022 }
2023
2024 pub fn requires_auth(&self) -> bool {
2028 match self.values.auth.ready {
2029 ReadinessCondition::Authenticated => self.relay_mode() == RelayMode::Managed,
2030 ReadinessCondition::Always => false,
2031 }
2032 }
2033
2034 pub fn http_auth_interval(&self) -> Option<Duration> {
2038 if self.processing_enabled() {
2039 return None;
2040 }
2041
2042 match self.values.http.auth_interval {
2043 None | Some(0) => None,
2044 Some(secs) => Some(Duration::from_secs(secs)),
2045 }
2046 }
2047
2048 pub fn http_outage_grace_period(&self) -> Duration {
2051 Duration::from_secs(self.values.http.outage_grace_period)
2052 }
2053
2054 pub fn http_retry_delay(&self) -> Duration {
2059 Duration::from_secs(self.values.http.retry_delay)
2060 }
2061
2062 pub fn http_project_failure_interval(&self) -> Duration {
2064 Duration::from_secs(self.values.http.project_failure_interval)
2065 }
2066
2067 pub fn http_encoding(&self) -> HttpEncoding {
2069 self.values.http.encoding
2070 }
2071
2072 pub fn http_global_metrics(&self) -> bool {
2074 self.values.http.global_metrics
2075 }
2076
2077 pub fn emit_outcomes(&self) -> EmitOutcomes {
2082 if self.processing_enabled() {
2083 return EmitOutcomes::AsOutcomes;
2084 }
2085 self.values.outcomes.emit_outcomes
2086 }
2087
2088 pub fn emit_client_outcomes(&self) -> bool {
2098 self.values.outcomes.emit_client_outcomes
2099 }
2100
2101 pub fn outcome_batch_size(&self) -> usize {
2103 self.values.outcomes.batch_size
2104 }
2105
2106 pub fn outcome_batch_interval(&self) -> Duration {
2108 Duration::from_millis(self.values.outcomes.batch_interval)
2109 }
2110
2111 pub fn outcome_source(&self) -> Option<&str> {
2113 self.values.outcomes.source.as_deref()
2114 }
2115
2116 pub fn outcome_aggregator(&self) -> &OutcomeAggregatorConfig {
2118 &self.values.outcomes.aggregator
2119 }
2120
2121 pub fn logging(&self) -> &relay_log::LogConfig {
2123 &self.values.logging
2124 }
2125
2126 pub fn sentry(&self) -> &relay_log::SentryConfig {
2128 &self.values.sentry
2129 }
2130
2131 pub fn statsd_addrs(&self) -> anyhow::Result<Vec<SocketAddr>> {
2135 if let Some(ref addr) = self.values.metrics.statsd {
2136 let addrs = addr
2137 .as_str()
2138 .to_socket_addrs()
2139 .with_context(|| ConfigError::file(ConfigErrorKind::InvalidValue, &self.path))?
2140 .collect();
2141 Ok(addrs)
2142 } else {
2143 Ok(vec![])
2144 }
2145 }
2146
2147 pub fn metrics_prefix(&self) -> &str {
2149 &self.values.metrics.prefix
2150 }
2151
2152 pub fn metrics_default_tags(&self) -> &BTreeMap<String, String> {
2154 &self.values.metrics.default_tags
2155 }
2156
2157 pub fn metrics_hostname_tag(&self) -> Option<&str> {
2159 self.values.metrics.hostname_tag.as_deref()
2160 }
2161
2162 pub fn metrics_sample_rate(&self) -> f32 {
2164 self.values.metrics.sample_rate
2165 }
2166
2167 pub fn metrics_aggregate(&self) -> bool {
2169 self.values.metrics.aggregate
2170 }
2171
2172 pub fn metrics_allow_high_cardinality_tags(&self) -> bool {
2174 self.values.metrics.allow_high_cardinality_tags
2175 }
2176
2177 pub fn metrics_periodic_interval(&self) -> Option<Duration> {
2181 match self.values.metrics.periodic_secs {
2182 0 => None,
2183 secs => Some(Duration::from_secs(secs)),
2184 }
2185 }
2186
2187 pub fn http_timeout(&self) -> Duration {
2189 Duration::from_secs(self.values.http.timeout.into())
2190 }
2191
2192 pub fn http_connection_timeout(&self) -> Duration {
2194 Duration::from_secs(self.values.http.connection_timeout.into())
2195 }
2196
2197 pub fn http_max_retry_interval(&self) -> Duration {
2199 Duration::from_secs(self.values.http.max_retry_interval.into())
2200 }
2201
2202 pub fn project_cache_expiry(&self) -> Duration {
2204 Duration::from_secs(self.values.cache.project_expiry.into())
2205 }
2206
2207 pub fn request_full_project_config(&self) -> bool {
2209 self.values.cache.project_request_full_config
2210 }
2211
2212 pub fn relay_cache_expiry(&self) -> Duration {
2214 Duration::from_secs(self.values.cache.relay_expiry.into())
2215 }
2216
2217 pub fn envelope_buffer_size(&self) -> usize {
2219 self.values
2220 .cache
2221 .envelope_buffer_size
2222 .try_into()
2223 .unwrap_or(usize::MAX)
2224 }
2225
2226 pub fn cache_miss_expiry(&self) -> Duration {
2228 Duration::from_secs(self.values.cache.miss_expiry.into())
2229 }
2230
2231 pub fn project_grace_period(&self) -> Duration {
2233 Duration::from_secs(self.values.cache.project_grace_period.into())
2234 }
2235
2236 pub fn project_refresh_interval(&self) -> Option<Duration> {
2240 self.values
2241 .cache
2242 .project_refresh_interval
2243 .map(Into::into)
2244 .map(Duration::from_secs)
2245 }
2246
2247 pub fn query_batch_interval(&self) -> Duration {
2250 Duration::from_millis(self.values.cache.batch_interval.into())
2251 }
2252
2253 pub fn downstream_relays_batch_interval(&self) -> Duration {
2255 Duration::from_millis(self.values.cache.downstream_relays_batch_interval.into())
2256 }
2257
2258 pub fn local_cache_interval(&self) -> Duration {
2260 Duration::from_secs(self.values.cache.file_interval.into())
2261 }
2262
2263 pub fn global_config_fetch_interval(&self) -> Duration {
2266 Duration::from_secs(self.values.cache.global_config_fetch_interval.into())
2267 }
2268
2269 pub fn spool_envelopes_path(&self, partition_id: u8) -> Option<PathBuf> {
2274 let mut path = self
2275 .values
2276 .spool
2277 .envelopes
2278 .path
2279 .as_ref()
2280 .map(|path| path.to_owned())?;
2281
2282 if partition_id == 0 {
2283 return Some(path);
2284 }
2285
2286 let file_name = path.file_name().and_then(|f| f.to_str())?;
2287 let new_file_name = format!("{file_name}.{partition_id}");
2288 path.set_file_name(new_file_name);
2289
2290 Some(path)
2291 }
2292
2293 pub fn spool_envelopes_max_disk_size(&self) -> usize {
2295 self.values.spool.envelopes.max_disk_size.as_bytes()
2296 }
2297
2298 pub fn spool_envelopes_batch_size_bytes(&self) -> usize {
2301 self.values.spool.envelopes.batch_size_bytes.as_bytes()
2302 }
2303
2304 pub fn spool_envelopes_max_age(&self) -> Duration {
2306 Duration::from_secs(self.values.spool.envelopes.max_envelope_delay_secs)
2307 }
2308
2309 pub fn spool_disk_usage_refresh_frequency_ms(&self) -> Duration {
2311 Duration::from_millis(self.values.spool.envelopes.disk_usage_refresh_frequency_ms)
2312 }
2313
2314 pub fn spool_max_backpressure_envelopes(&self) -> usize {
2316 self.values.spool.envelopes.max_backpressure_envelopes
2317 }
2318
2319 pub fn spool_max_backpressure_memory_percent(&self) -> f32 {
2321 self.values.spool.envelopes.max_backpressure_memory_percent
2322 }
2323
2324 pub fn spool_partitions(&self) -> NonZeroU8 {
2326 self.values.spool.envelopes.partitions
2327 }
2328
2329 pub fn max_event_size(&self) -> usize {
2331 self.values.limits.max_event_size.as_bytes()
2332 }
2333
2334 pub fn max_attachment_size(&self) -> usize {
2336 self.values.limits.max_attachment_size.as_bytes()
2337 }
2338
2339 pub fn max_attachments_size(&self) -> usize {
2342 self.values.limits.max_attachments_size.as_bytes()
2343 }
2344
2345 pub fn max_client_reports_size(&self) -> usize {
2347 self.values.limits.max_client_reports_size.as_bytes()
2348 }
2349
2350 pub fn max_check_in_size(&self) -> usize {
2352 self.values.limits.max_check_in_size.as_bytes()
2353 }
2354
2355 pub fn max_log_size(&self) -> usize {
2357 self.values.limits.max_log_size.as_bytes()
2358 }
2359
2360 pub fn max_span_size(&self) -> usize {
2362 self.values.limits.max_span_size.as_bytes()
2363 }
2364
2365 pub fn max_container_size(&self) -> usize {
2367 self.values.limits.max_container_size.as_bytes()
2368 }
2369
2370 pub fn max_envelope_size(&self) -> usize {
2374 self.values.limits.max_envelope_size.as_bytes()
2375 }
2376
2377 pub fn max_session_count(&self) -> usize {
2379 self.values.limits.max_session_count
2380 }
2381
2382 pub fn max_span_count(&self) -> usize {
2384 self.values.limits.max_span_count
2385 }
2386
2387 pub fn max_log_count(&self) -> usize {
2389 self.values.limits.max_log_count
2390 }
2391
2392 pub fn max_trace_metric_count(&self) -> usize {
2394 self.values.limits.max_trace_metric_count
2395 }
2396
2397 pub fn max_statsd_size(&self) -> usize {
2399 self.values.limits.max_statsd_size.as_bytes()
2400 }
2401
2402 pub fn max_metric_buckets_size(&self) -> usize {
2404 self.values.limits.max_metric_buckets_size.as_bytes()
2405 }
2406
2407 pub fn max_api_payload_size(&self) -> usize {
2409 self.values.limits.max_api_payload_size.as_bytes()
2410 }
2411
2412 pub fn max_api_file_upload_size(&self) -> usize {
2414 self.values.limits.max_api_file_upload_size.as_bytes()
2415 }
2416
2417 pub fn max_api_chunk_upload_size(&self) -> usize {
2419 self.values.limits.max_api_chunk_upload_size.as_bytes()
2420 }
2421
2422 pub fn max_profile_size(&self) -> usize {
2424 self.values.limits.max_profile_size.as_bytes()
2425 }
2426
2427 pub fn max_trace_metric_size(&self) -> usize {
2429 self.values.limits.max_trace_metric_size.as_bytes()
2430 }
2431
2432 pub fn max_replay_compressed_size(&self) -> usize {
2434 self.values.limits.max_replay_compressed_size.as_bytes()
2435 }
2436
2437 pub fn max_replay_uncompressed_size(&self) -> usize {
2439 self.values.limits.max_replay_uncompressed_size.as_bytes()
2440 }
2441
2442 pub fn max_replay_message_size(&self) -> usize {
2448 self.values.limits.max_replay_message_size.as_bytes()
2449 }
2450
2451 pub fn max_concurrent_requests(&self) -> usize {
2453 self.values.limits.max_concurrent_requests
2454 }
2455
2456 pub fn max_concurrent_queries(&self) -> usize {
2458 self.values.limits.max_concurrent_queries
2459 }
2460
2461 pub fn query_timeout(&self) -> Duration {
2463 Duration::from_secs(self.values.limits.query_timeout)
2464 }
2465
2466 pub fn shutdown_timeout(&self) -> Duration {
2469 Duration::from_secs(self.values.limits.shutdown_timeout)
2470 }
2471
2472 pub fn keepalive_timeout(&self) -> Duration {
2476 Duration::from_secs(self.values.limits.keepalive_timeout)
2477 }
2478
2479 pub fn idle_timeout(&self) -> Option<Duration> {
2481 self.values.limits.idle_timeout.map(Duration::from_secs)
2482 }
2483
2484 pub fn max_connections(&self) -> Option<usize> {
2486 self.values.limits.max_connections
2487 }
2488
2489 pub fn tcp_listen_backlog(&self) -> u32 {
2491 self.values.limits.tcp_listen_backlog
2492 }
2493
2494 pub fn cpu_concurrency(&self) -> usize {
2496 self.values.limits.max_thread_count
2497 }
2498
2499 pub fn pool_concurrency(&self) -> usize {
2501 self.values.limits.max_pool_concurrency
2502 }
2503
2504 pub fn query_batch_size(&self) -> usize {
2506 self.values.cache.batch_size
2507 }
2508
2509 pub fn project_configs_path(&self) -> PathBuf {
2511 self.path.join("projects")
2512 }
2513
2514 pub fn processing_enabled(&self) -> bool {
2516 self.values.processing.enabled
2517 }
2518
2519 pub fn normalization_level(&self) -> NormalizationLevel {
2521 self.values.normalization.level
2522 }
2523
2524 pub fn geoip_path(&self) -> Option<&Path> {
2526 self.values
2527 .geoip
2528 .path
2529 .as_deref()
2530 .or(self.values.processing.geoip_path.as_deref())
2531 }
2532
2533 pub fn max_secs_in_future(&self) -> i64 {
2537 self.values.processing.max_secs_in_future.into()
2538 }
2539
2540 pub fn max_session_secs_in_past(&self) -> i64 {
2542 self.values.processing.max_session_secs_in_past.into()
2543 }
2544
2545 pub fn kafka_configs(
2547 &self,
2548 topic: KafkaTopic,
2549 ) -> Result<KafkaTopicConfig<'_>, KafkaConfigError> {
2550 self.values.processing.topics.get(topic).kafka_configs(
2551 &self.values.processing.kafka_config,
2552 &self.values.processing.secondary_kafka_configs,
2553 )
2554 }
2555
2556 pub fn kafka_validate_topics(&self) -> bool {
2558 self.values.processing.kafka_validate_topics
2559 }
2560
2561 pub fn unused_topic_assignments(&self) -> &relay_kafka::Unused {
2563 &self.values.processing.topics.unused
2564 }
2565
2566 pub fn upload(&self) -> &UploadServiceConfig {
2568 &self.values.processing.upload
2569 }
2570
2571 pub fn redis(&self) -> Option<RedisConfigsRef<'_>> {
2574 let redis_configs = self.values.processing.redis.as_ref()?;
2575
2576 Some(build_redis_configs(
2577 redis_configs,
2578 self.cpu_concurrency() as u32,
2579 self.pool_concurrency() as u32,
2580 ))
2581 }
2582
2583 pub fn attachment_chunk_size(&self) -> usize {
2585 self.values.processing.attachment_chunk_size.as_bytes()
2586 }
2587
2588 pub fn metrics_max_batch_size_bytes(&self) -> usize {
2590 self.values.aggregator.max_flush_bytes
2591 }
2592
2593 pub fn projectconfig_cache_prefix(&self) -> &str {
2596 &self.values.processing.projectconfig_cache_prefix
2597 }
2598
2599 pub fn max_rate_limit(&self) -> Option<u64> {
2601 self.values.processing.max_rate_limit.map(u32::into)
2602 }
2603
2604 pub fn cardinality_limiter_cache_vacuum_interval(&self) -> Duration {
2608 Duration::from_secs(self.values.cardinality_limiter.cache_vacuum_interval)
2609 }
2610
2611 pub fn health_refresh_interval(&self) -> Duration {
2613 Duration::from_millis(self.values.health.refresh_interval_ms)
2614 }
2615
2616 pub fn health_max_memory_watermark_bytes(&self) -> u64 {
2618 self.values
2619 .health
2620 .max_memory_bytes
2621 .as_ref()
2622 .map_or(u64::MAX, |b| b.as_bytes() as u64)
2623 }
2624
2625 pub fn health_max_memory_watermark_percent(&self) -> f32 {
2627 self.values.health.max_memory_percent
2628 }
2629
2630 pub fn health_probe_timeout(&self) -> Duration {
2632 Duration::from_millis(self.values.health.probe_timeout_ms)
2633 }
2634
2635 pub fn memory_stat_refresh_frequency_ms(&self) -> u64 {
2637 self.values.health.memory_stat_refresh_frequency_ms
2638 }
2639
2640 pub fn cogs_max_queue_size(&self) -> u64 {
2642 self.values.cogs.max_queue_size
2643 }
2644
2645 pub fn cogs_relay_resource_id(&self) -> &str {
2647 &self.values.cogs.relay_resource_id
2648 }
2649
2650 pub fn default_aggregator_config(&self) -> &AggregatorServiceConfig {
2652 &self.values.aggregator
2653 }
2654
2655 pub fn secondary_aggregator_configs(&self) -> &Vec<ScopedAggregatorConfig> {
2657 &self.values.secondary_aggregators
2658 }
2659
2660 pub fn aggregator_config_for(&self, namespace: MetricNamespace) -> &AggregatorServiceConfig {
2662 for entry in &self.values.secondary_aggregators {
2663 if entry.condition.matches(Some(namespace)) {
2664 return &entry.config;
2665 }
2666 }
2667 &self.values.aggregator
2668 }
2669
2670 pub fn static_relays(&self) -> &HashMap<RelayId, RelayInfo> {
2672 &self.values.auth.static_relays
2673 }
2674
2675 pub fn signature_max_age(&self) -> Duration {
2677 Duration::from_secs(self.values.auth.signature_max_age)
2678 }
2679
2680 pub fn accept_unknown_items(&self) -> bool {
2682 let forward = self.values.routing.accept_unknown_items;
2683 forward.unwrap_or_else(|| !self.processing_enabled())
2684 }
2685}
2686
2687impl Default for Config {
2688 fn default() -> Self {
2689 Self {
2690 values: ConfigValues::default(),
2691 credentials: None,
2692 path: PathBuf::new(),
2693 }
2694 }
2695}
2696
2697#[cfg(test)]
2698mod tests {
2699
2700 use super::*;
2701
2702 #[test]
2704 fn test_event_buffer_size() {
2705 let yaml = r###"
2706cache:
2707 event_buffer_size: 1000000
2708 event_expiry: 1800
2709"###;
2710
2711 let values: ConfigValues = serde_yaml::from_str(yaml).unwrap();
2712 assert_eq!(values.cache.envelope_buffer_size, 1_000_000);
2713 assert_eq!(values.cache.envelope_expiry, 1800);
2714 }
2715
2716 #[test]
2717 fn test_emit_outcomes() {
2718 for (serialized, deserialized) in &[
2719 ("true", EmitOutcomes::AsOutcomes),
2720 ("false", EmitOutcomes::None),
2721 ("\"as_client_reports\"", EmitOutcomes::AsClientReports),
2722 ] {
2723 let value: EmitOutcomes = serde_json::from_str(serialized).unwrap();
2724 assert_eq!(value, *deserialized);
2725 assert_eq!(serde_json::to_string(&value).unwrap(), *serialized);
2726 }
2727 }
2728
2729 #[test]
2730 fn test_emit_outcomes_invalid() {
2731 assert!(serde_json::from_str::<EmitOutcomes>("asdf").is_err());
2732 }
2733}