use rusqlite::{Connection, OptionalExtension, params};
use super::aggregate::{Op, Shape};
use super::budget::Budget;
use super::clock::{self, Times};
use super::codec::Point;
use super::directory::{Block, Group, Row};
use super::engine::Engine;
use super::head::{self, Chunk, Extent};
use super::matching::{self, Found};
use super::names::{KEEP, millis};
use super::query::Asked;
use super::timer;
use super::values;
use crate::compress::frame::Zstd;
use crate::sqlite::sql_error;
use crate::{Error, ErrorKind, Result};
mod chosen;
mod paging;
mod sampled;
pub(super) use paging::{PageTaken, TakenGroup, Wide};
const KEPT_CLOCKS: usize = 64;
#[derive(Clone, Copy, Debug)]
pub(super) enum Want<'a> {
Samples,
Buckets(&'a Shape),
Newest,
}
#[derive(Clone, Copy, Debug)]
pub(super) struct Window {
pub(super) from: i64,
pub(super) to: i64,
pub(super) cutoff: i64,
}
#[derive(Debug)]
pub(super) struct Taken {
pub(super) found: Found,
pub(super) window: Window,
pub(super) trimmed: bool,
pub(super) blocks: Vec<Part>,
pub(super) head: Option<TakenHead>,
pub(super) until: i64,
}
#[derive(Debug)]
pub(super) struct Part {
pub(super) block: Block,
pub(super) whole: bool,
}
#[derive(Debug)]
pub(super) struct TakenHead {
extent: Extent,
bytes: Vec<u8>,
from: i64,
}
const STATE: &str = "select s.head_count, s.head_start, s.head_end,
s.trimmed = 1 or (s.due is not null and s.due <= ?5), length(h.body),
case when s.head_end >= ?2 and s.head_start < ?3 and length(h.body) <= ?4 then h.body end
from series_state s left join heads h on h.series_id = s.series_id where s.series_id = ?1";
const GROUPS: &str = "select start_ts, end_ts, clock, length(directory),
case when length(directory) <= ?5 then directory end
from groups where series_id = ?1
and start_ts >= coalesce((select start_ts from groups where series_id = ?1 and start_ts <= ?2
order by start_ts desc limit 1), ?2)
and start_ts < ?3 and end_ts >= ?2 order by start_ts";
const GROUPS_AND_BEFORE: &str = "select start_ts, end_ts, clock, length(directory),
case when length(directory) <= ?5 then directory end
from groups where series_id = ?1
and start_ts >= coalesce((select start_ts from groups where series_id = ?1 and start_ts < ?2
order by start_ts desc limit 1), ?2)
and start_ts < ?3 and end_ts >= ?4 order by start_ts";
const NEWEST_GROUP: &str = "select start_ts, end_ts, clock, length(directory),
case when length(directory) <= ?5 then directory end
from groups where id = (select id from groups where series_id = ?1 and start_ts < ?3
order by start_ts desc limit 1)
and end_ts >= ?2";
const PAYLOADS: &str = "select id, body from payloads where id in (select value from json_each(?1)) order by id";
const PAYLOADS_AT_ONCE: usize = 1024;
const HEAD: &str = "select body from heads where series_id = ?1 and length(body) <= ?2";
impl Engine {
pub(super) fn take(&self, asked: &Asked, want: Want<'_>, budget: &mut Budget) -> Result<Vec<Taken>> {
self.snapshot(asked, want, budget, |reading, asked| {
let found = matching::find(reading.connection, asked, reading.budget)?;
found.into_iter().map(|series| reading.series(self, series, asked, want)).collect()
})
}
fn snapshot<T: Holds>(
&self,
asked: &Asked,
want: Want<'_>,
budget: &mut Budget,
read: impl FnOnce(&mut Reading<'_, '_>, &Asked) -> Result<T>,
) -> Result<T> {
let mut zstd = self.codecs.take();
let mut met = None;
let taken = self.file.read(|connection| {
let read_as = timer::read_as(connection, asked, want)?;
let asked = read_as.as_ref().unwrap_or(asked);
let mut reading = Reading { connection, zstd: &mut zstd, budget, clocks: Vec::new(), met: &mut met };
let mut taken = read(&mut reading, asked)?;
reading.bodies(taken.taken())?;
Ok(taken)
});
self.codecs.give_back(zstd);
if let Some((id, failure)) = met {
self.suspend(id, &failure).ok();
}
taken
}
}
pub(super) trait Holds {
fn taken(&mut self) -> Vec<&mut Taken>;
}
impl Holds for Vec<Taken> {
fn taken(&mut self) -> Vec<&mut Taken> {
self.iter_mut().collect()
}
}
struct Reading<'r, 'c> {
connection: &'c Connection,
zstd: &'r mut Zstd,
budget: &'r mut Budget,
clocks: Vec<(i64, Vec<Times>)>,
met: &'r mut Option<(i64, String)>,
}
struct State {
extent: Extent,
trimmed: bool,
head_len: usize,
head: Option<Vec<u8>>,
}
impl Reading<'_, '_> {
fn series(&mut self, engine: &Engine, found: Found, asked: &Asked, want: Want<'_>) -> Result<Taken> {
let mut taken = Taken::of(engine, found, asked, i64::MIN);
match self.fill(&mut taken, asked.now, want) {
Ok(()) => Ok(taken),
Err(error) => Err(self.met(&taken.found, error)),
}
}
fn met(&mut self, found: &Found, error: Error) -> Error {
if error.kind() == ErrorKind::Corrupt {
*self.met = Some((found.id, error.to_string()));
}
error.within(&found.kept)
}
fn fill(&mut self, taken: &mut Taken, now: i64, want: Want<'_>) -> Result<()> {
let (id, window) = (taken.found.id, taken.window);
let state = self.state(id, window, now, self.budget.bytes_left() as i64)?;
let extent = state.extent;
taken.trimmed = state.trimmed;
if extent.count > 0 && extent.end < window.from {
return Ok(());
}
taken.head = self.head(&taken.found, state, window, want)?;
taken.blocks = match want {
Want::Newest if taken.head.is_some() => Vec::new(),
Want::Newest => self.newest_block(id, window)?,
Want::Samples => self.blocks(id, window, None, false)?,
Want::Buckets(shape) => {
let in_head = extent.count > 0 && extent.start < window.from;
let op = shape.series_op(&taken.found);
let before = Shape::steps(op) && window.from > window.cutoff && !in_head;
self.blocks(id, window, Some((shape, op)), before)?
}
};
Ok(())
}
fn state(&mut self, id: i64, window: Window, now: i64, room: i64) -> Result<State> {
let row = self.connection.prepare_cached(STATE).and_then(|mut select| {
let asked = params![id, window.from, window.to, room, now];
let read = select.query_row(asked, |row| {
let extent = (row.get::<_, i64>(0)?, row.get::<_, Option<i64>>(1)?, row.get::<_, Option<i64>>(2)?);
Ok((extent, row.get::<_, bool>(3)?, row.get::<_, Option<i64>>(4)?, row.get::<_, Option<Vec<u8>>>(5)?))
});
read.optional()
});
let row = row.map_err(|error| sql_error("read a series' state", error))?;
let Some(((count, start, end), trimmed, length, head)) = row else {
return Err(Error::corrupt("a series without its state"));
};
let extent =
Extent { count: usize::try_from(count).unwrap_or(0), start: start.unwrap_or(0), end: end.unwrap_or(0) };
let head_len = usize::try_from(length.unwrap_or(0)).unwrap_or(usize::MAX);
Ok(State { extent, trimmed, head_len, head })
}
fn head(&mut self, found: &Found, state: State, window: Window, want: Want<'_>) -> Result<Option<TakenHead>> {
let extent = state.extent;
if extent.count == 0 || extent.end < window.from || extent.start >= window.to {
return Ok(None);
}
self.budget.take_bytes(state.head_len)?;
let bytes = state.head.ok_or_else(|| Error::corrupt("a head its state says it has"))?;
let chunks = head::parse(found.id, extent, &bytes)?;
let from = match want {
Want::Buckets(shape) if Shape::steps(shape.series_op(found)) => from_the_chunk_before(&chunks, window),
Want::Samples | Want::Buckets(_) => window.from,
Want::Newest => from_the_newest_chunk(&chunks, window),
};
self.budget.take_decoded(head::samples_within(&chunks, from, window.to))?;
Ok(Some(TakenHead { extent, bytes, from }))
}
fn blocks(&mut self, id: i64, window: Window, shape: Option<(&Shape, Op)>, before: bool) -> Result<Vec<Part>> {
let rows = self.group_rows(if before { GROUPS_AND_BEFORE } else { GROUPS }, id, window)?;
let mut parts = Vec::new();
let mut carried = None;
for row in rows {
let clock = self.clock(row.clock)?;
let group = Group::decode(self.zstd, &row, clock)?;
for (slot, block) in group.blocks.into_iter().enumerate() {
if group.live >> slot & 1 == 0 || block.times.start >= window.to {
continue;
}
if block.times.end < window.from {
if before && block.times.end >= window.cutoff {
carried = Some(block);
}
continue;
}
let whole = shape.is_some_and(|(shape, op)| shape.holds(op, &block, window));
parts.push(self.part(block, whole)?);
}
}
if let Some(block) = carried {
let decoded = block.summary.last.is_nan() && shape.is_some_and(|(shape, _)| shape.skips_nan());
parts.insert(0, self.part(block, !decoded)?);
}
Ok(parts)
}
fn newest_block(&mut self, id: i64, window: Window) -> Result<Vec<Part>> {
let Some(row) = self.group_rows(NEWEST_GROUP, id, window)?.into_iter().next() else { return Ok(Vec::new()) };
let clock = self.clock(row.clock)?;
let group = Group::decode(self.zstd, &row, clock)?;
let live = group.live;
let mut blocks = group.blocks.into_iter().enumerate().rev();
let newest = blocks.find(|(slot, block)| live >> slot & 1 == 1 && block.times.start < window.to);
match newest {
Some((_, block)) if block.times.end >= window.from => {
let whole = block.times.end < window.to;
Ok(vec![self.part(block, whole)?])
}
_ => Ok(Vec::new()),
}
}
fn part(&mut self, block: Block, whole: bool) -> Result<Part> {
if !whole {
self.budget.take_decoded(block.times.count)?;
if block.external() {
self.budget.take_bytes(block.body_len)?;
}
}
Ok(Part { block, whole })
}
fn bodies(&mut self, mut taken: Vec<&mut Taken>) -> Result<()> {
if self.budget.is_planning() {
return Ok(());
}
let mut wanted: Vec<(i64, usize, usize)> = Vec::new();
for (series, one) in taken.iter().enumerate() {
for (at, part) in one.blocks.iter().enumerate() {
if !part.whole && part.block.external() {
wanted.push((part.block.payload, series, at));
}
}
}
wanted.sort_unstable();
for some in wanted.chunk_by(|a, b| a.0 == b.0).collect::<Vec<_>>().chunks(PAYLOADS_AT_ONCE) {
let ids: Vec<i64> = some.iter().map(|same| same[0].0).collect();
let mut found = self.payloads(&ids)?.into_iter().peekable();
for same in some {
let mut body = found.next_if(|(id, _)| *id == same[0].0).map(|(_, body)| body);
for (left, &(_, series, at)) in same.iter().enumerate().rev() {
let block = &mut taken[series].blocks[at].block;
if body.as_ref().is_none_or(|body| body.len() != block.body_len) {
let lost = Error::corrupt("a block's payload is missing or of another length");
return Err(self.met(&taken[series].found, lost));
}
block.body = if left == 0 { body.take() } else { body.clone() }.unwrap_or_default();
}
}
}
Ok(())
}
fn group_rows(&mut self, sql: &'static str, id: i64, window: Window) -> Result<Vec<Row>> {
let failed = |error| sql_error("read a series' groups", error);
let mut select = self.connection.prepare_cached(sql).map_err(failed)?;
let room = self.budget.bytes_left() as i64;
let mut rows = select.query(params![id, window.from, window.to, window.cutoff, room]).map_err(failed)?;
let mut found = Vec::new();
while let Some(row) = rows.next().map_err(failed)? {
let length: i64 = row.get(3).map_err(failed)?;
self.budget.take_bytes(usize::try_from(length).unwrap_or(usize::MAX))?;
let directory: Option<Vec<u8>> = row.get(4).map_err(failed)?;
let directory = directory.ok_or_else(|| Error::corrupt("a group's directory past its length"))?;
let (start, end) = (row.get(0).map_err(failed)?, row.get(1).map_err(failed)?);
found.push(Row { series: id, start, end, clock: row.get(2).map_err(failed)?, directory });
}
Ok(found)
}
fn clock(&mut self, id: i64) -> Result<Vec<Times>> {
if let Some((_, times)) = self.clocks.iter().find(|(kept, _)| *kept == id) {
return Ok(times.clone());
}
let (length, body) = clock::load(self.connection, id, self.budget.bytes_left())?;
self.keep_clock(id, length, &body.ok_or_else(|| Error::corrupt("a clock past its length"))?)
}
fn keep_clock(&mut self, id: i64, length: usize, body: &[u8]) -> Result<Vec<Times>> {
self.budget.take_bytes(length)?;
let times = clock::decode(body)?;
if self.clocks.len() == KEPT_CLOCKS {
self.clocks.remove(0);
}
self.clocks.push((id, times.clone()));
Ok(times)
}
fn payloads(&self, ids: &[i64]) -> Result<Vec<(i64, Vec<u8>)>> {
let failed = |error| sql_error("read the values of blocks", error);
let ids = serde_json::to_string(ids).map_err(|error| Error::internal("a list of ids").with_source(error))?;
let mut select = self.connection.prepare_cached(PAYLOADS).map_err(failed)?;
let rows = select.query_map(params![ids], |row| Ok((row.get(0)?, row.get(1)?))).map_err(failed)?;
rows.collect::<rusqlite::Result<_>>().map_err(failed)
}
}
fn from_the_chunk_before(chunks: &[Chunk<'_>], window: Window) -> i64 {
let before = chunks.iter().rev().find(|chunk| chunk.head.start < window.from);
let kept = before.filter(|chunk| chunk.head.end >= window.cutoff);
kept.map_or(window.from, |chunk| chunk.head.end.min(window.from))
}
fn from_the_newest_chunk(chunks: &[Chunk<'_>], window: Window) -> i64 {
let newest = chunks.iter().rev().find(|chunk| chunk.overlaps(window.from, window.to));
newest.map_or(window.from, |chunk| chunk.head.start.max(window.from))
}
impl Taken {
fn of(engine: &Engine, found: Found, asked: &Asked, at: i64) -> Taken {
let keep = engine.names.get(found.kept.name()).map_or(KEEP, |name| name.keeps());
let cutoff = asked.now.saturating_sub(millis(keep));
let window = Window { from: asked.from.max(cutoff).max(at), to: asked.to, cutoff };
Taken { found, window, trimmed: false, blocks: Vec::new(), head: None, until: window.to }
}
pub(super) fn decode_head(&self, zstd: &mut Zstd, out: &mut Vec<Point>) -> Result<()> {
let Some(taken) = &self.head else { return Ok(()) };
let chunks = head::parse(self.found.id, taken.extent, &taken.bytes)?;
head::decode(zstd, &chunks, taken.from, self.until, out)
}
pub(super) fn head_chunks(&self) -> Result<Vec<Chunk<'_>>> {
let Some(taken) = &self.head else { return Ok(Vec::new()) };
let chunks = head::parse(self.found.id, taken.extent, &taken.bytes)?;
Ok(chunks.into_iter().filter(|chunk| chunk.overlaps(taken.from, self.window.to)).collect())
}
}
pub(super) fn decode_block(zstd: &mut Zstd, block: &Block, out: &mut Vec<Point>) -> Result<()> {
let base = out.len();
out.resize(base + block.times.count, Point::default());
let run = &mut out[base..];
let decoded =
block.times.fill(run).and_then(|()| values::decode(zstd, block.first, &block.times, &block.body, run));
if decoded.is_err() {
out.truncate(base);
}
decoded.map_err(|error| error.within(format!("a block from {}", block.times.start)))
}