tinystore 0.10.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
use std::time::Duration;

use crate::pipe::Capability;
use crate::pipe::fixture::{Client, answered};
use crate::wire::codec::Message;
use crate::wire::frame::{self, Frame, Kind};
use crate::wire::protocol::{
    BlobsAt, BlobsChanges, BlobsDelete, BlobsDirectory, BlobsFolder, BlobsGot, BlobsHead, BlobsOpen, BlobsPiece,
    BlobsRead, BlobsScanned, BlobsSetMaxSize, BlobsSince, BlobsTrim, BlobsTrimmed, BlobsUsage, BlobsWrite,
    BlobsWritten, Empty, Failure, Handle, Hello, method,
};

fn open(client: &mut Client, name: &str) -> u64 {
    let open = BlobsOpen { name: name.to_owned(), ..BlobsOpen::default() };
    client.call::<Handle>(method::BLOBS_OPEN, &open).unwrap().handle
}

fn bytes(size: usize) -> Vec<u8> {
    (0..size).map(|n| (n * 31 % 251) as u8).collect()
}

/// A client greeted with `hello`, and the DATA bytes the server takes on a
/// stream before it gives credit back.
fn connect(dir: &std::path::Path, hello: Hello) -> (Client, u64) {
    let mut client = Client::connect(dir);
    let welcome = client.greet(hello).unwrap();
    (client, welcome.stream_credit)
}

/// Uploads `body` in pieces of `piece` bytes within the server's `credit`,
/// and the answer of its last DATA.
fn upload(client: &mut Client, write: &BlobsWrite, body: &[u8], piece: usize, mut credit: u64) -> Frame {
    let stream = client.open_stream(method::BLOBS_UPLOAD, write);
    let begun = client.next_on(stream);
    assert_eq!((begun.kind, begun.flags), (Kind::Response, 0), "an upload begins: {:?}", answered::<Empty>(&begun));
    let pieces: Vec<&[u8]> = body.chunks(piece).collect();
    for (n, bytes) in pieces.iter().enumerate() {
        let data =
            Frame::new(Kind::Data, stream, BlobsPiece { bytes: bytes.to_vec(), ..BlobsPiece::default() }.encode());
        while credit < data.body.len() as u64 {
            credit += client.credit_on(stream);
        }
        credit -= data.body.len() as u64;
        client.write(if n + 1 == pieces.len() { data.ending() } else { data });
    }
    if pieces.is_empty() {
        client.write(Frame::new(Kind::Data, stream, Vec::new()).ending());
    }
    client.next_on(stream)
}

/// A read of a file's bytes and how its stream ended: the RESPONSE's piece,
/// then pieces never past the `credit` the client gave, which it grants back
/// once half of it was taken, as the SDK does.
fn read(client: &mut Client, read: &BlobsRead, credit: u64) -> (Vec<u8>, Result<(), Failure>) {
    let stream = client.start(method::BLOBS_READ, read);
    let mut frame = client.next_on(stream);
    let mut bytes = match answered::<BlobsPiece>(&frame) {
        Ok(first) => first.bytes,
        Err(failure) => return (Vec::new(), Err(failure)),
    };
    assert!(bytes.len() as u64 <= credit / 2, "a piece is at most half the credit");
    let mut taken = 0_u64;
    while frame.flags & frame::END == 0 {
        frame = client.next_on(stream);
        if frame.flags & frame::END != 0 {
            return (bytes, answered::<Empty>(&frame).map(drop));
        }
        taken += frame.body.len() as u64;
        assert!(taken <= credit, "the server sends within the client's credit");
        bytes.extend_from_slice(&BlobsPiece::decode(&frame.body).unwrap().bytes);
        if taken >= credit / 2 {
            client.write(Frame::new(Kind::Credit, stream, u32::try_from(taken).unwrap().to_le_bytes().to_vec()));
            taken = 0;
        }
    }
    (bytes, Ok(()))
}

/// A read of the whole file at `path`, on the ETag its get gave.
fn whole(client: &mut Client, handle: u64, path: &str, credit: u64) -> (Vec<u8>, Result<(), Failure>) {
    let at = BlobsAt { handle, folder: Vec::new(), path: path.to_owned() };
    let got: BlobsGot = client.call(method::BLOBS_GET, &at).unwrap();
    assert!(got.bytes.is_empty(), "a file past half a body waits for its read");
    let if_match = got.info.map(|info| info.etag);
    read(client, &BlobsRead { handle, path: path.to_owned(), if_match, ..BlobsRead::default() }, credit)
}

