zebrad 7.2.0

The Zcash Foundation's independent, consensus-compatible implementation of a Zcash node
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
//! Checks that the dashboards, alert rules, and example queries in `docker/observability` only
//! query series that Zebra exports, and only use labels those series have.

use std::{
    collections::{BTreeMap, BTreeSet},
    path::{Path, PathBuf},
};

use regex::Regex;
use serde_json::Value;

use super::{workspace_root, Catalog};

/// Series that the observability stack queries but Zebra doesn't export, with their labels.
const OTHER_SERIES: &[(&str, &[&str])] = &[
    // Prometheus's own scrape health series.
    ("up", &[]),
    // Span metrics that Jaeger's spanmetrics connector derives from Zebra's traces. The
    // Prometheus exporter in `docker/observability/jaeger/config.yaml` names them from its
    // `traces` namespace, the connector's `span_metrics` namespace, and the `ms` unit of the
    // duration histogram.
    ("traces_span_metrics_calls_total", SPAN_METRIC_LABELS),
    (
        "traces_span_metrics_duration_milliseconds_bucket",
        SPAN_METRIC_LABELS,
    ),
    (
        "traces_span_metrics_duration_milliseconds_sum",
        SPAN_METRIC_LABELS,
    ),
    (
        "traces_span_metrics_duration_milliseconds_count",
        SPAN_METRIC_LABELS,
    ),
];

/// The labels of the span metrics that `docker/observability/jaeger/config.yaml` configures.
///
/// The connector always adds `service_name`, `span_name`, `span_kind`, and `status_code`, and
/// adds `rpc_method` and `rpc_system` from the configured dimensions. The exporter adds the
/// constant `service` label. The `otel.status_code` dimension never becomes a label, because
/// `tracing-opentelemetry` turns that span field into the span status instead of an attribute.
const SPAN_METRIC_LABELS: &[&str] = &[
    "service_name",
    "span_name",
    "span_kind",
    "status_code",
    "rpc_method",
    "rpc_system",
    "service",
];

/// Labels that Prometheus adds to every series it scrapes.
///
/// `__name__` isn't one of them, so any query that uses it is rejected, including a selector
/// that matches series by name instead of naming them, whose series the checks couldn't tell.
const PROMETHEUS_LABELS: &[&str] = &["instance", "job"];

/// The label of the bucket series of a Prometheus histogram.
const BUCKET_LABEL: &str = "le";

/// The label of the quantile series of a Prometheus summary.
const QUANTILE_LABEL: &str = "quantile";

/// PromQL keywords that look like metric names.
const PROMQL_KEYWORDS: &[&str] = &[
    "and",
    "or",
    "unless",
    "by",
    "without",
    "on",
    "ignoring",
    "group_left",
    "group_right",
    "bool",
    "offset",
    "inf",
    "nan",
];

/// A query in the observability stack.
struct Query {
    /// The file the query is in.
    path: PathBuf,
    /// The PromQL expression, or Grafana `label_values` template query.
    expr: String,
    /// The Grafana legend format of the panel target that runs the query, if any.
    legend: Option<String>,
}

impl Query {
    /// Returns the query's file, relative to the workspace root.
    fn file(&self) -> std::path::Display<'_> {
        self.path
            .strip_prefix(workspace_root())
            .unwrap_or(&self.path)
            .display()
    }
}

/// Every series queried by the observability stack is exported by Zebra or listed as another
/// component's series.
#[test]
fn queries_use_exported_series() {
    let _init_guard = zebra_test::init();

    let known = SeriesLabels::build(&Catalog::build());

    let mut errors = BTreeSet::new();
    for query in observability_queries() {
        for name in series_names(&query.expr) {
            if !known.series.contains_key(&name) {
                errors.insert(format!(
                    "{}: {name} isn't a series Zebra exports. The catalog in \
                     docker/observability/metrics-catalog.json lists every exported series.",
                    query.file(),
                ));
            }
        }
    }

    assert!(
        errors.is_empty(),
        "{}",
        errors.into_iter().collect::<Vec<_>>().join("\n")
    );
}

