tinystore 0.10.0

A small storage runtime for applications on SQLite: SQL, key-value state, durable jobs, files, search, logs and metrics in one directory
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
use std::collections::VecDeque;
use std::fmt;
use std::marker::PhantomData;
use std::sync::Arc;
use std::time::{Duration, SystemTime};

use serde::Serialize;
use serde::de::DeserializeOwned;

use super::call::{Asked, JobCall};
use super::claim::{self, Claiming, Lease};
use super::engine::Jobs;
use super::policy::{Concurrency, Policy};
use super::read::named::Which;
use super::read::{self, Counts, Filter, Job, JobRef, Page};
use super::run::{Outcome, Run};
use super::state::{Kind, QueueState};
use super::work::{self, Worker};
use super::write::{self, Cancelled, Prepared};
use crate::clock::millis;
use crate::engine::Home;
#[cfg(any(feature = "sql", feature = "wire"))]
use crate::engine::SharedFile;
#[cfg(feature = "sql")]
use crate::engine::{LentWrite, Wrote};
use crate::sqlite::Tx as SqlTx;
use crate::{Error, ErrorKind, Result, Store, Transaction};

/// A queue being opened: its name, its type, and how it treats its jobs.
#[must_use = "a queue opens with open()"]
pub struct QueueBuilder<V> {
    home: Home,
    name: String,
    policy: Policy,
    _value: PhantomData<fn() -> V>,
}

impl Store {
    /// A queue of jobs whose values are `V`, as JSON, in the store's jobs.db;
    /// the engine opens with the first queue.
    pub fn queue<V>(&self, name: &str) -> QueueBuilder<V>
    where
        V: Serialize + DeserializeOwned + Send + 'static,
    {
        QueueBuilder::new(Home::Store(self.clone()), name)
    }
}

impl<V> fmt::Debug for QueueBuilder<V> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("QueueBuilder").field("name", &self.name).field("policy", &self.policy).finish()
    }
}

impl<V> QueueBuilder<V>
where
    V: Serialize + DeserializeOwned + Send + 'static,
{
    fn new(home: Home, name: &str) -> Self {
        QueueBuilder { home, name: name.to_owned(), policy: Policy::default(), _value: PhantomData }
    }

    /// A queue kept in a file another engine lends, a database's.
    #[cfg(any(feature = "sql", feature = "wire"))]
    pub(crate) fn in_file(shared: Arc<SharedFile>, name: &str) -> Self {
        QueueBuilder::new(Home::Shared(shared), name)
    }

    /// Runs a job gets before it fails for good, the first counted: 10.
    pub fn attempts(mut self, attempts: u32) -> Self {
        self.policy.attempts = attempts;
        self
    }

    /// The wait before a retry: `initial`, doubling each time up to `max`, a
    /// tenth longer or shorter by the job: 1 s to 1 h.
    pub fn backoff(mut self, initial: Duration, max: Duration) -> Self {
        self.policy.backoff = (initial, max);
        self
    }

    /// How long one run may take before it is told to stop: a minute.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.policy.timeout = timeout;
        self
    }

    /// Jobs running at once across every worker of the store, `8`, or in all
    /// and in each group, `Concurrency::total(8).group(2)`. Without it each
    /// worker runs one at a time.
    pub fn concurrency(mut self, concurrency: impl Into<Concurrency>) -> Self {
        self.policy.concurrency = concurrency.into();
        self
    }

    /// Jobs started in any span of `per`: 30 a second, as an API's limit asks.
    /// It counts starts, retries among them, and lives in memory.
    pub fn rate(mut self, count: u32, per: Duration) -> Self {
        self.policy.rate = Some((count, per));
        self
    }

    /// Jobs of each group started in any span of `per`, beside the queue's
    /// `rate`: each account's own limit at a provider, 2 a second a bot. A
    /// job of a group past it waits for its group's turn, and the other
    /// groups' jobs start meanwhile. It lives in memory, as `rate` does.
    pub fn group_rate(mut self, count: u32, per: Duration) -> Self {
        self.policy.group_rate = Some((count, per));
        self
    }

    /// How long a done job keeps its id taken, so that adding it again adds
    /// nothing: an id runs once.
    pub fn dedupe(mut self, span: Duration) -> Self {
        self.policy.dedupe = Some(span);
        self
    }

    /// How long a failed job stays, with its error, to be found and started
    /// again: a week.
    pub fn keep(mut self, span: Duration) -> Self {
        self.policy.keep = span;
        self
    }

    /// Jobs that may wait; an add past it is a `limit`: ten million.
    pub fn max_waiting(mut self, jobs: u64) -> Self {
        self.policy.max_waiting = jobs;
        self
    }

    pub fn open(self) -> Result<Queue<V>> {
        Queue::open(&self.home, &self.name, Kind::Queue, self.policy)
    }
}

