tinystore 0.12.0

A small storage runtime for applications on SQLite: SQL, key-value state, durable jobs, files, search, logs and metrics in one directory
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
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
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::UNIX_EPOCH;

use super::fixture::{Client, answered};
use super::*;
use crate::wire::codec::{Message, Row};
use crate::wire::frame::{self, Frame, Kind};
use crate::wire::protocol::{
    Empty, Failure as Failed, Handle, Hello, KvAllowance, KvAnswer, KvBranch, KvCall, KvCheck, KvCount, KvCountersOpen,
    KvEntry, KvList, KvOnceOpen, KvOp, KvPage, KvQuotaOpen, KvTx, KvTxResults, KvWindow, KvWritten, METHODS,
    ServerClock, method,
};

#[test]
fn a_client_sets_and_gets_a_key_through_the_pipe() {
    let dir = tempfile::tempdir().unwrap();
    let mut client = Client::open(dir.path());
    let handle = client.bucket("sessions");
    let token = KvCall { handle, under: vec!["7".to_owned()], key: "token".to_owned(), ..KvCall::default() };

    let set = KvCall { value: Some(Row::Bin(b"hello".to_vec())), ..token.clone() };
    let written: KvWritten = client.call(method::KV_SET, &set).unwrap();
    assert!(written.written);

    let entry: KvEntry = client.call(method::KV_GET, &token).unwrap();
    assert_eq!((entry.found, entry.value), (true, Some(Row::Bin(b"hello".to_vec()))));
    assert_eq!(entry.version, Some(written.version), "the version the set gave");
}

// contract: ERR-03
// contract: WIRE-01
#[test]
fn a_take_or_a_delete_given_a_ttl_or_a_time_is_invalid_as_in_the_core() {
    let dir = tempfile::tempdir().unwrap();
    let mut client = Client::open(dir.path());
    let handle = client.bucket("sessions");
    let token = KvCall { handle, key: "token".to_owned(), ..KvCall::default() };
    client.call::<KvWritten>(method::KV_SET, &KvCall { value: Some(Row::Int(1)), ..token.clone() }).unwrap();
    let timed = [KvCall { ttl: Some(60_000), ..token.clone() }, KvCall { expires_at: Some(1 << 41), ..token.clone() }];
    for (called, verb) in [(method::KV_TAKE, "take"), (method::KV_DELETE, "delete")] {
        for call in &timed {
            let alone = client.call::<Empty>(called, call).unwrap_err();
            let batch = KvTx { checks: Vec::new(), writes: vec![KvOp { method: called.into(), call: call.clone() }] };
            let batched = client.call::<Empty>(method::KV_TX, &batch).unwrap_err();
            for failed in [alone, batched] {
                assert_eq!(failed.code, "invalid", "{verb}: {}", failed.message);
                assert!(failed.message.contains(&format!("a ttl or a time on a {verb}")), "{}", failed.message);
            }
        }
    }
    let entry: KvEntry = client.call(method::KV_GET, &token).unwrap();
    assert!(entry.found, "nothing took or deleted the key");
}

#[test]
fn every_method_of_the_schema_is_answered() {
    let dir = tempfile::tempdir().unwrap();
    let mut client = Client::open(dir.path());
    for &(name, called, _) in METHODS {
        let stream = client.start(called, &Empty {});
        let answer = client.next_on(stream);
        // an answer of its own shape, a poll's cursor among them, is an answer too
        if answer.flags & frame::ERROR != 0 {
            let failed = Failed::decode(&answer.body).unwrap();
            assert_ne!(failed.code, "unimplemented", "{name}: {}", failed.message);
        }
    }
}

#[test]
fn a_method_the_core_does_not_have_is_unimplemented() {
    let dir = tempfile::tempdir().unwrap();
    let mut client = Client::open(dir.path());
    let failed = client.call::<Empty>(0x0f01, &Empty {}).unwrap_err();
    assert_eq!(failed.code, "unimplemented");
}

// contract: WIRE-02
#[test]
fn a_field_the_core_does_not_know_is_unimplemented_and_named() {
    let dir = tempfile::tempdir().unwrap();
    let mut client = Client::open(dir.path());
    let handle = client.bucket("sessions");
    let mut body = KvCall { handle, key: "a".to_owned(), ..KvCall::default() }.encode();
    body[0] += 1; // one more pair in the map: field 99, a nil
    body.extend_from_slice(&[99, 0xc0]);
    client.next_stream += 1;
    client.write(Frame { method: method::KV_GET, ..Frame::new(Kind::Request, client.next_stream, body) }.ending());
    let failed = answered::<Empty>(&client.next_on(client.next_stream)).unwrap_err();
    assert_eq!(failed.code, "unimplemented");
    assert!(failed.message.contains("field 99 of kv.Call"), "{}", failed.message);
}

#[test]
fn a_client_of_another_protocol_is_refused_with_goaway() {
    let dir = tempfile::tempdir().unwrap();
    let mut client = Client::connect(dir.path());
    let refused = client.hello(2).unwrap_err();
    assert_eq!(refused.code, "protocol");
}

/// A newer client's HELLO may carry a field this server lacks: the server
/// reads past it, as docs/wire.md says, where a request's would be refused.
#[test]
fn a_hello_with_a_field_the_server_lacks_is_welcomed_and_one_nested_past_the_profile_is_not() {
    use crate::wire::msgpack::{write_array_head, write_map_head, write_str, write_uint};
    let hello = |nested: usize| {
        let mut body = Vec::new();
        write_map_head(&mut body, 3);
        write_uint(&mut body, 1);
        write_uint(&mut body, 1);
        write_uint(&mut body, 2);
        write_str(&mut body, "test/9");
        write_uint(&mut body, 99);
        for _ in 0..nested {
            write_map_head(&mut body, 1);
            write_str(&mut body, "later");
        }
        write_array_head(&mut body, 0);
        let mut bytes = Vec::new();
        Frame::new(Kind::Hello, 0, body).encode_into(&mut bytes);
        bytes
    };
    // the message is level 0 and its field level 1: seven maps put the array at 8
    for (nested, answered) in [(0, Kind::Welcome), (7, Kind::Welcome), (8, Kind::GoAway)] {
        let dir = tempfile::tempdir().unwrap();
        let mut client = Client::connect(dir.path());
        client.reader.push(&client.pipe.send(&hello(nested)));
        assert_eq!(client.read().kind, answered, "a field {nested} maps deep");
    }
}

#[test]
fn a_frame_before_hello_ends_the_pipe_with_goaway() {
    let dir = tempfile::tempdir().unwrap();
    let pipe = Pipe::open(dir.path(), &[], None).unwrap();
    let mut bytes = Vec::new();
    Frame::new(Kind::Ping, 0, vec![0; 8]).encode_into(&mut bytes);
    let mut reader = frame::Reader::default();
    reader.push(&pipe.send(&bytes));
    assert_eq!(reader.next(1 << 20).unwrap().unwrap().kind, Kind::GoAway);
}

// contract: KV-11
#[test]
fn a_run_of_once_is_handed_to_the_client_and_its_answer_kept_for_the_next() {
    let dir = tempfile::tempdir().unwrap();
    let mut client = Client::open(dir.path());
    let open = KvOnceOpen { name: "charges".to_owned(), ..KvOnceOpen::default() };
    let handle = client.call::<Handle>(method::KV_ONCE_OPEN, &open).unwrap().handle;
    let charge = KvCall { handle, key: "order-1".to_owned(), ..KvCall::default() };

    let first = client.run(&charge);
    let handed = client.next_on(first);
    assert_eq!((handed.kind, handed.flags), (Kind::Response, 0), "the run is the client's, its stream open");
    assert!(!KvAnswer::decode(&handed.body).unwrap().found);
    let second = client.run(&charge);

    let charged = KvAnswer { found: true, value: Some(Row::Int(42)) };
    client.write(Frame::new(Kind::Data, first, charged.encode()).ending());
    let kept = client.next_on(first);
    assert_eq!((kept.kind, kept.flags), (Kind::Data, frame::END));

    let waited = client.next_on(second);
    assert_eq!((waited.kind, waited.flags), (Kind::Response, frame::END), "the second caller ran nothing");
    assert_eq!(KvAnswer::decode(&waited.body).unwrap(), charged);
}

