mln-rs-engine 0.0.23

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

use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};

use geo_types::{Geometry, Point};
use mln_style::geo::{LatLng, LatLngBounds};
use mln_style::tileset::Scheme;
use rusqlite::{Connection, OpenFlags};

use super::{TempPath, fixture, incompressible, temp_path};
use crate::storage::chrono::{Timestamp, now};
use crate::storage::offline::{
    OfflineGeometryRegionDefinition, OfflineRegion, OfflineRegionDefinition, OfflineRegionExpiry,
    OfflineRegionMetadata, OfflineRegionStatus, OfflineTilePyramidRegionDefinition,
};
use crate::storage::offline_database::OfflineDatabase;
use crate::storage::resource::{Kind, LoadingMethod, Resource, TileData, TileFormat};
use crate::storage::response::{Caching, Data, Reason, ResourceError, Response};

fn style(url: &str) -> Resource {
    Resource::style(url)
}

fn tile(url: &str, x: i32, y: i32, z: i8) -> Resource {
    Resource::tile(url, 1.0, x, y, z, Scheme::Xyz, TileFormat::Mvt, LoadingMethod::ALL)
}

fn bytes(s: &str) -> Data {
    Arc::new(s.as_bytes().to_vec())
}

fn with_data(data: Data) -> Response {
    let mut response = Response::new();
    response.data = Some(data);
    response
}

fn no_content() -> Response {
    let mut response = Response::new();
    response.no_content = true;
    response
}

fn stored_data(db: &mut OfflineDatabase, resource: &Resource) -> Option<Vec<u8>> {
    db.get(resource).and_then(|response| response.data).map(|data| data.to_vec())
}

fn pyramid(min_zoom: f64, max_zoom: f64, include_ideographs: bool) -> OfflineRegionDefinition {
    let bounds = LatLngBounds::hull(LatLng::new(1.0, 2.0).unwrap(), LatLng::new(3.0, 4.0).unwrap());
    OfflineTilePyramidRegionDefinition::new(
        "https://example.com/style",
        bounds,
        min_zoom,
        max_zoom,
        2.0,
        include_ideographs,
    )
    .unwrap()
    .into()
}

fn world() -> OfflineRegionDefinition {
    OfflineTilePyramidRegionDefinition::new("", LatLngBounds::world(), 0.0, f64::INFINITY, 1.0, true).unwrap().into()
}

fn region(db: &mut OfflineDatabase, definition: &OfflineRegionDefinition) -> OfflineRegion {
    db.create_region(definition, &OfflineRegionMetadata::new()).expect("a region")
}

/// Copies the fixture database `name` to `path`.
fn copy_fixture(name: &str, path: &str) {
    std::fs::copy(fixture(&format!("offline_database/{name}")), path).expect("copy the fixture");
}

/// A copy of the fixture database `name`, which the test may change.
fn copy_of(name: &str) -> TempPath {
    let path = temp_path(name);
    copy_fixture(name, &path);
    path
}

fn file_size(path: &str) -> u64 {
    std::fs::metadata(path).expect("the database file").len()
}

fn sql(path: &str, sql: &str) {
    Connection::open(path).unwrap().execute_batch(sql).unwrap();
}

fn query<T: rusqlite::types::FromSql>(path: &str, sql: &str) -> T {
    let connection = Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY).unwrap();
    connection.query_row(sql, [], |row| row.get(0)).unwrap()
}

fn columns(path: &str, table: &str) -> Vec<String> {
    let connection = Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY).unwrap();
    let mut statement = connection.prepare(&format!("pragma table_info({table})")).unwrap();
    statement.query_map([], |row| row.get(1)).unwrap().collect::<Result<_, _>>().unwrap()
}

/// Checks that the database at `path` has the current schema.
fn assert_current_schema(path: &str, case: &str) {
    assert_eq!(6, query::<i64>(path, "pragma user_version"), "{case}");
    assert_eq!(2, query::<i64>(path, "pragma auto_vacuum"), "incremental vacuum: {case}");
    assert_eq!("delete", query::<String>(path, "pragma journal_mode"), "{case}");
    let tiles = "id url_template pixel_ratio z x y expires modified etag data compressed accessed must_revalidate";
    assert_eq!(tiles.split(' ').collect::<Vec<_>>(), columns(path, "tiles"), "{case}");
    let resources = "id url kind expires modified etag data compressed accessed must_revalidate";
    assert_eq!(resources.split(' ').collect::<Vec<_>>(), columns(path, "resources"), "{case}");
}

/// Checks that `db` stores and returns a style and a tile.
fn assert_usable(db: &mut OfflineDatabase) {
    for resource in [style("https://example.com/style"), tile("https://example.com/{z}/{x}/{y}", 0, 0, 0)] {
        assert_eq!((true, 5), db.put(&resource, &with_data(bytes("first"))));
        assert_eq!(Some(b"first".to_vec()), stored_data(db, &resource));
    }
}

