tinystore 0.4.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
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
use std::collections::HashMap;
use std::hash::{BuildHasher, Hasher, RandomState};
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Condvar, Mutex, MutexGuard, PoisonError};
use std::time::{Duration, Instant, SystemTime};

use super::Route;
#[cfg(feature = "backup")]
use super::backup;
#[cfg(feature = "blobs")]
use super::blobs;
#[cfg(feature = "channels")]
use super::channels;
use super::codec::Message;
#[cfg(feature = "config")]
use super::config;
use super::frame::{self, Frame, Kind};
#[cfg(feature = "jobs")]
use super::jobs;
use super::kv::{self, Run};
#[cfg(feature = "locks")]
use super::locks;
#[cfg(feature = "metrics")]
use super::metrics;
use super::output::Output;
use super::protocol::method::{self, Access};
use super::protocol::{Empty, Failure, GoAway, Hello, ServerClock, Welcome};
#[cfg(feature = "records")]
use super::records;
#[cfg(feature = "search")]
use super::search;
#[cfg(feature = "sql")]
use super::sql;
#[cfg(feature = "sql")]
use crate::Transaction;
use crate::clock::from_unix_millis;
use crate::engine::SharedFile;
use crate::kv::Handed;
use crate::pipe::{Capability, Connect};
use crate::pool::Pool;
use crate::sync::lock;
use crate::{CancellationToken, Clock, Result, Store, unix_millis};

/// The protocol this server speaks; a client of another is refused.
const PROTOCOL: u64 = 1;
const MAX_BODY: u64 = 4 << 20;
/// Streams a client may have open at once: as many writes as one grouped
/// commit carries, so an event loop with many writes in flight fills commits.
const IN_FLIGHT: u64 = 1024;
/// Bytes of REQUEST and DATA bodies a client may send before credit comes back.
pub(super) const CONNECTION_CREDIT: u64 = 8 << 20;
const STREAM_CREDIT: u64 = 2 << 20;
/// What a client grants a stream when its HELLO does not say.
const CLIENT_STREAM_CREDIT: u64 = 2 << 20;
/// The largest HELLO read before a body is agreed.
const HELLO_MOST: usize = 1 << 16;
/// The bytes of a HELLO's challenge, which a local server's proof answers.
const CHALLENGE: usize = 16;
/// What a connection may owe its client before it reads no frame more of
/// it and its workers start no call more: a PING's PONG counts against no
/// credit, and a call's answer leaves its stream's credit once queued, so a
/// client that sends and never reads would otherwise grow the server's
/// memory at the rate it sends.
pub(super) const OUTPUT_MOST: usize = 8 << 20;
/// What a connection owes its client below which it reads the frames that
/// waited, and the calls and subscriptions that stopped for its output go on.
const OUTPUT_LOW: usize = 1 << 20;

/// Requests read from a connection at once that send its point reads to the
/// workers. Five in flight are answered as fast where they are read, on a
/// host whose threads wake slowly; six are not.
const CROWD: usize = 6;

/// What a session calls when frames become ready after the host took the last
/// ones: once, until the host takes again. It must return quickly and not call
/// into the session.
pub type Wake = Arc<dyn Fn() + Send + Sync>;

/// One connection's protocol, apart from the bytes' transport: the frames a
/// client sends go in, the frames it is owed come out. A socket's server and
/// the FFI's pipe drive the same session.
pub(crate) struct Session {
    shared: Arc<Shared>,
}

struct Shared {
    store: Store,
    /// The store's pool, where the calls that do not answer inline run.
    workers: Arc<Pool>,
    kv: kv::Handles,
    #[cfg(feature = "config")]
    config: config::Configs,
    #[cfg(feature = "locks")]
    locks: Arc<locks::Holds>,
    #[cfg(feature = "channels")]
    channels: channels::Subscriptions,
    #[cfg(feature = "jobs")]
    jobs: jobs::Handles,
    #[cfg(feature = "sql")]
    sql: sql::Handles,
    #[cfg(feature = "search")]
    search: search::Handles,
    #[cfg(feature = "blobs")]
    blobs: blobs::Handles,
    #[cfg(feature = "records")]
    records: records::Handles,
    #[cfg(feature = "metrics")]
    metrics: metrics::Handles,
    #[cfg(feature = "backup")]
    backups: backup::Backups,
    input: Mutex<Input>,
    output: Mutex<Output>,
    /// Clients' runs of once, by stream, from the REQUEST to the last frame.
    runs: Mutex<HashMap<u32, ClientRun>>,
    /// The tokens of the reads the workers run, by stream, which a CANCEL of
    /// the stream or the connection's end cancels.
    reads: Mutex<HashMap<u32, CancellationToken>>,
    /// Numbers each run's asking, so that a wait that ends after its stream
    /// was cancelled, and its number named again, finds another run there.
    asked: AtomicU64,
    /// Streams whose final frame has not left, which a closing server waits
    /// for, each with its credit and the connection's bytes it holds.
    open: Mutex<HashMap<u32, OpenStream>>,
    /// REQUEST and DATA bytes the client sent and the server has not granted
    /// back: past the connection's credit is the client's fault.
    outstanding: AtomicU64,
    /// Bytes the server let go of and has not granted back yet: a grant goes
    /// once half the window has gathered.
    to_grant: AtomicU64,
    /// The largest body both sides agreed, once WELCOME went out: no frame of
    /// the server's passes it.
    agreed: AtomicUsize,
    /// Point reads the workers have of this connection, not yet answered.
    reads_away: AtomicUsize,
    /// The connection's HELLO admitted it to read only.
    read_only: AtomicBool,
    /// What the output owes, as of its last change: what the reading of
    /// frames looks at without the output's lock.
    owing: AtomicUsize,
    /// The output owed past [`OUTPUT_MOST`] when a frame came: the frames
    /// from it on wait in the reader until the host takes what is owed.
    held: AtomicBool,
    /// What waits for the output to drain: calls and subscriptions that
    /// stopped while the connection owed its client too much.
    waiting_output: Mutex<Vec<Box<dyn FnOnce() + Send>>>,
    ready: Condvar,
    /// The host's wake, called under this lock, which the session's end
    /// takes to let it go: a host frees its wake once the pipe closed, and a
    /// thread that queued a frame just before must not call it after.
    wake: Mutex<Option<Wake>>,
    connect: Connect,
}

/// A stream in use: the DATA its client may still send on it, and the bytes of
/// its REQUEST and DATA the connection's credit gets back once the server lets
/// go of them, as it grants the stream credit or ends the stream.
struct OpenStream {
    left: u64,
    held: u64,
}

/// Where a client's run of once stands.
enum ClientRun {
    /// Asking for its key, or waiting for the run that holds it.
    Asking(u64),
    /// Handed to the client, until its last DATA, a CANCEL or the session's end.
    Handed(Handed),
}

#[derive(Default)]
struct Input {
    reader: frame::Reader,
    /// The largest body both sides agreed, once WELCOME went out.
    max_body: Option<usize>,
    /// The DATA bytes the client takes on a stream before it grants more.
    stream_credit: u64,
    /// GOAWAY went out: a REQUEST after it is answered `unavailable`, unrun.
    going_away: bool,
    /// What the client may do, once its HELLO was admitted.
    capability: Option<Capability>,
    ended: bool,
    /// Whether the bytes last taken held a crowd of requests.
    crowd: bool,
}

impl Session {
    pub(crate) fn new(store: Store, mut connect: Connect) -> Result<Session> {
        let workers = Pool::of(&store)?;
        let wake = Mutex::new(connect.wake.take());
        let shared = Shared {
            store,
            workers,
            kv: kv::Handles::default(),
            #[cfg(feature = "config")]
            config: config::Configs::default(),
            #[cfg(feature = "locks")]
            locks: Arc::default(),
            #[cfg(feature = "channels")]
            channels: channels::Subscriptions::default(),
            #[cfg(feature = "jobs")]
            jobs: jobs::Handles::default(),
            #[cfg(feature = "sql")]
            sql: sql::Handles::default(),
            #[cfg(feature = "search")]
            search: search::Handles::default(),
            #[cfg(feature = "blobs")]
            blobs: blobs::Handles::default(),
            #[cfg(feature = "records")]
            records: records::Handles::default(),
            #[cfg(feature = "metrics")]
            metrics: metrics::Handles::default(),
            #[cfg(feature = "backup")]
            backups: backup::Backups::default(),
            input: Mutex::new(Input::default()),
            output: Mutex::new(Output::default()),
            runs: Mutex::new(HashMap::new()),
            reads: Mutex::new(HashMap::new()),
            asked: AtomicU64::new(0),
            open: Mutex::new(HashMap::new()),
            outstanding: AtomicU64::new(0),
            to_grant: AtomicU64::new(0),
            agreed: AtomicUsize::new(HELLO_MOST),
            reads_away: AtomicUsize::new(0),
            read_only: AtomicBool::new(false),
            owing: AtomicUsize::new(0),
            held: AtomicBool::new(false),
            waiting_output: Mutex::new(Vec::new()),
            ready: Condvar::new(),
            wake,
            connect,
        };
        shared.store.probe().shift("tinystore_wire_connections", &[], 1.0);
        Ok(Session { shared: Arc::new(shared) })
    }

