tinystore 0.12.0

A small storage runtime for applications on SQLite: SQL, key-value state, durable jobs, files, search, logs and metrics in one directory
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
//! A queue's awaited writes and reads, its claims, its watch and its walk,
//! each against the blocking call on the same store.

use std::pin::pin;
use std::sync::mpsc;
use std::task::{Context, Waker};
use std::thread;

use super::super::fixture::{Draft, HOUR, draft, eventually, fixture, next};
use super::*;
use crate::jobs::State;
use crate::testing::{PATIENCE, holds_within};

/// A draft past 512 bytes, which its job keeps in a row of its own.
fn long_draft() -> Draft {
    Draft { chat: 7, text: "a long draft ".repeat(64) }
}

#[tokio::test]
async fn each_call_answers_as_the_blocking_call_does_on_the_same_store() {
    let f = fixture();
    let later = f.store.queue::<Draft>("later").open().unwrap();
    let blocking = later.blocking();

    assert!(later.id("chat:42:1").add(&draft(1)).await.unwrap());
    assert!(!later.id("chat:42:1").add(&draft(2)).await.unwrap(), "an id adds once");
    assert!(!blocking.id("chat:42:1").add(&draft(2)).unwrap(), "and so it does blocking");
    blocking.id("chat:42:2").delay(HOUR).add(&draft(2)).unwrap();
    later.set("chat:42:3", &draft(3)).await.unwrap();
    assert!(later.id("chat:42:2").delay(2 * HOUR).update(&draft(20)).await.unwrap());
    assert!(!later.update("chat:42:9", &draft(9)).await.unwrap(), "no job under the id: nothing to update");

    let job = later.get("chat:42:2").await.unwrap();
    assert_eq!(job, blocking.get("chat:42:2").unwrap());
    let job = job.unwrap();
    assert_eq!((job.value, job.state, job.at), (draft(20), State::Scheduled, f.store.now() + 2 * HOUR));
    assert_eq!(later.get("chat:42:9").await.unwrap(), None);

    let filter = Filter::prefix("chat:42:").limit(2);
    assert_eq!(later.list(&filter).await.unwrap(), blocking.list(&filter).unwrap());
    let mut all = later.all(filter.clone());
    let mut walked = Vec::new();
    while let Some(job) = next(&mut all).await {
        walked.push(job.unwrap());
    }
    let blocking_walk: Vec<Job<Draft>> = blocking.all(filter).map(Result::unwrap).collect();
    assert_eq!(walked, blocking_walk);
    assert_eq!(walked.len(), 3, "two pages of a limit of two");

    assert!(later.cancel("chat:42:3").await.unwrap());
    assert!(!later.cancel("chat:42:3").await.unwrap(), "the job is gone");
    assert_eq!(blocking.get("chat:42:3").unwrap(), None);
    f.store.close().await.unwrap();
}

// contract: JOB-15, JOB-16
#[tokio::test]
async fn a_listed_job_without_an_id_is_cancelled_and_counted_as_blocking() {
    let f = fixture();
    let later = f.store.queue::<Draft>("later").open().unwrap();
    let blocking = later.blocking();
    later.delay(HOUR).add(&draft(1)).await.unwrap();
    later.delay(HOUR).add(&draft(2)).await.unwrap();
    later.add(&draft(3)).await.unwrap();
    let counts = later.counts().await.unwrap();
    assert_eq!(counts, blocking.counts().unwrap());
    assert_eq!((counts.scheduled, counts.waiting, counts.running, counts.failed), (2, 1, 0, 0));

    let page = later.list(&Filter::default()).await.unwrap();
    let first = page.jobs.iter().find(|job| job.value == draft(1)).unwrap();
    assert!(later.cancel(first).await.unwrap());
    assert!(!later.cancel(first).await.unwrap(), "cancelled already");
    let left: Vec<Draft> = blocking.all(Filter::default()).map(|job| job.unwrap().value).collect();
    assert_eq!(left, [draft(3), draft(2)], "the job due at the same time stays");
    f.store.close().await.unwrap();
}

#[tokio::test]
async fn a_call_refused_before_its_write_answers_as_the_blocking_one() {
    let f = fixture();
    let later = f.store.queue::<Draft>("later").open().unwrap();
    let refused = later.id("x").every(HOUR).at(f.store.now()).delay(HOUR).add(&draft(1)).await.unwrap_err();
    let blocking = later.blocking().id("x").every(HOUR).at(f.store.now()).delay(HOUR).add(&draft(1)).unwrap_err();
    assert_eq!((refused.kind(), refused.to_string()), (blocking.kind(), blocking.to_string()));
    let unnamed = later.call().every(HOUR).add(&draft(1)).await.unwrap_err();
    assert_eq!(unnamed.kind(), ErrorKind::Invalid, "a repeat needs an id: {unnamed}");
    f.store.close().await.unwrap();
}