#[test]
fn a_new_database_has_the_current_schema() {
    type Setup = fn(&str);
    let cases: [(&str, Setup); 3] = [
        ("no file", |_| {}),
        ("an empty file, as a runtime creates for its cache path", |path| std::fs::write(path, "").unwrap()),
        ("a cache database of before regions", |path| sql(path, "PRAGMA user_version = 1")),
    ];
    for (case, setup) in cases {
        let path = temp_path("offline.db");
        setup(&path);

        let mut db = OfflineDatabase::new(&*path);
        assert_usable(&mut db);
        drop(db);
        assert_current_schema(&path, case);
    }
}

#[test]
fn an_older_schema_migrates_and_keeps_working() {
    // v4 used `journal_mode = WAL`; no_auto_vacuum has the current version
    // without incremental vacuum.
    for name in ["v2.db", "v3.db", "v4.db", "v5.db", "no_auto_vacuum.db"] {
        let path = copy_of(name);
        {
            let mut db = OfflineDatabase::new(&*path);
            db.set_maximum_ambient_cache_size(0).unwrap();
            for region in db.list_regions().unwrap() {
                db.delete_region(&region).unwrap();
            }
            assert_eq!(Vec::<OfflineRegion>::new(), db.list_regions().unwrap(), "{name}");
        }
        assert_current_schema(&path, name);
    }
}

#[test]
fn a_database_it_cannot_use_is_replaced() {
    type Setup = fn(&str);
    let cases: [(&str, Setup); 3] = [
        ("not a database", |path| std::fs::write(path, "this is an invalid file").unwrap()),
        ("corrupt", |path| copy_fixture("corrupt-immediate.db", path)),
        ("a newer schema", |path| copy_fixture("v999.db", path)),
    ];
    for (case, setup) in cases {
        let path = temp_path("offline.db");
        setup(&path);

        let mut db = OfflineDatabase::new(&*path);
        assert_eq!(Vec::<OfflineRegion>::new(), db.list_regions().unwrap(), "{case}");
        assert_usable(&mut db);
        drop(db);
        assert_current_schema(&path, case);
    }
}

#[test]
fn a_database_found_corrupt_by_a_query_is_replaced() {
    // It opens, and fails its first read.
    let path = copy_of("corrupt-delayed.db");
    let mut db = OfflineDatabase::new(&*path);
    assert_eq!(None, db.get(&tile("https://example.com/{z}/{x}/{y}", 0, 0, 0)));
    assert_usable(&mut db);
}

#[test]
fn a_stored_response_is_returned_and_replaced() {
    let tile_data = TileData {
        url_template: "http://example.com/".to_owned(),
        pixel_ratio: 1,
        x: 0,
        y: 0,
        z: 0,
        format: TileFormat::Mvt,
    };
    let resources = [
        style("http://example.com/"),
        Resource::with_tile_data(Kind::Tile, "http://example.com/", Some(tile_data), LoadingMethod::ALL),
        // A tile without its address is stored by its URL.
        Resource::new(Kind::Tile, "http://example.com/0/0/0.pbf"),
    ];
    for resource in resources {
        let mut db = OfflineDatabase::new(":memory:");
        assert_eq!((true, 5), db.put(&resource, &with_data(bytes("first"))), "inserted: {resource:?}");
        assert_eq!(Some(b"first".to_vec()), stored_data(&mut db, &resource));
        assert_eq!((false, 6), db.put(&resource, &with_data(bytes("second"))), "updated: {resource:?}");
        assert_eq!(Some(b"second".to_vec()), stored_data(&mut db, &resource));

        db.put(&resource, &no_content());
        let stored = db.get(&resource).expect("the copy without content");
        assert!(stored.no_content && stored.data.is_none() && stored.error.is_none(), "{resource:?}");
    }
}

#[test]
fn what_must_not_be_cached_is_not_stored() {
    let error = |reason| {
        let mut response = Response::new();
        response.error = Some(Box::new(ResourceError::new(reason, "")));
        response
    };
    // A tile's 404 would read back as an empty tile.
    let mut tile_not_found = no_content();
    tile_not_found.tile_not_found = true;
    let mut no_store = with_data(bytes("data"));
    no_store.no_store = true;
    let tile = tile("http://example.com/{z}/{x}/{y}", 0, 0, 0);
    for (case, response) in [
        ("a connection error", error(Reason::Connection)),
        ("a server error", error(Reason::Server)),
        ("a tile that isn't found", tile_not_found),
        ("what the server forbids storing", no_store),
    ] {
        let mut db = OfflineDatabase::new(":memory:");
        assert_eq!((false, 0), db.put(&tile, &response), "{case}");
        assert_eq!(None, db.get(&tile), "{case}");
    }
}

#[test]
fn a_byte_range_has_a_cache_key_of_its_own() {
    let cases = [
        ("https://example.com/x.pmtiles", None, "https://example.com/x.pmtiles"),
        ("https://example.com/x.pmtiles", Some((0, 126)), "https://example.com/x.pmtiles?_mlnRange=0-126"),
        (
            "https://example.com/x.pmtiles?token=abc",
            Some((200, 399)),
            "https://example.com/x.pmtiles?token=abc&_mlnRange=200-399",
        ),
    ];
    for (url, range, key) in cases {
        let mut resource = Resource::new(Kind::Source, url);
        resource.data_range = range;
        assert_eq!(key, OfflineDatabase::cache_key(&resource));
    }
}

