tinystore 0.5.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
//! kv's methods of the protocol, protocol/kv.wire: a handle on what a client
//! opened, and the calls on it. A handle holds rows, nil, an integer or bin,
//! so that the server reads what any language wrote.

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

use super::codec::{Message, Row};
use super::protocol::{
    Empty, Failure, Handle, KvAllowance, KvAnswer, KvBranch, KvBucketOpen, KvCall, KvCheck, KvCount, KvCountersOpen,
    KvEntry, KvFound, KvList, KvOnceOpen, KvOutcome, KvPage, KvQuotaOpen, KvRateLimitOpen, KvResealed, KvTx,
    KvTxResults, KvWindowUse, KvWritten, method,
};
use super::{Lent, Route};
#[cfg(feature = "sql")]
use crate::Transaction;
use crate::clock::from_unix_millis;
use crate::kv::{
    Allowance, Batch, Bucket, BucketBuilder, Cell, Counters, Hand, Handed, MAX_KEY, Outcome, PAGE_KEYS, Place, Put,
    Quota, RateLimit, Raw, Stamp, Version, Waiter, WriteOptions, hand, once_rows,
};
#[cfg(feature = "sql")]
use crate::kv::{call_on_branch, call_on_key, clear_work};
use crate::limits::{ANSWER_BYTES, Limit};
use crate::{Error, Store, unix_millis};

/// What a connection opened, by handle.
#[derive(Debug, Default)]
pub(crate) struct Handles {
    open: Mutex<HashMap<u64, Opened>>,
    last: AtomicU64,
}

#[derive(Clone, Debug)]
enum Opened {
    Bucket(Bucket<()>),
    Counters(Counters),
    RateLimit(RateLimit),
    Quota(Quota),
    Once(Bucket<()>),
}

use super::Answered;

pub(crate) fn route(called: u16) -> Route {
    match called {
        method::KV_GET | method::KV_HAS | method::KV_ONCE_GET => Route::Inline,
        method::KV_SET | method::KV_CREATE | method::KV_TAKE | method::KV_DELETE | method::KV_EXPIRE => Route::Submit,
        method::KV_CLEAR | method::KV_TX | method::KV_ONCE_DELETE => Route::Submit,
        method::KV_COUNTERS_ADD | method::KV_COUNTERS_DELETE => Route::Submit,
        method::KV_ALLOW | method::KV_REFUND | method::KV_RESET => Route::Submit,
        method::KV_ONCE_RUN => Route::Handover,
        _ => Route::Worker,
    }
}

/// 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, read_only): (usize, bool),
) -> Answered {
    match called {
        method::KV_BUCKET_OPEN => handles.open(open_bucket(store, lent, KvBucketOpen::decode(body)?, read_only)?),
        method::KV_COUNTERS_OPEN => handles.open(open_counters(store, KvCountersOpen::decode(body)?, read_only)?),
        method::KV_RATE_LIMIT_OPEN => handles.open(open_rate_limit(store, KvRateLimitOpen::decode(body)?)?),
        method::KV_QUOTA_OPEN => handles.open(open_quota(store, KvQuotaOpen::decode(body)?)?),
        method::KV_ONCE_OPEN => {
            let open = KvOnceOpen::decode(body)?;
            handles.open(Opened::Once(once_rows(store, &open.name, open.keep.map(Duration::from_millis))?))
        }
        method::KV_GET => get(handles, KvCall::decode(body)?),
        method::KV_HAS => has(handles, KvCall::decode(body)?),
        method::KV_LIST => list(handles, KvList::decode(body)?, max_body),
        method::KV_COUNTERS_GET => {
            let call = KvCall::decode(body)?;
            Ok(KvCount { value: handles.counters(call.handle, &call.under)?.get(&*call.key)? }.encode())
        }
        method::KV_COUNTERS_CLEAR => {
            let branch = KvBranch::decode(body)?;
            handles.counters(branch.handle, &branch.under)?.clear()?;
            Ok(Empty {}.encode())
        }
        method::KV_RESEAL => {
            let branch = KvBranch::decode(body)?;
            Ok(KvResealed { count: handles.bucket(branch.handle, &branch.under)?.reseal()? }.encode())
        }
        method::KV_PEEK => limit(handles, called, KvCall::decode(body)?),
        method::KV_ONCE_GET => {
            let call = KvCall::decode(body)?;
            let cell = handles.once(call.handle, &call.under)?.read_cell(&call.key)?;
            Ok(answer(cell.map(|cell| cell.raw)).encode())
        }
        other => Err(Failure::unimplemented(format!("method {other:#06x}"))),
    }
}