/// Holds jobs.db's writer on a thread of its own until the sender is used or
/// a second passes, so that no commit of the file can end meanwhile.
fn hold_the_writer(queue: &Queue<Draft>) -> (mpsc::Sender<()>, thread::JoinHandle<()>) {
    let (release, held_until) = mpsc::channel::<()>();
    let (holding, held) = mpsc::channel();
    let engine = Arc::clone(&queue.queue.jobs);
    let holder = thread::spawn(move || {
        let _writer = engine.file().hold_writer();
        holding.send(()).unwrap();
        let _ = held_until.recv_timeout(std::time::Duration::from_secs(1));
    });
    held.recv().unwrap();
    (release, holder)
}

// contract: STORE-10
// contract: DUR-04
// contract: DUR-11
#[test]
fn an_add_polled_once_waits_for_no_commit_and_commits_though_its_future_is_dropped() {
    let f = fixture();
    let later = f.store.queue::<Draft>("later").open().unwrap();
    let (release, holder) = hold_the_writer(&later);
    {
        let mut adding = pin!(later.id("held").add(&draft(1)));
        let polled = adding.as_mut().poll(&mut Context::from_waker(Waker::noop()));
        assert!(polled.is_pending(), "the writer is held: the poll returned rather than wait for it");
        let mut cancelling = pin!(later.cancel("another"));
        assert!(cancelling.as_mut().poll(&mut Context::from_waker(Waker::noop())).is_pending());
    }
    release.send(()).unwrap();
    holder.join().unwrap();
    holds_within(PATIENCE, "the add dropped after its poll", || later.blocking().get("held").unwrap().is_some());
    drop(later);
    f.store.blocking().close().unwrap();
}

// contract: DUR-04
// contract: DUR-11
#[tokio::test]
async fn a_write_whose_future_is_never_polled_writes_nothing() {
    let f = fixture();
    let later = f.store.queue::<Draft>("later").open().unwrap();
    later.id("kept").add(&draft(1)).await.unwrap();
    drop(later.id("never").add(&draft(2)));
    drop(later.set("never", &draft(2)));
    drop(later.cancel("kept"));
    later.id("after").add(&draft(3)).await.unwrap();
    assert_eq!(later.get("never").await.unwrap(), None, "no write was polled");
    assert!(later.get("kept").await.unwrap().is_some(), "the cancel was never polled");
    f.store.close().await.unwrap();
}

// contract: STORE-09
#[test]
fn a_get_whose_future_is_dropped_while_it_waits_for_a_reader_stops_at_once() {
    let f = fixture();
    let later = f.store.queue::<Draft>("later").open().unwrap();
    later.blocking().id("a").add(&draft(1)).unwrap();
    let engine = Arc::clone(&later.queue.jobs);
    // Sixteen reads held open take every reader jobs.db opens, and wait for one.
    let gate = Arc::new(std::sync::RwLock::new(()));
    let closed = gate.write().unwrap();
    let holders: Vec<_> = (0..16)
        .map(|_| {
            let (engine, gate) = (Arc::clone(&engine), Arc::clone(&gate));
            thread::spawn(move || {
                engine.file().read(|_| {
                    drop(gate.read().unwrap());
                    Ok(())
                })
            })
        })
        .collect();
    let file = engine.file();
    holds_within(PATIENCE, "every holder reads or waits", || file.readers_open() + file.readers_waiting() == 16);
    let before = file.readers_waiting();
    {
        let mut getting = pin!(later.get("a"));
        assert!(getting.as_mut().poll(&mut Context::from_waker(Waker::noop())).is_pending());
        holds_within(PATIENCE, "the get waits for a reader on the pool", || file.readers_waiting() == before + 1);
    }
    let dropped = std::time::Instant::now();
    holds_within(PATIENCE, "the dropped get left the readers' line", || file.readers_waiting() == before);
    assert!(dropped.elapsed() < std::time::Duration::from_secs(5), "it stopped rather than waited out its patience");
    drop(closed);
    for holder in holders {
        holder.join().unwrap().unwrap();
    }
    drop(later);
    f.store.blocking().close().unwrap();
}

