redup-bootstrap 0.1.1

Ядро платформы: инстанс службы, модули, жизненный цикл, здоровье и телеметрия.
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
//! Проверки журнала: эталон строки JSON, экранирование, человекочитаемая строка, отбор по уровню,
//! формат, контекст запроса, захват и перехватчик паники.

#![allow(clippy::unwrap_used, clippy::expect_used)]

use std::error::Error as StdError;
use std::fmt;
use std::path::Path;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;

use redup_config::{Source, load};
use serde_json::Value;
use time::Month;
use time::OffsetDateTime;
use tracing_subscriber::layer::SubscriberExt;

use super::Clock;
use super::Journal;
use super::Logging;
use super::Output;
use super::set_panic_hook;
use crate::telemetry::journal::fatal;
use crate::telemetry::level::Level;
use crate::telemetry::logs_config::LogsConfig;
use crate::telemetry::service::Service;
use crate::telemetry::template::Template;

/// Постоянные имена полей строки: свойства с такими именами не повторяются наверху.
const FIXED_NAMES: [&str; 9] = [
    "timestamp",
    "Level",
    "Logger",
    "Message",
    "CorrelationId",
    "Exception",
    "Service",
    "EventProperties",
    "LogFormatVersion",
];

/// Идентификатор корреляции из эталона.
const CORRELATION: &str = "6f107bf6-289b-4421-acee-40e1b9f5b4c9";
/// Идентификатор трассировки для проверки контекста.
const TRACE_ID: &str = "4bf92f3577b34da6a3ce929d0e0e4736";
/// Идентификатор отрезка для проверки контекста.
const SPAN_ID: &str = "00f067aa0ba902b7";

/// Момент первой строки эталона.
fn reference_first() -> OffsetDateTime {
    moment(2026, 11, 28, 20, 10, 2, 490)
}

/// Момент последней строки эталона.
fn reference_last() -> OffsetDateTime {
    moment(2026, 11, 28, 20, 10, 3, 107)
}

/// Момент по частям.
fn moment(
    year: i32,
    month: u8,
    day: u8,
    hour: u8,
    minute: u8,
    second: u8,
    millisecond: u16,
) -> OffsetDateTime {
    let month = Month::try_from(month).expect("a month");
    let date = time::Date::from_calendar_date(year, month, day).expect("a date");
    let time = time::Time::from_hms_milli(hour, minute, second, millisecond).expect("a time");
    OffsetDateTime::new_utc(date, time)
}

/// Часы, застывшие в одном моменте.
fn clock_at(moment: OffsetDateTime) -> Clock {
    Arc::new(move || moment)
}

/// Уровень в имени для конфигурации.
fn level_name(level: Level) -> &'static str {
    match level {
        Level::Trace => "trace",
        Level::Debug => "debug",
        Level::Info => "info",
        Level::Warn => "warn",
        Level::Error => "error",
        Level::Fatal => "fatal",
        Level::Off => "off",
    }
}

/// Формат в имени для конфигурации.
fn template_name(template: Template) -> &'static str {
    match template {
        Template::Auto => "auto",
        Template::Human => "human",
        Template::Json => "json",
    }
}

/// Конфигурация с заданными уровнем и форматом: читается из файла, как в службе.
fn config(level: Level, template: Template) -> LogsConfig {
    let directory = tempfile::tempdir().expect("a temporary directory");
    let text = format!(
        "logs:\n  level: {}\n  template: {}\n",
        level_name(level),
        template_name(template)
    );
    std::fs::write(directory.path().join("config.yaml"), text).expect("the configuration file");
    load::<LogsConfig>(&Source::directory(directory.path()))
        .expect("the configuration is accepted")
        .value
}

/// Журнал с выводом в буфер и застывшими часами.
fn buffered(config: LogsConfig, moment: OffsetDateTime) -> (Journal, Arc<Mutex<Vec<u8>>>) {
    let buffer = Arc::new(Mutex::new(Vec::new()));
    let journal = Journal::new(
        config,
        Service::new("trial", "1.0.0"),
        Output::Buffer(Arc::clone(&buffer)),
        clock_at(moment),
    );
    (journal, buffer)
}

