Skip to main content

smb_server/s3/
backend.rs

1//! The backend: a bucket served as a share.
2
3use std::fmt;
4use std::io;
5use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
6use std::time::{Duration, SystemTime};
7
8use async_trait::async_trait;
9
10use crate::backend::{
11    BackendCapabilities, Handle, OpenAction, OpenIntent, OpenOptions, ShareBackend, VolumeInfo,
12};
13use crate::error::{SmbError, SmbResult};
14use crate::path::SmbPath;
15
16use super::cache::MetaCache;
17use super::cachedir::CacheDir;
18use super::client::S3Client;
19use super::entry::Own;
20use super::error::S3Error;
21use super::jobs::{Guard, Jobs};
22use super::overlay::Overlay;
23use super::readahead::ReadAhead;
24use super::retry::Retry;
25
26/// Serves the objects of an S3 bucket as files and directories.
27///
28/// A file is an object, and its key is the path of the file below the
29/// prefix. A directory is an object with a zero-length body and a key that
30/// ends in `/`, or just the common prefix of the keys below it. A name that
31/// is both an object and a directory is the directory. Keys that no client
32/// could open, such as one with a `:` in a name or an empty path component,
33/// are left out of listings.
34///
35/// A file or directory has the times and attributes in the user metadata of
36/// its object: `mtime`, `btime`, `atime` and `ctime` as Unix seconds with up
37/// to nine fraction digits, and `smb-attributes` as hexadecimal. The write
38/// time is `mtime`, else `src_last_modified_millis` (Unix milliseconds), else
39/// the time the store last modified the object; a value that does not parse
40/// counts as missing. The other times default to the write time. A directory
41/// with no marker object has the time the backend was built. Listings read
42/// the metadata of the entries the backend has not seen yet, up to
43/// [`listing_metadata_max`](crate::S3BackendBuilder::listing_metadata_max) of
44/// them.
45///
46/// What the backend reads from the store is kept for
47/// [`metadata_ttl`](crate::S3BackendBuilder::metadata_ttl). Clones share the
48/// connection pool and that cache.
49///
50/// A read of a file requests the chunks of
51/// [`read_chunk`](crate::S3BackendBuilder::read_chunk) bytes that hold its
52/// bytes, and keeps them for later reads while a handle that reads their
53/// version is open. A chunk not kept is requested for the ETag the file last
54/// saw. If the object has another ETag by then, the read looks the object up
55/// again and reads that version, and the file reports that version's size and
56/// times from then on. An object without an ETag is read as asked for, with
57/// no chunks, and a read fails once the answer has an ETag, or a size or
58/// modification time that differs from what the file was opened with.
59///
60/// A writable backend keeps what clients change in its cache directory: the
61/// bytes written to a file, and the times and attributes set on files and
62/// directories. Bytes written and size changes reach the disk when a client
63/// flushes the file, when the last handle open on the file closes, or when
64/// the backend starts to store it. The record of a closed file is written in
65/// the background. After a restart a file has what was last recorded: one
66/// made and never recorded is gone, and an object changed and never recorded
67/// reads as the bucket has it. A truncate below the length last recorded is
68/// recorded at once. Times and attributes reach the disk at once, except
69/// those of a file the backend holds bytes of, which reach it when the file
70/// is recorded. The share root keeps its times and attributes in memory. A
71/// read returns the bytes written and gets the rest from the store; it fails
72/// when it needs bytes of the store and the object under the file changed
73/// since the file was opened. If the backend stored the file meanwhile, the
74/// read returns the bytes from the object it stored. What the backend holds
75/// shows in lookups and listings at once. A directory made through the share
76/// has its marker object put in the store before the open returns. A file
77/// that is deleted or renamed is gone or has its new name in the share at
78/// once, and the bucket follows in the background.
79///
80/// A directory can be deleted when nothing is below it, and renamed with
81/// everything below it. The share shows the result at once. The objects of a
82/// renamed directory are copied and the old keys deleted in the background,
83/// and the directory and every directory below it have a marker object in
84/// the new place. Both calls wait for the requests in flight that delete keys
85/// below the directory, and fail with an I/O error once
86/// [`request_timeout`](crate::S3BackendBuilder::request_timeout) has passed.
87/// Both fail with `AccessDenied` for the share root. A delete fails with
88/// `NotEmpty` if the backend holds a change below the directory, or the
89/// bucket has an object there that is not to be deleted. A rename fails with
90/// `AccessDenied` and changes nothing if the directory holds more than
91/// [`max_dir_rename_objects`](crate::S3BackendBuilder::max_dir_rename_objects)
92/// objects, if a key below it cannot move, or if the move is too large for
93/// one record in the cache directory. A key cannot move if no client could
94/// open its name, if another key lands on the same name, or, when the rename
95/// changes only the case of the name, if the parent lists a directory of each
96/// spelling and neither is to be deleted. Both fail with `Sharing` if the
97/// directory, one above it or one below it is being renamed or deleted; a
98/// rename also if a directory below it is still being made, or if the keys
99/// below it keep changing while they are listed. While a directory is being
100/// renamed or checked for a delete, a create or a rename that lands below it
101/// fails with `Sharing`. While a rename moves the entries, so does an open of
102/// an existing name below it that the backend holds nothing of.
103///
104/// A file the backend holds bytes of is stored in the bucket in the
105/// background, [`upload_delay`](crate::S3BackendBuilder::upload_delay) after
106/// its last change, open or not. A file of up to
107/// [`part_size`](crate::S3BackendBuilder::part_size) bytes goes up in one
108/// request, a larger one as a multipart upload. The object gets the times and
109/// attributes of the file and keeps the other metadata it had. A file that has
110/// not changed since it was stored loses the bytes the backend held, and is
111/// read from the bucket. After a change to a file, the upload under way
112/// starts no more requests, a multipart upload is aborted, and a request
113/// already sent may still store the earlier content. Another upload starts
114/// after the delay. Times and attributes set on a file the backend holds no
115/// bytes of are stored by copying the object onto itself with the new
116/// metadata, and those set on a directory by putting its marker object, which
117/// a directory without one gets. If the store refuses to copy an object onto
118/// itself, an object of up to `part_size` bytes is read and put again, and the
119/// times and attributes of a larger one are not stored, with a warning in the
120/// log.
121///
122/// Before it stores a file that was changed in part, the backend reads the
123/// rest of its bytes from the object. If the object has changed or is gone by
124/// then, the file moves to the `conflicts` directory of the cache directory
125/// with an error in the log, and the bucket keeps what it has. If the move
126/// fails, the file stays and shows in [`failures`](S3Backend::failures). A
127/// file whose bytes are all local replaces the object with no check of what
128/// the bucket holds.
129///
130/// An upload, or the delete of the old keys of a renamed file, fails for good
131/// when the store refuses a request in a way trying again cannot fix, or when
132/// the cache directory cannot be read or written. It is logged, shows in
133/// [`failures`](S3Backend::failures), and is tried again when the next backend
134/// is built on the cache directory. That backend stores the files and
135/// directory markers an earlier one left without waiting for the upload
136/// delay, and aborts the multipart uploads the earlier one left running. A
137/// bucket should have a lifecycle rule that aborts incomplete multipart
138/// uploads. [`sync`](S3Backend::sync) waits until what the backend holds for
139/// the bucket has reached it.
140///
141/// A renamed file is stored at its new key, and the old key is deleted once
142/// the new key holds its content. A file the backend holds no bytes of is
143/// copied within the bucket with the metadata the object had, in parts above
144/// 5 GiB. The object of a deleted file is deleted in the background, in
145/// batches, once no file has been deleted for
146/// [`upload_delay`](crate::S3BackendBuilder::upload_delay), and at most a
147/// minute after the first of them was due. A file made again under the exact
148/// name of one that was deleted replaces the object, and the object is not
149/// deleted. Before the backend deletes an object it puts a marker object for
150/// each directory above it that would be left with no object, so a directory
151/// does not vanish with its last file. If the store answers the marker with
152/// `ObjectParentIsFile` or `ExistingObjectIsDirectory`, the directory is left
153/// without a marker; if it refuses the marker any other way, the object stays
154/// in the bucket and [`sync`](S3Backend::sync) fails (`OperationAborted` is
155/// tried again). A file is stored after the marker of a directory of its name
156/// is deleted, and a marker is put after the object of a file of its name is
157/// deleted. A directory made at the name of a file that is to be deleted shows
158/// at once, and its marker follows the delete. A write whose wait for such a
159/// delete would be a wait for the write itself, as when a file takes the name
160/// of the directory it was the only file of, is made without the wait, and the
161/// store takes it or refuses it. A delete the store refused for good, or one
162/// that only a file or directory that failed owns, is not waited for.
163///
164/// Files renamed in a ring, as when two names swap through a third, are
165/// stored in turn. For each ring, the backend downloads one file and uploads
166/// it again, and that file has to fit in the free space of the cache
167/// directory.
168///
169/// When names match without regard to case, which is the default, a job that
170/// stores a file or a directory marker and a request that deletes keys wait
171/// for each other if their keys differ in case only, and for a file that still
172/// copies from such a key. Creating a directory waits the same way for the
173/// requests in flight, and fails with an I/O error once
174/// [`request_timeout`](crate::S3BackendBuilder::request_timeout) has passed.
175/// Keys that differ in case only can go out in one delete request. A store
176/// that treats such names as one name keeps the object under its old spelling
177/// when a file is renamed to a new spelling of its name. Before it deletes an
178/// object whose name differs in case only from the name of a file the backend
179/// holds, and when it has just stored a file or a directory marker under a
180/// name that differs in case only from an object it is to delete, the backend
181/// asks the store for both names: if they have the same size, ETag and
182/// modification time and are not both listed, they are one object, and it is
183/// not deleted. A rename of a directory asks the same for each object below it
184/// that differs in case only from an object to delete, and does not move the
185/// object if the two are one. With
186/// [`case_insensitive(false)`](crate::S3BackendBuilder::case_insensitive) the
187/// store has to keep case.
188///
189/// Dropping the last clone ends the uploads. The cache directory stays locked
190/// until the handles opened through the backend are closed and the requests
191/// in flight and the saves of closed files have ended. A change made through
192/// a handle after the last clone is dropped is not stored by this backend;
193/// the next backend built on the cache directory stores what the directory
194/// records.
195///
196/// Build one with [`S3Backend::builder`].
197#[derive(Clone)]
198pub struct S3Backend {
199    pub(super) shared: Arc<Shared>,
200    /// Ends the worker when the last clone is dropped.
201    pub(super) _worker: Arc<Guard>,
202}
203
204pub(super) struct Shared {
205    pub(super) client: S3Client,
206    /// The key of the share root: the prefix without its trailing `/`, or
207    /// empty.
208    pub(super) prefix: String,
209    pub(super) case_insensitive: bool,
210    pub(super) request_timeout: Duration,
211    pub(super) listing_metadata_max: usize,
212    /// Most HEAD requests a listing has in flight.
213    pub(super) head_concurrency: usize,
214    /// The time of the share root and of directories without a marker.
215    pub(super) built: SystemTime,
216    pub(super) cache: Mutex<MetaCache>,
217    /// The size of the requests that read file data.
218    pub(super) read_chunk: u64,
219    /// The most objects a renamed directory may hold.
220    pub(super) max_dir_rename_objects: usize,
221    /// The chunks read requests brought, shared by every handle.
222    pub(super) ahead: Arc<ReadAhead>,
223    pub(super) read_only: bool,
224    /// What the backend holds for the paths that differ from the bucket, or
225    /// may.
226    pub(super) overlay: Arc<Overlay>,
227    /// The cache directory of a writable backend.
228    pub(super) local: Option<Arc<CacheDir>>,
229    /// The times and attributes of the share root, which the backend keeps
230    /// in memory.
231    pub(super) root_own: Mutex<Own>,
232    /// What the background jobs run with.
233    pub(super) jobs: Arc<Jobs>,
234}
235
236impl Shared {
237    /// The deadline of the store requests one call makes.
238    pub(super) fn retry(&self) -> Retry {
239        Retry::within(self.request_timeout)
240    }
241
242    /// Calls `check` until it answers `Some`, and again each time the overlay
243    /// changes. A `check` that fails fails the wait. Fails with `Io` once the
244    /// deadline of `retry` has passed.
245    pub(super) async fn await_clear<T>(
246        &self,
247        retry: &Retry,
248        mut check: impl FnMut() -> SmbResult<Option<T>>,
249    ) -> SmbResult<T> {
250        let mut progress = self.overlay.subscribe();
251        loop {
252            if let Some(done) = check()? {
253                return Ok(done);
254            }
255            #[cfg(test)]
256            self.jobs
257                .waits
258                .fetch_add(1, std::sync::atomic::Ordering::SeqCst);
259            let changed = progress.changed();
260            let woken = match retry.deadline() {
261                Some(deadline) => tokio::time::timeout_at(deadline, changed)
262                    .await
263                    .map_err(|_| S3Error::DeadlineExceeded.into_smb_error())?,
264                None => changed.await,
265            };
266            woken.map_err(|e| SmbError::Io(io::Error::other(e)))?;
267        }
268    }
269
270    /// The cache. Never held across an await.
271    pub(super) fn cache(&self) -> MutexGuard<'_, MetaCache> {
272        self.cache.lock().unwrap_or_else(PoisonError::into_inner)
273    }
274
275    /// The cache directory. A backend that is read-only has none, and
276    /// changes fail as refused.
277    pub(super) fn local(&self) -> SmbResult<&CacheDir> {
278        self.local.as_deref().ok_or(SmbError::AccessDenied)
279    }
280
281    /// The times and attributes of the share root.
282    pub(super) fn root_own(&self) -> MutexGuard<'_, Own> {
283        self.root_own.lock().unwrap_or_else(PoisonError::into_inner)
284    }
285}
286
287impl S3Backend {
288    /// Waits until the files the backend holds bytes of, the times, attributes
289    /// and names it has not stored, the directories whose marker objects it has
290    /// not put, and the objects it is to delete are stored in or deleted from
291    /// the bucket. Only what the backend holds when the call begins counts. A
292    /// file that keeps changing delays the call, as it delays its upload. The
293    /// call waits as long as the uploads take, through failures that trying
294    /// again may fix and through a full disk of the cache directory.
295    ///
296    /// # Errors
297    ///
298    /// Fails with the error of one of those files or directories whose upload
299    /// failed for good, or whose changes moved to the `conflicts` directory of
300    /// the cache directory because the object changed or is gone in the
301    /// bucket, or with the error of an object the store refuses to delete.
302    /// Fails with [`S3Error::Stopped`] if the background worker has ended.
303    pub async fn sync(&self) -> Result<(), S3Error> {
304        self.shared.sync().await
305    }
306
307    /// The paths of the files and directories whose upload, or whose delete
308    /// of keys they own, failed for good, with the error of each. A path has
309    /// `/` between its names and no `/` before the first. A renamed file is on
310    /// the list with its new path.
311    ///
312    /// A file or directory on the list keeps what the backend holds for it,
313    /// which clients still see. It gets no other upload until the next backend
314    /// is built on the cache directory, which tries it again. A file that
315    /// moved to the `conflicts` directory is not on the list. Nor is the
316    /// object of a file that was deleted, or replaced by a rename, when the
317    /// store refuses to delete it: that is logged and fails
318    /// [`sync`](Self::sync).
319    #[must_use]
320    pub fn failures(&self) -> Vec<(String, S3Error)> {
321        self.shared.overlay.failures(&self.shared.prefix)
322    }
323}
324
325impl fmt::Debug for S3Backend {
326    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
327        f.debug_struct("S3Backend")
328            .field("client", &self.shared.client)
329            .field("prefix", &self.shared.prefix)
330            .finish_non_exhaustive()
331    }
332}
333
334#[cfg(test)]
335impl S3Backend {
336    /// Empties the listing cache and bounds it to `rows` rows.
337    pub(crate) fn limit_listing_rows(&self, rows: usize) {
338        self.shared.cache().limit_rows(rows);
339    }
340
341    /// How many reads of a directory listing are under way.
342    pub(crate) fn listing_reads(&self) -> usize {
343        self.shared.cache().reads()
344    }
345
346    /// How many times a listing of a directory is read at most, when the
347    /// directory changes while it is.
348    pub(crate) fn listing_attempts() -> usize {
349        super::list::LIST_ATTEMPTS
350    }
351
352    /// Drops the chunks kept for reads and bounds them to `per_version` for
353    /// one version of an object and `bytes` in all.
354    pub(crate) fn limit_read_chunks(&self, per_version: usize, bytes: usize) {
355        self.shared.ahead.limit(per_version, bytes);
356    }
357
358    /// The bytes of chunks kept for reads.
359    pub(crate) fn read_chunk_bytes(&self) -> usize {
360        self.shared.ahead.held()
361    }
362
363    /// The reads that wait for a chunk another read is fetching.
364    pub(crate) fn read_chunk_waiters(&self) -> usize {
365        self.shared.ahead.waiting()
366    }
367
368    /// Whether the store holds the keys `a` and `b`, which differ in case
369    /// only, as one object.
370    pub(crate) async fn one_object(&self, a: &str, b: &str) -> bool {
371        self.shared
372            .one_object(a, b, &Retry::until(&self.shared.jobs.stop))
373            .await
374            .expect("the store answers")
375            .is_some()
376    }
377
378    /// The files and directories the overlay holds.
379    pub(crate) fn overlay_len(&self) -> usize {
380        self.shared.overlay.len()
381    }
382
383    /// How many times a job was put off because a key stood in its way.
384    pub(crate) fn parks(&self) -> usize {
385        self.shared.overlay.parks()
386    }
387
388    /// How many jobs wait for the slot of `key` to clear.
389    pub(crate) fn waiting_for(&self, key: &str) -> usize {
390        self.shared.overlay.waiting_for(key)
391    }
392
393    /// Whether a job writes a key of the slot of `key`, a file copies from
394    /// one, or a request deletes one.
395    pub(crate) fn key_in_use(&self, key: &str) -> bool {
396        self.shared.overlay.in_use(key)
397    }
398
399    /// What tests make the cache directory do.
400    pub(crate) fn hooks(&self) -> &super::cachedir::Hooks {
401        &self
402            .shared
403            .local
404            .as_ref()
405            .expect("a writable backend")
406            .hooks
407    }
408
409    /// Keeps the worker from starting jobs, or lets it start them again.
410    pub(crate) fn hold_uploads(&self, held: bool) {
411        self.shared
412            .jobs
413            .held
414            .store(held, std::sync::atomic::Ordering::SeqCst);
415        self.shared.overlay.queue().wake();
416    }
417
418    /// Keeps the worker from deleting keys no entry owns, or lets it delete
419    /// them again.
420    pub(crate) fn hold_sweeps(&self, held: bool) {
421        self.shared
422            .jobs
423            .sweeps_held
424            .store(held, std::sync::atomic::Ordering::SeqCst);
425        self.shared.overlay.queue().wake();
426    }
427
428    /// Makes the next job that has hashed a file wait: it notifies the first
429    /// `Notify`, and goes on when the second is notified.
430    pub(crate) fn pause_after_hash(&self) -> (Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>) {
431        gates(&self.shared.jobs.pause)
432    }
433
434    /// Makes the next job whose request has stored a file wait, as
435    /// [`pause_after_hash`](Self::pause_after_hash) does. If the backend is
436    /// dropped meanwhile, the job ends without noting what it stored.
437    pub(crate) fn pause_after_store(&self) -> (Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>) {
438        gates(&self.shared.jobs.pause_stored)
439    }
440
441    /// Makes the next job whose changes moved to the conflicts directory wait
442    /// once its entry has left the overlay, as
443    /// [`pause_after_hash`](Self::pause_after_hash) does.
444    pub(crate) fn pause_after_conflict(
445        &self,
446    ) -> (Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>) {
447        gates(&self.shared.jobs.pause_conflict)
448    }
449
450    /// Whether the metadata cache holds what a lookup of the object `key`
451    /// found.
452    pub(crate) fn cached_object(&self, key: &str) -> bool {
453        self.shared
454            .cache()
455            .known(key, tokio::time::Instant::now())
456            .is_some()
457    }
458
459    /// The names the metadata cache lists for the directory `dir`, each with
460    /// whether it is a directory, in order. `None` if it holds no listing.
461    pub(crate) fn cached_listing(&self, dir: &str) -> Option<Vec<(String, bool)>> {
462        let listing = self
463            .shared
464            .cache()
465            .listing(dir, tokio::time::Instant::now())?;
466        Some(
467            listing
468                .rows
469                .iter()
470                .map(|row| (row.name.clone(), row.is_dir()))
471                .collect(),
472        )
473    }
474
475    /// Makes the next lookup that found an object wait before it takes a hold
476    /// on the entry for it, as [`pause_after_hash`](Self::pause_after_hash)
477    /// does.
478    pub(crate) fn pause_after_lookup(
479        &self,
480    ) -> (Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>) {
481        gates(&self.shared.jobs.pause_found)
482    }
483
484    /// Makes the next rename wait after it has reserved its name, as
485    /// [`pause_after_hash`](Self::pause_after_hash) does.
486    pub(crate) fn pause_after_reserve(
487        &self,
488    ) -> (Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>) {
489        gates(&self.shared.jobs.pause_reserved)
490    }
491
492    /// Makes the next directory rename wait once its batch record is written
493    /// and its entries are at their new keys, before the entries get records
494    /// of their own, as [`pause_after_hash`](Self::pause_after_hash) does. If
495    /// the backend is dropped meanwhile, the entries are left to the batch
496    /// record.
497    pub(crate) fn pause_after_batch(&self) -> (Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>) {
498        gates(&self.shared.jobs.pause_batch)
499    }
500
501    /// Makes the next create wait once it has checked the directory it is in
502    /// and before it enters the overlay, as
503    /// [`pause_after_hash`](Self::pause_after_hash) does.
504    pub(crate) fn pause_before_create(
505        &self,
506    ) -> (Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>) {
507        gates(&self.shared.jobs.pause_create)
508    }
509
510    /// Makes the next directory rename wait once it has read the keys below
511    /// the directory, as [`pause_after_hash`](Self::pause_after_hash) does.
512    pub(crate) fn pause_after_listing(
513        &self,
514    ) -> (Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>) {
515        gates(&self.shared.jobs.pause_listed)
516    }
517
518    /// Makes the next listing of a directory wait once it has the rows of the
519    /// store, as [`pause_after_hash`](Self::pause_after_hash) does.
520    pub(crate) fn pause_after_rows(&self) -> (Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>) {
521        gates(&self.shared.jobs.pause_rows)
522    }
523
524    /// Makes the next listing of a directory wait once it has begun to note
525    /// the changes to the overlay and before it reads the entries of the
526    /// overlay, as [`pause_after_hash`](Self::pause_after_hash) does.
527    pub(crate) fn pause_after_watch(&self) -> (Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>) {
528        gates(&self.shared.jobs.pause_watch)
529    }
530
531    /// Makes the next listing of a directory wait once it has the entries of
532    /// the overlay below it, as [`pause_after_hash`](Self::pause_after_hash)
533    /// does.
534    pub(crate) fn pause_after_below(&self) -> (Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>) {
535        gates(&self.shared.jobs.pause_below)
536    }
537
538    /// Makes the next `reads` reads of a directory listing see the rows of the
539    /// directory change once they have them.
540    pub(crate) fn change_listings(&self, reads: usize) {
541        self.shared
542            .jobs
543            .churn
544            .store(reads, std::sync::atomic::Ordering::SeqCst);
545    }
546
547    /// Makes the next task that records a closed file wait before it takes
548    /// the locks of the file, as [`pause_after_hash`](Self::pause_after_hash)
549    /// does.
550    pub(crate) fn pause_before_close_seal(
551        &self,
552    ) -> (Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>) {
553        gates(&self.shared.jobs.pause_close)
554    }
555
556    /// How many tasks that record closed files are running.
557    pub(crate) fn saves(&self) -> tokio::sync::watch::Receiver<usize> {
558        self.shared.jobs.saves.subscribe()
559    }
560
561    /// How many tasks that record closed files sync data files at once, at
562    /// most.
563    pub(crate) fn saves_at_once(&self) -> usize {
564        super::jobs::SAVES_AT_ONCE
565    }
566
567    /// How many jobs ended to rest because no descriptor was left.
568    #[cfg(unix)]
569    pub(crate) fn descriptor_rests(&self) -> usize {
570        self.shared
571            .jobs
572            .descriptor_rests
573            .load(std::sync::atomic::Ordering::SeqCst)
574    }
575
576    /// Whether the data file of the entry for `key` has a descriptor open, or
577    /// `None` if the entry has no data file.
578    pub(crate) fn data_open(&self, key: &str) -> Option<bool> {
579        let entry = self.shared.overlay.peek(key)?;
580        let state = entry.state();
581        state.local().map(|local| local.file.is_open())
582    }
583
584    /// Makes the task that records the entries of the next moved directory
585    /// panic.
586    pub(crate) fn panic_dissolve(&self) {
587        self.shared.jobs.panic_dissolve.raise();
588    }
589
590    /// Makes the tasks that read the metadata of the objects of a moved
591    /// directory panic.
592    pub(crate) fn panic_read_base(&self) {
593        self.shared.jobs.panic_read_base.raise();
594    }
595
596    /// How many times a call waited for requests in flight or keys to clear.
597    pub(crate) fn waits(&self) -> usize {
598        self.shared
599            .jobs
600            .waits
601            .load(std::sync::atomic::Ordering::SeqCst)
602    }
603
604    /// Lowers the size of the largest object one copy request takes.
605    pub(crate) fn limit_copy(&self, bytes: u64) {
606        self.shared.jobs.limit_copy(bytes);
607    }
608
609    /// Makes the next job that has stored an entry's content wait before it
610    /// deletes the keys the entry owns, as
611    /// [`pause_after_hash`](Self::pause_after_hash) does.
612    pub(crate) fn pause_after_landing(
613        &self,
614    ) -> (Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>) {
615        gates(&self.shared.jobs.pause_landed)
616    }
617
618    /// Whether the worker has ended, which it does after the last clone of
619    /// the backend is dropped.
620    pub(crate) fn worker_exited(&self) -> tokio::sync::watch::Receiver<bool> {
621        self.shared.jobs.exited.subscribe()
622    }
623
624    /// Makes the worker panic.
625    pub(crate) fn panic_worker(&self) {
626        self.shared.jobs.panic_worker.raise();
627        self.shared.overlay.queue().wake();
628    }
629
630    /// Holds the `io` lock of the entry the overlay has for `key` until the
631    /// returned value is dropped.
632    pub(crate) fn hold_io(&self, key: &str) -> Option<IoHold> {
633        let entry = self.shared.overlay.peek(key)?;
634        let (locked, wait) = std::sync::mpsc::channel();
635        let (release, released) = std::sync::mpsc::channel::<()>();
636        let thread = std::thread::spawn(move || {
637            let _io = entry.lock_io();
638            let _ = locked.send(());
639            let _ = released.recv();
640        });
641        wait.recv().ok()?;
642        Some(IoHold {
643            release: Some(release),
644            thread: Some(thread),
645        })
646    }
647}
648
649/// Puts up new gates in `slot`.
650#[cfg(test)]
651fn gates(
652    slot: &Mutex<Option<super::jobs::Gates>>,
653) -> (Arc<tokio::sync::Notify>, Arc<tokio::sync::Notify>) {
654    let gates = (
655        Arc::new(tokio::sync::Notify::new()),
656        Arc::new(tokio::sync::Notify::new()),
657    );
658    *slot.lock().unwrap_or_else(PoisonError::into_inner) = Some(gates.clone());
659    gates
660}
661
662/// A hold on the `io` lock of an entry.
663#[cfg(test)]
664pub(crate) struct IoHold {
665    release: Option<std::sync::mpsc::Sender<()>>,
666    thread: Option<std::thread::JoinHandle<()>>,
667}
668
669#[cfg(test)]
670impl Drop for IoHold {
671    fn drop(&mut self) {
672        self.release.take();
673        if let Some(thread) = self.thread.take() {
674            let _ = thread.join();
675        }
676    }
677}
678
679/// Whether an open with `opts` may change the share.
680pub(super) fn changes(opts: &OpenOptions) -> bool {
681    opts.write || opts.write_attributes || opts.delete_on_close || opts.intent != OpenIntent::Open
682}
683
684#[async_trait]
685impl ShareBackend for S3Backend {
686    async fn open(
687        &self,
688        path: &SmbPath,
689        opts: OpenOptions,
690    ) -> SmbResult<(Box<dyn Handle>, OpenAction)> {
691        self.shared.open(path, opts).await
692    }
693
694    async fn unlink(&self, path: &SmbPath) -> SmbResult<()> {
695        self.shared.unlink(path).await
696    }
697
698    async fn rename(&self, from: &SmbPath, to: &SmbPath, replace_if_exists: bool) -> SmbResult<()> {
699        self.shared.rename(from, to, replace_if_exists).await
700    }
701
702    fn capabilities(&self) -> BackendCapabilities {
703        BackendCapabilities {
704            is_read_only: self.shared.read_only,
705            case_sensitive: !self.shared.case_insensitive,
706            ..BackendCapabilities::default()
707        }
708    }
709
710    async fn volume_info(&self) -> SmbResult<VolumeInfo> {
711        let Some(local) = self.shared.local.clone() else {
712            return Ok(VolumeInfo::default());
713        };
714        tokio::task::spawn_blocking(move || local.volume_info())
715            .await
716            .map_err(|e| SmbError::Io(io::Error::other(e)))?
717            .map_err(SmbError::Io)
718    }
719}