-
Notifications
You must be signed in to change notification settings - Fork 92
/
config.rs
2071 lines (1842 loc) · 69.4 KB
/
config.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::collections::{BTreeMap, HashMap};
use std::convert::TryInto;
use std::env;
use std::fmt;
use std::fs;
use std::io;
use std::io::Write;
use std::net::{IpAddr, SocketAddr, ToSocketAddrs};
use std::path::{Path, PathBuf};
use std::str::FromStr;
use std::time::Duration;
use failure::{Backtrace, Context, Fail};
use serde::de::{Unexpected, Visitor};
use serde::{de::DeserializeOwned, Deserialize, Deserializer, Serialize, Serializer};
use relay_auth::{generate_key_pair, generate_relay_id, PublicKey, RelayId, SecretKey};
use relay_common::{Dsn, Uuid};
use relay_metrics::AggregatorConfig;
use relay_redis::RedisConfig;
use crate::byte_size::ByteSize;
use crate::upstream::UpstreamDescriptor;
const DEFAULT_NETWORK_OUTAGE_GRACE_PERIOD: u64 = 10;
/// Defines the source of a config error
#[derive(Debug)]
enum ConfigErrorSource {
/// An error occurring independently.
None,
/// An error originating from a configuration file.
File(PathBuf),
/// An error originating in a field override (an env var, or a CLI parameter).
FieldOverride(String),
}
impl Default for ConfigErrorSource {
fn default() -> Self {
Self::None
}
}
/// Indicates config related errors.
#[derive(Debug)]
pub struct ConfigError {
source: ConfigErrorSource,
inner: Context<ConfigErrorKind>,
}
impl ConfigError {
#[inline]
fn new<C>(context: C) -> Self
where
C: Into<Context<ConfigErrorKind>>,
{
Self {
source: ConfigErrorSource::None,
inner: context.into(),
}
}
#[inline]
fn wrap<E>(inner: E, kind: ConfigErrorKind) -> Self
where
E: Fail,
{
Self::new(inner.context(kind))
}
#[inline]
fn for_field<E>(inner: E, field: &'static str) -> Self
where
E: Fail,
{
Self::wrap(inner, ConfigErrorKind::InvalidValue).field(field)
}
#[inline]
fn file<P: AsRef<Path>>(mut self, p: P) -> Self {
self.source = ConfigErrorSource::File(p.as_ref().to_path_buf());
self
}
#[inline]
fn field(mut self, name: &'static str) -> Self {
self.source = ConfigErrorSource::FieldOverride(name.to_owned());
self
}
/// Returns the error kind of the error.
pub fn kind(&self) -> ConfigErrorKind {
*self.inner.get_context()
}
}
impl Fail for ConfigError {
fn cause(&self) -> Option<&dyn Fail> {
self.inner.cause()
}
fn backtrace(&self) -> Option<&Backtrace> {
self.inner.backtrace()
}
}
impl fmt::Display for ConfigError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.source {
ConfigErrorSource::None => self.inner.fmt(f),
ConfigErrorSource::File(file_name) => {
write!(f, "{} (file {})", self.inner, file_name.display())
}
ConfigErrorSource::FieldOverride(name) => write!(f, "{} (field {})", self.inner, name),
}
}
}
/// Indicates config related errors.
#[derive(Fail, Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub enum ConfigErrorKind {
/// Failed to open the file.
#[fail(display = "could not open config file")]
CouldNotOpenFile,
/// Failed to save a file.
#[fail(display = "could not write config file")]
CouldNotWriteFile,
/// Parsing YAML failed.
#[fail(display = "could not parse yaml config file")]
BadYaml,
/// Parsing JSON failed.
#[fail(display = "could not parse json config file")]
BadJson,
/// Invalid config value
#[fail(display = "invalid config value")]
InvalidValue,
/// The user attempted to run Relay with processing enabled, but uses a binary that was
/// compiled without the processing feature.
#[fail(display = "was not compiled with processing, cannot enable processing")]
ProcessingNotAvailable,
/// The user referenced a kafka config name that does not exist.
#[fail(display = "unknown kafka config name")]
UnknownKafkaConfigName,
}
enum ConfigFormat {
Yaml,
Json,
}
impl ConfigFormat {
pub fn extension(&self) -> &'static str {
match self {
ConfigFormat::Yaml => "yml",
ConfigFormat::Json => "json",
}
}
}
trait ConfigObject: DeserializeOwned + Serialize {
/// The format in which to serialize this configuration.
fn format() -> ConfigFormat;
/// The basename of the config file.
fn name() -> &'static str;
/// The full filename of the config file, including the file extension.
fn path(base: &Path) -> PathBuf {
base.join(format!("{}.{}", Self::name(), Self::format().extension()))
}
/// Loads the config file from a file within the given directory location.
fn load(base: &Path) -> Result<Self, ConfigError> {
let path = Self::path(base);
let f = fs::File::open(&path)
.map_err(|e| ConfigError::wrap(e, ConfigErrorKind::CouldNotOpenFile).file(&path))?;
match Self::format() {
ConfigFormat::Yaml => serde_yaml::from_reader(io::BufReader::new(f))
.map_err(|e| ConfigError::wrap(e, ConfigErrorKind::BadYaml).file(&path)),
ConfigFormat::Json => serde_json::from_reader(io::BufReader::new(f))
.map_err(|e| ConfigError::wrap(e, ConfigErrorKind::BadJson).file(&path)),
}
}
/// Writes the configuration object to the given writer.
fn write<W: Write>(&self, writer: &mut W) -> Result<(), ConfigError> {
match Self::format() {
ConfigFormat::Yaml => serde_yaml::to_writer(writer, self)
.map_err(|e| ConfigError::wrap(e, ConfigErrorKind::CouldNotWriteFile)),
ConfigFormat::Json => serde_json::to_writer_pretty(writer, self)
.map_err(|e| ConfigError::wrap(e, ConfigErrorKind::CouldNotWriteFile)),
}
}
/// Writes the configuration to a file within the given directory location.
fn save(&self, base: &Path) -> Result<(), ConfigError> {
let path = Self::path(base);
let mut options = fs::OpenOptions::new();
options.write(true).truncate(true).create(true);
// Remove all non-user permissions for the newly created file
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let mut f = options
.open(&path)
.map_err(|e| ConfigError::wrap(e, ConfigErrorKind::CouldNotWriteFile).file(&path))?;
self.write(&mut f).map_err(|e| e.file(&path))?;
f.write_all(b"\n").ok();
Ok(())
}
}
/// Structure used to hold information about configuration overrides via
/// CLI parameters or environment variables
#[derive(Debug, Default)]
pub struct OverridableConfig {
/// The operation mode of this relay.
pub mode: Option<String>,
/// The upstream relay or sentry instance.
pub upstream: Option<String>,
/// Alternate upstream provided through a Sentry DSN. Key and project will be ignored.
pub upstream_dsn: Option<String>,
/// The host the relay should bind to (network interface).
pub host: Option<String>,
/// The port to bind for the unencrypted relay HTTP server.
pub port: Option<String>,
/// "true" if processing is enabled "false" otherwise
pub processing: Option<String>,
/// the kafka bootstrap.servers configuration string
pub kafka_url: Option<String>,
/// the redis server url
pub redis_url: Option<String>,
/// The globally unique ID of the relay.
pub id: Option<String>,
/// The secret key of the relay
pub secret_key: Option<String>,
/// The public key of the relay
pub public_key: Option<String>,
/// Outcome source
pub outcome_source: Option<String>,
/// shutdown timeout
pub shutdown_timeout: Option<String>,
/// AWS Extensions API URL
pub aws_runtime_api: Option<String>,
}
/// The relay credentials
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq)]
pub struct Credentials {
/// The secret key of the relay
pub secret_key: SecretKey,
/// The public key of the relay
pub public_key: PublicKey,
/// The globally unique ID of the relay.
pub id: RelayId,
}
impl Credentials {
/// Generates new random credentials.
pub fn generate() -> Self {
relay_log::info!("generating new relay credentials");
let (sk, pk) = generate_key_pair();
Self {
secret_key: sk,
public_key: pk,
id: generate_relay_id(),
}
}
/// Serializes this configuration to JSON.
pub fn to_json_string(&self) -> Result<String, ConfigError> {
serde_json::to_string(self)
.map_err(|e| ConfigError::wrap(e, ConfigErrorKind::CouldNotWriteFile))
}
}
impl ConfigObject for Credentials {
fn format() -> ConfigFormat {
ConfigFormat::Json
}
fn name() -> &'static str {
"credentials"
}
}
/// Information on a downstream Relay.
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct RelayInfo {
/// The public key that this Relay uses to authenticate and sign requests.
pub public_key: PublicKey,
/// Marks an internal relay that has privileged access to more project configuration.
#[serde(default)]
pub internal: bool,
}
impl RelayInfo {
/// Creates a new RelayInfo
pub fn new(public_key: PublicKey) -> Self {
Self {
public_key,
internal: false,
}
}
}
/// The operation mode of a relay.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum RelayMode {
/// This relay acts as a proxy for all requests and events.
///
/// Events are normalized and rate limits from the upstream are enforced, but the relay will not
/// fetch project configurations from the upstream or perform PII stripping. All events are
/// accepted unless overridden on the file system.
Proxy,
/// This relay is configured statically in the file system.
///
/// Events are only accepted for projects configured statically in the file system. All other
/// events are rejected. If configured, PII stripping is also performed on those events.
Static,
/// Project configurations are managed by the upstream.
///
/// Project configurations are always fetched from the upstream, unless they are statically
/// overridden in the file system. This relay must be allowed in the upstream Sentry. This is
/// only possible, if the upstream is Sentry directly, or another managed Relay.
Managed,
/// Events are held in memory for inspection only.
///
/// This mode is used for testing sentry SDKs.
Capture,
}
impl fmt::Display for RelayMode {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
RelayMode::Proxy => write!(f, "proxy"),
RelayMode::Static => write!(f, "static"),
RelayMode::Managed => write!(f, "managed"),
RelayMode::Capture => write!(f, "capture"),
}
}
}
impl FromStr for RelayMode {
type Err = Context<&'static str>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"proxy" => Ok(RelayMode::Proxy),
"static" => Ok(RelayMode::Static),
"managed" => Ok(RelayMode::Managed),
"capture" => Ok(RelayMode::Capture),
_ => Err(Context::new(
"Relay mode must be one of: managed, static, proxy, capture",
)),
}
}
}
/// Returns `true` if this value is equal to `Default::default()`.
fn is_default<T: Default + PartialEq>(t: &T) -> bool {
*t == T::default()
}
/// Checks if we are running in docker.
fn is_docker() -> bool {
if fs::metadata("/.dockerenv").is_ok() {
return true;
}
fs::read_to_string("/proc/self/cgroup").map_or(false, |s| s.contains("/docker"))
}
/// Default value for the "bind" configuration.
fn default_host() -> IpAddr {
if is_docker() {
// Docker images rely on this service being exposed
"0.0.0.0".parse().unwrap()
} else {
"127.0.0.1".parse().unwrap()
}
}
/// Controls responses from the readiness health check endpoint based on authentication.
///
/// Independent of the the readiness condition, shutdown always switches Relay into unready state.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum ReadinessCondition {
/// (default) Relay is ready when authenticated and connected to the upstream.
///
/// Before authentication has succeeded and during network outages, Relay responds as not ready.
/// Relay reauthenticates based on the `http.auth_interval` parameter. During reauthentication,
/// Relay remains ready until authentication fails.
///
/// Authentication is only required for Relays in managed mode. Other Relays will only check for
/// network outages.
Authenticated,
/// Relay reports readiness regardless of the authentication and networking state.
Always,
}
impl Default for ReadinessCondition {
fn default() -> Self {
Self::Authenticated
}
}
/// Relay specific configuration values.
#[derive(Serialize, Deserialize, Debug)]
#[serde(default)]
pub struct Relay {
/// The operation mode of this relay.
pub mode: RelayMode,
/// The upstream relay or sentry instance.
pub upstream: UpstreamDescriptor<'static>,
/// The host the relay should bind to (network interface).
pub host: IpAddr,
/// The port to bind for the unencrypted relay HTTP server.
pub port: u16,
/// Optional port to bind for the encrypted relay HTTPS server.
pub tls_port: Option<u16>,
/// The path to the identity (DER-encoded PKCS12) to use for TLS.
pub tls_identity_path: Option<PathBuf>,
/// Password for the PKCS12 archive.
pub tls_identity_password: Option<String>,
/// Always override project IDs from the URL and DSN with the identifier used at the upstream.
///
/// Enable this setting for Relays used to redirect traffic to a migrated Sentry instance.
/// Validation of project identifiers can be safely skipped in these cases.
#[serde(skip_serializing_if = "is_default")]
pub override_project_ids: bool,
}
impl Default for Relay {
fn default() -> Self {
Relay {
mode: RelayMode::Managed,
upstream: "https://sentry.io/".parse().unwrap(),
host: default_host(),
port: 3000,
tls_port: None,
tls_identity_path: None,
tls_identity_password: None,
override_project_ids: false,
}
}
}
/// Control the metrics.
#[derive(Serialize, Deserialize, Debug)]
#[serde(default)]
struct Metrics {
/// Hostname and port of the statsd server.
///
/// Defaults to `None`.
statsd: Option<String>,
/// Common prefix that should be added to all metrics.
///
/// Defaults to `"sentry.relay"`.
prefix: String,
/// Default tags to apply to all metrics.
default_tags: BTreeMap<String, String>,
/// Tag name to report the hostname to for each metric. Defaults to not sending such a tag.
hostname_tag: Option<String>,
/// Emitted metrics will be buffered to optimize performance.
///
/// Defaults to `true`.
buffering: bool,
/// Global sample rate for all emitted metrics between `0.0` and `1.0`.
///
/// For example, a value of `0.3` means that only 30% of the emitted metrics will be sent.
/// Defaults to `1.0` (100%).
sample_rate: f32,
}
impl Default for Metrics {
fn default() -> Self {
Metrics {
statsd: None,
prefix: "sentry.relay".into(),
default_tags: BTreeMap::new(),
hostname_tag: None,
buffering: true,
sample_rate: 1.0,
}
}
}
/// Controls various limits
#[derive(Serialize, Deserialize, Debug)]
#[serde(default)]
struct Limits {
/// How many requests can be sent concurrently from Relay to the upstream before Relay starts
/// buffering.
max_concurrent_requests: usize,
/// How many queries can be sent concurrently from Relay to the upstream before Relay starts
/// buffering.
///
/// The concurrency of queries is additionally constrained by `max_concurrent_requests`.
max_concurrent_queries: usize,
/// The maximum payload size for events.
max_event_size: ByteSize,
/// The maximum size for each attachment.
max_attachment_size: ByteSize,
/// The maximum combined size for all attachments in an envelope or request.
max_attachments_size: ByteSize,
/// The maximum combined size for all client reports in an envelope or request.
max_client_reports_size: ByteSize,
/// The maximum payload size for an entire envelopes. Individual limits still apply.
max_envelope_size: ByteSize,
/// The maximum number of session items per envelope.
max_session_count: usize,
/// The maximum payload size for general API requests.
max_api_payload_size: ByteSize,
/// The maximum payload size for file uploads and chunks.
max_api_file_upload_size: ByteSize,
/// The maximum payload size for chunks
max_api_chunk_upload_size: ByteSize,
/// The maximum payload size for a profile
max_profile_size: ByteSize,
/// The maximum number of threads to spawn for CPU and web work, each.
///
/// The total number of threads spawned will roughly be `2 * max_thread_count + 1`. Defaults to
/// the number of logical CPU cores on the host.
max_thread_count: usize,
/// The maximum number of seconds a query is allowed to take across retries. Individual requests
/// have lower timeouts. Defaults to 30 seconds.
query_timeout: u64,
/// The maximum number of connections to Relay that can be created at once.
max_connection_rate: usize,
/// The maximum number of pending connects to Relay. This corresponds to the backlog param of
/// `listen(2)` in POSIX.
max_pending_connections: i32,
/// The maximum number of open connections to Relay.
max_connections: usize,
/// The maximum number of seconds to wait for pending envelopes after receiving a shutdown
/// signal.
shutdown_timeout: u64,
}
impl Default for Limits {
fn default() -> Self {
Limits {
max_concurrent_requests: 100,
max_concurrent_queries: 5,
max_event_size: ByteSize::mebibytes(1),
max_attachment_size: ByteSize::mebibytes(100),
max_attachments_size: ByteSize::mebibytes(100),
max_client_reports_size: ByteSize::kibibytes(4),
max_envelope_size: ByteSize::mebibytes(100),
max_session_count: 100,
max_api_payload_size: ByteSize::mebibytes(20),
max_api_file_upload_size: ByteSize::mebibytes(40),
max_api_chunk_upload_size: ByteSize::mebibytes(100),
max_profile_size: ByteSize::mebibytes(50),
max_thread_count: num_cpus::get(),
query_timeout: 30,
max_connection_rate: 256,
max_pending_connections: 2048,
max_connections: 25_000,
shutdown_timeout: 10,
}
}
}
/// Controls traffic steering.
#[derive(Debug, Default, Deserialize, Serialize)]
#[serde(default)]
pub struct Routing {
/// Accept and forward unknown Envelope items to the upstream.
///
/// Forwarding unknown items should be enabled in most cases to allow proxying traffic for newer
/// SDK versions. The upstream in Sentry makes the final decision on which items are valid. If
/// this is disabled, just the unknown items are removed from Envelopes, and the rest is
/// processed as usual.
///
/// Defaults to `true` for all Relay modes other than processing mode. In processing mode, this
/// is disabled by default since the item cannot be handled.
accept_unknown_items: Option<bool>,
}
/// Http content encoding for both incoming and outgoing web requests.
#[derive(Clone, Copy, Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum HttpEncoding {
/// Identity function without no compression.
///
/// This is the default encoding and does not require the presence of the `content-encoding`
/// HTTP header.
Identity,
/// Compression using a [zlib](https://en.wikipedia.org/wiki/Zlib) structure with
/// [deflate](https://en.wikipedia.org/wiki/DEFLATE) encoding.
///
/// These structures are defined in [RFC 1950](https://datatracker.ietf.org/doc/html/rfc1950)
/// and [RFC 1951](https://datatracker.ietf.org/doc/html/rfc1951).
Deflate,
/// A format using the [Lempel-Ziv coding](https://en.wikipedia.org/wiki/LZ77_and_LZ78#LZ77)
/// (LZ77), with a 32-bit CRC.
///
/// This is the original format of the UNIX gzip program. The HTTP/1.1 standard also recommends
/// that the servers supporting this content-encoding should recognize `x-gzip` as an alias, for
/// compatibility purposes.
Gzip,
/// A format using the [Brotli](https://en.wikipedia.org/wiki/Brotli) algorithm.
Br,
}
impl HttpEncoding {
/// Parses a [`HttpEncoding`] from its `content-encoding` header value.
pub fn parse(str: &str) -> Self {
let str = str.trim();
if str.eq_ignore_ascii_case("br") {
Self::Br
} else if str.eq_ignore_ascii_case("gzip") || str.eq_ignore_ascii_case("x-gzip") {
Self::Gzip
} else if str.eq_ignore_ascii_case("deflate") {
Self::Deflate
} else {
Self::Identity
}
}
/// Returns the value for the `content-encoding` HTTP header.
///
/// Returns `None` for [`Identity`](Self::Identity), and `Some` for other encodings.
pub fn name(&self) -> Option<&'static str> {
match self {
Self::Identity => None,
Self::Deflate => Some("deflate"),
Self::Gzip => Some("gzip"),
Self::Br => Some("br"),
}
}
}
impl Default for HttpEncoding {
fn default() -> Self {
Self::Identity
}
}
/// Controls authentication with upstream.
#[derive(Serialize, Deserialize, Debug)]
#[serde(default)]
struct Http {
/// Timeout for upstream requests in seconds.
///
/// This timeout covers the time from sending the request until receiving response headers.
/// Neither the connection process and handshakes, nor reading the response body is covered in
/// this timeout.
timeout: u32,
/// Timeout for establishing connections with the upstream in seconds.
///
/// This includes SSL handshakes. Relay reuses connections when the upstream supports connection
/// keep-alive. Connections are retained for a maximum 75 seconds, or 15 seconds of inactivity.
connection_timeout: u32,
/// Maximum interval between failed request retries in seconds.
max_retry_interval: u32,
/// The custom HTTP Host header to send to the upstream.
host_header: Option<String>,
/// The interval in seconds at which Relay attempts to reauthenticate with the upstream server.
///
/// Re-authentication happens even when Relay is idle. If authentication fails, Relay reverts
/// back into startup mode and tries to establish a connection. During this time, incoming
/// envelopes will be buffered.
///
/// Defaults to `600` (10 minutes).
auth_interval: Option<u64>,
/// The maximum time of experiencing uninterrupted network failures until Relay considers that
/// it has encountered a network outage in seconds.
///
/// During a network outage relay will try to reconnect and will buffer all upstream messages
/// until it manages to reconnect.
outage_grace_period: u64,
/// Content encoding to apply to upstream store requests.
///
/// By default, Relay applies `gzip` content encoding to compress upstream requests. Compression
/// can be disabled to reduce CPU consumption, but at the expense of increased network traffic.
///
/// This setting applies to all store requests of SDK data, including events, transactions,
/// envelopes and sessions. At the moment, this does not apply to Relay's internal queries.
///
/// Available options are:
///
/// - `identity`: Disables compression.
/// - `deflate`: Compression using a zlib header with deflate encoding.
/// - `gzip` (default): Compression using gzip.
/// - `br`: Compression using the brotli algorithm.
encoding: HttpEncoding,
}
impl Default for Http {
fn default() -> Self {
Http {
timeout: 5,
connection_timeout: 3,
max_retry_interval: 60, // 1 minute
host_header: None,
auth_interval: Some(600), // 10 minutes
outage_grace_period: DEFAULT_NETWORK_OUTAGE_GRACE_PERIOD,
encoding: HttpEncoding::Gzip,
}
}
}
/// Controls internal caching behavior.
#[derive(Serialize, Deserialize, Debug)]
#[serde(default)]
struct Cache {
/// The cache timeout for project configurations in seconds.
project_expiry: u32,
/// Continue using project state this many seconds after cache expiry while a new state is
/// being fetched. This is added on top of `project_expiry` and `miss_expiry`. Default is 0.
project_grace_period: u32,
/// The cache timeout for downstream relay info (public keys) in seconds.
relay_expiry: u32,
/// Unused cache timeout for envelopes.
///
/// The envelope buffer is instead controlled by `envelope_buffer_size`, which controls the
/// maximum number of envelopes in the buffer. A time based configuration may be re-introduced
/// at a later point.
#[serde(alias = "event_expiry")]
envelope_expiry: u32,
/// The maximum amount of envelopes to queue before dropping them.
#[serde(alias = "event_buffer_size")]
envelope_buffer_size: u32,
/// The cache timeout for non-existing entries.
miss_expiry: u32,
/// The buffer timeout for batched queries before sending them upstream in ms.
batch_interval: u32,
/// The maximum number of project configs to fetch from Sentry at once. Defaults to 500.
///
/// `cache.batch_interval` controls how quickly batches are sent, this controls the batch size.
batch_size: usize,
/// Interval for watching local cache override files in seconds.
file_interval: u32,
/// Interval for evicting outdated project configs from memory.
eviction_interval: u32,
}
impl Default for Cache {
fn default() -> Self {
Cache {
project_expiry: 300, // 5 minutes
project_grace_period: 0,
relay_expiry: 3600, // 1 hour
envelope_expiry: 600, // 10 minutes
envelope_buffer_size: 1000,
miss_expiry: 60, // 1 minute
batch_interval: 100, // 100ms
batch_size: 500,
file_interval: 10, // 10 seconds
eviction_interval: 60, // 60 seconds
}
}
}
/// Define the topics over which Relay communicates with Sentry.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum KafkaTopic {
/// Simple events (without attachments) topic.
Events,
/// Complex events (with attachments) topic.
Attachments,
/// Transaction events topic.
Transactions,
/// Shared outcomes topic for Relay and Sentry.
Outcomes,
/// Override for billing critical outcomes.
OutcomesBilling,
/// Session health updates.
Sessions,
/// Any metric that is extracted from sessions.
MetricsSessions,
/// Any metric that is extracted from transactions.
MetricsTransactions,
/// Profiles
Profiles,
/// ReplayEvents, breadcrumb + session updates for replays
ReplayEvents,
/// ReplayRecordings, large blobs sent by the replay sdk
ReplayRecordings,
}
/// Configuration for topics.
#[derive(Serialize, Deserialize, Debug)]
#[serde(default)]
pub struct TopicAssignments {
/// Simple events topic name.
pub events: TopicAssignment,
/// Events with attachments topic name.
pub attachments: TopicAssignment,
/// Transaction events topic name.
pub transactions: TopicAssignment,
/// Outcomes topic name.
pub outcomes: TopicAssignment,
/// Outcomes topic name for billing critical outcomes. Defaults to the assignment of `outcomes`.
pub outcomes_billing: Option<TopicAssignment>,
/// Session health topic name.
pub sessions: TopicAssignment,
/// Default topic name for all aggregate metrics. Specialized topics for session-based and
/// transaction-based metrics can be configured via `metrics_sessions` and
/// `metrics_transactions` each.
pub metrics: TopicAssignment,
/// Topic name for metrics extracted from sessions. Defaults to the assignment of `metrics`.
pub metrics_sessions: Option<TopicAssignment>,
/// Topic name for metrics extracted from transactions. Defaults to the assignment of `metrics`.
pub metrics_transactions: Option<TopicAssignment>,
/// Stacktrace topic name
pub profiles: TopicAssignment,
/// Replay Events topic name.
pub replay_events: TopicAssignment,
/// Recordings topic name.
pub replay_recordings: TopicAssignment,
}
impl TopicAssignments {
/// Get a topic assignment by KafkaTopic value
pub fn get(&self, kafka_topic: KafkaTopic) -> &TopicAssignment {
match kafka_topic {
KafkaTopic::Attachments => &self.attachments,
KafkaTopic::Events => &self.events,
KafkaTopic::Transactions => &self.transactions,
KafkaTopic::Outcomes => &self.outcomes,
KafkaTopic::OutcomesBilling => self.outcomes_billing.as_ref().unwrap_or(&self.outcomes),
KafkaTopic::Sessions => &self.sessions,
KafkaTopic::MetricsSessions => self.metrics_sessions.as_ref().unwrap_or(&self.metrics),
KafkaTopic::MetricsTransactions => {
self.metrics_transactions.as_ref().unwrap_or(&self.metrics)
}
KafkaTopic::Profiles => &self.profiles,
KafkaTopic::ReplayEvents => &self.replay_events,
KafkaTopic::ReplayRecordings => &self.replay_recordings,
}
}
}
impl Default for TopicAssignments {
fn default() -> Self {
Self {
events: "ingest-events".to_owned().into(),
attachments: "ingest-attachments".to_owned().into(),
transactions: "ingest-transactions".to_owned().into(),
outcomes: "outcomes".to_owned().into(),
outcomes_billing: None,
sessions: "ingest-sessions".to_owned().into(),
metrics: "ingest-metrics".to_owned().into(),
metrics_sessions: None,
metrics_transactions: None,
profiles: "profiles".to_owned().into(),
replay_events: "ingest-replay-events".to_owned().into(),
replay_recordings: "ingest-replay-recordings".to_owned().into(),
}
}
}
/// Configuration for a "logical" topic/datasink that Relay should forward data into.
///
/// Can be either a string containing the kafka topic name to produce into (using the default
/// `kafka_config`), or an object containing keys `topic_name` and `kafka_config_name` for using a
/// custom kafka cluster.
///
/// See documentation for `secondary_kafka_configs` for more information.
#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
pub enum TopicAssignment {
/// String containing the kafka topic name. In this case the default kafka cluster configured
/// in `kafka_config` will be used.
Primary(String),
/// Object containing topic name and string identifier of one of the clusters configured in
/// `secondary_kafka_configs`. In this case that custom kafkaconfig will be used to produce
/// data to the given topic name.
Secondary {
/// The topic name to use.
#[serde(rename = "name")]
topic_name: String,
/// An identifier referencing one of the kafka configurations in `secondary_kafka_configs`.
#[serde(rename = "config")]
kafka_config_name: String,
},
}
impl From<String> for TopicAssignment {
fn from(topic_name: String) -> TopicAssignment {
TopicAssignment::Primary(topic_name)
}
}
impl TopicAssignment {
/// Get the topic name from this topic assignment.
fn topic_name(&self) -> &str {
match *self {
TopicAssignment::Primary(ref s) => s.as_str(),
TopicAssignment::Secondary { ref topic_name, .. } => topic_name.as_str(),
}
}
/// Get the name of the kafka config to use. `None` means default configuration.
fn kafka_config_name(&self) -> Option<&str> {
match *self {
TopicAssignment::Primary(_) => None,
TopicAssignment::Secondary {
ref kafka_config_name,
..
} => Some(kafka_config_name.as_str()),
}
}
}
/// A name value pair of Kafka config parameter.
#[derive(Serialize, Deserialize, Debug)]
pub struct KafkaConfigParam {
/// Name of the Kafka config parameter.
pub name: String,
/// Value of the Kafka config parameter.
pub value: String,
}
fn default_max_secs_in_future() -> u32 {
60 // 1 minute
}
fn default_max_secs_in_past() -> u32 {
30 * 24 * 3600 // 30 days
}
fn default_max_session_secs_in_past() -> u32 {
5 * 24 * 3600 // 5 days
}
fn default_chunk_size() -> ByteSize {
ByteSize::mebibytes(1)
}
fn default_projectconfig_cache_prefix() -> String {
"relayconfig".to_owned()
}
#[allow(clippy::unnecessary_wraps)]
fn default_max_rate_limit() -> Option<u32> {
Some(300) // 5 minutes
}
/// Controls Sentry-internal event processing.
#[derive(Serialize, Deserialize, Debug)]
pub struct Processing {
/// True if the Relay should do processing. Defaults to `false`.
pub enabled: bool,
/// GeoIp DB file source.
#[serde(default)]
pub geoip_path: Option<PathBuf>,
/// Maximum future timestamp of ingested events.
#[serde(default = "default_max_secs_in_future")]
pub max_secs_in_future: u32,
/// Maximum age of ingested events. Older events will be adjusted to `now()`.
#[serde(default = "default_max_secs_in_past")]
pub max_secs_in_past: u32,
/// Maximum age of ingested sessions. Older sessions will be dropped.
#[serde(default = "default_max_session_secs_in_past")]
pub max_session_secs_in_past: u32,
/// Kafka producer configurations.
pub kafka_config: Vec<KafkaConfigParam>,
/// Additional kafka producer configurations.
///
/// The `kafka_config` is the default producer configuration used for all topics. A secondary
/// kafka config can be referenced in `topics:` like this:
///
/// ```yaml
/// secondary_kafka_configs:
/// mycustomcluster:
/// - name: 'bootstrap.servers'
/// value: 'sentry_kafka_metrics:9093'
///
/// topics:
/// transactions: ingest-transactions
/// metrics:
/// name: ingest-metrics
/// config: mycustomcluster
/// ```
///
/// Then metrics will be produced to an entirely different Kafka cluster.
#[serde(default)]
pub secondary_kafka_configs: BTreeMap<String, Vec<KafkaConfigParam>>,
/// Kafka topic names.
#[serde(default)]
pub topics: TopicAssignments,