tinystore 0.4.1

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

use crate::pipe::fixture::{Client, answered};
use crate::wire::codec::Message;
use crate::wire::frame::{self, Frame, Kind};
use crate::wire::protocol::{
    BlobsAt, BlobsDelete, BlobsGot, BlobsHead, BlobsOpen, BlobsPiece, BlobsRead, 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() }.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");
}

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