amethystate 0.23.2

A state manager for Rust applications
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
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
use crate::migration::builder::MigrationBuilder;
use crate::store::config::{Disk, FileWritePolicy, StoreConfig, WriteLimits};
use crate::store::facts::Facts;
use crate::store::traits::StoreLayout;
use crate::store::{
    CodecFormat, Fallbacks, OpenStore, RuleContext, StorageError, StorageResult, WhenItWillNotRead,
    WillNotOpen,
};
use crate::{MigrationReport, Store};
use amethystate_core::path::StorePathError;
use error_stack::{Report, ResultExt};
use std::any::Any;
use std::path::{Path, PathBuf};
use std::sync::Arc;

/// A prefix handed to [`MigrationBuilder::for_prefix`] that is no path, as the
/// refusal a caller sees.
fn refused_prefix((written, why): (String, StorePathError)) -> OpenStore {
    OpenStore::from_store(
        Report::new(why)
            .change_context(StorageError::Migrate)
            .attach(amethystate_core::facts::RawKey(written))
            .attach("a migration set was given a prefix that cannot be read as a path"),
    )
}

/// Which engine backs a store.
///
/// A variant exists for each backend feature that is enabled. Pass one to
/// [`StoreBuilder::backend`]; without that, [`default_backend`] picks.
///
/// `non_exhaustive`, and demonstrably so: the variants are behind feature flags
/// already, so the set a caller sees depends on how this crate was built. A
/// `match` on it wants a `_` arm whatever happens next.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Backend {
    #[cfg(feature = "redb")]
    Redb,
    #[cfg(feature = "json")]
    Json,
    #[cfg(feature = "toml")]
    Toml,
    #[cfg(feature = "ron")]
    Ron,
    #[cfg(feature = "sqlite")]
    Sqlite,

    /// No file: everything lives as long as the store and goes with it.
    ///
    /// Never the default, and never picked by a build that has nothing else.
    /// A store asks for it by name, or is handed one by
    /// [`StoreBuilder::or_in_memory`] when its file will not open.
    #[cfg(feature = "memory")]
    Memory,

    /// The browser's `localStorage`: one JSON value per key, written in the
    /// call that makes it. A store opened anywhere but a page is refused.
    #[cfg(feature = "localstorage")]
    LocalStorage,
}

impl Backend {
    /// The engine that writes this codec.
    ///
    /// One to one in both directions: a codec is how an engine writes, and no
    /// two engines share one. `sqlite` and `json` come closest and are still
    /// two - one writes the document a serde codec renders, the other stores
    /// the same text in a column - and telling them apart is what the format
    /// record does.
    pub const fn writing(codec: CodecFormat) -> Self {
        match codec {
            #[cfg(feature = "redb")]
            CodecFormat::MessagePack => Backend::Redb,
            #[cfg(all(feature = "memory", not(feature = "redb")))]
            CodecFormat::MessagePack => Backend::Memory,
            #[cfg(feature = "json")]
            CodecFormat::Json => Backend::Json,
            #[cfg(all(feature = "localstorage", not(feature = "json")))]
            CodecFormat::Json => Backend::LocalStorage,
            #[cfg(feature = "sqlite")]
            CodecFormat::SonicJson => Backend::Sqlite,
            #[cfg(feature = "toml")]
            CodecFormat::Toml => Backend::Toml,
            #[cfg(feature = "ron")]
            CodecFormat::Ron => Backend::Ron,
        }
    }

    pub const fn extension(self) -> &'static str {
        match self {
            #[cfg(feature = "redb")]
            Backend::Redb => "redb",
            #[cfg(feature = "json")]
            Backend::Json => "json",
            #[cfg(feature = "toml")]
            Backend::Toml => "toml",
            #[cfg(feature = "ron")]
            Backend::Ron => "ron",
            #[cfg(feature = "sqlite")]
            Backend::Sqlite => "db",
            #[cfg(feature = "memory")]
            Backend::Memory => "",
            #[cfg(feature = "localstorage")]
            Backend::LocalStorage => "",
        }
    }

    /// How deeply this engine's codec will read, counting the path and the
    /// value together. A fact about the codec, enforced whatever the store is
    /// configured to allow.
    ///
    /// Every codec here reads less deeply than it writes, so a value past this
    /// is taken without complaint and cannot be read back - which on the text
    /// engines means the whole file, since the document is parsed as one. Each
    /// number comes from `tests/probe_*.rs`, which walks its engine to the
    /// boundary.
    ///
    /// `redb` has no limit of its own: `rmp_serde` recurses until the stack
    /// ends, around three thousand levels, and the process dies there - on
    /// every later start, because the value is already committed. Its number is
    /// imposed for that reason, far above any data anyone means to store and
    /// far below where the stack gives out. Memory writes the same codec and
    /// takes the same number.
    ///
    /// sqlite takes json's number. It stores its values as JSON, encoded by
    /// `sonic_rs`, so it belongs beside json rather than out at the 254 a walk
    /// to its give-out first suggested: a measured boundary is where a library
    /// happened to stop, not a promise about its next release, and two engines
    /// carrying the same format answering 127 levels apart is worse than
    /// either answer.
    pub const fn depth_ceiling(self) -> usize {
        match self {
            #[cfg(feature = "redb")]
            Backend::Redb => 512,
            #[cfg(feature = "json")]
            Backend::Json => 127,
            #[cfg(feature = "toml")]
            Backend::Toml => 80,
            #[cfg(feature = "ron")]
            Backend::Ron => 64,
            #[cfg(feature = "sqlite")]
            Backend::Sqlite => 127,
            #[cfg(feature = "memory")]
            Backend::Memory => 512,
            #[cfg(feature = "localstorage")]
            Backend::LocalStorage => 127,
        }
    }

    /// Whether committing one write on this engine commits every other write
    /// waiting beside it.
    ///
    /// A document engine keeps the store in one file and rewrites the whole of
    /// it to save any of it, so `flush_prefix` there ignores its prefix and
    /// calls `save_now`: asking for one value to be durable makes every
    /// buffered value durable with it. redb and sqlite commit the write that
    /// was asked for and leave the rest in the buffer.
    ///
    /// The document engines are not going to be taught otherwise. Splitting an
    /// in-memory document into per-key writes buys nothing a caller asked for -
    /// the file is rewritten either way - and would exist only to make the two
    /// kinds of engine behave alike. So this is the answer rather than a gap,
    /// and the tests read it from here instead of each naming a number.
    ///
    /// Memory answers `true` in the only sense it can: nothing waits there,
    /// and nothing survives either.
    ///
    /// What it decides is what survives a crash, which is the one place the
    /// difference shows from outside: `tests/durability_crash.rs` kills a
    /// process with one durable write and one plain one pending, and asks
    /// this.
    pub const fn a_commit_covers_the_whole_store(self) -> bool {
        match self {
            #[cfg(feature = "redb")]
            Backend::Redb => false,
            #[cfg(feature = "json")]
            Backend::Json => true,
            #[cfg(feature = "toml")]
            Backend::Toml => true,
            #[cfg(feature = "ron")]
            Backend::Ron => true,
            #[cfg(feature = "sqlite")]
            Backend::Sqlite => false,
            #[cfg(feature = "memory")]
            Backend::Memory => true,
            #[cfg(feature = "localstorage")]
            Backend::LocalStorage => true,
        }
    }

    /// What this engine's format can carry back unchanged.
    ///
    /// Behind a call of its own because these are questions about a *format*,
    /// asked by the handful of places that screen a write and by the tests that
    /// skip an engine which cannot hold what they are about. Somebody reaching
    /// for `Backend` is choosing an engine, not interviewing one.
    pub const fn holds(self) -> Holds {
        Holds(self)
    }
}