#[test]
fn put_reports_the_stored_size() {
    let mut db = OfflineDatabase::new(":memory:");

    let compressible = with_data(Arc::new(vec![0u8; 1024]));
    let size = db.put(&style("http://example.com/compressible"), &compressible).1;
    assert!(0 < size && size < 1024, "stored compressed: {size}");
    assert_eq!(compressible.data, db.get(&style("http://example.com/compressible")).unwrap().data);

    assert_eq!(1024, db.put(&style("http://example.com/incompressible"), &with_data(incompressible(1024))).1);
    assert_eq!(0, db.put(&style("http://example.com/noContent"), &no_content()).1);
}

/// A 304, or the copy it delivered, renews a copy's caching rules and keeps
/// its data.
#[test]
fn a_renewal_keeps_the_data_and_takes_the_caching_rules() {
    let mut db = OfflineDatabase::new(":memory:");
    let at = |secs: i64| Some(Timestamp::from_secs(secs));

    for resource in [style("https://example.com/style"), tile("https://example.com/{z}/{x}/{y}.pbf", 0, 0, 0)] {
        let mut response = with_data(bytes("first"));
        response.caching = Caching { expires: at(100), must_revalidate: true };
        db.put(&resource, &response);
        assert_eq!(response.caching, db.get(&resource).unwrap().caching);

        let mut not_modified = Response::new();
        not_modified.not_modified = true;
        not_modified.caching.expires = at(1000);
        db.put(&resource, &not_modified);
        let stored = db.get(&resource).unwrap();
        assert_eq!((not_modified.caching, Some(bytes("first"))), (stored.caching, stored.data));

        // The copy a 304 delivered back is the stored one.
        let mut delivered = with_data(bytes("delivered"));
        delivered.prior = true;
        delivered.caching.expires = at(2000);
        assert_eq!((false, 0), db.put(&resource, &delivered));
        let stored = db.get(&resource).unwrap();
        assert_eq!((delivered.caching, Some(bytes("first"))), (stored.caching, stored.data));
    }
}

#[test]
fn a_region_keeps_its_definition_and_metadata() {
    let geometry = OfflineGeometryRegionDefinition::new(
        "https://example.com/style",
        Geometry::Point(Point::new(-122.5744, 37.6609)),
        0.0,
        2.0,
        1.0,
        false,
    )
    .unwrap();
    let definitions =
        [pyramid(5.0, 6.0, true), pyramid(5.0, 6.0, false), pyramid(0.0, f64::INFINITY, false), geometry.into()];
    for definition in definitions {
        let mut db = OfflineDatabase::new(":memory:");
        let region = db.create_region(&definition, &vec![1, 2, 3]).unwrap();
        assert_eq!((&definition, &vec![1, 2, 3]), (&region.definition, &region.metadata));
        assert_eq!(vec![region.clone()], db.list_regions().unwrap());
        assert_eq!(Some(region.clone()), db.region(region.id).unwrap());
        assert_eq!(definition, db.region_definition(region.id).unwrap());
        assert_eq!(None, db.region(region.id + 1).unwrap());

        db.update_metadata(region.id, &vec![4, 5, 6]).unwrap();
        assert_eq!(vec![4, 5, 6], db.region(region.id).unwrap().unwrap().metadata);
    }
}

#[test]
fn a_regions_status_counts_its_resources_and_tiles() {
    let mut db = OfflineDatabase::new(":memory:");
    let region = region(&mut db, &pyramid(5.0, 6.0, false));
    assert_eq!(OfflineRegionStatus::default(), db.region_completed_status(region.id).unwrap());

    let style_size = db.put_region_resource(region.id, &style("http://example.com/"), &with_data(bytes("data")));
    let status = db.region_completed_status(region.id).unwrap();
    assert_eq!(
        (1, style_size, 0, 0),
        (
            status.completed_resource_count,
            status.completed_resource_size,
            status.completed_tile_count,
            status.completed_tile_size
        )
    );

    let tile_size = db.put_region_resource(region.id, &tile("http://example.com/", 0, 0, 0), &with_data(bytes("data")));
    let status = db.region_completed_status(region.id).unwrap();
    assert_eq!(
        (2, style_size + tile_size, 1, tile_size),
        (
            status.completed_resource_count,
            status.completed_resource_size,
            status.completed_tile_count,
            status.completed_tile_size
        )
    );
}

#[test]
fn the_ambient_cache_evicts_the_least_recently_used() {
    let mut db = OfflineDatabase::new(":memory:");
    db.set_maximum_ambient_cache_size(1024 * 100).unwrap();

    // One over what fits.
    for i in 1..=101 {
        let resource = style(&format!("http://example.com/{i}"));
        db.put(&resource, &with_data(incompressible(1024)));
        assert!(db.get(&resource).is_some(), "{i}");
    }
    assert_eq!(None, db.get(&style("http://example.com/1")));
}

