tinystore 0.2.0-rc.1

A small storage runtime for applications on SQLite: SQL, key-value state, durable jobs, files, search, logs and metrics in one directory
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
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
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
//! jobs' methods of the protocol, protocol/jobs.wire: handles on queues and
//! schedules, calls on their jobs, and workers whose handlers are a client's.
//! A value travels as its JSON, checked and kept as it came.
//!
//! A client's worker is a stream both ways. The server's loop claims the
//! queue's jobs as on any worker and hands each to the stream, which sends it
//! as a held job once one of the client's handlers is free; the client answers
//! each on the same stream. Every job the stream was handed is answered to the
//! loop once: by the client, by a cancel that took it, or by the stream's end.

use std::collections::{HashMap, VecDeque};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex, MutexGuard, PoisonError, Weak};
use std::time::Duration;

use serde_json::value::RawValue;

use super::codec::Message;
use super::protocol::{
    Empty, Failure, Handle, JobsAnswer, JobsCall, JobsChanged, JobsHeld, JobsId, JobsJob, JobsKept, JobsList, JobsOp,
    JobsPage, JobsQueueOpen, JobsScheduleOpen, JobsStep, JobsTx, JobsTxResults, JobsWork, method,
};
use super::{Lent, Route};
#[cfg(feature = "sql")]
use crate::TxHandle;
use crate::clock::from_unix_millis;
use crate::jobs::{
    Answers, Change, Concurrency, Ended, Filter, Hand, Hears, How, Job, JobCall, Lease, Queue, QueueBuilder, Remote,
    RemoteWork, Report, Seen, State, Subscription, keep_encoded, kept, read_value, start_remote,
};
use crate::{Error, ErrorKind, Store, Transaction, unix_millis};

/// A job's value as the wire carries it.
type Raw = Box<RawValue>;

use super::Answered;

/// Puts a DATA of a work stream on its connection.
pub(crate) type Sender = Arc<dyn Fn(Vec<u8>) + Send + Sync>;

/// Ends a work stream with its last frame.
pub(crate) type Finisher = Arc<dyn Fn(Answered) + Send + Sync>;

/// Runs a task on the session's workers, off the thread that asked.
pub(crate) use super::Spawn;

/// A connection's workers, by stream.
type Works = Mutex<HashMap<u32, Arc<Work>>>;

/// A connection's watches, by stream.
type Watches = Mutex<HashMap<u32, Arc<Watching>>>;

/// A progress, as JSON, is at most this long: memory keeps it while its job
/// runs.
const MAX_PROGRESS: usize = 4 << 10;
/// The handlers a client's worker runs at once at most.
const MAX_HANDLERS: u64 = 1024;

pub(crate) fn route(called: u16) -> Route {
    match called {
        method::JOBS_WORK => Route::Exchange,
        method::JOBS_WATCH => Route::Watch,
        method::JOBS_ADD | method::JOBS_SET | method::JOBS_UPDATE | method::JOBS_CANCEL => Route::Submit,
        _ => Route::Worker,
    }
}

/// What a connection opened, by handle, and its workers, by stream.
#[derive(Default)]
pub(crate) struct Handles {
    open: Mutex<HashMap<u64, Opened>>,
    last: AtomicU64,
    works: Arc<Works>,
    watches: Arc<Watches>,
    /// The last run given: a run's number names its job on the connection, to
    /// its answer, a step and a keep.
    runs: Arc<AtomicU64>,
}

#[derive(Clone)]
struct Opened {
    queue: Queue<Raw>,
    /// A schedule's one job is its repeat, which no call adds, sets or updates.
    schedule: bool,
}

/// Answers a call that runs to its end on this thread.
pub(crate) fn call(
    store: &Store,
    handles: &Handles,
    lent: Lent<'_>,
    called: u16,
    body: &[u8],
    max_body: usize,
) -> Answered {
    match called {
        method::JOBS_QUEUE_OPEN => handles.open(open_queue(store, lent, JobsQueueOpen::decode(body)?)?, false),
        method::JOBS_SCHEDULE_OPEN => handles.open(open_schedule(store, JobsScheduleOpen::decode(body)?)?, true),
        method::JOBS_GET => {
            let id = JobsId::decode(body)?;
            let job = handles.opened(id.handle)?.queue.get(&id.id)?;
            within(job.map_or_else(JobsJob::default, job_of).encode(), max_body)
        }
        method::JOBS_LIST => list(handles, JobsList::decode(body)?, max_body),
        method::JOBS_TX => tx(store, handles, &JobsTx::decode(body)?),
        method::JOBS_STEP => step(handles, JobsStep::decode(body)?, max_body),
        method::JOBS_KEEP => keep(handles, JobsStep::decode(body)?),
        other => Err(Failure::unimplemented(format!("method {other:#06x}"))),
    }
}