// contract: KV-11
#[test]
fn a_run_that_failed_or_was_cancelled_hands_the_key_to_the_next_caller() {
    let dir = tempfile::tempdir().unwrap();
    let mut client = Client::open(dir.path());
    let open = KvOnceOpen { name: "charges".to_owned(), ..KvOnceOpen::default() };
    let handle = client.call::<Handle>(method::KV_ONCE_OPEN, &open).unwrap().handle;
    let charge = KvCall { handle, key: "order-1".to_owned(), ..KvCall::default() };

    let failed = client.run(&charge);
    assert_eq!(client.next_on(failed).flags, 0);
    client.write(Frame::new(Kind::Data, failed, KvAnswer::default().encode()).ending());
    assert_eq!(client.next_on(failed).flags, frame::END, "nothing kept");

    let cancelled = client.run(&charge);
    assert_eq!(client.next_on(cancelled).flags, 0, "handed again after the failure");
    client.write(Frame::new(Kind::Cancel, cancelled, Vec::new()));
    let ended = client.next_on(cancelled);
    assert_eq!((ended.kind, ended.flags), (Kind::Data, frame::END | frame::ERROR));
    assert_eq!(Failed::decode(&ended.body).unwrap().code, "cancelled");

    let third = client.run(&charge);
    assert_eq!(client.next_on(third).flags, 0, "handed again after the cancel");
}

// contract: KV-11
#[test]
fn a_run_cancelled_while_it_waits_is_never_handed_the_key() {
    let dir = tempfile::tempdir().unwrap();
    let mut client = Client::open(dir.path());
    let open = KvOnceOpen { name: "charges".to_owned(), ..KvOnceOpen::default() };
    let handle = client.call::<Handle>(method::KV_ONCE_OPEN, &open).unwrap().handle;
    let charge = KvCall { handle, key: "order-1".to_owned(), ..KvCall::default() };

    let first = client.run(&charge);
    assert_eq!(client.next_on(first).flags, 0);
    let waiting = client.run(&charge);
    client.write(Frame::new(Kind::Cancel, waiting, Vec::new()));
    let cancelled = client.next_on(waiting);
    assert_eq!((cancelled.kind, cancelled.flags), (Kind::Response, frame::END | frame::ERROR));

    client.write(Frame::new(Kind::Data, first, KvAnswer::default().encode()).ending());
    assert_eq!(client.next_on(first).flags, frame::END, "nothing kept");
    let next = client.run(&charge);
    assert_eq!(client.next_on(next).flags, 0, "the key is the next caller's, not the cancelled one's");
}

#[test]
fn a_transaction_applies_its_writes_or_names_the_read_that_changed() {
    let dir = tempfile::tempdir().unwrap();
    let mut client = Client::open(dir.path());
    let handle = client.bucket("stock");
    let key = |key: &str| KvCall { handle, key: key.to_owned(), ..KvCall::default() };
    let set = |name: &str, n: i64| KvOp {
        method: method::KV_SET.into(),
        call: KvCall { value: Some(Row::Int(n)), ..key(name) },
    };
    let read: KvWritten = client.call(method::KV_SET, &KvCall { value: Some(Row::Int(5)), ..key("apples") }).unwrap();

    let check = KvCheck { handle, key: "apples".to_owned(), version: Some(read.version.clone()), ..KvCheck::default() };
    let tx = KvTx { checks: vec![check.clone()], writes: vec![set("apples", 4), set("baskets", 1)] };
    let results: KvTxResults = client.call(method::KV_TX, &tx).unwrap();
    assert!(results.outcomes.iter().all(|outcome| outcome.written));

    let absent = KvCheck { handle, key: "pears".to_owned(), ..KvCheck::default() };
    let stale = KvTx { checks: vec![absent, check], writes: vec![set("apples", 3)] };
    let failed = client.call::<KvTxResults>(method::KV_TX, &stale).unwrap_err();
    assert_eq!(failed.code, "conflict");
    assert_eq!(failed.what.unwrap().get("check").map(String::as_str), Some("1"), "the second read changed");
    let apples: KvEntry = client.call(method::KV_GET, &key("apples")).unwrap();
    assert_eq!(apples.value, Some(Row::Int(4)), "nothing of the failed transaction was written");
}

/// A server's connection to a store it holds: its stops counted, its clock
/// a test clock at 1,790,000,000,000 ms, its proof the challenge reversed.
fn served(store: &Store, stops: &Arc<AtomicUsize>) -> Pipe {
    let stops = Arc::clone(stops);
    let connect = Connect {
        stop: Some(Arc::new(move || {
            stops.fetch_add(1, Ordering::SeqCst);
        })),
        clock: Some(Arc::new(TestClock::new(UNIX_EPOCH + Duration::from_millis(1_790_000_000_000)))),
        prove: Some(Arc::new(|challenge: &[u8]| challenge.iter().rev().copied().collect())),
        ..Connect::default()
    };
    Pipe::connect(store, connect).unwrap()
}

#[test]
fn a_store_the_program_holds_answers_its_servers_calls() {
    let dir = tempfile::tempdir().unwrap();
    let store = Store::open(dir.path(), Options::default()).unwrap();
    let stops = Arc::new(AtomicUsize::new(0));
    let mut client = Client::over(served(&store, &stops));
    let challenge: Vec<u8> = (0..16).collect();
    let welcome = client.greet(Hello { protocol: 1, challenge: Some(challenge.clone()), ..Hello::default() }).unwrap();
    assert_eq!(welcome.proof, Some(challenge.iter().rev().copied().collect()), "the proof answers the challenge");

    let read: ServerClock = client.call(method::SERVER_CLOCK, &ServerClock::default()).unwrap();
    assert_eq!(read.at, Some(1_790_000_000_000));
    let moved: ServerClock = client.call(method::SERVER_CLOCK, &ServerClock { advance: Some(1500), at: None }).unwrap();
    assert_eq!(moved.at, Some(1_790_000_001_500));
    let back = ServerClock { at: Some(1_000), advance: None };
    assert_eq!(client.call::<ServerClock>(method::SERVER_CLOCK, &back).unwrap_err().code, "invalid", "never back");

    client.call::<Empty>(method::SERVER_STOP, &Empty {}).unwrap();
    assert_eq!(stops.load(Ordering::SeqCst), 1, "the stop runs once its answer has left");
    drop(client);
    store.close().unwrap();
}

#[test]
fn an_embedded_store_refuses_to_stop_and_has_no_clock_to_move() {
    let dir = tempfile::tempdir().unwrap();
    let mut client = Client::open(dir.path());
    assert_eq!(client.call::<Empty>(method::SERVER_STOP, &Empty {}).unwrap_err().code, "permission");
    assert_eq!(client.call::<ServerClock>(method::SERVER_CLOCK, &ServerClock::default()).unwrap_err().code, "invalid");
}

/// A pipe whose options start the store on a test's clock at `at`, in Unix ms.
fn on_a_clock(dir: &std::path::Path, at: Option<i64>) -> Result<Client> {
    let options = crate::wire::protocol::StoreOptions { clock: at, ..Default::default() }.encode();
    let mut client = Client::over(Pipe::open(dir, &options, None)?);
    client.hello(1).unwrap();
    Ok(client)
}

#[test]
fn an_embedded_store_opened_on_a_clock_moves_it_for_every_pipe_and_refuses_one_without() {
    let dir = tempfile::tempdir().unwrap();
    let mut first = on_a_clock(dir.path(), Some(1_790_000_000_000)).unwrap();
    let moved: ServerClock =
        first.call(method::SERVER_CLOCK, &ServerClock { advance: Some(3_600_000), at: None }).unwrap();
    assert_eq!(moved.at, Some(1_790_003_600_000));

    let mut second = on_a_clock(dir.path(), Some(1_000)).unwrap();
    let read: ServerClock = second.call(method::SERVER_CLOCK, &ServerClock::default()).unwrap();
    assert_eq!(read.at, Some(1_790_003_600_000), "a second pipe joins the clock as it runs, not at its own start");
    let Err(without) = on_a_clock(dir.path(), None) else { panic!("a pipe without the clock joined") };
    assert_eq!(without.kind(), ErrorKind::Invalid, "{without}");
    assert!(without.to_string().contains("open on a test's clock"), "{without}");
    drop((first, second));

    let mut plain = on_a_clock(dir.path(), None).unwrap();
    let Err(with) = on_a_clock(dir.path(), Some(1_000)) else { panic!("a pipe with a clock joined") };
    assert!(with.to_string().contains("open without a test's clock"), "{with}");
    assert_eq!(plain.call::<ServerClock>(method::SERVER_CLOCK, &ServerClock::default()).unwrap_err().code, "invalid");
}

