persistant 0.21.0

A thin persistence layer over Apache OpenDAL for blobs and records by key: declared capabilities, atomic replace, typed records, and a blocking facade for synchronous callers.
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
// SPDX-License-Identifier: MIT OR Apache-2.0
//! The registry: needs in, sorted backends out, the id kept in config opens the backend.
#![cfg(feature = "registry")]

use persistant::capability::CapabilityId;
use persistant::capability::choose::Durability;
use persistant::capability::provider::{DurabilityShortfall, ProviderNeeds};
use persistant::kv::KvBackend;
use persistant::registry::{self, Endpoint, OpenError, OpenOptions};
use std::time::Duration;

fn id(s: &str) -> CapabilityId {
    CapabilityId::new(s).unwrap()
}

fn basic(min: Durability) -> ProviderNeeds {
    ProviderNeeds::new(vec![id("kv.get"), id("kv.put"), id("kv.delete")], min)
}

#[test]
fn the_ids_a_program_stores_in_its_config_are_pinned() {
    // Append-only: this list only ever grows. A changed meaning is a new id.
    let want: &[&str] = &[
        "memory",
        "fs",
        #[cfg(feature = "registry-sqlite")]
        "sqlite",
        #[cfg(feature = "registry-sqlite")]
        "sqlite-full",
        #[cfg(feature = "registry-sqlite")]
        "sqlite-secure",
        #[cfg(feature = "registry-postgres")]
        "postgres",
        #[cfg(feature = "registry-mysql")]
        "mysql",
        #[cfg(feature = "registry-mysql")]
        "mariadb",
    ];
    assert_eq!(registry::known_ids(), want);
}

#[test]
fn a_need_lists_only_the_backends_that_have_all_of_it_and_says_why() {
    let list = registry::providers(&basic(Durability::Process)).unwrap();
    let ids: Vec<_> = list.iter().map(|l| l.id).collect();
    assert!(ids.contains(&"fs"), "{ids:?}");
    // Positive control for the exclusion: `memory` has the capabilities but is volatile, and the
    // same need at Volatile does list it.
    assert!(!ids.contains(&"memory"), "{ids:?}");
    let all = registry::providers(&basic(Durability::Volatile)).unwrap();
    assert!(all.iter().any(|l| l.id == "memory"));
    let fs = list.iter().find(|l| l.id == "fs").unwrap();
    let why = fs.why().join("\n");
    assert!(why.contains("durability: process"), "{why}");
    assert!(why.contains("not measured"), "{why}");
}

#[test]
fn explain_is_capants_line_per_need_for_one_provider() {
    let needs = ProviderNeeds::new(
        vec![id("kv.get"), id("kv.no_such_capability")],
        Durability::Volatile,
    );
    let lines = registry::explain(&needs, "memory").expect("memory is a known id");
    assert_eq!(lines.len(), 2, "{lines:?}");
    assert!(lines[0].starts_with("kv.get: yes"), "{lines:?}");
    // Known-bad control: the id nobody certifies is not "yes" for a provider that qualifies on kv.get.
    assert!(
        lines[1].starts_with("kv.no_such_capability: unverified"),
        "{lines:?}"
    );
    // An id that is not in the table is None, and registry::providers still refuses the same need.
    assert_eq!(registry::explain(&needs, "no-such-backend"), None);
    assert!(registry::providers(&needs).is_err());
}

#[test]
fn nothing_satisfying_is_an_error_naming_each_backends_unmet_id() {
    let needs = ProviderNeeds::new(
        vec![id("kv.get"), id("kv.no_such_capability")],
        Durability::Volatile,
    );
    let e = registry::providers(&needs).unwrap_err();
    let named: Vec<_> = e.providers.iter().map(|p| p.provider.as_str()).collect();
    assert_eq!(named, registry::known_ids());
    for p in &e.providers {
        assert_eq!(p.missing.len(), 1, "{p:?}");
        assert_eq!(p.missing[0].0.as_str(), "kv.no_such_capability");
    }
    // Durability alone can rule everything out, and says so.
    let needs = ProviderNeeds::new(vec![id("kv.get")], Durability::Machine);
    if let Err(e) = registry::providers(&needs) {
        let mem = e.providers.iter().find(|p| p.provider == "memory").unwrap();
        assert_eq!(
            mem.durability,
            Some(DurabilityShortfall::Below(Durability::Volatile))
        );
    }
}

