tinystore 0.7.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
//! metrics over the protocol: queries and their answers, what a store holds of
//! its series, and a client's instruments.
//!
//! A read, the newest samples and an aggregate answer in parts within the
//! client's credit, as many series or groups a part as a body holds, a series
//! longer than one cut across parts; a series' samples go as two columns, an
//! int64 time and a float64 value a sample, 8 bytes each, little end first,
//! so that every value's bits come back. A client's instruments send their
//! batches on a stream of their own, applied in turn, each answered with the
//! last batch of the session the store applied.
//!
//! An exposition's text past what one message holds comes as the client's
//! pieces, gathered in the store's memory, reserved for the whole text before
//! a piece is kept, then read and written as one text is.

use std::collections::{BTreeMap, HashMap, VecDeque};
use std::sync::{Arc, Mutex, Weak};
use std::time::Duration;

use super::codec::Message;
use super::protocol::{
    Empty, Failure, MetricsAck, MetricsAggregateAsked, MetricsAggregates, MetricsBatch, MetricsBucket,
    MetricsCondition, MetricsDamage, MetricsDamages, MetricsDeleted, MetricsDescription, MetricsExceeds,
    MetricsExposition, MetricsGroup, MetricsIngest, MetricsLatest, MetricsName, MetricsNameAsked, MetricsNamePage,
    MetricsNewSeries, MetricsNewest, MetricsPageAsked, MetricsPiece, MetricsPlan, MetricsQuery, MetricsRead,
    MetricsRefused, MetricsReplace, MetricsSeries, MetricsSeriesNamed, MetricsSession, MetricsTextPage, MetricsUpload,
    method,
};
use super::{Link, Route};
use crate::clock::from_unix_millis;
use crate::limits::TEXT_BYTES;
use crate::memory::PATIENCE;
use crate::metrics::{
    Ack, AggregatePage, Batch, Buckets, Change, Condition, Declared, Description, Latest, List, Metrics, Op,
    Prometheus, Query, Remote, Series, SeriesPage, Set, Value,
};
use crate::sync::lock;
use crate::{Calendar, Memory, Reservation, Store, unix_millis};

use super::Answered;

/// What a part's message takes past its series or groups, and each of them
/// past its samples or buckets.
const ENVELOPE: usize = 32;
/// What a name of a page takes past its text: its numbers and its fields'
/// keys.
const NAME_NUMBERS: usize = 64;
/// What a sample of a read takes of a part: its time and its value.
const SAMPLE: usize = 16;
/// What a bucket of an aggregate takes of a part at most.
const BUCKET: usize = 64;
/// The longest text an upload gathers: one text's 32 MiB, as the engine
/// bounds what its series weigh. It bounds what the session holds for a
/// client, so it is refused before a byte of the text comes.
const TEXT_MOST: usize = TEXT_BYTES.bound as usize;
/// What an uploaded text's memory is reserved as, and its refusals name.
const UPLOADED: &str = "metrics: an uploaded text";

pub(crate) fn route(called: u16) -> Route {
    match called {
        method::METRICS_READ | method::METRICS_LATEST | method::METRICS_AGGREGATE => Route::Parts,
        method::METRICS_INSTRUMENTS => Route::Instruments,
        method::METRICS_UPLOAD_PROMETHEUS => Route::Gather,
        _ => Route::Worker,
    }
}

/// A connection's texts that come in pieces, by stream.
type Gatherings = Mutex<HashMap<u32, Arc<Gathering>>>;

/// A connection's streams that send or take DATA: its downloads, its
/// clients' instruments and its texts that come in pieces.
#[derive(Default)]
pub(crate) struct Handles {
    downloads: Mutex<HashMap<u32, Arc<Downloading>>>,
    instruments: Arc<Mutex<HashMap<u32, Arc<Instruments>>>>,
    gatherings: Arc<Gatherings>,
}

impl Handles {
    /// Credit the client granted a download.
    pub(crate) fn grant(&self, stream: u32, credit: u32) {
        let download = lock(&self.downloads).get(&stream).cloned();
        if let Some(download) = download {
            download.grant(credit, &self.downloads);
        }
    }

    /// Ends a download, an instruments' stream or a text in pieces the client
    /// cancelled; says whether the stream was one.
    pub(crate) fn cancel(&self, stream: u32) -> bool {
        if let Some(download) = lock(&self.downloads).remove(&stream) {
            download.end(Err(Failure::cancelled("the client cancelled its read")));
            return true;
        }
        if let Some(instruments) = lock(&self.instruments).remove(&stream) {
            instruments.end(Err(Failure::cancelled("the client cancelled its instruments")));
            return true;
        }
        // out of its map before it ends, which takes the map's lock again
        let gathering = lock(&self.gatherings).remove(&stream);
        if let Some(gathering) = gathering {
            gathering.cancel();
            return true;
        }
        false
    }