#[test]
fn region_resources_neither_count_toward_nor_leave_the_ambient_cache() {
    let mut db = OfflineDatabase::new(":memory:");
    // Two resources of 100 KB, and their pages.
    db.set_maximum_ambient_cache_size(2 * (100 * 1024 + 4096)).unwrap();
    let response = with_data(incompressible(100 * 1024));
    let region = region(&mut db, &world());

    db.put(&style("http://example.com/ambient1.json"), &response);
    for i in 0..5 {
        db.put_region_resource(region.id, &style(&format!("http://example.com/single/{i}")), &response);
    }
    let batch: Vec<_> = (0..5).map(|i| (style(&format!("http://example.com/batch/{i}")), response.clone())).collect();
    db.put_region_resources(region.id, &batch, &mut OfflineRegionStatus::default());
    db.put(&style("http://example.com/ambient2.json"), &response);

    for url in ["ambient1.json", "ambient2.json", "single/0", "single/4", "batch/0", "batch/4"] {
        assert!(db.get(&style(&format!("http://example.com/{url}"))).is_some(), "{url}");
    }
}

#[test]
fn a_response_larger_than_the_ambient_cache_is_not_stored() {
    for (maximum, size) in [(100 * 1024, 100 * 1024 + 4096), (0, 1024)] {
        let mut db = OfflineDatabase::new(":memory:");
        db.set_maximum_ambient_cache_size(maximum).unwrap();
        // A region keeps the database in use with an ambient cache of 0.
        region(&mut db, &world());

        let resource = style("http://example.com/big");
        assert!(!db.put(&resource, &with_data(incompressible(size))).0, "{size} bytes in {maximum}");
        assert_eq!(None, db.get(&resource), "{size} bytes in {maximum}");
    }
}

/// A region's copy reports its stored size and freshness, and a 304 for it
/// reports the stored size again.
#[test]
fn a_region_resource_reports_its_size_and_freshness() {
    let mut db = OfflineDatabase::new(":memory:");
    let region = region(&mut db, &world());

    for resource in [style("http://example.com/style.json"), tile("http://example.com/{z}/{x}/{y}", 0, 0, 0)] {
        let fresh = |db: &mut OfflineDatabase| {
            db.check_region_resource(&resource).map(|(size, caching)| (size, caching.is_fresh(now())))
        };
        assert_eq!(None, fresh(&mut db));
        assert_eq!(5, db.put_region_resource(region.id, &resource, &with_data(bytes("first"))));
        assert_eq!(Some((5, true)), fresh(&mut db));

        db.invalidate_region(region.id).unwrap();
        assert_eq!(Some((5, false)), fresh(&mut db));

        let mut not_modified = Response::new();
        not_modified.not_modified = true;
        not_modified.caching.expires = Some(Timestamp::from_secs(now().secs_since_epoch() + 3600));
        assert_eq!(5, db.put_region_resource(region.id, &resource, &not_modified));
        assert_eq!(Some((5, true)), fresh(&mut db));
    }
}

#[test]
fn invalidating_a_region_or_the_ambient_cache_leaves_the_others_fresh() {
    let mut db = OfflineDatabase::new(":memory:");
    let mut response = no_content();
    response.caching.expires = Some(Timestamp::from_secs(now().secs_since_epoch() + 3600));

    let ambient = [tile("https://example.com/ambient", 0, 0, 0), style("https://example.com/ambient")];
    for resource in &ambient {
        db.put(resource, &response);
    }
    let mut regions = Vec::new();
    for name in ["region1", "region2"] {
        let region = region(&mut db, &pyramid(5.0, 6.0, true));
        let resources =
            [tile(&format!("https://example.com/{name}"), 0, 0, 0), style(&format!("https://example.com/{name}"))];
        for resource in &resources {
            db.put_region_resource(region.id, resource, &response);
        }
        regions.push((region, resources));
    }
    let [(region1, in_region1), (region2, in_region2)] = &regions[..] else { unreachable!() };

    db.invalidate_region(region1.id).unwrap();
    let mut fresh = |resource: &Resource| db.get(resource).unwrap().caching.is_fresh(now());
    let fresh_after_region =
        (ambient.iter().all(&mut fresh), in_region1.iter().any(&mut fresh), in_region2.iter().all(&mut fresh));
    assert_eq!((true, false, true), fresh_after_region);

    db.invalidate_ambient_cache().unwrap();
    // Stale, but still usable.
    for resource in ambient.iter().chain(in_region1) {
        let caching = db.get(resource).unwrap().caching;
        assert!(!caching.is_fresh(now()) && caching.is_usable(now()), "{resource:?}");
    }
    assert!(in_region2.iter().all(|resource| db.get(resource).unwrap().caching.is_fresh(now())));

    // Invalidating again, or a region that doesn't exist, succeeds, and
    // deletes nothing.
    db.invalidate_region(region2.id).unwrap();
    db.invalidate_region(region2.id).unwrap();
    db.invalidate_region(123).unwrap();
    assert_eq!(2, db.list_regions().unwrap().len());
}