#[test]
fn reads_sent_together_are_each_answered_though_workers_take_the_crowd() {
    let dir = tempfile::tempdir().unwrap();
    let mut client = Client::open(dir.path());
    let handle = client.bucket("sessions");
    for n in 0..40 {
        let set = KvCall { handle, key: format!("k{n}"), value: Some(Row::Int(n)), ..KvCall::default() };
        client.call::<KvWritten>(method::KV_SET, &set).unwrap();
    }
    // forty gets in one write are a crowd: the workers answer them, in any order
    let mut bytes = Vec::new();
    for n in 0..40 {
        let get = KvCall { handle, key: format!("k{n}"), ..KvCall::default() };
        let frame = Frame { method: method::KV_GET, ..Frame::new(Kind::Request, 1000 + n, get.encode()) };
        frame.ending().encode_into(&mut bytes);
    }
    let ready = client.pipe.send(&bytes);
    client.reader.push(&ready);
    for n in 0..40 {
        let got: KvEntry = answered(&client.next_on(1000 + n)).unwrap();
        assert_eq!((got.found, got.value), (true, Some(Row::Int(i64::from(n)))), "k{n}");
    }
    assert_eq!(client.pipe.streams(), 0, "every stream ended once");
}

#[test]
fn a_challenge_of_another_length_is_a_hello_the_server_cannot_take() {
    let dir = tempfile::tempdir().unwrap();
    let mut client = Client::connect(dir.path());
    let refused = client.greet(Hello { protocol: 1, challenge: Some(vec![1; 8]), ..Hello::default() }).unwrap_err();
    assert_eq!(refused.code, "protocol");
}

// contract: WIRE-07
#[test]
fn a_closing_server_says_goaway_and_answers_a_later_request_unavailable_unrun() {
    let dir = tempfile::tempdir().unwrap();
    let store = Store::open(dir.path(), Options::default()).unwrap();
    let mut client = Client::over(served(&store, &Arc::new(AtomicUsize::new(0))));
    client.hello(1).unwrap();
    let handle = client.bucket("sessions");
    assert_eq!(client.pipe.streams(), 0);

    client.pipe.go_away();
    assert_eq!(client.read().kind, Kind::GoAway);
    let set = KvCall { handle, key: "k".to_owned(), value: Some(Row::Int(1)), ..KvCall::default() };
    assert_eq!(client.call::<KvWritten>(method::KV_SET, &set).unwrap_err().code, "unavailable");
    assert_eq!(client.pipe.streams(), 0, "every stream ended once");
    drop(client);

    let mut again = Client::over(served(&store, &Arc::new(AtomicUsize::new(0))));
    again.hello(1).unwrap();
    let handle = again.bucket("sessions");
    let get = KvCall { handle, key: "k".to_owned(), ..KvCall::default() };
    assert!(!again.call::<KvEntry>(method::KV_GET, &get).unwrap().found, "the refused set never ran");
    drop(again);
    store.close().unwrap();
}

#[test]
fn pipes_on_one_directory_share_its_store_until_the_last_closes() {
    let dir = tempfile::tempdir().unwrap();
    let first = Client::open(dir.path());
    let second = Client::open(dir.path());
    assert!(Store::open(dir.path(), Options::default()).is_err(), "the pipes' store holds the LOCK");
    drop(first);
    assert!(Store::open(dir.path(), Options::default()).is_err(), "one pipe still holds it");
    drop(second);
    Store::open(dir.path(), Options::default()).unwrap().close().unwrap();
}

/// Two thousand sets in flight at once through a pipe, with no host language:
/// where the time goes when the Bun numbers disappoint. Run by hand:
/// cargo test --release -p tinystore pipe::tests::sets_in_flight -- --ignored --nocapture
#[test]
#[ignore = "a timing, not a check"]
fn sets_in_flight() {
    let dir = tempfile::tempdir().unwrap();
    let mut client = Client::open(dir.path());
    let handle = client.bucket("smoke");
    for pass in 0..5 {
        let started = std::time::Instant::now();
        let mut bytes = Vec::new();
        for n in 0..2000u32 {
            let set = KvCall {
                handle,
                key: format!("p{pass}-{n}"),
                value: Some(Row::Bin(vec![b'x'; 100])),
                ..KvCall::default()
            };
            Frame { method: method::KV_SET, ..Frame::new(Kind::Request, n + 1, set.encode()) }
                .ending()
                .encode_into(&mut bytes);
        }
        client.reader.push(&client.pipe.send(&bytes));
        let mut answered = 0;
        while answered < 2000 {
            match client.reader.next(1 << 22).unwrap() {
                Some(frame) if frame.kind == Kind::Response => answered += 1,
                Some(_) => {}
                None => {
                    let ready = client.pipe.recv(Duration::from_secs(10));
                    client.reader.push(&ready);
                }
            }
        }
        let seconds = started.elapsed().as_secs_f64();
        println!("pass {pass}: {:.0} sets/s", 2000.0 / seconds);
    }
}

#[test]
fn writes_of_kv_in_flight_hold_no_thread_of_the_session() {
    let dir = tempfile::tempdir().unwrap();
    let store = Store::open(dir.path(), Options { background: false, ..Options::default() }).unwrap();
    let mut client = Client::over(Pipe::connect(&store, Connect::default()).unwrap());
    client.hello(1).unwrap();
    let sessions = client.bucket("sessions");
    let hits = KvCountersOpen { name: "hits".to_owned(), ..KvCountersOpen::default() };
    let hits = client.call::<Handle>(method::KV_COUNTERS_OPEN, &hits).unwrap().handle;
    let window = KvWindow { name: "minute".to_owned(), limit: 100, per: 60_000 };
    let uses = KvQuotaOpen { name: "uses".to_owned(), windows: vec![window] };
    let uses = client.call::<Handle>(method::KV_QUOTA_OPEN, &uses).unwrap().handle;
    let held = store.bucket::<i64>("held").open().unwrap();
    let (began, begun) = std::sync::mpsc::channel();
    let (release, released) = std::sync::mpsc::channel::<()>();

    std::thread::scope(|scope| {
        // a transaction of kv.db holds its writer, so that no write can commit
        let (store, held) = (&store, &held);
        let holding = scope.spawn(move || {
            store.tx(|tx| -> crate::Result<()> {
                tx.with(held).set("k", &1)?;
                began.send(()).unwrap();
                released.recv().unwrap();
                Ok(())
            })
        });
        begun.recv().unwrap();
        let key = |handle, n: usize| KvCall { handle, key: format!("k{n}"), ..KvCall::default() };
        let adds: Vec<u32> = (0..20).map(|n| client.start(method::KV_COUNTERS_ADD, &key(hits, n))).collect();
        let allows: Vec<u32> = (0..10).map(|n| client.start(method::KV_ALLOW, &key(uses, n))).collect();
        let txs: Vec<u32> = (0..10)
            .map(|n| {
                let set = KvCall { value: Some(Row::Int(1)), ..key(sessions, n) };
                let writes = vec![KvOp { method: u64::from(method::KV_SET), call: set }];
                client.start(method::KV_TX, &KvTx { checks: Vec::new(), writes })
            })
            .collect();
        let clear = client.start(method::KV_CLEAR, &KvBranch { handle: sessions, under: vec!["gone".to_owned()] });
        // more writes wait than the session has threads, and a call that needs one is still answered
        let page: KvPage = client.call(method::KV_LIST, &KvList { handle: sessions, ..KvList::default() }).unwrap();
        assert!(page.entries.is_empty(), "nothing is committed yet");
        release.send(()).unwrap();
        holding.join().unwrap().unwrap();
        for stream in adds {
            assert_eq!(answered::<KvCount>(&client.next_on(stream)).unwrap().value, 1);
        }
        for stream in allows {
            assert!(answered::<KvAllowance>(&client.next_on(stream)).unwrap().ok);
        }
        for stream in txs {
            assert_eq!(answered::<KvTxResults>(&client.next_on(stream)).unwrap().outcomes.len(), 1);
        }
        answered::<Empty>(&client.next_on(clear)).unwrap();
    });
    assert_eq!(client.pipe.streams(), 0, "every stream ended once");
    drop(client);
    store.close().unwrap();
}