    /// Lets go of every stream: the connection ended, a client's gauges leave
    /// the totals with it, and a text in pieces leaves nothing written.
    pub(crate) fn end(&self) {
        lock(&self.downloads).clear();
        lock(&self.instruments).clear();
        let gatherings: Vec<_> = lock(&self.gatherings).drain().map(|(_, gathering)| gathering).collect();
        for gathering in gatherings {
            gathering.cancel();
        }
    }

    /// The text in pieces a client's DATA on `stream` is a piece of.
    pub(crate) fn gathering(&self, stream: u32) -> Option<Arc<Gathering>> {
        lock(&self.gatherings).get(&stream).cloned()
    }

    /// Takes a client's batch on its instruments' stream, applied in turn on
    /// a worker; says whether the stream is an instruments' stream.
    pub(crate) fn batch(&self, stream: u32, body: &[u8], last: bool) -> bool {
        let Some(instruments) = lock(&self.instruments).get(&stream).cloned() else { return false };
        let mut waiting = lock(&instruments.waiting);
        waiting.batches.push_back((body.to_vec(), last));
        if !std::mem::replace(&mut waiting.running, true) {
            let (spawn, open) = (Arc::clone(&instruments.link.spawn), Arc::clone(&self.instruments));
            let applying = Arc::clone(&instruments);
            spawn(Box::new(move || applying.drain(stream, &open)));
        }
        true
    }
}

/// Answers a call of one message.
pub(crate) fn call(store: &Store, called: u16, body: &[u8], max_body: usize) -> Answered {
    let metrics = store.metrics()?;
    match called {
        method::METRICS_EXPLAIN => explain(&metrics, MetricsAggregateAsked::decode(body)?),
        method::METRICS_NAMES => names(&metrics, MetricsPageAsked::decode(body)?, max_body),
        method::METRICS_LABEL_NAMES | method::METRICS_LABEL_VALUES => {
            texts(&metrics, called, MetricsPageAsked::decode(body)?, max_body)
        }
        method::METRICS_DESCRIPTION => description(&metrics, &MetricsNameAsked::decode(body)?.name),
        method::METRICS_DAMAGED => damaged(&metrics, max_body),
        method::METRICS_INGEST => ingest(&metrics, MetricsIngest::decode(body)?),
        method::METRICS_INGEST_PROMETHEUS => ingest_prometheus(&metrics, MetricsExposition::decode(body)?),
        method::METRICS_DESCRIBE => describe(&metrics, MetricsDescription::decode(body)?),
        method::METRICS_DELETE => delete(&metrics, MetricsSeriesNamed::decode(body)?),
        method::METRICS_REPLACE => replace(&metrics, MetricsReplace::decode(body)?),
        method::METRICS_FLUSH => metrics.flush().map(|()| Empty {}.encode()).map_err(Failure::from),
        _ => Err(Failure::unimplemented(format!("method {called:#06x}"))),
    }
}

/// The parts of a read's, the newest samples' or an aggregate's answer, each
/// of at most `bound` bytes.
pub(crate) fn parts(store: &Store, called: u16, body: &[u8], bound: usize) -> Result<VecDeque<Vec<u8>>, Failure> {
    let metrics = store.metrics()?;
    match called {
        method::METRICS_READ => Ok(read_parts(query(&metrics, MetricsQuery::decode(body)?)?.read()?, bound)),
        method::METRICS_LATEST => Ok(latest_parts(query(&metrics, MetricsQuery::decode(body)?)?.latest()?, bound)),
        _ => {
            let asked = MetricsAggregateAsked::decode(body)?;
            let op = op_of(asked.op.as_deref())?;
            Ok(aggregate_parts(aggregating(&metrics, asked)?.aggregate(op)?, bound))
        }
    }
}

/// A query as the engine takes it: its name, its conditions and its range.
fn query(metrics: &Metrics, asked: MetricsQuery) -> Result<Query, Failure> {
    let mut query = metrics.query();
    if let Some(name) = asked.name {
        query = query.name(name);
    }
    for (label, condition) in asked.r#where {
        query = query.filter(label, condition_of(condition)?);
    }
    if let Some(since) = asked.since {
        query = query.since(Duration::from_millis(since));
    }
    if let Some(from) = asked.from {
        query = query.from(from_unix_millis(from));
    }
    if let Some(to) = asked.to {
        query = query.to(from_unix_millis(to));
    }
    if let Some(limit) = asked.limit {
        query = query.limit(usize::try_from(limit).unwrap_or(usize::MAX));
    }
    if let Some(after) = &asked.after {
        query = query.after(after);
    }
    Ok(query)
}

