flareapp-core 0.2.0

The core of the Flare client: config, the client, and the worker thread that sends data.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
use std::borrow::Cow;
use std::cell::Cell;
use std::error::Error;
use std::fmt;
use std::io;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, Receiver, SyncSender, TrySendError};
use std::sync::{Arc, Mutex, OnceLock, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};

use flareapp_otlp::{LogRecord, Span};

use crate::config::{BeforeSend, Config};
use crate::debug::flare_debug;
use crate::report::{Report, ReportId};
use crate::scope;
use crate::time::later;
use crate::worker::{FlushWaiter, Log, Message, Worker};

/// The global Flare client.
///
/// [`init`] stores the client here, and public functions like [`flush`] read it
/// from here. It is `None` before `init` runs, after the [`Guard`] is dropped,
/// and when the Flare client is disabled.
static CLIENT: RwLock<Option<Arc<Client>>> = RwLock::new(None);

/// A function that gets every report that the client queued. See
/// [`set_report_listener`].
static REPORT_LISTENER: OnceLock<fn(QueuedReport)> = OnceLock::new();

/// Sets a function that gets every report that the client queued. Only the first
/// call has an effect.
///
/// The function runs on the thread that made the report, right after the client
/// queued the report. A report that the `before_send` hook dropped, or that did
/// not fit in the queue, does not reach the function.
///
/// The `tracing` integration uses this function to add the error to the current
/// span.
pub fn set_report_listener(listener: fn(QueuedReport)) {
    let _ = REPORT_LISTENER.set(listener);
}

/// The parts of a queued error report that the report listener gets. See
/// [`set_report_listener`].
///
/// The listener does not get the [`Report`] itself, because the report moves
/// into the queue.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct QueuedReport {
    /// The tracking id of the report.
    pub id: ReportId,
    /// The exception class, like `std::io::error::Error`.
    pub exception_class: String,
    /// The message of the error.
    pub message: String,
    /// `true` when your code handled the error, and `false` for a panic.
    pub handled: bool,
}

impl QueuedReport {
    fn new(report: &Report) -> Self {
        Self {
            id: report.id(),
            exception_class: report.exception_class().to_owned(),
            message: report.message().to_owned(),
            handled: report.handled(),
        }
    }
}

/// A call of the report listener for one report.
///
/// The client prepares the call before the report moves into the queue. The
/// client runs the call only when the report reached the queue.
struct ListenerCall(Option<(fn(QueuedReport), QueuedReport)>);

impl ListenerCall {
    /// Takes the parts of `report` that the report listener needs. Takes nothing
    /// when no report listener is set.
    fn new(report: &Report) -> Self {
        Self(
            REPORT_LISTENER
                .get()
                .map(|listener| (*listener, QueuedReport::new(report))),
        )
    }

    fn run(self) {
        if let Some((listener, report)) = self.0 {
            listener(report);
        }
    }
}

/// The name of the worker thread, shown in debuggers and panic messages.
const WORKER_THREAD_NAME: &str = "flare-worker";

thread_local! {
    /// `true` on the worker thread. [`is_worker_thread`] reads it.
    ///
    /// This is a flag and not a check of the thread name, because an app thread
    /// can have the same name.
    static IS_WORKER_THREAD: Cell<bool> = const { Cell::new(false) };
}

/// Hands telemetry to the worker thread and controls the thread's lifetime.
///
/// The client puts records on a queue. The worker thread takes them off the
/// queue, groups them into batches and sends them to Flare.
///
/// Applications use [`init`], which creates the global client. Integrations get
/// the global client with [`current`].
pub struct Client {
    sender: SyncSender<Message>,
    debug: bool,
    shutdown_timeout: Duration,
    before_send: Option<BeforeSend>,
    app_crates: Vec<String>,
    application_path: Option<String>,
    workspace_root: Option<String>,
    traces_sample_rate: f64,
    censor_client_ips: bool,
    /// `true` when the resource already has a framework, from the config or from an
    /// earlier [`Client::set_framework`] call.
    has_framework: AtomicBool,
    worker: Mutex<Option<WorkerThread>>,
}

/// The worker thread, kept so the client can wait for it to stop.
#[derive(Debug)]
struct WorkerThread {
    handle: JoinHandle<()>,
    /// Gets a message when the worker thread has finished. [`JoinHandle::join`]
    /// has no timeout, so `close` waits on this channel with a timeout. `close`
    /// joins the worker thread only after the worker thread has finished.
    stopped: Receiver<()>,
}