/// Queues a job's write and returns; `done` gets its answer on the thread
/// that commits it, so that no thread of the session waits for a commit and
/// the writes in flight share one.
pub(crate) fn submit(handles: &Handles, called: u16, body: &[u8], done: impl FnOnce(Answered) + Send + 'static) {
    if called == method::JOBS_CANCEL {
        let asked = JobsId::decode(body).and_then(|id| Ok((handles.opened(id.handle)?.queue, id.id)));
        return match asked {
            Ok((queue, id)) => queue.cancel_then(&id, move |found| {
                done(found.map(|changed| JobsChanged { changed }.encode()).map_err(Failure::from));
            }),
            Err(failure) => done(Err(failure)),
        };
    }
    let change = match called {
        method::JOBS_ADD => Change::Add,
        method::JOBS_SET => Change::Set,
        _ => Change::Update,
    };
    let mut done = Some(done);
    let queued = JobsCall::decode(body).and_then(|call| {
        on_job(handles, call, None, |job, value| {
            let done = done.take().expect("a job's write is queued once");
            job.write_then(change, &value, move |changed| {
                let answer = |changed| match change {
                    Change::Set => Empty {}.encode(),
                    _ => JobsChanged { changed }.encode(),
                };
                done(changed.map(answer).map_err(Failure::from));
            });
            Ok(())
        })
    });
    if let (Err(failure), Some(done)) = (queued, done) {
        done(Err(failure));
    }
}

/// Answers a call made inside a database's transaction, on its stream: a
/// queue kept in the database's file adds, changes and reads its jobs in the
/// transaction.
#[cfg(feature = "sql")]
pub(crate) fn call_in(handles: &Handles, tx: &Transaction<'_>, called: u16, body: &[u8], max_body: usize) -> Answered {
    match called {
        method::JOBS_ADD | method::JOBS_SET | method::JOBS_UPDATE => {
            let changed = write_op(
                handles,
                tx,
                &JobsOp { method: u64::from(called), call: Some(JobsCall::decode(body)?), id: None },
            )?;
            Ok(if called == method::JOBS_SET { Empty {}.encode() } else { JobsChanged { changed }.encode() })
        }
        method::JOBS_CANCEL => {
            let id = JobsId::decode(body)?;
            let changed = handles.opened(id.handle)?.queue.cancel_in(&id.id, Some(tx))?;
            Ok(JobsChanged { changed }.encode())
        }
        method::JOBS_GET => {
            let id = JobsId::decode(body)?;
            let job = handles.opened(id.handle)?.queue.in_tx(tx).get(&id.id)?;
            within(job.map_or_else(JobsJob::default, job_of).encode(), max_body)
        }
        other => Err(Failure::invalid(format!("method {other:#06x} is not a queue's call inside a transaction"))),
    }
}

/// A job's add that a database's batch carries, for a queue kept in its
/// file: it commits with the batch's rows, or not at all.
#[cfg(feature = "sql")]
pub(crate) fn lend(handles: &Handles, body: &[u8]) -> Result<crate::sql::Write, Failure> {
    on_job(handles, JobsCall::decode(body)?, None, |job, value| Ok(job.adding(&value)))
}

/// A transaction's writes in one transaction of jobs.db, all of them or
/// none; one that fails names its place in `what`.
fn tx(store: &Store, handles: &Handles, asked: &JobsTx) -> Answered {
    let outcomes = store.tx(|tx| -> Result<Vec<JobsChanged>, Failure> {
        let mut outcomes = Vec::with_capacity(asked.writes.len());
        for (index, op) in asked.writes.iter().enumerate() {
            let changed = write_op(handles, tx.transaction(), op);
            outcomes
                .push(JobsChanged { changed: changed.map_err(|failure| failure.naming("write", index.to_string()))? });
        }
        Ok(outcomes)
    })?;
    Ok(JobsTxResults { outcomes }.encode())
}

/// One write of a transaction, and whether it changed anything.
fn write_op(handles: &Handles, tx: &Transaction<'_>, op: &JobsOp) -> Result<bool, Failure> {
    let called = u16::try_from(op.method).map_err(|_| Failure::invalid(format!("method {:#06x}", op.method)))?;
    match (called, &op.call, &op.id) {
        (method::JOBS_ADD, Some(call), _) => on_job(handles, call.clone(), Some(tx), |job, value| job.add(&value)),
        (method::JOBS_SET, Some(call), _) => {
            on_job(handles, call.clone(), Some(tx), |job, value| job.set(&value)).map(|()| true)
        }
        (method::JOBS_UPDATE, Some(call), _) => {
            on_job(handles, call.clone(), Some(tx), |job, value| job.update(&value))
        }
        (method::JOBS_CANCEL, _, Some(id)) => Ok(handles.opened(id.handle)?.queue.cancel_in(&id.id, Some(tx))?),
        _ => Err(Failure::invalid(format!(
            "method {called:#06x} is not a write of a transaction, or lacks what it takes"
        ))),
    }
}

fn open_queue(store: &Store, lent: Lent<'_>, open: JobsQueueOpen) -> Result<Queue<Raw>, Failure> {
    let mut builder = match open.database {
        Some(database) => QueueBuilder::<Raw>::in_file(lent(database)?, &open.name),
        None => store.queue::<Raw>(&open.name),
    };
    if let Some(attempts) = open.attempts {
        builder = builder.attempts(small(attempts, "attempts")?);
    }
    if let Some(backoff) = open.backoff {
        builder = builder.backoff(span(backoff.initial), span(backoff.max));
    }
    if let Some(timeout) = open.timeout {
        builder = builder.timeout(span(timeout));
    }
    if let Some(concurrency) = open.concurrency {
        let mut bound = match concurrency.total {
            Some(total) => Concurrency::total(small(total, "a concurrency")?),
            None => Concurrency::default(),
        };
        if let Some(group) = concurrency.group {
            bound = bound.group(small(group, "a group's concurrency")?);
        }
        builder = builder.concurrency(bound);
    }
    if let Some(rate) = open.rate {
        builder = builder.rate(small(rate.count, "a rate")?, span(rate.per));
    }
    if let Some(rate) = open.group_rate {
        builder = builder.group_rate(small(rate.count, "a group's rate")?, span(rate.per));
    }
    if let Some(dedupe) = open.dedupe {
        builder = builder.dedupe(span(dedupe));
    }
    if let Some(keep) = open.keep {
        builder = builder.keep(span(keep));
    }
    if let Some(max_waiting) = open.max_waiting {
        builder = builder.max_waiting(max_waiting);
    }
    Ok(builder.open()?)
}

