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
//! The blobs engine: `blobs/` in the store's directory, its `blobs.db`, and
//! the files of the contents too large to keep inline; or in a database's
//! file, its tables beside the database's and its bytes in the folder beside
//! the file, so that a file commits with the rows that name it.
//!
//! ```text
//! blobs/
//! ├── blobs.db            sets, files, contents, inline bodies, marks
//! ├── uploads/1a3f08      an upload's bytes until its commit; emptied at open
//! └── objects/1a3/1a3f07  content 0x1a3f07's bytes: renamed here once, never changed
//! sql/app.db              a database's files: the same tables, _tinystore_blobs_…
//! sql/app.blobs/          and the same folders
//! ```

use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime};

use rusqlite::{OptionalExtension, params};

use super::disk::{Disk, OBJECTS, UPLOADS};
use super::ids::Ids;
use super::scrub::Scrubbing;
use crate::engine::{Claim, Copied, Copying, Engine, Host, Then, to_copy};
use crate::sqlite::{Config, File, Migration, Tx, own_work, sql_error};
use crate::sync::lock;
use crate::{Clock, Durability, Error, Memory, Result, Store, unix_millis};

const SETTLE: &str = "update _tinystore_blobs_meta set value = ?1 where name = 'settled' and value < ?1";
const RESERVE_IDS: &str = "update _tinystore_blobs_meta set value = value + ?1 where name = 'ids' returning value";
const HAS_CONTENT: &str = "select 1 from _tinystore_blobs_contents where id = ?1";
const MIGRATIONS: &[Migration] = &[
    Migration::of(1, "0001_schema.sql", include_str!("migrations/0001_schema.sql")),
    Migration::of(2, "0002_names.sql", include_str!("migrations/0002_names.sql")),
    Migration::of(3, "0003_directories.sql", include_str!("migrations/0003_directories.sql")),
    Migration::of(4, "0004_cache.sql", include_str!("migrations/0004_cache.sql")),
    Migration::of(5, "0005_claims.sql", include_str!("migrations/0005_claims.sql")),
];
/// A database's files, whose tables are made with blobs.db's names of its
/// step 2: a step after it goes to both histories, the next of each, but for
/// a directory's tables, which blobs.db alone keeps.
#[cfg(feature = "sql")]
const IN_A_DATABASE: &[Migration] = &[
    Migration::of(1, "0001_in_a_database.sql", include_str!("migrations/0001_in_a_database.sql")),
    Migration::of(2, "0002_cache.sql", include_str!("migrations/0002_cache.sql")),
    Migration::of(3, "0003_claims.sql", include_str!("migrations/0003_claims.sql")),
];
/// A content id taken in a database's transaction, which a rollback gives
/// back with every row the transaction wrote.
#[cfg(feature = "sql")]
const TAKE_ID: &str = "update _tinystore_blobs_meta set value = value + 1 where name = 'ids' returning value";

/// How often maintenance runs: expiry, marked clears, files no row names any
/// more, what uploads left, and a slice of the scrub.
const MAINTENANCE: Duration = Duration::from_secs(60);

pub(crate) struct Blobs {
    pub(crate) file: Arc<File>,
    /// Where it is kept: blobs.db, or a database's file.
    pub(crate) kept: Kept,
    /// What blobs tells the store's own metrics.
    pub(crate) probe: Arc<crate::probe::Probe>,
    pub(crate) disk: Disk,
    pub(crate) ids: Ids,
    pub(crate) memory: Arc<Memory>,
    pub(crate) scrubbing: Mutex<Option<Scrubbing>>,
    clock: Arc<dyn Clock>,
    /// The disk the store keeps free, which no file may take.
    keep_free: u64,
    sets: Mutex<HashMap<String, i64>>,
    /// The scans of directories under way, which a second scan waits on.
    pub(crate) scans: super::directory::Scans,
    /// The uses reads asked for, which the next flush writes.
    pub(crate) uses: super::uses::Uses,
    /// What each set's ceiling evicted since the store opened.
    pub(crate) evictions: Arc<super::cache::Evictions>,
    /// The runs of getOrCreate under way in this process, and who waits for each.
    pub(crate) fills: super::filling::Fills,
    /// The store, for the writes a copy passes to its home.
    #[cfg(feature = "replication")]
    store: crate::store::WeakStore,
    /// The store's pool, which an awaited call on files made from blocking
    /// ones runs on: the pool holds no store, so this keeps none open.
    #[cfg(feature = "async")]
    pub(crate) pool: Arc<crate::pool::Pool>,
    _claim: Option<Claim>,
}