/// Every label used by a query in the observability stack is a label of a series it queries.
#[test]
fn queries_use_series_labels() {
    let _init_guard = zebra_test::init();

    let known = SeriesLabels::build(&Catalog::build());

    let mut errors = BTreeSet::new();
    for query in observability_queries() {
        for label in known.unknown_labels(&query.expr, query.legend.as_deref()) {
            errors.insert(format!(
                "{}: {label} isn't a label of the series that `{}` queries. The catalog in \
                 docker/observability/metrics-catalog.json lists the labels of every exported \
                 series, and OTHER_SERIES lists the labels of other components' series.",
                query.file(),
                query.expr,
            ));
        }
    }

    assert!(
        errors.is_empty(),
        "{}",
        errors.into_iter().collect::<Vec<_>>().join("\n")
    );
}

/// Returns the queries of the dashboards, alert rules, and README in `docker/observability`.
fn observability_queries() -> Vec<Query> {
    let root = workspace_root().join("docker/observability");
    let mut queries = Vec::new();

    for path in files_with_extension(&root.join("grafana/dashboards"), "json") {
        let dashboard: Value =
            serde_json::from_str(&std::fs::read_to_string(&path).expect("dashboards are readable"))
                .expect("dashboards are valid JSON");
        let mut expressions = Vec::new();
        dashboard_queries(&dashboard, &mut expressions);
        queries.extend(expressions.into_iter().map(|(expr, legend)| Query {
            path: path.clone(),
            expr,
            legend,
        }));
    }

    for path in files_with_extension(&root.join("prometheus/rules"), "yml") {
        let rules = std::fs::read_to_string(&path).expect("rules are readable");
        let expressions =
            rule_expressions(&rules).unwrap_or_else(|error| panic!("{}: {error}", path.display()));
        queries.extend(expressions.into_iter().map(|expr| Query {
            path: path.clone(),
            expr,
            legend: None,
        }));
    }

    let readme_query = Regex::new(r"query\?query=([^'\s]+)").expect("valid regex");
    let readme = root.join("README.md");
    let readme_text = std::fs::read_to_string(&readme).expect("the README is readable");
    queries.extend(
        readme_query
            .captures_iter(&readme_text)
            .map(|captures| Query {
                path: readme.clone(),
                expr: captures[1].to_owned(),
                legend: None,
            }),
    );

    assert!(!queries.is_empty(), "the observability stack has queries");
    queries
}

/// The labels of every series that the observability stack can query.
struct SeriesLabels {
    /// The labels of each series, by series name, including the bucket and quantile labels of
    /// the series that have them.
    series: BTreeMap<String, BTreeSet<String>>,
    /// The labels that every series has.
    common: BTreeSet<String>,
}

impl SeriesLabels {
    /// Builds the labels of Zebra's exported series in `catalog`, the other components' series,
    /// and the labels that Prometheus adds to every series it scrapes.
    fn build(catalog: &Catalog) -> Self {
        let mut series = BTreeMap::new();
        for (name, entry) in &catalog.0 {
            let labels: BTreeSet<String> = entry.labels.iter().map(ToString::to_string).collect();
            let (metric_type, names) = entry.prometheus(name);
            for (index, name) in names.into_iter().enumerate() {
                // The first series of a histogram is its buckets, and of a summary its quantiles.
                let added = match (metric_type, index) {
                    ("histogram", 0) => Some(BUCKET_LABEL),
                    ("summary", 0) => Some(QUANTILE_LABEL),
                    _ => None,
                };
                let labels = labels.iter().cloned().chain(added.map(str::to_owned));
                series.insert(name, labels.collect());
            }
        }
        for (name, labels) in OTHER_SERIES {
            let added = name.ends_with("_bucket").then_some(BUCKET_LABEL);
            series.insert(
                name.to_string(),
                labels
                    .iter()
                    .chain(&added)
                    .map(ToString::to_string)
                    .collect(),
            );
        }

        let config_path = workspace_root().join("docker/observability/prometheus/prometheus.yaml");
        let config = std::fs::read_to_string(&config_path)
            .expect("the Prometheus configuration is readable");
        let scrape_labels = static_scrape_labels(&config)
            .unwrap_or_else(|error| panic!("{}: {error}", config_path.display()));

        let common = PROMETHEUS_LABELS
            .iter()
            .map(ToString::to_string)
            .chain(scrape_labels)
            .collect();

        Self { series, common }
    }