#[tokio::test]
async fn a_claim_and_its_settlement_answer_as_the_blocking_ones_do() {
    let f = fixture();
    let imports = f.store.queue::<Draft>("imports").open().unwrap();
    assert!(imports.claim().await.unwrap().is_none(), "nothing due: none, without waiting");

    imports.id("short").add(&draft(1)).await.unwrap();
    imports.id("long").add(&long_draft()).await.unwrap();
    let short = imports.claim().await.unwrap().unwrap();
    assert_eq!((&short.value, short.run().id(), short.run().attempt()), (&draft(1), Some("short"), 1));
    assert_eq!(imports.get("short").await.unwrap().unwrap().state, State::Running);
    short.settle(()).await.unwrap();
    assert_eq!(imports.get("short").await.unwrap(), None, "done");

    let long = imports.claim().await.unwrap().unwrap();
    assert_eq!(long.value, long_draft(), "a value in a row of its own is read after the claim");
    let later = long.run().retry(HOUR);
    long.settle(later).await.unwrap();
    let job = imports.blocking().get("long").unwrap().unwrap();
    assert_eq!((job.state, job.attempt, job.at), (State::Scheduled, 1, f.store.now() + HOUR));

    imports.id("again").add(&draft(2)).await.unwrap();
    let blocking = imports.blocking().claim().unwrap().unwrap();
    assert_eq!(blocking.value, draft(2));
    assert!(imports.claim().await.unwrap().is_none(), "the blocking claim holds the one job due");
    f.store.close().await.unwrap();
}

// contract: JOB-05
#[tokio::test]
async fn a_settlement_whose_lease_another_claim_took_is_a_conflict_and_changes_nothing() {
    let f = fixture();
    let imports = f.store.queue::<Draft>("imports").timeout(HOUR).open().unwrap();
    imports.id("a").add(&draft(1)).await.unwrap();
    let first = imports.claim().await.unwrap().unwrap();
    f.advance(2 * HOUR);
    let second = imports.claim().await.unwrap().unwrap();
    assert_eq!(second.run().attempt(), 2, "the first lease ended");
    let conflict = first.settle(()).await.unwrap_err();
    assert_eq!(conflict.kind(), ErrorKind::Conflict, "{conflict}");
    assert!(conflict.to_string().contains("jobs queue imports: id \"a\""), "{conflict}");
    assert_eq!(imports.get("a").await.unwrap().unwrap().state, State::Running, "the second claim runs it still");
    second.settle(()).await.unwrap();
    f.store.close().await.unwrap();
}

#[test]
fn a_settlement_polled_once_lets_its_job_go_though_its_future_is_dropped() {
    let f = fixture();
    let imports = f.store.queue::<Draft>("imports").open().unwrap();
    imports.blocking().id("a").add(&draft(1)).unwrap();
    let runtime = tokio::runtime::Builder::new_current_thread().enable_time().build().unwrap();
    let claimed = runtime.block_on(imports.claim()).unwrap().unwrap();
    {
        let mut settling = pin!(claimed.settle(()));
        let _ = settling.as_mut().poll(&mut Context::from_waker(Waker::noop()));
    }
    holds_within(PATIENCE, "the settlement dropped after its poll", || imports.blocking().get("a").unwrap().is_none());
    drop(imports);
    f.store.blocking().close().unwrap();
}

/// A waker that says whether it was woken.
struct Woken(std::sync::atomic::AtomicBool);

impl std::task::Wake for Woken {
    fn wake(self: Arc<Self>) {
        self.0.store(true, std::sync::atomic::Ordering::SeqCst);
    }
}

/// Claims blocking until a claim takes a job, failing the test after its
/// patience: on a clock that stands still, no lease runs out meanwhile.
fn claimed_again(queue: &Queue<Draft>) -> jobs::Claimed<Draft> {
    let mut claimed = None;
    holds_within(PATIENCE, "the job came back", || {
        claimed = queue.blocking().claim().unwrap();
        claimed.is_some()
    });
    claimed.unwrap()
}