#[test]
fn invalidated_copies_stay_usable_unless_they_must_revalidate() {
    let mut db = OfflineDatabase::new(":memory:");
    let region = region(&mut db, &world());
    let at = |secs: i64| Some(Timestamp::from_secs(now().secs_since_epoch() + secs));
    let cases = [
        Caching { expires: at(3600), must_revalidate: true },
        Caching { expires: at(3600), must_revalidate: false },
        Caching::default(),
        Caching { expires: at(-60), must_revalidate: true },
    ];
    let tile = |y: usize| tile("https://example.com/{z}/{x}/{y}.pbf", 0, y as i32, 1);
    for (y, caching) in cases.iter().enumerate() {
        let mut response = with_data(bytes("data"));
        response.caching = *caching;
        db.put_region_resource(region.id, &tile(y), &response);
    }

    db.invalidate_region(region.id).unwrap();

    for (y, before) in cases.iter().enumerate() {
        let caching = db.get(&tile(y)).unwrap().caching;
        assert!(!caching.is_fresh(now()), "{before:?}");
        assert_eq!(!before.must_revalidate, caching.is_usable(now()), "{before:?}");
    }
}

/// A region's expiry reports when its resources go stale and stop being
/// usable, and how many are stale or unusable now.
#[test]
fn a_regions_expiry_reports_its_stale_and_unusable_resources() {
    let mut db = OfflineDatabase::new(":memory:");
    let region = region(&mut db, &world());
    assert_eq!(OfflineRegionExpiry::default(), db.region_expiry(region.id).unwrap());

    let now = now().secs_since_epoch();
    let at = |secs: i64| Some(Timestamp::from_secs(now + secs));
    let resources = [
        // Fresh for an hour, then usable stale.
        (tile("https://example.com/{z}/{x}/{y}.pbf", 0, 0, 1), Caching { expires: at(3600), must_revalidate: false }),
        // Stale, and usable.
        (tile("https://example.com/{z}/{x}/{y}.pbf", 0, 1, 1), Caching { expires: at(-60), must_revalidate: false }),
        // Stale, and unusable without the server.
        (style("https://example.com/style.json"), Caching { expires: at(-30), must_revalidate: true }),
        // Never stale.
        (style("https://example.com/sprite.json"), Caching::default()),
    ];
    for (resource, caching) in resources {
        let mut response = with_data(bytes("data"));
        response.caching = caching;
        db.put_region_resource(region.id, &resource, &response);
    }

    let expiry = db.region_expiry(region.id).unwrap();
    assert_eq!((at(-60), at(-30)), (expiry.stale_after, expiry.usable_offline_until));
    assert_eq!((2, 1), (expiry.stale_resource_count, expiry.unusable_resource_count));
}

/// 20 resources of 64 KB that don't compress, at URLs that start with
/// `prefix`.
fn resources(prefix: &str) -> Vec<(Resource, Response)> {
    let response = with_data(incompressible(64 * 1024));
    (0..10)
        .flat_map(|i| {
            [
                (tile(&format!("https://example.com/{prefix}/tile_{i}"), 0, 0, 0), response.clone()),
                (style(&format!("https://example.com/{prefix}/style_{i}")), response.clone()),
            ]
        })
        .collect()
}

#[test]
fn deleting_a_region_frees_its_pages_at_once_or_once_packed() {
    let path = temp_path("offline.db");
    drop(OfflineDatabase::new(&*path));
    let initial_size = file_size(&path);
    {
        let mut db = OfflineDatabase::new(&*path);
        // A deleted region's resources move to the ambient cache, which
        // holds nothing.
        db.set_maximum_ambient_cache_size(0).unwrap();
        let region1 = region(&mut db, &pyramid(5.0, 6.0, true));
        let region2 = region(&mut db, &pyramid(5.0, 6.0, true));
        db.put_region_resources(region1.id, &resources("region1"), &mut OfflineRegionStatus::default());
        db.put_region_resources(region2.id, &resources("region2"), &mut OfflineRegionStatus::default());
        let size_with_two_regions = file_size(&path);

        db.run_pack_database_automatically(false);
        db.delete_region(&region1).unwrap();
        assert_eq!(vec![region2.clone()], db.list_regions().unwrap());
        assert_eq!(size_with_two_regions, file_size(&path), "unpacked");
        db.pack().unwrap();
        let size_with_one_region = file_size(&path);
        assert!(size_with_one_region < size_with_two_regions);

        db.run_pack_database_automatically(true);
        db.delete_region(&region2).unwrap();
        assert!(file_size(&path) < size_with_one_region);
    }
    assert_eq!(initial_size, file_size(&path));
}

#[test]
fn clearing_the_ambient_cache_frees_its_pages_at_once_or_once_packed() {
    for autopack in [true, false] {
        let path = temp_path("offline.db");
        let mut db = OfflineDatabase::new(&*path);
        let initial_size = file_size(&path);
        db.run_pack_database_automatically(autopack);
        for (resource, response) in resources("ambient") {
            db.put(&resource, &response);
        }
        let populated_size = file_size(&path);
        assert!(populated_size > initial_size);

        db.clear_ambient_cache().unwrap();
        assert_eq!(if autopack { initial_size } else { populated_size }, file_size(&path), "autopack: {autopack}");
        db.pack().unwrap();
        assert_eq!(initial_size, file_size(&path), "autopack: {autopack}");
    }
}