/// A host frees its wake once the pipe closes, as Bun frees its callback: a
/// wake that a commit's thread is making when the session ends has returned
/// by the time the end does, and none comes after.
#[test]
fn a_pipe_closed_while_a_commit_wakes_its_host_returns_once_that_wake_has() {
    use std::sync::Arc;
    use std::sync::atomic::AtomicBool;
    let dir = tempfile::tempdir().unwrap();
    let store = Store::open(dir.path(), Options { background: false, ..Options::default() }).unwrap();
    let (armed, returned) = (Arc::new(AtomicBool::new(false)), Arc::new(AtomicBool::new(false)));
    let (waking, woken) = std::sync::mpsc::channel();
    let wake: Wake = {
        let (armed, returned) = (Arc::clone(&armed), Arc::clone(&returned));
        let waking = std::sync::Mutex::new(waking);
        Arc::new(move || {
            if armed.load(Ordering::SeqCst) {
                let _ = waking.lock().unwrap().send(std::thread::current().id());
                std::thread::sleep(std::time::Duration::from_millis(200));
                returned.store(true, Ordering::SeqCst);
            }
        })
    };
    let pipe = Pipe::connect(&store, Connect { wake: Some(wake), ..Connect::default() }).unwrap();
    let mut client = Client::over(pipe);
    client.hello(1).unwrap();
    let handle = client.bucket("sessions");
    client.pipe.recv(std::time::Duration::ZERO);

    armed.store(true, Ordering::SeqCst);
    let set = KvCall { handle, key: "k".to_owned(), value: Some(Row::Int(1)), ..KvCall::default() };
    let mut request = Vec::new();
    Frame { method: method::KV_SET, ..Frame::new(Kind::Request, 99, set.encode()) }.ending().encode_into(&mut request);
    client.pipe.push(&request);
    let waker = woken.recv().unwrap();
    assert_ne!(waker, std::thread::current().id(), "the commit's thread wakes the host");
    client.pipe.session.end();
    assert!(returned.load(Ordering::SeqCst), "the session ended while its host was being woken");
    drop(client);
    store.close().unwrap();
}

#[test]
fn a_host_reading_into_its_own_bytes_gets_the_stream_in_order_and_a_wake_for_what_became_ready() {
    let dir = tempfile::tempdir().unwrap();
    let store = Store::open(dir.path(), Options { background: false, ..Options::default() }).unwrap();
    let wakes = std::sync::Arc::new(AtomicUsize::new(0));
    let counted = std::sync::Arc::clone(&wakes);
    let wake: Wake = std::sync::Arc::new(move || {
        counted.fetch_add(1, Ordering::SeqCst);
    });
    let pipe = Pipe::connect(&store, Connect { wake: Some(wake), ..Connect::default() }).unwrap();
    let mut hello = Vec::new();
    let said = Hello { protocol: 1, client: "test/0".to_owned(), ..Hello::default() };
    Frame::new(Kind::Hello, 0, said.encode()).encode_into(&mut hello);

    // given no room, a send leaves the WELCOME to the read, and the host is woken for it
    assert_eq!(pipe.send_into(&hello, &mut []), 0);
    assert_eq!(wakes.load(Ordering::SeqCst), 1);

    // five bytes at a time: a read that fills its room says more may wait, and no wake does
    let (mut welcome, mut piece) = (Vec::new(), [0u8; 5]);
    loop {
        let read = pipe.recv_into(std::time::Duration::ZERO, &mut piece);
        welcome.extend_from_slice(&piece[..read]);
        if read < piece.len() {
            break;
        }
    }
    assert_eq!(wakes.load(Ordering::SeqCst), 1, "what a read left wakes nobody");
    let mut reader = frame::Reader::default();
    reader.push(&welcome);
    assert_eq!(reader.next(1 << 16).unwrap().expect("the frame came whole").kind, Kind::Welcome);

    // read to its end, the stream wakes the host for the next frame
    let mut ping = Vec::new();
    Frame::new(Kind::Ping, 0, vec![7; 8]).encode_into(&mut ping);
    assert_eq!(pipe.send_into(&ping, &mut []), 0);
    assert_eq!(wakes.load(Ordering::SeqCst), 2);
    let mut pong = [0u8; 64];
    assert_eq!(pipe.recv_into(std::time::Duration::ZERO, &mut pong), 20, "a PONG, whole");
    drop(pipe);
    store.close().unwrap();
}

#[test]
fn a_pipes_store_holds_the_series_its_options_say_and_a_pipe_that_joins_it_asks_for_the_same_or_nothing() {
    use crate::wire::protocol::StoreOptions;

    let asking = |most: u64| StoreOptions { max_series: Some(most), ..StoreOptions::default() }.encode();
    let dir = tempfile::tempdir().unwrap();
    let first = Pipe::open(dir.path(), &asking(500_000), None).unwrap();
    let (same, unasked) = (Pipe::open(dir.path(), &asking(500_000), None).unwrap(), Pipe::open(dir.path(), &[], None));
    let refused = Pipe::open(dir.path(), &asking(7), None).unwrap_err();
    assert_eq!(
        refused.to_string(),
        "pipe: the store is open with max_series 500000, and asked for 7: open it with 500000 or without max_series: \
         invalid"
    );
    drop((first, same, unasked));
}

#[test]
fn a_pipes_store_opens_as_its_options_say_and_a_pipe_that_joins_it_asks_for_the_same_or_nothing() {
    use crate::wire::protocol::StoreOptions;

    let asking = |word: &str| StoreOptions { durability: Some(word.to_owned()), ..StoreOptions::default() }.encode();
    let dir = tempfile::tempdir().unwrap();
    let mut first = Client::over(Pipe::open(dir.path(), &asking("os"), None).unwrap());
    assert_eq!(first.hello(1).unwrap().durability.as_deref(), Some("os"), "the WELCOME says what the store has");

    let unasked = Pipe::open(dir.path(), &[], None).unwrap();
    let same = Pipe::open(dir.path(), &asking("os"), None).unwrap();
    let refused = Pipe::open(dir.path(), &asking("full"), None).unwrap_err();
    assert_eq!(
        refused.to_string(),
        "pipe: the store is open with durability os, and asked for full: open it with os or without durability: invalid"
    );
    drop((first, unasked, same));

    // a store opened with nothing said keeps each engine's own, which a pipe asking for one is not given
    let dir = tempfile::tempdir().unwrap();
    let mut plain = Client::over(Pipe::open(dir.path(), &[], None).unwrap());
    assert_eq!(plain.hello(1).unwrap().durability, None);
    let refused = Pipe::open(dir.path(), &asking("full"), None).unwrap_err();
    assert_eq!(
        refused.to_string(),
        "pipe: the store is open with no durability set, full but os for records and metrics, and asked for full: \
         open it without durability: invalid"
    );
    let unknown = Pipe::open(tempfile::tempdir().unwrap().path(), &asking("fast"), None).unwrap_err();
    assert_eq!(unknown.to_string(), "pipe: durability \"fast\": it is full or os: invalid");
}