/// Jobs of one type in the order of their time. A handle is cheap to clone
/// and to keep.
pub struct Queue<V> {
    pub(crate) jobs: Arc<Jobs>,
    pub(crate) state: Arc<QueueState>,
    _value: PhantomData<fn() -> V>,
}

impl<V> Clone for Queue<V> {
    fn clone(&self) -> Self {
        Queue { jobs: Arc::clone(&self.jobs), state: Arc::clone(&self.state), _value: PhantomData }
    }
}

impl<V> fmt::Debug for Queue<V> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.state.describe())
    }
}

impl<V> Queue<V>
where
    V: Serialize + DeserializeOwned + Send + 'static,
{
    /// The same queue, its values read as another type: the wire's raw JSON,
    /// or none for an awaited worker, whose loop reads no value.
    #[cfg(any(feature = "wire", feature = "async"))]
    pub(crate) fn retyped<W>(&self) -> Queue<W> {
        Queue { jobs: Arc::clone(&self.jobs), state: Arc::clone(&self.state), _value: PhantomData }
    }

    /// The queue whose state `jobs` holds open.
    #[cfg(feature = "replication")]
    pub(crate) fn of_state(jobs: Arc<Jobs>, state: Arc<QueueState>) -> Queue<V> {
        Queue { jobs, state, _value: PhantomData }
    }

    /// An add, a set or an update, run where the write would run, and whether
    /// it changed a job: a set always does.
    #[cfg(feature = "replication")]
    pub(crate) fn write_asked(&self, change: Change, asked: Asked, value: &V) -> Result<bool> {
        let due = self.write_now(change, asked, value, None)?;
        Ok(change == Change::Set || due.is_some())
    }

    /// Passes a write on a copy of jobs' file to its home.
    #[cfg(feature = "replication")]
    fn pass_on(&self, change: Change, asked: &Asked, value: &V) -> Result<bool> {
        let store = self.jobs.store()?;
        super::forward::pass_on_write(&store, self.passed_as(), change, asked, value)
    }

    /// The queue as a write passed on names it: its name, and the database
    /// whose file keeps it.
    #[cfg(feature = "replication")]
    fn passed_as(&self) -> (&str, Option<&str>) {
        (&self.state.name, self.jobs.lent_by().and_then(crate::replication::database_of))
    }

    pub(crate) fn open(home: &Home, name: &str, kind: Kind, policy: Policy) -> Result<Queue<V>> {
        let jobs = Jobs::at(home)?;
        let state = jobs.queue(name, kind, policy)?;
        Ok(Queue { jobs, state, _value: PhantomData })
    }

    /// The queue `name` where `home` says, as the store holds it, for a
    /// connection that may only read: neither jobs.db, nor jobs' tables in a
    /// database's file, nor the queue is made, and its options are the
    /// writers' to choose.
    #[cfg(feature = "wire")]
    pub(crate) fn open_as_it_is(home: &Home, name: &str) -> Result<Queue<V>> {
        let lent_by = match home {
            Home::Store(_) => None,
            Home::Shared(shared) => Some(shared.owner()),
        };
        let within = |error: Error| error.within(QueueState::described(lent_by, Kind::Queue, name));
        let jobs = Jobs::at_as_it_is(home).map_err(within)?;
        let state = jobs.queue_as_it_is(name)?;
        Ok(Queue { jobs, state, _value: PhantomData })
    }

    /// The queue as this process holds it open now. A handle a connection that
    /// only reads opened before any open here that writes takes that open's
    /// state once there is one, whose leases say what runs and whose watchers
    /// hear each change; any other handle has it already.
    #[cfg(feature = "wire")]
    pub(crate) fn as_open_now(&self) -> Queue<V> {
        let state = self.jobs.open_state(&self.state).unwrap_or_else(|| Arc::clone(&self.state));
        Queue { jobs: Arc::clone(&self.jobs), state, _value: PhantomData }
    }

    /// Adds a job that runs as soon as a worker is free, and returns once it
    /// is on disk. Adds from many callers share a commit.
    pub fn add(&self, value: &V) -> Result<bool> {
        self.add_asked(Asked::default(), value, None)
    }

    /// Makes the job under `id` this value, due now, whatever it was; see
    /// [`JobCall::set`].
    pub fn set(&self, id: impl AsRef<str>, value: &V) -> Result<()> {
        self.set_asked(Asked::with_id(id.as_ref()), value, None)
    }

    /// Gives the job under `id` this value when it is not running, the steps
    /// kept for the old one dropped with it, and says whether it did; see
    /// [`JobCall::update`].
    pub fn update(&self, id: impl AsRef<str>, value: &V) -> Result<bool> {
        self.update_asked(Asked::with_id(id.as_ref()), value, None)
    }

    /// Takes a job, whatever its state, and says whether it was there: the
    /// job under an id, `"welcome-42"`, or a job a page gave, `&job`, by its
    /// id or, for one without, by the row it was listed from. A job retried,
    /// run again for its repeat or cancelled since it was listed is in no
    /// row, and a cancel of it takes nothing, never another job.
    /// A running one's handler is told to stop: `run.stopped()` turns true,
    /// and what it returns settles nothing. A repeating job stops.
    pub fn cancel(&self, job: impl JobRef) -> Result<bool> {
        match job.which() {
            Some(which) => self.cancel_in(&which, None),
            None => Ok(false),
        }
    }

    /// How many jobs the queue holds in each state, from one snapshot; it
    /// reads no value.
    pub fn counts(&self) -> Result<Counts> {
        let now = self.jobs.now();
        self.jobs.file().read(|c| read::counts(c, &self.state, now)).map_err(|error| self.fail(None, error))
    }

    /// A cancel, in `tx` when there is one. Its watchers learn it was a cancel
    /// inside its write, before the commit, so that a watch that reads the job
    /// gone never takes it for done; a cancel that does not commit takes that
    /// back. A job without an id has no watchers.
    pub(crate) fn cancel_in(&self, which: &Which, tx: Option<&Transaction<'_>>) -> Result<bool> {
        #[cfg(feature = "replication")]
        if tx.is_none() && self.jobs.file().is_copy() {
            let store = self.jobs.store().map_err(|error| self.fail_on(which, error))?;
            return super::forward::pass_on_cancel(&store, self.passed_as(), which)
                .map_err(|error| self.fail_on(which, error));
        }
        let work = self.cancel_work(which);
        let written = match tx {
            None => self.jobs.file().write(0, work),
            Some(tx) => self.run_in(tx, work),
        };
        let cancelled = written.map_err(|error| {
            untold(&self.state, which);
            self.fail_on(which, error)
        })?;
        let found = !matches!(cancelled, Cancelled::Nothing);
        let (jobs, state, which) = (Arc::clone(&self.jobs), Arc::clone(&self.state), which.clone());
        let settle = move |committed: bool| cancel_settled(&jobs, &state, &which, cancelled, committed);
        match tx {
            None => settle(true),
            Some(tx) => tx.after(settle),
        }
        Ok(found)
    }

    /// `cancel` without waiting: the write is queued, and `done` is called
    /// with whether there was a job on the thread that commits it.
    #[cfg(any(feature = "wire", feature = "async"))]
    pub(crate) fn cancel_then(&self, which: Which, done: impl FnOnce(Result<bool>) + Send + 'static) {
        #[cfg(feature = "replication")]
        if self.jobs.file().is_copy() {
            let queue = self.clone();
            std::thread::spawn(move || done(queue.cancel_in(&which, None)));
            return;
        }
        let (work, named) = (self.cancel_work(&which), self.named_on(&which));
        let (jobs, state) = (Arc::clone(&self.jobs), Arc::clone(&self.state));
        self.jobs.file().submit(0, work, move |written| match written {
            Ok(cancelled) => {
                cancel_settled(&jobs, &state, &which, cancelled, true);
                done(Ok(!matches!(cancelled, Cancelled::Nothing)));
            }
            Err(error) => {
                untold(&state, &which);
                done(Err(error.within(named)));
            }
        });
    }

    /// The write that cancels the job `which` names, which tells the queue's
    /// watchers inside it.
    fn cancel_work(&self, which: &Which) -> impl FnOnce(&SqlTx<'_>) -> Result<Cancelled> + Send + 'static {
        let (queue, which) = (Arc::clone(&self.state), which.clone());
        move |c: &SqlTx<'_>| match &which {
            Which::Id(key) => {
                let cancelled = write::cancel(c, &queue, key)?;
                queue.watchers.cancelled(key, !matches!(cancelled, Cancelled::Nothing));
                Ok(cancelled)
            }
            Which::Row(row) => write::cancel_row(c, &queue, *row),
        }
    }

    /// Where the job under `id` is: scheduled, waiting and how many jobs are
    /// ahead of it, running and its progress, failed and why, or done while the
    /// queue's dedupe keeps its id; none for an id with no job.
    pub fn get(&self, id: impl AsRef<str>) -> Result<Option<Job<V>>> {
        let (id, now) = (id.as_ref(), self.jobs.now());
        self.jobs.file().read(|c| read::get(c, &self.state, id, now)).map_err(|error| self.fail(Some(id), error))
    }

    /// A page of the queue's jobs; see [`Filter`].
    pub fn list(&self, filter: &Filter) -> Result<Page<V>> {
        let page = self.read_page(filter)?;
        let jobs = page.jobs.into_iter().collect::<Result<Vec<Job<V>>>>()?;
        Ok(Page { jobs, next: page.next })
    }

    /// A page with each job whose value no longer reads as its error, which
    /// names the queue and the job, for a walk to go on past it.
    pub(crate) fn read_page(&self, filter: &Filter) -> Result<read::Listed<V>> {
        let now = self.jobs.now();
        let page = read::page(self.jobs.file(), &self.state, filter, now).map_err(|error| self.fail(None, error))?;
        let jobs = page.jobs.into_iter().map(|job| job.map_err(|error| self.fail(None, error))).collect();
        Ok(read::Listed { jobs, next: page.next })
    }

    /// Every job `filter` names, a page at a time, holding nothing between
    /// pages; a job written during the walk may or may not be met.
    pub fn all(&self, filter: Filter) -> All<V> {
        All { queue: self.clone(), filter: Some(filter), page: VecDeque::new() }
    }

    /// A call on the job with this id; see [`JobCall`].
    pub fn id(&self, id: impl AsRef<str>) -> JobCall<'_, V> {
        JobCall::new(self, None).id(id)
    }

    pub fn at(&self, time: SystemTime) -> JobCall<'_, V> {
        JobCall::new(self, None).at(time)
    }

    pub fn delay(&self, span: Duration) -> JobCall<'_, V> {
        JobCall::new(self, None).delay(span)
    }

    pub fn group(&self, group: impl AsRef<str>) -> JobCall<'_, V> {
        JobCall::new(self, None).group(group)
    }

    /// Runs `handler` on each job as it falls due, on threads the store starts
    /// for it, as many at once as the queue's concurrency lets, one when it
    /// sets none. It returns at once; see [`Worker`].
    ///
    /// The handler gets the job's value and its run. `Ok(())` is done; an
    /// answer of the run's says otherwise; an error retries the job after its
    /// backoff, its text kept as the job's error, and so does a panic.
    pub fn work<F, R, E>(&self, handler: F) -> Result<Worker>
    where
        F: Fn(V, &Run) -> std::result::Result<R, E> + Send + Sync + 'static,
        R: Into<Outcome>,
        E: fmt::Display,
    {
        self.workers(self.state.policy.local()).work(handler)
    }

    /// Runs what is due when it starts and what falls due meanwhile, then
    /// returns how many jobs ran; it never waits for a later job. Tests,
    /// scripts and commands use it.
    pub fn run_due<F, R, E>(&self, handler: F) -> Result<usize>
    where
        F: Fn(V, &Run) -> std::result::Result<R, E> + Sync,
        R: Into<Outcome>,
        E: fmt::Display,
    {
        self.workers(self.state.policy.local()).run_due(handler)
    }

    /// A worker that runs at most `handlers` at once, under the queue's
    /// concurrency.
    pub fn concurrency(&self, handlers: u32) -> Workers<'_, V> {
        self.workers(handlers)
    }

    fn workers(&self, handlers: u32) -> Workers<'_, V> {
        Workers { queue: self, handlers: usize::try_from(handlers).unwrap_or(1) }
    }

    /// Takes the next due job for a loop of the program's own, which settles
    /// it with [`Claimed::settle`]; none when nothing is due. A job not settled
    /// within the queue's timeout goes back to the queue.
    pub fn claim(&self) -> Result<Option<Claimed<V>>> {
        loop {
            let (now, write) = self.claim_one();
            let claimed = self.jobs.file().write(0, write).map_err(|error| self.fail(None, error))?;
            let lease = match took(&self.jobs, &self.state, claimed, now) {
                Took::Job(lease) => lease,
                Took::More => continue,
                Took::Nothing => return Ok(None),
            };
            let run = Run::new(Arc::clone(&lease), Arc::clone(&self.state), Arc::clone(&self.jobs));
            let value = match work::read_value::<V>(&self.jobs, &lease) {
                Ok(value) => value,
                Err(error) if error.kind() == ErrorKind::Invalid => {
                    Claimed { value: (), run }.settle(Outcome::fail_with(error.to_string()))?;
                    continue;
                }
                Err(error) => return Err(self.fail(lease.key.as_deref(), error)),
            };
            if lease.begin(now) {
                self.state.watchers.changed();
                return Ok(Some(Claimed { value, run }));
            }
            // a cancel took it as it was claimed
        }
    }

    /// The write of one claim of a job, and the time it claims at.
    fn claim_one(&self) -> (i64, impl FnOnce(&SqlTx<'_>) -> Result<claim::Claimed> + Send + 'static + use<V>) {
        let now = self.jobs.now();
        let until = now.saturating_add(millis(self.state.policy.timeout));
        let queue = Arc::clone(&self.state);
        (now, move |tx: &SqlTx<'_>| claim::claim(tx, Claiming { queue: &queue, now, until, limit: 1 }))
    }

    /// One claim of `claim` without waiting: the write is queued, and `done`
    /// is called on the thread that commits it with what it took, the lease
    /// held in memory. A spilled value is the caller's to read after, since
    /// the committing thread may lead the commit after this one.
    #[cfg(feature = "async")]
    pub(crate) fn claim_then(&self, done: impl FnOnce(Result<Took>) + Send + 'static) {
        let (now, write) = self.claim_one();
        let (jobs, state, named) = (Arc::clone(&self.jobs), Arc::clone(&self.state), self.named(None));
        self.jobs.file().submit(0, write, move |claimed| {
            done(claimed.map(|claimed| took(&jobs, &state, claimed, now)).map_err(|error| error.within(named)));
        });
    }

    pub(crate) fn add_asked(&self, asked: Asked, value: &V, tx: Option<&Transaction<'_>>) -> Result<bool> {
        Ok(self.write_now(Change::Add, asked, value, tx)?.is_some())
    }

    pub(crate) fn set_asked(&self, asked: Asked, value: &V, tx: Option<&Transaction<'_>>) -> Result<()> {
        self.write_now(Change::Set, asked, value, tx).map(|_| ())
    }

    pub(crate) fn update_asked(&self, asked: Asked, value: &V, tx: Option<&Transaction<'_>>) -> Result<bool> {
        Ok(self.write_now(Change::Update, asked, value, tx)?.is_some())
    }

    /// An add, a set or an update in `tx`, or in a commit of its own that it
    /// waits for. It gives the time the job is due at when the write changed
    /// it, and wakes the queue's workers for that time.
    fn write_now(&self, change: Change, asked: Asked, value: &V, tx: Option<&Transaction<'_>>) -> Result<Option<i64>> {
        let named = self.named(asked.id());
        #[cfg(feature = "replication")]
        if tx.is_none() && self.jobs.file().is_copy() {
            let changed = self.pass_on(change, &asked, value).map_err(|error| error.within(named))?;
            // the home's due time stays there: a copy's workers take nothing
            return Ok(changed.then_some(0));
        }
        let written = || {
            let call = self.prepared(change, asked, value)?;
            let bytes = call.value.len();
            match tx {
                None => self.jobs.file().write(bytes, self.change_of(change, call)),
                Some(tx) => self.run_in(tx, self.change_of(change, call)),
            }
        };
        let due = written().map_err(|error| error.within(named))?;
        if let Some(due) = due {
            self.wake(due, tx);
        }
        Ok(due)
    }

    /// The write of a change, which gives the time the job is due at when it
    /// changed that.
    fn change_of(
        &self,
        change: Change,
        call: Prepared,
    ) -> impl FnOnce(&SqlTx<'_>) -> Result<Option<i64>> + Send + 'static + use<V> {
        writes(Arc::clone(&self.state), change, call)
    }

    /// An add, a set or an update without waiting: the write is queued, and
    /// `done` is called with whether it changed anything, on the thread that
    /// commits it. For a host whose threads must not each wait for a commit:
    /// the writes waiting together are the writes one commit carries.
    #[cfg(feature = "wire")]
    pub(crate) fn write_then(
        &self,
        change: Change,
        asked: Asked,
        value: &V,
        done: impl FnOnce(Result<bool>) + Send + 'static,
    ) {
        self.writing(change, asked, value).submit(done);
    }

    /// An add, a set or an update checked and its value encoded now, to queue
    /// at the writer later with [`Writing::submit`].
    #[cfg(any(feature = "wire", feature = "async"))]
    pub(crate) fn writing(&self, change: Change, asked: Asked, value: &V) -> Writing {
        let named = self.named(asked.id());
        let (jobs, state) = (Arc::clone(&self.jobs), Arc::clone(&self.state));
        #[cfg(feature = "replication")]
        if self.jobs.file().is_copy() {
            let json =
                serde_json::to_value(value).map_err(|error| Error::invalid(format!("a job that is no JSON: {error}")));
            return Writing { jobs, state, change, named, ready: Ready::Passed(asked, json) };
        }
        Writing { jobs, state, change, named, ready: Ready::Here(self.prepared(change, asked, value)) }
    }

    /// An add, a set or an update for a batch of the file the queue is kept
    /// in, which runs it in its savepoint: the call checked and its value
    /// encoded now, the queue's workers woken once the batch's commit is
    /// durable. Its errors name the queue as a part of the batch's file.
    #[cfg(feature = "sql")]
    pub(crate) fn lent(&self, change: Change, asked: Asked, value: &V) -> Result<LentWrite> {
        let describe = match asked.id() {
            Some(id) => format!("{}: id {id:?}", self.state.describe_alone()),
            None => self.state.describe_alone(),
        };
        let call = self.prepared(change, asked, value).map_err(|error| error.within(describe.clone()))?;
        let (weight, write, state) = (call.value.len(), self.change_of(change, call), Arc::clone(&self.state));
        Ok(LentWrite {
            file: Arc::clone(self.jobs.shared_file()),
            place: self.jobs.place().to_owned(),
            describe,
            weight,
            write: Box::new(move |tx| {
                let due = write(tx)?;
                let wake = due.map(|at| Box::new(move || state.wake(at)) as Box<dyn FnOnce() + Send>);
                let changes = u64::from(change == Change::Set || due.is_some());
                Ok(Wrote { changes, committed: wake, before_answer: None })
            }),
        })
    }

    /// A call checked, its value encoded, before its write waits for the writer.
    fn prepared(&self, change: Change, asked: Asked, value: &V) -> Result<Prepared> {
        match (change, asked.id()) {
            (Change::Set, None) => return Err(Error::invalid("a set needs an id, which names the job it sets")),
            (Change::Update, None) => {
                return Err(Error::invalid("an update needs an id, which names the job it changes"));
            }
            _ => {}
        }
        asked.prepare(value, self.jobs.now())
    }

    /// Runs a write of the queue in a savepoint of `tx`, once the queue is
    /// kept in the transaction's file.
    pub(crate) fn run_in<T>(&self, tx: &Transaction<'_>, work: impl FnOnce(&SqlTx<'_>) -> Result<T>) -> Result<T> {
        tx.takes(self.jobs.file(), self.jobs.place())?;
        tx.call(work)
    }

    /// Wakes the queue's workers and watchers for a job due at `at`, at once,
    /// or once the transaction it was written in ends: a worker woken before
    /// the commit would not find the job, and sleep past it.
    fn wake(&self, at: i64, tx: Option<&Transaction<'_>>) {
        let state = Arc::clone(&self.state);
        let wake = move |_committed: bool| state.wake(at);
        match tx {
            None => wake(true),
            Some(tx) => tx.after(wake),
        }
    }

    /// Names the queue and the id a call failed on.
    pub(crate) fn fail(&self, id: Option<&str>, error: Error) -> Error {
        error.within(self.named(id))
    }

    /// The queue and the id of a call, as its error says them first.
    fn named(&self, id: Option<&str>) -> String {
        match id {
            Some(id) => format!("{}: id {id:?}", self.state.describe()),
            None => self.state.describe(),
        }
    }

    /// Names the queue and the job a cancel failed on.
    pub(crate) fn fail_on(&self, which: &Which, error: Error) -> Error {
        error.within(self.named_on(which))
    }

    fn named_on(&self, which: &Which) -> String {
        format!("{}: {}", self.state.describe(), which.describe())
    }
}

/// What a job's call writes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Change {
    Add,
    Set,
    Update,
}

