tinystore 0.3.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
//! blobs over the protocol: files by handle, the server holding nothing
//! between calls, as S3 does. A get answers what the file carries, and all
//! its bytes when they fit one message; a read streams a file's bytes, the
//! whole file checked or a range, on the ETag a get gave, as pieces within
//! the client's credit. An upload's pieces come as the client's DATA,
//! written in order as they come, the credit of each given back once it is
//! written, and its last DATA publishes the file.

use std::collections::{HashMap, VecDeque};
use std::io::{Read, Seek, SeekFrom};
use std::sync::{Arc, Mutex, Weak};
use std::time::Duration;

use super::codec::{self, Map, Message};
use super::protocol::{
    BlobsAt, BlobsDelete, BlobsExpire, BlobsFolder, BlobsFound, BlobsGot, BlobsHead, BlobsInfo, BlobsList, BlobsMove,
    BlobsOpen, BlobsPage, BlobsPiece, BlobsRead, BlobsUsage, BlobsWrite, BlobsWritten, Empty, Failure, Handle, method,
};
use super::{Link, Route};
use crate::blobs::{FileCall, FileInfo, Files, StoredFile, Upload};
use crate::sync::lock;
use crate::{Error, ErrorKind, Store, unix_millis};

use super::Answered;

pub(crate) fn route(called: u16) -> Route {
    match called {
        method::BLOBS_READ => Route::Read,
        method::BLOBS_UPLOAD => Route::Upload,
        _ => Route::Worker,
    }
}

/// What a connection opened, by handle, and its streams of a file's bytes.
#[derive(Default)]
pub(crate) struct Handles {
    open: super::ByHandle<Files>,
    reads: Arc<Mutex<HashMap<u32, Arc<Getting>>>>,
    uploads: Arc<Mutex<HashMap<u32, Arc<Uploading>>>>,
}

impl Handles {
    /// The files a handle names, in the folder of these segments.
    fn at(&self, handle: u64, folder: &[String]) -> Result<Files, Failure> {
        let files = self.open.get(handle, || format!("handle {handle} names no files this connection opened"))?;
        Ok(folder.iter().fold(files, |files, segment| files.folder(segment.as_str())))
    }

    /// Credit the client granted a read's stream.
    pub(crate) fn grant(&self, stream: u32, credit: u32) {
        let getting = lock(&self.reads).get(&stream).cloned();
        if let Some(getting) = getting {
            getting.grant(credit);
        }
    }

    /// The upload a client's DATA on `stream` is a piece of.
    pub(crate) fn uploading(&self, stream: u32) -> Option<Arc<Uploading>> {
        lock(&self.uploads).get(&stream).cloned()
    }

    /// Ends a read or an upload the client cancelled; says whether there was one.
    pub(crate) fn cancel(&self, stream: u32) -> bool {
        // out of its map before it ends, which takes the map's lock again:
        // an `if let` on the lock would hold it and wait for itself
        let getting = lock(&self.reads).remove(&stream);
        if let Some(getting) = getting {
            getting.end(Err(Failure::cancelled("the client cancelled its read")));
            return true;
        }
        let uploading = lock(&self.uploads).remove(&stream);
        if let Some(uploading) = uploading {
            uploading.cancel();
            return true;
        }
        false
    }

    /// Lets go of every stream at the session's end: a file read is closed,
    /// an upload's bytes removed.
    pub(crate) fn end(&self) {
        let reads: Vec<_> = lock(&self.reads).drain().map(|(_, getting)| getting).collect();
        for getting in reads {
            getting.drop_file();
        }
        let uploads: Vec<_> = lock(&self.uploads).drain().map(|(_, uploading)| uploading).collect();
        for uploading in uploads {
            uploading.cancel();
        }
    }
}

/// Answers a call of one message: everything but a read and an upload.
pub(crate) fn call(store: &Store, handles: &Handles, called: u16, body: &[u8], max_body: usize) -> Answered {
    match called {
        method::BLOBS_OPEN => open(store, handles, BlobsOpen::decode(body)?),
        method::BLOBS_PUT => put(handles, BlobsWrite::decode(body)?),
        method::BLOBS_GET => get(handles, &BlobsAt::decode(body)?, max_body),
        method::BLOBS_HEAD => head(handles, &BlobsAt::decode(body)?),
        method::BLOBS_DELETE => delete(handles, BlobsDelete::decode(body)?),
        method::BLOBS_COPY | method::BLOBS_RENAME => moved(handles, called, BlobsMove::decode(body)?),
        method::BLOBS_EXPIRE => expire(handles, &BlobsExpire::decode(body)?),
        method::BLOBS_LIST => list(handles, BlobsList::decode(body)?),
        method::BLOBS_USAGE => usage(handles, &BlobsFolder::decode(body)?),
        method::BLOBS_CLEAR => clear(handles, &BlobsFolder::decode(body)?),
        other => Err(Failure::unimplemented(format!("method {other:#06x}"))),
    }
}

