tinystore 0.2.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
//! The search engine: `search.db` in the store's directory, the indexes it
//! holds, and the work that keeps them fast and their settings as asked:
//! packing each head into blocks, purging the documents gone, building
//! again a dictionary of words that fell behind, keeping the clusters of
//! vectors, reading an index again beside itself and dropping what is
//! dropped. A table's indexes keep the same tables in a database's file,
//! beside the program's own, in an engine of their own.
//!
//! ```text
//! set ──► head, a grouped commit ── maintenance ──► blocks, a step a commit
//! search ◄── blocks and head, one snapshot
//! ```

use std::collections::{HashMap, HashSet};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, OnceLock, Weak};
use std::time::Duration;

use rusqlite::{Connection, OptionalExtension};

use super::open::{Beside, Current, Data, OpenIndex};
use super::read::{self, Answer, Asked, Query};
use super::rebuild;
use super::settings::{Changed, Settings, Table, Wanted};
use super::table;
use super::upkeep::PACK_AT;
use super::write::{self, Prepared};
use crate::clock::Clock;
use crate::engine::{Claim, Engine, Host, Wake};
use crate::sqlite::{Config, File, Migration, Tx, sql_error};
use crate::sync::lock;
use crate::{Error, Memory, Result, Store};

const MIGRATIONS: &[Migration] = &[Migration::of(1, "0001_schema.sql", include_str!("migrations/0001_schema.sql"))];

/// search's file in the store's directory.
pub(crate) const FILE: &str = "search.db";
/// How often maintenance looks for work, unless a set wakes it sooner.
const MAINTENANCE: Duration = Duration::from_secs(10);
/// The bytes of JSON an awaited set makes the words of in its poll, on the
/// executor's thread. Making them takes time in proportion to the bytes, so
/// a larger set, a `set_many` of many documents above all, makes them on the
/// store's pool.
#[cfg(feature = "async")]
const ANALYZED_IN_A_POLL: usize = 4 << 10;

const WRITE_SETTINGS: &str = "update _tinystore_search_indexes set settings = ?2 where id = ?1";
const COUNT_DOCUMENTS: &str = "select documents from _tinystore_search_indexes where id = ?1";
const READ_VALUE: &str = "select value from _tinystore_search_docs where index_id = ?1 and id = ?2";

pub(crate) struct Search {
    pub(crate) file: Arc<File>,
    /// What search tells the store's own metrics.
    probe: Arc<crate::probe::Probe>,
    /// What the log calls a file another engine lends: `sql app`.
    pub(super) lent_by: Option<String>,
    pub(super) memory: Arc<Memory>,
    pub(crate) clock: Arc<dyn Clock>,
    pub(crate) indexes: Mutex<HashMap<String, Arc<OpenIndex>>>,
    /// The store, for the writes a copy passes to its home, and the async
    /// API's handles made from blocking ones.
    #[cfg(any(feature = "replication", feature = "async"))]
    store: crate::store::WeakStore,
    /// Held by a pass of maintenance, so that two never pack the same head.
    maintaining: Mutex<()>,
    wake: OnceLock<Wake>,
    /// Rows a settle set since maintenance last packed, and the indexes it
    /// set them in, which maintenance keeps whether or not this process
    /// opened them. A settle runs on the writer, so these are all it holds.
    table_sets: AtomicU64,
    reached: Mutex<HashSet<String>>,
    _claim: Option<Claim>,
}

/// What one pass of maintenance did.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Maintenance {
    /// Postings packed from heads into blocks.
    pub packed: u64,
    /// Documents gone taken out of the blocks.
    pub purged: u64,
}

impl Engine for Search {
    /// Closes search.db; a database's file is the database's to close.
    fn close(&self) -> Result<()> {
        if self.lent_by.is_some() {
            return Ok(());
        }
        self.file.close()
    }

    /// Copies search.db; a table's indexes are copied with their database.
    fn snapshot(&self, into: &std::path::Path) -> Result<Vec<crate::engine::Copied>> {
        if self.lent_by.is_some() {
            return Ok(Vec::new());
        }
        Ok(vec![crate::engine::copy_file(&self.file, FILE, "search", into)?])
    }
}