fn open_schedule(store: &Store, open: JobsScheduleOpen) -> Result<Queue<Raw>, Failure> {
    let builder = store.schedule(&open.name);
    let mut builder = match (open.every, open.cron, open.time_zone) {
        (Some(every), None, None) => builder.every(span(every)),
        (None, Some(cron), zone) => builder.cron(&cron, zone.as_deref().unwrap_or_default()),
        (None, None, _) => return Err(Failure::invalid("a schedule repeats by every or by cron")),
        _ => return Err(Failure::invalid("a schedule repeats by every or by cron, not both; a time zone is a cron's")),
    };
    if let Some(attempts) = open.attempts {
        builder = builder.attempts(small(attempts, "attempts")?);
    }
    if let Some(backoff) = open.backoff {
        builder = builder.backoff(span(backoff.initial), span(backoff.max));
    }
    if let Some(timeout) = open.timeout {
        builder = builder.timeout(span(timeout));
    }
    Ok(builder.open()?.queue().retyped())
}

/// Runs an add, a set or an update on the job a call names, in `tx` when
/// there is one.
fn on_job<T>(
    handles: &Handles,
    call: JobsCall,
    tx: Option<&Transaction<'_>>,
    write: impl FnOnce(JobCall<'_, Raw>, Raw) -> crate::Result<T>,
) -> Result<T, Failure> {
    let opened = handles.opened(call.handle)?;
    if opened.schedule {
        return Err(Failure::invalid("a schedule's one job is its repeat, which no call adds, sets or updates"));
    }
    let value = RawValue::from_string(call.value)
        .map_err(|error| Failure::invalid(format!("a value that is not JSON: {error}")))?;
    let mut job = JobCall::new(&opened.queue, tx);
    if let Some(id) = &call.id {
        job = job.id(id);
    }
    if let Some(at) = call.at {
        job = job.at(from_unix_millis(at));
    }
    if let Some(delay) = call.delay {
        job = job.delay(span(delay));
    }
    if let Some(group) = &call.group {
        job = job.group(group);
    }
    job = match (call.every, &call.cron, &call.time_zone) {
        (None, None, None) => job,
        (Some(every), None, None) => job.every(span(every)),
        (None, Some(cron), zone) => job.cron(cron, zone.as_deref().unwrap_or_default()),
        _ => return Err(Failure::invalid("a repeat by every or by cron, not both; a time zone is a cron's")),
    };
    Ok(write(job, value)?)
}

/// A page of jobs within the body agreed: a page past it is read again with
/// half its jobs.
fn list(handles: &Handles, list: JobsList, max_body: usize) -> Answered {
    let queue = handles.opened(list.handle)?.queue;
    let mut filter = Filter::prefix(list.prefix.unwrap_or_default());
    if let Some(state) = &list.state {
        filter = filter.state(state_of(state)?);
    }
    if let Some(after) = list.after {
        filter = filter.after(after);
    }
    let mut limit = list.limit.map_or(100, |limit| usize::try_from(limit).unwrap_or(usize::MAX));
    loop {
        let page = queue.list(&filter.clone().limit(limit))?;
        let shown = page.jobs.len();
        let encoded = JobsPage { jobs: page.jobs.into_iter().map(job_of).collect(), next: page.next }.encode();
        if encoded.len() <= max_body || shown <= 1 {
            return within(encoded, max_body);
        }
        limit = shown / 2;
    }
}

/// The answer a held job's run kept under a step's name.
fn step(handles: &Handles, step: JobsStep, max_body: usize) -> Answered {
    let (lease, queue) = handles.held(step.run)?;
    let named = |error: Error| queue.fail(lease.key.as_deref(), error.within(format!("step {:?}", step.name)));
    let answer = kept(&queue.jobs, &lease, &step.name).map_err(named)?;
    let answer = answer
        .map(String::from_utf8)
        .transpose()
        .map_err(|_| named(Error::new(ErrorKind::Corrupt, "a kept answer that is not UTF-8")))?;
    within(JobsKept { found: answer.is_some(), answer }.encode(), max_body)
}

/// Keeps a step's answer for a held job's run, while its attempt holds the job.
fn keep(handles: &Handles, step: JobsStep) -> Answered {
    let (lease, queue) = handles.held(step.run)?;
    let answer = step.answer.ok_or_else(|| Failure::invalid("a keep without its answer"))?;
    serde_json::from_str::<&RawValue>(&answer)
        .map_err(|error| Failure::invalid(format!("a step's answer that is not JSON: {error}")))?;
    keep_encoded(&queue.jobs, &lease, &step.name, answer.into_bytes())
        .map_err(|error| queue.fail(lease.key.as_deref(), error.within(format!("step {:?}", step.name))))?;
    Ok(Empty {}.encode())
}

fn job_of(job: Job<Raw>) -> JobsJob {
    JobsJob {
        found: true,
        id: job.id,
        value: Some(text_of(job.value)),
        state: state_name(job.state).to_owned(),
        at: Some(unix_millis(job.at)),
        attempt: u64::from(job.attempt),
        ahead: u64::from(job.ahead),
        progress: job.progress.map(|progress| progress.to_string()),
        error: job.error,
        group: job.group,
        repeat: job.repeat,
        started_at: job.last_run.map(|run| unix_millis(run.started_at)),
        ended_at: job.last_run.map(|run| unix_millis(run.ended_at)),
    }
}

fn state_name(state: State) -> &'static str {
    match state {
        State::Scheduled => "scheduled",
        State::Waiting => "waiting",
        State::Running => "running",
        State::Done => "done",
        State::Failed => "failed",
        State::Cancelled => "cancelled",
    }
}

