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
//! The totals the store keeps of its instruments, a slot for each set of
//! labels: a counter's since its run began, a timer's and a histogram's
//! count, sum and buckets the same way, and a gauge's value with the
//! connection that set it.
//!
//! ```text
//! inc() ──► its slot's pending sum, an atomic add ──► the next write takes it into its run's total ──► a sample
//! ```
//!
//! A call changes a number in memory and takes no lock but a timer's. A
//! write, every 15 seconds, at a flush and when the store closes, takes what
//! changed into each run's total and writes every live total at one time.
//! A run begins with a zero at the write before its first call, the last
//! time the series is known to have been zero, so that a reset reads as one
//! even when the new count passed the old; it ends once nothing was sent for
//! an hour, its slot freed unless a handle holds it.
//!
//! A timer's exponential grid counts each interval apart, and an interval is
//! a run of its own: it begins with its zero at the first write that finds a
//! value in it, and ends once none fell in it for an hour.

use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};

use super::buckets::{Bounds, MOST_BOUNDS, bucket_of};
use super::grid::{Bin, FINEST};
use super::labels::{BIN, Kept, OVERFLOW};
use super::series::{Kind, Labels};
use crate::sync::lock;
use crate::{Error, Result};

/// The sets of labels an instrument holds at most; a new one past them
/// counts into its series of `__overflow`.
pub(super) const MOST_SETS: usize = 2000;
/// How long a counter's, a timer's or a histogram's series may go without a
/// call before its run ends and its slot is freed.
const IDLE: i64 = 3_600_000;
/// The owner of a gauge nobody has set.
const NOBODY: u64 = u64::MAX;
/// The owner of what this process sets through its own handles.
pub(super) const LOCAL: u64 = 0;

/// What an instrument is.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Form {
    Counter,
    Gauge,
    Timer,
    Histogram,
}

impl Form {
    /// The form a client names over the wire.
    #[cfg(feature = "wire")]
    pub(super) fn parse(word: &str) -> Option<Form> {
        [Form::Counter, Form::Gauge, Form::Timer, Form::Histogram].into_iter().find(|form| form.as_str() == word)
    }

    pub(super) fn as_str(self) -> &'static str {
        match self {
            Form::Counter => "counter",
            Form::Gauge => "gauge",
            Form::Timer => "timer",
            Form::Histogram => "histogram",
        }
    }

    /// The names an instrument of this form writes and their kinds: its own,
    /// or a timer's and a histogram's count, sum, longest and buckets.
    pub(super) fn written(self, name: &str, buckets: bool) -> Vec<(String, Kind)> {
        match self {
            Form::Counter => vec![(name.to_owned(), Kind::Counter)],
            Form::Gauge => vec![(name.to_owned(), Kind::Gauge)],
            Form::Timer | Form::Histogram => {
                let mut written = vec![
                    (format!("{name}_count"), Kind::Counter),
                    (format!("{name}_sum"), Kind::Counter),
                    (format!("{name}_max"), Kind::Gauge),
                ];
                written.extend(buckets.then(|| (format!("{name}_bucket"), Kind::Histogram)));
                written
            }
        }
    }

    fn measures(self) -> bool {
        matches!(self, Form::Timer | Form::Histogram)
    }
}

/// A series a slot writes: its labels, their identity and its kind.
#[derive(Clone, Debug)]
pub(super) struct Written {
    pub(super) kept: Kept,
    pub(super) identity: [u8; 32],
    pub(super) kind: Kind,
}

impl Written {
    fn of(kept: Kept, kind: Kind) -> Written {
        Written { identity: kept.identity(), kept, kind }
    }
}

/// One set of labels of an instrument and what calls changed of it.
pub(super) struct Slot {
    /// Its labels beside its instrument's name.
    pub(super) kept: Kept,
    /// The series it writes: a counter's or a gauge's own, a timer's count,
    /// sum, longest and given buckets, `+Inf` last; a grid's intervals are
    /// its run's.
    pub(super) series: Vec<Arc<Written>>,
    /// A counter's sum of what calls added since the last write, or a
    /// gauge's value: the bits of a float.
    pending: AtomicU64,
    /// A call since the last write, `add(0)` among them.
    sent: AtomicBool,
    /// The last total a program that keeps its own gave.
    absolute: AtomicU64,
    /// The connection that set a gauge last.
    owner: AtomicU64,
    /// A timer's or a histogram's measurements since the last write.
    measured: Option<Mutex<Measured>>,
    /// Labels it refused: nothing writes it.
    detached: bool,
    /// A refused call said.
    said: AtomicBool,
    /// What the writes keep of it.
    pub(super) run: Mutex<Run>,
}