    /// Takes bytes the client sent, in pieces of any size. Each frame they
    /// finish is answered: a call on the store's workers, everything else at
    /// once. A frame that breaks a rule ends the session with GOAWAY.
    pub(crate) fn receive(&self, bytes: &[u8]) {
        let mut input = self.shared.lock_input();
        if input.ended {
            return;
        }
        input.reader.push(bytes);
        input.crowd = input.reader.holds(CROWD);
        self.shared.read_frames(&mut input);
    }

    /// Whether the connection owes its client so much that it reads no frame
    /// more until the host takes some: what it is handed meanwhile waits.
    pub(crate) fn full(&self) -> bool {
        self.shared.held.load(Ordering::SeqCst)
    }

    /// The bytes ready now, leaving a wake already called to run: the host's
    /// read after a write, which a wake in flight answers anyway, so that a
    /// host writing often is not woken once a commit.
    pub(crate) fn take_ready(&self) -> Vec<u8> {
        let mut output = self.shared.lock_output();
        let taken = output.take_all();
        self.took(output);
        taken
    }

    /// As `take_ready`, into the host's own bytes: as many as fit, and how
    /// many they were.
    pub(crate) fn take_ready_into(&self, into: &mut [u8]) -> usize {
        let mut output = self.shared.lock_output();
        let taken = output.take_into(into);
        self.took(output);
        taken
    }

    /// The bytes the client is owed, waiting up to `wait` for the first; the
    /// next bytes ready wake the host again.
    pub(crate) fn take(&self, wait: Duration) -> Vec<u8> {
        let mut output = self.awaited(wait);
        let taken = output.take_all();
        self.took(output);
        taken
    }

    /// As `take`, into the host's own bytes: as many as fit, and how many
    /// they were. What did not fit stays for the next read, and wakes nobody.
    pub(crate) fn take_into(&self, wait: Duration, into: &mut [u8]) -> usize {
        let mut output = self.awaited(wait);
        let taken = output.take_into(into);
        self.took(output);
        taken
    }

    /// What follows the host's take: what the output owes now counted, then,
    /// its lock let go, what waited for it run, and the frames held for it
    /// read.
    fn took(&self, output: MutexGuard<'_, Output>) {
        self.shared.owing.store(output.owed(), Ordering::SeqCst);
        drop(output);
        self.shared.drained();
        self.shared.read_held();
    }

    /// The output once it owes bytes or `wait` has passed, the host counted
    /// as having read: the next bytes ready wake it again.
    fn awaited(&self, wait: Duration) -> MutexGuard<'_, Output> {
        let deadline = Instant::now() + wait;
        let mut output = self.shared.lock_output();
        while output.owes_nothing() && !output.ended {
            let left = deadline.saturating_duration_since(Instant::now());
            if left.is_zero() {
                break;
            }
            output.awaited = true;
            output = self.shared.ready.wait_timeout(output, left).unwrap_or_else(PoisonError::into_inner).0;
        }
        output.awaited = false;
        output.woken = false;
        output
    }

    /// Tells the client the server is closing; the streams running finish, and
    /// its workers take no job more but answer those they hold.
    pub(crate) fn go_away(&self) {
        let mut input = self.shared.lock_input();
        if input.ended || input.going_away {
            return;
        }
        input.going_away = true;
        let body = GoAway { code: "unavailable".to_owned(), message: "the server is closing".to_owned() }.encode();
        self.shared.send(&[Frame::new(Kind::GoAway, 0, body)]);
        self.end_open("the server is closing");
    }

    /// The client closed its side: no frame comes from it any more, so the
    /// streams only its cancel would end, its subscriptions, follows, tails
    /// and watches, end, and its workers take no job more. The calls running
    /// finish and their answers still leave, for a client that reads on, as
    /// a private child's parent does once it closed stdin.
    pub(crate) fn client_closed(&self) {
        self.end_open("the client closed its side");
    }

    /// Ends the streams that run until their client cancels them, saying why.
    fn end_open(&self, why: &str) {
        #[cfg(feature = "jobs")]
        {
            self.shared.jobs.halt_works();
            for watch in self.shared.jobs.take_watches() {
                watch.close(Err(Failure::unavailable(format!("{why}; watch again on another connection"))));
            }
        }
        #[cfg(feature = "records")]
        self.shared.records.go_away(why);
        #[cfg(feature = "config")]
        self.shared.config.go_away(why);
        #[cfg(feature = "channels")]
        self.shared.channels.go_away(why);
        let _ = why;
    }

    pub(crate) fn streams(&self) -> usize {
        self.shared.lock_open().len()
    }

    pub(crate) fn welcomed(&self) -> bool {
        self.shared.lock_input().max_body.is_some()
    }

    /// Whether the session reads nothing more and owes nothing more.
    pub(crate) fn finished(&self) -> bool {
        let output = self.shared.lock_output();
        output.ended && output.owes_nothing()
    }

    /// Ends the session: reads under way stop, other calls finish, what they
    /// answer is dropped, the calls waiting for the client to read are
    /// dropped unrun, the runs handed to the client are let go, and its
    /// workers end, the jobs they held failing their attempt. It waits for the
    /// workers to write that, so that a store closing with its last pipe finds
    /// them stopped rather than waits out their timeout.
    pub(crate) fn end(&self) {
        self.shared.lock_input().ended = true;
        let mut output = self.shared.lock_output();
        output.ended = true;
        output.clear();
        self.shared.owing.store(0, Ordering::SeqCst);
        drop(output);
        self.shared.ready.notify_all();
        // waits for a wake under way: once this returns none runs or will
        lock(&self.shared.wake).take();
        // a call that waits holds the session, which holds what waits
        let waiting = std::mem::take(&mut *lock(&self.shared.waiting_output));
        drop(waiting);
        let runs = std::mem::take(&mut *self.shared.lock_runs());
        drop(runs);
        let reads: Vec<CancellationToken> = lock(&self.shared.reads).drain().map(|(_, read)| read).collect();
        reads.iter().for_each(CancellationToken::cancel);
        #[cfg(feature = "jobs")]
        {
            for watch in self.shared.jobs.take_watches() {
                watch.end();
            }
            for work in self.shared.jobs.take_works() {
                work.end();
            }
        }
        #[cfg(feature = "sql")]
        self.shared.sql.end();
        #[cfg(feature = "blobs")]
        self.shared.blobs.end();
        #[cfg(feature = "records")]
        self.shared.records.end();
        #[cfg(feature = "metrics")]
        self.shared.metrics.end();
        #[cfg(feature = "config")]
        self.shared.config.end();
        #[cfg(feature = "locks")]
        self.shared.locks.end();
        #[cfg(feature = "channels")]
        self.shared.channels.end();
        #[cfg(feature = "backup")]
        self.shared.backups.end_all("the connection is gone");
    }
}

impl Shared {
    /// Answers the frames the reader holds whole, until the connection owes
    /// its client past its bound: the rest wait in the reader, read once the
    /// host takes what is owed.
    fn read_frames(self: &Arc<Self>, input: &mut Input) {
        while !input.ended {
            if input.max_body.is_some() && self.owes_past_bound() {
                return;
            }
            let max_body = input.max_body.unwrap_or(HELLO_MOST);
            match input.reader.next(max_body) {
                Ok(Some(frame)) => self.handle(input, frame),
                Ok(None) => return,
                Err(refused) => self.go_away(input, "protocol", &refused.0),
            }
        }
    }

    /// Whether the connection owes its client past its bound, which holds the
    /// frames that come. A take that lowers what is owed looks at `held`
    /// after it counted, and this looks at what is owed again after it set
    /// `held`: one of the two sees the other, so frames are never held with
    /// nobody to read them on.
    fn owes_past_bound(&self) -> bool {
        if self.owing.load(Ordering::SeqCst) > OUTPUT_MOST {
            self.held.store(true, Ordering::SeqCst);
            if self.owing.load(Ordering::SeqCst) > OUTPUT_MOST {
                return true;
            }
        }
        if self.held.load(Ordering::Relaxed) {
            self.held.store(false, Ordering::SeqCst);
        }
        false
    }

    /// Reads the frames held for the host's take, once the connection owes
    /// little.
    fn read_held(self: &Arc<Self>) {
        if !self.held.load(Ordering::SeqCst) || self.owing.load(Ordering::SeqCst) > OUTPUT_LOW {
            return;
        }
        let mut input = self.lock_input();
        self.read_frames(&mut input);
    }

