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;
pub trait Engine: Send + Sync + 'static {
fn close(&self) -> Result<()>;
fn clock_moved(&self) {}
fn applied(&self, file: &str) {
let _ = file;
}
fn snapshot(&self, into: &Path) -> Result<Vec<Copied>> {
let _ = into;
Ok(Vec::new())
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Copied {
pub name: String,
pub engine: &'static str,
}
#[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 = "sql", feature = "replication"))]
pub(crate) fn database_file(name: &str) -> String {
format!("sql/{name}.db")
}
#[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 copy_file(file: &crate::sqlite::File, name: &str, engine: &'static str, into: &Path) -> Result<Copied> {
let target = into.join(name);
if let Some(parent) = target.parent() {
std::fs::create_dir_all(parent).map_err(|error| crate::Error::io(format!("snapshot {name}"), error))?;
}
file.copy_into(&target).map_err(|error| error.within(format!("snapshot {name}")))?;
Ok(Copied { name: name.to_owned(), engine })
}
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
}