/// The reason why [`Client::start`] did not start a client.
#[derive(Debug)]
#[non_exhaustive]
pub enum StartError {
    /// No API key is set, so the Flare client is disabled.
    NoApiKey,
    /// The config has no [`Transport`](crate::Transport) to send requests with.
    NoTransport,
    /// The operating system did not start the worker thread.
    Spawn(io::Error),
}

impl fmt::Display for StartError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::NoApiKey => "no API key set",
            Self::NoTransport => "no transport set",
            Self::Spawn(_) => "could not start the worker thread",
        })
    }
}

impl Error for StartError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Spawn(error) => Some(error),
            Self::NoApiKey | Self::NoTransport => None,
        }
    }
}

impl Client {
    /// Starts the worker thread and returns a client that sends to it.
    ///
    /// With [`Config::debug`] on, this function first prints the warnings about
    /// the environment variables and the `.env` file. The warnings also print when
    /// the client does not start, for example without an API key.
    ///
    /// # Errors
    ///
    /// Returns a [`StartError`] when the Flare client cannot send anything: when
    /// no API key is set, when no transport is set, or when the operating system
    /// does not start the worker thread.
    pub fn start(mut config: Config) -> Result<Self, StartError> {
        for warning in &config.warnings {
            flare_debug!(config.debug, WARN, "{warning}");
        }
        let api_key = config.api_key.take().ok_or(StartError::NoApiKey)?;
        let transport = config.transport.take().ok_or(StartError::NoTransport)?;

        let worker = Worker::new(&config, transport, api_key);
        let (sender, messages) = mpsc::sync_channel(config.queue_capacity);
        let (stopped_sender, stopped) = mpsc::sync_channel(1);

        let handle = thread::Builder::new()
            .name(WORKER_THREAD_NAME.to_owned())
            .spawn(move || {
                IS_WORKER_THREAD.set(true);
                worker.run(&messages);
                let _ = stopped_sender.send(());
            })
            .map_err(StartError::Spawn)?;

        Ok(Self {
            sender,
            debug: config.debug,
            shutdown_timeout: config.shutdown_timeout,
            before_send: config.before_send,
            app_crates: config.app_crates,
            application_path: config.application_path,
            workspace_root: config.workspace_root,
            traces_sample_rate: config.traces_sample_rate,
            censor_client_ips: config.censor_client_ips,
            has_framework: AtomicBool::new(config.framework.is_some()),
            worker: Mutex::new(Some(WorkerThread { handle, stopped })),
        })
    }