/// The search engines kept in the store's databases' files, which
/// [`maintain`](super::maintain) reaches as it does search.db.
#[derive(Default)]
pub(crate) struct InFiles(Mutex<Vec<Weak<Search>>>);

impl Engine for InFiles {
    fn close(&self) -> Result<()> {
        Ok(())
    }
}

impl InFiles {
    pub(crate) fn of(store: &Store) -> Result<Arc<InFiles>> {
        store.engine(|_| Ok(Arc::new(InFiles::default())))
    }

    #[cfg(feature = "sql")]
    pub(crate) fn keep(&self, search: &Arc<Search>) {
        lock(&self.0).push(Arc::downgrade(search));
    }

    pub(crate) fn engines(&self) -> Vec<Arc<Search>> {
        lock(&self.0).iter().filter_map(Weak::upgrade).collect()
    }
}

impl Search {
    /// The store's search engine, opened by its first index: its file
    /// claimed and migrated, its maintenance on the store's schedule.
    pub(crate) fn of(store: &Store) -> Result<Arc<Search>> {
        store.engine(|store| {
            let claim = store.claim(FILE)?;
            let file = Arc::new(store.open_file(claim.name(), Config::committing(store.durability()))?);
            Search::start(store, file, None, Some(claim))
        })
    }

    /// Makes search's tables in `file` when it has none, and starts its
    /// maintenance on the store's schedule.
    pub(super) fn start(
        store: &Store,
        file: Arc<File>,
        lent_by: Option<String>,
        claim: Option<Claim>,
    ) -> Result<Arc<Search>> {
        file.migrate("search", MIGRATIONS)?;
        let tasks = lent_by.as_ref().map_or_else(|| "search".to_owned(), |owner| format!("search in {owner}"));
        let search = Arc::new(Search {
            file,
            probe: Arc::clone(store.probe()),
            lent_by,
            memory: Arc::clone(store.memory()),
            clock: store.clock(),
            indexes: Mutex::default(),
            #[cfg(any(feature = "replication", feature = "async"))]
            store: store.downgrade(),
            maintaining: Mutex::default(),
            wake: OnceLock::new(),
            table_sets: AtomicU64::new(0),
            reached: Mutex::default(),
            _claim: claim,
        });
        let sampler: std::sync::Weak<dyn crate::probe::Sample> = Arc::downgrade(&search) as std::sync::Weak<Search>;
        store.probe().sampled(sampler);
        // A copy's packing and purges are its home's, and reach it as pages:
        // each turn asks, since a file's home may move while it is open.
        let weak = Arc::downgrade(&search);
        let wake = store.every(&format!("{tasks}: maintenance"), MAINTENANCE, move || {
            weak.upgrade().filter(|search| !search.file.is_copy()).map_or(Ok(()), |search| {
                // a burst of reads otherwise keeps its readers open for good
                search.file.sweep();
                search.maintain(false).map(drop)
            })
        })?;
        let _ = search.wake.set(wake);
        Ok(search)
    }

    /// Whether the store's thread runs maintenance; without background work
    /// the program does, and a wait for a rebuild runs it itself.
    pub(super) fn runs_in_background(&self) -> bool {
        self.wake.get().is_some_and(crate::schedule::Wake::runs)
    }

    /// Counts a row a settle set in the index `name`, which maintenance
    /// then keeps, and wakes it once enough wait to be packed.
    pub(crate) fn table_set(&self, name: &str) {
        let mut reached = lock(&self.reached);
        if !reached.contains(name) {
            reached.insert(name.to_owned());
        }
        drop(reached);
        if self.table_sets.fetch_add(1, Ordering::Relaxed) + 1 == PACK_AT {
            self.wake();
        }
    }