fn condition_of(condition: MetricsCondition) -> Result<Condition, Failure> {
    match condition {
        MetricsCondition { values, not: false, prefix: Some(prefix) } if values.is_empty() => {
            Ok(Condition::Prefix(prefix))
        }
        MetricsCondition { prefix: Some(_), .. } => {
            Err(Failure::invalid("a condition is a list of values, `not` one, or a prefix alone"))
        }
        MetricsCondition { values, not: true, .. } => Ok(Condition::NoneOf(values)),
        MetricsCondition { values, .. } => Ok(Condition::OneOf(values)),
    }
}

/// An aggregate's query: its buckets, groups and estimate beside read's.
fn aggregating(metrics: &Metrics, asked: MetricsAggregateAsked) -> Result<Query, Failure> {
    let mut query = query(metrics, asked.query)?;
    if let Some(every) = asked.every {
        query = query.every(Duration::from_millis(every));
    }
    if let Some((unit, zone)) = Calendar::asked(asked.calendar.as_deref(), asked.time_zone.as_deref())? {
        query = query.calendar(unit, zone);
    }
    if let Some(by) = &asked.by {
        query = query.by(&by.iter().map(String::as_str).collect::<Vec<_>>());
    }
    if let Some(without) = &asked.without {
        query = query.without(&without.iter().map(String::as_str).collect::<Vec<_>>());
    }
    if asked.estimate {
        query = query.estimate();
    }
    Ok(query)
}

/// An `op` as a query writes it: `increase`, `p95`, `p99.9`.
fn op_of(op: Option<&str>) -> Result<Op, Failure> {
    let ops = [
        ("count", Op::Count),
        ("sum", Op::Sum),
        ("avg", Op::Avg),
        ("min", Op::Min),
        ("max", Op::Max),
        ("increase", Op::Increase),
        ("rate", Op::Rate),
        ("delta", Op::Delta),
        ("first", Op::First),
        ("last", Op::Last),
    ];
    let op = op.ok_or_else(|| Failure::invalid("an aggregate needs an op"))?;
    if let Some((_, found)) = ops.iter().find(|(word, _)| *word == op) {
        return Ok(*found);
    }
    let rank =
        op.strip_prefix('p').filter(|rank| !rank.is_empty() && rank.chars().all(|c| c.is_ascii_digit() || c == '.'));
    match rank.and_then(|rank| rank.parse::<f64>().ok()) {
        Some(rank) => Ok(Op::Percentile(rank)),
        None => Err(Failure::invalid(format!(
            "op {op:?}: count, sum, avg, min, max, increase, rate, delta, first, last, or p and a rank, p95"
        ))),
    }
}

fn explain(metrics: &Metrics, asked: MetricsAggregateAsked) -> Answered {
    let op = asked.op.as_deref().map(|op| op_of(Some(op))).transpose()?;
    let plan = aggregating(metrics, asked)?.explain(op)?;
    let exceeds = plan.exceeds.map(|exceeds| MetricsExceeds {
        limit: exceeds.limit.to_owned(),
        wanted: exceeds.wanted,
        bound: exceeds.bound,
    });
    Ok(MetricsPlan { series: plan.series, bytes: plan.bytes, decoded: plan.decoded, exceeds }.encode())
}

/// A page's options as the client gave them.
fn paged<P>(mut list: List<P>, asked: &MetricsPageAsked) -> List<P> {
    if let Some(prefix) = &asked.prefix {
        list = list.prefix(prefix.clone());
    }
    if let Some(after) = &asked.after {
        list = list.after(after.clone());
    }
    if let Some(limit) = asked.limit {
        list = list.limit(usize::try_from(limit).unwrap_or(usize::MAX));
    }
    list
}

/// A page of names, cut where a body ends, `next` past the last it holds.
fn names(metrics: &Metrics, asked: MetricsPageAsked, max_body: usize) -> Answered {
    let page = paged(metrics.names(), &asked).page()?;
    let names = page.names.into_iter().map(|info| MetricsName {
        kind: info.kind.as_str().to_owned(),
        series_count: info.series_count,
        keep: crate::clock::millis(info.keep) as u64,
        retained_from: unix_millis(info.retained_from),
        newest: unix_millis(info.newest),
        name: info.name,
        unit: info.unit,
        help: info.help,
    });
    let (names, next) = fitted(names.collect(), page.next, max_body, |name| {
        let text = name.name.len() + name.kind.len() + name.unit.len() + name.help.len();
        (name.name.clone(), text + NAME_NUMBERS)
    });
    Ok(MetricsNamePage { names, next }.encode())
}

