tinystore 0.4.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
//! Workers: handlers and their answers, retries, leases, limits and steps.

use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex, mpsc};
use std::thread;
use std::time::{Duration, Instant};

use serde::{Deserialize, Serialize};

use super::fixture::{HOUR, MINUTE, SECOND, fixture};
use super::{Concurrency, Run, State};
use crate::{ErrorKind, Result};

#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
struct Push {
    user: i64,
}

fn eventually(condition: impl Fn() -> bool) {
    crate::testing::holds_within(crate::testing::PATIENCE, "the condition", condition);
}

/// The leases the queue's file holds: the jobs claimed and not yet settled.
fn leases<V>(queue: &super::Queue<V>) -> i64 {
    let count =
        |c: &rusqlite::Connection| c.query_row("select count(*) from _tinystore_jobs_leases", [], |row| row.get(0));
    queue.jobs.file().read(|c| count(c).map_err(|error| crate::sqlite::sql_error("the leases", error))).unwrap()
}

// contract: JOB-07
#[test]
fn a_handler_settles_its_job_by_what_it_returns() {
    let f = fixture();
    let pushes = f.store.queue::<Push>("pushes").attempts(5).open().unwrap();
    for (id, user) in [("done", 1), ("error", 2), ("retry", 3), ("snooze", 4), ("fail", 5)] {
        pushes.id(id).add(&Push { user }).unwrap();
    }
    pushes
        .run_due(|push: Push, run: &Run| -> Result<super::Outcome, String> {
            match push.user {
                1 => Ok(().into()),
                2 => Err("the provider is down".into()),
                3 => Ok(run.retry(10 * MINUTE)),
                4 => Ok(run.snooze(10 * MINUTE)),
                _ => Ok(run.fail("the provider no longer knows the token")),
            }
        })
        .unwrap();

    assert!(pushes.get("done").unwrap().is_none());
    let error = pushes.get("error").unwrap().unwrap();
    assert_eq!((error.state, error.attempt), (State::Scheduled, 1));
    assert_eq!(error.error.as_deref(), Some("the provider is down"));
    let retry = pushes.get("retry").unwrap().unwrap();
    assert_eq!((retry.at, retry.attempt), (f.now() + 10 * MINUTE, 1), "a retry counts its run");
    let snooze = pushes.get("snooze").unwrap().unwrap();
    assert_eq!((snooze.at, snooze.attempt), (f.now() + 10 * MINUTE, 0), "a snooze does not");
    let fail = pushes.get("fail").unwrap().unwrap();
    assert_eq!((fail.state, fail.error.as_deref()), (State::Failed, Some("the provider no longer knows the token")));
}

// contract: JOB-07
#[test]
fn a_retry_waits_longer_each_time_then_fails_for_good() {
    let f = fixture();
    let emails = f.store.queue::<Push>("emails").attempts(4).backoff(SECOND, Duration::from_secs(4)).open().unwrap();
    emails.id("welcome").add(&Push { user: 1 }).unwrap();
    let mut waits = Vec::new();
    for _ in 0..4 {
        emails.run_due(|_: Push, _run| -> Result<(), &str> { Err("bounced") }).unwrap();
        let job = emails.get("welcome").unwrap().unwrap();
        if job.state == State::Failed {
            break;
        }
        waits.push(job.at.duration_since(f.now()).unwrap());
        f.clock.advance(job.at.duration_since(f.now()).unwrap());
    }
    let millis: Vec<u128> = waits.iter().map(Duration::as_millis).collect();
    for (wait, expected) in millis.iter().zip([1000u128, 2000, 4000]) {
        assert!((expected * 9 / 10..=expected * 11 / 10 + 1).contains(wait), "{millis:?}");
    }
    let failed = emails.get("welcome").unwrap().unwrap();
    assert_eq!((failed.state, failed.attempt), (State::Failed, 4));
}

#[test]
fn a_panic_is_an_error_with_its_message() {
    let f = fixture();
    let pushes = f.store.queue::<Push>("pushes").attempts(1).open().unwrap();
    pushes.id("p").add(&Push { user: 1 }).unwrap();
    pushes.run_due(|_: Push, _run| -> Result<()> { panic!("a bug") }).unwrap();
    let failed = pushes.get("p").unwrap().unwrap();
    assert_eq!(failed.error.as_deref(), Some("the handler panicked: a bug"));
}