/// What a client's timer or histogram measured since its last batch.
#[cfg(feature = "wire")]
#[derive(Debug, Default)]
pub(super) struct Measures {
    pub(super) count: u64,
    pub(super) sum: f64,
    pub(super) longest: f64,
    /// Each given bound's bucket's own count, `+Inf` last.
    pub(super) buckets: Vec<u64>,
    /// How many values fell in each interval of the finest grid.
    pub(super) bins: Vec<(Bin, u64)>,
}

/// What a timer or a histogram measured since the last write.
#[derive(Debug, Default)]
struct Measured {
    count: u64,
    sum: f64,
    longest: f64,
    measured: bool,
    /// Each given bound's bucket's own count, not yet summed into `le`'s.
    buckets: Vec<u64>,
    /// How many values fell in each interval of the finest grid.
    bins: BTreeMap<Bin, u64>,
}

impl Measured {
    /// Takes in a longest value since the write, the first since it the
    /// longest whatever it is.
    fn longest_is_at_least(&mut self, longest: f64) {
        self.longest = if self.measured { self.longest.max(longest) } else { longest };
        self.measured = true;
    }
}

impl Measured {
    /// What it measured, leaving it at zero with as many buckets, so that a
    /// call meanwhile always finds its bucket.
    fn take(&mut self) -> Measured {
        let buckets = vec![0; self.buckets.len()];
        let buckets = std::mem::replace(&mut self.buckets, buckets);
        let taken = Measured { buckets, bins: std::mem::take(&mut self.bins), ..*self };
        (self.count, self.sum, self.longest, self.measured) = (0, 0.0, 0.0, false);
        taken
    }
}

/// A slot's run, which the writes alone change.
#[derive(Debug, Default)]
pub(super) struct Run {
    live: bool,
    /// The zero the run begins with, until a write takes it.
    zero: Option<i64>,
    total: f64,
    count: u64,
    sum: f64,
    buckets: Vec<u64>,
    bins: Bins,
    /// The time of the last write that found a call.
    active_at: i64,
    /// What a write last refused it for, said once.
    refusal: Option<String>,
}

/// The intervals of an exponential grid a run counts, at one schema.
#[derive(Debug)]
struct Bins {
    schema: u8,
    live: BTreeMap<Bin, Counted>,
}

impl Default for Bins {
    fn default() -> Bins {
        Bins { schema: FINEST, live: BTreeMap::new() }
    }
}

/// An interval's run: how many values fell in it, the zero it begins with
/// until a write takes it, the last write that found a value in it, and its
/// series.
#[derive(Debug)]
struct Counted {
    total: u64,
    zero: Option<i64>,
    active_at: i64,
    written: Arc<Written>,
}

impl Bins {
    /// Counts a write's values, taken at the finest schema, into the run's
    /// intervals, and gives every live one's total. A new interval begins
    /// with its zero at `before`, the write before. Past `MOST_BOUNDS`
    /// intervals the schema lowers: the finer intervals end where they are,
    /// and the coarser begin at zero with this write's values, so that no
    /// value is counted twice. One nothing fell in for an hour ends.
    fn count(&mut self, slot: &Slot, taken: &BTreeMap<Bin, u64>, now: i64, before: i64) -> Vec<Value> {
        if self.schema > 0 && self.past_bound(taken) {
            self.lower(taken);
        }
        for (bin, count) in taken {
            let bin = bin.at(self.schema);
            if let Some(counted) = self.live.get_mut(&bin) {
                counted.total += count;
                counted.active_at = now;
            } else if let Some(written) = slot.interval(bin) {
                self.live.insert(bin, Counted { total: *count, zero: Some(before), active_at: now, written });
            }
        }
        let values = self.live.values().map(|counted| Value {
            written: Arc::clone(&counted.written),
            zero: counted.zero,
            value: counted.total as f64,
        });
        let values = values.collect();
        self.live.retain(|_, counted| now.saturating_sub(counted.active_at) < IDLE);
        values
    }

    /// Whether a write's values would hold the run past its bound of
    /// intervals at its schema.
    fn past_bound(&self, taken: &BTreeMap<Bin, u64>) -> bool {
        let fresh: BTreeSet<Bin> =
            taken.keys().map(|bin| bin.at(self.schema)).filter(|bin| !self.live.contains_key(bin)).collect();
        self.live.len() + fresh.len() > MOST_BOUNDS
    }