// contract: SEC-01
#[test]
fn a_read_connection_reads_and_writes_nothing() {
    let dir = tempfile::tempdir().unwrap();
    let store = crate::Store::open(dir.path(), crate::Options::default()).unwrap();
    let mut owner = Client::admitted(&store, Capability::Data);
    let handle = owner.bucket("sessions");
    let key = KvCall { handle, key: "42".to_owned(), ..KvCall::default() };
    let kept = KvCall { value: Some(Row::Bin(b"kept".to_vec())), ..key.clone() };
    owner.call::<KvWritten>(method::KV_SET, &kept).unwrap();

    let mut reader = Client::admitted(&store, Capability::Read);
    let handle = reader.bucket("sessions");
    let entry: KvEntry = reader.call(method::KV_GET, &KvCall { handle, ..key.clone() }).unwrap();
    assert_eq!(entry.value, Some(Row::Bin(b"kept".to_vec())));
    let changed = KvCall { handle, value: Some(Row::Bin(b"changed".to_vec())), ..key };
    let refused = reader.call::<KvWritten>(method::KV_SET, &changed).unwrap_err();
    assert_eq!(refused.code, "permission", "{}", refused.message);
    let refused = reader.call::<Empty>(method::SERVER_STOP, &Empty {}).unwrap_err();
    assert_eq!(refused.code, "permission", "{}", refused.message);
    let entry: KvEntry = owner.call(method::KV_GET, &KvCall { handle: 1, ..changed }).unwrap();
    assert_eq!(entry.value, Some(Row::Bin(b"kept".to_vec())));
}

/// What a bucket's reads renew and how counters count are the writers' to
/// choose: a read connection that chose them would write through its reads,
/// or bind the application's own opens.
// contract: SEC-01
#[test]
fn a_read_connection_gives_a_bucket_no_idle_and_counters_no_flush() {
    use crate::wire::protocol::KvBucketOpen;
    let dir = tempfile::tempdir().unwrap();
    let store = crate::Store::open(dir.path(), crate::Options::default()).unwrap();
    let mut owner = Client::admitted(&store, Capability::Data);
    let handle = owner.bucket("sessions");
    let hour = 3_600_000;
    let session =
        KvCall { handle, key: "s1".to_owned(), value: Some(Row::Int(1)), ttl: Some(hour), ..KvCall::default() };
    let expires = owner.call::<KvWritten>(method::KV_SET, &session).unwrap().expires_at;

    let mut reader = Client::admitted(&store, Capability::Read);
    let idle =
        KvBucketOpen { name: "sessions".to_owned(), idle: Some(100 * 365 * 24 * hour), ..KvBucketOpen::default() };
    let refused = reader.call::<Handle>(method::KV_BUCKET_OPEN, &idle).unwrap_err();
    assert_eq!(refused.code, "permission", "{}", refused.message);
    let flushed = KvCountersOpen { name: "visits".to_owned(), flush_every: Some(hour), ..KvCountersOpen::default() };
    let refused = reader.call::<Handle>(method::KV_COUNTERS_OPEN, &flushed).unwrap_err();
    assert_eq!(refused.code, "permission", "{}", refused.message);

    let read = reader.bucket("sessions");
    let entry: KvEntry = reader.call(method::KV_GET, &KvCall { handle: read, ..session.clone() }).unwrap();
    assert_eq!(entry.expires_at, expires, "a read connection's read renews nothing");
}

/// Each engine's open a read connection may call, of names no store here
/// holds, by what it opens.
#[cfg(all(feature = "jobs", feature = "sql", feature = "blobs", feature = "records", feature = "search"))]
fn open_names_not_held(client: &mut Client) -> Vec<(&'static str, Result<Handle, Failed>)> {
    use crate::wire::protocol::{
        BlobsOpen, JobsQueueOpen, KvBucketOpen, KvRateLimitOpen, RecordsOpen, SearchOpen, SqlOpen,
    };
    let window = KvWindow { name: "daily".to_owned(), limit: 100, per: 86_400_000 };
    let queue = |name: &str| JobsQueueOpen { name: name.to_owned(), ..JobsQueueOpen::default() };
    let bucket = KvBucketOpen { name: "sessions".to_owned(), ..KvBucketOpen::default() };
    let counters = KvCountersOpen { name: "visits".to_owned(), ..KvCountersOpen::default() };
    let limit = KvRateLimitOpen { name: "api".to_owned(), rate: 10, per: 1_000, burst: None };
    let quota = KvQuotaOpen { name: "ai".to_owned(), windows: vec![window] };
    let once = KvOnceOpen { name: "payments".to_owned(), ..KvOnceOpen::default() };
    let files = BlobsOpen { name: "avatars".to_owned(), ..BlobsOpen::default() };
    let stream = RecordsOpen { stream: "audit".to_owned(), ..RecordsOpen::default() };
    let index = SearchOpen { name: "products".to_owned(), ..SearchOpen::default() };
    let database = SqlOpen { name: "app".to_owned(), migrations: None, durability: None, backup: None };
    vec![
        ("bucket sessions", client.call::<Handle>(method::KV_BUCKET_OPEN, &bucket)),
        ("counters visits", client.call::<Handle>(method::KV_COUNTERS_OPEN, &counters)),
        ("rate limit api", client.call::<Handle>(method::KV_RATE_LIMIT_OPEN, &limit)),
        ("quota ai", client.call::<Handle>(method::KV_QUOTA_OPEN, &quota)),
        ("once payments", client.call::<Handle>(method::KV_ONCE_OPEN, &once)),
        ("queue emails", client.call::<Handle>(method::JOBS_QUEUE_OPEN, &queue("emails"))),
        ("queue reports", client.call::<Handle>(method::JOBS_QUEUE_OPEN, &queue("reports"))),
        ("files avatars", client.call::<Handle>(method::BLOBS_OPEN, &files)),
        ("stream audit", client.call::<Handle>(method::RECORDS_OPEN, &stream)),
        ("index products", client.call::<Handle>(method::SEARCH_OPEN, &index)),
        ("database app", client.call::<Handle>(method::SQL_OPEN, &database)),
    ]
}

/// The program's own opens of the names [`open_names_not_held`] asks for:
/// each kv name as another kind, a queue with options of its own and the
/// other as a schedule, and a stream and a database with what they keep.
#[cfg(all(feature = "jobs", feature = "sql", feature = "blobs", feature = "records", feature = "search"))]
fn open_as_the_program(store: &Store) {
    let day = std::time::Duration::from_secs(86_400);
    store.counters("sessions").open().unwrap();
    store.bucket::<i64>("visits").open().unwrap();
    store.quota("api").window("daily", 100, day).open().unwrap();
    store.rate_limit("ai").rate(10, std::time::Duration::from_secs(1)).open().unwrap();
    store.counters("payments").open().unwrap();
    let bound = crate::jobs::Concurrency::total(4).group(2);
    store.queue::<i64>("emails").attempts(3).concurrency(bound).open().unwrap();
    store.schedule("reports").every(day).open().unwrap();
    store.files("avatars").open().unwrap();
    store.events("audit").keep(day * 7).open().unwrap();
    store.index::<serde_json::Value>("products").field("title", 1.0).open().unwrap();
    store.database("app").durability(crate::Durability::Os).open().unwrap();
}

/// Every file and folder under `dir`, by its path there.
#[cfg(all(feature = "jobs", feature = "sql", feature = "blobs", feature = "records", feature = "search"))]
fn entries(dir: &std::path::Path) -> Vec<std::path::PathBuf> {
    let (mut found, mut folders) = (Vec::new(), vec![dir.to_path_buf()]);
    while let Some(folder) = folders.pop() {
        for entry in std::fs::read_dir(&folder).unwrap() {
            let path = entry.unwrap().path();
            if path.is_dir() {
                folders.push(path.clone());
            }
            found.push(path.strip_prefix(dir).unwrap().to_path_buf());
        }
    }
    found.sort();
    found
}

/// A read connection's opens of names a store never held are refused as a
/// guest's are, `not_found`, and make nothing: no file, no folder, and no
/// name or option the program's own opens then meet.
// contract: SEC-01
#[cfg(all(feature = "jobs", feature = "sql", feature = "blobs", feature = "records", feature = "search"))]
#[test]
fn a_read_connection_opens_nothing_of_a_store_that_holds_none_of_it() {
    let dir = tempfile::tempdir().unwrap();
    let store = Store::open(dir.path(), Options { background: false, ..Options::default() }).unwrap();
    let mut reader = Client::admitted(&store, Capability::Read);
    let before = entries(dir.path());
    for (what, opened) in open_names_not_held(&mut reader) {
        let refused = opened.unwrap_err();
        assert_eq!(refused.code, "not_found", "{what}: {}", refused.message);
    }
    assert_eq!(entries(dir.path()), before, "no file and no folder");
    open_as_the_program(&store);
}