// contract: JOB-07
#[test]
fn a_job_that_kills_its_process_fails_after_its_attempts() {
    let mut f = fixture();
    for _ in 0..3 {
        let pushes = f.store.queue::<Push>("pushes").attempts(3).open().unwrap();
        if pushes.get("deadly").unwrap().is_none() {
            pushes.id("deadly").add(&Push { user: 1 }).unwrap();
        }
        let claimed = pushes.claim().unwrap().expect("the job is due again at once");
        std::mem::forget(claimed); // the process dies with the job in hand
        f.reopen();
    }
    let pushes = f.store.queue::<Push>("pushes").attempts(3).open().unwrap();
    assert!(pushes.claim().unwrap().is_none(), "a fourth attempt is past its three");
    let failed = pushes.get("deadly").unwrap().unwrap();
    assert_eq!(failed.state, State::Failed);
    assert!(failed.error.unwrap().contains("each of its 3 attempts ended without a settlement"));
}

// contract: JOB-07
#[test]
fn a_repeating_job_that_kills_its_process_each_attempt_goes_on_at_its_next_time() {
    let mut f = fixture();
    let open = |store: &crate::Store| store.queue::<Push>("digests").attempts(2).open().unwrap();
    open(&f.store).id("nightly").every(HOUR).set(&Push { user: 1 }).unwrap();
    f.clock.advance(HOUR);
    for _ in 0..2 {
        let claimed = open(&f.store).claim().unwrap().expect("the job is due again at once");
        std::mem::forget(claimed); // the process dies with the job in hand
        f.reopen();
    }
    let digests = open(&f.store);
    assert!(digests.claim().unwrap().is_none(), "a third attempt is past its two, and its next run is later");
    let job = digests.get("nightly").unwrap().unwrap();
    assert_eq!((job.state, job.attempt), (State::Scheduled, 0), "the repeat goes on");
    assert!(job.at > f.now());
    assert!(job.error.unwrap().contains("each of its 2 attempts ended without a settlement"));
}

// contract: JOB-05
#[test]
fn a_job_whose_lease_ended_runs_again_and_its_stale_lease_settles_nothing() {
    let f = fixture();
    let pushes = f.store.queue::<Push>("pushes").timeout(MINUTE).open().unwrap();
    pushes.id("p").add(&Push { user: 1 }).unwrap();
    let first = pushes.claim().unwrap().unwrap();
    assert!(pushes.claim().unwrap().is_none(), "a live lease holds it");
    f.clock.advance(MINUTE);
    let second = pushes.claim().unwrap().unwrap();
    assert_eq!(second.run().attempt(), 2, "the attempt whose lease ended counts");
    assert_eq!(first.settle(()).unwrap_err().kind(), ErrorKind::Conflict);
    second.settle(()).unwrap();
    assert!(pushes.get("p").unwrap().is_none());
}

// contract: JOB-05
#[test]
fn a_change_after_a_lease_ended_runs_and_the_stale_lease_settles_nothing() {
    let f = fixture();
    let drafts = f.store.queue::<Push>("drafts").timeout(MINUTE).open().unwrap();
    let due = f.now();
    for (change, attempt) in [("update", 2), ("set", 1)] {
        drafts.id(change).at(due).add(&Push { user: 1 }).unwrap();
        let stale = drafts.claim().unwrap().unwrap();
        f.clock.advance(MINUTE);
        match change {
            "update" => assert!(drafts.id(change).update(&Push { user: 2 }).unwrap(), "it has not started again"),
            _ => drafts.id(change).at(due).set(&Push { user: 2 }).unwrap(),
        }
        assert_eq!(
            stale.settle(()).unwrap_err().kind(),
            ErrorKind::Conflict,
            "{change}: the stale lease settles nothing"
        );
        let next = drafts.claim().unwrap().expect("the changed job runs");
        assert_eq!((next.value.user, next.run().attempt()), (2, attempt), "{change}");
        next.settle(()).unwrap();
    }
}