    /// Ends every live interval and lowers the schema until a write's values
    /// alone fit, or to one interval a doubling.
    fn lower(&mut self, taken: &BTreeMap<Bin, u64>) {
        self.live.clear();
        while self.schema > 0 {
            self.schema -= 1;
            let distinct: BTreeSet<Bin> = taken.keys().map(|bin| bin.at(self.schema)).collect();
            if distinct.len() <= MOST_BOUNDS {
                break;
            }
        }
    }

    /// A write took every live interval's zero.
    fn written(&mut self) {
        for counted in self.live.values_mut() {
            counted.zero = None;
        }
    }
}

impl Slot {
    fn new(kept: Kept, series: Vec<Arc<Written>>, form: Form, buckets: usize) -> Slot {
        let measured =
            form.measures().then(|| Mutex::new(Measured { buckets: vec![0; buckets], ..Measured::default() }));
        Slot {
            kept,
            series,
            pending: AtomicU64::new(0.0_f64.to_bits()),
            sent: AtomicBool::new(false),
            absolute: AtomicU64::new(0),
            owner: AtomicU64::new(NOBODY),
            measured,
            detached: false,
            said: AtomicBool::new(false),
            run: Mutex::default(),
        }
    }

    /// A slot no write takes, for labels a call gave that were refused.
    fn detached(kept: Kept) -> Slot {
        Slot { detached: true, ..Slot::new(kept, Vec::new(), Form::Counter, 0) }
    }

    fn is_overflow(&self) -> bool {
        self.kept.pairs().iter().any(|(label, _)| label == OVERFLOW)
    }

    /// Adds to a counter: false when its pending sum would not be a finite
    /// number, and the call then changes nothing.
    pub(super) fn add(&self, n: f64) -> bool {
        let added = add_float(&self.pending, n);
        self.sent.store(true, Ordering::Release);
        added
    }

    /// What a total the program keeps itself grew since the last it gave,
    /// or all of it when it is smaller, a restart's.
    pub(super) fn advance_to(&self, total: u64) -> u64 {
        let last = self.absolute.swap(total, Ordering::AcqRel);
        if total >= last { total - last } else { total }
    }

    /// Sets a gauge, for `owner`.
    pub(super) fn set(&self, value: f64, owner: u64) {
        self.pending.store(value.to_bits(), Ordering::Release);
        self.owner.store(owner, Ordering::Release);
    }

    /// Moves a gauge by `delta`, for `owner`: false when its value would not
    /// be a finite number.
    pub(super) fn shift(&self, delta: f64, owner: u64) -> bool {
        let moved = add_float(&self.pending, delta);
        if moved {
            self.owner.store(owner, Ordering::Release);
        }
        moved
    }

    /// Counts a timer's duration or a histogram's value into its bucket.
    pub(super) fn measure(&self, value: f64, bounds: Option<&Bounds>) {
        let Some(measured) = &self.measured else { return };
        let mut measured = lock(measured);
        measured.count += 1;
        measured.sum += value;
        measured.longest_is_at_least(value);
        match bounds {
            Some(Bounds::Given(bounds)) => measured.buckets[bucket_of(bounds, value)] += 1,
            Some(Bounds::Exponential) => *measured.bins.entry(Bin::of(value, FINEST)).or_default() += 1,
            None => {}
        }
    }

    /// Adds what a client's timer or histogram measured since its last
    /// batch, under the lock a call takes, so that its parts move together.
    #[cfg(feature = "wire")]
    pub(super) fn merge(&self, measures: &Measures) {
        let Some(measured) = &self.measured else { return };
        if measures.count == 0 {
            return;
        }
        let mut measured = lock(measured);
        measured.count += measures.count;
        measured.sum += measures.sum;
        measured.longest_is_at_least(measures.longest);
        for (total, more) in measured.buckets.iter_mut().zip(&measures.buckets) {
            *total += more;
        }
        for (bin, count) in &measures.bins {
            *measured.bins.entry(*bin).or_default() += count;
        }
    }