/// The files of `objects/` that the copy of blobs.db in `store_dir` names
/// and the store lacks, by their paths in its directory: what a node fetches
/// from the node it copies blobs.db from.
#[cfg(feature = "replication")]
pub(crate) fn objects_missing(store_dir: &std::path::Path) -> Result<Vec<String>> {
    let paths = object_ids(store_dir, SELECT_NAMED, [])?.into_iter().map(object_in_store);
    Ok(paths.filter(|path| !store_dir.join(path).exists()).collect())
}

/// The files of `objects/` the blobs.db in `store_dir` holds past the id
/// `after`, oldest first, each with its id and its path in the store's
/// directory: what a node sends the nodes taking blobs.db from it before the
/// commits that name them. One its disk does not hold yet is left out.
#[cfg(feature = "replication")]
pub(crate) fn objects_after(store_dir: &std::path::Path, after: i64) -> Result<Vec<(i64, String)>> {
    let paths = object_ids(store_dir, SELECT_AFTER, [after])?.into_iter().map(|id| (id, object_in_store(id)));
    Ok(paths.filter(|(_, path)| store_dir.join(path).exists()).collect())
}

/// The content ids `select` reads from the blobs.db in `store_dir`, which
/// no process need hold; none when there is no blobs.db, or one whose tables
/// are not made yet.
///
/// A home serves its blobs.db from its first commit, before its migrations',
/// and a copy may hold that commit whole: read as an error, the home's link
/// ended, and the copy's ended again at each turn, never taking the commit
/// that made the tables.
#[cfg(feature = "replication")]
fn object_ids<const N: usize>(store_dir: &std::path::Path, select: &str, params: [i64; N]) -> Result<Vec<i64>> {
    let db = store_dir.join(DIR).join(FILE);
    if !db.exists() {
        return Ok(Vec::new());
    }
    crate::sqlite::read_copy(&db, |connection| {
        if connection.query_row(HAS_CONTENTS, [], |row| row.get::<_, i64>(0))? == 0 {
            return Ok(Vec::new());
        }
        let mut statement = connection.prepare(select)?;
        let ids = statement.query_map(rusqlite::params_from_iter(params), |row| row.get::<_, i64>(0))?;
        ids.collect::<rusqlite::Result<Vec<i64>>>()
    })
}

/// Content `id`'s file by its path in the store's directory.
#[cfg(feature = "replication")]
fn object_in_store(id: i64) -> String {
    format!("{DIR}/{}", Disk::object_name(id))
}

/// Whether `path` names a file of `objects/`, as [`objects_missing`] writes
/// one: what a node serves of blobs beside blobs.db.
#[cfg(feature = "replication")]
pub(crate) fn is_object(path: &str) -> bool {
    let hex = |part: &str| !part.is_empty() && part.len() <= 16 && part.bytes().all(|b| b.is_ascii_hexdigit());
    let mut parts = path.split('/');
    parts.next() == Some(DIR)
        && parts.next() == Some(OBJECTS)
        && parts.next().is_some_and(hex)
        && parts.next().is_some_and(hex)
        && parts.next().is_none()
}

/// blobs.db, as a node names it.
#[cfg(feature = "replication")]
pub(crate) const FILE_IN_STORE: &str = "blobs/blobs.db";

/// Where a blobs engine is kept, by the paths in the store's directory of its
/// file and of the folder its bytes lie in.
#[derive(Debug)]
pub(crate) struct Kept {
    pub(crate) file: String,
    pub(crate) folder: String,
    /// The database that lends its file, as an error names it: `sql app`.
    pub(crate) lent_by: Option<String>,
}

impl Engine for Blobs {
    /// Writes the uses reads asked for, then closes blobs.db; a database's
    /// file is the database's to close.
    fn close(&self) -> Result<()> {
        if !self.file.is_copy()
            && let Err(error) = self.flush_uses()
        {
            tracing::debug!(target: "tinystore", %error, "blobs: the uses of the last second, which the close loses");
        }
        if self.kept.lent_by.is_some() {
            return Ok(());
        }
        self.file.close()
    }