#[test]
fn preferred_capabilities_order_the_list_and_never_exclude() {
    let needs = basic(Durability::Volatile).prefer(vec![id("kv.ttl"), id("kv.no_such_capability")]);
    let list = registry::providers(&needs).unwrap();
    assert_eq!(
        list.len(),
        registry::known_ids().len(),
        "a preferred id never excludes"
    );
    for l in &list {
        assert_eq!(l.preferred.len(), 2);
        assert!(!l.preferred[1].1, "{}", l.id);
    }
    let why = list[0].why().join("\n");
    assert!(why.contains("lacks [kv.no_such_capability]"), "{why}");
}

#[tokio::test]
async fn open_named_gives_a_backend_agnostic_handle_for_memory_and_fs() {
    let needs = basic(Durability::Volatile);
    let h = registry::open_named("memory", &Endpoint::None, &needs)
        .await
        .unwrap();
    h.kv().put("k", b"v".to_vec(), None).await.unwrap();
    assert_eq!(h.kv().get("k").await.unwrap(), Some(b"v".to_vec()));
    assert_eq!(h.id(), "memory");

    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().join("kv");
    let h = registry::open_named("fs", &Endpoint::path(&root), &basic(Durability::Process))
        .await
        .expect("fs opens on every filesystem");
    h.kv().put("a", b"1".to_vec(), None).await.unwrap();
    drop(h);
    // The same id and path opened again sees the data: this is what "stored in config" means.
    let h = registry::open_named("fs", &Endpoint::path(&root), &basic(Durability::Process))
        .await
        .unwrap();
    assert_eq!(h.kv().get("a").await.unwrap(), Some(b"1".to_vec()));
}

#[tokio::test]
async fn open_named_refuses_before_touching_anything() {
    let needs = basic(Durability::Volatile);
    let e = registry::open_named("nope", &Endpoint::None, &needs)
        .await
        .unwrap_err();
    match e {
        OpenError::UnknownBackend { id, known } => {
            assert_eq!(id, "nope");
            assert_eq!(known, registry::known_ids());
        }
        other => panic!("{other:?}"),
    }
    let dir = tempfile::tempdir().unwrap();
    let e = registry::open_named("fs", &Endpoint::None, &needs)
        .await
        .unwrap_err();
    assert!(
        matches!(
            e,
            OpenError::WrongEndpoint {
                id: "fs",
                got: "none",
                ..
            }
        ),
        "{e:?}"
    );
    let e = registry::open_named("memory", &Endpoint::path(dir.path()), &needs)
        .await
        .unwrap_err();
    assert!(
        matches!(e, OpenError::WrongEndpoint { id: "memory", .. }),
        "{e:?}"
    );
    // Needs the backend does not meet: refused with the unmet id, and the directory is not created.
    let root = dir.path().join("never");
    let unmet = ProviderNeeds::new(vec![id("kv.no_such_capability")], Durability::Volatile);
    let e = registry::open_named("fs", &Endpoint::path(&root), &unmet)
        .await
        .unwrap_err();
    match e {
        OpenError::Unmet(u) => assert_eq!(
            u.providers[0].missing[0].0.as_str(),
            "kv.no_such_capability"
        ),
        other => panic!("{other:?}"),
    }
    assert!(!root.exists(), "the gate ran before any I/O");
    // Durability is part of the gate at open: memory is volatile.
    let e = registry::open_named("memory", &Endpoint::None, &basic(Durability::Process))
        .await
        .unwrap_err();
    assert!(matches!(e, OpenError::Unmet(_)), "{e:?}");
}

#[tokio::test(flavor = "multi_thread")]
async fn the_open_future_and_the_handle_are_send() {
    let needs = basic(Durability::Volatile);
    let t = tokio::spawn(async move {
        let h = registry::open_named("memory", &Endpoint::None, &needs)
            .await
            .unwrap();
        h.kv().put("k", vec![1], None).await.unwrap();
        h.kv().get("k").await.unwrap()
    });
    assert_eq!(t.await.unwrap(), Some(vec![1]));
}

