tinystore 0.10.0

A small storage runtime for applications on SQLite: SQL, key-value state, durable jobs, files, search, logs and metrics in one directory
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
//! A set of files by path, as a program opens it: `store.files("avatars")`,
//! or `db.files("packages")` in a database's file.

use std::collections::BTreeMap;
use std::fmt;
use std::sync::Arc;
use std::time::Duration;

use rusqlite::{OptionalExtension, params};

use super::cache::{Asked, Counted, WhenFull};
use super::change::{Change, Condition, Content, Place, Version, WhenThere, hidden};
use super::engine::Blobs;
use super::info::{FileInfo, FileRow, OCTETS, file_columns, meta_text};
use super::paths::Folder;
use super::read::StoredFile;
use super::upload::Upload;
use super::uses::{Seen, ceiled};
#[cfg(feature = "async")]
use crate::memory::Waiting;
use crate::sqlite::{Tx, sql_error};
use crate::{Error, Key, Result, Store};

const SET_EXPIRES: &str = "update _tinystore_blobs_files set expires = ?3 where set_id = ?1 and path = ?2";
/// A content type's bytes at most.
const MAX_TYPE: usize = 256;
/// Meta's names and values together, at most.
const MAX_META: usize = 2 << 10;

/// What opens a set of files: its name, the term and the bound of the files
/// written in it, and the ceiling of them all.
#[derive(Debug)]
pub struct FilesBuilder<'s> {
    home: Home<'s>,
    name: String,
    ttl: Option<Duration>,
    idle: Option<Duration>,
    max_file_size: Option<u64>,
    ceiling: Asked,
    /// Its reads record no use and its open writes no ceiling: a connection
    /// that only reads, and the command line's look from outside.
    observing: bool,
}

/// Where a set of files opens: in blobs.db, or in a database's file.
#[derive(Debug)]
enum Home<'s> {
    Store(&'s Store),
    #[cfg(feature = "sql")]
    Database(Arc<crate::engine::SharedFile>),
}

impl<'s> FilesBuilder<'s> {
    pub(crate) fn new(store: &'s Store, name: &str) -> Self {
        FilesBuilder::at(Home::Store(store), name)
    }

    /// The set of files `name` kept in a database's file.
    #[cfg(feature = "sql")]
    pub(crate) fn in_file(shared: Arc<crate::engine::SharedFile>, name: &str) -> FilesBuilder<'static> {
        FilesBuilder::at(Home::Database(shared), name)
    }

    fn at(home: Home<'s>, name: &str) -> Self {
        let name = name.to_owned();
        FilesBuilder {
            home,
            name,
            ttl: None,
            idle: None,
            max_file_size: None,
            ceiling: Asked::default(),
            observing: false,
        }
    }

    /// The term of every file written without its own, counted from its
    /// write; not a ceiling.
    pub fn ttl(mut self, ttl: Duration) -> Self {
        self.ttl = Some(ttl);
        self
    }

    /// The term of every file written without its own, counted from its last
    /// `get` or `head`, as a bucket's `idle` counts a key's; `ttl` and `idle`
    /// exclude each other.
    pub fn idle(mut self, idle: Duration) -> Self {
        self.idle = Some(idle);
        self
    }

    /// The largest file a write may leave: one past it is refused and leaves
    /// nothing, and nothing stored is ever removed to make room.
    pub fn max_file_size(mut self, bytes: u64) -> Self {
        self.max_file_size = Some(bytes);
        self
    }

    /// The most the set's files may hold together: a write past it removes
    /// the files used least recently until the set fits. The set keeps it, so
    /// that it holds for every handle; an open with another fails `conflict`,
    /// and [`Files::set_max_size`] changes it.
    pub fn max_size(mut self, bytes: u64) -> Self {
        self.ceiling.max_size = Some(bytes);
        self
    }

    /// What a write past `max_size` does: evicts, or with
    /// [`WhenFull::Refuse`] fails `limit` and removes nothing. Kept with the
    /// ceiling.
    pub fn when_full(mut self, when_full: WhenFull) -> Self {
        self.ceiling.when_full = Some(when_full);
        self
    }

    /// Opens the set for a look from outside: its reads record no use, and
    /// its open writes no ceiling.
    #[cfg(any(feature = "wire", feature = "client"))]
    pub(crate) fn observing(mut self) -> Self {
        self.observing = true;
        self
    }

    pub fn open(self) -> Result<Files> {
        check_name(&self.name)?;
        if self.ttl.is_some() && self.idle.is_some() {
            return Err(Error::invalid("ttl and idle exclude each other: a term from the write, or from the last use")
                .within(format!("files {}", self.name)));
        }
        let (blobs, beside) = match &self.home {
            Home::Store(store) => (Blobs::of(store)?, store.is_beside()),
            #[cfg(feature = "sql")]
            Home::Database(shared) => (Blobs::in_file(shared)?, false),
        };
        let set = blobs.set_id(&self.name)?;
        let observing = self.observing || beside;
        let files = Files {
            blobs,
            name: Arc::from(self.name),
            set,
            folder: Folder::default(),
            refused: None,
            ttl: self.ttl,
            max_file_size: self.max_file_size,
            policy: Arc::new(Policy { idle: self.idle, observing }),
        };
        self.ceiling.settle(&files, !observing).map_err(|error| error.within(files.describe()))?;
        Ok(files)
    }
}

