use std::borrow::Cow;
use std::collections::VecDeque;
use std::time::{Duration, Instant};
use flareapp_otlp::{
InstrumentationScope, LogRecord, Resource, ScopeLogs, Span, encode_logs_json,
encode_logs_protobuf, encode_traces_json, encode_traces_protobuf,
};
use super::retry::RetryPolicy;
use crate::config::{Config, OtlpProtocol};
use crate::report::ResolvedReport;
use crate::time::later;
use crate::transport::Signal;
pub(super) trait Batchable: Sized {
const SIGNAL: Signal;
const MIN_INTERVAL: Duration;
const BATCH_SIZE: Option<usize> = None;
const INTERVAL: Option<Duration> = None;
fn encode(
resource: &Resource,
scope: &InstrumentationScope,
records: &[Self],
protocol: OtlpProtocol,
) -> serde_json::Result<Vec<u8>>;
fn content_type(protocol: OtlpProtocol) -> &'static str {
protocol.content_type()
}
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Log {
pub(crate) target: Cow<'static, str>,
pub(crate) record: LogRecord,
}
impl Batchable for Log {
const SIGNAL: Signal = Signal::Logs;
const MIN_INTERVAL: Duration = Duration::ZERO;
fn encode(
resource: &Resource,
scope: &InstrumentationScope,
records: &[Self],
protocol: OtlpProtocol,
) -> serde_json::Result<Vec<u8>> {
let scope_logs = by_target(scope, records);
match protocol {
OtlpProtocol::HttpProtobuf => Ok(encode_logs_protobuf(resource, &scope_logs)),
OtlpProtocol::HttpJson => encode_logs_json(resource, &scope_logs),
}
}
}
fn by_target<'a>(scope: &InstrumentationScope, logs: &'a [Log]) -> Vec<ScopeLogs<'a>> {
let mut groups: Vec<ScopeLogs<'a>> = Vec::new();
for log in logs {
match groups
.iter_mut()
.find(|group| group.scope.name == log.target)
{
Some(group) => group.log_records.push(&log.record),
None => groups.push(ScopeLogs::new(
InstrumentationScope::new(log.target.clone(), scope.version.clone()),
vec![&log.record],
)),
}
}
groups
}
impl Batchable for ResolvedReport {
const SIGNAL: Signal = Signal::Errors;
const MIN_INTERVAL: Duration = Duration::ZERO;
const BATCH_SIZE: Option<usize> = Some(1);
const INTERVAL: Option<Duration> = Some(Duration::ZERO);
fn encode(
resource: &Resource,
_scope: &InstrumentationScope,
records: &[Self],
_protocol: OtlpProtocol,
) -> serde_json::Result<Vec<u8>> {
records
.first()
.map_or_else(|| Ok(Vec::new()), |report| report.encode(resource))
}
fn content_type(_protocol: OtlpProtocol) -> &'static str {
"application/json"
}
}
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct Trace(pub(crate) Vec<Span>);
impl Batchable for Trace {
const SIGNAL: Signal = Signal::Traces;
const MIN_INTERVAL: Duration = Duration::from_secs(20);
const BATCH_SIZE: Option<usize> = Some(usize::MAX);
fn encode(
resource: &Resource,
scope: &InstrumentationScope,
records: &[Self],
protocol: OtlpProtocol,
) -> serde_json::Result<Vec<u8>> {
let spans = records.iter().flat_map(|trace| &trace.0);
match protocol {
OtlpProtocol::HttpProtobuf => Ok(encode_traces_protobuf(resource, scope, spans)),
OtlpProtocol::HttpJson => encode_traces_json(resource, scope, spans),
}
}
}
pub(super) struct Batcher<T> {
records: VecDeque<T>,
capacity: usize,
batch_size: usize,
interval: Duration,
min_interval: Duration,
waiting: Option<Waiting>,
last_attempt: Option<Instant>,
retry_policy: RetryPolicy,
removed: u64,
flush_until: u64,
}
struct Waiting {
since: Instant,
retry: Option<Retry>,
}
struct Retry {
attempt: u32,
not_before: Instant,
}
impl<T: Batchable> Batcher<T> {
pub(super) fn new(config: &Config) -> Self {
Self {
records: VecDeque::new(),
capacity: config.queue_capacity,
batch_size: T::BATCH_SIZE.unwrap_or(config.batch_size),
interval: T::INTERVAL.unwrap_or(config.batch_interval),
min_interval: T::MIN_INTERVAL,
waiting: None,
last_attempt: None,
retry_policy: config.retry,
removed: 0,
flush_until: 0,
}
}
}
impl<T> Batcher<T> {
pub(super) fn push(&mut self, record: T, now: Instant) -> bool {
let dropped = self.records.len() >= self.capacity && self.records.pop_front().is_some();
if dropped {
self.removed += 1;
}
if self.records.is_empty() {
let retry = self.waiting.take().and_then(|waiting| waiting.retry);
self.waiting = Some(Waiting { since: now, retry });
}
self.records.push_back(record);
!dropped
}
pub(super) fn flush(&mut self) -> u64 {
self.flush_until = self.removed + self.records.len() as u64;
self.flush_until
}
pub(super) fn is_flushed(&self, mark: u64) -> bool {
self.removed >= mark
}
pub(super) fn is_flush_done_by(&self, mark: u64, deadline: Instant) -> bool {
let retry_planned = self
.waiting
.as_ref()
.is_some_and(|waiting| waiting.retry.is_some());
self.is_flushed(mark)
|| (retry_planned
&& self
.next_send_at()
.is_some_and(|send_at| send_at >= deadline))
}
pub(super) fn next_send_at(&self) -> Option<Instant> {
let waiting = self.waiting.as_ref()?;
if let Some(retry) = &waiting.retry {
let allowed_at = self.last_attempt.map_or(retry.not_before, |attempt| {
later(attempt, self.min_interval)
});
return Some(retry.not_before.max(allowed_at));
}
if !self.is_flushed(self.flush_until) {
return Some(waiting.since);
}
let ready_at = if self.records.len() >= self.batch_size {
waiting.since
} else {
later(waiting.since, self.interval)
};
let allowed_at = self
.last_attempt
.map_or(ready_at, |attempt| later(attempt, self.min_interval));
Some(ready_at.max(allowed_at))
}
pub(super) fn batch(&mut self) -> &[T] {
let size = self.records.len().min(self.batch_size);
self.records
.make_contiguous()
.get(..size)
.unwrap_or_default()
}
pub(super) fn remove(&mut self, count: usize, now: Instant) {
let count = count.min(self.records.len());
self.records.drain(..count);
self.removed += count as u64;
self.last_attempt = Some(now);
self.waiting = (!self.records.is_empty()).then_some(Waiting {
since: now,
retry: None,
});
}
pub(super) fn schedule_retry(&mut self, now: Instant, retry_after: Option<Duration>) -> bool {
let Some(waiting) = &mut self.waiting else {
return false;
};
self.last_attempt = Some(now);
let policy = &self.retry_policy;
let attempt = waiting.retry.as_ref().map_or(0, |retry| retry.attempt + 1);
if attempt >= policy.max_retries {
return false;
}
waiting.retry = Some(Retry {
attempt,
not_before: later(now, policy.delay(attempt, retry_after)),
});
true
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::test_support::{log as record, secs, span};
fn log(body: &str) -> Log {
log_of("shop", body)
}
fn log_of(target: &str, body: &str) -> Log {
Log {
target: target.to_owned().into(),
record: record(body),
}
}
fn config() -> Config {
Config::new()
.batch_size(3)
.batch_interval(Duration::from_secs(5))
.queue_capacity(5)
}
#[test]
fn an_empty_batcher_has_nothing_to_send() {
let batcher = Batcher::<Log>::new(&config());
assert_eq!(batcher.next_send_at(), None);
}
#[test]
fn sends_after_the_interval() {
let now = Instant::now();
let mut batcher = Batcher::new(&config());
batcher.push(log("one"), now);
assert_eq!(batcher.next_send_at(), Some(now + secs(5)));
}
#[test]
fn sends_right_away_when_a_batch_is_full() {
let now = Instant::now();
let mut batcher = Batcher::new(&config());
for body in ["one", "two", "three"] {
batcher.push(log(body), now);
}
assert_eq!(batcher.next_send_at(), Some(now));
}
#[test]
fn sends_right_away_when_flushing() {
let now = Instant::now();
let mut batcher = Batcher::new(&config());
batcher.push(log("one"), now);
batcher.flush();
assert_eq!(batcher.next_send_at(), Some(now));
}
#[test]
fn records_after_a_flush_wait_for_their_batch() {
let now = Instant::now();
let mut batcher = Batcher::new(&config());
batcher.push(log("one"), now);
let mark = batcher.flush();
batcher.push(log("two"), now);
let sent = batcher.batch().len();
batcher.remove(sent, now);
batcher.push(log("three"), now);
assert!(batcher.is_flushed(mark));
assert_eq!(batcher.next_send_at(), Some(now + secs(5)));
}
#[test]
fn a_dropped_record_no_longer_holds_up_the_flush() {
let now = Instant::now();
let mut batcher = Batcher::new(&config());
batcher.push(log("one"), now);
let mark = batcher.flush();
for index in 0..5 {
batcher.push(log(&index.to_string()), now);
}
assert!(batcher.is_flushed(mark));
}
#[test]
fn waits_between_trace_requests() {
let now = Instant::now();
let mut batcher = Batcher::<Trace>::new(&config());
batcher.push(Trace(vec![span()]), now);
batcher.remove(1, now);
batcher.push(Trace(vec![span()]), now);
assert_eq!(batcher.next_send_at(), Some(now + Trace::MIN_INTERVAL));
}
#[test]
fn the_batch_size_does_not_limit_a_batch_of_traces() {
let now = Instant::now();
let mut batcher = Batcher::<Trace>::new(&config().batch_size(1).queue_capacity(150));
for _ in 0..150 {
batcher.push(Trace(vec![span()]), now);
}
assert_eq!(batcher.batch().len(), 150);
}
#[test]
fn a_flush_sends_traces_without_the_minimum_interval() {
let now = Instant::now();
let mut batcher = Batcher::<Trace>::new(&config());
batcher.push(Trace(vec![span()]), now);
batcher.remove(1, now);
batcher.push(Trace(vec![span()]), now);
batcher.push(Trace(vec![span()]), now);
batcher.flush();
let first = batcher.next_send_at();
batcher.remove(1, now);
assert_eq!((first, batcher.next_send_at()), (Some(now), Some(now)));
}
fn full_batcher(now: Instant) -> Batcher<Log> {
let mut batcher = Batcher::new(&config());
for index in 0..5 {
batcher.push(log(&index.to_string()), now);
}
batcher
}
#[test]
fn push_returns_true_while_there_is_room() {
let now = Instant::now();
let mut batcher = Batcher::new(&config());
let pushed: Vec<bool> = (0..5)
.map(|index| batcher.push(log(&index.to_string()), now))
.collect();
assert_eq!(pushed, [true; 5]);
}
#[test]
fn push_returns_false_when_full() {
let now = Instant::now();
let mut batcher = full_batcher(now);
assert!(!batcher.push(log("5"), now));
}
#[test]
fn drops_the_oldest_record_when_full() {
let now = Instant::now();
let mut batcher = full_batcher(now);
batcher.push(log("5"), now);
let bodies: Vec<&str> = batcher
.batch()
.iter()
.map(|log| log.record.body.as_str())
.collect();
assert_eq!(bodies, ["1", "2", "3"]);
}
#[test]
fn a_batch_holds_at_most_batch_size_records() {
let now = Instant::now();
let mut batcher = Batcher::new(&config());
for index in 0..5 {
batcher.push(log(&index.to_string()), now);
}
assert_eq!(batcher.batch().len(), 3);
}
#[test]
fn removing_records_resets_the_retry() {
let now = Instant::now();
let mut batcher = Batcher::new(&config());
batcher.push(log("one"), now);
batcher.schedule_retry(now, Some(secs(60)));
batcher.remove(1, now);
batcher.push(log("two"), now);
assert_eq!(batcher.next_send_at(), Some(now + secs(5)));
}
#[test]
fn trace_retries_keep_the_minimum_interval() {
let now = Instant::now();
let mut batcher = Batcher::<Trace>::new(&config());
batcher.push(Trace(vec![span()]), now);
assert!(batcher.schedule_retry(now, Some(secs(1))));
assert_eq!(batcher.next_send_at(), Some(now + Trace::MIN_INTERVAL));
}
#[test]
fn a_long_trace_retry_wait_is_kept() {
let now = Instant::now();
let mut batcher = Batcher::<Trace>::new(&config());
batcher.push(Trace(vec![span()]), now);
assert!(batcher.schedule_retry(now, Some(secs(60))));
assert_eq!(batcher.next_send_at(), Some(now + secs(60)));
}
#[test]
fn retries_wait_until_the_retry_time() {
let now = Instant::now();
let mut batcher = Batcher::new(&config());
batcher.push(log("one"), now);
assert!(batcher.schedule_retry(now, Some(secs(60))));
batcher.flush();
assert_eq!(batcher.next_send_at(), Some(now + secs(60)));
}
#[test]
fn a_flush_is_not_done_while_its_records_wait() {
let now = Instant::now();
let mut batcher = Batcher::new(&config());
batcher.push(log("one"), now);
let mark = batcher.flush();
assert!(!batcher.is_flush_done_by(mark, now + secs(2)));
}
fn flush_with_a_retry(now: Instant) -> (Batcher<Log>, u64) {
let mut batcher = Batcher::new(&config());
batcher.push(log("one"), now);
let mark = batcher.flush();
batcher.schedule_retry(now, Some(secs(60)));
(batcher, mark)
}
#[test]
fn a_flush_is_done_by_a_deadline_before_its_retry() {
let now = Instant::now();
let (batcher, mark) = flush_with_a_retry(now);
assert!(batcher.is_flush_done_by(mark, now + secs(2)));
}
#[test]
fn a_flush_is_not_done_by_a_deadline_after_its_retry() {
let now = Instant::now();
let (batcher, mark) = flush_with_a_retry(now);
assert!(!batcher.is_flush_done_by(mark, now + secs(61)));
}
fn encoded_scope_logs(logs: &[Log]) -> Vec<serde_json::Value> {
let scope = InstrumentationScope::new("flareapp", "1.2.3");
let body = Log::encode(
&Resource::new(Vec::new()),
&scope,
logs,
OtlpProtocol::HttpJson,
)
.unwrap();
let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
json["resourceLogs"][0]["scopeLogs"]
.as_array()
.unwrap()
.clone()
}
fn record_bodies(scope_logs: &serde_json::Value) -> Vec<&str> {
scope_logs["logRecords"]
.as_array()
.unwrap()
.iter()
.map(|record| record["body"]["stringValue"].as_str().unwrap())
.collect()
}
#[test]
fn logs_get_one_scope_for_each_target() {
let scope_logs = encoded_scope_logs(&[
log_of("shop::auth", "one"),
log_of("shop::checkout", "two"),
log_of("shop::auth", "three"),
]);
let names: Vec<_> = scope_logs
.iter()
.map(|entry| entry["scope"]["name"].as_str().unwrap())
.collect();
assert_eq!(names, ["shop::auth", "shop::checkout"]);
}
#[test]
fn logs_of_one_target_share_a_scope_in_order() {
let scope_logs = encoded_scope_logs(&[
log_of("shop::auth", "one"),
log_of("shop::checkout", "two"),
log_of("shop::auth", "three"),
]);
assert_eq!(record_bodies(&scope_logs[0]), ["one", "three"]);
assert_eq!(record_bodies(&scope_logs[1]), ["two"]);
}
#[test]
fn target_scopes_have_the_sdk_version() {
let scope_logs = encoded_scope_logs(&[log_of("shop::auth", "one")]);
assert_eq!(scope_logs[0]["scope"]["version"], "1.2.3");
}
#[test]
fn a_trace_with_two_scopes_stays_in_one_request() {
let scope = InstrumentationScope::new("flareapp", "1.2.3");
let framework = Span {
scope: Some(InstrumentationScope::new("laravel", "")),
..span()
};
let trace = Trace(vec![framework, span()]);
let body = Trace::encode(
&Resource::new(Vec::new()),
&scope,
&[trace],
OtlpProtocol::HttpJson,
)
.unwrap();
let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
let scopes: Vec<_> = json["resourceSpans"][0]["scopeSpans"]
.as_array()
.unwrap()
.iter()
.map(|entry| {
(
entry["scope"]["name"].as_str().unwrap(),
entry["spans"].as_array().unwrap().len(),
)
})
.collect();
assert_eq!(scopes, [("laravel", 1), ("flareapp", 1)]);
}
#[test]
fn gives_up_after_the_last_retry() {
let now = Instant::now();
let policy = RetryPolicy::default();
let mut batcher = Batcher::new(&config());
batcher.push(log("one"), now);
for _ in 0..policy.max_retries {
assert!(batcher.schedule_retry(now, None));
}
assert!(!batcher.schedule_retry(now, None));
}
}