/// Where each engine's file holds other names, a read connection's open of
/// one it does not hold is refused, `invalid` as search's is, and leaves no
/// row: the same open again is refused too, and the program's own opens of
/// those names as other kinds, or with options of their own, all open.
// contract: SEC-01
#[cfg(all(feature = "jobs", feature = "sql", feature = "blobs", feature = "records", feature = "search"))]
#[test]
fn a_read_connection_makes_no_name_its_store_does_not_hold() {
    let dir = tempfile::tempdir().unwrap();
    let store = Store::open(dir.path(), Options { background: false, ..Options::default() }).unwrap();
    store.bucket::<i64>("other").open().unwrap();
    store.queue::<i64>("other").open().unwrap();
    store.files("other").open().unwrap();
    store.events("other").open().unwrap();
    store.index::<serde_json::Value>("other").field("title", 1.0).open().unwrap();
    let mut reader = Client::admitted(&store, Capability::Read);
    for _ in 0..2 {
        for (what, opened) in open_names_not_held(&mut reader) {
            // a database's name is its file
            let code = if what == "database app" { "not_found" } else { "invalid" };
            let refused = opened.unwrap_err();
            assert_eq!(refused.code, code, "{what}: {}", refused.message);
        }
    }
    open_as_the_program(&store);
}

/// A read connection opens what its store holds as it is, whatever options
/// it asks, and reads it; it binds nothing the program's own opens meet after
/// it, though it opened each engine first.
// contract: SEC-01
#[cfg(all(feature = "jobs", feature = "sql", feature = "blobs", feature = "records", feature = "search"))]
#[test]
fn a_read_connection_opens_what_its_store_holds_as_it_is_and_binds_none_of_it() {
    use crate::wire::protocol::{
        BlobsAt, BlobsGot, BlobsOpen, BlobsWrite, BlobsWritten, JobsCall, JobsId, JobsJob, JobsQueueOpen, KvBucketOpen,
        RecordsAppend, RecordsCount, RecordsNewEvent, RecordsOpen, RecordsQuery, SqlDone, SqlMigration, SqlOpen,
        SqlQuery, SqlRows, SqlStatement,
    };
    let dir = tempfile::tempdir().unwrap();
    let options = || Options { background: false, ..Options::default() };
    let bucket = KvBucketOpen { name: "sessions".to_owned(), ..KvBucketOpen::default() };
    let counters = KvCountersOpen { name: "hits".to_owned(), ..KvCountersOpen::default() };
    let queue = JobsQueueOpen { name: "emails".to_owned(), ..JobsQueueOpen::default() };
    let files = BlobsOpen { name: "avatars".to_owned(), ..BlobsOpen::default() };
    let stream = RecordsOpen { stream: "audit".to_owned(), ..RecordsOpen::default() };
    let notes =
        SqlMigration { name: "0001_notes.sql".to_owned(), sql: "create table notes (title text) strict".to_owned() };
    let database = SqlOpen { name: "app".to_owned(), migrations: Some(vec![notes]), durability: None, backup: None };
    {
        let store = Store::open(dir.path(), options()).unwrap();
        let mut owner = Client::admitted(&store, Capability::Data);
        let handle = owner.call::<Handle>(method::KV_BUCKET_OPEN, &bucket).unwrap().handle;
        let set = KvCall { handle, key: "s1".to_owned(), value: Some(Row::Bin(b"kept".to_vec())), ..KvCall::default() };
        owner.call::<KvWritten>(method::KV_SET, &set).unwrap();
        let handle = owner.call::<Handle>(method::KV_COUNTERS_OPEN, &counters).unwrap().handle;
        let add = KvCall { handle, key: "home".to_owned(), n: Some(3), ..KvCall::default() };
        owner.call::<KvCount>(method::KV_COUNTERS_ADD, &add).unwrap();
        let handle = owner.call::<Handle>(method::JOBS_QUEUE_OPEN, &queue).unwrap().handle;
        let job = JobsCall { handle, id: Some("e1".to_owned()), value: "1".to_owned(), ..JobsCall::default() };
        owner.call::<Empty>(method::JOBS_SET, &job).unwrap();
        let handle = owner.call::<Handle>(method::BLOBS_OPEN, &files).unwrap().handle;
        let put = BlobsWrite { handle, path: "a.png".to_owned(), bytes: b"png".to_vec(), ..BlobsWrite::default() };
        owner.call::<BlobsWritten>(method::BLOBS_PUT, &put).unwrap();
        let handle = owner.call::<Handle>(method::RECORDS_OPEN, &stream).unwrap().handle;
        let signup = RecordsNewEvent { name: "signup".to_owned(), ..RecordsNewEvent::default() };
        owner.call::<Empty>(method::RECORDS_APPEND, &RecordsAppend { handle, events: vec![signup] }).unwrap();
        let handle = owner.call::<Handle>(method::SQL_OPEN, &database).unwrap().handle;
        let insert = SqlStatement { handle, text: "insert into notes values ('kept')".to_owned(), values: Vec::new() };
        owner.call::<SqlDone>(method::SQL_EXEC, &insert).unwrap();
        drop(owner);
        store.close().unwrap();
    }

    let store = Store::open(dir.path(), options()).unwrap();
    let mut reader = Client::admitted(&store, Capability::Read);
    let asked = JobsQueueOpen { attempts: Some(5), ..queue };
    let emails = reader.call::<Handle>(method::JOBS_QUEUE_OPEN, &asked).unwrap().handle;
    let e1 = JobsId { handle: emails, id: "e1".to_owned(), row: None };
    assert!(reader.call::<JobsJob>(method::JOBS_GET, &e1).unwrap().found, "the job the program set");
    let handle = reader.call::<Handle>(method::KV_BUCKET_OPEN, &bucket).unwrap().handle;
    let entry: KvEntry =
        reader.call(method::KV_GET, &KvCall { handle, key: "s1".to_owned(), ..KvCall::default() }).unwrap();
    assert_eq!(entry.value, Some(Row::Bin(b"kept".to_vec())));
    let handle = reader.call::<Handle>(method::KV_COUNTERS_OPEN, &counters).unwrap().handle;
    let home = KvCall { handle, key: "home".to_owned(), ..KvCall::default() };
    assert_eq!(reader.call::<KvCount>(method::KV_COUNTERS_GET, &home).unwrap().value, 3);
    let handle = reader.call::<Handle>(method::BLOBS_OPEN, &files).unwrap().handle;
    let at = BlobsAt { handle, folder: Vec::new(), path: "a.png".to_owned() };
    assert_eq!(reader.call::<BlobsGot>(method::BLOBS_GET, &at).unwrap().bytes, b"png");
    let handle = reader.call::<Handle>(method::RECORDS_OPEN, &stream).unwrap().handle;
    let audit = RecordsQuery { handle: Some(handle), ..RecordsQuery::default() };
    assert_eq!(reader.call::<RecordsCount>(method::RECORDS_COUNT, &audit).unwrap().count, 1);
    let handle = reader.call::<Handle>(method::SQL_OPEN, &database).unwrap().handle;
    let titles = SqlQuery {
        handle,
        text: "select title from notes".to_owned(),
        values: Vec::new(),
        want: "all".to_owned(),
        order: None,
    };
    assert_eq!(reader.call::<SqlRows>(method::SQL_QUERY, &titles).unwrap().rows.len(), 1);

    store.counters("hits").flush_every(std::time::Duration::from_secs(1)).open().unwrap();
    store.queue::<i64>("emails").attempts(3).open().unwrap();
    store.database("app").durability(crate::Durability::Os).open().unwrap();
    let again = reader.call::<Handle>(method::JOBS_QUEUE_OPEN, &asked).unwrap().handle;
    let e1 = JobsId { handle: again, id: "e1".to_owned(), row: None };
    assert!(reader.call::<JobsJob>(method::JOBS_GET, &e1).unwrap().found, "the queue as the program opened it");
    assert_eq!(reader.call::<SqlRows>(method::SQL_QUERY, &titles).unwrap().rows.len(), 1, "beside the program's");
}