/// Answers a call made inside a database's transaction, on its stream: a
/// bucket kept in the database's file reads and writes 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::KV_CLEAR => {
            let branch = KvBranch::decode(body)?;
            let bucket = handles.bucket(branch.handle, &branch.under)?;
            call_on_branch(tx, &bucket.scope, clear_work(&bucket.scope)?)?;
            Ok(Empty {}.encode())
        }
        method::KV_LIST => {
            let list = KvList::decode(body)?;
            let bucket = handles.bucket(list.handle, &list.under)?;
            let (limit, after) = (page_limit(&list), list.after.as_deref());
            let read = |sql: &crate::sqlite::Tx<'_>, _: &_| bucket.page_rows(sql, limit.clamp(1, PAGE_KEYS), after);
            let rows = call_on_branch(tx, &bucket.scope, read)?;
            page(bucket.keyed(rows)?, &list, limit, max_body)
        }
        _ => key_call_in(handles, tx, called, &KvCall::decode(body)?),
    }
}

/// A call on one key of a bucket inside a database's transaction.
#[cfg(feature = "sql")]
fn key_call_in(handles: &Handles, tx: &Transaction<'_>, called: u16, call: &KvCall) -> Answered {
    let bucket = handles.bucket(call.handle, &call.under)?;
    let (key, scope) = (call.key.as_str(), &bucket.scope);
    match called {
        method::KV_GET | method::KV_HAS => {
            let cell = call_on_key(tx, scope, key, |sql, _| bucket.read_cell_in(sql, key))?;
            match called {
                method::KV_GET => Ok(entry(cell, None).encode()),
                _ => Ok(KvFound { found: cell.is_some() }.encode()),
            }
        }
        method::KV_SET | method::KV_CREATE => {
            let put = if called == method::KV_SET { Put::Always } else { Put::OnlyNew };
            let raw = raw_of(call.value.clone().unwrap_or_default());
            let (_, work) = bucket.put_work(key, raw, options(call)?, put)?;
            Ok(written(call_on_key(tx, scope, key, work)?))
        }
        method::KV_TAKE => Ok(taken(call_on_key(tx, scope, key, bucket.take_cell_work(key, options(call)?)?)?)),
        method::KV_DELETE => {
            let found = call_on_key(tx, scope, key, bucket.remove_work(key, options(call)?)?)?;
            Ok(KvFound { found }.encode())
        }
        method::KV_EXPIRE => {
            let found = call_on_key(tx, scope, key, bucket.expire_work(key, options(call)?)?)?;
            Ok(KvFound { found }.encode())
        }
        other => Err(Failure::invalid(format!("method {other:#06x} is not a bucket's call inside a transaction"))),
    }
}

/// Queues a write and returns; `done` gets its answer on the thread that
/// commits it. A call that waits for no commit, a counter kept in memory or
/// a rate limit, is answered before this returns.
pub(crate) fn submit(handles: &Handles, called: u16, body: &[u8], done: impl FnOnce(Answered) + Send + 'static) {
    match called {
        method::KV_CLEAR => clear(handles, body, done),
        method::KV_TX => tx(handles, body, done),
        method::KV_ONCE_DELETE => forget(handles, body, done),
        method::KV_COUNTERS_ADD | method::KV_COUNTERS_DELETE => counting(handles, called, body, done),
        method::KV_ALLOW | method::KV_REFUND | method::KV_RESET => using(handles, called, body, done),
        _ => write(handles, called, body, done),
    }
}

