use std::io;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use serde::Serialize;
use super::StatsState;
use super::stats::{beside, replace};
pub const EVENTS_FORMAT: u32 = 1;
pub const DEFAULT_EVENTS_INTERVAL: Duration = Duration::from_secs(1);
pub const MIN_EVENTS_INTERVAL: Duration = Duration::from_millis(200);
pub const MAX_EVENTS_INTERVAL: Duration = Duration::from_secs(60);
pub const DEFAULT_EVENTS_MAX: usize = 10_000;
pub const MAX_EVENTS_MAX: usize = 100_000;
const FAST: u64 = 1 << 63;
const FAILED: u64 = 1 << 62;
const MICROS: u64 = FAILED - 1;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Record {
at_us: u64,
took: u64,
}
const _: () = assert!(size_of::<Record>() <= 16);
impl Record {
fn new(at: Duration, took: Duration, fast: bool, failed: bool) -> Self {
let micros = |duration: Duration| u64::try_from(duration.as_micros()).unwrap_or(u64::MAX);
let mut packed = micros(took).min(MICROS);
if fast {
packed |= FAST;
}
if failed {
packed |= FAILED;
}
Self {
at_us: micros(at),
took: packed,
}
}
fn row(self, from_us: u64, length_ms: u64) -> [u64; 4] {
[
(self.at_us.saturating_sub(from_us) / 1_000).min(length_ms),
u64::from(self.took & FAST != 0),
u64::from(self.took & FAILED == 0),
self.took & MICROS,
]
}
}
#[derive(Debug)]
struct Pending {
records: Vec<Record>,
dropped: u64,
}
#[derive(Debug)]
pub(crate) struct Buffer {
origin: Instant,
max: usize,
pending: Mutex<Pending>,
}
impl Buffer {
pub(crate) fn new(origin: Instant, max: usize) -> Self {
Self {
origin,
max,
pending: Mutex::new(Pending {
records: Vec::with_capacity(max),
dropped: 0,
}),
}
}
pub(crate) fn record(&self, fast: bool, failed: bool, took: Duration) {
let record = Record::new(
Instant::now().saturating_duration_since(self.origin),
took,
fast,
failed,
);
let mut pending = self.pending.lock().unwrap_or_else(PoisonError::into_inner);
if pending.records.len() < self.max {
pending.records.push(record);
} else {
pending.dropped += 1;
}
}
fn take(&self, spare: &mut Vec<Record>) -> u64 {
let mut pending = self.pending.lock().unwrap_or_else(PoisonError::into_inner);
std::mem::swap(&mut pending.records, spare);
std::mem::take(&mut pending.dropped)
}
}
#[derive(Debug, Clone)]
pub struct Events {
pub(crate) buffer: Arc<Buffer>,
pub(crate) started_at: u64,
pub(crate) started_ms: u64,
}
impl Events {
#[must_use]
pub fn max(&self) -> usize {
self.buffer.max
}
#[must_use]
pub const fn started_at(&self) -> u64 {
self.started_at
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct EventsDocument {
pub state: StatsState,
pub started_at: u64,
pub seq: u64,
pub from_ms: u64,
pub at_ms: u64,
pub dropped: u64,
pub records: Vec<[u64; 4]>,
}
impl Default for EventsDocument {
fn default() -> Self {
Self {
state: StatsState::Running,
started_at: 0,
seq: 0,
from_ms: 0,
at_ms: 0,
dropped: 0,
records: Vec::new(),
}
}
}
#[must_use]
pub fn events_document(document: &EventsDocument) -> String {
#[derive(Serialize)]
struct Line<'a> {
format: u32,
program: &'static str,
version: &'static str,
state: StatsState,
started_at: u64,
seq: u64,
from_ms: u64,
at_ms: u64,
count: usize,
dropped: u64,
records: &'a [[u64; 4]],
}
let line = Line {
format: EVENTS_FORMAT,
program: crate::RUNNER.name,
version: env!("CARGO_PKG_VERSION"),
state: document.state,
started_at: document.started_at,
seq: document.seq,
from_ms: document.from_ms,
at_ms: document.at_ms,
count: document.records.len(),
dropped: document.dropped,
records: &document.records,
};
serde_json::to_string(&line).unwrap_or_default()
}
#[derive(Debug)]
pub struct EventsFile {
path: PathBuf,
temporary: PathBuf,
seq: u64,
from: Option<(u64, u64)>,
dropped: u64,
spare: Vec<Record>,
failure: Option<io::ErrorKind>,
}
impl EventsFile {
pub fn new(path: impl AsRef<Path>) -> io::Result<Self> {
let (path, temporary) = beside(path.as_ref())?;
Ok(Self {
path,
temporary,
seq: 0,
from: None,
dropped: 0,
spare: Vec::new(),
failure: None,
})
}
#[must_use]
pub fn path(&self) -> &Path {
&self.path
}
pub fn write(&mut self, events: &Events, state: StatsState) -> io::Result<Option<EventsDocument>> {
let buffer = &events.buffer;
let at_ms = unix_ms(SystemTime::now());
let at_us = u64::try_from(buffer.origin.elapsed().as_micros()).unwrap_or(u64::MAX);
if self.spare.capacity() < buffer.max {
self.spare.reserve_exact(buffer.max);
}
let first = self.seq == 0 && state == StatsState::Running;
let full = if first { 0 } else { buffer.take(&mut self.spare) };
let answered = !self.spare.is_empty() || full > 0;
if !answered && !first && state == StatsState::Running {
return Ok(None);
}
let (from_ms, from_us) = self.from.unwrap_or((events.started_ms, 0));
let at_ms = at_ms.max(from_ms);
let length_ms = at_ms - from_ms;
self.spare.sort_by_key(|record| record.at_us);
let records: Vec<[u64; 4]> = self.spare.iter().map(|record| record.row(from_us, length_ms)).collect();
self.spare.clear();
let dropped = self.dropped + full;
let document = EventsDocument {
state,
started_at: events.started_at,
seq: self.seq + 1,
from_ms,
at_ms,
dropped,
records,
};
let mut text = events_document(&document);
text.push('\n');
match replace(&self.temporary, &self.path, text.as_bytes()) {
Ok(()) => {
self.seq = document.seq;
self.from = Some((at_ms, at_us));
self.dropped = 0;
self.failure = None;
Ok(Some(document))
}
Err(error) => {
self.dropped = dropped + document.records.len() as u64;
if self.failure != Some(error.kind()) {
tracing::warn!(path = %self.path.display(), error = %error, "Couldn't write the events file; the worker carries on");
}
self.failure = Some(error.kind());
Err(error)
}
}
}
}
fn unix_ms(time: SystemTime) -> u64 {
time.duration_since(UNIX_EPOCH)
.map_or(0, |since| u64::try_from(since.as_millis()).unwrap_or(u64::MAX))
}
pub(crate) fn unix_ms_and_seconds(time: SystemTime) -> (u64, u64) {
let ms = unix_ms(time);
(ms, ms / 1_000)
}
#[cfg(test)]
mod tests {
use std::time::{Duration, Instant};
use super::{Buffer, MICROS, Record};
#[test]
fn a_record_keeps_its_lane_outcome_and_time_apart() {
for (fast, failed) in [(false, false), (false, true), (true, false), (true, true)] {
let record = Record::new(
Duration::from_millis(1_500),
Duration::from_micros(229_104),
fast,
failed,
);
assert_eq!(
record.row(1_000_000, 1_000),
[500, u64::from(fast), u64::from(!failed), 229_104]
);
}
let longest = Record::new(Duration::ZERO, Duration::MAX, true, false);
assert_eq!(longest.row(0, 0), [0, 1, 1, MICROS]);
}
#[test]
fn an_offset_is_clamped_to_the_interval() {
let record = Record::new(Duration::from_millis(10), Duration::ZERO, false, false);
assert_eq!(record.row(20_000, 100)[0], 0, "answered before the interval");
assert_eq!(record.row(0, 5)[0], 5, "past its end");
}
#[test]
fn a_full_buffer_counts_what_it_drops_and_a_take_empties_it() {
let buffer = Buffer::new(Instant::now(), 3);
for _ in 0..5 {
buffer.record(false, false, Duration::from_millis(1));
}
let mut spare = Vec::with_capacity(3);
assert_eq!(buffer.take(&mut spare), 2);
assert_eq!(spare.len(), 3);
spare.clear();
assert_eq!(buffer.take(&mut spare), 0);
assert!(spare.is_empty());
assert!(buffer.pending.lock().expect("unpoisoned").records.capacity() >= 3);
}
}