// contract: JOB-11
#[test]
fn a_claim_dropped_before_it_answered_gives_its_job_back_uncounted() {
    let f = fixture();
    let imports = f.store.queue::<Draft>("imports").open().unwrap();
    imports.blocking().id("a").add(&draft(1)).unwrap();
    // dropped while its lease waits for the writer, as a select! whose tick came first drops it
    let (release, holder) = hold_the_writer(&imports);
    {
        let mut claiming = pin!(imports.claim());
        assert!(claiming.as_mut().poll(&mut Context::from_waker(Waker::noop())).is_pending());
    }
    release.send(()).unwrap();
    holder.join().unwrap();
    let again = claimed_again(&imports);
    assert_eq!((again.run().id(), again.run().attempt()), (Some("a"), 1), "given back, its attempt not counted");
    again.settle(()).unwrap();

    // dropped once its answer came, which it never took
    imports.blocking().id("b").add(&draft(2)).unwrap();
    let (release, holder) = hold_the_writer(&imports);
    let woken = Arc::new(Woken(std::sync::atomic::AtomicBool::new(false)));
    {
        let waker = Waker::from(Arc::clone(&woken));
        let mut claiming = pin!(imports.claim());
        assert!(claiming.as_mut().poll(&mut Context::from_waker(&waker)).is_pending());
        release.send(()).unwrap();
        holder.join().unwrap();
        holds_within(PATIENCE, "the claim's answer came", || woken.0.load(std::sync::atomic::Ordering::SeqCst));
    }
    let again = claimed_again(&imports);
    assert_eq!((again.run().id(), again.run().attempt()), (Some("b"), 1), "given back, its attempt not counted");
    again.settle(()).unwrap();
    drop(imports);
    f.store.blocking().close().unwrap();
}

// contract: JOB-12
#[tokio::test]
async fn a_claimed_value_that_no_longer_reads_fails_its_job_and_the_claim_takes_the_next() {
    let f = fixture();
    let imports = f.store.queue::<Draft>("imports").open().unwrap();
    let as_text = f.store.queue::<String>("imports").open().unwrap();
    as_text.id("old").add(&"a value of an older type".to_owned()).await.unwrap();
    imports.id("new").add(&draft(1)).await.unwrap();
    let claimed = imports.claim().await.unwrap().unwrap();
    assert_eq!(claimed.run().id(), Some("new"));
    let old = imports.blocking().get("new").unwrap();
    assert_eq!(old.map(|job| job.state), Some(State::Running));
    let failed = as_text.get("old").await.unwrap().unwrap();
    assert_eq!(failed.state, State::Failed);
    assert!(failed.error.unwrap().contains("no longer reads"), "its error says why");
    claimed.settle(()).await.unwrap();
    f.store.close().await.unwrap();
}

// contract: ERR-07, JOB-12
#[tokio::test]
async fn a_walk_yields_a_job_whose_value_no_longer_reads_as_its_error_and_goes_on() {
    let f = fixture();
    let imports = f.store.queue::<Draft>("imports").open().unwrap();
    let as_text = f.store.queue::<String>("imports").open().unwrap();
    imports.id("a").delay(HOUR).add(&draft(1)).await.unwrap();
    as_text.id("b").delay(HOUR).add(&"a value of an older type".to_owned()).await.unwrap();
    imports.id("c").delay(HOUR).add(&draft(3)).await.unwrap();
    let mut all = imports.all(Filter::default());
    let mut walked = Vec::new();
    while let Some(job) = next(&mut all).await {
        walked.push(job.map(|job| job.id).map_err(|error| error.kind()));
    }
    let read = |id: &str| -> std::result::Result<Option<String>, ErrorKind> { Ok(Some(id.to_owned())) };
    assert_eq!(walked, [read("a"), Err(ErrorKind::Corrupt), read("c")], "the walk goes on past it");
    f.store.close().await.unwrap();
}

// contract: JOB-02
#[tokio::test]
async fn a_queue_joins_an_awaited_transaction_through_its_blocking_calls() {
    let f = fixture();
    let later = f.store.queue::<Draft>("later").open().unwrap();
    let queue = later.clone();
    let added = f.store.tx(move |tx| tx.with(&queue).id("in-tx").add(&draft(1))).await.unwrap();
    assert!(added);
    assert!(later.get("in-tx").await.unwrap().is_some(), "it committed with the transaction");

    let queue = later.clone();
    let rolled_back = f
        .store
        .tx(move |tx| -> Result<()> {
            tx.with(&queue).id("rolled-back").add(&draft(2))?;
            Err(crate::Error::invalid("the order was refused"))
        })
        .await;
    assert!(rolled_back.is_err());
    assert_eq!(later.get("rolled-back").await.unwrap(), None, "nothing of a transaction rolled back");
    f.store.close().await.unwrap();
}