fn open(store: &Store, handles: &Handles, asked: BlobsOpen) -> Answered {
    let mut files = store.files(&asked.name);
    if let Some(ttl) = asked.ttl {
        files = files.ttl(Duration::from_millis(ttl));
    }
    if let Some(most) = asked.max_file_size {
        files = files.max_file_size(most);
    }
    let files = files.open()?;
    let handle = handles.open.keep(files);
    Ok(Handle { handle }.encode())
}

fn put(handles: &Handles, mut asked: BlobsWrite) -> Answered {
    let files = handles.at(asked.handle, &asked.folder)?;
    let bytes = std::mem::take(&mut asked.bytes);
    let info = options(files.key(&asked.path), &asked).written(&bytes, asked.create)?;
    Ok(BlobsWritten { info: info.map(info_of) }.encode())
}

fn get(handles: &Handles, asked: &BlobsAt, max_body: usize) -> Answered {
    let Some(mut file) = handles.at(asked.handle, &asked.folder)?.get(&asked.path)? else {
        return Ok(BlobsGot::default().encode());
    };
    let info = info_of(file.info().clone());
    // half a body, the rest room for what it carries; a larger file waits for its read
    if info.size > (max_body / 2) as u64 {
        return Ok(BlobsGot { info: Some(info), bytes: Vec::new() }.encode());
    }
    got_whole(info, &mut file)
}

/// A get's answer with all the file's bytes, read straight into the message
/// that carries them: `BlobsGot { info, bytes }.encode()`, as the test beside
/// it checks, without the file's bytes held twice. A mebibyte's answer copied
/// from bytes of their own cost a fresh mebibyte and its copy (issue #10).
fn got_whole(info: BlobsInfo, file: &mut StoredFile) -> Answered {
    let size = usize::try_from(info.size).map_err(|_| Failure::internal("a file past this machine's memory"))?;
    // as `BlobsGot::size` reserves: a map's head, two fields' numbers, a bin's head of five
    let mut out = Vec::with_capacity(3 + 1 + info.size() + 1 + 5 + size);
    let mut map = Map::open(&mut out);
    map.field(&mut out, 1);
    codec::write_message(&mut out, &info);
    if size > 0 {
        map.field(&mut out, 2);
        codec::write_bin_in_place(&mut out, size, |bytes| file.read_whole(bytes))?;
    }
    map.close(&mut out);
    Ok(out)
}

fn head(handles: &Handles, asked: &BlobsAt) -> Answered {
    let info = handles.at(asked.handle, &asked.folder)?.head(&asked.path)?;
    Ok(BlobsHead { info: info.map(info_of) }.encode())
}

fn delete(handles: &Handles, asked: BlobsDelete) -> Answered {
    let files = handles.at(asked.handle, &asked.folder)?;
    let mut call = files.key(&asked.path);
    if let Some(etag) = asked.if_match {
        call = call.if_match(etag);
    }
    call.delete()?;
    Ok(Empty {}.encode())
}

/// A copy or a rename, as `called` says: the file at `from`, at `to`.
fn moved(handles: &Handles, called: u16, asked: BlobsMove) -> Answered {
    let files = handles.at(asked.handle, &asked.folder)?;
    let mut call = files.key(&asked.to);
    if let Some(etag) = asked.if_match {
        call = call.if_match(etag);
    }
    let info = if called == method::BLOBS_COPY { call.copy_from(&asked.from)? } else { call.rename_from(&asked.from)? };
    Ok(info_of(info).encode())
}

fn expire(handles: &Handles, asked: &BlobsExpire) -> Answered {
    let files = handles.at(asked.handle, &asked.folder)?;
    let found = files.expire(&asked.path, Duration::from_millis(asked.after))?;
    Ok(BlobsFound { found }.encode())
}

