Skip to main content

flareapp_core/
client.rs

1use std::borrow::Cow;
2use std::cell::Cell;
3use std::error::Error;
4use std::fmt;
5use std::io;
6use std::sync::atomic::{AtomicBool, Ordering};
7use std::sync::mpsc::{self, Receiver, SyncSender, TrySendError};
8use std::sync::{Arc, Mutex, OnceLock, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard};
9use std::thread::{self, JoinHandle};
10use std::time::{Duration, Instant};
11
12use flareapp_otlp::{LogRecord, Span};
13
14use crate::config::{BeforeSend, Config};
15use crate::debug::flare_debug;
16use crate::report::{Report, ReportId};
17use crate::scope;
18use crate::time::later;
19use crate::worker::{FlushWaiter, Log, Message, Worker};
20
21/// The global Flare client.
22///
23/// [`init`] stores the client here, and public functions like [`flush`] read it
24/// from here. It is `None` before `init` runs, after the [`Guard`] is dropped,
25/// and when the Flare client is disabled.
26static CLIENT: RwLock<Option<Arc<Client>>> = RwLock::new(None);
27
28/// A function that gets every report that the client queued. See
29/// [`set_report_listener`].
30static REPORT_LISTENER: OnceLock<fn(QueuedReport)> = OnceLock::new();
31
32/// Sets a function that gets every report that the client queued. Only the first
33/// call has an effect.
34///
35/// The function runs on the thread that made the report, right after the client
36/// queued the report. A report that the `before_send` hook dropped, or that did
37/// not fit in the queue, does not reach the function.
38///
39/// The `tracing` integration uses this function to add the error to the current
40/// span.
41pub fn set_report_listener(listener: fn(QueuedReport)) {
42    let _ = REPORT_LISTENER.set(listener);
43}
44
45/// The parts of a queued error report that the report listener gets. See
46/// [`set_report_listener`].
47///
48/// The listener does not get the [`Report`] itself, because the report moves
49/// into the queue.
50#[derive(Debug, Clone)]
51#[non_exhaustive]
52pub struct QueuedReport {
53    /// The tracking id of the report.
54    pub id: ReportId,
55    /// The exception class, like `std::io::error::Error`.
56    pub exception_class: String,
57    /// The message of the error.
58    pub message: String,
59    /// `true` when your code handled the error, and `false` for a panic.
60    pub handled: bool,
61}
62
63impl QueuedReport {
64    fn new(report: &Report) -> Self {
65        Self {
66            id: report.id(),
67            exception_class: report.exception_class().to_owned(),
68            message: report.message().to_owned(),
69            handled: report.handled(),
70        }
71    }
72}
73
74/// A call of the report listener for one report.
75///
76/// The client prepares the call before the report moves into the queue. The
77/// client runs the call only when the report reached the queue.
78struct ListenerCall(Option<(fn(QueuedReport), QueuedReport)>);
79
80impl ListenerCall {
81    /// Takes the parts of `report` that the report listener needs. Takes nothing
82    /// when no report listener is set.
83    fn new(report: &Report) -> Self {
84        Self(
85            REPORT_LISTENER
86                .get()
87                .map(|listener| (*listener, QueuedReport::new(report))),
88        )
89    }
90
91    fn run(self) {
92        if let Some((listener, report)) = self.0 {
93            listener(report);
94        }
95    }
96}
97
98/// The name of the worker thread, shown in debuggers and panic messages.
99const WORKER_THREAD_NAME: &str = "flare-worker";
100
101thread_local! {
102    /// `true` on the worker thread. [`is_worker_thread`] reads it.
103    ///
104    /// This is a flag and not a check of the thread name, because an app thread
105    /// can have the same name.
106    static IS_WORKER_THREAD: Cell<bool> = const { Cell::new(false) };
107}
108
109/// Hands telemetry to the worker thread and controls the thread's lifetime.
110///
111/// The client puts records on a queue. The worker thread takes them off the
112/// queue, groups them into batches and sends them to Flare.
113///
114/// Applications use [`init`], which creates the global client. Integrations get
115/// the global client with [`current`].
116pub struct Client {
117    sender: SyncSender<Message>,
118    debug: bool,
119    shutdown_timeout: Duration,
120    before_send: Option<BeforeSend>,
121    app_crates: Vec<String>,
122    application_path: Option<String>,
123    workspace_root: Option<String>,
124    traces_sample_rate: f64,
125    censor_client_ips: bool,
126    /// `true` when the resource already has a framework, from the config or from an
127    /// earlier [`Client::set_framework`] call.
128    has_framework: AtomicBool,
129    worker: Mutex<Option<WorkerThread>>,
130}
131
132/// The worker thread, kept so the client can wait for it to stop.
133#[derive(Debug)]
134struct WorkerThread {
135    handle: JoinHandle<()>,
136    /// Gets a message when the worker thread has finished. [`JoinHandle::join`]
137    /// has no timeout, so `close` waits on this channel with a timeout. `close`
138    /// joins the worker thread only after the worker thread has finished.
139    stopped: Receiver<()>,
140}
141
142/// The reason why [`Client::start`] did not start a client.
143#[derive(Debug)]
144#[non_exhaustive]
145pub enum StartError {
146    /// No API key is set, so the Flare client is disabled.
147    NoApiKey,
148    /// The config has no [`Transport`](crate::Transport) to send requests with.
149    NoTransport,
150    /// The operating system did not start the worker thread.
151    Spawn(io::Error),
152}
153
154impl fmt::Display for StartError {
155    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
156        f.write_str(match self {
157            Self::NoApiKey => "no API key set",
158            Self::NoTransport => "no transport set",
159            Self::Spawn(_) => "could not start the worker thread",
160        })
161    }
162}
163
164impl Error for StartError {
165    fn source(&self) -> Option<&(dyn Error + 'static)> {
166        match self {
167            Self::Spawn(error) => Some(error),
168            Self::NoApiKey | Self::NoTransport => None,
169        }
170    }
171}
172
173impl Client {
174    /// Starts the worker thread and returns a client that sends to it.
175    ///
176    /// With [`Config::debug`] on, this function first prints the warnings about
177    /// the environment variables and the `.env` file. The warnings also print when
178    /// the client does not start, for example without an API key.
179    ///
180    /// # Errors
181    ///
182    /// Returns a [`StartError`] when the Flare client cannot send anything: when
183    /// no API key is set, when no transport is set, or when the operating system
184    /// does not start the worker thread.
185    pub fn start(mut config: Config) -> Result<Self, StartError> {
186        for warning in &config.warnings {
187            flare_debug!(config.debug, WARN, "{warning}");
188        }
189        let api_key = config.api_key.take().ok_or(StartError::NoApiKey)?;
190        let transport = config.transport.take().ok_or(StartError::NoTransport)?;
191
192        let worker = Worker::new(&config, transport, api_key);
193        let (sender, messages) = mpsc::sync_channel(config.queue_capacity);
194        let (stopped_sender, stopped) = mpsc::sync_channel(1);
195
196        let handle = thread::Builder::new()
197            .name(WORKER_THREAD_NAME.to_owned())
198            .spawn(move || {
199                IS_WORKER_THREAD.set(true);
200                worker.run(&messages);
201                let _ = stopped_sender.send(());
202            })
203            .map_err(StartError::Spawn)?;
204
205        Ok(Self {
206            sender,
207            debug: config.debug,
208            shutdown_timeout: config.shutdown_timeout,
209            before_send: config.before_send,
210            app_crates: config.app_crates,
211            application_path: config.application_path,
212            workspace_root: config.workspace_root,
213            traces_sample_rate: config.traces_sample_rate,
214            censor_client_ips: config.censor_client_ips,
215            has_framework: AtomicBool::new(config.framework.is_some()),
216            worker: Mutex::new(Some(WorkerThread { handle, stopped })),
217        })
218    }
219
220    /// Queues a log record for sending. Returns right away.
221    ///
222    /// `target` is the `tracing` or `log` target that wrote the record, like
223    /// `my_app::billing`. It becomes the name of the record's instrumentation
224    /// scope, which Flare shows as the target of the log.
225    pub fn send_log<S: Into<Cow<'static, str>>>(&self, target: S, record: LogRecord) {
226        self.send(Message::Log(Log {
227            target: target.into(),
228            record,
229        }));
230    }
231
232    /// Queues all finished spans of one trace for sending. Returns right away.
233    ///
234    /// Flare drops a span when its parent is not in the same request, so the
235    /// spans of a trace always go out together.
236    pub fn send_trace(&self, spans: Vec<Span>) {
237        if !spans.is_empty() {
238            self.send(Message::Trace(spans));
239        }
240    }
241
242    /// Returns the share of traces to send, from 0.0 (none) to 1.0 (all).
243    pub fn traces_sample_rate(&self) -> f64 {
244        self.traces_sample_rate
245    }
246
247    /// Adds the framework the app runs on to the resource, as
248    /// `flare.framework.name` and `flare.framework.version`. Flare shows it with
249    /// every error, log and trace that is sent after this call.
250    ///
251    /// Web integrations call this when they detect their framework. Only the first
252    /// call counts, and a framework from [`Config::framework`] wins.
253    pub fn set_framework<N: Into<String>>(&self, name: N, version: Option<String>) {
254        if !self.has_framework.swap(true, Ordering::Relaxed) {
255            self.send(Message::Framework(name.into(), version));
256        }
257    }
258
259    /// Returns `true` when the IP address of a client must not be sent. See
260    /// [`Config::censor_client_ips`].
261    pub fn censors_client_ips(&self) -> bool {
262        self.censor_client_ips
263    }
264
265    /// Queues an error report for sending. Returns right away.
266    ///
267    /// Adds the current scope first, then runs the `before_send` hook. Returns the
268    /// tracking id. Returns `None` when the hook dropped the report. Also returns
269    /// `None` when the queue was full or the worker thread had stopped, because
270    /// the client then did not queue the report.
271    pub fn send_report(&self, report: Report) -> Option<ReportId> {
272        let report = self.prepare_report(report)?;
273        let id = report.id();
274        let listener = ListenerCall::new(&report);
275
276        if !self.send(Message::Report(Box::new(report))) {
277            return None;
278        }
279        listener.run();
280
281        Some(id)
282    }
283
284    /// Queues an error report and waits until it is sent, or until the shutdown
285    /// timeout has passed. When the queue is full, this function waits for room
286    /// and does not drop the report.
287    ///
288    /// Returns `None` when the `before_send` hook dropped the report, or when the
289    /// queue had no room before the timeout.
290    ///
291    /// The panic integration uses this function, because the process can end
292    /// right after a panic.
293    pub fn send_report_and_wait(&self, report: Report) -> Option<ReportId> {
294        let deadline = later(Instant::now(), self.shutdown_timeout);
295        let report = self.prepare_report(report)?;
296        let id = report.id();
297        let listener = ListenerCall::new(&report);
298
299        if let Err(error) = self.send_until(Message::Report(Box::new(report)), deadline) {
300            flare_debug!(self.debug, WARN, "{error}, dropped a report");
301            return None;
302        }
303        listener.run();
304
305        let _ = self.flush_until(deadline);
306
307        Some(id)
308    }
309
310    /// Resolves the entry point and adds the current scope. Then runs the
311    /// `before_send` hook. Returns `None` when the `before_send` hook drops the
312    /// report.
313    fn prepare_report(&self, mut report: Report) -> Option<Report> {
314        report.resolve_entry_point();
315        report.attach(
316            scope::current_scope(),
317            self.application_path.clone(),
318            self.workspace_root.as_deref(),
319        );
320
321        if let Some(before_send) = &self.before_send
322            && !before_send(&mut report)
323        {
324            return None;
325        }
326
327        Some(report)
328    }
329
330    /// Returns the crates whose frames count as application code.
331    pub fn app_crates(&self) -> &[String] {
332        &self.app_crates
333    }
334
335    /// Puts a message on the queue without waiting.
336    ///
337    /// When the queue is full, or the worker thread has stopped, the message is
338    /// dropped. That way, a slow network never slows down the application.
339    ///
340    /// Returns `true` when the client queued the message.
341    fn send(&self, message: Message) -> bool {
342        if let Err(error) = self.sender.try_send(message) {
343            let error = QueueError::from(error);
344            flare_debug!(self.debug, WARN, "{error}, dropped a record");
345
346            return false;
347        }
348
349        true
350    }
351
352    /// Puts a message on the queue. When the queue is full, this function tries
353    /// again every 5 ms until `deadline`. The worker thread takes messages off the
354    /// queue in the meantime.
355    fn send_until(&self, mut message: Message, deadline: Instant) -> Result<(), QueueError> {
356        loop {
357            match self.sender.try_send(message) {
358                Ok(()) => return Ok(()),
359                Err(TrySendError::Full(returned)) if Instant::now() < deadline => {
360                    message = returned;
361                    thread::sleep(Duration::from_millis(5));
362                }
363                Err(error) => return Err(error.into()),
364            }
365        }
366    }
367
368    /// Waits until the worker thread has sent everything in the queue, or until
369    /// `timeout` has passed. Returns `true` when nothing is left to send.
370    ///
371    /// Data that Flare refused, or that still failed after all retries, is dropped
372    /// and also counts as done. When the worker thread must wait longer than
373    /// `timeout` before the next retry, for example because of a `Retry-After`
374    /// header, this function returns `false` right away.
375    pub fn flush(&self, timeout: Duration) -> bool {
376        self.flush_until(later(Instant::now(), timeout))
377            .unwrap_or(false)
378    }
379
380    /// Same as [`Client::flush`], but with an end time instead of a duration.
381    /// Returns an error when the flush request did not reach the queue.
382    fn flush_until(&self, deadline: Instant) -> Result<bool, QueueError> {
383        let (flushed_sender, flushed) = mpsc::sync_channel(1);
384        let waiter = FlushWaiter {
385            flushed_sender,
386            deadline,
387        };
388        self.send_until(Message::Flush(waiter), deadline)?;
389
390        Ok(flushed
391            .recv_timeout(deadline.saturating_duration_since(Instant::now()))
392            .unwrap_or(false))
393    }
394
395    /// Sends everything that is still queued, then stops the worker thread.
396    ///
397    /// Waits at most `shutdown_timeout` in total. When the worker thread is still
398    /// busy after that, for example on a slow network, this function stops
399    /// waiting, and the worker thread finishes on its own.
400    fn close(&self) {
401        let deadline = later(Instant::now(), self.shutdown_timeout);
402
403        match self.flush_until(deadline) {
404            Ok(true) => {}
405            Ok(false) => flare_debug!(
406                self.debug,
407                WARN,
408                "shutdown timeout reached, some data was not sent"
409            ),
410            Err(error) => flare_debug!(self.debug, WARN, "{error}, some data was not sent"),
411        }
412
413        let _ = self.sender.try_send(Message::Shutdown);
414
415        // A poisoned lock is fine here, for the same reason as in `read_client`.
416        let Some(worker) = self
417            .worker
418            .lock()
419            .unwrap_or_else(PoisonError::into_inner)
420            .take()
421        else {
422            return;
423        };
424
425        let remaining = deadline.saturating_duration_since(Instant::now());
426        if worker.stopped.recv_timeout(remaining).is_ok() {
427            let _ = worker.handle.join();
428        }
429    }
430}
431
432/// The reason why a message did not reach the worker thread.
433#[derive(Debug, Clone, Copy)]
434enum QueueError {
435    /// The queue had no room.
436    Full,
437    /// The worker thread has stopped, so nothing reads the queue anymore. This
438    /// happens when code on the worker thread panics.
439    Stopped,
440}
441
442impl<T> From<TrySendError<T>> for QueueError {
443    fn from(error: TrySendError<T>) -> Self {
444        match error {
445            TrySendError::Full(_) => Self::Full,
446            TrySendError::Disconnected(_) => Self::Stopped,
447        }
448    }
449}
450
451impl fmt::Display for QueueError {
452    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
453        f.write_str(match self {
454            Self::Full => "queue full",
455            Self::Stopped => "the worker thread has stopped",
456        })
457    }
458}
459
460/// Returns `true` on the worker thread. Integrations use this function to skip
461/// their work on the worker thread, because the worker thread must not wait for
462/// itself.
463pub fn is_worker_thread() -> bool {
464    IS_WORKER_THREAD.try_with(Cell::get).unwrap_or(false)
465}
466
467/// Returns the global client, or `None` when the Flare client is not running.
468pub fn current() -> Option<Arc<Client>> {
469    read_client().clone()
470}
471
472/// Locks the global client for reading.
473///
474/// A panic in another thread poisons the lock. The client inside stays valid, so
475/// Flare keeps using it.
476fn read_client() -> RwLockReadGuard<'static, Option<Arc<Client>>> {
477    CLIENT.read().unwrap_or_else(PoisonError::into_inner)
478}
479
480/// Locks the global client for writing. A poisoned lock is fine here, for the
481/// same reason as in [`read_client`].
482fn write_client() -> RwLockWriteGuard<'static, Option<Arc<Client>>> {
483    CLIENT.write().unwrap_or_else(PoisonError::into_inner)
484}
485
486/// Returns the global client, unless this is the worker thread.
487///
488/// Integrations use this function to capture data. The HTTP client on the worker
489/// thread also writes logs. If the Flare client captures those logs, each send
490/// creates new logs to send, without end.
491pub fn active_client() -> Option<Arc<Client>> {
492    if is_worker_thread() { None } else { current() }
493}
494
495/// Starts the Flare client and returns a guard that keeps it running.
496///
497/// Without an API key, the Flare client stays disabled. All functions still work,
498/// but they do nothing. With [`Config::debug`] on, this function prints the
499/// warnings about the environment variables and the `.env` file, and why the Flare
500/// client did not start.
501///
502/// Keep the guard until your program ends. When the guard is dropped, it sends
503/// the queued data and stops the Flare client.
504///
505/// The config needs a [`Transport`](crate::Transport). The `flareapp` crate sets
506/// its default HTTP client before it calls this function.
507pub fn init(config: Config) -> Guard {
508    let debug = config.debug;
509    let client = match Client::start(config) {
510        Ok(client) => Some(Arc::new(client)),
511        Err(StartError::Spawn(error)) => {
512            flare_debug!(debug, ERROR, "could not start the worker thread: {error}");
513            None
514        }
515        Err(error) => {
516            flare_debug!(debug, WARN, "{error}, Flare is disabled");
517            None
518        }
519    };
520
521    write_client().clone_from(&client);
522
523    Guard { client }
524}
525
526/// Waits until all queued logs, spans and error reports are sent, or until
527/// `timeout` has passed. Returns `true` when nothing is left to send.
528///
529/// When the Flare client is disabled, nothing is queued, so this function also
530/// returns `true`. [`Client::flush`] explains the other cases.
531pub fn flush(timeout: Duration) -> bool {
532    current().is_none_or(|client| client.flush(timeout))
533}
534
535/// A handle that keeps the Flare client running. [`init`] returns the guard.
536///
537/// When you drop the guard, the guard sends the queued data and stops the Flare
538/// client. The guard waits at most [`Config::shutdown_timeout`] for the data.
539#[must_use = "Flare stops when the guard is dropped; keep it with `let _flare = …`"]
540pub struct Guard {
541    client: Option<Arc<Client>>,
542}
543
544impl Guard {
545    /// Returns `true` when the Flare client is running. The Flare client is
546    /// disabled when it did not start, for example without an API key.
547    pub fn is_enabled(&self) -> bool {
548        self.client.is_some()
549    }
550}
551
552impl Drop for Guard {
553    fn drop(&mut self) {
554        let Some(client) = self.client.take() else {
555            return;
556        };
557
558        {
559            let mut installed = write_client();
560            // When `init` was called again, the global client is a newer one.
561            // Only remove the global client when it is still the client of this
562            // guard.
563            if installed
564                .as_ref()
565                .is_some_and(|current| Arc::ptr_eq(current, &client))
566            {
567                *installed = None;
568            }
569        }
570
571        client.close();
572    }
573}
574
575impl fmt::Debug for Client {
576    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
577        f.debug_struct("Client")
578            .field("debug", &self.debug)
579            .field("shutdown_timeout", &self.shutdown_timeout)
580            .field("before_send", &self.before_send.is_some())
581            .field("app_crates", &self.app_crates)
582            .field("application_path", &self.application_path)
583            .field("workspace_root", &self.workspace_root)
584            .field("traces_sample_rate", &self.traces_sample_rate)
585            .field("censor_client_ips", &self.censor_client_ips)
586            .field("has_framework", &self.has_framework)
587            .finish_non_exhaustive()
588    }
589}
590
591impl fmt::Debug for Guard {
592    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
593        f.debug_struct("Guard")
594            .field("enabled", &self.is_enabled())
595            .finish()
596    }
597}
598
599#[cfg(test)]
600mod tests {
601
602    use super::*;
603    use crate::config::OtlpProtocol;
604    use crate::test_support::{
605        FakeTransport, GatedTransport, json, json_attribute, log, serial, span,
606    };
607    use crate::transport::{Request, Response, Signal, Transport, TransportError};
608    use crate::worker::RetryPolicy;
609
610    const WAIT: Duration = Duration::from_secs(2);
611
612    /// A config that sends logs and traces as JSON, so tests can read the bodies.
613    fn config(transport: &FakeTransport) -> Config {
614        Config::new()
615            .api_key("secret")
616            .endpoint("https://ingress.test/")
617            .otlp_protocol(OtlpProtocol::HttpJson)
618            .batch_interval(Duration::from_secs(60))
619            .transport(transport.clone())
620            .retry(RetryPolicy {
621                max_retries: 3,
622                base_delay: Duration::from_millis(1),
623                max_delay: Duration::from_millis(1),
624            })
625    }
626
627    fn record_count(request: &Request) -> usize {
628        json(request)["resourceLogs"][0]["scopeLogs"][0]["logRecords"]
629            .as_array()
630            .map_or(0, Vec::len)
631    }
632
633    /// Returns the resource attribute `key` of the first request, as JSON.
634    fn resource_attribute(transport: &FakeTransport, key: &str) -> Option<serde_json::Value> {
635        let body = json(&transport.requests()[0]);
636
637        json_attribute(&body["resourceLogs"][0]["resource"], key).cloned()
638    }
639
640    fn content_type(request: &Request) -> Option<&str> {
641        request
642            .headers
643            .iter()
644            .find(|(name, _)| *name == "content-type")
645            .map(|(_, value)| value.as_str())
646    }
647
648    fn report() -> Report {
649        Report::new(
650            "my_app::PaymentFailed",
651            "payment failed",
652            std::panic::Location::caller(),
653        )
654    }
655
656    #[test]
657    fn is_disabled_without_an_api_key() {
658        let transport = FakeTransport::default();
659
660        let started = Client::start(config(&transport).api_key(""));
661
662        assert!(matches!(started, Err(StartError::NoApiKey)));
663    }
664
665    #[test]
666    fn does_not_start_without_a_transport() {
667        let started = Client::start(Config::new().api_key("test-key"));
668
669        assert!(matches!(started, Err(StartError::NoTransport)));
670    }
671
672    #[test]
673    fn start_errors_say_what_is_missing() {
674        assert_eq!(StartError::NoApiKey.to_string(), "no API key set");
675    }
676
677    #[test]
678    fn a_spawn_error_keeps_the_error_of_the_operating_system_as_its_source() {
679        let error = StartError::Spawn(io::Error::other("no threads left"));
680
681        let source = error.source().map(ToString::to_string);
682
683        assert_eq!(source.as_deref(), Some("no threads left"));
684    }
685
686    #[test]
687    fn sends_logs_in_one_batch_on_flush() {
688        let transport = FakeTransport::default();
689        let client = Client::start(config(&transport)).unwrap();
690
691        client.send_log("shop", log("one"));
692        client.send_log("shop", log("two"));
693        client.send_log("shop", log("three"));
694
695        assert!(client.flush(WAIT));
696        let counts: Vec<usize> = transport.requests().iter().map(record_count).collect();
697        assert_eq!(counts, [3]);
698    }
699
700    #[test]
701    fn the_first_framework_goes_on_the_resource() {
702        let transport = FakeTransport::default();
703        let client = Client::start(config(&transport)).unwrap();
704
705        client.set_framework("axum", None);
706        client.set_framework("actix", Some("4.17.0".to_owned()));
707        client.send_log("shop", log("one"));
708
709        assert!(client.flush(WAIT));
710        assert_eq!(
711            resource_attribute(&transport, "flare.framework.name"),
712            Some(serde_json::json!({ "stringValue": "axum" }))
713        );
714        assert_eq!(
715            resource_attribute(&transport, "flare.framework.version"),
716            None
717        );
718    }
719
720    #[test]
721    fn the_framework_of_the_config_wins() {
722        let transport = FakeTransport::default();
723        let client =
724            Client::start(config(&transport).framework("omega", Some("1.0.0".to_owned()))).unwrap();
725
726        client.set_framework("axum", None);
727        client.send_log("shop", log("one"));
728
729        assert!(client.flush(WAIT));
730        assert_eq!(
731            resource_attribute(&transport, "flare.framework.name"),
732            Some(serde_json::json!({ "stringValue": "omega" }))
733        );
734    }
735
736    #[test]
737    fn reads_the_git_commit_from_the_application_path() {
738        let transport = FakeTransport::default();
739        let repository = crate::resource::git::test_repository();
740        let client =
741            Client::start(config(&transport).application_path(repository.to_string_lossy()))
742                .unwrap();
743
744        client.send_log("shop", log("one"));
745
746        assert!(client.flush(WAIT));
747        let _ = std::fs::remove_dir_all(&repository);
748        assert_eq!(
749            resource_attribute(&transport, "git.tag"),
750            Some(serde_json::json!({ "stringValue": "v1.0.0" }))
751        );
752    }
753
754    #[test]
755    fn logs_go_to_the_logs_endpoint() {
756        let transport = FakeTransport::default();
757        let client = Client::start(config(&transport)).unwrap();
758
759        client.send_log("shop", log("one"));
760
761        assert!(client.flush(WAIT));
762        let requests = transport.requests();
763        assert_eq!(requests[0].signal, Signal::Logs);
764        assert_eq!(requests[0].url, "https://ingress.test/v1/logs");
765    }
766
767    /// Sends one log, and returns the headers of the request.
768    fn log_request_headers() -> Vec<(&'static str, String)> {
769        let transport = FakeTransport::default();
770        let client = Client::start(config(&transport)).unwrap();
771
772        client.send_log("shop", log("one"));
773
774        assert!(client.flush(WAIT));
775
776        transport.requests().remove(0).headers
777    }
778
779    #[test]
780    fn requests_carry_the_api_key() {
781        let headers = log_request_headers();
782
783        assert!(
784            headers.contains(&("x-api-token", "secret".to_owned())),
785            "{headers:?}"
786        );
787    }
788
789    #[test]
790    fn requests_carry_the_content_type() {
791        let headers = log_request_headers();
792
793        assert!(
794            headers.contains(&("content-type", "application/json".to_owned())),
795            "{headers:?}"
796        );
797    }
798
799    #[test]
800    fn sends_logs_and_traces_as_protobuf_by_default() {
801        let transport = FakeTransport::default();
802        let client =
803            Client::start(config(&transport).otlp_protocol(OtlpProtocol::default())).unwrap();
804
805        client.send_log("shop", log("one"));
806        client.send_trace(vec![span()]);
807
808        assert!(client.flush(WAIT));
809        let requests = transport.requests();
810        let content_types: Vec<_> = requests.iter().map(content_type).collect();
811        assert_eq!(
812            content_types,
813            [
814                Some("application/x-protobuf"),
815                Some("application/x-protobuf")
816            ]
817        );
818    }
819
820    #[test]
821    fn sends_error_reports_as_json_with_protobuf() {
822        let transport = FakeTransport::default();
823        let client =
824            Client::start(config(&transport).otlp_protocol(OtlpProtocol::HttpProtobuf)).unwrap();
825
826        client.send_report(Report::new(
827            "my_app::PaymentFailed",
828            "payment failed",
829            std::panic::Location::caller(),
830        ));
831
832        assert!(client.flush(WAIT));
833        let requests = transport.requests();
834        assert_eq!(content_type(&requests[0]), Some("application/json"));
835        assert_eq!(json(&requests[0])["message"], "payment failed");
836    }
837
838    #[test]
839    fn sends_full_batches_without_waiting() {
840        let transport = FakeTransport::default();
841        let client = Client::start(config(&transport).batch_size(2)).unwrap();
842
843        for body in ["one", "two", "three", "four"] {
844            client.send_log("shop", log(body));
845        }
846
847        let counts: Vec<usize> = transport
848            .wait_for_requests(2, WAIT)
849            .iter()
850            .map(record_count)
851            .collect();
852        assert_eq!(counts, [2, 2]);
853    }
854
855    #[test]
856    fn sends_after_the_batch_interval() {
857        let transport = FakeTransport::default();
858        let client =
859            Client::start(config(&transport).batch_interval(Duration::from_millis(20))).unwrap();
860
861        client.send_log("shop", log("one"));
862
863        assert_eq!(transport.wait_for_requests(1, WAIT).len(), 1);
864    }
865
866    #[test]
867    fn sends_spans_to_the_traces_endpoint() {
868        let transport = FakeTransport::default();
869        let client = Client::start(config(&transport)).unwrap();
870
871        client.send_trace(vec![span()]);
872
873        assert!(client.flush(WAIT));
874        let urls: Vec<String> = transport
875            .requests()
876            .into_iter()
877            .map(|request| request.url)
878            .collect();
879        assert_eq!(urls, ["https://ingress.test/v1/traces"]);
880    }
881
882    #[test]
883    fn trace_requests_hold_the_spans() {
884        let transport = FakeTransport::default();
885        let client = Client::start(config(&transport)).unwrap();
886
887        client.send_trace(vec![span()]);
888
889        assert!(client.flush(WAIT));
890        assert_eq!(transport.spans().len(), 1);
891    }
892
893    #[test]
894    fn retries_temporary_failures() {
895        let transport = FakeTransport::default();
896        transport
897            .respond_with(Response::new(503))
898            .fail_with("connection reset");
899        let client = Client::start(config(&transport)).unwrap();
900
901        client.send_log("shop", log("one"));
902
903        assert!(client.flush(WAIT));
904        let bodies: Vec<serde_json::Value> = transport.requests().iter().map(json).collect();
905        assert_eq!(
906            bodies,
907            [bodies[0].clone(), bodies[0].clone(), bodies[0].clone()]
908        );
909    }
910
911    #[test]
912    fn gives_up_after_three_retries() {
913        let transport = FakeTransport::default();
914        for _ in 0..5 {
915            transport.respond_with(Response::new(503));
916        }
917        let client = Client::start(config(&transport)).unwrap();
918
919        client.send_log("shop", log("one"));
920
921        assert!(client.flush(WAIT));
922        assert_eq!(transport.requests().len(), 4);
923    }
924
925    #[test]
926    fn does_not_retry_rejected_requests() {
927        let transport = FakeTransport::default();
928        transport.respond_with(Response::new(422));
929        let client = Client::start(config(&transport)).unwrap();
930
931        client.send_log("shop", log("one"));
932
933        assert!(client.flush(WAIT));
934        assert_eq!(transport.requests().len(), 1);
935    }
936
937    #[test]
938    fn waits_for_retry_after_without_blocking() {
939        let transport = FakeTransport::default();
940        transport.respond_with(Response::new(429).with_retry_after_header("60"));
941        let client = Client::start(config(&transport)).unwrap();
942
943        client.send_log("shop", log("one"));
944        let _ = client.flush(Duration::from_millis(100));
945
946        // The worker still answers while it waits to retry.
947        client.send_trace(vec![span()]);
948        let _ = client.flush(Duration::from_millis(100));
949
950        let signals: Vec<Signal> = transport
951            .requests()
952            .iter()
953            .map(|request| request.signal)
954            .collect();
955        assert_eq!(signals, [Signal::Logs, Signal::Traces]);
956    }
957
958    #[test]
959    fn flush_does_not_wait_for_a_retry_after_its_timeout() {
960        let transport = FakeTransport::default();
961        transport.respond_with(Response::new(429).with_retry_after_header("60"));
962        let client = Client::start(config(&transport)).unwrap();
963
964        client.send_log("shop", log("one"));
965        let started = Instant::now();
966
967        assert!(!client.flush(Duration::from_secs(5)));
968        assert!(started.elapsed() < Duration::from_secs(1));
969    }
970
971    #[test]
972    fn a_report_does_not_wait_for_logs_that_retry_later() {
973        let transport = FakeTransport::default();
974        transport.respond_with(Response::new(429).with_retry_after_header("60"));
975        let client =
976            Client::start(config(&transport).shutdown_timeout(Duration::from_secs(5))).unwrap();
977        client.send_log("shop", log("one"));
978        assert!(!client.flush(WAIT));
979        let started = Instant::now();
980
981        client.send_report_and_wait(report());
982
983        assert!(started.elapsed() < Duration::from_secs(1));
984        assert_eq!(transport.requests()[1].signal, Signal::Errors);
985    }
986
987    #[test]
988    fn a_report_waits_for_room_in_a_full_queue() {
989        let transport = FakeTransport::default();
990        let gate = GatedTransport::new(&transport);
991        let client = Client::start(
992            config(&transport)
993                .transport(gate.clone())
994                .queue_capacity(1)
995                .batch_size(1),
996        )
997        .unwrap();
998
999        // The worker thread is stuck on the first log, and the second fills the queue.
1000        client.send_log("shop", log("one"));
1001        transport.wait_for_requests(1, WAIT);
1002        client.send_log("shop", log("two"));
1003
1004        let opener = thread::spawn(move || {
1005            thread::sleep(Duration::from_millis(50));
1006            gate.open();
1007        });
1008        let id = client.send_report_and_wait(report());
1009        opener.join().unwrap();
1010
1011        assert!(id.is_some(), "{id:?}");
1012        let signals: Vec<Signal> = transport
1013            .requests()
1014            .iter()
1015            .map(|request| request.signal)
1016            .collect();
1017        assert!(signals.contains(&Signal::Errors), "{signals:?}");
1018    }
1019
1020    #[test]
1021    fn a_report_that_did_not_fit_in_a_full_queue_has_no_id() {
1022        let transport = FakeTransport::default();
1023        let gate = GatedTransport::new(&transport);
1024        let client = Client::start(
1025            config(&transport)
1026                .transport(gate.clone())
1027                .queue_capacity(1)
1028                .batch_size(1),
1029        )
1030        .unwrap();
1031        client.send_log("shop", log("one"));
1032        transport.wait_for_requests(1, WAIT);
1033        client.send_log("shop", log("two"));
1034
1035        let id = client.send_report(report());
1036        gate.open();
1037
1038        assert_eq!(id, None);
1039    }
1040
1041    thread_local! {
1042        /// The number of reports that [`count_report`] got on this thread.
1043        static LISTENED_REPORTS: Cell<usize> = const { Cell::new(0) };
1044    }
1045
1046    /// A report listener that counts the reports of each thread, so tests on
1047    /// other threads do not change the count of a test.
1048    fn count_report(_report: QueuedReport) {
1049        LISTENED_REPORTS.set(LISTENED_REPORTS.get() + 1);
1050    }
1051
1052    #[test]
1053    fn the_report_listener_gets_only_queued_reports() {
1054        set_report_listener(count_report);
1055        let before = LISTENED_REPORTS.get();
1056        let transport = FakeTransport::default();
1057        let gate = GatedTransport::new(&transport);
1058        let client = Client::start(
1059            config(&transport)
1060                .transport(gate.clone())
1061                .queue_capacity(1)
1062                .batch_size(1),
1063        )
1064        .unwrap();
1065
1066        // The worker thread is stuck on the first report, and the log fills the queue.
1067        let queued = client.send_report(report());
1068        transport.wait_for_requests(1, WAIT);
1069        client.send_log("shop", log("one"));
1070        let dropped = client.send_report(report());
1071        gate.open();
1072
1073        assert!(queued.is_some());
1074        assert_eq!(dropped, None);
1075        assert_eq!(LISTENED_REPORTS.get() - before, 1);
1076    }
1077
1078    #[test]
1079    fn the_report_listener_does_not_get_a_report_that_found_no_room_in_time() {
1080        set_report_listener(count_report);
1081        let before = LISTENED_REPORTS.get();
1082        let transport = FakeTransport::default();
1083        let gate = GatedTransport::new(&transport);
1084        let client = Client::start(
1085            config(&transport)
1086                .transport(gate.clone())
1087                .queue_capacity(1)
1088                .batch_size(1)
1089                .shutdown_timeout(Duration::from_millis(50)),
1090        )
1091        .unwrap();
1092        client.send_log("shop", log("one"));
1093        transport.wait_for_requests(1, WAIT);
1094        client.send_log("shop", log("two"));
1095
1096        let id = client.send_report_and_wait(report());
1097        gate.open();
1098
1099        assert_eq!(id, None);
1100        assert_eq!(LISTENED_REPORTS.get() - before, 0);
1101    }
1102
1103    #[test]
1104    fn reports_go_before_logs_that_wait() {
1105        let transport = FakeTransport::default();
1106        let gate = GatedTransport::new(&transport);
1107        let client =
1108            Client::start(config(&transport).transport(gate.clone()).batch_size(10)).unwrap();
1109
1110        // The worker thread is stuck on the first report while logs and a second
1111        // report queue up behind it.
1112        client.send_report(report());
1113        transport.wait_for_requests(1, WAIT);
1114        for index in 0..30 {
1115            client.send_log("shop", log(&index.to_string()));
1116        }
1117        client.send_report(report());
1118        gate.open();
1119
1120        assert!(client.flush(WAIT));
1121        let signals: Vec<Signal> = transport
1122            .requests()
1123            .iter()
1124            .map(|request| request.signal)
1125            .collect();
1126        assert_eq!(signals[..2], [Signal::Errors, Signal::Errors]);
1127        assert_eq!(signals.len(), 5);
1128    }
1129
1130    /// Wraps a [`FakeTransport`] and panics on the first request.
1131    #[derive(Debug)]
1132    struct PanicsOnceTransport {
1133        inner: FakeTransport,
1134        panicked: AtomicBool,
1135    }
1136
1137    impl Transport for PanicsOnceTransport {
1138        #[expect(
1139            clippy::manual_assert,
1140            reason = "the panic is what the test needs, not a check"
1141        )]
1142        fn send(&self, request: &Request) -> Result<Response, TransportError> {
1143            if !self.panicked.swap(true, Ordering::SeqCst) {
1144                panic!("the connection pool is broken");
1145            }
1146
1147            self.inner.send(request)
1148        }
1149    }
1150
1151    #[test]
1152    fn a_panic_in_the_transport_is_retried_like_a_failed_request() {
1153        let transport = FakeTransport::default();
1154        let panics_once = PanicsOnceTransport {
1155            inner: transport.clone(),
1156            panicked: AtomicBool::new(false),
1157        };
1158        let client = Client::start(config(&transport).transport(panics_once)).unwrap();
1159
1160        client.send_log("shop", log("one"));
1161
1162        assert!(client.flush(WAIT));
1163        assert_eq!(transport.requests().len(), 1);
1164    }
1165
1166    /// Answers `201 Created`, and records whether the last request ran on the
1167    /// worker thread.
1168    #[derive(Debug, Clone, Default)]
1169    struct WorkerThreadCheck {
1170        on_worker_thread: Arc<AtomicBool>,
1171    }
1172
1173    impl Transport for WorkerThreadCheck {
1174        fn send(&self, _request: &Request) -> Result<Response, TransportError> {
1175            self.on_worker_thread
1176                .store(is_worker_thread(), Ordering::SeqCst);
1177
1178            Ok(Response::new(201))
1179        }
1180    }
1181
1182    #[test]
1183    fn requests_are_sent_on_the_worker_thread() {
1184        let check = WorkerThreadCheck::default();
1185        let client =
1186            Client::start(config(&FakeTransport::default()).transport(check.clone())).unwrap();
1187
1188        client.send_log("shop", log("one"));
1189
1190        assert!(client.flush(WAIT));
1191        assert!(check.on_worker_thread.load(Ordering::SeqCst));
1192    }
1193
1194    #[test]
1195    fn an_app_thread_with_the_name_of_the_worker_thread_is_not_the_worker_thread() {
1196        let is_worker = thread::Builder::new()
1197            .name(WORKER_THREAD_NAME.to_owned())
1198            .spawn(is_worker_thread)
1199            .unwrap()
1200            .join()
1201            .unwrap();
1202
1203        assert!(!is_worker);
1204    }
1205
1206    #[test]
1207    fn dropping_the_guard_sends_queued_data() {
1208        let _serial = serial();
1209        let transport = FakeTransport::default();
1210        let guard = init(config(&transport));
1211
1212        current().unwrap().send_log("shop", log("one"));
1213        drop(guard);
1214
1215        assert_eq!(transport.requests().len(), 1);
1216        assert!(current().is_none(), "the Flare client still runs");
1217    }
1218}