    /// Queues a log record for sending. Returns right away.
    ///
    /// `target` is the `tracing` or `log` target that wrote the record, like
    /// `my_app::billing`. It becomes the name of the record's instrumentation
    /// scope, which Flare shows as the target of the log.
    pub fn send_log<S: Into<Cow<'static, str>>>(&self, target: S, record: LogRecord) {
        self.send(Message::Log(Log {
            target: target.into(),
            record,
        }));
    }

    /// Queues all finished spans of one trace for sending. Returns right away.
    ///
    /// Flare drops a span when its parent is not in the same request, so the
    /// spans of a trace always go out together.
    pub fn send_trace(&self, spans: Vec<Span>) {
        if !spans.is_empty() {
            self.send(Message::Trace(spans));
        }
    }

    /// Returns the share of traces to send, from 0.0 (none) to 1.0 (all).
    pub fn traces_sample_rate(&self) -> f64 {
        self.traces_sample_rate
    }

    /// Adds the framework the app runs on to the resource, as
    /// `flare.framework.name` and `flare.framework.version`. Flare shows it with
    /// every error, log and trace that is sent after this call.
    ///
    /// Web integrations call this when they detect their framework. Only the first
    /// call counts, and a framework from [`Config::framework`] wins.
    pub fn set_framework<N: Into<String>>(&self, name: N, version: Option<String>) {
        if !self.has_framework.swap(true, Ordering::Relaxed) {
            self.send(Message::Framework(name.into(), version));
        }
    }

    /// Returns `true` when the IP address of a client must not be sent. See
    /// [`Config::censor_client_ips`].
    pub fn censors_client_ips(&self) -> bool {
        self.censor_client_ips
    }

    /// Queues an error report for sending. Returns right away.
    ///
    /// Adds the current scope first, then runs the `before_send` hook. Returns the
    /// tracking id. Returns `None` when the hook dropped the report. Also returns
    /// `None` when the queue was full or the worker thread had stopped, because
    /// the client then did not queue the report.
    pub fn send_report(&self, report: Report) -> Option<ReportId> {
        let report = self.prepare_report(report)?;
        let id = report.id();
        let listener = ListenerCall::new(&report);

        if !self.send(Message::Report(Box::new(report))) {
            return None;
        }
        listener.run();

        Some(id)
    }

    /// Queues an error report and waits until it is sent, or until the shutdown
    /// timeout has passed. When the queue is full, this function waits for room
    /// and does not drop the report.
    ///
    /// Returns `None` when the `before_send` hook dropped the report, or when the
    /// queue had no room before the timeout.
    ///
    /// The panic integration uses this function, because the process can end
    /// right after a panic.
    pub fn send_report_and_wait(&self, report: Report) -> Option<ReportId> {
        let deadline = later(Instant::now(), self.shutdown_timeout);
        let report = self.prepare_report(report)?;
        let id = report.id();
        let listener = ListenerCall::new(&report);

        if let Err(error) = self.send_until(Message::Report(Box::new(report)), deadline) {
            flare_debug!(self.debug, WARN, "{error}, dropped a report");
            return None;
        }
        listener.run();

        let _ = self.flush_until(deadline);

        Some(id)
    }

    /// Resolves the entry point and adds the current scope. Then runs the
    /// `before_send` hook. Returns `None` when the `before_send` hook drops the
    /// report.
    fn prepare_report(&self, mut report: Report) -> Option<Report> {
        report.resolve_entry_point();
        report.attach(
            scope::current_scope(),
            self.application_path.clone(),
            self.workspace_root.as_deref(),
        );

        if let Some(before_send) = &self.before_send
            && !before_send(&mut report)
        {
            return None;
        }

        Some(report)
    }

    /// Returns the crates whose frames count as application code.
    pub fn app_crates(&self) -> &[String] {
        &self.app_crates
    }

    /// Puts a message on the queue without waiting.
    ///
    /// When the queue is full, or the worker thread has stopped, the message is
    /// dropped. That way, a slow network never slows down the application.
    ///
    /// Returns `true` when the client queued the message.
    fn send(&self, message: Message) -> bool {
        if let Err(error) = self.sender.try_send(message) {
            let error = QueueError::from(error);
            flare_debug!(self.debug, WARN, "{error}, dropped a record");

            return false;
        }

        true
    }

    /// Puts a message on the queue. When the queue is full, this function tries
    /// again every 5 ms until `deadline`. The worker thread takes messages off the
    /// queue in the meantime.
    fn send_until(&self, mut message: Message, deadline: Instant) -> Result<(), QueueError> {
        loop {
            match self.sender.try_send(message) {
                Ok(()) => return Ok(()),
                Err(TrySendError::Full(returned)) if Instant::now() < deadline => {
                    message = returned;
                    thread::sleep(Duration::from_millis(5));
                }
                Err(error) => return Err(error.into()),
            }
        }
    }

    /// Waits until the worker thread has sent everything in the queue, or until
    /// `timeout` has passed. Returns `true` when nothing is left to send.
    ///
    /// Data that Flare refused, or that still failed after all retries, is dropped
    /// and also counts as done. When the worker thread must wait longer than
    /// `timeout` before the next retry, for example because of a `Retry-After`
    /// header, this function returns `false` right away.
    pub fn flush(&self, timeout: Duration) -> bool {
        self.flush_until(later(Instant::now(), timeout))
            .unwrap_or(false)
    }

    /// Same as [`Client::flush`], but with an end time instead of a duration.
    /// Returns an error when the flush request did not reach the queue.
    fn flush_until(&self, deadline: Instant) -> Result<bool, QueueError> {
        let (flushed_sender, flushed) = mpsc::sync_channel(1);
        let waiter = FlushWaiter {
            flushed_sender,
            deadline,
        };
        self.send_until(Message::Flush(waiter), deadline)?;

        Ok(flushed
            .recv_timeout(deadline.saturating_duration_since(Instant::now()))
            .unwrap_or(false))
    }

    /// Sends everything that is still queued, then stops the worker thread.
    ///
    /// Waits at most `shutdown_timeout` in total. When the worker thread is still
    /// busy after that, for example on a slow network, this function stops
    /// waiting, and the worker thread finishes on its own.
    fn close(&self) {
        let deadline = later(Instant::now(), self.shutdown_timeout);

        match self.flush_until(deadline) {
            Ok(true) => {}
            Ok(false) => flare_debug!(
                self.debug,
                WARN,
                "shutdown timeout reached, some data was not sent"
            ),
            Err(error) => flare_debug!(self.debug, WARN, "{error}, some data was not sent"),
        }

        let _ = self.sender.try_send(Message::Shutdown);

        // A poisoned lock is fine here, for the same reason as in `read_client`.
        let Some(worker) = self
            .worker
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
            .take()
        else {
            return;
        };

        let remaining = deadline.saturating_duration_since(Instant::now());
        if worker.stopped.recv_timeout(remaining).is_ok() {
            let _ = worker.handle.join();
        }
    }
}

