tinystore 0.5.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
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");
}

#[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");
}

#[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");
}

/// 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);
}