relay_config/
config.rs

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/// Indicates config related errors.
36#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
37#[non_exhaustive]
38pub enum ConfigErrorKind {
39    /// Failed to open the file.
40    CouldNotOpenFile,
41    /// Failed to save a file.
42    CouldNotWriteFile,
43    /// Parsing YAML failed.
44    BadYaml,
45    /// Parsing JSON failed.
46    BadJson,
47    /// Invalid config value
48    InvalidValue,
49    /// The user attempted to run Relay with processing enabled, but uses a binary that was
50    /// compiled without the processing feature.
51    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/// Defines the source of a config error
71#[derive(Debug, Default)]
72enum ConfigErrorSource {
73    /// An error occurring independently.
74    #[default]
75    None,
76    /// An error originating from a configuration file.
77    File(PathBuf),
78    /// An error originating in a field override (an env var, or a CLI parameter).
79    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/// Indicates config related errors.
95#[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    /// Returns the error kind of the error.
127    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    /// The format in which to serialize this configuration.
156    fn format() -> ConfigFormat;
157
158    /// The basename of the config file.
159    fn name() -> &'static str;
160
161    /// The full filename of the config file, including the file extension.
162    fn path(base: &Path) -> PathBuf {
163        base.join(format!("{}.{}", Self::name(), Self::format().extension()))
164    }
165
166    /// Loads the config file from a file within the given directory location.
167    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    /// Writes the configuration to a file within the given directory location.
188    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        // Remove all non-user permissions for the newly created file
194        #[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/// Structure used to hold information about configuration overrides via
221/// CLI parameters or environment variables
222#[derive(Debug, Default)]
223pub struct OverridableConfig {
224    /// The operation mode of this relay.
225    pub mode: Option<String>,
226    /// The instance type of this relay.
227    pub instance: Option<String>,
228    /// The log level of this relay.
229    pub log_level: Option<String>,
230    /// The log format of this relay.
231    pub log_format: Option<String>,
232    /// The upstream relay or sentry instance.
233    pub upstream: Option<String>,
234    /// Alternate upstream provided through a Sentry DSN. Key and project will be ignored.
235    pub upstream_dsn: Option<String>,
236    /// The host the relay should bind to (network interface).
237    pub host: Option<String>,
238    /// The port to bind for the unencrypted relay HTTP server.
239    pub port: Option<String>,
240    /// "true" if processing is enabled "false" otherwise
241    pub processing: Option<String>,
242    /// the kafka bootstrap.servers configuration string
243    pub kafka_url: Option<String>,
244    /// the redis server url
245    pub redis_url: Option<String>,
246    /// The globally unique ID of the relay.
247    pub id: Option<String>,
248    /// The secret key of the relay
249    pub secret_key: Option<String>,
250    /// The public key of the relay
251    pub public_key: Option<String>,
252    /// Outcome source
253    pub outcome_source: Option<String>,
254    /// shutdown timeout
255    pub shutdown_timeout: Option<String>,
256    /// Server name reported in the Sentry SDK.
257    pub server_name: Option<String>,
258}
259
260/// The relay credentials
261#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
262pub struct Credentials {
263    /// The secret key of the relay
264    pub secret_key: SecretKey,
265    /// The public key of the relay
266    pub public_key: PublicKey,
267    /// The globally unique ID of the relay.
268    pub id: RelayId,
269}
270
271impl Credentials {
272    /// Generates new random credentials.
273    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    /// Serializes this configuration to JSON.
284    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/// Information on a downstream Relay.
300#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
301#[serde(rename_all = "camelCase")]
302pub struct RelayInfo {
303    /// The public key that this Relay uses to authenticate and sign requests.
304    pub public_key: PublicKey,
305
306    /// Marks an internal relay that has privileged access to more project configuration.
307    #[serde(default)]
308    pub internal: bool,
309}
310
311impl RelayInfo {
312    /// Creates a new RelayInfo
313    pub fn new(public_key: PublicKey) -> Self {
314        Self {
315            public_key,
316            internal: false,
317        }
318    }
319}
320
321/// The operation mode of a relay.
322#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
323#[serde(rename_all = "camelCase")]
324pub enum RelayMode {
325    /// This relay acts as a proxy for all requests and events.
326    ///
327    /// Events are normalized and rate limits from the upstream are enforced, but the relay will not
328    /// fetch project configurations from the upstream or perform PII stripping. All events are
329    /// accepted unless overridden on the file system.
330    Proxy,
331
332    /// Project configurations are managed by the upstream.
333    ///
334    /// Project configurations are always fetched from the upstream, unless they are statically
335    /// overridden in the file system. This relay must be allowed in the upstream Sentry. This is
336    /// only possible, if the upstream is Sentry directly, or another managed Relay.
337    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/// The instance type of Relay.
370#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
371#[serde(rename_all = "camelCase")]
372pub enum RelayInstance {
373    /// This Relay is run as a default instance.
374    Default,
375
376    /// This Relay is run as a canary instance where experiments can be run.
377    Canary,
378}
379
380impl RelayInstance {
381    /// Returns `true` if the [`RelayInstance`] is of type [`RelayInstance::Canary`].
382    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/// Error returned when parsing an invalid [`RelayMode`].
408#[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
431/// Returns `true` if this value is equal to `Default::default()`.
432fn is_default<T: Default + PartialEq>(t: &T) -> bool {
433    *t == T::default()
434}
435
436/// Checks if we are running in docker.
437fn 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
445/// Default value for the "bind" configuration.
446fn default_host() -> IpAddr {
447    if is_docker() {
448        // Docker images rely on this service being exposed
449        "0.0.0.0".parse().unwrap()
450    } else {
451        "127.0.0.1".parse().unwrap()
452    }
453}
454
455/// Controls responses from the readiness health check endpoint based on authentication.
456///
457/// Independent of the the readiness condition, shutdown always switches Relay into unready state.
458#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
459#[serde(rename_all = "lowercase")]
460#[derive(Default)]
461pub enum ReadinessCondition {
462    /// (default) Relay is ready when authenticated and connected to the upstream.
463    ///
464    /// Before authentication has succeeded and during network outages, Relay responds as not ready.
465    /// Relay reauthenticates based on the `http.auth_interval` parameter. During reauthentication,
466    /// Relay remains ready until authentication fails.
467    ///
468    /// Authentication is only required for Relays in managed mode. Other Relays will only check for
469    /// network outages.
470    #[default]
471    Authenticated,
472    /// Relay reports readiness regardless of the authentication and networking state.
473    Always,
474}
475
476/// Relay specific configuration values.
477#[derive(Serialize, Deserialize, Debug)]
478#[serde(default)]
479pub struct Relay {
480    /// The operation mode of this relay.
481    pub mode: RelayMode,
482    /// The instance type of this relay.
483    pub instance: RelayInstance,
484    /// The upstream relay or sentry instance.
485    pub upstream: UpstreamDescriptor<'static>,
486    /// The host the relay should bind to (network interface).
487    pub host: IpAddr,
488    /// The port to bind for the unencrypted relay HTTP server.
489    pub port: u16,
490    /// The host the relay should bind to (network interface) for internally exposed APIs, like
491    /// health checks.
492    ///
493    /// If not configured, internal routes are exposed on the main HTTP server.
494    ///
495    /// Note: configuring the internal http server on an address which overlaps with the main
496    /// server (e.g. main on `0.0.0.0:3000` and internal on `127.0.0.1:3000`) is a misconfiguration
497    /// resulting in approximately half of the requests sent to `127.0.0.1:3000` to fail, as the handling
498    /// http server is chosen by the operating system 'at random'.
499    ///
500    /// As a best practice you should always choose different ports to avoid this issue.
501    ///
502    /// Defaults to [`Self::host`].
503    pub internal_host: Option<IpAddr>,
504    /// The port to bind for internally exposed APIs.
505    ///
506    /// Defaults to [`Self::port`].
507    pub internal_port: Option<u16>,
508    /// Optional port to bind for the encrypted relay HTTPS server.
509    #[serde(skip_serializing)]
510    pub tls_port: Option<u16>,
511    /// The path to the identity (DER-encoded PKCS12) to use for TLS.
512    #[serde(skip_serializing)]
513    pub tls_identity_path: Option<PathBuf>,
514    /// Password for the PKCS12 archive.
515    #[serde(skip_serializing)]
516    pub tls_identity_password: Option<String>,
517    /// Always override project IDs from the URL and DSN with the identifier used at the upstream.
518    ///
519    /// Enable this setting for Relays used to redirect traffic to a migrated Sentry instance.
520    /// Validation of project identifiers can be safely skipped in these cases.
521    #[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/// Control the metrics.
544#[derive(Serialize, Deserialize, Debug)]
545#[serde(default)]
546pub struct Metrics {
547    /// Hostname and port of the statsd server.
548    ///
549    /// Defaults to `None`.
550    pub statsd: Option<String>,
551    /// Common prefix that should be added to all metrics.
552    ///
553    /// Defaults to `"sentry.relay"`.
554    pub prefix: String,
555    /// Default tags to apply to all metrics.
556    pub default_tags: BTreeMap<String, String>,
557    /// Tag name to report the hostname to for each metric. Defaults to not sending such a tag.
558    pub hostname_tag: Option<String>,
559    /// Global sample rate for all emitted metrics between `0.0` and `1.0`.
560    ///
561    /// For example, a value of `0.3` means that only 30% of the emitted metrics will be sent.
562    /// Defaults to `1.0` (100%).
563    pub sample_rate: f32,
564    /// Interval for periodic metrics emitted from Relay.
565    ///
566    /// Setting it to `0` seconds disables the periodic metrics.
567    /// Defaults to 5 seconds.
568    pub periodic_secs: u64,
569    /// Whether local metric aggregation using statdsproxy should be enabled.
570    ///
571    /// Defaults to `true`.
572    pub aggregate: bool,
573    /// Allows emission of metrics with high cardinality tags.
574    ///
575    /// High cardinality tags are dynamic values attached to metrics,
576    /// such as project IDs. When enabled, these tags will be included
577    /// in the emitted metrics. When disabled, the tags will be omitted.
578    ///
579    /// Defaults to `false`.
580    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/// Controls various limits
599#[derive(Serialize, Deserialize, Debug)]
600#[serde(default)]
601pub struct Limits {
602    /// How many requests can be sent concurrently from Relay to the upstream before Relay starts
603    /// buffering.
604    pub max_concurrent_requests: usize,
605    /// How many queries can be sent concurrently from Relay to the upstream before Relay starts
606    /// buffering.
607    ///
608    /// The concurrency of queries is additionally constrained by `max_concurrent_requests`.
609    pub max_concurrent_queries: usize,
610    /// The maximum payload size for events.
611    pub max_event_size: ByteSize,
612    /// The maximum size for each attachment.
613    pub max_attachment_size: ByteSize,
614    /// The maximum combined size for all attachments in an envelope or request.
615    pub max_attachments_size: ByteSize,
616    /// The maximum combined size for all client reports in an envelope or request.
617    pub max_client_reports_size: ByteSize,
618    /// The maximum payload size for a monitor check-in.
619    pub max_check_in_size: ByteSize,
620    /// The maximum payload size for an entire envelopes. Individual limits still apply.
621    pub max_envelope_size: ByteSize,
622    /// The maximum number of session items per envelope.
623    pub max_session_count: usize,
624    /// The maximum number of standalone span items per envelope.
625    pub max_span_count: usize,
626    /// The maximum number of log items per envelope.
627    pub max_log_count: usize,
628    /// The maximum number of trace metrics per envelope.
629    pub max_trace_metric_count: usize,
630    /// The maximum payload size for general API requests.
631    pub max_api_payload_size: ByteSize,
632    /// The maximum payload size for file uploads and chunks.
633    pub max_api_file_upload_size: ByteSize,
634    /// The maximum payload size for chunks
635    pub max_api_chunk_upload_size: ByteSize,
636    /// The maximum payload size for a profile
637    pub max_profile_size: ByteSize,
638    /// The maximum payload size for a trace metric.
639    pub max_trace_metric_size: ByteSize,
640    /// The maximum payload size for a log.
641    pub max_log_size: ByteSize,
642    /// The maximum payload size for a span.
643    pub max_span_size: ByteSize,
644    /// The maximum payload size for an item container.
645    pub max_container_size: ByteSize,
646    /// The maximum payload size for a statsd metric.
647    pub max_statsd_size: ByteSize,
648    /// The maximum payload size for metric buckets.
649    pub max_metric_buckets_size: ByteSize,
650    /// The maximum payload size for a compressed replay.
651    pub max_replay_compressed_size: ByteSize,
652    /// The maximum payload size for an uncompressed replay.
653    #[serde(alias = "max_replay_size")]
654    max_replay_uncompressed_size: ByteSize,
655    /// The maximum size for a replay recording Kafka message.
656    pub max_replay_message_size: ByteSize,
657    /// The maximum number of threads to spawn for CPU and web work, each.
658    ///
659    /// The total number of threads spawned will roughly be `2 * max_thread_count`. Defaults to
660    /// the number of logical CPU cores on the host.
661    pub max_thread_count: usize,
662    /// Controls the maximum concurrency of each worker thread.
663    ///
664    /// Increasing the concurrency, can lead to a better utilization of worker threads by
665    /// increasing the amount of I/O done concurrently.
666    //
667    /// Currently has no effect on defaults to `1`.
668    pub max_pool_concurrency: usize,
669    /// The maximum number of seconds a query is allowed to take across retries. Individual requests
670    /// have lower timeouts. Defaults to 30 seconds.
671    pub query_timeout: u64,
672    /// The maximum number of seconds to wait for pending envelopes after receiving a shutdown
673    /// signal.
674    pub shutdown_timeout: u64,
675    /// Server keep-alive timeout in seconds.
676    ///
677    /// By default, keep-alive is set to 5 seconds.
678    pub keepalive_timeout: u64,
679    /// Server idle timeout in seconds.
680    ///
681    /// The idle timeout limits the amount of time a connection is kept open without activity.
682    /// Setting this too short may abort connections before Relay is able to send a response.
683    ///
684    /// By default there is no idle timeout.
685    pub idle_timeout: Option<u64>,
686    /// Sets the maximum number of concurrent connections.
687    ///
688    /// Upon reaching the limit, the server will stop accepting connections.
689    ///
690    /// By default there is no limit.
691    pub max_connections: Option<usize>,
692    /// The TCP listen backlog.
693    ///
694    /// Configures the TCP listen backlog for the listening socket of Relay.
695    /// See [`man listen(2)`](https://man7.org/linux/man-pages/man2/listen.2.html)
696    /// for a more detailed description of the listen backlog.
697    ///
698    /// Defaults to `1024`, a value [google has been using for a long time](https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/commit/?id=19f92a030ca6d772ab44b22ee6a01378a8cb32d4).
699    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/// Controls traffic steering.
743#[derive(Debug, Default, Deserialize, Serialize)]
744#[serde(default)]
745pub struct Routing {
746    /// Accept and forward unknown Envelope items to the upstream.
747    ///
748    /// Forwarding unknown items should be enabled in most cases to allow proxying traffic for newer
749    /// SDK versions. The upstream in Sentry makes the final decision on which items are valid. If
750    /// this is disabled, just the unknown items are removed from Envelopes, and the rest is
751    /// processed as usual.
752    ///
753    /// Defaults to `true` for all Relay modes other than processing mode. In processing mode, this
754    /// is disabled by default since the item cannot be handled.
755    pub accept_unknown_items: Option<bool>,
756}
757
758/// Http content encoding for both incoming and outgoing web requests.
759#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize)]
760#[serde(rename_all = "lowercase")]
761pub enum HttpEncoding {
762    /// Identity function without no compression.
763    ///
764    /// This is the default encoding and does not require the presence of the `content-encoding`
765    /// HTTP header.
766    #[default]
767    Identity,
768    /// Compression using a [zlib](https://en.wikipedia.org/wiki/Zlib) structure with
769    /// [deflate](https://en.wikipedia.org/wiki/DEFLATE) encoding.
770    ///
771    /// These structures are defined in [RFC 1950](https://datatracker.ietf.org/doc/html/rfc1950)
772    /// and [RFC 1951](https://datatracker.ietf.org/doc/html/rfc1951).
773    Deflate,
774    /// A format using the [Lempel-Ziv coding](https://en.wikipedia.org/wiki/LZ77_and_LZ78#LZ77)
775    /// (LZ77), with a 32-bit CRC.
776    ///
777    /// This is the original format of the UNIX gzip program. The HTTP/1.1 standard also recommends
778    /// that the servers supporting this content-encoding should recognize `x-gzip` as an alias, for
779    /// compatibility purposes.
780    Gzip,
781    /// A format using the [Brotli](https://en.wikipedia.org/wiki/Brotli) algorithm.
782    Br,
783    /// A format using the [Zstd](https://en.wikipedia.org/wiki/Zstd) compression algorithm.
784    Zstd,
785}
786
787impl HttpEncoding {
788    /// Parses a [`HttpEncoding`] from its `content-encoding` header value.
789    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    /// Returns the value for the `content-encoding` HTTP header.
805    ///
806    /// Returns `None` for [`Identity`](Self::Identity), and `Some` for other encodings.
807    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/// Controls authentication with upstream.
819#[derive(Serialize, Deserialize, Debug)]
820#[serde(default)]
821pub struct Http {
822    /// Timeout for upstream requests in seconds.
823    ///
824    /// This timeout covers the time from sending the request until receiving response headers.
825    /// Neither the connection process and handshakes, nor reading the response body is covered in
826    /// this timeout.
827    pub timeout: u32,
828    /// Timeout for establishing connections with the upstream in seconds.
829    ///
830    /// This includes SSL handshakes. Relay reuses connections when the upstream supports connection
831    /// keep-alive. Connections are retained for a maximum 75 seconds, or 15 seconds of inactivity.
832    pub connection_timeout: u32,
833    /// Maximum interval between failed request retries in seconds.
834    pub max_retry_interval: u32,
835    /// The custom HTTP Host header to send to the upstream.
836    pub host_header: Option<String>,
837    /// The interval in seconds at which Relay attempts to reauthenticate with the upstream server.
838    ///
839    /// Re-authentication happens even when Relay is idle. If authentication fails, Relay reverts
840    /// back into startup mode and tries to establish a connection. During this time, incoming
841    /// envelopes will be buffered.
842    ///
843    /// Defaults to `600` (10 minutes).
844    pub auth_interval: Option<u64>,
845    /// The maximum time of experiencing uninterrupted network failures until Relay considers that
846    /// it has encountered a network outage in seconds.
847    ///
848    /// During a network outage relay will try to reconnect and will buffer all upstream messages
849    /// until it manages to reconnect.
850    pub outage_grace_period: u64,
851    /// The time Relay waits before retrying an upstream request, in seconds.
852    ///
853    /// This time is only used before going into a network outage mode.
854    pub retry_delay: u64,
855    /// The interval in seconds for continued failed project fetches at which Relay will error.
856    ///
857    /// A successful fetch resets this interval. Relay does nothing during long
858    /// times without emitting requests.
859    pub project_failure_interval: u64,
860    /// Content encoding to apply to upstream store requests.
861    ///
862    /// By default, Relay applies `zstd` content encoding to compress upstream requests. Compression
863    /// can be disabled to reduce CPU consumption, but at the expense of increased network traffic.
864    ///
865    /// This setting applies to all store requests of SDK data, including events, transactions,
866    /// envelopes and sessions. At the moment, this does not apply to Relay's internal queries.
867    ///
868    /// Available options are:
869    ///
870    ///  - `identity`: Disables compression.
871    ///  - `deflate`: Compression using a zlib header with deflate encoding.
872    ///  - `gzip` (default): Compression using gzip.
873    ///  - `br`: Compression using the brotli algorithm.
874    ///  - `zstd`: Compression using the zstd algorithm.
875    pub encoding: HttpEncoding,
876    /// Submit metrics globally through a shared endpoint.
877    ///
878    /// As opposed to regular envelopes which are sent to an endpoint inferred from the project's
879    /// DSN, this submits metrics to the global endpoint with Relay authentication.
880    ///
881    /// This option does not have any effect on processing mode.
882    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, // 1 minute
891            host_header: None,
892            auth_interval: Some(600), // 10 minutes
893            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
902/// Default for unavailable upstream retry period, 1s.
903fn default_retry_delay() -> u64 {
904    1
905}
906
907/// Default for project failure interval, 90s.
908fn default_project_failure_interval() -> u64 {
909    90
910}
911
912/// Default for max disk size, 500 MB.
913fn spool_envelopes_max_disk_size() -> ByteSize {
914    ByteSize::mebibytes(500)
915}
916
917/// Default number of encoded envelope bytes to cache before writing to disk.
918fn 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
926/// Default refresh frequency in ms for the disk usage monitoring.
927fn spool_disk_usage_refresh_frequency_ms() -> u64 {
928    100
929}
930
931/// Default bounded buffer size for handling backpressure.
932fn spool_max_backpressure_envelopes() -> usize {
933    500
934}
935
936/// Default max memory usage for unspooling.
937fn spool_max_backpressure_memory_percent() -> f32 {
938    0.9
939}
940
941/// Default number of partitions for the buffer.
942fn spool_envelopes_partitions() -> NonZeroU8 {
943    NonZeroU8::new(1).unwrap()
944}
945
946/// Persistent buffering configuration for incoming envelopes.
947#[derive(Debug, Serialize, Deserialize)]
948pub struct EnvelopeSpool {
949    /// The path of the SQLite database file(s) which persist the data.
950    ///
951    /// Based on the number of partitions, more database files will be created within the same path.
952    ///
953    /// If not set, the envelopes will be buffered in memory.
954    pub path: Option<PathBuf>,
955    /// The maximum size of the buffer to keep, in bytes.
956    ///
957    /// When the on-disk buffer reaches this size, new envelopes will be dropped.
958    ///
959    /// Defaults to 500MB.
960    #[serde(default = "spool_envelopes_max_disk_size")]
961    pub max_disk_size: ByteSize,
962    /// Size of the batch of compressed envelopes that are spooled to disk at once.
963    ///
964    /// Note that this is the size after which spooling will be triggered but it does not guarantee
965    /// that exactly this size will be spooled, it can be greater or equal.
966    ///
967    /// Defaults to 10 KiB.
968    #[serde(default = "spool_envelopes_batch_size_bytes")]
969    pub batch_size_bytes: ByteSize,
970    /// Maximum time between receiving the envelope and processing it.
971    ///
972    /// When envelopes spend too much time in the buffer (e.g. because their project cannot be loaded),
973    /// they are dropped.
974    ///
975    /// Defaults to 24h.
976    #[serde(default = "spool_envelopes_max_envelope_delay_secs")]
977    pub max_envelope_delay_secs: u64,
978    /// The refresh frequency in ms of how frequently disk usage is updated by querying SQLite
979    /// internal page stats.
980    ///
981    /// Defaults to 100ms.
982    #[serde(default = "spool_disk_usage_refresh_frequency_ms")]
983    pub disk_usage_refresh_frequency_ms: u64,
984    /// The amount of envelopes that the envelope buffer can push to its output queue.
985    ///
986    /// Defaults to 500.
987    #[serde(default = "spool_max_backpressure_envelopes")]
988    pub max_backpressure_envelopes: usize,
989    /// The relative memory usage above which the buffer service will stop dequeueing envelopes.
990    ///
991    /// Only applies when [`Self::path`] is set.
992    ///
993    /// This value should be lower than [`Health::max_memory_percent`] to prevent flip-flopping.
994    ///
995    /// Warning: This threshold can cause the buffer service to deadlock when the buffer consumes
996    /// excessive memory (as influenced by [`Self::batch_size_bytes`]).
997    ///
998    /// This scenario arises when the buffer stops spooling due to reaching the
999    /// [`Self::max_backpressure_memory_percent`] limit, but the batch threshold for spooling
1000    /// ([`Self::batch_size_bytes`]) is never reached. As a result, no data is spooled, memory usage
1001    /// continues to grow, and the system becomes deadlocked.
1002    ///
1003    /// ### Example
1004    /// Suppose the system has 1GB of available memory and is configured to spool only after
1005    /// accumulating 10GB worth of envelopes. If Relay consumes 900MB of memory, it will stop
1006    /// unspooling due to reaching the [`Self::max_backpressure_memory_percent`] threshold.
1007    ///
1008    /// However, because the buffer hasn't accumulated the 10GB needed to trigger spooling,
1009    /// no data will be offloaded. Memory usage keeps increasing until it hits the
1010    /// [`Health::max_memory_percent`] threshold, e.g., at 950MB. At this point:
1011    ///
1012    /// - No more envelopes are accepted.
1013    /// - The buffer remains stuck, as unspooling won’t resume until memory drops below 900MB which
1014    ///   will not happen.
1015    /// - A deadlock occurs, with the system unable to recover without manual intervention.
1016    ///
1017    /// Defaults to 90% (5% less than max memory).
1018    #[serde(default = "spool_max_backpressure_memory_percent")]
1019    pub max_backpressure_memory_percent: f32,
1020    /// Number of partitions of the buffer.
1021    ///
1022    /// A partition is a separate instance of the buffer which has its own isolated queue, stacks
1023    /// and other resources.
1024    ///
1025    /// Defaults to 1.
1026    #[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/// Persistent buffering configuration.
1046#[derive(Debug, Serialize, Deserialize, Default)]
1047pub struct Spool {
1048    /// Configuration for envelope spooling.
1049    #[serde(default)]
1050    pub envelopes: EnvelopeSpool,
1051}
1052
1053/// Controls internal caching behavior.
1054#[derive(Serialize, Deserialize, Debug)]
1055#[serde(default)]
1056pub struct Cache {
1057    /// The full project state will be requested by this Relay if set to `true`.
1058    pub project_request_full_config: bool,
1059    /// The cache timeout for project configurations in seconds.
1060    pub project_expiry: u32,
1061    /// Continue using project state this many seconds after cache expiry while a new state is
1062    /// being fetched. This is added on top of `project_expiry`.
1063    ///
1064    /// Default is 2 minutes.
1065    pub project_grace_period: u32,
1066    /// Refresh a project after the specified seconds.
1067    ///
1068    /// The time must be between expiry time and the grace period.
1069    ///
1070    /// By default there are no refreshes enabled.
1071    pub project_refresh_interval: Option<u32>,
1072    /// The cache timeout for downstream relay info (public keys) in seconds.
1073    pub relay_expiry: u32,
1074    /// Unused cache timeout for envelopes.
1075    ///
1076    /// The envelope buffer is instead controlled by `envelope_buffer_size`, which controls the
1077    /// maximum number of envelopes in the buffer. A time based configuration may be re-introduced
1078    /// at a later point.
1079    #[serde(alias = "event_expiry")]
1080    envelope_expiry: u32,
1081    /// The maximum amount of envelopes to queue before dropping them.
1082    #[serde(alias = "event_buffer_size")]
1083    envelope_buffer_size: u32,
1084    /// The cache timeout for non-existing entries.
1085    pub miss_expiry: u32,
1086    /// The buffer timeout for batched project config queries before sending them upstream in ms.
1087    pub batch_interval: u32,
1088    /// The buffer timeout for batched queries of downstream relays in ms. Defaults to 100ms.
1089    pub downstream_relays_batch_interval: u32,
1090    /// The maximum number of project configs to fetch from Sentry at once. Defaults to 500.
1091    ///
1092    /// `cache.batch_interval` controls how quickly batches are sent, this controls the batch size.
1093    pub batch_size: usize,
1094    /// Interval for watching local cache override files in seconds.
1095    pub file_interval: u32,
1096    /// Interval for fetching new global configs from the upstream, in seconds.
1097    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,       // 5 minutes
1105            project_grace_period: 120, // 2 minutes
1106            project_refresh_interval: None,
1107            relay_expiry: 3600,   // 1 hour
1108            envelope_expiry: 600, // 10 minutes
1109            envelope_buffer_size: 1000,
1110            miss_expiry: 60,                       // 1 minute
1111            batch_interval: 100,                   // 100ms
1112            downstream_relays_batch_interval: 100, // 100ms
1113            batch_size: 500,
1114            file_interval: 10,                // 10 seconds
1115            global_config_fetch_interval: 10, // 10 seconds
1116        }
1117    }
1118}
1119
1120fn default_max_secs_in_future() -> u32 {
1121    60 // 1 minute
1122}
1123
1124fn default_max_session_secs_in_past() -> u32 {
1125    5 * 24 * 3600 // 5 days
1126}
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) // 5 minutes
1139}
1140
1141/// Controls Sentry-internal event processing.
1142#[derive(Serialize, Deserialize, Debug)]
1143pub struct Processing {
1144    /// True if the Relay should do processing. Defaults to `false`.
1145    pub enabled: bool,
1146    /// GeoIp DB file source.
1147    #[serde(default)]
1148    pub geoip_path: Option<PathBuf>,
1149    /// Maximum future timestamp of ingested events.
1150    #[serde(default = "default_max_secs_in_future")]
1151    pub max_secs_in_future: u32,
1152    /// Maximum age of ingested sessions. Older sessions will be dropped.
1153    #[serde(default = "default_max_session_secs_in_past")]
1154    pub max_session_secs_in_past: u32,
1155    /// Kafka producer configurations.
1156    pub kafka_config: Vec<KafkaConfigParam>,
1157    /// Additional kafka producer configurations.
1158    ///
1159    /// The `kafka_config` is the default producer configuration used for all topics. A secondary
1160    /// kafka config can be referenced in `topics:` like this:
1161    ///
1162    /// ```yaml
1163    /// secondary_kafka_configs:
1164    ///   mycustomcluster:
1165    ///     - name: 'bootstrap.servers'
1166    ///       value: 'sentry_kafka_metrics:9093'
1167    ///
1168    /// topics:
1169    ///   transactions: ingest-transactions
1170    ///   metrics:
1171    ///     name: ingest-metrics
1172    ///     config: mycustomcluster
1173    /// ```
1174    ///
1175    /// Then metrics will be produced to an entirely different Kafka cluster.
1176    #[serde(default)]
1177    pub secondary_kafka_configs: BTreeMap<String, Vec<KafkaConfigParam>>,
1178    /// Kafka topic names.
1179    #[serde(default)]
1180    pub topics: TopicAssignments,
1181    /// Whether to validate the supplied topics by calling Kafka's metadata endpoints.
1182    #[serde(default)]
1183    pub kafka_validate_topics: bool,
1184    /// Redis hosts to connect to for storing state for rate limits.
1185    #[serde(default)]
1186    pub redis: Option<RedisConfigs>,
1187    /// Maximum chunk size of attachments for Kafka.
1188    #[serde(default = "default_chunk_size")]
1189    pub attachment_chunk_size: ByteSize,
1190    /// Prefix to use when looking up project configs in Redis. Defaults to "relayconfig".
1191    #[serde(default = "default_projectconfig_cache_prefix")]
1192    pub projectconfig_cache_prefix: String,
1193    /// Maximum rate limit to report to clients.
1194    #[serde(default = "default_max_rate_limit")]
1195    pub max_rate_limit: Option<u32>,
1196    /// Configuration for attachment uploads.
1197    #[serde(default)]
1198    pub upload: UploadServiceConfig,
1199}
1200
1201impl Default for Processing {
1202    /// Constructs a disabled processing configuration.
1203    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/// Configuration for normalization in this Relay.
1223#[derive(Debug, Default, Serialize, Deserialize)]
1224#[serde(default)]
1225pub struct Normalization {
1226    /// Level of normalization for Relay to apply to incoming data.
1227    #[serde(default)]
1228    pub level: NormalizationLevel,
1229}
1230
1231/// Configuration for the level of normalization this Relay should do.
1232#[derive(Copy, Clone, Debug, Default, Serialize, Deserialize, Eq, PartialEq)]
1233#[serde(rename_all = "lowercase")]
1234pub enum NormalizationLevel {
1235    /// Runs normalization, excluding steps that break future compatibility.
1236    ///
1237    /// Processing Relays run [`NormalizationLevel::Full`] if this option is set.
1238    #[default]
1239    Default,
1240    /// Run full normalization.
1241    ///
1242    /// It includes steps that break future compatibility and should only run in
1243    /// the last layer of relays.
1244    Full,
1245}
1246
1247/// Configuration values for the outcome aggregator
1248#[derive(Serialize, Deserialize, Debug)]
1249#[serde(default)]
1250pub struct OutcomeAggregatorConfig {
1251    /// Defines the width of the buckets into which outcomes are aggregated, in seconds.
1252    pub bucket_interval: u64,
1253    /// Defines how often all buckets are flushed, in seconds.
1254    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/// Configuration values for attachment uploads.
1267#[derive(Serialize, Deserialize, Debug)]
1268#[serde(default)]
1269pub struct UploadServiceConfig {
1270    /// The base URL for the objectstore service.
1271    ///
1272    /// This defaults to [`None`], which means that the service will be disabled,
1273    /// unless a proper configuration is provided.
1274    pub objectstore_url: Option<String>,
1275
1276    /// Maximum concurrency of uploads.
1277    pub max_concurrent_requests: usize,
1278
1279    /// Maximum duration of an attachment upload in seconds. Uploads that take longer are discarded.
1280    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/// Determines how to emit outcomes.
1294/// For compatibility reasons, this can either be true, false or AsClientReports
1295#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1296
1297pub enum EmitOutcomes {
1298    /// Do not emit any outcomes
1299    None,
1300    /// Emit outcomes as client reports
1301    AsClientReports,
1302    /// Emit outcomes as outcomes
1303    AsOutcomes,
1304}
1305
1306impl EmitOutcomes {
1307    /// Returns true of outcomes are emitted via http, kafka, or client reports.
1308    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        // For compatibility, serialize None and AsOutcomes as booleans.
1319        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/// Outcome generation specific configuration values.
1369#[derive(Serialize, Deserialize, Debug)]
1370#[serde(default)]
1371pub struct Outcomes {
1372    /// Controls whether outcomes will be emitted when processing is disabled.
1373    /// Processing relays always emit outcomes (for backwards compatibility).
1374    /// Can take the following values: false, "as_client_reports", true
1375    pub emit_outcomes: EmitOutcomes,
1376    /// Controls wheather client reported outcomes should be emitted.
1377    pub emit_client_outcomes: bool,
1378    /// The maximum number of outcomes that are batched before being sent
1379    /// via http to the upstream (only applies to non processing relays).
1380    pub batch_size: usize,
1381    /// The maximum time interval (in milliseconds) that an outcome may be batched
1382    /// via http to the upstream (only applies to non processing relays).
1383    pub batch_interval: u64,
1384    /// Defines the source string registered in the outcomes originating from
1385    /// this Relay (typically something like the region or the layer).
1386    pub source: Option<String>,
1387    /// Configures the outcome aggregator.
1388    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/// Minimal version of a config for dumping out.
1405#[derive(Serialize, Deserialize, Debug, Default)]
1406pub struct MinimalConfig {
1407    /// The relay part of the config.
1408    pub relay: Relay,
1409}
1410
1411impl MinimalConfig {
1412    /// Saves the config in the given config folder as config.yml
1413    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
1433/// Alternative serialization of RelayInfo for config file using snake case.
1434mod config_relay_info {
1435    use serde::ser::SerializeMap;
1436
1437    use super::*;
1438
1439    // Uses snake_case as opposed to camelCase.
1440    #[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/// Authentication options.
1488#[derive(Serialize, Deserialize, Debug, Default)]
1489pub struct AuthConfig {
1490    /// Controls responses from the readiness health check endpoint based on authentication.
1491    #[serde(default, skip_serializing_if = "is_default")]
1492    pub ready: ReadinessCondition,
1493
1494    /// Statically authenticated downstream relays.
1495    #[serde(default, with = "config_relay_info")]
1496    pub static_relays: HashMap<RelayId, RelayInfo>,
1497
1498    /// How old a signature can be before it is considered invalid, in seconds.
1499    ///
1500    /// Defaults to 5 minutes.
1501    #[serde(default = "default_max_age")]
1502    pub signature_max_age: u64,
1503}
1504
1505fn default_max_age() -> u64 {
1506    300
1507}
1508
1509/// GeoIp database configuration options.
1510#[derive(Serialize, Deserialize, Debug, Default)]
1511pub struct GeoIpConfig {
1512    /// The path to GeoIP database.
1513    pub path: Option<PathBuf>,
1514}
1515
1516/// Cardinality Limiter configuration options.
1517#[derive(Serialize, Deserialize, Debug)]
1518#[serde(default)]
1519pub struct CardinalityLimiter {
1520    /// Cache vacuum interval in seconds for the in memory cache.
1521    ///
1522    /// The cache will scan for expired values based on this interval.
1523    ///
1524    /// Defaults to 180 seconds, 3 minutes.
1525    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/// Settings to control Relay's health checks.
1537///
1538/// After breaching one of the configured thresholds, Relay will
1539/// return an `unhealthy` status from its health endpoint.
1540#[derive(Serialize, Deserialize, Debug)]
1541#[serde(default)]
1542pub struct Health {
1543    /// Interval to refresh internal health checks.
1544    ///
1545    /// Shorter intervals will decrease the time it takes the health check endpoint to report
1546    /// issues, but can also increase sporadic unhealthy responses.
1547    ///
1548    /// Defaults to `3000`` (3 seconds).
1549    pub refresh_interval_ms: u64,
1550    /// Maximum memory watermark in bytes.
1551    ///
1552    /// By default, there is no absolute limit set and the watermark
1553    /// is only controlled by setting [`Self::max_memory_percent`].
1554    pub max_memory_bytes: Option<ByteSize>,
1555    /// Maximum memory watermark as a percentage of maximum system memory.
1556    ///
1557    /// Defaults to `0.95` (95%).
1558    pub max_memory_percent: f32,
1559    /// Health check probe timeout in milliseconds.
1560    ///
1561    /// Any probe exceeding the timeout will be considered failed.
1562    /// This limits the max execution time of Relay health checks.
1563    ///
1564    /// Defaults to 900 milliseconds.
1565    pub probe_timeout_ms: u64,
1566    /// The refresh frequency of memory stats which are used to poll memory
1567    /// usage of Relay.
1568    ///
1569    /// The implementation of memory stats guarantees that the refresh will happen at
1570    /// least every `x` ms since memory readings are lazy and are updated only if needed.
1571    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/// COGS configuration.
1587#[derive(Serialize, Deserialize, Debug)]
1588#[serde(default)]
1589pub struct Cogs {
1590    /// Maximium amount of COGS measurements allowed to backlog.
1591    ///
1592    /// Any additional COGS measurements recorded will be dropped.
1593    ///
1594    /// Defaults to `10_000`.
1595    pub max_queue_size: u64,
1596    /// Relay COGS resource id.
1597    ///
1598    /// All Relay related COGS measurements are emitted with this resource id.
1599    ///
1600    /// Defaults to `relay_service`.
1601    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
1665/// Config struct.
1666pub 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    /// Loads a config from a given config folder.
1683    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    /// Creates a config from a JSON value.
1706    ///
1707    /// This is mostly useful for tests.
1708    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    /// Override configuration with values coming from other sources (e.g. env variables or
1718    /// command line parameters)
1719    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        // credentials overrides
1798        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            //we have existing credentials we may override some entries
1828            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            //no existing credentials we may only create the full credentials
1839            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                    // nothing provided, we'll just leave the credentials None, maybe we
1849                    // don't need them in the current command or we'll override them later
1850                }
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    /// Checks if the config is already initialized.
1872    pub fn config_exists<P: AsRef<Path>>(path: P) -> bool {
1873        fs::metadata(ConfigValues::path(path.as_ref())).is_ok()
1874    }
1875
1876    /// Returns the filename of the config file.
1877    pub fn path(&self) -> &Path {
1878        &self.path
1879    }
1880
1881    /// Dumps out a YAML string of the values.
1882    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    /// Regenerates the relay credentials.
1888    ///
1889    /// This also writes the credentials back to the file.
1890    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    /// Return the current credentials
1900    pub fn credentials(&self) -> Option<&Credentials> {
1901        self.credentials.as_ref()
1902    }
1903
1904    /// Set new credentials.
1905    ///
1906    /// This also writes the credentials back to the file.
1907    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    /// Returns `true` if the config is ready to use.
1934    pub fn has_credentials(&self) -> bool {
1935        self.credentials.is_some()
1936    }
1937
1938    /// Returns the secret key if set.
1939    pub fn secret_key(&self) -> Option<&SecretKey> {
1940        self.credentials.as_ref().map(|x| &x.secret_key)
1941    }
1942
1943    /// Returns the public key if set.
1944    pub fn public_key(&self) -> Option<&PublicKey> {
1945        self.credentials.as_ref().map(|x| &x.public_key)
1946    }
1947
1948    /// Returns the relay ID.
1949    pub fn relay_id(&self) -> Option<&RelayId> {
1950        self.credentials.as_ref().map(|x| &x.id)
1951    }
1952
1953    /// Returns the relay mode.
1954    pub fn relay_mode(&self) -> RelayMode {
1955        self.values.relay.mode
1956    }
1957
1958    /// Returns the instance type of relay.
1959    pub fn relay_instance(&self) -> RelayInstance {
1960        self.values.relay.instance
1961    }
1962
1963    /// Returns the upstream target as descriptor.
1964    pub fn upstream_descriptor(&self) -> &UpstreamDescriptor<'_> {
1965        &self.values.relay.upstream
1966    }
1967
1968    /// Returns the custom HTTP "Host" header.
1969    pub fn http_host_header(&self) -> Option<&str> {
1970        self.values.http.host_header.as_deref()
1971    }
1972
1973    /// Returns the listen address.
1974    pub fn listen_addr(&self) -> SocketAddr {
1975        (self.values.relay.host, self.values.relay.port).into()
1976    }
1977
1978    /// Returns the listen address for internal APIs.
1979    ///
1980    /// Internal APIs are APIs which do not need to be publicly exposed,
1981    /// like health checks.
1982    ///
1983    /// Returns `None` when there is no explicit address configured for internal APIs,
1984    /// and they should instead be exposed on the main [`Self::listen_addr`].
1985    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    /// Returns the TLS listen address.
1998    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    /// Returns the path to the identity bundle
2008    pub fn tls_identity_path(&self) -> Option<&Path> {
2009        self.values.relay.tls_identity_path.as_deref()
2010    }
2011
2012    /// Returns the password for the identity bundle
2013    pub fn tls_identity_password(&self) -> Option<&str> {
2014        self.values.relay.tls_identity_password.as_deref()
2015    }
2016
2017    /// Returns `true` when project IDs should be overriden rather than validated.
2018    ///
2019    /// Defaults to `false`, which requires project ID validation.
2020    pub fn override_project_ids(&self) -> bool {
2021        self.values.relay.override_project_ids
2022    }
2023
2024    /// Returns `true` if Relay requires authentication for readiness.
2025    ///
2026    /// See [`ReadinessCondition`] for more information.
2027    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    /// Returns the interval at which Realy should try to re-authenticate with the upstream.
2035    ///
2036    /// Always disabled in processing mode.
2037    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    /// The maximum time of experiencing uninterrupted network failures until Relay considers that
2049    /// it has encountered a network outage.
2050    pub fn http_outage_grace_period(&self) -> Duration {
2051        Duration::from_secs(self.values.http.outage_grace_period)
2052    }
2053
2054    /// Time Relay waits before retrying an upstream request.
2055    ///
2056    /// Before going into a network outage, Relay may fail to make upstream
2057    /// requests. This is the time Relay waits before retrying the same request.
2058    pub fn http_retry_delay(&self) -> Duration {
2059        Duration::from_secs(self.values.http.retry_delay)
2060    }
2061
2062    /// Time of continued project request failures before Relay emits an error.
2063    pub fn http_project_failure_interval(&self) -> Duration {
2064        Duration::from_secs(self.values.http.project_failure_interval)
2065    }
2066
2067    /// Content encoding of upstream requests.
2068    pub fn http_encoding(&self) -> HttpEncoding {
2069        self.values.http.encoding
2070    }
2071
2072    /// Returns whether metrics should be sent globally through a shared endpoint.
2073    pub fn http_global_metrics(&self) -> bool {
2074        self.values.http.global_metrics
2075    }
2076
2077    /// Returns whether this Relay should emit outcomes.
2078    ///
2079    /// This is `true` either if `outcomes.emit_outcomes` is explicitly enabled, or if this Relay is
2080    /// in processing mode.
2081    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    /// Returns whether this Relay should emit client outcomes
2089    ///
2090    /// Relays that do not emit client outcomes will forward client recieved outcomes
2091    /// directly to the next relay in the chain as client report envelope.  This is only done
2092    /// if this relay emits outcomes at all. A relay that will not emit outcomes
2093    /// will forward the envelope unchanged.
2094    ///
2095    /// This flag can be explicitly disabled on processing relays as well to prevent the
2096    /// emitting of client outcomes to the kafka topic.
2097    pub fn emit_client_outcomes(&self) -> bool {
2098        self.values.outcomes.emit_client_outcomes
2099    }
2100
2101    /// Returns the maximum number of outcomes that are batched before being sent
2102    pub fn outcome_batch_size(&self) -> usize {
2103        self.values.outcomes.batch_size
2104    }
2105
2106    /// Returns the maximum interval that an outcome may be batched
2107    pub fn outcome_batch_interval(&self) -> Duration {
2108        Duration::from_millis(self.values.outcomes.batch_interval)
2109    }
2110
2111    /// The originating source of the outcome
2112    pub fn outcome_source(&self) -> Option<&str> {
2113        self.values.outcomes.source.as_deref()
2114    }
2115
2116    /// Returns the width of the buckets into which outcomes are aggregated, in seconds.
2117    pub fn outcome_aggregator(&self) -> &OutcomeAggregatorConfig {
2118        &self.values.outcomes.aggregator
2119    }
2120
2121    /// Returns logging configuration.
2122    pub fn logging(&self) -> &relay_log::LogConfig {
2123        &self.values.logging
2124    }
2125
2126    /// Returns logging configuration.
2127    pub fn sentry(&self) -> &relay_log::SentryConfig {
2128        &self.values.sentry
2129    }
2130
2131    /// Returns the socket addresses for statsd.
2132    ///
2133    /// If stats is disabled an empty vector is returned.
2134    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    /// Return the prefix for statsd metrics.
2148    pub fn metrics_prefix(&self) -> &str {
2149        &self.values.metrics.prefix
2150    }
2151
2152    /// Returns the default tags for statsd metrics.
2153    pub fn metrics_default_tags(&self) -> &BTreeMap<String, String> {
2154        &self.values.metrics.default_tags
2155    }
2156
2157    /// Returns the name of the hostname tag that should be attached to each outgoing metric.
2158    pub fn metrics_hostname_tag(&self) -> Option<&str> {
2159        self.values.metrics.hostname_tag.as_deref()
2160    }
2161
2162    /// Returns the global sample rate for all metrics.
2163    pub fn metrics_sample_rate(&self) -> f32 {
2164        self.values.metrics.sample_rate
2165    }
2166
2167    /// Returns whether local metric aggregation should be enabled.
2168    pub fn metrics_aggregate(&self) -> bool {
2169        self.values.metrics.aggregate
2170    }
2171
2172    /// Returns whether high cardinality tags should be removed before sending metrics.
2173    pub fn metrics_allow_high_cardinality_tags(&self) -> bool {
2174        self.values.metrics.allow_high_cardinality_tags
2175    }
2176
2177    /// Returns the interval for periodic metrics emitted from Relay.
2178    ///
2179    /// `None` if periodic metrics are disabled.
2180    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    /// Returns the default timeout for all upstream HTTP requests.
2188    pub fn http_timeout(&self) -> Duration {
2189        Duration::from_secs(self.values.http.timeout.into())
2190    }
2191
2192    /// Returns the connection timeout for all upstream HTTP requests.
2193    pub fn http_connection_timeout(&self) -> Duration {
2194        Duration::from_secs(self.values.http.connection_timeout.into())
2195    }
2196
2197    /// Returns the failed upstream request retry interval.
2198    pub fn http_max_retry_interval(&self) -> Duration {
2199        Duration::from_secs(self.values.http.max_retry_interval.into())
2200    }
2201
2202    /// Returns the expiry timeout for cached projects.
2203    pub fn project_cache_expiry(&self) -> Duration {
2204        Duration::from_secs(self.values.cache.project_expiry.into())
2205    }
2206
2207    /// Returns `true` if the full project state should be requested from upstream.
2208    pub fn request_full_project_config(&self) -> bool {
2209        self.values.cache.project_request_full_config
2210    }
2211
2212    /// Returns the expiry timeout for cached relay infos (public keys).
2213    pub fn relay_cache_expiry(&self) -> Duration {
2214        Duration::from_secs(self.values.cache.relay_expiry.into())
2215    }
2216
2217    /// Returns the maximum number of buffered envelopes
2218    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    /// Returns the expiry timeout for cached misses before trying to refetch.
2227    pub fn cache_miss_expiry(&self) -> Duration {
2228        Duration::from_secs(self.values.cache.miss_expiry.into())
2229    }
2230
2231    /// Returns the grace period for project caches.
2232    pub fn project_grace_period(&self) -> Duration {
2233        Duration::from_secs(self.values.cache.project_grace_period.into())
2234    }
2235
2236    /// Returns the refresh interval for a project.
2237    ///
2238    /// Validates the refresh time to be between the grace period and expiry.
2239    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    /// Returns the duration in which batchable project config queries are
2248    /// collected before sending them in a single request.
2249    pub fn query_batch_interval(&self) -> Duration {
2250        Duration::from_millis(self.values.cache.batch_interval.into())
2251    }
2252
2253    /// Returns the duration in which downstream relays are requested from upstream.
2254    pub fn downstream_relays_batch_interval(&self) -> Duration {
2255        Duration::from_millis(self.values.cache.downstream_relays_batch_interval.into())
2256    }
2257
2258    /// Returns the interval in seconds in which local project configurations should be reloaded.
2259    pub fn local_cache_interval(&self) -> Duration {
2260        Duration::from_secs(self.values.cache.file_interval.into())
2261    }
2262
2263    /// Returns the interval in seconds in which fresh global configs should be
2264    /// fetched from  upstream.
2265    pub fn global_config_fetch_interval(&self) -> Duration {
2266        Duration::from_secs(self.values.cache.global_config_fetch_interval.into())
2267    }
2268
2269    /// Returns the path of the buffer file if the `cache.persistent_envelope_buffer.path` is configured.
2270    ///
2271    /// In case a partition with id > 0 is supplied, the filename of the envelopes path will be
2272    /// suffixed with `.{partition_id}`.
2273    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    /// The maximum size of the buffer, in bytes.
2294    pub fn spool_envelopes_max_disk_size(&self) -> usize {
2295        self.values.spool.envelopes.max_disk_size.as_bytes()
2296    }
2297
2298    /// Number of encoded envelope bytes that need to be accumulated before
2299    /// flushing one batch to disk.
2300    pub fn spool_envelopes_batch_size_bytes(&self) -> usize {
2301        self.values.spool.envelopes.batch_size_bytes.as_bytes()
2302    }
2303
2304    /// Returns the time after which we drop envelopes as a [`Duration`] object.
2305    pub fn spool_envelopes_max_age(&self) -> Duration {
2306        Duration::from_secs(self.values.spool.envelopes.max_envelope_delay_secs)
2307    }
2308
2309    /// Returns the refresh frequency for disk usage monitoring as a [`Duration`] object.
2310    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    /// Returns the maximum number of envelopes that can be put in the bounded buffer.
2315    pub fn spool_max_backpressure_envelopes(&self) -> usize {
2316        self.values.spool.envelopes.max_backpressure_envelopes
2317    }
2318
2319    /// Returns the relative memory usage up to which the disk buffer will unspool envelopes.
2320    pub fn spool_max_backpressure_memory_percent(&self) -> f32 {
2321        self.values.spool.envelopes.max_backpressure_memory_percent
2322    }
2323
2324    /// Returns the number of partitions for the buffer.
2325    pub fn spool_partitions(&self) -> NonZeroU8 {
2326        self.values.spool.envelopes.partitions
2327    }
2328
2329    /// Returns the maximum size of an event payload in bytes.
2330    pub fn max_event_size(&self) -> usize {
2331        self.values.limits.max_event_size.as_bytes()
2332    }
2333
2334    /// Returns the maximum size of each attachment.
2335    pub fn max_attachment_size(&self) -> usize {
2336        self.values.limits.max_attachment_size.as_bytes()
2337    }
2338
2339    /// Returns the maximum combined size of attachments or payloads containing attachments
2340    /// (minidump, unreal, standalone attachments) in bytes.
2341    pub fn max_attachments_size(&self) -> usize {
2342        self.values.limits.max_attachments_size.as_bytes()
2343    }
2344
2345    /// Returns the maximum combined size of client reports in bytes.
2346    pub fn max_client_reports_size(&self) -> usize {
2347        self.values.limits.max_client_reports_size.as_bytes()
2348    }
2349
2350    /// Returns the maximum payload size of a monitor check-in in bytes.
2351    pub fn max_check_in_size(&self) -> usize {
2352        self.values.limits.max_check_in_size.as_bytes()
2353    }
2354
2355    /// Returns the maximum payload size of a log in bytes.
2356    pub fn max_log_size(&self) -> usize {
2357        self.values.limits.max_log_size.as_bytes()
2358    }
2359
2360    /// Returns the maximum payload size of a span in bytes.
2361    pub fn max_span_size(&self) -> usize {
2362        self.values.limits.max_span_size.as_bytes()
2363    }
2364
2365    /// Returns the maximum payload size of an item container in bytes.
2366    pub fn max_container_size(&self) -> usize {
2367        self.values.limits.max_container_size.as_bytes()
2368    }
2369
2370    /// Returns the maximum size of an envelope payload in bytes.
2371    ///
2372    /// Individual item size limits still apply.
2373    pub fn max_envelope_size(&self) -> usize {
2374        self.values.limits.max_envelope_size.as_bytes()
2375    }
2376
2377    /// Returns the maximum number of sessions per envelope.
2378    pub fn max_session_count(&self) -> usize {
2379        self.values.limits.max_session_count
2380    }
2381
2382    /// Returns the maximum number of standalone spans per envelope.
2383    pub fn max_span_count(&self) -> usize {
2384        self.values.limits.max_span_count
2385    }
2386
2387    /// Returns the maximum number of logs per envelope.
2388    pub fn max_log_count(&self) -> usize {
2389        self.values.limits.max_log_count
2390    }
2391
2392    /// Returns the maximum number of trace metrics per envelope.
2393    pub fn max_trace_metric_count(&self) -> usize {
2394        self.values.limits.max_trace_metric_count
2395    }
2396
2397    /// Returns the maximum payload size of a statsd metric in bytes.
2398    pub fn max_statsd_size(&self) -> usize {
2399        self.values.limits.max_statsd_size.as_bytes()
2400    }
2401
2402    /// Returns the maximum payload size of metric buckets in bytes.
2403    pub fn max_metric_buckets_size(&self) -> usize {
2404        self.values.limits.max_metric_buckets_size.as_bytes()
2405    }
2406
2407    /// Returns the maximum payload size for general API requests.
2408    pub fn max_api_payload_size(&self) -> usize {
2409        self.values.limits.max_api_payload_size.as_bytes()
2410    }
2411
2412    /// Returns the maximum payload size for file uploads and chunks.
2413    pub fn max_api_file_upload_size(&self) -> usize {
2414        self.values.limits.max_api_file_upload_size.as_bytes()
2415    }
2416
2417    /// Returns the maximum payload size for chunks
2418    pub fn max_api_chunk_upload_size(&self) -> usize {
2419        self.values.limits.max_api_chunk_upload_size.as_bytes()
2420    }
2421
2422    /// Returns the maximum payload size for a profile
2423    pub fn max_profile_size(&self) -> usize {
2424        self.values.limits.max_profile_size.as_bytes()
2425    }
2426
2427    /// Returns the maximum payload size for a trace metric.
2428    pub fn max_trace_metric_size(&self) -> usize {
2429        self.values.limits.max_trace_metric_size.as_bytes()
2430    }
2431
2432    /// Returns the maximum payload size for a compressed replay.
2433    pub fn max_replay_compressed_size(&self) -> usize {
2434        self.values.limits.max_replay_compressed_size.as_bytes()
2435    }
2436
2437    /// Returns the maximum payload size for an uncompressed replay.
2438    pub fn max_replay_uncompressed_size(&self) -> usize {
2439        self.values.limits.max_replay_uncompressed_size.as_bytes()
2440    }
2441
2442    /// Returns the maximum message size for an uncompressed replay.
2443    ///
2444    /// This is greater than max_replay_compressed_size because
2445    /// it can include additional metadata about the replay in
2446    /// addition to the recording.
2447    pub fn max_replay_message_size(&self) -> usize {
2448        self.values.limits.max_replay_message_size.as_bytes()
2449    }
2450
2451    /// Returns the maximum number of active requests
2452    pub fn max_concurrent_requests(&self) -> usize {
2453        self.values.limits.max_concurrent_requests
2454    }
2455
2456    /// Returns the maximum number of active queries
2457    pub fn max_concurrent_queries(&self) -> usize {
2458        self.values.limits.max_concurrent_queries
2459    }
2460
2461    /// The maximum number of seconds a query is allowed to take across retries.
2462    pub fn query_timeout(&self) -> Duration {
2463        Duration::from_secs(self.values.limits.query_timeout)
2464    }
2465
2466    /// The maximum number of seconds to wait for pending envelopes after receiving a shutdown
2467    /// signal.
2468    pub fn shutdown_timeout(&self) -> Duration {
2469        Duration::from_secs(self.values.limits.shutdown_timeout)
2470    }
2471
2472    /// Returns the server keep-alive timeout in seconds.
2473    ///
2474    /// By default keep alive is set to a 5 seconds.
2475    pub fn keepalive_timeout(&self) -> Duration {
2476        Duration::from_secs(self.values.limits.keepalive_timeout)
2477    }
2478
2479    /// Returns the server idle timeout in seconds.
2480    pub fn idle_timeout(&self) -> Option<Duration> {
2481        self.values.limits.idle_timeout.map(Duration::from_secs)
2482    }
2483
2484    /// Returns the maximum connections.
2485    pub fn max_connections(&self) -> Option<usize> {
2486        self.values.limits.max_connections
2487    }
2488
2489    /// TCP listen backlog to configure on Relay's listening socket.
2490    pub fn tcp_listen_backlog(&self) -> u32 {
2491        self.values.limits.tcp_listen_backlog
2492    }
2493
2494    /// Returns the number of cores to use for thread pools.
2495    pub fn cpu_concurrency(&self) -> usize {
2496        self.values.limits.max_thread_count
2497    }
2498
2499    /// Returns the number of tasks that can run concurrently in the worker pool.
2500    pub fn pool_concurrency(&self) -> usize {
2501        self.values.limits.max_pool_concurrency
2502    }
2503
2504    /// Returns the maximum size of a project config query.
2505    pub fn query_batch_size(&self) -> usize {
2506        self.values.cache.batch_size
2507    }
2508
2509    /// Get filename for static project config.
2510    pub fn project_configs_path(&self) -> PathBuf {
2511        self.path.join("projects")
2512    }
2513
2514    /// True if the Relay should do processing.
2515    pub fn processing_enabled(&self) -> bool {
2516        self.values.processing.enabled
2517    }
2518
2519    /// Level of normalization for Relay to apply to incoming data.
2520    pub fn normalization_level(&self) -> NormalizationLevel {
2521        self.values.normalization.level
2522    }
2523
2524    /// The path to the GeoIp database required for event processing.
2525    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    /// Maximum future timestamp of ingested data.
2534    ///
2535    /// Events past this timestamp will be adjusted to `now()`. Sessions will be dropped.
2536    pub fn max_secs_in_future(&self) -> i64 {
2537        self.values.processing.max_secs_in_future.into()
2538    }
2539
2540    /// Maximum age of ingested sessions. Older sessions will be dropped.
2541    pub fn max_session_secs_in_past(&self) -> i64 {
2542        self.values.processing.max_session_secs_in_past.into()
2543    }
2544
2545    /// Configuration name and list of Kafka configuration parameters for a given topic.
2546    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    /// Whether to validate the topics against Kafka.
2557    pub fn kafka_validate_topics(&self) -> bool {
2558        self.values.processing.kafka_validate_topics
2559    }
2560
2561    /// All unused but configured topic assignments.
2562    pub fn unused_topic_assignments(&self) -> &relay_kafka::Unused {
2563        &self.values.processing.topics.unused
2564    }
2565
2566    /// Configuration of the attachment upload service.
2567    pub fn upload(&self) -> &UploadServiceConfig {
2568        &self.values.processing.upload
2569    }
2570
2571    /// Redis servers to connect to for project configs, cardinality limits,
2572    /// rate limiting, and metrics metadata.
2573    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    /// Chunk size of attachments in bytes.
2584    pub fn attachment_chunk_size(&self) -> usize {
2585        self.values.processing.attachment_chunk_size.as_bytes()
2586    }
2587
2588    /// Maximum metrics batch size in bytes.
2589    pub fn metrics_max_batch_size_bytes(&self) -> usize {
2590        self.values.aggregator.max_flush_bytes
2591    }
2592
2593    /// Default prefix to use when looking up project configs in Redis. This is only done when
2594    /// Relay is in processing mode.
2595    pub fn projectconfig_cache_prefix(&self) -> &str {
2596        &self.values.processing.projectconfig_cache_prefix
2597    }
2598
2599    /// Maximum rate limit to report to clients in seconds.
2600    pub fn max_rate_limit(&self) -> Option<u64> {
2601        self.values.processing.max_rate_limit.map(u32::into)
2602    }
2603
2604    /// Cache vacuum interval for the cardinality limiter in memory cache.
2605    ///
2606    /// The cache will scan for expired values based on this interval.
2607    pub fn cardinality_limiter_cache_vacuum_interval(&self) -> Duration {
2608        Duration::from_secs(self.values.cardinality_limiter.cache_vacuum_interval)
2609    }
2610
2611    /// Interval to refresh internal health checks.
2612    pub fn health_refresh_interval(&self) -> Duration {
2613        Duration::from_millis(self.values.health.refresh_interval_ms)
2614    }
2615
2616    /// Maximum memory watermark in bytes.
2617    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    /// Maximum memory watermark as a percentage of maximum system memory.
2626    pub fn health_max_memory_watermark_percent(&self) -> f32 {
2627        self.values.health.max_memory_percent
2628    }
2629
2630    /// Health check probe timeout.
2631    pub fn health_probe_timeout(&self) -> Duration {
2632        Duration::from_millis(self.values.health.probe_timeout_ms)
2633    }
2634
2635    /// Refresh frequency for polling new memory stats.
2636    pub fn memory_stat_refresh_frequency_ms(&self) -> u64 {
2637        self.values.health.memory_stat_refresh_frequency_ms
2638    }
2639
2640    /// Maximum amount of COGS measurements buffered in memory.
2641    pub fn cogs_max_queue_size(&self) -> u64 {
2642        self.values.cogs.max_queue_size
2643    }
2644
2645    /// Resource ID to use for Relay COGS measurements.
2646    pub fn cogs_relay_resource_id(&self) -> &str {
2647        &self.values.cogs.relay_resource_id
2648    }
2649
2650    /// Returns configuration for the default metrics aggregator.
2651    pub fn default_aggregator_config(&self) -> &AggregatorServiceConfig {
2652        &self.values.aggregator
2653    }
2654
2655    /// Returns configuration for non-default metrics aggregator.
2656    pub fn secondary_aggregator_configs(&self) -> &Vec<ScopedAggregatorConfig> {
2657        &self.values.secondary_aggregators
2658    }
2659
2660    /// Returns aggregator config for a given metrics namespace.
2661    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    /// Return the statically configured Relays.
2671    pub fn static_relays(&self) -> &HashMap<RelayId, RelayInfo> {
2672        &self.values.auth.static_relays
2673    }
2674
2675    /// Returns the max age a signature is considered valid, in seconds.
2676    pub fn signature_max_age(&self) -> Duration {
2677        Duration::from_secs(self.values.auth.signature_max_age)
2678    }
2679
2680    /// Returns `true` if unknown items should be accepted and forwarded.
2681    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    /// Regression test for renaming the envelope buffer flags.
2703    #[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}