    /// Names blobs.db, and once it is copied links beside the copy every
    /// file it names: a link copies no byte and keeps the bytes after the
    /// engine lets its own name go, so a film costs the snapshot a directory
    /// entry. No removal begins from the moment on, so that none the copy
    /// names goes before it is linked. A database's file is the database's
    /// to name, and its files are linked once it is copied.
    fn snapshot(&self) -> Result<Copying<'_>> {
        // a database no backup takes keeps its bytes in local/, none of them copied
        #[cfg(feature = "sql")]
        if crate::engine::is_local(&self.kept.file) {
            return Ok(Copying::default());
        }
        let mut copying = match self.kept.lent_by {
            None => to_copy(&self.file, &self.kept.file, "blobs")?,
            Some(_) => Copying::default(),
        };
        copying.at_the_moment = Some(Box::new(move || {
            let paused = self.disk.pause_removals();
            let then: Then<'_> = Box::new(move |into| {
                let _paused = paused;
                self.link_named(into)
            });
            then
        }));
        Ok(copying)
    }

    /// A set's name and id are its home's, read again on a copy once its
    /// home's commits arrive.
    fn applied(&self, _: &str) {
        lock(&self.sets).clear();
    }
}

impl Blobs {
    /// Links into the snapshot at `into` every file its copy of the file names.
    fn link_named(&self, into: &std::path::Path) -> Result<Vec<Copied>> {
        let named = crate::sqlite::read_copy(&into.join(&self.kept.file), |connection| {
            let mut statement = connection.prepare(SELECT_NAMED)?;
            let ids = statement.query_map([], |row| row.get::<_, i64>(0))?;
            ids.collect::<rusqlite::Result<Vec<i64>>>()
        })
        .map_err(|error| error.within("snapshot blobs: the files the copy names"))?;
        let mut linked = Vec::new();
        for id in named {
            if let Some(name) = self.disk.link_object(id, &into.join(&self.kept.folder))? {
                linked.push(Copied { name: format!("{}/{name}", self.kept.folder), engine: "blobs" });
            }
        }
        Ok(linked)
    }
}

/// What opens a blobs engine on its file: where it is kept, its folder and
/// the claim on it, and its file's history.
struct Opening<'s> {
    store: &'s Store,
    file: Arc<File>,
    kept: Kept,
    dir: std::path::PathBuf,
    /// None for one that writes nothing in its folder: a copy of a database's
    /// file a connection that only reads opened, beside the database's own.
    claim: Option<Claim>,
    migrations: &'static [Migration],
    #[cfg(feature = "async")]
    pool: Arc<crate::pool::Pool>,
}

impl Opening<'_> {
    /// Its folders made, its file migrated, and what a process that died left
    /// removed before anything is written; then its maintenance started.
    fn start(self) -> Result<Arc<Blobs>> {
        let (store, dir) = (self.store, self.dir);
        // a store beside its holder makes nothing in the holder's directory,
        // nor an engine that holds no claim on its folder
        if !store.is_beside() && self.claim.is_some() {
            for made in [dir.clone(), dir.join(UPLOADS), dir.join(OBJECTS)] {
                std::fs::create_dir_all(&made)
                    .map_err(|error| Error::io(format!("blobs: create {}", made.display()), error))?;
            }
        }
        self.file.migrate("blobs", self.migrations)?;
        let durable = self.file.durability() == Durability::Full;
        let tasks = self.kept.lent_by.as_ref().map_or_else(|| "blobs".to_owned(), |owner| format!("blobs in {owner}"));
        let blobs = Arc::new(Blobs {
            file: self.file,
            kept: self.kept,
            probe: Arc::clone(store.probe()),
            disk: Disk::new(dir, durable),
            ids: Ids::default(),
            memory: Arc::clone(store.memory()),
            scrubbing: Mutex::new(None),
            clock: store.clock(),
            keep_free: store.keep_free(),
            sets: Mutex::new(HashMap::new()),
            scans: super::directory::Scans::default(),
            uses: super::uses::Uses::default(),
            evictions: Arc::default(),
            fills: super::filling::Fills::default(),
            #[cfg(feature = "replication")]
            store: store.downgrade(),
            #[cfg(feature = "async")]
            pool: self.pool,
            _claim: self.claim,
        });
        // What a process that died left, and the maintenance after it, are a
        // copy's home's to clear: each turn asks, since a file's home may
        // move while it is open.
        if !blobs.file.is_copy() {
            blobs.recover()?;
        }
        let sampler: std::sync::Weak<dyn crate::probe::Sample> = Arc::downgrade(&blobs) as std::sync::Weak<Blobs>;
        store.probe().sampled(sampler);
        let weak = Arc::downgrade(&blobs);
        store.every(&format!("{tasks}: uses"), super::uses::USES, move || {
            weak.upgrade().map_or(Ok(()), |blobs| blobs.flush_uses().map(drop))
        })?;
        let weak = Arc::downgrade(&blobs);
        store.every(&format!("{tasks}: maintenance"), MAINTENANCE, move || {
            weak.upgrade().filter(|blobs| !blobs.file.is_copy()).map_or(Ok(()), |blobs| {
                // a burst of reads otherwise keeps its readers open for good
                blobs.file.sweep();
                blobs.maintain().map(drop)
            })
        })?;
        let weak = Arc::downgrade(&blobs);
        store.every(&format!("{tasks}: claims"), super::filling::RENEW_EVERY, move || {
            weak.upgrade().filter(|blobs| !blobs.file.is_copy()).map_or(Ok(()), |blobs| blobs.renew_claims())
        })?;
        Ok(blobs)
    }
}