/// What a format can carry back unchanged, asked of the engine that writes it.
///
/// Reached through [`Backend::holds`]. Every answer here is a property of the
/// format or of the codec under it, never of this library: where one is `false`
/// the write is refused rather than quietly altered, and the doc on each says
/// which of the two is to blame.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Holds(Backend);

impl Holds {
    /// Whether this engine can carry an integer that does not fit in an `i64`.
    ///
    /// TOML has one integer type and it is signed and 64 bits wide, so
    /// `u64::MAX` has nowhere to go. Its own codec refuses the write, which is
    /// loud enough while toml is the engine running - but a store on any other
    /// engine that named toml in `portable_across` would otherwise take the
    /// value and break the promise quietly.
    pub const fn an_integer_past_i64(self) -> bool {
        match self.0 {
            #[cfg(feature = "memory")]
            Backend::Memory => true,
            #[cfg(feature = "localstorage")]
            Backend::LocalStorage => true,
            #[cfg(feature = "redb")]
            Backend::Redb => true,
            #[cfg(feature = "json")]
            Backend::Json => true,
            #[cfg(feature = "toml")]
            Backend::Toml => false,
            #[cfg(feature = "ron")]
            Backend::Ron => true,
            #[cfg(feature = "sqlite")]
            Backend::Sqlite => true,
        }
    }

    /// Whether this engine can carry a `u128` or an `i128` at all, whatever its
    /// value.
    ///
    /// toml and ron refuse the type rather than the number: `42u128` is turned
    /// down the same as `u128::MAX`, because neither format has a 128-bit
    /// integer to write it as.
    pub const fn a_128_bit_integer(self) -> bool {
        match self.0 {
            #[cfg(feature = "memory")]
            Backend::Memory => true,
            #[cfg(feature = "localstorage")]
            Backend::LocalStorage => true,
            #[cfg(feature = "redb")]
            Backend::Redb => true,
            #[cfg(feature = "json")]
            Backend::Json => true,
            #[cfg(feature = "toml")]
            Backend::Toml => false,
            #[cfg(feature = "ron")]
            Backend::Ron => false,
            #[cfg(feature = "sqlite")]
            Backend::Sqlite => true,
        }
    }

    /// Whether this engine can carry an integer that neither an `i64` nor a
    /// `u64` holds - a `u128` past `u64::MAX`, an `i128` below `i64::MIN`.
    ///
    /// A json number is read back into an `i64`, a `u64` or an `f64`, so one
    /// past both integer types comes back as none of them.
    pub const fn an_integer_past_64_bits(self) -> bool {
        match self.0 {
            #[cfg(feature = "memory")]
            Backend::Memory => true,
            #[cfg(feature = "localstorage")]
            Backend::LocalStorage => false,
            #[cfg(feature = "redb")]
            Backend::Redb => true,
            #[cfg(feature = "json")]
            Backend::Json => false,
            #[cfg(feature = "toml")]
            Backend::Toml => false,
            #[cfg(feature = "ron")]
            Backend::Ron => false,
            #[cfg(feature = "sqlite")]
            Backend::Sqlite => true,
        }
    }

    /// Whether this engine can write a `NaN` or an infinity and read it back.
    ///
    /// JSON has no spelling for either, and `serde_json` follows
    /// `JSON.stringify` in writing `null` - which then fails to decode as a
    /// float. sqlite answers the same way for the same reason: it encodes its
    /// values with `sonic_rs`. So the split follows the codec rather than the
    /// file, which is why the two are not the two text engines anyone would
    /// guess: msgpack, TOML and RON all carry the value.
    pub const fn non_finite_floats(self) -> bool {
        match self.0 {
            #[cfg(feature = "memory")]
            Backend::Memory => true,
            #[cfg(feature = "localstorage")]
            Backend::LocalStorage => false,
            #[cfg(feature = "redb")]
            Backend::Redb => true,
            #[cfg(feature = "json")]
            Backend::Json => false,
            #[cfg(feature = "toml")]
            Backend::Toml => true,
            #[cfg(feature = "ron")]
            Backend::Ron => true,
            #[cfg(feature = "sqlite")]
            Backend::Sqlite => false,
        }
    }

    /// Whether this engine can write an enum and read it back.
    ///
    /// ron cannot, and the reason is its document type rather than its syntax:
    /// `ron::value::Value` holds nine shapes and none of them is a variant, so
    /// a value rendered as `On(3)` and parsed back into a `Value` arrives as a
    /// sequence with the name gone. Upstream lists it - "enums not supported"
    /// is an open item of [ron-rs/ron#122] - and ron's own deserializer says
    /// the same of itself.
    ///
    /// Avoiding the round trip would take a `to_value`, which ron does not
    /// have either: [ron-rs/ron#140], open since 2018 across four releases
    /// that were each meant to carry it.
    ///
    /// [ron-rs/ron#122]: https://github.com/ron-rs/ron/issues/122
    /// [ron-rs/ron#140]: https://github.com/ron-rs/ron/issues/140
    pub const fn enums(self) -> bool {
        match self.0 {
            #[cfg(feature = "memory")]
            Backend::Memory => true,
            #[cfg(feature = "localstorage")]
            Backend::LocalStorage => true,
            #[cfg(feature = "redb")]
            Backend::Redb => true,
            #[cfg(feature = "json")]
            Backend::Json => true,
            #[cfg(feature = "toml")]
            Backend::Toml => true,
            #[cfg(feature = "ron")]
            Backend::Ron => false,
            #[cfg(feature = "sqlite")]
            Backend::Sqlite => true,
        }
    }