/// A set of files by path, or a folder of it: bytes written whole and
/// replaced whole, each with a type, an ETag and a few strings of the
/// program's.
#[derive(Clone)]
pub struct Files {
    pub(crate) blobs: Arc<Blobs>,
    pub(super) name: Arc<str>,
    pub(crate) set: i64,
    pub(crate) folder: Folder,
    /// A folder that is not one, refused by the first call that uses it.
    refused: Option<Arc<Error>>,
    ttl: Option<Duration>,
    pub(crate) max_file_size: Option<u64>,
    policy: Arc<Policy>,
}

/// What the uses a set's reads record follow, shared by every folder of one
/// open: its `idle`, and whether it only looks. A read also records a use on
/// a set that keeps a ceiling, which its lookup reads in the set's row.
#[derive(Debug)]
struct Policy {
    idle: Option<Duration>,
    observing: bool,
}

impl fmt::Debug for Files {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Files({}, {:?})", self.name, self.folder.prefix())
    }
}

impl Files {
    /// The folder in this one that `segment` names: `folder("users").folder(42)`
    /// is `users/42`, and its files' paths are its segments and then theirs.
    pub fn folder(&self, segment: impl Key) -> Files {
        let mut folder = self.clone();
        if folder.refused.is_none() {
            match self.folder.folder(&segment.text()) {
                Ok(inner) => folder.folder = inner,
                Err(error) => folder.refused = Some(Arc::new(self.fail(self.folder.prefix(), error))),
            }
        }
        folder
    }