/// A write of one key of a bucket, queued for its commit.
fn write(handles: &Handles, called: u16, body: &[u8], done: impl FnOnce(Answered) + Send + 'static) {
    let prepared = || -> Result<_, Failure> {
        let call = KvCall::decode(body)?;
        let bucket = handles.bucket(call.handle, &call.under)?;
        let options = options(&call)?;
        Ok((call, bucket, options))
    };
    let (call, bucket, options) = match prepared() {
        Ok(prepared) => prepared,
        Err(failure) => return done(Err(failure)),
    };
    let key = call.key.clone();
    match called {
        method::KV_SET | method::KV_CREATE => {
            let put = if called == method::KV_SET { Put::Always } else { Put::OnlyNew };
            let raw = raw_of(call.value.unwrap_or_default());
            bucket
                .put_raw_then(&key, (raw, options, put), move |stamp| done(stamp.map(written).map_err(Failure::from)));
        }
        method::KV_TAKE => {
            bucket.take_cell_then(&key, options, move |cell| done(cell.map(taken).map_err(Failure::from)));
        }
        method::KV_DELETE => bucket.remove_then(&key, options, move |found| {
            done(found.map(|found| KvFound { found }.encode()).map_err(Failure::from));
        }),
        method::KV_EXPIRE => bucket.expire_then(&key, options, move |found| {
            done(found.map(|found| KvFound { found }.encode()).map_err(Failure::from));
        }),
        other => done(Err(Failure::unimplemented(format!("method {other:#06x}")))),
    }
}

/// How a client's run of a once key starts: the answer kept, which ends the
/// stream; the run handed over, kept until the client's answer; or a wait for
/// the run that holds the key, `again` asked once it ends with the answer it
/// could not keep, if any.
pub(crate) enum Run {
    Answered(Vec<u8>),
    Handed(Box<Handed>, Vec<u8>),
    Waiting,
}

pub(crate) fn run(handles: &Handles, body: &[u8], again: Waiter) -> Result<Run, Failure> {
    let call = KvCall::decode(body)?;
    let answers = handles.once(call.handle, &call.under)?;
    Ok(match hand(&answers, &call.key, again)? {
        Hand::Kept(raw) => Run::Answered(answer(Some(raw)).encode()),
        Hand::Yours(handed) => Run::Handed(Box::new(handed), answer(None).encode()),
        Hand::Wait => Run::Waiting,
    })
}

/// Keeps what a client's handed run answered, and lets its key go.
pub(crate) fn kept(handed: Handed, body: &[u8]) -> Answered {
    let answered = KvAnswer::decode(body)?;
    let raw = answered.found.then(|| raw_of(answered.value.unwrap_or_default()));
    handed.keep(raw);
    Ok(Empty {}.encode())
}

/// The answer of the run a client waited for, which that run could not keep.
pub(crate) fn unkept(raw: &Raw) -> Run {
    Run::Answered(answer(Some(raw.clone())).encode())
}

impl Handles {
    fn open(&self, opened: Opened) -> Answered {
        let handle = self.last.fetch_add(1, Ordering::SeqCst) + 1;
        self.lock().insert(handle, opened);
        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 nothing this connection opened")))
    }

    fn bucket(&self, handle: u64, under: &[String]) -> Result<Bucket<()>, Failure> {
        match self.opened(handle)? {
            Opened::Bucket(bucket) => Ok(under.iter().fold(bucket, |bucket, owner| bucket.under(owner))),
            other => Err(wrong(handle, &other, "a bucket")),
        }
    }

    fn counters(&self, handle: u64, under: &[String]) -> Result<Counters, Failure> {
        match self.opened(handle)? {
            Opened::Counters(counters) => Ok(under.iter().fold(counters, |counters, owner| counters.under(owner))),
            other => Err(wrong(handle, &other, "counters")),
        }
    }

