obs-macros 0.1.0

Procedural macros for the obs SDK: #[derive(Event)], emit!, scope!, instrument.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
//! `#[derive(Event)]` expansion. Spec 12 § 1.2 + § 3.4.

use heck::ToShoutySnakeCase;
use obs_build::{LintField, LintInput, LintProtoType};
use obs_types::{Cardinality, Classification, FieldKind, Tier};
use proc_macro2::{Span, TokenStream};
use quote::{ToTokens, format_ident, quote};
use syn::{
    Attribute, Data, DataStruct, DeriveInput, Field, Fields, Ident, LitStr, Meta, Token, Type,
    parse2, punctuated::Punctuated,
};

pub(crate) fn expand(input: TokenStream) -> syn::Result<TokenStream> {
    let derive: DeriveInput = parse2(input)?;
    let name = derive.ident.clone();
    let vis = derive.vis.clone();

    let Data::Struct(DataStruct {
        fields: Fields::Named(named),
        ..
    }) = &derive.data
    else {
        return Err(syn::Error::new_spanned(
            &derive.ident,
            "#[derive(Event)] only supports structs with named fields",
        ));
    };

    let container = parse_container_attrs(&derive.attrs)?;
    let fields = named
        .named
        .iter()
        .map(parse_field)
        .collect::<syn::Result<Vec<_>>>()?;

    let full_name_lit = container.full_name(&name);
    let tier = container.tier_path();
    let default_sev = container.sev_path();

    let schema_hash = compute_schema_hash(&full_name_lit.value(), &container, &fields);
    let fields_const = fields_const_array(&fields);

    let project_body = project_impl(&fields);
    let project_metrics_body = project_metrics_impl(&full_name_lit.value(), &fields);
    let encode_body = encode_payload_impl(&fields);
    let paired_with_expr: TokenStream = match container.paired_with.as_deref() {
        Some(s) if !s.is_empty() => quote!(::std::option::Option::Some(#s)),
        _ => quote!(::std::option::Option::None),
    };

    let lints = lint_block(&name, &container, &fields)?;

    let schema_static_ident =
        format_ident!("__OBS_SCHEMA_{}", name.to_string().to_shouty_snake_case());
    let erased_struct_ident = format_ident!("{}Schema", name);
    let builder_ident = format_ident!("{}Builder", name);

    let setter_methods = fields.iter().map(|f| {
        let ident = &f.ident;
        let ty = &f.ty;
        quote! {
            #[doc = "Setter generated by `#[derive(Event)]`."]
            #vis fn #ident(mut self, value: impl ::std::convert::Into<#ty>) -> Self {
                self.inner.#ident = value.into();
                self
            }
        }
    });

    let out = quote! {
        impl ::obs_core::EventSchema for #name {
            const FULL_NAME: &'static str = #full_name_lit;
            const TIER: ::obs_core::__private::Tier = #tier;
            const DEFAULT_SEV: ::obs_core::__private::Severity = #default_sev;
            const FIELDS: &'static [::obs_core::FieldMeta] = &#fields_const;
            const SCHEMA_HASH: u64 = #schema_hash;
            const SPANS_PAIRED_WITH: ::std::option::Option<&'static str> = #paired_with_expr;

            fn encode_payload(&self, buf: &mut ::obs_core::__private::BytesMut) {
                #encode_body
            }

            fn project(&self, env: &mut ::obs_core::ObsEnvelope) {
                #project_body
            }

            fn project_metrics(&self, sink: &mut dyn ::obs_core::MetricEmitter) {
                #project_metrics_body
            }
        }

        #[doc(hidden)]
        #[allow(non_camel_case_types)]
        #vis struct #erased_struct_ident;

        impl ::obs_core::__private::Sealed for #erased_struct_ident {}

        impl ::obs_core::__private::EventSchemaErased for #erased_struct_ident {
            fn full_name(&self) -> &'static str {
                <#name as ::obs_core::EventSchema>::FULL_NAME
            }
            fn schema_hash(&self) -> u64 {
                <#name as ::obs_core::EventSchema>::SCHEMA_HASH
            }
            fn tier(&self) -> ::obs_core::__private::Tier {
                <#name as ::obs_core::EventSchema>::TIER
            }
            fn default_sev(&self) -> ::obs_core::__private::Severity {
                <#name as ::obs_core::EventSchema>::DEFAULT_SEV
            }
            fn fields(&self) -> &'static [::obs_core::FieldMeta] {
                <#name as ::obs_core::EventSchema>::FIELDS
            }
            fn spans_paired_with(&self) -> ::std::option::Option<&'static str> {
                <#name as ::obs_core::EventSchema>::SPANS_PAIRED_WITH
            }
        }

        #[::obs_core::__private::linkme::distributed_slice(::obs_core::__private::EVENT_SCHEMAS)]
        #[linkme(crate = ::obs_core::__private::linkme)]
        #[doc(hidden)]
        static #schema_static_ident: &'static dyn ::obs_core::__private::EventSchemaErased
            = &#erased_struct_ident;

        #lints

        #[doc = "Builder generated by `#[derive(Event)]`. Each setter takes the"]
        #[doc = "field's concrete type. Call `.emit()` to ship the event through"]
        #[doc = "`obs::observer()`."]
        #vis struct #builder_ident {
            inner: #name,
        }

        impl #builder_ident {
            #(#setter_methods)*

            /// Finalise the builder into the event struct.
            #vis fn build(self) -> #name {
                self.inner
            }

            /// Build and emit at the schema's default severity.
            ///
            /// Inlines a `static __CALLSITE: ObsCallsite` so the
            /// atomic-Interest cache short-circuits filtered-out
            /// callsites (spec 11 § 2.1).
            #[allow(clippy::let_underscore_must_use, dead_code)]
            #vis fn emit(self) {
                let evt = self.build();
                static __CALLSITE: ::obs_core::__private::ObsCallsite =
                    ::obs_core::__private::ObsCallsite::new(
                        <#name as ::obs_core::EventSchema>::FULL_NAME,
                        <#name as ::obs_core::EventSchema>::DEFAULT_SEV,
                        module_path!(),
                        file!(),
                        line!(),
                    );
                ::obs_core::emit::emit_with_callsite::<#name>(
                    &__CALLSITE,
                    &evt,
                    <#name as ::obs_core::EventSchema>::DEFAULT_SEV,
                );
            }

            /// Build and emit at a specific severity (escalate or demote).
            #[allow(clippy::let_underscore_must_use, dead_code)]
            #vis fn emit_at(self, sev: ::obs_core::__private::Severity) {
                let evt = self.build();
                static __CALLSITE: ::obs_core::__private::ObsCallsite =
                    ::obs_core::__private::ObsCallsite::new(
                        <#name as ::obs_core::EventSchema>::FULL_NAME,
                        <#name as ::obs_core::EventSchema>::DEFAULT_SEV,
                        module_path!(),
                        file!(),
                        line!(),
                    );
                ::obs_core::emit::emit_with_callsite::<#name>(&__CALLSITE, &evt, sev);
            }
        }

        impl #name {
            /// Begin building this event. Pair with field setters and `.emit()`.
            #vis fn builder() -> #builder_ident {
                #builder_ident {
                    inner: <Self as ::std::default::Default>::default(),
                }
            }
        }
    };
    Ok(out)
}