    /// Whether this engine tells `Some(None)` apart from `None`.
    ///
    /// Only ron does, and it is the one that writes an `Option` in words:
    /// `Some(None)` is in the document as itself. Everywhere else the outer
    /// `Some` has nothing of its own to write, so both values reach the file as
    /// one null - `c0` under msgpack, `null` under either JSON - and both read
    /// back as `None`. toml has no null at all and refuses the pair outright.
    ///
    /// It is serde's own representation rather than anything this crate does,
    /// so no engine can be taught otherwise; the write is refused instead.
    pub const fn a_nested_option(self) -> bool {
        match self.0 {
            #[cfg(feature = "memory")]
            Backend::Memory => false,
            #[cfg(feature = "localstorage")]
            Backend::LocalStorage => false,
            #[cfg(feature = "redb")]
            Backend::Redb => false,
            #[cfg(feature = "json")]
            Backend::Json => false,
            #[cfg(feature = "toml")]
            Backend::Toml => false,
            #[cfg(feature = "ron")]
            Backend::Ron => true,
            #[cfg(feature = "sqlite")]
            Backend::Sqlite => false,
        }
    }
}

impl Backend {
    /// Opens a store on this engine directly, skipping the builder.
    ///
    /// [`StoreBuilder`] is the ordinary route - it also collects migrations
    /// and settings this does not.
    pub fn open_public(
        self,
        config: StoreConfig,
        mset: crate::migration::set::MigrationSet,
    ) -> StorageResult<(Store, MigrationReport)> {
        match self {
            #[cfg(feature = "redb")]
            Backend::Redb => {
                let (s, r) = crate::store::backend::redb::RedbStore::open(config, mset)?;
                Ok((Store::from_arc(Arc::new(s)), r))
            }
            #[cfg(feature = "json")]
            Backend::Json => {
                let (s, r) = crate::store::backend::text::JsonStore::open(config, mset)?;
                Ok((Store::from_arc(Arc::new(s)), r))
            }
            #[cfg(feature = "toml")]
            Backend::Toml => {
                let (s, r) = crate::store::backend::text::TomlStore::open(config, mset)?;
                Ok((Store::from_arc(Arc::new(s)), r))
            }
            #[cfg(feature = "ron")]
            Backend::Ron => {
                let (s, r) = crate::store::backend::text::RonStore::open(config, mset)?;
                Ok((Store::from_arc(Arc::new(s)), r))
            }
            #[cfg(feature = "sqlite")]
            Backend::Sqlite => {
                let (s, r) = crate::store::backend::sqlite::SqliteStore::open(config, mset)?;
                Ok((Store::from_arc(Arc::new(s)), r))
            }
            #[cfg(feature = "memory")]
            Backend::Memory => {
                let (s, r) = crate::store::backend::memory::MemoryStore::open(&config, mset)?;
                Ok((Store::from_arc(Arc::new(s)), r))
            }
            #[cfg(feature = "localstorage")]
            Backend::LocalStorage => {
                let (s, r) =
                    crate::store::backend::local_storage::LocalStorageStore::open(&config, mset)?;
                Ok((Store::from_arc(Arc::new(s)), r))
            }
        }
    }
}

/// Expands a priority list into the `not(...)` cascade that picking the first
/// enabled feature otherwise requires by hand.
macro_rules! first_enabled_backend {
    ($feat:literal => $variant:expr $(, $rest_feat:literal => $rest_variant:expr)* $(,)?) => {
        {
            #[cfg(feature = $feat)]
            { Some($variant) }
            #[cfg(not(feature = $feat))]
            { first_enabled_backend!($($rest_feat => $rest_variant),*) }
        }
    };
    () => {
        None
    };
}

/// The first of redb, sqlite, json, toml, ron, localstorage this build has;
/// `None` in a build with no engine.
pub(crate) const fn built_in() -> Option<Backend> {
    first_enabled_backend! {
        "redb"         => Backend::Redb,
        "sqlite"       => Backend::Sqlite,
        "json"         => Backend::Json,
        "toml"         => Backend::Toml,
        "ron"          => Backend::Ron,
        "localstorage" => Backend::LocalStorage,
    }
}

/// What opening a store answers in a build with no engine to open it with.
pub(crate) fn no_engine_built_in() -> Report<StorageError> {
    Report::new(StorageError::Open).attach(
        "this build has no storage engine: turn on one of the features redb, sqlite, json, toml, \
         ron or localstorage",
    )
}

/// The engine used when the caller does not name one.
///
/// The first of redb, sqlite, json, toml, ron, localstorage that is enabled, in
/// a build that has one. Naming the engine with [`StoreBuilder::backend`] is
/// worth doing wherever it matters which one runs - the on-disk format differs,
/// and so does what a durable write commits.
#[cfg(any(
    feature = "redb",
    feature = "sqlite",
    feature = "json",
    feature = "toml",
    feature = "ron",
    feature = "localstorage"
))]
pub const fn default_backend() -> Backend {
    built_in().expect("a build with an engine has a first one")
}

