use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, Mutex, OnceLock, Weak};
use super::lease::LeaseFile;
use super::manifest::Manifest;
use super::record::{self, Kind};
use super::{Family, FamilyError, Layout};
use crate::cache::BlockCache;
use crate::checkout::CheckoutState;
use crate::ids::{CheckoutId, Digest128, FamilyId, Generation, SegmentId};
use crate::segment::{KnownSection, Segment};
#[derive(Clone, PartialEq, Eq, Hash)]
struct SharedKey {
path: PathBuf,
cache: usize,
known: Vec<KnownSection>,
}
fn shared_segments() -> &'static Mutex<HashMap<SharedKey, Weak<Segment>>> {
static SHARED: OnceLock<Mutex<HashMap<SharedKey, Weak<Segment>>>> = OnceLock::new();
SHARED.get_or_init(Mutex::default)
}
static SWEEP_AT: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(64);
pub(super) const MAX_TRIES: u32 = 16;
#[derive(Debug)]
pub struct Snapshot {
manifest: Manifest,
layout: Layout,
family: FamilyId,
skipped_manifests: usize,
_lease: Option<LeaseFile>,
}
pub(super) fn take(family: &Family) -> Result<Snapshot, FamilyError> {
for _ in 0..MAX_TRIES {
let Some((manifest, skipped_manifests)) = family.list_newest_manifest()? else {
continue;
};
let generation = manifest.generation();
if generation == Generation::EMPTY {
return Ok(Snapshot {
manifest,
layout: family.layout.clone(),
family: family.id,
skipped_manifests,
_lease: None,
});
}
let lease = family.owner()?.lease(family.id, generation)?;
let horizon = family
.newest_horizon()?
.map_or(Generation::EMPTY, |(_, horizon)| horizon);
if horizon > generation {
continue;
}
return Ok(Snapshot {
manifest,
layout: family.layout.clone(),
family: family.id,
skipped_manifests,
_lease: Some(lease),
});
}
Err(FamilyError::SnapshotRetries(MAX_TRIES))
}
impl Snapshot {
#[must_use]
pub fn manifest(&self) -> &Manifest {
&self.manifest
}
#[must_use]
pub fn generation(&self) -> Generation {
self.manifest.generation()
}
#[must_use]
pub const fn skipped_manifests(&self) -> usize {
self.skipped_manifests
}
#[must_use]
pub fn segment_path(&self, id: SegmentId) -> Option<PathBuf> {
self.manifest.segment(id).map(|_| self.layout.segment(id))
}
pub fn open_segment(
&self,
id: SegmentId,
known: &[KnownSection],
cache: Arc<BlockCache>,
) -> Result<Segment, FamilyError> {
let entry = self.manifest.segment(id).ok_or(FamilyError::Misuse(
"the snapshot's manifest does not name this segment",
))?;
let path = self.layout.segment(id);
let len = std::fs::metadata(&path)
.map_err(FamilyError::io(&path))?
.len();
if len != entry.len {
return Err(FamilyError::Damaged {
path,
reason: format!(
"the file is {len} bytes; generation {} published it at {} bytes",
self.manifest.generation(),
entry.len
),
});
}
let segment = Segment::open(&path, self.family, known, cache)?;
if segment.id() != id {
return Err(FamilyError::Damaged {
path,
reason: format!(
"the file holds segment {}; generation {} names segment {}",
segment.id().get(),
self.manifest.generation(),
id.get()
),
});
}
Ok(segment)
}
pub fn open_shared_segment(
&self,
id: SegmentId,
known: &[KnownSection],
cache: &Arc<BlockCache>,
) -> Result<Arc<Segment>, FamilyError> {
if self.manifest.segment(id).is_none() {
return Err(FamilyError::Misuse(
"the snapshot's manifest does not name this segment",
));
}
let key = SharedKey {
path: self.layout.segment(id),
cache: Arc::as_ptr(cache) as usize,
known: known.to_vec(),
};
if let Some(segment) = shared_segments()
.lock()
.expect("shared segment registry poisoned")
.get(&key)
.and_then(Weak::upgrade)
{
return Ok(segment);
}
let opened = Arc::new(self.open_segment(id, known, Arc::clone(cache))?);
let mut registry = shared_segments()
.lock()
.expect("shared segment registry poisoned");
if let Some(segment) = registry.get(&key).and_then(Weak::upgrade) {
return Ok(segment);
}
if registry.len() >= 2 * SWEEP_AT.load(std::sync::atomic::Ordering::Relaxed) {
registry.retain(|_, segment| segment.strong_count() > 0);
SWEEP_AT.store(registry.len().max(64), std::sync::atomic::Ordering::Relaxed);
}
registry.insert(key, Arc::downgrade(&opened));
Ok(opened)
}
pub fn read_state(&self, checkout: CheckoutId) -> Result<Option<Vec<u8>>, FamilyError> {
let Some(state) = self.manifest.checkout(checkout) else {
return Ok(None);
};
let path = self.layout.state(checkout, state.number);
let payload = record::read(&path, Kind::State, self.family, state.number)
.map_err(|error| FamilyError::record(&path, error))?;
if payload.len() as u64 != state.len || Digest128::of(&payload) != state.digest {
return Err(FamilyError::Damaged {
path,
reason: format!(
"the state's payload differs from the one generation {} published",
self.manifest.generation()
),
});
}
Ok(Some(payload))
}
pub fn checkout_state(
&self,
checkout: CheckoutId,
) -> Result<Option<CheckoutState>, FamilyError> {
let Some(payload) = self.read_state(checkout)? else {
return Ok(None);
};
CheckoutState::decode(&payload).map(Some).map_err(|error| {
let path = self
.manifest
.checkout(checkout)
.map_or_else(PathBuf::new, |state| {
self.layout.state(checkout, state.number)
});
FamilyError::record(&path, error)
})
}
}
crate::heap_bytes_of_fields!(Snapshot {
manifest,
layout,
family,
skipped_manifests,
_lease,
});