tinystore 0.11.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
//! A backup of a whole store and its restore: every engine back as it was,
//! every byte checked, the program's files and the store's key only when
//! asked for, and nothing left by a backup or a restore that fails.

use std::fs;
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use std::sync::{Arc, mpsc};
use std::time::{Duration, UNIX_EPOCH};

use serde::{Deserialize, Serialize};

use super::*;
use crate::metrics::Series;
use crate::store::RESTORING;
use crate::text::hex;
use crate::{ErrorKind, Options, TestClock, sql};

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
struct Email {
    to: String,
}

const NOTES: &str = "create table notes (id integer primary key, text text not null) strict";
/// Bytes past what blobs keeps inline, so that they are a file of `objects/`.
const PHOTO: usize = 100 << 10;

struct Fixture {
    _dirs: tempfile::TempDir,
    data: PathBuf,
    zip: PathBuf,
    restored: PathBuf,
    clock: Arc<TestClock>,
}

fn fixture() -> Fixture {
    let dirs = tempfile::tempdir().unwrap();
    let (data, zip, restored) =
        (dirs.path().join("data"), dirs.path().join("backup.zip"), dirs.path().join("restored"));
    let clock = Arc::new(TestClock::new(UNIX_EPOCH + Duration::from_secs(1_800_000_000)));
    Fixture { _dirs: dirs, data, zip, restored, clock }
}

impl Fixture {
    fn open(&self, dir: &Path) -> Store {
        Store::open(dir, Options { clock: Some(self.clock.clone()), background: false, ..Options::default() }).unwrap()
    }

    /// A store with something in every engine.
    fn filled(&self) -> Store {
        let store = self.open(&self.data);
        store.bucket::<String>("codes").open().unwrap().set("K7Q2", &"kept".to_owned()).unwrap();
        let emails = store.queue::<Email>("emails").open().unwrap();
        emails.id("e-1").add(&Email { to: "ann@example.com".to_owned() }).unwrap();
        let app = store.database("app").migrations([("0001_notes.sql", NOTES)]).open().unwrap();
        app.exec(sql!("insert into notes (text) values (?)", "a note")).unwrap();
        store.files("photos").open().unwrap().put("cat.jpg", photo()).unwrap();
        store.events("audit").open().unwrap().append("role.changed", &serde_json::json!({ "user": 42 })).unwrap();
        let sample = Series::gauge("temperature").label("room", "kitchen").sample(store.now(), 21.5);
        store.metrics().unwrap().ingest(&[sample]).unwrap();
        store.index::<String>("notes").open().unwrap().set("n-1", &"sourdough starter".to_owned()).unwrap();
        store
    }

    /// Checks that a store holds what `filled` wrote.
    fn holds_everything(&self, store: &Store) {
        assert_eq!(store.bucket::<String>("codes").open().unwrap().get("K7Q2").unwrap().as_deref(), Some("kept"));
        let email = store.queue::<Email>("emails").open().unwrap().get("e-1").unwrap().expect("the job kept");
        assert_eq!(email.value.to, "ann@example.com");
        let app = store.database("app").migrations([("0001_notes.sql", NOTES)]).open().unwrap();
        assert_eq!(app.scalar::<String>(sql!("select text from notes")).unwrap(), "a note");
        let mut cat = store.files("photos").open().unwrap().get("cat.jpg").unwrap().expect("the file kept");
        assert_eq!(cat.read_all().unwrap(), photo());
        let events = store.events("audit").open().unwrap().list().page().unwrap().events;
        assert_eq!(events.iter().map(|event| event.name.as_str()).collect::<Vec<_>>(), ["role.changed"]);
        let read = store.metrics().unwrap().query().name("temperature").since(Duration::from_secs(3600)).read();
        assert_eq!(read.unwrap().series[0].samples()[0].value, 21.5);
        let notes = store.index::<String>("notes").open().unwrap();
        let hits = notes.search("starter").run().unwrap().hits;
        assert_eq!(hits.iter().map(|hit| hit.id.as_str()).collect::<Vec<_>>(), ["n-1"]);
    }
}

fn photo() -> Vec<u8> {
    (0..PHOTO).map(|at| (at % 251) as u8).collect()
}

/// The names of what a directory holds, its folders' too, `/` between parts.
fn tree(dir: &Path) -> Vec<String> {
    let mut names = Vec::new();
    let mut folders = vec![dir.to_path_buf()];
    while let Some(folder) = folders.pop() {
        for entry in fs::read_dir(&folder).unwrap() {
            let path = entry.unwrap().path();
            let name = path.strip_prefix(dir).unwrap().to_string_lossy().replace('\\', "/");
            if path.is_dir() {
                folders.push(path);
            } else {
                names.push(name);
            }
        }
    }
    names.sort();
    names
}