fn state_of(name: &str) -> Result<State, Failure> {
    match name {
        "scheduled" => Ok(State::Scheduled),
        "waiting" => Ok(State::Waiting),
        "running" => Ok(State::Running),
        "failed" => Ok(State::Failed),
        other => Err(Failure::invalid(format!("a page of {other:?} jobs: scheduled, waiting, running or failed"))),
    }
}

/// What a work stream needs of its connection.
pub(crate) struct Link {
    pub(crate) send: Sender,
    /// Ends the stream with its last frame, when the server ends it.
    pub(crate) finish: Finisher,
    pub(crate) spawn: Spawn,
    /// The DATA bytes the client's HELLO lets the server send before it grants
    /// more.
    pub(crate) credit: u64,
    pub(crate) max_body: usize,
}

/// A client's worker: the loop on the server, and the stream that hands its
/// jobs to the client.
pub(crate) struct Work {
    number: u32,
    works: Weak<Works>,
    remote: Remote,
    stream: Arc<Stream>,
    /// The client's DATA bytes let go of since they were last granted back.
    released: Mutex<u64>,
}

/// Starts the worker a `jobs.work` asks for. Its stream sends nothing until
/// [`Work::begin`], once the stream's `RESPONSE` went out.
pub(crate) fn work(handles: &Handles, number: u32, body: &[u8], link: Link) -> Result<Arc<Work>, Failure> {
    let asked = JobsWork::decode(body)?;
    let queue = handles.opened(asked.handle)?.queue;
    let local = match asked.concurrency {
        None => u64::from(queue.state.policy.local()).min(MAX_HANDLERS),
        Some(0) => return Err(Failure::invalid("a worker of no handlers")),
        Some(handlers) if handlers > MAX_HANDLERS => {
            return Err(Failure::invalid(format!("a worker of {handlers} handlers, past {MAX_HANDLERS}")));
        }
        Some(handlers) => handlers,
    };
    let local = usize::try_from(local).unwrap_or(1);
    let answers = Answers::default();
    let stream = Arc::new_cyclic(|me| Stream {
        me: me.clone(),
        queue: queue.clone(),
        answers: answers.clone(),
        runs: Arc::clone(&handles.runs),
        local,
        state: Mutex::new(StreamState { credit: link.credit, ..StreamState::default() }),
        link,
    });
    let works = Arc::downgrade(&handles.works);
    let remote = start_remote(
        &queue.jobs,
        &queue.state,
        RemoteWork {
            local,
            until_idle: asked.until_idle,
            answers,
            hand: Arc::clone(&stream) as Arc<dyn Hand>,
            ended: on_loop_end(Arc::downgrade(&stream), Weak::clone(&works), number),
        },
    )?;
    let work = Arc::new(Work { number, works, remote, stream, released: Mutex::new(0) });
    handles.lock_works().insert(number, Arc::clone(&work));
    Ok(work)
}

/// What hears a worker's loop end by itself, once nothing was due or the
/// store closed: the stream ends then, unless the session ended it first, or
/// at its begin when it had not begun.
fn on_loop_end(stream: Weak<Stream>, works: Weak<Works>, number: u32) -> Ended {
    Box::new(move |ran| {
        let Some(ran) = stream.upgrade().and_then(|stream| stream.loop_ended(ran)) else {
            return;
        };
        let taken = works.upgrade().and_then(|works| locked(&works).remove(&number));
        if let Some(work) = taken {
            work.finish(ran);
        }
    })
}

impl Work {
    /// Lets the stream send what its worker hands it: its `RESPONSE` went out.
    /// A worker whose loop ended before, nothing being due, ends here.
    pub(crate) fn begin(&self) {
        let Some(ran) = self.stream.begin() else {
            return;
        };
        let taken = self.works.upgrade().and_then(|works| locked(&works).remove(&self.number));
        if let Some(work) = taken {
            work.finish(ran);
        }
    }

    /// Ends a worker whose loop ended by itself, already out of use, and its
    /// stream: `{}` once nothing was due, an error when the store closed or
    /// the loop failed.
    fn finish(&self, ran: crate::Result<usize>) {
        self.end();
        let last = match ran {
            Ok(_) if self.stream.queue.jobs.closed() => {
                Err(Failure::from(Error::closed(self.stream.queue.state.describe())))
            }
            Ok(_) => Ok(Empty {}.encode()),
            Err(error) => Err(Failure::from(error)),
        };
        (self.stream.link.finish)(last);
    }

