flareapp-core 0.3.0

The core of the Flare client: config, the client, and the worker thread that sends data.
Documentation
//! The worker thread: a background thread that collects records, groups them into
//! batches and sends them to Flare.
//!
//! The application puts records on a queue and never waits for the network. The
//! worker thread never sleeps either. When a request has to be tried again later,
//! the worker thread keeps the time when the next try is allowed. In the meantime,
//! the worker thread keeps taking new records from the queue.
//!
//! - [`batcher`] holds the records that wait, and decides when a batch is due.
//! - [`exporter`] turns a batch into an HTTP request and sends it.
//! - [`retry`] decides what a response means, and when to try again.

mod batcher;
mod exporter;
mod retry;

use std::path::PathBuf;
use std::sync::Arc;
use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender};
use std::time::{Duration, Instant};

use flareapp_otlp::Span;

pub(crate) use self::batcher::Log;
use self::batcher::{Batchable, Batcher, Trace};
use self::exporter::Exporter;
pub(crate) use self::retry::RetryPolicy;
use crate::config::Config;
use crate::debug::flare_debug;
use crate::report::{Report, ResolvedReport};
use crate::resource;
use crate::transport::Transport;

/// How long the worker thread waits for a message when it has nothing else to do.
const IDLE_WAIT: Duration = Duration::from_secs(3600);

/// Adds `record` to `batcher`. Prints a warning when the batcher was full and
/// dropped its oldest record.
fn enqueue<T: Batchable>(batcher: &mut Batcher<T>, record: T, now: Instant, debug: bool) {
    if !batcher.push(record, now) {
        flare_debug!(
            debug,
            WARN,
            "{:?} buffer full, dropped the oldest record",
            T::SIGNAL
        );
    }
}

/// A message from the application to the worker thread.
pub(crate) enum Message {
    /// A log record to send.
    Log(Log),
    /// All finished spans of one trace.
    Trace(Vec<Span>),
    /// An error report to send. The worker thread resolves its stack trace first.
    Report(Box<Report>),
    /// Adds the framework to the resource: its name, and its version when known.
    Framework(String, Option<String>),
    /// Asks the worker thread to send, right away, every record that was queued
    /// before this message. The worker thread answers the [`FlushWaiter`] when
    /// those records are sent, or when they can only be retried at or after its
    /// deadline.
    Flush(FlushWaiter),
    /// Stops the worker thread. Records that still wait are dropped.
    Shutdown,
}

/// A flush that a caller waits for, like a call of
/// [`Client::flush`](crate::Client::flush).
pub(crate) struct FlushWaiter {
    /// The channel for the answer. The worker thread sends `true` when all
    /// flushed records are sent. It sends `false` when the records that are left
    /// can only be retried at or after `deadline`.
    ///
    /// Records that Flare refused, or that failed after all retries, are dropped
    /// and count as sent.
    pub(crate) flushed_sender: SyncSender<bool>,
    /// When the caller stops waiting. After this time, the worker thread drops the
    /// waiter without an answer.
    pub(crate) deadline: Instant,
}

/// A [`FlushWaiter`] and, for each batcher, the mark of the flush that it waits
/// for. [`Batcher::flush`] explains the marks.
struct PendingFlush {
    waiter: FlushWaiter,
    logs: u64,
    traces: u64,
    reports: u64,
}

/// The state of the worker thread: one batcher for each kind of record, and the
/// callers that wait for a flush.
pub(crate) struct Worker {
    exporter: Exporter,
    logs: Batcher<Log>,
    traces: Batcher<Trace>,
    reports: Batcher<ResolvedReport>,
    flush_waiters: Vec<PendingFlush>,
    /// How many messages the queue holds.
    queue_capacity: usize,
    /// The folder to read the git commit from, once the worker thread runs.
    git_folder: Option<PathBuf>,
    debug: bool,
}

impl Worker {
    pub(crate) fn new(config: &Config, transport: Arc<dyn Transport>, api_key: String) -> Self {
        Self {
            exporter: Exporter::new(config, transport, api_key),
            logs: Batcher::new(config),
            traces: Batcher::new(config),
            reports: Batcher::new(config),
            flush_waiters: Vec::new(),
            queue_capacity: config.queue_capacity,
            git_folder: resource::git::source_folder(config),
            debug: config.debug,
        }
    }