    /// Returns the labels that `query` and its Grafana `legend` use but the series they apply to
    /// don't have.
    ///
    /// A label matcher applies to the series it selects. An `on` label must be a label of every
    /// series in the query, which is stricter than PromQL when the `on` clause is part of a larger
    /// expression. Other grouping clauses, `label_values` labels, and legend placeholders need a
    /// label of some series in the query.
    ///
    /// The checks use the labels of the selected series, not the labels left after an
    /// aggregation, so they can accept a label that an aggregation removed.
    fn unknown_labels(&self, query: &str, legend: Option<&str>) -> BTreeSet<String> {
        let query_series: Vec<Option<&BTreeSet<String>>> = series_names(query)
            .iter()
            .map(|series| self.series.get(series))
            .collect();
        let some_series_has = |label: &String| {
            query_series
                .iter()
                .flatten()
                .any(|labels| labels.contains(label))
        };
        let every_series_has = |label: &String| {
            !query_series.is_empty()
                && query_series
                    .iter()
                    .all(|labels| labels.is_some_and(|labels| labels.contains(label)))
        };

        label_uses(query, legend)
            .into_iter()
            .filter(|(scope, label)| {
                let known = match scope {
                    LabelScope::Selector(series) => self
                        .series
                        .get(series)
                        .is_some_and(|labels| labels.contains(label)),
                    LabelScope::AnySeries => some_series_has(label),
                    LabelScope::EverySeries => every_series_has(label),
                };
                !known && !self.common.contains(label)
            })
            .map(|(_, label)| label)
            .collect()
    }
}

/// Returns the files in `dir` with `extension`.
fn files_with_extension(dir: &Path, extension: &str) -> Vec<PathBuf> {
    let mut files: Vec<_> = std::fs::read_dir(dir)
        .expect("observability directories are readable")
        .map(|entry| {
            entry
                .expect("observability directories are readable")
                .path()
        })
        .filter(|path| path.extension().is_some_and(|ext| ext == extension))
        .collect();
    files.sort();
    files
}

/// Adds the PromQL expressions of the panels and template variables in `value` to `queries`,
/// each with the legend format of its panel target.
fn dashboard_queries(value: &Value, queries: &mut Vec<(String, Option<String>)>) {
    match value {
        Value::Object(object) => {
            let legend = object
                .get("legendFormat")
                .and_then(Value::as_str)
                .map(str::to_owned);
            for (key, value) in object {
                match (key.as_str(), value) {
                    ("expr" | "query", Value::String(query)) => {
                        queries.push((query.clone(), legend.clone()))
                    }
                    _ => dashboard_queries(value, queries),
                }
            }
        }
        Value::Array(values) => values
            .iter()
            .for_each(|value| dashboard_queries(value, queries)),
        _ => {}
    }
}

/// Returns the label names that the `labels` of the `static_configs` in the Prometheus
/// configuration `config` add to the scraped series.
///
/// Like [`rule_expressions`], this only reads `labels` written as a block mapping, and returns an
/// error for any other form instead of skipping labels it can't read.
fn static_scrape_labels(config: &str) -> Result<BTreeSet<String>, String> {
    let labels_key = Regex::new(r"^(\s*(?:-\s+)?)labels:(.*)$").map_err(|e| e.to_string())?;
    let label_key = Regex::new(r"^\s*([a-zA-Z_][a-zA-Z0-9_]*):\s").map_err(|e| e.to_string())?;
    let lines: Vec<&str> = config.lines().collect();

    let mut labels = BTreeSet::new();
    for (index, line) in lines.iter().enumerate() {
        let Some(captures) = labels_key.captures(line) else {
            continue;
        };
        let key_column = captures[1].len();
        if !captures[2]
            .split('#')
            .next()
            .unwrap_or_default()
            .trim()
            .is_empty()
        {
            return Err(format!(
                "line {}: write the labels as a block mapping, so the labels they add can be \
                 checked",
                index + 1,
            ));
        }

        for (next_index, next) in lines.iter().enumerate().skip(index + 1) {
            if next.trim().is_empty() || next.trim_start().starts_with('#') {
                continue;
            }
            if next.len() - next.trim_start().len() <= key_column {
                break;
            }
            let label = label_key.captures(next).ok_or_else(|| {
                format!(
                    "line {}: write each label as a plain `name: value` entry on its own line, so \
                     the labels can be checked",
                    next_index + 1,
                )
            })?;
            labels.insert(label[1].to_owned());
        }
    }

    Ok(labels)
}