    fn handle(self: &Arc<Self>, input: &mut Input, frame: Frame) {
        match (input.max_body, frame.kind) {
            (None, Kind::Hello) => self.welcome(input, &frame.body),
            (None, kind) => self.go_away(input, "protocol", &format!("a {kind:?} before HELLO")),
            (Some(_), Kind::Request) => self.request(input, frame),
            (Some(_), Kind::Data) => self.data(input, frame),
            (Some(_), Kind::Cancel) => self.cancel(frame.stream),
            (Some(_), Kind::Ping) => self.send(&[Frame::new(Kind::Pong, 0, frame.body)]),
            (Some(_), Kind::Credit) => self.credit(&frame),
            (Some(_), Kind::GoAway) => self.finish(input),
            (Some(_), kind) => self.go_away(input, "protocol", &format!("a {kind:?} from a client")),
        }
    }

    /// Answers HELLO with what the connection agrees: the protocol, and the
    /// smallest of the bodies either side takes and the client's stream
    /// credit, so that one body always fits a stream's window.
    fn welcome(&self, input: &mut Input, body: &[u8]) {
        let hello = match Hello::decode(body) {
            Ok(hello) => hello,
            Err(failure) => return self.go_away(input, "protocol", &failure.message),
        };
        if hello.protocol != PROTOCOL {
            let refused = format!("protocol {}, where this server speaks {PROTOCOL}", hello.protocol);
            return self.go_away(input, "protocol", &refused);
        }
        if let Some(length) = hello.challenge.as_ref().map(Vec::len).filter(|length| *length != CHALLENGE) {
            let refused = format!("a challenge of {length} bytes, not {CHALLENGE}");
            return self.go_away(input, "protocol", &refused);
        }
        let capability = match &self.connect.admit {
            None => Capability::Admin,
            Some(admit) => match admit(hello.token.as_deref()) {
                Some(capability) => capability,
                None => return self.go_away(input, "unauthenticated", "no token this server knows"),
            },
        };
        input.capability = Some(capability);
        self.read_only.store(capability == Capability::Read, Ordering::Relaxed);
        let client_most = hello.max_body.unwrap_or(MAX_BODY);
        let stream_credit = hello.stream_credit.unwrap_or(CLIENT_STREAM_CREDIT);
        let max_body = MAX_BODY.min(client_most).min(stream_credit);
        input.max_body = Some(max_body as usize);
        self.agreed.store(max_body as usize, Ordering::Release);
        input.stream_credit = stream_credit;
        let proof = hello.challenge.zip(self.connect.prove.as_ref()).map(|(challenge, prove)| prove(&challenge));
        self.send(&[Frame::new(Kind::Welcome, 0, self.welcome_body(max_body, capability, proof))]);
        if let Some(greeted) = &self.connect.greeted {
            greeted(&hello.client);
        }
    }

    fn welcome_body(&self, max_body: u64, capability: Capability, proof: Option<Vec<u8>>) -> Vec<u8> {
        let capability = match capability {
            Capability::Admin => "admin",
            Capability::Data => "data",
            Capability::Read => "read",
        };
        let welcome = Welcome {
            protocol: PROTOCOL,
            server: env!("CARGO_PKG_VERSION").to_owned(),
            instance: instance(),
            capability: capability.to_owned(),
            max_body,
            in_flight: IN_FLIGHT,
            connection_credit: CONNECTION_CREDIT,
            stream_credit: STREAM_CREDIT,
            engines: engines(),
            now: unix_millis(self.store.now()),
            proof,
            durability: self.store.durability().map(|durability| durability.to_string()),
        };
        welcome.encode()
    }

    /// Answers a call as its method's route says: a point read before this
    /// returns, a write once its group commits, a run of once handed over,
    /// anything else on a worker.
    fn request(self: &Arc<Self>, input: &mut Input, frame: Frame) {
        // A body past the connection's credit, a number in use, or one past
        // the streams WELCOME allowed, is the client's fault, and ends the
        // connection as the protocol says.
        let opened = self.receive(frame.body.len() as u64).and_then(|()| self.open_stream(frame.stream, &frame.body));
        if let Err(refused) = opened {
            return self.go_away(input, "protocol", &refused);
        }
        if input.going_away {
            let closing = Failure::unavailable("the server is closing; ask another connection");
            return self.answer(frame.stream, Err(closing));
        }
        if let Some(refused) = refused_to(input.capability, frame.method) {
            return self.answer(frame.stream, Err(Failure::permission(refused)));
        }
        if frame.method >> 8 == 0x00 {
            return self.server_call(frame.stream, frame.method, &frame.body);
        }
        self.route_call(input, frame);
    }

    /// Runs an admitted call where its method's route says.
    fn route_call(self: &Arc<Self>, input: &mut Input, frame: Frame) {
        let max_body = input.max_body.unwrap_or(HELLO_MOST);
        let (method, stream, body) = (frame.method, frame.stream, frame.body);
        if self.store.probe().listening() {
            self.store.probe().count("tinystore_wire_requests_total", &[("method", method_name(method))], 1.0);
        }
        // A point read is answered where it is read, in less time than
        // another thread takes to wake, while its host waits for nothing
        // else. A crowd of them would each wait its turn on this thread,
        // which is all a host with one thread has: a crowd goes to the
        // workers, where sixteen run together, and so does a read that comes
        // while they still have reads of this connection, whose answers the
        // host comes back for anyway.
        let route = route(method);
        if route == Route::Inline && (input.crowd || self.reads_away.load(Ordering::Acquire) > 0) {
            return self.read_away(stream, method, body, max_body);
        }
        match route {
            Route::Inline => self.answer(stream, guarded(|| self.call(method, &body, max_body))),
            Route::Submit => self.submit(stream, method, body),
            Route::Handover => self.hand_over(stream, body),
            #[cfg(feature = "jobs")]
            Route::Exchange => self.exchange(input, stream, &body),
            #[cfg(feature = "jobs")]
            Route::Watch => self.watch(input, stream, &body),
            #[cfg(feature = "sql")]
            Route::Download => self.download(input, stream, method, body),
            #[cfg(feature = "sql")]
            Route::Transaction => self.transaction(input, stream, &body),
            #[cfg(feature = "blobs")]
            Route::Read => self.read(input, stream, body),
            #[cfg(feature = "blobs")]
            Route::Upload => self.upload(input, stream, &body),
            #[cfg(feature = "records")]
            Route::Tail => self.tail(input, stream, &body),
            #[cfg(feature = "records")]
            Route::Lines => self.lines(input, stream, &body),
            #[cfg(feature = "metrics")]
            Route::Parts => self.parts(input, stream, method, body),
            #[cfg(feature = "metrics")]
            Route::Instruments => self.instruments(input, stream, &body),
            #[cfg(feature = "metrics")]
            Route::Gather => self.gather(input, stream, &body),
            #[cfg(feature = "config")]
            Route::Follow => self.follow(input, stream, &body),
            #[cfg(feature = "backup")]
            Route::Backup => self.backup(input, stream, &body),
            #[cfg(feature = "locks")]
            Route::Hold => self.hold(stream, &body),
            #[cfg(feature = "channels")]
            Route::Subscribe => self.subscribe(input, stream, &body),
            Route::Worker => {
                let (shared, reading) = (Arc::clone(self), self.reading(stream, method));
                let writes = method::access(method) == Some(Access::Write);
                self.run_call(Box::new(move || {
                    let answered =
                        shared.read_under(stream, reading, || guarded(|| shared.call(method, &body, max_body)));
                    shared.answer(stream, if writes { shared.written_within_agreed(answered) } else { answered });
                }));
            }
        }
    }

    /// Hands a write to its engine on a worker, which answers once its group
    /// commits.
    fn submit(self: &Arc<Self>, stream: u32, method: u16, body: Vec<u8>) {
        let shared = Arc::clone(self);
        self.run_call(Box::new(move || {
            let answering = Arc::clone(&shared);
            let done = move |answered| answering.answer(stream, answering.written_within_agreed(answered));
            let queued = guarded(|| {
                match method >> 8 {
                    #[cfg(feature = "jobs")]
                    0x02 => jobs::submit(&shared.jobs, method, &body, done),
                    #[cfg(feature = "sql")]
                    0x03 => sql::submit(&shared.sql, (method, &body), &|called, body| shared.lend(called, body), done),
                    _ => kv::submit(&shared.kv, method, &body, done),
                }
                Ok(())
            });
            if let Err(failure) = queued {
                shared.answer(stream, Err(failure));
            }
        }));
    }

    /// Asks for a once's key on a worker, the run handed to the client when
    /// it is its to run.
    fn hand_over(self: &Arc<Self>, stream: u32, body: Vec<u8>) {
        let asked = self.asked.fetch_add(1, Ordering::Relaxed);
        self.lock_runs().insert(stream, ClientRun::Asking(asked));
        let shared = Arc::clone(self);
        self.run_call(Box::new(move || shared.run_once(stream, asked, body, None)));
    }

    /// Answers a point read on a worker, counted as away until it is.
    fn read_away(self: &Arc<Self>, stream: u32, method: u16, body: Vec<u8>, max_body: usize) {
        self.reads_away.fetch_add(1, Ordering::AcqRel);
        let shared = Arc::clone(self);
        self.run_call(Box::new(move || {
            let answered = guarded(|| shared.call(method, &body, max_body));
            shared.reads_away.fetch_sub(1, Ordering::AcqRel);
            shared.answer(stream, answered);
        }));
    }