#[cfg(feature = "registry-sqlite")]
#[tokio::test]
async fn sqlite_and_sqlite_full_are_told_apart_in_the_list_text() {
    let list = registry::providers(&basic(Durability::Process)).unwrap();
    let plain = list
        .iter()
        .find(|l| l.id == "sqlite")
        .unwrap()
        .why()
        .join("\n");
    let full = list
        .iter()
        .find(|l| l.id == "sqlite-full")
        .unwrap()
        .why()
        .join("\n");
    assert!(plain.contains("durability: process"), "{plain}");
    assert!(plain.contains("Pick `sqlite-full`"), "{plain}");
    assert!(
        full.contains("durability: machine (verified: machine)"),
        "{full}"
    );
    assert!(full.contains("synchronous=FULL"), "{full}");
    // Asking for Machine lists the durable profile and not the default one.
    let machine: Vec<_> = registry::providers(&basic(Durability::Machine))
        .unwrap()
        .iter()
        .map(|l| l.id)
        .collect();
    assert!(machine.contains(&"sqlite-full"), "{machine:?}");
    assert!(!machine.contains(&"sqlite"), "{machine:?}");

    let dir = tempfile::tempdir().unwrap();
    for name in ["sqlite", "sqlite-full"] {
        let file = dir.path().join(format!("{name}.db"));
        let h = registry::open_named(name, &Endpoint::path(&file), &basic(Durability::Process))
            .await
            .unwrap();
        h.kv().put("k", b"v".to_vec(), None).await.unwrap();
        assert_eq!(h.kv().get("k").await.unwrap(), Some(b"v".to_vec()));
        assert_eq!(h.kv().backend(), format!("kv-on-relational:{name}"));
    }
    // sqlite refuses a Machine need at open.
    let file = dir.path().join("refused.db");
    let e = registry::open_named(
        "sqlite",
        &Endpoint::path(&file),
        &basic(Durability::Machine),
    )
    .await
    .unwrap_err();
    assert!(matches!(e, OpenError::Unmet(_)), "{e:?}");
}

fn bounded() -> ProviderNeeds {
    ProviderNeeds::new(
        vec![id("kv.get"), id("kv.put"), id("kv.bounded_call")],
        Durability::Volatile,
    )
}

#[test]
fn a_bounded_need_is_unmet_by_memory_and_fs_whatever_else_is_built() {
    match registry::providers(&bounded()) {
        Err(e) => {
            // Nothing built can be bounded: every provider is named with the unmet id.
            assert_eq!(e.providers.len(), registry::known_ids().len());
            assert!(e.providers.iter().all(|p| {
                p.missing
                    .iter()
                    .any(|(i, _)| i.as_str() == "kv.bounded_call")
            }));
        }
        Ok(list) => {
            let ids: Vec<_> = list.iter().map(|l| l.id).collect();
            assert!(!ids.contains(&"memory") && !ids.contains(&"fs"), "{ids:?}");
            assert!(list[0].why().join("\n").contains("OpenOptions::call_bound"));
        }
    }
}

#[tokio::test]
async fn into_kv_gives_an_owned_store_for_a_generic_consumer() {
    async fn consumer<K: KvBackend>(kv: K) -> Option<Vec<u8>> {
        kv.put("k", b"v".to_vec(), None).await.unwrap();
        kv.get("k").await.unwrap()
    }
    let h = registry::open_named("memory", &Endpoint::None, &basic(Durability::Volatile))
        .await
        .unwrap();
    assert_eq!(consumer(h.into_kv()).await, Some(b"v".to_vec()));
}

#[tokio::test]
async fn a_call_bound_is_refused_where_it_cannot_apply_and_required_where_needed() {
    let opts = OpenOptions::new().call_bound(Duration::from_secs(2));
    let e = registry::open_named_with(
        "memory",
        &Endpoint::None,
        &basic(Durability::Volatile),
        &opts,
    )
    .await
    .unwrap_err();
    assert!(
        matches!(e, OpenError::BoundUnsupported { id: "memory" }),
        "{e:?}"
    );
    // A bounded need without a bound: refused before any I/O (the directory is not created).
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().join("never");
    let e = registry::open_named("fs", &Endpoint::path(&root), &bounded())
        .await
        .unwrap_err();
    assert!(matches!(e, OpenError::BoundRequired { id: "fs" }), "{e:?}");
    assert!(!root.exists());
}