    /// A call on one path, its options before its verb:
    /// `files.key("a.md").if_match(&etag).put(&text)`.
    pub fn key(&self, path: &str) -> FileCall<'_> {
        FileCall::new(self, path, Options::default())
    }

    /// Writes the file and replaces whatever the path held, at the moment it
    /// returns.
    pub fn put(&self, path: &str, bytes: impl AsRef<[u8]>) -> Result<FileInfo> {
        self.key(path).put(bytes)
    }

    /// Writes the file only when the path holds none; says whether it did.
    pub fn create(&self, path: &str, bytes: impl AsRef<[u8]>) -> Result<bool> {
        self.key(path).create(bytes)
    }

    /// A file written a piece at a time, which appears at its `commit`.
    pub fn upload(&self, path: &str) -> Result<Upload> {
        self.key(path).upload()
    }

    /// The file at the path and the bytes it reads, which stay what they were
    /// now through a replace, a delete or an expiry; none when there is none.
    ///
    /// On a set with `idle` it renews the file's term, and on a set with a
    /// ceiling it moves the file up the eviction's order.
    pub fn get(&self, path: &str) -> Result<Option<StoredFile>> {
        let whole = self.whole(path)?;
        self.get_whole(&whole)
    }

    /// The file at a whole path, as [`Files::get`] finds it, its read a use.
    pub(crate) fn get_whole(&self, whole: &str) -> Result<Option<StoredFile>> {
        let opened = (|| {
            let Some((mut file, seen)) = StoredFile::open(self, whole)? else { return Ok(None) };
            if let Some(until) = self.used(whole, &seen)? {
                file.renewed(Blobs::time(until));
            }
            Ok(Some(file))
        })();
        opened.map_err(|error| self.fail(whole, error))
    }

    /// What the file at the path carries, none of its bytes. A use, as a
    /// `get` is: a conditional request answered `304` used the file.
    pub fn head(&self, path: &str) -> Result<Option<FileInfo>> {
        let whole = self.whole(path)?;
        let found = (|| {
            let Some((mut info, seen)) = self.head_seen(&whole)? else { return Ok(None) };
            if let Some(until) = self.used(&whole, &seen)? {
                info.expires = Some(Blobs::time(until));
            }
            Ok(Some(info))
        })();
        found.map_err(|error| self.fail(&whole, error))
    }

    /// Removes the file at the path; nothing to remove is not an error.
    pub fn delete(&self, path: &str) -> Result<()> {
        self.key(path).delete()
    }

    /// Writes the file at `from` at `to` too, sharing its bytes: no byte is
    /// copied, and the two are two files from then on. A file at `to` is a
    /// conflict: `key(to).if_match(etag).copy_from(from)` replaces the version
    /// it names.
    pub fn copy(&self, from: &str, to: &str) -> Result<FileInfo> {
        self.key(to).copy_from(from)
    }

    /// Moves the file at `from` to `to` in one write, as `copy` writes it.
    pub fn rename(&self, from: &str, to: &str) -> Result<FileInfo> {
        self.key(to).rename_from(from)
    }

    /// Makes the file at the path expire `after` from now; says whether there
    /// was one.
    pub fn expire(&self, path: &str, after: Duration) -> Result<bool> {
        let whole = self.whole(path)?;
        self.expire_after(&whole, after).map_err(|error| self.fail(&whole, error))
    }

    /// A call on the path with `options` given whole, as a write another node
    /// passed on asks it, and as an awaited call makes it in its first poll.
    #[cfg(any(feature = "replication", feature = "async"))]
    pub(crate) fn call(&self, path: &str, options: Options) -> FileCall<'_> {
        FileCall::new(self, path, options)
    }

    /// Whether the set's file is a copy, whose home takes its writes.
    #[cfg(feature = "replication")]
    pub(crate) fn is_copy(&self) -> bool {
        self.blobs.file.is_copy()
    }

    /// Passes a call on a copy of blobs' file to its home, and says whether
    /// it wrote or found a file.
    #[cfg(feature = "replication")]
    pub(crate) fn pass_on(&self, call: &super::forward::Call<'_>) -> Result<bool> {
        // an idle set's write gives its file the term a ttl would; its reads renew it here
        let ttl = self.ttl.or(self.policy.idle);
        let set = super::forward::Set { name: &self.name, ttl, max_file_size: self.max_file_size };
        super::forward::pass_on(&self.blobs.store()?, &set, call)
    }

    /// What the file at a whole path carries now, read here: a write passed
    /// on answers once this copy holds it.
    #[cfg(feature = "replication")]
    pub(crate) fn head_here(&self, whole: &str) -> Result<Option<FileInfo>> {
        self.head_of(whole)
    }

    pub(crate) fn whole(&self, path: &str) -> Result<String> {
        self.usable()?;
        self.folder.path(path).map_err(|error| self.fail(&format!("{}{path}", self.folder.prefix()), error))
    }

    /// Why a folder is not one, refused at the first call that uses it.
    pub(crate) fn usable(&self) -> Result<()> {
        self.refused.as_ref().map_or(Ok(()), |refused| Err(refused.duplicate()))
    }

    /// An error said of the files and the path it is about:
    /// `files avatars: "users/42/1.png": conflict`.
    pub(crate) fn fail(&self, path: &str, error: Error) -> Error {
        error.within(format!("{path:?}")).within(format!("files {}", self.name))
    }

    pub(crate) fn describe(&self) -> String {
        format!("files {}", self.name)
    }

    pub(crate) fn name(&self) -> &str {
        &self.name
    }

    pub(crate) fn expiry(&self, ttl: Option<Duration>, now: i64) -> Option<i64> {
        ttl.or(self.ttl).or(self.policy.idle).map(|ttl| now.saturating_add(crate::clock::millis(ttl)))
    }

    /// Whether a read of a row it `seen` records the use it makes: on a set
    /// with `idle` or a ceiling, unless the handle only looks.
    pub(super) fn records_uses(&self, seen: &Seen) -> bool {
        !self.policy.observing && (self.policy.idle.is_some() || seen.ceiled)
    }

    pub(super) fn idle(&self) -> Option<Duration> {
        self.policy.idle
    }

    /// Whose evictions a write counts.
    pub(super) fn counted(&self) -> Counted {
        Counted { set: self.set, name: Arc::clone(&self.name) }
    }

    #[cfg(feature = "replication")]
    fn head_of(&self, whole: &str) -> Result<Option<FileInfo>> {
        self.blobs.file.read(|connection| self.head_on(connection, whole))
    }

    /// What the file at a whole path carries, and what its read saw of its
    /// row, which a use it records is bound to.
    fn head_seen(&self, whole: &str) -> Result<Option<(FileInfo, Seen)>> {
        const SELECT_SEEN: &str = concat!(
            "select ",
            file_columns!(),
            ", f.revision, f.used, ",
            ceiled!(),
            " 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 ",
            hidden!()
        );
        let now = self.blobs.now();
        let row = self.blobs.file.read(|connection| {
            connection
                .prepare_cached(SELECT_SEEN)
                .and_then(|mut statement| {
                    let seen =
                        |row: &rusqlite::Row<'_>| Ok((FileRow::read(row)?, (row.get(7)?, row.get(8)?, row.get(9)?)));
                    statement.query_row(params![self.set, whole, now], seen).optional()
                })
                .map_err(|error| sql_error("blobs: a file's head", error))
        })?;
        row.map(|(row, (revision, used, ceiled)): (FileRow, (i64, Option<i64>, bool))| {
            let seen = Seen { revision, modified: row.modified, used, expires: row.expires, ceiled };
            Ok((row.info(&self.folder)?, seen))
        })
        .transpose()
    }

    /// What the file at a whole path carries, as `connection` reads it.
    #[cfg(any(feature = "replication", feature = "sql"))]
    pub(super) fn head_on(&self, connection: &rusqlite::Connection, whole: &str) -> Result<Option<FileInfo>> {
        const SELECT_HEAD: &str = concat!(
            "select ",
            file_columns!(),
            " 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 ",
            hidden!()
        );
        let now = self.blobs.now();
        let row = connection
            .prepare_cached(SELECT_HEAD)
            .and_then(|mut statement| statement.query_row(params![self.set, whole, now], FileRow::read).optional())
            .map_err(|error| sql_error("blobs: a file's head", error))?;
        row.map(|row| row.info(&self.folder)).transpose()
    }

    /// Publishes new bytes at the path when `condition` holds against what it
    /// holds; says what it wrote, or nothing when a `create` found a file.
    pub(crate) fn publish(
        &self,
        whole: &str,
        options: &Options,
        content: Content,
        condition: Condition,
    ) -> Result<Option<FileInfo>> {
        let (bytes, publication) = self.publication(whole, options, content, condition);
        let (info, freed) = self.blobs.file.write(bytes, publication)?;
        self.blobs.remove_freed(&freed);
        self.count_written(info.as_ref());
        Ok(info)
    }

    /// What a publication of `content` at the path writes in its transaction,
    /// and the bytes it adds to the commit.
    pub(super) fn publication(
        &self,
        whole: &str,
        options: &Options,
        content: Content,
        condition: Condition,
    ) -> (usize, Writing<Option<FileInfo>>) {
        let blobs = Arc::clone(&self.blobs);
        let files = self.clone();
        let (path, content_type, meta, ttl) =
            (whole.to_owned(), options.content_type(), meta_text(&options.meta), options.ttl);
        let bytes = match &content.place {
            Place::Inline(body) => body.len(),
            Place::File | Place::Shared => 0,
        };
        let publication = move |tx: &Tx<'_>| {
            let mut change = Change::new(tx, &blobs);
            let before = change.total(files.set)?.size;
            let version =
                Version { content, content_type, meta, modified: change.now, expires: files.expiry(ttl, change.now) };
            if !change.write(files.set, &path, &version, &condition)? {
                return Ok((None, Vec::new()));
            }
            change.fit(&files.counted(), (&path, version.content.size), before)?;
            Ok((Some(version.info(&files.folder, &path)?), change.freed))
        };
        (bytes, Box::new(publication))
    }

    pub(super) fn count_written(&self, info: Option<&FileInfo>) {
        if let Some(info) = info {
            self.blobs.probe.count("tinystore_blobs_written_total", &[], 1.0);
            self.blobs.probe.count("tinystore_blobs_written_bytes_total", &[], info.size as f64);
        }
    }

    /// Removes the files of the contents a write left without names, once it
    /// committed: an unlink, which waits while a snapshot links files.
    #[cfg(feature = "async")]
    pub(crate) fn remove_freed(&self, freed: &[i64]) {
        self.blobs.remove_freed(freed);
    }

    fn copy_to(&self, from: &str, to: &str, options: &Options, rename: bool) -> Result<FileInfo> {
        refuse_onto_itself(from, to)?;
        #[cfg(feature = "replication")]
        if self.is_copy() {
            self.pass_on(&super::forward::Call::Copy { from, to, options, rename })?;
            return self.head_of(to)?.ok_or_else(|| Error::internal("a copy its home wrote that this copy lacks"));
        }
        let (info, freed) = self.blobs.file.write(0, self.copying(from, to, options, rename))?;
        self.blobs.remove_freed(&freed);
        Ok(info)
    }

    /// What a copy or a rename writes in its transaction.
    fn copying(&self, from: &str, to: &str, options: &Options, rename: bool) -> Writing<FileInfo> {
        let blobs = Arc::clone(&self.blobs);
        let files = self.clone();
        let (from, to, options) = (from.to_owned(), to.to_owned(), options.clone());
        let condition = Condition { if_match: options.if_match.clone(), when_there: WhenThere::Conflict, fill: None };
        Box::new(move |tx| {
            let mut change = Change::new(tx, &blobs);
            let before = change.total(files.set)?.size;
            let source =
                change.current(files.set, &from)?.filter(|current| current.live(change.now)).ok_or_else(|| {
                    Error::not_found(format!("no file at {from:?} to {}", if rename { "rename" } else { "copy" }))
                })?;
            let version = Version {
                content: Content { id: source.content, size: source.size, sha256: source.sha256, place: Place::Shared },
                content_type: options.content_type.clone().unwrap_or(source.content_type),
                meta: if options.meta_given { meta_text(&options.meta) } else { source.meta },
                modified: change.now,
                expires: files.expiry(options.ttl, change.now),
            };
            change.write(files.set, &to, &version, &condition)?;
            if rename {
                change.remove(files.set, &from)?;
            }
            change.fit(&files.counted(), (&to, version.content.size), before)?;
            Ok((version.info(&files.folder, &to)?, change.freed))
        })
    }

    fn delete_at(&self, whole: &str, if_match: Option<String>) -> Result<()> {
        #[cfg(feature = "replication")]
        if self.is_copy() {
            return self
                .pass_on(&super::forward::Call::Delete { path: whole, if_match: if_match.as_deref() })
                .map(drop);
        }
        let ((), freed) = self.blobs.file.write(0, self.deleting(whole, if_match))?;
        self.blobs.remove_freed(&freed);
        Ok(())
    }

    /// What a delete writes in its transaction.
    fn deleting(&self, whole: &str, if_match: Option<String>) -> Writing<()> {
        let blobs = Arc::clone(&self.blobs);
        let (set, path) = (self.set, whole.to_owned());
        Box::new(move |tx| {
            let mut change = Change::new(tx, &blobs);
            if let Some(etag) = &if_match {
                super::change::holds_etag(etag, change.current(set, &path)?.as_ref(), change.now)?;
            }
            change.remove(set, &path)?;
            Ok(((), change.freed))
        })
    }

    fn expire_after(&self, whole: &str, after: Duration) -> Result<bool> {
        #[cfg(feature = "replication")]
        if self.is_copy() {
            return self.pass_on(&super::forward::Call::Expire { path: whole, after });
        }
        self.blobs.file.write(0, self.expiring(whole, after)).map(|(expired, _)| expired)
    }

    /// What an expiry writes in its transaction; it frees nothing.
    fn expiring(&self, whole: &str, after: Duration) -> Writing<bool> {
        let blobs = Arc::clone(&self.blobs);
        let (set, path) = (self.set, whole.to_owned());
        let after = crate::clock::millis(after);
        Box::new(move |tx| {
            let change = Change::new(tx, &blobs);
            if !change.current(set, &path)?.is_some_and(|current| current.live(change.now)) {
                return Ok((false, Vec::new()));
            }
            let expires = change.now.saturating_add(after);
            change.execute(SET_EXPIRES, params![set, path, expires])?;
            Ok((true, Vec::new()))
        })
    }

    /// [`Files::expire`] for an awaited write, submitted: `done` is given its
    /// answer once its commit ends, on the thread that answers the commit.
    #[cfg(feature = "async")]
    pub(crate) fn expire_then(&self, path: &str, after: Duration, done: impl Done<bool>) {
        let whole = match self.whole(path) {
            Ok(whole) => whole,
            Err(error) => return done(Err(error)),
        };
        let expiring = self.expiring(&whole, after);
        let files = self.clone();
        self.blobs.file.submit(0, expiring, move |expired| done(expired.map_err(|error| files.fail(&whole, error))));
    }
}