// contract: BAK-01
#[test]
fn a_backup_restores_every_engine_while_its_store_keeps_working() {
    let f = fixture();
    let store = f.filled();
    let backup = store.backup().write(&f.zip).unwrap();
    assert_eq!((backup.key_left_out, backup.files), (false, 8), "an engine's file each, a database's, a photo's bytes");
    store.bucket::<String>("codes").open().unwrap().set("after", &"not in it".to_owned()).unwrap();
    assert!(!tree(&f.data).iter().any(|name| name.starts_with(".snapshot-")), "the snapshot is gone");
    drop(store);

    assert_eq!(restore(&f.zip, &f.restored).unwrap(), backup);
    let restored = f.open(&f.restored);
    f.holds_everything(&restored);
    assert_eq!(restored.bucket::<String>("codes").open().unwrap().get("after").unwrap(), None);
}

#[test]
fn a_restored_records_and_metrics_file_gives_its_free_pages_back_as_its_store_made_it() {
    let f = fixture();
    let store = f.filled();
    store.backup().write(&f.zip).unwrap();
    store.close().unwrap();
    restore(&f.zip, &f.restored).unwrap();
    for name in ["records.db", "metrics.db"] {
        let flags = rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY;
        let connection = rusqlite::Connection::open_with_flags(f.restored.join(name), flags).unwrap();
        let mode: i64 = connection.query_row("pragma auto_vacuum", [], |row| row.get(0)).unwrap();
        assert_eq!(mode, 2, "{name}: incremental, as its store made it");
    }
}

// contract: BAK-01
#[test]
fn an_engine_no_handle_opened_is_backed_up_from_its_files() {
    let f = fixture();
    f.filled().close().unwrap();
    let store = f.open(&f.data);
    let backup = store.backup().write(&f.zip).unwrap();
    assert_eq!(backup.files, 8);
    drop(store);
    restore(&f.zip, &f.restored).unwrap();
    f.holds_everything(&f.open(&f.restored));
}

// contract: BAK-02
#[test]
fn a_changed_byte_is_refused_and_leaves_nothing() {
    let f = fixture();
    f.filled().backup().write(&f.zip).unwrap();
    let mut zip = fs::read(&f.zip).unwrap();
    let at = zip.windows(4).position(|bytes| bytes == b"SQLi").expect("an SQLite file's header") + 200;
    zip[at] ^= 0xff;
    fs::write(&f.zip, &zip).unwrap();
    let error = restore(&f.zip, &f.restored).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::Corrupt, "{error}");
    assert!(tree(&f.restored).is_empty(), "{:?}", tree(&f.restored));
}

// contract: BAK-02
#[test]
fn a_restore_writes_into_an_empty_directory_and_none_other() {
    let f = fixture();
    f.filled().backup().write(&f.zip).unwrap();
    fs::create_dir_all(&f.restored).unwrap();
    fs::write(f.restored.join("left.txt"), "x").unwrap();
    let error = restore(&f.zip, &f.restored).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::Invalid, "{error}");
    assert_eq!(tree(&f.restored), ["left.txt"], "what was there stays");
}

// contract: BAK-02
#[test]
fn a_directory_a_restore_did_not_finish_in_opens_not_and_takes_no_restore_saying_what_to_do() {
    let f = fixture();
    f.filled().backup().write(&f.zip).unwrap();
    restore(&f.zip, &f.restored).unwrap();
    assert!(!f.restored.join(RESTORING).exists(), "a restore that ends takes its marker away");

    // what a restore whose process died after its first file leaves
    let half = f.restored.with_extension("half");
    fs::create_dir_all(&half).unwrap();
    fs::copy(f.restored.join("kv.db"), half.join("kv.db")).unwrap();
    fs::write(half.join(RESTORING), "").unwrap();
    let opened = Store::open(&half, Options::default()).unwrap_err();
    assert_eq!(opened.kind(), ErrorKind::Invalid, "{opened}");
    let again = restore(&f.zip, &half).unwrap_err();
    assert_eq!(again.kind(), ErrorKind::Invalid, "{again}");
    let said = "the directory is not empty: a restore did not finish in it: remove the directory and restore again";
    assert!(again.to_string().contains(said), "{again}");
    assert!(half.join("kv.db").is_file() && half.join(RESTORING).is_file(), "what was there stays");

    let error = f.open(&f.data).backup().include(RESTORING).write(f.zip.with_extension("refused")).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::Invalid, "a file of the program's never takes the marker's name: {error}");
}