#[test]
fn two_connections_share_a_database_file() {
    let path = temp_path("offline.db");
    let mut db1 = OfflineDatabase::new(&*path);
    let mut db2 = OfflineDatabase::new(&*path);
    let resource = style("https://example.com/test");
    let response = with_data(bytes("first"));

    std::thread::scope(|s| {
        s.spawn(|| {
            for _ in 0..100 {
                assert_eq!(5, db1.put(&resource, &response).1);
                assert!(db1.get(&resource).is_some());
            }
        });
        s.spawn(|| {
            for i in 0..100 {
                assert_eq!(5, db2.put(&resource, &response).1);
                assert!(db2.get(&resource).is_some());
                if i == 50 {
                    db2.clear_ambient_cache().unwrap();
                }
            }
        });
    });
}

/// A side database, in the directory of `main`, with region `definition`
/// holding a shared tile and a style named for `name`, and an ambient tile
/// and style.
fn side_database(main: &TempPath, regions: &[(&str, OfflineRegionDefinition)]) -> String {
    let path = main.sibling("side.db");
    let mut side = OfflineDatabase::new(&*path);
    side.put(&tile("https://example.com/ambient", 0, 0, 0), &with_data(bytes("ambient")));
    side.put(&style("https://example.com/ambient"), &with_data(bytes("ambient")));
    for (name, definition) in regions {
        let region = side.create_region(definition, &name.as_bytes().to_vec()).unwrap();
        side.put_region_resource(region.id, &tile("https://example.com/shared", 0, 0, 0), &with_data(bytes("shared")));
        side.put_region_resource(region.id, &style(&format!("https://example.com/{name}")), &with_data(bytes(name)));
    }
    path
}

#[test]
fn merging_adds_the_regions_of_another_database_with_their_resources() {
    let main = temp_path("offline.db");
    let mut db = OfflineDatabase::new(&*main);
    let existing = region(&mut db, &pyramid(1.0, 2.0, false));
    let side = side_database(&main, &[("one", pyramid(5.0, 6.0, true)), ("two", pyramid(7.0, 8.0, true))]);

    let merged = db.merge_database(&side).unwrap();
    let names: Vec<&[u8]> = merged.iter().map(|region| region.metadata.as_slice()).collect();
    assert_eq!(vec![&b"one"[..], b"two"], names);
    assert_eq!(3, db.list_regions().unwrap().len());
    assert!(db.list_regions().unwrap().contains(&existing));
    for region in &merged {
        let status = db.region_completed_status(region.id).unwrap();
        assert_eq!((2, 1), (status.completed_resource_count, status.completed_tile_count), "{region:?}");
    }
    // Resources of no region stay behind.
    assert_eq!(None, db.check_region_resource(&tile("https://example.com/ambient", 0, 0, 0)));
    assert_eq!(None, db.check_region_resource(&style("https://example.com/ambient")));
}

#[test]
fn merging_keeps_the_newer_copy_of_a_regions_resource() {
    // The modification times of the main copy and the side's, and the copy
    // that stays.
    for (main_modified, side_modified, kept) in [(100, 200, "side"), (200, 100, "main")] {
        let main = temp_path("offline.db");
        let side_path = main.sibling("side.db");
        let resources = [tile("https://example.com/shared", 0, 0, 0), style("https://example.com/shared")];
        for (path, modified, data) in [(&*main, main_modified, "main"), (&*side_path, side_modified, "side")] {
            let mut db = OfflineDatabase::new(path);
            let region = db.create_region(&pyramid(5.0, 6.0, true), &b"region".to_vec()).unwrap();
            for resource in &resources {
                let mut response = with_data(bytes(data));
                response.modified = Some(Timestamp::from_secs(modified));
                db.put_region_resource(region.id, resource, &response);
            }
        }

        let mut db = OfflineDatabase::new(&*main);
        assert_eq!(1, db.merge_database(&side_path).unwrap().len());
        assert_eq!(1, db.list_regions().unwrap().len(), "the same region");
        for resource in &resources {
            let (stored, _) = db.region_resource(resource).unwrap();
            assert_eq!(Some(bytes(kept)), stored.data, "{main_modified} and {side_modified}: {resource:?}");
        }
    }
}

#[test]
fn merging_a_file_of_no_database_of_this_schema_fails() {
    type Setup = fn(&str);
    let cases: [(&str, Setup); 4] = [
        ("an empty file", |path| std::fs::write(path, "").unwrap()),
        ("no file", |_| {}),
        ("a corrupt database", |path| copy_fixture("corrupt-immediate.db", path)),
        ("an older schema", |path| copy_fixture("v5.db", path)),
    ];
    for (case, setup) in cases {
        let side = temp_path("side.db");
        setup(&side);
        let mut db = OfflineDatabase::new(":memory:");
        assert!(db.merge_database(&side).is_err(), "{case}");
        assert_eq!(Vec::<OfflineRegion>::new(), db.list_regions().unwrap(), "{case}");
        assert_usable(&mut db);
    }
}

#[test]
fn resetting_starts_an_empty_database() {
    let path = temp_path("offline.db");
    let mut db = OfflineDatabase::new(&*path);
    region(&mut db, &world());
    db.put(&style("https://example.com/style"), &with_data(bytes("data")));

    db.reset_database().unwrap();
    assert_eq!(Vec::<OfflineRegion>::new(), db.list_regions().unwrap());
    assert_eq!(None, db.get(&style("https://example.com/style")));
    assert_usable(&mut db);
}