#[test]
fn a_file_put_over_the_wire_reads_back_whole_in_one_answer() {
    let dir = tempfile::tempdir().unwrap();
    let mut client = Client::open(dir.path());
    let handle = open(&mut client, "avatars");
    let write = BlobsWrite {
        handle,
        folder: vec!["users".to_owned(), "42".to_owned()],
        path: "a.png".to_owned(),
        content_type: Some("image/png".to_owned()),
        bytes: b"not really a png".to_vec(),
        ..BlobsWrite::default()
    };
    let written: BlobsWritten = client.call(method::BLOBS_PUT, &write).unwrap();
    let info = written.info.expect("a put writes");
    assert_eq!((info.path.as_str(), info.size, info.content_type.as_str()), ("a.png", 16, "image/png"));
    let at = BlobsAt { handle, folder: write.folder.clone(), path: "a.png".to_owned() };
    let head: BlobsHead = client.call(method::BLOBS_HEAD, &at).unwrap();
    assert_eq!(head.info.as_ref(), Some(&info));
    let got: BlobsGot = client.call(method::BLOBS_GET, &at).unwrap();
    assert_eq!((got.info, got.bytes), (Some(info), write.bytes));
    let none: BlobsGot = client.call(method::BLOBS_GET, &BlobsAt { path: "b.png".to_owned(), ..at }).unwrap();
    assert_eq!(none.info, None);
}

#[test]
fn create_over_the_wire_writes_once() {
    let dir = tempfile::tempdir().unwrap();
    let mut client = Client::open(dir.path());
    let handle = open(&mut client, "docs");
    let create =
        BlobsWrite { handle, path: "a".to_owned(), create: true, bytes: b"1".to_vec(), ..BlobsWrite::default() };
    let first: BlobsWritten = client.call(method::BLOBS_PUT, &create).unwrap();
    assert!(first.info.is_some());
    let again: BlobsWritten = client.call(method::BLOBS_PUT, &BlobsWrite { bytes: b"2".to_vec(), ..create }).unwrap();
    assert_eq!(again.info, None, "a create that found a file writes nothing");
}

#[test]
fn a_large_file_goes_up_and_comes_down_in_pieces_within_the_credit() {
    let dir = tempfile::tempdir().unwrap();
    let credit = 256 << 10;
    let (mut client, server_credit) =
        connect(dir.path(), Hello { protocol: 1, stream_credit: Some(credit), ..Hello::default() });
    let handle = open(&mut client, "exports");
    let body = bytes(3 << 20);
    let write =
        BlobsWrite { handle, path: "big.bin".to_owned(), size: Some(body.len() as u64), ..BlobsWrite::default() };
    let last = upload(&mut client, &write, &body, 100_000, server_credit);
    let written = answered::<BlobsWritten>(&last).unwrap();
    assert_eq!(written.info.unwrap().size, body.len() as u64);

    let (downloaded, ended) = whole(&mut client, handle, "big.bin", credit);
    assert_eq!(ended, Ok(()));
    assert!(downloaded == body, "the bytes that went up come down");
    assert_eq!(client.pipe.streams(), 0);
}

#[test]
fn a_range_reads_only_its_bytes_and_is_not_checked() {
    let dir = tempfile::tempdir().unwrap();
    let (mut client, credit) = connect(dir.path(), Hello { protocol: 1, ..Hello::default() });
    let handle = open(&mut client, "videos");
    let body = bytes(5 << 20);
    let write = BlobsWrite { handle, path: "film.mp4".to_owned(), ..BlobsWrite::default() };
    answered::<BlobsWritten>(&upload(&mut client, &write, &body, 1 << 20, credit)).unwrap();
    let range = |offset: u64, length: Option<u64>| BlobsRead {
        handle,
        path: "film.mp4".to_owned(),
        offset: Some(offset),
        length,
        ..BlobsRead::default()
    };

    let (middle, ended) = read(&mut client, &range(1_000_000, Some(3_000_000)), 2 << 20);
    assert_eq!(ended, Ok(()));
    assert!(middle == body[1_000_000..4_000_000], "the range is its bytes");
    let (tail, _) = read(&mut client, &range(body.len() as u64 - 500, None), 2 << 20);
    assert!(tail == body[body.len() - 500..], "a range to the end");
    let (past, ended) = read(&mut client, &range(body.len() as u64 + 1, Some(10)), 2 << 20);
    assert_eq!((past.len(), ended), (0, Ok(())), "a range past the end is empty");

    let fan = std::fs::read_dir(dir.path().join("blobs/objects")).unwrap().next().unwrap().unwrap().path();
    let file = std::fs::read_dir(fan).unwrap().next().unwrap().unwrap().path();
    let mut changed = std::fs::read(&file).unwrap();
    changed[4096] ^= 0x5a;
    std::fs::write(&file, changed).unwrap();
    let (head, ended) = read(&mut client, &range(0, Some(8192)), 2 << 20);
    assert_eq!((head.len(), ended), (8192, Ok(())), "a range is not checked");
}