/// The reason why a message did not reach the worker thread.
#[derive(Debug, Clone, Copy)]
enum QueueError {
    /// The queue had no room.
    Full,
    /// The worker thread has stopped, so nothing reads the queue anymore. This
    /// happens when code on the worker thread panics.
    Stopped,
}

impl<T> From<TrySendError<T>> for QueueError {
    fn from(error: TrySendError<T>) -> Self {
        match error {
            TrySendError::Full(_) => Self::Full,
            TrySendError::Disconnected(_) => Self::Stopped,
        }
    }
}

impl fmt::Display for QueueError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            Self::Full => "queue full",
            Self::Stopped => "the worker thread has stopped",
        })
    }
}

/// Returns `true` on the worker thread. Integrations use this function to skip
/// their work on the worker thread, because the worker thread must not wait for
/// itself.
pub fn is_worker_thread() -> bool {
    IS_WORKER_THREAD.try_with(Cell::get).unwrap_or(false)
}

/// Returns the global client, or `None` when the Flare client is not running.
pub fn current() -> Option<Arc<Client>> {
    read_client().clone()
}

/// Locks the global client for reading.
///
/// A panic in another thread poisons the lock. The client inside stays valid, so
/// Flare keeps using it.
fn read_client() -> RwLockReadGuard<'static, Option<Arc<Client>>> {
    CLIENT.read().unwrap_or_else(PoisonError::into_inner)
}

/// Locks the global client for writing. A poisoned lock is fine here, for the
/// same reason as in [`read_client`].
fn write_client() -> RwLockWriteGuard<'static, Option<Arc<Client>>> {
    CLIENT.write().unwrap_or_else(PoisonError::into_inner)
}

/// Returns the global client, unless this is the worker thread.
///
/// Integrations use this function to capture data. The HTTP client on the worker
/// thread also writes logs. If the Flare client captures those logs, each send
/// creates new logs to send, without end.
pub fn active_client() -> Option<Arc<Client>> {
    if is_worker_thread() { None } else { current() }
}

/// Starts the Flare client and returns a guard that keeps it running.
///
/// Without an API key, the Flare client stays disabled. All functions still work,
/// but they do nothing. With [`Config::debug`] on, this function prints the
/// warnings about the environment variables and the `.env` file, and why the Flare
/// client did not start.
///
/// Keep the guard until your program ends. When the guard is dropped, it sends
/// the queued data and stops the Flare client.
///
/// The config needs a [`Transport`](crate::Transport). The `flareapp` crate sets
/// its default HTTP client before it calls this function.
pub fn init(config: Config) -> Guard {
    let debug = config.debug;
    let client = match Client::start(config) {
        Ok(client) => Some(Arc::new(client)),
        Err(StartError::Spawn(error)) => {
            flare_debug!(debug, ERROR, "could not start the worker thread: {error}");
            None
        }
        Err(error) => {
            flare_debug!(debug, WARN, "{error}, Flare is disabled");
            None
        }
    };

    write_client().clone_from(&client);

    Guard { client }
}

/// Waits until all queued logs, spans and error reports are sent, or until
/// `timeout` has passed. Returns `true` when nothing is left to send.
///
/// When the Flare client is disabled, nothing is queued, so this function also
/// returns `true`. [`Client::flush`] explains the other cases.
pub fn flush(timeout: Duration) -> bool {
    current().is_none_or(|client| client.flush(timeout))
}

/// A handle that keeps the Flare client running. [`init`] returns the guard.
///
/// When you drop the guard, the guard sends the queued data and stops the Flare
/// client. The guard waits at most [`Config::shutdown_timeout`] for the data.
#[must_use = "Flare stops when the guard is dropped; keep it with `let _flare = …`"]
pub struct Guard {
    client: Option<Arc<Client>>,
}

impl Guard {
    /// Returns `true` when the Flare client is running. The Flare client is
    /// disabled when it did not start, for example without an API key.
    pub fn is_enabled(&self) -> bool {
        self.client.is_some()
    }
}

impl Drop for Guard {
    fn drop(&mut self) {
        let Some(client) = self.client.take() else {
            return;
        };

        {
            let mut installed = write_client();
            // When `init` was called again, the global client is a newer one.
            // Only remove the global client when it is still the client of this
            // guard.
            if installed
                .as_ref()
                .is_some_and(|current| Arc::ptr_eq(current, &client))
            {
                *installed = None;
            }
        }

        client.close();
    }
}

impl fmt::Debug for Client {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Client")
            .field("debug", &self.debug)
            .field("shutdown_timeout", &self.shutdown_timeout)
            .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("has_framework", &self.has_framework)
            .finish_non_exhaustive()
    }
}

