Skip to main content

flareapp_core/
config.rs

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
12/// A function that runs before a report is sent. See [`Config::before_send`].
13pub(crate) type BeforeSend = Arc<dyn Fn(&mut Report) -> bool + Send + Sync>;
14
15const DEFAULT_ENDPOINT: &str = "https://ingress.flareapp.io";
16
17/// How logs and traces are encoded before they are sent. Set it with
18/// [`Config::otlp_protocol`].
19///
20/// Error reports do not use OTLP. They are always sent as JSON.
21#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
22#[non_exhaustive]
23pub enum OtlpProtocol {
24    /// OTLP protobuf over HTTP, with the content type `application/x-protobuf`.
25    /// This is the default, as in the OpenTelemetry SDKs.
26    #[default]
27    HttpProtobuf,
28    /// OTLP/JSON over HTTP, with the content type `application/json`. You can read
29    /// these requests while you debug.
30    HttpJson,
31}
32
33impl OtlpProtocol {
34    /// Reads a protocol from its OpenTelemetry name: `http/protobuf` or
35    /// `http/json`. Returns `None` for other names, like `grpc`.
36    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    /// Returns the value of the `content-type` header for a request body in this
45    /// protocol.
46    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/// Settings for the Flare client.
55///
56/// Applications usually start with the `flareapp::config!` macro, which also sets
57/// the name and version of the application.
58///
59/// # Examples
60///
61/// ```
62/// let config = flareapp_core::Config::new()
63///     .api_key("your-api-key")
64///     .environment("production");
65/// ```
66#[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    /// Problems that the config found in the environment variables and in
92    /// the `.env` file. [`Client::start`] prints these warnings when debug is on
93    /// at that time. So the warnings also print when you call `.debug(true)` in
94    /// code.
95    ///
96    /// [`Client::start`]: crate::Client::start
97    pub(crate) warnings: Vec<String>,
98}
99
100impl Config {
101    /// Creates a config with the default settings, filled in from these
102    /// environment variables, or from the `.env` file, when they are set:
103    ///
104    /// | Variable | Setting |
105    /// |---|---|
106    /// | `FLARE_KEY` | [`Config::api_key`] |
107    /// | `FLARE_ENVIRONMENT` | [`Config::environment`] |
108    /// | `FLARE_TRACES_SAMPLE_RATE` | [`Config::traces_sample_rate`], like `0.1` |
109    /// | `FLARE_ENDPOINT` | [`Config::endpoint`] |
110    /// | `FLARE_DEBUG` | [`Config::debug`]: `true` or `1` |
111    /// | `OTEL_EXPORTER_OTLP_PROTOCOL` | [`Config::otlp_protocol`]: `http/protobuf` or `http/json` |
112    ///
113    /// The `.env` file is the file in the current folder. The Flare client does
114    /// not search parent folders. The Flare client only reads the file. The Flare
115    /// client does not change the environment of your app. Reading the `.env` file
116    /// needs the `dotenv` feature of the `flareapp` crate, which is on by default.
117    ///
118    /// An environment variable wins over the same variable in the `.env` file.
119    /// Settings you make in code afterwards win over both.
120    pub fn new() -> Self {
121        Self::from_sources(|name| env::var(name).ok(), &DotenvFile::find())
122    }
123
124    /// Creates a config from the defaults, the environment variables that `lookup`
125    /// reads, and the `.env` file. Tests pass their own `lookup`, so they do not
126    /// change the real environment.
127    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    /// Sets the API key of your Flare project. An empty key disables the Flare
168    /// client. Spaces and line breaks around the key are removed.
169    ///
170    /// Logs and traces need the private API key of your project.
171    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    /// Sets the URL that data is sent to. The default is `https://ingress.flareapp.io`.
178    ///
179    /// Logs and traces can go to any server that accepts OTLP over HTTP, for
180    /// example a local OpenTelemetry Collector on `http://localhost:4318`. The
181    /// config removes spaces and line breaks around the URL. The config also removes a
182    /// slash at the end. The config ignores a blank URL, so the endpoint stays
183    /// the same.
184    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    /// Sets how logs and traces are encoded. The default is
195    /// [`OtlpProtocol::HttpProtobuf`].
196    ///
197    /// Use [`OtlpProtocol::HttpJson`] when you want to read the requests, or for a
198    /// server that only accepts OTLP/JSON. Error reports are always sent as JSON.
199    pub fn otlp_protocol(mut self, protocol: OtlpProtocol) -> Self {
200        self.otlp_protocol = protocol;
201
202        self
203    }
204
205    /// Sets the name of your application, sent as `service.name`.
206    ///
207    /// Without a name, Flare receives `unknown_service:<name of the executable>`.
208    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    /// Sets the version of your application, sent as `service.version`.
215    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    /// Sets the git commit of the code that runs, sent as `git.hash`. Flare shows
222    /// the first 7 characters as the version of your application. A blank hash
223    /// removes the hash.
224    ///
225    /// `flareapp::config!` sets the hash when you build the app with
226    /// `FLARE_GIT_HASH`, or on a CI that gives the commit, like GitHub Actions.
227    ///
228    /// Without a hash, the Flare client runs `git` in the
229    /// [`Config::application_path`] when it starts, if that folder exists. The
230    /// Flare client then also sends the branch and the newest tag.
231    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    /// Sets the environment your application runs in, like `production` or `staging`.
238    /// The config removes spaces and line breaks around the name. A blank name
239    /// removes the environment.
240    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    /// Prints what the Flare client does to stderr, like sent requests and errors.
247    /// Turn this on while you set up the Flare client.
248    pub fn debug(mut self, debug: bool) -> Self {
249        self.debug = debug;
250
251        self
252    }
253
254    /// Sets the longest time that one HTTP request to Flare can take. The default is
255    /// 10 seconds.
256    ///
257    /// Only the default HTTP client uses this setting. A transport that you set with
258    /// [`Config::transport`] uses its own timeouts.
259    pub fn timeout(mut self, timeout: Duration) -> Self {
260        self.timeout = timeout;
261
262        self
263    }
264
265    /// Sets how long the [`Guard`](crate::Guard) waits for queued data to be sent
266    /// when it is dropped. The default is 2 seconds.
267    pub fn shutdown_timeout(mut self, timeout: Duration) -> Self {
268        self.shutdown_timeout = timeout;
269
270        self
271    }
272
273    /// Sets how many records can wait in the queue. The default is 1024. A value of
274    /// 0 becomes 1.
275    ///
276    /// When the queue is full, new records are dropped, so your application never
277    /// waits for Flare.
278    ///
279    /// The worker thread also keeps at most this many records of each kind while
280    /// they wait to be sent. When that limit is reached, the oldest record is dropped.
281    pub fn queue_capacity(mut self, capacity: usize) -> Self {
282        self.queue_capacity = capacity.max(1);
283
284        self
285    }
286
287    /// Sets the maximum number of log records, or of traces, sent in one request. The
288    /// default is 100. A value of 0 becomes 1.
289    ///
290    /// A trace is never split over two requests, so one request can hold more spans
291    /// than this number. Error reports are always sent one per request.
292    pub fn batch_size(mut self, size: usize) -> Self {
293        self.batch_size = size.max(1);
294
295        self
296    }
297
298    /// Sets how long logs and spans wait before they are sent, so they can be sent
299    /// together in one request. The default is 5 seconds.
300    pub fn batch_interval(mut self, interval: Duration) -> Self {
301        self.batch_interval = interval;
302
303        self
304    }
305
306    /// Replaces the HTTP client that sends data to Flare.
307    ///
308    /// Use this to send data with your own HTTP client, or to capture requests in
309    /// tests. See [`Transport`].
310    pub fn transport<T: Transport>(mut self, transport: T) -> Self {
311        self.transport = Some(Arc::new(transport));
312
313        self
314    }
315
316    /// Runs `hook` before each report is sent. Return `false` to drop the report.
317    ///
318    /// Use this hook to remove sensitive data, or to skip errors that you do not
319    /// want in Flare.
320    ///
321    /// # Examples
322    ///
323    /// ```
324    /// let config = flareapp_core::Config::new().before_send(|report| {
325    ///     report.exception_class() != "my_app::NotFound"
326    /// });
327    /// ```
328    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    /// Marks the frames of a crate as application code. Write the crate name as in
338    /// your `Cargo.toml`, like `my-billing`, or with underscores, like
339    /// `my_billing`. Both spellings work. The macro `flareapp::config!` adds your
340    /// own crate.
341    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    /// Sets the root folder of your application. Flare uses it to show shorter file
348    /// paths. `flareapp::config!` sets it to the folder of your `Cargo.toml`.
349    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    /// Sets the root folder of your Cargo workspace, or the folder of your
356    /// `Cargo.toml` when there is no workspace. `flareapp::config!` finds it.
357    ///
358    /// Rust gives the file of a report location, like the line of a panic,
359    /// relative to this folder, like `crates/app/src/main.rs`. The Flare client puts
360    /// this folder in front of that path, so the path matches the rest of the stack
361    /// trace. When you build with `--remap-path-prefix`, set `workspace_root` to the
362    /// new prefix.
363    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    /// Sets the framework the application is built on, sent as
370    /// `flare.framework.name` and `flare.framework.version`. Framework
371    /// integrations set this value. Use a lowercase name.
372    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    /// Turns tracing on and sets the share of traces to send: from 0.0 (none, the
379    /// default) to 1.0 (all). Flare's PHP client uses 0.1. A value below 0.0
380    /// becomes 0.0, a value above 1.0 becomes 1.0, and `NaN` becomes 0.0.
381    ///
382    /// The Flare client decides once per trace, at the first span of the trace.
383    /// When an incoming request has a `traceparent` header, the decision in that
384    /// header wins.
385    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    /// Stops sending the IP address of the client that made a request, as
396    /// `client.address`. By default, the web integrations send it, like Flare's PHP
397    /// client.
398    pub fn censor_client_ips(mut self, censor: bool) -> Self {
399        self.censor_client_ips = censor;
400
401        self
402    }
403
404    /// Sets the transport that `make` creates, but only when no transport is set.
405    ///
406    /// `make` gets the request timeout from [`Config::timeout`]. The `flareapp`
407    /// crate uses this to set its default HTTP client.
408    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    /// Fills in settings from environment variables. `lookup` reads one variable.
428    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
462/// Removes the whitespace around `value`. Returns `None` when no text is left.
463fn 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}