// contract: JOB-05
#[test]
fn a_stale_lease_of_a_job_a_claim_parked_since_settles_nothing() {
    let f = fixture();
    let refreshes = f.store.queue::<Push>("refreshes").timeout(MINUTE).open().unwrap();
    refreshes.id("a").add(&Push { user: 1 }).unwrap();
    let stale = refreshes.claim().unwrap().unwrap();
    f.clock.advance(MINUTE);
    // as a claim parks a due job whose group is full: its row and its ended lease move together
    let (queue, next, id) = (refreshes.state.id, stale.run().lease.next, stale.run().lease.id);
    let park = |from: i64, to: i64| {
        refreshes.jobs.file().transaction(|tx| super::rows::move_to(tx, queue, (from, id, Some("a")), to)).unwrap();
    };
    park(next, next + super::rows::PARKED_BY);
    assert_eq!(stale.settle(()).unwrap_err().kind(), ErrorKind::Conflict);
    park(next + super::rows::PARKED_BY, next);
    let claimed = refreshes.claim().unwrap().unwrap();
    assert_eq!(claimed.run().attempt(), 2, "the stale settlement wrote nothing: its attempt still counts");
}

// contract: JOB-11
#[test]
fn a_worker_runs_jobs_on_the_stores_threads_until_it_stops() {
    let f = fixture();
    let pushes = f.store.queue::<Push>("pushes").concurrency(4).open().unwrap();
    let seen = Arc::new(AtomicUsize::new(0));
    let counted = Arc::clone(&seen);
    let worker = pushes
        .work(move |_: Push, _run| -> Result<()> {
            counted.fetch_add(1, Ordering::SeqCst);
            Ok(())
        })
        .unwrap();
    for user in 0..50 {
        pushes.add(&Push { user }).unwrap();
    }
    eventually(|| seen.load(Ordering::SeqCst) == 50);
    worker.stop();
    pushes.add(&Push { user: 50 }).unwrap();
    thread::sleep(Duration::from_millis(50));
    assert_eq!(seen.load(Ordering::SeqCst), 50, "a stopped worker takes nothing more");
}

// contract: JOB-11
#[test]
fn a_stopping_worker_waits_for_its_handlers_and_gives_back_what_it_had_not_started() {
    let f = fixture();
    let pushes = f.store.queue::<Push>("pushes").open().unwrap();
    pushes.id("first").add(&Push { user: 1 }).unwrap();
    pushes.id("second").add(&Push { user: 2 }).unwrap();
    let (started, wait) = (mpsc::channel(), mpsc::channel::<()>());
    let (started_tx, started_rx) = started;
    let (release_tx, release_rx) = wait;
    let release_rx = Mutex::new(release_rx);
    let worker = pushes
        .work(move |push: Push, _run| -> Result<()> {
            started_tx.send(push.user).unwrap();
            release_rx.lock().unwrap().recv().unwrap();
            Ok(())
        })
        .unwrap();
    assert_eq!(started_rx.recv().unwrap(), 1, "one handler, the second job held for it");
    eventually(|| pushes.get("second").unwrap().is_some_and(|job| job.state == State::Waiting));
    let stopping = thread::spawn(move || worker.stop());
    eventually(|| leases(&pushes) == 1); // the second given back while the first's handler runs
    release_tx.send(()).unwrap();
    stopping.join().unwrap();
    assert!(pushes.get("first").unwrap().is_none(), "the handler under way finished");
    let second = pushes.get("second").unwrap().unwrap();
    assert_eq!((second.state, second.attempt), (State::Waiting, 0), "given back, its attempt not counted");
}

#[test]
fn a_worker_runs_a_job_its_moved_clock_made_due_at_once() {
    let f = fixture();
    let pushes = f.store.queue::<Push>("pushes").open().unwrap();
    let (ran_tx, ran_rx) = mpsc::channel();
    let worker = pushes
        .work(move |push: Push, _run| -> Result<()> {
            ran_tx.send(push.user).unwrap();
            Ok(())
        })
        .unwrap();
    pushes.delay(HOUR).add(&Push { user: 7 }).unwrap();
    assert!(ran_rx.recv_timeout(Duration::from_millis(100)).is_err(), "not before its time");
    f.advance(HOUR);
    let ran = ran_rx.recv_timeout(Duration::from_secs(5));
    assert_eq!(ran, Ok(7), "run once the clock moved, not when the worker's minute of sleep ends");
    worker.stop();
}