/// How a [`Store`] is opened: where its file is, which engine reads it, and
/// what the store does while it runs.
///
/// Two ways in. [`StoreBuilder::new`] takes a path the caller already has;
/// [`StoreBuilder::located`] works one out from what the machine says, and is
/// where the platform's configuration directory and a portable install beside
/// the executable live.
///
/// ```no_run
/// use amethystate::store::builder::StoreBuilder;
///
/// let store = StoreBuilder::new("./settings").build()?;
/// # Ok::<(), error_stack::Report<amethystate::store::StorageError>>(())
/// ```
///
/// Everything past that is optional and reads in one chain. Naming the engine
/// matters wherever it matters which format is on disk, because
/// [`default_backend`] picks the first one the build has:
///
/// ```no_run
/// use amethystate::store::builder::{Layout, StoreBuilder, default_backend};
/// use amethystate::store::config::WriteAttempts;
/// use std::time::Duration;
///
/// // `Backend::Json` and the rest exist only where their feature is on, so an
/// // example that has to compile under every one of them names none.
/// let store = StoreBuilder::located(|at| at.app_under(Layout::Native, "my-app", "settings"))?
///     .backend(default_backend())
///     .disk(|d| d.debounce(Duration::from_millis(500)))
///     .file_write(|w| w.replacing(WriteAttempts::times(20).apart(Duration::from_millis(250))))
///     .build()?;
/// # Ok::<(), error_stack::Report<amethystate::store::StorageError>>(())
/// ```
///
/// A store is finished one of two ways: [`StoreBuilder::build`] opens it and
/// runs no migration step, [`StoreBuilder::migrate`] opens it and runs them
/// all. [`StoreBuilder::or_in_memory`] puts a store in memory behind either,
/// and `build_global` and `migrate_global` put what they open in place as the
/// process-wide store.
pub struct StoreBuilder {
    backend: Option<Backend>,
    config: StoreConfig,
    migration_builder: MigrationBuilder,
    rule_context: RuleContext,
    fallbacks: Fallbacks,
    /// Whether the extension on the path was spelled by the caller.
    ///
    /// An extension this crate chose belongs to whichever engine is going to
    /// run, and so has to follow [`StoreBuilder::backend`]; one the caller
    /// wrote is theirs, and naming an engine does not overrule it.
    caller_named_extension: bool,
}

/// Which convention decides where an application's files belong.
///
/// A store is found under the layout it was written under, so an application
/// that has shipped should name the one it means. [`Location::app`] takes
/// [`Layout::App`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Layout {
    /// The convention a command-line application follows: the XDG configuration
    /// directory on Linux and macOS, `AppData\Roaming\<app>\config` on Windows.
    /// What [`Location::app`] uses.
    App,

    /// The convention the rest of the platform's software follows, which is
    /// what a desktop application usually wants: `Library/Preferences/rs.<app>`
    /// on macOS, and the same place as [`Layout::App`] on Linux and Windows.
    Native,

    /// The layout the `directories` crate produces: the XDG configuration
    /// directory on Linux, `AppData\Roaming\<app>\config` on Windows, and
    /// `Library/Application Support/rs.<app>` on macOS.
    ///
    /// The one to name for an application whose files that crate already
    /// placed, since where it put them is what the store has to match. On
    /// Windows it lands where [`Layout::App`] does; on Linux it spells the
    /// application name as given, where [`Layout::App`] lowercases it and turns
    /// spaces into hyphens.
    ProjectDirs,
}

impl Layout {
    /// What [`Location::app`] picks when the caller does not say: [`Layout::App`].
    pub const fn default_for_build() -> Self {
        Self::App
    }
}

/// The places [`StoreBuilder::located`] knows how to find, one method each.
#[derive(Debug, Clone, Copy)]
pub struct Location;

impl Location {
    /// The configuration directory this platform keeps for `app_name`.
    ///
    /// That is [`Layout::App`]; name a convention with [`Location::app_under`]
    /// where the store must not move.
    pub fn app(
        self,
        app_name: impl AsRef<str>,
        config_name: impl AsRef<str>,
    ) -> StorageResult<PathBuf> {
        self.app_under(Layout::default_for_build(), app_name, config_name)
    }

    /// Which files a store at `path` under `backend` is made of.
    ///
    /// The other methods here answer with the path a store would be opened at,
    /// and that is one name where the engine writes two or four. A closure that
    /// moves a store from where an older release left it needs the rest, and
    /// the old place is not open to be asked - so the names are worked out from
    /// the path instead.
    ///
    /// [`StoreLayout::present`] is the half worth moving; the rewrite copies
    /// are named whether or not they exist, and normally they do not.
    pub fn files_at(self, path: impl AsRef<Path>, backend: Backend) -> StoreLayout {
        StoreLayout::of(path, backend)
    }

    /// The same, under the layout named.
    ///
    /// Answers under the temporary directory instead when `test-utils` is on.
    pub fn app_under(
        self,
        layout: Layout,
        app_name: impl AsRef<str>,
        config_name: impl AsRef<str>,
    ) -> StorageResult<PathBuf> {
        let app_name = app_name.as_ref();

        if cfg!(feature = "test-utils") {
            let path = std::env::temp_dir()
                .join("amethystate-app-dirs")
                .join(app_name)
                .join(config_name.as_ref());

            ensure_parent(&path).attach_with(|| format!("application: {app_name}"))?;
            return Ok(path);
        }

        let args = || etcetera::AppStrategyArgs {
            top_level_domain: "rs".to_string(),
            author: String::new(),
            app_name: app_name.to_string(),
        };

        let path = match layout {
            Layout::App => {
                use etcetera::{AppStrategy, app_strategy::choose_app_strategy};

                choose_app_strategy(args())
                    .change_context(StorageError::Open)
                    .attach("this system has no home directory to put an application's own under")?
                    .config_dir()
            }
            Layout::Native => {
                use etcetera::{AppStrategy, app_strategy::choose_native_strategy};

                choose_native_strategy(args())
                    .change_context(StorageError::Open)
                    .attach("this system has no home directory to put an application's own under")?
                    .config_dir()
            }
            Layout::ProjectDirs => {
                use directories::ProjectDirs;

                ProjectDirs::from("rs", "", app_name)
                    .ok_or_else(|| {
                        Report::new(StorageError::Open)
                            .attach("this system has no configuration directory for an application")
                    })?
                    .config_dir()
                    .to_path_buf()
            }
        }
        .join(config_name.as_ref());

        ensure_parent(&path).attach_with(|| format!("application: {app_name}"))?;
        Ok(path)
    }

    /// Beside the running executable, for an installation that is a folder
    /// somebody unpacked and can move.
    ///
    /// This wants a directory the person running the program can write to.
    /// `Program Files` and `/usr/bin` are not, and on macOS the executable
    /// lives inside the bundle, so a file beside it is inside a signed
    /// directory. Any of those shows up as a failure to open the store, at
    /// startup, before the first write.
    pub fn beside_the_executable(self, file_name: impl AsRef<Path>) -> StorageResult<PathBuf> {
        let exe = std::env::current_exe()
            .change_context(StorageError::Open)
            .attach("the running executable cannot be located, so nothing is beside it")?;

        let dir = exe.parent().ok_or_else(|| {
            Report::new(StorageError::Open)
                .attach(format!("executable: {}", exe.display()))
                .attach("the running executable is not in a directory")
        })?;

        let path = dir.join(file_name);
        ensure_parent(&path).attach_with(|| format!("executable: {}", exe.display()))?;
        Ok(path)
    }
}