/// A page of a name's labels or of a label's values.
fn texts(metrics: &Metrics, called: u16, asked: MetricsPageAsked, max_body: usize) -> Answered {
    let name = asked.name.clone().unwrap_or_default();
    let (texts, next) = if called == method::METRICS_LABEL_NAMES {
        let page = paged(metrics.label_names(name), &asked).page()?;
        (page.labels, page.next)
    } else {
        let label = asked.label.clone().unwrap_or_default();
        let page = paged(metrics.label_values(name, label), &asked).page()?;
        (page.values, page.next)
    };
    let (texts, next) = fitted(texts, next, max_body, |text| (text.clone(), text.len() + 8));
    Ok(MetricsTextPage { texts, next }.encode())
}

/// What a page holds that a body holds: past it, the page ends at the last
/// item that fits and `next` names it, room kept for the name.
fn fitted<T>(
    items: Vec<T>,
    next: Option<String>,
    max_body: usize,
    weigh: impl Fn(&T) -> (String, usize),
) -> (Vec<T>, Option<String>) {
    let (mut size, mut kept) = (ENVELOPE, Vec::with_capacity(items.len()));
    for item in items {
        let (key, weight) = weigh(&item);
        if size + weight + key.len() > max_body && !kept.is_empty() {
            let last = kept.last().map(|kept| weigh(kept).0);
            return (kept, last);
        }
        size += weight;
        kept.push(item);
    }
    (kept, next)
}

fn description(metrics: &Metrics, name: &str) -> Answered {
    let Description { unit, help } = metrics.description(name)?;
    Ok(MetricsDescription { name: name.to_owned(), unit, help }.encode())
}

/// The damaged series a body holds, 1000 at most: deleting them shows the
/// next.
fn damaged(metrics: &Metrics, max_body: usize) -> Answered {
    let mut size = ENVELOPE;
    let mut damages = Vec::new();
    for damage in metrics.damaged()? {
        let weight = damage.name.len() + damage.error.len() + labels_weight(&damage.labels) + ENVELOPE;
        if size + weight > max_body && !damages.is_empty() {
            break;
        }
        size += weight;
        damages.push(MetricsDamage { name: damage.name, labels: damage.labels, error: damage.error });
    }
    Ok(MetricsDamages { damages }.encode())
}

fn ingest(metrics: &Metrics, ingest: MetricsIngest) -> Answered {
    let series: Vec<Series> = ingest.series.into_iter().map(series_of).collect::<Result<_, _>>()?;
    metrics.ingest(&series)?;
    Ok(Empty {}.encode())
}

/// A text an exporter serves, read by the core's one parser for every SDK.
fn ingest_prometheus(metrics: &Metrics, given: MetricsExposition) -> Answered {
    prometheus(metrics, given.labels, given.at, given.keep).ingest(&given.text)?;
    Ok(Empty {}.encode())
}

/// What reads a text with the labels, the time and the keep a client gave.
fn prometheus(metrics: &Metrics, labels: BTreeMap<String, String>, at: Option<i64>, keep: Option<u64>) -> Prometheus {
    let mut text = metrics.prometheus();
    for (label, value) in labels {
        text = text.label(label, value);
    }
    if let Some(at) = at {
        text = text.at(from_unix_millis(at));
    }
    if let Some(keep) = keep {
        text = text.keep(Duration::from_millis(keep));
    }
    text
}

/// A series to write, its columns read back into samples.
fn series_of(given: MetricsNewSeries) -> Result<Series, Failure> {
    let mut series = match given.kind.as_str() {
        "gauge" => Series::gauge(given.name),
        "counter" => Series::counter(given.name),
        "histogram" => Series::histogram(given.name),
        kind => return Err(Failure::invalid(format!("a kind {kind:?}: gauge, counter or histogram"))),
    };
    for (label, value) in given.labels {
        series = series.label(label, value);
    }
    if given.times.len() != given.values.len() || !given.times.len().is_multiple_of(8) {
        return Err(Failure::invalid("a series' times and values: 8 bytes a sample each, as many of each"));
    }
    let times = given.times.as_chunks::<8>().0.iter().map(|time| i64::from_le_bytes(*time));
    let values = given.values.as_chunks::<8>().0.iter().map(|value| f64::from_le_bytes(*value));
    series.extend(times.zip(values).map(|(at, value)| (from_unix_millis(at), value)));
    if let Some(keep) = given.keep {
        series = series.keep(Duration::from_millis(keep));
    }
    Ok(series)
}

fn replace(metrics: &Metrics, asked: MetricsReplace) -> Answered {
    let series = series_of(asked.series)?;
    metrics.replace(&series, from_unix_millis(asked.from)..from_unix_millis(asked.to))?;
    Ok(Empty {}.encode())
}

fn describe(metrics: &Metrics, described: MetricsDescription) -> Answered {
    metrics.describe(&described.name, Description { unit: described.unit, help: described.help })?;
    Ok(Empty {}.encode())
}

fn delete(metrics: &Metrics, named: MetricsSeriesNamed) -> Answered {
    let found = metrics.delete(&named.name, &named.labels)?;
    Ok(MetricsDeleted { found }.encode())
}