    fn once(&self, handle: u64, under: &[String]) -> Result<Bucket<()>, Failure> {
        match self.opened(handle)? {
            Opened::Once(answers) => Ok(under.iter().fold(answers, |answers, owner| answers.under(owner))),
            other => Err(wrong(handle, &other, "once's answers")),
        }
    }

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

/// Opens a bucket as the call says. A connection that only reads opens no
/// encrypted one: what it may read is what the file shows without the key.
/// Nor does it give the bucket an idle term, under which each read renews a
/// key's expiry: a write, of a term the writers never chose.
fn open_bucket(store: &Store, lent: Lent<'_>, open: KvBucketOpen, read_only: bool) -> Result<Opened, Failure> {
    if open.encrypted && read_only {
        return Err(Failure::permission("a read connection opens no encrypted bucket"));
    }
    if open.idle.is_some() && read_only {
        return Err(Failure::permission(
            "a read connection gives a bucket no idle: a read that renews a key writes it",
        ));
    }
    let mut builder = match open.database {
        Some(database) => BucketBuilder::in_file(lent(database)?, &open.name),
        None => store.bucket::<()>(&open.name),
    };
    if let Some(ttl) = open.ttl {
        builder = builder.ttl(Duration::from_millis(ttl));
    }
    if let Some(idle) = open.idle {
        builder = builder.idle(Duration::from_millis(idle));
    }
    if open.encrypted {
        builder = builder.encrypted();
    }
    Ok(Opened::Bucket(builder.open()?))
}

/// Opens counters as the call says. How a name's counters count, each change
/// written or kept in memory, is the process's from its first open, so a
/// connection that only reads leaves it to the writers.
fn open_counters(store: &Store, open: KvCountersOpen, read_only: bool) -> Result<Opened, Failure> {
    if open.flush_every.is_some() && read_only {
        return Err(Failure::permission(
            "a read connection gives counters no flush_every: how they count is the writers'",
        ));
    }
    let mut builder = store.counters(&open.name);
    if let Some(ttl) = open.ttl {
        builder = builder.ttl(Duration::from_millis(ttl));
    }
    if let Some(span) = open.flush_every {
        builder = builder.flush_every(Duration::from_millis(span));
    }
    Ok(Opened::Counters(builder.open()?))
}

fn open_rate_limit(store: &Store, open: KvRateLimitOpen) -> Result<Opened, Failure> {
    let mut builder = store.rate_limit(&open.name).rate(open.rate, Duration::from_millis(open.per));
    if let Some(burst) = open.burst {
        builder = builder.burst(burst);
    }
    Ok(Opened::RateLimit(builder.open()?))
}

fn open_quota(store: &Store, open: KvQuotaOpen) -> Result<Opened, Failure> {
    let builder = open.windows.iter().fold(store.quota(&open.name), |quota, window| {
        quota.window(&window.name, window.limit, Duration::from_millis(window.per))
    });
    Ok(Opened::Quota(builder.open()?))
}

fn get(handles: &Handles, call: KvCall) -> Answered {
    let cell = handles.bucket(call.handle, &call.under)?.read_cell(&call.key)?;
    Ok(entry(cell, None).encode())
}

fn has(handles: &Handles, call: KvCall) -> Answered {
    let found = handles.bucket(call.handle, &call.under)?.has(&*call.key)?;
    Ok(KvFound { found }.encode())
}

fn clear(handles: &Handles, body: &[u8], done: impl FnOnce(Answered) + Send + 'static) {
    let bucket = KvBranch::decode(body).and_then(|branch| handles.bucket(branch.handle, &branch.under));
    match bucket {
        Ok(bucket) => {
            bucket.clear_then(move |cleared| done(cleared.map(|()| Empty {}.encode()).map_err(Failure::from)))
        }
        Err(failure) => done(Err(failure)),
    }
}

/// Removes a once key's kept answer.
fn forget(handles: &Handles, body: &[u8], done: impl FnOnce(Answered) + Send + 'static) {
    let answers = KvCall::decode(body).and_then(|call| Ok((handles.once(call.handle, &call.under)?, call.key)));
    match answers {
        Ok((answers, key)) => answers.remove_then(&key, WriteOptions::default(), move |removed| {
            done(removed.map(|found| KvFound { found }.encode()).map_err(Failure::from));
        }),
        Err(failure) => done(Err(failure)),
    }
}

/// A page of the branch's own keys, as many as `limit` asks and the agreed
/// body holds: a page cut by the body starts the next after its last key.
fn list(handles: &Handles, list: KvList, max_body: usize) -> Answered {
    let bucket = handles.bucket(list.handle, &list.under)?;
    let limit = page_limit(&list);
    let rows = bucket.list_rows(limit, list.after.as_deref())?;
    page(rows, &list, limit, max_body)
}

fn page_limit(list: &KvList) -> usize {
    list.limit.map_or(100, |limit| usize::try_from(limit).unwrap_or(usize::MAX))
}

/// The page a list's rows make, as many as the agreed body holds.
fn page(rows: Vec<(String, Cell)>, list: &KvList, limit: usize, max_body: usize) -> Answered {
    let full = rows.len() == limit.clamp(1, PAGE_KEYS);
    let mut page = KvPage::default();
    // a page's own fields and the next key's room, kept apart from what entries may take
    let mut room = max_body.saturating_sub(64 + list.after.as_ref().map_or(0, String::len) + MAX_KEY);
    for (key, cell) in rows {
        let entry = entry(Some(cell), Some(key));
        let bytes = entry.encode().len() + 1;
        if bytes > room {
            if page.entries.is_empty() {
                let agreed = Limit { bound: max_body as u64, ..ANSWER_BYTES };
                let refused = "an entry past the largest body this connection agreed";
                return Err(Failure::from(agreed.refuse(bytes as u64, refused)));
            }
            page.next = page.entries.last().and_then(|entry| entry.key.clone());
            return Ok(page.encode());
        }
        room -= bytes;
        page.entries.push(entry);
    }
    if full {
        page.next = page.entries.last().and_then(|entry| entry.key.clone());
    }
    Ok(page.encode())
}

/// A counter's add or its delete, answered once its commit ends, or at once
/// by counters kept in memory.
fn counting(handles: &Handles, called: u16, body: &[u8], done: impl FnOnce(Answered) + Send + 'static) {
    let counters = KvCall::decode(body).and_then(|call| Ok((handles.counters(call.handle, &call.under)?, call)));
    let (counters, call) = match counters {
        Ok(counters) => counters,
        Err(failure) => return done(Err(failure)),
    };
    if called == method::KV_COUNTERS_ADD {
        counters.add_then(&call.key, call.n.unwrap_or(1), move |sum| {
            done(sum.map(|value| KvCount { value }.encode()).map_err(Failure::from));
        });
    } else {
        counters.delete_then(&call.key, move |found| {
            done(found.map(|found| KvFound { found }.encode()).map_err(Failure::from));
        });
    }
}

/// A use of a limit that writes: a quota's, answered once its commit ends.
/// A rate limit counts in memory, and answers at once.
fn using(handles: &Handles, called: u16, body: &[u8], done: impl FnOnce(Answered) + Send + 'static) {
    let opened = KvCall::decode(body).and_then(|call| Ok((handles.opened(call.handle)?, call)));
    let (quota, call) = match opened {
        Ok((Opened::Quota(quota), call)) => (quota, call),
        Ok((_, call)) => return done(limit(handles, called, call)),
        Err(failure) => return done(Err(failure)),
    };
    let Ok(n) = u64::try_from(call.n.unwrap_or(1)) else {
        return done(Err(Failure::invalid("a negative count of requests")));
    };
    let quota = call.under.iter().fold(quota, |quota, owner| quota.under(owner));
    let nothing = |written: Result<(), Error>| written.map(|()| Empty {}.encode()).map_err(Failure::from);
    match called {
        method::KV_ALLOW => quota.allow_n_then(&call.key, n, move |allowance| {
            done(allowance.map(|allowance| allowance_of(&allowance).encode()).map_err(Failure::from));
        }),
        method::KV_RESET => quota.reset_then(&call.key, move |reset| done(nothing(reset))),
        _ => quota.refund_n_then(&call.key, n, move |refunded| done(nothing(refunded))),
    }
}

/// A rate limit's or a quota's call: n is the requests or uses asked, 1 when
/// absent.
fn limit(handles: &Handles, called: u16, call: KvCall) -> Answered {
    let n = u64::try_from(call.n.unwrap_or(1)).map_err(|_| Failure::invalid("a negative count of requests"))?;
    let key = &*call.key;
    let answered = match handles.opened(call.handle)? {
        Opened::RateLimit(limit) => {
            let limit = call.under.iter().fold(limit, |limit, owner| limit.under(owner));
            match called {
                method::KV_ALLOW => Some(limit.allow_n(key, n)?),
                method::KV_PEEK => Some(limit.peek(key)?),
                method::KV_RESET => limit.reset(key).map(|()| None)?,
                _ => return Err(Failure::invalid("a rate limit gives no refund: its requests are spent")),
            }
        }
        Opened::Quota(quota) => {
            let quota = call.under.iter().fold(quota, |quota, owner| quota.under(owner));
            match called {
                method::KV_ALLOW => Some(quota.allow_n(key, n)?),
                method::KV_PEEK => Some(quota.peek(key)?),
                method::KV_RESET => quota.reset(key).map(|()| None)?,
                _ => quota.refund_n(key, n).map(|()| None)?,
            }
        }
        other => return Err(wrong(call.handle, &other, "a rate limit or a quota")),
    };
    Ok(answered.map_or_else(|| Empty {}.encode(), |allowance| allowance_of(&allowance).encode()))
}

/// A transaction's checks and writes in one batch, all or none; a failed one
/// names its place in `what`.
fn tx(handles: &Handles, body: &[u8], done: impl FnOnce(Answered) + Send + 'static) {
    let batched = || -> Result<Batch, Failure> {
        let tx = KvTx::decode(body)?;
        let mut batch = Batch::default();
        for (index, check) in tx.checks.iter().enumerate() {
            add_check(handles, &mut batch, check).map_err(|failure| failure.at(Place::Check(index)))?;
        }
        for (index, op) in tx.writes.iter().enumerate() {
            add_write(handles, &mut batch, op.method, &op.call).map_err(|failure| failure.at(Place::Write(index)))?;
        }
        Ok(batch)
    };
    match batched() {
        Ok(batch) => batch.commit_then(move |committed| {
            done(match committed {
                Ok(outcomes) => Ok(KvTxResults { outcomes: outcomes.into_iter().map(outcome_of).collect() }.encode()),
                Err((Some(place), error)) => Err(Failure::from(error).at(place)),
                Err((None, error)) => Err(Failure::from(error)),
            });
        }),
        Err(failure) => done(Err(failure)),
    }
}

fn add_check(handles: &Handles, batch: &mut Batch, check: &KvCheck) -> Result<(), Failure> {
    let bucket = handles.bucket(check.handle, &check.under)?;
    let version = check.version.as_deref().map(revision_of).transpose()?;
    Ok(batch.check(&bucket, &check.key, version)?)
}

fn add_write(handles: &Handles, batch: &mut Batch, called: u64, call: &KvCall) -> Result<(), Failure> {
    let called = u16::try_from(called).map_err(|_| Failure::invalid(format!("method {called:#06x}")))?;
    if called == method::KV_COUNTERS_ADD {
        let counters = handles.counters(call.handle, &call.under)?;
        return Ok(batch.add(&counters, &call.key, call.n.unwrap_or(1))?);
    }
    let bucket = handles.bucket(call.handle, &call.under)?;
    let options = options(call)?;
    match called {
        method::KV_SET | method::KV_CREATE => {
            let put = if called == method::KV_SET { Put::Always } else { Put::OnlyNew };
            let raw = raw_of(call.value.clone().unwrap_or_default());
            Ok(batch.put(&bucket, &call.key, (raw, options, put))?)
        }
        method::KV_TAKE => Ok(batch.take(&bucket, &call.key, options)?),
        method::KV_DELETE => Ok(batch.remove(&bucket, &call.key, options)?),
        method::KV_EXPIRE => Ok(batch.expire(&bucket, &call.key, options)?),
        method::KV_CLEAR => Ok(batch.clear(&bucket.scope)?),
        other => Err(Failure::invalid(format!("method {other:#06x} in a transaction, which writes"))),
    }
}

/// What a call asks of a write: its expiry and the version the key must be at.
fn options(call: &KvCall) -> Result<WriteOptions, Failure> {
    let mut options = WriteOptions::default();
    if let Some(ttl) = call.ttl {
        options = options.ttl(Duration::from_millis(ttl));
    }
    if let Some(at) = call.expires_at {
        options = options.expires_at(from_unix_millis(at));
    }
    if let Some(version) = &call.if_version {
        options = options.if_version(Version::new(revision_of(version)?));
    }
    Ok(options)
}

/// A version travels as the decimal text of its revision, in a bin the client
/// compares only for equality.
fn revision_of(bytes: &[u8]) -> Result<i64, Failure> {
    std::str::from_utf8(bytes)
        .ok()
        .and_then(|text| text.parse().ok())
        .ok_or_else(|| Failure::invalid("a version this server never gave"))
}

fn version_bytes(revision: i64) -> Vec<u8> {
    revision.to_string().into_bytes()
}

fn entry(cell: Option<Cell>, key: Option<String>) -> KvEntry {
    let Some(cell) = cell else {
        return KvEntry::default();
    };
    KvEntry {
        found: true,
        value: Some(row_of(cell.raw)),
        version: Some(version_bytes(cell.version)),
        expires_at: cell.expires,
        key,
    }
}

fn answer(raw: Option<Raw>) -> KvAnswer {
    KvAnswer { found: raw.is_some(), value: raw.map(row_of) }
}

fn written(stamp: Stamp) -> Vec<u8> {
    let written = KvWritten {
        written: stamp.written,
        version: version_bytes(stamp.version.revision()),
        expires_at: stamp.expires,
    };
    written.encode()
}

fn taken(cell: Option<Cell>) -> Vec<u8> {
    KvEntry { found: cell.is_some(), value: cell.map(|cell| row_of(cell.raw)), ..KvEntry::default() }.encode()
}

fn outcome_of(outcome: Outcome) -> KvOutcome {
    KvOutcome {
        found: outcome.found,
        written: outcome.written,
        value: outcome.value.map(row_of),
        version: outcome.version.map(version_bytes),
        expires_at: outcome.expires,
        count: outcome.count,
    }
}

fn allowance_of(allowance: &Allowance) -> KvAllowance {
    let windows = allowance
        .windows
        .iter()
        .map(|window| KvWindowUse {
            name: window.name.clone(),
            used: window.used,
            limit: window.limit,
            left: window.left,
            resets_at: window.resets_at.map(unix_millis),
        })
        .collect();
    KvAllowance { ok: allowance.ok, left: allowance.left, retry_at: allowance.retry_at.map(unix_millis), windows }
}

fn row_of(raw: Raw) -> Row {
    match raw {
        Raw::None => Row::Nil,
        Raw::Int(number) => Row::Int(number),
        Raw::Bytes(bytes) => Row::Bin(bytes),
    }
}

fn raw_of(row: Row) -> Raw {
    match row {
        Row::Nil => Raw::None,
        Row::Int(number) => Raw::Int(number),
        Row::Bin(bytes) => Raw::Bytes(bytes),
    }
}

impl Failure {
    /// The failure of a transaction's check or write, its place named in
    /// `what`, so that a client knows which read changed.
    fn at(self, place: Place) -> Failure {
        match place {
            Place::Check(index) => self.naming("check", index.to_string()),
            Place::Write(index) => self.naming("write", index.to_string()),
        }
    }
}

fn wrong(handle: u64, opened: &Opened, wanted: &str) -> Failure {
    let opened = match opened {
        Opened::Bucket(_) => "a bucket",
        Opened::Counters(_) => "counters",
        Opened::RateLimit(_) => "a rate limit",
        Opened::Quota(_) => "a quota",
        Opened::Once(_) => "once's answers",
    };
    Failure::invalid(format!("handle {handle} is {opened}, not {wanted}"))
}