tinystore 0.8.0

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
//! A logger as a `tracing` layer: each event is printed as it is logged and,
//! when a store's logger keeps it, handed to the store. An event's fields are
//! its fields, its spans' fields its context, outermost first, and a span's
//! `trace_id` and `span_id` its trace.
//!
//! ```text
//! tracing::info!(user = 42, "signed in")   →  11:02:11.123 INFO  api  signed in  user=42
//! ```
//!
//! A logger's levels are its own: a line under the level it keeps is not
//! kept, one under the level it prints not printed, and the subscriber's
//! other layers still see both, as their own filters say. Each place a line
//! goes takes the context of the spans its own level takes, so the console's
//! never changes what is kept.
//!
//! ```text
//! .level(Levels { store: Some(INFO), console: Some(DEBUG) }), in a debug span `step`
//! tracing::debug!(…)   printed with step=1, not kept
//! tracing::info!(…)    printed with step=1, kept without it
//! ```

use std::fmt;
use std::io::{IsTerminal, Write};
use std::sync::atomic::{AtomicI32, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::SystemTime;

use jiff::tz::TimeZone;
use serde::Serialize;
use tracing::field::{Field, Visit};
use tracing::span::{Attributes, Id, Record};
use tracing::{Event, Level, Subscriber};
use tracing_subscriber::layer::Context;
use tracing_subscriber::registry::{LookupSpan, Registry, Scope};

use super::Format;
#[cfg(all(feature = "records", feature = "config"))]
use super::env::Said;
use super::env::{Environment, colors, first_said, forced};
use super::line::{LOG, Line, Look, SOURCE, Time, json, object_pairs, pretty, quoted};
use super::redact::Redactor;
use crate::unix_nanos;

/// The target and the stream of the store's own lines, which a logger prints
/// from info up and never keeps, so that a line that fails to be kept is not
/// kept again.
const OWN: &str = "tinystore";
/// slog's number of info.
const INFO: i32 = 0;
/// slog's number of trace, below which `tracing` has no level.
const TRACE: i32 = -8;

/// What changes each field before it is hidden and kept: given its key and
/// its JSON, the value to keep, or none to drop the field.
pub type Replace = Arc<dyn Fn(&str, &str) -> Option<String> + Send + Sync>;

/// Where a store's logger keeps the lines its layer hands it.
pub(crate) trait Keep: Send + Sync {
    /// Holds a line for the store, never waiting: a line it has no room for
    /// is dropped and counted.
    fn keep(&self, line: Line);
    /// The store's time, in nanoseconds since 1970.
    fn now(&self) -> i64;
    /// Writes what it holds, and returns once it is written.
    fn flush(&self);
    /// The lines dropped since the logger began.
    fn dropped(&self) -> u64;
}

/// What a logger is told: the least level kept and printed, how and where
/// its lines print, what it hides, and which variables of the environment it
/// reads.
pub(crate) struct Told {
    pub(crate) level: Option<Level>,
    /// The least level printed when it is not `level`: a store's logger's alone.
    pub(crate) printed: Option<Level>,
    pub(crate) format: Option<Format>,
    pub(crate) time: Time,
    pub(crate) hide_stream: bool,
    pub(crate) to: Option<Box<dyn Write + Send>>,
    pub(crate) redact: Vec<String>,
    pub(crate) keep_url_passwords: bool,
    pub(crate) replace: Option<Replace>,
    pub(crate) source: bool,
    pub(crate) env: Option<Environment>,
}

impl Default for Told {
    fn default() -> Told {
        Told {
            level: None,
            printed: None,
            format: None,
            time: Time::Clock,
            hide_stream: false,
            to: None,
            redact: Vec::new(),
            keep_url_passwords: false,
            replace: None,
            source: false,
            env: Some(Environment::default()),
        }
    }
}

/// Where lines print, and how.
struct Printer {
    out: Mutex<Box<dyn Write + Send>>,
    pretty: bool,
    look: Look,
}

impl Printer {
    /// Prints a line whole, so that the lines of many threads never
    /// interleave; a console that refuses it loses that line, never what the
    /// store keeps.
    fn print(&self, line: &Line) {
        let text = if self.pretty { pretty(line, &self.look) } else { json(line) };
        let mut out = self.out.lock().unwrap_or_else(PoisonError::into_inner);
        let _ = out.write_all(text.as_bytes());
    }

    fn flush(&self) {
        let _ = self.out.lock().unwrap_or_else(PoisonError::into_inner).flush();
    }
}

/// What a logger does with a line before it is kept: whether its level is
/// wanted, its fields changed and hidden, and where and how it prints.
pub(crate) struct Console {
    stream: String,
    /// slog's number of the least level kept, which the config `log` changes
    /// while the logger runs; trace takes every level.
    kept: AtomicI32,
    /// slog's number of the least level printed, `LOG_CONSOLE_LEVEL`'s or the
    /// code's; none prints what is kept, and follows its changes.
    printed: Option<i32>,
    printer: Option<Printer>,
    redactor: Redactor,
    replace: Option<Replace>,
    source: bool,
    /// Events refused before they could be kept: no name, or fields that
    /// are no object.
    refused: AtomicU64,
    #[cfg(all(feature = "records", feature = "config"))]
    declared: Declared,
}

/// What a store's logger declares its config `log` with: the code's options
/// as its defaults, trace for a logger told no level, and the variables of
/// the environment it read, which go over them.
#[cfg(all(feature = "records", feature = "config"))]
#[derive(Clone, Debug, PartialEq)]
pub(crate) struct Declared {
    pub(crate) level: &'static str,
    /// The code's format, or the one its terminal chose.
    pub(crate) format: &'static str,
    pub(crate) time: &'static str,
    /// The variables' prefix and those that said what a logger can mean;
    /// none for a logger that reads no variable.
    pub(crate) env: Option<(String, Vec<(String, String)>)>,
}

impl Console {
    /// A logger's console, as the environment and then the code tell it; a
    /// variable that says what none can mean is said once.
    pub(crate) fn new(stream: &str, told: Told) -> Console {
        let said = told.env.as_ref().map(Environment::said).unwrap_or_default();
        let kept = said.level.or(told.level.map(number));
        let printed = said.printed.or(told.printed.map(number));
        // the environment never turns on a console the code turned off
        let format = if told.format == Some(Format::Off) { Some(Format::Off) } else { said.format.or(told.format) };
        // colours are the terminal's, whatever variables of its own a logger reads
        let lookup: fn(&str) -> Option<String> = told.env.as_ref().map_or(real, |env| env.lookup);
        let terminal = told.to.is_none() && std::io::stderr().is_terminal();
        // whether a console told no format prints pretty lines
        let chosen = terminal || forced(lookup);
        #[cfg(all(feature = "records", feature = "config"))]
        let declared = Declared::of(&told, &said, chosen);
        let printer = (format != Some(Format::Off)).then(|| {
            let pretty = format == Some(Format::Pretty) || format.is_none() && chosen;
            let look = Look {
                color: pretty && colors(terminal, lookup),
                zone: TimeZone::system(),
                time: said.time.unwrap_or(told.time),
                hide_stream: told.hide_stream,
            };
            let out = told.to.unwrap_or_else(|| Box::new(std::io::stderr()));
            Printer { out: Mutex::new(out), pretty, look }
        });
        let console = Console {
            stream: stream.to_owned(),
            kept: AtomicI32::new(kept.unwrap_or(TRACE)),
            printed,
            printer,
            redactor: Redactor::new(&told.redact, told.keep_url_passwords),
            replace: told.replace,
            source: told.source,
            refused: AtomicU64::new(0),
            #[cfg(all(feature = "records", feature = "config"))]
            declared,
        };
        console.say_ignored(said.ignored);
        console
    }

    /// Says each variable that said what none can mean, unless a logger said it before.
    fn say_ignored(&self, ignored: Vec<(String, String, &'static str)>) {
        for (name, value, expected) in ignored {
            if first_said(&name, &value) {
                self.say(&Line {
                    level: Some(4),
                    message: Some(format!("{name} is ignored")),
                    fields: vec![("value".to_owned(), quoted(&value)), ("expected".to_owned(), quoted(expected))],
                    ..own_line(unix_nanos(SystemTime::now()))
                });
            }
        }
    }

    /// Prints a line, whether it is kept or not.
    pub(crate) fn say(&self, line: &Line) {
        if let Some(printer) = &self.printer {
            printer.print(line);
        }
    }

    /// slog's number of the least level kept; none when every one is.
    fn kept(&self) -> Option<i32> {
        let least = self.kept.load(Ordering::Relaxed);
        (least > TRACE).then_some(least)
    }

    /// slog's number of the least level printed; none when every one is.
    fn printed(&self) -> Option<i32> {
        match self.printed {
            Some(least) => (least > TRACE).then_some(least),
            None => self.kept(),
        }
    }

    /// Takes the level the config `log` gives, a name of `LEVELS`, as the
    /// least kept of every line logged after, and printed unless the logger
    /// was given a level to print from.
    #[cfg(all(feature = "records", feature = "config"))]
    pub(crate) fn set_level(&self, name: &str) {
        if let Some(least) = super::env::level(name) {
            self.kept.store(least, Ordering::Relaxed);
        }
    }

    #[cfg(all(feature = "records", feature = "config"))]
    pub(crate) fn declared(&self) -> &Declared {
        &self.declared
    }

    /// Fields as they are kept: changed or dropped by `replace`, then hidden.
    fn fields(&self, mut fields: Vec<(String, String)>) -> Vec<(String, String)> {
        if let Some(replace) = &self.replace {
            let replaced = |(key, json): (String, String)| {
                let value = replace(&key, &json)?;
                // what is no JSON is kept as text
                let json =
                    if serde_json::from_str::<serde::de::IgnoredAny>(&value).is_ok() { value } else { quoted(&value) };
                Some((key, json))
            };
            fields = fields.into_iter().filter_map(replaced).collect();
        }
        self.redactor.fields(&mut fields);
        fields
    }
}

#[cfg(all(feature = "records", feature = "config"))]
impl Declared {
    /// What the code and the environment told a logger, `pretty` whether a
    /// console told no format prints pretty lines.
    fn of(told: &Told, said: &Said, pretty: bool) -> Declared {
        use super::env::{FORMATS, LEVELS, TIMES, spelled};
        let format = told.format.unwrap_or(if pretty { Format::Pretty } else { Format::Json });
        let console_off = told.format == Some(Format::Off);
        Declared {
            level: told.level.and_then(|level| spelled(&LEVELS, number(level))).unwrap_or("trace"),
            format: spelled(&FORMATS, format).unwrap_or("json"),
            time: spelled(&TIMES, told.time).unwrap_or("clock"),
            env: told.env.as_ref().map(|env| env.as_config(said, console_off)),
        }
    }
}

/// A line of the store's own at `at`, which a logger prints and never keeps.
pub(crate) fn own_line(at: i64) -> Line {
    Line { at, stream: OWN.to_owned(), name: LOG.to_owned(), ..Line::default() }
}

pub(super) fn real(name: &str) -> Option<String> {
    std::env::var(name).ok()
}

/// A logger's layer: what `tracing` hands it is printed, and kept by a
/// store's logger. A clone is the same logger, for `flush` and `dropped` once
/// the subscriber holds the layer.
#[derive(Clone)]
pub struct Layer {
    console: Arc<Console>,
    keep: Option<Arc<dyn Keep>>,
    /// The config `log` a store's logger follows, whose watch sets its
    /// level, held while any clone of the logger is.
    #[cfg(all(feature = "records", feature = "config"))]
    #[expect(dead_code, reason = "held for its drop, which ends the watch")]
    following: Option<Arc<dyn std::any::Any + Send + Sync>>,
}

impl fmt::Debug for Layer {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Layer")
            .field("stream", &self.console.stream)
            .field("kept", &self.console.kept())
            .field("printed", &self.console.printed())
            .finish()
    }
}

/// Where a line goes: printed, kept, both or neither.
#[derive(Clone, Copy)]
struct To {
    print: bool,
    keep: bool,
}

impl Layer {
    pub(crate) fn new(console: Arc<Console>, keep: Option<Arc<dyn Keep>>) -> Layer {
        Layer {
            console,
            keep,
            #[cfg(all(feature = "records", feature = "config"))]
            following: None,
        }
    }

    /// The layer holding what keeps its console's level the config's.
    #[cfg(all(feature = "records", feature = "config"))]
    pub(crate) fn following(self, following: Arc<dyn std::any::Any + Send + Sync>) -> Layer {
        Layer { following: Some(following), ..self }
    }

    /// Writes what the logger holds and returns once it is written, as the
    /// store does every second and when it closes; then flushes the console.
    pub fn flush(&self) {
        if let Some(keep) = &self.keep {
            keep.flush();
        }
        if let Some(printer) = &self.console.printer {
            printer.flush();
        }
    }

    /// The lines dropped since the logger began: a full buffer, a line the
    /// file refused, an event without a name or whose fields are no object.
    pub fn dropped(&self) -> u64 {
        self.console.refused.load(Ordering::Relaxed) + self.keep.as_ref().map_or(0, |keep| keep.dropped())
    }

    /// Writes an event named `name` with `fields`, a struct or a map, and
    /// neither a level nor a message, as a line is written: at once, and
    /// dropped under load. Its context is the current span's.
    pub fn event(&self, name: &str, fields: &impl Serialize) {
        let pairs = serde_json::to_string(fields).ok().and_then(|object| object_pairs(&object).ok());
        let Some(pairs) = pairs.filter(|_| !name.is_empty()) else {
            self.console.refused.fetch_add(1, Ordering::Relaxed);
            return;
        };
        // an event has no level, and goes wherever the logger has a place
        let to = To { print: self.console.printer.is_some(), keep: self.keep.is_some() };
        if !to.print && !to.keep {
            return;
        }
        let line = Line {
            at: self.now(),
            stream: self.console.stream.clone(),
            name: name.to_owned(),
            fields: pairs,
            ..Line::default()
        };
        let spans = |least| {
            let current = tracing::Span::current().with_subscriber(|(id, dispatch)| {
                let span = dispatch.downcast_ref::<Registry>()?.span(id)?;
                Some(spanned(span.scope(), least))
            });
            current.flatten().unwrap_or_default()
        };
        self.write(line, to, spans);
    }

    fn now(&self) -> i64 {
        self.keep.as_ref().map_or_else(|| unix_nanos(SystemTime::now()), |keep| keep.now())
    }

    /// Where a line of `level` goes: printed from the level printed, and
    /// kept from the level kept unless it is the store's own.
    fn to(&self, level: i32, own: bool) -> To {
        let printed = self.console.printed();
        // the store's own lines print from info up unless the logger was given a level to print from
        let shown = if own && printed.is_none() { level >= INFO } else { printed.is_none_or(|least| level >= least) };
        let kept = !own && self.console.kept().is_none_or(|least| level >= least);
        To { print: shown && self.console.printer.is_some(), keep: kept && self.keep.is_some() }
    }

    /// Prints and keeps a line as `to` says, its fields changed and hidden,
    /// and its context what `spans` gives of the spans each place's level
    /// takes: a kept line never carries a span only the console takes.
    fn write(&self, mut line: Line, to: To, spans: impl Fn(Option<i32>) -> Spanned) {
        line.fields = self.console.fields(std::mem::take(&mut line.fields));
        let (printed, kept) = (self.console.printed(), self.console.kept());
        if to.print && to.keep && printed != kept {
            let mut shown = line.clone();
            self.add_scope(&mut shown, spans(printed));
            self.console.say(&shown);
            self.add_scope(&mut line, spans(kept));
            self.keep(line);
            return;
        }
        self.add_scope(&mut line, spans(if to.print { printed } else { kept }));
        if to.print {
            self.console.say(&line);
        }
        if to.keep {
            self.keep(line);
        }
    }

    /// Gives a line its spans' context, changed and hidden, and their trace
    /// where the line has none of its own.
    fn add_scope(&self, line: &mut Line, spanned: Spanned) {
        line.context = once_each(self.console.fields(spanned.fields));
        line.trace = line.trace.or(spanned.trace);
        line.span = line.span.or(spanned.span);
    }

    fn keep(&self, line: Line) {
        if let Some(keep) = &self.keep {
            keep.keep(line);
        }
    }

    /// Which of the subscriber's layers of this kind records a span's fields:
    /// the first to see it, so that two loggers never record a field twice.
    fn recorder(&self) -> usize {
        Arc::as_ptr(&self.console).addr()
    }
}

/// slog's number of a level: trace below debug, as Python's levels map.
fn number(level: Level) -> i32 {
    match level {
        Level::TRACE => -8,
        Level::DEBUG => -4,
        Level::INFO => 0,
        Level::WARN => 4,
        Level::ERROR => 8,
    }
}

/// A span's fields as a logger keeps them, and the trace it carries.
#[derive(Default)]
struct Spanned {
    recorder: usize,
    fields: Vec<(String, String)>,
    trace: Option<[u8; 16]>,
    span: Option<[u8; 8]>,
}

/// The fields of the spans a line was logged in, from the outermost, and the
/// innermost trace: a span under `least` gives none, and none takes every one.
fn spanned<'a, R: LookupSpan<'a>>(scope: Scope<'a, R>, least: Option<i32>) -> Spanned {
    let mut scoped = Spanned::default();
    for span in scope.from_root() {
        if least.is_some_and(|least| number(*span.metadata().level()) < least) {
            continue;
        }
        if let Some(spanned) = span.extensions().get::<Spanned>() {
            scoped.fields.extend(spanned.fields.iter().cloned());
            scoped.trace = spanned.trace.or(scoped.trace);
            scoped.span = spanned.span.or(scoped.span);
        }
    }
    scoped
}

/// A context with each key once, where it was first given and holding the
/// value given last: a span inside another replaces the outer one's key, as
/// a nested `with` does in every SDK, so that the line printed, the event
/// kept and a filter by the key agree on one value.
///
/// ```text
/// component=http user=7, then component=access  →  component=access user=7
/// ```
fn once_each(fields: Vec<(String, String)>) -> Vec<(String, String)> {
    let mut once: Vec<(String, String)> = Vec::with_capacity(fields.len());
    for (key, json) in fields {
        match once.iter_mut().find(|(held, _)| *held == key) {
            Some((_, value)) => *value = json,
            None => once.push((key, json)),
        }
    }
    once
}

impl<S> tracing_subscriber::Layer<S> for Layer
where
    S: Subscriber + for<'a> LookupSpan<'a>,
{
    fn on_new_span(&self, attributes: &Attributes<'_>, id: &Id, context: Context<'_, S>) {
        let Some(span) = context.span(id) else { return };
        let mut extensions = span.extensions_mut();
        if extensions.get_mut::<Spanned>().is_some() {
            return;
        }
        let mut spanned = Spanned { recorder: self.recorder(), ..Spanned::default() };
        attributes.record(&mut Fields { into: &mut spanned, message: None });
        extensions.insert(spanned);
    }

    fn on_record(&self, id: &Id, values: &Record<'_>, context: Context<'_, S>) {
        let Some(span) = context.span(id) else { return };
        let mut extensions = span.extensions_mut();
        if let Some(spanned) = extensions.get_mut::<Spanned>()
            && spanned.recorder == self.recorder()
        {
            values.record(&mut Fields { into: spanned, message: None });
        }
    }

    fn on_event(&self, event: &Event<'_>, context: Context<'_, S>) {
        let metadata = event.metadata();
        let (level, own) = (number(*metadata.level()), metadata.target() == OWN);
        let to = self.to(level, own);
        if !to.print && !to.keep {
            return;
        }
        let (mut called, mut message) = (Spanned::default(), None);
        event.record(&mut Fields { into: &mut called, message: Some(&mut message) });
        let mut line = Line {
            at: self.now(),
            stream: if own { OWN.to_owned() } else { self.console.stream.clone() },
            name: LOG.to_owned(),
            level: Some(level),
            message: Some(message.unwrap_or_default()),
            trace: called.trace,
            span: called.span,
            ..Line::default()
        };
        if self.console.source
            && let (Some(file), Some(number)) = (metadata.file(), metadata.line())
        {
            let function = metadata.module_path().unwrap_or_default();
            let spelled = serde_json::json!({ "function": function, "file": file, "line": number }).to_string();
            called.fields.push((SOURCE.to_owned(), spelled));
        }
        line.fields = called.fields;
        let spans = |least| context.event_scope(event).map(|scope| spanned(scope, least)).unwrap_or_default();
        self.write(line, to, spans);
    }
}

/// What a `tracing` event or span gives: each field's JSON as Go's and
/// Bun's loggers spell it, and an event's message apart.
struct Fields<'a> {
    into: &'a mut Spanned,
    message: Option<&'a mut Option<String>>,
}