/// Выполняет тело при журнале как подписчике потока.
fn install<T>(journal: &Journal, body: impl FnOnce() -> T) -> T {
    let subscriber = tracing_subscriber::registry().with(journal.clone());
    tracing::subscriber::with_default(subscriber, body)
}

/// Ручка журнала.
fn handle(journal: &Journal) -> Logging {
    journal.handle()
}

/// Строки буфера.
fn lines(buffer: &Mutex<Vec<u8>>) -> Vec<String> {
    let bytes = buffer.lock().expect("the output buffer is not poisoned");
    std::str::from_utf8(&bytes)
        .expect("the output is UTF-8")
        .lines()
        .map(str::to_owned)
        .collect()
}

/// Разобранная строка.
fn parse(line: &str) -> Value {
    serde_json::from_str(line).expect("a JSON line is valid")
}

/// Разобранные строки эталона. В крейте платформы эталон лежит в `lib/contracts`, здесь — копия.
fn reference() -> Vec<Value> {
    let manifest = env!("CARGO_MANIFEST_DIR");
    let candidates = [
        format!("{manifest}/../../contracts/log/json-lines.jsonl"),
        format!("{manifest}/contracts/log/json-lines.jsonl"),
    ];
    let path = candidates
        .iter()
        .find(|path| Path::new(path).is_file())
        .expect("the reference file of JSON lines");
    std::fs::read_to_string(path)
        .expect("the reference is readable")
        .lines()
        .map(|line| serde_json::from_str(line).expect("a reference line is valid"))
        .collect()
}

/// Ключи объекта.
fn keys_of(value: &Value) -> Vec<String> {
    value
        .as_object()
        .expect("an object")
        .keys()
        .cloned()
        .collect()
}

/// Ключи объектов совпадают как наборы.
fn assert_same_keys(actual: &Value, expected: &Value, what: &str) {
    let mut actual = keys_of(actual);
    let mut expected = keys_of(expected);
    actual.sort();
    expected.sort();
    assert_eq!(actual, expected, "{what}");
}

/// Метка времени в формате `YYYY-MM-DDTHH:MM:SS.mmmZ`.
fn looks_like_timestamp(text: &str) -> bool {
    let characters: Vec<char> = text.chars().collect();
    let separators = [4, 7, 10, 13, 16, 19, 23];
    let signs = ['-', '-', 'T', ':', ':', '.', 'Z'];
    characters.len() == 24
        && separators
            .iter()
            .zip(signs)
            .all(|(position, sign)| characters[*position] == sign)
        && (0..24)
            .filter(|position| !separators.contains(position))
            .all(|position| characters[position].is_ascii_digit())
}

/// Сверяет нашу строку с эталонной по разбору: набор ключей верхнего уровня, постоянные поля,
/// метка времени, `Service`, `EventProperties` и повторяющиеся поля.
fn assert_matches_reference(actual_line: &str, expected: &Value) {
    let actual = parse(actual_line);
    assert_same_keys(&actual, expected, "top-level keys");
    for field in ["Level", "LogFormatVersion"] {
        assert_eq!(&actual[field], &expected[field], "field {field}");
    }
    let actual_timestamp = actual["timestamp"].as_str().expect("a timestamp string");
    assert_eq!(
        actual_timestamp, expected["timestamp"],
        "the timestamp value"
    );
    assert!(
        looks_like_timestamp(actual_timestamp),
        "the timestamp format"
    );
    assert_same_keys(&actual["Service"], &expected["Service"], "Service keys");
    assert_eq!(actual["Service"]["Name"], "trial");
    assert_eq!(actual["Service"]["Version"], "1.0.0");
    assert_same_keys(
        &actual["EventProperties"],
        &expected["EventProperties"],
        "EventProperties keys",
    );
    for key in keys_of(&expected["EventProperties"]) {
        assert_eq!(
            &actual["EventProperties"][&key], &expected["EventProperties"][&key],
            "the property {key}"
        );
    }
    for key in keys_of(&expected["EventProperties"]) {
        if FIXED_NAMES.contains(&key.as_str()) {
            continue;
        }
        assert_eq!(
            &actual[&key], &expected["EventProperties"][&key],
            "the repeated property {key}"
        );
    }
    if expected.get("CorrelationId").is_some() {
        assert_eq!(&actual["CorrelationId"], &expected["CorrelationId"]);
    }
}

