use std::fmt;
use std::io;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::{Duration, SystemTime};
use async_trait::async_trait;
use crate::backend::{
BackendCapabilities, Handle, OpenAction, OpenIntent, OpenOptions, ShareBackend, VolumeInfo,
};
use crate::error::{SmbError, SmbResult};
use crate::path::SmbPath;
use super::cache::MetaCache;
use super::cachedir::CacheDir;
use super::client::S3Client;
use super::entry::Own;
use super::error::S3Error;
use super::jobs::{Guard, Jobs};
use super::overlay::Overlay;
use super::readahead::ReadAhead;
use super::retry::Retry;
#[derive(Clone)]
pub struct S3Backend {
pub(super) shared: Arc<Shared>,
pub(super) _worker: Arc<Guard>,
}
pub(super) struct Shared {
pub(super) client: S3Client,
pub(super) prefix: String,
pub(super) case_insensitive: bool,
pub(super) request_timeout: Duration,
pub(super) listing_metadata_max: usize,
pub(super) head_concurrency: usize,
pub(super) built: SystemTime,
pub(super) cache: Mutex<MetaCache>,
pub(super) read_chunk: u64,
pub(super) max_dir_rename_objects: usize,
pub(super) ahead: Arc<ReadAhead>,
pub(super) read_only: bool,
pub(super) overlay: Arc<Overlay>,
pub(super) local: Option<Arc<CacheDir>>,
pub(super) root_own: Mutex<Own>,
pub(super) jobs: Arc<Jobs>,
}
impl Shared {
pub(super) fn retry(&self) -> Retry {
Retry::within(self.request_timeout)
}
pub(super) async fn await_clear<T>(
&self,
retry: &Retry,
mut check: impl FnMut() -> SmbResult<Option<T>>,
) -> SmbResult<T> {
let mut progress = self.overlay.subscribe();
loop {
if let Some(done) = check()? {
return Ok(done);
}
#[cfg(test)]
self.jobs
.waits
.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
let changed = progress.changed();
let woken = match retry.deadline() {
Some(deadline) => tokio::time::timeout_at(deadline, changed)
.await
.map_err(|_| S3Error::DeadlineExceeded.into_smb_error())?,
None => changed.await,
};
woken.map_err(|e| SmbError::Io(io::Error::other(e)))?;
}
}
pub(super) fn cache(&self) -> MutexGuard<'_, MetaCache> {
self.cache.lock().unwrap_or_else(PoisonError::into_inner)
}
pub(super) fn local(&self) -> SmbResult<&CacheDir> {
self.local.as_deref().ok_or(SmbError::AccessDenied)
}
pub(super) fn root_own(&self) -> MutexGuard<'_, Own> {
self.root_own.lock().unwrap_or_else(PoisonError::into_inner)
}
}
impl S3Backend {
pub async fn sync(&self) -> Result<(), S3Error> {
self.shared.sync().await
}
#[must_use]
pub fn failures(&self) -> Vec<(String, S3Error)> {
self.shared.overlay.failures(&self.shared.prefix)
}
}
impl fmt::Debug for S3Backend {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("S3Backend")
.field("client", &self.shared.client)
.field("prefix", &self.shared.prefix)
.finish_non_exhaustive()
}
}
#[cfg(test)]
impl S3Backend {
pub(crate) fn limit_listing_rows(&self, rows: usize) {
self.shared.cache().limit_rows(rows);
}
pub(crate) fn listing_reads(&self) -> usize {
self.shared.cache().reads()
}
pub(crate) fn listing_attempts() -> usize {
super::list::LIST_ATTEMPTS
}
pub(crate) fn limit_read_chunks(&self, per_version: usize, bytes: usize) {
self.shared.ahead.limit(per_version, bytes);
}
pub(crate) fn read_chunk_bytes(&self) -> usize {
self.shared.ahead.held()
}
pub(crate) fn read_chunk_waiters(&self) -> usize {
self.shared.ahead.waiting()
}
pub(crate) async fn one_object(&self, a: &str, b: &str) -> bool {
self.shared
.one_object(a, b, &Retry::until(&self.shared.jobs.stop))
.await
.expect("the store answers")
.is_some()
}
pub(crate) fn overlay_len(&self) -> usize {
self.shared.overlay.len()
}
pub(crate) fn parks(&self) -> usize {
self.shared.overlay.parks()
}
pub(crate) fn waiting_for(&self, key: &str) -> usize {
self.shared.overlay.waiting_for(key)
}
pub(crate) fn key_in_use(&self, key: &str) -> bool {
self.shared.overlay.in_use(key)
}
pub(crate) fn hooks(&self) -> &super::cachedir::Hooks {
&self
.shared
.local
.as_ref()
.expect("a writable backend")
.hooks
}
pub(crate) fn hold_uploads(&self, held: bool) {
self.shared
.jobs
.held
.store(held, std::sync::atomic::Ordering::SeqCst);
self.shared.overlay.queue().wake();
}
pub(crate) fn hold_sweeps(&self, held: bool) {
self.shared
.jobs
.sweeps_held
.store(held, std::sync::atomic::Ordering::SeqCst);
self.shared.overlay.queue().wake();
}
pub(crate) fn pause_after_hash(&self) -> (Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>) {
gates(&self.shared.jobs.pause)
}
pub(crate) fn pause_after_store(&self) -> (Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>) {
gates(&self.shared.jobs.pause_stored)
}
pub(crate) fn pause_after_conflict(
&self,
) -> (Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>) {
gates(&self.shared.jobs.pause_conflict)
}
pub(crate) fn cached_object(&self, key: &str) -> bool {
self.shared
.cache()
.known(key, tokio::time::Instant::now())
.is_some()
}
pub(crate) fn cached_listing(&self, dir: &str) -> Option<Vec<(String, bool)>> {
let listing = self
.shared
.cache()
.listing(dir, tokio::time::Instant::now())?;
Some(
listing
.rows
.iter()
.map(|row| (row.name.clone(), row.is_dir()))
.collect(),
)
}
pub(crate) fn pause_after_lookup(
&self,
) -> (Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>) {
gates(&self.shared.jobs.pause_found)
}
pub(crate) fn pause_after_reserve(
&self,
) -> (Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>) {
gates(&self.shared.jobs.pause_reserved)
}
pub(crate) fn pause_after_batch(&self) -> (Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>) {
gates(&self.shared.jobs.pause_batch)
}
pub(crate) fn pause_before_create(
&self,
) -> (Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>) {
gates(&self.shared.jobs.pause_create)
}
pub(crate) fn pause_after_listing(
&self,
) -> (Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>) {
gates(&self.shared.jobs.pause_listed)
}
pub(crate) fn pause_after_rows(&self) -> (Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>) {
gates(&self.shared.jobs.pause_rows)
}
pub(crate) fn pause_after_watch(&self) -> (Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>) {
gates(&self.shared.jobs.pause_watch)
}
pub(crate) fn pause_after_below(&self) -> (Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>) {
gates(&self.shared.jobs.pause_below)
}
pub(crate) fn change_listings(&self, reads: usize) {
self.shared
.jobs
.churn
.store(reads, std::sync::atomic::Ordering::SeqCst);
}
pub(crate) fn pause_before_close_seal(
&self,
) -> (Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>) {
gates(&self.shared.jobs.pause_close)
}
pub(crate) fn saves(&self) -> tokio::sync::watch::Receiver<usize> {
self.shared.jobs.saves.subscribe()
}
pub(crate) fn saves_at_once(&self) -> usize {
super::jobs::SAVES_AT_ONCE
}
#[cfg(unix)]
pub(crate) fn descriptor_rests(&self) -> usize {
self.shared
.jobs
.descriptor_rests
.load(std::sync::atomic::Ordering::SeqCst)
}
pub(crate) fn data_open(&self, key: &str) -> Option<bool> {
let entry = self.shared.overlay.peek(key)?;
let state = entry.state();
state.local().map(|local| local.file.is_open())
}
pub(crate) fn panic_dissolve(&self) {
self.shared.jobs.panic_dissolve.raise();
}
pub(crate) fn panic_read_base(&self) {
self.shared.jobs.panic_read_base.raise();
}
pub(crate) fn waits(&self) -> usize {
self.shared
.jobs
.waits
.load(std::sync::atomic::Ordering::SeqCst)
}
pub(crate) fn limit_copy(&self, bytes: u64) {
self.shared.jobs.limit_copy(bytes);
}
pub(crate) fn pause_after_landing(
&self,
) -> (Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>) {
gates(&self.shared.jobs.pause_landed)
}
pub(crate) fn worker_exited(&self) -> tokio::sync::watch::Receiver<bool> {
self.shared.jobs.exited.subscribe()
}
pub(crate) fn panic_worker(&self) {
self.shared.jobs.panic_worker.raise();
self.shared.overlay.queue().wake();
}
pub(crate) fn hold_io(&self, key: &str) -> Option<IoHold> {
let entry = self.shared.overlay.peek(key)?;
let (locked, wait) = std::sync::mpsc::channel();
let (release, released) = std::sync::mpsc::channel::<()>();
let thread = std::thread::spawn(move || {
let _io = entry.lock_io();
let _ = locked.send(());
let _ = released.recv();
});
wait.recv().ok()?;
Some(IoHold {
release: Some(release),
thread: Some(thread),
})
}
}
#[cfg(test)]
fn gates(
slot: &Mutex<Option<super::jobs::Gates>>,
) -> (Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>) {
let gates = (
Arc::new(tokio::sync::Notify::new()),
Arc::new(tokio::sync::Notify::new()),
);
*slot.lock().unwrap_or_else(PoisonError::into_inner) = Some(gates.clone());
gates
}
#[cfg(test)]
pub(crate) struct IoHold {
release: Option<std::sync::mpsc::Sender<()>>,
thread: Option<std::thread::JoinHandle<()>>,
}
#[cfg(test)]
impl Drop for IoHold {
fn drop(&mut self) {
self.release.take();
if let Some(thread) = self.thread.take() {
let _ = thread.join();
}
}
}
pub(super) fn changes(opts: &OpenOptions) -> bool {
opts.write || opts.write_attributes || opts.delete_on_close || opts.intent != OpenIntent::Open
}
#[async_trait]
impl ShareBackend for S3Backend {
async fn open(
&self,
path: &SmbPath,
opts: OpenOptions,
) -> SmbResult<(Box<dyn Handle>, OpenAction)> {
self.shared.open(path, opts).await
}
async fn unlink(&self, path: &SmbPath) -> SmbResult<()> {
self.shared.unlink(path).await
}
async fn rename(&self, from: &SmbPath, to: &SmbPath, replace_if_exists: bool) -> SmbResult<()> {
self.shared.rename(from, to, replace_if_exists).await
}
fn capabilities(&self) -> BackendCapabilities {
BackendCapabilities {
is_read_only: self.shared.read_only,
case_sensitive: !self.shared.case_insensitive,
..BackendCapabilities::default()
}
}
async fn volume_info(&self) -> SmbResult<VolumeInfo> {
let Some(local) = self.shared.local.clone() else {
return Ok(VolumeInfo::default());
};
tokio::task::spawn_blocking(move || local.volume_info())
.await
.map_err(|e| SmbError::Io(io::Error::other(e)))?
.map_err(SmbError::Io)
}
}