Skip to main content

relay_config/
config.rs

1use std::collections::btree_map::Entry;
2use std::collections::{BTreeMap, HashMap};
3use std::error::Error;
4use std::io::Write;
5use std::net::{IpAddr, SocketAddr};
6use std::num::{NonZeroU8, NonZeroU16, NonZeroU32};
7use std::path::{Path, PathBuf};
8use std::str::FromStr;
9use std::sync::{Arc, Mutex, PoisonError};
10use std::time::Duration;
11use std::{env, fmt, fs, io};
12
13use anyhow::Context;
14use arc_swap::ArcSwap;
15use relay_auth::{PublicKey, RelayId, SecretKey, generate_key_pair, generate_relay_id};
16use relay_common::Dsn;
17use relay_kafka::{
18    ConfigError as KafkaConfigError, KafkaConfigParam, KafkaTopic, KafkaTopicConfig,
19    TopicAssignments,
20};
21use relay_metrics::MetricNamespace;
22use serde::de::{DeserializeOwned, Unexpected, Visitor};
23use serde::{Deserialize, Deserializer, Serialize, Serializer};
24use uuid::Uuid;
25
26use crate::aggregator::{AggregatorServiceConfig, ScopedAggregatorConfig};
27use crate::byte_size::ByteSize;
28use crate::upstream::UpstreamDescriptor;
29use crate::{RedisConfig, RedisConfigs, RedisConfigsRef, build_redis_configs};
30
31const DEFAULT_NETWORK_OUTAGE_GRACE_PERIOD: u64 = 10;
32
33static CONFIG_YAML_HEADER: &str = r###"# Please see the relevant documentation.
34# Performance tuning: https://docs.sentry.io/product/relay/operating-guidelines/
35# All config options: https://docs.sentry.io/product/relay/options/
36"###;
37
38/// Indicates config related errors.
39#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
40#[non_exhaustive]
41pub enum ConfigErrorKind {
42    /// Failed to open the file.
43    CouldNotOpenFile,
44    /// Failed to save a file.
45    CouldNotWriteFile,
46    /// Parsing YAML failed.
47    BadYaml,
48    /// Parsing JSON failed.
49    BadJson,
50    /// Invalid config value
51    InvalidValue,
52    /// The user attempted to run Relay with processing enabled, but uses a binary that was
53    /// compiled without the processing feature.
54    ProcessingNotAvailable,
55}
56
57impl fmt::Display for ConfigErrorKind {
58    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
59        match self {
60            Self::CouldNotOpenFile => write!(f, "could not open config file"),
61            Self::CouldNotWriteFile => write!(f, "could not write config file"),
62            Self::BadYaml => write!(f, "could not parse yaml config file"),
63            Self::BadJson => write!(f, "could not parse json config file"),
64            Self::InvalidValue => write!(f, "invalid config value"),
65            Self::ProcessingNotAvailable => write!(
66                f,
67                "was not compiled with processing, cannot enable processing"
68            ),
69        }
70    }
71}
72
73/// Defines the source of a config error
74#[derive(Debug, Default)]
75enum ConfigErrorSource {
76    /// An error occurring independently.
77    #[default]
78    None,
79    /// An error originating from a configuration file.
80    File(PathBuf),
81    /// An error originating in a field override (an env var, or a CLI parameter).
82    FieldOverride(String),
83}
84
85impl fmt::Display for ConfigErrorSource {
86    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87        match self {
88            ConfigErrorSource::None => Ok(()),
89            ConfigErrorSource::File(file_name) => {
90                write!(f, " (file {})", file_name.display())
91            }
92            ConfigErrorSource::FieldOverride(name) => write!(f, " (field {name})"),
93        }
94    }
95}
96
97/// Indicates config related errors.
98#[derive(Debug)]
99pub struct ConfigError {
100    source: ConfigErrorSource,
101    kind: ConfigErrorKind,
102}
103
104impl ConfigError {
105    #[inline]
106    fn new(kind: ConfigErrorKind) -> Self {
107        Self {
108            source: ConfigErrorSource::None,
109            kind,
110        }
111    }
112
113    #[inline]
114    fn field(field: &'static str) -> Self {
115        Self {
116            source: ConfigErrorSource::FieldOverride(field.to_owned()),
117            kind: ConfigErrorKind::InvalidValue,
118        }
119    }
120
121    #[inline]
122    fn file(kind: ConfigErrorKind, p: impl AsRef<Path>) -> Self {
123        Self {
124            source: ConfigErrorSource::File(p.as_ref().to_path_buf()),
125            kind,
126        }
127    }
128
129    /// Returns the error kind of the error.
130    pub fn kind(&self) -> ConfigErrorKind {
131        self.kind
132    }
133}
134
135impl fmt::Display for ConfigError {
136    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
137        write!(f, "{}{}", self.kind(), self.source)
138    }
139}
140
141impl Error for ConfigError {}
142
143enum ConfigFormat {
144    Yaml,
145    Json,
146}
147
148impl ConfigFormat {
149    pub fn extension(&self) -> &'static str {
150        match self {
151            ConfigFormat::Yaml => "yml",
152            ConfigFormat::Json => "json",
153        }
154    }
155}
156
157trait ConfigObject: DeserializeOwned + Serialize {
158    /// The format in which to serialize this configuration.
159    fn format() -> ConfigFormat;
160
161    /// The basename of the config file.
162    fn name() -> &'static str;
163
164    /// The full filename of the config file, including the file extension.
165    fn path(base: &Path) -> PathBuf {
166        base.join(format!("{}.{}", Self::name(), Self::format().extension()))
167    }
168
169    /// Loads the config file from a file within the given directory location.
170    fn load(base: &Path) -> anyhow::Result<Self> {
171        let path = Self::path(base);
172
173        let f = fs::File::open(&path)
174            .with_context(|| ConfigError::file(ConfigErrorKind::CouldNotOpenFile, &path))?;
175        let f = io::BufReader::new(f);
176
177        let mut source = {
178            let file = serde_vars::FileSource::default()
179                .with_variable_prefix("${file:")
180                .with_variable_suffix("}")
181                .with_base_path(base);
182            let env = serde_vars::EnvSource::default()
183                .with_variable_prefix("${")
184                .with_variable_suffix("}");
185            (file, env)
186        };
187        match Self::format() {
188            ConfigFormat::Yaml => {
189                serde_vars::deserialize(serde_yaml::Deserializer::from_reader(f), &mut source)
190                    .with_context(|| ConfigError::file(ConfigErrorKind::BadYaml, &path))
191            }
192            ConfigFormat::Json => {
193                serde_vars::deserialize(&mut serde_json::Deserializer::from_reader(f), &mut source)
194                    .with_context(|| ConfigError::file(ConfigErrorKind::BadJson, &path))
195            }
196        }
197    }
198
199    /// Writes the configuration to a file within the given directory location.
200    fn save(&self, base: &Path) -> anyhow::Result<()> {
201        let path = Self::path(base);
202        let mut options = fs::OpenOptions::new();
203        options.write(true).truncate(true).create(true);
204
205        // Remove all non-user permissions for the newly created file
206        #[cfg(unix)]
207        {
208            use std::os::unix::fs::OpenOptionsExt;
209            options.mode(0o600);
210        }
211
212        let mut f = options
213            .open(&path)
214            .with_context(|| ConfigError::file(ConfigErrorKind::CouldNotWriteFile, &path))?;
215
216        match Self::format() {
217            ConfigFormat::Yaml => {
218                f.write_all(CONFIG_YAML_HEADER.as_bytes())?;
219                serde_yaml::to_writer(&mut f, self)
220                    .with_context(|| ConfigError::file(ConfigErrorKind::CouldNotWriteFile, &path))?
221            }
222            ConfigFormat::Json => serde_json::to_writer_pretty(&mut f, self)
223                .with_context(|| ConfigError::file(ConfigErrorKind::CouldNotWriteFile, &path))?,
224        }
225
226        f.write_all(b"\n").ok();
227
228        Ok(())
229    }
230}
231
232/// Structure used to hold information about configuration overrides via
233/// CLI parameters or environment variables
234#[derive(Debug, Default, Clone)]
235pub struct OverridableConfig {
236    /// The operation mode of this relay.
237    pub mode: Option<String>,
238    /// The instance type of this relay.
239    pub instance: Option<String>,
240    /// The log level of this relay.
241    pub log_level: Option<String>,
242    /// The log format of this relay.
243    pub log_format: Option<String>,
244    /// The upstream relay or sentry instance.
245    pub upstream: Option<String>,
246    /// Alternate upstream provided through a Sentry DSN. Key and project will be ignored.
247    pub upstream_dsn: Option<String>,
248    /// The host the relay should bind to (network interface).
249    pub host: Option<String>,
250    /// The port to bind for the unencrypted relay HTTP server.
251    pub port: Option<String>,
252    /// "true" if processing is enabled "false" otherwise
253    pub processing: Option<String>,
254    /// the kafka bootstrap.servers configuration string
255    pub kafka_url: Option<String>,
256    /// the redis server url
257    pub redis_url: Option<String>,
258    /// The globally unique ID of the relay.
259    pub id: Option<String>,
260    /// The secret key of the relay
261    pub secret_key: Option<String>,
262    /// The public key of the relay
263    pub public_key: Option<String>,
264    /// Outcome source
265    pub outcome_source: Option<String>,
266    /// Server name reported in the Sentry SDK.
267    pub server_name: Option<String>,
268}
269
270/// The relay credentials
271#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
272pub struct Credentials {
273    /// The secret key of the relay
274    pub secret_key: SecretKey,
275    /// The public key of the relay
276    pub public_key: PublicKey,
277    /// The globally unique ID of the relay.
278    pub id: RelayId,
279}
280
281impl Credentials {
282    /// Generates new random credentials.
283    pub fn generate() -> Self {
284        relay_log::info!("generating new relay credentials");
285        let (secret_key, public_key) = generate_key_pair();
286        Self {
287            secret_key,
288            public_key,
289            id: generate_relay_id(),
290        }
291    }
292
293    /// Serializes this configuration to JSON.
294    pub fn to_json_string(&self) -> anyhow::Result<String> {
295        serde_json::to_string(self)
296            .with_context(|| ConfigError::new(ConfigErrorKind::CouldNotWriteFile))
297    }
298}
299
300impl ConfigObject for Credentials {
301    fn format() -> ConfigFormat {
302        ConfigFormat::Json
303    }
304    fn name() -> &'static str {
305        "credentials"
306    }
307}
308
309/// Information on a downstream Relay.
310#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
311#[serde(rename_all = "camelCase")]
312pub struct RelayInfo {
313    /// The public key that this Relay uses to authenticate and sign requests.
314    pub public_key: PublicKey,
315
316    /// Marks an internal relay that has privileged access to more project configuration.
317    #[serde(default)]
318    pub internal: bool,
319}
320
321impl RelayInfo {
322    /// Creates a new RelayInfo
323    pub fn new(public_key: PublicKey) -> Self {
324        Self {
325            public_key,
326            internal: false,
327        }
328    }
329}
330
331/// The operation mode of a relay.
332#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
333#[serde(rename_all = "camelCase")]
334pub enum RelayMode {
335    /// This relay acts as a proxy for all requests and events.
336    ///
337    /// Events are normalized and rate limits from the upstream are enforced, but the relay will not
338    /// fetch project configurations from the upstream or perform PII stripping. All events are
339    /// accepted unless overridden on the file system.
340    Proxy,
341
342    /// Project configurations are managed by the upstream.
343    ///
344    /// Project configurations are always fetched from the upstream, unless they are statically
345    /// overridden in the file system. This relay must be allowed in the upstream Sentry. This is
346    /// only possible, if the upstream is Sentry directly, or another managed Relay.
347    Managed,
348}
349
350impl<'de> Deserialize<'de> for RelayMode {
351    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
352    where
353        D: Deserializer<'de>,
354    {
355        let s = String::deserialize(deserializer)?;
356        match s.as_str() {
357            "proxy" => Ok(RelayMode::Proxy),
358            "managed" => Ok(RelayMode::Managed),
359            "static" => Err(serde::de::Error::custom(
360                "Relay mode 'static' has been removed. Please use 'managed' or 'proxy' instead.",
361            )),
362            other => Err(serde::de::Error::unknown_variant(
363                other,
364                &["proxy", "managed"],
365            )),
366        }
367    }
368}
369
370impl fmt::Display for RelayMode {
371    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
372        match self {
373            RelayMode::Proxy => write!(f, "proxy"),
374            RelayMode::Managed => write!(f, "managed"),
375        }
376    }
377}
378
379/// The instance type of Relay.
380#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
381#[serde(rename_all = "camelCase")]
382pub enum RelayInstance {
383    /// This Relay is run as a default instance.
384    Default,
385
386    /// This Relay is run as a canary instance where experiments can be run.
387    Canary,
388}
389
390impl RelayInstance {
391    /// Returns `true` if the [`RelayInstance`] is of type [`RelayInstance::Canary`].
392    pub fn is_canary(&self) -> bool {
393        matches!(self, RelayInstance::Canary)
394    }
395}
396
397impl fmt::Display for RelayInstance {
398    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
399        match self {
400            RelayInstance::Default => write!(f, "default"),
401            RelayInstance::Canary => write!(f, "canary"),
402        }
403    }
404}
405
406impl FromStr for RelayInstance {
407    type Err = fmt::Error;
408
409    fn from_str(s: &str) -> Result<Self, Self::Err> {
410        match s {
411            "canary" => Ok(RelayInstance::Canary),
412            _ => Ok(RelayInstance::Default),
413        }
414    }
415}
416
417/// Error returned when parsing an invalid [`RelayMode`].
418#[derive(Clone, Copy, Debug, Eq, PartialEq)]
419pub struct ParseRelayModeError;
420
421impl fmt::Display for ParseRelayModeError {
422    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
423        write!(f, "Relay mode must be one of: managed or proxy")
424    }
425}
426
427impl Error for ParseRelayModeError {}
428
429impl FromStr for RelayMode {
430    type Err = ParseRelayModeError;
431
432    fn from_str(s: &str) -> Result<Self, Self::Err> {
433        match s {
434            "proxy" => Ok(RelayMode::Proxy),
435            "managed" => Ok(RelayMode::Managed),
436            _ => Err(ParseRelayModeError),
437        }
438    }
439}
440
441/// Returns `true` if this value is equal to `Default::default()`.
442fn is_default<T: Default + PartialEq>(t: &T) -> bool {
443    *t == T::default()
444}
445
446/// Checks if we are running in docker.
447fn is_docker() -> bool {
448    if fs::metadata("/.dockerenv").is_ok() {
449        return true;
450    }
451
452    fs::read_to_string("/proc/self/cgroup").is_ok_and(|s| s.contains("/docker"))
453}
454
455/// Default value for the "bind" configuration.
456fn default_host() -> IpAddr {
457    if is_docker() {
458        // Docker images rely on this service being exposed
459        "0.0.0.0".parse().unwrap()
460    } else {
461        "127.0.0.1".parse().unwrap()
462    }
463}
464
465/// Controls responses from the readiness health check endpoint based on authentication.
466///
467/// Independent of the the readiness condition, shutdown always switches Relay into unready state.
468#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
469#[serde(rename_all = "lowercase")]
470#[derive(Default)]
471pub enum ReadinessCondition {
472    /// (default) Relay is ready when authenticated and connected to the upstream.
473    ///
474    /// Before authentication has succeeded and during network outages, Relay responds as not ready.
475    /// Relay reauthenticates based on the `http.auth_interval` parameter. During reauthentication,
476    /// Relay remains ready until authentication fails.
477    ///
478    /// Authentication is only required for Relays in managed mode. Other Relays will only check for
479    /// network outages.
480    #[default]
481    Authenticated,
482    /// Relay reports readiness regardless of the authentication and networking state.
483    Always,
484}
485
486/// Relay specific configuration values.
487#[derive(Serialize, Deserialize, Debug, Clone)]
488#[serde(default)]
489pub struct Relay {
490    /// The operation mode of this Relay.
491    pub mode: RelayMode,
492    /// The instance type of this Relay.
493    pub instance: RelayInstance,
494    /// The upstream Relay or Sentry instance.
495    pub upstream: UpstreamDescriptor,
496    /// The upstream advertised to downstream Relay instances.
497    ///
498    /// This value will be advertised to downstream Relays as the upstream to use when forwarding
499    /// data. It can be used for traffic routing and balancing, it must not redirect to a different
500    /// Sentry instance.
501    ///
502    /// Downstream Relays will treat the advertised upstream as the same logical component as this instance
503    /// and re-use already established authentication keys.
504    pub advertised_upstream: Option<UpstreamDescriptor>,
505    /// The host the relay should bind to (network interface).
506    pub host: IpAddr,
507    /// The port to bind for the unencrypted relay HTTP server.
508    pub port: u16,
509    /// The host the relay should bind to (network interface) for internally exposed APIs, like
510    /// health checks.
511    ///
512    /// If not configured, internal routes are exposed on the main HTTP server.
513    ///
514    /// Note: configuring the internal http server on an address which overlaps with the main
515    /// server (e.g. main on `0.0.0.0:3000` and internal on `127.0.0.1:3000`) is a misconfiguration
516    /// resulting in approximately half of the requests sent to `127.0.0.1:3000` to fail, as the handling
517    /// http server is chosen by the operating system 'at random'.
518    ///
519    /// As a best practice you should always choose different ports to avoid this issue.
520    ///
521    /// Defaults to [`Self::host`].
522    pub internal_host: Option<IpAddr>,
523    /// The port to bind for internally exposed APIs.
524    ///
525    /// Defaults to [`Self::port`].
526    pub internal_port: Option<u16>,
527    /// Always override project IDs from the URL and DSN with the identifier used at the upstream.
528    ///
529    /// Enable this setting for Relays used to redirect traffic to a migrated Sentry instance.
530    /// Validation of project identifiers can be safely skipped in these cases.
531    #[serde(skip_serializing_if = "is_default")]
532    pub override_project_ids: bool,
533    /// Interval in seconds for Relay to check if its configuration changed.
534    ///
535    /// If configured Relay will periodically check its configuration for changes
536    /// and hot reload it.
537    ///
538    /// Hot reloading is only supported for a limited set of values.
539    ///
540    /// Defaults to `None` / off.
541    pub config_reload_interval: Option<u64>,
542}
543
544impl Default for Relay {
545    fn default() -> Self {
546        Relay {
547            mode: RelayMode::Managed,
548            instance: RelayInstance::Default,
549            upstream: "https://sentry.io/".parse().unwrap(),
550            advertised_upstream: None,
551            host: default_host(),
552            port: 3000,
553            internal_host: None,
554            internal_port: None,
555            override_project_ids: false,
556            config_reload_interval: None,
557        }
558    }
559}
560
561/// Control the metrics.
562#[derive(Serialize, Deserialize, Debug, Clone)]
563#[serde(default)]
564pub struct Metrics {
565    /// Hostname and port of the statsd server.
566    ///
567    /// Defaults to `None`.
568    pub statsd: Option<String>,
569    /// Buffer size used for metrics sent to the statsd socket.
570    ///
571    /// Defaults to `None`.
572    pub statsd_buffer_size: Option<usize>,
573    /// Common prefix that should be added to all metrics.
574    ///
575    /// Defaults to `"sentry.relay"`.
576    pub prefix: String,
577    /// Default tags to apply to all metrics.
578    pub default_tags: BTreeMap<String, String>,
579    /// Tag name to report the hostname to for each metric. Defaults to not sending such a tag.
580    pub hostname_tag: Option<String>,
581    /// Interval for periodic metrics emitted from Relay.
582    ///
583    /// Setting it to `0` seconds disables the periodic metrics.
584    /// Defaults to 5 seconds.
585    pub periodic_secs: u64,
586}
587
588impl Default for Metrics {
589    fn default() -> Self {
590        Metrics {
591            statsd: None,
592            statsd_buffer_size: None,
593            prefix: "sentry.relay".into(),
594            default_tags: BTreeMap::new(),
595            hostname_tag: None,
596            periodic_secs: 5,
597        }
598    }
599}
600
601/// Controls various limits
602#[derive(Serialize, Deserialize, Debug, Clone)]
603#[serde(default)]
604pub struct Limits {
605    /// How many requests can be sent concurrently from Relay to the upstream before Relay starts
606    /// buffering.
607    pub max_concurrent_requests: usize,
608    /// How many queries can be sent concurrently from Relay to the upstream before Relay starts
609    /// buffering.
610    ///
611    /// The concurrency of queries is additionally constrained by `max_concurrent_requests`.
612    pub max_concurrent_queries: usize,
613    /// The maximum payload size for events.
614    pub max_event_size: ByteSize,
615    /// The maximum size for each attachment.
616    pub max_attachment_size: ByteSize,
617    /// The maximum amount of attachments in a single envelope.
618    pub max_attachment_count: usize,
619    /// The maximum combined size for all attachments in an envelope or request.
620    pub max_attachments_size: ByteSize,
621    /// The maximum size for a TUS upload request body.
622    ///
623    /// Applies to incoming request bytes at every hop and also to decoded bytes when writing to
624    /// objectstore.
625    pub max_upload_size: ByteSize,
626    /// The maximum combined size for all client reports in an envelope or request.
627    pub max_client_reports_size: ByteSize,
628    /// The maximum number of client report items per envelope.
629    pub max_client_reports_count: usize,
630    /// The maximum payload size for a monitor check-in.
631    pub max_check_in_size: ByteSize,
632    /// The maximum payload size for an entire envelopes. Individual limits still apply.
633    pub max_envelope_size: ByteSize,
634    /// The maximum combined size for all sessions in an envelope in bytes.
635    pub max_sessions_size: ByteSize,
636    /// The maximum number of session items per envelope.
637    pub max_session_count: usize,
638    /// The maximum payload size for general API requests.
639    pub max_api_payload_size: ByteSize,
640    /// The maximum payload size for file uploads and chunks.
641    pub max_api_file_upload_size: ByteSize,
642    /// The maximum payload size for chunks
643    pub max_api_chunk_upload_size: ByteSize,
644    /// The maximum payload size for a profile
645    pub max_profile_size: ByteSize,
646    /// The maximum payload size for a trace metric.
647    pub max_trace_metric_size: ByteSize,
648    /// The maximum payload size for a log.
649    pub max_log_size: ByteSize,
650    /// The maximum number of operations that can occur in a log expansion.
651    pub max_expanded_log_operations: usize,
652    /// The maximum number of operations that can occur in a span expansion.
653    pub max_expanded_span_operations: usize,
654    /// The maximum number of operations that can occur in a trace metric expansion.
655    pub max_expanded_trace_metric_operations: usize,
656    /// The maximum size in bytes of spans that can result from a span expansion.
657    pub max_expanded_span_bytes: ByteSize,
658    /// The maximum total number of bytes that can result from a log expansion.
659    pub max_expanded_logs_size: ByteSize,
660    /// The maximum payload size for a span.
661    pub max_span_size: ByteSize,
662    /// The maximum amount of standalone transaction spans per envelope.
663    pub max_standalone_span_count: usize,
664    /// The maximum payload size for an item container.
665    pub max_container_size: ByteSize,
666    /// The maximum payload size for metric buckets.
667    pub max_metric_buckets_size: ByteSize,
668    /// The maximum payload size for a compressed replay.
669    pub max_replay_compressed_size: ByteSize,
670    /// The maximum payload size for an uncompressed replay.
671    #[serde(alias = "max_replay_size")]
672    max_replay_uncompressed_size: ByteSize,
673    /// The maximum size for a replay recording Kafka message.
674    pub max_replay_message_size: ByteSize,
675    /// The byte size limit up to which Relay will retain
676    /// keys of invalid/removed attributes.
677    ///
678    /// This is only relevant for EAP items (spans, logs, …).
679    /// In principle, we want to record all deletions of attributes,
680    /// but we have to institute some limit to protect our infrastructure
681    /// against excessive metadata sizes.
682    ///
683    /// Defaults to 10KiB.
684    pub max_removed_attribute_key_size: ByteSize,
685    /// The maximum number of threads to spawn for CPU and web work, each.
686    ///
687    /// The total number of threads spawned will roughly be `2 * max_thread_count`. Defaults to
688    /// the number of logical CPU cores on the host.
689    pub max_thread_count: usize,
690    /// Controls the maximum concurrency of each worker thread.
691    ///
692    /// Increasing the concurrency, can lead to a better utilization of worker threads by
693    /// increasing the amount of I/O done concurrently.
694    //
695    /// Currently has no effect on defaults to `1`.
696    pub max_pool_concurrency: usize,
697    /// The maximum number of seconds a query is allowed to take across retries. Individual requests
698    /// have lower timeouts. Defaults to 30 seconds.
699    pub query_timeout: u64,
700    /// Server keep-alive timeout in seconds.
701    ///
702    /// By default, keep-alive is set to 5 seconds.
703    pub keepalive_timeout: u64,
704    /// How long Relay waits for a request on an HTTP/1.1 connection, in seconds.
705    ///
706    /// Relay closes the connection if the request headers don't arrive in time. This also
707    /// applies to idle connections waiting for their next request.
708    ///
709    /// Behind a proxy like nginx, set this higher than the proxy's keep-alive timeout.
710    /// Otherwise Relay can close a connection just as the proxy sends a request on it,
711    /// and the client gets an error.
712    ///
713    /// Defaults to 5 seconds.
714    pub header_read_timeout: u64,
715    /// Server idle timeout in seconds.
716    ///
717    /// The idle timeout limits the amount of time a connection is kept open without activity.
718    /// Setting this too short may abort connections before Relay is able to send a response.
719    ///
720    /// By default there is no idle timeout.
721    pub idle_timeout: Option<u64>,
722    /// Sets the maximum number of concurrent connections.
723    ///
724    /// Upon reaching the limit, the server will stop accepting connections.
725    ///
726    /// By default there is no limit.
727    pub max_connections: Option<usize>,
728    /// The TCP listen backlog.
729    ///
730    /// Configures the TCP listen backlog for the listening socket of Relay.
731    /// See [`man listen(2)`](https://man7.org/linux/man-pages/man2/listen.2.html)
732    /// for a more detailed description of the listen backlog.
733    ///
734    /// 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).
735    pub tcp_listen_backlog: u32,
736}
737
738impl Default for Limits {
739    fn default() -> Self {
740        Limits {
741            max_concurrent_requests: 100,
742            max_concurrent_queries: 5,
743            max_event_size: ByteSize::mebibytes(1),
744            max_attachment_size: ByteSize::mebibytes(200),
745            max_attachment_count: 30,
746            max_attachments_size: ByteSize::mebibytes(200),
747            max_upload_size: ByteSize::mebibytes(10240),
748            max_client_reports_size: ByteSize::kibibytes(100),
749            max_client_reports_count: 100,
750            max_check_in_size: ByteSize::kibibytes(100),
751            max_envelope_size: ByteSize::mebibytes(200),
752            max_sessions_size: ByteSize::mebibytes(10),
753            max_session_count: 100,
754            max_api_payload_size: ByteSize::mebibytes(20),
755            max_api_file_upload_size: ByteSize::mebibytes(40),
756            max_api_chunk_upload_size: ByteSize::mebibytes(100),
757            max_profile_size: ByteSize::mebibytes(50),
758            max_trace_metric_size: ByteSize::mebibytes(1),
759            max_log_size: ByteSize::mebibytes(2),
760            max_expanded_log_operations: 3_000_000,
761            max_expanded_span_operations: 3_000_000,
762            max_expanded_trace_metric_operations: 3_000_000,
763            max_expanded_span_bytes: ByteSize::mebibytes(20),
764            max_expanded_logs_size: ByteSize::mebibytes(100),
765            max_span_size: ByteSize::mebibytes(10),
766            max_standalone_span_count: 25,
767            max_container_size: ByteSize::mebibytes(12),
768            max_metric_buckets_size: ByteSize::mebibytes(1),
769            max_replay_compressed_size: ByteSize::mebibytes(10),
770            max_replay_uncompressed_size: ByteSize::mebibytes(100),
771            max_replay_message_size: ByteSize::mebibytes(15),
772            max_thread_count: num_cpus::get(),
773            max_pool_concurrency: 1,
774            query_timeout: 30,
775            keepalive_timeout: 5,
776            header_read_timeout: 5,
777            idle_timeout: None,
778            max_connections: None,
779            tcp_listen_backlog: 1024,
780            max_removed_attribute_key_size: ByteSize::kibibytes(10),
781        }
782    }
783}
784
785/// Controls traffic steering.
786#[derive(Debug, Default, Deserialize, Serialize, Clone)]
787#[serde(default)]
788pub struct Routing {
789    /// Accept and forward unknown Envelope items to the upstream.
790    ///
791    /// Forwarding unknown items should be enabled in most cases to allow proxying traffic for newer
792    /// SDK versions. The upstream in Sentry makes the final decision on which items are valid. If
793    /// this is disabled, just the unknown items are removed from Envelopes, and the rest is
794    /// processed as usual.
795    ///
796    /// Defaults to `true` for all Relay modes other than processing mode. In processing mode, this
797    /// is disabled by default since the item cannot be handled.
798    pub accept_unknown_items: Option<bool>,
799}
800
801/// Http content encoding for both incoming and outgoing web requests.
802#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
803#[serde(rename_all = "lowercase")]
804pub enum HttpEncoding {
805    /// Identity function without no compression.
806    ///
807    /// This is the default encoding and does not require the presence of the `content-encoding`
808    /// HTTP header.
809    #[default]
810    Identity,
811    /// Compression using a [zlib](https://en.wikipedia.org/wiki/Zlib) structure with
812    /// [deflate](https://en.wikipedia.org/wiki/DEFLATE) encoding.
813    ///
814    /// These structures are defined in [RFC 1950](https://datatracker.ietf.org/doc/html/rfc1950)
815    /// and [RFC 1951](https://datatracker.ietf.org/doc/html/rfc1951).
816    Deflate,
817    /// A format using the [Lempel-Ziv coding](https://en.wikipedia.org/wiki/LZ77_and_LZ78#LZ77)
818    /// (LZ77), with a 32-bit CRC.
819    ///
820    /// This is the original format of the UNIX gzip program. The HTTP/1.1 standard also recommends
821    /// that the servers supporting this content-encoding should recognize `x-gzip` as an alias, for
822    /// compatibility purposes.
823    Gzip,
824    /// A format using the [Brotli](https://en.wikipedia.org/wiki/Brotli) algorithm.
825    Br,
826    /// A format using the [Zstd](https://en.wikipedia.org/wiki/Zstd) compression algorithm.
827    Zstd,
828}
829
830impl HttpEncoding {
831    /// Parses a [`HttpEncoding`] from its `content-encoding` header value.
832    ///
833    /// Accepts aliases, whitespace, and mixed case; unknown values fall back to identity.
834    /// Use [`Self::parse_strict`] when validating an incoming request header.
835    pub fn parse(str: &str) -> Self {
836        let str = str.trim();
837        if str.eq_ignore_ascii_case("zstd") {
838            Self::Zstd
839        } else if str.eq_ignore_ascii_case("br") {
840            Self::Br
841        } else if str.eq_ignore_ascii_case("gzip") || str.eq_ignore_ascii_case("x-gzip") {
842            Self::Gzip
843        } else if str.eq_ignore_ascii_case("deflate") {
844            Self::Deflate
845        } else {
846            Self::Identity
847        }
848    }
849
850    /// Parses a canonical `Content-Encoding` value, returning `None` for unsupported values.
851    pub fn parse_strict(value: &str) -> Option<Self> {
852        match value {
853            "identity" => Some(Self::Identity),
854            "deflate" => Some(Self::Deflate),
855            "gzip" => Some(Self::Gzip),
856            "br" => Some(Self::Br),
857            "zstd" => Some(Self::Zstd),
858            _ => None,
859        }
860    }
861
862    /// Returns the value for the `content-encoding` HTTP header.
863    ///
864    /// Returns `None` for [`Identity`](Self::Identity), and `Some` for other encodings.
865    pub fn name(&self) -> Option<&'static str> {
866        match self {
867            Self::Identity => None,
868            Self::Deflate => Some("deflate"),
869            Self::Gzip => Some("gzip"),
870            Self::Br => Some("br"),
871            Self::Zstd => Some("zstd"),
872        }
873    }
874}
875
876/// Controls authentication with upstream.
877#[derive(Serialize, Deserialize, Debug, Clone)]
878#[serde(default)]
879pub struct Http {
880    /// Timeout for upstream requests in seconds.
881    ///
882    /// This timeout covers the time from sending the request until receiving response headers.
883    /// Neither the connection process and handshakes, nor reading the response body is covered in
884    /// this timeout.
885    pub timeout: u32,
886    /// Timeout for establishing connections with the upstream in seconds.
887    ///
888    /// This includes SSL handshakes. Relay reuses connections when the upstream supports connection
889    /// keep-alive. Connections are retained for a maximum 75 seconds, or 15 seconds of inactivity.
890    pub connection_timeout: u32,
891    /// Maximum interval between failed request retries in seconds.
892    pub max_retry_interval: u32,
893    /// The custom HTTP Host header to send to the upstream.
894    pub host_header: Option<String>,
895    /// The interval in seconds at which Relay attempts to reauthenticate with the upstream server.
896    ///
897    /// Re-authentication happens even when Relay is idle. If authentication fails, Relay reverts
898    /// back into startup mode and tries to establish a connection. During this time, incoming
899    /// envelopes will be buffered.
900    ///
901    /// Defaults to `600` (10 minutes).
902    pub auth_interval: Option<u64>,
903    /// The maximum time of experiencing uninterrupted network failures until Relay considers that
904    /// it has encountered a network outage in seconds.
905    ///
906    /// During a network outage relay will try to reconnect and will buffer all upstream messages
907    /// until it manages to reconnect.
908    pub outage_grace_period: u64,
909    /// The time Relay waits before retrying an upstream request, in seconds.
910    ///
911    /// This time is only used before going into a network outage mode.
912    pub retry_delay: u64,
913    /// The interval in seconds for continued failed project fetches at which Relay will error.
914    ///
915    /// A successful fetch resets this interval. Relay does nothing during long
916    /// times without emitting requests.
917    pub project_failure_interval: u64,
918    /// Content encoding to apply to upstream store requests.
919    ///
920    /// By default, Relay applies `zstd` content encoding to compress upstream requests. Compression
921    /// can be disabled to reduce CPU consumption, but at the expense of increased network traffic.
922    ///
923    /// This setting applies to all store requests of SDK data, including events, transactions,
924    /// envelopes and sessions. At the moment, this does not apply to Relay's internal queries.
925    ///
926    /// Available options are:
927    ///
928    ///  - `identity`: Disables compression.
929    ///  - `deflate`: Compression using a zlib header with deflate encoding.
930    ///  - `gzip` (default): Compression using gzip.
931    ///  - `br`: Compression using the brotli algorithm.
932    ///  - `zstd`: Compression using the zstd algorithm.
933    pub encoding: HttpEncoding,
934    /// Submit metrics globally through a shared endpoint.
935    ///
936    /// As opposed to regular envelopes which are sent to an endpoint inferred from the project's
937    /// DSN, this submits metrics to the global endpoint with Relay authentication.
938    ///
939    /// This option does not have any effect on processing mode.
940    pub global_metrics: bool,
941    /// Controls whether the forward endpoint is enabled.
942    ///
943    /// The forward endpoint forwards unknown API requests to the upstream.
944    ///
945    /// Relay instances with processing enabled are expected to support the latest API and do never
946    /// support forwarding requests to Sentry.
947    pub forward: bool,
948    /// Enables an async DNS resolver through the `hickory-dns` crate, which uses an LRU cache for
949    /// the resolved entries. This helps to limit the amount of requests made to the upstream DNS
950    /// server (important for K8s infrastructure).
951    pub dns_cache: bool,
952}
953
954impl Default for Http {
955    fn default() -> Self {
956        Http {
957            timeout: 5,
958            connection_timeout: 3,
959            max_retry_interval: 60, // 1 minute
960            host_header: None,
961            auth_interval: Some(600), // 10 minutes
962            outage_grace_period: DEFAULT_NETWORK_OUTAGE_GRACE_PERIOD,
963            retry_delay: 1,
964            project_failure_interval: 90,
965            encoding: HttpEncoding::Zstd,
966            global_metrics: false,
967            forward: true,
968            dns_cache: true,
969        }
970    }
971}
972
973/// Strategy used to assign envelopes to buffer partitions.
974#[derive(Clone, Copy, Debug, Eq, PartialEq, Default, Deserialize, Serialize)]
975#[serde(rename_all = "snake_case")]
976pub enum EnvelopeSpoolPartitioning {
977    /// Envelopes with the same project key pair land on the same partition.
978    ///
979    /// Keeps per-project state, disk files, and event ordering co-located on one partition.
980    ProjectKeyPair,
981    /// Envelopes are distributed across partitions in a round-robin fashion (default).
982    ///
983    /// This prevents "hot" partitions when a single project pair dominates traffic, but has
984    /// trade-offs:
985    /// - Per-project LIFO ordering is no longer preserved across partitions.
986    /// - Per-partition memory footprint grows since every partition sees every project.
987    #[default]
988    RoundRobin,
989}
990
991/// Persistent buffering configuration for incoming envelopes.
992#[derive(Debug, Serialize, Deserialize, Clone)]
993#[serde(default)]
994pub struct EnvelopeSpool {
995    /// The path of the SQLite database file(s) which persist the data.
996    ///
997    /// Based on the number of partitions, more database files will be created within the same path.
998    ///
999    /// If not set, the envelopes will be buffered in memory.
1000    pub path: Option<PathBuf>,
1001    /// The maximum size of the buffer to keep, in bytes.
1002    ///
1003    /// When the on-disk buffer reaches this size, new envelopes will be dropped.
1004    ///
1005    /// Defaults to 500MB.
1006    pub max_disk_size: ByteSize,
1007    /// Size of the batch of compressed envelopes that are spooled to disk at once.
1008    ///
1009    /// Note that this is the size after which spooling will be triggered but it does not guarantee
1010    /// that exactly this size will be spooled, it can be greater or equal.
1011    ///
1012    /// Defaults to 10 KiB.
1013    pub batch_size_bytes: ByteSize,
1014    /// Time after which a batch is flushed, regardless of batch size.
1015    ///
1016    /// The age of the batch is only checked when a new envelope comes in, but in practice this
1017    /// has the desired effect: High-volume projects always form full batches, low-volume batches
1018    /// flush individual envelopes to keep memory usage low.
1019    pub flush_timeout_secs: Option<u64>,
1020    /// Maximum time between receiving the envelope and processing it.
1021    ///
1022    /// When envelopes spend too much time in the buffer (e.g. because their project cannot be loaded),
1023    /// they are dropped.
1024    ///
1025    /// Defaults to 24h.
1026    pub max_envelope_delay_secs: u64,
1027    /// The refresh frequency in ms of how frequently disk usage is updated by querying SQLite
1028    /// internal page stats.
1029    ///
1030    /// Defaults to 100ms.
1031    pub disk_usage_refresh_frequency_ms: u64,
1032    /// The relative memory usage above which the buffer service will stop dequeueing envelopes.
1033    ///
1034    /// Only applies when [`Self::path`] is set.
1035    ///
1036    /// This value should be lower than [`Health::max_memory_percent`] to prevent flip-flopping.
1037    ///
1038    /// Warning: This threshold can cause the buffer service to deadlock when the buffer consumes
1039    /// excessive memory (as influenced by [`Self::batch_size_bytes`]).
1040    ///
1041    /// This scenario arises when the buffer stops spooling due to reaching the
1042    /// [`Self::max_backpressure_memory_percent`] limit, but the batch threshold for spooling
1043    /// ([`Self::batch_size_bytes`]) is never reached. As a result, no data is spooled, memory usage
1044    /// continues to grow, and the system becomes deadlocked.
1045    ///
1046    /// ### Example
1047    /// Suppose the system has 1GB of available memory and is configured to spool only after
1048    /// accumulating 10GB worth of envelopes. If Relay consumes 900MB of memory, it will stop
1049    /// unspooling due to reaching the [`Self::max_backpressure_memory_percent`] threshold.
1050    ///
1051    /// However, because the buffer hasn't accumulated the 10GB needed to trigger spooling,
1052    /// no data will be offloaded. Memory usage keeps increasing until it hits the
1053    /// [`Health::max_memory_percent`] threshold, e.g., at 950MB. At this point:
1054    ///
1055    /// - No more envelopes are accepted.
1056    /// - The buffer remains stuck, as unspooling won’t resume until memory drops below 900MB which
1057    ///   will not happen.
1058    /// - A deadlock occurs, with the system unable to recover without manual intervention.
1059    ///
1060    /// Defaults to 90% (5% less than max memory).
1061    pub max_backpressure_memory_percent: f32,
1062    /// Number of partitions of the buffer.
1063    ///
1064    /// A partition is a separate instance of the buffer which has its own isolated queue, stacks
1065    /// and other resources.
1066    ///
1067    /// Defaults to 1.
1068    pub partitions: NonZeroU8,
1069    /// Strategy used to assign envelopes to buffer partitions.
1070    ///
1071    /// Defaults to partitioning by `ProjectKeyPair`, which keeps all envelopes of a given project
1072    /// pair on the same partition. See [`EnvelopeSpoolPartitioning`] for alternatives and
1073    /// trade-offs.
1074    pub partitioning: EnvelopeSpoolPartitioning,
1075    /// Maximum number of envelopes unspooled from disk per second.
1076    ///
1077    /// The limit applies per Relay instance, not per spool partition.
1078    ///
1079    /// Defaults to `None`, which disables the limit.
1080    pub max_unspool_envelopes_per_second: Option<NonZeroU32>,
1081    /// Whether the database defined in `path` is on an ephemeral storage disk.
1082    ///
1083    /// With `ephemeral: true`, Relay does not spool in-flight data to disk
1084    /// during graceful shutdown. Instead, it attempts to process all data before it terminates.
1085    ///
1086    /// Defaults to `false`.
1087    pub ephemeral: bool,
1088}
1089
1090impl Default for EnvelopeSpool {
1091    fn default() -> Self {
1092        Self {
1093            path: None,
1094            max_disk_size: ByteSize::mebibytes(500),
1095            batch_size_bytes: ByteSize::kibibytes(10),
1096            max_envelope_delay_secs: 24 * 60 * 60,
1097            disk_usage_refresh_frequency_ms: 100,
1098            max_backpressure_memory_percent: 0.8,
1099            partitions: NonZeroU8::new(1).unwrap(),
1100            partitioning: EnvelopeSpoolPartitioning::default(),
1101            ephemeral: false,
1102            flush_timeout_secs: None,
1103            max_unspool_envelopes_per_second: None,
1104        }
1105    }
1106}
1107
1108/// Persistent buffering configuration.
1109#[derive(Debug, Serialize, Deserialize, Default, Clone)]
1110#[serde(default)]
1111pub struct Spool {
1112    /// Configuration for envelope spooling.
1113    pub envelopes: EnvelopeSpool,
1114}
1115
1116/// Controls internal caching behavior.
1117#[derive(Serialize, Deserialize, Debug, Clone)]
1118#[serde(default)]
1119pub struct Cache {
1120    /// The full project state will be requested by this Relay if set to `true`.
1121    ///
1122    /// Relay instances that receive the full project config have full access to quota config
1123    /// and perform dynamic sampling.
1124    pub project_request_full_config: bool,
1125    /// The cache timeout for project configurations in seconds.
1126    pub project_expiry: u32,
1127    /// Continue using project state this many seconds after cache expiry while a new state is
1128    /// being fetched. This is added on top of `project_expiry`.
1129    ///
1130    /// Default is 2 minutes.
1131    pub project_grace_period: u32,
1132    /// Refresh a project after the specified seconds.
1133    ///
1134    /// The time must be between expiry time and the grace period.
1135    ///
1136    /// By default there are no refreshes enabled.
1137    pub project_refresh_interval: Option<u32>,
1138    /// The cache timeout for downstream relay info (public keys) in seconds.
1139    pub relay_expiry: u32,
1140    /// The cache timeout for non-existing entries.
1141    pub miss_expiry: u32,
1142    /// The buffer timeout for batched project config queries before sending them upstream in ms.
1143    pub batch_interval: u32,
1144    /// The buffer timeout for batched queries of downstream relays in ms. Defaults to 100ms.
1145    pub downstream_relays_batch_interval: u32,
1146    /// The maximum number of project configs to fetch from Sentry at once. Defaults to 500.
1147    ///
1148    /// `cache.batch_interval` controls how quickly batches are sent, this controls the batch size.
1149    pub batch_size: usize,
1150    /// Interval for watching local cache override files in seconds.
1151    pub file_interval: u32,
1152    /// Interval for fetching new global configs from the upstream, in seconds.
1153    pub global_config_fetch_interval: u32,
1154}
1155
1156impl Default for Cache {
1157    fn default() -> Self {
1158        Cache {
1159            project_request_full_config: false,
1160            project_expiry: 300,       // 5 minutes
1161            project_grace_period: 120, // 2 minutes
1162            project_refresh_interval: None,
1163            relay_expiry: 3600,                    // 1 hour
1164            miss_expiry: 60,                       // 1 minute
1165            batch_interval: 100,                   // 100ms
1166            downstream_relays_batch_interval: 100, // 100ms
1167            batch_size: 500,
1168            file_interval: 10,                // 10 seconds
1169            global_config_fetch_interval: 10, // 10 seconds
1170        }
1171    }
1172}
1173
1174/// Controls Sentry-internal event processing.
1175#[derive(Serialize, Deserialize, Debug, Clone)]
1176#[serde(default)]
1177pub struct Processing {
1178    /// True if the Relay should do processing. Defaults to `false`.
1179    pub enabled: bool,
1180    /// GeoIp DB file source.
1181    pub geoip_path: Option<PathBuf>,
1182    /// Maximum future timestamp of ingested events.
1183    pub max_secs_in_future: u32,
1184    /// Maximum age of ingested sessions. Older sessions will be dropped.
1185    pub max_session_secs_in_past: u32,
1186    /// Kafka producer configurations.
1187    pub kafka_config: Vec<KafkaConfigParam>,
1188    /// Additional kafka producer configurations.
1189    ///
1190    /// The `kafka_config` is the default producer configuration used for all topics. A secondary
1191    /// kafka config can be referenced in `topics:` like this:
1192    ///
1193    /// ```yaml
1194    /// secondary_kafka_configs:
1195    ///   mycustomcluster:
1196    ///     - name: 'bootstrap.servers'
1197    ///       value: 'sentry_kafka_metrics:9093'
1198    ///
1199    /// topics:
1200    ///   transactions: ingest-transactions
1201    ///   metrics:
1202    ///     name: ingest-metrics
1203    ///     config: mycustomcluster
1204    /// ```
1205    ///
1206    /// Then metrics will be produced to an entirely different Kafka cluster.
1207    pub secondary_kafka_configs: BTreeMap<String, Vec<KafkaConfigParam>>,
1208    /// Kafka topic names.
1209    pub topics: TopicAssignments,
1210    /// Whether to validate the supplied topics by calling Kafka's metadata endpoints.
1211    pub kafka_validate_topics: bool,
1212    /// Upper bound, in seconds, on the random delay before a Kafka producer swaps its client
1213    /// after the Kafka config changed.
1214    ///
1215    /// Spreads swaps out so that a config change does not have every pod in the fleet reconnect
1216    /// at once. Keep it well below how often the Kafka config is expected to change. Tests set
1217    /// this to `0` to observe a swap without waiting.
1218    pub reloading_producer_jitter_secs: u64,
1219    /// Redis hosts to connect to for storing state for rate limits.
1220    pub redis: Option<RedisConfigs>,
1221    /// Maximum chunk size of attachments for Kafka.
1222    pub attachment_chunk_size: ByteSize,
1223    /// Prefix to use when looking up project configs in Redis. Defaults to "relayconfig".
1224    pub projectconfig_cache_prefix: String,
1225    /// Maximum rate limit to report to clients.
1226    pub max_rate_limit: Option<u32>,
1227    /// Configures the quota cache ratio between `0.0` and `1.0`.
1228    ///
1229    /// The quota cache, caches the specified ratio of remaining quota in memory to reduce the
1230    /// amount of synchronizations required with Redis.
1231    ///
1232    /// The ratio is applied to the (per second) rate of the quota, not the total limit.
1233    /// For example a quota with limit 100 with a 10 second window is treated equally to a quota of
1234    /// 10 with a 1 second window.
1235    ///
1236    /// By default quota caching is disabled.
1237    pub quota_cache_ratio: Option<f32>,
1238    /// Relative amount of the total quota limit to which quota caching is applied.
1239    ///
1240    /// If exceeded, the rate limiter will no longer cache the quota and sync with Redis on every call instead.
1241    /// Lowering this value reduces the probability of incorrectly over-accepting.
1242    ///
1243    /// Must be between `0.0` and `1.0`, by default there is no limit configured.
1244    pub quota_cache_max: Option<f32>,
1245    /// Configuration for the objectstore service.
1246    #[serde(alias = "upload")]
1247    pub objectstore: ObjectstoreServiceConfig,
1248}
1249
1250impl Default for Processing {
1251    /// Constructs a disabled processing configuration.
1252    fn default() -> Self {
1253        Self {
1254            enabled: false,
1255            geoip_path: None,
1256            max_secs_in_future: 60,                  // 1 minute
1257            max_session_secs_in_past: 5 * 24 * 3600, // 5 days
1258            kafka_config: Vec::new(),
1259            secondary_kafka_configs: BTreeMap::new(),
1260            topics: TopicAssignments::default(),
1261            kafka_validate_topics: false,
1262            reloading_producer_jitter_secs: 60,
1263            redis: None,
1264            attachment_chunk_size: ByteSize::mebibytes(1),
1265            projectconfig_cache_prefix: "relayconfig".to_owned(),
1266            max_rate_limit: Some(300), // 5 minutes
1267            quota_cache_ratio: None,
1268            quota_cache_max: None,
1269            objectstore: ObjectstoreServiceConfig::default(),
1270        }
1271    }
1272}
1273
1274/// Picks a cluster name for the default `kafka_config` that no secondary config uses.
1275///
1276/// Only relevant to [`ConfigSnapshot::kafka_config_blob`]: the blob names every cluster, while
1277/// Relay's own config leaves the default one anonymous. Appends underscores to `default` until
1278/// it is unused.
1279fn default_cluster_name(processing: &Processing) -> String {
1280    let mut name = String::from("default");
1281    while processing.secondary_kafka_configs.contains_key(&name) {
1282        name.push('_');
1283    }
1284    name
1285}
1286
1287/// Configuration for normalization in this Relay.
1288#[derive(Debug, Default, Serialize, Deserialize, Clone)]
1289#[serde(default)]
1290pub struct Normalization {
1291    /// Level of normalization for Relay to apply to incoming data.
1292    pub level: NormalizationLevel,
1293}
1294
1295/// Configuration for the level of normalization this Relay should do.
1296#[derive(Copy, Clone, Debug, Default, Serialize, Deserialize, Eq, PartialEq)]
1297#[serde(rename_all = "lowercase")]
1298pub enum NormalizationLevel {
1299    /// Runs normalization, excluding steps that break future compatibility.
1300    ///
1301    /// Processing Relays run [`NormalizationLevel::Full`] if this option is set.
1302    #[default]
1303    Default,
1304    /// Run full normalization.
1305    ///
1306    /// It includes steps that break future compatibility and should only run in
1307    /// the last layer of relays.
1308    Full,
1309}
1310
1311/// Configuration options for objectstore's auth scheme.
1312#[derive(Serialize, Deserialize, Clone)]
1313pub struct ObjectstoreAuthConfig {
1314    /// Identifier for the private key used to sign objectstore's tokens. Must correspond to a
1315    /// public key configured in objectstore.
1316    pub key_id: String,
1317
1318    /// EdDSA private key used to sign Objectstore's tokens, in PEM format.
1319    pub signing_key: String,
1320}
1321
1322impl fmt::Debug for ObjectstoreAuthConfig {
1323    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1324        f.debug_struct("ObjectstoreAuthConfig")
1325            .field("key_id", &self.key_id)
1326            .field("signing_key", &"[redacted]")
1327            .finish()
1328    }
1329}
1330
1331/// Configuration values for the objectstore service.
1332#[derive(Serialize, Deserialize, Debug, Clone)]
1333#[serde(default)]
1334pub struct ObjectstoreServiceConfig {
1335    /// The base URL for the objectstore service.
1336    ///
1337    /// This defaults to [`None`], which means that the service will be disabled,
1338    /// unless a proper configuration is provided.
1339    pub objectstore_url: Option<String>,
1340
1341    /// Maximum concurrency of uploads.
1342    pub max_concurrent_requests: usize,
1343
1344    /// Maximum size of the service input queue when `max_concurrent_requests` is saturated.
1345    ///
1346    /// The service will loadshed if this threshold is reached.
1347    pub max_backlog: usize,
1348
1349    /// Maximum duration of an attachment upload in seconds. Uploads that take longer are discarded.
1350    ///
1351    /// NOTE: This timeout applies to attachments that are already in-memory. Streaming uploads
1352    /// might take longer and are restricted independently by [`Self::stream_timeout`].
1353    pub timeout: u64,
1354
1355    /// Maximum duration of an upload stream.
1356    ///
1357    /// Streams get a larger default timeout because their duration depends on the client
1358    /// as well as the server.
1359    pub stream_timeout: u64,
1360
1361    /// Time between upload attempts.
1362    pub retry_delay: f64,
1363
1364    /// Maximum number of attempts made to upload.
1365    pub max_attempts: NonZeroU16,
1366
1367    /// Configuration values for objectstore's auth scheme.
1368    pub auth: Option<ObjectstoreAuthConfig>,
1369}
1370
1371impl Default for ObjectstoreServiceConfig {
1372    fn default() -> Self {
1373        Self {
1374            objectstore_url: None,
1375            max_concurrent_requests: 10,
1376            max_backlog: 20,
1377            timeout: 60,
1378            stream_timeout: 5 * 60, // synced with `Upload::timeout`
1379            retry_delay: 1.0,
1380            max_attempts: NonZeroU16::new(5).unwrap(),
1381            auth: None,
1382        }
1383    }
1384}
1385
1386/// Determines how to emit outcomes.
1387/// For compatibility reasons, this can either be true, false or AsClientReports
1388#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1389
1390pub enum EmitOutcomes {
1391    /// Do not emit any outcomes.
1392    None,
1393    /// Emit outcomes as client reports.
1394    AsClientReports,
1395    /// Emit outcomes as outcomes.
1396    AsOutcomes,
1397}
1398
1399impl EmitOutcomes {
1400    /// Returns true of outcomes are emitted via http, kafka, or client reports.
1401    pub fn any(&self) -> bool {
1402        !matches!(self, EmitOutcomes::None)
1403    }
1404}
1405
1406impl Serialize for EmitOutcomes {
1407    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1408    where
1409        S: Serializer,
1410    {
1411        // For compatibility, serialize None and AsOutcomes as booleans.
1412        match self {
1413            Self::None => serializer.serialize_bool(false),
1414            Self::AsClientReports => serializer.serialize_str("as_client_reports"),
1415            Self::AsOutcomes => serializer.serialize_bool(true),
1416        }
1417    }
1418}
1419
1420struct EmitOutcomesVisitor;
1421
1422impl Visitor<'_> for EmitOutcomesVisitor {
1423    type Value = EmitOutcomes;
1424
1425    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1426        formatter.write_str("true, false, 'as_client_reports'")
1427    }
1428
1429    fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
1430    where
1431        E: serde::de::Error,
1432    {
1433        Ok(if v {
1434            EmitOutcomes::AsOutcomes
1435        } else {
1436            EmitOutcomes::None
1437        })
1438    }
1439
1440    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1441    where
1442        E: serde::de::Error,
1443    {
1444        match v {
1445            "as_client_reports" => Ok(EmitOutcomes::AsClientReports),
1446            _ => Err(E::invalid_value(Unexpected::Str(v), &self)),
1447        }
1448    }
1449}
1450
1451impl<'de> Deserialize<'de> for EmitOutcomes {
1452    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1453    where
1454        D: Deserializer<'de>,
1455    {
1456        deserializer.deserialize_any(EmitOutcomesVisitor)
1457    }
1458}
1459
1460/// Outcome generation specific configuration values.
1461#[derive(Serialize, Deserialize, Debug, Clone)]
1462#[serde(default)]
1463pub struct Outcomes {
1464    /// Controls whether outcomes will be emitted when processing is disabled.
1465    /// Processing relays always emit outcomes (for backwards compatibility).
1466    /// Can take the following values: false, "as_client_reports", true
1467    pub emit_outcomes: EmitOutcomes,
1468    /// Defines the source string registered in the outcomes originating from
1469    /// this Relay (typically something like the region or the layer).
1470    pub source: Option<String>,
1471}
1472
1473impl Default for Outcomes {
1474    fn default() -> Self {
1475        Outcomes {
1476            emit_outcomes: EmitOutcomes::AsClientReports,
1477            source: None,
1478        }
1479    }
1480}
1481
1482/// Minimal version of a config for dumping out.
1483#[derive(Serialize, Deserialize, Debug, Default)]
1484pub struct MinimalConfig {
1485    /// The relay part of the config.
1486    pub relay: Relay,
1487}
1488
1489impl MinimalConfig {
1490    /// Saves the config in the given config folder as config.yml
1491    pub fn save_in_folder<P: AsRef<Path>>(&self, p: P) -> anyhow::Result<()> {
1492        let path = p.as_ref();
1493        if fs::metadata(path).is_err() {
1494            fs::create_dir_all(path)
1495                .with_context(|| ConfigError::file(ConfigErrorKind::CouldNotOpenFile, path))?;
1496        }
1497        self.save(path)
1498    }
1499}
1500
1501impl ConfigObject for MinimalConfig {
1502    fn format() -> ConfigFormat {
1503        ConfigFormat::Yaml
1504    }
1505
1506    fn name() -> &'static str {
1507        "config"
1508    }
1509}
1510
1511/// Alternative serialization of RelayInfo for config file using snake case.
1512mod config_relay_info {
1513    use serde::ser::SerializeMap;
1514
1515    use super::*;
1516
1517    // Uses snake_case as opposed to camelCase.
1518    #[derive(Debug, Serialize, Deserialize, Clone)]
1519    struct RelayInfoConfig {
1520        public_key: PublicKey,
1521        #[serde(default)]
1522        internal: bool,
1523    }
1524
1525    impl From<RelayInfoConfig> for RelayInfo {
1526        fn from(v: RelayInfoConfig) -> Self {
1527            RelayInfo {
1528                public_key: v.public_key,
1529                internal: v.internal,
1530            }
1531        }
1532    }
1533
1534    impl From<RelayInfo> for RelayInfoConfig {
1535        fn from(v: RelayInfo) -> Self {
1536            RelayInfoConfig {
1537                public_key: v.public_key,
1538                internal: v.internal,
1539            }
1540        }
1541    }
1542
1543    pub(super) fn deserialize<'de, D>(des: D) -> Result<HashMap<RelayId, RelayInfo>, D::Error>
1544    where
1545        D: Deserializer<'de>,
1546    {
1547        let map = HashMap::<RelayId, RelayInfoConfig>::deserialize(des)?;
1548        Ok(map.into_iter().map(|(k, v)| (k, v.into())).collect())
1549    }
1550
1551    pub(super) fn serialize<S>(elm: &HashMap<RelayId, RelayInfo>, ser: S) -> Result<S::Ok, S::Error>
1552    where
1553        S: Serializer,
1554    {
1555        let mut map = ser.serialize_map(Some(elm.len()))?;
1556
1557        for (k, v) in elm {
1558            map.serialize_entry(k, &RelayInfoConfig::from(v.clone()))?;
1559        }
1560
1561        map.end()
1562    }
1563}
1564
1565/// Authentication options.
1566#[derive(Serialize, Deserialize, Debug, Clone)]
1567#[serde(default)]
1568pub struct AuthConfig {
1569    /// Controls responses from the readiness health check endpoint based on authentication.
1570    #[serde(skip_serializing_if = "is_default")]
1571    pub ready: ReadinessCondition,
1572
1573    /// Statically authenticated downstream relays.
1574    #[serde(with = "config_relay_info")]
1575    pub static_relays: HashMap<RelayId, RelayInfo>,
1576
1577    /// How old a signature can be before it is considered invalid, in seconds.
1578    ///
1579    /// Defaults to 5 minutes.
1580    pub signature_max_age: u64,
1581}
1582
1583impl Default for AuthConfig {
1584    fn default() -> Self {
1585        Self {
1586            ready: ReadinessCondition::default(),
1587            static_relays: HashMap::new(),
1588            signature_max_age: 300, // 5 minutes
1589        }
1590    }
1591}
1592
1593/// GeoIp database configuration options.
1594#[derive(Serialize, Deserialize, Debug, Default, Clone)]
1595pub struct GeoIpConfig {
1596    /// The path to GeoIP database.
1597    pub path: Option<PathBuf>,
1598}
1599
1600/// Settings to control Relay's health checks.
1601///
1602/// After breaching one of the configured thresholds, Relay will
1603/// return an `unhealthy` status from its health endpoint.
1604#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
1605#[serde(default)]
1606pub struct Health {
1607    /// Interval to refresh internal health checks.
1608    ///
1609    /// Shorter intervals will decrease the time it takes the health check endpoint to report
1610    /// issues, but can also increase sporadic unhealthy responses.
1611    ///
1612    /// Defaults to `3000`` (3 seconds).
1613    pub refresh_interval_ms: u64,
1614    /// Maximum memory watermark in bytes.
1615    ///
1616    /// By default, there is no absolute limit set and the watermark
1617    /// is only controlled by setting [`Self::max_memory_percent`].
1618    pub max_memory_bytes: Option<ByteSize>,
1619    /// Maximum memory watermark as a percentage of maximum system memory.
1620    ///
1621    /// Defaults to `0.95` (95%).
1622    pub max_memory_percent: f32,
1623    /// Health check probe timeout in milliseconds.
1624    ///
1625    /// Any probe exceeding the timeout will be considered failed.
1626    /// This limits the max execution time of Relay health checks.
1627    ///
1628    /// Defaults to 900 milliseconds.
1629    pub probe_timeout_ms: u64,
1630    /// The refresh frequency of memory stats which are used to poll memory
1631    /// usage of Relay.
1632    ///
1633    /// The implementation of memory stats guarantees that the refresh will happen at
1634    /// least every `x` ms since memory readings are lazy and are updated only if needed.
1635    pub memory_stat_refresh_frequency_ms: u64,
1636}
1637
1638impl Default for Health {
1639    fn default() -> Self {
1640        Self {
1641            refresh_interval_ms: 3000,
1642            max_memory_bytes: None,
1643            max_memory_percent: 0.95,
1644            probe_timeout_ms: 900,
1645            memory_stat_refresh_frequency_ms: 100,
1646        }
1647    }
1648}
1649
1650/// COGS configuration.
1651#[derive(Serialize, Deserialize, Debug, Clone)]
1652#[serde(default)]
1653pub struct Cogs {
1654    /// Maximium amount of COGS measurements allowed to backlog.
1655    ///
1656    /// Any additional COGS measurements recorded will be dropped.
1657    ///
1658    /// Defaults to `10_000`.
1659    pub max_queue_size: u64,
1660    /// Relay COGS resource id.
1661    ///
1662    /// All Relay related COGS measurements are emitted with this resource id.
1663    ///
1664    /// Defaults to `relay_service`.
1665    pub relay_resource_id: String,
1666}
1667
1668impl Default for Cogs {
1669    fn default() -> Self {
1670        Self {
1671            max_queue_size: 10_000,
1672            relay_resource_id: "relay_service".to_owned(),
1673        }
1674    }
1675}
1676
1677/// Configuration for the upload service.
1678#[derive(Debug, Clone, Serialize, Deserialize)]
1679#[serde(default)]
1680pub struct Upload {
1681    /// Maximum number of uploads that the service accepts.
1682    ///
1683    /// Additional uploads will be rejected.
1684    pub max_concurrent_requests: usize,
1685    /// Maximum time spent trying to upload, in seconds.
1686    pub timeout: u64,
1687    /// The maximum time between creating the upload and uploading the data / the attachment placeholder.
1688    ///
1689    /// In seconds.
1690    pub max_age: i64,
1691
1692    /// Credentials used for signing & verifying upload locations.
1693    ///
1694    /// If omitted, relay's default [`Credentials`] are used.
1695    pub credentials: Option<UploadCredentials>,
1696}
1697
1698impl Default for Upload {
1699    fn default() -> Self {
1700        Self {
1701            max_concurrent_requests: 100,
1702            timeout: 5 * 60,  // five minutes
1703            max_age: 60 * 60, // 1h
1704            credentials: None,
1705        }
1706    }
1707}
1708
1709/// Credentials used for signing & verifying upload locations.
1710#[derive(Clone, Serialize, Deserialize)]
1711pub struct UploadCredentials {
1712    /// Key used to sign upload locations.
1713    #[cfg(feature = "processing")]
1714    pub signing_key: SecretKey,
1715
1716    /// Key used to verify upload locations.
1717    pub verification_key: PublicKey,
1718}
1719
1720impl fmt::Debug for UploadCredentials {
1721    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1722        let Self {
1723            #[cfg(feature = "processing")]
1724                signing_key: _,
1725            verification_key,
1726        } = self;
1727        let mut b = f.debug_struct("UploadCredentials");
1728        #[cfg(feature = "processing")]
1729        b.field("signing_key", &"[redacted]");
1730        b.field("verification_key", verification_key).finish()
1731    }
1732}
1733
1734/// All configuration values that can be deserialized from `config.yml`.
1735#[derive(Serialize, Deserialize, Debug, Default, Clone)]
1736#[serde(default)]
1737#[allow(missing_docs)]
1738pub struct ConfigValues {
1739    pub relay: Relay,
1740    pub http: Http,
1741    pub cache: Cache,
1742    pub spool: Spool,
1743    pub limits: Limits,
1744    pub logging: relay_log::LogConfig,
1745    pub routing: Routing,
1746    pub metrics: Metrics,
1747    pub sentry: relay_log::SentryConfig,
1748    pub processing: Processing,
1749    pub outcomes: Outcomes,
1750    pub aggregator: AggregatorServiceConfig,
1751    pub secondary_aggregators: Vec<ScopedAggregatorConfig>,
1752    pub auth: AuthConfig,
1753    pub geoip: GeoIpConfig,
1754    pub normalization: Normalization,
1755    pub health: Health,
1756    pub cogs: Cogs,
1757    pub upload: Upload,
1758}
1759
1760impl ConfigObject for ConfigValues {
1761    fn format() -> ConfigFormat {
1762        ConfigFormat::Yaml
1763    }
1764
1765    fn name() -> &'static str {
1766        "config"
1767    }
1768}
1769
1770#[derive(Default, Clone)]
1771struct ConfigInner {
1772    /// Relay's config values.
1773    values: ConfigValues,
1774    /// Configured Relay credentials.
1775    ///
1776    /// Credentials may be missing for proxy mode.
1777    credentials: Option<Credentials>,
1778}
1779
1780impl ConfigInner {
1781    fn apply_overrides(&mut self, overrides: &OverridableConfig) -> anyhow::Result<()> {
1782        if let Some(log_level) = &overrides.log_level {
1783            self.values.logging.level = log_level.parse()?;
1784        }
1785
1786        if let Some(log_format) = &overrides.log_format {
1787            self.values.logging.format = log_format.parse()?;
1788        }
1789
1790        let relay = &mut self.values.relay;
1791        if let Some(mode) = &overrides.mode {
1792            relay.mode = mode
1793                .parse::<RelayMode>()
1794                .with_context(|| ConfigError::field("mode"))?;
1795        }
1796        if let Some(deployment) = &overrides.instance {
1797            relay.instance = deployment
1798                .parse::<RelayInstance>()
1799                .with_context(|| ConfigError::field("deployment"))?;
1800        }
1801        if let Some(upstream) = &overrides.upstream {
1802            relay.upstream = upstream
1803                .parse::<UpstreamDescriptor>()
1804                .with_context(|| ConfigError::field("upstream"))?;
1805        } else if let Some(upstream_dsn) = &overrides.upstream_dsn {
1806            relay.upstream = upstream_dsn
1807                .parse::<Dsn>()
1808                .map(|dsn| UpstreamDescriptor::from_dsn(&dsn))
1809                .with_context(|| ConfigError::field("upstream_dsn"))?;
1810        }
1811        if let Some(host) = &overrides.host {
1812            relay.host = host
1813                .parse::<IpAddr>()
1814                .with_context(|| ConfigError::field("host"))?;
1815        }
1816        if let Some(port) = &overrides.port {
1817            relay.port = port
1818                .as_str()
1819                .parse()
1820                .with_context(|| ConfigError::field("port"))?;
1821        }
1822
1823        let processing = &mut self.values.processing;
1824        if let Some(enabled) = &overrides.processing {
1825            match enabled.to_lowercase().as_str() {
1826                "true" | "1" => processing.enabled = true,
1827                "false" | "0" | "" => processing.enabled = false,
1828                _ => return Err(ConfigError::field("processing").into()),
1829            }
1830        }
1831        if let Some(redis) = overrides.redis_url.clone() {
1832            processing.redis = Some(RedisConfigs::Unified(RedisConfig::single(redis)))
1833        }
1834        if let Some(kafka_url) = overrides.kafka_url.clone() {
1835            let existing = processing
1836                .kafka_config
1837                .iter_mut()
1838                .find(|e| e.name == "bootstrap.servers");
1839
1840            if let Some(config_param) = existing {
1841                config_param.value = kafka_url;
1842            } else {
1843                self.values.processing.kafka_config.push(KafkaConfigParam {
1844                    name: "bootstrap.servers".to_owned(),
1845                    value: kafka_url,
1846                })
1847            }
1848        }
1849
1850        if overrides.outcome_source.is_some() {
1851            self.values.outcomes.source = overrides.outcome_source.clone();
1852        }
1853
1854        if let Some(server_name) = overrides.server_name.clone() {
1855            self.values.sentry.server_name = Some(server_name.into());
1856        }
1857
1858        let id = if let Some(id) = &overrides.id {
1859            let id = Uuid::parse_str(id).with_context(|| ConfigError::field("id"))?;
1860            Some(id)
1861        } else {
1862            None
1863        };
1864        let public_key = if let Some(public_key) = &overrides.public_key {
1865            let public_key = public_key
1866                .parse::<PublicKey>()
1867                .with_context(|| ConfigError::field("public_key"))?;
1868            Some(public_key)
1869        } else {
1870            None
1871        };
1872
1873        let secret_key = if let Some(secret_key) = &overrides.secret_key {
1874            let secret_key = secret_key
1875                .parse::<SecretKey>()
1876                .with_context(|| ConfigError::field("secret_key"))?;
1877            Some(secret_key)
1878        } else {
1879            None
1880        };
1881
1882        if let Some(credentials) = &mut self.credentials {
1883            //we have existing credentials we may override some entries
1884            if let Some(id) = id {
1885                credentials.id = id;
1886            }
1887            if let Some(public_key) = public_key {
1888                credentials.public_key = public_key;
1889            }
1890            if let Some(secret_key) = secret_key {
1891                credentials.secret_key = secret_key
1892            }
1893        } else {
1894            //no existing credentials we may only create the full credentials
1895            match (id, public_key, secret_key) {
1896                (Some(id), Some(public_key), Some(secret_key)) => {
1897                    self.credentials = Some(Credentials {
1898                        secret_key,
1899                        public_key,
1900                        id,
1901                    })
1902                }
1903                (None, None, None) => {
1904                    // nothing provided, we'll just leave the credentials None, maybe we
1905                    // don't need them in the current command or we'll override them later
1906                }
1907                _ => {
1908                    return Err(ConfigError::field("incomplete credentials").into());
1909                }
1910            }
1911        }
1912
1913        Ok(())
1914    }
1915
1916    /// Merges reloadable parts of the config from `other` into `self`.
1917    ///
1918    /// Returns `true` if any parts of the config were updated.
1919    fn reload_with(&mut self, other: &Self) -> bool {
1920        let mut changed = false;
1921
1922        if self.values.health != other.values.health {
1923            relay_log::debug!("updating health");
1924            self.values.health = other.values.health.clone();
1925            changed = true;
1926        }
1927
1928        // Broker settings only. Producers hold their topic name and shard list from startup,
1929        // so `topics` changes cannot be applied here at all, including moving a topic to
1930        // another cluster via its `config` key. Those need a restart.
1931        //
1932        // Merging `topics` anyway would also break later pushes: `kafka_config_blob` reads it
1933        // live, so a renamed topic would be keyed by its new name while the producer still
1934        // selects the old one.
1935        //
1936        // Running Kafka clients pick this up via `ConfigReloadService`.
1937        if self.values.processing.kafka_config != other.values.processing.kafka_config
1938            || self.values.processing.secondary_kafka_configs
1939                != other.values.processing.secondary_kafka_configs
1940        {
1941            relay_log::debug!("updating kafka config");
1942            self.values.processing.kafka_config = other.values.processing.kafka_config.clone();
1943            self.values.processing.secondary_kafka_configs =
1944                other.values.processing.secondary_kafka_configs.clone();
1945            changed = true;
1946        }
1947
1948        if self.values.spool.envelopes.max_unspool_envelopes_per_second
1949            != other
1950                .values
1951                .spool
1952                .envelopes
1953                .max_unspool_envelopes_per_second
1954        {
1955            relay_log::debug!("updating spool.envelopes.max_unspool_envelopes_per_second");
1956            self.values.spool.envelopes.max_unspool_envelopes_per_second = other
1957                .values
1958                .spool
1959                .envelopes
1960                .max_unspool_envelopes_per_second;
1961            changed = true;
1962        }
1963
1964        changed
1965    }
1966}
1967
1968/// Relay's Configuration.
1969pub struct Config {
1970    /// A mutex to serialize all write accesses to `inner`.
1971    ///
1972    /// Accessing the arc swap is done with compare and swap, but we still want serialized
1973    /// access and operations to guarantee consistency when dealing with e.g. the filesystem.
1974    ///
1975    /// The mutex must be acquired before changing `inner`. Methods taking `&mut` can omit
1976    /// this, as the `&mut` requirement already satisfies that there is no concurrent access
1977    /// possible.
1978    inner_access: Mutex<()>,
1979    /// The actual config.
1980    inner: ArcSwap<ConfigInner>,
1981    /// A list of overrides applied to the config, in order.
1982    ///
1983    /// When re-loading the configuration these overrides need to be applied again
1984    /// in the same order as they were applied originally.
1985    overrides: Vec<OverridableConfig>,
1986    /// Path from which the config is loaded.
1987    ///
1988    /// This is Relay's configuration directory.
1989    path: PathBuf,
1990}
1991
1992impl fmt::Debug for Config {
1993    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1994        let inner = self.inner.load();
1995
1996        f.debug_struct("Config")
1997            .field("path", &self.path)
1998            // Only print specific parts of `inner` to not leak the credentials.
1999            .field("values", &inner.values)
2000            .finish()
2001    }
2002}
2003
2004impl Config {
2005    /// Loads a config from a given config folder.
2006    pub fn from_path<P: AsRef<Path>>(path: P) -> anyhow::Result<Config> {
2007        let path = env::current_dir()
2008            .map(|x| x.join(path.as_ref()))
2009            .unwrap_or_else(|_| path.as_ref().to_path_buf());
2010
2011        let inner = ConfigInner {
2012            values: ConfigValues::load(&path)?,
2013            credentials: match Credentials::path(&path).exists() {
2014                true => Some(Credentials::load(&path)?),
2015                false => None,
2016            },
2017        };
2018
2019        let config = Config {
2020            inner_access: Mutex::new(()),
2021            inner: ArcSwap::from_pointee(inner),
2022            overrides: Vec::new(),
2023            path: path.clone(),
2024        };
2025
2026        if cfg!(not(feature = "processing")) && config.current().processing_enabled() {
2027            return Err(ConfigError::file(ConfigErrorKind::ProcessingNotAvailable, &path).into());
2028        }
2029
2030        Ok(config)
2031    }
2032
2033    /// Creates a config from a JSON value.
2034    ///
2035    /// This is mostly useful for tests.
2036    pub fn from_json_value(value: serde_json::Value) -> anyhow::Result<Config> {
2037        Ok(Config {
2038            inner_access: Mutex::new(()),
2039            inner: ArcSwap::from_pointee(ConfigInner {
2040                values: serde_json::from_value(value)
2041                    .with_context(|| ConfigError::new(ConfigErrorKind::BadJson))?,
2042                credentials: None,
2043            }),
2044            overrides: Vec::new(),
2045            path: PathBuf::new(),
2046        })
2047    }
2048
2049    /// Override configuration with values coming from other sources (e.g. env variables or
2050    /// command line parameters).
2051    ///
2052    /// If applying the overrides fails, the config may be left in an inconsistent state.
2053    pub fn apply_override(&mut self, overrides: OverridableConfig) -> anyhow::Result<&mut Self> {
2054        // We could introduce a config builder which operates on mutable configs, which would eliminate
2055        // the need for this `try_rcu` dance here.
2056        crate::utils::try_rcu(&self.inner, |inner| {
2057            let mut new = ConfigInner::clone(inner);
2058            new.apply_overrides(&overrides)?;
2059            Ok::<_, anyhow::Error>(Arc::new(new))
2060        })?;
2061
2062        // Overrides successfully applied.
2063        self.overrides.push(overrides);
2064
2065        Ok(self)
2066    }
2067
2068    /// Checks if the config is already initialized.
2069    pub fn config_exists<P: AsRef<Path>>(path: P) -> bool {
2070        fs::metadata(ConfigValues::path(path.as_ref())).is_ok()
2071    }
2072
2073    /// Returns the filename of the config file.
2074    pub fn path(&self) -> &Path {
2075        &self.path
2076    }
2077
2078    /// Dumps out a YAML string of the values.
2079    pub fn to_yaml_string(&self) -> anyhow::Result<String> {
2080        serde_yaml::to_string(&self.inner.load().values)
2081            .with_context(|| ConfigError::new(ConfigErrorKind::CouldNotWriteFile))
2082    }
2083
2084    /// Set new credentials.
2085    ///
2086    /// This also writes the credentials back to the file, if this config was loaded from the file-system.
2087    pub fn replace_credentials(
2088        &mut self,
2089        credentials: Option<Credentials>,
2090    ) -> anyhow::Result<bool> {
2091        if self.inner.load().credentials == credentials {
2092            return Ok(false);
2093        }
2094
2095        if !self.path.is_empty() {
2096            match &credentials {
2097                Some(creds) => {
2098                    creds.save(&self.path)?;
2099                }
2100                None => {
2101                    let path = Credentials::path(&self.path);
2102                    if fs::metadata(&path).is_ok() {
2103                        fs::remove_file(&path).with_context(|| {
2104                            ConfigError::file(ConfigErrorKind::CouldNotWriteFile, &path)
2105                        })?;
2106                    }
2107                }
2108            }
2109        }
2110
2111        // Note: there is never anyone racing on the `ArcSwap` as long as `Self` borrowed mutably.
2112        //
2113        // We can improve this if we split out mutable operations into a separate struct and only
2114        // once `frozen()` we change to an `ArcSwap` internally.
2115        self.inner.rcu(|inner| {
2116            let mut inner = ConfigInner::clone(inner);
2117            inner.credentials = credentials.clone();
2118            Arc::new(inner)
2119        });
2120
2121        Ok(true)
2122    }
2123
2124    /// Reloads the configuration from disk.
2125    ///
2126    /// Returns `true` if the configuration changed.
2127    ///
2128    /// In order for a config to be reloadable it must've been loaded from a path. The original
2129    /// config will be re-read and reloadable parts of the config will be replaced with their updated
2130    /// values.
2131    ///
2132    /// If the reload fails for any reason, the current config is untouched.
2133    pub fn reload(&self) -> anyhow::Result<bool> {
2134        if self.path.is_empty() {
2135            return Ok(false);
2136        }
2137
2138        let _access = self
2139            .inner_access
2140            .lock()
2141            .unwrap_or_else(PoisonError::into_inner);
2142
2143        let mut new_config = Self::from_path(&self.path)?;
2144        for overrides in &self.overrides {
2145            new_config.apply_override(overrides.clone())?;
2146        }
2147        let new_config = new_config.current();
2148
2149        let mut changed = false;
2150
2151        // Since we do have the `_access` lock, this will always succeed on the first try.
2152        self.inner.rcu(|inner| {
2153            let mut new_inner = ConfigInner::clone(inner);
2154            changed = new_inner.reload_with(&new_config.inner);
2155            match changed {
2156                true => Arc::new(new_inner),
2157                false => Arc::clone(inner),
2158            }
2159        });
2160
2161        Ok(changed)
2162    }
2163
2164    /// Acquires a current [`snapshot`](ConfigSnapshot) of the config.
2165    ///
2166    /// A snapshot is the way to actually consume values from the config. A snapshot should ideally be acquired
2167    /// once per unit of work.
2168    pub fn current(&self) -> ConfigSnapshot {
2169        let inner = self.inner.load();
2170        ConfigSnapshot { inner }
2171    }
2172}
2173
2174impl Default for Config {
2175    fn default() -> Self {
2176        Self {
2177            inner_access: Mutex::new(()),
2178            inner: ArcSwap::from_pointee(Default::default()),
2179            overrides: Vec::new(),
2180            path: PathBuf::new(),
2181        }
2182    }
2183}
2184
2185/// A config snapshot is a point in time snapshot of the [`Config`].
2186///
2187/// The [`Config`] may change over time, to guarantee a consistent view of the config
2188/// a snapshot must be acquired first.
2189///
2190/// The snapshot should not be stored in a long lasting datastructure. As a rule of thumb it should
2191/// only exist on the stack.
2192pub struct ConfigSnapshot {
2193    inner: arc_swap::Guard<Arc<ConfigInner>>,
2194}
2195
2196impl ConfigSnapshot {
2197    /// Returns `true` if the config is ready to use.
2198    pub fn has_credentials(&self) -> bool {
2199        self.inner.credentials.is_some()
2200    }
2201
2202    /// Return the current credentials.
2203    pub fn credentials(&self) -> Option<&Credentials> {
2204        self.inner.credentials.as_ref()
2205    }
2206
2207    /// Returns the secret key if set.
2208    pub fn secret_key(&self) -> Option<&SecretKey> {
2209        self.inner.credentials.as_ref().map(|x| &x.secret_key)
2210    }
2211
2212    /// Returns the public key if set.
2213    pub fn public_key(&self) -> Option<&PublicKey> {
2214        self.inner.credentials.as_ref().map(|x| &x.public_key)
2215    }
2216
2217    /// Returns the relay ID.
2218    pub fn relay_id(&self) -> Option<&RelayId> {
2219        self.inner.credentials.as_ref().map(|x| &x.id)
2220    }
2221
2222    /// Returns the relay mode.
2223    pub fn relay_mode(&self) -> RelayMode {
2224        self.inner.values.relay.mode
2225    }
2226
2227    /// Returns the instance type of relay.
2228    pub fn relay_instance(&self) -> RelayInstance {
2229        self.inner.values.relay.instance
2230    }
2231
2232    /// Returns the upstream target as descriptor.
2233    pub fn upstream(&self) -> &UpstreamDescriptor {
2234        &self.inner.values.relay.upstream
2235    }
2236
2237    /// Returns the advertised upstream for downstream instances as descriptor.
2238    pub fn advertised_upstream(&self) -> Option<&UpstreamDescriptor> {
2239        self.inner.values.relay.advertised_upstream.as_ref()
2240    }
2241
2242    /// Returns the custom HTTP "Host" header.
2243    pub fn http_host_header(&self) -> Option<&str> {
2244        self.inner.values.http.host_header.as_deref()
2245    }
2246
2247    /// Returns the listen address.
2248    pub fn listen_addr(&self) -> SocketAddr {
2249        (self.inner.values.relay.host, self.inner.values.relay.port).into()
2250    }
2251
2252    /// Returns the listen address for internal APIs.
2253    ///
2254    /// Internal APIs are APIs which do not need to be publicly exposed,
2255    /// like health checks.
2256    ///
2257    /// Returns `None` when there is no explicit address configured for internal APIs,
2258    /// and they should instead be exposed on the main [`Self::listen_addr`].
2259    pub fn listen_addr_internal(&self) -> Option<SocketAddr> {
2260        match (
2261            self.inner.values.relay.internal_host,
2262            self.inner.values.relay.internal_port,
2263        ) {
2264            (Some(host), None) => Some((host, self.inner.values.relay.port).into()),
2265            (None, Some(port)) => Some((self.inner.values.relay.host, port).into()),
2266            (Some(host), Some(port)) => Some((host, port).into()),
2267            (None, None) => None,
2268        }
2269    }
2270
2271    /// Returns `true` when project IDs should be overriden rather than validated.
2272    ///
2273    /// Defaults to `false`, which requires project ID validation.
2274    pub fn override_project_ids(&self) -> bool {
2275        self.inner.values.relay.override_project_ids
2276    }
2277
2278    /// Returns the interval to check for configuration changes.
2279    ///
2280    /// `None` if the config should never be reloaded.
2281    pub fn config_reload_interval(&self) -> Option<Duration> {
2282        let interval = self.inner.values.relay.config_reload_interval?;
2283        Some(match interval {
2284            // Useful for tests to be able to configure this to a very small value,
2285            // but we also don't want it to be actually 0.
2286            0 => Duration::from_millis(50),
2287            secs => Duration::from_secs(secs),
2288        })
2289    }
2290
2291    /// Returns `true` if Relay requires authentication for readiness.
2292    ///
2293    /// See [`ReadinessCondition`] for more information.
2294    pub fn requires_auth(&self) -> bool {
2295        match self.inner.values.auth.ready {
2296            ReadinessCondition::Authenticated => self.relay_mode() == RelayMode::Managed,
2297            ReadinessCondition::Always => false,
2298        }
2299    }
2300
2301    /// Returns the interval at which Realy should try to re-authenticate with the upstream.
2302    ///
2303    /// Always disabled in processing mode.
2304    pub fn http_auth_interval(&self) -> Option<Duration> {
2305        if self.processing_enabled() {
2306            return None;
2307        }
2308
2309        match self.inner.values.http.auth_interval {
2310            None | Some(0) => None,
2311            Some(secs) => Some(Duration::from_secs(secs)),
2312        }
2313    }
2314
2315    /// The maximum time of experiencing uninterrupted network failures until Relay considers that
2316    /// it has encountered a network outage.
2317    pub fn http_outage_grace_period(&self) -> Duration {
2318        Duration::from_secs(self.inner.values.http.outage_grace_period)
2319    }
2320
2321    /// Time Relay waits before retrying an upstream request.
2322    ///
2323    /// Before going into a network outage, Relay may fail to make upstream
2324    /// requests. This is the time Relay waits before retrying the same request.
2325    pub fn http_retry_delay(&self) -> Duration {
2326        Duration::from_secs(self.inner.values.http.retry_delay)
2327    }
2328
2329    /// Time of continued project request failures before Relay emits an error.
2330    pub fn http_project_failure_interval(&self) -> Duration {
2331        Duration::from_secs(self.inner.values.http.project_failure_interval)
2332    }
2333
2334    /// Content encoding of upstream requests.
2335    pub fn http_encoding(&self) -> HttpEncoding {
2336        self.inner.values.http.encoding
2337    }
2338
2339    /// Returns whether metrics should be sent globally through a shared endpoint.
2340    pub fn http_global_metrics(&self) -> bool {
2341        self.inner.values.http.global_metrics
2342    }
2343
2344    /// Returns `true` if Relay supports forwarding unknown API requests.
2345    ///
2346    /// Relay instances with processing enabled are expected to support the latest API and do never
2347    /// support forwarding requests to Sentry.
2348    pub fn http_forward(&self) -> bool {
2349        self.inner.values.http.forward && !self.processing_enabled()
2350    }
2351
2352    /// Returns whether this Relay should emit outcomes.
2353    ///
2354    /// This is `true` either if `outcomes.emit_outcomes` is explicitly enabled, or if this Relay is
2355    /// in processing mode.
2356    pub fn emit_outcomes(&self) -> EmitOutcomes {
2357        if self.processing_enabled() {
2358            return EmitOutcomes::AsOutcomes;
2359        }
2360        self.inner.values.outcomes.emit_outcomes
2361    }
2362
2363    /// The originating source of the outcome
2364    pub fn outcome_source(&self) -> Option<&str> {
2365        self.inner.values.outcomes.source.as_deref()
2366    }
2367
2368    /// Returns logging configuration.
2369    pub fn logging(&self) -> &relay_log::LogConfig {
2370        &self.inner.values.logging
2371    }
2372
2373    /// Returns logging configuration.
2374    pub fn sentry(&self) -> &relay_log::SentryConfig {
2375        &self.inner.values.sentry
2376    }
2377
2378    /// Returns the addresses for statsd metrics.
2379    pub fn statsd_addr(&self) -> Option<&str> {
2380        self.inner.values.metrics.statsd.as_deref()
2381    }
2382
2383    /// Returns the addresses for statsd metrics.
2384    pub fn statsd_buffer_size(&self) -> Option<usize> {
2385        self.inner.values.metrics.statsd_buffer_size
2386    }
2387
2388    /// Return the prefix for statsd metrics.
2389    pub fn metrics_prefix(&self) -> &str {
2390        &self.inner.values.metrics.prefix
2391    }
2392
2393    /// Returns the default tags for statsd metrics.
2394    pub fn metrics_default_tags(&self) -> &BTreeMap<String, String> {
2395        &self.inner.values.metrics.default_tags
2396    }
2397
2398    /// Returns the name of the hostname tag that should be attached to each outgoing metric.
2399    pub fn metrics_hostname_tag(&self) -> Option<&str> {
2400        self.inner.values.metrics.hostname_tag.as_deref()
2401    }
2402
2403    /// Returns the interval for periodic metrics emitted from Relay.
2404    ///
2405    /// `None` if periodic metrics are disabled.
2406    pub fn metrics_periodic_interval(&self) -> Option<Duration> {
2407        match self.inner.values.metrics.periodic_secs {
2408            0 => None,
2409            secs => Some(Duration::from_secs(secs)),
2410        }
2411    }
2412
2413    /// Returns the default timeout for all upstream HTTP requests.
2414    pub fn http_timeout(&self) -> Duration {
2415        Duration::from_secs(self.inner.values.http.timeout.into())
2416    }
2417
2418    /// Returns the connection timeout for all upstream HTTP requests.
2419    pub fn http_connection_timeout(&self) -> Duration {
2420        Duration::from_secs(self.inner.values.http.connection_timeout.into())
2421    }
2422
2423    /// Returns the failed upstream request retry interval.
2424    pub fn http_max_retry_interval(&self) -> Duration {
2425        Duration::from_secs(self.inner.values.http.max_retry_interval.into())
2426    }
2427
2428    /// Returns `true` if relay should use an in-process cache for DNS lookups.
2429    pub fn http_dns_cache(&self) -> bool {
2430        self.inner.values.http.dns_cache
2431    }
2432
2433    /// Returns the expiry timeout for cached projects.
2434    pub fn project_cache_expiry(&self) -> Duration {
2435        Duration::from_secs(self.inner.values.cache.project_expiry.into())
2436    }
2437
2438    /// Returns `true` if the full project state should be requested from upstream.
2439    pub fn request_full_project_config(&self) -> bool {
2440        self.inner.values.cache.project_request_full_config
2441    }
2442
2443    /// Returns the expiry timeout for cached relay infos (public keys).
2444    pub fn relay_cache_expiry(&self) -> Duration {
2445        Duration::from_secs(self.inner.values.cache.relay_expiry.into())
2446    }
2447
2448    /// Returns the expiry timeout for cached misses before trying to refetch.
2449    pub fn cache_miss_expiry(&self) -> Duration {
2450        Duration::from_secs(self.inner.values.cache.miss_expiry.into())
2451    }
2452
2453    /// Returns the grace period for project caches.
2454    pub fn project_grace_period(&self) -> Duration {
2455        Duration::from_secs(self.inner.values.cache.project_grace_period.into())
2456    }
2457
2458    /// Returns the refresh interval for a project.
2459    ///
2460    /// Validates the refresh time to be between the grace period and expiry.
2461    pub fn project_refresh_interval(&self) -> Option<Duration> {
2462        self.inner
2463            .values
2464            .cache
2465            .project_refresh_interval
2466            .map(Into::into)
2467            .map(Duration::from_secs)
2468    }
2469
2470    /// Returns the duration in which batchable project config queries are
2471    /// collected before sending them in a single request.
2472    pub fn query_batch_interval(&self) -> Duration {
2473        Duration::from_millis(self.inner.values.cache.batch_interval.into())
2474    }
2475
2476    /// Returns the duration in which downstream relays are requested from upstream.
2477    pub fn downstream_relays_batch_interval(&self) -> Duration {
2478        Duration::from_millis(
2479            self.inner
2480                .values
2481                .cache
2482                .downstream_relays_batch_interval
2483                .into(),
2484        )
2485    }
2486
2487    /// Returns the interval in seconds in which local project configurations should be reloaded.
2488    pub fn local_cache_interval(&self) -> Duration {
2489        Duration::from_secs(self.inner.values.cache.file_interval.into())
2490    }
2491
2492    /// Returns the interval in seconds in which fresh global configs should be
2493    /// fetched from  upstream.
2494    pub fn global_config_fetch_interval(&self) -> Duration {
2495        Duration::from_secs(self.inner.values.cache.global_config_fetch_interval.into())
2496    }
2497
2498    /// Returns the path of the buffer file if the `cache.persistent_envelope_buffer.path` is configured.
2499    ///
2500    /// In case a partition with id > 0 is supplied, the filename of the envelopes path will be
2501    /// suffixed with `.{partition_id}`.
2502    pub fn spool_envelopes_path(&self, partition_id: u8) -> Option<PathBuf> {
2503        let mut path = self
2504            .inner
2505            .values
2506            .spool
2507            .envelopes
2508            .path
2509            .as_ref()
2510            .map(|path| path.to_owned())?;
2511
2512        if partition_id == 0 {
2513            return Some(path);
2514        }
2515
2516        let file_name = path.file_name().and_then(|f| f.to_str())?;
2517        let new_file_name = format!("{file_name}.{partition_id}");
2518        path.set_file_name(new_file_name);
2519
2520        Some(path)
2521    }
2522
2523    /// The maximum size of the buffer, in bytes.
2524    pub fn spool_envelopes_max_disk_size(&self) -> usize {
2525        self.inner.values.spool.envelopes.max_disk_size.as_bytes()
2526    }
2527
2528    /// Number of encoded envelope bytes that need to be accumulated before
2529    /// flushing one batch to disk.
2530    pub fn spool_envelopes_batch_size_bytes(&self) -> usize {
2531        self.inner
2532            .values
2533            .spool
2534            .envelopes
2535            .batch_size_bytes
2536            .as_bytes()
2537    }
2538
2539    /// Time after which a batch of envelopes is flushed to disk, regardless of its size.
2540    pub fn spool_envelopes_flush_timeout(&self) -> Option<Duration> {
2541        self.inner
2542            .values
2543            .spool
2544            .envelopes
2545            .flush_timeout_secs
2546            .map(Duration::from_secs)
2547    }
2548
2549    /// Maximum number of envelopes unspooled from disk per second.
2550    pub fn spool_max_unspool_envelopes_per_second(&self) -> Option<NonZeroU32> {
2551        self.inner
2552            .values
2553            .spool
2554            .envelopes
2555            .max_unspool_envelopes_per_second
2556    }
2557
2558    /// Returns the time after which we drop envelopes as a [`Duration`] object.
2559    pub fn spool_envelopes_max_age(&self) -> Duration {
2560        Duration::from_secs(self.inner.values.spool.envelopes.max_envelope_delay_secs)
2561    }
2562
2563    /// Returns the refresh frequency for disk usage monitoring as a [`Duration`] object.
2564    pub fn spool_disk_usage_refresh_frequency_ms(&self) -> Duration {
2565        Duration::from_millis(
2566            self.inner
2567                .values
2568                .spool
2569                .envelopes
2570                .disk_usage_refresh_frequency_ms,
2571        )
2572    }
2573
2574    /// Returns the relative memory usage up to which the disk buffer will unspool envelopes.
2575    pub fn spool_max_backpressure_memory_percent(&self) -> f32 {
2576        self.inner
2577            .values
2578            .spool
2579            .envelopes
2580            .max_backpressure_memory_percent
2581    }
2582
2583    /// Returns the number of partitions for the buffer.
2584    pub fn spool_partitions(&self) -> NonZeroU8 {
2585        self.inner.values.spool.envelopes.partitions
2586    }
2587
2588    /// Returns the strategy used to assign envelopes to buffer partitions.
2589    pub fn spool_partitioning(&self) -> EnvelopeSpoolPartitioning {
2590        self.inner.values.spool.envelopes.partitioning
2591    }
2592
2593    /// Returns `true` if the data is stored on ephemeral disks.
2594    pub fn spool_ephemeral(&self) -> bool {
2595        self.inner.values.spool.envelopes.ephemeral
2596    }
2597
2598    /// Returns the maximum size of an event payload in bytes.
2599    pub fn max_event_size(&self) -> usize {
2600        self.inner.values.limits.max_event_size.as_bytes()
2601    }
2602
2603    /// Returns the maximum size of each attachment.
2604    pub fn max_attachment_size(&self) -> usize {
2605        self.inner.values.limits.max_attachment_size.as_bytes()
2606    }
2607
2608    /// The maximum amount of attachments in a single envelope.
2609    pub fn max_attachment_count(&self) -> usize {
2610        self.inner.values.limits.max_attachment_count
2611    }
2612
2613    /// Returns the maximum combined size of attachments or payloads containing attachments
2614    /// (minidump, unreal, standalone attachments) in bytes.
2615    pub fn max_attachments_size(&self) -> usize {
2616        self.inner.values.limits.max_attachments_size.as_bytes()
2617    }
2618
2619    /// Returns the maximum size of a TUS upload request body.
2620    pub fn max_upload_size(&self) -> usize {
2621        self.inner.values.limits.max_upload_size.as_bytes()
2622    }
2623
2624    /// Returns the maximum number of client reports per envelope.
2625    pub fn max_client_reports_count(&self) -> usize {
2626        self.inner.values.limits.max_client_reports_count
2627    }
2628
2629    /// Returns the maximum combined size of client reports in bytes.
2630    pub fn max_client_reports_size(&self) -> usize {
2631        self.inner.values.limits.max_client_reports_size.as_bytes()
2632    }
2633
2634    /// Returns the maximum payload size of a monitor check-in in bytes.
2635    pub fn max_check_in_size(&self) -> usize {
2636        self.inner.values.limits.max_check_in_size.as_bytes()
2637    }
2638
2639    /// Returns the maximum payload size of a log in bytes.
2640    pub fn max_log_size(&self) -> usize {
2641        self.inner.values.limits.max_log_size.as_bytes()
2642    }
2643
2644    /// Returns the maximum number of operations to allow for a log expansion.
2645    pub fn max_expanded_log_operations(&self) -> usize {
2646        self.inner.values.limits.max_expanded_log_operations
2647    }
2648
2649    /// Returns the maximum number of operations to allow for a span expansion.
2650    pub fn max_expanded_span_operations(&self) -> usize {
2651        self.inner.values.limits.max_expanded_span_operations
2652    }
2653
2654    /// Returns the maximum number of operations to allow for a span expansion.
2655    pub fn max_expanded_trace_metric_operations(&self) -> usize {
2656        self.inner
2657            .values
2658            .limits
2659            .max_expanded_trace_metric_operations
2660    }
2661
2662    /// Returns the maximum number of bytes than can be generated from a span expansion.
2663    pub fn max_expanded_span_bytes(&self) -> ByteSize {
2664        self.inner.values.limits.max_expanded_span_bytes
2665    }
2666
2667    /// Returns the maximum number of bytes that can be generated from a log expansion.
2668    pub fn max_expanded_logs_size(&self) -> ByteSize {
2669        self.inner.values.limits.max_expanded_logs_size
2670    }
2671
2672    /// Returns the maximum payload size of a span in bytes.
2673    pub fn max_span_size(&self) -> usize {
2674        self.inner.values.limits.max_span_size.as_bytes()
2675    }
2676
2677    /// Returns the maximum amount of standalone transaction spans per envelope.
2678    pub fn max_standalone_span_count(&self) -> usize {
2679        self.inner.values.limits.max_standalone_span_count
2680    }
2681
2682    /// Returns the maximum payload size of an item container in bytes.
2683    pub fn max_container_size(&self) -> usize {
2684        self.inner.values.limits.max_container_size.as_bytes()
2685    }
2686
2687    /// Returns the maximum size of an envelope payload in bytes.
2688    ///
2689    /// Individual item size limits still apply.
2690    pub fn max_envelope_size(&self) -> usize {
2691        self.inner.values.limits.max_envelope_size.as_bytes()
2692    }
2693
2694    /// Returns the maximum number of sessions per envelope.
2695    pub fn max_session_count(&self) -> usize {
2696        self.inner.values.limits.max_session_count
2697    }
2698
2699    /// Returns the maximum combined size for all sessions in an envelope in bytes.
2700    pub fn max_sessions_size(&self) -> usize {
2701        self.inner.values.limits.max_sessions_size.as_bytes()
2702    }
2703
2704    /// Returns the maximum payload size of metric buckets in bytes.
2705    pub fn max_metric_buckets_size(&self) -> usize {
2706        self.inner.values.limits.max_metric_buckets_size.as_bytes()
2707    }
2708
2709    /// Returns the maximum payload size for general API requests.
2710    pub fn max_api_payload_size(&self) -> usize {
2711        self.inner.values.limits.max_api_payload_size.as_bytes()
2712    }
2713
2714    /// Returns the maximum payload size for file uploads and chunks.
2715    pub fn max_api_file_upload_size(&self) -> usize {
2716        self.inner.values.limits.max_api_file_upload_size.as_bytes()
2717    }
2718
2719    /// Returns the maximum payload size for chunks
2720    pub fn max_api_chunk_upload_size(&self) -> usize {
2721        self.inner
2722            .values
2723            .limits
2724            .max_api_chunk_upload_size
2725            .as_bytes()
2726    }
2727
2728    /// Returns the maximum payload size for a profile
2729    pub fn max_profile_size(&self) -> usize {
2730        self.inner.values.limits.max_profile_size.as_bytes()
2731    }
2732
2733    /// Returns the maximum payload size for a trace metric.
2734    pub fn max_trace_metric_size(&self) -> usize {
2735        self.inner.values.limits.max_trace_metric_size.as_bytes()
2736    }
2737
2738    /// Returns the maximum payload size for a compressed replay.
2739    pub fn max_replay_compressed_size(&self) -> usize {
2740        self.inner
2741            .values
2742            .limits
2743            .max_replay_compressed_size
2744            .as_bytes()
2745    }
2746
2747    /// Returns the maximum payload size for an uncompressed replay.
2748    pub fn max_replay_uncompressed_size(&self) -> usize {
2749        self.inner
2750            .values
2751            .limits
2752            .max_replay_uncompressed_size
2753            .as_bytes()
2754    }
2755
2756    /// Returns the maximum message size for an uncompressed replay.
2757    ///
2758    /// This is greater than max_replay_compressed_size because
2759    /// it can include additional metadata about the replay in
2760    /// addition to the recording.
2761    pub fn max_replay_message_size(&self) -> usize {
2762        self.inner.values.limits.max_replay_message_size.as_bytes()
2763    }
2764
2765    /// Returns the maximum number of active requests
2766    pub fn max_concurrent_requests(&self) -> usize {
2767        self.inner.values.limits.max_concurrent_requests
2768    }
2769
2770    /// Returns the maximum number of active queries
2771    pub fn max_concurrent_queries(&self) -> usize {
2772        self.inner.values.limits.max_concurrent_queries
2773    }
2774
2775    /// Returns the maximum combined size of keys of invalid attributes.
2776    pub fn max_removed_attribute_key_size(&self) -> usize {
2777        self.inner
2778            .values
2779            .limits
2780            .max_removed_attribute_key_size
2781            .as_bytes()
2782    }
2783
2784    /// The maximum number of seconds a query is allowed to take across retries.
2785    pub fn query_timeout(&self) -> Duration {
2786        Duration::from_secs(self.inner.values.limits.query_timeout)
2787    }
2788
2789    /// Returns the server keep-alive timeout in seconds.
2790    ///
2791    /// By default keep alive is set to a 5 seconds.
2792    pub fn keepalive_timeout(&self) -> Duration {
2793        Duration::from_secs(self.inner.values.limits.keepalive_timeout)
2794    }
2795
2796    /// Returns how long Relay waits for a request on an HTTP/1.1 connection.
2797    ///
2798    /// This also limits how long idle connections stay open.
2799    pub fn header_read_timeout(&self) -> Duration {
2800        Duration::from_secs(self.inner.values.limits.header_read_timeout)
2801    }
2802
2803    /// Returns the server idle timeout in seconds.
2804    pub fn idle_timeout(&self) -> Option<Duration> {
2805        self.inner
2806            .values
2807            .limits
2808            .idle_timeout
2809            .map(Duration::from_secs)
2810    }
2811
2812    /// Returns the maximum connections.
2813    pub fn max_connections(&self) -> Option<usize> {
2814        self.inner.values.limits.max_connections
2815    }
2816
2817    /// TCP listen backlog to configure on Relay's listening socket.
2818    pub fn tcp_listen_backlog(&self) -> u32 {
2819        self.inner.values.limits.tcp_listen_backlog
2820    }
2821
2822    /// Returns the number of cores to use for thread pools.
2823    pub fn cpu_concurrency(&self) -> usize {
2824        self.inner.values.limits.max_thread_count
2825    }
2826
2827    /// Returns the number of tasks that can run concurrently in the worker pool.
2828    pub fn pool_concurrency(&self) -> usize {
2829        self.inner.values.limits.max_pool_concurrency
2830    }
2831
2832    /// Returns the maximum size of a project config query.
2833    pub fn query_batch_size(&self) -> usize {
2834        self.inner.values.cache.batch_size
2835    }
2836
2837    /// True if the Relay should do processing.
2838    pub fn processing_enabled(&self) -> bool {
2839        self.inner.values.processing.enabled
2840    }
2841
2842    /// Level of normalization for Relay to apply to incoming data.
2843    pub fn normalization_level(&self) -> NormalizationLevel {
2844        self.inner.values.normalization.level
2845    }
2846
2847    /// The path to the GeoIp database required for event processing.
2848    pub fn geoip_path(&self) -> Option<&Path> {
2849        self.inner.values.geoip.path.as_deref().or(self
2850            .inner
2851            .values
2852            .processing
2853            .geoip_path
2854            .as_deref())
2855    }
2856
2857    /// Maximum future timestamp of ingested data.
2858    ///
2859    /// Events past this timestamp will be adjusted to `now()`. Sessions will be dropped.
2860    pub fn max_secs_in_future(&self) -> i64 {
2861        self.inner.values.processing.max_secs_in_future.into()
2862    }
2863
2864    /// Maximum age of ingested sessions. Older sessions will be dropped.
2865    pub fn max_session_secs_in_past(&self) -> i64 {
2866        self.inner.values.processing.max_session_secs_in_past.into()
2867    }
2868
2869    /// Configuration name and list of Kafka configuration parameters for a given topic.
2870    pub fn kafka_configs(
2871        &self,
2872        topic: KafkaTopic,
2873    ) -> Result<KafkaTopicConfig<'_>, KafkaConfigError> {
2874        self.inner
2875            .values
2876            .processing
2877            .topics
2878            .get(topic)
2879            .kafka_configs(
2880                &self.inner.values.processing.kafka_config,
2881                &self.inner.values.processing.secondary_kafka_configs,
2882            )
2883    }
2884
2885    /// Whether to validate the topics against Kafka.
2886    pub fn kafka_validate_topics(&self) -> bool {
2887        self.inner.values.processing.kafka_validate_topics
2888    }
2889
2890    /// Upper bound on the random delay before a Kafka producer swaps its client.
2891    pub fn reloading_producer_jitter(&self) -> Duration {
2892        Duration::from_secs(self.inner.values.processing.reloading_producer_jitter_secs)
2893    }
2894
2895    /// Builds the Kafka config blob describing every configured topic.
2896    ///
2897    /// # This is a stand-in
2898    ///
2899    /// The blob is meant to be opaque to Relay: one is published per region covering every
2900    /// cluster and topic, and Relay passes the bytes to Arroyo without interpreting them. That
2901    /// delivery channel does not yet exist, so this builds a blob out of Relay's own
2902    /// `kafka_config`, `secondary_kafka_configs` and `topics` instead.
2903    pub fn kafka_config_blob(&self) -> Result<Vec<u8>, KafkaConfigError> {
2904        // Sorted throughout, so an unchanged config always serializes to the same bytes and the
2905        // caller can skip pushing by comparing them.
2906        let mut clusters = BTreeMap::new();
2907        let mut topics = BTreeMap::new();
2908
2909        // A topic without a `config` uses the default `kafka_config`. The blob has no notion of
2910        // a default, so that becomes a cluster under a name derived to not collide with any
2911        // `secondary_kafka_configs` entry the user may have written.
2912        let default_cluster = default_cluster_name(&self.inner.values.processing);
2913
2914        for topic in KafkaTopic::iter() {
2915            let topic_config = self.kafka_configs(*topic)?;
2916
2917            for params in topic_config.topics() {
2918                let cluster_name = params.config_name.unwrap_or(&default_cluster);
2919
2920                let config: BTreeMap<_, _> = params
2921                    .params
2922                    .iter()
2923                    .map(|param| (param.name.as_str(), param.value.as_str()))
2924                    .collect();
2925
2926                clusters.insert(
2927                    cluster_name.to_owned(),
2928                    serde_json::json!({ "config": config }),
2929                );
2930
2931                // Arroyo keys the blob by logical topic and maps it to one physical topic. Relay's
2932                // sharded topics are one logical topic to many physical ones, which Arroyo cannot
2933                // express yet, so each physical topic is its own entry and maps to itself.
2934                //
2935                // That also means one topic name cannot point at two clusters.
2936                let entry = serde_json::json!({ "physical_topics": [{ "cluster": cluster_name }] });
2937                match topics.entry(params.topic_name.clone()) {
2938                    Entry::Vacant(vacant) => {
2939                        vacant.insert(entry);
2940                    }
2941                    Entry::Occupied(occupied) if *occupied.get() != entry => {
2942                        return Err(KafkaConfigError::AmbiguousTopic(params.topic_name.clone()));
2943                    }
2944                    Entry::Occupied(_) => {}
2945                }
2946            }
2947        }
2948
2949        // Serializing maps of strings cannot fail.
2950        Ok(serde_json::to_vec(&serde_json::json!({
2951            "clusters": clusters,
2952            "topics": topics,
2953        }))
2954        .expect("kafka config blob is serializable"))
2955    }
2956
2957    /// All unused but configured topic assignments.
2958    pub fn unused_topic_assignments(&self) -> &relay_kafka::Unused {
2959        &self.inner.values.processing.topics.unused
2960    }
2961
2962    /// Configuration of the objectstore service.
2963    pub fn objectstore(&self) -> &ObjectstoreServiceConfig {
2964        &self.inner.values.processing.objectstore
2965    }
2966
2967    /// Configuration of the upload service.
2968    pub fn upload(&self) -> &Upload {
2969        &self.inner.values.upload
2970    }
2971
2972    /// Returns the key used to sign upload locations.
2973    #[cfg(feature = "processing")]
2974    pub fn upload_signing_key(&self) -> Option<&SecretKey> {
2975        self.upload()
2976            .credentials
2977            .as_ref()
2978            .map(|c| &c.signing_key)
2979            .or(self.credentials().map(|c| &c.secret_key))
2980    }
2981
2982    /// Returns the key used to verify upload locations.
2983    #[cfg(feature = "processing")]
2984    pub fn upload_verification_key(&self) -> Option<&PublicKey> {
2985        self.upload()
2986            .credentials
2987            .as_ref()
2988            .map(|c| &c.verification_key)
2989            .or(self.credentials().map(|c| &c.public_key))
2990    }
2991
2992    /// Redis servers to connect to for project configs, rate limiting, and metrics metadata.
2993    pub fn redis(&self) -> Option<RedisConfigsRef<'_>> {
2994        let redis_configs = self.inner.values.processing.redis.as_ref()?;
2995
2996        Some(build_redis_configs(
2997            redis_configs,
2998            self.cpu_concurrency() as u32,
2999            self.pool_concurrency() as u32,
3000        ))
3001    }
3002
3003    /// Chunk size of attachments in bytes.
3004    pub fn attachment_chunk_size(&self) -> usize {
3005        self.inner
3006            .values
3007            .processing
3008            .attachment_chunk_size
3009            .as_bytes()
3010    }
3011
3012    /// Maximum metrics batch size in bytes.
3013    pub fn metrics_max_batch_size_bytes(&self) -> usize {
3014        self.inner.values.aggregator.max_flush_bytes
3015    }
3016
3017    /// Default prefix to use when looking up project configs in Redis. This is only done when
3018    /// Relay is in processing mode.
3019    pub fn projectconfig_cache_prefix(&self) -> &str {
3020        &self.inner.values.processing.projectconfig_cache_prefix
3021    }
3022
3023    /// Maximum rate limit to report to clients in seconds.
3024    pub fn max_rate_limit(&self) -> Option<u64> {
3025        self.inner.values.processing.max_rate_limit.map(u32::into)
3026    }
3027
3028    /// Amount of remaining quota which is cached in memory.
3029    pub fn quota_cache_ratio(&self) -> Option<f32> {
3030        self.inner.values.processing.quota_cache_ratio
3031    }
3032
3033    /// Maximum limit (ratio) for the in memory quota cache.
3034    pub fn quota_cache_max(&self) -> Option<f32> {
3035        self.inner.values.processing.quota_cache_max
3036    }
3037
3038    /// Interval to refresh internal health checks.
3039    pub fn health_refresh_interval(&self) -> Duration {
3040        Duration::from_millis(self.inner.values.health.refresh_interval_ms)
3041    }
3042
3043    /// Maximum memory watermark in bytes.
3044    pub fn health_max_memory_watermark_bytes(&self) -> u64 {
3045        self.inner
3046            .values
3047            .health
3048            .max_memory_bytes
3049            .as_ref()
3050            .map_or(u64::MAX, |b| b.as_bytes() as u64)
3051    }
3052
3053    /// Maximum memory watermark as a percentage of maximum system memory.
3054    pub fn health_max_memory_watermark_percent(&self) -> f32 {
3055        self.inner.values.health.max_memory_percent
3056    }
3057
3058    /// Health check probe timeout.
3059    pub fn health_probe_timeout(&self) -> Duration {
3060        Duration::from_millis(self.inner.values.health.probe_timeout_ms)
3061    }
3062
3063    /// Refresh frequency for polling new memory stats.
3064    pub fn memory_stat_refresh_frequency_ms(&self) -> u64 {
3065        self.inner.values.health.memory_stat_refresh_frequency_ms
3066    }
3067
3068    /// Maximum amount of COGS measurements buffered in memory.
3069    pub fn cogs_max_queue_size(&self) -> u64 {
3070        self.inner.values.cogs.max_queue_size
3071    }
3072
3073    /// Resource ID to use for Relay COGS measurements.
3074    pub fn cogs_relay_resource_id(&self) -> &str {
3075        &self.inner.values.cogs.relay_resource_id
3076    }
3077
3078    /// Returns configuration for the default metrics aggregator.
3079    pub fn default_aggregator_config(&self) -> &AggregatorServiceConfig {
3080        &self.inner.values.aggregator
3081    }
3082
3083    /// Returns configuration for non-default metrics aggregator.
3084    pub fn secondary_aggregator_configs(&self) -> &Vec<ScopedAggregatorConfig> {
3085        &self.inner.values.secondary_aggregators
3086    }
3087
3088    /// Returns aggregator config for a given metrics namespace.
3089    pub fn aggregator_config_for(&self, namespace: MetricNamespace) -> &AggregatorServiceConfig {
3090        for entry in &self.inner.values.secondary_aggregators {
3091            if entry.condition.matches(Some(namespace)) {
3092                return &entry.config;
3093            }
3094        }
3095        &self.inner.values.aggregator
3096    }
3097
3098    /// Return the statically configured Relays.
3099    pub fn static_relays(&self) -> &HashMap<RelayId, RelayInfo> {
3100        &self.inner.values.auth.static_relays
3101    }
3102
3103    /// Returns the max age a signature is considered valid, in seconds.
3104    pub fn signature_max_age(&self) -> Duration {
3105        Duration::from_secs(self.inner.values.auth.signature_max_age)
3106    }
3107
3108    /// Returns `true` if unknown items should be accepted and forwarded.
3109    pub fn accept_unknown_items(&self) -> bool {
3110        let forward = self.inner.values.routing.accept_unknown_items;
3111        forward.unwrap_or_else(|| !self.processing_enabled())
3112    }
3113}
3114
3115impl fmt::Debug for ConfigSnapshot {
3116    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3117        f.debug_struct("ConfigSnapshot")
3118            .field("values", &self.inner.values)
3119            .finish()
3120    }
3121}
3122
3123#[cfg(test)]
3124mod tests {
3125    use super::*;
3126
3127    #[test]
3128    fn test_http_encoding_parse_strict() {
3129        for (value, expected) in [
3130            ("identity", Some(HttpEncoding::Identity)),
3131            ("gzip", Some(HttpEncoding::Gzip)),
3132            ("deflate", Some(HttpEncoding::Deflate)),
3133            ("br", Some(HttpEncoding::Br)),
3134            ("zstd", Some(HttpEncoding::Zstd)),
3135            ("", None),
3136            ("unknown", None),
3137            ("x-gzip", None),
3138            ("GZIP", None),
3139            (" gzip ", None),
3140            ("zstd, gzip", None),
3141        ] {
3142            assert_eq!(HttpEncoding::parse_strict(value), expected, "{value:?}");
3143        }
3144    }
3145
3146    #[cfg(feature = "processing")]
3147    #[test]
3148    fn test_upload_secret_key_from_file() {
3149        let path = env::temp_dir().join(Uuid::new_v4().to_string());
3150        fs::create_dir(&path).unwrap();
3151        fs::write(
3152            path.join("my_secret.txt"),
3153            "U3LSQM5NorvgnoYHW_aZpc_43nuuh3lhs3zjjcBwaks",
3154        )
3155        .unwrap();
3156        fs::write(
3157            ConfigValues::path(&path),
3158            r#"
3159    upload:
3160        credentials:
3161            signing_key: ${file:my_secret.txt}
3162            verification_key: "VNS8haF0VTnuMMDR2t-f7AgnmUcXmcdzV3SVksSk34s""#,
3163        )
3164        .unwrap();
3165
3166        let config = Config::from_path(&path).unwrap().current();
3167
3168        fs::remove_dir_all(path).unwrap();
3169
3170        let signing_key = &config.upload().credentials.as_ref().unwrap().signing_key;
3171        assert_eq!(
3172            signing_key.to_string(),
3173            "U3LSQM5NorvgnoYHW_aZpc_43nuuh3lhs3zjjcBwaks"
3174        );
3175    }
3176
3177    #[test]
3178    fn test_emit_outcomes() {
3179        for (serialized, deserialized) in &[
3180            ("true", EmitOutcomes::AsOutcomes),
3181            ("false", EmitOutcomes::None),
3182            ("\"as_client_reports\"", EmitOutcomes::AsClientReports),
3183        ] {
3184            let value: EmitOutcomes = serde_json::from_str(serialized).unwrap();
3185            assert_eq!(value, *deserialized);
3186            assert_eq!(serde_json::to_string(&value).unwrap(), *serialized);
3187        }
3188    }
3189
3190    #[test]
3191    fn test_emit_outcomes_invalid() {
3192        assert!(serde_json::from_str::<EmitOutcomes>("asdf").is_err());
3193    }
3194
3195    /// Builds a config from YAML under `processing`.
3196    #[cfg(feature = "processing")]
3197    fn processing_config(yaml: &str) -> Config {
3198        let path = env::temp_dir().join(Uuid::new_v4().to_string());
3199        fs::create_dir(&path).unwrap();
3200        fs::write(ConfigValues::path(&path), yaml).unwrap();
3201        Config::from_path(&path).unwrap()
3202    }
3203
3204    /// A generated blob must resolve to the same broker params Relay would have built directly.
3205    #[cfg(feature = "processing")]
3206    #[test]
3207    fn test_kafka_config_blob_round_trips() {
3208        use sentry_arroyo::backends::kafka::config_blob::{ConfigBlob, ProducerSelector};
3209
3210        // Covers sharding, a secondary cluster, and a secondary config named `default`.
3211        let config = processing_config(
3212            r#"
3213processing:
3214  enabled: true
3215  kafka_config:
3216    - {name: "bootstrap.servers", value: "primary:9092"}
3217    - {name: "compression.type", value: "lz4"}
3218  secondary_kafka_configs:
3219    default:
3220      - {name: "bootstrap.servers", value: "impostor:9092"}
3221  topics:
3222    ingest-events: ["events-1", "events-2"]
3223    ingest-metrics:
3224      name: "metrics-topic"
3225      config: "default"
3226"#,
3227        );
3228        let config = config.current();
3229
3230        let blob = config.kafka_config_blob().unwrap();
3231        let parsed = ConfigBlob::parse(&blob).unwrap();
3232
3233        let resolve = |topic: &str| {
3234            let resolved = parsed
3235                .producer_config(&ProducerSelector::new(topic, "relay"))
3236                .unwrap_or_else(|_| panic!("{topic} is missing from the blob"));
3237
3238            // Each entry must produce to the topic it is keyed by.
3239            assert_eq!(resolved.physical_topic.as_str(), topic);
3240
3241            resolved
3242                .config
3243                .config_map()
3244                .iter()
3245                // Arroyo adds these itself when building a producer config.
3246                .filter(|(key, _)| !matches!(key.as_str(), "statistics.interval.ms" | "client.id"))
3247                .map(|(key, value)| (key.clone(), value.clone()))
3248                .collect::<BTreeMap<_, _>>()
3249        };
3250
3251        for (topic, physical) in [
3252            (KafkaTopic::Events, ["events-1", "events-2"].as_slice()),
3253            (KafkaTopic::MetricsSessions, ["metrics-topic"].as_slice()),
3254        ] {
3255            let params = config.kafka_configs(topic).unwrap();
3256
3257            for (shard, physical) in params.topics().iter().zip(physical) {
3258                let expected: BTreeMap<_, _> = shard
3259                    .params
3260                    .iter()
3261                    .map(|param| (param.name.clone(), param.value.clone()))
3262                    .collect();
3263
3264                assert_eq!(
3265                    resolve(physical),
3266                    expected,
3267                    "{physical} resolved differently"
3268                );
3269            }
3270        }
3271
3272        // The secondary config named `default` must not have swallowed the anonymous one.
3273        assert_eq!(
3274            resolve("events-1").get("bootstrap.servers").unwrap(),
3275            "primary:9092"
3276        );
3277        assert_eq!(
3278            resolve("metrics-topic").get("bootstrap.servers").unwrap(),
3279            "impostor:9092"
3280        );
3281    }
3282
3283    /// Moving a topic to a different cluster must change the broker it resolves to.
3284    #[cfg(feature = "processing")]
3285    #[test]
3286    fn test_topic_can_move_between_clusters() {
3287        use sentry_arroyo::backends::kafka::config_blob::{ConfigBlob, ProducerSelector};
3288
3289        let resolve = |yaml: &str| {
3290            let config = processing_config(yaml);
3291            let blob = config.current().kafka_config_blob().unwrap();
3292            ConfigBlob::parse(&blob)
3293                .unwrap()
3294                .producer_config(&ProducerSelector::new("events-topic", "relay"))
3295                .unwrap()
3296                .config
3297                .get_config_value("bootstrap.servers")
3298                .unwrap()
3299                .clone()
3300        };
3301
3302        let before = resolve(
3303            r#"
3304processing:
3305  enabled: true
3306  kafka_config:
3307    - {name: "bootstrap.servers", value: "primary:9092"}
3308  secondary_kafka_configs:
3309    other:
3310      - {name: "bootstrap.servers", value: "other:9092"}
3311  topics:
3312    ingest-events: "events-topic"
3313"#,
3314        );
3315
3316        // Same physical topic, now pointed at the secondary cluster.
3317        let after = resolve(
3318            r#"
3319processing:
3320  enabled: true
3321  kafka_config:
3322    - {name: "bootstrap.servers", value: "primary:9092"}
3323  secondary_kafka_configs:
3324    other:
3325      - {name: "bootstrap.servers", value: "other:9092"}
3326  topics:
3327    ingest-events:
3328      name: "events-topic"
3329      config: "other"
3330"#,
3331        );
3332
3333        assert_eq!(before, "primary:9092");
3334        assert_eq!(after, "other:9092");
3335    }
3336
3337    /// The blob is keyed by topic name, so one name on two clusters cannot be expressed. That
3338    /// must fail loudly instead of sending one of the two to the wrong cluster.
3339    #[cfg(feature = "processing")]
3340    #[test]
3341    fn test_kafka_config_blob_rejects_topic_on_two_clusters() {
3342        let config = processing_config(
3343            r#"
3344processing:
3345  enabled: true
3346  kafka_config:
3347    - {name: "bootstrap.servers", value: "primary:9092"}
3348  secondary_kafka_configs:
3349    other:
3350      - {name: "bootstrap.servers", value: "other:9092"}
3351  topics:
3352    outcomes:
3353      name: "outcomes-topic"
3354      config: "other"
3355    outcomes-billing: "outcomes-topic"
3356"#,
3357        );
3358
3359        assert!(matches!(
3360            config.current().kafka_config_blob(),
3361            Err(KafkaConfigError::AmbiguousTopic(topic)) if topic == "outcomes-topic"
3362        ));
3363    }
3364
3365    /// Broker settings reload; topic assignments do not, since producers hold theirs from
3366    /// startup.
3367    #[test]
3368    fn test_reload_takes_kafka_config_but_not_topics() {
3369        let mut current = ConfigValues::default();
3370        current.processing.kafka_config = vec![KafkaConfigParam {
3371            name: "bootstrap.servers".to_owned(),
3372            value: "old:9092".to_owned(),
3373        }];
3374        current.processing.topics.events = "old-topic".to_owned().into();
3375
3376        let mut other = ConfigValues::default();
3377        other.processing.kafka_config = vec![KafkaConfigParam {
3378            name: "bootstrap.servers".to_owned(),
3379            value: "new:9092".to_owned(),
3380        }];
3381        other.processing.topics.events = "new-topic".to_owned().into();
3382
3383        let mut current = ConfigInner {
3384            values: current,
3385            ..Default::default()
3386        };
3387        let other = ConfigInner {
3388            values: other,
3389            ..Default::default()
3390        };
3391
3392        assert!(current.reload_with(&other));
3393        assert_eq!(current.values.processing.kafka_config[0].value, "new:9092");
3394
3395        let assignment = format!("{:?}", current.values.processing.topics.events);
3396        assert!(
3397            assignment.contains("old-topic"),
3398            "topic assignment was reloaded, but the producers cannot pick it up: {assignment}"
3399        );
3400    }
3401}