impl fmt::Debug for Guard {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Guard")
            .field("enabled", &self.is_enabled())
            .finish()
    }
}

#[cfg(test)]
mod tests {

    use super::*;
    use crate::config::OtlpProtocol;
    use crate::test_support::{
        FakeTransport, GatedTransport, json, json_attribute, log, serial, span,
    };
    use crate::transport::{Request, Response, Signal, Transport, TransportError};
    use crate::worker::RetryPolicy;

    const WAIT: Duration = Duration::from_secs(2);

    /// A config that sends logs and traces as JSON, so tests can read the bodies.
    fn config(transport: &FakeTransport) -> Config {
        Config::new()
            .api_key("secret")
            .endpoint("https://ingress.test/")
            .otlp_protocol(OtlpProtocol::HttpJson)
            .batch_interval(Duration::from_secs(60))
            .transport(transport.clone())
            .retry(RetryPolicy {
                max_retries: 3,
                base_delay: Duration::from_millis(1),
                max_delay: Duration::from_millis(1),
            })
    }

    fn record_count(request: &Request) -> usize {
        json(request)["resourceLogs"][0]["scopeLogs"][0]["logRecords"]
            .as_array()
            .map_or(0, Vec::len)
    }

    /// Returns the resource attribute `key` of the first request, as JSON.
    fn resource_attribute(transport: &FakeTransport, key: &str) -> Option<serde_json::Value> {
        let body = json(&transport.requests()[0]);

        json_attribute(&body["resourceLogs"][0]["resource"], key).cloned()
    }

    fn content_type(request: &Request) -> Option<&str> {
        request
            .headers
            .iter()
            .find(|(name, _)| *name == "content-type")
            .map(|(_, value)| value.as_str())
    }

    fn report() -> Report {
        Report::new(
            "my_app::PaymentFailed",
            "payment failed",
            std::panic::Location::caller(),
        )
    }

    #[test]
    fn is_disabled_without_an_api_key() {
        let transport = FakeTransport::default();

        let started = Client::start(config(&transport).api_key(""));

        assert!(matches!(started, Err(StartError::NoApiKey)));
    }

    #[test]
    fn does_not_start_without_a_transport() {
        let started = Client::start(Config::new().api_key("test-key"));

        assert!(matches!(started, Err(StartError::NoTransport)));
    }

    #[test]
    fn start_errors_say_what_is_missing() {
        assert_eq!(StartError::NoApiKey.to_string(), "no API key set");
    }

    #[test]
    fn a_spawn_error_keeps_the_error_of_the_operating_system_as_its_source() {
        let error = StartError::Spawn(io::Error::other("no threads left"));

        let source = error.source().map(ToString::to_string);

        assert_eq!(source.as_deref(), Some("no threads left"));
    }

    #[test]
    fn sends_logs_in_one_batch_on_flush() {
        let transport = FakeTransport::default();
        let client = Client::start(config(&transport)).unwrap();

        client.send_log("shop", log("one"));
        client.send_log("shop", log("two"));
        client.send_log("shop", log("three"));

        assert!(client.flush(WAIT));
        let counts: Vec<usize> = transport.requests().iter().map(record_count).collect();
        assert_eq!(counts, [3]);
    }

    #[test]
    fn the_first_framework_goes_on_the_resource() {
        let transport = FakeTransport::default();
        let client = Client::start(config(&transport)).unwrap();

        client.set_framework("axum", None);
        client.set_framework("actix", Some("4.17.0".to_owned()));
        client.send_log("shop", log("one"));

        assert!(client.flush(WAIT));
        assert_eq!(
            resource_attribute(&transport, "flare.framework.name"),
            Some(serde_json::json!({ "stringValue": "axum" }))
        );
        assert_eq!(
            resource_attribute(&transport, "flare.framework.version"),
            None
        );
    }

    #[test]
    fn the_framework_of_the_config_wins() {
        let transport = FakeTransport::default();
        let client =
            Client::start(config(&transport).framework("omega", Some("1.0.0".to_owned()))).unwrap();

        client.set_framework("axum", None);
        client.send_log("shop", log("one"));

        assert!(client.flush(WAIT));
        assert_eq!(
            resource_attribute(&transport, "flare.framework.name"),
            Some(serde_json::json!({ "stringValue": "omega" }))
        );
    }

    #[test]
    fn reads_the_git_commit_from_the_application_path() {
        let transport = FakeTransport::default();
        let repository = crate::resource::git::test_repository();
        let client =
            Client::start(config(&transport).application_path(repository.to_string_lossy()))
                .unwrap();

        client.send_log("shop", log("one"));

        assert!(client.flush(WAIT));
        let _ = std::fs::remove_dir_all(&repository);
        assert_eq!(
            resource_attribute(&transport, "git.tag"),
            Some(serde_json::json!({ "stringValue": "v1.0.0" }))
        );
    }

