use std::collections::HashMap;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::Duration;
use rusqlite::params;
use super::buffer::Held;
use super::head::Codec;
use super::repair::Damaged;
use super::tail::Recent;
use crate::engine::{Claim, Engine, Host};
use crate::sqlite::{Config, File, Migration, sql_error};
use crate::store::WeakStore;
use crate::{Clock, Durability, Error, Memory, Result, Store, unix_nanos};
const MIGRATIONS: &[Migration] = &[
Migration::of(1, "0001_schema.sql", include_str!("migrations/0001_schema.sql")),
Migration::of(2, "0002_arrivals.sql", include_str!("migrations/0002_arrivals.sql")),
Migration::of(3, "0003_ids.sql", include_str!("migrations/0003_ids.sql")),
];
const FILE: &str = "records.db";
pub(crate) const KEEP: Duration = Duration::from_hours(14 * 24);
pub(crate) const AHEAD: Duration = Duration::from_mins(10);
const MAINTENANCE: Duration = Duration::from_mins(1);
pub(super) const LATENESS: Duration = Duration::from_secs(10);
pub(crate) struct Records {
store: WeakStore,
pub(super) probe: Arc<crate::probe::Probe>,
pub(crate) file: File,
pub(crate) memory: Arc<Memory>,
clock: Arc<dyn Clock>,
streams: Mutex<HashMap<String, Stream>>,
pub(super) codec: Mutex<Codec>,
pub(super) maintaining: Mutex<()>,
pub(super) waiting: Mutex<HashMap<i64, i64>>,
pub(super) recent: Recent,
pub(super) held: Mutex<Held>,
pub(super) damaged: Mutex<Damaged>,
_claim: Claim,
}
#[derive(Clone, Debug)]
pub(crate) struct Stream {
pub(crate) id: i64,
pub(crate) name: Arc<str>,
keep: Option<Duration>,
said: Option<Duration>,
}
impl Stream {
pub(crate) fn keeps(&self) -> Duration {
self.keep.unwrap_or(KEEP)
}
}
impl Engine for Records {
fn close(&self) -> Result<()> {
let flushed = self.flush_held(true);
self.recent.close();
self.file.close().and(flushed)
}
fn snapshot(&self) -> Result<crate::engine::Copying<'_>> {
self.flush_held(false)?;
crate::engine::to_copy(&self.file, FILE, "records")
}
fn applied(&self, file: &str) {
if file != FILE {
return;
}
match (read_streams(&self.file), read_waiting(&self.file)) {
(Ok(streams), Ok(waiting)) => {
*self.streams() = streams;
*self.waiting.lock().unwrap_or_else(PoisonError::into_inner) = waiting;
}
(Err(error), _) | (_, Err(error)) => {
tracing::warn!(
target: "tinystore",
%error,
"records: a copy's streams, read again after its home's commit",
);
}
}
}
}
const SELECT_STREAMS: &str = "select id, name, keep from streams";
const SELECT_WAITING: &str = "select stream, max(last_at) from heads where late = 0 group by stream";
const INSERT_STREAM: &str = "insert into streams (name, keep) values (?1, ?2) returning id";
const SET_KEEP: &str = "update streams set keep = ?2 where id = ?1";
impl Records {
pub(crate) fn of(store: &Store) -> Result<Arc<Records>> {
store.engine(|store| {
let claim = store.claim(FILE)?;
let durability = store.durability().or(Some(Durability::Os));
let config = Config { page_size: 1024, incremental_vacuum: true, ..Config::committing(durability) };
let file = store.open_file(claim.name(), config)?;
file.migrate("records", MIGRATIONS)?;
let records = Arc::new(Records {
store: store.downgrade(),
probe: Arc::clone(store.probe()),
streams: Mutex::new(read_streams(&file)?),
waiting: Mutex::new(read_waiting(&file)?),
file,
memory: Arc::clone(store.memory()),
clock: store.clock(),
codec: Mutex::default(),
maintaining: Mutex::default(),
recent: Recent::default(),
held: Mutex::default(),
damaged: Mutex::default(),
_claim: claim,
});
if records.file.is_copy() {
return Ok(records);
}
let weak = Arc::downgrade(&records);
store.every("records: maintenance", MAINTENANCE, move || {
weak.upgrade().map_or(Ok(()), |records| {
records.file.sweep();
records.maintain().map(drop)
})
})?;
Ok(records)
})
}
pub(crate) fn now(&self) -> i64 {
unix_nanos(self.clock.now())
}
pub(super) fn clock(&self) -> Arc<dyn Clock> {
Arc::clone(&self.clock)
}
pub(super) fn store(&self) -> Option<Store> {
self.store.upgrade()
}
fn streams(&self) -> MutexGuard<'_, HashMap<String, Stream>> {
self.streams.lock().unwrap_or_else(PoisonError::into_inner)
}
pub(crate) fn every_stream(&self) -> Vec<Stream> {
self.streams().values().cloned().collect()
}
pub(crate) fn stream(&self, name: &str) -> Option<Stream> {
self.streams().get(name).cloned()
}
pub(crate) fn open_stream(&self, name: &str, keep: Option<Duration>) -> Result<Stream> {
check_name(name)?;
if keep.is_some_and(|keep| keep.as_millis() == 0) {
return Err(Error::invalid("a stream keeps its events for more than no time"));
}
let mut streams = self.streams();
let Some(stream) = streams.get_mut(name) else {
let (named, kept) = (name.to_owned(), keep.map(crate::clock::millis));
let id = self.file.write(name.len(), move |tx| {
let made = tx.prepare_cached(INSERT_STREAM);
let id = made.and_then(|mut insert| insert.query_row(params![named, kept], |row| row.get(0)));
id.map_err(|error| sql_error("write a stream", error))
})?;
let stream = Stream { id, name: Arc::from(name), keep, said: keep };
streams.insert(name.to_owned(), stream.clone());
return Ok(stream);
};
let Some(keep) = keep else { return Ok(stream.clone()) };
if let Some(said) = stream.said.filter(|said| *said != keep) {
let (said, keep) = (crate::text::span(said), crate::text::span(keep));
return Err(Error::invalid(format!("keep {keep}, where the stream is open with keep {said}")));
}
if stream.keep != Some(keep) {
let id = stream.id;
self.file.write(8, move |tx| {
execute(tx, SET_KEEP, params![id, crate::clock::millis(keep)], "write a stream's keep")
})?;
}
(stream.keep, stream.said) = (Some(keep), Some(keep));
Ok(stream.clone())
}
}
fn read_streams(file: &File) -> Result<HashMap<String, Stream>> {
file.read(|connection| {
let mut select = connection.prepare(SELECT_STREAMS).map_err(|error| sql_error("read the streams", error))?;
let streams = select.query_map([], |row| {
let (name, keep): (String, Option<i64>) = (row.get(1)?, row.get(2)?);
let keep = keep.map(|millis| Duration::from_millis(millis.max(0) as u64));
Ok((name.clone(), Stream { id: row.get(0)?, name: Arc::from(name), keep, said: None }))
});
let streams = streams.and_then(Iterator::collect);
streams.map_err(|error| sql_error("read the streams", error))
})
}
fn read_waiting(file: &File) -> Result<HashMap<i64, i64>> {
let failed = |error| sql_error("read what the heads hold", error);
file.read(|connection| {
let mut select = connection.prepare(SELECT_WAITING).map_err(failed)?;
let waiting = select.query_map([], |row| Ok((row.get(0)?, row.get(1)?)));
waiting.and_then(Iterator::collect).map_err(failed)
})
}
pub(super) use crate::sqlite::execute_cached as execute;
pub(super) fn nanos(span: Duration) -> i64 {
i64::try_from(span.as_nanos()).unwrap_or(i64::MAX)
}
fn check_name(name: &str) -> Result<()> {
crate::text::check_name("a stream's", name)
}
#[cfg(test)]
#[path = "engine_tests.rs"]
mod tests;