    /// Opens the index `name`, made the first time, with the settings
    /// `wanted`; an index that holds others is changed to them, and read
    /// again beside itself where they need it, or where `reindex` asks.
    pub(crate) fn open_index(&self, name: &str, wanted: &Wanted, reindex: bool) -> Result<Arc<OpenIndex>> {
        check_name(name)?;
        wanted.check()?;
        let mut indexes = lock(&self.indexes);
        let mut made = false;
        let open = match indexes.get(name) {
            Some(open) => Arc::clone(open),
            None => {
                let current = match self.file.read(|connection| rebuild::read_current(connection, name))? {
                    Some(current) => current,
                    None => {
                        made = true;
                        let settings = Settings::new(wanted);
                        // A table's index's triggers commit with it, so that
                        // the fill it wakes reads no row before its writes are noted.
                        let id = self.file.transaction(|tx| {
                            let id = rebuild::add_index(tx, name, &settings)?;
                            if let Some(followed) = &settings.table {
                                table::begin_fill(tx, id)?;
                                table::follow(tx, name, followed)?;
                            }
                            Ok::<i64, Error>(id)
                        })?;
                        self.wake();
                        Current { serving: Data::new(id, settings), beside: None }
                    }
                };
                let open = Arc::new(OpenIndex::new(name, current));
                indexes.insert(name.to_owned(), Arc::clone(&open));
                open
            }
        };
        drop(indexes);
        open.manual.store(wanted.manual, Ordering::Relaxed);
        self.change(&open, wanted, reindex)?;
        if let Some(followed) = &wanted.table {
            self.follow(&open, followed, made)?;
        }
        self.opened(open.id())?;
        Ok(open)
    }

    /// Puts a table's index's triggers on its table; when they were missing
    /// from an index it did not make now, as after a migration rebuilt the
    /// table, it reads the table again, said in the log.
    fn follow(&self, open: &OpenIndex, followed: &Table, made: bool) -> Result<()> {
        let id = open.id();
        let again = self.file.transaction(|tx| {
            let missing = table::follow(tx, &open.name, followed)?;
            if missing && !made {
                table::begin_again(tx, id)?;
            }
            Ok::<bool, Error>(missing && !made)
        })?;
        if again {
            tracing::warn!(target: "tinystore", "search {}: its triggers were missing from table {}, as a migration \
                that rebuilds the table leaves it; reading the table again", open.name, followed.name);
            self.wake();
        }
        Ok(())
    }

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

    /// The index `name` as it is, made by no one: a read connection's, or
    /// what runs the writes a copy passed on.
    #[cfg(any(feature = "wire", feature = "replication"))]
    pub(crate) fn open_existing(&self, name: &str) -> Result<Arc<OpenIndex>> {
        check_name(name)?;
        let mut indexes = lock(&self.indexes);
        if let Some(open) = indexes.get(name) {
            return Ok(Arc::clone(open));
        }
        let Some(current) = self.file.read(|connection| rebuild::read_current(connection, name))? else {
            return Err(Error::invalid("no such index, and a connection that only reads makes none"));
        };
        let open = Arc::new(OpenIndex::new(name, current));
        indexes.insert(name.to_owned(), Arc::clone(&open));
        Ok(open)
    }

    /// Changes an index to `wanted`: what applies at once to its serving
    /// rows and to a rebuild's beside them, and a rebuild begun where the
    /// change needs one that none under way gives; each said in the log.
    fn change(&self, open: &OpenIndex, wanted: &Wanted, reindex: bool) -> Result<()> {
        let mut current = open.change(&self.file);
        let documents = self.file.read(|connection| count(connection, COUNT_DOCUMENTS, current.serving.id))?;
        let changed = current.serving.settings.change(wanted, documents)?;
        let why = rebuild_asked(&changed, wanted, reindex)?;
        let serving = self.changed_data(&current.serving, &changed)?;
        let target = Settings::new(wanted);
        let reads_as_asked = current.beside.as_ref().filter(|b| !b.failed && b.data.settings.reads_as(&target));
        let beside = match (reads_as_asked, why) {
            (Some(beside), _) => Some(self.change_beside(beside, wanted)?),
            (None, Some(why)) => Some(self.begin_beside(open, &current, (target, why))?),
            (None, None) => self.keep_beside(current.beside.as_ref(), wanted)?,
        };
        for line in &changed.said {
            tracing::info!(target: "tinystore", "search {}: {line}", open.name);
        }
        *current = Arc::new(Current { serving, beside });
        Ok(())
    }