fn ensure_parent(path: &Path) -> StorageResult<()> {
    let Some(parent) = path.parent() else {
        return Ok(());
    };

    std::fs::create_dir_all(parent)
        .change_context(StorageError::Open)
        .attach_with(|| format!("directory: {}", parent.display()))
        .attach_store_file(path)
}

impl StoreBuilder {
    /// A store at an explicit path.
    ///
    /// An extension that is given is kept, whatever engine ends up running -
    /// the path is the caller's. Without one the engine's own extension is
    /// used, and it follows [`StoreBuilder::backend`] if that names another
    /// engine later. [`StoreBuilder::located`] is the variant that picks a
    /// location as well.
    pub fn new(path: impl Into<PathBuf>) -> Self {
        let mut path: PathBuf = path.into();
        let caller_named_extension = path.extension().is_some();
        let backend = built_in();
        if let Some(backend) = backend
            && !caller_named_extension
        {
            path.set_extension(backend.extension());
        }
        Self {
            backend,
            config: StoreConfig::new(path),
            migration_builder: MigrationBuilder::default(),
            rule_context: RuleContext::default(),
            fallbacks: Fallbacks::default(),
            caller_named_extension,
        }
    }

    /// A store where the machine says it goes.
    ///
    /// The questions about the machine - which directory this platform keeps
    /// for an application, whether this install is a folder somebody unpacked -
    /// are all answered behind here, in one place. [`StoreBuilder::new`] is the
    /// way in when the path is already known.
    ///
    /// The closure is handed a [`Location`] and returns the path it picked.
    /// Every method on it makes sure the directory above the file exists, so
    /// what comes back is somewhere a store can actually be opened, and reports
    /// what went wrong when it is not.
    ///
    /// ```no_run
    /// # use amethystate::store::builder::{Layout, StoreBuilder};
    /// // The configuration directory this platform keeps for an application.
    /// let store = StoreBuilder::located(|at| at.app("my-app", "settings"))?.build()?;
    ///
    /// // The same, under a named convention - worth spelling once an
    /// // application has shipped.
    /// let store = StoreBuilder::located(|at| {
    ///     at.app_under(Layout::Native, "my-app", "settings")
    /// })?
    /// .build()?;
    ///
    /// // Beside the running executable, for an install that can be moved.
    /// let store = StoreBuilder::located(|at| at.beside_the_executable("settings"))?.build()?;
    /// # Ok::<(), error_stack::Report<amethystate::store::StorageError>>(())
    /// ```
    ///
    /// The file name carries no extension in any of those, so the engine that
    /// runs names it - see [`StoreBuilder::backend`] for what that means when
    /// the engine is chosen afterwards.
    pub fn located(
        pick: impl FnOnce(Location) -> StorageResult<PathBuf>,
    ) -> Result<Self, OpenStore> {
        Ok(Self::new(pick(Location).map_err(OpenStore::from_store)?))
    }

    /// When this store touches the file, and what it does when the file will
    /// not be touched.
    ///
    /// The closure is handed the defaults and gives back what it changed, so
    /// nothing has to be restated and nothing can be silently zeroed by
    /// forgetting to. See [`Disk`] for the knobs.
    ///
    /// ```no_run
    /// # use amethystate::store::builder::StoreBuilder;
    /// # use std::time::Duration;
    /// let store = StoreBuilder::new("settings.json")
    ///     .disk(|d| d.debounce(Duration::from_millis(200)))
    ///     .build()?;
    /// # Ok::<(), error_stack::Report<amethystate::store::StorageError>>(())
    /// ```
    pub fn disk(mut self, configure: impl FnOnce(Disk) -> Disk) -> Self {
        let settled = configure(Disk {
            save_debounce: self.config.save_debounce,
            watch_debounce: self.config.watch_debounce,
            retry_policy: self.config.retry_policy.clone(),
            on_persist_failure: self.config.on_persist_failure.clone(),
        });

        self.config.save_debounce = settled.save_debounce;
        self.config.watch_debounce = settled.watch_debounce;
        self.config.retry_policy = settled.retry_policy;
        self.config.on_persist_failure = settled.on_persist_failure;
        self
    }

    /// How hard one write to one file fights before it reports a failure.
    ///
    /// This sits inside a single flush attempt, below [`Disk::retry_every`]:
    /// only
    /// once it has run out does a flush count as having failed at all. It
    /// applies to the text engines, which replace a file to write it; `redb`
    /// and `sqlite` hold their own handle.
    ///
    /// ```no_run
    /// # use amethystate::store::builder::StoreBuilder;
    /// # use amethystate::store::config::WriteAttempts;
    /// # use std::time::Duration;
    /// let store = StoreBuilder::new("settings.json")
    ///     .file_write(|w| {
    ///         w.replacing(WriteAttempts::times(20).apart(Duration::from_millis(250)))
    ///     })
    ///     .build()?;
    /// # Ok::<(), error_stack::Report<amethystate::store::StorageError>>(())
    /// ```
    pub fn file_write(
        mut self,
        configure: impl FnOnce(FileWritePolicy) -> FileWritePolicy,
    ) -> Self {
        self.config.file_write = configure(self.config.file_write);
        self
    }

    /// What this store refuses to hold, as against what its codec cannot.
    ///
    /// The codec's own ceiling is enforced whatever is set here - a value it
    /// cannot read back is refused always, because taking it produces a file
    /// that will not open. What this adds is the store's own: a cap on how deep
    /// a path may go, and a claim that the contents stay readable on engines
    /// other than the one running.
    ///
    /// ```no_run
    /// # use amethystate::store::builder::{Backend, StoreBuilder, default_backend};
    /// let store = StoreBuilder::new("./settings")
    ///     .limits(|l| l.key_depth(8).portable_across([default_backend()]))
    ///     .build()?;
    /// # Ok::<(), error_stack::Report<amethystate::store::StorageError>>(())
    /// ```
    ///
    /// The claim names the engines it means, so it stays what the application
    /// asked for when this crate gains another one, and so it can be as narrow
    /// as the requirement really is.
    pub fn limits(mut self, configure: impl FnOnce(WriteLimits) -> WriteLimits) -> Self {
        self.config.limits = configure(std::mem::take(&mut self.config.limits));
        self
    }