    /// The series of an interval of its grid: its `_bucket`, the interval in
    /// the store's label `__bin`; none for labels that leave it no room,
    /// said once.
    fn interval(&self, bin: Bin) -> Option<Arc<Written>> {
        let name = format!("{}_bucket", self.kept.name());
        match self.kept.derived(&name, Some((BIN, &bin.label()))) {
            Ok(kept) => Some(Arc::new(Written::of(kept, Kind::Histogram))),
            Err(error) => {
                self.refuse(&format!("an interval of its buckets: {error}"));
                None
            }
        }
    }

    /// Says once that a call was refused, and why.
    pub(super) fn refuse(&self, why: &str) {
        if !self.said.swap(true, Ordering::AcqRel) {
            tracing::warn!(target: "tinystore", series = %self.kept, "metrics: {why}; said once");
        }
    }
}

/// An instrument: its name, its form, its buckets, and its slots by their
/// labels.
pub(super) struct Instrument {
    pub(super) name: String,
    pub(super) form: Form,
    pub(super) bounds: Option<Bounds>,
    sets: Mutex<Sets>,
    said_overflow: AtomicBool,
    said_labels: AtomicBool,
}

/// An instrument's slots: its own name's without labels, which takes none
/// of the places of its sets, those of its sets of labels, and the one of
/// `__overflow`.
#[derive(Default)]
struct Sets {
    base: Option<Arc<Slot>>,
    by_labels: HashMap<Kept, Arc<Slot>>,
    overflow: Option<Arc<Slot>>,
}

impl Instrument {
    pub(super) fn new(name: &str, form: Form, bounds: Option<Bounds>) -> Instrument {
        Instrument {
            name: name.to_owned(),
            form,
            bounds,
            sets: Mutex::default(),
            said_overflow: AtomicBool::new(false),
            said_labels: AtomicBool::new(false),
        }
    }

    /// The slot of the instrument's own name without labels.
    pub(super) fn base(&self) -> Result<Arc<Slot>> {
        self.slot(&Labels::new())
    }

    /// The slot of `parent`'s labels and `more`: a label given again takes
    /// its new value. Labels it refuses give a slot nothing writes, said
    /// once; past its sets of labels, its series of `__overflow`.
    pub(super) fn with(&self, parent: &Arc<Slot>, more: &[(&str, &str)]) -> Arc<Slot> {
        if parent.detached || parent.is_overflow() {
            return Arc::clone(parent);
        }
        let mut labels = parent.kept.labels();
        labels.extend(more.iter().map(|(label, value)| ((*label).to_owned(), (*value).to_owned())));
        self.slot(&labels).unwrap_or_else(|error| {
            if !self.said_labels.swap(true, Ordering::AcqRel) {
                let name = &self.name;
                let why = "labels refused, written nowhere";
                tracing::warn!(target: "tinystore", %error, "metrics {name}: {why}; said once");
            }
            Arc::new(Slot::detached(parent.kept.clone()))
        })
    }

    fn slot(&self, labels: &Labels) -> Result<Arc<Slot>> {
        if self.form.measures() && labels.contains_key("le") {
            return Err(Error::invalid("label \"le\": a timer's `_bucket` series give it"));
        }
        let kept = Kept::of(&self.name, labels)?;
        let mut sets = lock(&self.sets);
        if labels.is_empty() {
            if let Some(base) = &sets.base {
                return Ok(Arc::clone(base));
            }
            let base = Arc::new(self.made(kept)?);
            sets.base = Some(Arc::clone(&base));
            return Ok(base);
        }
        if let Some(slot) = sets.by_labels.get(&kept) {
            return Ok(Arc::clone(slot));
        }
        if sets.by_labels.len() >= MOST_SETS {
            return self.overflow(&mut sets);
        }
        let slot = Arc::new(self.made(kept.clone())?);
        sets.by_labels.insert(kept, Arc::clone(&slot));
        Ok(slot)
    }

    /// Its series of `__overflow`, for a client that counts past the sets
    /// of labels it holds.
    #[cfg(feature = "wire")]
    pub(super) fn overflowed(&self) -> Result<Arc<Slot>> {
        self.overflow(&mut lock(&self.sets))
    }

    /// Its series of `__overflow`, said once when it is first counted into.
    fn overflow(&self, sets: &mut Sets) -> Result<Arc<Slot>> {
        if let Some(slot) = &sets.overflow {
            return Ok(Arc::clone(slot));
        }
        if !self.said_overflow.swap(true, Ordering::AcqRel) {
            let name = &self.name;
            let why = format!("past {MOST_SETS} sets of labels, counting into __overflow");
            tracing::warn!(target: "tinystore", "metrics {name}: {why}; said once");
        }
        let slot = Arc::new(self.made(Kept::overflow(&self.name))?);
        sets.overflow = Some(Arc::clone(&slot));
        Ok(slot)
    }