    /// Rows read by changed settings, written to their row when they differ.
    fn changed_data(&self, data: &Data, changed: &Changed) -> Result<Data> {
        if changed.settings == *data.settings {
            return Ok(data.clone());
        }
        let (id, json) = (data.id, changed.settings.to_json());
        self.file.write(json.len(), move |tx| write::execute(tx, WRITE_SETTINGS, (id, json), "write settings"))?;
        Ok(data.with(changed.settings.clone()))
    }

    /// A rebuild under way that no change asks again: a failed one kept to
    /// say why, one that can take `wanted` at once changed, and one that
    /// cannot dropped.
    fn keep_beside(&self, beside: Option<&Beside>, wanted: &Wanted) -> Result<Option<Beside>> {
        let Some(beside) = beside else { return Ok(None) };
        if beside.failed {
            return Ok(Some(beside.clone()));
        }
        match self.change_beside(beside, wanted) {
            Ok(changed) => Ok(Some(changed)),
            Err(error) => {
                tracing::info!(
                    target: "tinystore",
                    %error,
                    "search: a rebuild under way dropped, since the change asks another",
                );
                self.file.transaction(|tx| rebuild::mark_dropping(tx, beside.data.id))?;
                Ok(None)
            }
        }
    }

    /// A rebuild's rows with what of `wanted` applies at once.
    fn change_beside(&self, beside: &Beside, wanted: &Wanted) -> Result<Beside> {
        let documents = self.file.read(|connection| count(connection, COUNT_DOCUMENTS, beside.data.id))?;
        let changed = beside.data.settings.change(wanted, documents)?;
        Ok(Beside { data: self.changed_data(&beside.data, &changed)?, failed: beside.failed })
    }

    /// Sets the documents `documents` makes of the serving rows' settings,
    /// which hold still until they commit, all of them in one commit or
    /// none; a rebuild under way copies them in turn.
    pub(crate) fn set(&self, open: &OpenIndex, documents: impl FnOnce(&Data) -> Result<Vec<Prepared>>) -> Result<()> {
        let current = open.hold();
        open.refuse_dropped()?;
        let prepared = documents(&current.serving)?;
        let count = prepared.len() as u64;
        if count == 0 {
            return Ok(());
        }
        let bytes = prepared.iter().map(Prepared::bytes).sum();
        self.file.write(bytes, move |tx| prepared.iter().try_for_each(|document| write::set(tx, document)))?;
        drop(current);
        self.count_sets(open, count);
        Ok(())
    }

    /// [`set`](Self::set) for an awaited set, which waits for nothing: the
    /// rows held still from the documents' analysis to their commit by a
    /// hold the commit drops on whichever thread it runs, and `done` called
    /// there with the answer. Documents of more than [`ANALYZED_IN_A_POLL`]
    /// bytes as JSON, `json`, are set on the store's pool instead, through
    /// [`elsewhere`], and so are any where a change holds the rows, since the
    /// set waits for it there.
    #[cfg(feature = "async")]
    pub(crate) fn set_then(
        self: &Arc<Self>,
        open: &Arc<OpenIndex>,
        json: usize,
        documents: impl FnOnce(&Data) -> Result<Vec<Prepared>> + Send + 'static,
        done: impl FnOnce(Result<()>) + Send + 'static,
    ) {
        let held = if json <= ANALYZED_IN_A_POLL { open.try_hold_submitted() } else { None };
        let Some(held) = held else {
            let (search, open) = (Arc::clone(self), Arc::clone(open));
            return elsewhere(move || done(search.set(&open, documents)));
        };
        if let Err(dropped) = open.refuse_dropped() {
            return done(Err(dropped));
        }
        let prepared = match documents(&held.current().serving) {
            Ok(prepared) => prepared,
            Err(refused) => return done(Err(refused)),
        };
        let count = prepared.len() as u64;
        if count == 0 {
            return done(Ok(()));
        }
        let bytes = prepared.iter().map(Prepared::bytes).sum();
        let search = Arc::clone(self);
        let write = move |tx: &Tx<'_>| prepared.iter().try_for_each(|document| write::set(tx, document));
        self.file.submit(bytes, write, move |written| {
            let open = Arc::clone(held.open());
            drop(held);
            if written.is_ok() {
                search.count_sets(&open, count);
            }
            done(written);
        });
        // a change waiting for the set may now take the lead that its submit handed to the pool
        open.queued();
    }

