use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;
use crate::Result;
pub use crate::schedule::Wake;
#[cfg(any(feature = "kv", feature = "jobs", feature = "sql"))]
mod shared;
#[cfg(any(feature = "kv", feature = "jobs"))]
pub(crate) use shared::Home;
#[cfg(any(feature = "sql", feature = "wire"))]
pub(crate) use shared::SharedFile;
#[cfg(all(feature = "sql", feature = "jobs"))]
pub(crate) use shared::{LentWrite, Wrote};
pub trait Engine: Send + Sync + 'static {
fn stop(&self) {}
fn close(&self) -> Result<()>;
fn clock_moved(&self) {}
fn applied(&self, file: &str) {
let _ = file;
}
fn snapshot(&self) -> Result<Copying<'_>> {
Ok(Copying::default())
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Copied {
pub name: String,
pub engine: &'static str,
}
#[derive(Default)]
pub struct Copying<'a> {
pub(crate) files: Vec<(Copied, crate::sqlite::Source)>,
pub(crate) at_the_moment: Option<AtTheMoment<'a>>,
}
impl fmt::Debug for Copying<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let files: Vec<&str> = self.files.iter().map(|(copied, _)| copied.name.as_str()).collect();
let at_the_moment = self.at_the_moment.is_some();
f.debug_struct("Copying").field("files", &files).field("at_the_moment", &at_the_moment).finish()
}
}
pub(crate) type AtTheMoment<'a> = Box<dyn FnOnce() -> Then<'a> + 'a>;
pub(crate) type Then<'a> = Box<dyn FnOnce(&Path) -> Result<Vec<Copied>> + 'a>;
#[cfg_attr(
not(any(
feature = "kv",
feature = "jobs",
feature = "sql",
feature = "blobs",
feature = "records",
feature = "metrics",
feature = "search"
)),
expect(dead_code, reason = "every engine copies its files with it, and a store of none has none")
)]
pub(crate) fn to_copy<'a>(file: &crate::sqlite::File, name: &str, engine: &'static str) -> Result<Copying<'a>> {
let copied = Copied { name: name.to_owned(), engine };
Ok(Copying { files: vec![(copied, file.source()?)], at_the_moment: None })
}
#[cfg(any(feature = "jobs", feature = "blobs"))]
pub(crate) const BATCH: usize = 10_000;
#[cfg(any(feature = "jobs", feature = "blobs"))]
pub(crate) const BATCHES: usize = 10;
#[cfg(any(feature = "jobs", feature = "blobs"))]
pub(crate) fn in_batches(mut batch: impl FnMut() -> Result<usize>) -> Result<usize> {
let mut total = 0;
for _ in 0..BATCHES {
let removed = batch()?;
total += removed;
if removed < BATCH {
break;
}
}
Ok(total)
}
#[cfg(any(feature = "kv", feature = "sql", feature = "replication"))]
pub(crate) const DATABASES: &str = "sql";
#[cfg(any(feature = "sql", feature = "replication"))]
pub(crate) fn database_file(name: &str) -> String {
format!("{DATABASES}/{name}.db")
}
pub trait Host {
fn engine<E: Engine>(&self, open: impl FnOnce(&crate::Store) -> Result<Arc<E>>) -> Result<Arc<E>>;
fn attach(&self, engine: Arc<dyn Engine>) -> Result<()>;
fn every(&self, name: &str, period: Duration, work: impl FnMut() -> Result<()> + Send + 'static) -> Result<Wake>;
fn claim(&self, name: &str) -> Result<Claim>;
}
type Release = Box<dyn FnOnce(&str) + Send + Sync>;
pub struct Claim {
name: String,
path: PathBuf,
release: Option<Release>,
}
impl Claim {
pub(crate) fn new(name: &str, path: PathBuf, release: Release) -> Self {
Self { name: name.to_owned(), path, release: Some(release) }
}
pub fn name(&self) -> &str {
&self.name
}
pub fn path(&self) -> &Path {
&self.path
}
}
impl Drop for Claim {
fn drop(&mut self) {
if let Some(release) = self.release.take() {
release(&self.name);
}
}
}
impl fmt::Debug for Claim {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Claim({})", self.path.display())
}
}
#[cfg(any(feature = "kv", feature = "jobs"))]
pub(crate) fn migrate_in(
store: &crate::Store,
file: &crate::sqlite::File,
history: &str,
migrations: &[crate::sqlite::Migration],
lent_by: Option<&str>,
) -> Result<()> {
let migrated = file.migrate(history, migrations);
#[cfg(feature = "replication")]
if let Err(error) = &migrated
&& error.kind() == crate::ErrorKind::Unavailable
&& file.is_copy()
&& let Some(database) = lent_by.and_then(crate::replication::database_of)
&& let Some(tag) = crate::replication::tag_of(history)
{
crate::replication::make_in(store, &crate::replication::database_file(database), tag)?;
return file.migrate(history, migrations);
}
let _ = (store, lent_by);
migrated
}