/// `OpenOptions::with_live_check` (ROADMAP row 10): refused, before any I/O, where there is no
/// relational layer to run it on.
#[tokio::test]
async fn a_live_check_is_refused_where_there_is_nothing_to_run_it_on() {
    let opts = OpenOptions::new().with_live_check();
    let e = registry::open_named_with(
        "memory",
        &Endpoint::None,
        &basic(Durability::Volatile),
        &opts,
    )
    .await
    .unwrap_err();
    assert!(
        matches!(e, OpenError::LiveCheckUnsupported { id: "memory" }),
        "{e:?}"
    );
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().join("never");
    let e = registry::open_named_with(
        "fs",
        &Endpoint::path(&root),
        &basic(Durability::Process),
        &opts,
    )
    .await
    .unwrap_err();
    assert!(
        matches!(e, OpenError::LiveCheckUnsupported { id: "fs" }),
        "{e:?}"
    );
    assert!(!root.exists(), "nothing was touched");
    // Without the option the same opens still work (control: the refusal is the option's).
    registry::open_named("memory", &Endpoint::None, &basic(Durability::Volatile))
        .await
        .unwrap();
}

#[cfg(feature = "registry-sqlite")]
#[tokio::test]
async fn a_live_check_passes_on_sqlite_and_leaves_the_store_usable() {
    let dir = tempfile::tempdir().unwrap();
    let opts = OpenOptions::new().with_live_check();
    for name in ["sqlite", "sqlite-full"] {
        let file = dir.path().join(format!("{name}-live.db"));
        let h = registry::open_named_with(
            name,
            &Endpoint::path(&file),
            &basic(Durability::Process),
            &opts,
        )
        .await
        .unwrap();
        assert!(h.rel().is_none(), "the needs named no rel.* capability");
        h.kv().put("k", b"v".to_vec(), None).await.unwrap();
        assert_eq!(h.kv().get("k").await.unwrap(), Some(b"v".to_vec()));
    }
}

#[cfg(feature = "registry-sqlite")]
#[tokio::test]
async fn sqlite_lists_kv_bounded_call_and_opens_bounded_only_with_a_bound() {
    let list = registry::providers(&bounded()).unwrap();
    let ids: Vec<_> = list.iter().map(|l| l.id).collect();
    assert!(
        ids.contains(&"sqlite") && ids.contains(&"sqlite-full"),
        "{ids:?}"
    );
    assert!(!ids.contains(&"memory") && !ids.contains(&"fs"), "{ids:?}");
    let dir = tempfile::tempdir().unwrap();
    for name in ["sqlite", "sqlite-full"] {
        let file = dir.path().join(format!("{name}.db"));
        let e = registry::open_named(name, &Endpoint::path(&file), &bounded())
            .await
            .unwrap_err();
        assert!(matches!(e, OpenError::BoundRequired { .. }), "{e:?}");
        let opts = OpenOptions::new().call_bound(Duration::from_secs(5));
        let h = registry::open_named_with(name, &Endpoint::path(&file), &bounded(), &opts)
            .await
            .unwrap();
        assert_eq!(h.kv().call_bound(), Some(Duration::from_secs(5)));
        h.kv().put("k", b"v".to_vec(), None).await.unwrap();
        assert_eq!(h.kv().get("k").await.unwrap(), Some(b"v".to_vec()));
    }
    // Opened without the need and without a bound, the same backend reports no bound.
    let file = dir.path().join("plain.db");
    let h = registry::open_named(
        "sqlite",
        &Endpoint::path(&file),
        &basic(Durability::Process),
    )
    .await
    .unwrap();
    assert_eq!(h.kv().call_bound(), None);
}

// ---- the blob and relational kinds are listed (docs/DESIGN-REGISTRY-KINDS.md, work order 1) ----

fn blob_need(min: Durability) -> ProviderNeeds {
    ProviderNeeds::new(
        vec![id("blob.read"), id("blob.write"), id("blob.stat")],
        min,
    )
}

fn listed(needs: &ProviderNeeds) -> Vec<&'static str> {
    registry::providers(needs)
        .unwrap()
        .iter()
        .map(|l| l.id)
        .collect()
}

#[test]
fn a_blob_need_lists_the_blob_backends_and_no_sql_database() {
    let ids = listed(&blob_need(Durability::Volatile));
    assert!(ids.contains(&"memory") && ids.contains(&"fs"), "{ids:?}");
    // Control: the same build lists SQL backends for a kv need, so their absence here is the need's doing.
    let kv_ids = listed(&basic(Durability::Volatile));
    #[cfg(feature = "registry-sqlite")]
    {
        assert!(kv_ids.contains(&"sqlite"), "{kv_ids:?}");
        assert!(
            !ids.contains(&"sqlite") && !ids.contains(&"sqlite-full"),
            "{ids:?}"
        );
    }
    assert!(kv_ids.len() >= ids.len());
}