    /// A slot of `kept` and the series it writes.
    fn made(&self, kept: Kept) -> Result<Slot> {
        let buckets = self.bounds.as_ref().map_or(0, Bounds::buckets);
        let mut series = Vec::new();
        for (name, kind) in self.form.written(&self.name, self.bounds.is_some()) {
            if kind == Kind::Histogram {
                let labels = self.bounds.as_ref().map(Bounds::labels).unwrap_or_default();
                for le in labels {
                    series.push(Arc::new(Written::of(kept.derived(&name, Some(("le", &le)))?, kind)));
                }
            } else if name == self.name {
                series.push(Arc::new(Written::of(kept.clone(), kind)));
            } else {
                series.push(Arc::new(Written::of(kept.derived(&name, None)?, kind)));
            }
        }
        Ok(Slot::new(kept, series, self.form, buckets))
    }

    /// Every slot it holds.
    fn slots(&self) -> Vec<Arc<Slot>> {
        let sets = lock(&self.sets);
        sets.base.iter().chain(sets.by_labels.values()).chain(sets.overflow.iter()).cloned().collect()
    }

    /// Frees the slots of runs that ended which no handle holds. Under the
    /// lock no call can take another handle, so a count of the slot's own
    /// references is exact: the set's entry, `ended`'s and the write's plan.
    fn free(&self, ended: &[Arc<Slot>]) {
        const OURS: usize = 3;
        let mut sets = lock(&self.sets);
        for slot in ended {
            if Arc::strong_count(slot) == OURS
                && sets.by_labels.get(&slot.kept).is_some_and(|held| Arc::ptr_eq(held, slot))
            {
                sets.by_labels.remove(&slot.kept);
            }
        }
    }
}

/// A gauge's function, its error as text.
pub(super) type Read = Box<dyn Fn() -> std::result::Result<f64, String> + Send + Sync>;

/// A gauge whose value a function reads at each write.
pub(super) struct Reader {
    pub(super) slot: Arc<Slot>,
    read: Read,
    /// The error said, while it repeats.
    said: Mutex<Option<String>>,
}

impl Reader {
    /// Reads the gauge's value into its slot; a failure, a panic or a value
    /// that is not a finite number leaves it unset this time, said once
    /// while it repeats.
    fn read(&self) {
        let read = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| (self.read)()));
        let value = match read {
            Ok(Ok(value)) if value.is_finite() => Ok(value),
            Ok(Ok(value)) => Err(format!("its function gave {value}, where a gauge is a finite number")),
            Ok(Err(error)) => Err(format!("its function failed: {error}")),
            Err(_) => Err("its function panicked".to_owned()),
        };
        let mut said = lock(&self.said);
        match value {
            Ok(value) => {
                self.slot.set(value, LOCAL);
                *said = None;
            }
            Err(why) => {
                self.slot.owner.store(NOBODY, Ordering::Release);
                if said.as_deref() != Some(&why) {
                    let series = &self.slot.kept;
                    tracing::warn!(target: "tinystore", %series, "metrics: {why}, nothing written; said once");
                    *said = Some(why);
                }
            }
        }
    }
}

/// What an instrument was told of a name it writes, which the next write
/// writes: its unit, its help, a timer's bounds.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub(super) struct Told {
    pub(super) unit: Option<String>,
    pub(super) help: Option<String>,
    pub(super) buckets: Option<String>,
}

/// One slot's samples of a write: each of its series' value, and the zero a
/// run begins with.
pub(super) struct Planned {
    pub(super) slot: Arc<Slot>,
    pub(super) values: Vec<Value>,
    /// The longest duration a write took from a timer, which a failed write
    /// gives back.
    longest: Option<f64>,
}

/// A series' sample of a write.
#[derive(Clone, Debug)]
pub(super) struct Value {
    pub(super) written: Arc<Written>,
    /// The zero its run begins with, at this time.
    pub(super) zero: Option<i64>,
    pub(super) value: f64,
}

/// What a write did with a slot's samples.
pub(super) enum Outcome {
    Written,
    Refused(Error),
    /// Its write failed whole: tried again at the next.
    Failed,
}

