flareapp-core 0.2.0

The core of the Flare client: config, the client, and the worker thread that sends data.
Documentation
//! Turns batches into HTTP requests and sends them with the transport.

use std::panic::{self, AssertUnwindSafe};
use std::sync::Arc;
use std::time::Instant;

use tracing::Level;

use flareapp_otlp::{ExportKind, InstrumentationScope, KeyValue, PartialSuccess, Resource};

use super::batcher::{Batchable, Batcher};
use super::retry::{Outcome, classify};
use crate::config::{Config, OtlpProtocol};
use crate::debug::{self, flare_debug};
use crate::transport::{Request, Response, Signal, Transport, TransportError};
use crate::{SDK_NAME, SDK_VERSION, resource};

/// The largest request body that the exporter sends, in bytes. The limit applies
/// to JSON and protobuf bodies. A batch that is bigger is split in half until each
/// part fits.
const MAX_BATCH_BYTES: usize = 800_000;

/// The result of turning a batch into a request body.
enum Encoded {
    /// The request body for the first `count` records of the batch.
    Body { body: Vec<u8>, count: usize },
    /// The first `count` records cannot be sent, so the exporter drops them.
    /// `reason` says why.
    Skip { count: usize, reason: String },
}

/// The part of the worker thread that turns batches into HTTP requests and sends
/// them with the transport.
pub(super) struct Exporter {
    transport: Arc<dyn Transport>,
    endpoint: String,
    headers: Vec<(&'static str, String)>,
    resource: Resource,
    scope: InstrumentationScope,
    protocol: OtlpProtocol,
    debug: bool,
}

impl Exporter {
    /// Collects the resource attributes and builds the request headers, so this
    /// work happens only once.
    pub(super) fn new(config: &Config, transport: Arc<dyn Transport>, api_key: String) -> Self {
        let headers = vec![
            ("x-api-token", api_key),
            ("user-agent", format!("{SDK_NAME}-rust/{SDK_VERSION}")),
        ];

        Self {
            transport,
            endpoint: config.endpoint.clone(),
            headers,
            resource: resource::detect(config),
            scope: InstrumentationScope::new(SDK_NAME, SDK_VERSION),
            protocol: config.otlp_protocol,
            debug: config.debug,
        }
    }

    /// Adds attributes to the resource, or replaces the ones with the same key.
    /// Batches that are sent after this call get the new attributes.
    pub(super) fn set_resource_attributes(&mut self, attributes: Vec<KeyValue>) {
        for attribute in attributes {
            match self
                .resource
                .attributes
                .iter_mut()
                .find(|existing| existing.key == attribute.key)
            {
                Some(existing) => existing.value = attribute.value,
                None => self.resource.attributes.push(attribute),
            }
        }
    }

    /// Adds the framework to the resource, as `flare.framework.name` and
    /// `flare.framework.version`.
    pub(super) fn set_framework(&mut self, name: String, version: Option<String>) {
        self.set_resource_attributes(resource::framework_attributes(name, version));
    }

    /// Sends batches from `batcher`, one after the other, for as long as a batch is due.
    pub(super) fn send_due<T: Batchable>(&self, batcher: &mut Batcher<T>, mut now: Instant) {
        while batcher.next_send_at().is_some_and(|send_at| send_at <= now) {
            let (body, count) = match self.encode(batcher.batch()) {
                Encoded::Body { body, count } => (body, count),
                Encoded::Skip { count, reason } => {
                    flare_debug!(
                        self.debug,
                        WARN,
                        "dropped {count} {:?} record(s): {reason}",
                        T::SIGNAL
                    );
                    batcher.remove(count, now);
                    continue;
                }
            };

            let outcome = self.send(T::SIGNAL, T::content_type(self.protocol), body);
            // The request can take seconds. Plan the retry from the time that the
            // request ended.
            now = Instant::now();
            if let Outcome::Retry(retry_after) = outcome {
                if batcher.schedule_retry(now, retry_after) {
                    continue;
                }
                flare_debug!(
                    self.debug,
                    ERROR,
                    "gave up sending {count} {:?} record(s)",
                    T::SIGNAL
                );
            }
            batcher.remove(count, now);
        }
    }