    /// Runs a call on a worker once the connection owes its client within
    /// its bound. The frames of one write are all read before a worker
    /// answers any, so the bound looked at where frames are read holds none
    /// of them: each call looks again where it starts, and one past the
    /// bound waits, as a subscription does, until the host takes what is
    /// owed. What the workers had started still answers: a call on each,
    /// and the writes they queued for a commit.
    fn run_call(self: &Arc<Self>, call: Box<dyn FnOnce() + Send>) {
        let shared = Arc::clone(self);
        self.workers.run(Box::new(move || shared.start_call(call)));
    }

    /// Runs `call` here, or once the host took what is owed. Between the two
    /// marks a call waits behind those already waiting, which the calls that
    /// keep coming would otherwise hold off for as long as they come.
    fn start_call(self: &Arc<Self>, call: Box<dyn FnOnce() + Send>) {
        let owing = self.owing.load(Ordering::SeqCst);
        if owing <= OUTPUT_LOW || (owing <= OUTPUT_MOST && lock(&self.waiting_output).is_empty()) {
            return call();
        }
        let shared = Arc::clone(self);
        self.when_drained(Box::new(move || shared.start_call(call)));
    }

    /// Registers a subscription: the stream's RESPONSE once the store has it,
    /// then its batches as DATA within the client's credit.
    #[cfg(feature = "channels")]
    fn subscribe(self: &Arc<Self>, input: &Input, stream: u32, body: &[u8]) {
        let link = self.stream_link(input, stream);
        match guarded(|| channels::subscribe(&self.store, &self.channels, stream, body, link)) {
            Ok(subscribed) => {
                self.send(&[Frame::new(Kind::Response, stream, Empty {}.encode())]);
                subscribed.begin();
            }
            Err(failure) => self.answer(stream, Err(failure)),
        }
    }

    /// Asks for the key a hold names; the stream's RESPONSE goes once the key
    /// is given, from whichever thread lets it go.
    #[cfg(feature = "locks")]
    fn hold(self: &Arc<Self>, stream: u32, body: &[u8]) {
        let answering = Arc::downgrade(self);
        let answer: locks::Answering = Box::new(move |answered| {
            if let Some(shared) = answering.upgrade() {
                shared.answer(stream, answered);
            }
        });
        if let Err(failure) = guarded(|| locks::hold(&self.store, &self.locks, stream, body, answer)) {
            self.locks.cancel(stream);
            self.answer(stream, Err(failure));
        }
    }

    /// Starts a client's worker: the stream's `RESPONSE`, then the jobs it
    /// hands the client and the client's answers, as DATA both ways.
    #[cfg(feature = "jobs")]
    fn exchange(self: &Arc<Self>, input: &Input, stream: u32, body: &[u8]) {
        match guarded(|| jobs::work(&self.jobs, stream, body, self.link(input, stream))) {
            Ok(work) => {
                self.send(&[Frame::new(Kind::Response, stream, Empty {}.encode())]);
                work.begin();
            }
            Err(failure) => self.answer(stream, Err(failure)),
        }
    }

    /// Starts a client's watch of a job: the stream's `RESPONSE`, then a DATA
    /// each time the job changes, until it ends.
    #[cfg(feature = "jobs")]
    fn watch(self: &Arc<Self>, input: &Input, stream: u32, body: &[u8]) {
        match guarded(|| jobs::watch(&self.jobs, stream, body, self.link(input, stream))) {
            Ok(watch) => {
                self.send(&[Frame::new(Kind::Response, stream, Empty {}.encode())]);
                watch.begin();
            }
            Err(failure) => self.answer(stream, Err(failure)),
        }
    }

    /// What a stream the server sends DATA on needs of the session.
    #[cfg(feature = "jobs")]
    fn link(self: &Arc<Self>, input: &Input, stream: u32) -> jobs::Link {
        let (sending, finishing, spawning) = (Arc::downgrade(self), Arc::downgrade(self), Arc::downgrade(self));
        let send: jobs::Sender = Arc::new(move |body| {
            if let Some(shared) = sending.upgrade() {
                shared.send(&[Frame::new(Kind::Data, stream, body)]);
            }
        });
        let finish: jobs::Finisher = Arc::new(move |last| {
            if let Some(shared) = finishing.upgrade() {
                shared.end_stream(stream, last);
            }
        });
        let spawn: jobs::Spawn = Arc::new(move |task| {
            if let Some(shared) = spawning.upgrade() {
                shared.workers.run(task);
            }
        });
        let max_body = input.max_body.unwrap_or(HELLO_MOST);
        jobs::Link { send, finish, spawn, credit: input.stream_credit, max_body }
    }

    /// Answers a query on a worker: its rows in the RESPONSE when they fit
    /// one message, else a RESPONSE and their parts as DATA within the
    /// client's credit.
    #[cfg(feature = "sql")]
    fn download(self: &Arc<Self>, input: &Input, stream: u32, called: u16, body: Vec<u8>) {
        let link = self.sql_link(input, stream);
        let (shared, reading) = (Arc::clone(self), self.reading(stream, called));
        self.run_call(Box::new(move || {
            let (answering, sending) = (Arc::clone(&shared), link.clone());
            let done = move |queried: std::result::Result<sql::Queried, Failure>| match queried {
                Ok(sql::Queried::Whole(rows)) => answering.answer(stream, Ok(rows)),
                Ok(sql::Queried::Parts(parts, held)) => {
                    answering.send(&[Frame::new(Kind::Response, stream, Empty {}.encode())]);
                    sql::download(&answering.sql, stream, (parts, held), &sending);
                }
                Err(failure) => answering.answer(stream, Err(failure)),
            };
            let queued = shared.read_under(stream, reading, || {
                guarded(|| {
                    let read_only = shared.read_only.load(Ordering::Relaxed);
                    sql::query(&shared.sql, (called, &body), &link, read_only, done);
                    Ok(())
                })
            });
            if let Err(failure) = queued {
                shared.answer(stream, Err(failure));
            }
        }));
    }

