use std::path::Path;
use super::copy::{self, Position, io_error};
use super::entry::Point;
use super::{DIR, node};
use crate::{Error, ErrorKind, Result};
pub(crate) const PROMOTED: &str = "promoted";
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Promoted {
pub file: String,
pub sequence: u64,
pub epoch: u64,
}
pub fn promote(dir: &Path, files: &[String]) -> Result<Vec<Promoted>> {
let what = || format!("promote {}", dir.display());
let _lock = crate::store::take_lock(dir).map_err(|error| error.within(what()))?;
let logs = dir.join(DIR);
let names = if files.is_empty() { node::files_logged_in(&logs)? } else { files.to_vec() };
let mut promoting = Vec::new();
for name in names {
let log = logs.join(&name);
if !copy::is_copy(&log) {
if files.is_empty() {
continue;
}
return Err(Error::invalid(format!("{name} is no copy this node holds")).within(what()));
}
if !copy::is_ready(&log, &dir.join(&name)) {
return Err(Error::new(
ErrorKind::Unavailable,
format!("{name}: its copy is not whole yet, and a copy becomes a home only whole"),
)
.within(what()));
}
promoting.push((name, log));
}
promoting
.into_iter()
.map(|(name, log)| promote_one(name.clone(), &dir.join(&name), &log, 0).map_err(|error| error.within(what())))
.collect()
}
pub(crate) fn promote_one(file: String, path: &Path, log: &Path, at_least: u64) -> Result<Promoted> {
let point = match promoted_at(log)? {
Some(point) => point,
None => promoted_point(&file, path, log, at_least)?,
};
if point.check == [0; 16] {
super::log::Log::clear(log)?;
}
crate::sqlite::checkpoint_away(path)?;
for gone in [copy::MARK, Position::FILE, super::node::DIRECT] {
copy::remove_if_there(&log.join(gone))?;
}
crate::durable::sync_directory(log).map_err(|error| io_error(log, error))?;
Ok(Promoted { file, sequence: point.sequence, epoch: point.epoch })
}
fn promoted_point(file: &str, path: &Path, log: &Path, at_least: u64) -> Result<Point> {
let mut position = Position::read(log.join(Position::FILE))?;
let unnamed = position.settle(path, log)?.len() as u64;
let applied = position.point();
drop(position);
let mut point = Point { epoch: (applied.epoch + 1).max(at_least), ..applied };
if unnamed > 0 {
point = Point { sequence: point.sequence + unnamed, check: [0; 16], ..point };
tracing::warn!(
target: "tinystore",
file,
unnamed,
"a copy promoted holds commits no entry it keeps names: its log begins again, and each copy of it takes a \
snapshot"
);
}
Position::read(log.join(PROMOTED))?.keep_durably(point)?;
Ok(point)
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Demoted {
pub file: String,
pub last: Option<(u64, u64)>,
}
pub fn demote(dir: &Path, files: &[String]) -> Result<Vec<Demoted>> {
let what = || format!("demote {}", dir.display());
let _lock = crate::store::take_lock(dir).map_err(|error| error.within(what()))?;
let logs = dir.join(DIR);
let names = if files.is_empty() {
node::files_logged_in(&logs)?.into_iter().filter(|name| !super::NODE_LOCAL.contains(&name.as_str())).collect()
} else {
files.to_vec()
};
let mut demoting = Vec::new();
for name in names {
let log = logs.join(&name);
if copy::is_copy(&log) {
if files.is_empty() {
continue;
}
return Err(Error::invalid(format!("{name} is a copy already")).within(what()));
}
if !log.exists() {
return Err(Error::invalid(format!("{name} keeps no log on this node")).within(what()));
}
demoting.push((name, log));
}
demoting.into_iter().map(|(name, log)| demote_one(name, &log).map_err(|error| error.within(what()))).collect()
}
fn demote_one(file: String, log: &Path) -> Result<Demoted> {
let last = super::log::Log::last_in(log)?.map(|point| (point.sequence, point.epoch));
tracing::warn!(
target: "tinystore",
file = %file,
last = ?last,
"a file becomes a copy again: the commits its new home never had are lost"
);
super::log::Log::clear(log)?;
forget_promotion(log)?;
copy::mark(log)?;
Ok(Demoted { file, last })
}
pub(crate) fn forget_promotion(log: &Path) -> Result<()> {
copy::remove_if_there(&log.join(PROMOTED))
}
pub(crate) fn promoted_at(dir: &Path) -> Result<Option<Point>> {
Position::read_point(&dir.join(PROMOTED))
}