/// A read's series in parts of at most `bound` bytes: a series longer than
/// what a part leaves goes on in the next, `more` set on the piece before.
fn read_parts(page: SeriesPage, bound: usize) -> VecDeque<Vec<u8>> {
    let mut parts: Parts<MetricsRead> = Parts::new(bound);
    for read in page.series {
        let head = read.name().len() + labels_weight(read.labels()) + ENVELOPE;
        let samples = read.samples();
        let mut from = 0;
        loop {
            let take = parts.room(head, SAMPLE).min(samples.len() - from);
            let cut = &samples[from..from + take];
            let piece = MetricsSeries {
                name: read.name().to_owned(),
                kind: read.kind().as_str().to_owned(),
                labels: read.labels().clone(),
                times: cut.iter().flat_map(|sample| unix_millis(sample.at).to_le_bytes()).collect(),
                values: cut.iter().flat_map(|sample| sample.value.to_le_bytes()).collect(),
                more: from + take < samples.len() || read.more(),
            };
            parts.take(head + take * SAMPLE, |part| part.series.push(piece));
            from += take;
            if from == samples.len() {
                break;
            }
            parts.close();
        }
    }
    let next = page.next;
    parts.last(next.as_ref().map_or(0, String::len), |part| part.next = next)
}

fn latest_parts(latest: Vec<Latest>, bound: usize) -> VecDeque<Vec<u8>> {
    let mut parts: Parts<MetricsLatest> = Parts::new(bound);
    for newest in latest {
        let weight = newest.name.len() + labels_weight(&newest.labels) + ENVELOPE;
        parts.room(weight, 0);
        let newest =
            MetricsNewest { name: newest.name, labels: newest.labels, at: unix_millis(newest.at), value: newest.value };
        parts.take(weight, |part| part.series.push(newest));
    }
    parts.finish()
}

/// An aggregate's groups in parts of at most `bound` bytes: a group longer
/// than what a part leaves goes on in the next, `more` set on the piece
/// before.
fn aggregate_parts(page: AggregatePage, bound: usize) -> VecDeque<Vec<u8>> {
    let mut parts: Parts<MetricsAggregates> = Parts::new(bound);
    for group in page.groups {
        let head = group.name.len() + labels_weight(&group.labels) + ENVELOPE;
        let mut buckets = group.buckets.into_iter().map(bucket_of).peekable();
        loop {
            let take = parts.room(head, BUCKET);
            let cut: Vec<MetricsBucket> = buckets.by_ref().take(take).collect();
            let rest = buckets.peek().is_some();
            let (name, labels, more) = (group.name.clone(), group.labels.clone(), rest || group.more);
            let piece = MetricsGroup { name, labels, buckets: cut, more };
            parts.take(head + piece.buckets.len() * BUCKET, |part| part.groups.push(piece));
            if !rest {
                break;
            }
            parts.close();
        }
    }
    let next = page.next;
    parts.last(next.as_ref().map_or(0, String::len), |part| part.next = next)
}

fn bucket_of(bucket: crate::metrics::Bucket) -> MetricsBucket {
    let mut out = MetricsBucket {
        at: unix_millis(bucket.at),
        samples: bucket.samples,
        resets: bucket.resets,
        partial: bucket.partial,
        gap: bucket.gap,
        ..MetricsBucket::default()
    };
    match bucket.value {
        Value::Exact(value) => out.value = Some(value),
        Value::Between { lower, upper, estimate } => {
            (out.lower, out.upper, out.estimate) = (Some(lower), Some(upper), estimate);
        }
    }
    out
}

fn labels_weight(labels: &BTreeMap<String, String>) -> usize {
    labels.iter().map(|(label, value)| label.len() + value.len() + 4).sum()
}

/// An answer's parts as they are filled: those closed, the one being
/// filled and what it weighs.
struct Parts<M> {
    bound: usize,
    done: VecDeque<Vec<u8>>,
    open: M,
    filled: bool,
    size: usize,
}

impl<M: Message> Parts<M> {
    fn new(bound: usize) -> Parts<M> {
        Parts { bound, done: VecDeque::new(), open: M::default(), filled: false, size: ENVELOPE }
    }

    /// How many items of `each` bytes the open part takes beside a head of
    /// `head`, closing it first when it holds something and has no room:
    /// one at least, so that an item larger than a part still goes.
    fn room(&mut self, head: usize, each: usize) -> usize {
        if self.filled && self.size + head + each > self.bound {
            self.close();
        }
        let left = self.bound.saturating_sub(self.size + head);
        left.checked_div(each).map_or(1, |fits| fits.max(1))
    }

    fn take(&mut self, weight: usize, put: impl FnOnce(&mut M)) {
        put(&mut self.open);
        self.filled = true;
        self.size += weight;
    }

