eyes-subscriber 0.8.0

Tracing subscriber for sending traces to Eyes (eyes.coreyja.com)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! Boot-declared semantic dashboards: presentation declarations referencing
//! named metrics by stable semantic ID. No query IR lives here — the
//! dashboard says *what to show*; the named metric says *how to compute it*.
//!
//! Validation split (mirrors `metrics.rs`): constructors validate structural
//! grammar (id/title/href) and fail at boot; metadata setters are infallible
//! and the server enforces caps and ranges at manifest ingestion.
//!
//! Referenced `query_id`s point at named metrics declared in the same
//! manifest, whose filters/group dimensions follow the span-creation
//! contract — fields must exist when the span is created; `Span::record()`
//! after creation is invisible to Eyes queries (see `metrics.rs`). If a
//! dashboard item renders empty, check that layer first.

use serde::Serialize;

/// A semantic dashboard declaration carried by the boot manifest. A
/// dashboard carries zero query IR: every `stat`/`time_series`/`table` item
/// references a named metric declared in the same manifest by `query_id`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct NamedDashboard {
    pub id: String,
    pub title: String,
    pub description: Option<String>,
    pub default_range_seconds: Option<u64>,
    pub sections: Vec<DashboardSection>,
}

/// One titled grouping of dashboard items.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct DashboardSection {
    pub title: Option<String>,
    pub description: Option<String>,
    pub items: Vec<DashboardItem>,
}

/// One dashboard item: a typed presentation declaration. The wire form is
/// internally tagged on `kind` (`snake_case`), pinned key-for-key by the
/// manifest payload serialization test.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
pub enum DashboardItem {
    Stat {
        query_id: String,
        label: Option<String>,
        unit: Option<String>,
    },
    TimeSeries {
        query_id: String,
        label: Option<String>,
        unit: Option<String>,
        preferred_bucket_seconds: Option<u64>,
    },
    Table {
        query_id: String,
        label: Option<String>,
        unit: Option<String>,
    },
    HealthSummary {
        label: Option<String>,
    },
    Links {
        links: Vec<DashboardLink>,
    },
}

/// One navigation link: rendered, never fetched.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(deny_unknown_fields)]
pub struct DashboardLink {
    pub label: String,
    pub href: String,
}

/// Dashboard-id grammar (the named-metric id grammar): non-empty, trimmed,
/// ASCII, at most 128 bytes, chars in `[A-Za-z0-9._:-]`.
fn valid_id(id: &str) -> bool {
    !id.is_empty()
        && id.len() <= 128
        && id.trim() == id
        && id.is_ascii()
        && id
            .bytes()
            .all(|b| b.is_ascii_alphanumeric() || b"._:-".contains(&b))
}

/// Link href grammar: root-relative path (starts with `/` but not `//` —
/// protocol-relative URLs resolve as scheme-relative external URLs) or an
/// absolute `http(s)://` URL, with no backslash anywhere (WHATWG parsing
/// treats `\` as `/` for special schemes, so `/\host` becomes `//host`), no
/// ASCII control bytes, at most 512 chars. Links are rendered, never
/// fetched — no SSRF machinery applies; the grammar check is the whole
/// rule.
fn valid_href(href: &str) -> bool {
    !href.is_empty()
        && href.chars().count() <= 512
        && !href.chars().any(|c| c.is_ascii_control())
        && !href.contains('\\')
        && (href.starts_with("http://")
            || href.starts_with("https://")
            || (href.starts_with('/') && !href.starts_with("//")))
}

impl NamedDashboard {
    /// Start a declaration. **Fallible**: validates the id grammar
    /// (non-empty, `[A-Za-z0-9._:-]`, ASCII, at most 128 bytes, trimmed)
    /// and the title (non-empty after trim, at most 256 chars) — a bad
    /// declaration fails at boot in the app.
    pub fn new(id: impl Into<String>, title: impl Into<String>) -> Result<Self, String> {
        let id = id.into();
        if !valid_id(&id) {
            return Err(format!(
                "invalid dashboard id {id:?}: must be non-empty, trimmed, ASCII, at most 128 bytes, chars [A-Za-z0-9._:-]"
            ));
        }
        let title = title.into();
        if title.trim().is_empty() || title.chars().count() > 256 {
            return Err(format!(
                "invalid dashboard title {title:?}: must be non-empty after trim and at most 256 characters"
            ));
        }
        Ok(Self {
            id,
            title,
            description: None,
            default_range_seconds: None,
            sections: Vec::new(),
        })
    }

    /// **Infallible**: the server rejects descriptions over 4096 chars at
    /// manifest ingestion.
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// **Infallible**: stores the value verbatim; the server rejects
    /// anything outside `60..=2_678_400` seconds (one minute to 31 days,
    /// the executor window cap) at manifest ingestion.
    pub fn default_range_seconds(mut self, seconds: u64) -> Self {
        self.default_range_seconds = Some(seconds);
        self
    }