    /// Encodes as many records as fit in one request. Starts with all `records` and
    /// halves the number until the body is small enough.
    fn encode<T: Batchable>(&self, records: &[T]) -> Encoded {
        let mut count = records.len();

        loop {
            let batch = records.get(..count).unwrap_or_default();

            match T::encode(&self.resource, &self.scope, batch, self.protocol) {
                Ok(body) if body.len() <= MAX_BATCH_BYTES => return Encoded::Body { body, count },
                Ok(_) if count > 1 => count /= 2,
                Ok(_) => {
                    return Encoded::Skip {
                        count: 1,
                        reason: format!("larger than {MAX_BATCH_BYTES} bytes"),
                    };
                }
                Err(error) => {
                    return Encoded::Skip {
                        count,
                        reason: error.to_string(),
                    };
                }
            }
        }
    }

    /// Sends one request and decides what its response means. Prints the result
    /// when debug output is on.
    fn send(&self, signal: Signal, content_type: &'static str, body: Vec<u8>) -> Outcome {
        let mut headers = self.headers.clone();
        // OTLP servers answer in the format of the request. The `accept` header asks
        // for that same format.
        headers.push(("content-type", content_type.to_owned()));
        headers.push(("accept", content_type.to_owned()));

        let request = Request {
            signal,
            url: format!("{}{}", self.endpoint, signal.path()),
            headers,
            body,
        };

        // A panic in the transport fails only this request. Without the catch, the
        // panic stops the worker thread, and the Flare client sends nothing after
        // that.
        let result = panic::catch_unwind(AssertUnwindSafe(|| self.transport.send(&request)))
            .unwrap_or_else(|_| Err(TransportError::new("the transport panicked")));
        let outcome = classify(&result);
        self.print_result(signal, &result, outcome);

        outcome
    }

    /// Prints the result of one request when debug output is on.
    fn print_result(
        &self,
        signal: Signal,
        result: &Result<Response, TransportError>,
        outcome: Outcome,
    ) {
        if !self.debug {
            return;
        }
        let response = match result {
            Ok(response) => response,
            Err(error) => {
                debug::print(Level::WARN, format_args!("{signal:?} failed: {error}"));
                return;
            }
        };

        if outcome != Outcome::Sent {
            let level = if outcome == Outcome::Rejected {
                Level::ERROR
            } else {
                Level::WARN
            };
            debug::print(
                level,
                format_args!(
                    "{signal:?} failed with {}: {}",
                    response.status,
                    String::from_utf8_lossy(&response.body)
                ),
            );
            return;
        }

        match self.partial_success(signal, &response.body) {
            Some(partial) => debug::print(
                Level::WARN,
                format_args!(
                    "{signal:?} partly rejected: {} rejected. {}",
                    partial.rejected, partial.message
                ),
            ),
            None => debug::print(
                Level::DEBUG,
                format_args!("sent {signal:?} ({})", response.status),
            ),
        }
    }