#[test]
fn a_read_on_an_etag_the_path_no_longer_holds_is_a_conflict() {
    let dir = tempfile::tempdir().unwrap();
    let (mut client, credit) = connect(dir.path(), Hello { protocol: 1, ..Hello::default() });
    let handle = open(&mut client, "docs");
    let write = BlobsWrite { handle, path: "a".to_owned(), ..BlobsWrite::default() };
    answered::<BlobsWritten>(&upload(&mut client, &write, &bytes(3 << 20), 1 << 20, credit)).unwrap();
    let at = BlobsAt { handle, folder: Vec::new(), path: "a".to_owned() };
    let got: BlobsGot = client.call(method::BLOBS_GET, &at).unwrap();
    let on =
        BlobsRead { handle, path: "a".to_owned(), if_match: got.info.map(|info| info.etag), ..BlobsRead::default() };

    client.call::<BlobsWritten>(method::BLOBS_PUT, &BlobsWrite { bytes: b"other".to_vec(), ..write }).unwrap();
    let (_, ended) = read(&mut client, &on, 2 << 20);
    assert_eq!(ended.unwrap_err().code, "conflict", "a file replaced since its get");
    let (now, ended) = read(&mut client, &BlobsRead { if_match: None, ..on.clone() }, 2 << 20);
    assert_eq!((now, ended), (b"other".to_vec(), Ok(())), "without an ETag, what is there now");

    let delete = BlobsDelete { handle, path: "a".to_owned(), ..BlobsDelete::default() };
    client.call::<Empty>(method::BLOBS_DELETE, &delete).unwrap();
    let (_, ended) = read(&mut client, &on, 2 << 20);
    assert_eq!(ended.unwrap_err().code, "conflict", "a file deleted since its get");
    let (_, ended) = read(&mut client, &BlobsRead { if_match: None, ..on }, 2 << 20);
    assert_eq!(ended.unwrap_err().code, "not_found");
}

// contract: WIRE-01
#[test]
fn a_read_compares_its_etag_as_a_write_does_without_its_quotes_and_in_either_case() {
    let dir = tempfile::tempdir().unwrap();
    let mut client = Client::open(dir.path());
    let handle = open(&mut client, "docs");
    let write = BlobsWrite { handle, path: "a".to_owned(), bytes: b"first".to_vec(), ..BlobsWrite::default() };
    let written: BlobsWritten = client.call(method::BLOBS_PUT, &write).unwrap();
    let bare = written.info.unwrap().etag.trim_matches('"').to_ascii_uppercase();
    let on = BlobsRead { handle, path: "a".to_owned(), if_match: Some(bare.clone()), ..BlobsRead::default() };

    let (first, ended) = read(&mut client, &on, 2 << 20);
    assert_eq!((first, ended), (b"first".to_vec(), Ok(())), "the ETag, unquoted and in capitals, names the bytes");
    let replace = BlobsWrite { if_match: Some(bare), bytes: b"second".to_vec(), ..write };
    assert!(client.call::<BlobsWritten>(method::BLOBS_PUT, &replace).unwrap().info.is_some(), "as a write takes it");
    let (_, ended) = read(&mut client, &on, 2 << 20);
    assert_eq!(ended.unwrap_err().code, "conflict", "the bytes it named were replaced");
}

#[test]
fn a_whole_read_of_a_changed_byte_ends_corrupt_before_its_last_piece() {
    let dir = tempfile::tempdir().unwrap();
    let credit = 1 << 20;
    let (mut client, server_credit) =
        connect(dir.path(), Hello { protocol: 1, stream_credit: Some(credit), ..Hello::default() });
    let handle = open(&mut client, "docs");
    let body = bytes(5 << 20);
    let write = BlobsWrite { handle, path: "a".to_owned(), ..BlobsWrite::default() };
    answered::<BlobsWritten>(&upload(&mut client, &write, &body, 256 << 10, server_credit)).unwrap();
    let fan = std::fs::read_dir(dir.path().join("blobs/objects")).unwrap().next().unwrap().unwrap().path();
    let file = std::fs::read_dir(fan).unwrap().next().unwrap().unwrap().path();
    let mut changed = std::fs::read(&file).unwrap();
    changed[4096] ^= 0x5a;
    std::fs::write(&file, changed).unwrap();

    let (downloaded, ended) = whole(&mut client, handle, "a", credit);
    assert!(downloaded.len() < body.len(), "the last bytes are held back");
    let failed = ended.unwrap_err();
    assert_eq!(failed.code, "corrupt", "{}", failed.message);
}

// contract: BLOB-02
#[test]
fn a_get_of_a_changed_byte_is_corrupt_rather_than_answered() {
    let dir = tempfile::tempdir().unwrap();
    let mut client = Client::open(dir.path());
    let handle = open(&mut client, "docs");
    let write = BlobsWrite { handle, path: "a".to_owned(), bytes: bytes(1 << 20), ..BlobsWrite::default() };
    client.call::<BlobsWritten>(method::BLOBS_PUT, &write).unwrap();
    let fan = std::fs::read_dir(dir.path().join("blobs/objects")).unwrap().next().unwrap().unwrap().path();
    let file = std::fs::read_dir(fan).unwrap().next().unwrap().unwrap().path();
    let mut changed = std::fs::read(&file).unwrap();
    changed[(1 << 20) - 1] ^= 0x5a;
    std::fs::write(&file, changed).unwrap();

    let at = BlobsAt { handle, folder: Vec::new(), path: "a".to_owned() };
    let failed = client.call::<BlobsGot>(method::BLOBS_GET, &at).unwrap_err();
    assert_eq!(failed.code, "corrupt", "{}", failed.message);
}