#[test]
fn resetting_a_database_in_memory_deletes_no_file() {
    for path in [":memory:", "file::memory:", "file::memory:?cache=shared", "file:reset-test?mode=memory"] {
        // A file at the path, relative to the working directory, that isn't
        // the database. Skipped where the directory is read-only, or the
        // name isn't a file name.
        let decoy = std::fs::write(path, "unrelated file").is_ok();

        let mut db = OfflineDatabase::new(path);
        db.put(&style("https://example.com/style"), &with_data(bytes("data")));
        db.reset_database().unwrap();
        assert_eq!(None, db.get(&style("https://example.com/style")), "{path}");
        if decoy {
            assert_eq!("unrelated file", std::fs::read_to_string(path).unwrap(), "{path}");
            let _ = std::fs::remove_file(path);
        }
    }
}

#[test]
fn a_read_only_database_refuses_writes() {
    let path = temp_path("offline.db");
    let mut db = OfflineDatabase::new(&*path);
    let resource = style("http://example.com/");

    db.reopen_database_read_only(true);
    assert_eq!((false, 0), db.put(&resource, &with_data(bytes("success"))));
    assert!(db.clear_ambient_cache().is_err());
    assert!(db.create_region(&world(), &OfflineRegionMetadata::new()).is_err());

    db.reopen_database_read_only(false);
    assert_eq!((true, 7), db.put(&resource, &with_data(bytes("success"))));
    assert_eq!(Some(b"success".to_vec()), stored_data(&mut db, &resource));
}

fn accessed(path: &str, table: &str) -> i64 {
    query(path, &format!("SELECT accessed FROM {table}"))
}

/// A database at a fresh path with a style and a tile in its ambient cache,
/// each last accessed at time 100.
fn with_cached_resources() -> (TempPath, OfflineDatabase, [Resource; 2]) {
    let path = temp_path("offline.db");
    let mut db = OfflineDatabase::new(&*path);
    let resources = [style("https://example.com/style"), tile("https://example.com/{z}/{x}/{y}", 0, 0, 0)];
    for resource in &resources {
        db.put(resource, &with_data(bytes("first")));
    }
    sql(&path, "UPDATE resources SET accessed = 100; UPDATE tiles SET accessed = 100");
    (path, db, resources)
}

/// A trigger that fails each update of `table`'s `accessed` times.
fn fail_accessed_updates(path: &str, table: &str) {
    sql(
        path,
        &format!(
            "CREATE TRIGGER fail_touch BEFORE UPDATE OF accessed ON {table} \
             BEGIN SELECT RAISE(ABORT, 'injected failure'); END"
        ),
    );
}

fn stop_failing(path: &str) {
    sql(path, "DROP TRIGGER fail_touch");
}

#[test]
fn cache_hits_write_their_accessed_times_in_one_flush() {
    let (path, mut db, [style, tile]) = with_cached_resources();
    let hits = Arc::new(AtomicUsize::new(0));
    let counter = Arc::clone(&hits);
    db.set_accessed_callback(Box::new(move || {
        counter.fetch_add(1, Ordering::Relaxed);
    }));

    for resource in [&style, &style, &tile, &tile] {
        assert!(db.get(resource).is_some());
    }
    assert!(db.region_resource(&style).is_some());
    assert_eq!(None, db.get(&self::style("not-cached")));

    // Each hit asks for a flush; the rows wait once each, unwritten.
    assert_eq!(5, hits.load(Ordering::Relaxed));
    assert_eq!(2, db.pending_accessed_count());
    assert_eq!((100, 100), (accessed(&path, "resources"), accessed(&path, "tiles")));
    assert!(db.flush_accessed());
    assert_eq!(0, db.pending_accessed_count());
    assert!(accessed(&path, "resources") > 100 && accessed(&path, "tiles") > 100);
}

#[test]
fn a_failed_flush_writes_nothing_and_keeps_the_hits_for_the_next() {
    let (path, mut db, resources) = with_cached_resources();
    fail_accessed_updates(&path, "tiles");
    for resource in &resources {
        assert!(db.get(resource).is_some());
    }

    assert!(!db.flush_accessed());
    assert_eq!(2, db.pending_accessed_count());
    // The resources' update ran first, and rolled back with the tiles'.
    assert_eq!((100, 100), (accessed(&path, "resources"), accessed(&path, "tiles")));

    stop_failing(&path);
    assert!(db.flush_accessed());
    assert_eq!(0, db.pending_accessed_count());
    assert!(accessed(&path, "resources") > 100 && accessed(&path, "tiles") > 100);
}

#[test]
fn a_flush_keeps_a_newer_accessed_time_and_runs_before_going_read_only() {
    let (path, mut db, [style, _]) = with_cached_resources();
    assert!(db.get(&style).is_some());
    sql(&path, "UPDATE resources SET accessed = 4102444800");
    assert!(db.flush_accessed());
    assert_eq!(4_102_444_800, accessed(&path, "resources"));

    sql(&path, "UPDATE resources SET accessed = 100");
    assert!(db.get(&style).is_some());
    db.reopen_database_read_only(true);
    assert_eq!(0, db.pending_accessed_count());
    assert!(accessed(&path, "resources") > 100);
    // Read-only, hits wait for nothing.
    assert!(db.get(&style).is_some());
    assert_eq!(0, db.pending_accessed_count());
}