#[test]
fn a_stopping_worker_writes_each_answer_as_its_handler_gives_it() {
    let f = fixture();
    let pushes = f.store.queue::<Push>("pushes").open().unwrap();
    pushes.id("fast").add(&Push { user: 1 }).unwrap();
    pushes.id("slow").add(&Push { user: 2 }).unwrap();
    let (started_tx, started_rx) = mpsc::channel();
    let ((fast_tx, fast_rx), (slow_tx, slow_rx)) = (mpsc::channel::<()>(), mpsc::channel::<()>());
    let (fast_rx, slow_rx) = (Mutex::new(fast_rx), Mutex::new(slow_rx));
    let worker = pushes
        .concurrency(2)
        .work(move |push: Push, _run| -> Result<()> {
            started_tx.send(push.user).unwrap();
            let release = if push.user == 1 { &fast_rx } else { &slow_rx };
            release.lock().unwrap().recv().unwrap();
            Ok(())
        })
        .unwrap();
    let mut started = [started_rx.recv().unwrap(), started_rx.recv().unwrap()];
    started.sort_unstable();
    assert_eq!(started, [1, 2], "both run at once");

    let stopping = thread::spawn(move || worker.stop());
    thread::sleep(Duration::from_millis(20));
    fast_tx.send(()).unwrap();
    eventually(|| pushes.get("fast").unwrap().is_none());
    assert!(!stopping.is_finished(), "the slow handler still holds the stop");
    assert_eq!(pushes.get("slow").unwrap().map(|job| job.state), Some(State::Running));
    slow_tx.send(()).unwrap();
    stopping.join().unwrap();
    assert!(pushes.get("slow").unwrap().is_none());
}

#[test]
fn jobs_due_together_are_claimed_and_settled_in_batches() {
    let f = fixture();
    let pushes = f.store.queue::<Push>("pushes").open().unwrap();
    for user in 0..200 {
        pushes.add(&Push { user }).unwrap();
    }
    let before = pushes.jobs.file().commits();
    let ran = pushes.concurrency(8).run_due(|_: Push, _run| -> Result<()> { Ok(()) }).unwrap();
    let commits = pushes.jobs.file().commits() - before;
    assert_eq!(ran, 200);
    assert!(commits < 100, "{commits} commits for 200 jobs");
}

// contract: JOB-09
#[test]
fn a_total_holds_a_queue_to_its_places_across_claims() {
    let f = fixture();
    let videos = f.store.queue::<Push>("videos").concurrency(2).open().unwrap();
    for user in 0..3 {
        videos.add(&Push { user }).unwrap();
    }
    let first = videos.claim().unwrap().unwrap();
    let _second = videos.claim().unwrap().unwrap();
    assert!(videos.claim().unwrap().is_none(), "two places, both taken");
    first.settle(()).unwrap();
    assert!(videos.claim().unwrap().is_some(), "a settlement gives its place back");
}

// contract: JOB-09
#[test]
fn a_group_bounds_its_running_jobs_and_holds_back_no_other_group() {
    let f = fixture();
    let refreshes = f.store.queue::<Push>("refreshes").concurrency(Concurrency::total(10).group(1)).open().unwrap();
    refreshes.group("db:1").add(&Push { user: 1 }).unwrap();
    refreshes.group("db:1").add(&Push { user: 2 }).unwrap();
    refreshes.group("db:2").add(&Push { user: 3 }).unwrap();
    let first = refreshes.claim().unwrap().unwrap();
    let other = refreshes.claim().unwrap().unwrap();
    assert_eq!((first.value.user, other.value.user), (1, 3), "db:1's second waits; db:2 runs");
    assert!(refreshes.claim().unwrap().is_none());
    first.settle(()).unwrap();
    assert_eq!(refreshes.claim().unwrap().unwrap().value.user, 2, "db:1's place went to its next job");
}

// contract: JOB-09
#[test]
fn a_rate_lets_no_more_than_its_count_start_in_a_span() {
    let f = fixture();
    let telegram = f.store.queue::<Push>("telegram").rate(2, SECOND).open().unwrap();
    for user in 0..3 {
        telegram.add(&Push { user }).unwrap();
    }
    let ran = telegram.run_due(|_: Push, _run| -> Result<()> { Ok(()) }).unwrap();
    assert_eq!(ran, 2);
    f.clock.advance(SECOND);
    assert_eq!(telegram.run_due(|_: Push, _run| -> Result<()> { Ok(()) }).unwrap(), 1);
}