/// What a read connection's reads that name no handle read is every stream,
/// the metrics, the indexes and a config's changes the store holds: on a
/// store that holds none, each is refused as an open of the same file is,
/// `not_found`, and makes nothing.
// contract: SEC-01
#[cfg(all(
    feature = "jobs",
    feature = "sql",
    feature = "blobs",
    feature = "records",
    feature = "search",
    feature = "metrics",
    feature = "config"
))]
#[test]
fn a_read_connection_reads_nothing_into_a_store_that_holds_none_of_it() {
    use crate::wire::protocol::{
        ConfigOpen, MetricsPageAsked, MetricsQuery, RecordsFieldsAsked, RecordsPollAsked, RecordsQuery,
    };
    let dir = tempfile::tempdir().unwrap();
    let store = Store::open(dir.path(), Options { background: false, ..Options::default() }).unwrap();
    let mut reader = Client::admitted(&store, Capability::Read);
    let before = entries(dir.path());
    let fields = RecordsFieldsAsked { stream: "audit".to_owned() };
    let config = ConfigOpen {
        name: "app".to_owned(),
        declaration: "{}".to_owned(),
        layers: "[]".to_owned(),
        ..ConfigOpen::default()
    };
    let read = [
        ("records.streams", reader.call::<Empty>(method::RECORDS_STREAMS, &Empty {})),
        ("records.list", reader.call::<Empty>(method::RECORDS_LIST, &RecordsQuery::default())),
        ("records.count", reader.call::<Empty>(method::RECORDS_COUNT, &RecordsQuery::default())),
        ("records.tail", reader.call::<Empty>(method::RECORDS_TAIL, &RecordsQuery::default())),
        ("records.poll", reader.call::<Empty>(method::RECORDS_POLL, &RecordsPollAsked::default())),
        ("records.damaged", reader.call::<Empty>(method::RECORDS_DAMAGED, &Empty {})),
        ("records.fields", reader.call::<Empty>(method::RECORDS_FIELDS, &fields)),
        ("metrics.names", reader.call::<Empty>(method::METRICS_NAMES, &MetricsPageAsked::default())),
        ("metrics.read", reader.call::<Empty>(method::METRICS_READ, &MetricsQuery::default())),
        ("metrics.damaged", reader.call::<Empty>(method::METRICS_DAMAGED, &Empty {})),
        ("search.list", reader.call::<Empty>(method::SEARCH_LIST, &Empty {})),
        ("config.open", reader.call::<Empty>(method::CONFIG_OPEN, &config)),
    ];
    for (what, answered) in read {
        let refused = answered.unwrap_err();
        assert_eq!(refused.code, "not_found", "{what}: {}", refused.message);
        assert!(refused.message.contains(": it holds no "), "{what}: {}", refused.message);
    }
    assert_eq!(entries(dir.path()), before, "no file and no folder");
}

/// A read connection's open of a bucket, a queue, files, a table's index or
/// a stream through a database whose file keeps none of them makes no
/// engine's tables in it: each is refused as a name the store lacks, and a
/// stream, the store's, as records.db the store lacks.
// contract: SEC-01
#[cfg(all(feature = "jobs", feature = "sql", feature = "blobs", feature = "records", feature = "search"))]
#[test]
fn a_read_connection_makes_no_engines_tables_in_a_databases_file() {
    use crate::wire::codec::Cell;
    use crate::wire::protocol::{
        BlobsOpen, JobsQueueOpen, KvBucketOpen, RecordsOpen, SearchOpen, SqlMigration, SqlOpen, SqlQuery, SqlRows,
    };
    let dir = tempfile::tempdir().unwrap();
    let store = Store::open(dir.path(), Options { background: false, ..Options::default() }).unwrap();
    let notes = "create table notes (id text primary key, title text) strict".to_owned();
    let notes = SqlMigration { name: "0001_notes.sql".to_owned(), sql: notes };
    let database = SqlOpen { name: "app".to_owned(), migrations: Some(vec![notes]), durability: None, backup: None };
    Client::admitted(&store, Capability::Data).call::<Handle>(method::SQL_OPEN, &database).unwrap();
    let mut reader = Client::admitted(&store, Capability::Read);
    let app = reader.call::<Handle>(method::SQL_OPEN, &database).unwrap().handle;
    let bucket = KvBucketOpen { name: "sessions".to_owned(), database: Some(app), ..KvBucketOpen::default() };
    let queue = JobsQueueOpen { name: "emails".to_owned(), database: Some(app), ..JobsQueueOpen::default() };
    let files = BlobsOpen { name: "avatars".to_owned(), database: Some(app), ..BlobsOpen::default() };
    let table = Some("notes".to_owned());
    let index = SearchOpen { name: "notes".to_owned(), database: Some(app), table, ..SearchOpen::default() };
    let stream = RecordsOpen { stream: "audit".to_owned(), database: Some(app), ..RecordsOpen::default() };
    let opened = [
        ("bucket sessions", reader.call::<Handle>(method::KV_BUCKET_OPEN, &bucket), "invalid"),
        ("queue emails", reader.call::<Handle>(method::JOBS_QUEUE_OPEN, &queue), "invalid"),
        ("files avatars", reader.call::<Handle>(method::BLOBS_OPEN, &files), "invalid"),
        ("index notes", reader.call::<Handle>(method::SEARCH_OPEN, &index), "invalid"),
        ("stream audit", reader.call::<Handle>(method::RECORDS_OPEN, &stream), "not_found"),
    ];
    for (what, opened, code) in opened {
        let refused = opened.unwrap_err();
        assert_eq!(refused.code, code, "{what}: {}", refused.message);
    }
    let text = "select count(*) from sqlite_schema where substr(name, 1, 11) = '_tinystore_' \
                and name <> '_tinystore_migrations'";
    let tables =
        SqlQuery { handle: app, text: text.to_owned(), values: Vec::new(), want: "all".to_owned(), order: None };
    assert_eq!(reader.call::<SqlRows>(method::SQL_QUERY, &tables).unwrap().rows, vec![vec![Cell::Int(0)]]);
}

/// A read connection's open may be the first of jobs in its process: the
/// lease a process that died left stays as it is, its attempt not counted,
/// until the program's own open gives it back.
// contract: SEC-01
#[cfg(feature = "jobs")]
#[test]
fn a_read_connection_gives_back_no_lease_a_process_that_died_held() {
    use crate::wire::protocol::{JobsId, JobsJob, JobsQueueOpen};
    let dir = tempfile::tempdir().unwrap();
    let options = || Options { background: false, ..Options::default() };
    {
        let store = Store::open(dir.path(), options()).unwrap();
        let emails = store.queue::<i64>("emails").open().unwrap();
        emails.set("e1", &1).unwrap();
        let claimed = emails.claim().unwrap();
        assert!(claimed.is_some(), "the job is due at once");
        drop((claimed, emails)); // its lease stays, as a process that died leaves it
        store.close().unwrap();
    }
    let store = Store::open(dir.path(), options()).unwrap();
    let mut reader = Client::admitted(&store, Capability::Read);
    let open = JobsQueueOpen { name: "emails".to_owned(), ..JobsQueueOpen::default() };
    let handle = reader.call::<Handle>(method::JOBS_QUEUE_OPEN, &open).unwrap().handle;
    let e1 = JobsId { handle, id: "e1".to_owned(), row: None };
    assert_eq!(reader.call::<JobsJob>(method::JOBS_GET, &e1).unwrap().attempt, 0, "the lease as it was left");
    store.queue::<i64>("emails").open().unwrap();
    assert_eq!(reader.call::<JobsJob>(method::JOBS_GET, &e1).unwrap().attempt, 1, "given back by the program's open");
}