fn list(handles: &Handles, asked: BlobsList) -> Answered {
    let files = handles.at(asked.handle, &asked.folder)?;
    let mut list = files.list().prefix(asked.prefix);
    if let Some(after) = asked.after {
        list = list.after(after);
    }
    if let Some(limit) = asked.limit {
        list = list.limit(usize::try_from(limit).unwrap_or(usize::MAX));
    }
    let page = list.page()?;
    Ok(BlobsPage { files: page.files.into_iter().map(info_of).collect(), next: page.next }.encode())
}

fn usage(handles: &Handles, asked: &BlobsFolder) -> Answered {
    let usage = handles.at(asked.handle, &asked.folder)?.usage()?;
    Ok(BlobsUsage { count: usage.count, size: usage.size }.encode())
}

fn clear(handles: &Handles, asked: &BlobsFolder) -> Answered {
    handles.at(asked.handle, &asked.folder)?.clear()?;
    Ok(Empty {}.encode())
}

/// A write's options from its message.
fn options<'f>(mut call: FileCall<'f>, asked: &BlobsWrite) -> FileCall<'f> {
    if let Some(content_type) = &asked.content_type {
        call = call.content_type(content_type.clone());
    }
    for (name, value) in asked.meta.iter().flatten() {
        call = call.meta(name.clone(), value.clone());
    }
    if let Some(ttl) = asked.ttl {
        call = call.ttl(Duration::from_millis(ttl));
    }
    if let Some(etag) = &asked.if_match {
        call = call.if_match(etag.clone());
    }
    if let Some(size) = asked.size {
        call = call.size(size);
    }
    call
}

fn info_of(info: FileInfo) -> BlobsInfo {
    BlobsInfo {
        path: info.path,
        size: info.size,
        etag: info.etag,
        content_type: info.content_type,
        last_modified: unix_millis(info.last_modified),
        expires: info.expires.map(unix_millis),
        meta: (!info.meta.is_empty()).then_some(info.meta),
    }
}

/// The largest piece of a file a message carries: half of what the client
/// takes at once, so that one grant lets the next piece go while it reads
/// the last, less the piece's own few bytes.
fn piece_bound(link: &Link) -> usize {
    super::part_bound(link.max_body, link.credit, 16)
}

/// How a read's answer goes: whole in the RESPONSE, or the RESPONSE's piece
/// and then the rest within the client's credit.
pub(crate) enum Reading {
    Whole(Vec<u8>),
    Begun(Vec<u8>, Arc<Getting>),
}

/// Reads a file's bytes: the whole file, checked, or a range, which is not.
/// The file is opened here and held until the read ends, so that the bytes
/// are those of the ETag it was asked on, through a replace.
pub(crate) fn read(handles: &Handles, stream: u32, body: &[u8], link: &Link) -> Result<Reading, Failure> {
    let asked = BlobsRead::decode(body)?;
    let files = handles.at(asked.handle, &asked.folder)?;
    let mut file = match (files.get(&asked.path)?, &asked.if_match) {
        (Some(file), Some(etag)) if file.info().etag != *etag => return Err(changed(&files, &asked.path)),
        (None, Some(_)) => return Err(changed(&files, &asked.path)),
        (None, None) => return Err(files.fail(&asked.path, Error::not_found("no file is there")).into()),
        (Some(file), _) => file,
    };
    let size = file.info().size;
    let from = asked.offset.unwrap_or(0).min(size);
    let left = asked.length.map_or(size - from, |length| length.min(size - from));
    file.seek(SeekFrom::Start(from)).map_err(|error| Error::io("blobs: seek a file", error))?;
    let piece = piece_bound(link);
    let first = bound(piece, left);
    let response = read_piece(&mut file, first)?;
    let left = left - first as u64;
    if left == 0 {
        return Ok(Reading::Whole(response));
    }
    let state = GetState { file: Some(file), left, credit: link.credit, busy: false, ended: false };
    let getting = Arc::new(Getting {
        stream,
        piece,
        state: Mutex::new(state),
        link: link.clone(),
        reads: Arc::downgrade(&handles.reads),
    });
    lock(&handles.reads).insert(stream, Arc::clone(&getting));
    Ok(Reading::Begun(response, getting))
}

/// A read on an ETag the path no longer holds, as a write's `ifMatch` is.
fn changed(files: &Files, path: &str) -> Failure {
    let error = Error::new(ErrorKind::Conflict, "the path holds no file with the ETag given");
    files.fail(path, error).into()
}

/// The bytes the next piece reads: a piece's, or fewer when the read has
/// fewer left.
fn bound(piece: usize, left: u64) -> usize {
    usize::try_from(left).map_or(piece, |left| left.min(piece))
}

