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
use std::env;
use std::fmt;
use std::sync::Arc;
use std::time::Duration;
use crate::dotenv::DotenvFile;
use crate::report::Report;
use crate::source_path::code_crate_name;
use crate::transport::Transport;
use crate::worker::RetryPolicy;
/// A function that runs before a report is sent. See [`Config::before_send`].
pub(crate) type BeforeSend = Arc<dyn Fn(&mut Report) -> bool + Send + Sync>;
const DEFAULT_ENDPOINT: &str = "https://ingress.flareapp.io";
/// How logs and traces are encoded before they are sent. Set it with
/// [`Config::otlp_protocol`].
///
/// Error reports do not use OTLP. They are always sent as JSON.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum OtlpProtocol {
/// OTLP protobuf over HTTP, with the content type `application/x-protobuf`.
/// This is the default, as in the OpenTelemetry SDKs.
#[default]
HttpProtobuf,
/// OTLP/JSON over HTTP, with the content type `application/json`. You can read
/// these requests while you debug.
HttpJson,
}
impl OtlpProtocol {
/// Reads a protocol from its OpenTelemetry name: `http/protobuf` or
/// `http/json`. Returns `None` for other names, like `grpc`.
fn from_name(name: &str) -> Option<Self> {
match name.trim() {
"http/protobuf" => Some(Self::HttpProtobuf),
"http/json" => Some(Self::HttpJson),
_ => None,
}
}
/// Returns the value of the `content-type` header for a request body in this
/// protocol.
pub(crate) const fn content_type(self) -> &'static str {
match self {
Self::HttpProtobuf => "application/x-protobuf",
Self::HttpJson => "application/json",
}
}
}
/// Settings for the Flare client.
///
/// Applications usually start with the `flareapp::config!` macro, which also sets
/// the name and version of the application.
///
/// # Examples
///
/// ```
/// let config = flareapp_core::Config::new()
/// .api_key("your-api-key")
/// .environment("production");
/// ```
#[derive(Clone)]
#[must_use]
pub struct Config {
pub(crate) api_key: Option<String>,
pub(crate) endpoint: String,
pub(crate) otlp_protocol: OtlpProtocol,
pub(crate) service_name: Option<String>,
pub(crate) service_version: Option<String>,
pub(crate) git_hash: Option<String>,
pub(crate) environment: Option<String>,
pub(crate) debug: bool,
pub(crate) timeout: Duration,
pub(crate) shutdown_timeout: Duration,
pub(crate) queue_capacity: usize,
pub(crate) batch_size: usize,
pub(crate) batch_interval: Duration,
pub(crate) transport: Option<Arc<dyn Transport>>,
pub(crate) retry: RetryPolicy,
pub(crate) before_send: Option<BeforeSend>,
pub(crate) app_crates: Vec<String>,
pub(crate) application_path: Option<String>,
pub(crate) workspace_root: Option<String>,
pub(crate) traces_sample_rate: f64,
pub(crate) censor_client_ips: bool,
pub(crate) framework: Option<(String, Option<String>)>,
/// Problems that the config found in the environment variables and in
/// the `.env` file. [`Client::start`] prints these warnings when debug is on
/// at that time. So the warnings also print when you call `.debug(true)` in
/// code.
///
/// [`Client::start`]: crate::Client::start
pub(crate) warnings: Vec<String>,
}
impl Config {
/// Creates a config with the default settings, filled in from these
/// environment variables, or from the `.env` file, when they are set:
///
/// | Variable | Setting |
/// |---|---|
/// | `FLARE_KEY` | [`Config::api_key`] |
/// | `FLARE_ENVIRONMENT` | [`Config::environment`] |
/// | `FLARE_TRACES_SAMPLE_RATE` | [`Config::traces_sample_rate`], like `0.1` |
/// | `FLARE_ENDPOINT` | [`Config::endpoint`] |
/// | `FLARE_DEBUG` | [`Config::debug`]: `true` or `1` |
/// | `OTEL_EXPORTER_OTLP_PROTOCOL` | [`Config::otlp_protocol`]: `http/protobuf` or `http/json` |
///
/// The `.env` file is the file in the current folder. The Flare client does
/// not search parent folders. The Flare client only reads the file. The Flare
/// client does not change the environment of your app. Reading the `.env` file
/// needs the `dotenv` feature of the `flareapp` crate, which is on by default.
///
/// An environment variable wins over the same variable in the `.env` file.
/// Settings you make in code afterwards win over both.
pub fn new() -> Self {
Self::from_sources(|name| env::var(name).ok(), &DotenvFile::find())
}
/// Creates a config from the defaults, the environment variables that `lookup`
/// reads, and the `.env` file. Tests pass their own `lookup`, so they do not
/// change the real environment.
fn from_sources<F: Fn(&str) -> Option<String>>(lookup: F, dotenv: &DotenvFile) -> Self {
let mut config =
Self::defaults().with_environment(|name| lookup(name).or_else(|| dotenv.get(name)));
if let Some(error) = dotenv.error() {
config.warnings.push(format!(
"the .env file has an error, Flare ignored the rest of it: {error}"
));
}
config
}
fn defaults() -> Self {
Self {
api_key: None,
endpoint: DEFAULT_ENDPOINT.to_owned(),
otlp_protocol: OtlpProtocol::default(),
service_name: None,
service_version: None,
git_hash: None,
environment: None,
debug: false,
timeout: Duration::from_secs(10),
shutdown_timeout: Duration::from_secs(2),
queue_capacity: 1024,
batch_size: 100,
batch_interval: Duration::from_secs(5),
transport: None,
retry: RetryPolicy::default(),
before_send: None,
app_crates: Vec::new(),
application_path: None,
workspace_root: None,
traces_sample_rate: 0.0,
censor_client_ips: false,
framework: None,
warnings: Vec::new(),
}
}
/// Sets the API key of your Flare project. An empty key disables the Flare
/// client. Spaces and line breaks around the key are removed.
///
/// Logs and traces need the private API key of your project.
pub fn api_key<S: Into<String>>(mut self, api_key: S) -> Self {
self.api_key = non_blank(&api_key.into()).map(str::to_owned);
self
}
/// Sets the URL that data is sent to. The default is `https://ingress.flareapp.io`.
///
/// Logs and traces can go to any server that accepts OTLP over HTTP, for
/// example a local OpenTelemetry Collector on `http://localhost:4318`. The
/// config removes spaces and line breaks around the URL. The config also removes a
/// slash at the end. The config ignores a blank URL, so the endpoint stays
/// the same.
pub fn endpoint<S: Into<String>>(mut self, endpoint: S) -> Self {
if let Some(endpoint) = non_blank(&endpoint.into()) {
endpoint
.trim_end_matches('/')
.clone_into(&mut self.endpoint);
}
self
}
/// Sets how logs and traces are encoded. The default is
/// [`OtlpProtocol::HttpProtobuf`].
///
/// Use [`OtlpProtocol::HttpJson`] when you want to read the requests, or for a
/// server that only accepts OTLP/JSON. Error reports are always sent as JSON.
pub fn otlp_protocol(mut self, protocol: OtlpProtocol) -> Self {
self.otlp_protocol = protocol;
self
}
/// Sets the name of your application, sent as `service.name`.
///
/// Without a name, Flare receives `unknown_service:<name of the executable>`.
pub fn service_name<S: Into<String>>(mut self, name: S) -> Self {
self.service_name = Some(name.into());
self
}
/// Sets the version of your application, sent as `service.version`.
pub fn service_version<S: Into<String>>(mut self, version: S) -> Self {
self.service_version = Some(version.into());
self
}
/// Sets the git commit of the code that runs, sent as `git.hash`. Flare shows
/// the first 7 characters as the version of your application. A blank hash
/// removes the hash.
///
/// `flareapp::config!` sets the hash when you build the app with
/// `FLARE_GIT_HASH`, or on a CI that gives the commit, like GitHub Actions.
///
/// Without a hash, the Flare client runs `git` in the
/// [`Config::application_path`] when it starts, if that folder exists. The
/// Flare client then also sends the branch and the newest tag.
pub fn git_hash<S: Into<String>>(mut self, hash: S) -> Self {
self.git_hash = non_blank(&hash.into()).map(str::to_owned);
self
}
/// Sets the environment your application runs in, like `production` or `staging`.
/// The config removes spaces and line breaks around the name. A blank name
/// removes the environment.
pub fn environment<S: Into<String>>(mut self, environment: S) -> Self {
self.environment = non_blank(&environment.into()).map(str::to_owned);
self
}
/// Prints what the Flare client does to stderr, like sent requests and errors.
/// Turn this on while you set up the Flare client.
pub fn debug(mut self, debug: bool) -> Self {
self.debug = debug;
self
}
/// Sets the longest time that one HTTP request to Flare can take. The default is
/// 10 seconds.
///
/// Only the default HTTP client uses this setting. A transport that you set with
/// [`Config::transport`] uses its own timeouts.
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
/// Sets how long the [`Guard`](crate::Guard) waits for queued data to be sent
/// when it is dropped. The default is 2 seconds.
pub fn shutdown_timeout(mut self, timeout: Duration) -> Self {
self.shutdown_timeout = timeout;
self
}
/// Sets how many records can wait in the queue. The default is 1024. A value of
/// 0 becomes 1.
///
/// When the queue is full, new records are dropped, so your application never
/// waits for Flare.
///
/// The worker thread also keeps at most this many records of each kind while
/// they wait to be sent. When that limit is reached, the oldest record is dropped.
pub fn queue_capacity(mut self, capacity: usize) -> Self {
self.queue_capacity = capacity.max(1);
self
}
/// Sets the maximum number of log records, or of traces, sent in one request. The
/// default is 100. A value of 0 becomes 1.
///
/// A trace is never split over two requests, so one request can hold more spans
/// than this number. Error reports are always sent one per request.
pub fn batch_size(mut self, size: usize) -> Self {
self.batch_size = size.max(1);
self
}
/// Sets how long logs and spans wait before they are sent, so they can be sent
/// together in one request. The default is 5 seconds.
pub fn batch_interval(mut self, interval: Duration) -> Self {
self.batch_interval = interval;
self
}
/// Replaces the HTTP client that sends data to Flare.
///
/// Use this to send data with your own HTTP client, or to capture requests in
/// tests. See [`Transport`].
pub fn transport<T: Transport>(mut self, transport: T) -> Self {
self.transport = Some(Arc::new(transport));
self
}
/// Runs `hook` before each report is sent. Return `false` to drop the report.
///
/// Use this hook to remove sensitive data, or to skip errors that you do not
/// want in Flare.
///
/// # Examples
///
/// ```
/// let config = flareapp_core::Config::new().before_send(|report| {
/// report.exception_class() != "my_app::NotFound"
/// });
/// ```
pub fn before_send<F>(mut self, hook: F) -> Self
where
F: Fn(&mut Report) -> bool + Send + Sync + 'static,
{
self.before_send = Some(Arc::new(hook));
self
}
/// Marks the frames of a crate as application code. Write the crate name as in
/// your `Cargo.toml`, like `my-billing`, or with underscores, like
/// `my_billing`. Both spellings work. The macro `flareapp::config!` adds your
/// own crate.
pub fn app_crate<S: Into<String>>(mut self, name: S) -> Self {
self.app_crates.push(code_crate_name(&name.into()));
self
}
/// Sets the root folder of your application. Flare uses it to show shorter file
/// paths. `flareapp::config!` sets it to the folder of your `Cargo.toml`.
pub fn application_path<S: Into<String>>(mut self, path: S) -> Self {
self.application_path = Some(path.into());
self
}
/// Sets the root folder of your Cargo workspace, or the folder of your
/// `Cargo.toml` when there is no workspace. `flareapp::config!` finds it.
///
/// Rust gives the file of a report location, like the line of a panic,
/// relative to this folder, like `crates/app/src/main.rs`. The Flare client puts
/// this folder in front of that path, so the path matches the rest of the stack
/// trace. When you build with `--remap-path-prefix`, set `workspace_root` to the
/// new prefix.
pub fn workspace_root<S: Into<String>>(mut self, path: S) -> Self {
self.workspace_root = Some(path.into());
self
}
/// Sets the framework the application is built on, sent as
/// `flare.framework.name` and `flare.framework.version`. Framework
/// integrations set this value. Use a lowercase name.
pub fn framework<N: Into<String>>(mut self, name: N, version: Option<String>) -> Self {
self.framework = Some((name.into(), version));
self
}
/// Turns tracing on and sets the share of traces to send: from 0.0 (none, the
/// default) to 1.0 (all). Flare's PHP client uses 0.1. A value below 0.0
/// becomes 0.0, a value above 1.0 becomes 1.0, and `NaN` becomes 0.0.
///
/// The Flare client decides once per trace, at the first span of the trace.
/// When an incoming request has a `traceparent` header, the decision in that
/// header wins.
pub fn traces_sample_rate(mut self, rate: f64) -> Self {
self.traces_sample_rate = if rate.is_nan() {
0.0
} else {
rate.clamp(0.0, 1.0)
};
self
}
/// Stops sending the IP address of the client that made a request, as
/// `client.address`. By default, the web integrations send it, like Flare's PHP
/// client.
pub fn censor_client_ips(mut self, censor: bool) -> Self {
self.censor_client_ips = censor;
self
}
/// Sets the transport that `make` creates, but only when no transport is set.
///
/// `make` gets the request timeout from [`Config::timeout`]. The `flareapp`
/// crate uses this to set its default HTTP client.
pub fn default_transport<T, F>(mut self, make: F) -> Self
where
T: Transport,
F: FnOnce(Duration) -> T,
{
if self.transport.is_none() {
self.transport = Some(Arc::new(make(self.timeout)));
}
self
}
#[cfg(test)]
pub(crate) fn retry(mut self, retry: RetryPolicy) -> Self {
self.retry = retry;
self
}
/// Fills in settings from environment variables. `lookup` reads one variable.
fn with_environment<F: Fn(&str) -> Option<String>>(mut self, lookup: F) -> Self {
if let Some(key) = lookup("FLARE_KEY") {
self = self.api_key(key);
}
if let Some(environment) = lookup("FLARE_ENVIRONMENT") {
self = self.environment(environment);
}
if let Some(endpoint) = lookup("FLARE_ENDPOINT") {
self = self.endpoint(endpoint);
}
if let Some(debug) = lookup("FLARE_DEBUG") {
self.debug = matches!(debug.trim(), "true" | "1");
}
if let Some(name) = lookup("OTEL_EXPORTER_OTLP_PROTOCOL") {
match OtlpProtocol::from_name(&name) {
Some(protocol) => self.otlp_protocol = protocol,
None => self.warnings.push(format!(
"OTEL_EXPORTER_OTLP_PROTOCOL is not http/protobuf or http/json, ignored: {name}"
)),
}
}
if let Some(rate) = lookup("FLARE_TRACES_SAMPLE_RATE") {
match rate.trim().parse::<f64>() {
Ok(rate) => self = self.traces_sample_rate(rate),
Err(_) => self.warnings.push(format!(
"FLARE_TRACES_SAMPLE_RATE is not a number, ignored: {rate}"
)),
}
}
self
}
}
/// Removes the whitespace around `value`. Returns `None` when no text is left.
fn non_blank(value: &str) -> Option<&str> {
let value = value.trim();
(!value.is_empty()).then_some(value)
}
impl Default for Config {
fn default() -> Self {
Self::new()
}
}
impl fmt::Debug for Config {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Config")
.field("api_key", &self.api_key.as_ref().map(|_| "<hidden>"))
.field("endpoint", &self.endpoint)
.field("otlp_protocol", &self.otlp_protocol)
.field("service_name", &self.service_name)
.field("service_version", &self.service_version)
.field("git_hash", &self.git_hash)
.field("environment", &self.environment)
.field("debug", &self.debug)
.field("timeout", &self.timeout)
.field("shutdown_timeout", &self.shutdown_timeout)
.field("queue_capacity", &self.queue_capacity)
.field("batch_size", &self.batch_size)
.field("batch_interval", &self.batch_interval)
.field("transport", &self.transport)
.field("before_send", &self.before_send.is_some())
.field("app_crates", &self.app_crates)
.field("application_path", &self.application_path)
.field("workspace_root", &self.workspace_root)
.field("traces_sample_rate", &self.traces_sample_rate)
.field("censor_client_ips", &self.censor_client_ips)
.field("framework", &self.framework)
.finish_non_exhaustive()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn from<const N: usize>(variables: [(&str, &str); N]) -> Config {
Config::defaults().with_environment(|name| {
variables
.iter()
.find(|(variable, _)| *variable == name)
.map(|(_, value)| (*value).to_owned())
})
}
#[test]
fn reads_the_api_key_from_flare_key() {
let config = from([("FLARE_KEY", "secret")]);
assert_eq!(config.api_key.as_deref(), Some("secret"));
}
#[test]
fn reads_the_environment_from_flare_environment() {
let config = from([("FLARE_ENVIRONMENT", "staging")]);
assert_eq!(config.environment.as_deref(), Some("staging"));
}
#[test]
fn reads_the_sample_rate_from_flare_traces_sample_rate() {
let config = from([("FLARE_TRACES_SAMPLE_RATE", "0.25")]);
let rate = config.traces_sample_rate;
assert!((rate - 0.25).abs() < f64::EPSILON, "{rate}");
}
#[test]
fn reads_the_endpoint_without_its_last_slash_from_flare_endpoint() {
let config = from([("FLARE_ENDPOINT", "http://localhost:4318/")]);
assert_eq!(config.endpoint, "http://localhost:4318");
}
#[test]
fn trims_the_endpoint_and_ignores_a_blank_one() {
let default = Config::defaults().endpoint;
let trimmed = Config::defaults().endpoint(" http://localhost:4318/\n");
let blank = Config::defaults().endpoint(" \n");
let from_env = from([("FLARE_ENDPOINT", "http://localhost:4318\n")]);
let blank_env = from([("FLARE_ENDPOINT", "")]);
assert_eq!(trimmed.endpoint, "http://localhost:4318");
assert_eq!(blank.endpoint, default);
assert_eq!(from_env.endpoint, "http://localhost:4318");
assert_eq!(blank_env.endpoint, default);
}
#[test]
fn trims_the_environment_and_ignores_a_blank_one() {
let trimmed = Config::defaults().environment("\tproduction\n");
let blank = Config::defaults()
.environment("production")
.environment(" ");
let from_env = from([("FLARE_ENVIRONMENT", "production\n")]);
let blank_env = from([("FLARE_ENVIRONMENT", "\n")]);
assert_eq!(trimmed.environment.as_deref(), Some("production"));
assert_eq!(blank.environment, None);
assert_eq!(from_env.environment.as_deref(), Some("production"));
assert_eq!(blank_env.environment, None);
}
#[test]
fn trims_the_api_key_and_git_hash() {
let key = from([("FLARE_KEY", "secret\n")]);
let blank_key = from([("FLARE_KEY", " ")]);
let hash = Config::defaults().git_hash(" abc1234\n");
let blank_hash = Config::defaults().git_hash("abc1234").git_hash("\n");
assert_eq!(key.api_key.as_deref(), Some("secret"));
assert_eq!(blank_key.api_key, None);
assert_eq!(hash.git_hash.as_deref(), Some("abc1234"));
assert_eq!(blank_hash.git_hash, None);
}
#[test]
fn reads_the_debug_setting_from_flare_debug() {
assert!(from([("FLARE_DEBUG", "1")]).debug);
}
#[test]
fn reads_the_protocol_from_otel_exporter_otlp_protocol() {
let config = from([("OTEL_EXPORTER_OTLP_PROTOCOL", "http/json")]);
assert_eq!(config.otlp_protocol, OtlpProtocol::HttpJson);
}
#[test]
fn removes_line_breaks_around_the_api_key() {
let config = from([("FLARE_KEY", "secret\r\n")]);
assert_eq!(config.api_key.as_deref(), Some("secret"));
}
#[test]
fn a_blank_api_key_is_not_set() {
let config = Config::new().api_key("secret").api_key(" \n");
assert_eq!(config.api_key, None);
}
#[test]
fn ignores_a_sample_rate_that_is_not_a_number() {
let rate = from([("FLARE_TRACES_SAMPLE_RATE", "often")]).traces_sample_rate;
assert!(rate.abs() < f64::EPSILON, "{rate}");
}
#[test]
fn keeps_warnings_when_debug_is_set_later() {
let config = from([
("OTEL_EXPORTER_OTLP_PROTOCOL", "grpc"),
("FLARE_TRACES_SAMPLE_RATE", "often"),
])
.debug(true);
assert_eq!(config.warnings.len(), 2, "{:?}", config.warnings);
assert!(config.warnings[0].contains("OTEL_EXPORTER_OTLP_PROTOCOL"));
assert!(config.warnings[1].contains("FLARE_TRACES_SAMPLE_RATE"));
}
#[test]
fn keeps_the_error_of_the_dotenv_file_as_a_warning() {
let dotenv = DotenvFile::with_error("bad line");
let config = Config::from_sources(|_| None, &dotenv).debug(true);
assert_eq!(config.warnings.len(), 1, "{:?}", config.warnings);
assert!(config.warnings[0].contains("bad line"));
}
#[test]
fn app_crate_accepts_a_name_with_hyphens() {
let config = Config::defaults().app_crate("my-billing");
let file =
std::path::Path::new("/home/me/.cargo/registry/src/index/my-billing-1.0.0/src/lib.rs");
assert_eq!(config.app_crates, ["my_billing"]);
assert!(crate::source_path::is_application_file(
file,
&config.app_crates
));
}
#[test]
fn valid_variables_give_no_warnings() {
let config = from([("FLARE_TRACES_SAMPLE_RATE", "0.5")]);
assert_eq!(config.warnings.len(), 0);
}
#[test]
fn ignores_a_debug_setting_that_is_not_1() {
assert!(!from([("FLARE_DEBUG", "yes")]).debug);
}
#[test]
fn ignores_an_unknown_protocol() {
let config = from([("OTEL_EXPORTER_OTLP_PROTOCOL", "grpc")]);
assert_eq!(config.otlp_protocol, OtlpProtocol::HttpProtobuf);
}
#[test]
fn sends_protobuf_by_default() {
assert_eq!(from([]).otlp_protocol, OtlpProtocol::HttpProtobuf);
}
#[test]
fn reads_settings_from_the_dotenv_file() {
let dotenv = DotenvFile::from_variables([("FLARE_KEY", "secret")]);
let config = Config::from_sources(|_| None, &dotenv);
assert_eq!(config.api_key.as_deref(), Some("secret"));
}
#[test]
fn environment_variables_win_over_the_dotenv_file() {
let dotenv = DotenvFile::from_variables([
("FLARE_KEY", "from-file"),
("FLARE_ENVIRONMENT", "staging"),
]);
let config = Config::from_sources(
|name| (name == "FLARE_KEY").then(|| "from-environment".to_owned()),
&dotenv,
);
assert_eq!(config.api_key.as_deref(), Some("from-environment"));
assert_eq!(config.environment.as_deref(), Some("staging"));
}
#[test]
fn code_wins_over_environment_variables() {
let config = from([("FLARE_ENVIRONMENT", "staging")]).environment("production");
assert_eq!(config.environment.as_deref(), Some("production"));
}
}