/// The instruments of an engine and the totals of their series.
pub(super) struct Totals {
    registry: Mutex<Registry>,
    described: Mutex<BTreeMap<String, Told>>,
    /// The time of the last write, or the engine's start: a run that begins
    /// after it begins with a zero there.
    last_write: AtomicI64,
    #[cfg_attr(
        all(not(test), not(feature = "wire")),
        expect(dead_code, reason = "a client's connection comes over the wire")
    )]
    next_owner: AtomicU64,
}

#[derive(Default)]
struct Registry {
    /// By name, a timer's and a histogram's by its own.
    instruments: HashMap<String, Arc<Instrument>>,
    /// The gauges functions read, by name, a set of labels each.
    readers: HashMap<String, Vec<Arc<Reader>>>,
    /// The names written, each by the name of the one instrument that
    /// writes it.
    writers: HashMap<String, String>,
}

impl Totals {
    pub(super) fn new(started: i64) -> Totals {
        Totals {
            registry: Mutex::default(),
            described: Mutex::default(),
            last_write: AtomicI64::new(started),
            next_owner: AtomicU64::new(LOCAL + 1),
        }
    }

    /// The instrument of `name`, made the first time; another form or
    /// other buckets than it has, or a name another instrument writes, is
    /// refused.
    pub(super) fn instrument(&self, name: &str, form: Form, bounds: Option<Bounds>) -> Result<Arc<Instrument>> {
        let mut registry = lock(&self.registry);
        if let Some(held) = registry.instruments.get(name) {
            if held.form != form {
                let held = held.form.as_str();
                return Err(Error::invalid(format!(
                    "a {}, where it is a {held} while the store is open",
                    form.as_str()
                )));
            }
            if held.bounds != bounds {
                return Err(Error::invalid("buckets other than it has while the store is open"));
            }
            return Ok(Arc::clone(held));
        }
        let written = form.written(name, bounds.is_some());
        registry.claim(name, &written)?;
        let instrument = Arc::new(Instrument::new(name, form, bounds));
        registry.instruments.insert(name.to_owned(), Arc::clone(&instrument));
        Ok(instrument)
    }

    /// A gauge of these labels read by `read` at each write: each set of
    /// labels of a name has a function of its own, and the name no other
    /// instrument.
    pub(super) fn reader(&self, name: &str, labels: &Labels, read: Read) -> Result<()> {
        let kept = Kept::of(name, labels)?;
        let mut registry = lock(&self.registry);
        match registry.readers.get(name) {
            Some(readers) if readers.iter().any(|reader| reader.slot.kept == kept) => {
                return Err(Error::invalid(format!("{kept}: a gauge its function already reads")));
            }
            Some(_) => {}
            None => registry.claim(name, &[(name.to_owned(), Kind::Gauge)])?,
        }
        let written = vec![Arc::new(Written::of(kept.clone(), Kind::Gauge))];
        let slot = Arc::new(Slot::new(kept, written, Form::Gauge, 0));
        let reader = Arc::new(Reader { slot, read, said: Mutex::default() });
        registry.readers.entry(name.to_owned()).or_default().push(reader);
        Ok(())
    }

    /// Keeps what a name says of itself for the next write; a later call
    /// replaces what it gives.
    pub(super) fn describe(&self, name: &str, description: Told) {
        let mut described = lock(&self.described);
        let kept = described.entry(name.to_owned()).or_default();
        kept.unit = description.unit.or(kept.unit.take());
        kept.help = description.help.or(kept.help.take());
        kept.buckets = description.buckets.or(kept.buckets.take());
    }

    pub(super) fn take_descriptions(&self) -> BTreeMap<String, Told> {
        std::mem::take(&mut *lock(&self.described))
    }

    /// Gives back what a failed write took, under what was said since.
    pub(super) fn give_back_descriptions(&self, taken: BTreeMap<String, Told>) {
        let mut described = lock(&self.described);
        for (name, description) in taken {
            let newer = described.remove(&name).unwrap_or_default();
            let unit = newer.unit.or(description.unit);
            let help = newer.help.or(description.help);
            let buckets = newer.buckets.or(description.buckets);
            described.insert(name, Told { unit, help, buckets });
        }
    }