    /// Declares migration steps written by hand, and leaves a builder that can
    /// only [`migrate`](WithSteps::migrate).
    ///
    /// Steps written with `#[migrate]` are collected by
    /// [`StoreBuilder::migrate`] on its own; this is for the ones built by
    /// hand. What comes back has no `build`, since `build` runs no step and a
    /// step handed to it would be dropped without a word. Everything else the
    /// store is opened with is set before this.
    pub fn migrations(mut self, configure: impl FnOnce(&mut MigrationBuilder)) -> WithSteps {
        configure(&mut self.migration_builder);
        WithSteps(self)
    }

    /// Hands a value to every migration step that runs when this store opens.
    ///
    /// A step written with `#[migrate]` is collected at link time as a bare
    /// `fn(&mut MigrationContext)`, so it captures nothing: anything it needs
    /// from the application - a lookup table, a client, the settings it is
    /// porting away from - has no way in except a global. This is that way in.
    ///
    /// One value per type; the step asks for it back with
    /// [`MigrationContext::provided`] or [`MigrationContext::require`].
    ///
    /// ```
    /// # use amethystate::StoreBuilder;
    /// # let path = amethystate_core::test_utils::TempPath::new("doc");
    /// struct LegacyDefaults {
    ///     port: u16,
    /// }
    ///
    /// let (store, report) = StoreBuilder::new(&*path)
    ///     .provide(LegacyDefaults { port: 8080 })
    ///     .migrate()
    ///     .unwrap();
    /// # let _ = (store, report);
    /// ```
    ///
    /// [`MigrationContext::provided`]: crate::MigrationContext::provided
    /// [`MigrationContext::require`]: crate::MigrationContext::require
    pub fn provide<T: Any>(mut self, value: T) -> Self {
        self.migration_builder.provide(value);
        self
    }

    /// Hands a value to every rule this store's declared structs run.
    ///
    /// A rule written with `#[amestate(rule = ..)]` is a bare `fn` and
    /// captures nothing, so the world it has to judge a value against - which
    /// monitors exist, which themes are installed, what this machine allows -
    /// arrives here. One value per type; the rule asks for it back with
    /// [`RuleContext::get`] or [`RuleContext::require`].
    ///
    /// The `Send + Sync` bound is what separates this from
    /// [`StoreBuilder::provide`]. A migration step runs once, inside
    /// [`build`](StoreBuilder::build), on the thread that called it. A rule
    /// runs every time a value arrives or is written, including on the thread
    /// that watches the file, so what it reads has to be readable from there.
    ///
    /// ```
    /// # use amethystate::StoreBuilder;
    /// # let path = amethystate_core::test_utils::TempPath::new("doc_context");
    /// struct Monitors {
    ///     count: usize,
    /// }
    ///
    /// let store = StoreBuilder::new(&*path)
    ///     .context(Monitors { count: 2 })
    ///     .build()
    ///     .unwrap();
    ///
    /// assert_eq!(store.context().get::<Monitors>().unwrap().count, 2);
    /// ```
    ///
    /// [`RuleContext::get`]: crate::store::RuleContext::get
    /// [`RuleContext::require`]: crate::store::RuleContext::require
    pub fn context<T: Any + Send + Sync>(mut self, value: T) -> Self {
        self.rule_context.insert(value);
        self
    }

    /// Lets reading a large collection back use more than one core. Off by
    /// default, read by the `redb` engine, and what that trades is on
    /// [`StoreConfig::parallel_reads`](crate::store::config::StoreConfig::parallel_reads).
    pub fn parallel_reads(mut self, yes: bool) -> Self {
        self.config.parallel_reads = yes;
        self
    }

    /// What this store answers for the declarations that did not say.
    ///
    /// A field's own rule wins over its struct's, and a struct's over this. So
    /// an application says here what it wants of everything that had no
    /// opinion, and nothing that had one is overruled: a declaration is a
    /// promise its author made, and this is the last word in the chain rather
    /// than a word over it.
    ///
    /// ```
    /// use amethystate::StoreBuilder;
    /// use amethystate::store::OnUnreadable;
    ///
    /// # let path = amethystate_core::test_utils::TempPath::new("doc");
    /// // A store used as a cache: nothing in it is worth failing to start over.
    /// let store = StoreBuilder::new(&*path)
    ///     .rules(|r| r.on_unreadable(OnUnreadable::UseDefault))
    ///     .build()?;
    /// # Ok::<(), error_stack::Report<amethystate::store::StorageError>>(())
    /// ```
    ///
    /// Without this a value that will not decode refuses the open, and a field
    /// whose key is removed goes on reporting what it last held.
    pub fn rules(mut self, configure: impl FnOnce(Fallbacks) -> Fallbacks) -> Self {
        self.fallbacks = configure(self.fallbacks);
        self
    }

    /// What to do when the store's own files will not read.
    ///
    /// Without this the open is refused and the files are left for a person to
    /// look at, which is the answer settings want. A store whose contents can
    /// be rebuilt wants the other one.
    ///
    /// ```
    /// use amethystate::StoreBuilder;
    /// use amethystate::store::WillNotOpen;
    ///
    /// # let path = amethystate_core::test_utils::TempPath::new("doc");
    /// // A cache: whatever is in it is worth less than starting.
    /// let store = StoreBuilder::new(&*path)
    ///     .when_it_will_not_open(WillNotOpen::StartFresh)
    ///     .build()?;
    /// # Ok::<(), amethystate::store::OpenStore>(())
    /// ```
    ///
    /// It says nothing about a value inside a store that opened - that is
    /// [`StoreBuilder::rules`] - and nothing about a directory that cannot be
    /// written or a file something else holds, which are refused either way.
    pub fn when_it_will_not_open(mut self, rule: WillNotOpen) -> Self {
        self.config.will_not_open = rule;
        self
    }