    /// Counts `count` sets that wait in an index's head, waking maintenance
    /// once enough of them wait to be packed.
    fn count_sets(&self, open: &OpenIndex, count: u64) {
        let before = open.sets.fetch_add(count, Ordering::Relaxed);
        if before < PACK_AT && before + count >= PACK_AT {
            self.wake();
        }
    }

    /// Deletes the document `id` from the serving rows and a rebuild's beside
    /// them, in one commit; says whether the serving rows held it.
    pub(crate) fn delete(&self, open: &OpenIndex, id: String) -> Result<bool> {
        let current = open.hold();
        open.refuse_dropped()?;
        let deleted = self.file.write(id.len(), deletes(&current, id));
        drop(current);
        deleted
    }

    /// [`delete`](Self::delete) for an awaited delete, which waits for
    /// nothing, as [`set_then`](Self::set_then) sets.
    #[cfg(feature = "async")]
    pub(crate) fn delete_then(
        self: &Arc<Self>,
        open: &Arc<OpenIndex>,
        id: String,
        done: impl FnOnce(Result<bool>) + Send + 'static,
    ) {
        let Some(held) = open.try_hold_submitted() else {
            let (search, open) = (Arc::clone(self), Arc::clone(open));
            return elsewhere(move || done(search.delete(&open, id)));
        };
        if let Err(dropped) = open.refuse_dropped() {
            return done(Err(dropped));
        }
        let bytes = id.len();
        let write = deletes(held.current(), id);
        self.file.submit(bytes, write, move |deleted| {
            drop(held);
            done(deleted);
        });
        open.queued();
    }

    /// The value of the document `id`, as JSON.
    pub(crate) fn get(&self, open: &OpenIndex, id: &str) -> Result<Option<Vec<u8>>> {
        open.refuse_dropped()?;
        let index = open.serving_id()?;
        self.file.read(|connection| {
            let failed = |error| sql_error("read a document", error);
            let mut select = connection.prepare_cached(READ_VALUE).map_err(failed)?;
            select.query_row((index, id), |row| row.get(0)).optional().map_err(failed)
        })
    }

    pub(crate) fn search(&self, open: &OpenIndex, query: Query) -> Result<Answer> {
        self.search_then(open, query, |_, _, _| Ok(())).map(|(answer, ())| answer)
    }

    /// Searches, then runs `then` on its answer in the same snapshot, told
    /// the settings it searched by, as a table's index reads its hits' rows.
    pub(crate) fn search_then<R>(
        &self,
        open: &OpenIndex,
        query: Query,
        then: impl FnOnce(&Connection, &Settings, &Answer) -> Result<R>,
    ) -> Result<(Answer, R)> {
        self.file.read(|connection| {
            let serving = open.current().serving.clone();
            self.search_on(connection, open, &serving, query, then)
        })
    }

    /// Searches on the writer of a transaction that holds the file, seeing
    /// what it wrote. The index is read from the transaction's rows, never
    /// from the lock a change of the index holds while it waits for this
    /// writer, and what searches keep is borrowed only as far as no
    /// transaction changes it.
    #[cfg(feature = "sql")]
    pub(crate) fn search_in<R>(
        &self,
        writer: &Connection,
        open: &OpenIndex,
        query: Query,
        then: impl FnOnce(&Connection, &Settings, &Answer) -> Result<R>,
    ) -> Result<(Answer, R)> {
        open.refuse_dropped()?;
        let current = rebuild::read_current(writer, &open.name)?;
        let serving = current.ok_or_else(|| Error::invalid("the index was dropped"))?.serving;
        let serving = Data { kept: Arc::new(open.kept_for_a_transaction(serving.id)), ..serving };
        self.search_on(writer, open, &serving, query, then)
    }