    /// Opens a client's transaction: the stream's RESPONSE, then, in its turn
    /// on its database's line, a worker that holds the writer while the
    /// client's calls come as DATA.
    #[cfg(feature = "sql")]
    fn transaction(self: &Arc<Self>, input: &Input, stream: u32, body: &[u8]) {
        let link = self.sql_link(input, stream);
        match guarded(|| sql::transaction(&self.sql, stream, body, &link)) {
            Ok((txing, running)) => {
                self.send(&[Frame::new(Kind::Response, stream, Empty {}.encode())]);
                let (shared, line) = (Arc::clone(self), running.line());
                let turn = Box::new(move || {
                    let nested = |tx: &Transaction<'_>, method, body: &[u8], max_body| {
                        shared.call_in(tx, method, body, max_body)
                    };
                    txing.run(running, &shared.sql, stream, &nested);
                });
                self.workers.run_in_line(&line, turn);
            }
            Err(failure) => self.answer(stream, Err(failure)),
        }
    }

    /// Answers a read of a file's bytes on a worker: its first piece in the
    /// RESPONSE, and the rest as pieces within the client's credit.
    #[cfg(feature = "blobs")]
    fn read(self: &Arc<Self>, input: &Input, stream: u32, body: Vec<u8>) {
        let link = self.stream_link(input, stream);
        let shared = Arc::clone(self);
        self.run_call(Box::new(move || match guarded(|| blobs::read(&shared.blobs, stream, &body, &link)) {
            Ok(blobs::Reading::Whole(response)) => shared.answer(stream, Ok(response)),
            Ok(blobs::Reading::Begun(response, getting)) => {
                shared.queue_moved(Frame::new(Kind::Response, stream, response), None);
                getting.pump();
            }
            Err(failure) => shared.answer(stream, Err(failure)),
        }));
    }

    /// Begins an upload: the stream's RESPONSE, then the client's pieces as
    /// DATA, its last publishing the file.
    #[cfg(feature = "blobs")]
    fn upload(self: &Arc<Self>, input: &Input, stream: u32, body: &[u8]) {
        let link = self.stream_link(input, stream);
        match guarded(|| blobs::upload(&self.blobs, stream, body, &link)) {
            Ok(()) => self.send(&[Frame::new(Kind::Response, stream, Empty {}.encode())]),
            Err(failure) => self.answer(stream, Err(failure)),
        }
    }

    /// Starts a client's tail: the stream's RESPONSE, then a DATA each time
    /// events arrive that its query finds.
    #[cfg(feature = "records")]
    fn tail(self: &Arc<Self>, input: &Input, stream: u32, body: &[u8]) {
        let link = self.stream_link(input, stream);
        match guarded(|| records::tail(&self.store, &self.records, stream, body, link)) {
            Ok(tailing) => {
                self.send(&[Frame::new(Kind::Response, stream, Empty {}.encode())]);
                tailing.begin();
            }
            Err(failure) => self.answer(stream, Err(failure)),
        }
    }

    /// Begins a client's writer of lines: the stream's RESPONSE, then its
    /// pieces as DATA, the last answered with what the writer dropped.
    #[cfg(feature = "records")]
    fn lines(self: &Arc<Self>, input: &Input, stream: u32, body: &[u8]) {
        let link = self.stream_link(input, stream);
        match guarded(|| records::lines(&self.records, stream, body, link)) {
            Ok(()) => self.send(&[Frame::new(Kind::Response, stream, Empty {}.encode())]),
            Err(failure) => self.answer(stream, Err(failure)),
        }
    }

    /// Answers a read, the newest samples or an aggregate on a worker: one
    /// part in the RESPONSE, or the RESPONSE and then the parts within the
    /// client's credit, half of what it takes at once each.
    #[cfg(feature = "metrics")]
    fn parts(self: &Arc<Self>, input: &Input, stream: u32, called: u16, body: Vec<u8>) {
        let link = self.stream_link(input, stream);
        let (shared, reading) = (Arc::clone(self), self.reading(stream, called));
        self.run_call(Box::new(move || {
            let bound = super::part_bound(link.max_body, link.credit, 0);
            let parted =
                shared.read_under(stream, reading, || guarded(|| metrics::parts(&shared.store, called, &body, bound)));
            match parted {
                Ok(mut parts) if parts.len() == 1 => shared.answer(stream, Ok(parts.pop_front().unwrap_or_default())),
                Ok(parts) => {
                    shared.send(&[Frame::new(Kind::Response, stream, Empty {}.encode())]);
                    metrics::download(&shared.metrics, stream, parts, link);
                }
                Err(failure) => shared.answer(stream, Err(failure)),
            }
        }));
    }

    /// Opens a client's instruments' stream: the RESPONSE says what the
    /// store knows of its session, then its batches come as DATA, each
    /// answered with one.
    #[cfg(feature = "metrics")]
    fn instruments(self: &Arc<Self>, input: &Input, stream: u32, body: &[u8]) {
        let link = self.stream_link(input, stream);
        match guarded(|| metrics::instruments(&self.store, &self.metrics, stream, body, link)) {
            Ok(response) => self.send(&[Frame::new(Kind::Response, stream, response)]),
            Err(failure) => self.answer(stream, Err(failure)),
        }
    }

    /// Begins a text a client sends in pieces: the stream's RESPONSE, then
    /// the store's memory for the whole text, then its pieces as DATA, the
    /// last answered once the text is written. The memory is reserved on a
    /// worker once the RESPONSE has gone: its refusal, a final frame, never
    /// leaves before it.
    #[cfg(feature = "metrics")]
    fn gather(self: &Arc<Self>, input: &Input, stream: u32, body: &[u8]) {
        let link = self.stream_link(input, stream);
        match guarded(|| metrics::gather(&self.store, &self.metrics, stream, body, link)) {
            Ok(gathering) => {
                self.send(&[Frame::new(Kind::Response, stream, Empty {}.encode())]);
                gathering.begin();
            }
            Err(failure) => self.answer(stream, Err(failure)),
        }
    }

    /// Starts a client's follow of a config: the stream's RESPONSE, then a
    /// DATA with its value now and one each time it changes.
    #[cfg(feature = "config")]
    fn follow(self: &Arc<Self>, input: &Input, stream: u32, body: &[u8]) {
        let link = self.stream_link(input, stream);
        match guarded(|| config::follow(&self.config, stream, body, link)) {
            Ok(following) => {
                self.send(&[Frame::new(Kind::Response, stream, Empty {}.encode())]);
                following.begin();
            }
            Err(failure) => self.answer(stream, Err(failure)),
        }
    }

    /// Starts a backup of the store: the stream's RESPONSE, then its zip in
    /// pieces within the client's credit, then what it holds.
    #[cfg(feature = "backup")]
    fn backup(self: &Arc<Self>, input: &Input, stream: u32, body: &[u8]) {
        let link = self.stream_link(input, stream);
        match guarded(|| backup::asked(&self.backups, stream, body, link)) {
            Ok(sending) => {
                self.send(&[Frame::new(Kind::Response, stream, Empty {}.encode())]);
                sending.begin(&self.store, &self.backups);
            }
            Err(failure) => self.answer(stream, Err(failure)),
        }
    }

    /// What a stream of a file's bytes, a tail's batches, a writer's lines, a
    /// read's parts, a client's instruments, a text's pieces, a config's
    /// values or a backup's zip needs of the session.
    #[cfg(any(
        feature = "blobs",
        feature = "records",
        feature = "metrics",
        feature = "config",
        feature = "backup",
        feature = "channels"
    ))]
    fn stream_link(self: &Arc<Self>, input: &Input, stream: u32) -> super::Link {
        let (sending, finishing, granting, spawning) =
            (Arc::downgrade(self), Arc::downgrade(self), Arc::downgrade(self), Arc::downgrade(self));
        super::Link {
            send: Arc::new(move |body| {
                if let Some(shared) = sending.upgrade() {
                    shared.queue_moved(Frame::new(Kind::Data, stream, body), None);
                }
            }),
            finish: Arc::new(move |last| {
                if let Some(shared) = finishing.upgrade() {
                    shared.end_stream(stream, last);
                }
            }),
            grant: Arc::new(move |bytes: u32| {
                if let Some(shared) = granting.upgrade() {
                    shared.send(&[Frame::new(Kind::Credit, stream, bytes.to_le_bytes().to_vec())]);
                }
            }),
            spawn: Arc::new(move |task| {
                if let Some(shared) = spawning.upgrade() {
                    shared.workers.run(task);
                }
            }),
            credit: input.stream_credit,
            max_body: input.max_body.unwrap_or(HELLO_MOST),
            #[cfg(feature = "channels")]
            owed: {
                let owing = Arc::downgrade(self);
                Arc::new(move || owing.upgrade().map_or(0, |shared| shared.owed()))
            },
            #[cfg(feature = "channels")]
            when_drained: {
                let draining = Arc::downgrade(self);
                Arc::new(move |task| {
                    if let Some(shared) = draining.upgrade() {
                        shared.when_drained(task);
                    }
                })
            },
        }
    }

    /// What an sql stream that sends DATA needs of the session.
    #[cfg(feature = "sql")]
    fn sql_link(self: &Arc<Self>, input: &Input, stream: u32) -> sql::Link {
        let (sending, finishing) = (Arc::downgrade(self), Arc::downgrade(self));
        sql::Link {
            send: Arc::new(move |body| {
                if let Some(shared) = sending.upgrade() {
                    shared.send(&[Frame::new(Kind::Data, stream, body)]);
                }
            }),
            finish: Arc::new(move |last| {
                if let Some(shared) = finishing.upgrade() {
                    shared.end_stream(stream, last);
                }
            }),
            credit: input.stream_credit,
            max_body: input.max_body.unwrap_or(HELLO_MOST),
        }
    }

    /// Starts a client's run of a once key: its kept answer ends the stream, a
    /// run handed over waits for the client's last DATA, and a run held
    /// elsewhere asks again once it ends, unless it ends with an answer it
    /// could not keep, which is this client's. A run cancelled meanwhile goes
    /// back.
    fn run_once(self: &Arc<Self>, stream: u32, asked: u64, body: Vec<u8>, unkept: Option<Arc<crate::kv::Raw>>) {
        if !still_asking(&self.lock_runs(), stream, asked) {
            return;
        }
        let started = match unkept {
            Some(raw) => Ok(kv::unkept(&raw)),
            None => {
                let again = {
                    let (shared, body) = (Arc::clone(self), body.clone());
                    Box::new(move |unkept| {
                        let asking = Arc::clone(&shared);
                        shared.workers.run(Box::new(move || asking.run_once(stream, asked, body, unkept)));
                    })
                };
                catch_unwind(AssertUnwindSafe(|| kv::run(&self.kv, &body, again)))
                    .unwrap_or_else(|_| Err(Failure::internal("a call panicked")))
            }
        };
        // the answer leaves under the lock, so that a CANCEL either finds the
        // run or comes after this stream's frames
        let mut runs = self.lock_runs();
        if !still_asking(&runs, stream, asked) {
            drop(runs);
            drop(started);
            return;
        }
        match started {
            Ok(Run::Answered(answer)) => {
                runs.remove(&stream);
                self.answer(stream, Ok(answer));
            }
            Ok(Run::Handed(handed, answer)) => {
                runs.insert(stream, ClientRun::Handed(*handed));
                self.send(&[Frame::new(Kind::Response, stream, answer)]);
            }
            Ok(Run::Waiting) => {}
            Err(failure) => {
                runs.remove(&stream);
                self.answer(stream, Err(failure));
            }
        }
    }

    /// A client's DATA: an item of its worker's stream, or the last of a run
    /// handed over, its answer to keep. A DATA of a stream no longer in use is
    /// dropped, its credit still given back.
    fn data(self: &Arc<Self>, input: &mut Input, frame: Frame) {
        let bytes = frame.body.len() as u64;
        if let Err(refused) = self.receive(bytes).and_then(|()| self.spend_stream_credit(frame.stream, bytes)) {
            return self.go_away(input, "protocol", &refused);
        }
        #[cfg(feature = "blobs")]
        if let Some(uploading) = self.blobs.uploading(frame.stream) {
            let last = frame.flags & frame::END != 0;
            return uploading.piece(frame.body, last);
        }
        #[cfg(feature = "records")]
        if self.records.piece(frame.stream, &frame.body, frame.flags & frame::END != 0) {
            return;
        }
        #[cfg(feature = "metrics")]
        if let Some(gathering) = self.metrics.gathering(frame.stream) {
            return gathering.piece(frame.body, frame.flags & frame::END != 0);
        }
        #[cfg(feature = "metrics")]
        if self.metrics.batch(frame.stream, &frame.body, frame.flags & frame::END != 0) {
            return;
        }
        #[cfg(feature = "sql")]
        if let Some(tx) = self.sql.tx(frame.stream) {
            // a call is read once it is queued: its credit goes back at once
            if let Ok(read) = u32::try_from(frame.body.len()) {
                self.send(&[Frame::new(Kind::Credit, frame.stream, read.to_le_bytes().to_vec())]);
            }
            return tx.item(&frame.body, frame.flags & frame::END != 0);
        }
        #[cfg(feature = "jobs")]
        if let Some(work) = self.jobs.work(frame.stream) {
            return self.work_data(&work, &frame);
        }
        if frame.flags & frame::END == 0 {
            return;
        }
        let handed = {
            let mut runs = self.lock_runs();
            match runs.remove(&frame.stream) {
                Some(ClientRun::Handed(handed)) => handed,
                Some(asking) => {
                    runs.insert(frame.stream, asking);
                    return;
                }
                None => return,
            }
        };
        let (shared, stream, body) = (Arc::clone(self), frame.stream, frame.body);
        self.workers.run(Box::new(move || {
            let kept = guarded(|| kv::kept(handed, &body));
            shared.end_stream(stream, kept);
        }));
    }

    /// A client's item on its worker's stream: an answer, a progress or a
    /// stop. Its END ends the worker, and the server's DATA·END follows once
    /// what was answered is written; an item that is not one fails the stream.
    #[cfg(feature = "jobs")]
    fn work_data(self: &Arc<Self>, work: &jobs::Work, frame: &Frame) {
        // The stream's grant waits for half its window, which nine workers
        // sharing the connection's window may never reach: the connection
        // gets its bytes back as soon as the item is read.
        self.let_go_of(frame.stream, frame.body.len() as u64);
        if let Some(granted) = work.release(frame.body.len() as u64, STREAM_CREDIT) {
            self.send(&[Frame::new(Kind::Credit, frame.stream, granted.to_le_bytes().to_vec())]);
        }
        let ended = frame.flags & frame::END != 0;
        let item = if ended && frame.body.is_empty() { Ok(()) } else { guarded(|| work.item(&frame.body)) };
        match (item, ended) {
            (Ok(()), false) => {}
            (Ok(()), true) => self.end_work(frame.stream, Ok(Empty {}.encode())),
            (Err(failure), _) => self.end_work(frame.stream, Err(failure)),
        }
    }

    /// Ends a client's worker off this thread, and its stream with `last` once
    /// the worker wrote what was answered.
    #[cfg(feature = "jobs")]
    fn end_work(self: &Arc<Self>, stream: u32, last: std::result::Result<Vec<u8>, Failure>) {
        let Some(work) = self.jobs.take_work(stream) else {
            return;
        };
        let shared = Arc::clone(self);
        self.workers.run(Box::new(move || {
            work.end();
            shared.end_stream(stream, last);
        }));
    }

    /// A client's grant of DATA on a stream: a worker's or a watch's sends
    /// what waited for it. No other stream sends DATA a client grants credit
    /// for: a call answers in one message, within the body agreed.
    #[cfg_attr(
        not(any(
            feature = "jobs",
            feature = "sql",
            feature = "blobs",
            feature = "records",
            feature = "metrics",
            feature = "config",
            feature = "backup",
            feature = "channels"
        )),
        expect(
            unused_variables,
            reason = "only the streams of jobs, sql, blobs, records, metrics, config, backup and channels take credit"
        )
    )]
    fn credit(&self, frame: &Frame) {
        let Ok(granted) = <[u8; 4]>::try_from(frame.body.as_slice()) else {
            return;
        };
        let granted = u32::from_le_bytes(granted);
        #[cfg(feature = "jobs")]
        self.jobs.grant(frame.stream, granted);
        #[cfg(feature = "sql")]
        self.sql.grant(frame.stream, granted);
        #[cfg(feature = "blobs")]
        self.blobs.grant(frame.stream, granted);
        #[cfg(feature = "records")]
        self.records.grant(frame.stream, granted);
        #[cfg(feature = "metrics")]
        self.metrics.grant(frame.stream, granted);
        #[cfg(feature = "config")]
        self.config.grant(frame.stream, granted);
        #[cfg(feature = "backup")]
        self.backups.grant(frame.stream, granted);
        #[cfg(feature = "channels")]
        self.channels.grant(frame.stream, granted);
    }

    /// Lets go of a client's run of once, answering `cancelled`. A read under
    /// way stops, its statement interrupted, and answers `cancelled`; a call
    /// that writes runs to its end, short as a call is. A worker cancelled
    /// ends as its END would end it, the jobs it held failing their attempt,
    /// and a watch cancelled ends.
    fn cancel(self: &Arc<Self>, stream: u32) {
        let read = lock(&self.reads).get(&stream).cloned();
        if let Some(read) = read {
            read.cancel();
        }
        #[cfg(feature = "sql")]
        if self.sql.cancel(stream) {
            return;
        }
        #[cfg(feature = "blobs")]
        if self.blobs.cancel(stream) {
            return;
        }
        #[cfg(feature = "records")]
        if self.records.cancel(stream) {
            return;
        }
        #[cfg(feature = "metrics")]
        if self.metrics.cancel(stream) {
            return;
        }
        #[cfg(feature = "config")]
        if self.config.cancel(stream) {
            return;
        }
        #[cfg(feature = "backup")]
        if self.backups.cancel(stream) {
            return;
        }
        #[cfg(feature = "channels")]
        if self.channels.cancel(stream) {
            return;
        }
        #[cfg(feature = "locks")]
        if self.locks.cancel(stream) {
            return self.answer(stream, Err(Failure::cancelled("the client cancelled its hold")));
        }
        #[cfg(feature = "jobs")]
        if self.jobs.work(stream).is_some() {
            return self.end_work(stream, Err(Failure::cancelled("the client cancelled its worker")));
        }
        #[cfg(feature = "jobs")]
        if let Some(watch) = self.jobs.take_watch(stream) {
            return watch.close(Err(Failure::cancelled("the client cancelled its watch")));
        }
        let mut runs = self.lock_runs();
        let cancelled = Failure::cancelled("the client cancelled the run");
        match runs.remove(&stream) {
            Some(ClientRun::Asking(_)) => self.answer(stream, Err(cancelled)),
            Some(ClientRun::Handed(handed)) => {
                self.end_stream(stream, Err(cancelled));
                drop(runs);
                drop(handed);
            }
            None => {}
        }
    }

    /// The token of a read a worker runs for `stream`, which a CANCEL of the
    /// stream cancels; none for a call that writes, which runs to its end.
    fn reading(&self, stream: u32, method: u16) -> Option<CancellationToken> {
        if method::access(method) != Some(Access::Read) {
            return None;
        }
        let token = CancellationToken::new();
        lock(&self.reads).insert(stream, token.clone());
        Some(token)
    }

    /// Runs `read` under its stream's token, then lets the token go, unless a
    /// REQUEST that named the stream's number again has put its own there.
    fn read_under<T>(&self, stream: u32, token: Option<CancellationToken>, read: impl FnOnce() -> T) -> T {
        let Some(token) = token else { return read() };
        let answered = token.run(read);
        let mut reads = lock(&self.reads);
        if reads.get(&stream).is_some_and(|kept| kept.same(&token)) {
            reads.remove(&stream);
        }
        answered
    }

    /// The server's own methods, answered before this returns: a stop once its
    /// answer has left, so that the client hears it before the GOAWAY.
    fn server_call(&self, stream: u32, called: u16, body: &[u8]) {
        match called {
            method::SERVER_STOP => match self.stopping(body) {
                Ok(stop) => {
                    self.answer(stream, Ok(Empty {}.encode()));
                    stop();
                }
                Err(failure) => self.answer(stream, Err(failure)),
            },
            method::SERVER_CLOCK => self.answer(stream, guarded(|| self.clock(body))),
            other => self.answer(stream, Err(Failure::unimplemented(format!("method {other:#06x}")))),
        }
    }

    fn stopping(&self, body: &[u8]) -> std::result::Result<crate::pipe::Stop, Failure> {
        Empty::decode(body)?;
        let refused = || Failure::permission("this store's program decides when its server stops");
        self.connect.stop.clone().ok_or_else(refused)
    }

    /// Reads a private server's clock, set to a time or moved forward first.
    fn clock(&self, body: &[u8]) -> std::result::Result<Vec<u8>, Failure> {
        let asked = ServerClock::decode(body)?;
        let Some(clock) = &self.connect.clock else {
            return Err(Failure::invalid("a clock call to a server that runs on the system's clock"));
        };
        match (asked.at, asked.advance) {
            (Some(_), Some(_)) => return Err(Failure::invalid("a clock set and moved in one call")),
            (Some(at), None) => clock.set(from_unix_millis(at))?,
            (None, Some(advance)) => clock.advance(Duration::from_millis(advance)),
            (None, None) => return Ok(ServerClock { at: Some(unix_millis(clock.now())), advance: None }.encode()),
        }
        self.store.clock_moved();
        Ok(ServerClock { at: Some(unix_millis(clock.now())), advance: None }.encode())
    }

    /// Ends a stream with its RESPONSE.
    fn answer(&self, stream: u32, answered: std::result::Result<Vec<u8>, Failure>) {
        let response = match self.within_agreed(answered) {
            Ok(body) => Frame::new(Kind::Response, stream, body).ending(),
            Err(failure) => Frame::new(Kind::Response, stream, failure.encode()).failing(),
        };
        self.send_last(response);
    }

    /// Ends a stream whose RESPONSE went out already, with its last DATA.
    fn end_stream(&self, stream: u32, answered: std::result::Result<Vec<u8>, Failure>) {
        let data = match self.within_agreed(answered) {
            Ok(body) => Frame::new(Kind::Data, stream, body).ending(),
            Err(failure) => Frame::new(Kind::Data, stream, failure.encode()).failing(),
        };
        self.send_last(data);
    }

    fn call(&self, method: u16, body: &[u8], max_body: usize) -> std::result::Result<Vec<u8>, Failure> {
        let started = self.store.probe().start();
        let answered = self.call_engine(method, body, max_body);
        if let Some(started) = started {
            self.store.probe().time("tinystore_wire_call_ms", &[("method", method_name(method))], started.elapsed());
        }
        answered
    }

    fn call_engine(&self, method: u16, body: &[u8], max_body: usize) -> std::result::Result<Vec<u8>, Failure> {
        let lent = |handle| self.lent(handle);
        match method >> 8 {
            0x01 => {
                let read_only = self.read_only.load(Ordering::Relaxed);
                kv::call(&self.store, &self.kv, &lent, method, body, (max_body, read_only))
            }
            #[cfg(feature = "jobs")]
            0x02 => jobs::call(&self.store, &self.jobs, &lent, method, body, max_body),
            #[cfg(feature = "sql")]
            0x03 => sql::call(&self.store, &self.sql, method, body, self.read_only.load(Ordering::Relaxed)),
            #[cfg(feature = "blobs")]
            0x04 => blobs::call(&self.store, &self.blobs, &lent, method, body, max_body),
            #[cfg(feature = "records")]
            0x05 => records::call(&self.store, &self.records, method, body, self.read_only.load(Ordering::Relaxed)),
            #[cfg(feature = "metrics")]
            0x06 => metrics::call(&self.store, method, body, max_body),
            #[cfg(feature = "config")]
            0x07 => config::call(&self.store, &self.config, method, body, self.read_only.load(Ordering::Relaxed)),
            #[cfg(feature = "locks")]
            0x09 => locks::call(&self.store, method, body),
            #[cfg(feature = "channels")]
            0x0a => channels::call(&self.store, method, body),
            #[cfg(feature = "search")]
            0x0b => {
                let read_only = self.read_only.load(Ordering::Relaxed);
                search::call(&self.store, &self.search, &lent, method, body, read_only)
            }
            _ => Err(Failure::unimplemented(format!("method {method:#06x}"))),
        }
    }

    /// The file of a database this connection opened, for a bucket or a
    /// queue opened in it.
    fn lent(&self, handle: u64) -> std::result::Result<Arc<SharedFile>, Failure> {
        #[cfg(feature = "sql")]
        return self.sql.shared(handle);
        #[cfg(not(feature = "sql"))]
        Err(Failure::invalid(format!("database {handle}: this server keeps no databases")))
    }

    /// A call of another engine that a database's batch carries: a queue's
    /// add, for a queue kept in the database's file.
    #[cfg(feature = "sql")]
    fn lend(&self, called: u16, body: &[u8]) -> std::result::Result<crate::sql::Write, Failure> {
        match called {
            #[cfg(feature = "jobs")]
            method::JOBS_ADD => jobs::lend(&self.jobs, body),
            _ => Err(Failure::invalid(format!(
                "method {called:#06x} does not run in a batch, which takes a queue's add"
            ))),
        }
    }

    /// Answers a call of kv or jobs made inside a database's transaction.
    #[cfg(feature = "sql")]
    fn call_in(
        &self,
        tx: &Transaction<'_>,
        method: u16,
        body: &[u8],
        max_body: usize,
    ) -> std::result::Result<Vec<u8>, Failure> {
        match method >> 8 {
            0x01 => kv::call_in(&self.kv, tx, method, body, max_body),
            #[cfg(feature = "jobs")]
            0x02 => jobs::call_in(&self.jobs, tx, method, body, max_body),
            #[cfg(feature = "blobs")]
            0x04 => blobs::call_in(&self.blobs, tx, method, body),
            #[cfg(feature = "channels")]
            0x0a => channels::call_in(&self.store, tx, method, body),
            _ => Err(Failure::invalid(format!("method {method:#06x} does not run inside a transaction"))),
        }
    }

    fn go_away(&self, input: &mut Input, code: &str, message: &str) {
        let body = GoAway { code: code.to_owned(), message: message.to_owned() }.encode();
        self.send(&[Frame::new(Kind::GoAway, 0, body)]);
        self.finish(input);
    }

    /// Reads nothing more; what is owed already stays for the host to take.
    fn finish(&self, input: &mut Input) {
        input.ended = true;
        self.lock_output().ended = true;
        self.ready.notify_all();
    }

    fn send(&self, frames: &[Frame]) {
        self.queue(frames, None);
    }

    /// Runs what waited for the output once it owes less than its low mark.
    fn drained(&self) {
        let mut waiting = self.waiting_output.lock().unwrap_or_else(PoisonError::into_inner);
        if waiting.is_empty() || self.owed() > OUTPUT_LOW {
            return;
        }
        for task in std::mem::take(&mut *waiting) {
            self.workers.run(task);
        }
    }

    /// The bytes queued for the client and not yet taken by the host.
    fn owed(&self) -> usize {
        self.lock_output().owed()
    }

    /// Runs `task` once the output drains; at once when it has already.
    fn when_drained(&self, task: Box<dyn FnOnce() + Send>) {
        self.waiting_output.lock().unwrap_or_else(PoisonError::into_inner).push(task);
        self.drained();
    }

    /// Sends a stream's last frame.
    fn send_last(&self, frame: Frame) {
        let stream = frame.stream;
        self.queue_moved(frame, Some(stream));
    }

    /// Takes a stream number into use, refusing one in use already or one
    /// past the streams in flight WELCOME allowed.
    fn open_stream(&self, stream: u32, body: &[u8]) -> std::result::Result<(), String> {
        let mut open = self.lock_open();
        if open.contains_key(&stream) {
            return Err(format!("a REQUEST on stream {stream}, which is in use"));
        }
        if open.len() >= IN_FLIGHT as usize {
            return Err(format!("a REQUEST past the {IN_FLIGHT} streams in flight WELCOME allowed"));
        }
        open.insert(stream, OpenStream { left: STREAM_CREDIT, held: body.len() as u64 });
        Ok(())
    }

    /// Counts a body against the connection's credit.
    fn receive(&self, bytes: u64) -> std::result::Result<(), String> {
        let outstanding = self.outstanding.fetch_add(bytes, Ordering::AcqRel) + bytes;
        if outstanding > CONNECTION_CREDIT {
            return Err(format!("{outstanding} bytes sent past the connection's credit of {CONNECTION_CREDIT}"));
        }
        Ok(())
    }

    /// Counts a DATA body against its stream's credit; one past it is the
    /// client's fault. A DATA of a stream no longer in use is dropped, as the
    /// protocol says, and counts against nothing.
    fn spend_stream_credit(&self, stream: u32, bytes: u64) -> std::result::Result<(), String> {
        let mut open = self.lock_open();
        let Some(opened) = open.get_mut(&stream) else {
            drop(open);
            self.let_go(bytes);
            self.grant_when_due();
            return Ok(());
        };
        opened.left =
            opened.left.checked_sub(bytes).ok_or_else(|| format!("a DATA on stream {stream} past its credit"))?;
        opened.held += bytes;
        Ok(())
    }

    /// Gives the connection back `bytes` a stream holds of it, the stream's
    /// own credit left as it is: what the server read and let go of before
    /// it grants the stream more.
    #[cfg(feature = "jobs")]
    fn let_go_of(&self, stream: u32, bytes: u64) {
        let released = match self.lock_open().get_mut(&stream) {
            Some(opened) => {
                let released = bytes.min(opened.held);
                opened.held -= released;
                released
            }
            None => return,
        };
        self.let_go(released);
        self.grant_when_due();
    }

    /// Bytes the server let go of, which the next grant gives back.
    fn let_go(&self, bytes: u64) {
        self.to_grant.fetch_add(bytes, Ordering::AcqRel);
    }

    /// Grants the connection's credit back once half its window gathered.
    fn grant_when_due(&self) {
        let gathered = self.to_grant.load(Ordering::Acquire);
        if gathered < CONNECTION_CREDIT / 2 {
            return;
        }
        let granted = self.to_grant.swap(0, Ordering::AcqRel);
        if granted == 0 {
            return;
        }
        self.outstanding.fetch_sub(granted, Ordering::AcqRel);
        let granted = u32::try_from(granted).unwrap_or(u32::MAX);
        self.send(&[Frame::new(Kind::Credit, 0, granted.to_le_bytes().to_vec())]);
    }

    /// A body as it may go out: one past the agreed body is `limit`, which a
    /// client takes, rather than a frame it would end the connection over.
    fn within_agreed(&self, answered: std::result::Result<Vec<u8>, Failure>) -> std::result::Result<Vec<u8>, Failure> {
        let agreed = self.agreed.load(Ordering::Acquire);
        match answered {
            Ok(body) if body.len() > agreed => Err(Failure {
                code: "limit".to_owned(),
                message: format!("an answer of {} bytes, past the {agreed} a body holds", body.len()),
                what: None,
            }),
            answered => answered,
        }
    }

    /// A write's answer as it may go out. Past the agreed body it is
    /// `outcome_unknown`, never `limit`: the write ran, what it took is gone,
    /// and a client that sent it again, as it does a `limit`, would write
    /// twice.
    fn written_within_agreed(
        &self,
        answered: std::result::Result<Vec<u8>, Failure>,
    ) -> std::result::Result<Vec<u8>, Failure> {
        let agreed = self.agreed.load(Ordering::Acquire);
        match answered {
            Ok(body) if body.len() > agreed => Err(Failure {
                code: "outcome_unknown".to_owned(),
                message: format!(
                    "the write ran, and its answer of {} bytes is past the {agreed} a body holds: read what it wrote",
                    body.len()
                ),
                what: None,
            }),
            answered => answered,
        }
    }

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

    /// Queues frames for the host to take, `ended` of them their streams'
    /// last. Those streams leave the count under the output's lock, after
    /// their frames are queued: whoever read a stream's last frame finds
    /// `streams` without it, and whoever finds no stream finds every last
    /// frame queued. Counted after the lock instead, a client that had read
    /// its answer could still see its stream in flight.
    fn queue(&self, frames: &[Frame], ended: Option<u32>) {
        let mut output = self.lock_output();
        let dropped = output.ended && frames.iter().all(|frame| frame.kind != Kind::GoAway);
        if !dropped {
            for frame in frames {
                output.copy(frame);
            }
        }
        self.queued(output, dropped, frames, ended);
    }

    /// Queues one frame as `queue` does, a long body moved behind what is
    /// owed rather than copied: a file's mebibyte is written once into the
    /// message that carries it, and once more into the host's bytes.
    fn queue_moved(&self, frame: Frame, ended: Option<u32>) {
        debug_assert!(frame.kind != Kind::Credit, "a grant is counted where it is queued");
        let mut output = self.lock_output();
        let dropped = output.ended && frame.kind != Kind::GoAway;
        if !dropped {
            output.push(frame);
        }
        self.queued(output, dropped, &[], ended);
    }

    /// What follows the frames' queueing, under the output's lock: their
    /// streams' grants and ends counted, and the host woken.
    fn queued(&self, mut output: MutexGuard<'_, Output>, dropped: bool, frames: &[Frame], ended: Option<u32>) {
        self.owing.store(output.owed(), Ordering::SeqCst);
        let mut let_go = 0;
        {
            let mut open = self.lock_open();
            // a grant of the server's on a stream is room its client may send
            // into, and says the server let go of as many of its bytes
            for frame in frames.iter().filter(|frame| frame.kind == Kind::Credit && frame.stream != 0) {
                if let (Some(opened), Ok(granted)) = (open.get_mut(&frame.stream), <[u8; 4]>::try_from(&frame.body[..]))
                {
                    let granted = u64::from(u32::from_le_bytes(granted));
                    opened.left = opened.left.saturating_add(granted);
                    let released = granted.min(opened.held);
                    opened.held -= released;
                    let_go += released;
                }
            }
            if let Some(opened) = ended.and_then(|stream| open.remove(&stream)) {
                let_go += opened.held;
            }
        }
        if let_go > 0 {
            self.let_go(let_go);
        }
        if dropped {
            return;
        }
        let wake = !std::mem::replace(&mut output.woken, true);
        let awaited = output.awaited;
        drop(output);
        if awaited {
            self.ready.notify_all();
        }
        if wake && let Some(wake) = &*lock(&self.wake) {
            wake();
        }
        // the output's lock is let go: a grant goes out as a frame of its own
        if let_go > 0 {
            self.grant_when_due();
        }
    }

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

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

    fn lock_runs(&self) -> MutexGuard<'_, HashMap<u32, ClientRun>> {
        self.runs.lock().unwrap_or_else(PoisonError::into_inner)
    }
}