#[test]
fn the_durability_of_a_blob_need_is_the_blob_stores() {
    // opendal-memory declares Volatile, opendal-fs Process.
    let ids = listed(&blob_need(Durability::Process));
    assert_eq!(ids, ["fs"]);
    let e = registry::providers(&blob_need(Durability::Machine)).unwrap_err();
    assert!(
        e.providers
            .iter()
            .any(|p| p.provider == "fs" && p.durability.is_some()),
        "{e}"
    );
}

#[test]
fn a_need_naming_two_kinds_is_met_only_where_both_are_served() {
    let both = ProviderNeeds::new(
        vec![id("kv.get"), id("kv.put"), id("blob.stat")],
        Durability::Volatile,
    );
    let ids = listed(&both);
    assert!(ids.contains(&"memory") && ids.contains(&"fs"), "{ids:?}");
    #[cfg(feature = "registry-sqlite")]
    assert!(!ids.contains(&"sqlite"), "{ids:?}");
    let list = registry::providers(&both).unwrap();
    assert!(
        list.iter()
            .all(|l| l.why().iter().any(|w| w.contains("weakest"))),
        "a multi-kind need says whose durability is shown"
    );
}

#[test]
fn a_need_no_provider_serves_is_unmet_and_names_each_backends_missing_id() {
    // Blob and relational at once: no provider has both layers.
    let n = ProviderNeeds::new(
        vec![id("blob.stat"), id("rel.transaction")],
        Durability::Volatile,
    );
    let e = registry::providers(&n).unwrap_err();
    let fs = e.providers.iter().find(|p| p.provider == "fs").unwrap();
    assert!(
        fs.missing
            .iter()
            .any(|(i, _)| i.as_str() == "rel.transaction")
            && !fs.missing.iter().any(|(i, _)| i.as_str() == "blob.stat"),
        "{e}"
    );
    // The wording is `capant`'s: a capability nothing shows is unverified, not "no row".
    let text = e.to_string();
    assert!(
        text.contains("rel.transaction unverified(no row)"),
        "{text}"
    );
    assert!(!text.contains("no-row"), "{text}");
}

#[cfg(feature = "registry-sqlite")]
#[test]
fn a_relational_need_lists_sqlite_and_not_the_blob_stores() {
    let n = ProviderNeeds::new(
        vec![id("rel.values"), id("rel.transaction")],
        Durability::Volatile,
    );
    let ids = listed(&n);
    assert!(ids.contains(&"sqlite"), "{ids:?}");
    assert!(!ids.contains(&"memory") && !ids.contains(&"fs"), "{ids:?}");
    // `sqlite-full` is the same engine with a stricter flush and has its own relational rows since
    // 0.12.1 (the matrix job certifies the kind on both profiles): it is listed too.
    assert!(ids.contains(&"sqlite-full"), "{ids:?}");
}

#[cfg(feature = "registry-sqlite")]
fn rel_need() -> ProviderNeeds {
    ProviderNeeds::new(
        vec![id("rel.values"), id("rel.transaction")],
        Durability::Volatile,
    )
}

#[cfg(feature = "registry-sqlite")]
#[tokio::test]
async fn the_rel_handle_passes_the_same_contract_as_the_driver() {
    use persistant::capability::Config;
    use persistant::relational::RelationalBackend;
    use persistant::relational::conformance::certify;
    use persistant::sqlx_driver::SqliteBackend;

    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("x.sqlite");
    let h = registry::open_named("sqlite", &Endpoint::path(&file), &rel_need())
        .await
        .unwrap();
    let rel = h.rel().expect("a rel need gets a relational handle");
    let direct = SqliteBackend::open(&dir.path().join("direct.sqlite"))
        .await
        .unwrap();
    let through = certify(
        rel,
        &Config::new().with("dialect", "sqlite"),
        &Config::new(),
    )
    .await;
    let plain = certify(
        &direct,
        &Config::new().with("dialect", "sqlite"),
        &Config::new(),
    )
    .await;
    let sum = |rows: &[persistant::relational::conformance::Certified]| -> Vec<(String, bool)> {
        rows.iter()
            .map(|c| (c.leaf.id().to_string(), c.row.enabled))
            .collect()
    };
    assert_eq!(sum(&through), sum(&plain));
    // Control: the contract ran, and something passed.
    assert!(through.iter().any(|c| c.row.enabled));
    assert_eq!(rel.backend(), direct.backend());
}