#[test]
fn a_get_and_a_read_write_their_bytes_in_place_as_their_messages_encode() {
    use std::io::{Seek, SeekFrom};

    let dir = tempfile::tempdir().unwrap();
    let store = crate::Store::open(dir.path(), crate::Options::default()).unwrap();
    let docs = store.files("docs").open().unwrap();
    // empty, inline, the first past inline, and a file of pieces
    for size in [0, 1, 16 << 10, (16 << 10) + 1, 1 << 20] {
        let body = bytes(size);
        docs.put("a", &body).unwrap();
        let mut file = docs.get("a").unwrap().unwrap();
        let info = super::info_of(file.info().clone());
        let got = super::got_whole(info.clone(), &mut file).unwrap();
        assert_eq!(got, BlobsGot { info: Some(info), bytes: body.clone() }.encode(), "a get of {size} bytes");
        file.seek(SeekFrom::Start(0)).unwrap();
        let (piece, _) = super::read_piece(&mut file, size).unwrap();
        assert_eq!(piece, BlobsPiece { bytes: body, ..BlobsPiece::default() }.encode(), "a piece of {size} bytes");
    }
    store.close().unwrap();
}

// contract: WIRE-04
#[test]
fn a_read_cancelled_mid_way_sends_nothing_after_its_last_frame() {
    let dir = tempfile::tempdir().unwrap();
    let (mut client, credit) = connect(dir.path(), Hello { protocol: 1, ..Hello::default() });
    let handle = open(&mut client, "films");
    let write = BlobsWrite { handle, path: "film.mp4".to_owned(), ..BlobsWrite::default() };
    answered::<BlobsWritten>(&upload(&mut client, &write, &bytes(16 << 20), 1 << 20, credit)).unwrap();
    let film = BlobsRead { handle, path: "film.mp4".to_owned(), ..BlobsRead::default() };
    for _ in 0..20 {
        let stream = client.start(method::BLOBS_READ, &film);
        assert_eq!(client.next_on(stream).flags, 0, "the read goes on past its RESPONSE");
        // the cancel meets a piece the worker read and is about to send
        client.write(Frame::new(Kind::Cancel, stream, Vec::new()));
        while client.next_on(stream).flags & frame::END == 0 {}
        assert!(client.silent_on(stream, Duration::from_millis(50)), "a piece went after the read's last frame");
    }
}

#[test]
fn an_upload_cancelled_or_refused_leaves_nothing() {
    let dir = tempfile::tempdir().unwrap();
    let mut client = Client::open(dir.path());
    let handle = open(&mut client, "docs");
    let write = BlobsWrite { handle, path: "a".to_owned(), ..BlobsWrite::default() };
    let stream = client.open_stream(method::BLOBS_UPLOAD, &write);
    assert_eq!(client.next_on(stream).flags, 0);
    client.write(Frame::new(
        Kind::Data,
        stream,
        BlobsPiece { bytes: bytes(1 << 20), ..BlobsPiece::default() }.encode(),
    ));
    client.write(Frame::new(Kind::Cancel, stream, Vec::new()));
    assert_eq!(answered::<Empty>(&client.next_on(stream)).unwrap_err().code, "cancelled");

    let sized = BlobsWrite { size: Some(10), ..write.clone() };
    let refused = answered::<BlobsWritten>(&upload(&mut client, &sized, &bytes(11), 4, 1 << 20)).unwrap_err();
    assert_eq!(refused.code, "invalid", "{}", refused.message);
    let head: BlobsHead =
        client.call(method::BLOBS_HEAD, &BlobsAt { handle, folder: Vec::new(), path: "a".to_owned() }).unwrap();
    assert_eq!(head.info, None);
    assert_eq!(std::fs::read_dir(dir.path().join("blobs/uploads")).unwrap().count(), 0);
}

#[test]
fn a_connection_that_ends_mid_upload_leaves_nothing() {
    let dir = tempfile::tempdir().unwrap();
    {
        let mut client = Client::open(dir.path());
        let handle = open(&mut client, "docs");
        let write = BlobsWrite { handle, path: "a".to_owned(), ..BlobsWrite::default() };
        let stream = client.open_stream(method::BLOBS_UPLOAD, &write);
        assert_eq!(client.next_on(stream).flags, 0);
        client.write(Frame::new(
            Kind::Data,
            stream,
            BlobsPiece { bytes: bytes(1 << 20), ..BlobsPiece::default() }.encode(),
        ));
        std::thread::sleep(Duration::from_millis(100));
    }
    assert_eq!(std::fs::read_dir(dir.path().join("blobs/uploads")).unwrap().count(), 0);
}