impl Fields<'_> {
    fn add(&mut self, field: &Field, json: String) {
        self.into.fields.push((field.name().to_owned(), json));
    }

    fn text(&mut self, field: &Field, text: &str) {
        let name = field.name();
        if name == "message"
            && let Some(message) = self.message.as_mut()
        {
            **message = Some(text.to_owned());
        } else if name == "trace_id"
            && let Some(trace) = from_hex(text)
        {
            self.into.trace = Some(trace);
        } else if name == "span_id"
            && let Some(span) = from_hex(text)
        {
            self.into.span = Some(span);
        } else {
            self.add(field, quoted(text));
        }
    }
}

impl Visit for Fields<'_> {
    fn record_str(&mut self, field: &Field, value: &str) {
        self.text(field, value);
    }

    fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
        self.text(field, &format!("{value:?}"));
    }

    fn record_error(&mut self, field: &Field, value: &(dyn std::error::Error + 'static)) {
        self.text(field, &value.to_string());
    }

    fn record_i64(&mut self, field: &Field, value: i64) {
        self.add(field, value.to_string());
    }

    fn record_u64(&mut self, field: &Field, value: u64) {
        self.add(field, value.to_string());
    }

    fn record_i128(&mut self, field: &Field, value: i128) {
        self.add(field, value.to_string());
    }

    fn record_u128(&mut self, field: &Field, value: u128) {
        self.add(field, value.to_string());
    }

    fn record_bool(&mut self, field: &Field, value: bool) {
        self.add(field, value.to_string());
    }

    fn record_f64(&mut self, field: &Field, value: f64) {
        self.add(field, float(value));
    }
}