/// blobs' directory in the store's, and its file in it.
const DIR: &str = "blobs";
const FILE: &str = "blobs.db";
const SELECT_NAMED: &str = "select id from _tinystore_blobs_contents where inline = 0 and names > 0 order by id";
#[cfg(feature = "replication")]
const SELECT_AFTER: &str = "select id from _tinystore_blobs_contents where inline = 0 and id > ?1 order by id";
#[cfg(feature = "replication")]
const HAS_CONTENTS: &str = "select count(*) from sqlite_schema where name = '_tinystore_blobs_contents'";

const SELECT_MARKS: &str = "select (select value from _tinystore_blobs_meta where name = 'ids'), (select value from _tinystore_blobs_meta where name = 'settled')";
const NEXT_REVISION: &str =
    "update _tinystore_blobs_meta set value = value + 1 where name = 'revision' returning value";
const SELECT_SET: &str = "select id from _tinystore_blobs_sets where name = ?1";
const INSERT_SET: &str = "insert into _tinystore_blobs_sets (name) values (?1) on conflict (name) do nothing";

impl Blobs {
    /// The store's blobs engine, opened by the first files: its directory
    /// claimed and made, its file migrated, and what a process that died left
    /// removed before anything is written.
    pub(crate) fn of(store: &Store) -> Result<Arc<Blobs>> {
        // found first: an engine's open holds the lock a second open waits for
        #[cfg(feature = "async")]
        let pool = crate::pool::Pool::of(store)?;
        store.engine(|store| {
            let claim = store.claim(DIR)?;
            let config = Config::committing(store.durability());
            let file = Arc::new(store.open_file(&format!("{DIR}/{FILE}"), config)?);
            let kept = Kept { file: format!("{DIR}/{FILE}"), folder: DIR.to_owned(), lent_by: None };
            let (dir, claim) = (claim.path().to_owned(), Some(claim));
            #[cfg(feature = "async")]
            let opening = Opening { store, file, kept, dir, claim, migrations: MIGRATIONS, pool };
            #[cfg(not(feature = "async"))]
            let opening = Opening { store, file, kept, dir, claim, migrations: MIGRATIONS };
            opening.start()
        })
    }

    /// The blobs engine kept in a database's file, which every set of files
    /// opened from the database shares: its bytes lie in the folder beside
    /// the file, `sql/app.blobs/` beside `sql/app.db`, and `local/app.blobs/`
    /// beside one no backup takes.
    #[cfg(feature = "sql")]
    pub(crate) fn in_file(shared: &Arc<crate::engine::SharedFile>) -> Result<Arc<Blobs>> {
        shared.engine(|store| {
            let in_store = shared.file().path().strip_prefix(store.dir()).map_err(|_| {
                Error::internal(format!("{}: a database's file outside its store's directory", shared.owner()))
            })?;
            let file_name = in_store.to_string_lossy().replace('\\', "/");
            // a database of local/ is this node's own, which no copy takes, bytes and all
            #[cfg(feature = "replication")]
            if store.node().is_some() && !crate::engine::is_local(&file_name) {
                return Err(Error::invalid(format!(
                    "{}: a database's files on a node, whose copies take no bytes of a database yet",
                    shared.owner()
                )));
            }
            let folder = format!("{}.blobs", file_name.strip_suffix(".db").unwrap_or(&file_name));
            // a copy writes nothing in the folder, which the database's own claims
            let claim = if shared.file().is_copy() { None } else { Some(store.claim(&folder)?) };
            let dir = store.dir().join(&folder);
            let kept = Kept { file: file_name, folder, lent_by: Some(shared.owner().to_owned()) };
            let file = Arc::clone(shared.file());
            #[cfg(feature = "async")]
            let opening = Opening {
                store,
                file,
                kept,
                dir,
                claim,
                migrations: IN_A_DATABASE,
                pool: crate::pool::Pool::of(store)?,
            };
            #[cfg(not(feature = "async"))]
            let opening = Opening { store, file, kept, dir, claim, migrations: IN_A_DATABASE };
            opening.start()
        })
    }