    /// The client's item: an answer for a job it holds, a progress, or a stop.
    pub(crate) fn item(&self, body: &[u8]) -> Result<(), Failure> {
        let answer = JobsAnswer::decode(body)?;
        match answer.how.as_str() {
            "stop" => self.halt(),
            "progress" => self.stream.progress(answer.run, answer.progress)?,
            _ => {
                let run = answer.run;
                let how = how_of(answer, self.stream.queue.jobs.now())?;
                self.stream.answer(run, how);
            }
        }
        Ok(())
    }

    /// Credit the client granted the stream for the server's DATA.
    pub(crate) fn grant(&self, credit: u32) {
        self.stream.lock().credit += u64::from(credit);
        self.stream.flush();
    }

    /// Takes no job more: the client asked to stop, or the server is closing.
    /// The jobs the client holds are still its to answer.
    pub(crate) fn halt(&self) {
        self.stream.lock().halted = true;
        self.remote.halt();
    }

    /// Ends the worker: the jobs the client holds unanswered fail their
    /// attempt, as a worker's that died, those never sent go back uncounted,
    /// and the loop writes what was answered. It waits for the loop, so it
    /// runs off the connection's own thread.
    pub(crate) fn end(&self) {
        for lease in self.stream.end() {
            let cause = "the client's worker ended with the job in hand".to_owned();
            self.stream.answers.answer(lease, Some(How::Retry { at: None, cause }));
        }
        self.remote.stop();
    }

    /// Counts the bytes of the client's DATA let go of, and says what to grant
    /// back once half the stream's window has gone.
    pub(crate) fn release(&self, bytes: u64, window: u64) -> Option<u32> {
        let mut released = self.released.lock().unwrap_or_else(PoisonError::into_inner);
        *released += bytes;
        if *released < window / 2 {
            return None;
        }
        Some(u32::try_from(std::mem::take(&mut *released)).unwrap_or(u32::MAX))
    }
}

/// How a client's answer settles its job; a time given as a delay counts from
/// `now`, the server's clock.
fn how_of(answer: JobsAnswer, now: i64) -> Result<How, Failure> {
    let at = match (answer.at, answer.delay) {
        (Some(_), Some(_)) => return Err(Failure::invalid("an answer's time given twice: at or delay, not both")),
        (at, None) => at,
        (None, Some(delay)) => Some(now.saturating_add(i64::try_from(delay).unwrap_or(i64::MAX))),
    };
    Ok(match answer.how.as_str() {
        "done" => How::Done,
        "retry" => How::Retry { at, cause: answer.error.unwrap_or_else(|| "its handler asked for a retry".to_owned()) },
        "snooze" => How::Snooze { at: at.ok_or_else(|| Failure::invalid("a snooze without its time"))? },
        "fail" => How::Fail { cause: answer.error.unwrap_or_else(|| "its handler failed it".to_owned()) },
        "back" => How::GiveBack,
        other => {
            let known = "done, retry, snooze, fail, back, progress or stop";
            return Err(Failure::invalid(format!("an answer of {other:?}, not {known}")));
        }
    })
}

/// A work stream's side of its worker: the jobs the loop hands it go out in
/// the order handed, no more unanswered at once than the client's handlers,
/// within the credit the client granted.
struct Stream {
    me: Weak<Stream>,
    queue: Queue<Raw>,
    answers: Answers,
    link: Link,
    runs: Arc<AtomicU64>,
    /// The client's handlers.
    local: usize,
    state: Mutex<StreamState>,
}

#[derive(Default)]
struct StreamState {
    /// The DATA bytes the client still takes.
    credit: u64,
    /// The jobs it holds by run, sent or waiting to be.
    held: HashMap<u64, Holding>,
    /// Held jobs in the order handed, waiting for a handler and credit.
    waiting: VecDeque<(u64, Vec<u8>)>,
    /// Notices of cancels, which go before the jobs waiting.
    notices: VecDeque<Vec<u8>>,
    /// Jobs sent and not yet answered.
    out: usize,
    /// Its `RESPONSE` went out, and DATA may follow.
    begun: bool,
    /// It sends no job more.
    halted: bool,
    /// It sends nothing more: its last frame comes.
    ended: bool,
    /// How the worker's loop ended, when it ended by itself before the stream
    /// began.
    ran: Option<crate::Result<usize>>,
}

struct Holding {
    lease: Arc<Lease>,
    sent: bool,
}

impl Hand for Stream {
    fn hand(&self, lease: Arc<Lease>) -> Result<(), Option<How>> {
        if lease.cancelled() {
            return Err(None);
        }
        if self.lock().halted {
            return Err(Some(How::GiveBack));
        }
        let (run, body) = self.held_job(&lease).map_err(Some)?;
        {
            let mut state = self.lock();
            if state.halted {
                return Err(Some(How::GiveBack));
            }
            state.held.insert(run, Holding { lease: Arc::clone(&lease), sent: false });
            state.waiting.push_back((run, body));
        }
        let me = self.me.clone();
        lease.when_cancelled(Box::new(move || {
            if let Some(stream) = me.upgrade() {
                stream.cancelled(run);
            }
        }));
        self.flush();
        Ok(())
    }