// contract: BAK-03
#[test]
fn a_file_of_the_programs_is_kept_only_when_named_and_one_of_the_stores_never() {
    let f = fixture();
    let store = f.filled();
    fs::write(f.data.join("secret.key"), "k3y").unwrap();
    fs::create_dir_all(f.data.join("keys")).unwrap();
    fs::write(f.data.join("keys/signing.pem"), "pem").unwrap();
    store.backup().write(&f.zip).unwrap();
    restore(&f.zip, &f.restored).unwrap();
    assert!(!f.restored.join("secret.key").exists(), "a file of the program's is left out unless named");

    fs::remove_dir_all(&f.restored).unwrap();
    fs::remove_file(&f.zip).unwrap();
    store.backup().include("secret.key").include("keys/signing.pem").write(&f.zip).unwrap();
    restore(&f.zip, &f.restored).unwrap();
    assert_eq!(fs::read_to_string(f.restored.join("secret.key")).unwrap(), "k3y");
    assert_eq!(fs::read_to_string(f.restored.join("keys/signing.pem")).unwrap(), "pem");

    for name in ["../outside", "/etc/passwd", "a\\b", "kv.db", "kv.db-wal", "LOCK", "manifest.json", "sql/app.db"] {
        let error = store.backup().include(name).write(f.zip.with_extension("refused")).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::Invalid, "{name}: {error}");
    }
    let error = store.backup().include("encryption.key").write(f.zip.with_extension("refused")).unwrap_err();
    assert!(error.to_string().contains("include_encryption_key()"), "{error}");
}

// contract: BAK-04
#[test]
fn a_backup_that_fails_leaves_no_zip() {
    let f = fixture();
    let store = f.filled();
    let error = store.backup().include("missing.txt").write(&f.zip).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::Io, "{error}");
    let beside: Vec<String> =
        tree(f.zip.parent().unwrap()).into_iter().filter(|name| name.contains("backup.zip")).collect();
    assert!(beside.is_empty(), "{beside:?}");
    assert!(!tree(&f.data).iter().any(|name| name.starts_with(".snapshot-")), "the snapshot is gone");
}

// contract: BAK-04, ERR-05
#[test]
fn a_backup_the_disk_has_no_room_for_fails_limit_before_it_copies() {
    let f = fixture();
    f.filled().close().unwrap();
    // a disk with a gibibyte less than the store keeps free
    let keep_free = crate::space::available(&f.data).unwrap().saturating_add(1 << 30);
    let options = Options { clock: Some(f.clock.clone()), background: false, keep_free, ..Options::default() };
    let store = Store::open(&f.data, options).unwrap();
    let error = store.backup().write(&f.zip).unwrap_err();
    assert_eq!((error.kind(), error.fact("limit")), (ErrorKind::Limit, Some("disk space")), "{error}");
    let said = error.to_string();
    assert!(
        error.fact("bound").is_some() && said.contains("its snapshot: ") && said.contains("where the disk has"),
        "{said}"
    );
    // what each SQLite file and its WAL hold, the photo's bytes linked
    let sqlite: u64 = tree(&f.data)
        .iter()
        .filter(|name| name.ends_with(".db") || name.ends_with(".db-wal"))
        .map(|name| fs::metadata(f.data.join(name)).unwrap().len())
        .sum();
    assert_eq!(error.fact("wanted"), Some(sqlite.to_string().as_str()), "{error}");
    let beside: Vec<String> =
        tree(f.zip.parent().unwrap()).into_iter().filter(|name| name.contains("backup.zip")).collect();
    assert!(beside.is_empty(), "{beside:?}");
    assert!(!tree(&f.data).iter().any(|name| name.starts_with(".snapshot-")), "the snapshot is gone");
}

/// A zip's writer that stops at its first byte until it is let go, and
/// keeps nothing.
struct Stopped {
    stopped: Option<mpsc::Sender<()>>,
    go_on: mpsc::Receiver<()>,
}

impl Write for Stopped {
    fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
        if let Some(stopped) = self.stopped.take() {
            stopped.send(()).unwrap();
            self.go_on.recv().unwrap();
        }
        Ok(bytes.len())
    }

    fn flush(&mut self) -> io::Result<()> {
        Ok(())
    }
}

// contract: BAK-04
#[test]
fn a_store_opened_again_while_a_backup_runs_keeps_its_snapshot() {
    let f = fixture();
    let store = f.filled();
    let (stopped, stops) = mpsc::channel();
    let (go_on, goes_on) = mpsc::channel();
    let backup = store.backup();
    let backing_up = std::thread::spawn(move || backup.write_to(Stopped { stopped: Some(stopped), go_on: goes_on }));
    stops.recv_timeout(Duration::from_secs(10)).unwrap();
    // the store opened again while its backup copies, as a server restarted
    // beside the backup the command line takes
    store.close().unwrap();
    let again = f.open(&f.data);
    assert!(tree(&f.data).iter().any(|name| name.starts_with(".snapshot-")), "the running backup's snapshot stays");
    go_on.send(()).unwrap();
    assert_eq!(backing_up.join().unwrap().unwrap().files, 8);
    assert!(!tree(&f.data).iter().any(|name| name.starts_with(".snapshot-")), "and goes with its backup");
    again.close().unwrap();
}

