use std::fs::File;
use std::future::Future;
use std::io;
use std::ops::Range;
use std::pin::Pin;
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime};
use bytes::{Bytes, BytesMut};
use tokio::task::{JoinError, JoinSet, spawn_blocking};
use tracing::{debug, error, warn};
use crate::error::{SmbError, SmbResult};
use super::backend::Shared;
use super::cache::Known;
use super::change;
use super::data::{disk_error, out_of_descriptors};
use super::entry::{Body, Entry, Upload};
use super::error::S3Error;
use super::jobs::Running;
use super::keys::{FileStamp, RowKind, dir_prefix};
use super::meta;
use super::object::{ByteRange, Metadata, ObjectHead};
use super::outcome;
use super::overlay::{Fence, GoneClaim};
use super::parts::{hash_range, part_size_for, parts};
use super::payload::Payload;
use super::read::same_version;
use super::retry::{Retry, Stop};
use super::xml::CompletedPart;
mod copy;
const NEW_FILE_TYPE: &str = "application/octet-stream";
pub(super) const FULL_DISK_REST: Duration = Duration::from_secs(1);
#[derive(Debug)]
enum Halt {
Stopped,
Gone,
Again,
Blocked,
Full,
Descriptors,
Conflict(S3Error),
Failed(S3Error),
}
fn classify(error: S3Error, stopped: bool) -> Halt {
if error.is_stopped() || (stopped && matches!(error, S3Error::SourceRead(_))) {
Halt::Stopped
} else if error.is_source_changed() {
Halt::Again
} else {
Halt::Failed(error)
}
}
struct Snapshot {
key: String,
generation: u64,
file: Arc<File>,
len: u64,
metadata: Metadata,
replaced: Option<String>,
}
type PartFuture = Pin<Box<dyn Future<Output = Result<CompletedPart, S3Error>> + Send>>;
enum Kind {
Upload,
Copy,
Nothing,
}
struct CopyJob {
key: String,
from: String,
head: Arc<ObjectHead>,
metadata: Metadata,
replace: bool,
prior: Option<String>,
generation: u64,
}
struct Want {
range: Range<u64>,
base: Option<(String, Arc<ObjectHead>)>,
}
struct Job<'a> {
shared: &'a Arc<Shared>,
run: &'a Running,
path: String,
}
pub(super) async fn run(shared: Arc<Shared>, running: Running) {
let job = Job {
path: running.entry.state().path(&shared.prefix),
shared: &shared,
run: &running,
};
let result = if running.entry.is_dir() {
job.directory().await
} else {
job.file().await
};
match result {
Ok(()) => debug!(path = %job.path, "the entry is in the bucket"),
Err(halt) => job.end(halt).await,
}
}
impl Job<'_> {
fn entry(&self) -> &Arc<Entry> {
&self.run.entry
}
fn stop(&self) -> &Stop {
&self.run.stop
}
fn retry(&self) -> Retry {
Retry::until(self.stop())
}
fn halt(&self, error: S3Error) -> Halt {
classify(error, self.stop().is_stopped())
}
fn local(&self, error: SmbError) -> Halt {
if self.entry().state().detached {
return Halt::Gone;
}
match error {
SmbError::DiskFull => Halt::Full,
SmbError::Io(ref e) if out_of_descriptors(e) => Halt::Descriptors,
other => Halt::Failed(S3Error::cache(other)),
}
}
fn check(&self) -> Result<(), Halt> {
if self.entry().state().detached {
return Err(Halt::Gone);
}
if self.stop().is_stopped() {
return Err(Halt::Stopped);
}
Ok(())
}
async fn blocking<T: Send + 'static>(
&self,
work: impl FnOnce(&Shared, &Arc<Entry>) -> SmbResult<T> + Send + 'static,
) -> Result<T, Halt> {
let (shared, entry) = (Arc::clone(self.shared), Arc::clone(self.entry()));
match spawn_blocking(move || work(&shared, &entry)).await {
Ok(done) => done.map_err(|e| self.local(e)),
Err(e) => Err(self.local(SmbError::Io(io::Error::other(e)))),
}
}
async fn end(&self, halt: Halt) {
match halt {
Halt::Stopped => debug!(path = %self.path, "the job was stopped"),
Halt::Gone => debug!(path = %self.path, "the entry left the overlay during its job"),
Halt::Blocked => debug!(path = %self.path, "the key is in use; the job waits for it"),
Halt::Again => {
debug!(path = %self.path, "the bytes changed under the job");
self.entry().state().changed = Instant::now();
}
Halt::Full => {
warn!(
path = %self.path,
"the disk of the cache directory is full; the upload is tried again after the file has rested"
);
self.rest();
}
Halt::Descriptors => {
warn!(
path = %self.path,
"no file descriptor is left to open the data file; the upload is tried again after the file has rested"
);
#[cfg(test)]
self.shared
.jobs
.descriptor_rests
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
self.rest();
}
Halt::Conflict(error) => self.conflict(error).await,
Halt::Failed(error) => self.fail(error).await,
}
}
async fn conflict(&self, error: S3Error) {
let (key, base) = {
let state = self.entry().state();
(
state.key.clone(),
state.base.as_ref().map(|base| base.key.clone()),
)
};
let (status, code) = (error.http_status(), error.code().map(str::to_owned));
self.shared.forget_file(&key);
if let Some(base) = base.filter(|base| *base != key) {
self.shared.forget_file(&base);
}
let moved = self
.blocking(move |shared, entry| outcome::conflict(shared, entry, error))
.await;
let code = code.as_deref();
match moved {
Ok(_) => error!(
path = %self.path,
status,
code,
"the object changed or was deleted in the bucket while the file held changes of its own; \
the changes were moved to the conflicts directory"
),
Err(Halt::Gone) => {
debug!(path = %self.path, "the entry left the overlay during its job")
}
Err(halt) => {
error!(
path = %self.path,
status,
code,
"the object changed or was deleted in the bucket while the file held changes of its own, \
and the changes could not be moved to the conflicts directory"
);
if let Halt::Failed(failure) = halt {
self.fail(failure).await;
}
}
}
}
fn rest(&self) {
let now = Instant::now();
let mut state = self.entry().state();
state.changed = now;
state.rest_until = Some(now + FULL_DISK_REST);
}
async fn fail(&self, failure: S3Error) {
error!(
path = %self.path,
status = failure.http_status(),
code = failure.code(),
request_id = failure.request_id(),
error = %failure,
"a change could not be stored in the bucket, and is tried again when the next backend is built"
);
let marked = self
.blocking(move |shared, entry| outcome::failed(shared, entry, failure))
.await;
if marked.is_err() {
warn!(path = %self.path, "the record of a failed upload could not be written");
}
}
async fn refresh(&self) -> Result<(), Halt> {
let (key, head, is_dir) = {
let state = self.entry().state();
if state.detached {
return Err(Halt::Gone);
}
match &state.base {
Some(base) if base.bare => {
(base.key.clone(), Arc::clone(&base.head), state.is_dir())
}
_ => return Ok(()),
}
};
let found = match self.shared.client.head_object(&key, self.retry()).await {
Ok(found) => Arc::new(found),
Err(e) if e.is_no_such_key() && is_dir => return Ok(()),
Err(e) if e.is_no_such_key() => return Err(Halt::Conflict(e)),
Err(e) => return Err(self.halt(e)),
};
if !is_dir && !head.same_object(&found) {
return Err(Halt::Conflict(S3Error::status(
412,
Some("PreconditionFailed"),
None,
)));
}
self.check()?;
self.entry()
.state()
.complete_base(&self.shared.ahead, &key, found);
Ok(())
}
async fn file(&self) -> Result<(), Halt> {
self.abort_stale().await;
self.refresh().await?;
if self.run.cycle && self.entry().state().local().is_none() {
self.blocking(|shared, entry| outcome::local_copy(shared, entry))
.await?;
}
let kind = {
let state = self.entry().state();
if state.detached {
return Err(Halt::Gone);
}
if state.local().is_some() {
Kind::Upload
} else if state.base.is_some() && (state.moved() || state.own.is_some()) {
Kind::Copy
} else {
Kind::Nothing
}
};
match kind {
Kind::Upload => self.upload().await?,
Kind::Copy => self.copy().await?,
Kind::Nothing => self.drop_own().await?,
}
self.finish().await
}
async fn upload(&self) -> Result<(), Halt> {
self.blocking(|shared, entry| change::seal(shared, entry, false))
.await?;
let filled = self.fill().await?;
let file = self.open_data().await?;
let snapshot = self.snapshot(file)?;
self.check()?;
let jobs = &self.shared.jobs;
let part_size =
(snapshot.len > jobs.part_size).then(|| part_size_for(snapshot.len, jobs.part_size));
let hashes = self.hash(&snapshot, part_size).await?;
self.check()?;
#[cfg(test)]
super::jobs::pause(&self.shared.jobs.pause).await;
let existed = self.before_store(&snapshot.key, filled).await?;
let etag = match part_size {
None => self.put(&snapshot, &hashes[0]).await?,
Some(size) => {
let prior = self
.prior_etag(&snapshot.key, snapshot.replaced.clone(), existed)
.await?;
self.upload_parts(&snapshot, size, &hashes, prior.as_deref())
.await?
}
};
let head = Arc::new(ObjectHead {
size: snapshot.len,
etag,
last_modified: SystemTime::now(),
metadata: snapshot.metadata.clone(),
});
let Snapshot {
key,
generation,
file,
..
} = snapshot;
drop(file);
self.land(generation, key, head).await
}
async fn before_store(&self, key: &str, filled: bool) -> Result<bool, Halt> {
let (name, stop) = (key.to_owned(), self.stop().clone());
let taken = self
.blocking(move |shared, entry| {
outcome::before_store(shared, entry, &name, filled, &stop)
})
.await?;
let Some(existed) = taken else {
self.check()?;
return Err(Halt::Stopped);
};
match self
.shared
.overlay
.begin_write(self.entry(), key, self.stop())
{
Ok(()) => Ok(existed),
Err(Fence::Gone) => Err(Halt::Gone),
Err(Fence::Stopped) => Err(Halt::Stopped),
Err(Fence::Blocked) => Err(Halt::Blocked),
}
}
async fn prior_etag(
&self,
key: &str,
known: Option<String>,
existed: bool,
) -> Result<Option<String>, Halt> {
if known.is_some() || !existed {
return Ok(known);
}
match self.shared.client.head_object(key, self.retry()).await {
Ok(head) => Ok(Some(head.etag).filter(|etag| !etag.is_empty())),
Err(e) if e.is_no_such_key() => Ok(None),
Err(e) => Err(self.halt(e)),
}
}
async fn land(&self, generation: u64, key: String, head: Arc<ObjectHead>) -> Result<(), Halt> {
#[cfg(test)]
self.pause_or_stop(&self.shared.jobs.pause_stored).await?;
self.remember(&key, &head);
self.settle_variants(&key).await?;
let took = self
.blocking(move |shared, entry| outcome::landed(shared, entry, generation, &key, head))
.await?;
if !took {
return Err(Halt::Stopped);
}
Ok(())
}
async fn settle_variants(&self, key: &str) -> Result<(), Halt> {
let retry = Retry::until(&self.shared.jobs.stop);
let found = self
.shared
.compare_variants(self.entry(), key, &retry)
.await
.map_err(|e| classify(e, true))?;
if found.is_empty() {
return Ok(());
}
self.blocking(move |shared, _| outcome::settle(shared, found))
.await
}
async fn abort_stale(&self) {
let stale = {
let state = self.entry().state();
match &state.body {
Body::File {
upload: Some(upload),
..
} => Some(upload.clone()),
_ => None,
}
};
if let Some(upload) = stale {
self.abort(&upload.key, &upload.id).await;
}
}
async fn fill(&self) -> Result<bool, Halt> {
let mut from = 0;
let mut filled = false;
loop {
self.check()?;
let Some(want) = self.missing(from)? else {
return Ok(filled);
};
from = want.range.end;
let data = self.fetch(&want).await?;
let range = want.range;
filled |= self
.blocking(move |shared, entry| outcome::fill(shared, entry, &range, data.as_ref()))
.await?;
}
}
fn missing(&self, from: u64) -> Result<Option<Want>, Halt> {
let state = self.entry().state();
if state.detached {
return Err(Halt::Gone);
}
let Some(local) = state.local() else {
return Err(Halt::Gone);
};
if from >= local.len {
return Ok(None);
}
let next = local
.present
.segments(from..local.len)
.into_iter()
.find(|(_, present)| !present);
Ok(next.map(|(range, _)| Want {
range: range.start..range.end.min(range.start + self.shared.read_chunk),
base: state
.base
.as_ref()
.map(|base| (base.key.clone(), Arc::clone(&base.head))),
}))
}
async fn fetch(&self, want: &Want) -> Result<Option<Bytes>, Halt> {
let Some((key, head)) = &want.base else {
return Ok(None);
};
let end = want.range.end.min(head.size);
if want.range.start >= end {
return Ok(None);
}
let range =
ByteRange::new(want.range.start, end - want.range.start).map_err(Halt::Failed)?;
let etag = Some(head.etag.as_str()).filter(|etag| !etag.is_empty());
let object = match self
.shared
.client
.get_object(key, range, etag, self.retry())
.await
{
Ok(object) => object,
Err(e) if e.is_precondition_failed() || e.is_no_such_key() => {
return Err(Halt::Conflict(e));
}
Err(e) => return Err(self.halt(e)),
};
let whole = object.data.len() as u64 == range.len();
if !whole || (etag.is_none() && !same_version(&object.head, head)) {
return Err(Halt::Conflict(S3Error::status(
412,
Some("PreconditionFailed"),
None,
)));
}
let missing = (want.range.end - end) as usize;
if missing == 0 {
return Ok(Some(object.data));
}
let mut padded = BytesMut::with_capacity(object.data.len() + missing);
padded.extend_from_slice(&object.data);
padded.resize(object.data.len() + missing, 0);
Ok(Some(padded.freeze()))
}
async fn open_data(&self) -> Result<Arc<File>, Halt> {
let opened = self
.blocking(|_, entry| {
let _io = entry.lock_io();
let data = entry.state().local().map(|local| Arc::clone(&local.file));
data.map(|data| data.file().map_err(disk_error)).transpose()
})
.await?;
opened.ok_or(Halt::Gone)
}
fn snapshot(&self, file: Arc<File>) -> Result<Snapshot, Halt> {
let state = self.entry().state();
if state.detached {
return Err(Halt::Gone);
}
let Some(local) = state.local() else {
return Err(Halt::Gone);
};
if !local.present.covers(local.len) {
return Err(Halt::Again);
}
let own = state.own_or_base(self.shared.built);
let mut metadata = state.base.as_ref().map_or_else(
|| Metadata {
content_type: Some(NEW_FILE_TYPE.to_owned()),
..Metadata::default()
},
|base| base.head.metadata.clone(),
);
metadata
.user
.extend(meta::stored_metadata(own.times, own.attributes));
Ok(Snapshot {
key: state.key.clone(),
generation: state.generation,
file,
len: local.len,
metadata,
replaced: state.prior.clone(),
})
}
#[cfg(test)]
async fn pause_or_stop(
&self,
gates: &std::sync::Mutex<Option<super::jobs::Gates>>,
) -> Result<(), Halt> {
super::jobs::pause(gates).await;
if self.shared.jobs.stop.is_stopped() {
return Err(Halt::Stopped);
}
Ok(())
}
async fn hash(&self, snapshot: &Snapshot, part_size: Option<u64>) -> Result<Vec<String>, Halt> {
let ranges: Vec<Range<u64>> = match part_size {
None => std::iter::once(0..snapshot.len).collect(),
Some(size) => parts(snapshot.len, size).map(|(_, range)| range).collect(),
};
let mut hashes = Vec::with_capacity(ranges.len());
for range in ranges {
let hash = hash_range(Arc::clone(&snapshot.file), range, self.stop().clone())
.await
.map_err(|e| self.halt(e))?;
hashes.push(hash);
}
Ok(hashes)
}
async fn put(&self, snapshot: &Snapshot, hash: &str) -> Result<String, Halt> {
let payload = if snapshot.len == 0 {
Payload::empty()
} else {
Payload::file(Arc::clone(&snapshot.file), 0, snapshot.len, hash)
.map_err(|e| self.halt(e))?
};
self.shared
.client
.put_object(&snapshot.key, payload, &snapshot.metadata, self.retry())
.await
.map_err(|e| self.halt(e))
}
async fn upload_parts(
&self,
snapshot: &Snapshot,
part_size: u64,
hashes: &[String],
prior: Option<&str>,
) -> Result<String, Halt> {
self.multipart(
&snapshot.key,
&snapshot.metadata,
snapshot.len,
part_size,
prior,
|id, number, range, retry| {
let hash = &hashes[(number - 1) as usize];
let payload = Payload::file(
Arc::clone(&snapshot.file),
range.start,
range.end - range.start,
hash,
)?;
let (client, key, id) = (
self.shared.client.clone(),
snapshot.key.clone(),
id.to_owned(),
);
Ok(Box::pin(async move {
client
.upload_part(&key, &id, number, payload, retry)
.await
.map(|etag| CompletedPart { number, etag })
}) as PartFuture)
},
)
.await
}
async fn multipart(
&self,
key: &str,
metadata: &Metadata,
len: u64,
part_size: u64,
prior: Option<&str>,
part: impl Fn(&str, u32, Range<u64>, Retry) -> Result<PartFuture, S3Error>,
) -> Result<String, Halt> {
let client = &self.shared.client;
let id = client
.create_multipart_upload(key, metadata, self.retry())
.await
.map_err(|e| self.halt(e))?;
let noted = Upload {
key: key.to_owned(),
id: id.clone(),
};
let sent = match self
.blocking(move |shared, entry| outcome::note_upload(shared, entry, Some(noted)))
.await
{
Ok(()) => self.send_parts(&id, len, part_size, part).await,
Err(halt) => Err(halt),
};
let done = match sent {
Ok(parts) => client
.complete_multipart_upload(key, &id, &parts, len, prior, self.retry())
.await
.map_err(|e| self.halt(e)),
Err(halt) => Err(halt),
};
if done.is_err() {
self.abort(key, &id).await;
}
done
}
async fn send_parts(
&self,
id: &str,
len: u64,
part_size: u64,
part: impl Fn(&str, u32, Range<u64>, Retry) -> Result<PartFuture, S3Error>,
) -> Result<Vec<CompletedPart>, Halt> {
let concurrency = self.shared.jobs.concurrency;
let mut sending: JoinSet<Result<CompletedPart, S3Error>> = JoinSet::new();
let mut sent = Vec::new();
let mut failure = None;
for (number, range) in parts(len, part_size) {
while sending.len() >= concurrency {
if let Some(joined) = sending.join_next().await {
note(joined, &mut sent, &mut failure);
}
}
if failure.is_some() || self.stop().is_stopped() {
break;
}
match part(id, number, range, self.retry()) {
Ok(next) => {
sending.spawn(next);
}
Err(e) => {
failure = Some(e);
break;
}
}
}
while let Some(joined) = sending.join_next().await {
note(joined, &mut sent, &mut failure);
}
if let Some(failure) = failure {
return Err(self.halt(failure));
}
if sent.len() as u64 != len.div_ceil(part_size) {
return Err(Halt::Stopped);
}
sent.sort_by_key(|part| part.number);
Ok(sent)
}
async fn abort(&self, key: &str, id: &str) {
let retry = Retry::until(&self.shared.jobs.stop);
match self
.shared
.client
.abort_multipart_upload(key, id, retry)
.await
{
Ok(()) => {
let cleared = self
.blocking(|shared, entry| outcome::note_upload(shared, entry, None))
.await;
if cleared.is_err() && !self.entry().state().detached {
warn!(path = %self.path, "the record of an aborted upload could not be written");
}
}
Err(e) if e.is_stopped() => {}
Err(e) => warn!(
path = %self.path,
error = %e,
"a multipart upload could not be aborted"
),
}
}
fn remember(&self, key: &str, head: &Arc<ObjectHead>) {
let stamp = FileStamp {
size: head.size,
etag: head.etag.clone(),
last_modified: head.last_modified,
};
self.shared
.remember(key, Known::File(Arc::clone(head)), RowKind::File(stamp));
}
async fn drop_own(&self) -> Result<(), Halt> {
let (pending, generation) = {
let state = self.entry().state();
(state.own.is_some(), state.generation)
};
if pending {
self.blocking(move |shared, entry| outcome::dropped(shared, entry, generation))
.await?;
}
Ok(())
}
async fn finish(&self) -> Result<(), Halt> {
#[cfg(test)]
self.pause_or_stop(&self.shared.jobs.pause_landed).await?;
let gone = self.entry().state().gone.clone();
if gone.is_empty() {
return Ok(());
}
let GoneClaim {
claimed,
left,
busy,
} = self.shared.overlay.claim_gone(&gone, self.entry());
if !busy.is_empty() {
debug!(path = %self.path, keys = busy.len(), "keys to delete are in use and stay");
}
let done = self.shared.delete_claimed(&claimed).await;
drop(claimed);
let done = done.map_err(|refused| classify(refused.error, true))?;
let mut removed = left;
removed.extend(done.deleted);
if !removed.is_empty() {
self.blocking(move |shared, entry| outcome::deleted(shared, entry, &removed))
.await?;
}
if done.stopped {
return Err(Halt::Stopped);
}
match done.failed.into_iter().next() {
Some((_, error)) => Err(Halt::Failed(error)),
None => Ok(()),
}
}
async fn directory(&self) -> Result<(), Halt> {
self.refresh().await?;
let writes = {
let state = self.entry().state();
if state.detached {
return Err(Halt::Gone);
}
state.writes()
};
if writes {
self.marker().await?;
}
self.finish().await
}
async fn marker(&self) -> Result<(), Halt> {
let (key, generation, metadata) = {
let state = self.entry().state();
if state.detached {
return Err(Halt::Gone);
}
let own = state.own_or_base(self.shared.built);
let mut metadata = meta::marker_metadata(own.times, own.attributes);
if let Some(base) = &state.base {
let mut kept = base.head.metadata.clone();
kept.user.extend(metadata.user);
metadata = kept;
}
(state.key.clone(), state.generation, metadata)
};
self.check()?;
self.before_store(&dir_prefix(&key), false).await?;
let head = change::store_marker(self.shared, &key, metadata, self.retry())
.await
.map_err(|e| self.halt(e))?;
self.settle_variants(&dir_prefix(&key)).await?;
let took = change::marker_put(self.shared, self.run.held(), generation, &key, head)
.await
.map_err(|e| self.local(e))?;
if !took {
return Err(Halt::Stopped);
}
let mut state = self.entry().state();
state.uploaded = generation;
Ok(())
}
}
fn note(
joined: Result<Result<CompletedPart, S3Error>, JoinError>,
sent: &mut Vec<CompletedPart>,
failure: &mut Option<S3Error>,
) {
match joined {
Ok(Ok(part)) => sent.push(part),
Ok(Err(e)) => {
failure.get_or_insert(e);
}
Err(e) => {
failure.get_or_insert(S3Error::transport(e));
}
}
}
#[cfg(test)]
mod tests {
use super::*;
fn status(status: u16, code: &str) -> S3Error {
S3Error::status(status, Some(code), None)
}
#[test]
fn a_stop_and_a_source_that_changed_are_not_failures() {
assert!(matches!(classify(S3Error::Stopped, false), Halt::Stopped));
assert!(matches!(
classify(S3Error::SourceChanged, false),
Halt::Again
));
}
#[test]
fn a_failed_read_of_the_file_is_a_failure_unless_the_job_was_stopped() {
let read = || S3Error::SourceRead(Arc::new(io::Error::other("read")));
assert!(matches!(classify(read(), false), Halt::Failed(_)));
assert!(matches!(classify(read(), true), Halt::Stopped));
}
#[test]
fn what_the_store_refuses_for_good_is_a_failure_stopped_or_not() {
for error in [
status(403, "AccessDenied"),
status(400, "EntityTooLarge"),
status(404, "NoSuchBucket"),
S3Error::InvalidResponse("bad"),
] {
for stopped in [false, true] {
assert!(
matches!(classify(error.clone(), stopped), Halt::Failed(_)),
"{error:?}, stopped {stopped}"
);
}
}
}
}