/// The write of a change in `queue`, which gives the time the job is due at
/// when it changed that.
fn writes(
    queue: Arc<QueueState>,
    change: Change,
    call: Prepared,
) -> impl FnOnce(&SqlTx<'_>) -> Result<Option<i64>> + Send + 'static {
    move |c| match change {
        Change::Add => Ok(write::add(c, &queue, &call)?.then_some(call.at)),
        Change::Set => write::set(c, &queue, &call).map(|set| Some(set.due)),
        Change::Update => write::update(c, &queue, &call),
    }
}

/// An add, a set or an update whose call was checked and whose value was
/// encoded when it was made, queued at the writer by [`Writing::submit`]:
/// the wire's call submits it at once, an awaited one at its future's first
/// poll, which owns it meanwhile.
#[cfg(any(feature = "wire", feature = "async"))]
pub(crate) struct Writing {
    jobs: Arc<Jobs>,
    state: Arc<QueueState>,
    change: Change,
    /// The queue and the id, as the write's error names them.
    named: String,
    ready: Ready,
}

#[cfg(any(feature = "wire", feature = "async"))]
enum Ready {
    /// The call checked and its value encoded, or why it was refused.
    Here(Result<Prepared>),
    /// On a copy of the queue's file: the call and its value as JSON, which
    /// its home writes.
    #[cfg(feature = "replication")]
    Passed(Asked, Result<serde_json::Value>),
}

#[cfg(any(feature = "wire", feature = "async"))]
impl Writing {
    /// Queues the write, and calls `done` with whether it changed a job, on
    /// the thread that commits it; a write refused before it is queued is
    /// answered here. A copy passes it to its home on a thread of its own,
    /// which waits for the home's answer.
    pub(crate) fn submit(self, done: impl FnOnce(Result<bool>) + Send + 'static) {
        let Writing { jobs, state, change, named, ready } = self;
        let call = match ready {
            Ready::Here(Ok(call)) => call,
            Ready::Here(Err(error)) => return done(Err(error.within(named))),
            #[cfg(feature = "replication")]
            Ready::Passed(asked, json) => {
                let queue = Queue::<serde_json::Value>::of_state(jobs, state);
                std::thread::spawn(move || {
                    let written = json.and_then(|json| queue.pass_on(change, &asked, &json));
                    done(written.map_err(|error| error.within(named)));
                });
                return;
            }
        };
        let bytes = call.value.len();
        let write = writes(Arc::clone(&state), change, call);
        jobs.file().submit(bytes, write, move |due| {
            if let Ok(Some(at)) = due {
                state.wake(at);
            }
            done(due.map(|due| due.is_some()).map_err(|error| error.within(named)));
        });
    }
}

/// What one claim of a job for a loop of the program's own took.
pub(crate) enum Took {
    /// A job, its lease held in memory, its value still to read.
    Job(Arc<Lease>),
    /// No job, but the claim ended jobs whose attempts were all spent, or
    /// parked as many as it may: another claim may find one.
    More,
    Nothing,
}

/// Follows in memory what a claim's write took: the jobs it failed for good,
/// how late it took them, and the lease it holds.
fn took(jobs: &Jobs, state: &QueueState, claimed: claim::Claimed, now: i64) -> Took {
    for _ in 0..claimed.failed {
        state.failures.observe(&state.name, "its attempts ended without a settlement");
    }
    jobs.measure_claims(&state.name, &claimed.leases, now);
    if let Some(lease) = claimed.leases.into_iter().next() {
        let lease = Arc::new(lease);
        state.hold(&lease);
        return Took::Job(lease);
    }
    if claimed.abandoned.is_empty() && !claimed.more { Took::Nothing } else { Took::More }
}

/// What follows a cancel's write: a cancel that did not commit takes back what
/// it told the job's watchers, and one that did stops the job's handler, when
/// it runs here, and tells the watchers of the change.
fn cancel_settled(jobs: &Jobs, state: &QueueState, which: &Which, cancelled: Cancelled, committed: bool) {
    if !committed {
        untold(state, which);
        return;
    }
    if let Cancelled::Job(job) = cancelled {
        if let Some(lease) = state.held(job) {
            lease.cancel();
            state.release(&lease);
        }
        state.room_made(jobs.now());
    }
    if !matches!(cancelled, Cancelled::Nothing) {
        state.watchers.changed();
    }
}

/// Takes back what a cancel that did not happen told the watchers of its job.
fn untold(state: &QueueState, which: &Which) {
    if let Which::Id(key) = which {
        state.watchers.cancelled(key, false);
    }
}

/// A worker being started: how many handlers it runs at once.
#[must_use = "a worker starts with work() or runs with run_due()"]
pub struct Workers<'a, V> {
    queue: &'a Queue<V>,
    handlers: usize,
}