    /// The store blobs opened in, while it is open.
    #[cfg(feature = "replication")]
    pub(crate) fn store(&self) -> Result<Store> {
        self.store.upgrade().ok_or_else(|| Error::closed("the store"))
    }

    /// The file as an error names it: `blobs.db`, or `sql app`.
    #[cfg(feature = "sql")]
    pub(crate) fn place(&self) -> &str {
        self.kept.lent_by.as_deref().unwrap_or(FILE)
    }

    /// A content id taken in a database's transaction: the meta row it moves
    /// is the transaction's, so that a rollback gives it back and no content
    /// that committed has an id past what its file reserved.
    #[cfg(feature = "sql")]
    pub(crate) fn id_in(&self, tx: &Tx<'_>) -> Result<i64> {
        tx.prepare_cached(TAKE_ID)
            .and_then(|mut take| take.query_row([], |row| row.get(0)))
            .map_err(|error| sql_error("blobs: a content id", error))
    }

    /// Refuses `coming` bytes that would leave the disk less free than the
    /// store keeps, asking the system how much is free now.
    pub(crate) fn room(&self, coming: u64) -> Result<()> {
        crate::space::room(self.disk.dir(), self.keep_free, coming).map_err(|error| error.within("blobs"))
    }

    /// Takes up the file's marks and removes what a process that died left:
    /// every file of `uploads/`, and in the directories of `objects/` that
    /// hold the ids past the settled mark, each file no content names. Only an
    /// upload makes such a file, between its rename and its commit, and every
    /// id at or below the mark is committed or has none, so nothing else is
    /// walked.
    fn recover(&self) -> Result<()> {
        let (reserved, settled): (i64, i64) = self.file.read(|connection| {
            connection
                .query_row(SELECT_MARKS, [], |row| Ok((row.get(0)?, row.get(1)?)))
                .map_err(|error| sql_error("blobs: read the marks", error))
        })?;
        self.ids.start(reserved);
        // An upload left that will not go now, as one Windows still shares, is
        // swept later and keeps no store from opening.
        if let Err(error) = self.disk.sweep_uploads(&self.ids) {
            tracing::warn!(target: "tinystore", %error, "blobs: an upload left by a process that died stays for now");
        }
        // A database's transaction takes its ids in its own rows, so that a
        // file it placed and a crash left lies past the mark: any past it is
        // no content's, as no upload runs before the store opened.
        let last = self.disk.last_fan()?.unwrap_or(0).max(Disk::fan(reserved));
        for fan in Disk::fan(settled + 1)..=last {
            self.remove_unnamed_in(fan, settled)?;
        }
        self.forget_claims()?;
        self.settle()
    }

    /// Removes the files of one directory of `objects/` whose ids lie past
    /// `settled` and that no content names. One that will not go now, as one
    /// a scanner holds on Windows, stays in doubt: the settled mark stays
    /// below it, and maintenance removes it later.
    fn remove_unnamed_in(&self, fan: i64, settled: i64) -> Result<()> {
        let ids = self.disk.ids_in(fan)?;
        if ids.is_empty() {
            return Ok(());
        }
        let (low, high) = Disk::span(fan);
        let low = low.max(settled + 1);
        let named =
            ("select id from _tinystore_blobs_contents where id >= ?1 and id <= ?2", "blobs: the contents named");
        let named: Vec<i64> =
            self.file.read(|connection| rows_of(connection, named, params![low, high], |row| row.get(0)))?;
        for id in ids.into_iter().filter(|id| (low..=high).contains(id) && !named.contains(id)) {
            if let Err(error) = self.disk.remove_object(id) {
                tracing::warn!(target: "tinystore", %error, "blobs: a file left by a process that died stays for now");
                self.ids.doubt(id);
            }
        }
        Ok(())
    }

    /// Moves the settled mark up to what no upload holds, so that the next
    /// open walks only the directories of the ids reserved since.
    pub(crate) fn settle(&self) -> Result<()> {
        let mark = self.ids.settled_mark();
        own_work(|| {
            self.file.write(0, move |tx| {
                tx.prepare_cached(SETTLE)
                    .and_then(|mut update| update.execute([mark]))
                    .map(drop)
                    .map_err(|error| sql_error("blobs: settle the content ids", error))
            })
        })
    }