    /// A connection of its own for the gauges a client sets, which leave the
    /// totals when it does.
    #[cfg_attr(
        all(not(test), not(feature = "wire")),
        expect(dead_code, reason = "a client's connection comes over the wire")
    )]
    pub(super) fn connect(self: &Arc<Totals>) -> Connection {
        Connection { totals: Arc::clone(self), id: self.next_owner.fetch_add(1, Ordering::Relaxed) }
    }

    /// What the write at `now` writes of every slot: each live run's
    /// totals, a gauge's value, and the zero a run begins with. Runs a call
    /// began begin; those nothing was sent to for an hour end after it.
    ///
    /// A series no call reached before now is zero at now, written or not,
    /// so a run the next call begins begins with its zero here.
    pub(super) fn collect(&self, now: i64) -> Vec<Planned> {
        let (instruments, readers) = {
            let registry = lock(&self.registry);
            let instruments: Vec<Arc<Instrument>> = registry.instruments.values().cloned().collect();
            (instruments, registry.readers.values().flatten().cloned().collect::<Vec<_>>())
        };
        let zero = self.last_write.swap(now, Ordering::AcqRel);
        let mut planned = Vec::new();
        for reader in &readers {
            reader.read();
            planned.extend(gauge(&reader.slot));
        }
        for instrument in &instruments {
            let mut ended = Vec::new();
            for slot in instrument.slots() {
                let plan = match instrument.form {
                    Form::Gauge => gauge(&slot),
                    Form::Counter => counted(&slot, now, zero, &mut ended),
                    Form::Timer | Form::Histogram => measured(&slot, now, zero, &mut ended),
                };
                planned.extend(plan);
            }
            instrument.free(&ended);
        }
        planned
    }

    /// Settles a write: each slot's zero taken, or what refused it said
    /// once, or what a failed write took given back.
    pub(super) fn settle(&self, planned: Vec<Planned>, outcomes: Vec<Outcome>) {
        for (plan, outcome) in planned.into_iter().zip(outcomes) {
            let mut run = lock(&plan.slot.run);
            match outcome {
                Outcome::Written => {
                    run.zero = None;
                    run.refusal = None;
                    run.bins.written();
                }
                Outcome::Refused(error) => {
                    let why = error.to_string();
                    if run.refusal.as_ref() != Some(&why) {
                        let series = &plan.slot.kept;
                        tracing::warn!(target: "tinystore", %series, "metrics: a write refused it: {why}; said once");
                        run.refusal = Some(why);
                    }
                }
                Outcome::Failed => {
                    drop(run);
                    give_back(&plan);
                }
            }
        }
    }

    /// How many sets of labels the instrument of `name` holds.
    #[cfg(test)]
    pub(super) fn sets_held(&self, name: &str) -> usize {
        lock(&self.registry).instruments.get(name).map_or(0, |instrument| lock(&instrument.sets).by_labels.len())
    }

    /// Unsets the gauges `owner` set last: they are written no longer.
    #[cfg_attr(
        all(not(test), not(feature = "wire")),
        expect(dead_code, reason = "a client's connection comes over the wire")
    )]
    fn leave(&self, owner: u64) {
        let instruments: Vec<Arc<Instrument>> = lock(&self.registry).instruments.values().cloned().collect();
        for instrument in instruments.iter().filter(|instrument| instrument.form == Form::Gauge) {
            for slot in instrument.slots() {
                let _ = slot.owner.compare_exchange(owner, NOBODY, Ordering::AcqRel, Ordering::Acquire);
            }
        }
    }
}

impl Registry {
    /// Claims the names an instrument writes, each of which one instrument
    /// alone may write.
    fn claim(&mut self, name: &str, written: &[(String, Kind)]) -> Result<()> {
        if self.readers.contains_key(name) {
            return Err(Error::invalid("a gauge its function already reads"));
        }
        if let Some((series, writer)) =
            written.iter().find_map(|(series, _)| Some(series).zip(self.writers.get(series)))
        {
            return Err(Error::invalid(format!(
                "{series} is written by the instrument {writer}: a series has one writer"
            )));
        }
        for (series, _) in written {
            self.writers.insert(series.clone(), name.to_owned());
        }
        Ok(())
    }
}

/// A gauge's value, once a connection set it.
fn gauge(slot: &Arc<Slot>) -> Option<Planned> {
    if slot.owner.load(Ordering::Acquire) == NOBODY {
        return None;
    }
    let value = f64::from_bits(slot.pending.load(Ordering::Acquire));
    let values = vec![Value { written: Arc::clone(&slot.series[0]), zero: None, value }];
    Some(Planned { slot: Arc::clone(slot), values, longest: None })
}