/// The GOAWAY that ends a connection, past whatever frames came before it.
fn gone_away(client: &mut Client) -> crate::wire::protocol::GoAway {
    loop {
        let frame = client.read();
        if frame.kind == Kind::GoAway {
            return crate::wire::protocol::GoAway::decode(&frame.body).unwrap();
        }
    }
}

#[test]
fn a_request_on_a_stream_in_use_ends_the_connection() {
    let dir = tempfile::tempdir().unwrap();
    let mut client = Client::open(dir.path());
    let handle = open(&mut client, "docs");
    let write = BlobsWrite { handle, path: "a".to_owned(), ..BlobsWrite::default() };
    let stream = client.open_stream(method::BLOBS_UPLOAD, &write);
    client.write(Frame { method: method::BLOBS_UPLOAD, ..Frame::new(Kind::Request, stream, write.encode()) });
    let gone = gone_away(&mut client);
    assert_eq!(gone.code, "protocol");
    assert!(gone.message.contains("in use"), "{}", gone.message);
}

#[test]
fn data_past_its_streams_credit_ends_the_connection() {
    let dir = tempfile::tempdir().unwrap();
    let (mut client, credit) =
        connect(dir.path(), Hello { protocol: 1, client: "test/0".to_owned(), ..Hello::default() });
    let handle = open(&mut client, "docs");
    let write = BlobsWrite { handle, path: "a".to_owned(), ..BlobsWrite::default() };
    let stream = client.open_stream(method::BLOBS_UPLOAD, &write);
    // two pieces of the whole credit in one write: the second cannot have been granted
    let piece = Frame::new(
        Kind::Data,
        stream,
        BlobsPiece { bytes: bytes(credit as usize - 16), ..BlobsPiece::default() }.encode(),
    );
    let mut flood = Vec::new();
    piece.encode_into(&mut flood);
    piece.encode_into(&mut flood);
    let ready = client.pipe.send(&flood);
    client.reader.push(&ready);
    let gone = gone_away(&mut client);
    assert_eq!(gone.code, "protocol");
    assert!(gone.message.contains("past its credit"), "{}", gone.message);
}

/// Gets of a mebibyte a second through a pipe, 1 and 16 in flight, with no
/// host language: the core's side of issue #10's read. The host reads each
/// frame into bytes it keeps from one to the next, as no SDK can, so that
/// what is timed is the core's. Run by hand:
/// cargo test --release -p tinystore --lib wire::blobs::tests::mebibyte_gets_in_flight -- --ignored --nocapture
#[test]
#[ignore = "a timing, not a check"]
fn mebibyte_gets_in_flight() {
    let dir = tempfile::tempdir().unwrap();
    let mut client = Client::open(dir.path());
    let handle = open(&mut client, "attachments");
    let body = bytes(1 << 20);
    for n in 0..100 {
        let write = BlobsWrite { handle, path: format!("{n}.bin"), bytes: body.clone(), ..BlobsWrite::default() };
        client.call::<BlobsWritten>(method::BLOBS_PUT, &write).unwrap();
    }
    let get = |stream: u32, n: u32| {
        let at = BlobsAt { handle, folder: Vec::new(), path: format!("{}.bin", n % 100) };
        let mut bytes = Vec::new();
        Frame { method: method::BLOBS_GET, ..Frame::new(Kind::Request, stream, at.encode()) }
            .ending()
            .encode_into(&mut bytes);
        bytes
    };
    let mut frame = vec![0; 2 << 20];
    for in_flight in [1_u32, 16] {
        let mut passes = Vec::new();
        for _ in 0..5 {
            let started = std::time::Instant::now();
            let mut asked = 0;
            for _ in 0..in_flight {
                asked += 1;
                client.pipe.push(&get(asked, asked * 13));
            }
            let mut answered = 0_u32;
            while started.elapsed() < Duration::from_secs(2) || answered < asked {
                let (kind, length) = next_frame(&client.pipe, &mut frame);
                if kind != Kind::Response as u8 {
                    continue;
                }
                assert!(length > 1 << 20, "a get answers the whole file");
                answered += 1;
                if started.elapsed() < Duration::from_secs(2) {
                    asked += 1;
                    client.pipe.push(&get(asked, asked * 13));
                }
            }
            client.next_stream = asked;
            passes.push(f64::from(answered) / started.elapsed().as_secs_f64());
        }
        passes.sort_by(f64::total_cmp);
        println!("{in_flight} in flight: {:.0} gets/s, median of {passes:.0?}", passes[2]);
    }
}