    /// Searches `serving` on `connection`, a reader's snapshot or the writer
    /// of a transaction that holds the file.
    fn search_on<R>(
        &self,
        connection: &Connection,
        open: &OpenIndex,
        serving: &Data,
        query: Query,
        then: impl FnOnce(&Connection, &Settings, &Answer) -> Result<R>,
    ) -> Result<(Answer, R)> {
        open.refuse_dropped()?;
        let started = self.probe.start();
        let asked =
            Asked { index: serving.id, settings: &serving.settings, kept: &serving.kept, memory: &self.memory, query };
        let answer = read::search(connection, asked)?;
        let then = then(connection, &serving.settings, &answer)?;
        if let Some(started) = started {
            self.probe.time("tinystore_search_ms", &[("index", &open.name)], started.elapsed());
        }
        if answer.behind {
            self.wake();
        }
        Ok((answer, then))
    }

    pub(crate) fn wake(&self) {
        if let Some(wake) = self.wake.get() {
            wake.wake();
        }
    }

    /// Packs each index's heads, purges their documents gone, builds again
    /// their dictionaries of words and keeps their clusters when they are
    /// due, for its serving rows and a rebuild's beside them; goes on with
    /// each rebuild, and drops what is dropped. `everything` takes each as
    /// due once it has any work, as a store without background work asks.
    pub(crate) fn maintain(&self, everything: bool) -> Result<Maintenance> {
        let _one = lock(&self.maintaining);
        let mut done = Maintenance::default();
        self.keep_reached()?;
        self.table_sets.store(0, Ordering::Relaxed);
        let indexes: Vec<Arc<OpenIndex>> = lock(&self.indexes).values().cloned().collect();
        // One index that fails keeps no other from its maintenance; the
        // first failure is the pass's error, which the scheduler says once.
        let mut failed = None;
        for open in indexes {
            if let Err(error) = self.maintain_one(&open, everything, &mut done) {
                failed.get_or_insert(error.within(format!("index {}", open.name)));
            }
        }
        self.drop_rows()?;
        failed.map_or(Ok(done), Err)
    }

    fn maintain_one(&self, open: &OpenIndex, everything: bool, done: &mut Maintenance) -> Result<()> {
        self.fill(open)?;
        let current = open.current();
        for data in current.written() {
            done.packed += self.pack(data, everything)?;
            if data.id == current.serving.id {
                open.sets.store(0, Ordering::Relaxed);
            }
            done.purged += self.purge(data, everything)?;
            self.build_dictionary(data, everything)?;
            self.cluster(open, data, everything)?;
        }
        self.rebuild(open)
    }

    /// Opens, for maintenance, each table's index a settle set rows in that
    /// this process has not opened.
    fn keep_reached(&self) -> Result<()> {
        let names = std::mem::take(&mut *lock(&self.reached));
        for name in &names {
            // Held across the read, as an open holds them, so that a drop
            // that commits meanwhile finds what the read made, and takes it out.
            let mut indexes = lock(&self.indexes);
            if indexes.contains_key(name) {
                continue;
            }
            match self.file.read(|connection| rebuild::read_current(connection, name)) {
                Ok(Some(current)) => {
                    indexes.insert(name.clone(), Arc::new(OpenIndex::new(name, current)));
                }
                Ok(None) => {}
                Err(error) => {
                    drop(indexes);
                    // The names not opened yet wait for the next pass.
                    lock(&self.reached).extend(names.iter().skip_while(|left| *left != name).cloned());
                    return Err(error);
                }
            }
        }
        Ok(())
    }

    /// Reads a table's index's rows the first time, a step a commit, and
    /// wakes whoever waits for it once they are read.
    fn fill(&self, open: &OpenIndex) -> Result<()> {
        if open.current().serving.settings.table.is_none() {
            return Ok(());
        }
        let mut stepped = false;
        while !self.file.transaction(|tx| self.fill_step(tx, &open.name))? {
            stepped = true;
        }
        if stepped {
            open.settle();
        }
        Ok(())
    }
}