/// A take commits before its answer is sized: one past the agreed body says
/// the write ran, where `limit` would have the client send it again and find
/// the key gone.
#[test]
fn a_write_whose_answer_is_past_the_agreed_body_is_outcome_unknown_and_stands() {
    let dir = tempfile::tempdir().unwrap();
    let store = Store::open(dir.path(), Options { background: false, ..Options::default() }).unwrap();
    let mut client = Client::over(Pipe::connect(&store, Connect::default()).unwrap());
    let hello = Hello { protocol: 1, stream_credit: Some(64 << 10), ..Hello::default() };
    assert_eq!(client.greet(hello).unwrap().max_body, 64 << 10);
    let first = client.bucket("sessions");
    let mut written = Client::over(Pipe::connect(&store, Connect::default()).unwrap());
    written.hello(1).unwrap();
    let handle = written.bucket("sessions");
    let long =
        KvCall { handle, key: "long".to_owned(), value: Some(Row::Bin(vec![7; 100 << 10])), ..KvCall::default() };
    written.call::<KvWritten>(method::KV_SET, &long).unwrap();

    let take = KvCall { handle: first, key: "long".to_owned(), ..KvCall::default() };
    let failed = client.call::<KvEntry>(method::KV_TAKE, &take).unwrap_err();
    assert_eq!(failed.code, "outcome_unknown", "{}", failed.message);
    let has = client.call::<crate::wire::protocol::KvFound>(method::KV_HAS, &take).unwrap();
    assert!(!has.found, "the take stands");
    drop((client, written));
    store.close().unwrap();
}

#[test]
fn an_encrypted_bucket_opens_for_a_connection_that_writes_and_for_none_that_only_reads() {
    use crate::wire::protocol::KvBucketOpen;

    let dir = tempfile::tempdir().unwrap();
    let store = crate::Store::open(dir.path(), crate::Options::default()).unwrap();
    let encrypted = KvBucketOpen { name: "passwords".to_owned(), encrypted: true, ..KvBucketOpen::default() };
    let mut owner = Client::admitted(&store, Capability::Data);
    let handle = owner.call::<Handle>(method::KV_BUCKET_OPEN, &encrypted).unwrap().handle;
    let key = KvCall { handle, key: "source-42".to_owned(), ..KvCall::default() };
    let password = Row::Bin(b"hunter2-the-password".to_vec());
    owner.call::<KvWritten>(method::KV_SET, &KvCall { value: Some(password.clone()), ..key.clone() }).unwrap();
    assert_eq!(owner.call::<KvEntry>(method::KV_GET, &key).unwrap().value, Some(password.clone()));
    assert_eq!(owner.call::<KvEntry>(method::KV_TAKE, &key).unwrap().value, Some(password));

    let mut reader = Client::admitted(&store, Capability::Read);
    let refused = reader.call::<Handle>(method::KV_BUCKET_OPEN, &encrypted).unwrap_err();
    assert_eq!(refused.code, "permission", "{}", refused.message);
    // nor as a bucket that is not: the name keeps that its values are sealed
    let plain = KvBucketOpen { encrypted: false, ..encrypted };
    let refused = reader.call::<Handle>(method::KV_BUCKET_OPEN, &plain).unwrap_err();
    assert_eq!(refused.code, "invalid", "{}", refused.message);
}

#[test]
fn a_pipes_store_reads_its_encryption_key_from_the_file_its_options_name() {
    use crate::wire::protocol::{KvBucketOpen, StoreOptions};

    let dir = tempfile::tempdir().unwrap();
    let key = dir.path().join("tinystore.key");
    std::fs::write(&key, "5a".repeat(32)).unwrap();
    let data = dir.path().join("data");
    let named = |file: &std::path::Path| {
        StoreOptions { encryption_key_file: Some(file.display().to_string()), ..StoreOptions::default() }.encode()
    };
    let mut client = Client::over(Pipe::open(&data, &named(&key), None).unwrap());
    client.hello(1).unwrap();
    let encrypted = KvBucketOpen { name: "passwords".to_owned(), encrypted: true, ..KvBucketOpen::default() };
    client.call::<Handle>(method::KV_BUCKET_OPEN, &encrypted).unwrap();
    assert!(!data.join("encryption.key").exists(), "the store made no key of its own");

    let other = Pipe::open(&data, &named(&dir.path().join("another.key")), None).unwrap_err();
    assert!(other.to_string().contains("another encryption key file"), "{other}");
}

// contract: SEC-04
#[test]
fn a_pipes_store_opens_with_its_older_keys_and_reseals_what_they_sealed() {
    use crate::wire::protocol::{KvBranch, KvBucketOpen, KvResealed, StoreOptions};

    let dir = tempfile::tempdir().unwrap();
    let (old, new) = (dir.path().join("old.key"), dir.path().join("new.key"));
    std::fs::write(&old, "1a".repeat(32)).unwrap();
    std::fs::write(&new, "2b".repeat(32)).unwrap();
    let data = dir.path().join("data");
    let before = Store::open(&data, Options { encryption_key_file: Some(old.clone()), ..Options::default() }).unwrap();
    before.bucket::<String>("passwords").encrypted().open().unwrap().set("db", &"hunter2".to_owned()).unwrap();
    before.close().unwrap();

    let options = StoreOptions {
        encryption_key_file: Some(new.display().to_string()),
        older_encryption_keys: vec![old.display().to_string()],
        ..StoreOptions::default()
    };
    let mut client = Client::over(Pipe::open(&data, &options.encode(), None).unwrap());
    client.hello(1).unwrap();
    let encrypted = KvBucketOpen { name: "passwords".to_owned(), encrypted: true, ..KvBucketOpen::default() };
    let handle = client.call::<Handle>(method::KV_BUCKET_OPEN, &encrypted).unwrap().handle;
    let resealed = client.call::<KvResealed>(method::KV_RESEAL, &KvBranch { handle, under: Vec::new() }).unwrap();
    assert_eq!(resealed.count, 1, "the value the old key sealed");
    let key = KvCall { handle, key: "db".to_owned(), ..KvCall::default() };
    assert!(client.call::<KvEntry>(method::KV_GET, &key).unwrap().found);
}

/// kv's sets through the pipe, 20 batches of 1000 in flight, the store measured and not in
/// turns, the median of five passes: what a request costs the store's own
/// metrics, its count and its time by method.
///
/// cargo test --release -p tinystore pipe::tests::sets_in_flight_measured_and_not -- --ignored --nocapture
#[cfg(feature = "metrics")]
#[test]
#[ignore = "a timing, not a check"]
fn sets_in_flight_measured_and_not() {
    const BATCHES: u32 = 20;
    let rate = |measured: bool| {
        let dir = tempfile::tempdir().unwrap();
        let self_metrics = measured.then(crate::metrics::SelfMetrics::default);
        let options = Options { self_metrics, durability: Some(crate::Durability::Os), ..Options::default() };
        let store = Store::open(dir.path(), options).unwrap();
        let mut client = Client::over(Pipe::connect(&store, Connect::default()).unwrap());
        client.hello(1).unwrap();
        let handle = client.bucket("smoke");
        let started = std::time::Instant::now();
        for batch in 0..BATCHES {
            let mut bytes = Vec::new();
            for n in 0..1000u32 {
                let key = format!("{batch}-{n}");
                let set = KvCall { handle, key, value: Some(Row::Bin(vec![b'x'; 100])), ..KvCall::default() };
                Frame { method: method::KV_SET, ..Frame::new(Kind::Request, client.next_stream + 1 + n, set.encode()) }
                    .ending()
                    .encode_into(&mut bytes);
            }
            client.reader.push(&client.pipe.send(&bytes));
            let mut answered = 0;
            while answered < 1000 {
                match client.reader.next(1 << 22).unwrap() {
                    Some(frame) if frame.kind == Kind::Response => answered += 1,
                    Some(frame) => panic!("a {:?} among the answers", frame.kind),
                    None => {
                        let ready = client.pipe.recv(Duration::from_secs(10));
                        assert!(!ready.is_empty(), "the pipe answered {answered} of 1000 sets, then nothing");
                        client.reader.push(&ready);
                    }
                }
            }
        }
        let rate = f64::from(BATCHES * 1000) / started.elapsed().as_secs_f64();
        drop(client);
        store.close().unwrap();
        rate
    };
    let (mut off, mut on) = (Vec::new(), Vec::new());
    for _ in 0..5 {
        off.push(rate(false));
        on.push(rate(true));
    }
    off.sort_by(f64::total_cmp);
    on.sort_by(f64::total_cmp);
    println!("off {:.0}/s, on {:.0}/s, {:+.1} %", off[2], on[2], (on[2] / off[2] - 1.0) * 100.0);
}