/// The next frame off the pipe, its header and then its body read into
/// `into`, which grows to hold it; its kind and its body's length.
fn next_frame(pipe: &crate::pipe::Pipe, into: &mut Vec<u8>) -> (u8, usize) {
    fill(pipe, &mut into[..frame::HEADER]);
    let length = u32::from_le_bytes(into[..4].try_into().unwrap()) as usize;
    if into.len() < frame::HEADER + length {
        into.resize(frame::HEADER + length, 0);
    }
    fill(pipe, &mut into[frame::HEADER..frame::HEADER + length]);
    (into[4], length)
}

fn fill(pipe: &crate::pipe::Pipe, into: &mut [u8]) {
    let mut filled = 0;
    while filled < into.len() {
        filled += pipe.recv_into(Duration::from_secs(10), &mut into[filled..]);
    }
}

/// A store, a folder beside it holding `film.mkv`, and a client of the
/// store, admitted with a token of `token` when one is given, on a server
/// given that folder as the directory `movies`.
fn beside_a_folder(token: Option<Capability>) -> (Client, crate::Store, tempfile::TempDir, tempfile::TempDir) {
    let (dir, folder) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
    std::fs::write(folder.path().join("film.mkv"), b"the folder's film").unwrap();
    let store = crate::Store::open(dir.path(), crate::Options { background: false, ..Default::default() }).unwrap();
    (client_of(&store, folder.path(), token), store, dir, folder)
}

/// A client of `store` on a server given `folder` as the directory `movies`.
fn client_of(store: &crate::Store, folder: &std::path::Path, token: Option<Capability>) -> Client {
    let given = std::collections::BTreeMap::from([("movies".to_owned(), folder.to_owned())]);
    let admit = token.map(|capability| -> crate::pipe::Admit { std::sync::Arc::new(move |_| Some(capability)) });
    let connect = crate::pipe::Connect { admit, directories: Some(std::sync::Arc::new(given)), ..Default::default() };
    let mut client = Client::over(crate::pipe::Pipe::connect(store, connect).unwrap());
    let hello = Hello { protocol: 1, token: token.map(|_| "a token".to_owned()), ..Hello::default() };
    client.greet(hello).unwrap();
    client
}

fn open_directory(client: &mut Client, asked: BlobsDirectory) -> Result<u64, Failure> {
    client.call::<Handle>(method::BLOBS_DIRECTORY, &asked).map(|handle| handle.handle)
}

#[test]
fn a_directory_scans_lists_reads_and_follows_its_changes_over_the_wire_and_takes_no_write() {
    let (mut client, store, _dir, folder) = beside_a_folder(None);
    let asked = BlobsDirectory {
        name: "films".to_owned(),
        path: Some(folder.path().display().to_string()),
        ..Default::default()
    };
    let handle = open_directory(&mut client, asked).unwrap();
    let scanned: BlobsScanned = client.call(method::BLOBS_SCAN, &BlobsFolder { handle, folder: Vec::new() }).unwrap();
    assert_eq!((scanned.added, scanned.count, scanned.size), (1, 1, 17));
    let at = BlobsAt { handle, folder: Vec::new(), path: "film.mkv".to_owned() };
    let got: BlobsGot = client.call(method::BLOBS_GET, &at).unwrap();
    assert_eq!(got.bytes, b"the folder's film");
    let etag = got.info.unwrap().etag;
    assert!(etag.starts_with("\"d-11-"), "{etag}");
    let asked = BlobsRead {
        if_match: Some(etag.clone()),
        ..BlobsRead { handle, path: "film.mkv".to_owned(), ..Default::default() }
    };
    assert_eq!(read(&mut client, &asked, 1 << 20), (b"the folder's film".to_vec(), Ok(())));
    let changes: BlobsChanges = client.call(method::BLOBS_CHANGES, &BlobsSince { handle, after: None }).unwrap();
    assert_eq!((changes.items.len(), changes.items[0].change.as_str()), (1, "added"));

    std::fs::write(folder.path().join("film.mkv"), b"another film, longer").unwrap();
    let moved = read(&mut client, &asked, 1 << 20).1.unwrap_err();
    assert_eq!(moved.code, "conflict", "{moved:?}");
    let write = BlobsWrite { handle, path: "new.mkv".to_owned(), bytes: b"x".to_vec(), ..Default::default() };
    let refused = client.call::<BlobsWritten>(method::BLOBS_PUT, &write).unwrap_err();
    assert_eq!(refused.code, "invalid", "{refused:?}");
    client.call::<Empty>(method::BLOBS_FORGET, &BlobsFolder { handle, folder: Vec::new() }).unwrap();
    let usage: BlobsUsage = client.call(method::BLOBS_USAGE, &BlobsFolder { handle, folder: Vec::new() }).unwrap();
    assert_eq!(usage.count, 0);
    drop(client);
    store.close().unwrap();
}