/// A counter's run total: what calls added since the write before taken in,
/// a run begun by the first call after a write that found none.
fn counted(slot: &Arc<Slot>, now: i64, zero: i64, ended: &mut Vec<Arc<Slot>>) -> Option<Planned> {
    let added = f64::from_bits(slot.pending.swap(0.0_f64.to_bits(), Ordering::AcqRel));
    let sent = slot.sent.swap(false, Ordering::AcqRel) || added != 0.0;
    let mut run = lock(&slot.run);
    begin(&mut run, sent, now, zero);
    if !run.live {
        return None;
    }
    let total = run.total + added;
    if total.is_finite() {
        run.total = total;
    } else {
        slot.refuse("a counter's total past what a float holds");
    }
    let values = vec![Value { written: Arc::clone(&slot.series[0]), zero: run.zero, value: run.total }];
    end_if_idle(slot, &mut run, now, ended);
    Some(Planned { slot: Arc::clone(slot), values, longest: None })
}

/// A timer's or a histogram's run totals, and the longest since the write
/// before when it measured any.
fn measured(slot: &Arc<Slot>, now: i64, zero: i64, ended: &mut Vec<Arc<Slot>>) -> Option<Planned> {
    let taken = slot.measured.as_ref().map(|measured| lock(measured).take())?;
    let mut run = lock(&slot.run);
    begin(&mut run, taken.measured, now, zero);
    if !run.live {
        return None;
    }
    run.count += taken.count;
    run.sum += taken.sum;
    let buckets = taken.buckets.len().max(run.buckets.len());
    run.buckets.resize(buckets, 0);
    for (total, more) in run.buckets.iter_mut().zip(&taken.buckets) {
        *total += more;
    }
    let begins = run.zero;
    let series = |index: usize| Arc::clone(&slot.series[index]);
    let mut values = vec![
        Value { written: series(0), zero: begins, value: run.count as f64 },
        Value { written: series(1), zero: begins, value: run.sum },
    ];
    values.extend(taken.measured.then(|| Value { written: series(2), zero: None, value: taken.longest }));
    let mut cumulative = 0;
    for (bucket, count) in run.buckets.iter().enumerate() {
        cumulative += count;
        values.push(Value { written: series(3 + bucket), zero: begins, value: cumulative as f64 });
    }
    values.extend(run.bins.count(slot, &taken.bins, now, zero));
    end_if_idle(slot, &mut run, now, ended);
    Some(Planned { slot: Arc::clone(slot), values, longest: taken.measured.then_some(taken.longest) })
}

/// Begins a run at a call when none is live: its totals at zero, and its
/// zero written at the last write, when the series was known to be zero.
fn begin(run: &mut Run, sent: bool, now: i64, zero: i64) {
    if !sent {
        return;
    }
    run.active_at = now;
    if !run.live {
        *run = Run { live: true, zero: Some(zero), active_at: now, refusal: run.refusal.take(), ..Run::default() };
    }
}

/// Ends a run nothing was sent to for an hour, after this write; its slot is
/// freed unless a handle holds it.
fn end_if_idle(slot: &Arc<Slot>, run: &mut Run, now: i64, ended: &mut Vec<Arc<Slot>>) {
    if now.saturating_sub(run.active_at) >= IDLE {
        run.live = false;
        run.zero = None;
        ended.push(Arc::clone(slot));
    }
}

/// Adds `delta` to the float whose bits `cell` holds, unless the sum would
/// not be a finite number: a compare and swap, so that no call waits.
fn add_float(cell: &AtomicU64, delta: f64) -> bool {
    let mut bits = cell.load(Ordering::Acquire);
    loop {
        let sum = f64::from_bits(bits) + delta;
        if !sum.is_finite() {
            return false;
        }
        match cell.compare_exchange_weak(bits, sum.to_bits(), Ordering::AcqRel, Ordering::Acquire) {
            Ok(_) => return true,
            Err(now) => bits = now,
        }
    }
}

/// Gives a timer's longest back to its slot after a failed write.
fn give_back(plan: &Planned) {
    let (Some(longest), Some(measured)) = (plan.longest, &plan.slot.measured) else { return };
    lock(measured).longest_is_at_least(longest);
}

/// A client's own gauges: they leave the totals when it does.
#[cfg_attr(
    all(not(test), not(feature = "wire")),
    expect(dead_code, reason = "a client's connection comes over the wire")
)]
pub(super) struct Connection {
    totals: Arc<Totals>,
    pub(super) id: u64,
}

impl Drop for Connection {
    fn drop(&mut self) {
        self.totals.leave(self.id);
    }
}