    fn close(&mut self) {
        if std::mem::replace(&mut self.filled, false) {
            self.done.push_back(std::mem::take(&mut self.open).encode());
        }
        self.size = ENVELOPE;
    }

    /// Every part, the last among them: an empty answer is one empty part.
    fn finish(mut self) -> VecDeque<Vec<u8>> {
        self.done.push_back(self.open.encode());
        self.done
    }

    /// Every part, with `put` on the last: in a part of its own when the open
    /// one has no room for its `weight`.
    fn last(mut self, weight: usize, put: impl FnOnce(&mut M)) -> VecDeque<Vec<u8>> {
        if self.filled && self.size + weight > self.bound {
            self.close();
        }
        put(&mut self.open);
        self.finish()
    }
}

/// Sends an answer's parts within the client's credit, its RESPONSE gone
/// out; the last ends the stream.
pub(crate) fn download(handles: &Handles, stream: u32, parts: VecDeque<Vec<u8>>, link: Link) {
    let download = Arc::new(Downloading { stream, state: Mutex::new((parts, link.credit, false)), link });
    lock(&handles.downloads).insert(stream, Arc::clone(&download));
    download.flush(&handles.downloads);
}

/// An answer's parts going out within the client's credit: those left, the
/// credit, and whether the stream ended.
struct Downloading {
    stream: u32,
    state: Mutex<(VecDeque<Vec<u8>>, u64, bool)>,
    link: Link,
}

impl Downloading {
    fn grant(&self, credit: u32, downloads: &Mutex<HashMap<u32, Arc<Downloading>>>) {
        lock(&self.state).1 += u64::from(credit);
        self.flush(downloads);
    }

    /// Sends the parts the credit takes; the last ends the stream.
    fn flush(&self, downloads: &Mutex<HashMap<u32, Arc<Downloading>>>) {
        let mut state = lock(&self.state);
        let (parts, credit, ended) = &mut *state;
        while !*ended {
            let Some(next) = parts.front() else { return };
            if next.len() as u64 > *credit {
                return;
            }
            let part = parts.pop_front().unwrap_or_default();
            *credit -= part.len() as u64;
            if parts.is_empty() {
                *ended = true;
                drop(state);
                lock(downloads).remove(&self.stream);
                return (self.link.finish)(Ok(part));
            }
            (self.link.send)(part);
        }
    }

    fn end(&self, last: Answered) {
        if std::mem::replace(&mut lock(&self.state).2, true) {
            return;
        }
        (self.link.finish)(last);
    }
}

/// Opens a client's instruments' stream: its session on the store, answered
/// in the RESPONSE with what the store knows of it.
pub(crate) fn instruments(store: &Store, handles: &Handles, stream: u32, body: &[u8], link: Link) -> Answered {
    let session = MetricsSession::decode(body)?;
    let id: [u8; 16] = session.id.as_slice().try_into().map_err(|_| Failure::invalid("a session of 16 bytes"))?;
    let (remote, ack) = store.metrics()?.remote(id, session.after);
    let instruments = Instruments { remote: Mutex::new(remote), waiting: Mutex::default(), link };
    lock(&handles.instruments).insert(stream, Arc::new(instruments));
    Ok(ack_of(ack).encode())
}

/// A client's instruments' stream: its session's stream on the store, the
/// batches waiting their turn, and what the stream needs of the session.
struct Instruments {
    remote: Mutex<Remote>,
    waiting: Mutex<Waiting>,
    link: Link,
}

#[derive(Default)]
struct Waiting {
    /// Each batch's bytes, and whether it was the client's last DATA.
    batches: VecDeque<(Vec<u8>, bool)>,
    /// A worker applies them.
    running: bool,
    /// The stream's final frame went: a batch applied after answers nothing.
    ended: bool,
}

impl Instruments {
    /// Applies the waiting batches in turn, each answered as a DATA; the
    /// client's last ends the stream with the last answer, and a batch
    /// refused ends it with why. A cancel may end the stream while a batch
    /// is applied: what goes out is decided under `waiting`, where the
    /// cancel says the stream ended, so that nothing follows its final frame.
    fn drain(self: &Arc<Self>, stream: u32, open: &Mutex<HashMap<u32, Arc<Instruments>>>) {
        loop {
            let (body, last) = {
                let mut waiting = lock(&self.waiting);
                let Some(next) = waiting.batches.pop_front().filter(|_| !waiting.ended) else {
                    waiting.running = false;
                    return;
                };
                next
            };
            let applied = self.apply(&body);
            let mut waiting = lock(&self.waiting);
            if waiting.ended {
                waiting.running = false;
                return;
            }
            match (applied, last) {
                (Ok(ack), false) => {
                    // Credit goes back once a batch is applied, as records and
                    // blobs grant theirs: a client sends no faster than it is taken.
                    (self.link.grant)(u32::try_from(body.len()).unwrap_or(u32::MAX));
                    (self.link.send)(ack);
                }
                (answered, _) => {
                    (waiting.ended, waiting.running) = (true, false);
                    drop(waiting);
                    // the number may name another stream by now, whose instruments stay
                    let mut open = lock(open);
                    if open.get(&stream).is_some_and(|kept| Arc::ptr_eq(kept, self)) {
                        open.remove(&stream);
                    }
                    drop(open);
                    return (self.link.finish)(answered);
                }
            }
        }
    }