    /// What a save does when the file it is about to replace will not read.
    ///
    /// A text store's file is meant to be edited, which means it can be found
    /// half-typed - and a save that meets one cannot lay its own paths over a
    /// document it cannot parse. Without this the file is moved aside under
    /// `<name>.unreadable` and the save goes ahead: nothing is lost and the
    /// application keeps running.
    ///
    /// ```
    /// use amethystate::StoreBuilder;
    /// use amethystate::store::WhenItWillNotRead;
    ///
    /// # let path = amethystate_core::test_utils::TempPath::new("doc");
    /// // A file somebody keeps open in their editor: do not touch it at all
    /// // until it parses again.
    /// let store = StoreBuilder::new(&*path)
    ///     .when_it_will_not_read(WhenItWillNotRead::Refuse)
    ///     .build()?;
    /// # Ok::<(), amethystate::store::OpenStore>(())
    /// ```
    ///
    /// This is about a file that broke while the store was open. A file that
    /// will not read at the moment of opening is
    /// [`StoreBuilder::when_it_will_not_open`], and the flat engines answer
    /// neither, because nobody else writes their file.
    pub fn when_it_will_not_read(mut self, rule: WhenItWillNotRead) -> Self {
        self.config.will_not_read = rule;
        self
    }

    /// Picks the engine explicitly. Without this the store uses
    /// [`default_backend`].
    ///
    /// An extension this crate chose moves with the engine: a path left
    /// without one by [`StoreBuilder::new`] or [`StoreBuilder::located`] is
    /// named for whichever engine actually runs, so a store asked for as
    /// `json` is not opened on a file called `.redb`. An extension the caller
    /// spelled stays as it is.
    pub fn backend(mut self, backend: Backend) -> Self {
        self.backend = Some(backend);
        if !self.caller_named_extension {
            self.config.path.set_extension(backend.extension());
        }
        self
    }

    /// Opens the store and runs no migration step.
    ///
    /// Steps handed to [`StoreBuilder::migrations`] and the ones written with
    /// `#[migrate]` are all [`StoreBuilder::migrate`]'s; here they are left
    /// alone. What is recorded about the declarations - their schema, and
    /// whether the stored data has drifted from them - is recorded either way,
    /// and a drift that would hand the code data of another shape refuses the
    /// open with [`OpenStore::Migrating`].
    ///
    /// ```
    /// # use amethystate::StoreBuilder;
    /// # let path = amethystate_core::test_utils::TempPath::new("doc");
    /// let store = StoreBuilder::new(&*path).build().unwrap();
    /// store.kv().set("a", &1u8).unwrap();
    /// assert_eq!(store.kv().get::<u8>("a").unwrap(), Some(1));
    /// ```
    pub fn build(self) -> Result<Store, OpenStore> {
        self.opening(Steps::None).map(|(store, _)| store)
    }

    /// Opens the store and brings what it holds up to what the code declares:
    /// every step handed to [`StoreBuilder::migrations`], and every one
    /// written with `#[migrate]` anywhere in the binary.
    ///
    /// Hands back what the pass did. A step that fails refuses the open with
    /// [`OpenStore::Migrating`], which carries the same report: the data under
    /// that prefix was not brought up to date, and a store opened over it
    /// would hand new code old data. A file a newer release wrote is one of
    /// those - see [`MigrationError::Downgrade`](crate::migration::MigrationError::Downgrade).
    pub fn migrate(self) -> Result<(Store, MigrationReport), OpenStore> {
        self.opening(Steps::All)
    }

    /// A store with no file, on [`Backend::Memory`].
    ///
    /// Everything the builder takes applies except what is about a file:
    /// limits, rules and context hold as they would on disk, and nothing is
    /// written anywhere.
    #[cfg(feature = "memory")]
    pub fn in_memory() -> Self {
        Self::new(PathBuf::new()).backend(Backend::Memory)
    }

    /// What the store answers where it will not open: a store in memory
    /// instead, and why. See [`OrInMemory`].
    #[cfg(feature = "memory")]
    pub fn or_in_memory(self) -> OrInMemory {
        OrInMemory(self)
    }

    fn opening(mut self, steps: Steps) -> Result<(Store, MigrationReport), OpenStore> {
        let context = Arc::new(std::mem::take(&mut self.rule_context));
        self.opening_with(steps, context)
    }

    fn opening_with(
        self,
        steps: Steps,
        context: Arc<RuleContext>,
    ) -> Result<(Store, MigrationReport), OpenStore> {
        let fallbacks = self.fallbacks;
        let (store, report) = self.on_disk(steps)?;

        if report.has_failures() {
            drop(store);
            return Err(OpenStore::migrating(report));
        }

        Ok((
            store.with_context(context).with_fallbacks(fallbacks),
            report,
        ))
    }

    fn on_disk(mut self, steps: Steps) -> Result<(Store, MigrationReport), OpenStore> {
        let backend = self
            .backend
            .ok_or_else(no_engine_built_in)
            .map_err(OpenStore::from_store)?;

        let mut migration_set = match steps {
            Steps::None => MigrationBuilder::default(),
            Steps::All => {
                self.migration_builder.collect_codegen();
                self.migration_builder
            }
        }
        .into_set()
        .map_err(refused_prefix)?;
        migration_set.take_on_undeclared(self.fallbacks.on_undeclared);

        let (store, report) = backend
            .open_public(self.config, migration_set)
            .map_err(OpenStore::from_store)?;

        report.log_to_tracing();
        Ok((store, report))
    }
}

enum Steps {
    None,
    All,
}

/// A [`StoreBuilder`] that opens a store in memory where the file will not
/// open, and says which it did.
///
/// For an application that would rather run without its settings than not
/// run: a file another process holds, a directory it cannot write, a file
/// that will not read, a file a newer release wrote that this one's steps turn
/// down. The store in memory starts empty, so every declared struct seeds its
/// defaults, and it writes nothing: the file stays for whoever can read it.
///
/// The refusal comes back whole in [`Persistence::InMemory`], so the
/// application can tell the user, or try again later on its own terms.
///
/// ```
/// # use amethystate::StoreBuilder;
/// # use amethystate::store::Persistence;
/// # let path = amethystate_core::test_utils::TempPath::new("doc_or_in_memory");
/// let (store, persistence) = StoreBuilder::new(&*path).or_in_memory().build();
///
/// if let Persistence::InMemory { because } = &persistence {
///     eprintln!("settings will not be saved this run: {because}");
/// }
/// # store.kv().set("port", &8080u16).unwrap();
/// ```
#[cfg(feature = "memory")]
pub struct OrInMemory<B = StoreBuilder>(B);