impl<V> Workers<'_, V>
where
    V: Serialize + DeserializeOwned + Send + 'static,
{
    /// Starts the worker; see [`Queue::work`].
    pub fn work<F, R, E>(self, handler: F) -> Result<Worker>
    where
        F: Fn(V, &Run) -> std::result::Result<R, E> + Send + Sync + 'static,
        R: Into<Outcome>,
        E: fmt::Display,
    {
        let queue = self.queue;
        work::start(&queue.jobs, &queue.state, self.handlers.max(1), handler).map_err(|error| queue.fail(None, error))
    }

    /// Runs what is due; see [`Queue::run_due`].
    pub fn run_due<F, R, E>(self, handler: F) -> Result<usize>
    where
        F: Fn(V, &Run) -> std::result::Result<R, E> + Sync,
        R: Into<Outcome>,
        E: fmt::Display,
    {
        let queue = self.queue;
        work::run_due(&queue.jobs, &queue.state, self.handlers.max(1), &handler)
            .map_err(|error| queue.fail(None, error))
    }
}

impl<V> fmt::Debug for Workers<'_, V> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Workers").field("handlers", &self.handlers).finish()
    }
}

/// A job a program claimed for a loop of its own: its value, its run, and the
/// lease it settles.
pub struct Claimed<V> {
    pub value: V,
    run: Run,
}