/// The next `length` bytes of a file as a piece's message, read straight
/// into it: `BlobsPiece { bytes }.encode()`, as the test beside it checks.
/// The read's last bytes wait until the whole file's SHA-256 is checked.
fn read_piece(file: &mut StoredFile, length: usize) -> Result<Vec<u8>, Failure> {
    // as `BlobsPiece::size` reserves: a map's head, a field's number, a bin's head of five
    let mut out = Vec::with_capacity(3 + 1 + 5 + length);
    let mut map = Map::open(&mut out);
    if length > 0 {
        map.field(&mut out, 1);
        codec::write_bin_in_place(&mut out, length, |bytes| fill(file, bytes))?;
    }
    map.close(&mut out);
    Ok(out)
}

/// Fills `bytes` from where the file's next read begins; the file reads to
/// its end, so that a read short of it is the store's fault.
fn fill(file: &mut StoredFile, bytes: &mut [u8]) -> Result<(), Failure> {
    let mut filled = 0;
    while filled < bytes.len() {
        match file.read(&mut bytes[filled..]) {
            Ok(0) => return Err(Failure::internal("a read of a file ended before its piece")),
            Ok(read) => filled += read,
            Err(error) => return Err(Failure::from(read_error(error))),
        }
    }
    Ok(())
}

/// The store's error a read carried, or an I/O one.
fn read_error(error: std::io::Error) -> crate::Error {
    // An OS error carries no inner error, and `into_inner` would drop it whole.
    if !error.get_ref().is_some_and(|inner| inner.is::<crate::Error>()) {
        return crate::Error::io("blobs: read a file", error);
    }
    match error.into_inner().map(|inner| inner.downcast::<crate::Error>()) {
        Some(Ok(error)) => *error,
        _ => crate::Error::internal("blobs: a read failed"),
    }
}

/// A read's bytes going out a piece at a time within the client's credit.
pub(crate) struct Getting {
    stream: u32,
    piece: usize,
    state: Mutex<GetState>,
    link: Link,
    reads: Weak<Mutex<HashMap<u32, Arc<Getting>>>>,
}

struct GetState {
    /// The file, here between two runs of the pieces that go.
    file: Option<StoredFile>,
    /// The read's bytes still to go.
    left: u64,
    credit: u64,
    /// A worker sends pieces now.
    busy: bool,
    ended: bool,
}

impl Getting {
    fn grant(self: &Arc<Self>, credit: u32) {
        lock(&self.state).credit += u64::from(credit);
        self.pump();
    }

    /// Sends what the credit takes, on a worker, unless one does already.
    pub(crate) fn pump(self: &Arc<Self>) {
        {
            let mut state = lock(&self.state);
            if state.busy || state.ended {
                return;
            }
            state.busy = true;
        }
        let getting = Arc::clone(self);
        (self.link.spawn)(Box::new(move || getting.send_pieces()));
    }

    fn send_pieces(&self) {
        // a piece's message: its bytes and a few of its own
        let room = (self.piece + 16) as u64;
        loop {
            let (mut file, left) = {
                let mut state = lock(&self.state);
                match state.file.take() {
                    Some(file) if !state.ended && state.credit >= room => (file, state.left),
                    file => {
                        state.file = file;
                        state.busy = false;
                        return;
                    }
                }
            };
            let length = bound(self.piece, left);
            let body = match read_piece(&mut file, length) {
                Ok(body) => body,
                Err(failure) => return self.end(Err(failure)),
            };
            let left = left - length as u64;
            let ended = left == 0 || length == 0;
            if length > 0 {
                // sent under the lock a cancel's end takes, as records' and
                // metrics' are: a piece read while a cancel ended the read
                // never goes after the stream's last frame
                let mut state = lock(&self.state);
                if state.ended {
                    return;
                }
                // the message's bytes, which the client gives back, and not the room:
                // counted apart, the two drift until the stream waits for good
                state.credit -= body.len() as u64;
                (self.link.send)(body);
            }
            if ended {
                return self.end(Ok(Empty {}.encode()));
            }
            let mut state = lock(&self.state);
            state.file = Some(file);
            state.left = left;
        }
    }

    fn end(&self, last: Answered) {
        {
            let mut state = lock(&self.state);
            if std::mem::replace(&mut state.ended, true) {
                return;
            }
            state.file = None;
        }
        if let Some(reads) = self.reads.upgrade() {
            lock(&reads).remove(&self.stream);
        }
        (self.link.finish)(last);
    }