// contract: JOB-09
#[test]
fn a_group_rate_lets_each_group_start_its_count_a_span_and_a_group_past_it_holds_back_no_other() {
    let f = fixture();
    let messages = f.store.queue::<Push>("messages").group_rate(2, SECOND).open().unwrap();
    // bot-a's backlog first, then bot-b's: bot-b still sends two in the first second
    for user in 0..5 {
        messages.group("bot-a").add(&Push { user }).unwrap();
    }
    for user in 10..13 {
        messages.group("bot-b").add(&Push { user }).unwrap();
    }
    let sent = std::sync::Mutex::new(Vec::new());
    let send = |push: Push, _run: &Run| -> Result<()> {
        sent.lock().unwrap().push(push.user);
        Ok(())
    };
    let mut seconds = Vec::new();
    for _ in 0..4 {
        messages.run_due(send).unwrap();
        assert_eq!(messages.run_due(send).unwrap(), 0, "nothing more within the second");
        seconds.push(std::mem::take(&mut *sent.lock().unwrap()));
        f.clock.advance(SECOND);
    }
    assert_eq!(seconds, [vec![0, 1, 10, 11], vec![2, 3, 12], vec![4], vec![]]);
}

// contract: JOB-09
#[test]
fn a_worker_claims_no_job_of_a_group_rate_ahead_of_a_free_handler() {
    let f = fixture();
    let messages = f.store.queue::<Push>("messages").group_rate(1, SECOND).open().unwrap();
    messages.group("b").add(&Push { user: 0 }).unwrap();
    messages.group("a").add(&Push { user: 1 }).unwrap();
    messages.group("a").add(&Push { user: 2 }).unwrap();
    let (started_tx, started_rx) = mpsc::channel();
    let (release_tx, release_rx) = mpsc::channel::<()>();
    let release_rx = Mutex::new(release_rx);
    let worker = messages
        .work(move |push: Push, _run| -> Result<()> {
            started_tx.send(push.user).unwrap();
            if push.user == 0 {
                release_rx.lock().unwrap().recv().unwrap();
            }
            Ok(())
        })
        .unwrap();
    assert_eq!(started_rx.recv().unwrap(), 0);
    // a's first job waits for the handler unclaimed, so its start is counted when it starts
    thread::sleep(Duration::from_millis(100));
    assert_eq!(leases(&messages), 1, "only the job running holds a lease");
    f.advance(SECOND);
    release_tx.send(()).unwrap();
    assert_eq!(started_rx.recv_timeout(Duration::from_secs(5)), Ok(1));
    assert!(started_rx.recv_timeout(Duration::from_millis(200)).is_err(), "a's second waits a second after its first");
    f.advance(SECOND);
    assert_eq!(started_rx.recv_timeout(Duration::from_secs(5)), Ok(2));
    worker.stop();
}

// contract: JOB-09
#[test]
fn a_group_rate_and_a_group_bound_hold_together_and_the_queues_rate_over_both() {
    let f = fixture();
    let bounded = Concurrency::total(10).group(1);
    let calls =
        f.store.queue::<Push>("calls").concurrency(bounded).group_rate(1, SECOND).rate(3, SECOND).open().unwrap();
    for (group, user) in [("a", 1), ("a", 2), ("b", 3), ("c", 4), ("d", 5)] {
        calls.group(group).add(&Push { user }).unwrap();
    }
    let mut claimed = Vec::new();
    while let Some(job) = calls.claim().unwrap() {
        claimed.push(job);
    }
    let users: Vec<i64> = claimed.iter().map(|job| job.value.user).collect();
    assert_eq!(users, [1, 3, 4], "a's second waits for its group, and d for the queue's rate");
    claimed.remove(0).settle(()).unwrap();
    assert!(calls.claim().unwrap().is_none(), "a's place is free, and its rate and the queue's are not");
    f.clock.advance(SECOND);
    let next: Vec<i64> = std::iter::from_fn(|| calls.claim().unwrap()).map(|job| job.value.user).collect();
    assert_eq!(next, [2, 5]);
}