    #[test]
    fn logs_go_to_the_logs_endpoint() {
        let transport = FakeTransport::default();
        let client = Client::start(config(&transport)).unwrap();

        client.send_log("shop", log("one"));

        assert!(client.flush(WAIT));
        let requests = transport.requests();
        assert_eq!(requests[0].signal, Signal::Logs);
        assert_eq!(requests[0].url, "https://ingress.test/v1/logs");
    }

    /// Sends one log, and returns the headers of the request.
    fn log_request_headers() -> Vec<(&'static str, String)> {
        let transport = FakeTransport::default();
        let client = Client::start(config(&transport)).unwrap();

        client.send_log("shop", log("one"));

        assert!(client.flush(WAIT));

        transport.requests().remove(0).headers
    }

    #[test]
    fn requests_carry_the_api_key() {
        let headers = log_request_headers();

        assert!(
            headers.contains(&("x-api-token", "secret".to_owned())),
            "{headers:?}"
        );
    }

    #[test]
    fn requests_carry_the_content_type() {
        let headers = log_request_headers();

        assert!(
            headers.contains(&("content-type", "application/json".to_owned())),
            "{headers:?}"
        );
    }

    #[test]
    fn sends_logs_and_traces_as_protobuf_by_default() {
        let transport = FakeTransport::default();
        let client =
            Client::start(config(&transport).otlp_protocol(OtlpProtocol::default())).unwrap();

        client.send_log("shop", log("one"));
        client.send_trace(vec![span()]);

        assert!(client.flush(WAIT));
        let requests = transport.requests();
        let content_types: Vec<_> = requests.iter().map(content_type).collect();
        assert_eq!(
            content_types,
            [
                Some("application/x-protobuf"),
                Some("application/x-protobuf")
            ]
        );
    }

    #[test]
    fn sends_error_reports_as_json_with_protobuf() {
        let transport = FakeTransport::default();
        let client =
            Client::start(config(&transport).otlp_protocol(OtlpProtocol::HttpProtobuf)).unwrap();

        client.send_report(Report::new(
            "my_app::PaymentFailed",
            "payment failed",
            std::panic::Location::caller(),
        ));

        assert!(client.flush(WAIT));
        let requests = transport.requests();
        assert_eq!(content_type(&requests[0]), Some("application/json"));
        assert_eq!(json(&requests[0])["message"], "payment failed");
    }

    #[test]
    fn sends_full_batches_without_waiting() {
        let transport = FakeTransport::default();
        let client = Client::start(config(&transport).batch_size(2)).unwrap();

        for body in ["one", "two", "three", "four"] {
            client.send_log("shop", log(body));
        }

        let counts: Vec<usize> = transport
            .wait_for_requests(2, WAIT)
            .iter()
            .map(record_count)
            .collect();
        assert_eq!(counts, [2, 2]);
    }

    #[test]
    fn sends_after_the_batch_interval() {
        let transport = FakeTransport::default();
        let client =
            Client::start(config(&transport).batch_interval(Duration::from_millis(20))).unwrap();

        client.send_log("shop", log("one"));

        assert_eq!(transport.wait_for_requests(1, WAIT).len(), 1);
    }

    #[test]
    fn sends_spans_to_the_traces_endpoint() {
        let transport = FakeTransport::default();
        let client = Client::start(config(&transport)).unwrap();

        client.send_trace(vec![span()]);

        assert!(client.flush(WAIT));
        let urls: Vec<String> = transport
            .requests()
            .into_iter()
            .map(|request| request.url)
            .collect();
        assert_eq!(urls, ["https://ingress.test/v1/traces"]);
    }

    #[test]
    fn trace_requests_hold_the_spans() {
        let transport = FakeTransport::default();
        let client = Client::start(config(&transport)).unwrap();

        client.send_trace(vec![span()]);

        assert!(client.flush(WAIT));
        assert_eq!(transport.spans().len(), 1);
    }

    #[test]
    fn retries_temporary_failures() {
        let transport = FakeTransport::default();
        transport
            .respond_with(Response::new(503))
            .fail_with("connection reset");
        let client = Client::start(config(&transport)).unwrap();

        client.send_log("shop", log("one"));

        assert!(client.flush(WAIT));
        let bodies: Vec<serde_json::Value> = transport.requests().iter().map(json).collect();
        assert_eq!(
            bodies,
            [bodies[0].clone(), bodies[0].clone(), bodies[0].clone()]
        );
    }