#[cfg(feature = "registry-sqlite")]
#[tokio::test]
async fn the_rel_handle_runs_statements_and_transactions_and_exists_only_when_asked_for() {
    use persistant::relational::{Isolation, RelationalBackend, RelationalTx, Value};

    let dir = tempfile::tempdir().unwrap();
    let file = dir.path().join("x.sqlite");
    // A kv-only need: no relational handle (the kv store is there regardless).
    let h = registry::open_named(
        "sqlite",
        &Endpoint::path(&file),
        &basic(Durability::Volatile),
    )
    .await
    .unwrap();
    assert!(h.rel().is_none());
    drop(h);

    let h = registry::open_named("sqlite", &Endpoint::path(&file), &rel_need())
        .await
        .unwrap();
    let rel = h.rel().unwrap();
    assert_eq!(rel.dialect(), persistant::relational::Dialect::Sqlite);
    assert_eq!(rel.call_bound(), None);
    rel.execute("CREATE TABLE t (a INTEGER)", &[])
        .await
        .unwrap();
    // A rolled-back transaction leaves nothing; a committed one does.
    let mut tx = rel.begin(Isolation::default()).await.unwrap();
    tx.execute("INSERT INTO t (a) VALUES (?)", &[Value::Int(1)])
        .await
        .unwrap();
    tx.rollback().await.unwrap();
    assert!(rel.query("SELECT a FROM t", &[]).await.unwrap().is_empty());
    let mut tx = rel.begin(Isolation::default()).await.unwrap();
    tx.execute("INSERT INTO t (a) VALUES (?)", &[Value::Int(2)])
        .await
        .unwrap();
    tx.commit().await.unwrap();
    assert_eq!(rel.query("SELECT a FROM t", &[]).await.unwrap().len(), 1);
    // The key-value store shares the file and is untouched by the table.
    h.kv().put("k", b"v".to_vec(), None).await.unwrap();
    assert_eq!(h.kv().get("k").await.unwrap().unwrap(), b"v");

    // A call bound is carried through to the relational handle.
    let opts = OpenOptions::new().call_bound(Duration::from_secs(7));
    let b = registry::open_named_with("sqlite", &Endpoint::path(&file), &rel_need(), &opts)
        .await
        .unwrap();
    assert_eq!(b.rel().unwrap().call_bound(), Some(Duration::from_secs(7)));
    let mut tx = b.rel().unwrap().begin(Isolation::default()).await.unwrap();
    assert_eq!(tx.query("SELECT a FROM t", &[]).await.unwrap().len(), 1);
    tx.rollback().await.unwrap();
}

#[cfg(feature = "registry-sqlite")]
#[tokio::test]
async fn blob_and_rel_together_open_both_and_a_rel_need_on_a_blob_store_is_refused_untouched() {
    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().join("blobs");
    let e = registry::open_named("fs", &Endpoint::path(&root), &rel_need())
        .await
        .unwrap_err();
    assert!(matches!(e, OpenError::Unmet(_)), "{e:?}");
    assert!(!root.exists());
    let file = dir.path().join("y.sqlite");
    let both = ProviderNeeds::new(
        vec![id("rel.values"), id("blob.read")],
        Durability::Volatile,
    );
    // No provider serves blob and rel both (sqlite has no blob row): unmet, nothing opened.
    let e = registry::open_named("sqlite", &Endpoint::path(&file), &both)
        .await
        .unwrap_err();
    assert!(matches!(e, OpenError::Unmet(_)), "{e:?}");
    assert!(!file.exists());
}

fn summary(rows: &[persistant::blob::conformance::Certified]) -> Vec<(String, bool)> {
    rows.iter()
        .map(|c| (c.leaf.id().to_string(), c.row.enabled))
        .collect()
}