/// What a write submitted for an awaited call is given once its commit
/// ends: its answer, and what it freed, whose files the caller removes off
/// the thread that answers the commit, since the commits behind this one
/// wait for that thread.
#[cfg(feature = "async")]
pub(crate) trait Done<T>: FnOnce(Result<(T, Freed)>) + Send + 'static {}

#[cfg(feature = "async")]
impl<T, F: FnOnce(Result<(T, Freed)>) + Send + 'static> Done<T> for F {}

/// The contents a write left without names, whose files go once it commits.
pub(crate) type Freed = Vec<i64>;

/// What a write of blobs.db runs in its transaction: its answer, and what it
/// freed.
pub(super) type Writing<T> = Box<dyn FnOnce(&Tx<'_>) -> Result<(T, Freed)> + Send>;

fn refuse_onto_itself(from: &str, to: &str) -> Result<()> {
    if from == to {
        return Err(Error::invalid("a copy or a rename onto its own path"));
    }
    Ok(())
}

/// A write's options, as a [`FileCall`] gathers them.
#[derive(Clone, Debug, Default)]
pub(crate) struct Options {
    pub(crate) content_type: Option<String>,
    pub(crate) meta: BTreeMap<String, String>,
    pub(crate) meta_given: bool,
    pub(crate) ttl: Option<Duration>,
    pub(crate) if_match: Option<String>,
    /// How long the body is, as a `Content-Length` says it.
    pub(crate) size: Option<u64>,
    /// How long a getOrCreate's claim is renewed while its function runs.
    pub(crate) timeout: Option<Duration>,
    /// The run of a getOrCreate a write lands, by its owner.
    pub(crate) fill: Option<i64>,
}

impl Options {
    /// A write's condition: `when_there` with its ETag, or for a run of a
    /// getOrCreate its claim and an empty path.
    pub(super) fn condition(&self, when_there: WhenThere) -> Condition {
        let when_there = if self.fill.is_some() { WhenThere::Skip } else { when_there };
        Condition { if_match: self.if_match.clone(), when_there, fill: self.fill }
    }

    fn content_type(&self) -> String {
        self.content_type.clone().unwrap_or_else(|| OCTETS.to_owned())
    }

    pub(super) fn check(&self) -> Result<()> {
        if self.content_type.as_ref().is_some_and(|content_type| content_type.len() > MAX_TYPE) {
            return Err(Error::invalid(format!("a content type over {MAX_TYPE} bytes")));
        }
        let meta: usize = self.meta.iter().map(|(name, value)| name.len() + value.len()).sum();
        if meta > MAX_META {
            return Err(Error::invalid(format!("meta of {meta} bytes, over 2 KiB")));
        }
        Ok(())
    }
}

/// One path and the options of a call on it, which ends in its verb.
#[derive(Debug)]
#[must_use = "a call does nothing until its verb"]
pub struct FileCall<'f> {
    files: &'f Files,
    path: String,
    options: Options,
    /// The database's transaction the call runs in, when it runs in one.
    #[cfg(feature = "sql")]
    tx: Option<&'f crate::Transaction<'f>>,
}