/// A float as Go's loggers write one, strconv's shortest `'g'`: the fewest
/// digits that read back as it, in an exponent's form below 1e-4 and from
/// 1e+06; NaN and the infinities, which JSON has no number for, as their
/// names' strings.
///
/// ```text
/// 0.5 → 0.5    1234567 → 1.234567e+06    0.00001 → 1e-05    NaN → "NaN"
/// ```
pub(crate) fn float(value: f64) -> String {
    if value.is_nan() {
        return quoted("NaN");
    }
    if value.is_infinite() {
        return quoted(if value > 0.0 { "+Inf" } else { "-Inf" });
    }
    let scientific = format!("{value:e}");
    let (mantissa, exponent) = scientific.split_once('e').unwrap_or((&scientific, "0"));
    let exponent: i32 = exponent.parse().unwrap_or(0);
    if value != 0.0 && !(-4..6).contains(&exponent) {
        let sign = if exponent < 0 { '-' } else { '+' };
        return format!("{mantissa}e{sign}{:02}", exponent.abs());
    }
    format!("{value}")
}

/// Hex of `N` bytes, the case ignored; all zeros is none, as OpenTelemetry
/// reads an id.
fn from_hex<const N: usize>(text: &str) -> Option<[u8; N]> {
    // `from_str_radix` takes a leading `+`, which is no hex digit of an id.
    if text.len() != 2 * N || !text.bytes().all(|byte| byte.is_ascii_hexdigit()) {
        return None;
    }
    let bytes: Option<Vec<u8>> = (0..N).map(|at| u8::from_str_radix(text.get(2 * at..2 * at + 2)?, 16).ok()).collect();
    bytes?.try_into().ok().filter(|bytes: &[u8; N]| bytes.iter().any(|byte| *byte != 0))
}

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