/// The write of a delete of the document `id` from the rows `current` holds:
/// says whether the serving rows held it.
fn deletes(current: &Current, id: String) -> impl FnOnce(&Tx<'_>) -> Result<bool> + Send + 'static {
    let indexes: Vec<i64> = current.written().map(|data| data.id).collect();
    move |tx| {
        let mut deleted = Vec::with_capacity(indexes.len());
        for index in indexes {
            deleted.push(write::delete(tx, index, &id)?);
        }
        Ok(deleted.first().copied().unwrap_or(false))
    }
}

/// Runs `work`, which may wait, off the thread that polls an awaited write:
/// on the store's pool inside the write's submit, as `File::submit` answers
/// a copy's write there; here, outside one.
#[cfg(feature = "async")]
pub(crate) fn elsewhere(work: impl FnOnce() + Send + 'static) {
    match crate::polled::lead() {
        Some(lead) => lead(Box::new(work)),
        None => work(),
    }
}

/// Why a change needs an index read again, if it does: a change that needs
/// it to serve what was asked, a field or a filter removed whose keys it
/// drops, or `reindex`'s asking. An index rebuilt by hand refuses the first
/// until `reindex`, and leaves the second for its next rebuild.
fn rebuild_asked(changed: &Changed, wanted: &Wanted, reindex: bool) -> Result<Option<String>> {
    match &changed.rebuild {
        Some(asked) if wanted.manual && !reindex && asked.needed => Err(Error::invalid(format!(
            "{}: the index needs reading again, which an index rebuilt by hand waits for reindex to ask",
            asked.why
        ))),
        Some(_) if wanted.manual && !reindex => Ok(None),
        Some(asked) => Ok(Some(asked.why.clone())),
        None if reindex => Ok(Some("read again as reindex asked".to_owned())),
        None => Ok(None),
    }
}

#[cfg(test)]
impl Search {
    /// Reads search.db in a snapshot, as a search does.
    pub(crate) fn file_read<T>(&self, read: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
        self.file.read(read)
    }

    /// Writes search.db in a transaction of its own.
    pub(crate) fn file_write<T>(&self, write: impl FnOnce(&crate::sqlite::Tx<'_>) -> Result<T>) -> Result<T> {
        self.file.transaction(write)
    }

    /// Keeps every pass of maintenance waiting while it is held, so that a
    /// test moves a rebuild on itself, with [`rebuild`](Self::rebuild).
    #[cfg(feature = "async")]
    pub(crate) fn hold_maintenance(&self) -> std::sync::MutexGuard<'_, ()> {
        lock(&self.maintaining)
    }

    /// One step of packing an index's head, as maintenance takes them.
    pub(crate) fn pack_step(&self, open: &OpenIndex, most_rows: usize) -> Result<super::pack::Packed> {
        let id = open.id();
        self.file.transaction(|tx| super::pack::step(tx, id, most_rows))
    }

    /// Purges what an index has gone now, `most_keys` keys a step, calling
    /// `after` once each step commits.
    pub(crate) fn purge_in_steps(&self, open: &OpenIndex, most_keys: usize, mut after: impl FnMut()) -> Result<()> {
        let id = open.id();
        let mut purge = self.file.read(|connection| super::purge::begin(connection, id))?;
        loop {
            let at = self.file.transaction(|tx| purge.step(tx, id, most_keys))?;
            after();
            if purge.advance(at) {
                return Ok(());
            }
        }
    }
}

/// A count an index's row or rows give.
pub(crate) fn count(connection: &Connection, sql: &str, index: i64) -> Result<u64> {
    let failed = |error| sql_error("read an index", error);
    let mut select = connection.prepare_cached(sql).map_err(failed)?;
    let count: i64 = select.query_row([index], |row| row.get(0)).map_err(failed)?;
    Ok(count.max(0) as u64)
}

pub(crate) fn check_name(name: &str) -> Result<()> {
    crate::text::check_name("an index's", name)
}

impl crate::probe::Sample for Search {
    /// The sets each open index holds in its head, waiting to be packed.
    fn sample(&self, probe: &crate::probe::Probe) {
        let indexes: Vec<Arc<OpenIndex>> = lock(&self.indexes).values().cloned().collect();
        for index in indexes {
            let sets = index.sets.load(std::sync::atomic::Ordering::Relaxed);
            probe.set("tinystore_search_head_sets", &[("index", &index.name)], sets as f64);
        }
    }
}