1use std::env;
2use std::fmt;
3use std::sync::Arc;
4use std::time::Duration;
5
6use crate::dotenv::DotenvFile;
7use crate::report::Report;
8use crate::source_path::code_crate_name;
9use crate::transport::Transport;
10use crate::worker::RetryPolicy;
11
12pub(crate) type BeforeSend = Arc<dyn Fn(&mut Report) -> bool + Send + Sync>;
14
15const DEFAULT_ENDPOINT: &str = "https://ingress.flareapp.io";
16
17#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
22#[non_exhaustive]
23pub enum OtlpProtocol {
24 #[default]
27 HttpProtobuf,
28 HttpJson,
31}
32
33impl OtlpProtocol {
34 fn from_name(name: &str) -> Option<Self> {
37 match name.trim() {
38 "http/protobuf" => Some(Self::HttpProtobuf),
39 "http/json" => Some(Self::HttpJson),
40 _ => None,
41 }
42 }
43
44 pub(crate) const fn content_type(self) -> &'static str {
47 match self {
48 Self::HttpProtobuf => "application/x-protobuf",
49 Self::HttpJson => "application/json",
50 }
51 }
52}
53
54#[derive(Clone)]
67#[must_use]
68pub struct Config {
69 pub(crate) api_key: Option<String>,
70 pub(crate) endpoint: String,
71 pub(crate) otlp_protocol: OtlpProtocol,
72 pub(crate) service_name: Option<String>,
73 pub(crate) service_version: Option<String>,
74 pub(crate) git_hash: Option<String>,
75 pub(crate) environment: Option<String>,
76 pub(crate) debug: bool,
77 pub(crate) timeout: Duration,
78 pub(crate) shutdown_timeout: Duration,
79 pub(crate) queue_capacity: usize,
80 pub(crate) batch_size: usize,
81 pub(crate) batch_interval: Duration,
82 pub(crate) transport: Option<Arc<dyn Transport>>,
83 pub(crate) retry: RetryPolicy,
84 pub(crate) before_send: Option<BeforeSend>,
85 pub(crate) app_crates: Vec<String>,
86 pub(crate) application_path: Option<String>,
87 pub(crate) workspace_root: Option<String>,
88 pub(crate) traces_sample_rate: f64,
89 pub(crate) censor_client_ips: bool,
90 pub(crate) framework: Option<(String, Option<String>)>,
91 pub(crate) warnings: Vec<String>,
98}
99
100impl Config {
101 pub fn new() -> Self {
121 Self::from_sources(|name| env::var(name).ok(), &DotenvFile::find())
122 }
123
124 fn from_sources<F: Fn(&str) -> Option<String>>(lookup: F, dotenv: &DotenvFile) -> Self {
128 let mut config =
129 Self::defaults().with_environment(|name| lookup(name).or_else(|| dotenv.get(name)));
130 if let Some(error) = dotenv.error() {
131 config.warnings.push(format!(
132 "the .env file has an error, Flare ignored the rest of it: {error}"
133 ));
134 }
135
136 config
137 }
138
139 fn defaults() -> Self {
140 Self {
141 api_key: None,
142 endpoint: DEFAULT_ENDPOINT.to_owned(),
143 otlp_protocol: OtlpProtocol::default(),
144 service_name: None,
145 service_version: None,
146 git_hash: None,
147 environment: None,
148 debug: false,
149 timeout: Duration::from_secs(10),
150 shutdown_timeout: Duration::from_secs(2),
151 queue_capacity: 1024,
152 batch_size: 100,
153 batch_interval: Duration::from_secs(5),
154 transport: None,
155 retry: RetryPolicy::default(),
156 before_send: None,
157 app_crates: Vec::new(),
158 application_path: None,
159 workspace_root: None,
160 traces_sample_rate: 0.0,
161 censor_client_ips: false,
162 framework: None,
163 warnings: Vec::new(),
164 }
165 }
166
167 pub fn api_key<S: Into<String>>(mut self, api_key: S) -> Self {
172 self.api_key = non_blank(&api_key.into()).map(str::to_owned);
173
174 self
175 }
176
177 pub fn endpoint<S: Into<String>>(mut self, endpoint: S) -> Self {
185 if let Some(endpoint) = non_blank(&endpoint.into()) {
186 endpoint
187 .trim_end_matches('/')
188 .clone_into(&mut self.endpoint);
189 }
190
191 self
192 }
193
194 pub fn otlp_protocol(mut self, protocol: OtlpProtocol) -> Self {
200 self.otlp_protocol = protocol;
201
202 self
203 }
204
205 pub fn service_name<S: Into<String>>(mut self, name: S) -> Self {
209 self.service_name = Some(name.into());
210
211 self
212 }
213
214 pub fn service_version<S: Into<String>>(mut self, version: S) -> Self {
216 self.service_version = Some(version.into());
217
218 self
219 }
220
221 pub fn git_hash<S: Into<String>>(mut self, hash: S) -> Self {
232 self.git_hash = non_blank(&hash.into()).map(str::to_owned);
233
234 self
235 }
236
237 pub fn environment<S: Into<String>>(mut self, environment: S) -> Self {
241 self.environment = non_blank(&environment.into()).map(str::to_owned);
242
243 self
244 }
245
246 pub fn debug(mut self, debug: bool) -> Self {
249 self.debug = debug;
250
251 self
252 }
253
254 pub fn timeout(mut self, timeout: Duration) -> Self {
260 self.timeout = timeout;
261
262 self
263 }
264
265 pub fn shutdown_timeout(mut self, timeout: Duration) -> Self {
268 self.shutdown_timeout = timeout;
269
270 self
271 }
272
273 pub fn queue_capacity(mut self, capacity: usize) -> Self {
282 self.queue_capacity = capacity.max(1);
283
284 self
285 }
286
287 pub fn batch_size(mut self, size: usize) -> Self {
293 self.batch_size = size.max(1);
294
295 self
296 }
297
298 pub fn batch_interval(mut self, interval: Duration) -> Self {
301 self.batch_interval = interval;
302
303 self
304 }
305
306 pub fn transport<T: Transport>(mut self, transport: T) -> Self {
311 self.transport = Some(Arc::new(transport));
312
313 self
314 }
315
316 pub fn before_send<F>(mut self, hook: F) -> Self
329 where
330 F: Fn(&mut Report) -> bool + Send + Sync + 'static,
331 {
332 self.before_send = Some(Arc::new(hook));
333
334 self
335 }
336
337 pub fn app_crate<S: Into<String>>(mut self, name: S) -> Self {
342 self.app_crates.push(code_crate_name(&name.into()));
343
344 self
345 }
346
347 pub fn application_path<S: Into<String>>(mut self, path: S) -> Self {
350 self.application_path = Some(path.into());
351
352 self
353 }
354
355 pub fn workspace_root<S: Into<String>>(mut self, path: S) -> Self {
364 self.workspace_root = Some(path.into());
365
366 self
367 }
368
369 pub fn framework<N: Into<String>>(mut self, name: N, version: Option<String>) -> Self {
373 self.framework = Some((name.into(), version));
374
375 self
376 }
377
378 pub fn traces_sample_rate(mut self, rate: f64) -> Self {
386 self.traces_sample_rate = if rate.is_nan() {
387 0.0
388 } else {
389 rate.clamp(0.0, 1.0)
390 };
391
392 self
393 }
394
395 pub fn censor_client_ips(mut self, censor: bool) -> Self {
399 self.censor_client_ips = censor;
400
401 self
402 }
403
404 pub fn default_transport<T, F>(mut self, make: F) -> Self
409 where
410 T: Transport,
411 F: FnOnce(Duration) -> T,
412 {
413 if self.transport.is_none() {
414 self.transport = Some(Arc::new(make(self.timeout)));
415 }
416
417 self
418 }
419
420 #[cfg(test)]
421 pub(crate) fn retry(mut self, retry: RetryPolicy) -> Self {
422 self.retry = retry;
423
424 self
425 }
426
427 fn with_environment<F: Fn(&str) -> Option<String>>(mut self, lookup: F) -> Self {
429 if let Some(key) = lookup("FLARE_KEY") {
430 self = self.api_key(key);
431 }
432 if let Some(environment) = lookup("FLARE_ENVIRONMENT") {
433 self = self.environment(environment);
434 }
435 if let Some(endpoint) = lookup("FLARE_ENDPOINT") {
436 self = self.endpoint(endpoint);
437 }
438 if let Some(debug) = lookup("FLARE_DEBUG") {
439 self.debug = matches!(debug.trim(), "true" | "1");
440 }
441 if let Some(name) = lookup("OTEL_EXPORTER_OTLP_PROTOCOL") {
442 match OtlpProtocol::from_name(&name) {
443 Some(protocol) => self.otlp_protocol = protocol,
444 None => self.warnings.push(format!(
445 "OTEL_EXPORTER_OTLP_PROTOCOL is not http/protobuf or http/json, ignored: {name}"
446 )),
447 }
448 }
449 if let Some(rate) = lookup("FLARE_TRACES_SAMPLE_RATE") {
450 match rate.trim().parse::<f64>() {
451 Ok(rate) => self = self.traces_sample_rate(rate),
452 Err(_) => self.warnings.push(format!(
453 "FLARE_TRACES_SAMPLE_RATE is not a number, ignored: {rate}"
454 )),
455 }
456 }
457
458 self
459 }
460}
461
462fn non_blank(value: &str) -> Option<&str> {
464 let value = value.trim();
465
466 (!value.is_empty()).then_some(value)
467}
468
469impl Default for Config {
470 fn default() -> Self {
471 Self::new()
472 }
473}
474
475impl fmt::Debug for Config {
476 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
477 f.debug_struct("Config")
478 .field("api_key", &self.api_key.as_ref().map(|_| "<hidden>"))
479 .field("endpoint", &self.endpoint)
480 .field("otlp_protocol", &self.otlp_protocol)
481 .field("service_name", &self.service_name)
482 .field("service_version", &self.service_version)
483 .field("git_hash", &self.git_hash)
484 .field("environment", &self.environment)
485 .field("debug", &self.debug)
486 .field("timeout", &self.timeout)
487 .field("shutdown_timeout", &self.shutdown_timeout)
488 .field("queue_capacity", &self.queue_capacity)
489 .field("batch_size", &self.batch_size)
490 .field("batch_interval", &self.batch_interval)
491 .field("transport", &self.transport)
492 .field("before_send", &self.before_send.is_some())
493 .field("app_crates", &self.app_crates)
494 .field("application_path", &self.application_path)
495 .field("workspace_root", &self.workspace_root)
496 .field("traces_sample_rate", &self.traces_sample_rate)
497 .field("censor_client_ips", &self.censor_client_ips)
498 .field("framework", &self.framework)
499 .finish_non_exhaustive()
500 }
501}
502
503#[cfg(test)]
504mod tests {
505 use super::*;
506
507 fn from<const N: usize>(variables: [(&str, &str); N]) -> Config {
508 Config::defaults().with_environment(|name| {
509 variables
510 .iter()
511 .find(|(variable, _)| *variable == name)
512 .map(|(_, value)| (*value).to_owned())
513 })
514 }
515
516 #[test]
517 fn reads_the_api_key_from_flare_key() {
518 let config = from([("FLARE_KEY", "secret")]);
519
520 assert_eq!(config.api_key.as_deref(), Some("secret"));
521 }
522
523 #[test]
524 fn reads_the_environment_from_flare_environment() {
525 let config = from([("FLARE_ENVIRONMENT", "staging")]);
526
527 assert_eq!(config.environment.as_deref(), Some("staging"));
528 }
529
530 #[test]
531 fn reads_the_sample_rate_from_flare_traces_sample_rate() {
532 let config = from([("FLARE_TRACES_SAMPLE_RATE", "0.25")]);
533
534 let rate = config.traces_sample_rate;
535 assert!((rate - 0.25).abs() < f64::EPSILON, "{rate}");
536 }
537
538 #[test]
539 fn reads_the_endpoint_without_its_last_slash_from_flare_endpoint() {
540 let config = from([("FLARE_ENDPOINT", "http://localhost:4318/")]);
541
542 assert_eq!(config.endpoint, "http://localhost:4318");
543 }
544
545 #[test]
546 fn trims_the_endpoint_and_ignores_a_blank_one() {
547 let default = Config::defaults().endpoint;
548
549 let trimmed = Config::defaults().endpoint(" http://localhost:4318/\n");
550 let blank = Config::defaults().endpoint(" \n");
551 let from_env = from([("FLARE_ENDPOINT", "http://localhost:4318\n")]);
552 let blank_env = from([("FLARE_ENDPOINT", "")]);
553
554 assert_eq!(trimmed.endpoint, "http://localhost:4318");
555 assert_eq!(blank.endpoint, default);
556 assert_eq!(from_env.endpoint, "http://localhost:4318");
557 assert_eq!(blank_env.endpoint, default);
558 }
559
560 #[test]
561 fn trims_the_environment_and_ignores_a_blank_one() {
562 let trimmed = Config::defaults().environment("\tproduction\n");
563 let blank = Config::defaults()
564 .environment("production")
565 .environment(" ");
566 let from_env = from([("FLARE_ENVIRONMENT", "production\n")]);
567 let blank_env = from([("FLARE_ENVIRONMENT", "\n")]);
568
569 assert_eq!(trimmed.environment.as_deref(), Some("production"));
570 assert_eq!(blank.environment, None);
571 assert_eq!(from_env.environment.as_deref(), Some("production"));
572 assert_eq!(blank_env.environment, None);
573 }
574
575 #[test]
576 fn trims_the_api_key_and_git_hash() {
577 let key = from([("FLARE_KEY", "secret\n")]);
578 let blank_key = from([("FLARE_KEY", " ")]);
579 let hash = Config::defaults().git_hash(" abc1234\n");
580 let blank_hash = Config::defaults().git_hash("abc1234").git_hash("\n");
581
582 assert_eq!(key.api_key.as_deref(), Some("secret"));
583 assert_eq!(blank_key.api_key, None);
584 assert_eq!(hash.git_hash.as_deref(), Some("abc1234"));
585 assert_eq!(blank_hash.git_hash, None);
586 }
587
588 #[test]
589 fn reads_the_debug_setting_from_flare_debug() {
590 assert!(from([("FLARE_DEBUG", "1")]).debug);
591 }
592
593 #[test]
594 fn reads_the_protocol_from_otel_exporter_otlp_protocol() {
595 let config = from([("OTEL_EXPORTER_OTLP_PROTOCOL", "http/json")]);
596
597 assert_eq!(config.otlp_protocol, OtlpProtocol::HttpJson);
598 }
599
600 #[test]
601 fn removes_line_breaks_around_the_api_key() {
602 let config = from([("FLARE_KEY", "secret\r\n")]);
603
604 assert_eq!(config.api_key.as_deref(), Some("secret"));
605 }
606
607 #[test]
608 fn a_blank_api_key_is_not_set() {
609 let config = Config::new().api_key("secret").api_key(" \n");
610
611 assert_eq!(config.api_key, None);
612 }
613
614 #[test]
615 fn ignores_a_sample_rate_that_is_not_a_number() {
616 let rate = from([("FLARE_TRACES_SAMPLE_RATE", "often")]).traces_sample_rate;
617
618 assert!(rate.abs() < f64::EPSILON, "{rate}");
619 }
620
621 #[test]
622 fn keeps_warnings_when_debug_is_set_later() {
623 let config = from([
624 ("OTEL_EXPORTER_OTLP_PROTOCOL", "grpc"),
625 ("FLARE_TRACES_SAMPLE_RATE", "often"),
626 ])
627 .debug(true);
628
629 assert_eq!(config.warnings.len(), 2, "{:?}", config.warnings);
630 assert!(config.warnings[0].contains("OTEL_EXPORTER_OTLP_PROTOCOL"));
631 assert!(config.warnings[1].contains("FLARE_TRACES_SAMPLE_RATE"));
632 }
633
634 #[test]
635 fn keeps_the_error_of_the_dotenv_file_as_a_warning() {
636 let dotenv = DotenvFile::with_error("bad line");
637
638 let config = Config::from_sources(|_| None, &dotenv).debug(true);
639
640 assert_eq!(config.warnings.len(), 1, "{:?}", config.warnings);
641 assert!(config.warnings[0].contains("bad line"));
642 }
643
644 #[test]
645 fn app_crate_accepts_a_name_with_hyphens() {
646 let config = Config::defaults().app_crate("my-billing");
647 let file =
648 std::path::Path::new("/home/me/.cargo/registry/src/index/my-billing-1.0.0/src/lib.rs");
649
650 assert_eq!(config.app_crates, ["my_billing"]);
651 assert!(crate::source_path::is_application_file(
652 file,
653 &config.app_crates
654 ));
655 }
656
657 #[test]
658 fn valid_variables_give_no_warnings() {
659 let config = from([("FLARE_TRACES_SAMPLE_RATE", "0.5")]);
660
661 assert_eq!(config.warnings.len(), 0);
662 }
663
664 #[test]
665 fn ignores_a_debug_setting_that_is_not_1() {
666 assert!(!from([("FLARE_DEBUG", "yes")]).debug);
667 }
668
669 #[test]
670 fn ignores_an_unknown_protocol() {
671 let config = from([("OTEL_EXPORTER_OTLP_PROTOCOL", "grpc")]);
672
673 assert_eq!(config.otlp_protocol, OtlpProtocol::HttpProtobuf);
674 }
675
676 #[test]
677 fn sends_protobuf_by_default() {
678 assert_eq!(from([]).otlp_protocol, OtlpProtocol::HttpProtobuf);
679 }
680
681 #[test]
682 fn reads_settings_from_the_dotenv_file() {
683 let dotenv = DotenvFile::from_variables([("FLARE_KEY", "secret")]);
684 let config = Config::from_sources(|_| None, &dotenv);
685
686 assert_eq!(config.api_key.as_deref(), Some("secret"));
687 }
688
689 #[test]
690 fn environment_variables_win_over_the_dotenv_file() {
691 let dotenv = DotenvFile::from_variables([
692 ("FLARE_KEY", "from-file"),
693 ("FLARE_ENVIRONMENT", "staging"),
694 ]);
695 let config = Config::from_sources(
696 |name| (name == "FLARE_KEY").then(|| "from-environment".to_owned()),
697 &dotenv,
698 );
699
700 assert_eq!(config.api_key.as_deref(), Some("from-environment"));
701 assert_eq!(config.environment.as_deref(), Some("staging"));
702 }
703
704 #[test]
705 fn code_wins_over_environment_variables() {
706 let config = from([("FLARE_ENVIRONMENT", "staging")]).environment("production");
707
708 assert_eq!(config.environment.as_deref(), Some("production"));
709 }
710}