// contract: BAK-03
#[test]
fn the_encryption_key_is_left_out_unless_asked_for_and_the_backup_says_so() {
    let f = fixture();
    let store = f.open(&f.data);
    let passwords = store.bucket::<String>("passwords").encrypted().open().unwrap();
    passwords.set("db", &"hunter2".to_owned()).unwrap();
    let without = store.backup().write(&f.zip).unwrap();
    assert!(without.key_left_out);
    restore(&f.zip, &f.restored).unwrap();
    assert!(!f.restored.join(KEY).exists());
    let error = f.open(&f.restored).bucket::<String>("passwords").encrypted().open().unwrap_err();
    assert!(error.to_string().contains("encrypted with the key"), "a bucket whose key is not there says so: {error}");

    let (zip, restored) = (f.zip.with_extension("keyed"), f.restored.with_extension("keyed"));
    let with = store.backup().include_encryption_key().write(&zip).unwrap();
    assert!(!with.key_left_out);
    restore(&zip, &restored).unwrap();
    let back = f.open(&restored);
    let passwords = back.bucket::<String>("passwords").encrypted().open().unwrap();
    assert_eq!(passwords.get("db").unwrap().as_deref(), Some("hunter2"));
}

// contract: BAK-03
#[test]
fn a_backup_with_the_key_says_it_leaves_out_an_older_key_until_a_reseal() {
    let f = fixture();
    f.open(&f.data).bucket::<String>("passwords").encrypted().open().unwrap().set("db", &"hunter2".to_owned()).unwrap();
    let (old, new) = (f.data.join("old.key"), f.data.join("encryption.key"));
    fs::rename(&new, &old).unwrap();
    fs::write(&new, "cd".repeat(32)).unwrap();
    let options = Options { clock: Some(f.clock.clone()), older_encryption_keys: vec![old], ..Options::default() };
    let store = Store::open(&f.data, Options { background: false, ..options }).unwrap();
    let passwords = store.bucket::<String>("passwords").encrypted().open().unwrap();

    let before = store.backup().include_encryption_key().write(&f.zip).unwrap();
    assert!(before.key_left_out, "the old key sealed a value, and a backup takes the sealing key alone");
    passwords.reseal().unwrap();
    let after = store.backup().include_encryption_key().write(f.zip.with_extension("resealed")).unwrap();
    assert!(!after.key_left_out);
}

// contract: BAK-03
#[test]
fn a_backup_beside_a_holder_that_keeps_its_key_apart_says_it_leaves_the_key_out() {
    let f = fixture();
    let key = f.zip.with_file_name("tinystore.key");
    fs::write(&key, "0f".repeat(32)).unwrap();
    let options = Options { encryption_key_file: Some(key), background: false, ..Options::default() };
    let held = Store::open(&f.data, options).unwrap();
    let db = held.database("app").open().unwrap();
    db.bucket::<String>("passwords").encrypted().open().unwrap().set("db", &"hunter2".to_owned()).unwrap();

    // beside its holder, the store reads a key in its directory alone, and finds none
    let beside = Store::open_beside(&f.data).unwrap();
    let asked = beside.backup().include_encryption_key().write(&f.zip).unwrap_err();
    assert_eq!(asked.kind(), ErrorKind::Io, "{asked}");
    assert!(asked.to_string().contains("values sealed with the key"), "{asked}");
    assert!(!f.zip.exists(), "no zip without the key it was asked to take");
    let without = beside.backup().write(&f.zip).unwrap();
    assert!(without.key_left_out, "the backup says the values it holds open with a key it does not");
    assert!(restore(&f.zip, &f.restored).unwrap().key_left_out, "and its restore says so too");
    held.close().unwrap();
}

// contract: BAK-03
#[test]
fn a_backup_of_a_store_that_seals_nothing_misses_no_key() {
    let f = fixture();
    let store = f.open(&f.data);
    store.bucket::<String>("tokens").encrypted().open().unwrap();
    assert!(f.data.join(KEY).exists(), "the key is made for the encrypted bucket");
    assert!(!store.backup().write(&f.zip).unwrap().key_left_out, "nothing it holds needs the key");
}

// contract: BAK-04
#[test]
fn a_closed_store_takes_no_backup() {
    let f = fixture();
    let store = f.filled();
    let again = store.clone();
    store.close().unwrap();
    let error = again.backup().write(&f.zip).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::Closed, "{error}");
    assert!(!f.zip.exists());
}

