use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::fs::File;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use super::lease::{self, LeaseScan};
use super::manifest::{Manifest, SegmentEntry, StateRef};
use super::record::{self, Kind, RecordError};
use super::{Family, FamilyError, HORIZON_PREFIX, MANIFEST_PREFIX, STATE_PREFIX, numbered_desc};
use crate::checkout::CheckoutState;
use crate::ids::{CheckoutId, Digest128, Generation, SegmentId, WriterIncarnation};
use crate::segment::{SegmentMeta, SegmentWriter};
#[derive(Debug)]
pub struct WriteSession<'f> {
family: &'f Family,
_lock: File,
incarnation: WriterIncarnation,
base: Manifest,
next_generation: Generation,
next_horizon: u64,
next_segment: u64,
next_state: HashMap<CheckoutId, u64>,
open_segments: BTreeSet<SegmentId>,
staged_segments: BTreeMap<SegmentId, u64>,
staged_states: BTreeMap<(CheckoutId, u64), StateRef>,
poisoned: bool,
}
#[derive(Debug)]
pub struct PendingSegment {
id: SegmentId,
writer: SegmentWriter,
}
pub struct BuildScratch<E> {
path: PathBuf,
_lock: Option<File>,
admit: Box<dyn Fn(u64) -> Result<(), E> + Send + Sync>,
}
impl<E> std::fmt::Debug for BuildScratch<E> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BuildScratch")
.field("path", &self.path)
.finish_non_exhaustive()
}
}
impl<E> BuildScratch<E> {
pub fn create_unattached(
parent: &Path,
admit: impl Fn(u64) -> Result<(), E> + Send + Sync + 'static,
) -> Result<Self, FamilyError> {
private_dir_builder()
.recursive(true)
.create(parent)
.map_err(FamilyError::io(parent))?;
Self::create_in(parent, None, admit)
}
fn create_in(
parent: &Path,
lock: Option<File>,
admit: impl Fn(u64) -> Result<(), E> + Send + Sync + 'static,
) -> Result<Self, FamilyError> {
let path = parent.join(lease::fresh_id().to_string());
private_dir_builder()
.create(&path)
.map_err(FamilyError::io(&path))?;
Ok(BuildScratch {
path,
_lock: lock,
admit: Box::new(admit),
})
}
#[must_use]
pub fn path(&self) -> &Path {
&self.path
}
pub fn subdir(self: &Arc<Self>, name: &str) -> std::io::Result<ScratchDir<E>> {
let path = self.path.join(name);
private_dir_builder().create(&path)?;
Ok(ScratchDir {
workspace: Arc::clone(self),
path,
})
}
pub fn subdir_existing(self: &Arc<Self>, name: &str) -> std::io::Result<ScratchDir<E>> {
let path = self.path.join(name);
match private_dir_builder().create(&path) {
Err(error) if error.kind() != std::io::ErrorKind::AlreadyExists => return Err(error),
_ => {}
}
Ok(ScratchDir {
workspace: Arc::clone(self),
path,
})
}
pub fn mark_paused(&self) -> std::io::Result<()> {
std::fs::File::create(self.path.join(crate::family::workspace::PAUSED)).map(drop)
}
pub fn check_space(&self, additional_bytes: u64) -> Result<(), E> {
(self.admit)(additional_bytes)
}
pub fn remove(&self) -> std::io::Result<()> {
match std::fs::remove_dir_all(&self.path) {
Err(error) if error.kind() != std::io::ErrorKind::NotFound => Err(error),
_ => Ok(()),
}
}
}
pub struct ScratchDir<E> {
workspace: Arc<BuildScratch<E>>,
path: PathBuf,
}
impl<E> std::fmt::Debug for ScratchDir<E> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ScratchDir")
.field("path", &self.path)
.finish_non_exhaustive()
}
}
impl<E> ScratchDir<E> {
#[must_use]
pub fn path(&self) -> &Path {
&self.path
}
#[must_use]
pub fn workspace(&self) -> &Arc<BuildScratch<E>> {
&self.workspace
}
}
fn private_dir_builder() -> std::fs::DirBuilder {
let builder = std::fs::DirBuilder::new();
#[cfg(unix)]
let builder = {
use std::os::unix::fs::DirBuilderExt;
let mut builder = builder;
builder.mode(0o700);
builder
};
builder
}
#[cfg(test)]
mod build_scratch_tests {
use super::*;
use crate::ids::FamilyId;
fn checkout(name: &[u8]) -> CheckoutId {
CheckoutId::from_digest(Digest128::of(name))
}
#[test]
fn build_scratch_live_abandoned_and_torn_workspaces() {
let dir = tempfile::tempdir().unwrap();
let family =
Family::open(dir.path(), FamilyId::from_digest(Digest128::of(b"scratch"))).unwrap();
let scratch = family
.try_write()
.unwrap()
.unwrap()
.create_scratch(checkout(b"checkout"), |bytes| {
if bytes <= 100 {
Ok(())
} else {
Err("disk floor")
}
})
.unwrap();
assert!(scratch.check_space(100).is_ok());
assert_eq!(scratch.check_space(101), Err("disk floor"));
let path = scratch.path().to_path_buf();
let checkout_dir = path.parent().unwrap().to_path_buf();
assert_eq!(checkout_dir.parent().unwrap(), family.dir().join("builds"));
assert_eq!(
std::fs::read_dir(&path).unwrap().count(),
0,
"the lock is beside the workspace, not inside it"
);
assert!(checkout_dir.join("checkout.lock").is_file());
std::fs::write(path.join("partial.seg"), b"unfinished").unwrap();
let mut session = family.try_write().unwrap().unwrap();
assert!(
session
.create_scratch(checkout(b"checkout"), |_| Ok::<_, ()>(()))
.is_err()
);
let other = session
.create_scratch(checkout(b"other"), |_| Ok::<_, ()>(()))
.unwrap();
drop(session);
assert!(
other.path().exists(),
"a different checkout can build concurrently"
);
assert!(
path.join("partial.seg").exists(),
"startup preserves a live build"
);
drop(scratch);
assert!(
path.join("partial.seg").exists(),
"dropping a workspace does not delete it"
);
drop(family.try_write().unwrap().unwrap());
assert!(!path.exists(), "startup removes an abandoned build");
assert!(
checkout_dir.join("checkout.lock").is_file(),
"the sweep keeps the lock file"
);
let torn = checkout_dir.join("torn");
std::fs::create_dir(&torn).unwrap();
drop(family.try_write().unwrap().unwrap());
assert!(!torn.exists(), "startup removes a half-made workspace");
}
#[test]
fn build_scratch_survives_an_error_until_removed() {
let dir = tempfile::tempdir().unwrap();
let family =
Family::open(dir.path(), FamilyId::from_digest(Digest128::of(b"drop"))).unwrap();
let mut path = PathBuf::new();
let result = (|| -> Result<(), &str> {
let scratch = family
.try_write()
.unwrap()
.unwrap()
.create_scratch(checkout(b"checkout"), |_| Ok::<_, &str>(()))
.unwrap();
path = scratch.path().to_path_buf();
std::fs::write(path.join("partial.seg"), b"unfinished").unwrap();
Err("cancelled")
})();
assert!(result.is_err());
assert!(
path.join("partial.seg").exists(),
"an error or pause leaves the build's work on disk"
);
let scratch = family
.try_write()
.unwrap()
.unwrap()
.create_scratch(checkout(b"checkout"), |_| Ok::<_, &str>(()))
.unwrap();
assert!(!path.exists(), "the next build of the checkout clears it");
let next = scratch.path().to_path_buf();
scratch.remove().unwrap();
assert!(!next.exists());
scratch.remove().unwrap();
}
#[test]
fn a_workspace_with_an_identity_is_kept_for_its_checkout_to_adopt() {
let dir = tempfile::tempdir().unwrap();
let family =
Family::open(dir.path(), FamilyId::from_digest(Digest128::of(b"adopt"))).unwrap();
let root = dir.path().join("checkout-root");
std::fs::create_dir(&root).unwrap();
let scratch = family
.try_write()
.unwrap()
.unwrap()
.create_scratch(checkout(b"checkout"), |_| Ok::<_, ()>(()))
.unwrap();
let kept = scratch.path().to_path_buf();
crate::family::workspace::write_identity(
&kept,
&crate::family::workspace::WorkspaceIdentity {
root: root.clone(),
payload: b"one".to_vec(),
},
)
.unwrap();
std::fs::write(kept.join("staged"), b"work").unwrap();
scratch.mark_paused().unwrap();
drop(scratch);
drop(family.try_write().unwrap().unwrap());
assert!(kept.join("staged").exists(), "the sweep keeps it");
let claim = family
.try_write()
.unwrap()
.unwrap()
.claim_scratch(checkout(b"checkout"))
.unwrap();
let torn = claim.dir().join("torn");
std::fs::create_dir(&torn).unwrap();
assert_eq!(claim.leftovers().unwrap().len(), 2);
assert!(
family
.try_write()
.unwrap()
.unwrap()
.claim_scratch(checkout(b"checkout"))
.is_err(),
"one claim at a time"
);
let adopted = claim.adopt(&kept, |_| Ok::<_, ()>(())).unwrap();
assert_eq!(adopted.path(), kept);
assert!(!torn.exists(), "adoption deletes the other leftovers");
assert!(!crate::family::workspace::is_paused(&kept));
assert!(kept.join(crate::family::workspace::ADOPTED).exists());
let again = Arc::new(adopted);
let records = again.subdir_existing("records").unwrap();
assert!(again.subdir_existing("records").is_ok());
drop(records);
drop(again);
std::fs::remove_dir(&root).unwrap();
drop(family.try_write().unwrap().unwrap());
assert!(!kept.exists());
}
#[test]
fn disk_reclaim_deletes_other_dead_workspaces_oldest_first_and_paused_last() {
let dir = tempfile::tempdir().unwrap();
let family =
Family::open(dir.path(), FamilyId::from_digest(Digest128::of(b"reclaim"))).unwrap();
let root = dir.path().join("checkout-root");
std::fs::create_dir(&root).unwrap();
let mut made = Vec::new();
for (name, paused) in [
(b"old".as_slice(), false),
(b"paused", true),
(b"new", false),
] {
let scratch = family
.try_write()
.unwrap()
.unwrap()
.create_scratch(checkout(name), |_| Ok::<_, ()>(()))
.unwrap();
crate::family::workspace::write_identity(
scratch.path(),
&crate::family::workspace::WorkspaceIdentity {
root: root.clone(),
payload: Vec::new(),
},
)
.unwrap();
if paused {
scratch.mark_paused().unwrap();
}
made.push(scratch.path().to_path_buf());
std::thread::sleep(std::time::Duration::from_millis(20));
}
let own = family
.try_write()
.unwrap()
.unwrap()
.create_scratch(checkout(b"own"), |_| Ok::<_, ()>(()))
.unwrap();
let mut asked = 0;
let removed = family
.try_write()
.unwrap()
.unwrap()
.reclaim_dead_workspaces(
Some(checkout(b"own")),
|| {
asked += 1;
Ok::<_, ()>(asked <= 1)
},
|| Ok(false),
)
.removed;
assert_eq!(removed, 1);
assert!(!made[0].exists(), "the oldest dead one goes first");
assert!(made[1].exists() && made[2].exists());
let removed = family
.try_write()
.unwrap()
.unwrap()
.reclaim_dead_workspaces(Some(checkout(b"own")), || Ok::<_, ()>(true), || Ok(false))
.removed;
assert_eq!(removed, 1);
assert!(made[1].exists(), "a paused one stays above the floor");
assert!(!made[2].exists());
let removed = family
.try_write()
.unwrap()
.unwrap()
.reclaim_dead_workspaces(Some(checkout(b"own")), || Ok::<_, ()>(true), || Ok(true))
.removed;
assert_eq!(removed, 1);
assert!(!made[1].exists(), "below the floor a paused one goes too");
assert!(
own.path().exists(),
"a live build's workspace is never reclaimed"
);
}
#[test]
fn disk_reclaim_passes_over_a_live_build_and_an_undeletable_workspace() {
let dir = tempfile::tempdir().unwrap();
let family =
Family::open(dir.path(), FamilyId::from_digest(Digest128::of(b"past"))).unwrap();
let mut made = Vec::new();
for name in [b"stuck".as_slice(), b"free"] {
let scratch = family
.try_write()
.unwrap()
.unwrap()
.create_scratch(checkout(name), |_| Ok::<_, ()>(()))
.unwrap();
crate::family::workspace::write_identity(
scratch.path(),
&crate::family::workspace::WorkspaceIdentity {
root: dir.path().to_path_buf(),
payload: Vec::new(),
},
)
.unwrap();
made.push(scratch.path().to_path_buf());
std::thread::sleep(std::time::Duration::from_millis(20));
}
let live = family
.try_write()
.unwrap()
.unwrap()
.create_scratch(checkout(b"live"), |_| Ok::<_, ()>(()))
.unwrap();
UNDELETABLE_FOR_TEST.lock().unwrap().push(made[0].clone());
let removed = reclaim_dead_workspaces(
dir.path(),
None,
|| Ok::<_, ()>(made[1].exists()),
|| Ok(false),
)
.removed;
UNDELETABLE_FOR_TEST
.lock()
.unwrap()
.retain(|stuck| stuck != &made[0]);
assert_eq!(removed, 1);
assert!(made[0].exists(), "the undeletable one stays");
assert!(!made[1].exists(), "the next one is deleted all the same");
let removed =
reclaim_dead_workspaces(dir.path(), None, || Ok::<_, ()>(true), || Ok(true)).removed;
assert_eq!(removed, 1);
assert!(!made[0].exists());
assert!(
live.path().exists(),
"a live build's workspace is never reclaimed"
);
}
#[test]
fn disk_reclaim_reads_a_workspace_again_once_it_holds_the_lock() {
let dir = tempfile::tempdir().unwrap();
let family =
Family::open(dir.path(), FamilyId::from_digest(Digest128::of(b"stale"))).unwrap();
let scratch = family
.try_write()
.unwrap()
.unwrap()
.create_scratch(checkout(b"victim"), |_| Ok::<_, ()>(()))
.unwrap();
crate::family::workspace::write_identity(
scratch.path(),
&crate::family::workspace::WorkspaceIdentity {
root: dir.path().to_path_buf(),
payload: Vec::new(),
},
)
.unwrap();
let victim = scratch.path().to_path_buf();
drop(scratch);
assert!(!crate::family::workspace::is_paused(&victim));
PAUSE_BEFORE_DELETION_FOR_TEST
.lock()
.unwrap()
.push(victim.clone());
let reclaimed =
reclaim_dead_workspaces(dir.path(), None, || Ok::<_, ()>(true), || Ok(false));
PAUSE_BEFORE_DELETION_FOR_TEST
.lock()
.unwrap()
.retain(|path| path != &victim);
assert_eq!(reclaimed.removed, 0);
assert!(victim.exists(), "a workspace paused meanwhile stays");
let reclaimed =
reclaim_dead_workspaces(dir.path(), None, || Ok::<_, ()>(true), || Ok(true));
assert_eq!(reclaimed.removed, 1, "below the floor it goes");
}
#[test]
fn disk_reclaim_stops_when_the_free_space_cannot_be_measured() {
let dir = tempfile::tempdir().unwrap();
let family =
Family::open(dir.path(), FamilyId::from_digest(Digest128::of(b"probe"))).unwrap();
let scratch = family
.try_write()
.unwrap()
.unwrap()
.create_scratch(checkout(b"victim"), |_| Ok::<_, ()>(()))
.unwrap();
crate::family::workspace::write_identity(
scratch.path(),
&crate::family::workspace::WorkspaceIdentity {
root: dir.path().to_path_buf(),
payload: Vec::new(),
},
)
.unwrap();
let victim = scratch.path().to_path_buf();
drop(scratch);
let reclaimed =
reclaim_dead_workspaces(dir.path(), None, || Err("unknown"), || Err("unknown"));
assert_eq!(reclaimed.removed, 0);
assert_eq!(reclaimed.stopped, Some("unknown"));
assert!(victim.exists());
}
#[test]
fn a_workspace_the_sweep_cannot_delete_does_not_block_the_writer() {
let dir = tempfile::tempdir().unwrap();
let family =
Family::open(dir.path(), FamilyId::from_digest(Digest128::of(b"stuck"))).unwrap();
let scratch = family
.try_write()
.unwrap()
.unwrap()
.create_scratch(checkout(b"checkout"), |_| Ok::<_, ()>(()))
.unwrap();
let path = scratch.path().to_path_buf();
drop(scratch);
UNDELETABLE_FOR_TEST.lock().unwrap().push(path.clone());
let session = family.try_write();
assert!(
matches!(session, Ok(Some(_))),
"the writer starts: {session:?}"
);
drop(session);
assert!(path.exists(), "the workspace could not be deleted");
UNDELETABLE_FOR_TEST
.lock()
.unwrap()
.retain(|stuck| stuck != &path);
drop(family.try_write().unwrap().unwrap());
assert!(!path.exists(), "the next writer deletes it");
}
#[test]
fn build_scratch_subdirs_share_one_workspace() {
let dir = tempfile::tempdir().unwrap();
let scratch = Arc::new(
BuildScratch::create_unattached(&dir.path().join("builds"), |bytes| {
if bytes <= 10 {
Ok(())
} else {
Err("disk floor")
}
})
.unwrap(),
);
let root = scratch.path().to_path_buf();
let text = scratch.subdir("text").unwrap();
let graph = scratch.subdir("graph").unwrap();
assert_eq!(text.path(), root.join("text"));
assert_eq!(graph.path(), root.join("graph"));
assert!(
scratch.subdir("text").is_err(),
"two builders never share one folder"
);
assert_eq!(graph.workspace().check_space(11), Err("disk floor"));
std::fs::write(text.path().join("run"), b"partial").unwrap();
drop(text);
drop(graph);
assert!(root.join("text").join("run").exists());
scratch.remove().unwrap();
assert!(!root.exists());
}
}
fn try_checkout_lock(dir: &Path) -> Result<Option<File>, FamilyError> {
let path = dir.join("checkout.lock");
let mut options = std::fs::OpenOptions::new();
options.read(true).write(true).create(true).truncate(false);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let file = options.open(&path).map_err(FamilyError::io(&path))?;
match file.try_lock() {
Ok(()) => Ok(Some(file)),
Err(std::fs::TryLockError::WouldBlock) => Ok(None),
Err(std::fs::TryLockError::Error(error)) => Err(FamilyError::io(&path)(error)),
}
}
fn remove_dead_workspaces(dir: &Path) -> Result<(), FamilyError> {
let now = SystemTime::now();
for workspace in read_dir(dir)? {
if !workspace.is_dir() || crate::family::workspace::worth_keeping(&workspace, now) {
continue;
}
remove_workspace_dir(&workspace)?;
}
Ok(())
}
#[cfg(test)]
static UNDELETABLE_FOR_TEST: std::sync::Mutex<Vec<PathBuf>> = std::sync::Mutex::new(Vec::new());
fn remove_workspace_dir(workspace: &Path) -> Result<(), FamilyError> {
#[cfg(test)]
if UNDELETABLE_FOR_TEST
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.iter()
.any(|path| path == workspace)
{
return Err(FamilyError::io(workspace)(std::io::Error::other(
"a test keeps it",
)));
}
match std::fs::remove_dir_all(workspace) {
Err(error) if error.kind() != std::io::ErrorKind::NotFound => {
Err(FamilyError::io(workspace)(error))
}
_ => Ok(()),
}
}
pub fn reclaim_dead_workspaces<E>(
family_dir: &Path,
keep: Option<CheckoutId>,
mut short: impl FnMut() -> Result<bool, E>,
mut below_floor: impl FnMut() -> Result<bool, E>,
) -> Reclaimed<E> {
let builds = family_dir.join("builds");
let Ok(checkouts) = read_dir(&builds) else {
return Reclaimed {
removed: 0,
stopped: None,
};
};
let keep = keep.map(|checkout| checkout.to_string());
let mut dead = Vec::new();
for checkout in checkouts {
if !checkout.is_dir()
|| (keep.is_some()
&& checkout.file_name().and_then(|name| name.to_str()) == keep.as_deref())
{
continue;
}
let Ok(Some(_listing)) = try_checkout_lock(&checkout) else {
continue;
};
let Ok(workspaces) = read_dir(&checkout) else {
continue;
};
for workspace in workspaces {
if workspace.is_dir() {
let paused = crate::family::workspace::is_paused(&workspace);
dead.push((
paused,
crate::family::workspace::last_used(&workspace),
checkout.clone(),
workspace,
));
}
}
}
dead.sort();
let mut removed = 0;
for (_, _, checkout, workspace) in dead {
#[cfg(test)]
pause_before_deletion_for_test(&workspace);
let Ok(Some(_lock)) = try_checkout_lock(&checkout) else {
continue;
};
if !workspace.is_dir() {
continue;
}
let paused = crate::family::workspace::is_paused(&workspace);
match if paused { below_floor() } else { short() } {
Ok(true) => {}
Ok(false) => continue,
Err(error) => {
return Reclaimed {
removed,
stopped: Some(error),
};
}
}
if remove_workspace_dir(&workspace).is_ok() {
removed += 1;
}
}
Reclaimed {
removed,
stopped: None,
}
}
#[derive(Debug)]
pub struct Reclaimed<E> {
pub removed: usize,
pub stopped: Option<E>,
}
#[cfg(test)]
static PAUSE_BEFORE_DELETION_FOR_TEST: std::sync::Mutex<Vec<PathBuf>> =
std::sync::Mutex::new(Vec::new());
#[cfg(test)]
fn pause_before_deletion_for_test(workspace: &Path) {
if PAUSE_BEFORE_DELETION_FOR_TEST
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.iter()
.any(|path| path == workspace)
{
std::fs::File::create(workspace.join(crate::family::workspace::PAUSED)).unwrap();
}
}
#[derive(Debug)]
pub struct ScratchClaim {
dir: PathBuf,
lock: File,
}
impl ScratchClaim {
#[must_use]
pub fn dir(&self) -> &Path {
&self.dir
}
pub fn leftovers(&self) -> Result<Vec<PathBuf>, FamilyError> {
let mut found = read_dir(&self.dir)?
.into_iter()
.filter(|path| path.is_dir())
.map(|path| (crate::family::workspace::last_used(&path), path))
.collect::<Vec<_>>();
found.sort();
Ok(found.into_iter().map(|(_, path)| path).collect())
}
pub fn remove(&self, workspace: &Path) -> Result<(), FamilyError> {
if workspace.parent() != Some(self.dir.as_path()) {
return Err(FamilyError::Misuse("not a workspace of this checkout"));
}
remove_workspace_dir(workspace)
}
pub fn adopt<E>(
self,
workspace: &Path,
admit: impl Fn(u64) -> Result<(), E> + Send + Sync + 'static,
) -> Result<BuildScratch<E>, FamilyError> {
if workspace.parent() != Some(self.dir.as_path()) || !workspace.is_dir() {
return Err(FamilyError::Misuse("not a workspace of this checkout"));
}
for other in self.leftovers()? {
if other != workspace {
remove_workspace_dir(&other)?;
}
}
crate::family::workspace::mark_adopted(workspace).map_err(FamilyError::io(workspace))?;
let paused = workspace.join(crate::family::workspace::PAUSED);
match std::fs::remove_file(&paused) {
Err(error) if error.kind() != std::io::ErrorKind::NotFound => {
return Err(FamilyError::io(&paused)(error));
}
_ => {}
}
Ok(BuildScratch {
path: workspace.to_path_buf(),
_lock: Some(self.lock),
admit: Box::new(admit),
})
}
pub fn fresh<E>(
self,
admit: impl Fn(u64) -> Result<(), E> + Send + Sync + 'static,
) -> Result<BuildScratch<E>, FamilyError> {
remove_dead_workspaces(&self.dir)?;
BuildScratch::create_in(&self.dir, Some(self.lock), admit)
}
}
fn sweep_build_scratch(builds: &Path) {
if !builds.exists() {
return;
}
let Ok(checkouts) = read_dir(builds) else {
return;
};
for checkout in checkouts {
if !checkout.is_dir() {
continue;
}
if let Ok(Some(_lock)) = try_checkout_lock(&checkout) {
let _ = remove_dead_workspaces(&checkout);
}
}
}
impl PendingSegment {
#[must_use]
pub const fn id(&self) -> SegmentId {
self.id
}
pub fn writer(&mut self) -> &mut SegmentWriter {
&mut self.writer
}
}
#[derive(Clone, Debug, Default)]
pub struct Publication {
pub add_segments: Vec<SegmentId>,
pub remove_segments: Vec<SegmentId>,
pub states: Vec<StateRef>,
pub retire_checkouts: Vec<CheckoutId>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ReclaimReport {
pub outcome: ReclaimOutcome,
pub horizon: Generation,
pub removed_segments: usize,
pub removed_states: usize,
pub removed_manifests: usize,
pub removed_horizons: usize,
pub removed_leases: usize,
pub failed_removals: usize,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ReclaimOutcome {
Complete,
Raced,
UnreadableLeases(usize),
}
impl<'f> WriteSession<'f> {
pub(super) fn start(family: &'f Family, lock: File) -> Result<Self, FamilyError> {
let layout = &family.layout;
let (base, _) = family.newest_manifest()?;
family.check_named_formats(&base)?;
sweep_build_scratch(&layout.dir.join("builds"));
let mut next_segment = 1;
for entry in read_dir(&layout.tmp_dir())? {
if let Some(id) = segment_id_of(&entry) {
next_segment = next_segment.max(id + 1);
}
crate::fs::remove_file(&entry).map_err(FamilyError::io(&entry))?;
}
for entry in read_dir(&layout.segments_dir())? {
if let Some(id) = segment_id_of(&entry) {
next_segment = next_segment.max(id + 1);
}
}
next_segment = next_segment.max(base.next_segment().get());
let manifests = numbered_desc(&layout.dir, MANIFEST_PREFIX)?;
let next_generation = manifests
.first()
.map_or(1, |(number, _)| number + 1)
.max(base.generation().get() + 1);
for (number, path) in &manifests {
if *number > base.generation().get() {
crate::fs::remove_file(path).map_err(FamilyError::io(path))?;
}
}
let next_horizon = numbered_desc(&layout.dir, HORIZON_PREFIX)?
.first()
.map_or(1, |(number, _)| number + 1);
Ok(Self {
family,
_lock: lock,
incarnation: WriterIncarnation::new(u64::from_le_bytes(crate::le::array(
lease::fresh_id().as_bytes(),
0,
))),
base,
next_generation: Generation::new(next_generation),
next_horizon,
next_segment,
next_state: HashMap::new(),
open_segments: BTreeSet::new(),
staged_segments: BTreeMap::new(),
staged_states: BTreeMap::new(),
poisoned: false,
})
}
#[must_use]
pub fn base(&self) -> &Manifest {
&self.base
}
#[must_use]
pub const fn incarnation(&self) -> WriterIncarnation {
self.incarnation
}
pub fn create_segment(&mut self) -> Result<PendingSegment, FamilyError> {
let id = SegmentId::new(self.next_segment);
self.next_segment += 1;
let path = self.family.layout.tmp_segment(id);
crate::fault::point("segment.create").map_err(FamilyError::io(&path))?;
let writer = SegmentWriter::create(
&path,
SegmentMeta {
family: self.family.id,
segment: id,
incarnation: self.incarnation,
created_unix_ms: now_unix_ms(),
},
)?;
self.open_segments.insert(id);
Ok(PendingSegment { id, writer })
}
pub fn create_scratch<E>(
&mut self,
checkout: CheckoutId,
admit: impl Fn(u64) -> Result<(), E> + Send + Sync + 'static,
) -> Result<BuildScratch<E>, FamilyError> {
self.claim_scratch(checkout)?.fresh(admit)
}
pub fn claim_scratch(&mut self, checkout: CheckoutId) -> Result<ScratchClaim, FamilyError> {
let parent = self
.family
.layout
.dir
.join("builds")
.join(checkout.to_string());
private_dir_builder()
.recursive(true)
.create(&parent)
.map_err(FamilyError::io(&parent))?;
let Some(lock) = try_checkout_lock(&parent)? else {
return Err(FamilyError::CheckoutBusy(
"another process is building this checkout",
));
};
Ok(ScratchClaim { dir: parent, lock })
}
pub fn reclaim_dead_workspaces<E>(
&mut self,
keep: Option<CheckoutId>,
short: impl FnMut() -> Result<bool, E>,
below_floor: impl FnMut() -> Result<bool, E>,
) -> Reclaimed<E> {
reclaim_dead_workspaces(&self.family.layout.dir, keep, short, below_floor)
}
pub fn finish_segment(&mut self, pending: PendingSegment) -> Result<SegmentId, FamilyError> {
if !self.open_segments.remove(&pending.id) {
return Err(FamilyError::Misuse(
"the segment was not created by this session",
));
}
crate::fault::point("segment.finish")
.map_err(FamilyError::io(&self.family.layout.tmp_segment(pending.id)))?;
let summary = pending.writer.finish()?;
self.staged_segments.insert(pending.id, summary.len);
Ok(pending.id)
}
pub fn write_state(
&mut self,
checkout: CheckoutId,
payload: &[u8],
) -> Result<StateRef, FamilyError> {
let layout = &self.family.layout;
let dir = layout.checkout_dir(checkout);
let number = match self.next_state.get(&checkout) {
Some(number) => *number,
None => {
if !dir.is_dir() {
std::fs::create_dir_all(&dir).map_err(FamilyError::io(&dir))?;
if let Some(parent) = dir.parent() {
crate::fs::sync_dir(parent).map_err(FamilyError::io(parent))?;
}
}
numbered_desc(&dir, STATE_PREFIX)?
.first()
.map_or(1, |(number, _)| number + 1)
}
};
self.next_state.insert(checkout, number + 1);
let path = layout.state(checkout, number);
record::write(&path, Kind::State, self.family.id, number, payload)
.map_err(FamilyError::io(&path))?;
let state = StateRef {
checkout,
number,
len: payload.len() as u64,
digest: Digest128::of(payload),
};
self.staged_states.insert((checkout, number), state);
Ok(state)
}
pub fn write_checkout_state(
&mut self,
checkout: CheckoutId,
state: &CheckoutState,
) -> Result<StateRef, FamilyError> {
self.write_state(checkout, &state.encode())
}
pub fn publish(&mut self, change: &Publication) -> Result<Generation, FamilyError> {
if self.poisoned {
return Err(FamilyError::Poisoned);
}
let mut segments = self
.base
.segments()
.iter()
.map(|entry| (entry.id, entry.len))
.collect::<BTreeMap<_, _>>();
for id in &change.remove_segments {
if segments.remove(id).is_none() {
return Err(FamilyError::Misuse(
"the publication removes a segment the current generation does not hold",
));
}
}
for id in &change.add_segments {
let Some(len) = self.staged_segments.get(id) else {
return Err(FamilyError::Misuse(
"the publication adds a segment this session did not finish",
));
};
segments.insert(*id, *len);
}
let mut checkouts = self
.base
.checkouts()
.iter()
.map(|state| (state.checkout, *state))
.collect::<BTreeMap<_, _>>();
for checkout in &change.retire_checkouts {
checkouts.remove(checkout);
}
for state in &change.states {
if self.staged_states.get(&(state.checkout, state.number)) != Some(state) {
return Err(FamilyError::Misuse(
"the publication names a state this session did not write",
));
}
if change.retire_checkouts.contains(&state.checkout) {
return Err(FamilyError::Misuse(
"the publication both updates and retires a checkout",
));
}
checkouts.insert(state.checkout, *state);
}
self.poisoned = true;
let layout = &self.family.layout;
for id in &change.add_segments {
let from = layout.tmp_segment(*id);
let to = layout.segment(*id);
crate::fs::rename_new_durable(&from, &to).map_err(FamilyError::io(&to))?;
self.staged_segments.remove(id);
}
let generation = self.next_generation;
let manifest = Manifest::new(
generation,
now_unix_ms(),
SegmentId::new(self.next_segment),
segments
.into_iter()
.map(|(id, len)| SegmentEntry { id, len })
.collect(),
checkouts.into_values().collect(),
);
let path = layout.manifest(generation);
record::write(
&path,
Kind::Manifest,
self.family.id,
generation.get(),
&manifest.encode(),
)
.map_err(FamilyError::io(&path))?;
for state in &change.states {
self.staged_states.remove(&(state.checkout, state.number));
}
self.base = manifest;
self.next_generation = generation.next();
self.poisoned = false;
Ok(generation)
}
pub fn reclaim(&mut self) -> Result<ReclaimReport, FamilyError> {
let layout = self.family.layout.clone();
let family = self.family.id;
let mut report = ReclaimReport {
outcome: ReclaimOutcome::Complete,
horizon: Generation::EMPTY,
removed_segments: 0,
removed_states: 0,
removed_manifests: 0,
removed_horizons: 0,
removed_leases: 0,
failed_removals: 0,
};
let mut scan = lease::scan(&layout, family)?;
remove_dead(&mut scan, &mut report);
let current = self.family.newest_horizon()?;
report.horizon = current.map_or(Generation::EMPTY, |(_, horizon)| horizon);
if scan.unreadable > 0 {
report.outcome = ReclaimOutcome::UnreadableLeases(scan.unreadable);
return Ok(report);
}
let newest = self.base.generation();
let horizon = scan
.lowest_live()
.map_or(newest, |lowest| lowest.min(newest));
if current.is_none_or(|(_, written)| written != horizon) {
if current.is_some_and(|(_, written)| written > horizon) {
report.outcome = ReclaimOutcome::Raced;
return Ok(report);
}
let path = layout.horizon(self.next_horizon);
record::write(
&path,
Kind::Horizon,
family,
self.next_horizon,
&horizon.get().to_le_bytes(),
)
.map_err(FamilyError::io(&path))?;
self.next_horizon += 1;
}
report.horizon = horizon;
let mut rescan = lease::scan(&layout, family)?;
if rescan.unreadable > 0 {
report.outcome = ReclaimOutcome::UnreadableLeases(rescan.unreadable);
return Ok(report);
}
if rescan.lowest_live().is_some_and(|lowest| lowest < horizon) {
report.outcome = ReclaimOutcome::Raced;
return Ok(report);
}
let mut keep_segments = BTreeSet::new();
let mut keep_states = BTreeSet::new();
let mut manifests_to_remove = Vec::new();
for (number, path) in numbered_desc(&layout.dir, MANIFEST_PREFIX)? {
let generation = Generation::new(number);
if generation > newest {
continue;
}
if generation < horizon {
manifests_to_remove.push(path);
continue;
}
let manifest = match record::read(&path, Kind::Manifest, family, number)
.and_then(|payload| Manifest::decode(generation, &payload))
{
Ok(manifest) => manifest,
Err(RecordError::Invalid(_)) => {
manifests_to_remove.push(path);
continue;
}
Err(error) => return Err(FamilyError::record(&path, error)),
};
keep_segments.extend(manifest.segments().iter().map(|entry| entry.id));
keep_states.extend(
manifest
.checkouts()
.iter()
.map(|state| (state.checkout, state.number)),
);
}
keep_states.extend(self.staged_states.keys().copied());
for path in read_dir(&layout.segments_dir())? {
let keep =
segment_id_of(&path).is_some_and(|id| keep_segments.contains(&SegmentId::new(id)));
if !keep && remove(&path, &mut report) {
report.removed_segments += 1;
}
}
for checkout_dir in read_dir(&layout.checkouts_dir())? {
let Some(checkout) = checkout_id_of(&checkout_dir) else {
continue;
};
let mut left = 0;
for (number, path) in numbered_desc(&checkout_dir, STATE_PREFIX)? {
if keep_states.contains(&(checkout, number)) {
left += 1;
} else if remove(&path, &mut report) {
report.removed_states += 1;
}
}
if left == 0 && !self.next_state.contains_key(&checkout) {
let _ = std::fs::remove_dir(&checkout_dir);
}
}
for path in manifests_to_remove {
if remove(&path, &mut report) {
report.removed_manifests += 1;
}
}
let newest_horizon = self.family.newest_horizon()?.map(|(number, _)| number);
for (number, path) in numbered_desc(&layout.dir, HORIZON_PREFIX)? {
if Some(number) != newest_horizon && remove(&path, &mut report) {
report.removed_horizons += 1;
}
}
remove_dead(&mut rescan, &mut report);
Ok(report)
}
}
fn remove(path: &std::path::Path, report: &mut ReclaimReport) -> bool {
if crate::fs::remove_file(path).is_ok() {
true
} else {
report.failed_removals += 1;
false
}
}
fn remove_dead(scan: &mut LeaseScan, report: &mut ReclaimReport) {
for path in scan
.dead_leases
.drain(..)
.chain(scan.abandoned_incoming.drain(..))
{
if remove(&path, report) {
report.removed_leases += 1;
}
}
for owner in scan.dead_owners.drain(..) {
if remove(&owner.path, report) {
report.removed_leases += 1;
}
}
}
fn read_dir(dir: &std::path::Path) -> Result<Vec<PathBuf>, FamilyError> {
let mut paths = Vec::new();
for entry in std::fs::read_dir(dir).map_err(FamilyError::io(dir))? {
paths.push(entry.map_err(FamilyError::io(dir))?.path());
}
paths.sort();
Ok(paths)
}
fn segment_id_of(path: &std::path::Path) -> Option<u64> {
path.file_name()?
.to_str()?
.strip_suffix(".seg")
.and_then(super::canonical_number)
}
fn checkout_id_of(path: &std::path::Path) -> Option<CheckoutId> {
let name = path.file_name()?.to_str()?;
if name.len() != 2 * Digest128::LEN {
return None;
}
let mut bytes = [0; Digest128::LEN];
for (index, byte) in bytes.iter_mut().enumerate() {
*byte = u8::from_str_radix(name.get(2 * index..2 * index + 2)?, 16).ok()?;
}
let checkout = CheckoutId::from_digest(Digest128::from_bytes(bytes));
(checkout.to_string() == name).then_some(checkout)
}
fn now_unix_ms() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |elapsed| {
u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX)
})
}