#[tokio::test]
async fn the_blob_handle_passes_the_same_contract_as_the_driver_on_memory_and_fs() {
    use persistant::blob::BlobBackend;
    use persistant::blob::conformance::certify;
    use persistant::capability::Config;
    use persistant::opendal_driver::OpendalBlob;

    let dir = tempfile::tempdir().unwrap();
    let root = dir.path().join("blobs");
    let direct_dir = dir.path().join("direct");
    std::fs::create_dir_all(&direct_dir).unwrap();
    let scratch = dir.path().join("direct.persistant-atomic");
    std::fs::create_dir_all(&scratch).unwrap();
    let cases: [(&str, Endpoint, OpendalBlob); 2] = [
        ("memory", Endpoint::None, OpendalBlob::memory().unwrap()),
        (
            "fs",
            Endpoint::path(&root),
            OpendalBlob::fs(&direct_dir, Some(&scratch)).unwrap(),
        ),
    ];
    for (name, endpoint, direct) in cases {
        let h = registry::open_named(name, &endpoint, &blob_need(Durability::Volatile))
            .await
            .unwrap();
        let blob = h.blob().expect("a blob need gets a blob handle");
        let through = certify(blob, blob.config(), &Config::new()).await;
        let plain = certify(&direct, direct.config(), &Config::new()).await;
        assert_eq!(summary(&through), summary(&plain), "{name}");
        // Control: the contract ran (a result per leaf, and at least one on).
        assert!(through.iter().any(|c| c.row.enabled), "{name}");
        assert_eq!(blob.backend(), direct.backend());
    }
}

#[tokio::test]
async fn the_blob_handle_refuses_the_keys_the_key_value_store_keeps() {
    use persistant::blob::BlobBackend;

    let dir = tempfile::tempdir().unwrap();
    for (name, endpoint) in [
        ("memory", Endpoint::None),
        ("fs", Endpoint::path(dir.path().join("b"))),
    ] {
        let both = ProviderNeeds::new(
            vec![
                id("kv.get"),
                id("kv.put"),
                id("blob.read"),
                id("blob.write"),
            ],
            Durability::Volatile,
        );
        let h = registry::open_named(name, &endpoint, &both).await.unwrap();
        let blob = h.blob().unwrap();
        for key in ["kv", "kvx", "kv/a", "kvx/6b/x"] {
            let e = blob.write(key, b"x".to_vec()).await.unwrap_err();
            assert!(
                e.to_string().contains("key-value store"),
                "{name} {key}: {e}"
            );
            assert!(blob.read(key).await.is_err(), "{name} {key}");
            assert!(blob.delete(key).await.is_err(), "{name} {key}");
            assert!(blob.stat(key).await.is_err(), "{name} {key}");
            // The ranged and streamed operations go through the same check (work order 2): the
            // refusal names the key-value store, not "does not support".
            let e = blob.read_range(key, 0, 1).await.unwrap_err();
            assert!(
                e.to_string().contains("key-value store"),
                "{name} {key}: {e}"
            );
            for atomic in [false, true] {
                let r = if atomic {
                    blob.write_stream_atomic(key).await
                } else {
                    blob.write_stream(key).await
                };
                let e = r.err().expect("a reserved key opens no stream");
                assert!(
                    e.to_string().contains("key-value store"),
                    "{name} {key}: {e}"
                );
            }
        }
        assert!(blob.list("kv/", None, 10).await.is_err());
        assert!(blob.list("kvx/", None, 10).await.is_err());
        // Control: names that only start like a reserved one are ordinary keys.
        for key in ["kvs/a", "kvx2", "kvx.txt", "k"] {
            blob.write(key, b"ok".to_vec()).await.unwrap();
            assert_eq!(
                blob.read(key).await.unwrap().unwrap(),
                b"ok",
                "{name} {key}"
            );
        }
        // The key-value store writes through the same directory, and a listing never shows it.
        h.kv().put("some key", b"v".to_vec(), None).await.unwrap();
        let page = blob.list("", None, 100).await.unwrap();
        let keys: Vec<&str> = page.entries.iter().map(|e| e.key.as_str()).collect();
        assert_eq!(keys, vec!["k", "kvs/a", "kvx.txt", "kvx2"], "{name}");
        assert_eq!(h.kv().get("some key").await.unwrap().unwrap(), b"v");
    }
}

#[tokio::test]
async fn the_blob_handle_exists_only_for_a_need_that_named_a_blob_id() {
    let h = registry::open_named("memory", &Endpoint::None, &basic(Durability::Volatile))
        .await
        .unwrap();
    assert!(h.blob().is_none());
    let h = registry::open_named("memory", &Endpoint::None, &blob_need(Durability::Volatile))
        .await
        .unwrap();
    assert!(h.blob().is_some());
    // The key-value store is always there (additive).
    h.kv().put("k", b"v".to_vec(), None).await.unwrap();
}