/// Фрагменты идут в строке именно в этом порядке.
fn assert_raw_order(line: &str, needles: &[&str]) {
    let mut position = 0;
    for needle in needles {
        let found = line[position..].find(needle);
        assert!(
            found.is_some(),
            "the fragment {needle} is missing or out of order"
        );
        position += found.expect("checked above") + needle.len();
    }
}

/// Ошибка проверки: без причин.
#[derive(Debug)]
struct Unavailable;

impl fmt::Display for Unavailable {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Storage is unavailable")
    }
}

impl StdError for Unavailable {}

/// Ошибка проверки: с одной причиной.
#[derive(Debug)]
struct PackError;

impl fmt::Display for PackError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Document body is corrupt")
    }
}

impl StdError for PackError {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        Some(&DecodeError)
    }
}

/// Причина ошибки проверки.
#[derive(Debug)]
struct DecodeError;

impl fmt::Display for DecodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Unexpected end of input")
    }
}

impl StdError for DecodeError {}

/// Стек из эталона: одна строка кадра.
const STACK: &str = "   0: trial::worker::start\n             at ./src/worker.rs:42:9";

/// Ошибка проверки: сосед не готов — текст пробы зависимости.
#[derive(Debug)]
struct NotReady;

impl fmt::Display for NotReady {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("neighbor replied that it is not ready")
    }
}

impl StdError for NotReady {}

/// Ошибка проверки: запись о панике — тип `Panic`, текст с местом.
struct PanicFailure;

impl fmt::Debug for PanicFailure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Panic")
    }
}

impl fmt::Display for PanicFailure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("boom at src/main.rs:10:5")
    }
}

impl StdError for PanicFailure {}

#[test]
fn reference_line_module_started_is_reproduced() {
    let samples = reference();
    let (journal, buffer) = buffered(config(Level::Info, Template::Json), reference_first());
    install(&journal, || {
        tracing::info!(
            target: "redup_bootstrap::instance",
            module = "Storage",
            "module started"
        );
    });
    let lines = lines(&buffer);
    assert_eq!(lines.len(), 1);
    assert_matches_reference(&lines[0], &samples[0]);
}

#[test]
fn reference_line_request_handled_is_reproduced() {
    let samples = reference();
    let (journal, buffer) = buffered(
        config(Level::Debug, Template::Json),
        moment(2026, 11, 28, 20, 10, 2, 500),
    );
    install(&journal, || {
        let span = tracing::info_span!(
            "request",
            correlation_id = CORRELATION,
            trace_id = TRACE_ID,
            span_id = SPAN_ID
        );
        let _entered = span.enter();
        tracing::debug!(
            target: "redup_bootstrap::routes",
            status = 200_i64,
            elapsed_ms = 5_i64,
            "request handled"
        );
    });
    let lines = lines(&buffer);
    assert_eq!(lines.len(), 1);
    assert_matches_reference(&lines[0], &samples[1]);
}