// contract: BLOB-15
#[test]
fn a_connection_that_came_with_a_token_names_no_path_and_reaches_only_what_the_server_was_given() {
    let (mut client, store, _dir, folder) = beside_a_folder(Some(Capability::Data));
    let path = Some(folder.path().display().to_string());
    let named = open_directory(&mut client, BlobsDirectory { name: "movies".to_owned(), path, ..Default::default() });
    assert_eq!(named.unwrap_err().code, "invalid");
    let missing = open_directory(&mut client, BlobsDirectory { name: "photos".to_owned(), ..Default::default() });
    assert_eq!(missing.unwrap_err().code, "invalid");
    let handle =
        open_directory(&mut client, BlobsDirectory { name: "movies".to_owned(), ..Default::default() }).unwrap();
    let scanned: BlobsScanned = client.call(method::BLOBS_SCAN, &BlobsFolder { handle, folder: Vec::new() }).unwrap();
    assert_eq!(scanned.added, 1, "the server's own folder");
    drop(client);

    let mut reading = client_of(&store, folder.path(), Some(Capability::Read));
    let handle = open_directory(&mut reading, BlobsDirectory { name: "movies".to_owned(), ..Default::default() });
    let handle = handle.unwrap();
    let refused = reading.call::<BlobsScanned>(method::BLOBS_SCAN, &BlobsFolder { handle, folder: Vec::new() });
    assert!(refused.is_err(), "a token that only reads scanned");
    let usage: BlobsUsage = reading.call(method::BLOBS_USAGE, &BlobsFolder { handle, folder: Vec::new() }).unwrap();
    assert_eq!(usage.count, 1, "a token that only reads lists");
    drop(reading);
    store.close().unwrap();
}

// contract: BLOB-13
#[test]
fn a_growing_directorys_pieces_go_past_the_size_its_get_gave_and_bring_the_size_now() {
    let (mut client, store, _dir, folder) = beside_a_folder(None);
    let path = Some(folder.path().display().to_string());
    let asked = BlobsDirectory { name: "live".to_owned(), path, growing: true, ..Default::default() };
    let handle = open_directory(&mut client, asked).unwrap();
    client.call::<BlobsScanned>(method::BLOBS_SCAN, &BlobsFolder { handle, folder: Vec::new() }).unwrap();
    {
        use std::io::Write;
        let mut file = std::fs::OpenOptions::new().append(true).open(folder.path().join("film.mkv")).unwrap();
        file.write_all(b", and more").unwrap();
    }
    let read = BlobsRead { handle, folder: Vec::new(), path: "film.mkv".to_owned(), ..Default::default() };
    let stream = client.start(method::BLOBS_READ, &read);
    let piece = answered::<BlobsPiece>(&client.next_on(stream)).unwrap();
    assert_eq!(piece.bytes, b"the folder's film, and more");
    assert_eq!(piece.size, Some(27), "a piece of a growing file brings its size");
    drop(client);
    store.close().unwrap();
}

fn put(client: &mut Client, handle: u64, path: &str, size: usize) -> Result<BlobsWritten, Failure> {
    let write = BlobsWrite { handle, path: path.to_owned(), bytes: bytes(size), ..Default::default() };
    client.call::<BlobsWritten>(method::BLOBS_PUT, &write)
}

fn usage_of(client: &mut Client, handle: u64) -> BlobsUsage {
    client.call(method::BLOBS_USAGE, &BlobsFolder { handle, folder: Vec::new() }).unwrap()
}

// contract: BLOB-20, BLOB-24
#[test]
fn a_ceiling_over_the_wire_evicts_conflicts_with_another_and_changes_by_set_max_size() {
    let (mut client, store, _dir, _folder) = beside_a_folder(None);
    let open = BlobsOpen { name: "pages".to_owned(), max_size: Some(200), ..BlobsOpen::default() };
    let handle = client.call::<Handle>(method::BLOBS_OPEN, &open).unwrap().handle;
    for path in ["a", "b", "c"] {
        put(&mut client, handle, path, 100).unwrap();
    }
    let usage = usage_of(&mut client, handle);
    assert_eq!((usage.count, usage.size, usage.max_size, usage.evictions), (2, 200, Some(200), 1));
    let other = BlobsOpen { max_size: Some(300), ..open.clone() };
    assert_eq!(client.call::<Handle>(method::BLOBS_OPEN, &other).unwrap_err().code, "conflict");
    let refusing = BlobsOpen { when_full: Some("refuse".to_owned()), ..open.clone() };
    assert_eq!(client.call::<Handle>(method::BLOBS_OPEN, &refusing).unwrap_err().code, "conflict");
    let change = BlobsSetMaxSize { handle, max_size: Some(100), if_current: Some(300), ..BlobsSetMaxSize::default() };
    assert_eq!(client.call::<Empty>(method::BLOBS_SET_MAX_SIZE, &change).unwrap_err().code, "conflict");
    let change = BlobsSetMaxSize { if_current: Some(200), ..change };
    client.call::<Empty>(method::BLOBS_SET_MAX_SIZE, &change).unwrap();
    let usage = usage_of(&mut client, handle);
    assert_eq!((usage.count, usage.max_size, usage.evictions), (1, Some(100), 2), "a lower ceiling evicts at once");
    let trimmed: BlobsTrimmed = client.call(method::BLOBS_TRIM, &BlobsTrim { handle, to: 0 }).unwrap();
    assert_eq!((trimmed.evictions, trimmed.freed), (1, 100));
    let none = BlobsSetMaxSize { handle, ..BlobsSetMaxSize::default() };
    client.call::<Empty>(method::BLOBS_SET_MAX_SIZE, &none).unwrap();
    assert_eq!(usage_of(&mut client, handle).max_size, None);
    drop(client);
    store.close().unwrap();
}