    #[test]
    fn gives_up_after_three_retries() {
        let transport = FakeTransport::default();
        for _ in 0..5 {
            transport.respond_with(Response::new(503));
        }
        let client = Client::start(config(&transport)).unwrap();

        client.send_log("shop", log("one"));

        assert!(client.flush(WAIT));
        assert_eq!(transport.requests().len(), 4);
    }

    #[test]
    fn does_not_retry_rejected_requests() {
        let transport = FakeTransport::default();
        transport.respond_with(Response::new(422));
        let client = Client::start(config(&transport)).unwrap();

        client.send_log("shop", log("one"));

        assert!(client.flush(WAIT));
        assert_eq!(transport.requests().len(), 1);
    }

    #[test]
    fn waits_for_retry_after_without_blocking() {
        let transport = FakeTransport::default();
        transport.respond_with(Response::new(429).with_retry_after_header("60"));
        let client = Client::start(config(&transport)).unwrap();

        client.send_log("shop", log("one"));
        let _ = client.flush(Duration::from_millis(100));

        // The worker still answers while it waits to retry.
        client.send_trace(vec![span()]);
        let _ = client.flush(Duration::from_millis(100));

        let signals: Vec<Signal> = transport
            .requests()
            .iter()
            .map(|request| request.signal)
            .collect();
        assert_eq!(signals, [Signal::Logs, Signal::Traces]);
    }

    #[test]
    fn flush_does_not_wait_for_a_retry_after_its_timeout() {
        let transport = FakeTransport::default();
        transport.respond_with(Response::new(429).with_retry_after_header("60"));
        let client = Client::start(config(&transport)).unwrap();

        client.send_log("shop", log("one"));
        let started = Instant::now();

        assert!(!client.flush(Duration::from_secs(5)));
        assert!(started.elapsed() < Duration::from_secs(1));
    }

    #[test]
    fn a_report_does_not_wait_for_logs_that_retry_later() {
        let transport = FakeTransport::default();
        transport.respond_with(Response::new(429).with_retry_after_header("60"));
        let client =
            Client::start(config(&transport).shutdown_timeout(Duration::from_secs(5))).unwrap();
        client.send_log("shop", log("one"));
        assert!(!client.flush(WAIT));
        let started = Instant::now();

        client.send_report_and_wait(report());

        assert!(started.elapsed() < Duration::from_secs(1));
        assert_eq!(transport.requests()[1].signal, Signal::Errors);
    }

    #[test]
    fn a_report_waits_for_room_in_a_full_queue() {
        let transport = FakeTransport::default();
        let gate = GatedTransport::new(&transport);
        let client = Client::start(
            config(&transport)
                .transport(gate.clone())
                .queue_capacity(1)
                .batch_size(1),
        )
        .unwrap();

        // The worker thread is stuck on the first log, and the second fills the queue.
        client.send_log("shop", log("one"));
        transport.wait_for_requests(1, WAIT);
        client.send_log("shop", log("two"));

        let opener = thread::spawn(move || {
            thread::sleep(Duration::from_millis(50));
            gate.open();
        });
        let id = client.send_report_and_wait(report());
        opener.join().unwrap();

        assert!(id.is_some(), "{id:?}");
        let signals: Vec<Signal> = transport
            .requests()
            .iter()
            .map(|request| request.signal)
            .collect();
        assert!(signals.contains(&Signal::Errors), "{signals:?}");
    }

    #[test]
    fn a_report_that_did_not_fit_in_a_full_queue_has_no_id() {
        let transport = FakeTransport::default();
        let gate = GatedTransport::new(&transport);
        let client = Client::start(
            config(&transport)
                .transport(gate.clone())
                .queue_capacity(1)
                .batch_size(1),
        )
        .unwrap();
        client.send_log("shop", log("one"));
        transport.wait_for_requests(1, WAIT);
        client.send_log("shop", log("two"));

        let id = client.send_report(report());
        gate.open();

        assert_eq!(id, None);
    }

    thread_local! {
        /// The number of reports that [`count_report`] got on this thread.
        static LISTENED_REPORTS: Cell<usize> = const { Cell::new(0) };
    }

    /// A report listener that counts the reports of each thread, so tests on
    /// other threads do not change the count of a test.
    fn count_report(_report: QueuedReport) {
        LISTENED_REPORTS.set(LISTENED_REPORTS.get() + 1);
    }