    /// Reads the partial success from the body of an OTLP response. The response
    /// to an error report has none, because error reports are not OTLP.
    fn partial_success(&self, signal: Signal, body: &[u8]) -> Option<PartialSuccess> {
        let kind = match signal {
            Signal::Logs => ExportKind::Logs,
            Signal::Traces => ExportKind::Traces,
            Signal::Errors => return None,
        };

        match self.protocol {
            OtlpProtocol::HttpProtobuf => flareapp_otlp::partial_success_protobuf(kind, body),
            OtlpProtocol::HttpJson => flareapp_otlp::partial_success_json(kind, body),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::time::Duration;

    use super::*;
    use crate::test_support::{FakeTransport, log as record};
    use crate::worker::batcher::{Log, Trace};
    use crate::worker::retry::RetryPolicy;

    /// A transport that waits for some time and then returns an error.
    #[derive(Debug)]
    struct SlowFailure(Duration);

    impl Transport for SlowFailure {
        fn send(&self, _request: &Request) -> Result<Response, TransportError> {
            std::thread::sleep(self.0);

            Err(TransportError::new("broken"))
        }
    }

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

    fn exporter() -> Exporter {
        Exporter::new(
            &Config::new(),
            Arc::new(FakeTransport::default()),
            "key".to_owned(),
        )
    }

    /// An exporter that sends JSON, so tests can read the body.
    fn json_exporter() -> Exporter {
        let config = Config::new().otlp_protocol(OtlpProtocol::HttpJson);

        Exporter::new(
            &config,
            Arc::new(FakeTransport::default()),
            "key".to_owned(),
        )
    }

    #[test]
    fn reads_the_partial_success_of_a_protobuf_response() {
        // The protobuf encoding of a logs response with 2 rejected log records.
        let body = [0x0a, 0x02, 0x08, 0x02];

        let partial = exporter().partial_success(Signal::Logs, &body);

        assert_eq!(partial.map(|partial| partial.rejected), Some(2));
    }

    #[test]
    fn reads_the_partial_success_of_a_json_response() {
        let body = br#"{"partialSuccess":{"rejectedSpans":"1"}}"#;

        let partial = json_exporter().partial_success(Signal::Traces, body);

        assert_eq!(partial.map(|partial| partial.rejected), Some(1));
    }

    #[test]
    fn error_reports_have_no_partial_success() {
        let body = br#"{"partialSuccess":{"rejectedLogRecords":"1"}}"#;

        assert_eq!(json_exporter().partial_success(Signal::Errors, body), None);
    }

    #[test]
    fn splits_batches_that_are_too_large() {
        let big = "x".repeat(MAX_BATCH_BYTES / 2);
        let records = [log(&big), log(&big)];

        let Encoded::Body { count, .. } = exporter().encode(&records) else {
            panic!("expected a body");
        };

        assert_eq!(count, 1);
    }

    #[test]
    fn splits_batches_between_traces_not_inside_them() {
        let span = |name: &str| {
            let mut span = crate::test_support::span();
            span.name = name.to_owned().into();

            span
        };
        let big = "x".repeat(MAX_BATCH_BYTES / 2);
        let traces = [
            Trace(vec![span(&big), span("child")]),
            Trace(vec![span(&big), span("child")]),
        ];

        let Encoded::Body { count, body } = json_exporter().encode(&traces) else {
            panic!("expected a body");
        };
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();

        assert_eq!(count, 1);
        assert_eq!(
            json["resourceSpans"][0]["scopeSpans"][0]["spans"]
                .as_array()
                .map(Vec::len),
            Some(2)
        );
    }

    #[test]
    fn skips_a_single_record_that_is_too_large() {
        let records = [log(&"x".repeat(MAX_BATCH_BYTES))];

        assert!(matches!(
            exporter().encode(&records),
            Encoded::Skip { count: 1, .. }
        ));
    }

    #[test]
    fn plans_a_retry_from_the_end_of_a_slow_request() {
        let config = Config::new().retry(RetryPolicy {
            max_retries: 3,
            base_delay: Duration::from_millis(100),
            max_delay: Duration::from_millis(100),
        });
        let transport = Arc::new(SlowFailure(Duration::from_millis(300)));
        let exporter = Exporter::new(&config, transport, "key".to_owned());
        let mut batcher = Batcher::new(&config);
        let started = Instant::now();
        batcher.push(log("one"), started);
        batcher.flush();

        exporter.send_due(&mut batcher, started);

        let retry_at = batcher.next_send_at().unwrap();
        assert!(retry_at >= started + Duration::from_millis(350));
    }
}