Skip to main content

tinystore/blobs/
files.rs

1//! A set of files by path, as a program opens it: `store.files("avatars")`,
2//! or `db.files("packages")` in a database's file.
3
4use std::collections::BTreeMap;
5use std::fmt;
6use std::sync::Arc;
7use std::time::Duration;
8
9use rusqlite::{OptionalExtension, params};
10
11use super::change::{Change, Condition, Content, Place, Version, WhenThere, hidden};
12use super::engine::Blobs;
13use super::info::{FileInfo, FileRow, OCTETS, file_columns, meta_text};
14use super::paths::Folder;
15use super::read::StoredFile;
16use super::upload::Upload;
17#[cfg(feature = "async")]
18use crate::memory::Waiting;
19use crate::sqlite::{Tx, sql_error};
20use crate::{Error, Key, Result, Store};
21
22const SET_EXPIRES: &str = "update _tinystore_blobs_files set expires = ?3 where set_id = ?1 and path = ?2";
23/// A content type's bytes at most.
24const MAX_TYPE: usize = 256;
25/// Meta's names and values together, at most.
26const MAX_META: usize = 2 << 10;
27
28/// What opens a set of files: its name, and the term and the bound of the
29/// files written in it.
30#[derive(Debug)]
31pub struct FilesBuilder<'s> {
32    home: Home<'s>,
33    name: String,
34    ttl: Option<Duration>,
35    max_file_size: Option<u64>,
36}
37
38/// Where a set of files opens: in blobs.db, or in a database's file.
39#[derive(Debug)]
40enum Home<'s> {
41    Store(&'s Store),
42    #[cfg(feature = "sql")]
43    Database(Arc<crate::engine::SharedFile>),
44}
45
46impl<'s> FilesBuilder<'s> {
47    pub(crate) fn new(store: &'s Store, name: &str) -> Self {
48        FilesBuilder { home: Home::Store(store), name: name.to_owned(), ttl: None, max_file_size: None }
49    }
50
51    /// The set of files `name` kept in a database's file.
52    #[cfg(feature = "sql")]
53    pub(crate) fn in_file(shared: Arc<crate::engine::SharedFile>, name: &str) -> FilesBuilder<'static> {
54        FilesBuilder { home: Home::Database(shared), name: name.to_owned(), ttl: None, max_file_size: None }
55    }
56
57    /// The term of every file written without its own, counted from its
58    /// write; not a ceiling.
59    pub fn ttl(mut self, ttl: Duration) -> Self {
60        self.ttl = Some(ttl);
61        self
62    }
63
64    /// The largest file a write may leave: one past it is refused and leaves
65    /// nothing, and nothing stored is ever removed to make room.
66    pub fn max_file_size(mut self, bytes: u64) -> Self {
67        self.max_file_size = Some(bytes);
68        self
69    }
70
71    pub fn open(self) -> Result<Files> {
72        check_name(&self.name)?;
73        let blobs = match &self.home {
74            Home::Store(store) => Blobs::of(store)?,
75            #[cfg(feature = "sql")]
76            Home::Database(shared) => Blobs::in_file(shared)?,
77        };
78        let set = blobs.set_id(&self.name)?;
79        Ok(Files {
80            blobs,
81            name: Arc::from(self.name),
82            set,
83            folder: Folder::default(),
84            refused: None,
85            ttl: self.ttl,
86            max_file_size: self.max_file_size,
87        })
88    }
89}
90
91/// A set of files by path, or a folder of it: bytes written whole and
92/// replaced whole, each with a type, an ETag and a few strings of the
93/// program's.
94#[derive(Clone)]
95pub struct Files {
96    pub(crate) blobs: Arc<Blobs>,
97    name: Arc<str>,
98    pub(crate) set: i64,
99    pub(crate) folder: Folder,
100    /// A folder that is not one, refused by the first call that uses it.
101    refused: Option<Arc<Error>>,
102    ttl: Option<Duration>,
103    pub(crate) max_file_size: Option<u64>,
104}
105
106impl fmt::Debug for Files {
107    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108        write!(f, "Files({}, {:?})", self.name, self.folder.prefix())
109    }
110}
111
112impl Files {
113    /// The folder in this one that `segment` names: `folder("users").folder(42)`
114    /// is `users/42`, and its files' paths are its segments and then theirs.
115    pub fn folder(&self, segment: impl Key) -> Files {
116        let mut folder = self.clone();
117        if folder.refused.is_none() {
118            match self.folder.folder(&segment.text()) {
119                Ok(inner) => folder.folder = inner,
120                Err(error) => folder.refused = Some(Arc::new(self.fail(self.folder.prefix(), error))),
121            }
122        }
123        folder
124    }
125
126    /// A call on one path, its options before its verb:
127    /// `files.key("a.md").if_match(&etag).put(&text)`.
128    pub fn key(&self, path: &str) -> FileCall<'_> {
129        FileCall::new(self, path, Options::default())
130    }
131
132    /// Writes the file and replaces whatever the path held, at the moment it
133    /// returns.
134    pub fn put(&self, path: &str, bytes: impl AsRef<[u8]>) -> Result<FileInfo> {
135        self.key(path).put(bytes)
136    }
137
138    /// Writes the file only when the path holds none; says whether it did.
139    pub fn create(&self, path: &str, bytes: impl AsRef<[u8]>) -> Result<bool> {
140        self.key(path).create(bytes)
141    }
142
143    /// A file written a piece at a time, which appears at its `commit`.
144    pub fn upload(&self, path: &str) -> Result<Upload> {
145        self.key(path).upload()
146    }
147
148    /// The file at the path and the bytes it reads, which stay what they were
149    /// now through a replace, a delete or an expiry; none when there is none.
150    pub fn get(&self, path: &str) -> Result<Option<StoredFile>> {
151        let whole = self.whole(path)?;
152        StoredFile::open(self, &whole).map_err(|error| self.fail(&whole, error))
153    }
154
155    /// What the file at the path carries, none of its bytes.
156    pub fn head(&self, path: &str) -> Result<Option<FileInfo>> {
157        let whole = self.whole(path)?;
158        self.head_of(&whole).map_err(|error| self.fail(&whole, error))
159    }
160
161    /// Removes the file at the path; nothing to remove is not an error.
162    pub fn delete(&self, path: &str) -> Result<()> {
163        self.key(path).delete()
164    }
165
166    /// Writes the file at `from` at `to` too, sharing its bytes: no byte is
167    /// copied, and the two are two files from then on. A file at `to` is a
168    /// conflict: `key(to).if_match(etag).copy_from(from)` replaces the version
169    /// it names.
170    pub fn copy(&self, from: &str, to: &str) -> Result<FileInfo> {
171        self.key(to).copy_from(from)
172    }
173
174    /// Moves the file at `from` to `to` in one write, as `copy` writes it.
175    pub fn rename(&self, from: &str, to: &str) -> Result<FileInfo> {
176        self.key(to).rename_from(from)
177    }
178
179    /// Makes the file at the path expire `after` from now; says whether there
180    /// was one.
181    pub fn expire(&self, path: &str, after: Duration) -> Result<bool> {
182        let whole = self.whole(path)?;
183        self.expire_after(&whole, after).map_err(|error| self.fail(&whole, error))
184    }
185
186    /// A call on the path with `options` given whole, as a write another node
187    /// passed on asks it, and as an awaited call makes it in its first poll.
188    #[cfg(any(feature = "replication", feature = "async"))]
189    pub(crate) fn call(&self, path: &str, options: Options) -> FileCall<'_> {
190        FileCall::new(self, path, options)
191    }
192
193    /// Whether the set's file is a copy, whose home takes its writes.
194    #[cfg(feature = "replication")]
195    pub(crate) fn is_copy(&self) -> bool {
196        self.blobs.file.is_copy()
197    }
198
199    /// Passes a call on a copy of blobs' file to its home, and says whether
200    /// it wrote or found a file.
201    #[cfg(feature = "replication")]
202    pub(crate) fn pass_on(&self, call: &super::forward::Call<'_>) -> Result<bool> {
203        let set = super::forward::Set { name: &self.name, ttl: self.ttl, max_file_size: self.max_file_size };
204        super::forward::pass_on(&self.blobs.store()?, &set, call)
205    }
206
207    /// What the file at a whole path carries now, read here: a write passed
208    /// on answers once this copy holds it.
209    #[cfg(feature = "replication")]
210    pub(crate) fn head_here(&self, whole: &str) -> Result<Option<FileInfo>> {
211        self.head_of(whole)
212    }
213
214    pub(crate) fn whole(&self, path: &str) -> Result<String> {
215        self.usable()?;
216        self.folder.path(path).map_err(|error| self.fail(&format!("{}{path}", self.folder.prefix()), error))
217    }
218
219    /// Why a folder is not one, refused at the first call that uses it.
220    pub(crate) fn usable(&self) -> Result<()> {
221        self.refused.as_ref().map_or(Ok(()), |refused| Err(refused.duplicate()))
222    }
223
224    /// An error said of the files and the path it is about:
225    /// `files avatars: "users/42/1.png": conflict`.
226    pub(crate) fn fail(&self, path: &str, error: Error) -> Error {
227        error.within(format!("{path:?}")).within(format!("files {}", self.name))
228    }
229
230    pub(crate) fn describe(&self) -> String {
231        format!("files {}", self.name)
232    }
233
234    pub(crate) fn expiry(&self, ttl: Option<Duration>, now: i64) -> Option<i64> {
235        ttl.or(self.ttl).map(|ttl| now.saturating_add(crate::clock::millis(ttl)))
236    }
237
238    fn head_of(&self, whole: &str) -> Result<Option<FileInfo>> {
239        self.blobs.file.read(|connection| self.head_on(connection, whole))
240    }
241
242    /// What the file at a whole path carries, as `connection` reads it.
243    pub(super) fn head_on(&self, connection: &rusqlite::Connection, whole: &str) -> Result<Option<FileInfo>> {
244        const SELECT_HEAD: &str = concat!(
245            "select ",
246            file_columns!(),
247            " from _tinystore_blobs_files as f where f.set_id = ?1 and f.path = ?2 and (f.expires is null or f.expires > ?3) and not ",
248            hidden!()
249        );
250        let now = self.blobs.now();
251        let row = connection
252            .prepare_cached(SELECT_HEAD)
253            .and_then(|mut statement| statement.query_row(params![self.set, whole, now], FileRow::read).optional())
254            .map_err(|error| sql_error("blobs: a file's head", error))?;
255        row.map(|row| row.info(&self.folder)).transpose()
256    }
257
258    /// Publishes new bytes at the path when `condition` holds against what it
259    /// holds; says what it wrote, or nothing when a `create` found a file.
260    pub(crate) fn publish(
261        &self,
262        whole: &str,
263        options: &Options,
264        content: Content,
265        condition: Condition,
266    ) -> Result<Option<FileInfo>> {
267        let (bytes, publication) = self.publication(whole, options, content, condition);
268        let (info, freed) = self.blobs.file.write(bytes, publication)?;
269        self.blobs.remove_freed(&freed);
270        self.count_written(info.as_ref());
271        Ok(info)
272    }
273
274    /// What a publication of `content` at the path writes in its transaction,
275    /// and the bytes it adds to the commit.
276    pub(super) fn publication(
277        &self,
278        whole: &str,
279        options: &Options,
280        content: Content,
281        condition: Condition,
282    ) -> (usize, Writing<Option<FileInfo>>) {
283        let blobs = Arc::clone(&self.blobs);
284        let files = self.clone();
285        let (path, content_type, meta, ttl) =
286            (whole.to_owned(), options.content_type(), meta_text(&options.meta), options.ttl);
287        let bytes = match &content.place {
288            Place::Inline(body) => body.len(),
289            Place::File | Place::Shared => 0,
290        };
291        let publication = move |tx: &Tx<'_>| {
292            let mut change = Change::new(tx, &blobs);
293            let version =
294                Version { content, content_type, meta, modified: change.now, expires: files.expiry(ttl, change.now) };
295            if !change.write(files.set, &path, &version, &condition)? {
296                return Ok((None, Vec::new()));
297            }
298            Ok((Some(version.info(&files.folder, &path)?), change.freed))
299        };
300        (bytes, Box::new(publication))
301    }
302
303    pub(super) fn count_written(&self, info: Option<&FileInfo>) {
304        if let Some(info) = info {
305            self.blobs.probe.count("tinystore_blobs_written_total", &[], 1.0);
306            self.blobs.probe.count("tinystore_blobs_written_bytes_total", &[], info.size as f64);
307        }
308    }
309
310    /// Removes the files of the contents a write left without names, once it
311    /// committed: an unlink, which waits while a snapshot links files.
312    #[cfg(feature = "async")]
313    pub(crate) fn remove_freed(&self, freed: &[i64]) {
314        self.blobs.remove_freed(freed);
315    }
316
317    fn copy_to(&self, from: &str, to: &str, options: &Options, rename: bool) -> Result<FileInfo> {
318        refuse_onto_itself(from, to)?;
319        #[cfg(feature = "replication")]
320        if self.is_copy() {
321            self.pass_on(&super::forward::Call::Copy { from, to, options, rename })?;
322            return self.head_of(to)?.ok_or_else(|| Error::internal("a copy its home wrote that this copy lacks"));
323        }
324        let (info, freed) = self.blobs.file.write(0, self.copying(from, to, options, rename))?;
325        self.blobs.remove_freed(&freed);
326        Ok(info)
327    }
328
329    /// What a copy or a rename writes in its transaction.
330    fn copying(&self, from: &str, to: &str, options: &Options, rename: bool) -> Writing<FileInfo> {
331        let blobs = Arc::clone(&self.blobs);
332        let files = self.clone();
333        let (from, to, options) = (from.to_owned(), to.to_owned(), options.clone());
334        let condition = Condition { if_match: options.if_match.clone(), when_there: WhenThere::Conflict };
335        Box::new(move |tx| {
336            let mut change = Change::new(tx, &blobs);
337            let source =
338                change.current(files.set, &from)?.filter(|current| current.live(change.now)).ok_or_else(|| {
339                    Error::not_found(format!("no file at {from:?} to {}", if rename { "rename" } else { "copy" }))
340                })?;
341            let version = Version {
342                content: Content { id: source.content, size: source.size, sha256: source.sha256, place: Place::Shared },
343                content_type: options.content_type.clone().unwrap_or(source.content_type),
344                meta: if options.meta_given { meta_text(&options.meta) } else { source.meta },
345                modified: change.now,
346                expires: files.expiry(options.ttl, change.now),
347            };
348            change.write(files.set, &to, &version, &condition)?;
349            if rename {
350                change.remove(files.set, &from)?;
351            }
352            Ok((version.info(&files.folder, &to)?, change.freed))
353        })
354    }
355
356    fn delete_at(&self, whole: &str, if_match: Option<String>) -> Result<()> {
357        #[cfg(feature = "replication")]
358        if self.is_copy() {
359            return self
360                .pass_on(&super::forward::Call::Delete { path: whole, if_match: if_match.as_deref() })
361                .map(drop);
362        }
363        let ((), freed) = self.blobs.file.write(0, self.deleting(whole, if_match))?;
364        self.blobs.remove_freed(&freed);
365        Ok(())
366    }
367
368    /// What a delete writes in its transaction.
369    fn deleting(&self, whole: &str, if_match: Option<String>) -> Writing<()> {
370        let blobs = Arc::clone(&self.blobs);
371        let (set, path) = (self.set, whole.to_owned());
372        Box::new(move |tx| {
373            let mut change = Change::new(tx, &blobs);
374            if let Some(etag) = &if_match {
375                super::change::holds_etag(etag, change.current(set, &path)?.as_ref(), change.now)?;
376            }
377            change.remove(set, &path)?;
378            Ok(((), change.freed))
379        })
380    }
381
382    fn expire_after(&self, whole: &str, after: Duration) -> Result<bool> {
383        #[cfg(feature = "replication")]
384        if self.is_copy() {
385            return self.pass_on(&super::forward::Call::Expire { path: whole, after });
386        }
387        self.blobs.file.write(0, self.expiring(whole, after)).map(|(expired, _)| expired)
388    }
389
390    /// What an expiry writes in its transaction; it frees nothing.
391    fn expiring(&self, whole: &str, after: Duration) -> Writing<bool> {
392        let blobs = Arc::clone(&self.blobs);
393        let (set, path) = (self.set, whole.to_owned());
394        let after = crate::clock::millis(after);
395        Box::new(move |tx| {
396            let change = Change::new(tx, &blobs);
397            if !change.current(set, &path)?.is_some_and(|current| current.live(change.now)) {
398                return Ok((false, Vec::new()));
399            }
400            let expires = change.now.saturating_add(after);
401            change.execute(SET_EXPIRES, params![set, path, expires])?;
402            Ok((true, Vec::new()))
403        })
404    }
405
406    /// [`Files::expire`] for an awaited write, submitted: `done` is given its
407    /// answer once its commit ends, on the thread that answers the commit.
408    #[cfg(feature = "async")]
409    pub(crate) fn expire_then(&self, path: &str, after: Duration, done: impl Done<bool>) {
410        let whole = match self.whole(path) {
411            Ok(whole) => whole,
412            Err(error) => return done(Err(error)),
413        };
414        let expiring = self.expiring(&whole, after);
415        let files = self.clone();
416        self.blobs.file.submit(0, expiring, move |expired| done(expired.map_err(|error| files.fail(&whole, error))));
417    }
418}
419
420/// What a write submitted for an awaited call is given once its commit
421/// ends: its answer, and what it freed, whose files the caller removes off
422/// the thread that answers the commit, since the commits behind this one
423/// wait for that thread.
424#[cfg(feature = "async")]
425pub(crate) trait Done<T>: FnOnce(Result<(T, Freed)>) + Send + 'static {}
426
427#[cfg(feature = "async")]
428impl<T, F: FnOnce(Result<(T, Freed)>) + Send + 'static> Done<T> for F {}
429
430/// The contents a write left without names, whose files go once it commits.
431pub(crate) type Freed = Vec<i64>;
432
433/// What a write of blobs.db runs in its transaction: its answer, and what it
434/// freed.
435pub(super) type Writing<T> = Box<dyn FnOnce(&Tx<'_>) -> Result<(T, Freed)> + Send>;
436
437fn refuse_onto_itself(from: &str, to: &str) -> Result<()> {
438    if from == to {
439        return Err(Error::invalid("a copy or a rename onto its own path"));
440    }
441    Ok(())
442}
443
444/// A write's options, as a [`FileCall`] gathers them.
445#[derive(Clone, Debug, Default)]
446pub(crate) struct Options {
447    pub(crate) content_type: Option<String>,
448    pub(crate) meta: BTreeMap<String, String>,
449    pub(crate) meta_given: bool,
450    pub(crate) ttl: Option<Duration>,
451    pub(crate) if_match: Option<String>,
452    /// How long the body is, as a `Content-Length` says it.
453    pub(crate) size: Option<u64>,
454}
455
456impl Options {
457    fn content_type(&self) -> String {
458        self.content_type.clone().unwrap_or_else(|| OCTETS.to_owned())
459    }
460
461    fn check(&self) -> Result<()> {
462        if self.content_type.as_ref().is_some_and(|content_type| content_type.len() > MAX_TYPE) {
463            return Err(Error::invalid(format!("a content type over {MAX_TYPE} bytes")));
464        }
465        let meta: usize = self.meta.iter().map(|(name, value)| name.len() + value.len()).sum();
466        if meta > MAX_META {
467            return Err(Error::invalid(format!("meta of {meta} bytes, over 2 KiB")));
468        }
469        Ok(())
470    }
471}
472
473/// One path and the options of a call on it, which ends in its verb.
474#[derive(Debug)]
475#[must_use = "a call does nothing until its verb"]
476pub struct FileCall<'f> {
477    files: &'f Files,
478    path: String,
479    options: Options,
480    /// The database's transaction the call runs in, when it runs in one.
481    #[cfg(feature = "sql")]
482    tx: Option<&'f crate::Transaction<'f>>,
483}
484
485impl<'f> FileCall<'f> {
486    fn new(files: &'f Files, path: &str, options: Options) -> Self {
487        #[cfg(feature = "sql")]
488        return FileCall { files, path: path.to_owned(), options, tx: None };
489        #[cfg(not(feature = "sql"))]
490        FileCall { files, path: path.to_owned(), options }
491    }
492
493    /// A call inside a database's transaction.
494    #[cfg(feature = "sql")]
495    pub(super) fn inside(files: &'f Files, tx: &'f crate::Transaction<'f>, path: &str) -> Self {
496        FileCall { tx: Some(tx), ..FileCall::new(files, path, Options::default()) }
497    }
498
499    pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
500        self.options.content_type = Some(content_type.into());
501        self
502    }
503
504    /// A string of the program's the file carries, such as the name it was
505    /// uploaded as.
506    pub fn meta(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
507        self.options.meta.insert(name.into(), value.into());
508        self.options.meta_given = true;
509        self
510    }
511
512    /// The file's own term, from its write.
513    pub fn ttl(mut self, ttl: Duration) -> Self {
514        self.options.ttl = Some(ttl);
515        self
516    }
517
518    /// Writes only over the file with this ETag: one that changed, expired or
519    /// went since is a conflict, and nothing is written.
520    pub fn if_match(mut self, etag: impl Into<String>) -> Self {
521        self.options.if_match = Some(etag.into());
522        self
523    }
524
525    /// How long the body is; one longer or shorter is refused and leaves
526    /// nothing.
527    pub fn size(mut self, bytes: u64) -> Self {
528        self.options.size = Some(bytes);
529        self
530    }
531
532    pub fn put(self, bytes: impl AsRef<[u8]>) -> Result<FileInfo> {
533        let condition = Condition { if_match: self.options.if_match.clone(), when_there: WhenThere::Replace };
534        self.write_all(bytes.as_ref(), condition)?.ok_or_else(|| Error::internal("a put that wrote nothing"))
535    }
536
537    /// Writes only when the path holds no file; says whether it did.
538    pub fn create(self, bytes: impl AsRef<[u8]>) -> Result<bool> {
539        let condition = Condition { if_match: self.options.if_match.clone(), when_there: WhenThere::Skip };
540        self.write_all(bytes.as_ref(), condition).map(|info| info.is_some())
541    }
542
543    /// A file written a piece at a time, which appears at its `commit`.
544    pub fn upload(self) -> Result<Upload> {
545        let whole = self.checked()?;
546        #[cfg(feature = "sql")]
547        if self.tx.is_some() {
548            let refused = Error::invalid("an upload inside a transaction: put its bytes, which commit with it");
549            return Err(self.files.fail(&whole, refused));
550        }
551        Upload::start(self.files.clone(), whole, self.options)
552    }
553
554    pub fn delete(self) -> Result<()> {
555        let whole = self.files.whole(&self.path)?;
556        #[cfg(feature = "sql")]
557        if let Some(tx) = self.tx {
558            let deleting = self.files.deleting(&whole, self.options.if_match);
559            let deleted = super::tx::on_file(tx, self.files, |sql| deleting(sql).map(drop));
560            return deleted.map_err(|error| self.files.fail(&whole, error));
561        }
562        self.files.delete_at(&whole, self.options.if_match).map_err(|error| self.files.fail(&whole, error))
563    }
564
565    /// Writes the file at `from` here too, sharing its bytes.
566    pub fn copy_from(self, from: &str) -> Result<FileInfo> {
567        self.copied(from, false)
568    }
569
570    /// Moves the file at `from` here in one write.
571    pub fn rename_from(self, from: &str) -> Result<FileInfo> {
572        self.copied(from, true)
573    }
574
575    fn copied(self, from: &str, rename: bool) -> Result<FileInfo> {
576        let (source, target) = (self.files.whole(from)?, self.checked()?);
577        #[cfg(feature = "sql")]
578        if let Some(tx) = self.tx {
579            let copied = refuse_onto_itself(&source, &target).and_then(|()| {
580                let copying = self.files.copying(&source, &target, &self.options, rename);
581                super::tx::on_file(tx, self.files, |sql| copying(sql).map(|(info, _)| info))
582            });
583            return copied.map_err(|error| self.files.fail(&target, error));
584        }
585        self.files.copy_to(&source, &target, &self.options, rename).map_err(|error| self.files.fail(&target, error))
586    }
587
588    /// The whole path, its options checked, as each verb that writes bytes or
589    /// a row checks them first.
590    fn checked(&self) -> Result<String> {
591        let whole = self.files.whole(&self.path)?;
592        self.options.check().map_err(|error| self.files.fail(&whole, error))?;
593        Ok(whole)
594    }
595
596    /// The files, the path and the options: what an awaited call owns until
597    /// its first poll makes the call again with [`Files::call`].
598    #[cfg(feature = "async")]
599    pub(crate) fn into_parts(self) -> (&'f Files, String, Options) {
600        (self.files, self.path, self.options)
601    }
602
603    /// [`FileCall::upload`] waiting on no thread for the memory an upload
604    /// holds: `done` is given the upload once that memory fits, on whichever
605    /// thread gives memory back, or here when it fits now, and a path or an
606    /// option that is not one here at once. What this returns takes the
607    /// waiter out of line when it is dropped unanswered.
608    #[cfg(feature = "async")]
609    pub(crate) fn upload_then(self, done: impl FnOnce(Result<Upload>) + Send + 'static) -> Option<Waiting> {
610        let whole = match self.checked() {
611            Ok(whole) => whole,
612            Err(error) => {
613                done(Err(error));
614                return None;
615            }
616        };
617        let (files, options) = (self.files.clone(), self.options);
618        Some(Upload::reserve_then(self.files, move |reserved| {
619            let reserved = reserved.map_err(|error| files.fail(&whole, error));
620            done(reserved.and_then(|reserved| Upload::reserved(files, whole, options, reserved)));
621        }))
622    }
623
624    /// [`FileCall::delete`] for an awaited write, submitted: `done` is given
625    /// its answer once its commit ends, on the thread that answers the commit.
626    #[cfg(feature = "async")]
627    pub(crate) fn delete_then(self, done: impl Done<()>) {
628        let whole = match self.files.whole(&self.path) {
629            Ok(whole) => whole,
630            Err(error) => return done(Err(error)),
631        };
632        let deleting = self.files.deleting(&whole, self.options.if_match);
633        let files = self.files.clone();
634        self.files
635            .blobs
636            .file
637            .submit(0, deleting, move |deleted| done(deleted.map_err(|error| files.fail(&whole, error))));
638    }
639
640    /// [`FileCall::copy_from`], or with `rename` [`FileCall::rename_from`],
641    /// for an awaited write, submitted as [`FileCall::delete_then`] is.
642    #[cfg(feature = "async")]
643    pub(crate) fn copied_then(self, from: &str, rename: bool, done: impl Done<FileInfo>) {
644        let wholes = self.files.whole(from).and_then(|source| Ok((source, self.checked()?)));
645        let (source, target) = match wholes {
646            Ok(wholes) => wholes,
647            Err(error) => return done(Err(error)),
648        };
649        if let Err(error) = refuse_onto_itself(&source, &target) {
650            return done(Err(self.files.fail(&target, error)));
651        }
652        let copying = self.files.copying(&source, &target, &self.options, rename);
653        let files = self.files.clone();
654        self.files
655            .blobs
656            .file
657            .submit(0, copying, move |copied| done(copied.map_err(|error| files.fail(&target, error))));
658    }
659
660    /// Writes the whole file, or with `create` only where no file is; says
661    /// what it wrote, nothing when a create found a file. The wire's put, a
662    /// put another node passed on, and an awaited put of a large file, on the
663    /// store's pool.
664    #[cfg(any(feature = "wire", feature = "replication", feature = "async"))]
665    pub(crate) fn written(self, bytes: &[u8], create: bool) -> Result<Option<FileInfo>> {
666        let when_there = if create { WhenThere::Skip } else { WhenThere::Replace };
667        let condition = Condition { if_match: self.options.if_match.clone(), when_there };
668        self.write_all(bytes, condition)
669    }
670
671    fn write_all(self, bytes: &[u8], condition: Condition) -> Result<Option<FileInfo>> {
672        let whole = self.checked()?;
673        #[cfg(feature = "sql")]
674        if let Some(tx) = self.tx {
675            let written = super::tx::write_in(tx, self.files, (&whole, &self.options), bytes, condition);
676            return written.map_err(|error| self.files.fail(&whole, error));
677        }
678        let mut upload = Upload::start(self.files.clone(), whole, self.options)?;
679        upload.take(bytes)?;
680        upload.finish(condition)
681    }
682}
683
684/// A set's name, as a file's is: short and plain.
685fn check_name(name: &str) -> Result<()> {
686    crate::text::check_name("a set's", name)
687}
688
689#[cfg(test)]
690#[path = "files_tests.rs"]
691mod tests;