    /// The next content id, held until its upload ends; a block is reserved
    /// in a write of its own when the last one is spent.
    pub(crate) fn take_id(&self) -> Result<i64> {
        self.ids.take(|block| {
            own_work(|| {
                self.file.write(0, move |tx| {
                    tx.prepare_cached(RESERVE_IDS)
                        .and_then(|mut reserve| reserve.query_row([block], |row| row.get(0)))
                        .map_err(|error| sql_error("blobs: reserve content ids", error))
                })
            })
        })
    }

    /// Learns what became of a file content whose commit's outcome is
    /// unknown: a content row says it committed, and none that it did not, so
    /// its file goes. A file that cannot answer leaves the id in doubt.
    pub(crate) fn resolve(&self, id: i64) {
        let found = self.file.read(|connection| {
            connection
                .prepare_cached(HAS_CONTENT)
                .and_then(|mut select| select.query_row([id], |_| Ok(())))
                .optional()
                .map_err(|error| sql_error("blobs: a content in doubt", error))
        });
        match found {
            Ok(Some(())) => self.ids.let_go(id),
            Ok(None) if self.disk.remove_object(id).is_ok() => self.ids.let_go(id),
            _ => self.ids.doubt(id),
        }
    }

    /// The revision of one write, taken from the file in the write's own
    /// transaction rather than counted in memory: a copy's file moves under
    /// its engine as its home's commits arrive, and a copy that takes over
    /// writes past every revision its home wrote.
    pub(crate) fn next_revision(&self, tx: &Tx<'_>) -> Result<i64> {
        tx.prepare_cached(NEXT_REVISION)
            .and_then(|mut next| next.query_row([], |row| row.get(0)))
            .map_err(|error| sql_error("blobs: the revision", error))
    }

    /// The id of the set of files `name`, made the first time it is asked.
    pub(crate) fn set_id(&self, name: &str) -> Result<i64> {
        if let Some(&id) = lock(&self.sets).get(name) {
            return Ok(id);
        }
        let owned = name.to_owned();
        let in_store = self.kept.lent_by.is_none();
        // Found before it is made, so that a copy, which writes nothing,
        // opens a set its home made.
        let made = own_work(|| {
            self.file.write(0, move |tx| {
                let failed = |error| sql_error("blobs: a set of files", error);
                let found = tx.query_row(SELECT_SET, [&owned], |row| row.get(0)).optional().map_err(failed)?;
                if let Some(id) = found {
                    return Ok(id);
                }
                if in_store {
                    super::directory::refuse_a_directory(tx, &owned)?;
                }
                tx.execute(INSERT_SET, [&owned]).map_err(failed)?;
                tx.query_row(SELECT_SET, [&owned], |row| row.get(0)).map_err(failed)
            })
        });
        let id = made?;
        lock(&self.sets).insert(name.to_owned(), id);
        Ok(id)
    }

    /// The id of the set of files `name` as the file holds it, for a
    /// connection that may only read: a set it does not hold is refused
    /// rather than made. One it holds is kept here as [`set_id`](Self::set_id)
    /// keeps it, which then finds it and writes nothing.
    #[cfg(feature = "wire")]
    fn set_id_as_it_is(&self, name: &str) -> Result<i64> {
        if let Some(&id) = lock(&self.sets).get(name) {
            return Ok(id);
        }
        let found = self.file.read(|connection| {
            let failed = |error| sql_error("blobs: a set of files", error);
            let set = connection.prepare_cached(SELECT_SET);
            set.and_then(|mut select| select.query_row([name], |row| row.get::<_, i64>(0))).optional().map_err(failed)
        })?;
        let id = found.ok_or_else(|| crate::engine::not_held("set of files"))?;
        lock(&self.sets).insert(name.to_owned(), id);
        Ok(id)
    }

    /// The store's clock, as the rows keep it: unix milliseconds.
    pub(crate) fn now(&self) -> i64 {
        unix_millis(self.clock.now())
    }

    /// A row's time; a term too far for Windows' clock, such as a ttl of
    /// `Duration::MAX`, reads as the last second of 9999.
    pub(crate) fn time(millis: i64) -> SystemTime {
        crate::clock::from_unix_millis(millis)
    }

    /// Writes the uses reads asked for, or on a copy passes them to its home;
    /// says how many files they reached.
    pub(crate) fn flush_uses(&self) -> Result<usize> {
        #[cfg(feature = "replication")]
        if self.file.is_copy() {
            return super::forward::pass_uses(&self.store()?, self.uses.take());
        }
        let clock = Arc::clone(&self.clock);
        own_work(|| self.uses.flush(&self.file, move || unix_millis(clock.now())))
    }