impl<V> Claimed<V> {
    pub fn run(&self) -> &Run {
        &self.run
    }

    /// Settles the job by `outcome`, as a handler's answer does: `()` for done,
    /// or one of the run's answers. A job whose lease ended and that another
    /// claim, a set or an update took since, or that a cancel took, is a
    /// `conflict`, and the settlement changes nothing.
    pub fn settle(self, outcome: impl Into<Outcome>) -> Result<()> {
        let settling = Settling::of(&self.run, outcome.into());
        let settled = self.run.jobs.file().write(0, settling.write())?;
        settling.settled(&settled)
    }
}

/// A claimed job's settlement: what its write changes in the file, then in
/// memory once it committed.
pub(crate) struct Settling {
    lease: Arc<Lease>,
    queue: Arc<QueueState>,
    jobs: Arc<Jobs>,
    how: claim::How,
    now: i64,
}

impl Settling {
    pub(crate) fn of(run: &Run, outcome: Outcome) -> Settling {
        let now = run.jobs.now();
        let (lease, queue, jobs) = (Arc::clone(&run.lease), Arc::clone(&run.queue), Arc::clone(&run.jobs));
        Settling { lease, queue, jobs, how: outcome.how(now), now }
    }

    /// A claimed job given back before anything began it, as a stopping
    /// worker gives one back: due at its own time, its attempt not counted.
    #[cfg(feature = "async")]
    pub(crate) fn given_back(run: &Run) -> Settling {
        Settling { how: claim::How::GiveBack, ..Settling::of(run, Outcome::from(())) }
    }

