use std::borrow::Cow;
use std::collections::btree_map::Entry;
use std::collections::{BTreeMap, HashMap};
use std::time::Duration;
use rusqlite::{Connection, OptionalExtension, params};
use super::buckets::{bound_of, le};
use super::codec::Point;
use super::describe::{self, Description};
use super::engine::{AHEAD, Engine, execute};
use super::head::{self, Extent};
use super::labels::Kept;
use super::ladder::{unit_end, unit_of};
use super::names::{Changes, KEEP, Name, checked_keep, millis, write_changes};
use super::registry::Registering;
use super::repeat::Packed;
use super::retention::expires;
use super::series::{Kind, Labels, Series};
use super::timestamp::rfc3339;
use crate::compress::frame::Zstd;
use crate::limits::{INGEST_BYTES, INGEST_SAMPLES, Limit, REPLACE_BYTES, REPLACE_SAMPLES, TEXT_BYTES, TEXT_SAMPLES};
use crate::sqlite::{Tx, sql_error};
use crate::{Error, ErrorKind, Reservation, Result, unix_millis};
#[derive(Clone, Copy, Debug)]
pub(super) struct Bound {
samples: Limit,
bytes: Limit,
}
pub(super) const ONE_INGEST: Bound = Bound { samples: INGEST_SAMPLES, bytes: INGEST_BYTES };
pub(super) const ONE_REPLACE: Bound = Bound { samples: REPLACE_SAMPLES, bytes: REPLACE_BYTES };
pub(super) const ONE_TEXT: Bound = Bound { samples: TEXT_SAMPLES, bytes: TEXT_BYTES };
pub(super) const SAMPLE_BYTES: usize = 16;
pub(super) const VERSIONS: Limit = Limit { name: "series versions", bound: i64::MAX as u64 };
use crate::memory::PATIENCE;
pub(super) const SERIES_HOLDS: usize = 2 * (32 + size_of::<Gathered>()) + size_of::<Batch>() + 64;
pub(super) const NAME_HOLDS: usize = 384;
pub(super) const PAIR_HOLDS: usize = size_of::<(String, String)>();
pub(super) const POINT_HOLDS: usize = 2 * size_of::<Point>();
#[derive(Debug)]
pub(super) struct Batch {
pub(super) kept: Kept,
pub(super) identity: [u8; 32],
pub(super) kind: Kind,
pub(super) name: i64,
pub(super) keep: i64,
pub(super) points: Vec<Point>,
}
struct Gathered {
kept: Kept,
kind: Kind,
keep: Option<Duration>,
points: Vec<Point>,
}
pub(super) struct Gathering {
bound: Bound,
gathered: BTreeMap<[u8; 32], Gathered>,
samples: usize,
bytes: usize,
holds: usize,
}
impl Gathering {
pub(super) fn new(bound: Bound) -> Gathering {
Gathering { bound, gathered: BTreeMap::new(), samples: 0, bytes: 0, holds: 0 }
}
pub(super) fn add(&mut self, given: &Series) -> Result<()> {
let named = || format!("metrics {given}");
super::instruments::refuse_the_stores_own(&given.name).map_err(|error| error.within(named()))?;
let labels = bounded(given).map_err(|error| error.within(named()))?;
let kept = Kept::of(&given.name, &labels).map_err(|error| error.within(named()))?;
if given.samples.is_empty() {
return Err(Error::invalid(format!("{}: a series without samples", named())));
}
let keep = given.keep.map(checked_keep).transpose().map_err(|error| error.within(named()))?;
self.samples += given.samples.len();
self.bytes += kept.bytes() + SAMPLE_BYTES * given.samples.len();
within(self.bound, "an ingest", self.samples, self.bytes).map_err(|error| error.within("metrics"))?;
self.holds += POINT_HOLDS * given.samples.len();
let points = given.samples.iter().map(|sample| Point { at: unix_millis(sample.at), value: sample.value });
let entry = match self.gathered.entry(kept.identity()) {
Entry::Occupied(entry) => entry.into_mut(),
Entry::Vacant(entry) => {
self.holds += SERIES_HOLDS + kept.holds() + NAME_HOLDS + 4 * given.name.len();
entry.insert(Gathered { kept, kind: given.kind, keep, points: Vec::new() })
}
};
if entry.kind != given.kind || (keep.is_some() && entry.keep.is_some_and(|before| Some(before) != keep)) {
return Err(Error::invalid(format!("{}: given twice in one ingest, as two kinds or two keeps", named())));
}
entry.keep = entry.keep.or(keep);
entry.points.extend(points);
Ok(())
}
}
pub(crate) struct Checked {
now: i64,
gathering: Gathering,
described: Vec<(String, Description)>,
}
impl Checked {
pub(crate) fn holds(&self) -> u64 {
self.gathering.holds as u64
}
pub(super) fn described(mut self, described: Vec<(String, Description)>) -> Checked {
let weighs = |(name, given): &(String, Description)| name.len() + given.unit.len() + given.help.len();
let weight = described.iter().map(weighs).sum::<usize>();
self.gathering.bytes += weight;
self.gathering.holds += weight + described.len() * size_of::<(String, Description)>();
self.described = described;
self
}
}
impl Engine {
pub(super) fn ingest(&self, series: &[Series]) -> Result<()> {
self.ingest_held(self.check(series)?)
}
pub(super) fn ingest_held(&self, checked: Checked) -> Result<()> {
let held = self.memory.reserve(checked.holds(), "metrics: an ingest", PATIENCE)?;
self.ingest_checked(checked, held)
}
pub(super) fn check(&self, series: &[Series]) -> Result<Checked> {
let mut gathering = Gathering::new(ONE_INGEST);
series.iter().try_for_each(|given| gathering.add(given))?;
Ok(self.checked(gathering))
}
pub(super) fn checked(&self, gathering: Gathering) -> Checked {
Checked { now: self.now(), gathering, described: Vec::new() }
}
pub(super) fn ingest_checked(&self, checked: Checked, _held: Reservation) -> Result<()> {
let Checked { now, gathering, described } = checked;
let Gathering { gathered, samples, bytes, .. } = gathering;
let wanted = wanted_names(&gathered)?;
let keeps = self.names.foreseen(&wanted);
for series in gathered.values() {
within_window(series, keeps.get(series.kept.name()).copied().unwrap_or(KEEP), now)?;
}
let settling = self.names.settling(&wanted)?;
let names = settling.names();
let mut batches = Vec::with_capacity(gathered.len());
for (identity, series) in gathered {
batches.push(batch(identity, series, &names, now)?);
}
if batches.is_empty() {
return Ok(());
}
let (ready, made) = self.write(batches, (settling.changes(), described), bytes)?;
settling.settled(made);
if ready {
self.wake();
}
self.probe.count("tinystore_metrics_samples_total", &[], samples as f64);
Ok(())
}
fn write(
&self,
mut batches: Vec<Batch>,
(names, described): (Changes, Vec<(String, Description)>),
bytes: usize,
) -> Result<(bool, HashMap<String, i64>)> {
let zstd = self.codecs.take();
let max_series = self.max_series;
let (zstd, ready, made) = self.file.write(bytes, move |tx| {
let mut zstd = zstd;
let made = write_changes(tx, &names)?;
let (mut ready, mut registering) = (false, Registering::new(max_series));
for batch in &mut batches {
if let Some(id) = made.get(batch.kept.name()) {
batch.name = *id;
}
let written = write_series(tx, &mut zstd, &mut registering, batch);
ready |= written.map_err(|error| error.within(format!("metrics {}", batch.kept)))?;
}
registering.finish(tx)?;
describe::fill(tx, &described)?;
Ok((zstd, ready, made))
})?;
self.codecs.give_back(zstd);
Ok((ready, made))
}
}
pub(super) fn within(bound: Bound, what: &str, samples: usize, bytes: usize) -> Result<()> {
let (most, mib) = (bound.samples.bound, bound.bytes.bound >> 20);
let refused = || format!("{what} past {most} samples or {mib} MiB: send it in parts");
if samples as u64 > bound.samples.bound {
return Err(bound.samples.refuse(samples as u64, refused()));
}
if bytes as u64 > bound.bytes.bound {
return Err(bound.bytes.refuse(bytes as u64, refused()));
}
Ok(())
}
fn bounded(series: &Series) -> Result<Cow<'_, Labels>> {
if series.kind != Kind::Histogram {
return Ok(Cow::Borrowed(&series.labels));
}
let bound = series.labels.get("le").and_then(|text| bound_of(text)).ok_or_else(|| {
Error::invalid("a histogram's series counts the values at most its bound, `le`: a number of 0 or more, or +Inf")
})?;
let mut labels = series.labels.clone();
labels.insert("le".to_owned(), le(bound));
Ok(Cow::Owned(labels))
}
fn wanted_names(gathered: &BTreeMap<[u8; 32], Gathered>) -> Result<BTreeMap<&str, Option<Duration>>> {
let mut wanted: BTreeMap<&str, Option<Duration>> = BTreeMap::new();
for series in gathered.values() {
let given = wanted.entry(series.kept.name()).or_default();
match (*given, series.keep) {
(Some(before), Some(keep)) if before != keep => {
return Err(Error::invalid(format!("metrics {}: two keeps in one ingest", series.kept.name())));
}
(None, keep) => *given = keep,
_ => {}
}
}
Ok(wanted)
}
fn batch(identity: [u8; 32], series: Gathered, names: &HashMap<String, Name>, now: i64) -> Result<Batch> {
let named = || format!("metrics {}", series.kept);
let name = names.get(series.kept.name()).ok_or_else(|| Error::internal(format!("{}: its name", named())))?;
within_window(&series, name.keeps(), now)?;
let keep = millis(name.keeps());
let points = ordered(series.points);
Ok(Batch { identity, kept: series.kept, kind: series.kind, name: name.id, keep, points })
}
fn within_window(series: &Gathered, keep: Duration, now: i64) -> Result<()> {
let (cutoff, horizon) = (now.saturating_sub(millis(keep)), now.saturating_add(millis(AHEAD)));
for point in &series.points {
let refused =
|kind, why| Error::new(kind, format!("metrics {}: sample at {}{why}", series.kept, rfc3339(point.at)));
if point.at < cutoff {
return Err(refused(ErrorKind::TooOld, ", older than its name keeps"));
}
if point.at > horizon || point.at == i64::MAX {
return Err(refused(ErrorKind::TooNew, ", more than ten minutes ahead of the store's clock"));
}
}
Ok(())
}
pub(super) fn ordered(mut points: Vec<Point>) -> Vec<Point> {
if points.windows(2).all(|pair| pair[0].at < pair[1].at) {
return points;
}
points.sort_by_key(|point| point.at);
let mut kept: Vec<Point> = Vec::with_capacity(points.len());
for point in points {
match kept.last_mut() {
Some(last) if last.at == point.at => *last = point,
_ => kept.push(point),
}
}
kept
}
pub(super) struct State {
pub(super) sealed_before: Option<i64>,
pub(super) version: i64,
oldest: i64,
pub(super) max_seen: i64,
ready: bool,
due: Option<i64>,
pub(super) failure: Option<String>,
pub(super) extent: Extent,
pub(super) head: Option<Vec<u8>>,
}
const STATE: &str = "select s.sealed_before, s.version, s.max_seen, s.ready, s.due, s.failed_at, s.failure,
s.head_count, s.head_start, s.head_end, h.body, s.oldest
from series_state s left join heads h on h.series_id = s.series_id where s.series_id = ?1";
macro_rules! save_state {
($set:literal) => {
concat!(
"update series_state set max_seen = ?2, version = version + 1, head_count = ?3, head_start = ?4,",
" head_end = ?5",
$set,
" where series_id = ?1"
)
};
}
const SAVE_STATE: &str = save_state!("");
const SAVE_STATE_READY: &str = save_state!(", ready = ?6");
const SAVE_STATE_DUE: &str = save_state!(", due = ?6");
const SAVE_STATE_BOTH: &str = save_state!(", ready = ?6, due = ?7");
const SAVING: &str = "write a series' state";
const SET_OLDEST: &str = "update series_state set oldest = ?2 where series_id = ?1";
pub(super) const SET_NEWEST: &str = "update names set newest = ?2 where id = ?1 and (newest is null or newest < ?2)";
const SAVE_HEAD: &str =
"insert into heads (series_id, body) values (?1, ?2) on conflict (series_id) do update set body = excluded.body";
impl State {
pub(super) fn read(connection: &Connection, id: i64) -> Result<State> {
let state = connection.prepare_cached(STATE).and_then(|mut select| {
select
.query_row(params![id], |row| {
let failed: Option<i64> = row.get(5)?;
let failure: Option<String> = row.get(6)?;
let count: i64 = row.get(7)?;
let (start, end): (Option<i64>, Option<i64>) = (row.get(8)?, row.get(9)?);
Ok(State {
sealed_before: row.get(0)?,
version: row.get(1)?,
oldest: row.get(11)?,
max_seen: row.get(2)?,
ready: row.get(3)?,
due: row.get(4)?,
failure: failed.map(|_| failure.unwrap_or_default()),
extent: Extent {
count: usize::try_from(count).unwrap_or(usize::MAX),
start: start.unwrap_or(0),
end: end.unwrap_or(0),
},
head: row.get(10)?,
})
})
.optional()
});
state
.map_err(|error| sql_error("read a series' state", error))?
.ok_or_else(|| Error::corrupt("a series without its state"))
}
fn drop_repeats(&self, tx: &Tx<'_>, zstd: &mut Zstd, id: i64, points: &mut Vec<Point>) -> Result<()> {
match self.sealed_before {
Some(sealed) if self.failure.is_none() => Packed::of(tx, zstd, id, sealed).drop_repeats(points),
_ => Ok(()),
}
}
fn accepts(&self, points: &[Point]) -> Result<()> {
if let Some(failure) = &self.failure {
return Err(Error::new(ErrorKind::Suspended, format!("it stopped taking samples: {failure}")));
}
if let Some(sealed) = self.sealed_before
&& let Some(behind) = points.iter().find(|point| point.at < sealed)
{
let at = rfc3339(behind.at);
return Err(Error::new(ErrorKind::TooOld, format!("sample at {at}, behind what its series has packed")));
}
if self.version == i64::MAX {
return Err(VERSIONS.run_out("its version cannot move once more"));
}
Ok(())
}
}
fn write_series(tx: &Tx<'_>, zstd: &mut Zstd, registering: &mut Registering, batch: &mut Batch) -> Result<bool> {
let (id, _) = registering.resolve(tx, batch)?;
let state = State::read(tx, id)?;
state.drop_repeats(tx, zstd, id, &mut batch.points)?;
if batch.points.is_empty() {
return Ok(false);
}
store(tx, zstd, id, &state, batch)
}
pub(super) fn store(tx: &Tx<'_>, zstd: &mut Zstd, id: i64, state: &State, batch: &Batch) -> Result<bool> {
state.accepts(&batch.points)?;
let Some((bytes, extent)) = next_head(zstd, id, state, &batch.points)? else { return Ok(state.ready) };
let max_seen = state.max_seen.max(batch.points[batch.points.len() - 1].at);
let ready = ready(extent, max_seen);
let first_due = expires(batch.points[0].at, batch.keep);
let due = state.due.map_or(first_due, |due| due.min(first_due));
let (count, start, end) = (extent.count as i64, extent.start, extent.end);
let saved = match (ready != state.ready, Some(due) != state.due) {
(false, false) => execute(tx, SAVE_STATE, params![id, max_seen, count, start, end], SAVING),
(true, false) => execute(tx, SAVE_STATE_READY, params![id, max_seen, count, start, end, ready], SAVING),
(false, true) => execute(tx, SAVE_STATE_DUE, params![id, max_seen, count, start, end, due], SAVING),
(true, true) => execute(tx, SAVE_STATE_BOTH, params![id, max_seen, count, start, end, ready, due], SAVING),
};
saved?;
execute(tx, SAVE_HEAD, params![id, bytes], "write a series' head")?;
if batch.points[0].at < state.oldest {
execute(tx, SET_OLDEST, params![id, batch.points[0].at], "move a series' oldest sample")?;
}
execute(tx, SET_NEWEST, params![batch.name, max_seen], "move a name's newest sample")?;
Ok(ready)
}
fn next_head(zstd: &mut Zstd, id: i64, state: &State, points: &[Point]) -> Result<Option<(Vec<u8>, Extent)>> {
let chunks = match &state.head {
Some(bytes) if state.extent.count > 0 => head::parse(id, state.extent, bytes)?,
None if state.extent.count == 0 => Vec::new(),
_ => return Err(Error::corrupt("a head that is not its state's")),
};
let kept = head::kept_before(&chunks, points[0].at);
let mut rest = Vec::new();
head::decode(zstd, &chunks[kept..], i64::MIN, i64::MAX, &mut rest)?;
let merged = head::merge(&rest, points);
let unchanged = |one: &Point, other: &Point| one.at == other.at && one.value.to_bits() == other.value.to_bits();
if merged.len() == rest.len() && merged.iter().zip(&rest).all(|(one, other)| unchanged(one, other)) {
return Ok(None);
}
let bytes = head::encode(zstd, id, &chunks[..kept], &merged)?;
let kept_count: usize = chunks[..kept].iter().map(|chunk| chunk.head.count).sum();
let start = chunks.first().filter(|_| kept > 0).map_or(merged[0].at, |chunk| chunk.head.start);
Ok(Some((bytes, Extent { count: kept_count + merged.len(), start, end: merged[merged.len() - 1].at })))
}
pub(super) fn ready(extent: Extent, max_seen: i64) -> bool {
extent.count > 1 && unit_end(extent.start, unit_of(extent.count, extent.start, extent.end)) <= max_seen
}
#[cfg(test)]
#[path = "ingest_tests.rs"]
mod tests;