// contract: JOB-06
#[test]
fn a_step_runs_once_across_the_attempts_of_a_run() {
    let f = fixture();
    let agents = f.store.queue::<Push>("agents").backoff(SECOND, SECOND * 2).open().unwrap();
    agents.id("question").add(&Push { user: 1 }).unwrap();
    let searches = AtomicUsize::new(0);
    let answer = |_: Push, run: &Run| -> Result<()> {
        let found: Vec<String> = run.step("search", || -> Result<Vec<String>> {
            searches.fetch_add(1, Ordering::SeqCst);
            Ok(vec!["a hit".to_owned()])
        })?;
        assert_eq!(found, ["a hit"]);
        if run.attempt() == 1 {
            return Err(crate::Error::invalid("the model timed out"));
        }
        Ok(())
    };
    agents.run_due(answer).unwrap();
    f.clock.advance(HOUR);
    agents.run_due(answer).unwrap();
    assert_eq!(searches.load(Ordering::SeqCst), 1, "the retry got the search back");
    assert!(agents.get("question").unwrap().is_none());
}

// contract: JOB-09
#[test]
fn a_job_cancelled_while_it_runs_gives_its_groups_place_to_the_next() {
    let f = fixture();
    let refreshes = f.store.queue::<Push>("refreshes").concurrency(Concurrency::default().group(1)).open().unwrap();
    refreshes.id("a").group("db:1").add(&Push { user: 1 }).unwrap();
    refreshes.id("b").group("db:1").add(&Push { user: 2 }).unwrap();
    let first = refreshes.claim().unwrap().unwrap();
    assert!(refreshes.claim().unwrap().is_none(), "b is parked behind a");
    assert!(refreshes.cancel("a").unwrap());
    assert_eq!(first.settle(()).unwrap_err().kind(), ErrorKind::Conflict, "a cancelled job settles nothing");
    assert_eq!(refreshes.claim().unwrap().unwrap().value.user, 2);
}

#[test]
fn a_run_that_ends_takes_its_steps_along_and_a_repeats_next_run_starts_without_them() {
    let f = fixture();
    let digests = f.store.queue::<Push>("digests").open().unwrap();
    digests.id("user:1").every(HOUR).set(&Push { user: 1 }).unwrap();
    let steps = AtomicUsize::new(0);
    let digest = |_: Push, run: &Run| -> Result<()> {
        run.step("gather", || -> Result<()> {
            steps.fetch_add(1, Ordering::SeqCst);
            Ok(())
        })
    };
    for _ in 0..2 {
        f.clock.advance(HOUR);
        assert_eq!(digests.run_due(digest).unwrap(), 1);
    }
    assert_eq!(steps.load(Ordering::SeqCst), 2, "each run of the repeat ran its step");
}

#[test]
fn an_update_of_a_parked_job_gives_it_back_its_time() {
    let f = fixture();
    let refreshes = f.store.queue::<Push>("refreshes").concurrency(Concurrency::default().group(1)).open().unwrap();
    refreshes.id("a").group("db:1").add(&Push { user: 1 }).unwrap();
    refreshes.id("b").group("db:1").add(&Push { user: 2 }).unwrap();
    let _running = refreshes.claim().unwrap().unwrap();
    assert!(refreshes.claim().unwrap().is_none(), "b is parked behind a");
    assert!(refreshes.update("b", &Push { user: 3 }).unwrap());
    let b = refreshes.get("b").unwrap().unwrap();
    assert_eq!((b.at, b.state, b.value.user), (f.now(), State::Waiting, 3));
}

#[test]
fn a_worker_its_program_let_go_of_still_stops_when_the_store_closes() {
    let f = fixture();
    let pushes = f.store.queue::<Push>("pushes").open().unwrap();
    let seen = Arc::new(AtomicUsize::new(0));
    let counted = Arc::clone(&seen);
    let worker = pushes.work(move |_: Push, _run| -> Result<()> {
        counted.fetch_add(1, Ordering::SeqCst);
        Ok(())
    });
    drop(worker.unwrap());
    pushes.add(&Push { user: 1 }).unwrap();
    eventually(|| seen.load(Ordering::SeqCst) == 1);
    let closing = Instant::now();
    f.store.close().unwrap();
    assert!(closing.elapsed() < Duration::from_secs(5), "{:?}", closing.elapsed());
}