// contract: BAK-01
#[test]
fn a_backup_copies_while_a_writer_writes_and_holds_a_moment_of_it() {
    let f = fixture();
    let store = f.filled();
    let codes = store.bucket::<i64>("counted").open().unwrap();
    let writer = {
        let codes = codes.clone();
        std::thread::spawn(move || (0..300).for_each(|n| codes.set(format!("k{n:03}"), &n).unwrap()))
    };
    store.backup().write(&f.zip).unwrap();
    writer.join().unwrap();
    drop(store);
    restore(&f.zip, &f.restored).unwrap();
    let restored = f.open(&f.restored);
    let counted = restored.bucket::<i64>("counted").open().unwrap();
    let mut held = 0;
    for n in 0..300 {
        match counted.get(format!("k{n:03}")).unwrap() {
            Some(value) => {
                assert_eq!((value, n), (n, held), "the writes before the copy's moment, in order");
                held += 1;
            }
            None => break,
        }
    }
    assert!((held..300).all(|n| counted.get(format!("k{n:03}")).unwrap().is_none()), "a moment: nothing after a gap");
}

/// A collector's cursor in the program's database, saying how far its samples
/// in metrics.db go.
const CURSOR: &str = "create table cursor (id integer primary key, upto integer not null) strict; \
                      insert into cursor values (1, -1)";

// contract: BAK-01
#[test]
fn a_backup_is_one_moment_of_the_store_so_a_cursor_names_only_samples_it_holds() {
    for metrics_first in [false, true] {
        let f = fixture();
        let store = f.open(&f.data);
        // the files were copied in the order their engines opened
        let early = metrics_first.then(|| store.metrics().unwrap());
        let db = store.database("app").migrations([("0001_cursor.sql", CURSOR)]).open().unwrap();
        let stats = early.unwrap_or_else(|| store.metrics().unwrap());
        let base = store.now() - Duration::from_secs(3600);
        let stop = std::sync::atomic::AtomicBool::new(false);
        std::thread::scope(|scope| {
            scope.spawn(|| {
                for i in 0_i64.. {
                    if stop.load(std::sync::atomic::Ordering::Relaxed) {
                        break;
                    }
                    let at = base + Duration::from_millis(i as u64);
                    stats.ingest(&[Series::gauge("reading").sample(at, i as f64)]).unwrap();
                    db.exec(sql!("update cursor set upto = ? where id = 1", i)).unwrap();
                }
            });
            for n in 0..4 {
                std::thread::sleep(Duration::from_millis(30));
                let (zip, restored) = (f.zip.with_extension(format!("{n}.zip")), f.restored.join(n.to_string()));
                store.backup().write(&zip).unwrap();
                restore(&zip, &restored).unwrap();
                let again = f.open(&restored);
                let app = again.database("app").migrations([("0001_cursor.sql", CURSOR)]).open().unwrap();
                let cursor: i64 = app.scalar(sql!("select upto from cursor where id = 1")).unwrap();
                let read = again.metrics().unwrap().query().name("reading").since(Duration::from_secs(7200)).read();
                let kept = read.unwrap().series.iter().flat_map(|series| series.samples().to_vec()).count() as i64;
                assert!(
                    kept == cursor + 1 || kept == cursor + 2,
                    "metrics first {metrics_first}, backup {n}: the cursor says {cursor}, and {kept} samples are kept"
                );
            }
            stop.store(true, std::sync::atomic::Ordering::Relaxed);
        });
    }
}

// contract: BAK-02
#[test]
fn a_file_whose_sha256_is_not_its_manifests_is_refused_though_its_crc_is_the_zips() {
    let f = fixture();
    let (bytes, other) = (b"kv's bytes".to_vec(), b"kv's other".to_vec());
    let listed = manifest::Listed {
        name: "kv.db".to_owned(),
        engine: "kv",
        size: other.len() as u64,
        sha256: hex(&Sha256::digest(&other)),
    };
    let manifest = Manifest { created: 0, files: vec![listed], key_left_out: false }.to_json();
    let mut writer = zip::Writer::new(Vec::new());
    writer.add("kv.db", bytes.len() as u64, bytes.as_slice(), |_| {}).unwrap();
    writer.add(MANIFEST, manifest.len() as u64, manifest.as_bytes(), |_| {}).unwrap();
    fs::write(&f.zip, writer.finish().unwrap()).unwrap();
    let error = restore(&f.zip, &f.restored).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::Corrupt, "{error}");
    assert!(error.to_string().contains("kv.db: its SHA-256 is not its manifest's"), "{error}");
    assert!(tree(&f.restored).is_empty());
}

