use std::io;
use std::ops::Range;
use std::sync::Arc;
use bytes::Bytes;
use tracing::warn;
use crate::error::{SmbError, SmbResult};
use super::backend::Shared;
use super::change::{
ensure_local, persist, persist_held, persist_with, record_held, recount_source,
};
use super::data::disk_error;
use super::entry::{Body, Entry, Landing, Upload};
use super::error::S3Error;
use super::object::ObjectHead;
use super::ranges::RangeSet;
use super::record::RecordId;
use super::retry::Stop;
use super::tombs::Variant;
use super::unlink::drop_record;
pub(super) fn to_fill(present: &RangeSet, len: u64, range: &Range<u64>) -> Vec<Range<u64>> {
let end = range.end.min(len);
if range.start >= end {
return Vec::new();
}
present
.segments(range.start..end)
.into_iter()
.filter(|(_, held)| !held)
.map(|(piece, _)| piece)
.collect()
}
pub(super) fn fill(
shared: &Shared,
entry: &Entry,
range: &Range<u64>,
data: Option<&Bytes>,
) -> SmbResult<bool> {
let cache = shared.local()?;
let _io = entry.lock_io();
let (held, pieces) = {
let state = entry.state();
state.attached()?;
let Some(local) = state.local() else {
return Ok(false);
};
(
Arc::clone(&local.file),
to_fill(&local.present, local.len, range),
)
};
if let Some(data) = data
&& !pieces.is_empty()
{
let file = held.file().map_err(disk_error)?;
for piece in &pieces {
let from = usize::try_from(piece.start - range.start)
.map_err(|_| SmbError::InvalidParameter)?;
let to =
usize::try_from(piece.end - range.start).map_err(|_| SmbError::InvalidParameter)?;
let bytes = data.get(from..to).ok_or(SmbError::InvalidParameter)?;
cache
.write_data(&file, bytes, piece.start)
.map_err(disk_error)?;
}
}
let mut state = entry.state();
let Some(local) = state
.local_mut()
.filter(|local| Arc::ptr_eq(&local.file, &held))
else {
return Ok(false);
};
let grew = !pieces.is_empty();
for piece in pieces {
local.present.insert(piece);
}
Ok(grew)
}
fn taking<T>(
shared: &Shared,
entry: &Arc<Entry>,
key: &str,
stop: &Stop,
work: impl FnOnce(&[Arc<Entry>]) -> SmbResult<T>,
) -> SmbResult<Option<T>> {
let owners = shared.overlay.owners(key, entry);
let locking: Vec<&Arc<Entry>> = std::iter::once(entry).chain(&owners).collect();
let _locks = Entry::lock_all(&locking);
{
let state = entry.state();
if state.detached || !state.is_write_key(key) || stop.is_stopped() {
return Ok(None);
}
}
work(&owners).map(Some)
}
pub(super) fn before_store(
shared: &Shared,
entry: &Arc<Entry>,
key: &str,
filled: bool,
stop: &Stop,
) -> SmbResult<Option<bool>> {
taking(shared, entry, key, stop, |owners| {
let existed = std::mem::replace(&mut entry.state().may_exist, true);
if !existed || filled {
persist_held(shared, entry, true)?;
}
release_key(shared, owners, key)?;
Ok(existed)
})
}
pub(super) fn take_over(
shared: &Shared,
entry: &Arc<Entry>,
key: &str,
stop: &Stop,
) -> SmbResult<bool> {
let taken = taking(shared, entry, key, stop, |owners| {
release_key(shared, owners, key)
})?;
Ok(taken.is_some())
}
pub(super) fn settle(shared: &Shared, found: Vec<Variant>) -> SmbResult<()> {
for Variant { key, owner, same } in found {
if !same {
shared.overlay.keep_apart(&key);
continue;
}
let name = key.strip_suffix('/').unwrap_or(&key).to_owned();
match owner {
Some(owner) => match taken_over(shared, &owner, &[key]) {
Err(SmbError::AccessDenied) => {}
done => done?,
},
None => shared
.overlay
.drop_tombs(shared.local()?, &[key])
.map_err(disk_error)?,
}
shared.forget_file(&name);
}
Ok(())
}
fn release_key(shared: &Shared, owners: &[Arc<Entry>], key: &str) -> SmbResult<()> {
for owner in owners {
match taken_over_held(shared, owner, &[key.to_owned()]) {
Ok(()) | Err(SmbError::AccessDenied) => {}
Err(e) => return Err(e),
}
}
if let Some(cache) = shared.local.as_deref()
&& shared.overlay.tomb_named(key)
{
shared
.overlay
.drop_tombs(cache, &[key.to_owned()])
.map_err(disk_error)?;
}
Ok(())
}
pub(super) fn local_copy(shared: &Shared, entry: &Entry) -> SmbResult<()> {
let cache = shared.local()?;
let _io = entry.lock_io();
ensure_local(cache, entry, None)?;
Ok(())
}
pub(super) fn landed(
shared: &Shared,
entry: &Arc<Entry>,
generation: u64,
key: &str,
head: Arc<ObjectHead>,
) -> SmbResult<bool> {
let cache = shared.local()?;
let io = entry.lock_io();
let _seal = entry.lock_seal();
let (landing, id, keeps_keys) = {
let mut state = entry.state();
state.attached()?;
let landing = state.landed(&shared.ahead, generation, key, head);
(landing, state.id.clone(), !state.gone.is_empty())
};
match landing {
Landing::Moved => return Ok(false),
Landing::Newer => {
drop(io);
persist_held(shared, entry, true)?;
return Ok(true);
}
Landing::Whole => {}
}
if keeps_keys {
entry.state().stored();
if id.is_some() {
record_held(shared, entry)?;
}
} else if let Some(id) = &id {
cache.remove_record(id).map_err(SmbError::Io)?;
}
if let Some(id) = &id
&& let Err(e) = cache.remove_data(id)
{
warn!(error = %e, "a data file that is no longer needed could not be removed");
}
if !keeps_keys {
entry.state().settled();
}
recount_source(shared, entry);
Ok(true)
}
fn rest(shared: &Shared, entry: &Arc<Entry>, gone: Option<Vec<String>>) -> SmbResult<()> {
let cache = shared.local()?;
let (idle, id, recorded, batch) = {
let state = entry.state();
let owned = gone.as_deref().unwrap_or(&state.gone);
(
!state.writes() && owned.is_empty(),
state.id.clone(),
state.recorded,
state.batch.clone(),
)
};
if idle {
drop_record(shared, cache, batch.as_ref(), id.as_ref(), recorded)?;
let mut state = entry.state();
if let Some(gone) = gone {
state.gone = gone;
}
state.batch = None;
state.settled();
} else {
persist_with(shared, entry, true, gone, None)?;
}
shared.overlay.track(entry);
if idle {
shared.overlay.leave_if_idle(entry);
}
Ok(())
}
pub(super) fn deleted(shared: &Shared, entry: &Arc<Entry>, removed: &[String]) -> SmbResult<()> {
let _io = entry.lock_io();
let _seal = entry.lock_seal();
deleted_held(shared, entry, removed)
}
fn deleted_held(shared: &Shared, entry: &Arc<Entry>, removed: &[String]) -> SmbResult<()> {
let gone = {
let state = entry.state();
state.attached()?;
state
.gone
.iter()
.filter(|key| !removed.contains(key))
.cloned()
.collect()
};
rest(shared, entry, Some(gone))
}
pub(super) fn taken_over(shared: &Shared, owner: &Arc<Entry>, keys: &[String]) -> SmbResult<()> {
let _io = owner.lock_io();
let _seal = owner.lock_seal();
taken_over_held(shared, owner, keys)
}
fn taken_over_held(shared: &Shared, owner: &Arc<Entry>, keys: &[String]) -> SmbResult<()> {
match deleted_held(shared, owner, keys) {
Err(e) if !matches!(e, SmbError::AccessDenied | SmbError::DiskFull) => {
let failure = S3Error::cache(e);
shared.overlay.failed(owner, failure.clone());
shared.overlay.touch();
Err(SmbError::Io(io::Error::other(failure)))
}
done => done,
}
}
pub(super) fn dropped(shared: &Shared, entry: &Arc<Entry>, generation: u64) -> SmbResult<()> {
let _io = entry.lock_io();
let _seal = entry.lock_seal();
{
let mut state = entry.state();
state.attached()?;
if state.generation != generation {
return Ok(());
}
state.own = None;
state.uploaded = generation;
}
rest(shared, entry, None)
}
pub(super) fn note_upload(
shared: &Shared,
entry: &Arc<Entry>,
upload: Option<Upload>,
) -> SmbResult<()> {
{
let mut state = entry.state();
state.attached()?;
if let Body::File { upload: held, .. } = &mut state.body {
*held = upload;
}
}
persist(shared, entry, true)
}
pub(super) fn failed(shared: &Shared, entry: &Arc<Entry>, error: S3Error) -> SmbResult<()> {
shared.overlay.failed(entry, error);
persist(shared, entry, true)
}
pub(super) fn conflict(
shared: &Shared,
entry: &Arc<Entry>,
error: S3Error,
) -> SmbResult<Option<RecordId>> {
let cache = shared.local()?;
let _io = entry.lock_io();
let _seal = entry.lock_seal();
let id = {
let state = entry.state();
state.attached()?;
state.id.clone()
};
let moved = id
.map(|id| cache.keep_conflict(&id).map_err(SmbError::Io))
.transpose()?;
{
let mut state = entry.state();
state.failure = Some(error);
state.gone.clear();
}
shared.overlay.evict(entry);
#[cfg(test)]
super::jobs::pause_blocking(&shared.jobs.pause_conflict);
Ok(moved)
}
#[cfg(test)]
mod tests {
use super::*;
fn ranges(ranges: &[(u64, u64)]) -> Vec<Range<u64>> {
ranges.iter().map(|&(start, end)| start..end).collect()
}
#[test]
fn a_fill_writes_only_the_bytes_the_file_does_not_hold() {
let present: RangeSet = ranges(&[(100, 110), (150, 160)]).into_iter().collect();
assert_eq!(
to_fill(&present, 1000, &(0..200)),
ranges(&[(0, 100), (110, 150), (160, 200)])
);
assert_eq!(to_fill(&present, 1000, &(100..110)), ranges(&[]));
assert_eq!(to_fill(&present, 1000, &(105..120)), ranges(&[(110, 120)]));
}
#[test]
fn a_fill_stops_at_the_length_the_file_has_now() {
let present: RangeSet = ranges(&[(10, 20)]).into_iter().collect();
assert_eq!(
to_fill(&present, 50, &(0..100)),
ranges(&[(0, 10), (20, 50)])
);
assert_eq!(to_fill(&present, 15, &(0..100)), ranges(&[(0, 10)]));
assert_eq!(to_fill(&present, 10, &(10..100)), ranges(&[]));
assert_eq!(to_fill(&present, 0, &(0..100)), ranges(&[]));
}
}