/// Whether the run asked as `asked` is still the one on its stream.
fn still_asking(runs: &HashMap<u32, ClientRun>, stream: u32, asked: u64) -> bool {
    matches!(runs.get(&stream), Some(ClientRun::Asking(asking)) if *asking == asked)
}

/// Why a connection admitted as `capability` may not call `method`, if it may not.
fn refused_to(capability: Option<Capability>, method: u16) -> Option<&'static str> {
    match method::access(method) {
        Some(Access::Admin) if capability != Some(Capability::Admin) => Some("the server's own calls are an admin's"),
        Some(Access::Write) if capability == Some(Capability::Read) => Some("a read connection writes nothing"),
        _ => None,
    }
}

/// How a method runs: kv's and jobs' say theirs; every other engine's runs on
/// a worker.
fn route(method: u16) -> Route {
    match method >> 8 {
        0x01 => kv::route(method),
        #[cfg(feature = "jobs")]
        0x02 => jobs::route(method),
        #[cfg(feature = "sql")]
        0x03 => sql::route(method),
        #[cfg(feature = "blobs")]
        0x04 => blobs::route(method),
        #[cfg(feature = "records")]
        0x05 => records::route(method),
        #[cfg(feature = "metrics")]
        0x06 => metrics::route(method),
        #[cfg(feature = "config")]
        0x07 => config::route(method),
        #[cfg(feature = "backup")]
        0x08 => Route::Backup,
        #[cfg(feature = "locks")]
        0x09 => locks::route(method),
        #[cfg(feature = "channels")]
        0x0a => channels::route(method),
        _ => Route::Worker,
    }
}

