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    /// shutdown timeout
267    pub shutdown_timeout: Option<String>,
268    /// Server name reported in the Sentry SDK.
269    pub server_name: Option<String>,
270}
271
272/// The relay credentials
273#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
274pub struct Credentials {
275    /// The secret key of the relay
276    pub secret_key: SecretKey,
277    /// The public key of the relay
278    pub public_key: PublicKey,
279    /// The globally unique ID of the relay.
280    pub id: RelayId,
281}
282
283impl Credentials {
284    /// Generates new random credentials.
285    pub fn generate() -> Self {
286        relay_log::info!("generating new relay credentials");
287        let (secret_key, public_key) = generate_key_pair();
288        Self {
289            secret_key,
290            public_key,
291            id: generate_relay_id(),
292        }
293    }
294
295    /// Serializes this configuration to JSON.
296    pub fn to_json_string(&self) -> anyhow::Result<String> {
297        serde_json::to_string(self)
298            .with_context(|| ConfigError::new(ConfigErrorKind::CouldNotWriteFile))
299    }
300}
301
302impl ConfigObject for Credentials {
303    fn format() -> ConfigFormat {
304        ConfigFormat::Json
305    }
306    fn name() -> &'static str {
307        "credentials"
308    }
309}
310
311/// Information on a downstream Relay.
312#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
313#[serde(rename_all = "camelCase")]
314pub struct RelayInfo {
315    /// The public key that this Relay uses to authenticate and sign requests.
316    pub public_key: PublicKey,
317
318    /// Marks an internal relay that has privileged access to more project configuration.
319    #[serde(default)]
320    pub internal: bool,
321}
322
323impl RelayInfo {
324    /// Creates a new RelayInfo
325    pub fn new(public_key: PublicKey) -> Self {
326        Self {
327            public_key,
328            internal: false,
329        }
330    }
331}
332
333/// The operation mode of a relay.
334#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize)]
335#[serde(rename_all = "camelCase")]
336pub enum RelayMode {
337    /// This relay acts as a proxy for all requests and events.
338    ///
339    /// Events are normalized and rate limits from the upstream are enforced, but the relay will not
340    /// fetch project configurations from the upstream or perform PII stripping. All events are
341    /// accepted unless overridden on the file system.
342    Proxy,
343
344    /// Project configurations are managed by the upstream.
345    ///
346    /// Project configurations are always fetched from the upstream, unless they are statically
347    /// overridden in the file system. This relay must be allowed in the upstream Sentry. This is
348    /// only possible, if the upstream is Sentry directly, or another managed Relay.
349    Managed,
350}
351
352impl<'de> Deserialize<'de> for RelayMode {
353    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
354    where
355        D: Deserializer<'de>,
356    {
357        let s = String::deserialize(deserializer)?;
358        match s.as_str() {
359            "proxy" => Ok(RelayMode::Proxy),
360            "managed" => Ok(RelayMode::Managed),
361            "static" => Err(serde::de::Error::custom(
362                "Relay mode 'static' has been removed. Please use 'managed' or 'proxy' instead.",
363            )),
364            other => Err(serde::de::Error::unknown_variant(
365                other,
366                &["proxy", "managed"],
367            )),
368        }
369    }
370}
371
372impl fmt::Display for RelayMode {
373    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
374        match self {
375            RelayMode::Proxy => write!(f, "proxy"),
376            RelayMode::Managed => write!(f, "managed"),
377        }
378    }
379}
380
381/// The instance type of Relay.
382#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
383#[serde(rename_all = "camelCase")]
384pub enum RelayInstance {
385    /// This Relay is run as a default instance.
386    Default,
387
388    /// This Relay is run as a canary instance where experiments can be run.
389    Canary,
390}
391
392impl RelayInstance {
393    /// Returns `true` if the [`RelayInstance`] is of type [`RelayInstance::Canary`].
394    pub fn is_canary(&self) -> bool {
395        matches!(self, RelayInstance::Canary)
396    }
397}
398
399impl fmt::Display for RelayInstance {
400    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
401        match self {
402            RelayInstance::Default => write!(f, "default"),
403            RelayInstance::Canary => write!(f, "canary"),
404        }
405    }
406}
407
408impl FromStr for RelayInstance {
409    type Err = fmt::Error;
410
411    fn from_str(s: &str) -> Result<Self, Self::Err> {
412        match s {
413            "canary" => Ok(RelayInstance::Canary),
414            _ => Ok(RelayInstance::Default),
415        }
416    }
417}
418
419/// Error returned when parsing an invalid [`RelayMode`].
420#[derive(Clone, Copy, Debug, Eq, PartialEq)]
421pub struct ParseRelayModeError;
422
423impl fmt::Display for ParseRelayModeError {
424    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
425        write!(f, "Relay mode must be one of: managed or proxy")
426    }
427}
428
429impl Error for ParseRelayModeError {}
430
431impl FromStr for RelayMode {
432    type Err = ParseRelayModeError;
433
434    fn from_str(s: &str) -> Result<Self, Self::Err> {
435        match s {
436            "proxy" => Ok(RelayMode::Proxy),
437            "managed" => Ok(RelayMode::Managed),
438            _ => Err(ParseRelayModeError),
439        }
440    }
441}
442
443/// Returns `true` if this value is equal to `Default::default()`.
444fn is_default<T: Default + PartialEq>(t: &T) -> bool {
445    *t == T::default()
446}
447
448/// Checks if we are running in docker.
449fn is_docker() -> bool {
450    if fs::metadata("/.dockerenv").is_ok() {
451        return true;
452    }
453
454    fs::read_to_string("/proc/self/cgroup").is_ok_and(|s| s.contains("/docker"))
455}
456
457/// Default value for the "bind" configuration.
458fn default_host() -> IpAddr {
459    if is_docker() {
460        // Docker images rely on this service being exposed
461        "0.0.0.0".parse().unwrap()
462    } else {
463        "127.0.0.1".parse().unwrap()
464    }
465}
466
467/// Controls responses from the readiness health check endpoint based on authentication.
468///
469/// Independent of the the readiness condition, shutdown always switches Relay into unready state.
470#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
471#[serde(rename_all = "lowercase")]
472#[derive(Default)]
473pub enum ReadinessCondition {
474    /// (default) Relay is ready when authenticated and connected to the upstream.
475    ///
476    /// Before authentication has succeeded and during network outages, Relay responds as not ready.
477    /// Relay reauthenticates based on the `http.auth_interval` parameter. During reauthentication,
478    /// Relay remains ready until authentication fails.
479    ///
480    /// Authentication is only required for Relays in managed mode. Other Relays will only check for
481    /// network outages.
482    #[default]
483    Authenticated,
484    /// Relay reports readiness regardless of the authentication and networking state.
485    Always,
486}
487
488/// Relay specific configuration values.
489#[derive(Serialize, Deserialize, Debug, Clone)]
490#[serde(default)]
491pub struct Relay {
492    /// The operation mode of this Relay.
493    pub mode: RelayMode,
494    /// The instance type of this Relay.
495    pub instance: RelayInstance,
496    /// The upstream Relay or Sentry instance.
497    pub upstream: UpstreamDescriptor,
498    /// The upstream advertised to downstream Relay instances.
499    ///
500    /// This value will be advertised to downstream Relays as the upstream to use when forwarding
501    /// data. It can be used for traffic routing and balancing, it must not redirect to a different
502    /// Sentry instance.
503    ///
504    /// Downstream Relays will treat the advertised upstream as the same logical component as this instance
505    /// and re-use already established authentication keys.
506    pub advertised_upstream: Option<UpstreamDescriptor>,
507    /// The host the relay should bind to (network interface).
508    pub host: IpAddr,
509    /// The port to bind for the unencrypted relay HTTP server.
510    pub port: u16,
511    /// The host the relay should bind to (network interface) for internally exposed APIs, like
512    /// health checks.
513    ///
514    /// If not configured, internal routes are exposed on the main HTTP server.
515    ///
516    /// Note: configuring the internal http server on an address which overlaps with the main
517    /// server (e.g. main on `0.0.0.0:3000` and internal on `127.0.0.1:3000`) is a misconfiguration
518    /// resulting in approximately half of the requests sent to `127.0.0.1:3000` to fail, as the handling
519    /// http server is chosen by the operating system 'at random'.
520    ///
521    /// As a best practice you should always choose different ports to avoid this issue.
522    ///
523    /// Defaults to [`Self::host`].
524    pub internal_host: Option<IpAddr>,
525    /// The port to bind for internally exposed APIs.
526    ///
527    /// Defaults to [`Self::port`].
528    pub internal_port: Option<u16>,
529    /// Always override project IDs from the URL and DSN with the identifier used at the upstream.
530    ///
531    /// Enable this setting for Relays used to redirect traffic to a migrated Sentry instance.
532    /// Validation of project identifiers can be safely skipped in these cases.
533    #[serde(skip_serializing_if = "is_default")]
534    pub override_project_ids: bool,
535    /// Interval in seconds for Relay to check if its configuration changed.
536    ///
537    /// If configured Relay will periodically check its configuration for changes
538    /// and hot reload it.
539    ///
540    /// Hot reloading is only supported for a limited set of values.
541    ///
542    /// Defaults to `None` / off.
543    pub config_reload_interval: Option<u64>,
544}
545
546impl Default for Relay {
547    fn default() -> Self {
548        Relay {
549            mode: RelayMode::Managed,
550            instance: RelayInstance::Default,
551            upstream: "https://sentry.io/".parse().unwrap(),
552            advertised_upstream: None,
553            host: default_host(),
554            port: 3000,
555            internal_host: None,
556            internal_port: None,
557            override_project_ids: false,
558            config_reload_interval: None,
559        }
560    }
561}
562
563/// Control the metrics.
564#[derive(Serialize, Deserialize, Debug, Clone)]
565#[serde(default)]
566pub struct Metrics {
567    /// Hostname and port of the statsd server.
568    ///
569    /// Defaults to `None`.
570    pub statsd: Option<String>,
571    /// Buffer size used for metrics sent to the statsd socket.
572    ///
573    /// Defaults to `None`.
574    pub statsd_buffer_size: Option<usize>,
575    /// Common prefix that should be added to all metrics.
576    ///
577    /// Defaults to `"sentry.relay"`.
578    pub prefix: String,
579    /// Default tags to apply to all metrics.
580    pub default_tags: BTreeMap<String, String>,
581    /// Tag name to report the hostname to for each metric. Defaults to not sending such a tag.
582    pub hostname_tag: Option<String>,
583    /// Interval for periodic metrics emitted from Relay.
584    ///
585    /// Setting it to `0` seconds disables the periodic metrics.
586    /// Defaults to 5 seconds.
587    pub periodic_secs: u64,
588}
589
590impl Default for Metrics {
591    fn default() -> Self {
592        Metrics {
593            statsd: None,
594            statsd_buffer_size: None,
595            prefix: "sentry.relay".into(),
596            default_tags: BTreeMap::new(),
597            hostname_tag: None,
598            periodic_secs: 5,
599        }
600    }
601}
602
603/// Controls various limits
604#[derive(Serialize, Deserialize, Debug, Clone)]
605#[serde(default)]
606pub struct Limits {
607    /// How many requests can be sent concurrently from Relay to the upstream before Relay starts
608    /// buffering.
609    pub max_concurrent_requests: usize,
610    /// How many queries can be sent concurrently from Relay to the upstream before Relay starts
611    /// buffering.
612    ///
613    /// The concurrency of queries is additionally constrained by `max_concurrent_requests`.
614    pub max_concurrent_queries: usize,
615    /// The maximum payload size for events.
616    pub max_event_size: ByteSize,
617    /// The maximum size for each attachment.
618    pub max_attachment_size: ByteSize,
619    /// The maximum amount of attachments in a single envelope.
620    pub max_attachment_count: usize,
621    /// The maximum combined size for all attachments in an envelope or request.
622    pub max_attachments_size: ByteSize,
623    /// The maximum size for a TUS upload request body.
624    ///
625    /// Applies to incoming request bytes at every hop and also to decoded bytes when writing to
626    /// objectstore.
627    pub max_upload_size: ByteSize,
628    /// The maximum combined size for all client reports in an envelope or request.
629    pub max_client_reports_size: ByteSize,
630    /// The maximum number of client report items per envelope.
631    pub max_client_reports_count: usize,
632    /// The maximum payload size for a monitor check-in.
633    pub max_check_in_size: ByteSize,
634    /// The maximum payload size for an entire envelopes. Individual limits still apply.
635    pub max_envelope_size: ByteSize,
636    /// The maximum combined size for all sessions in an envelope in bytes.
637    pub max_sessions_size: ByteSize,
638    /// The maximum number of session items per envelope.
639    pub max_session_count: usize,
640    /// The maximum payload size for general API requests.
641    pub max_api_payload_size: ByteSize,
642    /// The maximum payload size for file uploads and chunks.
643    pub max_api_file_upload_size: ByteSize,
644    /// The maximum payload size for chunks
645    pub max_api_chunk_upload_size: ByteSize,
646    /// The maximum payload size for a profile
647    pub max_profile_size: ByteSize,
648    /// The maximum payload size for a trace metric.
649    pub max_trace_metric_size: ByteSize,
650    /// The maximum payload size for a log.
651    pub max_log_size: ByteSize,
652    /// The maximum number of operations that can occur in a log expansion.
653    pub max_expanded_log_operations: usize,
654    /// The maximum number of operations that can occur in a span expansion.
655    pub max_expanded_span_operations: usize,
656    /// The maximum number of operations that can occur in a trace metric expansion.
657    pub max_expanded_trace_metric_operations: usize,
658    /// The maximum size in bytes of spans that can result from a span expansion.
659    pub max_expanded_span_bytes: ByteSize,
660    /// The maximum total number of bytes that can result from a log expansion.
661    pub max_expanded_logs_size: ByteSize,
662    /// The maximum payload size for a span.
663    pub max_span_size: ByteSize,
664    /// The maximum amount of standalone transaction spans per envelope.
665    pub max_standalone_span_count: usize,
666    /// The maximum payload size for an item container.
667    pub max_container_size: ByteSize,
668    /// The maximum payload size for metric buckets.
669    pub max_metric_buckets_size: ByteSize,
670    /// The maximum payload size for a compressed replay.
671    pub max_replay_compressed_size: ByteSize,
672    /// The maximum payload size for an uncompressed replay.
673    #[serde(alias = "max_replay_size")]
674    max_replay_uncompressed_size: ByteSize,
675    /// The maximum size for a replay recording Kafka message.
676    pub max_replay_message_size: ByteSize,
677    /// The byte size limit up to which Relay will retain
678    /// keys of invalid/removed attributes.
679    ///
680    /// This is only relevant for EAP items (spans, logs, …).
681    /// In principle, we want to record all deletions of attributes,
682    /// but we have to institute some limit to protect our infrastructure
683    /// against excessive metadata sizes.
684    ///
685    /// Defaults to 10KiB.
686    pub max_removed_attribute_key_size: ByteSize,
687    /// The maximum number of threads to spawn for CPU and web work, each.
688    ///
689    /// The total number of threads spawned will roughly be `2 * max_thread_count`. Defaults to
690    /// the number of logical CPU cores on the host.
691    pub max_thread_count: usize,
692    /// Controls the maximum concurrency of each worker thread.
693    ///
694    /// Increasing the concurrency, can lead to a better utilization of worker threads by
695    /// increasing the amount of I/O done concurrently.
696    //
697    /// Currently has no effect on defaults to `1`.
698    pub max_pool_concurrency: usize,
699    /// The maximum number of seconds a query is allowed to take across retries. Individual requests
700    /// have lower timeouts. Defaults to 30 seconds.
701    pub query_timeout: u64,
702    /// The maximum number of seconds to wait for pending envelopes after receiving a shutdown
703    /// signal.
704    pub shutdown_timeout: u64,
705    /// Server keep-alive timeout in seconds.
706    ///
707    /// By default, keep-alive is set to 5 seconds.
708    pub keepalive_timeout: u64,
709    /// Server idle timeout in seconds.
710    ///
711    /// The idle timeout limits the amount of time a connection is kept open without activity.
712    /// Setting this too short may abort connections before Relay is able to send a response.
713    ///
714    /// By default there is no idle timeout.
715    pub idle_timeout: Option<u64>,
716    /// Sets the maximum number of concurrent connections.
717    ///
718    /// Upon reaching the limit, the server will stop accepting connections.
719    ///
720    /// By default there is no limit.
721    pub max_connections: Option<usize>,
722    /// The TCP listen backlog.
723    ///
724    /// Configures the TCP listen backlog for the listening socket of Relay.
725    /// See [`man listen(2)`](https://man7.org/linux/man-pages/man2/listen.2.html)
726    /// for a more detailed description of the listen backlog.
727    ///
728    /// 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).
729    pub tcp_listen_backlog: u32,
730}
731
732impl Default for Limits {
733    fn default() -> Self {
734        Limits {
735            max_concurrent_requests: 100,
736            max_concurrent_queries: 5,
737            max_event_size: ByteSize::mebibytes(1),
738            max_attachment_size: ByteSize::mebibytes(200),
739            max_attachment_count: 30,
740            max_attachments_size: ByteSize::mebibytes(200),
741            max_upload_size: ByteSize::mebibytes(10240),
742            max_client_reports_size: ByteSize::kibibytes(100),
743            max_client_reports_count: 100,
744            max_check_in_size: ByteSize::kibibytes(100),
745            max_envelope_size: ByteSize::mebibytes(200),
746            max_sessions_size: ByteSize::mebibytes(10),
747            max_session_count: 100,
748            max_api_payload_size: ByteSize::mebibytes(20),
749            max_api_file_upload_size: ByteSize::mebibytes(40),
750            max_api_chunk_upload_size: ByteSize::mebibytes(100),
751            max_profile_size: ByteSize::mebibytes(50),
752            max_trace_metric_size: ByteSize::mebibytes(1),
753            max_log_size: ByteSize::mebibytes(2),
754            max_expanded_log_operations: 3_000_000,
755            max_expanded_span_operations: 3_000_000,
756            max_expanded_trace_metric_operations: 3_000_000,
757            max_expanded_span_bytes: ByteSize::mebibytes(20),
758            max_expanded_logs_size: ByteSize::mebibytes(100),
759            max_span_size: ByteSize::mebibytes(10),
760            max_standalone_span_count: 25,
761            max_container_size: ByteSize::mebibytes(12),
762            max_metric_buckets_size: ByteSize::mebibytes(1),
763            max_replay_compressed_size: ByteSize::mebibytes(10),
764            max_replay_uncompressed_size: ByteSize::mebibytes(100),
765            max_replay_message_size: ByteSize::mebibytes(15),
766            max_thread_count: num_cpus::get(),
767            max_pool_concurrency: 1,
768            query_timeout: 30,
769            shutdown_timeout: 10,
770            keepalive_timeout: 5,
771            idle_timeout: None,
772            max_connections: None,
773            tcp_listen_backlog: 1024,
774            max_removed_attribute_key_size: ByteSize::kibibytes(10),
775        }
776    }
777}
778
779/// Controls traffic steering.
780#[derive(Debug, Default, Deserialize, Serialize, Clone)]
781#[serde(default)]
782pub struct Routing {
783    /// Accept and forward unknown Envelope items to the upstream.
784    ///
785    /// Forwarding unknown items should be enabled in most cases to allow proxying traffic for newer
786    /// SDK versions. The upstream in Sentry makes the final decision on which items are valid. If
787    /// this is disabled, just the unknown items are removed from Envelopes, and the rest is
788    /// processed as usual.
789    ///
790    /// Defaults to `true` for all Relay modes other than processing mode. In processing mode, this
791    /// is disabled by default since the item cannot be handled.
792    pub accept_unknown_items: Option<bool>,
793}
794
795/// Http content encoding for both incoming and outgoing web requests.
796#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
797#[serde(rename_all = "lowercase")]
798pub enum HttpEncoding {
799    /// Identity function without no compression.
800    ///
801    /// This is the default encoding and does not require the presence of the `content-encoding`
802    /// HTTP header.
803    #[default]
804    Identity,
805    /// Compression using a [zlib](https://en.wikipedia.org/wiki/Zlib) structure with
806    /// [deflate](https://en.wikipedia.org/wiki/DEFLATE) encoding.
807    ///
808    /// These structures are defined in [RFC 1950](https://datatracker.ietf.org/doc/html/rfc1950)
809    /// and [RFC 1951](https://datatracker.ietf.org/doc/html/rfc1951).
810    Deflate,
811    /// A format using the [Lempel-Ziv coding](https://en.wikipedia.org/wiki/LZ77_and_LZ78#LZ77)
812    /// (LZ77), with a 32-bit CRC.
813    ///
814    /// This is the original format of the UNIX gzip program. The HTTP/1.1 standard also recommends
815    /// that the servers supporting this content-encoding should recognize `x-gzip` as an alias, for
816    /// compatibility purposes.
817    Gzip,
818    /// A format using the [Brotli](https://en.wikipedia.org/wiki/Brotli) algorithm.
819    Br,
820    /// A format using the [Zstd](https://en.wikipedia.org/wiki/Zstd) compression algorithm.
821    Zstd,
822}
823
824impl HttpEncoding {
825    /// Parses a [`HttpEncoding`] from its `content-encoding` header value.
826    ///
827    /// Accepts aliases, whitespace, and mixed case; unknown values fall back to identity.
828    /// Use [`Self::parse_strict`] when validating an incoming request header.
829    pub fn parse(str: &str) -> Self {
830        let str = str.trim();
831        if str.eq_ignore_ascii_case("zstd") {
832            Self::Zstd
833        } else if str.eq_ignore_ascii_case("br") {
834            Self::Br
835        } else if str.eq_ignore_ascii_case("gzip") || str.eq_ignore_ascii_case("x-gzip") {
836            Self::Gzip
837        } else if str.eq_ignore_ascii_case("deflate") {
838            Self::Deflate
839        } else {
840            Self::Identity
841        }
842    }
843
844    /// Parses a canonical `Content-Encoding` value, returning `None` for unsupported values.
845    pub fn parse_strict(value: &str) -> Option<Self> {
846        match value {
847            "identity" => Some(Self::Identity),
848            "deflate" => Some(Self::Deflate),
849            "gzip" => Some(Self::Gzip),
850            "br" => Some(Self::Br),
851            "zstd" => Some(Self::Zstd),
852            _ => None,
853        }
854    }
855
856    /// Returns the value for the `content-encoding` HTTP header.
857    ///
858    /// Returns `None` for [`Identity`](Self::Identity), and `Some` for other encodings.
859    pub fn name(&self) -> Option<&'static str> {
860        match self {
861            Self::Identity => None,
862            Self::Deflate => Some("deflate"),
863            Self::Gzip => Some("gzip"),
864            Self::Br => Some("br"),
865            Self::Zstd => Some("zstd"),
866        }
867    }
868}
869
870/// Controls authentication with upstream.
871#[derive(Serialize, Deserialize, Debug, Clone)]
872#[serde(default)]
873pub struct Http {
874    /// Timeout for upstream requests in seconds.
875    ///
876    /// This timeout covers the time from sending the request until receiving response headers.
877    /// Neither the connection process and handshakes, nor reading the response body is covered in
878    /// this timeout.
879    pub timeout: u32,
880    /// Timeout for establishing connections with the upstream in seconds.
881    ///
882    /// This includes SSL handshakes. Relay reuses connections when the upstream supports connection
883    /// keep-alive. Connections are retained for a maximum 75 seconds, or 15 seconds of inactivity.
884    pub connection_timeout: u32,
885    /// Maximum interval between failed request retries in seconds.
886    pub max_retry_interval: u32,
887    /// The custom HTTP Host header to send to the upstream.
888    pub host_header: Option<String>,
889    /// The interval in seconds at which Relay attempts to reauthenticate with the upstream server.
890    ///
891    /// Re-authentication happens even when Relay is idle. If authentication fails, Relay reverts
892    /// back into startup mode and tries to establish a connection. During this time, incoming
893    /// envelopes will be buffered.
894    ///
895    /// Defaults to `600` (10 minutes).
896    pub auth_interval: Option<u64>,
897    /// The maximum time of experiencing uninterrupted network failures until Relay considers that
898    /// it has encountered a network outage in seconds.
899    ///
900    /// During a network outage relay will try to reconnect and will buffer all upstream messages
901    /// until it manages to reconnect.
902    pub outage_grace_period: u64,
903    /// The time Relay waits before retrying an upstream request, in seconds.
904    ///
905    /// This time is only used before going into a network outage mode.
906    pub retry_delay: u64,
907    /// The interval in seconds for continued failed project fetches at which Relay will error.
908    ///
909    /// A successful fetch resets this interval. Relay does nothing during long
910    /// times without emitting requests.
911    pub project_failure_interval: u64,
912    /// Content encoding to apply to upstream store requests.
913    ///
914    /// By default, Relay applies `zstd` content encoding to compress upstream requests. Compression
915    /// can be disabled to reduce CPU consumption, but at the expense of increased network traffic.
916    ///
917    /// This setting applies to all store requests of SDK data, including events, transactions,
918    /// envelopes and sessions. At the moment, this does not apply to Relay's internal queries.
919    ///
920    /// Available options are:
921    ///
922    ///  - `identity`: Disables compression.
923    ///  - `deflate`: Compression using a zlib header with deflate encoding.
924    ///  - `gzip` (default): Compression using gzip.
925    ///  - `br`: Compression using the brotli algorithm.
926    ///  - `zstd`: Compression using the zstd algorithm.
927    pub encoding: HttpEncoding,
928    /// Submit metrics globally through a shared endpoint.
929    ///
930    /// As opposed to regular envelopes which are sent to an endpoint inferred from the project's
931    /// DSN, this submits metrics to the global endpoint with Relay authentication.
932    ///
933    /// This option does not have any effect on processing mode.
934    pub global_metrics: bool,
935    /// Controls whether the forward endpoint is enabled.
936    ///
937    /// The forward endpoint forwards unknown API requests to the upstream.
938    ///
939    /// Relay instances with processing enabled are expected to support the latest API and do never
940    /// support forwarding requests to Sentry.
941    pub forward: bool,
942    /// Enables an async DNS resolver through the `hickory-dns` crate, which uses an LRU cache for
943    /// the resolved entries. This helps to limit the amount of requests made to the upstream DNS
944    /// server (important for K8s infrastructure).
945    pub dns_cache: bool,
946}
947
948impl Default for Http {
949    fn default() -> Self {
950        Http {
951            timeout: 5,
952            connection_timeout: 3,
953            max_retry_interval: 60, // 1 minute
954            host_header: None,
955            auth_interval: Some(600), // 10 minutes
956            outage_grace_period: DEFAULT_NETWORK_OUTAGE_GRACE_PERIOD,
957            retry_delay: 1,
958            project_failure_interval: 90,
959            encoding: HttpEncoding::Zstd,
960            global_metrics: false,
961            forward: true,
962            dns_cache: true,
963        }
964    }
965}
966
967/// Strategy used to assign envelopes to buffer partitions.
968#[derive(Clone, Copy, Debug, Eq, PartialEq, Default, Deserialize, Serialize)]
969#[serde(rename_all = "snake_case")]
970pub enum EnvelopeSpoolPartitioning {
971    /// Envelopes with the same project key pair land on the same partition.
972    ///
973    /// Keeps per-project state, disk files, and event ordering co-located on one partition.
974    ProjectKeyPair,
975    /// Envelopes are distributed across partitions in a round-robin fashion (default).
976    ///
977    /// This prevents "hot" partitions when a single project pair dominates traffic, but has
978    /// trade-offs:
979    /// - Per-project LIFO ordering is no longer preserved across partitions.
980    /// - Per-partition memory footprint grows since every partition sees every project.
981    #[default]
982    RoundRobin,
983}
984
985/// Persistent buffering configuration for incoming envelopes.
986#[derive(Debug, Serialize, Deserialize, Clone)]
987#[serde(default)]
988pub struct EnvelopeSpool {
989    /// The path of the SQLite database file(s) which persist the data.
990    ///
991    /// Based on the number of partitions, more database files will be created within the same path.
992    ///
993    /// If not set, the envelopes will be buffered in memory.
994    pub path: Option<PathBuf>,
995    /// The maximum size of the buffer to keep, in bytes.
996    ///
997    /// When the on-disk buffer reaches this size, new envelopes will be dropped.
998    ///
999    /// Defaults to 500MB.
1000    pub max_disk_size: ByteSize,
1001    /// Size of the batch of compressed envelopes that are spooled to disk at once.
1002    ///
1003    /// Note that this is the size after which spooling will be triggered but it does not guarantee
1004    /// that exactly this size will be spooled, it can be greater or equal.
1005    ///
1006    /// Defaults to 10 KiB.
1007    pub batch_size_bytes: ByteSize,
1008    /// Time after which a batch is flushed, regardless of batch size.
1009    ///
1010    /// The age of the batch is only checked when a new envelope comes in, but in practice this
1011    /// has the desired effect: High-volume projects always form full batches, low-volume batches
1012    /// flush individual envelopes to keep memory usage low.
1013    pub flush_timeout_secs: Option<u64>,
1014    /// Maximum time between receiving the envelope and processing it.
1015    ///
1016    /// When envelopes spend too much time in the buffer (e.g. because their project cannot be loaded),
1017    /// they are dropped.
1018    ///
1019    /// Defaults to 24h.
1020    pub max_envelope_delay_secs: u64,
1021    /// The refresh frequency in ms of how frequently disk usage is updated by querying SQLite
1022    /// internal page stats.
1023    ///
1024    /// Defaults to 100ms.
1025    pub disk_usage_refresh_frequency_ms: u64,
1026    /// The relative memory usage above which the buffer service will stop dequeueing envelopes.
1027    ///
1028    /// Only applies when [`Self::path`] is set.
1029    ///
1030    /// This value should be lower than [`Health::max_memory_percent`] to prevent flip-flopping.
1031    ///
1032    /// Warning: This threshold can cause the buffer service to deadlock when the buffer consumes
1033    /// excessive memory (as influenced by [`Self::batch_size_bytes`]).
1034    ///
1035    /// This scenario arises when the buffer stops spooling due to reaching the
1036    /// [`Self::max_backpressure_memory_percent`] limit, but the batch threshold for spooling
1037    /// ([`Self::batch_size_bytes`]) is never reached. As a result, no data is spooled, memory usage
1038    /// continues to grow, and the system becomes deadlocked.
1039    ///
1040    /// ### Example
1041    /// Suppose the system has 1GB of available memory and is configured to spool only after
1042    /// accumulating 10GB worth of envelopes. If Relay consumes 900MB of memory, it will stop
1043    /// unspooling due to reaching the [`Self::max_backpressure_memory_percent`] threshold.
1044    ///
1045    /// However, because the buffer hasn't accumulated the 10GB needed to trigger spooling,
1046    /// no data will be offloaded. Memory usage keeps increasing until it hits the
1047    /// [`Health::max_memory_percent`] threshold, e.g., at 950MB. At this point:
1048    ///
1049    /// - No more envelopes are accepted.
1050    /// - The buffer remains stuck, as unspooling won’t resume until memory drops below 900MB which
1051    ///   will not happen.
1052    /// - A deadlock occurs, with the system unable to recover without manual intervention.
1053    ///
1054    /// Defaults to 90% (5% less than max memory).
1055    pub max_backpressure_memory_percent: f32,
1056    /// Number of partitions of the buffer.
1057    ///
1058    /// A partition is a separate instance of the buffer which has its own isolated queue, stacks
1059    /// and other resources.
1060    ///
1061    /// Defaults to 1.
1062    pub partitions: NonZeroU8,
1063    /// Strategy used to assign envelopes to buffer partitions.
1064    ///
1065    /// Defaults to partitioning by `ProjectKeyPair`, which keeps all envelopes of a given project
1066    /// pair on the same partition. See [`EnvelopeSpoolPartitioning`] for alternatives and
1067    /// trade-offs.
1068    pub partitioning: EnvelopeSpoolPartitioning,
1069    /// Maximum number of envelopes unspooled from disk per second.
1070    ///
1071    /// The limit applies per Relay instance, not per spool partition.
1072    ///
1073    /// Defaults to `None`, which disables the limit.
1074    pub max_unspool_envelopes_per_second: Option<NonZeroU32>,
1075    /// Whether the database defined in `path` is on an ephemeral storage disk.
1076    ///
1077    /// With `ephemeral: true`, Relay does not spool in-flight data to disk
1078    /// during graceful shutdown. Instead, it attempts to process all data before it terminates.
1079    ///
1080    /// Defaults to `false`.
1081    pub ephemeral: bool,
1082}
1083
1084impl Default for EnvelopeSpool {
1085    fn default() -> Self {
1086        Self {
1087            path: None,
1088            max_disk_size: ByteSize::mebibytes(500),
1089            batch_size_bytes: ByteSize::kibibytes(10),
1090            max_envelope_delay_secs: 24 * 60 * 60,
1091            disk_usage_refresh_frequency_ms: 100,
1092            max_backpressure_memory_percent: 0.8,
1093            partitions: NonZeroU8::new(1).unwrap(),
1094            partitioning: EnvelopeSpoolPartitioning::default(),
1095            ephemeral: false,
1096            flush_timeout_secs: None,
1097            max_unspool_envelopes_per_second: None,
1098        }
1099    }
1100}
1101
1102/// Persistent buffering configuration.
1103#[derive(Debug, Serialize, Deserialize, Default, Clone)]
1104#[serde(default)]
1105pub struct Spool {
1106    /// Configuration for envelope spooling.
1107    pub envelopes: EnvelopeSpool,
1108}
1109
1110/// Controls internal caching behavior.
1111#[derive(Serialize, Deserialize, Debug, Clone)]
1112#[serde(default)]
1113pub struct Cache {
1114    /// The full project state will be requested by this Relay if set to `true`.
1115    ///
1116    /// Relay instances that receive the full project config have full access to quota config
1117    /// and perform dynamic sampling.
1118    pub project_request_full_config: bool,
1119    /// The cache timeout for project configurations in seconds.
1120    pub project_expiry: u32,
1121    /// Continue using project state this many seconds after cache expiry while a new state is
1122    /// being fetched. This is added on top of `project_expiry`.
1123    ///
1124    /// Default is 2 minutes.
1125    pub project_grace_period: u32,
1126    /// Refresh a project after the specified seconds.
1127    ///
1128    /// The time must be between expiry time and the grace period.
1129    ///
1130    /// By default there are no refreshes enabled.
1131    pub project_refresh_interval: Option<u32>,
1132    /// The cache timeout for downstream relay info (public keys) in seconds.
1133    pub relay_expiry: u32,
1134    /// The cache timeout for non-existing entries.
1135    pub miss_expiry: u32,
1136    /// The buffer timeout for batched project config queries before sending them upstream in ms.
1137    pub batch_interval: u32,
1138    /// The buffer timeout for batched queries of downstream relays in ms. Defaults to 100ms.
1139    pub downstream_relays_batch_interval: u32,
1140    /// The maximum number of project configs to fetch from Sentry at once. Defaults to 500.
1141    ///
1142    /// `cache.batch_interval` controls how quickly batches are sent, this controls the batch size.
1143    pub batch_size: usize,
1144    /// Interval for watching local cache override files in seconds.
1145    pub file_interval: u32,
1146    /// Interval for fetching new global configs from the upstream, in seconds.
1147    pub global_config_fetch_interval: u32,
1148}
1149
1150impl Default for Cache {
1151    fn default() -> Self {
1152        Cache {
1153            project_request_full_config: false,
1154            project_expiry: 300,       // 5 minutes
1155            project_grace_period: 120, // 2 minutes
1156            project_refresh_interval: None,
1157            relay_expiry: 3600,                    // 1 hour
1158            miss_expiry: 60,                       // 1 minute
1159            batch_interval: 100,                   // 100ms
1160            downstream_relays_batch_interval: 100, // 100ms
1161            batch_size: 500,
1162            file_interval: 10,                // 10 seconds
1163            global_config_fetch_interval: 10, // 10 seconds
1164        }
1165    }
1166}
1167
1168/// Controls Sentry-internal event processing.
1169#[derive(Serialize, Deserialize, Debug, Clone)]
1170#[serde(default)]
1171pub struct Processing {
1172    /// True if the Relay should do processing. Defaults to `false`.
1173    pub enabled: bool,
1174    /// GeoIp DB file source.
1175    pub geoip_path: Option<PathBuf>,
1176    /// Maximum future timestamp of ingested events.
1177    pub max_secs_in_future: u32,
1178    /// Maximum age of ingested sessions. Older sessions will be dropped.
1179    pub max_session_secs_in_past: u32,
1180    /// Kafka producer configurations.
1181    pub kafka_config: Vec<KafkaConfigParam>,
1182    /// Additional kafka producer configurations.
1183    ///
1184    /// The `kafka_config` is the default producer configuration used for all topics. A secondary
1185    /// kafka config can be referenced in `topics:` like this:
1186    ///
1187    /// ```yaml
1188    /// secondary_kafka_configs:
1189    ///   mycustomcluster:
1190    ///     - name: 'bootstrap.servers'
1191    ///       value: 'sentry_kafka_metrics:9093'
1192    ///
1193    /// topics:
1194    ///   transactions: ingest-transactions
1195    ///   metrics:
1196    ///     name: ingest-metrics
1197    ///     config: mycustomcluster
1198    /// ```
1199    ///
1200    /// Then metrics will be produced to an entirely different Kafka cluster.
1201    pub secondary_kafka_configs: BTreeMap<String, Vec<KafkaConfigParam>>,
1202    /// Kafka topic names.
1203    pub topics: TopicAssignments,
1204    /// Whether to validate the supplied topics by calling Kafka's metadata endpoints.
1205    pub kafka_validate_topics: bool,
1206    /// Upper bound, in seconds, on the random delay before a Kafka producer swaps its client
1207    /// after the Kafka config changed.
1208    ///
1209    /// Spreads swaps out so that a config change does not have every pod in the fleet reconnect
1210    /// at once. Keep it well below how often the Kafka config is expected to change. Tests set
1211    /// this to `0` to observe a swap without waiting.
1212    pub reloading_producer_jitter_secs: u64,
1213    /// Redis hosts to connect to for storing state for rate limits.
1214    pub redis: Option<RedisConfigs>,
1215    /// Maximum chunk size of attachments for Kafka.
1216    pub attachment_chunk_size: ByteSize,
1217    /// Prefix to use when looking up project configs in Redis. Defaults to "relayconfig".
1218    pub projectconfig_cache_prefix: String,
1219    /// Maximum rate limit to report to clients.
1220    pub max_rate_limit: Option<u32>,
1221    /// Configures the quota cache ratio between `0.0` and `1.0`.
1222    ///
1223    /// The quota cache, caches the specified ratio of remaining quota in memory to reduce the
1224    /// amount of synchronizations required with Redis.
1225    ///
1226    /// The ratio is applied to the (per second) rate of the quota, not the total limit.
1227    /// For example a quota with limit 100 with a 10 second window is treated equally to a quota of
1228    /// 10 with a 1 second window.
1229    ///
1230    /// By default quota caching is disabled.
1231    pub quota_cache_ratio: Option<f32>,
1232    /// Relative amount of the total quota limit to which quota caching is applied.
1233    ///
1234    /// If exceeded, the rate limiter will no longer cache the quota and sync with Redis on every call instead.
1235    /// Lowering this value reduces the probability of incorrectly over-accepting.
1236    ///
1237    /// Must be between `0.0` and `1.0`, by default there is no limit configured.
1238    pub quota_cache_max: Option<f32>,
1239    /// Configuration for the objectstore service.
1240    #[serde(alias = "upload")]
1241    pub objectstore: ObjectstoreServiceConfig,
1242}
1243
1244impl Default for Processing {
1245    /// Constructs a disabled processing configuration.
1246    fn default() -> Self {
1247        Self {
1248            enabled: false,
1249            geoip_path: None,
1250            max_secs_in_future: 60,                  // 1 minute
1251            max_session_secs_in_past: 5 * 24 * 3600, // 5 days
1252            kafka_config: Vec::new(),
1253            secondary_kafka_configs: BTreeMap::new(),
1254            topics: TopicAssignments::default(),
1255            kafka_validate_topics: false,
1256            reloading_producer_jitter_secs: 60,
1257            redis: None,
1258            attachment_chunk_size: ByteSize::mebibytes(1),
1259            projectconfig_cache_prefix: "relayconfig".to_owned(),
1260            max_rate_limit: Some(300), // 5 minutes
1261            quota_cache_ratio: None,
1262            quota_cache_max: None,
1263            objectstore: ObjectstoreServiceConfig::default(),
1264        }
1265    }
1266}
1267
1268/// Picks a cluster name for the default `kafka_config` that no secondary config uses.
1269///
1270/// Only relevant to [`ConfigSnapshot::kafka_config_blob`]: the blob names every cluster, while
1271/// Relay's own config leaves the default one anonymous. Appends underscores to `default` until
1272/// it is unused.
1273fn default_cluster_name(processing: &Processing) -> String {
1274    let mut name = String::from("default");
1275    while processing.secondary_kafka_configs.contains_key(&name) {
1276        name.push('_');
1277    }
1278    name
1279}
1280
1281/// Configuration for normalization in this Relay.
1282#[derive(Debug, Default, Serialize, Deserialize, Clone)]
1283#[serde(default)]
1284pub struct Normalization {
1285    /// Level of normalization for Relay to apply to incoming data.
1286    pub level: NormalizationLevel,
1287}
1288
1289/// Configuration for the level of normalization this Relay should do.
1290#[derive(Copy, Clone, Debug, Default, Serialize, Deserialize, Eq, PartialEq)]
1291#[serde(rename_all = "lowercase")]
1292pub enum NormalizationLevel {
1293    /// Runs normalization, excluding steps that break future compatibility.
1294    ///
1295    /// Processing Relays run [`NormalizationLevel::Full`] if this option is set.
1296    #[default]
1297    Default,
1298    /// Run full normalization.
1299    ///
1300    /// It includes steps that break future compatibility and should only run in
1301    /// the last layer of relays.
1302    Full,
1303}
1304
1305/// Configuration options for objectstore's auth scheme.
1306#[derive(Serialize, Deserialize, Clone)]
1307pub struct ObjectstoreAuthConfig {
1308    /// Identifier for the private key used to sign objectstore's tokens. Must correspond to a
1309    /// public key configured in objectstore.
1310    pub key_id: String,
1311
1312    /// EdDSA private key used to sign Objectstore's tokens, in PEM format.
1313    pub signing_key: String,
1314}
1315
1316impl fmt::Debug for ObjectstoreAuthConfig {
1317    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1318        f.debug_struct("ObjectstoreAuthConfig")
1319            .field("key_id", &self.key_id)
1320            .field("signing_key", &"[redacted]")
1321            .finish()
1322    }
1323}
1324
1325/// Configuration values for the objectstore service.
1326#[derive(Serialize, Deserialize, Debug, Clone)]
1327#[serde(default)]
1328pub struct ObjectstoreServiceConfig {
1329    /// The base URL for the objectstore service.
1330    ///
1331    /// This defaults to [`None`], which means that the service will be disabled,
1332    /// unless a proper configuration is provided.
1333    pub objectstore_url: Option<String>,
1334
1335    /// Maximum concurrency of uploads.
1336    pub max_concurrent_requests: usize,
1337
1338    /// Maximum size of the service input queue when `max_concurrent_requests` is saturated.
1339    ///
1340    /// The service will loadshed if this threshold is reached.
1341    pub max_backlog: usize,
1342
1343    /// Maximum duration of an attachment upload in seconds. Uploads that take longer are discarded.
1344    ///
1345    /// NOTE: This timeout applies to attachments that are already in-memory. Streaming uploads
1346    /// might take longer and are restricted independently by [`Self::stream_timeout`].
1347    pub timeout: u64,
1348
1349    /// Maximum duration of an upload stream.
1350    ///
1351    /// Streams get a larger default timeout because their duration depends on the client
1352    /// as well as the server.
1353    pub stream_timeout: u64,
1354
1355    /// Time between upload attempts.
1356    pub retry_delay: f64,
1357
1358    /// Maximum number of attempts made to upload.
1359    pub max_attempts: NonZeroU16,
1360
1361    /// Configuration values for objectstore's auth scheme.
1362    pub auth: Option<ObjectstoreAuthConfig>,
1363}
1364
1365impl Default for ObjectstoreServiceConfig {
1366    fn default() -> Self {
1367        Self {
1368            objectstore_url: None,
1369            max_concurrent_requests: 10,
1370            max_backlog: 20,
1371            timeout: 60,
1372            stream_timeout: 5 * 60, // synced with `Upload::timeout`
1373            retry_delay: 1.0,
1374            max_attempts: NonZeroU16::new(5).unwrap(),
1375            auth: None,
1376        }
1377    }
1378}
1379
1380/// Determines how to emit outcomes.
1381/// For compatibility reasons, this can either be true, false or AsClientReports
1382#[derive(Copy, Clone, Debug, PartialEq, Eq)]
1383
1384pub enum EmitOutcomes {
1385    /// Do not emit any outcomes.
1386    None,
1387    /// Emit outcomes as client reports.
1388    AsClientReports,
1389    /// Emit outcomes as outcomes.
1390    AsOutcomes,
1391}
1392
1393impl EmitOutcomes {
1394    /// Returns true of outcomes are emitted via http, kafka, or client reports.
1395    pub fn any(&self) -> bool {
1396        !matches!(self, EmitOutcomes::None)
1397    }
1398}
1399
1400impl Serialize for EmitOutcomes {
1401    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1402    where
1403        S: Serializer,
1404    {
1405        // For compatibility, serialize None and AsOutcomes as booleans.
1406        match self {
1407            Self::None => serializer.serialize_bool(false),
1408            Self::AsClientReports => serializer.serialize_str("as_client_reports"),
1409            Self::AsOutcomes => serializer.serialize_bool(true),
1410        }
1411    }
1412}
1413
1414struct EmitOutcomesVisitor;
1415
1416impl Visitor<'_> for EmitOutcomesVisitor {
1417    type Value = EmitOutcomes;
1418
1419    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1420        formatter.write_str("true, false, 'as_client_reports'")
1421    }
1422
1423    fn visit_bool<E>(self, v: bool) -> Result<Self::Value, E>
1424    where
1425        E: serde::de::Error,
1426    {
1427        Ok(if v {
1428            EmitOutcomes::AsOutcomes
1429        } else {
1430            EmitOutcomes::None
1431        })
1432    }
1433
1434    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
1435    where
1436        E: serde::de::Error,
1437    {
1438        match v {
1439            "as_client_reports" => Ok(EmitOutcomes::AsClientReports),
1440            _ => Err(E::invalid_value(Unexpected::Str(v), &self)),
1441        }
1442    }
1443}
1444
1445impl<'de> Deserialize<'de> for EmitOutcomes {
1446    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1447    where
1448        D: Deserializer<'de>,
1449    {
1450        deserializer.deserialize_any(EmitOutcomesVisitor)
1451    }
1452}
1453
1454/// Outcome generation specific configuration values.
1455#[derive(Serialize, Deserialize, Debug, Clone)]
1456#[serde(default)]
1457pub struct Outcomes {
1458    /// Controls whether outcomes will be emitted when processing is disabled.
1459    /// Processing relays always emit outcomes (for backwards compatibility).
1460    /// Can take the following values: false, "as_client_reports", true
1461    pub emit_outcomes: EmitOutcomes,
1462    /// Defines the source string registered in the outcomes originating from
1463    /// this Relay (typically something like the region or the layer).
1464    pub source: Option<String>,
1465}
1466
1467impl Default for Outcomes {
1468    fn default() -> Self {
1469        Outcomes {
1470            emit_outcomes: EmitOutcomes::AsClientReports,
1471            source: None,
1472        }
1473    }
1474}
1475
1476/// Minimal version of a config for dumping out.
1477#[derive(Serialize, Deserialize, Debug, Default)]
1478pub struct MinimalConfig {
1479    /// The relay part of the config.
1480    pub relay: Relay,
1481}
1482
1483impl MinimalConfig {
1484    /// Saves the config in the given config folder as config.yml
1485    pub fn save_in_folder<P: AsRef<Path>>(&self, p: P) -> anyhow::Result<()> {
1486        let path = p.as_ref();
1487        if fs::metadata(path).is_err() {
1488            fs::create_dir_all(path)
1489                .with_context(|| ConfigError::file(ConfigErrorKind::CouldNotOpenFile, path))?;
1490        }
1491        self.save(path)
1492    }
1493}
1494
1495impl ConfigObject for MinimalConfig {
1496    fn format() -> ConfigFormat {
1497        ConfigFormat::Yaml
1498    }
1499
1500    fn name() -> &'static str {
1501        "config"
1502    }
1503}
1504
1505/// Alternative serialization of RelayInfo for config file using snake case.
1506mod config_relay_info {
1507    use serde::ser::SerializeMap;
1508
1509    use super::*;
1510
1511    // Uses snake_case as opposed to camelCase.
1512    #[derive(Debug, Serialize, Deserialize, Clone)]
1513    struct RelayInfoConfig {
1514        public_key: PublicKey,
1515        #[serde(default)]
1516        internal: bool,
1517    }
1518
1519    impl From<RelayInfoConfig> for RelayInfo {
1520        fn from(v: RelayInfoConfig) -> Self {
1521            RelayInfo {
1522                public_key: v.public_key,
1523                internal: v.internal,
1524            }
1525        }
1526    }
1527
1528    impl From<RelayInfo> for RelayInfoConfig {
1529        fn from(v: RelayInfo) -> Self {
1530            RelayInfoConfig {
1531                public_key: v.public_key,
1532                internal: v.internal,
1533            }
1534        }
1535    }
1536
1537    pub(super) fn deserialize<'de, D>(des: D) -> Result<HashMap<RelayId, RelayInfo>, D::Error>
1538    where
1539        D: Deserializer<'de>,
1540    {
1541        let map = HashMap::<RelayId, RelayInfoConfig>::deserialize(des)?;
1542        Ok(map.into_iter().map(|(k, v)| (k, v.into())).collect())
1543    }
1544
1545    pub(super) fn serialize<S>(elm: &HashMap<RelayId, RelayInfo>, ser: S) -> Result<S::Ok, S::Error>
1546    where
1547        S: Serializer,
1548    {
1549        let mut map = ser.serialize_map(Some(elm.len()))?;
1550
1551        for (k, v) in elm {
1552            map.serialize_entry(k, &RelayInfoConfig::from(v.clone()))?;
1553        }
1554
1555        map.end()
1556    }
1557}
1558
1559/// Authentication options.
1560#[derive(Serialize, Deserialize, Debug, Clone)]
1561#[serde(default)]
1562pub struct AuthConfig {
1563    /// Controls responses from the readiness health check endpoint based on authentication.
1564    #[serde(skip_serializing_if = "is_default")]
1565    pub ready: ReadinessCondition,
1566
1567    /// Statically authenticated downstream relays.
1568    #[serde(with = "config_relay_info")]
1569    pub static_relays: HashMap<RelayId, RelayInfo>,
1570
1571    /// How old a signature can be before it is considered invalid, in seconds.
1572    ///
1573    /// Defaults to 5 minutes.
1574    pub signature_max_age: u64,
1575}
1576
1577impl Default for AuthConfig {
1578    fn default() -> Self {
1579        Self {
1580            ready: ReadinessCondition::default(),
1581            static_relays: HashMap::new(),
1582            signature_max_age: 300, // 5 minutes
1583        }
1584    }
1585}
1586
1587/// GeoIp database configuration options.
1588#[derive(Serialize, Deserialize, Debug, Default, Clone)]
1589pub struct GeoIpConfig {
1590    /// The path to GeoIP database.
1591    pub path: Option<PathBuf>,
1592}
1593
1594/// Settings to control Relay's health checks.
1595///
1596/// After breaching one of the configured thresholds, Relay will
1597/// return an `unhealthy` status from its health endpoint.
1598#[derive(Serialize, Deserialize, Debug, Clone, PartialEq)]
1599#[serde(default)]
1600pub struct Health {
1601    /// Interval to refresh internal health checks.
1602    ///
1603    /// Shorter intervals will decrease the time it takes the health check endpoint to report
1604    /// issues, but can also increase sporadic unhealthy responses.
1605    ///
1606    /// Defaults to `3000`` (3 seconds).
1607    pub refresh_interval_ms: u64,
1608    /// Maximum memory watermark in bytes.
1609    ///
1610    /// By default, there is no absolute limit set and the watermark
1611    /// is only controlled by setting [`Self::max_memory_percent`].
1612    pub max_memory_bytes: Option<ByteSize>,
1613    /// Maximum memory watermark as a percentage of maximum system memory.
1614    ///
1615    /// Defaults to `0.95` (95%).
1616    pub max_memory_percent: f32,
1617    /// Health check probe timeout in milliseconds.
1618    ///
1619    /// Any probe exceeding the timeout will be considered failed.
1620    /// This limits the max execution time of Relay health checks.
1621    ///
1622    /// Defaults to 900 milliseconds.
1623    pub probe_timeout_ms: u64,
1624    /// The refresh frequency of memory stats which are used to poll memory
1625    /// usage of Relay.
1626    ///
1627    /// The implementation of memory stats guarantees that the refresh will happen at
1628    /// least every `x` ms since memory readings are lazy and are updated only if needed.
1629    pub memory_stat_refresh_frequency_ms: u64,
1630}
1631
1632impl Default for Health {
1633    fn default() -> Self {
1634        Self {
1635            refresh_interval_ms: 3000,
1636            max_memory_bytes: None,
1637            max_memory_percent: 0.95,
1638            probe_timeout_ms: 900,
1639            memory_stat_refresh_frequency_ms: 100,
1640        }
1641    }
1642}
1643
1644/// COGS configuration.
1645#[derive(Serialize, Deserialize, Debug, Clone)]
1646#[serde(default)]
1647pub struct Cogs {
1648    /// Maximium amount of COGS measurements allowed to backlog.
1649    ///
1650    /// Any additional COGS measurements recorded will be dropped.
1651    ///
1652    /// Defaults to `10_000`.
1653    pub max_queue_size: u64,
1654    /// Relay COGS resource id.
1655    ///
1656    /// All Relay related COGS measurements are emitted with this resource id.
1657    ///
1658    /// Defaults to `relay_service`.
1659    pub relay_resource_id: String,
1660}
1661
1662impl Default for Cogs {
1663    fn default() -> Self {
1664        Self {
1665            max_queue_size: 10_000,
1666            relay_resource_id: "relay_service".to_owned(),
1667        }
1668    }
1669}
1670
1671/// Configuration for the upload service.
1672#[derive(Debug, Clone, Serialize, Deserialize)]
1673#[serde(default)]
1674pub struct Upload {
1675    /// Maximum number of uploads that the service accepts.
1676    ///
1677    /// Additional uploads will be rejected.
1678    pub max_concurrent_requests: usize,
1679    /// Maximum time spent trying to upload, in seconds.
1680    pub timeout: u64,
1681    /// The maximum time between creating the upload and uploading the data / the attachment placeholder.
1682    ///
1683    /// In seconds.
1684    pub max_age: i64,
1685
1686    /// Credentials used for signing & verifying upload locations.
1687    ///
1688    /// If omitted, relay's default [`Credentials`] are used.
1689    pub credentials: Option<UploadCredentials>,
1690}
1691
1692impl Default for Upload {
1693    fn default() -> Self {
1694        Self {
1695            max_concurrent_requests: 100,
1696            timeout: 5 * 60,  // five minutes
1697            max_age: 60 * 60, // 1h
1698            credentials: None,
1699        }
1700    }
1701}
1702
1703/// Credentials used for signing & verifying upload locations.
1704#[derive(Clone, Serialize, Deserialize)]
1705pub struct UploadCredentials {
1706    /// Key used to sign upload locations.
1707    #[cfg(feature = "processing")]
1708    pub signing_key: SecretKey,
1709
1710    /// Key used to verify upload locations.
1711    pub verification_key: PublicKey,
1712}
1713
1714impl fmt::Debug for UploadCredentials {
1715    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1716        let Self {
1717            #[cfg(feature = "processing")]
1718                signing_key: _,
1719            verification_key,
1720        } = self;
1721        let mut b = f.debug_struct("UploadCredentials");
1722        #[cfg(feature = "processing")]
1723        b.field("signing_key", &"[redacted]");
1724        b.field("verification_key", verification_key).finish()
1725    }
1726}
1727
1728/// All configuration values that can be deserialized from `config.yml`.
1729#[derive(Serialize, Deserialize, Debug, Default, Clone)]
1730#[serde(default)]
1731#[allow(missing_docs)]
1732pub struct ConfigValues {
1733    pub relay: Relay,
1734    pub http: Http,
1735    pub cache: Cache,
1736    pub spool: Spool,
1737    pub limits: Limits,
1738    pub logging: relay_log::LogConfig,
1739    pub routing: Routing,
1740    pub metrics: Metrics,
1741    pub sentry: relay_log::SentryConfig,
1742    pub processing: Processing,
1743    pub outcomes: Outcomes,
1744    pub aggregator: AggregatorServiceConfig,
1745    pub secondary_aggregators: Vec<ScopedAggregatorConfig>,
1746    pub auth: AuthConfig,
1747    pub geoip: GeoIpConfig,
1748    pub normalization: Normalization,
1749    pub health: Health,
1750    pub cogs: Cogs,
1751    pub upload: Upload,
1752}
1753
1754impl ConfigObject for ConfigValues {
1755    fn format() -> ConfigFormat {
1756        ConfigFormat::Yaml
1757    }
1758
1759    fn name() -> &'static str {
1760        "config"
1761    }
1762}
1763
1764#[derive(Default, Clone)]
1765struct ConfigInner {
1766    /// Relay's config values.
1767    values: ConfigValues,
1768    /// Configured Relay credentials.
1769    ///
1770    /// Credentials may be missing for proxy mode.
1771    credentials: Option<Credentials>,
1772}
1773
1774impl ConfigInner {
1775    fn apply_overrides(&mut self, overrides: &OverridableConfig) -> anyhow::Result<()> {
1776        if let Some(log_level) = &overrides.log_level {
1777            self.values.logging.level = log_level.parse()?;
1778        }
1779
1780        if let Some(log_format) = &overrides.log_format {
1781            self.values.logging.format = log_format.parse()?;
1782        }
1783
1784        let relay = &mut self.values.relay;
1785        if let Some(mode) = &overrides.mode {
1786            relay.mode = mode
1787                .parse::<RelayMode>()
1788                .with_context(|| ConfigError::field("mode"))?;
1789        }
1790        if let Some(deployment) = &overrides.instance {
1791            relay.instance = deployment
1792                .parse::<RelayInstance>()
1793                .with_context(|| ConfigError::field("deployment"))?;
1794        }
1795        if let Some(upstream) = &overrides.upstream {
1796            relay.upstream = upstream
1797                .parse::<UpstreamDescriptor>()
1798                .with_context(|| ConfigError::field("upstream"))?;
1799        } else if let Some(upstream_dsn) = &overrides.upstream_dsn {
1800            relay.upstream = upstream_dsn
1801                .parse::<Dsn>()
1802                .map(|dsn| UpstreamDescriptor::from_dsn(&dsn))
1803                .with_context(|| ConfigError::field("upstream_dsn"))?;
1804        }
1805        if let Some(host) = &overrides.host {
1806            relay.host = host
1807                .parse::<IpAddr>()
1808                .with_context(|| ConfigError::field("host"))?;
1809        }
1810        if let Some(port) = &overrides.port {
1811            relay.port = port
1812                .as_str()
1813                .parse()
1814                .with_context(|| ConfigError::field("port"))?;
1815        }
1816
1817        let processing = &mut self.values.processing;
1818        if let Some(enabled) = &overrides.processing {
1819            match enabled.to_lowercase().as_str() {
1820                "true" | "1" => processing.enabled = true,
1821                "false" | "0" | "" => processing.enabled = false,
1822                _ => return Err(ConfigError::field("processing").into()),
1823            }
1824        }
1825        if let Some(redis) = overrides.redis_url.clone() {
1826            processing.redis = Some(RedisConfigs::Unified(RedisConfig::single(redis)))
1827        }
1828        if let Some(kafka_url) = overrides.kafka_url.clone() {
1829            let existing = processing
1830                .kafka_config
1831                .iter_mut()
1832                .find(|e| e.name == "bootstrap.servers");
1833
1834            if let Some(config_param) = existing {
1835                config_param.value = kafka_url;
1836            } else {
1837                self.values.processing.kafka_config.push(KafkaConfigParam {
1838                    name: "bootstrap.servers".to_owned(),
1839                    value: kafka_url,
1840                })
1841            }
1842        }
1843
1844        if overrides.outcome_source.is_some() {
1845            self.values.outcomes.source = overrides.outcome_source.clone();
1846        }
1847
1848        if let Some(shutdown_timeout) = &overrides.shutdown_timeout
1849            && let Ok(shutdown_timeout) = shutdown_timeout.parse::<u64>()
1850        {
1851            self.values.limits.shutdown_timeout = shutdown_timeout;
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    /// The maximum number of seconds to wait for pending envelopes after receiving a shutdown
2790    /// signal.
2791    pub fn shutdown_timeout(&self) -> Duration {
2792        Duration::from_secs(self.inner.values.limits.shutdown_timeout)
2793    }
2794
2795    /// Returns the server keep-alive timeout in seconds.
2796    ///
2797    /// By default keep alive is set to a 5 seconds.
2798    pub fn keepalive_timeout(&self) -> Duration {
2799        Duration::from_secs(self.inner.values.limits.keepalive_timeout)
2800    }
2801
2802    /// Returns the server idle timeout in seconds.
2803    pub fn idle_timeout(&self) -> Option<Duration> {
2804        self.inner
2805            .values
2806            .limits
2807            .idle_timeout
2808            .map(Duration::from_secs)
2809    }
2810
2811    /// Returns the maximum connections.
2812    pub fn max_connections(&self) -> Option<usize> {
2813        self.inner.values.limits.max_connections
2814    }
2815
2816    /// TCP listen backlog to configure on Relay's listening socket.
2817    pub fn tcp_listen_backlog(&self) -> u32 {
2818        self.inner.values.limits.tcp_listen_backlog
2819    }
2820
2821    /// Returns the number of cores to use for thread pools.
2822    pub fn cpu_concurrency(&self) -> usize {
2823        self.inner.values.limits.max_thread_count
2824    }
2825
2826    /// Returns the number of tasks that can run concurrently in the worker pool.
2827    pub fn pool_concurrency(&self) -> usize {
2828        self.inner.values.limits.max_pool_concurrency
2829    }
2830
2831    /// Returns the maximum size of a project config query.
2832    pub fn query_batch_size(&self) -> usize {
2833        self.inner.values.cache.batch_size
2834    }
2835
2836    /// True if the Relay should do processing.
2837    pub fn processing_enabled(&self) -> bool {
2838        self.inner.values.processing.enabled
2839    }
2840
2841    /// Level of normalization for Relay to apply to incoming data.
2842    pub fn normalization_level(&self) -> NormalizationLevel {
2843        self.inner.values.normalization.level
2844    }
2845
2846    /// The path to the GeoIp database required for event processing.
2847    pub fn geoip_path(&self) -> Option<&Path> {
2848        self.inner.values.geoip.path.as_deref().or(self
2849            .inner
2850            .values
2851            .processing
2852            .geoip_path
2853            .as_deref())
2854    }
2855
2856    /// Maximum future timestamp of ingested data.
2857    ///
2858    /// Events past this timestamp will be adjusted to `now()`. Sessions will be dropped.
2859    pub fn max_secs_in_future(&self) -> i64 {
2860        self.inner.values.processing.max_secs_in_future.into()
2861    }
2862
2863    /// Maximum age of ingested sessions. Older sessions will be dropped.
2864    pub fn max_session_secs_in_past(&self) -> i64 {
2865        self.inner.values.processing.max_session_secs_in_past.into()
2866    }
2867
2868    /// Configuration name and list of Kafka configuration parameters for a given topic.
2869    pub fn kafka_configs(
2870        &self,
2871        topic: KafkaTopic,
2872    ) -> Result<KafkaTopicConfig<'_>, KafkaConfigError> {
2873        self.inner
2874            .values
2875            .processing
2876            .topics
2877            .get(topic)
2878            .kafka_configs(
2879                &self.inner.values.processing.kafka_config,
2880                &self.inner.values.processing.secondary_kafka_configs,
2881            )
2882    }
2883
2884    /// Whether to validate the topics against Kafka.
2885    pub fn kafka_validate_topics(&self) -> bool {
2886        self.inner.values.processing.kafka_validate_topics
2887    }
2888
2889    /// Upper bound on the random delay before a Kafka producer swaps its client.
2890    pub fn reloading_producer_jitter(&self) -> Duration {
2891        Duration::from_secs(self.inner.values.processing.reloading_producer_jitter_secs)
2892    }
2893
2894    /// Builds the Kafka config blob describing every configured topic.
2895    ///
2896    /// # This is a stand-in
2897    ///
2898    /// The blob is meant to be opaque to Relay: one is published per region covering every
2899    /// cluster and topic, and Relay passes the bytes to Arroyo without interpreting them. That
2900    /// delivery channel does not yet exist, so this builds a blob out of Relay's own
2901    /// `kafka_config`, `secondary_kafka_configs` and `topics` instead.
2902    pub fn kafka_config_blob(&self) -> Result<Vec<u8>, KafkaConfigError> {
2903        // Sorted throughout, so an unchanged config always serializes to the same bytes and the
2904        // caller can skip pushing by comparing them.
2905        let mut clusters = BTreeMap::new();
2906        let mut topics = BTreeMap::new();
2907
2908        // A topic without a `config` uses the default `kafka_config`. The blob has no notion of
2909        // a default, so that becomes a cluster under a name derived to not collide with any
2910        // `secondary_kafka_configs` entry the user may have written.
2911        let default_cluster = default_cluster_name(&self.inner.values.processing);
2912
2913        for topic in KafkaTopic::iter() {
2914            let topic_config = self.kafka_configs(*topic)?;
2915
2916            for params in topic_config.topics() {
2917                let cluster_name = params.config_name.unwrap_or(&default_cluster);
2918
2919                let config: BTreeMap<_, _> = params
2920                    .params
2921                    .iter()
2922                    .map(|param| (param.name.as_str(), param.value.as_str()))
2923                    .collect();
2924
2925                clusters.insert(
2926                    cluster_name.to_owned(),
2927                    serde_json::json!({ "config": config }),
2928                );
2929
2930                // Arroyo keys the blob by logical topic and maps it to one physical topic. Relay's
2931                // sharded topics are one logical topic to many physical ones, which Arroyo cannot
2932                // express yet, so each physical topic is its own entry and maps to itself.
2933                //
2934                // That also means one topic name cannot point at two clusters.
2935                let entry = serde_json::json!({ "physical_topics": [{ "cluster": cluster_name }] });
2936                match topics.entry(params.topic_name.clone()) {
2937                    Entry::Vacant(vacant) => {
2938                        vacant.insert(entry);
2939                    }
2940                    Entry::Occupied(occupied) if *occupied.get() != entry => {
2941                        return Err(KafkaConfigError::AmbiguousTopic(params.topic_name.clone()));
2942                    }
2943                    Entry::Occupied(_) => {}
2944                }
2945            }
2946        }
2947
2948        // Serializing maps of strings cannot fail.
2949        Ok(serde_json::to_vec(&serde_json::json!({
2950            "clusters": clusters,
2951            "topics": topics,
2952        }))
2953        .expect("kafka config blob is serializable"))
2954    }
2955
2956    /// All unused but configured topic assignments.
2957    pub fn unused_topic_assignments(&self) -> &relay_kafka::Unused {
2958        &self.inner.values.processing.topics.unused
2959    }
2960
2961    /// Configuration of the objectstore service.
2962    pub fn objectstore(&self) -> &ObjectstoreServiceConfig {
2963        &self.inner.values.processing.objectstore
2964    }
2965
2966    /// Configuration of the upload service.
2967    pub fn upload(&self) -> &Upload {
2968        &self.inner.values.upload
2969    }
2970
2971    /// Returns the key used to sign upload locations.
2972    #[cfg(feature = "processing")]
2973    pub fn upload_signing_key(&self) -> Option<&SecretKey> {
2974        self.upload()
2975            .credentials
2976            .as_ref()
2977            .map(|c| &c.signing_key)
2978            .or(self.credentials().map(|c| &c.secret_key))
2979    }
2980
2981    /// Returns the key used to verify upload locations.
2982    #[cfg(feature = "processing")]
2983    pub fn upload_verification_key(&self) -> Option<&PublicKey> {
2984        self.upload()
2985            .credentials
2986            .as_ref()
2987            .map(|c| &c.verification_key)
2988            .or(self.credentials().map(|c| &c.public_key))
2989    }
2990
2991    /// Redis servers to connect to for project configs, rate limiting, and metrics metadata.
2992    pub fn redis(&self) -> Option<RedisConfigsRef<'_>> {
2993        let redis_configs = self.inner.values.processing.redis.as_ref()?;
2994
2995        Some(build_redis_configs(
2996            redis_configs,
2997            self.cpu_concurrency() as u32,
2998            self.pool_concurrency() as u32,
2999        ))
3000    }
3001
3002    /// Chunk size of attachments in bytes.
3003    pub fn attachment_chunk_size(&self) -> usize {
3004        self.inner
3005            .values
3006            .processing
3007            .attachment_chunk_size
3008            .as_bytes()
3009    }
3010
3011    /// Maximum metrics batch size in bytes.
3012    pub fn metrics_max_batch_size_bytes(&self) -> usize {
3013        self.inner.values.aggregator.max_flush_bytes
3014    }
3015
3016    /// Default prefix to use when looking up project configs in Redis. This is only done when
3017    /// Relay is in processing mode.
3018    pub fn projectconfig_cache_prefix(&self) -> &str {
3019        &self.inner.values.processing.projectconfig_cache_prefix
3020    }
3021
3022    /// Maximum rate limit to report to clients in seconds.
3023    pub fn max_rate_limit(&self) -> Option<u64> {
3024        self.inner.values.processing.max_rate_limit.map(u32::into)
3025    }
3026
3027    /// Amount of remaining quota which is cached in memory.
3028    pub fn quota_cache_ratio(&self) -> Option<f32> {
3029        self.inner.values.processing.quota_cache_ratio
3030    }
3031
3032    /// Maximum limit (ratio) for the in memory quota cache.
3033    pub fn quota_cache_max(&self) -> Option<f32> {
3034        self.inner.values.processing.quota_cache_max
3035    }
3036
3037    /// Interval to refresh internal health checks.
3038    pub fn health_refresh_interval(&self) -> Duration {
3039        Duration::from_millis(self.inner.values.health.refresh_interval_ms)
3040    }
3041
3042    /// Maximum memory watermark in bytes.
3043    pub fn health_max_memory_watermark_bytes(&self) -> u64 {
3044        self.inner
3045            .values
3046            .health
3047            .max_memory_bytes
3048            .as_ref()
3049            .map_or(u64::MAX, |b| b.as_bytes() as u64)
3050    }
3051
3052    /// Maximum memory watermark as a percentage of maximum system memory.
3053    pub fn health_max_memory_watermark_percent(&self) -> f32 {
3054        self.inner.values.health.max_memory_percent
3055    }
3056
3057    /// Health check probe timeout.
3058    pub fn health_probe_timeout(&self) -> Duration {
3059        Duration::from_millis(self.inner.values.health.probe_timeout_ms)
3060    }
3061
3062    /// Refresh frequency for polling new memory stats.
3063    pub fn memory_stat_refresh_frequency_ms(&self) -> u64 {
3064        self.inner.values.health.memory_stat_refresh_frequency_ms
3065    }
3066
3067    /// Maximum amount of COGS measurements buffered in memory.
3068    pub fn cogs_max_queue_size(&self) -> u64 {
3069        self.inner.values.cogs.max_queue_size
3070    }
3071
3072    /// Resource ID to use for Relay COGS measurements.
3073    pub fn cogs_relay_resource_id(&self) -> &str {
3074        &self.inner.values.cogs.relay_resource_id
3075    }
3076
3077    /// Returns configuration for the default metrics aggregator.
3078    pub fn default_aggregator_config(&self) -> &AggregatorServiceConfig {
3079        &self.inner.values.aggregator
3080    }
3081
3082    /// Returns configuration for non-default metrics aggregator.
3083    pub fn secondary_aggregator_configs(&self) -> &Vec<ScopedAggregatorConfig> {
3084        &self.inner.values.secondary_aggregators
3085    }
3086
3087    /// Returns aggregator config for a given metrics namespace.
3088    pub fn aggregator_config_for(&self, namespace: MetricNamespace) -> &AggregatorServiceConfig {
3089        for entry in &self.inner.values.secondary_aggregators {
3090            if entry.condition.matches(Some(namespace)) {
3091                return &entry.config;
3092            }
3093        }
3094        &self.inner.values.aggregator
3095    }
3096
3097    /// Return the statically configured Relays.
3098    pub fn static_relays(&self) -> &HashMap<RelayId, RelayInfo> {
3099        &self.inner.values.auth.static_relays
3100    }
3101
3102    /// Returns the max age a signature is considered valid, in seconds.
3103    pub fn signature_max_age(&self) -> Duration {
3104        Duration::from_secs(self.inner.values.auth.signature_max_age)
3105    }
3106
3107    /// Returns `true` if unknown items should be accepted and forwarded.
3108    pub fn accept_unknown_items(&self) -> bool {
3109        let forward = self.inner.values.routing.accept_unknown_items;
3110        forward.unwrap_or_else(|| !self.processing_enabled())
3111    }
3112}
3113
3114impl fmt::Debug for ConfigSnapshot {
3115    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3116        f.debug_struct("ConfigSnapshot")
3117            .field("values", &self.inner.values)
3118            .finish()
3119    }
3120}
3121
3122#[cfg(test)]
3123mod tests {
3124    use super::*;
3125
3126    #[test]
3127    fn test_http_encoding_parse_strict() {
3128        for (value, expected) in [
3129            ("identity", Some(HttpEncoding::Identity)),
3130            ("gzip", Some(HttpEncoding::Gzip)),
3131            ("deflate", Some(HttpEncoding::Deflate)),
3132            ("br", Some(HttpEncoding::Br)),
3133            ("zstd", Some(HttpEncoding::Zstd)),
3134            ("", None),
3135            ("unknown", None),
3136            ("x-gzip", None),
3137            ("GZIP", None),
3138            (" gzip ", None),
3139            ("zstd, gzip", None),
3140        ] {
3141            assert_eq!(HttpEncoding::parse_strict(value), expected, "{value:?}");
3142        }
3143    }
3144
3145    #[cfg(feature = "processing")]
3146    #[test]
3147    fn test_upload_secret_key_from_file() {
3148        let path = env::temp_dir().join(Uuid::new_v4().to_string());
3149        fs::create_dir(&path).unwrap();
3150        fs::write(
3151            path.join("my_secret.txt"),
3152            "U3LSQM5NorvgnoYHW_aZpc_43nuuh3lhs3zjjcBwaks",
3153        )
3154        .unwrap();
3155        fs::write(
3156            ConfigValues::path(&path),
3157            r#"
3158    upload:
3159        credentials:
3160            signing_key: ${file:my_secret.txt}
3161            verification_key: "VNS8haF0VTnuMMDR2t-f7AgnmUcXmcdzV3SVksSk34s""#,
3162        )
3163        .unwrap();
3164
3165        let config = Config::from_path(&path).unwrap().current();
3166
3167        fs::remove_dir_all(path).unwrap();
3168
3169        let signing_key = &config.upload().credentials.as_ref().unwrap().signing_key;
3170        assert_eq!(
3171            signing_key.to_string(),
3172            "U3LSQM5NorvgnoYHW_aZpc_43nuuh3lhs3zjjcBwaks"
3173        );
3174    }
3175
3176    #[test]
3177    fn test_emit_outcomes() {
3178        for (serialized, deserialized) in &[
3179            ("true", EmitOutcomes::AsOutcomes),
3180            ("false", EmitOutcomes::None),
3181            ("\"as_client_reports\"", EmitOutcomes::AsClientReports),
3182        ] {
3183            let value: EmitOutcomes = serde_json::from_str(serialized).unwrap();
3184            assert_eq!(value, *deserialized);
3185            assert_eq!(serde_json::to_string(&value).unwrap(), *serialized);
3186        }
3187    }
3188
3189    #[test]
3190    fn test_emit_outcomes_invalid() {
3191        assert!(serde_json::from_str::<EmitOutcomes>("asdf").is_err());
3192    }
3193
3194    /// Builds a config from YAML under `processing`.
3195    #[cfg(feature = "processing")]
3196    fn processing_config(yaml: &str) -> Config {
3197        let path = env::temp_dir().join(Uuid::new_v4().to_string());
3198        fs::create_dir(&path).unwrap();
3199        fs::write(ConfigValues::path(&path), yaml).unwrap();
3200        Config::from_path(&path).unwrap()
3201    }
3202
3203    /// A generated blob must resolve to the same broker params Relay would have built directly.
3204    #[cfg(feature = "processing")]
3205    #[test]
3206    fn test_kafka_config_blob_round_trips() {
3207        use sentry_arroyo::backends::kafka::config_blob::{ConfigBlob, ProducerSelector};
3208
3209        // Covers sharding, a secondary cluster, and a secondary config named `default`.
3210        let config = processing_config(
3211            r#"
3212processing:
3213  enabled: true
3214  kafka_config:
3215    - {name: "bootstrap.servers", value: "primary:9092"}
3216    - {name: "compression.type", value: "lz4"}
3217  secondary_kafka_configs:
3218    default:
3219      - {name: "bootstrap.servers", value: "impostor:9092"}
3220  topics:
3221    ingest-events: ["events-1", "events-2"]
3222    ingest-metrics:
3223      name: "metrics-topic"
3224      config: "default"
3225"#,
3226        );
3227        let config = config.current();
3228
3229        let blob = config.kafka_config_blob().unwrap();
3230        let parsed = ConfigBlob::parse(&blob).unwrap();
3231
3232        let resolve = |topic: &str| {
3233            let resolved = parsed
3234                .producer_config(&ProducerSelector::new(topic, "relay"))
3235                .unwrap_or_else(|_| panic!("{topic} is missing from the blob"));
3236
3237            // Each entry must produce to the topic it is keyed by.
3238            assert_eq!(resolved.physical_topic.as_str(), topic);
3239
3240            resolved
3241                .config
3242                .config_map()
3243                .iter()
3244                // Arroyo adds these itself when building a producer config.
3245                .filter(|(key, _)| !matches!(key.as_str(), "statistics.interval.ms" | "client.id"))
3246                .map(|(key, value)| (key.clone(), value.clone()))
3247                .collect::<BTreeMap<_, _>>()
3248        };
3249
3250        for (topic, physical) in [
3251            (KafkaTopic::Events, ["events-1", "events-2"].as_slice()),
3252            (KafkaTopic::MetricsSessions, ["metrics-topic"].as_slice()),
3253        ] {
3254            let params = config.kafka_configs(topic).unwrap();
3255
3256            for (shard, physical) in params.topics().iter().zip(physical) {
3257                let expected: BTreeMap<_, _> = shard
3258                    .params
3259                    .iter()
3260                    .map(|param| (param.name.clone(), param.value.clone()))
3261                    .collect();
3262
3263                assert_eq!(
3264                    resolve(physical),
3265                    expected,
3266                    "{physical} resolved differently"
3267                );
3268            }
3269        }
3270
3271        // The secondary config named `default` must not have swallowed the anonymous one.
3272        assert_eq!(
3273            resolve("events-1").get("bootstrap.servers").unwrap(),
3274            "primary:9092"
3275        );
3276        assert_eq!(
3277            resolve("metrics-topic").get("bootstrap.servers").unwrap(),
3278            "impostor:9092"
3279        );
3280    }
3281
3282    /// Moving a topic to a different cluster must change the broker it resolves to.
3283    #[cfg(feature = "processing")]
3284    #[test]
3285    fn test_topic_can_move_between_clusters() {
3286        use sentry_arroyo::backends::kafka::config_blob::{ConfigBlob, ProducerSelector};
3287
3288        let resolve = |yaml: &str| {
3289            let config = processing_config(yaml);
3290            let blob = config.current().kafka_config_blob().unwrap();
3291            ConfigBlob::parse(&blob)
3292                .unwrap()
3293                .producer_config(&ProducerSelector::new("events-topic", "relay"))
3294                .unwrap()
3295                .config
3296                .get_config_value("bootstrap.servers")
3297                .unwrap()
3298                .clone()
3299        };
3300
3301        let before = resolve(
3302            r#"
3303processing:
3304  enabled: true
3305  kafka_config:
3306    - {name: "bootstrap.servers", value: "primary:9092"}
3307  secondary_kafka_configs:
3308    other:
3309      - {name: "bootstrap.servers", value: "other:9092"}
3310  topics:
3311    ingest-events: "events-topic"
3312"#,
3313        );
3314
3315        // Same physical topic, now pointed at the secondary cluster.
3316        let after = resolve(
3317            r#"
3318processing:
3319  enabled: true
3320  kafka_config:
3321    - {name: "bootstrap.servers", value: "primary:9092"}
3322  secondary_kafka_configs:
3323    other:
3324      - {name: "bootstrap.servers", value: "other:9092"}
3325  topics:
3326    ingest-events:
3327      name: "events-topic"
3328      config: "other"
3329"#,
3330        );
3331
3332        assert_eq!(before, "primary:9092");
3333        assert_eq!(after, "other:9092");
3334    }
3335
3336    /// The blob is keyed by topic name, so one name on two clusters cannot be expressed. That
3337    /// must fail loudly instead of sending one of the two to the wrong cluster.
3338    #[cfg(feature = "processing")]
3339    #[test]
3340    fn test_kafka_config_blob_rejects_topic_on_two_clusters() {
3341        let config = processing_config(
3342            r#"
3343processing:
3344  enabled: true
3345  kafka_config:
3346    - {name: "bootstrap.servers", value: "primary:9092"}
3347  secondary_kafka_configs:
3348    other:
3349      - {name: "bootstrap.servers", value: "other:9092"}
3350  topics:
3351    outcomes:
3352      name: "outcomes-topic"
3353      config: "other"
3354    outcomes-billing: "outcomes-topic"
3355"#,
3356        );
3357
3358        assert!(matches!(
3359            config.current().kafka_config_blob(),
3360            Err(KafkaConfigError::AmbiguousTopic(topic)) if topic == "outcomes-topic"
3361        ));
3362    }
3363
3364    /// Broker settings reload; topic assignments do not, since producers hold theirs from
3365    /// startup.
3366    #[test]
3367    fn test_reload_takes_kafka_config_but_not_topics() {
3368        let mut current = ConfigValues::default();
3369        current.processing.kafka_config = vec![KafkaConfigParam {
3370            name: "bootstrap.servers".to_owned(),
3371            value: "old:9092".to_owned(),
3372        }];
3373        current.processing.topics.events = "old-topic".to_owned().into();
3374
3375        let mut other = ConfigValues::default();
3376        other.processing.kafka_config = vec![KafkaConfigParam {
3377            name: "bootstrap.servers".to_owned(),
3378            value: "new:9092".to_owned(),
3379        }];
3380        other.processing.topics.events = "new-topic".to_owned().into();
3381
3382        let mut current = ConfigInner {
3383            values: current,
3384            ..Default::default()
3385        };
3386        let other = ConfigInner {
3387            values: other,
3388            ..Default::default()
3389        };
3390
3391        assert!(current.reload_with(&other));
3392        assert_eq!(current.values.processing.kafka_config[0].value, "new:9092");
3393
3394        let assignment = format!("{:?}", current.values.processing.topics.events);
3395        assert!(
3396            assignment.contains("old-topic"),
3397            "topic assignment was reloaded, but the producers cannot pick it up: {assignment}"
3398        );
3399    }
3400}