impl<'f> FileCall<'f> {
    fn new(files: &'f Files, path: &str, options: Options) -> Self {
        #[cfg(feature = "sql")]
        return FileCall { files, path: path.to_owned(), options, tx: None };
        #[cfg(not(feature = "sql"))]
        FileCall { files, path: path.to_owned(), options }
    }

    /// A call inside a database's transaction.
    #[cfg(feature = "sql")]
    pub(super) fn inside(files: &'f Files, tx: &'f crate::Transaction<'f>, path: &str) -> Self {
        FileCall { tx: Some(tx), ..FileCall::new(files, path, Options::default()) }
    }

    pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
        self.options.content_type = Some(content_type.into());
        self
    }

    /// A string of the program's the file carries, such as the name it was
    /// uploaded as.
    pub fn meta(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
        self.options.meta.insert(name.into(), value.into());
        self.options.meta_given = true;
        self
    }

    /// The file's own term, from its write.
    pub fn ttl(mut self, ttl: Duration) -> Self {
        self.options.ttl = Some(ttl);
        self
    }

    /// Writes only over the file with this ETag: one that changed, expired or
    /// went since is a conflict, and nothing is written.
    pub fn if_match(mut self, etag: impl Into<String>) -> Self {
        self.options.if_match = Some(etag.into());
        self
    }

    /// How long the body is; one longer or shorter is refused and leaves
    /// nothing.
    pub fn size(mut self, bytes: u64) -> Self {
        self.options.size = Some(bytes);
        self
    }

    /// How long a `get_or_create`'s claim of the path is renewed while its
    /// function runs: 10 minutes unless said. A function still running then
    /// loses the claim within 30 s, and another call may run its own.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.options.timeout = Some(timeout);
        self
    }

    /// The file at the path, or, on a miss, the one `work` makes, written
    /// with the call's type and meta unless what it gives says its own.
    ///
    /// ```no_run
    /// # fn convert(doc: &str) -> tinystore::Result<Vec<u8>> { Ok(doc.as_bytes().to_vec()) }
    /// # fn main() -> tinystore::Result<()> {
    /// # let store = tinystore::Store::open("data", Default::default())?;
    /// # let (hash, doc) = ("7f3a", "lecture");
    /// let pages = store.files("pages").open()?;
    /// let page = pages.key(&format!("{hash}.pdf")).content_type("application/pdf").get_or_create(|| convert(doc))?;
    /// assert_eq!(page.info().content_type, "application/pdf");
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// While one call runs `work`, every other `get_or_create` of the path,
    /// in this process or through its server, waits for it and gets the file
    /// it wrote (BLOB-21). The call claims the path for 30 s and the store
    /// renews the claim while `work` runs, up to its [`timeout`](Self::timeout);
    /// what `work` gives lands only while the claim still holds the path and
    /// no file is there (BLOB-22). A put of the path meanwhile wins, and the
    /// calls get the put's file; a delete ends the claim, what `work` gave is
    /// dropped, and one of the calls runs it again, so `work` may run more
    /// than once. A failure of `work` is the answer of every call that waited
    /// for it, an error of the store's as it is and any other `unavailable`
    /// with its text, and the next call runs it again.
    ///
    /// Inside a database's transaction, or on a node's copy of blobs.db, it
    /// is `Invalid`; so is a call of the path inside its own `work`.
    pub fn get_or_create<T, E>(
        self,
        work: impl FnMut() -> std::result::Result<T, E>,
    ) -> std::result::Result<StoredFile, E>
    where
        T: Into<super::Fill>,
        E: From<Error> + fmt::Display + 'static,
    {
        let whole = self.to_get_or_create()?;
        super::filling::get_or_create(self.files, &whole, &self.options, work)
    }

    /// The whole path a getOrCreate claims, its options checked, or why it
    /// may not run here: inside a transaction its function would hold the
    /// writer, and a copy's claims are its home's.
    pub(crate) fn to_get_or_create(&self) -> Result<String> {
        let whole = self.checked()?;
        #[cfg(feature = "sql")]
        if self.tx.is_some() {
            let refused = Error::invalid("a getOrCreate inside a transaction, whose function would hold its writer");
            return Err(self.files.fail(&whole, refused));
        }
        #[cfg(feature = "replication")]
        if self.files.is_copy() {
            let refused = Error::invalid("a getOrCreate on a node's copy of blobs.db: call it at the file's home");
            return Err(self.files.fail(&whole, refused));
        }
        Ok(whole)
    }

    /// The write lands the run of a getOrCreate `owner` names: only while its
    /// claim holds the path, and only where no file is.
    #[cfg(feature = "wire")]
    pub(crate) fn filling(mut self, owner: i64) -> Self {
        self.options.fill = Some(owner);
        self
    }

    pub fn put(self, bytes: impl AsRef<[u8]>) -> Result<FileInfo> {
        let condition = self.options.condition(WhenThere::Replace);
        self.write_all(bytes.as_ref(), condition)?.ok_or_else(|| Error::internal("a put that wrote nothing"))
    }

    /// Writes only when the path holds no file; says whether it did.
    pub fn create(self, bytes: impl AsRef<[u8]>) -> Result<bool> {
        let condition = self.options.condition(WhenThere::Skip);
        self.write_all(bytes.as_ref(), condition).map(|info| info.is_some())
    }

    /// A file written a piece at a time, which appears at its `commit`.
    pub fn upload(self) -> Result<Upload> {
        let whole = self.checked()?;
        #[cfg(feature = "sql")]
        if self.tx.is_some() {
            let refused = Error::invalid("an upload inside a transaction: put its bytes, which commit with it");
            return Err(self.files.fail(&whole, refused));
        }
        Upload::start(self.files.clone(), whole, self.options)
    }

    pub fn delete(self) -> Result<()> {
        let whole = self.files.whole(&self.path)?;
        #[cfg(feature = "sql")]
        if let Some(tx) = self.tx {
            let deleting = self.files.deleting(&whole, self.options.if_match);
            let deleted = super::tx::on_file(tx, self.files, |sql| deleting(sql).map(drop));
            return deleted.map_err(|error| self.files.fail(&whole, error));
        }
        self.files.delete_at(&whole, self.options.if_match).map_err(|error| self.files.fail(&whole, error))
    }

    /// Writes the file at `from` here too, sharing its bytes.
    pub fn copy_from(self, from: &str) -> Result<FileInfo> {
        self.copied(from, false)
    }

    /// Moves the file at `from` here in one write.
    pub fn rename_from(self, from: &str) -> Result<FileInfo> {
        self.copied(from, true)
    }

    fn copied(self, from: &str, rename: bool) -> Result<FileInfo> {
        let (source, target) = (self.files.whole(from)?, self.checked()?);
        #[cfg(feature = "sql")]
        if let Some(tx) = self.tx {
            let copied = refuse_onto_itself(&source, &target).and_then(|()| {
                let copying = self.files.copying(&source, &target, &self.options, rename);
                super::tx::on_file(tx, self.files, |sql| copying(sql).map(|(info, _)| info))
            });
            return copied.map_err(|error| self.files.fail(&target, error));
        }
        self.files.copy_to(&source, &target, &self.options, rename).map_err(|error| self.files.fail(&target, error))
    }

    /// The whole path, its options checked, as each verb that writes bytes or
    /// a row checks them first.
    fn checked(&self) -> Result<String> {
        let whole = self.files.whole(&self.path)?;
        self.options.check().map_err(|error| self.files.fail(&whole, error))?;
        Ok(whole)
    }

    /// The files, the path and the options: what an awaited call owns until
    /// its first poll makes the call again with [`Files::call`].
    #[cfg(feature = "async")]
    pub(crate) fn into_parts(self) -> (&'f Files, String, Options) {
        (self.files, self.path, self.options)
    }

    /// [`FileCall::upload`] waiting on no thread for the memory an upload
    /// holds: `done` is given the upload once that memory fits, on whichever
    /// thread gives memory back, or here when it fits now, and a path or an
    /// option that is not one here at once. What this returns takes the
    /// waiter out of line when it is dropped unanswered.
    #[cfg(feature = "async")]
    pub(crate) fn upload_then(self, done: impl FnOnce(Result<Upload>) + Send + 'static) -> Option<Waiting> {
        let whole = match self.checked() {
            Ok(whole) => whole,
            Err(error) => {
                done(Err(error));
                return None;
            }
        };
        let (files, options) = (self.files.clone(), self.options);
        Some(Upload::reserve_then(self.files, move |reserved| {
            let reserved = reserved.map_err(|error| files.fail(&whole, error));
            done(reserved.and_then(|reserved| Upload::reserved(files, whole, options, reserved)));
        }))
    }

    /// [`FileCall::delete`] for an awaited write, submitted: `done` is given
    /// its answer once its commit ends, on the thread that answers the commit.
    #[cfg(feature = "async")]
    pub(crate) fn delete_then(self, done: impl Done<()>) {
        let whole = match self.files.whole(&self.path) {
            Ok(whole) => whole,
            Err(error) => return done(Err(error)),
        };
        let deleting = self.files.deleting(&whole, self.options.if_match);
        let files = self.files.clone();
        self.files
            .blobs
            .file
            .submit(0, deleting, move |deleted| done(deleted.map_err(|error| files.fail(&whole, error))));
    }

    /// [`FileCall::copy_from`], or with `rename` [`FileCall::rename_from`],
    /// for an awaited write, submitted as [`FileCall::delete_then`] is.
    #[cfg(feature = "async")]
    pub(crate) fn copied_then(self, from: &str, rename: bool, done: impl Done<FileInfo>) {
        let wholes = self.files.whole(from).and_then(|source| Ok((source, self.checked()?)));
        let (source, target) = match wholes {
            Ok(wholes) => wholes,
            Err(error) => return done(Err(error)),
        };
        if let Err(error) = refuse_onto_itself(&source, &target) {
            return done(Err(self.files.fail(&target, error)));
        }
        let copying = self.files.copying(&source, &target, &self.options, rename);
        let files = self.files.clone();
        self.files
            .blobs
            .file
            .submit(0, copying, move |copied| done(copied.map_err(|error| files.fail(&target, error))));
    }

    /// Writes the whole file, or with `create` only where no file is; says
    /// what it wrote, nothing when a create found a file. The wire's put, a
    /// put another node passed on, and an awaited put of a large file, on the
    /// store's pool.
    #[cfg(any(feature = "wire", feature = "replication", feature = "async"))]
    pub(crate) fn written(self, bytes: &[u8], create: bool) -> Result<Option<FileInfo>> {
        let when_there = if create { WhenThere::Skip } else { WhenThere::Replace };
        let condition = self.options.condition(when_there);
        self.write_all(bytes, condition)
    }

    fn write_all(self, bytes: &[u8], condition: Condition) -> Result<Option<FileInfo>> {
        let whole = self.checked()?;
        #[cfg(feature = "sql")]
        if let Some(tx) = self.tx {
            let written = super::tx::write_in(tx, self.files, (&whole, &self.options), bytes, condition);
            return written.map_err(|error| self.files.fail(&whole, error));
        }
        let mut upload = Upload::start(self.files.clone(), whole, self.options)?;
        upload.take(bytes)?;
        upload.finish(condition)
    }
}

/// A set's name, as a file's is: short and plain.
fn check_name(name: &str) -> Result<()> {
    crate::text::check_name("a set's", name)
}

#[cfg(test)]
#[path = "files_tests.rs"]
mod tests;