#[cfg(feature = "memory")]
impl OrInMemory {
    /// [`StoreBuilder::build`], or a store in memory.
    pub fn build(self) -> (Store, Persistence) {
        let (store, _, persistence) = falling_back(self.0, Steps::None);
        (store, persistence)
    }

    /// [`StoreBuilder::migrate`], or a store in memory.
    ///
    /// The report is the store's that came back: on a fall back, that is the
    /// store in memory, which had nothing to migrate. What the file's open
    /// said is in the refusal.
    pub fn migrate(self) -> (Store, MigrationReport, Persistence) {
        falling_back(self.0, Steps::All)
    }
}

#[cfg(feature = "memory")]
impl OrInMemory<WithSteps> {
    /// [`WithSteps::migrate`], or a store in memory.
    pub fn migrate(self) -> (Store, MigrationReport, Persistence) {
        falling_back(self.0.0, Steps::All)
    }
}

/// A [`StoreBuilder`] that was handed migration steps, which only
/// [`migrate`](WithSteps::migrate) runs.
pub struct WithSteps(StoreBuilder);

impl WithSteps {
    /// More steps written by hand, as [`StoreBuilder::migrations`] takes them.
    pub fn migrations(mut self, configure: impl FnOnce(&mut MigrationBuilder)) -> Self {
        configure(&mut self.0.migration_builder);
        self
    }

    /// A value for the steps, as [`StoreBuilder::provide`] hands it over.
    pub fn provide<T: Any>(self, value: T) -> Self {
        Self(self.0.provide(value))
    }

    /// [`StoreBuilder::migrate`], with the steps handed over as well.
    pub fn migrate(self) -> Result<(Store, MigrationReport), OpenStore> {
        self.0.migrate()
    }

    /// What the store answers where it will not open. See [`OrInMemory`].
    #[cfg(feature = "memory")]
    pub fn or_in_memory(self) -> OrInMemory<WithSteps> {
        OrInMemory(self)
    }

    pub(crate) fn into_builder(self) -> StoreBuilder {
        self.0
    }
}

#[cfg(feature = "memory")]
fn falling_back(mut builder: StoreBuilder, steps: Steps) -> (Store, MigrationReport, Persistence) {
    let context = Arc::new(std::mem::take(&mut builder.rule_context));
    let fallbacks = builder.fallbacks;
    let mut memory = StoreConfig::new(PathBuf::new());
    memory.limits = builder.config.limits.clone();
    memory.parallel_reads = builder.config.parallel_reads;

    match builder.opening_with(steps, context.clone()) {
        Ok((store, report)) => (store, report, Persistence::OnDisk),
        Err(because) => {
            tracing::warn!(
                target: "amethystate",
                reason = ?because,
                "the store would not open, so this run keeps it in memory and writes nothing",
            );

            let (store, report) = crate::store::backend::memory::MemoryStore::open(
                &memory,
                crate::migration::set::MigrationSet::default(),
            )
            .map(|(store, report)| (Store::from_arc(Arc::new(store)), report))
            .expect("an empty store in memory has no file to refuse it and no step to fail");

            (
                store.with_context(context).with_fallbacks(fallbacks),
                report,
                Persistence::InMemory { because },
            )
        }
    }
}

/// Where a store opened through [`StoreBuilder::or_in_memory`] keeps what it
/// is given.
#[cfg(feature = "memory")]
#[non_exhaustive]
pub enum Persistence {
    /// In its file, as asked.
    OnDisk,

    /// In memory, for this run only, because the file would not open.
    InMemory { because: OpenStore },
}

#[cfg(feature = "memory")]
impl Persistence {
    /// Whether the store fell back to memory.
    pub fn is_in_memory(&self) -> bool {
        matches!(self, Self::InMemory { .. })
    }

    /// Why the store fell back to memory, if it did.
    pub fn because(&self) -> Option<&OpenStore> {
        match self {
            Self::OnDisk => None,
            Self::InMemory { because } => Some(because),
        }
    }
}

#[cfg(feature = "memory")]
impl std::fmt::Debug for Persistence {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::OnDisk => f.write_str("OnDisk"),
            Self::InMemory { because } => write!(f, "InMemory: {because:?}"),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[cfg(all(feature = "redb", feature = "json"))]
    #[test]
    fn a_defaulted_extension_follows_the_engine_that_is_named() {
        let builder = StoreBuilder::new("app/settings").backend(Backend::Json);

        assert_eq!(
            builder.config.path.extension().and_then(|e| e.to_str()),
            Some("json"),
            "the engine was named after the path was built, and the path did not follow"
        );
    }

    #[cfg(all(feature = "redb", feature = "json", feature = "toml"))]
    #[test]
    fn the_last_engine_named_is_the_one_the_path_follows() {
        let builder = StoreBuilder::new("app/settings")
            .backend(Backend::Json)
            .backend(Backend::Toml);

        assert_eq!(
            builder.config.path.extension().and_then(|e| e.to_str()),
            Some("toml")
        );
    }

    #[cfg(all(feature = "redb", feature = "json"))]
    #[test]
    fn an_extension_the_caller_wrote_is_left_alone() {
        let builder = StoreBuilder::new("app/settings.conf").backend(Backend::Json);

        assert_eq!(
            builder.config.path.extension().and_then(|e| e.to_str()),
            Some("conf")
        );
    }

    #[test]
    fn an_unnamed_engine_keeps_the_default_extension() {
        let builder = StoreBuilder::new("app/settings");

        assert_eq!(
            builder.config.path.extension().and_then(|e| e.to_str()),
            Some(default_backend().extension())
        );
    }

    #[test]
    fn a_build_with_no_engine_refuses_the_open_and_names_the_features() {
        let mut builder = StoreBuilder::new("app/settings");
        builder.backend = None;

        let Err(refused) = builder.build() else {
            panic!("a store opened with no engine to open it with");
        };
        let OpenStore::WouldNotOpen { why } = &refused else {
            panic!("{refused:?}");
        };
        let said: Vec<&str> = why
            .frames()
            .filter_map(|frame| frame.downcast_ref::<&str>().copied())
            .collect();

        insta::assert_snapshot!(format!("{refused}\n{}", said.join("\n")));

        let mut migrating = StoreBuilder::new("app/settings");
        migrating.backend = None;

        assert!(matches!(
            migrating.migrate(),
            Err(OpenStore::WouldNotOpen { .. })
        ));
    }
}