    /// Ends the stream with `last` unless it ended already, the batches
    /// waiting dropped unapplied.
    fn end(&self, last: Answered) {
        {
            let mut waiting = lock(&self.waiting);
            if std::mem::replace(&mut waiting.ended, true) {
                return;
            }
            waiting.batches.clear();
        }
        (self.link.finish)(last);
    }

    fn apply(&self, body: &[u8]) -> Answered {
        let mut remote = lock(&self.remote);
        if body.is_empty() {
            return Ok(ack_of(remote.ack()).encode());
        }
        let batch = batch_of(MetricsBatch::decode(body)?)?;
        Ok(ack_of(remote.apply(batch)?).encode())
    }
}

fn ack_of(ack: Ack) -> MetricsAck {
    let refused = ack.refused.into_iter().map(|(instrument, error)| MetricsRefused { instrument, error }).collect();
    MetricsAck { applied: ack.applied, known: ack.known, refused }
}

/// A batch as the store applies it.
fn batch_of(batch: MetricsBatch) -> Result<Batch, Failure> {
    let instruments = batch.instruments.into_iter().map(|declared| {
        let buckets = match (declared.bounds, declared.exponential) {
            (Some(_), true) => return Err(Failure::invalid("an instrument's bounds or its grid, not both")),
            (Some(bounds), false) => Some(Buckets::Bounds(bounds)),
            (None, true) => Some(Buckets::Exponential),
            (None, false) => None,
        };
        Ok(Declared {
            number: declared.number,
            name: declared.name,
            form: declared.form,
            unit: declared.unit,
            help: declared.help,
            keep: declared.keep.map(Duration::from_millis),
            buckets,
        })
    });
    let sets = batch.sets.into_iter().map(|set| Set {
        number: set.number,
        instrument: set.instrument,
        labels: set.labels,
        overflow: set.overflow,
    });
    let changes = batch.changes.into_iter().map(|change| Change {
        set: change.set,
        add: change.add,
        value: change.value,
        count: change.count,
        sum: change.sum,
        longest: change.longest,
        buckets: change.buckets,
        bins: change.bins.into_iter().collect(),
    });
    Ok(Batch {
        number: batch.number,
        instruments: instruments.collect::<Result<_, _>>()?,
        sets: sets.collect(),
        changes: changes.collect(),
        flush: batch.flush,
    })
}

/// Begins a text that comes in pieces: what reads it, and its size, a size
/// past what an upload gathers refused before any of it comes. The store's
/// memory for it is reserved by [`Gathering::begin`], once the RESPONSE went.
pub(crate) fn gather(
    store: &Store,
    handles: &Handles,
    stream: u32,
    body: &[u8],
    link: Link,
) -> Result<Arc<Gathering>, Failure> {
    let asked = MetricsUpload::decode(body)?;
    let size = usize::try_from(asked.size).ok().filter(|size| *size <= TEXT_MOST).ok_or_else(|| past(asked.size))?;
    let gathering = Arc::new(Gathering {
        stream,
        size,
        prometheus: prometheus(&store.metrics()?, asked.labels, asked.at, asked.keep),
        memory: Arc::clone(store.memory()),
        // busy until `begin`'s worker has the memory: a piece before it waits
        state: Mutex::new(Gathered { busy: true, ..Gathered::default() }),
        link,
        gatherings: Arc::downgrade(&handles.gatherings),
    });
    lock(&handles.gatherings).insert(stream, Arc::clone(&gathering));
    Ok(gathering)
}

/// A text of `size` bytes, past what an upload gathers, with the facts a
/// limit names.
fn past(size: u64) -> Failure {
    TEXT_BYTES.refuse(size, format!("{UPLOADED} of {size} bytes, past one text's {} MiB", TEXT_MOST >> 20)).into()
}

/// A text that comes as the client's pieces, gathered in the store's memory
/// before it is read and written whole. Its pieces are taken in turn on a
/// worker, the first of which reserves the memory of the whole text.
pub(crate) struct Gathering {
    stream: u32,
    size: usize,
    prometheus: Prometheus,
    memory: Arc<Memory>,
    state: Mutex<Gathered>,
    link: Link,
    gatherings: Weak<Gatherings>,
}