    fn close(&self) -> Vec<Arc<Lease>> {
        let mut state = self.lock();
        state.halted = true;
        let unsent: Vec<u64> = state.held.iter().filter(|(_, holding)| !holding.sent).map(|(run, _)| *run).collect();
        state.waiting.clear();
        unsent.into_iter().filter_map(|run| state.held.remove(&run)).map(|holding| holding.lease).collect()
    }
}

impl Stream {
    /// Lets the stream send: its `RESPONSE` went out. A loop that ended
    /// before gives how it ended.
    fn begin(&self) -> Option<crate::Result<usize>> {
        let ran = {
            let mut state = self.lock();
            state.begun = true;
            state.ran.take()
        };
        if ran.is_none() {
            self.flush();
        }
        ran
    }

    /// Hears that the worker's loop ended by itself, and gives that back when
    /// the stream has begun; one not yet begun keeps it for its begin.
    fn loop_ended(&self, ran: crate::Result<usize>) -> Option<crate::Result<usize>> {
        let mut state = self.lock();
        if state.begun {
            return Some(ran);
        }
        state.ran = Some(ran);
        None
    }

    /// The held job a lease goes out as, and its run; a value that cannot be
    /// read or sent says how to settle the job instead.
    fn held_job(&self, lease: &Lease) -> Result<(u64, Vec<u8>), How> {
        let value = match read_value::<Raw>(&self.queue.jobs, lease) {
            Ok(value) => value,
            Err(error) if error.kind() == ErrorKind::Invalid => return Err(How::Fail { cause: error.to_string() }),
            Err(error) => return Err(How::Retry { at: None, cause: error.to_string() }),
        };
        let run = self.runs.fetch_add(1, Ordering::Relaxed) + 1;
        let held = JobsHeld {
            run,
            id: lease.key.clone(),
            value: Some(text_of(value)),
            at: lease.at,
            attempt: u64::try_from(lease.attempt).unwrap_or(0),
            group: lease.group.clone(),
            cancelled: false,
        };
        let body = held.encode();
        if body.len() > self.link.max_body {
            // another worker, whose client takes larger bodies, may run it
            let cause = format!("a job of {} bytes, past the {} its client takes", body.len(), self.link.max_body);
            return Err(How::Retry { at: None, cause });
        }
        Ok((run, body))
    }

    /// Sends what waits while the client's credit takes it: the notices
    /// first, then the jobs in order while a handler is free. A job sent is
    /// the client's to answer; one a cancel took first goes nowhere.
    fn flush(&self) {
        let mut taken = Vec::new();
        let mut began = false;
        let mut state = self.lock();
        let now = self.queue.jobs.now();
        while state.begun && !state.ended {
            if let Some(size) = state.notices.front().map(|notice| notice.len() as u64) {
                if size > state.credit {
                    break;
                }
                state.credit -= size;
                if let Some(notice) = state.notices.pop_front() {
                    (self.link.send)(notice);
                }
                continue;
            }
            if state.halted || state.out >= self.local {
                break;
            }
            let Some((run, size)) = state.waiting.front().map(|(run, body)| (*run, body.len() as u64)) else {
                break;
            };
            let Some(holding) = state.held.get(&run) else {
                state.waiting.pop_front();
                continue;
            };
            if size > state.credit {
                break;
            }
            if !holding.lease.begin(now) {
                taken.extend(state.held.remove(&run).map(|holding| holding.lease));
                state.waiting.pop_front();
                continue;
            }
            if let Some((_, body)) = state.waiting.pop_front() {
                state.credit -= size;
                state.out += 1;
                if let Some(holding) = state.held.get_mut(&run) {
                    holding.sent = true;
                }
                (self.link.send)(body);
                began = true;
            }
        }
        drop(state);
        if began {
            self.queue.state.watchers.changed();
        }
        for lease in taken {
            self.answers.answer(lease, None);
        }
    }

    /// The client's answer for a job it was sent; one a cancel took first, or
    /// a run it never was sent, is dropped.
    fn answer(&self, run: u64, how: How) {
        let mut state = self.lock();
        let lease = match state.held.remove(&run) {
            Some(holding) if holding.sent => holding.lease,
            Some(unsent) => {
                state.held.insert(run, unsent);
                return;
            }
            None => return,
        };
        state.out -= 1;
        drop(state);
        self.answers.answer(lease, Some(how));
        self.flush();
    }

    /// What the handler of a job the client was sent reports of it; one that
    /// is not JSON, or past 4 KiB, fails the stream.
    fn progress(&self, run: u64, report: Option<String>) -> Result<(), Failure> {
        let report = report.ok_or_else(|| Failure::invalid("a progress without its report"))?;
        if report.len() > MAX_PROGRESS {
            let refused = format!("a progress of {} bytes, past {MAX_PROGRESS}", report.len());
            return Err(Failure::from(Error::limit(refused)));
        }
        let report = serde_json::from_str(&report)
            .map_err(|error| Failure::invalid(format!("a progress that is not JSON: {error}")))?;
        if let Some(holding) = self.lock().held.get(&run).filter(|holding| holding.sent) {
            holding.lease.set_progress(report);
        }
        self.queue.state.watchers.changed();
        Ok(())
    }