// contract: BLOB-23
#[test]
fn a_refusing_ceiling_over_the_wire_fails_limit_and_refuses_a_trim() {
    let (mut client, store, _dir, _folder) = beside_a_folder(None);
    let open = BlobsOpen {
        name: "uploads".to_owned(),
        max_size: Some(150),
        when_full: Some("refuse".to_owned()),
        ..BlobsOpen::default()
    };
    let handle = client.call::<Handle>(method::BLOBS_OPEN, &open).unwrap().handle;
    put(&mut client, handle, "a", 100).unwrap();
    assert_eq!(put(&mut client, handle, "b", 100).unwrap_err().code, "limit");
    assert_eq!(usage_of(&mut client, handle).count, 1);
    let refused = client.call::<BlobsTrimmed>(method::BLOBS_TRIM, &BlobsTrim { handle, to: 0 }).unwrap_err();
    assert_eq!(refused.code, "invalid", "{refused:?}");
    let unknown = BlobsOpen { name: "other".to_owned(), when_full: Some("drop".to_owned()), ..BlobsOpen::default() };
    assert_eq!(client.call::<Handle>(method::BLOBS_OPEN, &unknown).unwrap_err().code, "invalid");
    drop(client);
    store.close().unwrap();
}

#[test]
fn a_read_connection_writes_no_policy_and_its_reads_record_no_use() {
    let (mut client, store, dir, folder) = beside_a_folder(None);
    let open = BlobsOpen { name: "pages".to_owned(), max_size: Some(1000), ..BlobsOpen::default() };
    let handle = client.call::<Handle>(method::BLOBS_OPEN, &open).unwrap().handle;
    put(&mut client, handle, "a", 10).unwrap();
    let mut reading = client_of(&store, folder.path(), Some(Capability::Read));
    let idle = BlobsOpen { name: "pages".to_owned(), idle: Some(60_000), ..BlobsOpen::default() };
    assert_eq!(reading.call::<Handle>(method::BLOBS_OPEN, &idle).unwrap_err().code, "permission");
    let other = BlobsOpen { max_size: Some(2000), ..open.clone() };
    assert_eq!(reading.call::<Handle>(method::BLOBS_OPEN, &other).unwrap_err().code, "permission");
    let read = reading.call::<Handle>(method::BLOBS_OPEN, &open).unwrap().handle;
    let change = BlobsSetMaxSize { handle: read, max_size: Some(5), ..BlobsSetMaxSize::default() };
    assert_eq!(reading.call::<Empty>(method::BLOBS_SET_MAX_SIZE, &change).unwrap_err().code, "permission");
    assert_eq!(
        reading.call::<BlobsTrimmed>(method::BLOBS_TRIM, &BlobsTrim { handle: read, to: 0 }).unwrap_err().code,
        "permission"
    );
    // written long ago, so that a read's use is due
    let made = "update _tinystore_blobs_files set modified = 0";
    let pages = store.files("pages").open().unwrap();
    pages
        .blobs
        .file
        .write(0, move |tx| crate::sqlite::execute_cached(tx, made, [], "a change by hand").map(drop))
        .unwrap();
    let at = BlobsAt { handle: read, folder: Vec::new(), path: "a".to_owned() };
    reading.call::<BlobsHead>(method::BLOBS_HEAD, &at).unwrap().info.unwrap();
    crate::blobs::maintain(&store).unwrap();
    let used = || {
        let read = |c: &rusqlite::Connection| {
            Ok(c.query_row("select used from _tinystore_blobs_files", [], |row| row.get::<_, Option<i64>>(0)).unwrap())
        };
        pages.blobs.file.read(read).unwrap()
    };
    assert_eq!(used(), None::<i64>, "a read connection's head recorded no use");
    client.call::<BlobsHead>(method::BLOBS_HEAD, &BlobsAt { handle, ..at }).unwrap().info.unwrap();
    crate::blobs::maintain(&store).unwrap();
    assert!(used().is_some(), "a connection that writes records its head's use");
    drop((reading, client, pages));
    let _ = dir;
    store.close().unwrap();
}