    fn drop_file(&self) {
        let mut state = lock(&self.state);
        state.ended = true;
        state.file = None;
    }
}

/// Begins an upload: its file to write and the client's pieces to come.
pub(crate) fn upload(handles: &Handles, stream: u32, body: &[u8], link: &Link) -> Result<(), Failure> {
    let asked = BlobsWrite::decode(body)?;
    let files = handles.at(asked.handle, &asked.folder)?;
    let upload = options(files.key(&asked.path), &asked).upload()?;
    let state =
        UploadState { upload: Some(upload), pieces: VecDeque::new(), busy: false, cancelled: false, ended: false };
    let uploading = Arc::new(Uploading {
        stream,
        create: asked.create,
        state: Mutex::new(state),
        link: link.clone(),
        uploads: Arc::downgrade(&handles.uploads),
    });
    lock(&handles.uploads).insert(stream, uploading);
    Ok(())
}

/// An upload under way: the client's pieces, written in order on a worker.
pub(crate) struct Uploading {
    stream: u32,
    /// Its last DATA writes only where no file is.
    create: bool,
    state: Mutex<UploadState>,
    link: Link,
    uploads: Weak<Mutex<HashMap<u32, Arc<Uploading>>>>,
}

struct UploadState {
    /// The upload, here while no worker writes its pieces.
    upload: Option<Upload>,
    /// The client's DATA not written yet, and whether each was its last.
    pieces: VecDeque<(Vec<u8>, bool)>,
    /// A worker holds the upload and writes the pieces.
    busy: bool,
    /// The client cancelled: whoever holds the upload lets it go, and then
    /// answers, so that `cancelled` means its bytes are gone.
    cancelled: bool,
    ended: bool,
}

impl Uploading {
    /// A DATA the client sent, its last when `last`: queued, and written in
    /// the order it came on a worker.
    pub(crate) fn piece(self: &Arc<Self>, body: Vec<u8>, last: bool) {
        {
            let mut state = lock(&self.state);
            if state.ended || state.cancelled {
                return;
            }
            state.pieces.push_back((body, last));
            if std::mem::replace(&mut state.busy, true) {
                return;
            }
        }
        let uploading = Arc::clone(self);
        (self.link.spawn)(Box::new(move || uploading.write_pieces()));
    }

    /// Ends the upload with its bytes removed: here, or by the worker that
    /// writes a piece once it is written. A last piece the worker took still
    /// publishes, and the answer says so.
    fn cancel(&self) {
        let upload = {
            let mut state = lock(&self.state);
            state.cancelled = true;
            if state.busy {
                return;
            }
            state.upload.take()
        };
        drop(upload);
        self.end(Err(Failure::cancelled("the client cancelled its upload")));
    }

    fn write_pieces(&self) {
        let Some(mut upload) = lock(&self.state).upload.take() else { return };
        loop {
            let (body, last) = {
                let mut state = lock(&self.state);
                if state.cancelled {
                    drop(state);
                    drop(upload);
                    return self.end(Err(Failure::cancelled("the client cancelled its upload")));
                }
                let Some(next) = state.pieces.pop_front() else {
                    state.upload = Some(upload);
                    state.busy = false;
                    return;
                };
                next
            };
            let length = u32::try_from(body.len()).unwrap_or(u32::MAX);
            let written = if body.is_empty() {
                Ok(())
            } else {
                BlobsPiece::decode(&body).and_then(|piece| upload.take(&piece.bytes).map_err(Failure::from))
            };
            match (written, last) {
                (Err(failure), _) => {
                    drop(upload);
                    return self.end(Err(failure));
                }
                (Ok(()), true) => {
                    let published = upload.publish(self.create).map_err(Failure::from);
                    return self.end(published.map(|info| BlobsWritten { info: info.map(info_of) }.encode()));
                }
                (Ok(()), false) => (self.link.grant)(length),
            }
        }
    }

    fn end(&self, last: Answered) {
        {
            let mut state = lock(&self.state);
            if std::mem::replace(&mut state.ended, true) {
                return;
            }
            state.pieces.clear();
        }
        if let Some(uploads) = self.uploads.upgrade() {
            lock(&uploads).remove(&self.stream);
        }
        (self.link.finish)(last);
    }
}

#[cfg(test)]
#[path = "blobs_tests.rs"]
mod tests;