/// Returns the `expr` values of the Prometheus rules file `rules`.
///
/// The workspace has no YAML parser, so this only reads `expr` values written as plain scalars on
/// one line. It returns an error for any other form, such as a quoted or block scalar, instead of
/// skipping an expression it can't check.
fn rule_expressions(rules: &str) -> Result<Vec<String>, String> {
    let expr_key = Regex::new(r"^(\s*(?:-\s+)?)expr:(\s.*)?$").map_err(|e| e.to_string())?;
    let lines: Vec<&str> = rules.lines().collect();

    let mut expressions = Vec::new();
    for (index, line) in lines.iter().enumerate() {
        let Some(captures) = expr_key.captures(line) else {
            // An `expr` key the pattern doesn't match, such as a quoted key or a flow mapping,
            // would otherwise skip the check without failing it.
            if line.split('#').next().unwrap_or_default().contains("expr") {
                return Err(format!(
                    "line {}: write each expr as a plain `expr:` key on its own line, so the \
                     series it queries can be checked",
                    index + 1,
                ));
            }
            continue;
        };
        let key_column = captures[1].len();
        let value = captures.get(2).map_or("", |value| value.as_str());
        let value = value.split(" #").next().unwrap_or_default().trim();

        let continues_on_next_line = lines[index + 1..]
            .iter()
            .find(|next| !next.trim().is_empty() && !next.trim_start().starts_with('#'))
            .is_some_and(|next| next.len() - next.trim_start().len() > key_column);
        let unreadable = value.is_empty()
            || value.starts_with(['"', '\'', '|', '>', '&', '*', '!', '{', '['])
            || continues_on_next_line;

        if unreadable {
            return Err(format!(
                "line {}: write the expr value as a plain scalar on one line, so the series it \
                 queries can be checked",
                index + 1,
            ));
        }
        expressions.push(value.to_owned());
    }

    Ok(expressions)
}

/// Matches Grafana's `label_values(series, label)` and `label_values(label)` template queries,
/// capturing the series selector and the label.
fn label_values_regex() -> Regex {
    Regex::new(r"label_values\(\s*(?:(.*?)\s*,\s*)?([a-zA-Z_][a-zA-Z0-9_]*)\s*\)")
        .expect("valid regex")
}