/// A file as a manifest lists it, with `padding` spaces inside its object,
/// as JSON allows.
fn listing(name: &str, bytes: &[u8], padding: usize) -> String {
    let (size, sha256, spaces) = (bytes.len(), hex(&Sha256::digest(bytes)), " ".repeat(padding));
    format!(r#"{{"name":"{name}","engine":"program","size":{size},{spaces}"sha256":"{sha256}"}}"#)
}

/// A manifest of format 1 that lists `listings`.
fn manifest_of(listings: impl Iterator<Item = String>) -> String {
    let mut text = String::from(r#"{"format":1,"created":0,"files":["#);
    for (at, listing) in listings.enumerate() {
        if at > 0 {
            text.push(',');
        }
        text.push_str(&listing);
    }
    text.push_str("]}\n");
    text
}

/// Writes a zip of `files` and `manifest` at `path`.
fn zipped(path: &Path, files: &[(String, Vec<u8>)], manifest: &str) {
    let mut writer = zip::Writer::new(Vec::new());
    for (name, bytes) in files {
        writer.add(name, bytes.len() as u64, bytes.as_slice(), |_| {}).unwrap();
    }
    writer.add(MANIFEST, manifest.len() as u64, manifest.as_bytes(), |_| {}).unwrap();
    fs::write(path, writer.finish().unwrap()).unwrap();
}

// contract: BAK-02
#[test]
fn a_restore_reads_a_manifest_longer_than_64_mib() {
    let f = fixture();
    // spaces in each file's field, so that a few files make a manifest that
    // long, as some hundreds of thousands of files do
    let files: Vec<(String, Vec<u8>)> = (0..70_u8).map(|n| (format!("notes/{n:02}"), vec![n])).collect();
    let manifest = manifest_of(files.iter().map(|(name, bytes)| listing(name, bytes, 1_000_000)));
    assert!(manifest.len() > 64 << 20, "{} bytes", manifest.len());
    zipped(&f.zip, &files, &manifest);
    drop(manifest);
    let restored = restore(&f.zip, &f.restored).unwrap();
    assert_eq!((restored.files, restored.bytes), (70, 70));
    assert_eq!(fs::read(f.restored.join("notes/69")).unwrap(), [69]);
}

// contract: BAK-02
#[test]
fn a_manifest_lists_no_more_files_than_its_zip_holds_nor_a_field_past_a_mebibyte() {
    let f = fixture();
    let files = vec![("kv.db".to_owned(), b"kv's bytes".to_vec())];
    let (name, bytes) = &files[0];
    zipped(&f.zip, &files, &manifest_of((0..3).map(|_| listing(name, bytes, 0))));
    let error = restore(&f.zip, &f.restored).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::Corrupt, "{error}");
    assert!(error.to_string().contains("more files than the 2 its zip holds"), "{error}");

    zipped(&f.zip, &files, &manifest_of(std::iter::once(listing(name, bytes, 1_100_000))));
    let error = restore(&f.zip, &f.restored).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::Corrupt, "{error}");
    assert!(error.to_string().contains("past 1048576 bytes"), "{error}");
    assert!(!f.restored.exists(), "a restore writes nothing before its manifest reads");
}

// contract: BAK-02
#[test]
fn a_manifest_an_older_release_wrote_reads_as_it_did_and_the_one_written_now_alike() {
    // with the spaces of the releases before, which every release reads
    let older = r#"{
  "created": 1800000000000,
  "files": [
    {
      "engine": "kv",
      "name": "kv.db",
      "sha256": "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
      "size": 8192
    }
  ],
  "format": 1,
  "keyLeftOut": true
}
"#;
    let sha256 = "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08".to_owned();
    let kv = manifest::Listed { name: "kv.db".to_owned(), engine: "kv", size: 8192, sha256 };
    let read = Manifest::read(older.as_bytes(), 2).unwrap();
    assert_eq!(read, Manifest { created: 1_800_000_000_000, files: vec![kv], key_left_out: true });
    let written = read.to_json();
    assert!(!written.contains(' '), "written without the spaces: {written}");
    assert_eq!(Manifest::read(written.as_bytes(), 2).unwrap(), read);
}

/// The backup at `path` written again with every file of the database `from`
/// as the database `to`'s, as a store that held `to` would have backed it up.
fn renamed_database(path: &Path, from: &str, to: &str) {
    let (old, new) = (format!("sql/{from}."), format!("sql/{to}."));
    let mut archive = io::BufReader::new(fs::File::open(path).unwrap());
    let (mut files, mut manifest) = (Vec::new(), String::new());
    for entry in zip::entries(&mut archive).unwrap() {
        let mut bytes = Vec::new();
        zip::open(&mut archive, &entry).unwrap().read_to_end(&mut bytes).unwrap();
        if entry.name == MANIFEST {
            manifest = String::from_utf8(bytes).unwrap().replace(&format!("\"{old}"), &format!("\"{new}"));
            continue;
        }
        let name = entry.name.strip_prefix(&old).map_or_else(|| entry.name.clone(), |rest| format!("{new}{rest}"));
        files.push((name, bytes));
    }
    zipped(path, &files, &manifest);
}