    /// Answers a job a cancel took for the client, and tells the client when it
    /// was sent the job, so that its handler stops: what the client says of it
    /// later settles nothing.
    fn cancelled(&self, run: u64) {
        let mut state = self.lock();
        let Some(holding) = state.held.remove(&run) else {
            return;
        };
        if holding.sent {
            state.out -= 1;
            state.notices.push_back(JobsHeld { run, cancelled: true, ..JobsHeld::default() }.encode());
        }
        drop(state);
        self.answers.answer(holding.lease, None);
        self.flush();
    }

    /// The job a run names, sent to the client and not yet answered.
    fn held(&self, run: u64) -> Option<Arc<Lease>> {
        self.lock().held.get(&run).filter(|holding| holding.sent).map(|holding| Arc::clone(&holding.lease))
    }

    /// Sends nothing more, and lets go of the jobs the client was sent and has
    /// not answered.
    fn end(&self) -> Vec<Arc<Lease>> {
        let mut state = self.lock();
        (state.halted, state.ended, state.out) = (true, true, 0);
        let sent: Vec<u64> = state.held.iter().filter(|(_, holding)| holding.sent).map(|(run, _)| *run).collect();
        sent.into_iter().filter_map(|run| state.held.remove(&run)).map(|holding| holding.lease).collect()
    }

    fn lock(&self) -> MutexGuard<'_, StreamState> {
        self.state.lock().unwrap_or_else(PoisonError::into_inner)
    }
}

impl Handles {
    fn open(&self, queue: Queue<Raw>, schedule: bool) -> Answered {
        let handle = self.last.fetch_add(1, Ordering::SeqCst) + 1;
        self.lock().insert(handle, Opened { queue, schedule });
        Ok(Handle { handle }.encode())
    }

    fn opened(&self, handle: u64) -> Result<Opened, Failure> {
        self.lock()
            .get(&handle)
            .cloned()
            .ok_or_else(|| Failure::invalid(format!("handle {handle} names no queue this connection opened")))
    }

    /// The job a run of this connection's workers holds, and its queue.
    fn held(&self, run: u64) -> Result<(Arc<Lease>, Queue<Raw>), Failure> {
        let works: Vec<Arc<Work>> = self.lock_works().values().cloned().collect();
        let found = works.iter().find_map(|work| work.stream.held(run).map(|lease| (lease, work.stream.queue.clone())));
        found.ok_or_else(|| {
            let ended = format!("run {run} holds no job: it was answered, a cancel took it, or its worker ended");
            Failure::from(Error::new(ErrorKind::Conflict, ended))
        })
    }

    /// The worker on a stream.
    pub(crate) fn work(&self, stream: u32) -> Option<Arc<Work>> {
        self.lock_works().get(&stream).cloned()
    }

    /// Takes the worker on a stream out of use, its stream's last frame to come.
    pub(crate) fn take_work(&self, stream: u32) -> Option<Arc<Work>> {
        self.lock_works().remove(&stream)
    }

    /// Takes every worker out of use: the connection ends.
    pub(crate) fn take_works(&self) -> Vec<Arc<Work>> {
        self.lock_works().drain().map(|(_, work)| work).collect()
    }

    /// Credit the client granted a stream for the server's DATA: a worker's or
    /// a watch's.
    pub(crate) fn grant(&self, stream: u32, credit: u32) {
        if let Some(work) = self.work(stream) {
            return work.grant(credit);
        }
        let watch = locked(&self.watches).get(&stream).cloned();
        if let Some(watch) = watch {
            watch.grant(credit);
        }
    }

    /// Takes the watch on a stream out of use, its stream's last frame to come.
    pub(crate) fn take_watch(&self, stream: u32) -> Option<Arc<Watching>> {
        locked(&self.watches).remove(&stream)
    }

    /// Takes every watch out of use: the connection ends, or the server closes.
    pub(crate) fn take_watches(&self) -> Vec<Arc<Watching>> {
        locked(&self.watches).drain().map(|(_, watch)| watch).collect()
    }

    /// Halts every worker: the server is closing.
    pub(crate) fn halt_works(&self) {
        let works: Vec<Arc<Work>> = self.lock_works().values().cloned().collect();
        for work in works {
            work.halt();
        }
    }

    fn lock(&self) -> MutexGuard<'_, HashMap<u64, Opened>> {
        self.open.lock().unwrap_or_else(PoisonError::into_inner)
    }

    fn lock_works(&self) -> MutexGuard<'_, HashMap<u32, Arc<Work>>> {
        locked(&self.works)
    }
}

fn locked<T>(by_stream: &Mutex<HashMap<u32, T>>) -> MutexGuard<'_, HashMap<u32, T>> {
    by_stream.lock().unwrap_or_else(PoisonError::into_inner)
}

/// A client's watch of a job: the job as it is, then again each time it
/// changes, until it ends. Its reads run on the session's workers, one at a
/// time, and only the latest report waits when the client's credit is spent.
pub(crate) struct Watching {
    me: Weak<Watching>,
    number: u32,
    watches: Weak<Watches>,
    queue: Queue<Raw>,
    key: String,
    link: Link,
    /// The watcher's place among the queue's, given up when the watch ends.
    sub: Mutex<Option<Subscription>>,
    /// What the reads saw; one read runs at a time.
    seen: Mutex<Seen<Raw>>,
    state: Mutex<WatchState>,
}

#[derive(Default)]
struct WatchState {
    credit: u64,
    /// A read is queued or under way.
    reading: bool,
    /// A change came since the read under way began: another read follows.
    again: bool,
    /// The latest report, waiting for credit, and whether the watch ends with it.
    report: Option<(Vec<u8>, bool)>,
    begun: bool,
    ended: bool,
}