#[test]
fn reference_line_dependency_failure_is_reproduced() {
    let samples = reference();
    let (journal, buffer) = buffered(
        config(Level::Info, Template::Json),
        moment(2026, 11, 28, 20, 10, 3, 104),
    );
    install(&journal, || {
        let not_ready: &(dyn StdError + 'static) = &NotReady;
        tracing::warn!(
            target: "redup_bootstrap::dependency::runner",
            module = "Worker",
            dependency = "neighbour",
            error = not_ready,
            "dependency probe trial failed"
        );
    });
    let lines = lines(&buffer);
    assert_eq!(lines.len(), 1);
    assert_matches_reference(&lines[0], &samples[2]);
    let actual = parse(&lines[0]);
    // Текстовая ошибка даёт тип `Error` и текст, без стека и причин.
    assert_same_keys(
        &actual["Exception"],
        &samples[2]["Exception"],
        "Exception keys",
    );
    assert_eq!(
        actual["Exception"]["Message"],
        samples[2]["Exception"]["Message"]
    );
}

#[test]
fn reference_line_panic_is_reproduced() {
    let samples = reference();
    let (journal, buffer) = buffered(config(Level::Info, Template::Json), reference_last());
    install(&journal, || {
        let panic: &(dyn StdError + 'static) = &PanicFailure;
        tracing::error!(
            target: "redup_bootstrap::telemetry::journal::panic_hook",
            thread = "main",
            error = panic,
            exception_stack = STACK,
            "panic"
        );
    });
    let lines = lines(&buffer);
    assert_eq!(lines.len(), 1);
    assert_matches_reference(&lines[0], &samples[3]);
    let actual = parse(&lines[0]);
    // Стек проходит без изменений, текст ошибки совпадает с эталонным.
    assert_eq!(
        actual["Exception"]["StackTrace"],
        samples[3]["Exception"]["StackTrace"]
    );
    assert_eq!(
        actual["Exception"]["Message"],
        samples[3]["Exception"]["Message"]
    );
}

#[test]
fn escaped_characters_pass_through_json() {
    let (journal, buffer) = buffered(config(Level::Info, Template::Json), reference_first());
    let payload = "quote\"back\\slash\nnew\ttab\u{1f}кириллица-🦀";
    install(&journal, || {
        tracing::info!(
            target: "trial",
            payload = payload,
            displayed = %payload,
            whole = -5_i64,
            natural = 12_i64,
            fraction = 2.25_f64,
            flag = true,
            off = false,
            "Message with \"quote\" and\nnewline"
        );
    });
    let value = parse(&lines(&buffer)[0]);
    assert_eq!(value["Message"], "Message with \"quote\" and\nnewline");
    assert_eq!(value["EventProperties"]["payload"], payload);
    assert_eq!(value["EventProperties"]["displayed"], payload);
    assert_eq!(value["EventProperties"]["whole"], -5);
    assert_eq!(value["EventProperties"]["natural"], 12);
    assert_eq!(value["EventProperties"]["fraction"], 2.25);
    assert_eq!(value["EventProperties"]["flag"], true);
    assert_eq!(value["EventProperties"]["off"], false);
}

#[test]
fn properties_keep_record_order() {
    let (journal, buffer) = buffered(config(Level::Info, Template::Json), reference_first());
    install(&journal, || {
        tracing::info!(
            target: "trial",
            zeta = 1_i64,
            alpha = 2_i64,
            middle = 3_i64,
            "Order kept"
        );
    });
    let line = &lines(&buffer)[0];
    assert_raw_order(line, &["\"zeta\":1", "\"alpha\":2", "\"middle\":3"]);
    let after_fixed = line
        .split("\"LogFormatVersion\":\"1.0\"")
        .nth(1)
        .expect("the version marker");
    assert_raw_order(after_fixed, &["\"zeta\":1", "\"alpha\":2", "\"middle\":3"]);
}

#[test]
fn human_line_without_correlation_quotes_spaced_values() {
    let (journal, buffer) = buffered(config(Level::Info, Template::Human), reference_first());
    install(&journal, || {
        tracing::info!(
            target: "redup_bootstrap::instance",
            Endpoint = "0.0.0.0:4200",
            reason = "PACK FAILED",
            "Instance started"
        );
    });
    let expected = format!(
        "2026-11-28T20:10:02.490Z INFO{}Instance started Endpoint=0.0.0.0:4200 reason=\"PACK FAILED\"",
        " ".repeat(10)
    );
    assert_eq!(lines(&buffer), vec![expected]);
}

#[test]
fn human_line_with_correlation_error_causes_and_stack() {
    let (journal, buffer) = buffered(config(Level::Info, Template::Human), reference_last());
    install(&journal, || {
        let span = tracing::info_span!("request", correlation_id = CORRELATION);
        let _entered = span.enter();
        let pack: &(dyn StdError + 'static) = &PackError;
        tracing::error!(
            target: "redup_bootstrap::grpc::server",
            grpcCode = "Internal",
            error = pack,
            exception_stack = "   0: trial::module::pack\n   1: server::serve",
            "Request failed, error returned to client"
        );
    });
    assert_eq!(
        lines(&buffer),
        vec![
            "2026-11-28T20:10:03.107Z ERROR  6f107b Request failed, error returned to client grpcCode=Internal",
            "EXCEPTION OCCURRED: PackError: Document body is corrupt",
            "  Caused by: DecodeError: Unexpected end of input",
            "     0: trial::module::pack",
            "     1: server::serve",
        ]
    );
}

#[test]
fn human_line_with_text_error() {
    let (journal, buffer) = buffered(config(Level::Info, Template::Human), reference_last());
    install(&journal, || {
        let unavailable = Unavailable;
        tracing::warn!(target: "trial", error = %unavailable, "Outgoing request failed");
    });
    assert_eq!(
        lines(&buffer),
        vec![
            "2026-11-28T20:10:03.107Z WARN          Outgoing request failed",
            "EXCEPTION OCCURRED: Error: Storage is unavailable",
        ]
    );
}

#[test]
fn level_boundary_gates_events() {
    let (journal, buffer) = buffered(config(Level::Info, Template::Json), reference_first());
    let handle = handle(&journal);
    assert_eq!(handle.level(), Level::Info);
    // По умолчанию `Info` Debug и Trace отсекает.
    install(&journal, || {
        tracing::trace!(target: "trial", "Too detailed");
        tracing::debug!(target: "trial", "Diagnostic");
        tracing::info!(target: "trial", "Notable");
    });
    assert_eq!(lines(&buffer).len(), 1);
    // Смена уровня включит подробные события сразу.
    handle.set_level(Level::Trace);
    assert_eq!(handle.level(), Level::Trace);
    install(&journal, || {
        tracing::trace!(target: "trial", "Now visible");
        tracing::debug!(target: "trial", "Also visible");
    });
    assert_eq!(lines(&buffer).len(), 3);
    // `Off` не пропускает ничего.
    handle.set_level(Level::Off);
    install(&journal, || {
        tracing::error!(target: "trial", "Hidden");
        fatal!(target: "trial", "Hidden fatal");
    });
    assert_eq!(lines(&buffer).len(), 3);
    // `Fatal` пропускает только события с маркером; маркер наружу не выходит.
    handle.set_level(Level::Fatal);
    install(&journal, || {
        tracing::error!(target: "trial", "Regular error stays hidden");
        fatal!(target: "trial", reason = "OUT_OF_MEMORY", "Out of memory");
    });
    let lines = lines(&buffer);
    assert_eq!(lines.len(), 4);
    let value = parse(&lines[3]);
    assert_eq!(value["Level"], "Fatal");
    assert_eq!(value["Message"], "Out of memory");
    assert_eq!(value["EventProperties"]["reason"], "OUT_OF_MEMORY");
    assert!(!lines[3].contains("fatal"));
}

#[test]
fn template_selection_is_immediate() {
    // `Auto` вне кластера — читаемая строка.
    let (journal, buffer) = buffered(config(Level::Info, Template::Auto), reference_first());
    let handle = handle(&journal);
    assert_eq!(handle.template(), Template::Auto);
    install(&journal, || {
        tracing::info!(target: "trial", "Auto line");
    });
    let auto_is_json = Template::Auto.resolved() == Template::Json;
    assert_eq!(lines(&buffer)[0].starts_with('{'), auto_is_json);
    // Смена формата действует на следующее событие.
    handle.set_template(Template::Json);
    assert_eq!(handle.template(), Template::Json);
    install(&journal, || {
        tracing::info!(target: "trial", "Json line");
    });
    let switched = parse(&lines(&buffer)[1]);
    assert_eq!(switched["Message"], "Json line");
    // Смена обратно: `Auto` раскрывается в момент смены, ручка возвращает формат как задан.
    handle.set_template(Template::Auto);
    assert_eq!(handle.template(), Template::Auto);
    // `Json` в конфигурации — сразу JSON.
    let (journal, buffer) = buffered(config(Level::Info, Template::Json), reference_first());
    install(&journal, || {
        tracing::info!(target: "trial", "Immediate");
    });
    let immediate = parse(&lines(&buffer)[0]);
    assert_eq!(immediate["Message"], "Immediate");
}

#[test]
fn request_context_comes_from_spans() {
    let (journal, buffer) = buffered(config(Level::Info, Template::Json), reference_first());
    install(&journal, || {
        // Вне спана идентификаторов нет.
        tracing::info!(target: "trial", alpha = 1_i64, "Outside request");
        // Спан со всеми тремя полями.
        let span = tracing::info_span!(
            "request",
            correlation_id = CORRELATION,
            trace_id = TRACE_ID,
            span_id = SPAN_ID
        );
        {
            let _entered = span.enter();
            tracing::info!(target: "trial", beta = 2_i64, "Inside request");
        }
        // Вложенный спан без полей берёт данные из охватывающего.
        {
            let _entered = span.enter();
            let child = tracing::info_span!("child");
            let _child = child.enter();
            tracing::info!(target: "trial", gamma = 3_i64, "Nested request");
        }
        // Поля, записанные после создания спана, тоже читаются: поле объявлено незаполненным.
        let late = tracing::info_span!("late", correlation_id = tracing::field::Empty);
        let _late = late.enter();
        late.record("correlation_id", CORRELATION);
        tracing::info!(target: "trial", delta = 4_i64, "Late correlation");
    });
    let lines = lines(&buffer);
    assert_eq!(lines.len(), 4);
    // Вне спана.
    let outside = parse(&lines[0]);
    assert!(outside.get("CorrelationId").is_none());
    assert!(!lines[0].contains("traceId"));
    assert!(!lines[0].contains("spanId"));
    // В спане: корреляция отдельным полем, трассировка и отрезок — первыми в свойствах.
    let inside = parse(&lines[1]);
    assert_eq!(inside["CorrelationId"], CORRELATION);
    assert_eq!(inside["EventProperties"]["traceId"], TRACE_ID);
    assert_eq!(inside["EventProperties"]["spanId"], SPAN_ID);
    assert_eq!(inside["traceId"], TRACE_ID);
    assert_eq!(inside["spanId"], SPAN_ID);
    assert_raw_order(&lines[1], &["\"traceId\"", "\"spanId\"", "\"beta\""]);
    // Во вложенном спане.
    let nested = parse(&lines[2]);
    assert_eq!(nested["CorrelationId"], CORRELATION);
    assert_eq!(nested["EventProperties"]["traceId"], TRACE_ID);
    assert_eq!(nested["EventProperties"]["spanId"], SPAN_ID);
    // Запись поля после создания спана.
    let late = parse(&lines[3]);
    assert_eq!(late["CorrelationId"], CORRELATION);
}

#[tokio::test]
async fn capture_delivers_messages_not_below_threshold() {
    let (journal, buffer) = buffered(config(Level::Debug, Template::Human), reference_first());
    let handle = handle(&journal);
    let mut capture = handle.capture(Level::Info);
    install(&journal, || {
        // Ниже порога журнала: в поток не попадает вовсе.
        tracing::trace!(target: "trial", "Too detailed");
        let span = tracing::info_span!("request", correlation_id = CORRELATION);
        {
            let _entered = span.enter();
            // Ниже порога потока: в канал попадает, читателю не выдаётся.
            tracing::debug!(target: "trial", alpha = 1_i64, "Diagnostic line");
            tracing::info!(target: "trial", alpha = 2_i64, "Notable line");
        }
        let pack: &(dyn StdError + 'static) = &PackError;
        tracing::error!(target: "trial", error = pack, "Pack failed");
    });
    let notable = capture.next().await.expect("the notable message");
    assert_eq!(notable.level(), Level::Info);
    assert_eq!(notable.message(), "Notable line");
    assert_eq!(notable.correlation_id(), Some(CORRELATION));
    assert_eq!(notable.timestamp(), reference_first());
    assert_eq!(notable.exception(), None);
    let failure = capture.next().await.expect("the failure message");
    assert_eq!(failure.level(), Level::Error);
    assert_eq!(failure.correlation_id(), None);
    let exception = failure.exception().expect("the exception text");
    assert!(exception.contains("PackError: Document body is corrupt"));
    assert!(exception.contains("Caused by: DecodeError: Unexpected end of input"));
    // Больше сообщений не выдаётся: диагностическое ниже порога потока.
    let nothing = tokio::time::timeout(Duration::from_millis(100), capture.next()).await;
    assert!(nothing.is_err(), "no messages below the capture threshold");
    // После отписки всех читателей журнал продолжает работать.
    drop(capture);
    install(&journal, || {
        tracing::info!(target: "trial", "Still writing");
    });
    // Диагностическая строка, значимая, ошибка с причиной (заголовок и причина) и новая запись.
    assert_eq!(lines(&buffer).len(), 6);
}

#[tokio::test]
async fn slow_reader_skips_lost_messages_without_blocking() {
    let (journal, _) = buffered(config(Level::Info, Template::Human), reference_first());
    let handle = handle(&journal);
    let mut capture = handle.capture(Level::Info);
    install(&journal, || {
        for index in 0..1100_i64 {
            tracing::info!(target: "trial", index = index, "Cycled message");
        }
    });
    // Читатель отстал: пропуск не виден, журнал не блокируется, сообщения идут.
    let message = capture.next().await.expect("a message after the lag");
    assert_eq!(message.level(), Level::Info);
    assert_eq!(message.message(), "Cycled message");
}

#[test]
fn panic_is_recorded_as_an_error() {
    let (journal, buffer) = buffered(config(Level::Info, Template::Json), reference_first());
    let subscriber = tracing_subscriber::registry().with(journal);
    tracing::subscriber::with_default(subscriber, || {
        set_panic_hook();
        // Паника без макроса `panic!`: переменная окружения не задана, поэтому значение пустое;
        // текст ожидания становится текстом паники ровно в том виде, в каком его читает журнал.
        let boom = std::env::var_os("JOURNAL_PANIC_PROBE");
        let outcome = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
            boom.expect("boom at sea");
        }));
        assert!(outcome.is_err(), "the panic is caught");
    });
    let line = &lines(&buffer)[0];
    let value = parse(line);
    assert_eq!(value["Level"], "Error");
    assert_eq!(value["Exception"]["Type"], "Panic");
    assert_eq!(value["Message"], "panic");
    let exception_message = value["Exception"]["Message"]
        .as_str()
        .expect("the panic message");
    assert!(
        exception_message.starts_with("boom at sea at "),
        "the message shows the panic and the place: {exception_message}"
    );
    assert!(
        value["EventProperties"]["thread"].is_string(),
        "the thread name is a property"
    );
    let backtrace_disabled = matches!(std::env::var("RUST_BACKTRACE").as_deref(), Ok("0"));
    if !backtrace_disabled {
        let stack = value["Exception"]["StackTrace"]
            .as_str()
            .expect("the stack trace");
        assert!(!stack.trim().is_empty(), "the stack trace is captured");
    }
}

#[test]
fn fixed_property_names_are_not_repeated() {
    let (journal, buffer) = buffered(config(Level::Info, Template::Json), reference_first());
    install(&journal, || {
        tracing::info!(
            target: "trial",
            Level = "odd",
            Service = "wide",
            note = "plain",
            "Kept names"
        );
    });
    let line = &lines(&buffer)[0];
    let value = parse(line);
    // Свойства остались в объекте событий.
    assert_eq!(value["EventProperties"]["Level"], "odd");
    assert_eq!(value["EventProperties"]["Service"], "wide");
    // Постоянные поля наверху одни.
    assert_eq!(value["Level"], "Info");
    assert_eq!(value["Service"]["Name"], "trial");
    assert_eq!(raw_count(line, "\"Level\":"), 2);
    assert_eq!(raw_count(line, "\"Service\":"), 2);
    // Обычное свойство повторяется.
    assert_eq!(value["note"], "plain");
}

#[test]
fn missing_message_field_gives_empty_message() {
    let (journal, buffer) = buffered(config(Level::Info, Template::Json), reference_first());
    install(&journal, || {
        tracing::info!(target: "trial", alpha = 1_i64);
    });
    let value = parse(&lines(&buffer)[0]);
    assert_eq!(value["Message"], "");
    assert_eq!(value["EventProperties"]["alpha"], 1);
}

/// Число вхождений фрагмента в строку.
fn raw_count(text: &str, needle: &str) -> usize {
    text.match_indices(needle).count()
}