#[test]
fn endpoint_fits_says_which_listings_an_endpoint_can_open() {
    use persistant::capability::provider::EndpointSpec;
    use persistant::relational::ConnectionSecret;
    let url = |s: &str| Endpoint::Secret(ConnectionSecret::literal(s));
    let pg = EndpointSpec::Url {
        schemes: vec!["postgres".into(), "postgresql".into()],
    };
    let dir = std::env::temp_dir();
    assert!(Endpoint::None.fits(&EndpointSpec::None).unwrap());
    assert!(!Endpoint::None.fits(&EndpointSpec::Path).unwrap());
    assert!(Endpoint::path(&dir).fits(&EndpointSpec::Path).unwrap());
    assert!(!Endpoint::path(&dir).fits(&pg).unwrap());
    assert!(url("postgres://u:pw@h/db").fits(&pg).unwrap());
    assert!(!url("mysql://u:pw@h/db").fits(&pg).unwrap());
    assert!(!url("no-scheme-here").fits(&pg).unwrap());
    assert!(
        !url("postgres://u:pw@h/db")
            .fits(&EndpointSpec::Path)
            .unwrap()
    );
    // An unreadable secret is an error that does not carry what it could not read.
    let e = Endpoint::url_env("PERSISTANT_NO_SUCH_VARIABLE_FOR_FITS")
        .fits(&pg)
        .unwrap_err();
    assert!(!format!("{e} {e:?}").contains("pw"));
    // Every listing a consumer gets can be asked the same question.
    let needs = basic(Durability::Volatile);
    let listings = registry::providers(&needs).unwrap();
    let ids: Vec<_> = listings
        .iter()
        .filter(|l| Endpoint::None.fits(&l.endpoint).unwrap())
        .map(|l| l.id)
        .collect();
    assert_eq!(ids, ["memory"]);
}

/// `storage.secure_delete` is something a consumer can prefer: `sqlite-secure` has it, `sqlite`
/// does not, and neither is excluded. The profile opens, and a plain overwrite through the handle
/// leaves no old bytes in the file (the default profile is the control).
#[cfg(feature = "registry-sqlite")]
#[tokio::test]
async fn sqlite_secure_is_preferable_and_zeroes_what_a_plain_overwrite_frees() {
    const CANARY: &[u8] = b"CANARY-3c5f9a10-not-a-secret";
    let needs = basic(Durability::Process).prefer(vec![id("storage.secure_delete")]);
    let listed = registry::providers(&needs).unwrap();
    let has = |name: &str| {
        listed
            .iter()
            .find(|l| l.id == name)
            .unwrap_or_else(|| panic!("no listing for {name}"))
            .preferred[0]
            .1
    };
    assert!(has("sqlite-secure"));
    assert!(
        !has("sqlite"),
        "control: the default profile does not claim it"
    );
    assert!(!has("sqlite-full"));
    assert_eq!(
        listed[0].id, "sqlite-secure",
        "the preference orders it first among those that fit"
    );

    let needs = &needs;
    let leaves_canary = |name: &'static str| async move {
        let dir = std::env::temp_dir().join(format!(
            "persistant-reg-secure-{}-{name}",
            std::process::id()
        ));
        let _ = std::fs::remove_dir_all(&dir);
        std::fs::create_dir_all(&dir).unwrap();
        let h = registry::open_named(name, &Endpoint::path(dir.join("k.db")), needs)
            .await
            .unwrap();
        for i in 0..20 {
            h.kv()
                .put(&format!("b/{i}"), vec![b'.'; 100], None)
                .await
                .unwrap();
        }
        h.kv().put("u/over", CANARY.to_vec(), None).await.unwrap();
        h.kv().put("u/other", CANARY.to_vec(), None).await.unwrap();
        h.kv().put("u/over", b"short".to_vec(), None).await.unwrap();
        h.kv().delete("u/other").await.unwrap();
        let found = std::fs::read_dir(&dir).unwrap().any(|e| {
            std::fs::read(e.unwrap().path())
                .unwrap()
                .windows(CANARY.len())
                .any(|w| w == CANARY)
        });
        drop(h);
        let _ = std::fs::remove_dir_all(&dir);
        found
    };
    assert!(
        leaves_canary("sqlite").await,
        "control: the default profile keeps the old bytes"
    );
    assert!(!leaves_canary("sqlite-secure").await);
}