    /// **Infallible**: appends a section; the server rejects zero sections
    /// and more than 20 at ingestion. The builder stays permissive, like
    /// `HttpMonitor`'s setters.
    pub fn section(mut self, section: DashboardSection) -> Self {
        self.sections.push(section);
        self
    }
}

impl DashboardSection {
    pub fn new() -> Self {
        Self {
            title: None,
            description: None,
            items: Vec::new(),
        }
    }

    /// **Infallible**: the server enforces the 256-char cap at ingestion.
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// **Infallible**: the server enforces the 4096-char cap at ingestion.
    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// **Infallible**: appends an item; the server rejects empty sections
    /// and more than 24 items at ingestion.
    pub fn item(mut self, item: DashboardItem) -> Self {
        self.items.push(item);
        self
    }
}

impl Default for DashboardSection {
    fn default() -> Self {
        Self::new()
    }
}

impl DashboardItem {
    /// A single-value item rendering a `scalar` named metric.
    /// **Infallible**: a `query_id` is an opaque reference to a
    /// same-manifest metric; the server rejects unknown ones at ingest.
    pub fn stat(query_id: impl Into<String>) -> Self {
        Self::Stat {
            query_id: query_id.into(),
            label: None,
            unit: None,
        }
    }

    /// A chart item rendering a `time_series` named metric.
    /// **Infallible**: see [`DashboardItem::stat`].
    pub fn time_series(query_id: impl Into<String>) -> Self {
        Self::TimeSeries {
            query_id: query_id.into(),
            label: None,
            unit: None,
            preferred_bucket_seconds: None,
        }
    }

    /// A table item rendering a `table` named metric.
    /// **Infallible**: see [`DashboardItem::stat`].
    pub fn table(query_id: impl Into<String>) -> Self {
        Self::Table {
            query_id: query_id.into(),
            label: None,
            unit: None,
        }
    }

    /// Renders the app's durable run-health state; carries no query.
    pub fn health_summary() -> Self {
        Self::HealthSummary { label: None }
    }

    /// A navigation link list; carries no query.
    pub fn links(links: Vec<DashboardLink>) -> Self {
        Self::Links { links }
    }

    /// **Infallible**: sets the display label, overriding the referenced
    /// metric's `display_name`. The server enforces the 256-char cap at
    /// ingestion. No documented no-op case: every item kind carries a
    /// `label`.
    pub fn label(mut self, label: impl Into<String>) -> Self {
        let new_label = Some(label.into());
        match &mut self {
            Self::Stat { label, .. }
            | Self::TimeSeries { label, .. }
            | Self::Table { label, .. }
            | Self::HealthSummary { label } => *label = new_label,
            Self::Links { .. } => {}
        }
        self
    }

    /// **Infallible**: sets the display unit, overriding the referenced
    /// metric's `unit`. When the referenced metric declares a unit, the
    /// server requires exact equality at ingest; over a unit-less metric
    /// any valid unit text is allowed. The builder does not duplicate that
    /// check. Documented no-op on `health_summary` and `links`, which
    /// carry no unit field — returns `self` unchanged.
    pub fn unit(mut self, unit: impl Into<String>) -> Self {
        let new_unit = Some(unit.into());
        match &mut self {
            Self::Stat { unit, .. } | Self::TimeSeries { unit, .. } | Self::Table { unit, .. } => {
                *unit = new_unit
            }
            Self::HealthSummary { .. } | Self::Links { .. } => {}
        }
        self
    }

    /// **Infallible**: bucket-width guidance for callers of the execute
    /// endpoint (which already accepts `bucket_seconds`); the server never
    /// rewrites queries for it. Documented no-op on every kind except
    /// `time_series` — returns `self` unchanged.
    pub fn preferred_bucket_seconds(mut self, seconds: u64) -> Self {
        if let Self::TimeSeries {
            preferred_bucket_seconds,
            ..
        } = &mut self
        {
            *preferred_bucket_seconds = Some(seconds);
        }
        self
    }
}