/// Matches quoted PromQL strings.
fn strings_regex() -> Regex {
    Regex::new(r#""(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'"#).expect("valid regex")
}

/// Matches Grafana template variables.
fn variables_regex() -> Regex {
    Regex::new(r"\$\{[^}]*\}|\$\w+").expect("valid regex")
}

/// Matches PromQL grouping and vector matching clauses, capturing their keyword and label list.
fn groupings_regex() -> Regex {
    Regex::new(r"\b(by|without|on|ignoring|group_left|group_right)\s*\(([^)]*)\)")
        .expect("valid regex")
}

/// The series that a label used in a query must be a label of.
#[derive(Debug, PartialEq)]
enum LabelScope {
    /// The series a label matcher selects.
    Selector(String),
    /// Some series in the query.
    AnySeries,
    /// Every series in the query.
    EverySeries,
}

/// Returns the series names that the PromQL expression `query` selects.
///
/// Also accepts Grafana's `label_values(series, label)` template queries.
fn series_names(query: &str) -> BTreeSet<String> {
    let matchers = Regex::new(r"\{[^}]*\}").expect("valid regex");
    let ranges = Regex::new(r"\[[^\]]*\]").expect("valid regex");
    let tokens =
        Regex::new(r"\d+(?:\.\d+)?(?:[eE][+-]?\d+)?[a-zA-Z]*|([a-zA-Z_:][a-zA-Z0-9_:]*)(\s*\()?")
            .expect("valid regex");

    let query = label_values_regex().replace_all(query, "$1");
    let query = strings_regex().replace_all(&query, "\"\"");
    let query = matchers.replace_all(&query, "");
    let query = ranges.replace_all(&query, "");
    let query = variables_regex().replace_all(&query, "");
    let query = groupings_regex().replace_all(&query, "");

    tokens
        .captures_iter(&query)
        .filter_map(|token| {
            let name = token.get(1)?.as_str();
            let is_function = token.get(2).is_some();
            let is_keyword = PROMQL_KEYWORDS.contains(&name.to_lowercase().as_str());
            (!is_function && !is_keyword).then(|| name.to_owned())
        })
        .collect()
}

/// Returns the labels that the PromQL expression `query` and its Grafana `legend` use.
///
/// Each label comes with the series it must be a label of. A label matcher without a series name
/// before it, such as `{__name__="x"}`, needs a label of every series in the query.
fn label_uses(query: &str, legend: Option<&str>) -> Vec<(LabelScope, String)> {
    let selectors = Regex::new(r"([a-zA-Z_:][a-zA-Z0-9_:]*)?\s*\{([^}]*)\}").expect("valid regex");
    let matcher = Regex::new(r"([a-zA-Z_][a-zA-Z0-9_]*)\s*(?:=~|!~|!=|=)").expect("valid regex");
    let placeholders = Regex::new(r"\{\{\s*([^{}\s]+)\s*\}\}").expect("valid regex");

    let mut uses = Vec::new();

    let label_values = label_values_regex();
    for captures in label_values.captures_iter(query) {
        uses.push((LabelScope::AnySeries, captures[2].to_owned()));
    }
    let query = label_values.replace_all(query, "$1");
    let query = strings_regex().replace_all(&query, "\"\"");
    let query = variables_regex().replace_all(&query, "");

    for captures in selectors.captures_iter(&query) {
        for label in matcher.captures_iter(&captures[2]) {
            let scope = match captures.get(1) {
                Some(series) => LabelScope::Selector(series.as_str().to_owned()),
                None => LabelScope::EverySeries,
            };
            uses.push((scope, label[1].to_owned()));
        }
    }

    for captures in groupings_regex().captures_iter(&query) {
        for label in captures[2].split(',').map(str::trim) {
            if !label.is_empty() {
                let scope = match &captures[1] {
                    "on" => LabelScope::EverySeries,
                    _ => LabelScope::AnySeries,
                };
                uses.push((scope, label.to_owned()));
            }
        }
    }

    for captures in placeholders.captures_iter(legend.unwrap_or_default()) {
        uses.push((LabelScope::AnySeries, captures[1].to_owned()));
    }

    uses
}

/// Returns the labels for the label tests: series with known labels, and Prometheus's labels.
fn test_labels() -> SeriesLabels {
    let series = [
        ("rpc_requests_total", &["method"][..]),
        (
            "rpc_request_duration_seconds_bucket",
            &["method", BUCKET_LABEL],
        ),
        ("rpc_request_duration_seconds_sum", &["method"]),
        ("rpc_active_requests", &[]),
        ("state_commit_seconds", &[QUANTILE_LABEL]),
        ("sync_block_error_count", &["kind"]),
        ("zcash_net_peers", &[]),
    ]
    .into_iter()
    .map(|(series, labels)| {
        (
            series.to_owned(),
            labels.iter().map(ToString::to_string).collect(),
        )
    })
    .collect();
    let common = PROMETHEUS_LABELS.iter().map(ToString::to_string).collect();

    SeriesLabels { series, common }
}

#[test]
fn accepts_labels_of_the_queried_series() {
    let _init_guard = zebra_test::init();

    let known = test_labels();
    let unknown = |query, legend| known.unknown_labels(query, legend);

    assert_eq!(
        unknown(
            r#"histogram_quantile(0.99, sum by (le, method) (rate(rpc_request_duration_seconds_bucket{job="$job", method!~"getblocktemplate|z_.*"}[${__rate_interval}])))"#,
            Some("{{method}} on {{ instance }}"),
        ),
        BTreeSet::new(),
    );
    assert_eq!(
        unknown(
            "sum by (method) (rate(rpc_request_duration_seconds_sum[5m])) / on (method) group_left (le) rpc_request_duration_seconds_bucket",
            None,
        ),
        BTreeSet::new(),
    );
    assert_eq!(
        unknown(r#"state_commit_seconds{quantile="0.99"}"#, None),
        BTreeSet::new(),
    );
    assert_eq!(
        unknown(
            "rpc_requests_total / ignoring (kind) sync_block_error_count",
            None
        ),
        BTreeSet::new(),
        "an ignoring clause only needs a label of some series",
    );
    assert_eq!(
        unknown("label_values(zcash_net_peers, job)", None),
        BTreeSet::new(),
    );
    assert_eq!(
        unknown(
            r#"rpc_requests_total{method="by (nope)", job=~"$nope"}"#,
            None
        ),
        BTreeSet::new(),
        "labels inside strings and variables aren't label names",
    );
}

#[test]
fn rejects_unknown_labels_wherever_they_are_used() {
    let _init_guard = zebra_test::init();

    let known = test_labels();
    let nope = BTreeSet::from(["nope".to_owned()]);

    for query in [
        r#"rpc_requests_total{nope="x"}"#,
        r#"rate(rpc_requests_total{job="zebra", nope!~"x"}[5m])"#,
        "sum by (method, nope) (rpc_requests_total)",
        "sum (rpc_requests_total) by (nope)",
        "sum without (nope) (rpc_requests_total)",
        "rpc_requests_total / on (nope) sync_block_error_count",
        "rpc_requests_total / ignoring (nope) sync_block_error_count",
        "rpc_requests_total * on (method) group_left (nope) rpc_request_duration_seconds_sum",
        "rpc_requests_total * on (method) group_right (nope) rpc_request_duration_seconds_sum",
        "label_values(zcash_net_peers, nope)",
        r#"label_values(rpc_requests_total{job="zebra", method="getinfo"}, nope)"#,
        "label_values(nope)",
    ] {
        assert_eq!(known.unknown_labels(query, None), nope, "{query}");
    }

    for legend in ["{{nope}}", "{{method}} {{ nope }}"] {
        assert_eq!(
            known.unknown_labels("rpc_requests_total", Some(legend)),
            nope,
            "{legend}",
        );
    }

    assert_eq!(
        known.unknown_labels(
            r#"rpc_requests_total{kind="invalid"} / sync_block_error_count"#,
            None
        ),
        BTreeSet::from(["kind".to_owned()]),
        "a label matcher only accepts the labels of the series it selects",
    );

    for (query, label, reason) in [
        (
            r#"rpc_request_duration_seconds_bucket{quantile="0.99"}"#,
            QUANTILE_LABEL,
            "only summaries have quantiles",
        ),
        (
            r#"rpc_active_requests{le="1"}"#,
            BUCKET_LABEL,
            "only histogram buckets have bounds",
        ),
        (
            r#"rpc_request_duration_seconds_sum{le="1"}"#,
            BUCKET_LABEL,
            "a histogram's sum has no bounds",
        ),
        (
            "rpc_requests_total / on (method) sync_block_error_count",
            "method",
            "an on clause needs a label of both operands",
        ),
        (
            r#"{__name__="missing_total"}"#,
            "__name__",
            "a selector that matches series by name hides which series it queries",
        ),
        (
            r#"rpc_requests_total{__name__=~".+"}"#,
            "__name__",
            "a selector can't match other series by name",
        ),
    ] {
        assert_eq!(
            known.unknown_labels(query, None),
            BTreeSet::from([label.to_owned()]),
            "{reason}: {query}",
        );
    }
}

#[test]
fn reads_static_scrape_labels_and_rejects_other_forms() {
    let _init_guard = zebra_test::init();

    let config = "scrape_configs:\n  - job_name: zebra\n    static_configs:\n      - targets: [\"zebra:9999\"]\n        labels:\n          # The network.\n          network: mainnet\n\n          region: eu\n      - targets: [\"other:9999\"]\n  - job_name: other\n";
    assert_eq!(
        static_scrape_labels(config),
        Ok(BTreeSet::from(["network".to_owned(), "region".to_owned()])),
    );
    assert_eq!(
        static_scrape_labels("scrape_configs:\n  - job_name: zebra\n"),
        Ok(BTreeSet::new()),
    );

    let flow = "static_configs:\n  - targets: [a]\n    labels: {network: mainnet}\n";
    let quoted = "static_configs:\n  - targets: [a]\n    labels:\n      \"network\": mainnet\n";
    for config in [flow, quoted] {
        let error = static_scrape_labels(config).expect_err("unreadable labels are rejected");
        assert!(
            error.starts_with("line 3:") || error.starts_with("line 4:"),
            "{error}"
        );
    }
}

#[test]
fn extracts_series_names_from_promql() {
    let _init_guard = zebra_test::init();

    let names = |query| series_names(query).into_iter().collect::<Vec<_>>();

    assert_eq!(
        names(
            r#"histogram_quantile(0.99, sum(rate(rpc_request_duration_seconds_bucket{job="$job"}[$__rate_interval])) by (le, method)) > 2"#
        ),
        ["rpc_request_duration_seconds_bucket"],
    );
    assert_eq!(
        names("sum(rate(a_total[5m])) / (sum(rate(b_count[5m])) + 1e-3) > 0.5 and on(instance) c"),
        ["a_total", "b_count", "c"],
    );
    assert_eq!(
        names("label_values(zcash_net_peers, job)"),
        ["zcash_net_peers"]
    );
    assert_eq!(
        names("sum without (le) (increase(x_bucket[1h] offset 1d))"),
        ["x_bucket"]
    );
}

#[test]
fn reads_plain_rule_expressions_and_rejects_other_forms() {
    let _init_guard = zebra_test::init();

    let plain = "rules:\n  - alert: A\n    expr: rate(a_total[5m]) > 0 # comment\n    for: 5m\n  - expr: b\n";
    assert_eq!(
        rule_expressions(plain),
        Ok(vec!["rate(a_total[5m]) > 0".to_owned(), "b".to_owned()]),
    );

    let quoted = "rules:\n  - alert: A\n    expr: \"not_a_zebra_series > 0\"\n";
    let single_quoted = "rules:\n  - alert: A\n    expr: 'not_a_zebra_series > 0'\n";
    let block = "rules:\n  - alert: A\n    expr: |\n      not_a_zebra_series > 0\n";
    let folded = "rules:\n  - alert: A\n    expr: >-\n      not_a_zebra_series > 0\n";
    let multi_line =
        "rules:\n  - alert: A\n    expr: rate(a_total[5m])\n      > not_a_zebra_series\n";
    let empty = "rules:\n  - alert: A\n    expr:\n      not_a_zebra_series > 0\n";

    let quoted_key = "rules:\n  - alert: A\n    \"expr\": not_a_zebra_series > 0\n";
    let flow_mapping = "rules:\n  - alert: A\n  - {alert: B, expr: not_a_zebra_series > 0}\n";
    for rules in [quoted_key, flow_mapping] {
        let error = rule_expressions(rules).expect_err("unmatched expr keys are rejected");
        assert!(error.starts_with("line 3:"), "{error}");
    }

    for rules in [quoted, single_quoted, block, folded, multi_line, empty] {
        let error = rule_expressions(rules).expect_err("unreadable expr values are rejected");
        assert!(error.starts_with("line 3:"), "{error}");
    }
}