#[derive(Debug)]
struct ContainerAttrs {
    tier: String,
    default_sev: String,
    full_name: Option<String>,
    paired_with: Option<String>,
}

impl ContainerAttrs {
    fn full_name(&self, ident: &Ident) -> LitStr {
        // Spec 10 § 7 + spec 12 § 1: the canonical full_name is
        // `<package>.v1.<TypeName>`. When the user supplies one
        // explicitly via `#[event(full_name = ...)]` we honour that;
        // otherwise we synthesise from `CARGO_PKG_NAME` set by cargo
        // for the *consuming* crate (proc-macros run during the
        // consumer's compile so this resolves correctly per crate).
        let value = self.full_name.clone().unwrap_or_else(|| {
            let pkg = std::env::var("CARGO_PKG_NAME").unwrap_or_else(|_| "anon".to_string());
            // Replace dashes/colons with underscore so the package
            // segment is a valid proto identifier; downstream consumers
            // (analytics column names, OTLP attribute keys) require
            // `[a-z][a-z0-9_]*`-shaped tokens.
            let pkg_norm = pkg
                .chars()
                .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
                .collect::<String>();
            format!("{pkg_norm}.v1.{ident}")
        });
        LitStr::new(&value, Span::call_site())
    }

    fn tier_path(&self) -> TokenStream {
        match self.tier.to_ascii_lowercase().as_str() {
            "log" => quote!(::obs_core::__private::Tier::Log),
            "metric" => quote!(::obs_core::__private::Tier::Metric),
            "trace" => quote!(::obs_core::__private::Tier::Trace),
            "audit" => quote!(::obs_core::__private::Tier::Audit),
            other => {
                let msg = format!("obs: unknown tier `{other}`; expected log|metric|trace|audit");
                quote!(compile_error!(#msg))
            }
        }
    }

    fn sev_path(&self) -> TokenStream {
        match self.default_sev.to_ascii_lowercase().as_str() {
            "trace" => quote!(::obs_core::__private::Severity::Trace),
            "debug" => quote!(::obs_core::__private::Severity::Debug),
            "info" => quote!(::obs_core::__private::Severity::Info),
            "warn" => quote!(::obs_core::__private::Severity::Warn),
            "error" => quote!(::obs_core::__private::Severity::Error),
            "fatal" => quote!(::obs_core::__private::Severity::Fatal),
            other => {
                let msg = format!(
                    "obs: unknown default_sev `{other}`; expected \
                     trace|debug|info|warn|error|fatal"
                );
                quote!(compile_error!(#msg))
            }
        }
    }
}

fn parse_container_attrs(attrs: &[Attribute]) -> syn::Result<ContainerAttrs> {
    let mut tier = String::from("log");
    let mut default_sev = String::from("info");
    let mut full_name: Option<String> = None;
    let mut paired_with: Option<String> = None;

    for attr in attrs {
        if !attr.path().is_ident("event") {
            continue;
        }
        let pairs: Punctuated<Meta, Token![,]> =
            attr.parse_args_with(Punctuated::parse_terminated)?;
        for meta in pairs {
            match meta {
                Meta::NameValue(nv) if nv.path.is_ident("tier") => {
                    tier = lit_to_string(&nv.value)?;
                }
                Meta::NameValue(nv) if nv.path.is_ident("default_sev") => {
                    default_sev = lit_to_string(&nv.value)?;
                }
                Meta::NameValue(nv) if nv.path.is_ident("full_name") => {
                    full_name = Some(lit_to_string(&nv.value)?);
                }
                Meta::NameValue(nv) if nv.path.is_ident("paired_with") => {
                    paired_with = Some(lit_to_string(&nv.value)?);
                }
                other => {
                    return Err(syn::Error::new_spanned(
                        other,
                        "#[event(...)] supports tier / default_sev / full_name / paired_with",
                    ));
                }
            }
        }
    }

    Ok(ContainerAttrs {
        tier,
        default_sev,
        full_name,
        paired_with,
    })
}

struct ObsField {
    ident: Ident,
    ty: Type,
    role: String,
    cardinality: String,
    classification: String,
    proto_number: u32,
    /// MEASUREMENT-only: `counter` (default), `gauge`, or `histogram`.
    metric_kind: String,
    /// MEASUREMENT-only: UCUM unit string (`ms`, `By`, `1`, …).
    unit: Option<String>,
    /// Histogram bucket bounds parsed from a comma-separated list.
    bounds: Vec<f64>,
}

impl ObsField {
    fn role_token(&self) -> TokenStream {
        match self.role.as_str() {
            "label" => quote!(::obs_core::FieldRole::Label),
            "attribute" => quote!(::obs_core::FieldRole::Attribute),
            "measurement" => quote!(::obs_core::FieldRole::Measurement),
            "trace_id" => quote!(::obs_core::FieldRole::TraceId),
            "span_id" => quote!(::obs_core::FieldRole::SpanId),
            "parent_span_id" => quote!(::obs_core::FieldRole::ParentSpanId),
            "timestamp_ns" => quote!(::obs_core::FieldRole::TimestampNs),
            "duration_ns" => quote!(::obs_core::FieldRole::DurationNs),
            "forensic" => quote!(::obs_core::FieldRole::Forensic),
            _ => quote!(::obs_core::FieldRole::Attribute),
        }
    }
    fn cardinality_token(&self) -> TokenStream {
        match self.cardinality.as_str() {
            "low" => quote!(::obs_core::__private::Cardinality::Low),
            "medium" => quote!(::obs_core::__private::Cardinality::Medium),
            "high" => quote!(::obs_core::__private::Cardinality::High),
            "unbounded" => quote!(::obs_core::__private::Cardinality::Unbounded),
            _ => quote!(::obs_core::__private::Cardinality::Unspecified),
        }
    }
    fn classification_token(&self) -> TokenStream {
        match self.classification.as_str() {
            "pii" => quote!(::obs_core::__private::Classification::Pii),
            "secret" => quote!(::obs_core::__private::Classification::Secret),
            "internal" => quote!(::obs_core::__private::Classification::Internal),
            _ => quote!(::obs_core::__private::Classification::Internal),
        }
    }
}

fn parse_field(field: &Field) -> syn::Result<ObsField> {
    let ident = field
        .ident
        .clone()
        .ok_or_else(|| syn::Error::new_spanned(field, "obs: only named fields are supported"))?;
    let mut role = String::new();
    let mut cardinality = String::new();
    let mut classification = String::new();
    let mut number: u32 = 0;
    let mut metric_kind = String::new();
    let mut unit: Option<String> = None;
    let mut bounds: Vec<f64> = Vec::new();

    for attr in &field.attrs {
        if !attr.path().is_ident("obs") {
            continue;
        }
        let pairs: Punctuated<Meta, Token![,]> =
            attr.parse_args_with(Punctuated::parse_terminated)?;
        for meta in pairs {
            match meta {
                Meta::Path(p) => {
                    role = p.get_ident().map(Ident::to_string).unwrap_or_default();
                }
                Meta::NameValue(nv) if nv.path.is_ident("cardinality") => {
                    cardinality = lit_to_string(&nv.value)?;
                }
                Meta::NameValue(nv) if nv.path.is_ident("classification") => {
                    classification = lit_to_string(&nv.value)?;
                }
                Meta::NameValue(nv) if nv.path.is_ident("number") => {
                    number = lit_to_string(&nv.value)?
                        .parse::<u32>()
                        .map_err(|e| syn::Error::new_spanned(nv, format!("invalid number: {e}")))?;
                }
                Meta::NameValue(nv) if nv.path.is_ident("metric") => {
                    metric_kind = lit_to_string(&nv.value)?;
                }
                Meta::NameValue(nv) if nv.path.is_ident("unit") => {
                    unit = Some(lit_to_string(&nv.value)?);
                }
                Meta::NameValue(nv) if nv.path.is_ident("bounds") => {
                    let raw = lit_to_string(&nv.value)?;
                    bounds = raw
                        .split(',')
                        .filter_map(|s| s.trim().parse::<f64>().ok())
                        .collect();
                }
                other => {
                    return Err(syn::Error::new_spanned(
                        other,
                        "#[obs(...)] supports the role keyword (label|attribute|measurement|trace_id|span_id|parent_span_id|timestamp_ns|duration_ns|forensic) plus cardinality / classification / number / metric / unit / bounds",
                    ));
                }
            }
        }
    }

    Ok(ObsField {
        ident,
        ty: field.ty.clone(),
        role,
        cardinality,
        classification,
        proto_number: number,
        metric_kind,
        unit,
        bounds,
    })
}

fn lit_to_string(expr: &syn::Expr) -> syn::Result<String> {
    if let syn::Expr::Lit(syn::ExprLit {
        lit: syn::Lit::Str(s),
        ..
    }) = expr
    {
        return Ok(s.value());
    }
    if let syn::Expr::Lit(syn::ExprLit {
        lit: syn::Lit::Int(i),
        ..
    }) = expr
    {
        return Ok(i.base10_digits().to_string());
    }
    Err(syn::Error::new_spanned(expr, "expected string literal"))
}

fn fields_const_array(fields: &[ObsField]) -> TokenStream {
    let entries = fields.iter().enumerate().map(|(i, f)| {
        let name_lit = LitStr::new(&f.ident.to_string(), Span::call_site());
        let role = f.role_token();
        let card = f.cardinality_token();
        let classn = f.classification_token();
        let number: u32 = if f.proto_number == 0 {
            (i as u32) + 1
        } else {
            f.proto_number
        };
        quote! {
            ::obs_core::FieldMeta::new(
                #name_lit,
                #number,
                #role,
                #card,
                #classn,
            )
        }
    });
    quote!([#(#entries),*])
}

fn project_impl(fields: &[ObsField]) -> TokenStream {
    let mut stmts: Vec<TokenStream> = Vec::new();
    for f in fields {
        let ident = &f.ident;
        let name = LitStr::new(&ident.to_string(), Span::call_site());
        match f.role.as_str() {
            "label" => stmts.push(quote! {
                {
                    let v = ::std::string::ToString::to_string(&self.#ident);
                    env.labels.insert(#name.to_string(), v);
                }
            }),
            "trace_id" => stmts.push(quote! {
                env.trace_id = ::std::string::ToString::to_string(&self.#ident);
            }),
            "span_id" => stmts.push(quote! {
                env.span_id = ::std::string::ToString::to_string(&self.#ident);
            }),
            "parent_span_id" => stmts.push(quote! {
                env.parent_span_id = ::std::string::ToString::to_string(&self.#ident);
            }),
            _ => {}
        }
    }
    quote! { #(#stmts)* }
}

fn project_metrics_impl(full_name: &str, fields: &[ObsField]) -> TokenStream {
    // Per spec 12 § 3.6 / spec 93 P1-6: walk MEASUREMENT-tagged fields
    // and dispatch to the matching `MetricEmitter::record_*` method.
    // The instrument name follows `<full_name>.<field>` so OTLP metric
    // names line up with the event taxonomy.
    let mut stmts: Vec<TokenStream> = Vec::new();
    for f in fields {
        if f.role != "measurement" {
            continue;
        }
        let ident = &f.ident;
        let instrument = format!("{full_name}.{}", ident);
        let unit_expr: TokenStream = match f.unit.as_deref() {
            Some(u) if !u.is_empty() => quote!(::std::option::Option::Some(#u)),
            _ => quote!(::std::option::Option::None),
        };
        let kind = f.metric_kind.to_ascii_lowercase();
        match kind.as_str() {
            "gauge" => stmts.push(quote! {
                sink.record_gauge_u64(#instrument, self.#ident as u64, #unit_expr);
            }),
            "histogram" => {
                let bounds = &f.bounds;
                stmts.push(quote! {
                    static BOUNDS: &[f64] = &[#(#bounds),*];
                    sink.record_histogram(
                        #instrument,
                        self.#ident as f64,
                        #unit_expr,
                        BOUNDS,
                    );
                });
            }
            // counter | "" | _ — default to counter
            _ => stmts.push(quote! {
                sink.record_counter(#instrument, self.#ident as u64, #unit_expr);
            }),
        }
    }
    if stmts.is_empty() {
        quote! { let _ = sink; }
    } else {
        quote! { #(#stmts)* }
    }
}

fn encode_payload_impl(fields: &[ObsField]) -> TokenStream {
    // Phase-6.1 / spec 93 P0-2 + decision D6-1: emit buffa wire-format
    // bytes via `BuffaEncodeField`, byte-identical to what
    // `buffa::Message::write_to` produces for the proto-first path.
    //
    // The trait is implemented on every supported scalar type plus
    // `Option<T>`, `secrecy::SecretString`, and `secrecy::SecretBox<T>`,
    // so the macro does not need to dispatch on the syntactic field
    // type — trait resolution picks the right wire encoding at compile
    // time. Fields whose value equals the proto3 default (empty string,
    // zero, false, …) are elided.
    let stmts = fields.iter().enumerate().map(|(i, f)| {
        let ident = &f.ident;
        let number: u32 = if f.proto_number == 0 {
            (i as u32) + 1
        } else {
            f.proto_number
        };
        quote! {
            <_ as ::obs_core::__private::BuffaEncodeField>::buffa_encode_field(
                &self.#ident,
                #number,
                buf,
            );
        }
    });
    quote! {
        #(#stmts)*
    }
}

fn lint_block(
    name: &Ident,
    container: &ContainerAttrs,
    fields: &[ObsField],
) -> syn::Result<TokenStream> {
    // Decision D8-1 / spec 95 § 2.1: both authoring paths build a
    // `LintInput` and call `obs_build::emit_lints`. Each `LintError`
    // becomes one `const _: () = panic!(MSG)`. Drift between this
    // path and `obs-build::codegen` is impossible because both render
    // identical message bytes.
    let prefix = std::env::var("OBS_EVENT_PREFIX").unwrap_or_else(|_| "Obs".to_string());

    let input = LintInput {
        event_name: name.to_string(),
        tier: parse_tier(&container.tier),
        event_prefix: prefix,
        fields: fields.iter().map(field_to_lint).collect(),
    };

    let asserts: Vec<TokenStream> = obs_build::emit_lints(&input)
        .into_iter()
        .map(|err| {
            let msg = err.message;
            quote! { const _: () = ::std::panic!(#msg); }
        })
        .collect();

    Ok(quote! { #(#asserts)* })
}

fn parse_tier(s: &str) -> Tier {
    match s.to_ascii_lowercase().as_str() {
        "log" => Tier::Log,
        "metric" => Tier::Metric,
        "trace" => Tier::Trace,
        "audit" => Tier::Audit,
        _ => Tier::Unspecified,
    }
}

fn parse_field_kind(s: &str) -> FieldKind {
    match s {
        "label" => FieldKind::Label,
        "attribute" => FieldKind::Attribute,
        "measurement" => FieldKind::Measurement,
        "trace_id" => FieldKind::TraceId,
        "span_id" => FieldKind::SpanId,
        "parent_span_id" => FieldKind::ParentSpanId,
        "timestamp_ns" => FieldKind::TimestampNs,
        "duration_ns" => FieldKind::DurationNs,
        "forensic" => FieldKind::Forensic,
        _ => FieldKind::Attribute,
    }
}

fn parse_cardinality(s: &str) -> Cardinality {
    match s {
        "low" => Cardinality::Low,
        "medium" => Cardinality::Medium,
        "high" => Cardinality::High,
        "unbounded" => Cardinality::Unbounded,
        _ => Cardinality::Unspecified,
    }
}

fn parse_classification(s: &str) -> Classification {
    match s {
        "pii" => Classification::Pii,
        "secret" => Classification::Secret,
        "internal" => Classification::Internal,
        _ => Classification::Internal,
    }
}

fn field_to_lint(f: &ObsField) -> LintField {
    let proto_type = LintProtoType::from_rust_token(&f.ty.to_token_stream().to_string());
    LintField {
        name: f.ident.to_string(),
        kind: parse_field_kind(&f.role),
        cardinality: parse_cardinality(&f.cardinality),
        classification: parse_classification(&f.classification),
        has_metric: !f.metric_kind.is_empty(),
        proto_type: Some(proto_type),
    }
}

fn compute_schema_hash(full_name: &str, container: &ContainerAttrs, fields: &[ObsField]) -> u64 {
    // BLAKE3 over a stable canonical descriptor string. The first 8
    // bytes (little-endian) become `SCHEMA_HASH`. Spec 10 § 6 + spec
    // 12 § 3.5.
    let mut s = String::new();
    s.push_str(full_name);
    s.push('|');
    s.push_str(&container.tier);
    s.push('|');
    s.push_str(&container.default_sev);
    s.push('|');
    for f in fields {
        s.push_str(&f.ident.to_string());
        s.push(':');
        s.push_str(&f.role);
        s.push(':');
        s.push_str(&f.cardinality);
        s.push(':');
        s.push_str(&f.classification);
        s.push(',');
    }
    let h = blake3::hash(s.as_bytes());
    let bytes = h.as_bytes();
    let arr = <[u8; 8]>::try_from(&bytes[..8]).expect("blake3 always produces 32 bytes");
    u64::from_le_bytes(arr)
}