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};
const MAX_BATCH_BYTES: usize = 800_000;
enum Encoded {
Body { body: Vec<u8>, count: usize },
Skip { count: usize, reason: String },
}
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 {
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,
}
}
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),
}
}
}
pub(super) fn set_framework(&mut self, name: String, version: Option<String>) {
self.set_resource_attributes(resource::framework_attributes(name, version));
}
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);
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);
}
}
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(),
};
}
}
}
}
fn send(&self, signal: Signal, content_type: &'static str, body: Vec<u8>) -> Outcome {
let mut headers = self.headers.clone();
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,
};
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
}
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),
),
}
}
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;
#[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(),
)
}
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() {
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));
}
}