#[test]
fn clearing_the_ambient_cache_drops_its_pending_hits() {
    let (_path, mut db, [style, _]) = with_cached_resources();
    assert!(db.get(&style).is_some());
    assert_eq!(1, db.pending_accessed_count());
    db.clear_ambient_cache().unwrap();
    assert_eq!(0, db.pending_accessed_count());
    assert_eq!(None, db.get(&style));
    assert!(db.flush_accessed());
}

#[test]
fn changing_the_path_or_closing_flushes_the_pending_hits() {
    let (path, mut db, [style, _]) = with_cached_resources();
    assert!(db.get(&style).is_some());
    db.change_path(":memory:");
    assert_eq!(0, db.pending_accessed_count());
    assert!(accessed(&path, "resources") > 100);
    assert_eq!(None, db.get(&style));
    drop(db);

    sql(&path, "UPDATE resources SET accessed = 100");
    let mut db = OfflineDatabase::new(&*path);
    assert!(db.get(&style).is_some());
    drop(db);
    assert!(accessed(&path, "resources") > 100);
}

#[test]
fn pending_hits_are_bounded_while_flushes_fail() {
    let path = temp_path("offline.db");
    let mut db = OfflineDatabase::new(&*path);
    sql(
        &path,
        "WITH RECURSIVE sequence(n) AS (VALUES(1) UNION ALL SELECT n+1 FROM sequence WHERE n<4100) \
         INSERT INTO resources(url,kind,accessed) SELECT 'key-'||n,2,100 FROM sequence",
    );
    fail_accessed_updates(&path, "resources");
    for i in 1..=4100 {
        assert!(db.get(&Resource::new(Kind::Source, format!("key-{i}"))).is_some());
    }
    assert_eq!(4096, db.pending_accessed_count());

    stop_failing(&path);
    assert!(db.flush_accessed());
    assert_eq!(0, db.pending_accessed_count());
}

#[test]
fn pending_hits_count_in_the_eviction_that_a_put_makes() {
    let path = temp_path("offline.db");
    let mut db = OfflineDatabase::new(&*path);
    sql(
        &path,
        "WITH RECURSIVE sequence(n) AS (VALUES(1) UNION ALL SELECT n+1 FROM sequence WHERE n<60) \
         INSERT INTO resources(url,kind,accessed,data) SELECT 'evict-'||n,2,n,randomblob(1024) FROM sequence",
    );
    db.set_maximum_ambient_cache_size(100_000).unwrap();
    // The oldest by its stored time, and the newest by its pending one.
    let recent = Resource::new(Kind::Source, "evict-1");
    assert!(db.get(&recent).is_some());
    let incoming = Resource::new(Kind::Source, "evict-incoming");
    let response = with_data(incompressible(50_000));

    // A put that fails keeps the hit waiting.
    sql(
        &path,
        "CREATE TRIGGER fail_insert BEFORE INSERT ON resources WHEN NEW.url='evict-incoming' \
         BEGIN SELECT RAISE(ABORT,'injected insertion failure'); END",
    );
    assert!(!db.put(&incoming, &response).0);
    assert_eq!(1, db.pending_accessed_count());
    assert_eq!(1, accessed(&path, "resources"));

    sql(&path, "DROP TRIGGER fail_insert");
    assert!(db.put(&incoming, &response).0);
    assert_eq!(0, db.pending_accessed_count());
    assert!(db.get(&recent).is_some());
    assert_eq!(None, db.get(&Resource::new(Kind::Source, "evict-2")));
    assert_eq!(response.data, db.get(&incoming).unwrap().data);
}

#[test]
fn a_failed_flush_stops_neither_a_resize_nor_a_region_deletion() {
    // A resize to nothing evicts the hit's resource.
    let (path, mut db, [style, _]) = with_cached_resources();
    assert!(db.get(&style).is_some());
    fail_accessed_updates(&path, "resources");
    db.set_maximum_ambient_cache_size(0).unwrap();
    assert_eq!(None, db.get(&style));
    assert_eq!(1, db.pending_accessed_count());
    stop_failing(&path);
    assert!(db.flush_accessed());

    // Deleting the region evicts its tile, as the ambient cache holds
    // nothing.
    let path = temp_path("offline.db");
    let mut db = OfflineDatabase::new(&*path);
    db.set_maximum_ambient_cache_size(0).unwrap();
    let region = region(&mut db, &pyramid(5.0, 6.0, true));
    let tile = tile("https://example.com/{z}/{x}/{y}", 0, 0, 0);
    db.put_region_resource(region.id, &tile, &with_data(bytes("first")));
    assert!(db.region_resource(&tile).is_some());
    fail_accessed_updates(&path, "tiles");
    db.delete_region(&region).unwrap();
    assert_eq!(Vec::<OfflineRegion>::new(), db.list_regions().unwrap());
    assert_eq!(None, db.get(&tile));
    assert_eq!(1, db.pending_accessed_count());
    stop_failing(&path);
    assert!(db.flush_accessed());
    assert_eq!(0, db.pending_accessed_count());
}