// contract: JOB-06
#[test]
fn a_set_while_its_job_runs_starts_a_run_of_its_own_after_a_retry_or_a_snooze() {
    let f = fixture();
    let invoices = f.store.queue::<Push>("invoices").open().unwrap();
    for id in ["retried", "snoozed"] {
        invoices.id(id).add(&Push { user: 100 }).unwrap();
        let claimed = invoices.claim().unwrap().unwrap();
        let charged: i64 = claimed.run().step("charge", || -> Result<i64> { Ok(100) }).unwrap();
        assert_eq!(charged, 100);
        invoices.id(id).delay(HOUR).set(&Push { user: 120 }).unwrap();
        let run = claimed.run();
        let outcome = if id == "retried" { run.retry(MINUTE) } else { run.snooze(MINUTE) };
        claimed.settle(outcome).unwrap();
        let job = invoices.get(id).unwrap().unwrap();
        assert_eq!((job.at, job.attempt, job.value.user), (f.now() + HOUR, 0, 120), "{id}: the set's run, at its time");

        f.clock.advance(HOUR);
        let claimed = invoices.claim().unwrap().unwrap();
        let user = claimed.value.user;
        let charged: i64 = claimed.run().step("charge", || -> Result<i64> { Ok(user) }).unwrap();
        assert_eq!(charged, 120, "{id}: the run before kept no answer for the set's value");
        claimed.settle(()).unwrap();
    }
}

// contract: JOB-01
#[test]
fn a_set_of_a_job_a_stopping_worker_gives_back_waits_for_the_sets_time() {
    let f = fixture();
    let pushes = f.store.queue::<Push>("pushes").open().unwrap();
    pushes.id("first").add(&Push { user: 1 }).unwrap();
    pushes.id("second").add(&Push { user: 2 }).unwrap();
    let (started_tx, started_rx) = mpsc::channel();
    let (release_tx, release_rx) = mpsc::channel::<()>();
    let release_rx = Mutex::new(release_rx);
    let worker = pushes
        .work(move |push: Push, _run| -> Result<()> {
            started_tx.send(push.user).unwrap();
            release_rx.lock().unwrap().recv().unwrap();
            Ok(())
        })
        .unwrap();
    assert_eq!(started_rx.recv().unwrap(), 1, "one handler, the second job held for it");
    eventually(|| leases(&pushes) == 2);
    pushes.id("second").delay(HOUR).set(&Push { user: 3 }).unwrap();
    let stopping = thread::spawn(move || worker.stop());
    eventually(|| leases(&pushes) == 1); // the second given back while the first's handler runs
    release_tx.send(()).unwrap();
    stopping.join().unwrap();
    let second = pushes.get("second").unwrap().unwrap();
    assert_eq!((second.state, second.at, second.value.user), (State::Scheduled, f.now() + HOUR, 3));
}

#[cfg(feature = "replication")]
#[test]
fn a_commit_a_copy_applied_leaves_the_queues_open_here_as_they_were() {
    let f = fixture();
    let emails = f.store.queue::<Push>("emails").attempts(5).open().unwrap();
    let (ran_tx, ran_rx) = mpsc::channel();
    let worker = emails
        .work(move |push: Push, _run| -> Result<()> {
            ran_tx.send(push.user).unwrap();
            Ok(())
        })
        .unwrap();
    emails.add(&Push { user: 1 }).unwrap();
    assert_eq!(ran_rx.recv_timeout(Duration::from_secs(5)), Ok(1), "the worker ran its first job, and sleeps");
    for file in ["kv.db", "jobs.db"] {
        f.store.applied(file);
        let refused = f.store.queue::<Push>("emails").attempts(3).open().unwrap_err();
        assert_eq!(refused.kind(), ErrorKind::Invalid, "{file}: the queue is still open here with 5 attempts");
        let again = f.store.queue::<Push>("emails").attempts(5).open().unwrap();
        again.add(&Push { user: 2 }).unwrap();
        let ran = ran_rx.recv_timeout(Duration::from_secs(5));
        assert_eq!(ran, Ok(2), "{file}: an add through a handle opened since wakes the worker");
    }
    worker.stop();
}

#[cfg(feature = "replication")]
#[test]
fn a_queue_its_file_registers_otherwise_after_a_commit_is_read_again_at_its_next_open() {
    let f = fixture();
    let emails = f.store.queue::<Push>("emails").open().unwrap();
    let renumber = "update _tinystore_jobs_queues set id = id + 100 where name = 'emails'";
    let file = emails.jobs.file();
    file.transaction(|tx| tx.execute(renumber, []).map_err(|error| crate::sqlite::sql_error("a test", error))).unwrap();
    f.store.applied("jobs.db");
    let again = f.store.queue::<Push>("emails").open().unwrap();
    assert_eq!(again.state.id, emails.state.id + 100, "a copy taken again from another home");
}