    /// Takes messages from the queue and sends batches when they are due.
    ///
    /// Runs until it gets [`Message::Shutdown`], or until the client is dropped.
    pub(crate) fn run(mut self, messages: &Receiver<Message>) {
        if let Some(folder) = self.git_folder.take() {
            self.exporter
                .set_resource_attributes(resource::git::attributes(&folder));
        }

        loop {
            let wait = self.next_wake().map_or(IDLE_WAIT, |wake_at| {
                wake_at.saturating_duration_since(Instant::now())
            });
            let first = match messages.recv_timeout(wait) {
                Ok(message) => Some(message),
                Err(RecvTimeoutError::Timeout) => None,
                Err(RecvTimeoutError::Disconnected) => return,
            };

            // Also take the other messages that wait now, so an error report does
            // not wait behind a long line of logs. Take at most one full queue, so
            // an app that logs without a pause cannot keep the worker thread from
            // sending.
            let now = Instant::now();
            let waiting = messages.try_iter().take(self.queue_capacity);
            for message in first.into_iter().chain(waiting) {
                if !self.handle(message, now) {
                    return;
                }
            }

            // Send the reports first, because the process can end soon after a
            // panic.
            self.exporter.send_due(&mut self.reports, now);
            self.exporter.send_due(&mut self.logs, now);
            self.exporter.send_due(&mut self.traces, now);
            self.answer_flush_waiters(now);
        }
    }

    /// Handles one message. Returns `false` when the worker thread must stop.
    fn handle(&mut self, message: Message, now: Instant) -> bool {
        match message {
            Message::Log(record) => enqueue(&mut self.logs, record, now, self.debug),
            Message::Trace(spans) => enqueue(&mut self.traces, Trace(spans), now, self.debug),
            Message::Report(report) => {
                enqueue(
                    &mut self.reports,
                    report.resolve_frames(self.debug),
                    now,
                    self.debug,
                );
            }
            Message::Framework(name, version) => self.exporter.set_framework(name, version),
            Message::Flush(waiter) => self.flush_waiters.push(PendingFlush {
                waiter,
                logs: self.logs.flush(),
                traces: self.traces.flush(),
                reports: self.reports.flush(),
            }),
            Message::Shutdown => return false,
        }

        true
    }

    /// Returns the next time the worker thread has something to do: send a batch,
    /// or give up on a flush. `None` means that the worker thread only waits for
    /// the next message.
    fn next_wake(&self) -> Option<Instant> {
        [
            self.logs.next_send_at(),
            self.traces.next_send_at(),
            self.reports.next_send_at(),
            self.flush_waiters
                .iter()
                .map(|flush| flush.waiter.deadline)
                .min(),
        ]
        .into_iter()
        .flatten()
        .min()
    }

    /// Answers each flush waiter whose records are sent, or whose records that are
    /// left can only be retried at or after its deadline. Drops the waiters whose
    /// deadline has passed, without an answer.
    fn answer_flush_waiters(&mut self, now: Instant) {
        self.flush_waiters.retain(|flush| {
            let deadline = flush.waiter.deadline;
            let done = self.logs.is_flush_done_by(flush.logs, deadline)
                && self.traces.is_flush_done_by(flush.traces, deadline)
                && self.reports.is_flush_done_by(flush.reports, deadline);

            if done {
                let sent_all = self.logs.is_flushed(flush.logs)
                    && self.traces.is_flushed(flush.traces)
                    && self.reports.is_flushed(flush.reports);
                // The caller can stop waiting before the answer arrives. The answer
                // is then lost, and that is fine.
                let _ = flush.waiter.flushed_sender.try_send(sent_all);
                return false;
            }

            deadline > now
        });
    }
}

#[cfg(test)]
mod tests {
    use std::sync::mpsc::{self, Receiver};

    use super::*;
    use crate::test_support::{FakeTransport, log, secs};
    use crate::transport::Response;

    fn log_message(body: &str) -> Message {
        Message::Log(Log {
            target: "shop".into(),
            record: log(body),
        })
    }

    /// Returns a flush message, and the channel that gets its answer.
    fn flush_message(deadline: Instant) -> (Message, Receiver<bool>) {
        let (flushed_sender, flushed) = mpsc::sync_channel(1);
        let waiter = FlushWaiter {
            flushed_sender,
            deadline,
        };

        (Message::Flush(waiter), flushed)
    }

    #[test]
    fn a_flush_is_done_when_its_own_records_are_sent() {
        let transport = FakeTransport::default();
        transport
            .respond_with(Response::new(201))
            .respond_with(Response::new(429).with_retry_after_header("60"));
        let config = Config::new().batch_size(1);
        let mut worker = Worker::new(&config, Arc::new(transport), "key".to_owned());
        let now = Instant::now();
        let (first_flush, first_flushed) = flush_message(now + secs(2));
        let (second_flush, _second_flushed) = flush_message(now + secs(120));

        worker.handle(log_message("one"), now);
        worker.handle(first_flush, now);
        worker.handle(log_message("two"), now);
        worker.handle(second_flush, now);
        worker.exporter.send_due(&mut worker.logs, now);
        worker.answer_flush_waiters(now);

        assert_eq!(first_flushed.try_recv(), Ok(true));
    }
}