#[derive(Default)]
struct Gathered {
    /// The text's bytes so far, here while no worker takes pieces: none
    /// before its memory is reserved.
    text: Option<Text>,
    /// The client's DATA not taken yet, and whether each was its last.
    pieces: VecDeque<(Vec<u8>, bool)>,
    /// A worker reserves the text's memory or takes its pieces.
    busy: bool,
    /// The client cancelled: whoever holds the text lets it go, and then
    /// answers, so that `cancelled` means nothing of it is held.
    cancelled: bool,
    ended: bool,
}

/// A text's bytes, and the store's memory held for all of them.
struct Text {
    bytes: Vec<u8>,
    _held: Reservation,
}

impl Gathering {
    /// Reserves the store's memory for the whole text on a worker, then takes
    /// the pieces that came meanwhile.
    pub(crate) fn begin(self: &Arc<Self>) {
        let gathering = Arc::clone(self);
        (self.link.spawn)(Box::new(move || gathering.reserve()));
    }

    /// Waits for the text's memory as an ingest does, rather than refuse a
    /// scrape while a merge holds it for a moment.
    fn reserve(&self) {
        match self.memory.reserve(self.size as u64, UPLOADED, PATIENCE) {
            Ok(held) => self.take_pieces(Text { bytes: Vec::with_capacity(self.size), _held: held }),
            Err(error) => self.end(Err(error.into())),
        }
    }

    /// A DATA the client sent, its last when `last`: queued, and taken in the
    /// order it came on a worker.
    pub(crate) fn piece(self: &Arc<Self>, body: Vec<u8>, last: bool) {
        {
            let mut state = lock(&self.state);
            if state.ended || state.cancelled {
                return;
            }
            state.pieces.push_back((body, last));
            if std::mem::replace(&mut state.busy, true) {
                return;
            }
        }
        let gathering = Arc::clone(self);
        (self.link.spawn)(Box::new(move || gathering.resume()));
    }

    /// Takes the pieces waiting with the text a worker before left.
    fn resume(&self) {
        let Some(text) = lock(&self.state).text.take() else { return };
        self.take_pieces(text);
    }

    /// Takes the pieces waiting into the text in turn, each one's credit
    /// given back once it is kept, the last writing the text; with none
    /// waiting, the text stays for the worker of the next.
    fn take_pieces(&self, mut text: Text) {
        loop {
            let (body, last) = {
                let mut state = lock(&self.state);
                if state.cancelled {
                    drop(state);
                    drop(text);
                    return self.end(Err(Failure::cancelled("the client cancelled its upload")));
                }
                let Some(next) = state.pieces.pop_front() else {
                    state.text = Some(text);
                    state.busy = false;
                    return;
                };
                next
            };
            if let Err(failure) = self.keep(&mut text.bytes, &body) {
                drop(text);
                return self.end(Err(failure));
            }
            if last {
                return self.end(self.write(text));
            }
            (self.link.grant)(u32::try_from(body.len()).unwrap_or(u32::MAX));
        }
    }

    /// Adds a piece's bytes to the text, refusing those past the size its
    /// upload said, which is all its memory holds.
    fn keep(&self, bytes: &mut Vec<u8>, body: &[u8]) -> Result<(), Failure> {
        if body.is_empty() {
            return Ok(());
        }
        let piece = MetricsPiece::decode(body)?;
        if bytes.len() + piece.bytes.len() > self.size {
            return Err(Failure::invalid(format!("{UPLOADED}: pieces past the {} bytes its upload said", self.size)));
        }
        bytes.extend_from_slice(&piece.bytes);
        Ok(())
    }

    /// Reads and writes the whole text, every series or none, its memory let
    /// go before the answer leaves.
    fn write(&self, text: Text) -> Answered {
        let (came, size) = (text.bytes.len(), self.size);
        if came != size {
            return Err(Failure::invalid(format!("{UPLOADED}: pieces of {came} bytes, short of the {size} it said")));
        }
        self.prometheus.ingest(&text.bytes)?;
        Ok(Empty {}.encode())
    }

    /// Ends the upload, what it gathered let go: here, or by the worker that
    /// holds the text once it is done with a piece. A text being written
    /// still is, and the answer says how that went.
    fn cancel(&self) {
        let text = {
            let mut state = lock(&self.state);
            state.cancelled = true;
            if state.busy {
                return;
            }
            state.text.take()
        };
        drop(text);
        self.end(Err(Failure::cancelled("the client cancelled its upload")));
    }

    fn end(&self, last: Answered) {
        {
            let mut state = lock(&self.state);
            if std::mem::replace(&mut state.ended, true) {
                return;
            }
            state.pieces.clear();
        }
        if let Some(gatherings) = self.gatherings.upgrade() {
            lock(&gatherings).remove(&self.stream);
        }
        (self.link.finish)(last);
    }
}

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