    /// Removes the files of the contents a commit left without names. One that
    /// will not go stays listed, and maintenance tries it again.
    pub(crate) fn remove_freed(&self, ids: &[i64]) {
        for &id in ids {
            if let Err(error) = self.disk.remove_object(id) {
                tracing::debug!(target: "tinystore", %error, "blobs: a file maintenance removes later");
            }
        }
    }
}

pub(super) use crate::sqlite::query_cached as rows_of;

/// Each set's files' sizes together, as its row counts them.
const SELECT_SIZES: &str = "select name, size from _tinystore_blobs_sets order by id";

impl crate::probe::Sample for Blobs {
    /// What each set holds now: `tinystore_files_bytes`, by set.
    fn sample(&self, probe: &crate::probe::Probe) {
        let sizes: Result<Vec<(String, i64)>> = self.file.read(|connection| {
            rows_of(connection, (SELECT_SIZES, "blobs: its sets' sizes"), [], |row| Ok((row.get(0)?, row.get(1)?)))
        });
        for (set, size) in sizes.unwrap_or_default() {
            probe.set("tinystore_files_bytes", &[("set", &set)], size as f64);
        }
    }
}

/// Refuses, for a connection that may only read, the set of files `name`
/// while the store does not hold it: neither `blobs/` and its file nor the
/// set is made. Once it is found, an open of the set finds it as this did.
#[cfg(feature = "wire")]
pub(crate) fn set_as_it_is(store: &Store, name: &str) -> Result<()> {
    let within = |error: Error| error.within(format!("files {name}"));
    crate::text::check_name("a set's", name).map_err(within)?;
    store.holds(&format!("{DIR}/{FILE}")).map_err(within)?;
    Blobs::of(store).and_then(|blobs| blobs.set_id_as_it_is(name)).map(drop).map_err(within)
}

/// Refuses, for a connection that may only read, the set of files `name` in
/// a database's file while it does not hold it: neither blobs' tables in the
/// file, nor the folder beside it, nor the set is made.
#[cfg(all(feature = "wire", feature = "sql"))]
pub(crate) fn set_in_file_as_it_is(shared: &Arc<crate::engine::SharedFile>, name: &str) -> Result<()> {
    let within = |error: Error| error.within(format!("{}: files {name}", shared.owner()));
    crate::text::check_name("a set's", name).map_err(within)?;
    shared.keeps("_tinystore_blobs_sets", "set of files").map_err(within)?;
    Blobs::in_file(shared).and_then(|blobs| blobs.set_id_as_it_is(name)).map(drop).map_err(within)
}

/// The sets of files blobs.db holds, by name. None while the store has no
/// blobs, which a read beside would otherwise try to make.
#[cfg(feature = "client")]
pub(crate) fn sets(store: &Store) -> Result<Vec<String>> {
    const SELECT_SETS: &str = "select name from _tinystore_blobs_sets order by name";
    if !store.dir().join("blobs").join("blobs.db").exists() {
        return Ok(Vec::new());
    }
    Blobs::of(store)?.file.read(|c| {
        let mut select = c.prepare_cached(SELECT_SETS).map_err(|error| sql_error("blobs: its sets", error))?;
        let rows = select.query_map([], |row| row.get(0));
        rows.and_then(Iterator::collect).map_err(|error| sql_error("blobs: its sets", error))
    })
}

/// A set's live files and their sizes, which a copy that shares its content
/// with another counts again.
#[cfg(feature = "client")]
const SELECT_HELD: &str = concat!(
    "select count(*), coalesce(sum(f.size), 0) from _tinystore_blobs_files as f
        where f.set_id = ?1 and (f.expires is null or f.expires > ?2) and not ",
    super::change::hidden!()
);

/// What each set of files holds: its files and their sizes, read a set at a
/// time, so that a big store keeps no reader open for long.
#[cfg(feature = "client")]
pub(crate) fn held(store: &Store) -> Result<Vec<crate::engine::Held>> {
    const SELECT_IDS: &str = "select id, name from _tinystore_blobs_sets order by name";
    if !store.dir().join(DIR).join(FILE).exists() {
        return Ok(Vec::new());
    }
    let blobs = Blobs::of(store)?;
    let sets: Vec<(i64, String)> =
        blobs.file.read(|c| rows_of(c, (SELECT_IDS, "blobs: its sets"), [], |row| Ok((row.get(0)?, row.get(1)?))))?;
    let now = blobs.now();
    let held_in = |(id, name): (i64, String)| {
        let (count, bytes): (i64, i64) = blobs
            .file
            .read(|c| {
                c.prepare_cached(SELECT_HELD)
                    .and_then(|mut select| select.query_row(params![id, now], |row| Ok((row.get(0)?, row.get(1)?))))
                    .map_err(|error| sql_error("what a set of files holds", error))
            })
            .map_err(|error| error.within(format!("files {name}")))?;
        Ok(crate::engine::Held { name, count: count.unsigned_abs(), bytes: bytes.unsigned_abs() })
    };
    sets.into_iter().map(held_in).collect()
}