    fn write(&self) -> impl FnOnce(&SqlTx<'_>) -> Result<claim::Settled> + Send + 'static {
        let (lease, queue, how, now) = (Arc::clone(&self.lease), Arc::clone(&self.queue), self.how.clone(), self.now);
        move |tx: &SqlTx<'_>| claim::settle(tx, &queue, &lease, &how, now)
    }

    /// Follows in memory what the written settlement changed: the lease let
    /// go, the queue's watchers and workers woken. One whose lease another
    /// claim, a change or a cancel took is a `conflict`.
    fn settled(&self, settled: &claim::Settled) -> Result<()> {
        let (lease, queue, now) = (&self.lease, &self.queue, self.now);
        self.jobs.measure_settled(&queue.name, lease, &self.how, settled, now);
        lease.apply(settled, false);
        queue.release(lease);
        queue.watchers.changed();
        if let Some(due) = settled.due {
            queue.alarm.lower(due);
        }
        if let Some(failed) = &settled.failed {
            queue.failures.observe(&queue.name, failed);
        }
        queue.room_made(now);
        if settled.lost {
            let why = if lease.cancelled() {
                "a cancel took the job"
            } else {
                "the job's lease ended and another claim or a change took it"
            };
            return Err(Error::new(ErrorKind::Conflict, why).within(super::run::described(queue, lease)));
        }
        Ok(())
    }

    /// The settlement without waiting: the write is queued, and `done` is
    /// called on the thread that commits it once memory follows, so that a
    /// caller gone before the answer still lets the job go.
    #[cfg(feature = "async")]
    pub(crate) fn submit(self, done: impl FnOnce(Result<()>) + Send + 'static) {
        let (write, jobs) = (self.write(), Arc::clone(&self.jobs));
        jobs.file().submit(0, write, move |settled| done(settled.and_then(|settled| self.settled(&settled))));
    }
}

impl<V: fmt::Debug> fmt::Debug for Claimed<V> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Claimed").field("value", &self.value).field("run", &self.run).finish()
    }
}

/// Every job a filter names, a page at a time; a job whose value no longer
/// reads is its error, and the walk goes on past it.
pub struct All<V> {
    queue: Queue<V>,
    /// The filter of the next page; none once the last page was read.
    filter: Option<Filter>,
    page: VecDeque<Result<Job<V>>>,
}

impl<V> Iterator for All<V>
where
    V: Serialize + DeserializeOwned + Send + 'static,
{
    type Item = Result<Job<V>>;

    fn next(&mut self) -> Option<Self::Item> {
        while self.page.is_empty() {
            let filter = self.filter.take()?;
            match self.queue.read_page(&filter) {
                Ok(page) => {
                    self.filter = page.next.map(|next| filter.after(next));
                    self.page.extend(page.jobs);
                }
                Err(error) => return Some(Err(error)),
            }
        }
        self.page.pop_front()
    }
}

impl<V> fmt::Debug for All<V> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("All").field("queue", &self.queue).finish()
    }
}