#[tokio::test]
async fn from_and_blocking_cross_between_the_two_apis_on_one_queue() {
    let f = fixture();
    let blocking = f.store.blocking().queue::<Draft>("later").open().unwrap();
    let later = Queue::from(blocking.clone());
    blocking.id("written").add(&draft(1)).unwrap();
    assert_eq!(later.get("written").await.unwrap(), blocking.get("written").unwrap());
    assert_eq!(format!("{:?}", later.blocking()), format!("{blocking:?}"));

    let gone = {
        let dir = tempfile::tempdir().unwrap();
        let store = crate::Store::open(dir.path(), crate::Options::default()).unwrap();
        let queue = store.queue::<Draft>("later").open().unwrap();
        store.close().unwrap();
        Queue::from(queue)
    };
    let closed = gone.get("x").await.unwrap_err();
    assert_eq!(closed.kind(), ErrorKind::Closed, "{closed}");
    let closed = gone.id("x").add(&draft(1)).await.unwrap_err();
    assert_eq!(closed.kind(), ErrorKind::Closed, "{closed}");
    f.store.close().await.unwrap();
}

#[tokio::test]
async fn a_watch_yields_the_job_each_time_it_changes_and_ends_with_it() {
    let f = fixture();
    let pushes = f.store.queue::<Draft>("pushes").open().unwrap();
    pushes.id("p").delay(HOUR).add(&draft(1)).await.unwrap();
    let mut watch = pushes.watch("p");
    assert_eq!(next(&mut watch).await.unwrap().unwrap().state, State::Scheduled);
    pushes.id("p").at(f.store.now()).update(&draft(2)).await.unwrap();
    assert_eq!(next(&mut watch).await.unwrap().unwrap().state, State::Waiting);
    let claimed = pushes.claim().await.unwrap().unwrap();
    assert_eq!(next(&mut watch).await.unwrap().unwrap().state, State::Running);
    claimed.settle(()).await.unwrap();
    assert_eq!(next(&mut watch).await.unwrap().unwrap().state, State::Done);
    assert!(next(&mut watch).await.is_none(), "it ends with its job");

    pushes.id("q").delay(HOUR).add(&draft(3)).await.unwrap();
    let mut cancelled = pushes.watch("q");
    assert_eq!(next(&mut cancelled).await.unwrap().unwrap().state, State::Scheduled);
    pushes.cancel("q").await.unwrap();
    assert_eq!(next(&mut cancelled).await.unwrap().unwrap().state, State::Cancelled);
    assert!(next(&mut cancelled).await.is_none());
    assert!(next(&mut pushes.watch("nothing")).await.is_none(), "an id with no job yields nothing");
    f.store.close().await.unwrap();
}

#[tokio::test]
async fn a_dropped_watch_stops_watching() {
    let f = fixture();
    let pushes = f.store.queue::<Draft>("pushes").open().unwrap();
    pushes.id("p").delay(HOUR).add(&draft(1)).await.unwrap();
    let mut watch = pushes.watch("p");
    let watchers = || format!("{:?}", pushes.queue.state.watchers);
    assert_eq!(watchers(), "Watchers(0)", "it watches from its first poll");
    next(&mut watch).await.unwrap().unwrap();
    assert_eq!(watchers(), "Watchers(1)");
    drop(watch);
    eventually("the watch gave its place up", || watchers() == "Watchers(0)").await;
    f.store.close().await.unwrap();
}

#[tokio::test]
async fn a_watch_and_a_walk_end_with_closed_when_the_store_closes() {
    let f = fixture();
    let pushes = f.store.queue::<Draft>("pushes").open().unwrap();
    for chat in [1, 2] {
        pushes.id(format!("chat:{chat}")).delay(HOUR).add(&draft(chat)).await.unwrap();
    }
    let mut watch = pushes.watch("chat:1");
    assert_eq!(next(&mut watch).await.unwrap().unwrap().state, State::Scheduled);
    let mut all = pushes.all(Filter::prefix("chat:").limit(1));
    assert_eq!(next(&mut all).await.unwrap().unwrap().id.as_deref(), Some("chat:1"));

    f.store.close().await.unwrap();
    let closed = next(&mut watch).await.unwrap().unwrap_err();
    assert_eq!(closed.kind(), ErrorKind::Closed, "{closed}");
    assert!(next(&mut watch).await.is_none(), "the watch ends");
    let closed = next(&mut all).await.unwrap().unwrap_err();
    assert_eq!(closed.kind(), ErrorKind::Closed, "{closed}");
    assert!(next(&mut all).await.is_none(), "the walk ends");
}