    #[test]
    fn the_report_listener_gets_only_queued_reports() {
        set_report_listener(count_report);
        let before = LISTENED_REPORTS.get();
        let transport = FakeTransport::default();
        let gate = GatedTransport::new(&transport);
        let client = Client::start(
            config(&transport)
                .transport(gate.clone())
                .queue_capacity(1)
                .batch_size(1),
        )
        .unwrap();

        // The worker thread is stuck on the first report, and the log fills the queue.
        let queued = client.send_report(report());
        transport.wait_for_requests(1, WAIT);
        client.send_log("shop", log("one"));
        let dropped = client.send_report(report());
        gate.open();

        assert!(queued.is_some());
        assert_eq!(dropped, None);
        assert_eq!(LISTENED_REPORTS.get() - before, 1);
    }

    #[test]
    fn the_report_listener_does_not_get_a_report_that_found_no_room_in_time() {
        set_report_listener(count_report);
        let before = LISTENED_REPORTS.get();
        let transport = FakeTransport::default();
        let gate = GatedTransport::new(&transport);
        let client = Client::start(
            config(&transport)
                .transport(gate.clone())
                .queue_capacity(1)
                .batch_size(1)
                .shutdown_timeout(Duration::from_millis(50)),
        )
        .unwrap();
        client.send_log("shop", log("one"));
        transport.wait_for_requests(1, WAIT);
        client.send_log("shop", log("two"));

        let id = client.send_report_and_wait(report());
        gate.open();

        assert_eq!(id, None);
        assert_eq!(LISTENED_REPORTS.get() - before, 0);
    }

    #[test]
    fn reports_go_before_logs_that_wait() {
        let transport = FakeTransport::default();
        let gate = GatedTransport::new(&transport);
        let client =
            Client::start(config(&transport).transport(gate.clone()).batch_size(10)).unwrap();

        // The worker thread is stuck on the first report while logs and a second
        // report queue up behind it.
        client.send_report(report());
        transport.wait_for_requests(1, WAIT);
        for index in 0..30 {
            client.send_log("shop", log(&index.to_string()));
        }
        client.send_report(report());
        gate.open();

        assert!(client.flush(WAIT));
        let signals: Vec<Signal> = transport
            .requests()
            .iter()
            .map(|request| request.signal)
            .collect();
        assert_eq!(signals[..2], [Signal::Errors, Signal::Errors]);
        assert_eq!(signals.len(), 5);
    }

    /// Wraps a [`FakeTransport`] and panics on the first request.
    #[derive(Debug)]
    struct PanicsOnceTransport {
        inner: FakeTransport,
        panicked: AtomicBool,
    }

    impl Transport for PanicsOnceTransport {
        #[expect(
            clippy::manual_assert,
            reason = "the panic is what the test needs, not a check"
        )]
        fn send(&self, request: &Request) -> Result<Response, TransportError> {
            if !self.panicked.swap(true, Ordering::SeqCst) {
                panic!("the connection pool is broken");
            }

            self.inner.send(request)
        }
    }

    #[test]
    fn a_panic_in_the_transport_is_retried_like_a_failed_request() {
        let transport = FakeTransport::default();
        let panics_once = PanicsOnceTransport {
            inner: transport.clone(),
            panicked: AtomicBool::new(false),
        };
        let client = Client::start(config(&transport).transport(panics_once)).unwrap();

        client.send_log("shop", log("one"));

        assert!(client.flush(WAIT));
        assert_eq!(transport.requests().len(), 1);
    }

    /// Answers `201 Created`, and records whether the last request ran on the
    /// worker thread.
    #[derive(Debug, Clone, Default)]
    struct WorkerThreadCheck {
        on_worker_thread: Arc<AtomicBool>,
    }

    impl Transport for WorkerThreadCheck {
        fn send(&self, _request: &Request) -> Result<Response, TransportError> {
            self.on_worker_thread
                .store(is_worker_thread(), Ordering::SeqCst);

            Ok(Response::new(201))
        }
    }

    #[test]
    fn requests_are_sent_on_the_worker_thread() {
        let check = WorkerThreadCheck::default();
        let client =
            Client::start(config(&FakeTransport::default()).transport(check.clone())).unwrap();

        client.send_log("shop", log("one"));

        assert!(client.flush(WAIT));
        assert!(check.on_worker_thread.load(Ordering::SeqCst));
    }

    #[test]
    fn an_app_thread_with_the_name_of_the_worker_thread_is_not_the_worker_thread() {
        let is_worker = thread::Builder::new()
            .name(WORKER_THREAD_NAME.to_owned())
            .spawn(is_worker_thread)
            .unwrap()
            .join()
            .unwrap();

        assert!(!is_worker);
    }

    #[test]
    fn dropping_the_guard_sends_queued_data() {
        let _serial = serial();
        let transport = FakeTransport::default();
        let guard = init(config(&transport));

        current().unwrap().send_log("shop", log("one"));
        drop(guard);

        assert_eq!(transport.requests().len(), 1);
        assert!(current().is_none(), "the Flare client still runs");
    }
}