/// The engines this server serves.
fn engines() -> Vec<String> {
    let jobs = cfg!(feature = "jobs").then_some("jobs");
    let sql = cfg!(feature = "sql").then_some("sql");
    let blobs = cfg!(feature = "blobs").then_some("blobs");
    let records = cfg!(feature = "records").then_some("records");
    let metrics = cfg!(feature = "metrics").then_some("metrics");
    let config = cfg!(feature = "config").then_some("config");
    let backup = cfg!(feature = "backup").then_some("backup");
    let locks = cfg!(feature = "locks").then_some("locks");
    let channels = cfg!(feature = "channels").then_some("channels");
    let search = cfg!(feature = "search").then_some("search");
    let engines = [Some("kv"), config, locks, channels, jobs, sql, blobs, records, metrics, search, backup];
    engines.into_iter().flatten().map(str::to_owned).collect()
}

/// A call that panics answers `internal` rather than leaving its stream open.
fn guarded<T>(call: impl FnOnce() -> std::result::Result<T, Failure>) -> std::result::Result<T, Failure> {
    catch_unwind(AssertUnwindSafe(call)).unwrap_or_else(|_| Err(Failure::internal("a call panicked")))
}

/// Sixteen bytes that differ for each session: the process's random hasher
/// keys, over the time and an address.
fn instance() -> Vec<u8> {
    let state = RandomState::new();
    let now = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).map_or(0, |since| since.as_nanos());
    let mut bytes = Vec::with_capacity(16);
    for half in 0..2u8 {
        let mut hasher = state.build_hasher();
        hasher.write_u8(half);
        hasher.write_u128(now);
        hasher.write_usize(&bytes as *const _ as usize);
        bytes.extend_from_slice(&hasher.finish().to_le_bytes());
    }
    bytes
}

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

impl Drop for Shared {
    fn drop(&mut self) {
        self.store.probe().shift("tinystore_wire_connections", &[], -1.0);
    }
}

/// A method's name as the protocol spells it, `kv.get`.
fn method_name(method: u16) -> &'static str {
    super::protocol::METHODS.iter().find(|(_, id, _)| *id == method).map_or("unknown", |(name, ..)| name)
}