impl DashboardLink {
    /// **Fallible**: validates the href grammar (root-relative `/…` but not
    /// `//…`, no backslash anywhere, or `http(s)://…`; no ASCII control
    /// bytes; at most 512 chars) and the label (non-empty after trim, at
    /// most 256 chars) so a bad link fails at boot — the same grammar the
    /// server enforces.
    pub fn new(label: impl Into<String>, href: impl Into<String>) -> Result<Self, String> {
        let label = label.into();
        if label.trim().is_empty() || label.chars().count() > 256 {
            return Err(format!(
                "invalid dashboard link label {label:?}: must be non-empty after trim and at most 256 characters"
            ));
        }
        let href = href.into();
        if !valid_href(&href) {
            return Err(format!(
                "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"
            ));
        }
        Ok(Self { label, href })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn named_dashboard_new_validates_id_and_title() {
        for bad_id in [
            "",
            " leading",
            "trailing ",
            "id with spaces",
            "non-ascii-é",
            &"x".repeat(129),
            "bad!char",
        ] {
            let error = NamedDashboard::new(bad_id, "Title").unwrap_err();
            assert!(error.contains("invalid dashboard id"), "{error}");
        }
        for bad_title in ["", "   ", &"x".repeat(257)] {
            let error = NamedDashboard::new("api-overview", bad_title).unwrap_err();
            assert!(error.contains("invalid dashboard title"), "{error}");
        }
        // A valid construction serializes to the exact expected JSON.
        let dashboard = NamedDashboard::new("api-overview", "API Overview")
            .unwrap()
            .description("Front-door health")
            .default_range_seconds(3600)
            .section(DashboardSection::new().title("Traffic"));
        assert_eq!(
            serde_json::to_value(&dashboard).unwrap(),
            json!({
                "id": "api-overview",
                "title": "API Overview",
                "description": "Front-door health",
                "default_range_seconds": 3600,
                "sections": [{ "title": "Traffic", "description": null, "items": [] }],
            })
        );
    }

    #[test]
    fn dashboard_link_new_validates_href_grammar() {
        for bad_href in [
            "foo/bar",                        // relative without leading /
            "//host/path",                    // protocol-relative
            "\\host",                         // bare backslash
            "/\\host",                        // backslash after root
            "ftp://host/x",                   // non-http scheme
            "/a\u{0000}b",                    // ASCII control byte
            &format!("/{}", "x".repeat(512)), // > 512 chars
        ] {
            let error = DashboardLink::new("Label", bad_href).unwrap_err();
            assert!(error.contains("invalid dashboard link href"), "{error}");
        }
        for bad_label in ["", "   ", &"x".repeat(257)] {
            let error = DashboardLink::new(bad_label, "/requests").unwrap_err();
            assert!(error.contains("invalid dashboard link label"), "{error}");
        }
        // Valid forms pass and serialize exactly.
        let root_relative =
            DashboardLink::new("Requests view", "/orgs/00000000-0000-0000-0000-000000000000/apps/11111111-1111-1111-1111-111111111111/requests")
                .unwrap();
        assert_eq!(
            serde_json::to_value(&root_relative).unwrap(),
            json!({ "label": "Requests view", "href": "/orgs/00000000-0000-0000-0000-000000000000/apps/11111111-1111-1111-1111-111111111111/requests" })
        );
        let absolute = DashboardLink::new("Docs", "https://example.com/x").unwrap();
        assert_eq!(
            serde_json::to_value(&absolute).unwrap(),
            json!({ "label": "Docs", "href": "https://example.com/x" })
        );
        // Backslash anywhere in the path is rejected, even mid-path.
        assert!(DashboardLink::new("L", "/orgs/\\host").is_err());
    }

    #[test]
    fn item_kinds_serialize_the_wire_tagging() {
        let stat = DashboardItem::stat("http.request_count.total").label("Requests");
        assert_eq!(
            serde_json::to_value(&stat).unwrap(),
            json!({ "kind": "stat", "query_id": "http.request_count.total", "label": "Requests", "unit": null })
        );
        let time_series = DashboardItem::time_series("http.request_count")
            .unit("requests")
            .preferred_bucket_seconds(300);
        assert_eq!(
            serde_json::to_value(&time_series).unwrap(),
            json!({ "kind": "time_series", "query_id": "http.request_count", "label": null, "unit": "requests", "preferred_bucket_seconds": 300 })
        );
        let table = DashboardItem::table("http.top_routes");
        assert_eq!(
            serde_json::to_value(&table).unwrap(),
            json!({ "kind": "table", "query_id": "http.top_routes", "label": null, "unit": null })
        );
        let health = DashboardItem::health_summary().label("Service health");
        assert_eq!(
            serde_json::to_value(&health).unwrap(),
            json!({ "kind": "health_summary", "label": "Service health" })
        );
        let links = DashboardItem::links(vec![DashboardLink::new("Home", "/").unwrap()]);
        assert_eq!(
            serde_json::to_value(&links).unwrap(),
            json!({ "kind": "links", "links": [{ "label": "Home", "href": "/" }] })
        );
    }

    #[test]
    fn setters_are_documented_no_ops_on_kinds_without_the_field() {
        // unit and preferred_bucket_seconds on non-carrying kinds return
        // self unchanged; label is carried by every kind but links.
        let health = DashboardItem::health_summary().unit("requests");
        assert_eq!(health, DashboardItem::HealthSummary { label: None });
        let stat = DashboardItem::stat("m").preferred_bucket_seconds(300);
        assert_eq!(
            stat,
            DashboardItem::Stat {
                query_id: "m".into(),
                label: None,
                unit: None,
            }
        );
        let links = DashboardItem::links(vec![]).label("Nope");
        assert_eq!(links, DashboardItem::Links { links: vec![] });
    }
}