/// Starts the watch a `jobs.watch` asks for. It reads nothing until
/// [`Watching::begin`], once the stream's `RESPONSE` went out.
pub(crate) fn watch(handles: &Handles, number: u32, body: &[u8], link: Link) -> Result<Arc<Watching>, Failure> {
    let asked = JobsId::decode(body)?;
    let queue = handles.opened(asked.handle)?.queue;
    let watching = Arc::new_cyclic(|me: &Weak<Watching>| {
        let waking = me.clone();
        let hears: Hears = Arc::new(move || {
            if let Some(watching) = waking.upgrade() {
                watching.wake();
            }
        });
        let sub = Subscription::new(&queue.state, &asked.id, hears);
        Watching {
            me: me.clone(),
            number,
            watches: Arc::downgrade(&handles.watches),
            queue,
            key: asked.id,
            sub: Mutex::new(Some(sub)),
            seen: Mutex::new(Seen::default()),
            state: Mutex::new(WatchState { credit: link.credit, ..WatchState::default() }),
            link,
        }
    });
    locked(&handles.watches).insert(number, Arc::clone(&watching));
    Ok(watching)
}

impl Watching {
    /// Reads the job a first time: the stream's `RESPONSE` went out.
    pub(crate) fn begin(&self) {
        self.lock().begun = true;
        self.wake();
    }

    /// Credit the client granted the stream for the server's DATA.
    pub(crate) fn grant(&self, credit: u32) {
        self.lock().credit += u64::from(credit);
        self.flush();
    }

    /// Ends the watch without a frame: the client cancelled it or left. Says
    /// whether it was still going.
    pub(crate) fn end(&self) -> bool {
        if std::mem::replace(&mut self.lock().ended, true) {
            return false;
        }
        drop(self.sub.lock().unwrap_or_else(PoisonError::into_inner).take());
        if let Some(watches) = self.watches.upgrade() {
            locked(&watches).remove(&self.number);
        }
        true
    }

    /// Ends the watch and its stream with `last`, unless it ended already.
    pub(crate) fn close(&self, last: Answered) {
        if self.end() {
            (self.link.finish)(last);
        }
    }

    /// Asks for a read, off this thread, since a change the queue committed
    /// may be one the client sees; one asked for while a read runs follows it.
    fn wake(&self) {
        let mut state = self.lock();
        if !state.begun || state.ended {
            return;
        }
        if std::mem::replace(&mut state.reading, true) {
            state.again = true;
            return;
        }
        drop(state);
        let me = self.me.clone();
        (self.link.spawn)(Box::new(move || {
            if let Some(watching) = me.upgrade() {
                watching.read();
            }
        }));
    }

    /// Reads the job again until no change came meanwhile, and sends what the
    /// client has not seen.
    fn read(&self) {
        loop {
            let read = {
                let sub = self.sub.lock().unwrap_or_else(PoisonError::into_inner);
                let Some(sub) = sub.as_ref() else {
                    return;
                };
                self.seen.lock().unwrap_or_else(PoisonError::into_inner).read(&self.queue, &self.key, sub)
            };
            match read {
                Ok(Report::Changed(job)) => {
                    let last = matches!(job.state, State::Done | State::Failed | State::Cancelled);
                    match within(job_of(job).encode(), self.link.max_body) {
                        Ok(body) => {
                            self.lock().report = Some((body, last));
                            self.flush();
                        }
                        Err(failure) => return self.close(Err(failure)),
                    }
                }
                Ok(Report::Same) => {}
                Ok(Report::Over) => {
                    if self.lock().report.is_none() {
                        return self.close(Ok(Empty {}.encode()));
                    }
                }
                Err(error) => return self.close(Err(Failure::from(error))),
            }
            let mut state = self.lock();
            if !std::mem::replace(&mut state.again, false) || state.ended {
                state.reading = false;
                return;
            }
        }
    }

    /// Sends the latest report when the client's credit takes it, and ends
    /// the stream after the last.
    fn flush(&self) {
        let mut state = self.lock();
        if state.ended {
            return;
        }
        let Some((body, last)) = state.report.take() else {
            return;
        };
        if body.len() as u64 > state.credit {
            state.report = Some((body, last));
            return;
        }
        state.credit -= body.len() as u64;
        (self.link.send)(body);
        drop(state);
        if last {
            self.close(Ok(Empty {}.encode()));
        }
    }

    fn lock(&self) -> MutexGuard<'_, WatchState> {
        self.state.lock().unwrap_or_else(PoisonError::into_inner)
    }
}

/// An answer within the body agreed: a larger one is `limit`.
fn within(encoded: Vec<u8>, max_body: usize) -> Answered {
    if encoded.len() > max_body {
        let refused = format!("an answer of {} bytes, past the {max_body} this connection agreed", encoded.len());
        return Err(Failure::from(Error::limit(refused)));
    }
    Ok(encoded)
}

fn text_of(value: Raw) -> String {
    Box::<str>::from(value).into_string()
}

fn span(ms: u64) -> Duration {
    Duration::from_millis(ms)
}

fn small(n: u64, what: &str) -> Result<u32, Failure> {
    u32::try_from(n).map_err(|_| Failure::invalid(format!("{what} of {n}, past {}", u32::MAX)))
}

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