// On Windows, before Windows 11, sql/nul.db is the device NUL and not a file,
// so a backup made elsewhere of a store that holds such a database restores
// there not.
// contract: BAK-02, SQL-11
#[test]
fn a_database_windows_reads_as_a_device_restores_on_windows_not_and_writes_nothing_there() {
    let f = fixture();
    let store = f.open(&f.data);
    let app = store.database("app").migrations([("0001_notes.sql", NOTES)]).open().unwrap();
    app.exec(sql!("insert into notes (text) values (?)", "a note")).unwrap();
    app.files("photos").open().unwrap().put("cat.jpg", photo()).unwrap();
    store.backup().write(&f.zip).unwrap();
    drop(app);
    store.close().unwrap();
    renamed_database(&f.zip, "app", "nul");

    let restored = restore(&f.zip, &f.restored);
    if cfg!(windows) {
        let error = restored.unwrap_err();
        assert_eq!(error.kind(), ErrorKind::Invalid, "{error}");
        assert!(error.to_string().contains(r#"a database's name "nul""#), "{error}");
        assert!(!f.restored.exists(), "a restore refused makes no directory");
        fs::create_dir_all(&f.restored).unwrap();
        assert_eq!(restore(&f.zip, &f.restored).unwrap_err().kind(), ErrorKind::Invalid);
        assert!(fs::read_dir(&f.restored).unwrap().next().is_none(), "an empty directory stays empty");
    } else {
        restored.unwrap();
        let store = f.open(&f.restored);
        let nul = store.database("nul").migrations([("0001_notes.sql", NOTES)]).open().unwrap();
        assert_eq!(nul.scalar::<String>(sql!("select text from notes")).unwrap(), "a note");
        let mut cat = nul.files("photos").open().unwrap().get("cat.jpg").unwrap().expect("the file kept");
        assert_eq!(cat.read_all().unwrap(), photo());
    }
}

// contract: BAK-02
#[test]
fn a_file_beside_a_database_or_of_the_programs_named_as_a_device_restores_on_windows_not() {
    let f = fixture();
    let restores = |name: &str| {
        let (file, bytes) = (name.to_owned(), b"bytes".to_vec());
        zipped(&f.zip, &[(file, bytes.clone())], &manifest_of(std::iter::once(listing(name, &bytes, 0))));
        let _ = fs::remove_dir_all(&f.restored);
        restore(&f.zip, &f.restored)
    };
    for name in ["sql/nul.db-wal", "sql/com1.blobs/objects/1a3/1a3f07", "sql/lpt9.db", "sql/aux.db"] {
        match restores(name) {
            Err(error) if cfg!(windows) => {
                assert_eq!(error.kind(), ErrorKind::Invalid, "{name}: {error}");
                let database = name["sql/".len()..].split(['.', '/']).next().unwrap();
                assert!(error.to_string().contains(&format!("a database's name {database:?}")), "{error}");
                assert!(!f.restored.exists(), "{name}: made the directory");
            }
            restored => assert!(restored.is_ok() && !cfg!(windows), "{name}: {restored:?}"),
        }
    }
    // a file of the program's too, whatever the case of its name
    match restores("keys/Con.pem") {
        Err(error) if cfg!(windows) => {
            let said = r#"keys/Con.pem: "con": Windows reads it as a device, not a file"#;
            assert!(error.kind() == ErrorKind::Invalid && error.to_string().contains(said), "{error}");
        }
        restored => assert!(restored.is_ok() && !cfg!(windows), "{restored:?}"),
    }
    for name in ["sql/com10.db", "sql/console.db", "sql/nul_x.db", "sql/app.db", "keys/console.pem"] {
        restores(name).unwrap();
        assert_eq!(fs::read(f.restored.join(name)).unwrap(), b"bytes", "{name}");
    }
}

#[test]
fn an_archive_shorter_than_a_zip_end_is_corrupt() {
    let f = fixture();
    for length in [0, 1, 3, 21] {
        fs::write(&f.zip, vec![b'P'; length]).unwrap();
        let error = restore(&f.zip, &f.restored).unwrap_err();
        assert_eq!(error.kind(), ErrorKind::Corrupt, "{length} bytes: {error}");
    }
}

// contract: BAK-06
#[test]
fn verify_checks_what_a_restore_checks_and_writes_nothing() {
    let f = fixture();
    let written = f.filled().backup().write(&f.zip).unwrap();
    let around = tree(f.zip.parent().unwrap());
    let zip = fs::read(&f.zip).unwrap();
    assert_eq!(verify(&f.zip).unwrap(), written, "the files and the bytes a restore writes");
    assert_eq!(tree(f.zip.parent().unwrap()), around, "nothing written beside the zip");
    assert_eq!(fs::read(&f.zip).unwrap(), zip, "the zip as it was");
    assert!(!f.restored.exists());

    let mut changed = zip.clone();
    let at = changed.windows(4).position(|bytes| bytes == b"SQLi").expect("an SQLite file's header") + 200;
    changed[at] ^= 0xff;
    fs::write(&f.zip, &changed).unwrap();
    let error = verify(&f.zip).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::Corrupt, "{error}");
    assert!(error.to_string().contains(".db: "), "names the file: {error}");
    assert_eq!(restore(&f.zip, &f.restored).unwrap_err().kind(), ErrorKind::Corrupt, "a restore refuses it too");

    fs::write(&f.zip, &zip[..zip.len() - 30]).unwrap();
    assert_eq!(verify(&f.zip).unwrap_err().kind(), ErrorKind::Corrupt, "a zip cut short");
}

// contract: BAK-06
#[test]
fn verify_refuses_a_file_whose_sha256_is_not_its_manifests_or_that_its_zip_lacks_naming_it() {
    let f = fixture();
    let (bytes, other) = (b"kv's bytes".to_vec(), b"kv's other".to_vec());
    zipped(&f.zip, &[("kv.db".to_owned(), bytes)], &manifest_of(std::iter::once(listing("kv.db", &other, 0))));
    let error = verify(&f.zip).unwrap_err();
    assert_eq!(error.kind(), ErrorKind::Corrupt, "{error}");
    assert!(error.to_string().contains("kv.db: its SHA-256 is not its manifest's"), "{error}");
    zipped(&f.zip, &[], &manifest_of(std::iter::once(listing("sql/app.db", b"rows", 0))));
    let error = verify(&f.zip).unwrap_err();
    assert!(error.kind() == ErrorKind::Corrupt && error.to_string().contains("sql/app.db: listed by"), "{error}");
}

/// A report of 5 MiB, far past what blobs keeps inline, so that its bytes
/// are a file of `local/uploads.blobs/objects/`; no stretch of it repeats,
/// so that a stretch found in a zip is the report's.
fn report() -> Vec<u8> {
    let mut state: u64 = 0x9e37_79b9_7f4a_7c15;
    (0..5 << 20)
        .map(|_| {
            state ^= state << 13;
            state ^= state >> 7;
            state ^= state << 17;
            (state >> 24) as u8
        })
        .collect()
}

/// Checks that the zip at `path` holds nothing of the database `uploads`:
/// no file of it by name, no line of its manifest, and no stretch of the
/// report's bytes anywhere, whatever name they might go under.
fn holds_nothing_of_uploads(path: &Path) {
    let bytes = fs::read(path).unwrap();
    let mut zip = io::Cursor::new(&bytes);
    let entries = zip::entries(&mut zip).unwrap();
    let names: Vec<&str> = entries.iter().map(|entry| entry.name.as_str()).collect();
    assert!(!names.iter().any(|name| name.contains("uploads") || name.starts_with("local")), "{names:?}");
    let listed = entries.iter().find(|entry| entry.name == MANIFEST).unwrap();
    let mut manifest = String::new();
    zip::open(&mut zip, listed).unwrap().read_to_string(&mut manifest).unwrap();
    assert!(!manifest.contains("uploads") && !manifest.contains("local"), "{manifest}");
    let report = report();
    for at in [0, 1 << 20, (5 << 20) - 64] {
        let stretch = &report[at..at + 64];
        assert!(!bytes.windows(64).any(|window| window == stretch), "the report's bytes at {at} are in the zip");
    }
}

// contract: BAK-05
#[test]
fn a_database_left_out_of_backups_is_in_none_open_or_closed_nor_any_byte_of_its_files() {
    let f = fixture();
    let store = f.filled();
    let uploads = store.database("uploads").backup(false).open().unwrap();
    let pending = uploads.files("pending").ttl(Duration::from_secs(15 * 60)).open().unwrap();
    pending.put("u1/report.pdf", report()).unwrap();
    assert!(f.data.join("local/uploads.db").is_file() && f.data.join("local/uploads.blobs").is_dir());
    assert!(!f.data.join("sql/uploads.db").exists(), "{:?}", tree(&f.data));

    let open = store.backup().write(&f.zip).unwrap();
    assert_eq!(open.excluded, ["uploads"], "the answer names what it left out");
    assert_eq!(open.files, 8, "what filled() holds, and nothing more");
    holds_nothing_of_uploads(&f.zip);
    drop((pending, uploads));
    store.close().unwrap();

    let store = f.open(&f.data);
    let closed_zip = f.zip.with_file_name("closed.zip");
    let closed = store.backup().write(&closed_zip).unwrap();
    assert_eq!((closed.excluded, closed.files), (vec!["uploads".to_owned()], 8), "with no handle open");
    holds_nothing_of_uploads(&closed_zip);
    let named = store.backup().include("local/uploads.db").write(f.zip.with_file_name("named.zip"));
    assert_eq!(named.unwrap_err().kind(), ErrorKind::Invalid, "a program's include takes none of it either");
    drop(store);

    let restored = restore(&f.zip, &f.restored).unwrap();
    assert!(restored.excluded.is_empty(), "a zip says nothing of what it lacks");
    assert!(!f.restored.join("local").exists(), "{:?}", tree(&f.restored));
    let store = f.open(&f.restored);
    f.holds_everything(&store);
    let uploads = store.database("uploads").backup(false).open().unwrap();
    assert!(uploads.files("pending").open().unwrap().get("u1/report.pdf").unwrap().is_none(), "opened empty");
}