/// Each set of blobs.db that keeps a ceiling, by name, with it.
#[cfg(feature = "client")]
pub(crate) fn ceilings(store: &Store) -> Result<Vec<(String, u64)>> {
    const SELECT_CEILINGS: &str = "select name, max_size from _tinystore_blobs_sets where max_size is not null";
    if !store.dir().join(DIR).join(FILE).exists() {
        return Ok(Vec::new());
    }
    Blobs::of(store)?.file.read(|c| {
        rows_of(c, (SELECT_CEILINGS, "blobs: its sets' ceilings"), [], |row| {
            Ok((row.get(0)?, row.get::<_, i64>(1)?.unsigned_abs()))
        })
    })
}

/// The sets whose counters are not what their rows sum to: the set's name,
/// what its row counts, files and bytes, and what its files' rows hold.
#[cfg(feature = "client")]
const SELECT_MISCOUNTED: &str = "select s.name, s.count, s.size, coalesce(f.count, 0), coalesce(f.size, 0)
    from _tinystore_blobs_sets as s left join (
        select set_id, count(*) as count, sum(size) as size from _tinystore_blobs_files group by set_id
    ) as f on f.set_id = s.id
    where s.count <> coalesce(f.count, 0) or s.size <> coalesce(f.size, 0) order by s.name";

/// Each set whose counters differ from its rows, in blobs.db and in every
/// database's file of the store at `dir`, a line each: what `tinystore
/// verify` reports. A file read in one snapshot, beside whoever holds it,
/// through a connection that writes nothing; one whose sets keep no counters
/// yet, of a release before them, is left out.
#[cfg(feature = "client")]
pub(crate) fn miscounted(dir: &std::path::Path) -> Result<Vec<String>> {
    let mut files = vec![format!("{DIR}/{FILE}")];
    for folder in ["sql", "local"] {
        let Ok(entries) = std::fs::read_dir(dir.join(folder)) else { continue };
        let mut databases: Vec<String> = entries
            .filter_map(|entry| entry.ok()?.file_name().into_string().ok())
            .filter(|name| name.ends_with(".db"))
            .map(|name| format!("{folder}/{name}"))
            .collect();
        databases.sort();
        files.extend(databases);
    }
    let mut found = Vec::new();
    for file in files.into_iter().filter(|file| dir.join(file).is_file()) {
        let lines = crate::sqlite::read_file(&dir.join(&file), |c| {
            const COUNTED: &str =
                "select count(*) from pragma_table_info('_tinystore_blobs_sets') where name = 'count'";
            if c.query_row(COUNTED, [], |row| row.get::<_, i64>(0))? == 0 {
                return Ok(Vec::new());
            }
            let mut select = c.prepare(SELECT_MISCOUNTED)?;
            let rows = select.query_map([], |row| {
                let (name, count, size): (String, i64, i64) = (row.get(0)?, row.get(1)?, row.get(2)?);
                let (rows, bytes): (i64, i64) = (row.get(3)?, row.get(4)?);
                Ok(format!(
                    "{file}: files {name} counts {count} files and {size} bytes, and its rows hold {rows} files and \
                     {bytes} bytes"
                ))
            })?;
            rows.collect::<rusqlite::Result<Vec<String>>>()
        })?;
        found.extend(lines);
    }
    Ok(found)
}

#[cfg(all(test, feature = "replication"))]
mod tests {
    use super::*;

    #[test]
    fn a_blobs_db_whose_tables_are_not_made_yet_holds_no_object() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir(dir.path().join(DIR)).unwrap();
        // a home's first commit of blobs.db, before its migrations': SQLite's file, none of blobs' tables
        let first = rusqlite::Connection::open(dir.path().join(DIR).join(FILE)).unwrap();
        first.execute_batch("create table first (x)").unwrap();
        drop(first);
        assert_eq!(objects_after(dir.path(), 0).unwrap(), Vec::<(i64, String)>::new());
        assert_eq!(objects_missing(dir.path()).unwrap(), Vec::<String>::new());
    }
}