Skip to main content

cja/observability/
declarations.rs

1//! App-owned declarations shared by both observability sinks.
2use super::{AggregateFunction, MetricValueType};
3use eyes::eyes_query::{Expr, Function, Literal, NamedExpr, Stage};
4use eyes_subscriber as eyes;
5
6fn ratio_groups(metric: &eyes::NamedMetric) -> (Vec<NamedExpr>, Option<(i64, i64)>) {
7    let groups = metric
8        .query
9        .as_ref()
10        .and_then(|query| {
11            query.query.stages.iter().find_map(|stage| {
12                if let Stage::Aggregate { groups, .. } = stage {
13                    Some(groups.clone())
14                } else {
15                    None
16                }
17            })
18        })
19        .unwrap_or_default();
20    let bucket = groups.first().and_then(|group| {
21        let Expr::Call {
22            function: Function::TimeBucket,
23            args,
24        } = &group.expr
25        else {
26            return None;
27        };
28        let Some(Expr::Literal {
29            value: Literal::Duration(width),
30        }) = args.get(1)
31        else {
32            return None;
33        };
34        let origin = match args.get(2) {
35            Some(Expr::Literal {
36                value: Literal::Duration(origin),
37            }) => *origin,
38            _ => 0,
39        };
40        Some((*width, origin))
41    });
42    (groups, bucket)
43}
44/// Numeric comparison applied to the first `HogQL` result cell.
45#[derive(Debug, Clone, Copy, serde::Serialize)]
46#[serde(rename_all = "snake_case")]
47pub enum HogqlComparison {
48    Gt,
49    Gte,
50    Lt,
51    Lte,
52    Eq,
53    Neq,
54}
55
56/// Alert severity for a `HogQL` check.
57#[derive(Debug, Clone, Copy, serde::Serialize)]
58#[serde(rename_all = "snake_case")]
59pub enum HogqlSeverity {
60    Critical,
61    Warning,
62    Info,
63}
64
65/// A declarative `HogQL` health check; cja does not execute it.
66#[derive(Debug, Clone)]
67pub struct HogqlCheck {
68    pub name: String,
69    pub query: String,
70    pub comparison: HogqlComparison,
71    pub threshold: f64,
72    pub interval_seconds: u64,
73    pub severity: HogqlSeverity,
74}
75
76impl HogqlCheck {
77    pub fn new(
78        name: impl Into<String>,
79        query: impl Into<String>,
80        comparison: HogqlComparison,
81        threshold: f64,
82        interval_seconds: u64,
83        severity: HogqlSeverity,
84    ) -> Self {
85        Self {
86            name: name.into(),
87            query: query.into(),
88            comparison,
89            threshold,
90            interval_seconds,
91            severity,
92        }
93    }
94}
95/// A named dashboard with ordered sections and a stable remote identity.
96#[derive(Debug, Clone, PartialEq, Eq)]
97#[must_use]
98pub struct Dashboard {
99    pub id: String,
100    pub title: String,
101    pub description: Option<String>,
102    pub default_range_seconds: Option<u64>,
103    pub sections: Vec<Section>,
104}
105
106/// One titled grouping of dashboard items.
107#[derive(Debug, Clone, PartialEq, Eq)]
108#[must_use]
109pub struct Section {
110    pub title: Option<String>,
111    pub description: Option<String>,
112    pub items: Vec<Item>,
113}
114
115/// Presentation of a metric, health summary or navigation links on a dashboard.
116#[derive(Debug, Clone, PartialEq, Eq)]
117#[must_use]
118pub enum Item {
119    Stat {
120        metric_id: String,
121        label: Option<String>,
122        unit: Option<String>,
123        window_seconds: Option<u64>,
124    },
125    TimeSeries {
126        metric_id: String,
127        label: Option<String>,
128        unit: Option<String>,
129        preferred_bucket_seconds: Option<u64>,
130        window_seconds: Option<u64>,
131    },
132    Table {
133        metric_id: String,
134        label: Option<String>,
135        unit: Option<String>,
136        window_seconds: Option<u64>,
137    },
138    HealthSummary {
139        label: Option<String>,
140    },
141    Links {
142        links: Vec<Link>,
143    },
144}
145
146/// One navigation link: rendered, never fetched.
147#[derive(Debug, Clone, PartialEq, Eq)]
148pub struct Link {
149    pub label: String,
150    pub href: String,
151}
152
153/// Metric- and alert-id grammar: non-empty, at most 128 bytes, chars in
154/// `[a-z0-9._:-]`.
155///
156/// Every declaration id becomes part of a `PostHog` identity: a tag for
157/// metrics and dashboards, a name suffix for alerts. `PostHog` lowercases
158/// tags on write, so an uppercase id would never be echoed back and would
159/// leak one orphan per deploy. Lowercase is therefore part of the grammar.
160fn valid_id(id: &str) -> bool {
161    !id.is_empty()
162        && id.len() <= 128
163        && id
164            .bytes()
165            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b"._:-".contains(&b))
166}
167
168const ID_RULE: &str = "must be non-empty, at most 128 bytes, lowercase chars [a-z0-9._:-]";
169
170/// Link href grammar: root-relative path (starts with `/` but not `//` —
171/// protocol-relative URLs resolve as scheme-relative external URLs) or an
172/// absolute `http(s)://` URL, with no backslash anywhere (WHATWG parsing
173/// treats `\` as `/` for special schemes, so `/\host` becomes `//host`), no
174/// ASCII control bytes, at most 512 chars. Links are rendered, never
175/// fetched — no SSRF machinery applies; the grammar check is the whole
176/// rule.
177fn valid_href(href: &str) -> bool {
178    !href.is_empty()
179        && href.chars().count() <= 512
180        && !href.chars().any(|c| c.is_ascii_control())
181        && !href.contains('\\')
182        && (href.starts_with("http://")
183            || href.starts_with("https://")
184            || (href.starts_with('/') && !href.starts_with("//")))
185}
186
187impl Dashboard {
188    /// Start a declaration. **Fallible**: validates the id grammar
189    /// (non-empty, lowercase `[a-z0-9._:-]`, at most 128 bytes)
190    /// and the title (non-empty after trim, at most 256 chars) — a bad
191    /// declaration fails at boot in the app.
192    pub fn new(id: impl Into<String>, title: impl Into<String>) -> Result<Self, String> {
193        let id = id.into();
194        if !valid_id(&id) {
195            return Err(format!("invalid dashboard id {id:?}: {ID_RULE}"));
196        }
197        let title = title.into();
198        if title.trim().is_empty() || title.chars().count() > 256 {
199            return Err(format!(
200                "invalid dashboard title {title:?}: must be non-empty after trim and at most 256 characters"
201            ));
202        }
203        Ok(Self {
204            id,
205            title,
206            description: None,
207            default_range_seconds: None,
208            sections: Vec::new(),
209        })
210    }
211
212    /// **Infallible**: the server rejects descriptions over 4096 chars at
213    /// manifest ingestion.
214    pub fn description(mut self, description: impl Into<String>) -> Self {
215        self.description = Some(description.into());
216        self
217    }
218
219    /// **Infallible**: stores the value verbatim; the server rejects
220    /// anything outside `60..=31_622_400` seconds (one minute to 366
221    /// days, the unified engine's range cap) at manifest ingestion.
222    pub fn default_range_seconds(mut self, seconds: u64) -> Self {
223        self.default_range_seconds = Some(seconds);
224        self
225    }
226
227    /// **Infallible**: appends a section; the server rejects zero sections
228    /// and more than 20 at ingestion. The builder stays permissive, like
229    /// `HttpMonitor`'s setters.
230    pub fn section(mut self, section: Section) -> Self {
231        self.sections.push(section);
232        self
233    }
234}
235
236impl Section {
237    pub fn new() -> Self {
238        Self {
239            title: None,
240            description: None,
241            items: Vec::new(),
242        }
243    }
244
245    /// **Infallible**: the server enforces the 256-char cap at ingestion.
246    pub fn title(mut self, title: impl Into<String>) -> Self {
247        self.title = Some(title.into());
248        self
249    }
250
251    /// **Infallible**: the server enforces the 4096-char cap at ingestion.
252    pub fn description(mut self, description: impl Into<String>) -> Self {
253        self.description = Some(description.into());
254        self
255    }
256
257    /// **Infallible**: appends an item; the server rejects empty sections
258    /// and more than 24 items at ingestion.
259    pub fn item(mut self, item: Item) -> Self {
260        self.items.push(item);
261        self
262    }
263}
264
265impl Default for Section {
266    fn default() -> Self {
267        Self::new()
268    }
269}
270
271impl Item {
272    /// The declared trailing window, when this item has one.
273    pub(crate) fn declared_window_seconds(&self) -> Option<u64> {
274        match self {
275            Self::Stat { window_seconds, .. }
276            | Self::TimeSeries { window_seconds, .. }
277            | Self::Table { window_seconds, .. } => *window_seconds,
278            Self::HealthSummary { .. } | Self::Links { .. } => None,
279        }
280    }
281
282    /// A single-value item rendering a `scalar` named metric.
283    /// **Infallible**: a `metric_id` is an opaque reference to a
284    /// same-manifest metric; the server rejects unknown ones at ingest.
285    pub fn stat(metric_id: impl Into<String>) -> Self {
286        Self::Stat {
287            metric_id: metric_id.into(),
288            label: None,
289            unit: None,
290            window_seconds: None,
291        }
292    }
293
294    /// A chart item rendering a `time_series` named metric.
295    /// **Infallible**: see [`Item::stat`].
296    pub fn time_series(metric_id: impl Into<String>) -> Self {
297        Self::TimeSeries {
298            metric_id: metric_id.into(),
299            label: None,
300            unit: None,
301            preferred_bucket_seconds: None,
302            window_seconds: None,
303        }
304    }
305
306    /// A table item rendering a `table` named metric.
307    /// **Infallible**: see [`Item::stat`].
308    pub fn table(metric_id: impl Into<String>) -> Self {
309        Self::Table {
310            metric_id: metric_id.into(),
311            label: None,
312            unit: None,
313            window_seconds: None,
314        }
315    }
316
317    /// Renders the app's durable run-health state; carries no query.
318    pub fn health_summary() -> Self {
319        Self::HealthSummary { label: None }
320    }
321
322    /// A navigation link list; carries no query.
323    pub fn links(links: Vec<Link>) -> Self {
324        Self::Links { links }
325    }
326
327    /// **Infallible**: sets the display label, overriding the referenced
328    /// metric's `display_name`. The server enforces the 256-char cap at
329    /// ingestion. No documented no-op case: every item kind carries a
330    /// `label`.
331    pub fn label(mut self, label: impl Into<String>) -> Self {
332        let new_label = Some(label.into());
333        match &mut self {
334            Self::Stat { label, .. }
335            | Self::TimeSeries { label, .. }
336            | Self::Table { label, .. }
337            | Self::HealthSummary { label } => *label = new_label,
338            Self::Links { .. } => {}
339        }
340        self
341    }
342
343    /// **Infallible**: sets the display unit, overriding the referenced
344    /// metric's `unit`. When the referenced metric declares a unit, the
345    /// server requires exact equality at ingest; over a unit-less metric
346    /// any valid unit text is allowed. The builder does not duplicate that
347    /// check. Documented no-op on `health_summary` and `links`, which
348    /// carry no unit field — returns `self` unchanged.
349    pub fn unit(mut self, unit: impl Into<String>) -> Self {
350        let new_unit = Some(unit.into());
351        match &mut self {
352            Self::Stat { unit, .. } | Self::TimeSeries { unit, .. } | Self::Table { unit, .. } => {
353                *unit = new_unit;
354            }
355            Self::HealthSummary { .. } | Self::Links { .. } => {}
356        }
357        self
358    }
359
360    /// **Infallible**: bucket-width guidance for callers of the execute
361    /// endpoint (which already accepts `bucket_seconds`); the server never
362    /// rewrites queries for it. Documented no-op on every kind except
363    /// `time_series` — returns `self` unchanged.
364    pub fn preferred_bucket_seconds(mut self, seconds: u64) -> Self {
365        if let Self::TimeSeries {
366            preferred_bucket_seconds,
367            ..
368        } = &mut self
369        {
370            *preferred_bucket_seconds = Some(seconds);
371        }
372        self
373    }
374
375    /// **Infallible**: declares a fixed trailing window for this item —
376    /// `seconds` back from the dashboard page's window end at render time —
377    /// overriding the page range for this item alone. The server rejects
378    /// anything outside `1..=31_622_400` seconds (one second to 366 days)
379    /// at manifest ingestion. Documented no-op on `health_summary` and
380    /// `links`, which carry no window — returns `self` unchanged.
381    pub fn window_seconds(mut self, seconds: u64) -> Self {
382        let new_window = Some(seconds);
383        match &mut self {
384            Self::Stat { window_seconds, .. }
385            | Self::TimeSeries { window_seconds, .. }
386            | Self::Table { window_seconds, .. } => *window_seconds = new_window,
387            Self::HealthSummary { .. } | Self::Links { .. } => {}
388        }
389        self
390    }
391}
392
393impl Link {
394    /// **Fallible**: validates the href grammar (root-relative `/…` but not
395    /// `//…`, no backslash anywhere, or `http(s)://…`; no ASCII control
396    /// bytes; at most 512 chars) and the label (non-empty after trim, at
397    /// most 256 chars) so a bad link fails at boot — the same grammar the
398    /// server enforces.
399    pub fn new(label: impl Into<String>, href: impl Into<String>) -> Result<Self, String> {
400        let label = label.into();
401        if label.trim().is_empty() || label.chars().count() > 256 {
402            return Err(format!(
403                "invalid dashboard link label {label:?}: must be non-empty after trim and at most 256 characters"
404            ));
405        }
406        let href = href.into();
407        if !valid_href(&href) {
408            return Err(format!(
409                "invalid dashboard link href {href:?}: must be a root-relative path (not //), an http(s) URL, at most 512 characters, with no backslash or control characters"
410            ));
411        }
412        Ok(Self { label, href })
413    }
414}
415
416/// Direction in which a threshold is breached.
417#[derive(Debug, Clone, Copy, PartialEq, Eq)]
418pub enum Comparison {
419    Above,
420    Below,
421}
422
423/// One severity policy of a metric threshold: a comparison direction and
424/// the boundary value. The threshold crosses the wire as an `f64` number —
425/// serde emits `1.0` for whole values, and the server validates by value,
426/// not JSON representation, so `1.0` is accepted for an int metric.
427#[derive(Debug, Clone, PartialEq)]
428pub struct Severity {
429    pub comparison: Comparison,
430    pub threshold: f64,
431}
432
433/// How multi-row results feed a threshold breach: `Any` breaches when at
434/// least one numeric cell breaches; `All` when every numeric cell does.
435#[derive(Debug, Clone, Copy, PartialEq, Eq)]
436pub enum GroupMatch {
437    Any,
438    All,
439}
440
441/// A metric-threshold declaration carried by the boot manifest: references
442/// a named metric declared in the same manifest by `metric_id` (no query
443/// embedded — the server joins by id). `PartialEq` only (f64 thresholds),
444/// mirroring `NamedMetric`.
445#[derive(Debug, Clone, PartialEq)]
446pub struct Alert {
447    pub id: String,
448    pub metric_id: String,
449    pub description: Option<String>,
450    pub window_seconds: u64,
451    pub evaluation_interval_seconds: u64,
452    pub evaluation_delay_seconds: u64,
453    pub group_match: GroupMatch,
454    pub failure_threshold: u32,
455    pub recovery_threshold: u32,
456    pub enabled: bool,
457    pub warning: Option<Severity>,
458    pub critical: Option<Severity>,
459}
460
461/// The ergonomic Rust surface for declaring a metric threshold. All
462/// validation happens in [`AlertBuilder::build`] — no I/O, no
463/// server round trip. The builder does **not** enforce int-range on
464/// severity thresholds: the subscriber cannot know the referenced metric's
465/// `value_type`; out-of-domain values are rejected server-side at ingest.
466#[derive(Debug)]
467#[must_use]
468pub struct AlertBuilder {
469    id: String,
470    metric_id: String,
471    description: Option<String>,
472    window_seconds: Option<u64>,
473    evaluation_interval_seconds: Option<u64>,
474    evaluation_delay_seconds: u64,
475    group_match: GroupMatch,
476    failure_threshold: u32,
477    recovery_threshold: u32,
478    enabled: bool,
479    warning: Option<Severity>,
480    critical: Option<Severity>,
481}
482
483impl AlertBuilder {
484    /// Start a declaration referencing `metric_id` (which must be declared
485    /// in the same manifest's `metrics`).
486    pub fn new(id: impl Into<String>, metric_id: impl Into<String>) -> Self {
487        Self {
488            id: id.into(),
489            metric_id: metric_id.into(),
490            description: None,
491            window_seconds: None,
492            evaluation_interval_seconds: None,
493            evaluation_delay_seconds: 0,
494            group_match: GroupMatch::Any,
495            failure_threshold: 3,
496            recovery_threshold: 1,
497            enabled: true,
498            warning: None,
499            critical: None,
500        }
501    }
502
503    pub fn window_seconds(mut self, v: u64) -> Self {
504        self.window_seconds = Some(v);
505        self
506    }
507    pub fn evaluation_interval_seconds(mut self, v: u64) -> Self {
508        self.evaluation_interval_seconds = Some(v);
509        self
510    }
511    pub fn evaluation_delay_seconds(mut self, v: u64) -> Self {
512        self.evaluation_delay_seconds = v;
513        self
514    }
515    pub fn group_match(mut self, v: GroupMatch) -> Self {
516        self.group_match = v;
517        self
518    }
519    pub fn failure_threshold(mut self, v: u32) -> Self {
520        self.failure_threshold = v;
521        self
522    }
523    pub fn recovery_threshold(mut self, v: u32) -> Self {
524        self.recovery_threshold = v;
525        self
526    }
527    pub fn enabled(mut self, v: bool) -> Self {
528        self.enabled = v;
529        self
530    }
531    pub fn description(mut self, v: impl Into<String>) -> Self {
532        self.description = Some(v.into());
533        self
534    }
535    /// Declare (or replace) the warning severity policy.
536    pub fn warning(mut self, comparison: Comparison, threshold: f64) -> Self {
537        self.warning = Some(Severity {
538            comparison,
539            threshold,
540        });
541        self
542    }
543    /// Declare (or replace) the critical severity policy.
544    pub fn critical(mut self, comparison: Comparison, threshold: f64) -> Self {
545        self.critical = Some(Severity {
546            comparison,
547            threshold,
548        });
549        self
550    }
551
552    /// Assemble + validate: window `1..=2_678_400`, interval `10..=86_400`,
553    /// delay 0..=600, failure/recovery thresholds 1..=100, at least one
554    /// severity, finite severity thresholds. Out-of-domain (int-range)
555    /// thresholds are the server's job — see the struct docs.
556    pub fn build(self) -> Result<Alert, String> {
557        let Self {
558            id,
559            metric_id,
560            description,
561            window_seconds,
562            evaluation_interval_seconds,
563            evaluation_delay_seconds,
564            group_match,
565            failure_threshold,
566            recovery_threshold,
567            enabled,
568            warning,
569            critical,
570        } = self;
571        let Some(window_seconds) = window_seconds else {
572            return Err(format!("metric threshold {id}: window_seconds is required"));
573        };
574        if !(1..=2_678_400).contains(&window_seconds) {
575            return Err(format!(
576                "metric threshold {id}: window_seconds must be 1..=2678400"
577            ));
578        }
579        let Some(evaluation_interval_seconds) = evaluation_interval_seconds else {
580            return Err(format!(
581                "metric threshold {id}: evaluation_interval_seconds is required"
582            ));
583        };
584        if !(10..=86_400).contains(&evaluation_interval_seconds) {
585            return Err(format!(
586                "metric threshold {id}: evaluation_interval_seconds must be 10..=86400"
587            ));
588        }
589        if evaluation_delay_seconds > 600 {
590            return Err(format!(
591                "metric threshold {id}: evaluation_delay_seconds must be 0..=600"
592            ));
593        }
594        for (label, value) in [
595            ("failure_threshold", failure_threshold),
596            ("recovery_threshold", recovery_threshold),
597        ] {
598            if !(1..=100).contains(&value) {
599                return Err(format!("metric threshold {id}: {label} must be 1..=100"));
600            }
601        }
602        if warning.is_none() && critical.is_none() {
603            return Err(format!(
604                "metric threshold {id}: at least one of warning or critical is required"
605            ));
606        }
607        for (label, policy) in [("warning", &warning), ("critical", &critical)] {
608            if let Some(policy) = policy
609                && !policy.threshold.is_finite()
610            {
611                return Err(format!(
612                    "metric threshold {id}: {label} threshold must be finite"
613                ));
614            }
615        }
616        Ok(Alert {
617            id,
618            metric_id,
619            description,
620            window_seconds,
621            evaluation_interval_seconds,
622            evaluation_delay_seconds,
623            group_match,
624            failure_threshold,
625            recovery_threshold,
626            enabled,
627            warning,
628            critical,
629        })
630    }
631}
632/// Scalar event property used in a metric filter.
633#[derive(Debug, Clone, PartialEq)]
634pub enum FilterValue {
635    Bool(bool),
636    Int(i64),
637    Float(f64),
638    Str(String),
639}
640
641impl From<bool> for FilterValue {
642    fn from(value: bool) -> Self {
643        Self::Bool(value)
644    }
645}
646impl From<i64> for FilterValue {
647    fn from(value: i64) -> Self {
648        Self::Int(value)
649    }
650}
651impl From<f64> for FilterValue {
652    fn from(value: f64) -> Self {
653        Self::Float(value)
654    }
655}
656impl From<&str> for FilterValue {
657    fn from(value: &str) -> Self {
658        Self::Str(value.to_owned())
659    }
660}
661impl From<String> for FilterValue {
662    fn from(value: String) -> Self {
663        Self::Str(value)
664    }
665}
666
667/// A metric with a stable ID and editable presentation metadata.
668#[derive(Debug, Clone, PartialEq)]
669pub struct Metric {
670    pub id: String,
671    pub display_name: Option<String>,
672    pub description: Option<String>,
673    pub unit: Option<String>,
674    pub query: MetricQuery,
675}
676/// The source and aggregation used by a metric.
677#[derive(Debug, Clone, PartialEq)]
678pub enum MetricQuery {
679    Telemetry(TelemetryMetric),
680    ProductEvent(ProductEventMetric),
681    Ratio(RatioMetric),
682}
683/// One declared metric divided by another, both in the same [`Declarations`].
684///
685#[derive(Debug, Clone, PartialEq, Eq)]
686pub struct RatioMetric {
687    pub numerator: String,
688    pub denominator: String,
689    pub numerator_window_seconds: Option<u64>,
690    pub denominator_window_seconds: Option<u64>,
691    pub as_percentage: bool,
692    pub preferred_bucket_seconds: Option<u64>,
693}
694/// Build a ratio metric over two other declared metrics.
695///
696/// Mirrors the Eyes ratio builder, except that `build` takes no result
697/// shapes or value types: [`Declarations::validate`] reads them from the
698/// two declared operands.
699#[derive(Debug)]
700#[must_use]
701pub struct RatioMetricBuilder {
702    id: String,
703    display_name: Option<String>,
704    description: Option<String>,
705    unit: Option<String>,
706    spec: RatioMetric,
707}
708impl RatioMetricBuilder {
709    pub fn new(
710        id: impl Into<String>,
711        numerator: impl Into<String>,
712        denominator: impl Into<String>,
713    ) -> Self {
714        Self {
715            id: id.into(),
716            display_name: None,
717            description: None,
718            unit: None,
719            spec: RatioMetric {
720                numerator: numerator.into(),
721                denominator: denominator.into(),
722                numerator_window_seconds: None,
723                denominator_window_seconds: None,
724                as_percentage: false,
725                preferred_bucket_seconds: None,
726            },
727        }
728    }
729    /// Trailing window of the numerator. Scalar and table ratios only.
730    pub fn numerator_window_seconds(mut self, seconds: u64) -> Self {
731        self.spec.numerator_window_seconds = Some(seconds);
732        self
733    }
734    /// Trailing window of the denominator. Scalar and table ratios only.
735    pub fn denominator_window_seconds(mut self, seconds: u64) -> Self {
736        self.spec.denominator_window_seconds = Some(seconds);
737        self
738    }
739    /// Multiply the value by 100 for display and thresholds. Forbids a unit.
740    pub fn as_percentage(mut self) -> Self {
741        self.spec.as_percentage = true;
742        self
743    }
744    pub fn display_name(mut self, v: impl Into<String>) -> Self {
745        self.display_name = Some(v.into());
746        self
747    }
748    pub fn description(mut self, v: impl Into<String>) -> Self {
749        self.description = Some(v.into());
750        self
751    }
752    pub fn unit(mut self, v: impl Into<String>) -> Self {
753        self.unit = Some(v.into());
754        self
755    }
756    pub fn preferred_bucket_seconds(mut self, v: u64) -> Self {
757        self.spec.preferred_bucket_seconds = Some(v);
758        self
759    }
760    /// Check the id grammar. The operands are checked by
761    /// [`Declarations::validate`], which can see them.
762    pub fn build(self) -> Result<Metric, String> {
763        if !valid_id(&self.id) {
764            return Err(format!("invalid metric id {:?}: {ID_RULE}", self.id));
765        }
766        Ok(Metric {
767            id: self.id,
768            display_name: self.display_name,
769            description: self.description,
770            unit: self.unit,
771            query: MetricQuery::Ratio(self.spec),
772        })
773    }
774}
775/// An Eyes telemetry query validated by the telemetry builder.
776#[derive(Debug, Clone, PartialEq)]
777pub struct TelemetryMetric(eyes::NamedMetric);
778impl TelemetryMetric {
779    pub(crate) fn named_metric(&self) -> &eyes::NamedMetric {
780        &self.0
781    }
782
783    #[cfg(test)]
784    pub(crate) fn named_metric_mut(&mut self) -> &mut eyes::NamedMetric {
785        &mut self.0
786    }
787}
788/// Build a span or log metric for the Eyes manifest.
789#[derive(Debug)]
790#[must_use]
791pub struct TelemetryMetricBuilder {
792    inner: eyes::NamedMetricBuilder,
793    filter_count: usize,
794    float_literals: Vec<(usize, eyes::eyes_query::FiniteF64)>,
795}
796impl From<FilterValue> for eyes::MetricFilterValue {
797    fn from(v: FilterValue) -> Self {
798        match v {
799            FilterValue::Int(x) => Self::Int(x),
800            FilterValue::Str(x) => Self::Str(x),
801            FilterValue::Bool(x) => Self::Bool(x),
802            FilterValue::Float(x) => Self::Float(x),
803        }
804    }
805}
806impl TelemetryMetricBuilder {
807    pub fn new(
808        id: impl Into<String>,
809        function: AggregateFunction,
810        argument: Option<&str>,
811    ) -> Result<Self, String> {
812        Ok(Self {
813            inner: eyes::NamedMetricBuilder::new(id, function, argument)?,
814            filter_count: 0,
815            float_literals: Vec::new(),
816        })
817    }
818    fn filter(
819        mut self,
820        path: &str,
821        operator: FilterOperator,
822        value: FilterValue,
823    ) -> Result<Self, String> {
824        // The Eyes builder validates using a serde round-trip. With serde_json's
825        // arbitrary_precision feature, serde's tagged-enum buffer cannot decode
826        // floats. Validate the same predicate with an integer operand, then
827        // restore its checked finite literal in the typed IR.
828        let operand = if let FilterValue::Float(number) = value {
829            self.float_literals
830                .push((self.filter_count, eyes::eyes_query::FiniteF64::new(number)?));
831            eyes::MetricFilterValue::Int(0)
832        } else {
833            value.into()
834        };
835        self.inner = match operator {
836            FilterOperator::Eq => self.inner.filter_eq(path, operand)?,
837            FilterOperator::Gte => self.inner.filter_gte(path, operand)?,
838        };
839        self.filter_count += 1;
840        Ok(self)
841    }
842    pub fn filter_eq(self, path: &str, value: impl Into<FilterValue>) -> Result<Self, String> {
843        self.filter(path, FilterOperator::Eq, value.into())
844    }
845    pub fn filter_gte(self, path: &str, value: impl Into<FilterValue>) -> Result<Self, String> {
846        self.filter(path, FilterOperator::Gte, value.into())
847    }
848    pub fn filter_numeric(self, path: &str) -> Result<Self, String> {
849        self.filter_gte(path, f64::MIN)
850    }
851    pub fn group_by(self, path: &str) -> Result<Self, String> {
852        Ok(Self {
853            inner: self.inner.group_by(path)?,
854            ..self
855        })
856    }
857    pub fn display_name(self, v: impl Into<String>) -> Self {
858        Self {
859            inner: self.inner.display_name(v),
860            ..self
861        }
862    }
863    pub fn description(self, v: impl Into<String>) -> Self {
864        Self {
865            inner: self.inner.description(v),
866            ..self
867        }
868    }
869    pub fn unit(self, v: impl Into<String>) -> Self {
870        Self {
871            inner: self.inner.unit(v),
872            ..self
873        }
874    }
875    pub fn value_type(self, v: MetricValueType) -> Self {
876        Self {
877            inner: self.inner.value_type(v),
878            ..self
879        }
880    }
881    pub fn preferred_bucket_seconds(self, v: u64) -> Self {
882        Self {
883            inner: self.inner.preferred_bucket_seconds(v),
884            ..self
885        }
886    }
887    pub fn time_bucket(self, v: u64) -> Self {
888        Self {
889            inner: self.inner.time_bucket(v),
890            ..self
891        }
892    }
893    pub fn time_bucket_weeks(self, v: u32) -> Self {
894        Self {
895            inner: self.inner.time_bucket_weeks(v),
896            ..self
897        }
898    }
899    fn build_eyes(self) -> Result<eyes::NamedMetric, String> {
900        use eyes::eyes_query::{Expr, Literal, Stage};
901        let mut metric = self.inner.build()?;
902        for (index, number) in self.float_literals {
903            let stage = metric
904                .query
905                .as_mut()
906                .and_then(|doc| doc.query.stages.get_mut(index));
907            let Some(Stage::Where {
908                predicate: Expr::Binary { right, .. },
909            }) = stage
910            else {
911                return Err(format!(
912                    "metric {}: missing filter stage {index}",
913                    metric.id
914                ));
915            };
916            **right = Expr::Literal {
917                value: Literal::Float(number),
918            };
919        }
920        Ok(metric)
921    }
922    pub fn build(self) -> Result<Metric, String> {
923        let m = self.build_eyes()?;
924        Ok(Metric {
925            id: m.id.clone(),
926            display_name: m.display_name.clone(),
927            description: m.description.clone(),
928            unit: m.unit.clone(),
929            query: MetricQuery::Telemetry(TelemetryMetric(m)),
930        })
931    }
932}
933
934/// One predicate applied to the event series in both sinks.
935#[derive(Debug, Clone, PartialEq)]
936pub struct PropertyFilter {
937    pub property: String,
938    pub operator: FilterOperator,
939    pub value: FilterValue,
940}
941/// Comparison operators shared by the Eyes and product-event backends.
942#[derive(Debug, Clone, Copy, PartialEq, Eq)]
943pub enum FilterOperator {
944    Eq,
945    Gte,
946}
947/// A single event series with optional property aggregation, filters and grouping.
948#[derive(Debug, Clone, PartialEq)]
949pub struct ProductEventMetric {
950    pub event: String,
951    pub aggregate: ProductAggregate,
952    pub property_filters: Vec<PropertyFilter>,
953    pub breakdown_property: Option<String>,
954    pub bucket: Option<Bucket>,
955}
956/// Width of one time bucket of a product metric.
957#[derive(Debug, Clone, Copy, PartialEq, Eq)]
958pub enum Bucket {
959    /// Epoch-aligned buckets this many seconds wide.
960    Seconds(u64),
961    /// Monday-aligned buckets this many weeks wide (1 to 4).
962    Weeks(u32),
963}
964/// Aggregation over matching product events.
965#[derive(Debug, Clone, PartialEq)]
966pub enum ProductAggregate {
967    Count,
968    DistinctUsers,
969    Sum { property: String },
970    Avg { property: String },
971    Min { property: String },
972    Max { property: String },
973    Median { property: String },
974    P90 { property: String },
975    P95 { property: String },
976    P99 { property: String },
977}
978/// Build a product metric shared by Eyes and `PostHog`.
979#[derive(Debug)]
980#[must_use]
981pub struct ProductMetricBuilder {
982    id: String,
983    display_name: Option<String>,
984    description: Option<String>,
985    unit: Option<String>,
986    spec: ProductEventMetric,
987}
988impl ProductMetricBuilder {
989    fn new(id: impl Into<String>, event: impl Into<String>, aggregate: ProductAggregate) -> Self {
990        Self {
991            id: id.into(),
992            display_name: None,
993            description: None,
994            unit: None,
995            spec: ProductEventMetric {
996                event: event.into(),
997                aggregate,
998                property_filters: vec![],
999                breakdown_property: None,
1000                bucket: None,
1001            },
1002        }
1003    }
1004    pub fn count(id: impl Into<String>, event: impl Into<String>) -> Self {
1005        Self::new(id, event, ProductAggregate::Count)
1006    }
1007    pub fn distinct_users(id: impl Into<String>, event: impl Into<String>) -> Self {
1008        Self::new(id, event, ProductAggregate::DistinctUsers)
1009    }
1010    pub fn sum(
1011        id: impl Into<String>,
1012        event: impl Into<String>,
1013        property: impl Into<String>,
1014    ) -> Self {
1015        Self::new(
1016            id,
1017            event,
1018            ProductAggregate::Sum {
1019                property: property.into(),
1020            },
1021        )
1022    }
1023    pub fn avg(
1024        id: impl Into<String>,
1025        event: impl Into<String>,
1026        property: impl Into<String>,
1027    ) -> Self {
1028        Self::new(
1029            id,
1030            event,
1031            ProductAggregate::Avg {
1032                property: property.into(),
1033            },
1034        )
1035    }
1036    pub fn min(
1037        id: impl Into<String>,
1038        event: impl Into<String>,
1039        property: impl Into<String>,
1040    ) -> Self {
1041        Self::new(
1042            id,
1043            event,
1044            ProductAggregate::Min {
1045                property: property.into(),
1046            },
1047        )
1048    }
1049    pub fn max(
1050        id: impl Into<String>,
1051        event: impl Into<String>,
1052        property: impl Into<String>,
1053    ) -> Self {
1054        Self::new(
1055            id,
1056            event,
1057            ProductAggregate::Max {
1058                property: property.into(),
1059            },
1060        )
1061    }
1062    pub fn median(
1063        id: impl Into<String>,
1064        event: impl Into<String>,
1065        property: impl Into<String>,
1066    ) -> Self {
1067        Self::new(
1068            id,
1069            event,
1070            ProductAggregate::Median {
1071                property: property.into(),
1072            },
1073        )
1074    }
1075    pub fn p90(
1076        id: impl Into<String>,
1077        event: impl Into<String>,
1078        property: impl Into<String>,
1079    ) -> Self {
1080        Self::new(
1081            id,
1082            event,
1083            ProductAggregate::P90 {
1084                property: property.into(),
1085            },
1086        )
1087    }
1088    pub fn p95(
1089        id: impl Into<String>,
1090        event: impl Into<String>,
1091        property: impl Into<String>,
1092    ) -> Self {
1093        Self::new(
1094            id,
1095            event,
1096            ProductAggregate::P95 {
1097                property: property.into(),
1098            },
1099        )
1100    }
1101    pub fn p99(
1102        id: impl Into<String>,
1103        event: impl Into<String>,
1104        property: impl Into<String>,
1105    ) -> Self {
1106        Self::new(
1107            id,
1108            event,
1109            ProductAggregate::P99 {
1110                property: property.into(),
1111            },
1112        )
1113    }
1114    pub fn display_name(mut self, v: impl Into<String>) -> Self {
1115        self.display_name = Some(v.into());
1116        self
1117    }
1118    pub fn description(mut self, v: impl Into<String>) -> Self {
1119        self.description = Some(v.into());
1120        self
1121    }
1122    pub fn unit(mut self, v: impl Into<String>) -> Self {
1123        self.unit = Some(v.into());
1124        self
1125    }
1126
1127    pub fn filter(
1128        mut self,
1129        property: impl Into<String>,
1130        operator: FilterOperator,
1131        value: impl Into<FilterValue>,
1132    ) -> Self {
1133        self.spec.property_filters.push(PropertyFilter {
1134            property: property.into(),
1135            operator,
1136            value: value.into(),
1137        });
1138        self
1139    }
1140    pub fn breakdown(mut self, property: impl Into<String>) -> Self {
1141        self.spec.breakdown_property = Some(property.into());
1142        self
1143    }
1144    /// Epoch-aligned buckets. Replaces any earlier bucket choice.
1145    pub fn bucket_seconds(mut self, seconds: u64) -> Self {
1146        self.spec.bucket = Some(Bucket::Seconds(seconds));
1147        self
1148    }
1149    /// Monday-aligned calendar weeks, 1 to 4 wide. Replaces any earlier
1150    /// bucket choice. `PostHog` charts these at its `week` interval.
1151    pub fn bucket_weeks(mut self, weeks: u32) -> Self {
1152        self.spec.bucket = Some(Bucket::Weeks(weeks));
1153        self
1154    }
1155    pub fn build(self) -> Result<Metric, String> {
1156        let metric = Metric {
1157            id: self.id,
1158            display_name: self.display_name,
1159            description: self.description,
1160            unit: self.unit,
1161            query: MetricQuery::ProductEvent(self.spec),
1162        };
1163        metric.eyes()?;
1164        Ok(metric)
1165    }
1166}
1167fn name(v: &str) -> Result<&str, String> {
1168    if v.trim().is_empty() || v.contains('.') {
1169        Err(format!("invalid event or property name {v:?}"))
1170    } else {
1171        Ok(v)
1172    }
1173}
1174impl ProductAggregate {
1175    pub(super) fn parts(&self) -> (AggregateFunction, &'static str, Option<&str>) {
1176        match self {
1177            Self::Count => (AggregateFunction::Count, "total", None),
1178            Self::DistinctUsers => (AggregateFunction::CountDistinct, "dau", None),
1179            Self::Sum { property } => (AggregateFunction::Sum, "sum", Some(property)),
1180            Self::Avg { property } => (AggregateFunction::Avg, "avg", Some(property)),
1181            Self::Min { property } => (AggregateFunction::Min, "min", Some(property)),
1182            Self::Max { property } => (AggregateFunction::Max, "max", Some(property)),
1183            Self::Median { property } => (AggregateFunction::P50, "median", Some(property)),
1184            Self::P90 { property } => (AggregateFunction::P90, "p90", Some(property)),
1185            Self::P95 { property } => (AggregateFunction::P95, "p95", Some(property)),
1186            Self::P99 { property } => (AggregateFunction::P99, "p99", Some(property)),
1187        }
1188    }
1189}
1190
1191impl RatioMetric {
1192    /// Exactly what the Eyes ratio builder produces for the same inputs,
1193    /// with the shapes and value types read from the declared operands.
1194    fn eyes(
1195        &self,
1196        metric: &Metric,
1197        singular: &std::collections::HashMap<&str, eyes::NamedMetric>,
1198    ) -> Result<eyes::NamedMetric, String> {
1199        let side = |label: &str, id: &str| {
1200            singular.get(id).ok_or_else(|| {
1201                format!(
1202                    "ratio metric {}: {label} {id:?} is not a declared telemetry or product metric",
1203                    metric.id
1204                )
1205            })
1206        };
1207        let numerator = side("numerator", &self.numerator)?;
1208        let denominator = side("denominator", &self.denominator)?;
1209        let mut b = eyes::RatioMetricBuilder::new(&metric.id, &self.numerator, &self.denominator);
1210        if let Some(v) = self.numerator_window_seconds {
1211            b = b.numerator_window_seconds(v);
1212        }
1213        if let Some(v) = self.denominator_window_seconds {
1214            b = b.denominator_window_seconds(v);
1215        }
1216        if self.as_percentage {
1217            b = b.as_percentage();
1218        }
1219        if let Some(v) = &metric.display_name {
1220            b = b.display_name(v);
1221        }
1222        if let Some(v) = &metric.description {
1223            b = b.description(v);
1224        }
1225        if let Some(v) = &metric.unit {
1226            b = b.unit(v);
1227        }
1228        if let Some(v) = self.preferred_bucket_seconds {
1229            b = b.preferred_bucket_seconds(v);
1230        }
1231        b.build(
1232            numerator.result_shape,
1233            numerator.value_type,
1234            denominator.result_shape,
1235            denominator.value_type,
1236        )
1237    }
1238}
1239
1240impl Metric {
1241    /// Convert a telemetry or product metric. A ratio needs its operands,
1242    /// so it converts through [`Declarations::eyes_metrics`] instead.
1243    fn eyes(&self) -> Result<eyes::NamedMetric, String> {
1244        if !valid_id(&self.id) {
1245            return Err(format!("invalid metric id {:?}: {ID_RULE}", self.id));
1246        }
1247        let mut m = match &self.query {
1248            MetricQuery::Ratio(_) => {
1249                return Err(format!(
1250                    "ratio metric {} converts only as part of its declarations",
1251                    self.id
1252                ));
1253            }
1254            MetricQuery::Telemetry(m) => m.0.clone(),
1255            MetricQuery::ProductEvent(p) => {
1256                let (function, _, property) = p.aggregate.parts();
1257                let field = property
1258                    .map(|p| name(p).map(|p| format!("fields.{p}")))
1259                    .transpose()?;
1260                let arg = if matches!(p.aggregate, ProductAggregate::DistinctUsers) {
1261                    Some("fields.user_id")
1262                } else {
1263                    field.as_deref()
1264                };
1265                let mut b = TelemetryMetricBuilder::new(&self.id, function, arg)?
1266                    .filter_eq("fields.event_type", name(&p.event)?)?;
1267                if let Some(path) = field {
1268                    b = b.filter_numeric(&path)?;
1269                }
1270                for f in &p.property_filters {
1271                    let path = format!("fields.{}", name(&f.property)?);
1272                    let v = f.value.clone();
1273                    b = match f.operator {
1274                        FilterOperator::Eq => b.filter_eq(&path, v)?,
1275                        FilterOperator::Gte => b.filter_gte(&path, v)?,
1276                    };
1277                }
1278                if let Some(p) = &p.breakdown_property {
1279                    b = b.group_by(&format!("fields.{}", name(p)?))?;
1280                }
1281                b = match p.bucket {
1282                    Some(Bucket::Seconds(n)) => b.time_bucket(n),
1283                    Some(Bucket::Weeks(n)) => b.time_bucket_weeks(n),
1284                    None => b,
1285                };
1286                b.build_eyes()?
1287            }
1288        };
1289        m.id.clone_from(&self.id);
1290        m.display_name.clone_from(&self.display_name);
1291        m.description.clone_from(&self.description);
1292        m.unit.clone_from(&self.unit);
1293        Ok(m)
1294    }
1295}
1296
1297impl Item {
1298    pub(super) fn reference(&self) -> Option<(&str, eyes::MetricResultShape)> {
1299        use eyes::MetricResultShape::{Scalar, Table, TimeSeries};
1300        match self {
1301            Self::Stat { metric_id, .. } => Some((metric_id, Scalar)),
1302            Self::TimeSeries { metric_id, .. } => Some((metric_id, TimeSeries)),
1303            Self::Table { metric_id, .. } => Some((metric_id, Table)),
1304            Self::HealthSummary { .. } | Self::Links { .. } => None,
1305        }
1306    }
1307    fn eyes(self) -> Result<eyes::DashboardItem, String> {
1308        use eyes::DashboardItem as E;
1309        Ok(match self {
1310            Self::Stat {
1311                metric_id,
1312                label,
1313                unit,
1314                window_seconds,
1315            } => E::Stat {
1316                query_id: metric_id,
1317                label,
1318                unit,
1319                window_seconds,
1320            },
1321            Self::Table {
1322                metric_id,
1323                label,
1324                unit,
1325                window_seconds,
1326            } => E::Table {
1327                query_id: metric_id,
1328                label,
1329                unit,
1330                window_seconds,
1331            },
1332            Self::TimeSeries {
1333                metric_id,
1334                label,
1335                unit,
1336                window_seconds,
1337                preferred_bucket_seconds,
1338            } => E::TimeSeries {
1339                query_id: metric_id,
1340                label,
1341                unit,
1342                window_seconds,
1343                preferred_bucket_seconds,
1344            },
1345            Self::HealthSummary { label } => E::HealthSummary { label },
1346            Self::Links { links } => E::Links {
1347                links: links
1348                    .into_iter()
1349                    .map(|l| eyes::DashboardLink::new(l.label, l.href))
1350                    .collect::<Result<_, _>>()?,
1351            },
1352        })
1353    }
1354}
1355impl Dashboard {
1356    fn eyes(&self) -> Result<eyes::NamedDashboard, String> {
1357        let mut d = eyes::NamedDashboard::new(&self.id, &self.title)?;
1358        d.description.clone_from(&self.description);
1359        d.default_range_seconds = self.default_range_seconds;
1360        for s in &self.sections {
1361            d.sections.push(eyes::DashboardSection {
1362                title: s.title.clone(),
1363                description: s.description.clone(),
1364                items: s
1365                    .items
1366                    .iter()
1367                    .cloned()
1368                    .map(Item::eyes)
1369                    .collect::<Result<_, _>>()?,
1370            });
1371        }
1372        Ok(d)
1373    }
1374}
1375impl Alert {
1376    fn eyes(&self) -> Result<eyes::MetricThreshold, String> {
1377        let mut b = eyes::MetricThresholdBuilder::new(&self.id, &self.metric_id)
1378            .window_seconds(self.window_seconds)
1379            .evaluation_interval_seconds(self.evaluation_interval_seconds)
1380            .evaluation_delay_seconds(self.evaluation_delay_seconds)
1381            .failure_threshold(self.failure_threshold)
1382            .recovery_threshold(self.recovery_threshold)
1383            .enabled(self.enabled)
1384            .group_match(match self.group_match {
1385                GroupMatch::Any => eyes::ThresholdGroupMatch::Any,
1386                GroupMatch::All => eyes::ThresholdGroupMatch::All,
1387            });
1388        if let Some(v) = &self.description {
1389            b = b.description(v);
1390        }
1391        let comparison = |c| match c {
1392            Comparison::Above => eyes::ThresholdComparison::Above,
1393            Comparison::Below => eyes::ThresholdComparison::Below,
1394        };
1395        if let Some(v) = &self.warning {
1396            b = b.warning(comparison(v.comparison), v.threshold);
1397        }
1398        if let Some(v) = &self.critical {
1399            b = b.critical(comparison(v.comparison), v.threshold);
1400        }
1401        b.build()
1402    }
1403}
1404/// One application's declared dashboards, metrics and alerts.
1405#[derive(Debug, Clone, Default, PartialEq)]
1406#[must_use]
1407pub struct Declarations {
1408    pub metrics: Vec<Metric>,
1409    pub dashboards: Vec<Dashboard>,
1410    pub alerts: Vec<Alert>,
1411}
1412impl Declarations {
1413    pub fn new() -> Self {
1414        Self::default()
1415    }
1416    pub fn metric(mut self, m: Metric) -> Self {
1417        self.metrics.push(m);
1418        self
1419    }
1420    pub fn dashboard(mut self, d: Dashboard) -> Self {
1421        self.dashboards.push(d);
1422        self
1423    }
1424    pub fn alert(mut self, a: Alert) -> Self {
1425        self.alerts.push(a);
1426        self
1427    }
1428    /// Convert every metric for the Eyes manifest, in declaration order.
1429    /// Rejects duplicate ids and ratios whose operands are missing, are
1430    /// ratios themselves, or pair incompatible shapes.
1431    fn eyes_metrics(&self) -> Result<Vec<eyes::NamedMetric>, String> {
1432        use std::collections::{HashMap, HashSet};
1433        let mut ids = HashSet::new();
1434        let mut singular = HashMap::new();
1435        for m in &self.metrics {
1436            if !ids.insert(m.id.as_str()) {
1437                return Err(format!("duplicate metric {}", m.id));
1438            }
1439            if !matches!(m.query, MetricQuery::Ratio(_)) {
1440                singular.insert(m.id.as_str(), m.eyes()?);
1441            }
1442        }
1443        self.metrics
1444            .iter()
1445            .map(|m| match &m.query {
1446                MetricQuery::Ratio(ratio) => {
1447                    if !valid_id(&m.id) {
1448                        return Err(format!("invalid metric id {:?}: {ID_RULE}", m.id));
1449                    }
1450                    ratio.eyes(m, &singular)
1451                }
1452                _ => singular
1453                    .get(m.id.as_str())
1454                    .cloned()
1455                    .ok_or_else(|| format!("metric {} did not convert", m.id)),
1456            })
1457            .collect()
1458    }
1459    /// Check declaration identities, references, result shapes and manifest limits.
1460    pub fn validate(&self) -> Result<(), String> {
1461        use std::collections::{HashMap, HashSet};
1462        if self.metrics.len() > 100 || self.dashboards.len() > 20 {
1463            return Err("manifest exceeds 100 metrics or 20 dashboards".into());
1464        }
1465        let converted = self.eyes_metrics()?;
1466        let singular = converted
1467            .iter()
1468            .filter(|m| m.ratio.is_none())
1469            .map(|m| (m.id.as_str(), m))
1470            .collect::<HashMap<_, _>>();
1471        for metric in &self.metrics {
1472            let MetricQuery::Ratio(ratio) = &metric.query else {
1473                continue;
1474            };
1475            let numerator = singular.get(ratio.numerator.as_str()).ok_or_else(|| {
1476                format!(
1477                    "ratio {} has missing numerator {}",
1478                    metric.id, ratio.numerator
1479                )
1480            })?;
1481            let denominator = singular.get(ratio.denominator.as_str()).ok_or_else(|| {
1482                format!(
1483                    "ratio {} has missing denominator {}",
1484                    metric.id, ratio.denominator
1485                )
1486            })?;
1487            let (num_groups, num_bucket) = ratio_groups(numerator);
1488            let (den_groups, den_bucket) = ratio_groups(denominator);
1489            let compatible = match (numerator.result_shape, denominator.result_shape) {
1490                (eyes::MetricResultShape::TimeSeries, eyes::MetricResultShape::TimeSeries) => {
1491                    num_bucket.is_some()
1492                        && num_bucket == den_bucket
1493                        && num_groups
1494                            .iter()
1495                            .map(|g| &g.alias)
1496                            .eq(den_groups.iter().map(|g| &g.alias))
1497                        && num_groups.get(1..) == den_groups.get(1..)
1498                }
1499                (eyes::MetricResultShape::Table, eyes::MetricResultShape::Table) => {
1500                    num_groups == den_groups
1501                }
1502                _ => true,
1503            };
1504            if !compatible {
1505                return Err(format!(
1506                    "ratio {} operands {} and {} have incompatible buckets or groups",
1507                    metric.id, ratio.numerator, ratio.denominator
1508                ));
1509            }
1510        }
1511        let shapes = converted
1512            .iter()
1513            .map(|m| (m.id.as_str(), m.result_shape))
1514            .collect::<HashMap<_, _>>();
1515        let mut ids = HashSet::new();
1516        for a in &self.alerts {
1517            if !valid_id(&a.id) {
1518                return Err(format!("invalid alert id {:?}: {ID_RULE}", a.id));
1519            }
1520            if !ids.insert(&a.id) {
1521                return Err(format!("duplicate alert {}", a.id));
1522            }
1523            if !shapes.contains_key(a.metric_id.as_str()) {
1524                return Err(format!(
1525                    "alert {}: metric {} is not declared",
1526                    a.id, a.metric_id
1527                ));
1528            }
1529            a.eyes()?;
1530        }
1531        ids.clear();
1532        for d in &self.dashboards {
1533            if !valid_id(&d.id) {
1534                return Err(format!("invalid dashboard id {:?}: {ID_RULE}", d.id));
1535            }
1536            if !ids.insert(&d.id) || d.sections.len() > 20 {
1537                return Err(format!("duplicate or oversized dashboard {}", d.id));
1538            }
1539            for s in &d.sections {
1540                if s.items.len() > 24 {
1541                    return Err(format!("too many items on {}", d.id));
1542                }
1543                for item in &s.items {
1544                    if let Some((id, shape)) = item.reference()
1545                        && shapes.get(id) != Some(&shape)
1546                    {
1547                        return Err(format!(
1548                            "{}: missing metric or incompatible shape for {id}",
1549                            d.id
1550                        ));
1551                    }
1552                }
1553            }
1554            d.eyes()?;
1555        }
1556        Ok(())
1557    }
1558    /// Populate the three declaration lists while preserving other manifest fields.
1559    pub fn attach_to_eyes_manifest(
1560        self,
1561        manifest: eyes::AppManifest,
1562    ) -> Result<eyes::AppManifest, String> {
1563        self.validate()?;
1564        Ok(manifest
1565            .metrics(self.eyes_metrics()?)
1566            .metric_thresholds(
1567                self.alerts
1568                    .iter()
1569                    .map(Alert::eyes)
1570                    .collect::<Result<_, _>>()?,
1571            )
1572            .dashboards(
1573                self.dashboards
1574                    .iter()
1575                    .map(Dashboard::eyes)
1576                    .collect::<Result<_, _>>()?,
1577            ))
1578    }
1579}
1580
1581#[cfg(test)]
1582mod tests {
1583    use super::*;
1584    #[test]
1585    fn both_sinks_validate_the_same_shapes() {
1586        let mut metric =
1587            TelemetryMetricBuilder::new("old", AggregateFunction::P95, Some("fields.duration"))
1588                .unwrap()
1589                .filter_eq("fields.semantic_kind", "request")
1590                .unwrap()
1591                .time_bucket(300)
1592                .unit("ms")
1593                .build()
1594                .unwrap();
1595        metric.id = "latency".into();
1596        metric.display_name = Some("Latency".into());
1597        let dashboard = Dashboard::new("ops", "Ops")
1598            .unwrap()
1599            .default_range_seconds(300)
1600            .section(
1601                Section::new()
1602                    .description("Latency percentiles")
1603                    .item(Item::time_series("latency")),
1604            );
1605        let alert = AlertBuilder::new("slow", "latency")
1606            .window_seconds(300)
1607            .evaluation_interval_seconds(60)
1608            .critical(Comparison::Above, 100.)
1609            .build()
1610            .unwrap();
1611        let mut d = Declarations::new()
1612            .metric(metric)
1613            .dashboard(dashboard)
1614            .alert(alert);
1615        let manifest = d
1616            .clone()
1617            .attach_to_eyes_manifest(eyes::AppManifest::default())
1618            .unwrap();
1619        assert_eq!(manifest.metrics.as_ref().unwrap()[0].id, "latency");
1620        assert_eq!(
1621            manifest.metrics.as_ref().unwrap()[0]
1622                .display_name
1623                .as_deref(),
1624            Some("Latency")
1625        );
1626        assert_eq!(
1627            manifest.metrics.as_ref().unwrap()[0].unit.as_deref(),
1628            Some("ms")
1629        );
1630        assert_eq!(
1631            manifest.metrics.as_ref().unwrap()[0].result_shape,
1632            eyes::MetricResultShape::TimeSeries
1633        );
1634        assert_eq!(
1635            manifest.dashboards.as_ref().unwrap()[0].default_range_seconds,
1636            Some(300)
1637        );
1638        assert_eq!(
1639            manifest.dashboards.as_ref().unwrap()[0].sections[0]
1640                .description
1641                .as_deref(),
1642            Some("Latency percentiles")
1643        );
1644        assert_eq!(
1645            manifest.metric_thresholds.as_ref().unwrap()[0].metric_id,
1646            "latency"
1647        );
1648        d.dashboards[0].sections[0].items[0] = Item::stat("latency");
1649        assert!(d.validate().is_err());
1650    }
1651    #[test]
1652    fn product_names_caps_and_refs() {
1653        for bad in ["", "a.b"] {
1654            assert!(ProductMetricBuilder::count("m", bad).build().is_err());
1655            assert!(
1656                ProductMetricBuilder::sum("m", "event", bad)
1657                    .build()
1658                    .is_err()
1659            );
1660        }
1661        let mut d = Declarations::new();
1662        for i in 0..100 {
1663            d.metrics.push(
1664                ProductMetricBuilder::count(format!("m{i}"), "e")
1665                    .build()
1666                    .unwrap(),
1667            );
1668        }
1669        d.validate().unwrap();
1670        d.metrics
1671            .push(ProductMetricBuilder::count("extra", "e").build().unwrap());
1672        assert!(d.validate().is_err());
1673        d.metrics.pop();
1674        d.metrics[0].id = "m1".into();
1675        assert!(d.validate().is_err());
1676    }
1677}
1678
1679#[cfg(test)]
1680mod product_tests {
1681    use super::*;
1682    #[test]
1683    fn product_queries_match_the_emission_fields() {
1684        let product = ProductMetricBuilder::sum("orders", "placed", "amount")
1685            .filter("tier", FilterOperator::Eq, "pro")
1686            .filter("units", FilterOperator::Gte, 3_i64)
1687            .breakdown("region")
1688            .build()
1689            .unwrap();
1690        let expected =
1691            eyes::NamedMetricBuilder::new("orders", AggregateFunction::Sum, Some("fields.amount"))
1692                .unwrap()
1693                .filter_eq("fields.event_type", "placed")
1694                .unwrap()
1695                .filter_gte("fields.amount", 0_i64)
1696                .unwrap()
1697                .filter_eq("fields.tier", "pro")
1698                .unwrap()
1699                .filter_gte("fields.units", 3_i64)
1700                .unwrap()
1701                .group_by("fields.region")
1702                .unwrap()
1703                .build()
1704                .unwrap();
1705        let mut expected_json = serde_json::to_value(expected).unwrap();
1706        expected_json["query"]["query"]["stages"][1]["predicate"]["right"]["value"] =
1707            serde_json::json!({"type":"float","value":f64::MIN});
1708        assert_eq!(
1709            serde_json::to_value(product.eyes().unwrap()).unwrap(),
1710            expected_json
1711        );
1712    }
1713    #[test]
1714    fn invalid_alert_policies() {
1715        let builder = || {
1716            AlertBuilder::new("alert", "count")
1717                .window_seconds(60)
1718                .evaluation_interval_seconds(10)
1719        };
1720        assert!(builder().build().is_err());
1721        assert!(
1722            builder()
1723                .critical(Comparison::Above, f64::NAN)
1724                .build()
1725                .is_err()
1726        );
1727        for (window, ok) in [(0, false), (1, true), (2_678_400, true), (2_678_401, false)] {
1728            assert_eq!(
1729                builder()
1730                    .window_seconds(window)
1731                    .warning(Comparison::Below, 3.)
1732                    .build()
1733                    .is_ok(),
1734                ok
1735            );
1736        }
1737    }
1738}
1739
1740#[cfg(test)]
1741mod parity_tests {
1742    use super::*;
1743    use serde_json::to_value;
1744
1745    const DAY: u64 = 86_400;
1746    const FOUR_WEEKS: u64 = 2_419_200;
1747
1748    fn eyes_users(id: &str) -> eyes::NamedMetric {
1749        eyes::NamedMetricBuilder::new(id, AggregateFunction::CountDistinct, Some("fields.user_id"))
1750            .unwrap()
1751            .display_name("Users")
1752            .filter_eq("target", "cja::server::trace")
1753            .unwrap()
1754            .filter_eq("message", "finished processing request")
1755            .unwrap()
1756            .unit("users")
1757            .build()
1758            .unwrap()
1759    }
1760    fn users(id: &str) -> Metric {
1761        TelemetryMetricBuilder::new(id, AggregateFunction::CountDistinct, Some("fields.user_id"))
1762            .unwrap()
1763            .display_name("Users")
1764            .filter_eq("target", "cja::server::trace")
1765            .unwrap()
1766            .filter_eq("message", "finished processing request")
1767            .unwrap()
1768            .unit("users")
1769            .build()
1770            .unwrap()
1771    }
1772    fn stickiness() -> RatioMetricBuilder {
1773        RatioMetricBuilder::new(
1774            "product.users.active.stickiness.daily",
1775            "product.users.active",
1776            "product.users.active.month",
1777        )
1778        .numerator_window_seconds(DAY)
1779        .denominator_window_seconds(FOUR_WEEKS)
1780        .as_percentage()
1781        .display_name("Users: last 1 day as % of last 28 days")
1782        .description("Distinct users in the last day as a percentage of the last 28 days.")
1783    }
1784    /// Two telemetry metrics, a ratio over them and a stat tile on the
1785    /// ratio, as arena's `arena-product` dashboard declares them.
1786    fn arena_shaped() -> Declarations {
1787        Declarations::new()
1788            .metric(users("product.users.active"))
1789            .metric(users("product.users.active.month"))
1790            .metric(stickiness().build().unwrap())
1791            .dashboard(
1792                Dashboard::new("arena-product", "Arena product")
1793                    .unwrap()
1794                    .section(
1795                        Section::new().title("Engagement").item(
1796                            Item::stat("product.users.active.stickiness.daily")
1797                                .label("DAU / MAU")
1798                                .window_seconds(DAY),
1799                        ),
1800                    ),
1801            )
1802    }
1803
1804    #[test]
1805    fn ratio_metric_converts_to_exactly_the_eyes_ratio_builder_output() {
1806        let mut declarations = arena_shaped();
1807        declarations.metrics[2] = RatioMetricBuilder::new(
1808            "product.users.active.stickiness.daily",
1809            "product.users.active",
1810            "product.users.active.month",
1811        )
1812        .numerator_window_seconds(DAY)
1813        .denominator_window_seconds(FOUR_WEEKS)
1814        .unit("ratio")
1815        .preferred_bucket_seconds(300)
1816        .display_name("Users: last 1 day as fraction of last 28 days")
1817        .description("Distinct users in the last day divided by the last 28 days.")
1818        .build()
1819        .unwrap();
1820        declarations.validate().unwrap();
1821        let manifest = declarations
1822            .attach_to_eyes_manifest(eyes::AppManifest::default())
1823            .unwrap();
1824        let metrics = manifest.metrics.unwrap();
1825        let expected = eyes::RatioMetricBuilder::new(
1826            "product.users.active.stickiness.daily",
1827            "product.users.active",
1828            "product.users.active.month",
1829        )
1830        .numerator_window_seconds(DAY)
1831        .denominator_window_seconds(FOUR_WEEKS)
1832        .unit("ratio")
1833        .preferred_bucket_seconds(300)
1834        .display_name("Users: last 1 day as fraction of last 28 days")
1835        .description("Distinct users in the last day divided by the last 28 days.")
1836        .build(
1837            eyes::MetricResultShape::Scalar,
1838            MetricValueType::Int,
1839            eyes::MetricResultShape::Scalar,
1840            MetricValueType::Int,
1841        )
1842        .unwrap();
1843        assert_eq!(expected.unit.as_deref(), Some("ratio"));
1844        assert_eq!(expected.preferred_bucket_seconds, Some(300));
1845        let wire = to_value(&expected).unwrap();
1846        assert_eq!(wire["unit"], "ratio");
1847        assert_eq!(wire["preferred_bucket_seconds"], 300);
1848        assert_eq!(
1849            to_value(&metrics).unwrap(),
1850            to_value([
1851                eyes_users("product.users.active"),
1852                eyes_users("product.users.active.month"),
1853                expected,
1854            ])
1855            .unwrap()
1856        );
1857        assert_eq!(
1858            to_value(&manifest.dashboards.unwrap()[0].sections[0].items[0]).unwrap(),
1859            to_value(
1860                eyes::DashboardItem::stat("product.users.active.stickiness.daily")
1861                    .label("DAU / MAU")
1862                    .window_seconds(DAY)
1863            )
1864            .unwrap()
1865        );
1866    }
1867
1868    #[test]
1869    fn ratio_operands_must_be_declared_singular_metrics() {
1870        let with = |ratio: RatioMetricBuilder| {
1871            let mut declarations = arena_shaped();
1872            declarations.metrics[2] = ratio.build().unwrap();
1873            declarations.validate()
1874        };
1875        let id = "product.users.active.stickiness.daily";
1876        let error = with(RatioMetricBuilder::new(
1877            id,
1878            "missing",
1879            "product.users.active.month",
1880        ))
1881        .unwrap_err();
1882        assert!(error.contains("numerator \"missing\""), "{error}");
1883        let error = with(RatioMetricBuilder::new(
1884            id,
1885            "product.users.active",
1886            "missing",
1887        ))
1888        .unwrap_err();
1889        assert!(error.contains("denominator \"missing\""), "{error}");
1890        // A ratio cannot be the side of a ratio, itself included.
1891        let error = with(RatioMetricBuilder::new(id, "product.users.active", id)).unwrap_err();
1892        assert!(error.contains("denominator"), "{error}");
1893        // The Eyes builder's own rules still apply.
1894        assert!(with(stickiness().unit("users")).is_err());
1895        assert!(
1896            with(RatioMetricBuilder::new(
1897                id,
1898                "product.users.active",
1899                "product.users.active"
1900            ))
1901            .is_err()
1902        );
1903        // A time-series tile needs a time-series ratio.
1904        let mut declarations = arena_shaped();
1905        declarations.dashboards[0].sections[0].items[0] = Item::time_series(id);
1906        assert!(declarations.validate().is_err());
1907    }
1908
1909    #[test]
1910    fn ids_must_be_lowercase() {
1911        let mut declarations = arena_shaped();
1912        declarations.metrics[0].id = "product.Users.active".into();
1913        let error = declarations.validate().unwrap_err();
1914        assert!(error.contains("invalid metric id"), "{error}");
1915
1916        let mut declarations = arena_shaped();
1917        declarations.metrics[2].id = "Stickiness".into();
1918        declarations.dashboards[0].sections.clear();
1919        let error = declarations.validate().unwrap_err();
1920        assert!(error.contains("invalid metric id"), "{error}");
1921
1922        let mut declarations = arena_shaped();
1923        declarations.dashboards[0].id = "Arena-product".into();
1924        let error = declarations.validate().unwrap_err();
1925        assert!(error.contains("invalid dashboard id"), "{error}");
1926        assert!(Dashboard::new("Arena", "Arena").is_err());
1927
1928        let alert = |id: &str| {
1929            AlertBuilder::new(id, "product.users.active")
1930                .window_seconds(300)
1931                .evaluation_interval_seconds(60)
1932                .critical(Comparison::Below, 1.)
1933                .build()
1934                .unwrap()
1935        };
1936        arena_shaped().alert(alert("quiet")).validate().unwrap();
1937        let error = arena_shaped().alert(alert("Quiet")).validate().unwrap_err();
1938        assert!(error.contains("invalid alert id"), "{error}");
1939        for bad in ["a]", "a b", ""] {
1940            assert!(arena_shaped().alert(alert(bad)).validate().is_err());
1941        }
1942        assert!(RatioMetricBuilder::new("Ratio", "a", "b").build().is_err());
1943        assert!(ProductMetricBuilder::count("Signups", "e").build().is_err());
1944    }
1945
1946    #[test]
1947    fn arena_metric_ids_with_underscores_stay_valid() {
1948        let mut declarations = arena_shaped();
1949        declarations.metrics[0].id = "game.queue_wait.p95".into();
1950        if let MetricQuery::Ratio(ratio) = &mut declarations.metrics[2].query {
1951            ratio.numerator = "game.queue_wait.p95".into();
1952        }
1953        let manifest = declarations
1954            .alert(
1955                AlertBuilder::new("game-queue_delay", "game.queue_wait.p95")
1956                    .window_seconds(300)
1957                    .evaluation_interval_seconds(60)
1958                    .critical(Comparison::Above, 1.)
1959                    .build()
1960                    .unwrap(),
1961            )
1962            .attach_to_eyes_manifest(eyes::AppManifest::default())
1963            .unwrap();
1964        assert_eq!(manifest.metrics.unwrap()[0].id, "game.queue_wait.p95");
1965    }
1966
1967    #[test]
1968    fn dashboard_underscore_is_valid_through_manifest_attachment() {
1969        let dashboard = Dashboard::new("arena_product", "Arena product").unwrap();
1970        let declarations = Declarations::default().dashboard(dashboard);
1971        declarations.validate().unwrap();
1972        let manifest = declarations
1973            .attach_to_eyes_manifest(eyes::AppManifest::default())
1974            .unwrap();
1975        assert_eq!(manifest.dashboards.unwrap()[0].id, "arena_product");
1976        assert!(Dashboard::new("Arena_product", "Arena product").is_err());
1977    }
1978
1979    fn with_bucket_origin(mut metric: Metric, origin: i64) -> Metric {
1980        let MetricQuery::Telemetry(TelemetryMetric(eyes)) = &mut metric.query else {
1981            panic!()
1982        };
1983        let groups = eyes
1984            .query
1985            .as_mut()
1986            .unwrap()
1987            .query
1988            .stages
1989            .iter_mut()
1990            .find_map(|stage| {
1991                if let Stage::Aggregate { groups, .. } = stage {
1992                    Some(groups)
1993                } else {
1994                    None
1995                }
1996            })
1997            .unwrap();
1998        let Expr::Call { args, .. } = &mut groups[0].expr else {
1999            panic!()
2000        };
2001        args.push(Expr::Literal {
2002            value: Literal::Duration(origin),
2003        });
2004        metric
2005    }
2006
2007    fn with_first_group_alias(mut metric: Metric, alias: String) -> Metric {
2008        let MetricQuery::Telemetry(TelemetryMetric(eyes)) = &mut metric.query else {
2009            panic!()
2010        };
2011        let groups = eyes
2012            .query
2013            .as_mut()
2014            .unwrap()
2015            .query
2016            .stages
2017            .iter_mut()
2018            .find_map(|stage| {
2019                if let Stage::Aggregate { groups, .. } = stage {
2020                    Some(groups)
2021                } else {
2022                    None
2023                }
2024            })
2025            .unwrap();
2026        groups[0].alias = alias;
2027        metric
2028    }
2029
2030    #[test]
2031    fn ratio_operands_must_match_bucket_and_group_expressions() {
2032        let make = |id: &str, width: Option<u64>, group: &str| {
2033            let mut builder = TelemetryMetricBuilder::new(id, AggregateFunction::Count, None)
2034                .unwrap()
2035                .group_by(group)
2036                .unwrap();
2037            if let Some(width) = width {
2038                builder = builder.time_bucket(width);
2039            }
2040            builder.build().unwrap()
2041        };
2042        let ratio = || {
2043            RatioMetricBuilder::new("share", "num", "den")
2044                .build()
2045                .unwrap()
2046        };
2047        let validate = |num: Metric, den: Metric| {
2048            Declarations::default()
2049                .metric(num)
2050                .metric(den)
2051                .metric(ratio())
2052                .validate()
2053        };
2054        assert!(
2055            validate(
2056                make("num", Some(60), "fields.kind"),
2057                make("den", Some(60), "fields.kind")
2058            )
2059            .is_ok()
2060        );
2061        for (num, den) in [
2062            (
2063                make("num", Some(60), "fields.kind"),
2064                make("den", Some(120), "fields.kind"),
2065            ),
2066            (
2067                make("num", Some(60), "fields.kind"),
2068                make("den", Some(60), "fields.other"),
2069            ),
2070            (
2071                make("num", None, "fields.kind"),
2072                make("den", None, "fields.other"),
2073            ),
2074        ] {
2075            let error = validate(num, den).unwrap_err();
2076            assert!(
2077                error.contains("share") && error.contains("num") && error.contains("den"),
2078                "{error}"
2079            );
2080        }
2081        assert!(
2082            validate(
2083                make("num", None, "fields.kind"),
2084                make("den", None, "fields.kind")
2085            )
2086            .is_ok()
2087        );
2088        let num = make("num", None, "fields.kind");
2089        let alias = ratio_groups(&num.eyes().unwrap()).0[0].alias.clone();
2090        let den = with_first_group_alias(make("den", None, "fields.other"), alias);
2091        let error = validate(num, den).unwrap_err();
2092        assert!(
2093            error.contains("share") && error.contains("num") && error.contains("den"),
2094            "{error}"
2095        );
2096        let den = with_bucket_origin(make("den", Some(60), "fields.kind"), 1_000_000);
2097        let error = validate(make("num", Some(60), "fields.kind"), den).unwrap_err();
2098        assert!(
2099            error.contains("share") && error.contains("num") && error.contains("den"),
2100            "{error}"
2101        );
2102        let den = with_bucket_origin(make("den", Some(60), "fields.kind"), 0);
2103        assert!(validate(make("num", Some(60), "fields.kind"), den).is_ok());
2104    }
2105
2106    #[test]
2107    fn weekly_product_bucket_converts_to_monday_aligned_eyes_weeks() {
2108        let weekly = ProductMetricBuilder::count("signups.weekly", "user_created")
2109            .bucket_weeks(1)
2110            .build()
2111            .unwrap();
2112        let eyes_builder = || {
2113            eyes::NamedMetricBuilder::new("signups.weekly", AggregateFunction::Count, None)
2114                .unwrap()
2115                .filter_eq("fields.event_type", "user_created")
2116                .unwrap()
2117        };
2118        let monday = to_value(eyes_builder().time_bucket_weeks(1).build().unwrap()).unwrap();
2119        let epoch = to_value(eyes_builder().time_bucket(604_800).build().unwrap()).unwrap();
2120        assert_ne!(monday, epoch);
2121        assert_eq!(to_value(weekly.eyes().unwrap()).unwrap(), monday);
2122        let seconds = ProductMetricBuilder::count("signups.weekly", "user_created")
2123            .bucket_seconds(604_800)
2124            .build()
2125            .unwrap();
2126        assert_eq!(to_value(seconds.eyes().unwrap()).unwrap(), epoch);
2127        assert_eq!(
2128            weekly.eyes().unwrap().result_shape,
2129            eyes::MetricResultShape::TimeSeries
2130        );
2131        assert!(
2132            ProductMetricBuilder::count("m", "e")
2133                .bucket_weeks(0)
2134                .build()
2135                .is_err()
2136        );
2137    }
2138}