From 4f79d65bffdaf8cefd67bdb011c03bfc07840290 Mon Sep 17 00:00:00 2001 From: Yordis Prieto Date: Tue, 13 Oct 2026 05:38:48 -0400 Subject: [PATCH] fix(rust): mirror the official semantic conventions crate layout Signed-off-by: Yordis Prieto --- templates/code/rust/README.md | 76 +- templates/code/rust/entities.rs.j2 | 4 +- templates/code/rust/events.rs.j2 | 16 +- templates/code/rust/metrics.rs.j2 | 24 +- templates/code/rust/mod.rs.j2 | 6 +- templates/code/rust/signal_helpers.j2 | 2 +- templates/code/rust/spans.rs.j2 | 18 +- .../expected/{probeattr.rs => attribute.rs} | 116 +- .../rust/tests/allocations/expected/event.rs | 51 + .../rust/tests/allocations/expected/metric.rs | 139 +++ .../rust/tests/allocations/expected/mod.rs | 6 +- .../tests/allocations/expected/probeevent.rs | 43 - .../tests/allocations/expected/probemetric.rs | 123 --- templates/code/rust/tests/allocations/test.rs | 80 +- .../attributes/compile-fail/dynamic_borrow.rs | 2 +- .../compile-fail/inherited_deprecation.rs | 2 +- .../attributes/compile-fail/unknown_enum.rs | 2 +- .../wrong_scalar.expected-error.txt | 2 +- .../attributes/compile-fail/wrong_scalar.rs | 2 +- .../tests/attributes/expected/attribute.rs | 999 ++++++++++++++++++ .../tests/attributes/expected/authattr.rs | 172 --- .../rust/tests/attributes/expected/mod.rs | 3 +- .../tests/attributes/expected/myappattr.rs | 827 --------------- templates/code/rust/tests/attributes/test.rs | 78 +- .../tests/attributes/tests/allocations.rs | 10 +- .../rust/tests/attributes/tests/log_values.rs | 32 +- .../excluded_attribute.expected-error.txt | 2 +- .../compile-fail/excluded_attribute.rs | 2 +- .../compile-fail/excluded_member.rs | 2 +- .../expected/{demoattr.rs => attribute.rs} | 48 +- .../tests/codegen_exclusion/expected/mod.rs | 2 +- .../code/rust/tests/codegen_exclusion/test.rs | 6 +- .../entities/compile-fail/missing_identity.rs | 4 +- .../entities/compile-fail/required_default.rs | 2 +- .../wrong_identity.expected-error.txt | 2 +- .../entities/compile-fail/wrong_identity.rs | 4 +- .../expected/{myappattr.rs => attribute.rs} | 138 +-- .../code/rust/tests/entities/expected/mod.rs | 4 +- .../expected/{myappentity.rs => resource.rs} | 116 +- templates/code/rust/tests/entities/test.rs | 36 +- .../expected-error.txt | 1 + .../registry/manifest.yaml | 2 + .../registry/model.yaml | 10 + .../error_event_collision/expected-error.txt | 2 +- .../expected-error.txt | 1 - .../registry/manifest.yaml | 2 - .../registry/model.yaml | 10 - .../expected-error.txt | 1 + .../registry/manifest.yaml | 2 + .../registry/model.yaml | 18 + .../error_metric_collision/expected-error.txt | 2 +- .../expected-error.txt | 2 +- .../error_span_collision/expected-error.txt | 2 +- .../expected/{probeevent.rs => event.rs} | 20 +- .../tests/event_no_attributes/expected/mod.rs | 2 +- .../rust/tests/event_no_attributes/test.rs | 6 +- .../expected/{myappattr.rs => attribute.rs} | 195 ++-- .../code/rust/tests/events/expected/event.rs | 199 ++++ .../code/rust/tests/events/expected/mod.rs | 6 +- .../rust/tests/events/expected/myappevent.rs | 85 -- .../rust/tests/events/expected/workerattr.rs | 65 -- .../rust/tests/events/expected/workerevent.rs | 80 -- templates/code/rust/tests/events/test.rs | 49 +- .../tests/filtering/expected/attribute.rs | 614 +++++++++++ .../rust/tests/filtering/expected/authattr.rs | 122 --- .../code/rust/tests/filtering/expected/mod.rs | 3 +- .../rust/tests/filtering/expected/taskattr.rs | 492 --------- templates/code/rust/tests/filtering/test.rs | 6 +- .../expected/attribute.rs} | 24 +- .../expected/{myappmetric.rs => metric.rs} | 72 +- .../expected/mod.rs | 4 +- .../expected/attribute.rs} | 24 +- .../expected/metric.rs | 56 + .../expected/mod.rs | 4 +- .../expected/myappmetric.rs | 48 - .../expected/attribute.rs} | 24 +- .../rust/tests/imported/expected/edgeevent.rs | 43 - .../tests/imported/expected/edgemetric.rs | 39 - .../rust/tests/imported/expected/event.rs | 51 + .../rust/tests/imported/expected/metric.rs | 120 +++ .../code/rust/tests/imported/expected/mod.rs | 9 +- .../tests/imported/expected/myappmetric.rs | 70 -- .../expected/{edgespan.rs => trace.rs} | 58 +- templates/code/rust/tests/imported/test.rs | 22 +- .../expected/{myappattr.rs => attribute.rs} | 24 +- .../tests/imported_typed/expected/event.rs | 49 + .../tests/imported_typed/expected/metric.rs | 78 ++ .../rust/tests/imported_typed/expected/mod.rs | 8 +- .../imported_typed/expected/myappevent.rs | 41 - .../imported_typed/expected/myappmetric.rs | 70 -- .../expected/{myappspan.rs => trace.rs} | 40 +- .../code/rust/tests/imported_typed/test.rs | 20 +- .../expected/{demoattr.rs => attribute.rs} | 28 +- .../tests/integer_boundaries/expected/mod.rs | 2 +- .../rust/tests/integer_boundaries/test.rs | 6 +- .../expected/{demoattr.rs => attribute.rs} | 30 +- .../literal_escaping/expected/demometric.rs | 54 - .../tests/literal_escaping/expected/metric.rs | 62 ++ .../tests/literal_escaping/expected/mod.rs | 4 +- .../code/rust/tests/literal_escaping/test.rs | 18 +- .../metrics/compile-fail/missing_required.rs | 4 +- .../metrics/compile-fail/signed_counter.rs | 4 +- .../compile-fail/unrelated_optional.rs | 4 +- .../wrong_required_type.expected-error.txt | 2 +- .../compile-fail/wrong_required_type.rs | 4 +- .../rust/tests/metrics/expected/attribute.rs | 220 ++++ .../rust/tests/metrics/expected/authattr.rs | 98 -- .../rust/tests/metrics/expected/authmetric.rs | 54 - .../rust/tests/metrics/expected/metric.rs | 614 +++++++++++ .../code/rust/tests/metrics/expected/mod.rs | 7 +- .../rust/tests/metrics/expected/myappattr.rs | 122 --- .../tests/metrics/expected/myappmetric.rs | 445 -------- .../tests/metrics/expected/workermetric.rs | 45 - templates/code/rust/tests/metrics/test.rs | 90 +- .../expected/{capsattr.rs => attribute.rs} | 48 +- .../rust/tests/naming/expected/capsmetric.rs | 54 - .../code/rust/tests/naming/expected/metric.rs | 62 ++ .../code/rust/tests/naming/expected/mod.rs | 4 +- templates/code/rust/tests/naming/test.rs | 8 +- .../tests/no_namespace/expected/attribute.rs | 366 +++++++ .../rust/tests/no_namespace/expected/event.rs | 49 + .../no_namespace/expected/exceptionattr.rs | 130 --- .../no_namespace/expected/exceptionevent.rs | 41 - .../no_namespace/expected/heartbeatattr.rs | 106 -- .../tests/no_namespace/expected/hostattr.rs | 130 --- .../rust/tests/no_namespace/expected/mod.rs | 10 +- .../expected/{hostentity.rs => resource.rs} | 26 +- .../expected/{heartbeatspan.rs => trace.rs} | 52 +- .../code/rust/tests/no_namespace/test.rs | 26 +- .../rust/tests/params/expected/attribute.rs | 195 ++++ .../rust/tests/params/expected/billingattr.rs | 130 --- .../tests/params/expected/billingmetric.rs | 40 - .../expected/{billingevent.rs => event.rs} | 22 +- .../code/rust/tests/params/expected/metric.rs | 44 + .../code/rust/tests/params/expected/mod.rs | 9 +- .../rust/tests/params/expected/myappattr.rs | 65 -- .../expected/{billingspan.rs => trace.rs} | 20 +- templates/code/rust/tests/params/test.rs | 24 +- .../spans/compile-fail/missing_required.rs | 4 +- ...sampling_attribute_late.expected-error.txt | 2 +- .../compile-fail/sampling_attribute_late.rs | 8 +- .../rust/tests/spans/expected/attribute.rs | 602 +++++++++++ .../code/rust/tests/spans/expected/mod.rs | 6 +- .../rust/tests/spans/expected/myappattr.rs | 496 --------- .../spans/expected/{myappspan.rs => trace.rs} | 327 ++++-- .../rust/tests/spans/expected/workerattr.rs | 106 -- .../rust/tests/spans/expected/workerspan.rs | 73 -- templates/code/rust/tests/spans/test.rs | 82 +- .../rust/tests/spans/tests/allocations.rs | 36 +- templates/code/rust/weaver.yaml | 103 +- 150 files changed, 6018 insertions(+), 5605 deletions(-) rename templates/code/rust/tests/allocations/expected/{probeattr.rs => attribute.rs} (60%) create mode 100644 templates/code/rust/tests/allocations/expected/event.rs create mode 100644 templates/code/rust/tests/allocations/expected/metric.rs delete mode 100644 templates/code/rust/tests/allocations/expected/probeevent.rs delete mode 100644 templates/code/rust/tests/allocations/expected/probemetric.rs create mode 100644 templates/code/rust/tests/attributes/expected/attribute.rs delete mode 100644 templates/code/rust/tests/attributes/expected/authattr.rs delete mode 100644 templates/code/rust/tests/attributes/expected/myappattr.rs rename templates/code/rust/tests/codegen_exclusion/expected/{demoattr.rs => attribute.rs} (61%) rename templates/code/rust/tests/entities/expected/{myappattr.rs => attribute.rs} (57%) rename templates/code/rust/tests/entities/expected/{myappentity.rs => resource.rs} (58%) create mode 100644 templates/code/rust/tests/error_cross_namespace_collision/expected-error.txt create mode 100644 templates/code/rust/tests/error_cross_namespace_collision/registry/manifest.yaml create mode 100644 templates/code/rust/tests/error_cross_namespace_collision/registry/model.yaml delete mode 100644 templates/code/rust/tests/error_event_option_collision/expected-error.txt delete mode 100644 templates/code/rust/tests/error_event_option_collision/registry/manifest.yaml delete mode 100644 templates/code/rust/tests/error_event_option_collision/registry/model.yaml create mode 100644 templates/code/rust/tests/error_metric_attr_collision/expected-error.txt create mode 100644 templates/code/rust/tests/error_metric_attr_collision/registry/manifest.yaml create mode 100644 templates/code/rust/tests/error_metric_attr_collision/registry/model.yaml rename templates/code/rust/tests/event_no_attributes/expected/{probeevent.rs => event.rs} (59%) rename templates/code/rust/tests/events/expected/{myappattr.rs => attribute.rs} (51%) create mode 100644 templates/code/rust/tests/events/expected/event.rs delete mode 100644 templates/code/rust/tests/events/expected/myappevent.rs delete mode 100644 templates/code/rust/tests/events/expected/workerattr.rs delete mode 100644 templates/code/rust/tests/events/expected/workerevent.rs create mode 100644 templates/code/rust/tests/filtering/expected/attribute.rs delete mode 100644 templates/code/rust/tests/filtering/expected/authattr.rs delete mode 100644 templates/code/rust/tests/filtering/expected/taskattr.rs rename templates/code/rust/tests/{imported/expected/myappattr.rs => histogram_boundaries_by_unit/expected/attribute.rs} (62%) rename templates/code/rust/tests/histogram_boundaries_by_unit/expected/{myappmetric.rs => metric.rs} (51%) rename templates/code/rust/tests/{histogram_boundaries_by_unit/expected/myappattr.rs => histogram_boundaries_by_unit_params/expected/attribute.rs} (62%) create mode 100644 templates/code/rust/tests/histogram_boundaries_by_unit_params/expected/metric.rs delete mode 100644 templates/code/rust/tests/histogram_boundaries_by_unit_params/expected/myappmetric.rs rename templates/code/rust/tests/{histogram_boundaries_by_unit_params/expected/myappattr.rs => imported/expected/attribute.rs} (62%) delete mode 100644 templates/code/rust/tests/imported/expected/edgeevent.rs delete mode 100644 templates/code/rust/tests/imported/expected/edgemetric.rs create mode 100644 templates/code/rust/tests/imported/expected/event.rs create mode 100644 templates/code/rust/tests/imported/expected/metric.rs delete mode 100644 templates/code/rust/tests/imported/expected/myappmetric.rs rename templates/code/rust/tests/imported/expected/{edgespan.rs => trace.rs} (65%) rename templates/code/rust/tests/imported_typed/expected/{myappattr.rs => attribute.rs} (62%) create mode 100644 templates/code/rust/tests/imported_typed/expected/event.rs create mode 100644 templates/code/rust/tests/imported_typed/expected/metric.rs delete mode 100644 templates/code/rust/tests/imported_typed/expected/myappevent.rs delete mode 100644 templates/code/rust/tests/imported_typed/expected/myappmetric.rs rename templates/code/rust/tests/imported_typed/expected/{myappspan.rs => trace.rs} (61%) rename templates/code/rust/tests/integer_boundaries/expected/{demoattr.rs => attribute.rs} (50%) rename templates/code/rust/tests/literal_escaping/expected/{demoattr.rs => attribute.rs} (57%) delete mode 100644 templates/code/rust/tests/literal_escaping/expected/demometric.rs create mode 100644 templates/code/rust/tests/literal_escaping/expected/metric.rs create mode 100644 templates/code/rust/tests/metrics/expected/attribute.rs delete mode 100644 templates/code/rust/tests/metrics/expected/authattr.rs delete mode 100644 templates/code/rust/tests/metrics/expected/authmetric.rs create mode 100644 templates/code/rust/tests/metrics/expected/metric.rs delete mode 100644 templates/code/rust/tests/metrics/expected/myappattr.rs delete mode 100644 templates/code/rust/tests/metrics/expected/myappmetric.rs delete mode 100644 templates/code/rust/tests/metrics/expected/workermetric.rs rename templates/code/rust/tests/naming/expected/{capsattr.rs => attribute.rs} (57%) delete mode 100644 templates/code/rust/tests/naming/expected/capsmetric.rs create mode 100644 templates/code/rust/tests/naming/expected/metric.rs create mode 100644 templates/code/rust/tests/no_namespace/expected/attribute.rs create mode 100644 templates/code/rust/tests/no_namespace/expected/event.rs delete mode 100644 templates/code/rust/tests/no_namespace/expected/exceptionattr.rs delete mode 100644 templates/code/rust/tests/no_namespace/expected/exceptionevent.rs delete mode 100644 templates/code/rust/tests/no_namespace/expected/heartbeatattr.rs delete mode 100644 templates/code/rust/tests/no_namespace/expected/hostattr.rs rename templates/code/rust/tests/no_namespace/expected/{hostentity.rs => resource.rs} (63%) rename templates/code/rust/tests/no_namespace/expected/{heartbeatspan.rs => trace.rs} (57%) create mode 100644 templates/code/rust/tests/params/expected/attribute.rs delete mode 100644 templates/code/rust/tests/params/expected/billingattr.rs delete mode 100644 templates/code/rust/tests/params/expected/billingmetric.rs rename templates/code/rust/tests/params/expected/{billingevent.rs => event.rs} (50%) create mode 100644 templates/code/rust/tests/params/expected/metric.rs delete mode 100644 templates/code/rust/tests/params/expected/myappattr.rs rename templates/code/rust/tests/params/expected/{billingspan.rs => trace.rs} (68%) create mode 100644 templates/code/rust/tests/spans/expected/attribute.rs delete mode 100644 templates/code/rust/tests/spans/expected/myappattr.rs rename templates/code/rust/tests/spans/expected/{myappspan.rs => trace.rs} (59%) delete mode 100644 templates/code/rust/tests/spans/expected/workerattr.rs delete mode 100644 templates/code/rust/tests/spans/expected/workerspan.rs diff --git a/templates/code/rust/README.md b/templates/code/rust/README.md index f39ff89..b54a61b 100644 --- a/templates/code/rust/README.md +++ b/templates/code/rust/README.md @@ -36,24 +36,26 @@ Keep the consuming crate's files outside that directory. ## Generated API -The root `mod.rs` carries `SCHEMA_URL` and declares the generated modules. -Each attribute namespace lives in a sibling `attr.rs` file, alongside -the signal modules. Names use the first dotted -segment as their namespace; `vendor_prefixes` removes a leading vendor segment -before choosing that namespace. - -| Module | API | -| ------------------- | ---------------------------------------------------------------------------------------------- | -| `attr` | Attribute newtypes and enum variants, `KEY` and conversions into `KeyValue` or log `AnyValue`. | -| `options` | Typed instrumentation options containing scope configuration. | -| `scope` | Scope attributes configuration; package identity is fixed. | -| `meter` | Schema-aware `Meter`, with `new`, `inner`, and a no-op `Default`. | -| `tracer` | Schema-aware `Tracer`, with `new`, `inner`, and a no-op `Default`. | -| `logger` | Schema-aware generic `Logger`, with `new`, `inner`, and a no-op `Default`. | -| `metric` | Synchronous instruments and observable counters, up-down counters, and gauges. | -| `span` | Span starters, typed names, start attributes, and attributes allowed after starting. | -| `event` | Typed log event emitters and options for attributes, severity, and timestamp. | -| `entity` | Typed entity values, attribute iterators, and resources carrying the registry schema URL. | +The root `mod.rs` carries `SCHEMA_URL` and declares the generated modules. The +layout mirrors the `opentelemetry-semantic-conventions` crate: one flat module +per signal, holding every namespace. Each generated type and function name +starts with its namespace, the first dotted segment of the registry name; +`vendor_prefixes` removes a leading vendor segment before choosing that +namespace. For example, `myapp.task.id` becomes `attribute::MyappTaskId`, +and the `myapp.task.run` span starter becomes `trace::start_myapp_task_run`. + +| Module | API | +| ----------- | ---------------------------------------------------------------------------------------------- | +| `attribute` | Attribute newtypes and enum variants, `KEY` and conversions into `KeyValue` or log `AnyValue`. | +| `options` | Typed instrumentation options containing scope configuration. | +| `scope` | Scope attributes configuration; package identity is fixed. | +| `meter` | Schema-aware `Meter`, with `new`, `inner`, and a no-op `Default`. | +| `tracer` | Schema-aware `Tracer`, with `new`, `inner`, and a no-op `Default`. | +| `logger` | Schema-aware generic `Logger`, with `new`, `inner`, and a no-op `Default`. | +| `metric` | Synchronous instruments and observable counters, up-down counters, and gauges. | +| `trace` | Span starters, typed names, start attributes, and attributes allowed after starting. | +| `event` | Typed log event emitters and options for attributes, severity, and timestamp. | +| `resource` | Typed entity values, attribute iterators, and resources carrying the registry schema URL. | Handle modules are emitted when the registry includes their corresponding signals. Their `new(provider, options)` constructor takes the exact @@ -83,16 +85,16 @@ Attribute keys, metric names, and event names retain their full registry names. ### Typed attributes An attribute such as `myapp.task.id` becomes -`myappattr::TaskIdAttr::from("task-1")`. Convert the attribute into an OpenTelemetry `KeyValue` with +`attribute::MyappTaskId::from("task-1")`. Convert the attribute into an OpenTelemetry `KeyValue` with `KeyValue::from(attribute)` or `attribute.into()`. String attributes implement `From`, `From<&'static str>`, and `From`. Static strings retain their static storage. Own a dynamic borrowed string -explicitly, such as `Attr::from(text.to_owned())`. Scalar and array attributes +explicitly, such as `MyappTaskId::from(text.to_owned())`. Scalar and array attributes implement `From` for their backing types; string arrays accept `Vec` and native `Vec`. Native storage moves into the SDK -without rebuilding the vector. Use `Attr::from(value)` or `value.into()` when +without rebuilding the vector. Use `MyappTaskId::from(value)` or `value.into()` when the attribute type is known. Enums expose named variants, -such as `myappattr::TaskStateAttr::Running`, rather than arbitrary constructors. +such as `attribute::MyappTaskState::Running`, rather than arbitrary constructors. Supported backing types are `StringValue`, `i64`, `f64`, `bool`, and their `Vec` forms. Enums can have string, integer, fractional, or boolean values. @@ -103,14 +105,14 @@ formatting. Boolean, integer, floating-point and enum attributes are `Copy`. Deprecation metadata becomes Rust deprecation annotations. Attributes also convert directly into `opentelemetry::logs::AnyValue` through -`From`. Generated event emitters pass `Attr::KEY` and the typed attribute to +`From`. Generated event emitters pass the attribute type's `KEY` and the typed attribute to the SDK log record. ### Metrics Each metric becomes a typed instrument with a `new(&meter)` constructor and an `add` or `record` method. Required attributes are typed arguments. Other -attributes are variants of the instrument's `Attr` enum, passed as an iterator. +attributes are variants of the metric's `Attr` enum, such as `metric::MyappTaskDurationAttr`, passed as an iterator. Observable constructors register a callback whose typed observer has the same required arguments and optional attribute contract. @@ -203,12 +205,36 @@ params: error: upstream ``` -That mapping refers to `upstream::errorattr` in the consuming crate. Both +That mapping refers to `upstream::attribute` in the consuming crate, so +`error.type` becomes `upstream::attribute::ErrorType`. Both registries must use compatible namespace and vendor-prefix settings. Plain imported strings use `opentelemetry::StringValue`, and string arrays use `Vec`, preserving their SDK storage. Convert a static string with `.into()` or `StringValue::from` at the call site. +### Signal metadata + +Signal types carry their registry metadata as associated constants, usable in +`const` contexts. The generated code reads these constants, so each value +appears once. + +| Type | Constants | +| ----------------------------------- | ---------------------------------------------------------------- | +| `metric::MyappTaskDuration` | `NAME`, `UNIT`, `DESCRIPTION` | +| `metric::MyappQueueDepthObservable` | `NAME`, `UNIT`, `DESCRIPTION`, defined as the synchronous type's | +| `trace::MyappTaskRun` | `NAME`, the span type | +| `event::MyappTaskFinished` | `NAME`, the event name | +| `resource::MyappHost` | `NAME`, the entity type | + +`UNIT` and `DESCRIPTION` are empty strings when the registry leaves them unset. +Refinements report the type they refine. Each event has a unit struct that +holds its `NAME`; emitting still goes through its `emit_` function. + +```rust +const DURATION: &str = metric::MyappTaskDuration::NAME; +assert_eq!(metric::MyappTaskDuration::UNIT, "s"); +``` + ## Parameters | Parameter | Default | Purpose | diff --git a/templates/code/rust/entities.rs.j2 b/templates/code/rust/entities.rs.j2 index 7483a33..de95b1f 100644 --- a/templates/code/rust/entities.rs.j2 +++ b/templates/code/rust/entities.rs.j2 @@ -8,7 +8,7 @@ // Code generated by weaver. DO NOT EDIT. #![allow(deprecated)] {% for def in ctx.entities %} -{%- set name = s.exported(def.short_name) ~ "Entity" %} +{%- set name = s.exported(def.qualified) %} {% if def.optional %} #[derive(Clone, Debug)] pub enum {{ name }}Attr { @@ -46,6 +46,8 @@ pub struct {{ name }} { } impl {{ name }} { + pub const NAME: &'static str = {{ s.literal(def.type) }}; + pub fn new({% for req in def.required %}{{ s.ident(req.attr_param) }}: {{ s.attr_type(req) }}, {% endfor %}{% if def.optional %}options: impl IntoIterator{% endif %}) -> Self { Self { {% for req in def.required %} diff --git a/templates/code/rust/events.rs.j2 b/templates/code/rust/events.rs.j2 index 2af44aa..46d9c26 100644 --- a/templates/code/rust/events.rs.j2 +++ b/templates/code/rust/events.rs.j2 @@ -5,7 +5,15 @@ use ::opentelemetry::trace::TraceContextExt; {% import "signal_helpers.j2" as h %} {% for def in ctx.events %} -{% set name = h.exported(def.short_name) or 'Event' %} +{% set name = h.exported(def.qualified) %} +{{ (h.docs(def) ~ "\n" ~ h.deprecated(def)) | trim }} +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct {{ name }}; + +impl {{ name }} { + pub const NAME: &'static str = {{ h.literal(def.name) }}; +} + #[derive(Clone, Debug)] pub enum {{ name }}Option { Severity(::opentelemetry::logs::Severity), @@ -18,7 +26,7 @@ pub enum {{ name }}Option { {% endfor %} } {{ (h.docs(def) ~ "\n" ~ h.deprecated(def)) | trim }} -pub fn {{ h.signal_fn('emit', def.short_name) }}(context: &::opentelemetry::Context, logger: &super::logger::Logger{% for req in def.required %}, {{ h.ident(req.attr_param) }}: {{ h.attr_type(req) }}{% endfor %}, options: impl IntoIterator) { +pub fn {{ h.signal_fn('emit', def.qualified) }}(context: &::opentelemetry::Context, logger: &super::logger::Logger{% for req in def.required %}, {{ h.ident(req.attr_param) }}: {{ h.attr_type(req) }}{% endfor %}, options: impl IntoIterator) { let mut severity = ::opentelemetry::logs::Severity::Info; let mut timestamp = None; {% if def.optional %} @@ -33,10 +41,10 @@ pub fn {{ h.signal_fn('emit', def.short_name) }} Self { - let instrument = meter.inner().{{ builder }}({{ h.literal(def.instrument_name) }}) - .with_description({{ h.literal(def.description | trim) }}) - .with_unit({{ h.literal(def.unit) }}) + let instrument = meter.inner().{{ builder }}(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) {% if def.bucket_boundaries %} .with_boundaries(vec![{% for bound in def.bucket_boundaries %}{{ bound }}_f64{% if not loop.last %}, {% endif %}{% endfor %}]) {% endif %} @@ -63,7 +67,7 @@ impl Default for {{ name }} { fn default() -> Self { Self::new(&super::meter::Meter::default()) } } {% if def.instrument != 'histogram' %} -{% set observable = h.exported(def.short_name) ~ 'Observable' ~ suffix %} +{% set observable = name ~ 'Observable' %} pub struct {{ name }}Observer<'a> { observer: &'a dyn ::opentelemetry::metrics::AsyncInstrument<{{ value_type }}>, } @@ -89,10 +93,14 @@ pub struct {{ observable }} { } impl {{ observable }} { + pub const NAME: &'static str = {{ name }}::NAME; + pub const UNIT: &'static str = {{ name }}::UNIT; + pub const DESCRIPTION: &'static str = {{ name }}::DESCRIPTION; + pub fn new(meter: &super::meter::Meter, callback: impl Fn({{ name }}Observer<'_>) + Send + Sync + 'static) -> Self { - let instrument = meter.inner().{{ value_type }}_observable_{{ 'up_down_counter' if def.instrument == 'updowncounter' else def.instrument }}({{ h.literal(def.instrument_name) }}) - .with_description({{ h.literal(def.description | trim) }}) - .with_unit({{ h.literal(def.unit) }}) + let instrument = meter.inner().{{ value_type }}_observable_{{ 'up_down_counter' if def.instrument == 'updowncounter' else def.instrument }}(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) .with_callback(move |observer| callback({{ name }}Observer { observer })) .build(); Self { _instrument: instrument } diff --git a/templates/code/rust/mod.rs.j2 b/templates/code/rust/mod.rs.j2 index 229f253..8e4c236 100644 --- a/templates/code/rust/mod.rs.j2 +++ b/templates/code/rust/mod.rs.j2 @@ -8,9 +8,9 @@ // Regenerate: {{ params.regenerate_command | replace("\n", " ") | replace("\r", " ") }} {% endif %} pub const SCHEMA_URL: &str = {{ ctx.schema_literal }}; -{% for namespace in ctx.namespaces %} -pub mod {{ namespace }}; -{% endfor %} +{% if ctx.has_attributes %} +pub mod attribute; +{% endif %} {% if ctx.has_metrics or ctx.has_spans or ctx.has_events %} pub mod scope; diff --git a/templates/code/rust/signal_helpers.j2 b/templates/code/rust/signal_helpers.j2 index 90ef6e9..2ef7395 100644 --- a/templates/code/rust/signal_helpers.j2 +++ b/templates/code/rust/signal_helpers.j2 @@ -6,7 +6,7 @@ {% macro signal_fn(prefix, short_name) -%}{{ ident(prefix ~ ('.' ~ short_name if short_name else '')) }}{%- endmacro %} {% macro attr_type(a) -%} {%- if a.imported -%}{{ "::opentelemetry::StringValue" if a.attr_type == "string" else ("Vec<::opentelemetry::StringValue>" if a.attr_type == "string[]" else a.attr_type | map_text("rust_type")) }} -{%- else -%}{{ a.attr_import_path if a.attr_import_path else 'super::' ~ a.attr_namespace ~ 'attr' }}::{{ exported(a.attr_short_name) }}Attr +{%- else -%}{{ a.attr_import_path if a.attr_import_path else 'super::attribute' }}::{{ exported(a.attr_param) }} {%- endif -%} {%- endmacro %} {% macro attr_kv(a, value) -%} diff --git a/templates/code/rust/spans.rs.j2 b/templates/code/rust/spans.rs.j2 index 9a11638..980f6f1 100644 --- a/templates/code/rust/spans.rs.j2 +++ b/templates/code/rust/spans.rs.j2 @@ -1,6 +1,6 @@ {%- filter trim %} #![allow(deprecated)] -use ::opentelemetry::trace::{TraceContextExt, Tracer}; +use ::opentelemetry::trace::{TraceContextExt as _, Tracer as _}; {% macro needs_name_formatting(definitions) -%} {%- for definition in definitions -%} {%- for part in definition.name_parts or [] -%} @@ -9,7 +9,7 @@ use ::opentelemetry::trace::{TraceContextExt, Tracer}; {%- endfor -%} {%- endmacro %} {% if needs_name_formatting(ctx.spans) %} -use ::std::fmt::Write; +use ::std::fmt::Write as _; {% endif %} {% import "signal_helpers.j2" as h %} @@ -32,8 +32,8 @@ use ::std::fmt::Write; {%- endif -%} {%- endmacro %} {% for def in ctx.spans %} -{% set name = h.exported(def.short_name) %} -{% set span = name ~ 'Span' %} +{% set name = h.exported(def.qualified) %} +{% set span = name %} {% if def.optional %} #[derive(Clone, Debug)] pub enum {{ name }}StartAttr { @@ -112,13 +112,17 @@ impl {{ span }} { {% endif %} } +impl {{ span }} { + pub const NAME: &'static str = {{ h.literal(def.type) }}; +} + impl Default for {{ span }} { fn default() -> Self { - Self { span: super::tracer::Tracer::default().inner().start({{ h.literal(def.type) }}) } + Self { span: super::tracer::Tracer::default().inner().start(Self::NAME) } } } {{ h.deprecated(def) }} -pub fn {{ h.signal_fn('start', def.short_name) }}(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer{% if not def.name_parts %}, name: {{ name }}Name{% endif %}{% for req in def.required %}, {{ h.ident(req.attr_param) }}: {{ h.attr_type(req) }}{% endfor %}{% if def.optional %}, options: impl IntoIterator{% endif %}) -> {{ span }} { +pub fn {{ h.signal_fn('start', def.qualified) }}(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer{% if not def.name_parts %}, name: {{ name }}Name{% endif %}{% for req in def.required %}, {{ h.ident(req.attr_param) }}: {{ h.attr_type(req) }}{% endfor %}{% if def.optional %}, options: impl IntoIterator{% endif %}) -> {{ span }} { {% if def.name_parts %} let mut name = String::with_capacity({% for part in def.name_parts %}{% if not loop.first %} + {% endif %}{% if part.attr %}{{ name_capacity(part.attr, h.ident(part.attr.attr_param)) }}{% else %}{{ h.literal(part.text) }}.len(){% endif %}{% endfor %}); {% for part in def.name_parts %} @@ -142,7 +146,7 @@ pub fn {{ h.signal_fn('start', def.short_name) }} for FlagAttr { +impl From for ProbeFlag { #[inline] fn from(value: bool) -> Self { Self(value) @@ -17,7 +17,7 @@ impl From for FlagAttr { } #[allow(deprecated)] -impl ::std::fmt::Display for FlagAttr { +impl ::std::fmt::Display for ProbeFlag { #[inline] fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { ::std::fmt::Display::fmt(&self.0, formatter) @@ -25,32 +25,32 @@ impl ::std::fmt::Display for FlagAttr { } #[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { +impl From for ::opentelemetry::KeyValue { #[inline] - fn from(value: FlagAttr) -> Self { - ::opentelemetry::KeyValue::new(FlagAttr::KEY, value.0) + fn from(value: ProbeFlag) -> Self { + ::opentelemetry::KeyValue::new(ProbeFlag::KEY, value.0) } } #[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { +impl From for ::opentelemetry::logs::AnyValue { #[inline] - fn from(value: FlagAttr) -> Self { + fn from(value: ProbeFlag) -> Self { value.0.into() } } /// A synthetic fractional value. #[derive(Debug, Clone, PartialEq, Copy)] -pub struct FractionAttr(f64); +pub struct ProbeFraction(f64); #[allow(deprecated)] -impl FractionAttr { +impl ProbeFraction { pub const KEY: &'static str = "probe.fraction"; } #[allow(deprecated)] -impl From for FractionAttr { +impl From for ProbeFraction { #[inline] fn from(value: f64) -> Self { Self(value) @@ -58,7 +58,7 @@ impl From for FractionAttr { } #[allow(deprecated)] -impl ::std::fmt::Display for FractionAttr { +impl ::std::fmt::Display for ProbeFraction { #[inline] fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { ::std::fmt::Display::fmt(&self.0, formatter) @@ -66,32 +66,32 @@ impl ::std::fmt::Display for FractionAttr { } #[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { +impl From for ::opentelemetry::KeyValue { #[inline] - fn from(value: FractionAttr) -> Self { - ::opentelemetry::KeyValue::new(FractionAttr::KEY, value.0) + fn from(value: ProbeFraction) -> Self { + ::opentelemetry::KeyValue::new(ProbeFraction::KEY, value.0) } } #[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { +impl From for ::opentelemetry::logs::AnyValue { #[inline] - fn from(value: FractionAttr) -> Self { + fn from(value: ProbeFraction) -> Self { value.0.into() } } /// A synthetic text value. #[derive(Debug, Clone, PartialEq)] -pub struct LabelAttr(::opentelemetry::StringValue); +pub struct ProbeLabel(::opentelemetry::StringValue); #[allow(deprecated)] -impl LabelAttr { +impl ProbeLabel { pub const KEY: &'static str = "probe.label"; } #[allow(deprecated)] -impl From<::opentelemetry::StringValue> for LabelAttr { +impl From<::opentelemetry::StringValue> for ProbeLabel { #[inline] fn from(value: ::opentelemetry::StringValue) -> Self { Self(value) @@ -99,7 +99,7 @@ impl From<::opentelemetry::StringValue> for LabelAttr { } #[allow(deprecated)] -impl From for LabelAttr { +impl From for ProbeLabel { #[inline] fn from(value: String) -> Self { Self(value.into()) @@ -107,7 +107,7 @@ impl From for LabelAttr { } #[allow(deprecated)] -impl From<&'static str> for LabelAttr { +impl From<&'static str> for ProbeLabel { #[inline] fn from(value: &'static str) -> Self { Self(value.into()) @@ -115,7 +115,7 @@ impl From<&'static str> for LabelAttr { } #[allow(deprecated)] -impl AsRef for LabelAttr { +impl AsRef for ProbeLabel { #[inline] fn as_ref(&self) -> &str { self.0.as_str() @@ -123,7 +123,7 @@ impl AsRef for LabelAttr { } #[allow(deprecated)] -impl ::std::fmt::Display for LabelAttr { +impl ::std::fmt::Display for ProbeLabel { #[inline] fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { formatter.write_str(self.as_ref()) @@ -131,32 +131,32 @@ impl ::std::fmt::Display for LabelAttr { } #[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { +impl From for ::opentelemetry::KeyValue { #[inline] - fn from(value: LabelAttr) -> Self { - ::opentelemetry::KeyValue::new(LabelAttr::KEY, value.0) + fn from(value: ProbeLabel) -> Self { + ::opentelemetry::KeyValue::new(ProbeLabel::KEY, value.0) } } #[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { +impl From for ::opentelemetry::logs::AnyValue { #[inline] - fn from(value: LabelAttr) -> Self { + fn from(value: ProbeLabel) -> Self { value.0.into() } } /// Optional numeric measurement identity. #[derive(Debug, Clone, PartialEq, Copy)] -pub struct OptionalAttr(i64); +pub struct ProbeOptional(i64); #[allow(deprecated)] -impl OptionalAttr { +impl ProbeOptional { pub const KEY: &'static str = "probe.optional"; } #[allow(deprecated)] -impl From for OptionalAttr { +impl From for ProbeOptional { #[inline] fn from(value: i64) -> Self { Self(value) @@ -164,7 +164,7 @@ impl From for OptionalAttr { } #[allow(deprecated)] -impl ::std::fmt::Display for OptionalAttr { +impl ::std::fmt::Display for ProbeOptional { #[inline] fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { ::std::fmt::Display::fmt(&self.0, formatter) @@ -172,32 +172,32 @@ impl ::std::fmt::Display for OptionalAttr { } #[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { +impl From for ::opentelemetry::KeyValue { #[inline] - fn from(value: OptionalAttr) -> Self { - ::opentelemetry::KeyValue::new(OptionalAttr::KEY, value.0) + fn from(value: ProbeOptional) -> Self { + ::opentelemetry::KeyValue::new(ProbeOptional::KEY, value.0) } } #[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { +impl From for ::opentelemetry::logs::AnyValue { #[inline] - fn from(value: OptionalAttr) -> Self { + fn from(value: ProbeOptional) -> Self { value.0.into() } } /// Required numeric measurement identity. #[derive(Debug, Clone, PartialEq, Copy)] -pub struct RequiredAttr(i64); +pub struct ProbeRequired(i64); #[allow(deprecated)] -impl RequiredAttr { +impl ProbeRequired { pub const KEY: &'static str = "probe.required"; } #[allow(deprecated)] -impl From for RequiredAttr { +impl From for ProbeRequired { #[inline] fn from(value: i64) -> Self { Self(value) @@ -205,7 +205,7 @@ impl From for RequiredAttr { } #[allow(deprecated)] -impl ::std::fmt::Display for RequiredAttr { +impl ::std::fmt::Display for ProbeRequired { #[inline] fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { ::std::fmt::Display::fmt(&self.0, formatter) @@ -213,32 +213,32 @@ impl ::std::fmt::Display for RequiredAttr { } #[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { +impl From for ::opentelemetry::KeyValue { #[inline] - fn from(value: RequiredAttr) -> Self { - ::opentelemetry::KeyValue::new(RequiredAttr::KEY, value.0) + fn from(value: ProbeRequired) -> Self { + ::opentelemetry::KeyValue::new(ProbeRequired::KEY, value.0) } } #[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { +impl From for ::opentelemetry::logs::AnyValue { #[inline] - fn from(value: RequiredAttr) -> Self { + fn from(value: ProbeRequired) -> Self { value.0.into() } } /// Numeric values attached to an event. #[derive(Debug, Clone, PartialEq)] -pub struct ValuesAttr(Vec); +pub struct ProbeValues(Vec); #[allow(deprecated)] -impl ValuesAttr { +impl ProbeValues { pub const KEY: &'static str = "probe.values"; } #[allow(deprecated)] -impl From> for ValuesAttr { +impl From> for ProbeValues { #[inline] fn from(value: Vec) -> Self { Self(value) @@ -246,7 +246,7 @@ impl From> for ValuesAttr { } #[allow(deprecated)] -impl AsRef<[i64]> for ValuesAttr { +impl AsRef<[i64]> for ProbeValues { #[inline] fn as_ref(&self) -> &[i64] { &self.0 @@ -254,7 +254,7 @@ impl AsRef<[i64]> for ValuesAttr { } #[allow(deprecated)] -impl ::std::fmt::Display for ValuesAttr { +impl ::std::fmt::Display for ProbeValues { fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { formatter.write_str("[")?; for (index, value) in self.0.iter().enumerate() { @@ -268,17 +268,17 @@ impl ::std::fmt::Display for ValuesAttr { } #[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { +impl From for ::opentelemetry::KeyValue { #[inline] - fn from(value: ValuesAttr) -> Self { - ::opentelemetry::KeyValue::new(ValuesAttr::KEY, ::opentelemetry::Value::Array(::opentelemetry::Array::I64(value.0))) + fn from(value: ProbeValues) -> Self { + ::opentelemetry::KeyValue::new(ProbeValues::KEY, ::opentelemetry::Value::Array(::opentelemetry::Array::I64(value.0))) } } #[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { +impl From for ::opentelemetry::logs::AnyValue { #[inline] - fn from(value: ValuesAttr) -> Self { + fn from(value: ProbeValues) -> Self { value.0.into_iter().collect::<::opentelemetry::logs::AnyValue>() } } diff --git a/templates/code/rust/tests/allocations/expected/event.rs b/templates/code/rust/tests/allocations/expected/event.rs new file mode 100644 index 0000000..17877ec --- /dev/null +++ b/templates/code/rust/tests/allocations/expected/event.rs @@ -0,0 +1,51 @@ +#![allow(deprecated)] +use ::opentelemetry::logs::LogRecord; +use ::opentelemetry::trace::TraceContextExt; + +/// A measurement was recorded. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct ProbeRecorded; + +impl ProbeRecorded { + pub const NAME: &'static str = "probe.recorded"; +} + +#[derive(Clone, Debug)] +pub enum ProbeRecordedOption { + Severity(::opentelemetry::logs::Severity), + Timestamp(::std::time::SystemTime), + Optional(super::attribute::ProbeOptional), + Values(super::attribute::ProbeValues), +} +/// A measurement was recorded. +pub fn r#emit_probe_recorded(context: &::opentelemetry::Context, logger: &super::logger::Logger, r#probe_required: super::attribute::ProbeRequired, options: impl IntoIterator) { + let mut severity = ::opentelemetry::logs::Severity::Info; + let mut timestamp = None; + let mut attributes = ::smallvec::SmallVec::<[ProbeRecordedOption; 2]>::new(); + for option in options { + match option { + ProbeRecordedOption::Severity(value) => severity = value, + ProbeRecordedOption::Timestamp(value) => timestamp = Some(value), + attribute => attributes.push(attribute), + } + } + if !logger.inner().event_enabled(severity, "", Some(ProbeRecorded::NAME)) { return; } + let _context_guard = context.clone().attach(); + let mut record = logger.inner().create_log_record(); + record.set_event_name(ProbeRecorded::NAME); + record.set_severity_number(severity); + record.set_observed_timestamp(::std::time::SystemTime::now()); + if let Some(timestamp) = timestamp { record.set_timestamp(timestamp); } + let span = context.span(); + let span_context = span.span_context(); + if span_context.is_valid() { record.set_trace_context(span_context.trace_id(), span_context.span_id(), Some(span_context.trace_flags())); } + record.add_attribute(super::attribute::ProbeRequired::KEY, r#probe_required); + for option in attributes { + match option { + ProbeRecordedOption::Optional(value) => record.add_attribute(super::attribute::ProbeOptional::KEY, value), + ProbeRecordedOption::Values(value) => record.add_attribute(super::attribute::ProbeValues::KEY, value), + ProbeRecordedOption::Severity(_) | ProbeRecordedOption::Timestamp(_) => continue, + } + } + logger.inner().emit(record); +} diff --git a/templates/code/rust/tests/allocations/expected/metric.rs b/templates/code/rust/tests/allocations/expected/metric.rs new file mode 100644 index 0000000..48ff53e --- /dev/null +++ b/templates/code/rust/tests/allocations/expected/metric.rs @@ -0,0 +1,139 @@ +#![allow(deprecated)] +#[derive(Clone, Debug)] +pub enum ProbeOptionalAttr { + Optional(super::attribute::ProbeOptional), +} + +impl From for ::opentelemetry::KeyValue { + fn from(value: ProbeOptionalAttr) -> Self { + match value { + ProbeOptionalAttr::Optional(value) => ::opentelemetry::KeyValue::from(value), + } + } +} +/// Measurements with optional numeric attributes. +#[derive(Clone)] +pub struct ProbeOptional { + instrument: ::opentelemetry::metrics::Counter, +} + +impl ProbeOptional { + pub const NAME: &'static str = "probe.optional"; + pub const UNIT: &'static str = "{measurement}"; + pub const DESCRIPTION: &'static str = "Measurements with optional numeric attributes."; + + pub fn new(meter: &super::meter::Meter) -> Self { + let instrument = meter.inner().u64_counter(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .build(); + Self { instrument } + } + pub fn add(&self, value: u64, r#probe_required: super::attribute::ProbeRequired, options: impl IntoIterator) { + let mut attributes = ::smallvec::SmallVec::<[::opentelemetry::KeyValue; 2]>::new(); + attributes.extend([::opentelemetry::KeyValue::from(r#probe_required)]); + attributes.extend(options.into_iter().map(::opentelemetry::KeyValue::from)); + self.instrument.add(value, &attributes); + } +} + +impl Default for ProbeOptional { + fn default() -> Self { Self::new(&super::meter::Meter::default()) } +} +pub struct ProbeOptionalObserver<'a> { + observer: &'a dyn ::opentelemetry::metrics::AsyncInstrument, +} + +impl ProbeOptionalObserver<'_> { + pub fn observe(&self, value: u64, r#probe_required: super::attribute::ProbeRequired, options: impl IntoIterator) { + let mut attributes = ::smallvec::SmallVec::<[::opentelemetry::KeyValue; 2]>::new(); + attributes.extend([::opentelemetry::KeyValue::from(r#probe_required)]); + attributes.extend(options.into_iter().map(::opentelemetry::KeyValue::from)); + self.observer.observe(value, &attributes); + } +} + +#[derive(Clone)] +pub struct ProbeOptionalObservable { + _instrument: ::opentelemetry::metrics::ObservableCounter, +} + +impl ProbeOptionalObservable { + pub const NAME: &'static str = ProbeOptional::NAME; + pub const UNIT: &'static str = ProbeOptional::UNIT; + pub const DESCRIPTION: &'static str = ProbeOptional::DESCRIPTION; + + pub fn new(meter: &super::meter::Meter, callback: impl Fn(ProbeOptionalObserver<'_>) + Send + Sync + 'static) -> Self { + let instrument = meter.inner().u64_observable_counter(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .with_callback(move |observer| callback(ProbeOptionalObserver { observer })) + .build(); + Self { _instrument: instrument } + } +} + +impl Default for ProbeOptionalObservable { + fn default() -> Self { Self::new(&super::meter::Meter::default(), |_| {}) } +} +/// Measurements with a required numeric attribute. +#[derive(Clone)] +pub struct ProbeRequired { + instrument: ::opentelemetry::metrics::Counter, +} + +impl ProbeRequired { + pub const NAME: &'static str = "probe.required"; + pub const UNIT: &'static str = "{measurement}"; + pub const DESCRIPTION: &'static str = "Measurements with a required numeric attribute."; + + pub fn new(meter: &super::meter::Meter) -> Self { + let instrument = meter.inner().u64_counter(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .build(); + Self { instrument } + } + pub fn add(&self, value: u64, r#probe_required: super::attribute::ProbeRequired) { + let attributes = [::opentelemetry::KeyValue::from(r#probe_required)]; + self.instrument.add(value, &attributes); + } +} + +impl Default for ProbeRequired { + fn default() -> Self { Self::new(&super::meter::Meter::default()) } +} +pub struct ProbeRequiredObserver<'a> { + observer: &'a dyn ::opentelemetry::metrics::AsyncInstrument, +} + +impl ProbeRequiredObserver<'_> { + pub fn observe(&self, value: u64, r#probe_required: super::attribute::ProbeRequired) { + let attributes = [::opentelemetry::KeyValue::from(r#probe_required)]; + self.observer.observe(value, &attributes); + } +} + +#[derive(Clone)] +pub struct ProbeRequiredObservable { + _instrument: ::opentelemetry::metrics::ObservableCounter, +} + +impl ProbeRequiredObservable { + pub const NAME: &'static str = ProbeRequired::NAME; + pub const UNIT: &'static str = ProbeRequired::UNIT; + pub const DESCRIPTION: &'static str = ProbeRequired::DESCRIPTION; + + pub fn new(meter: &super::meter::Meter, callback: impl Fn(ProbeRequiredObserver<'_>) + Send + Sync + 'static) -> Self { + let instrument = meter.inner().u64_observable_counter(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .with_callback(move |observer| callback(ProbeRequiredObserver { observer })) + .build(); + Self { _instrument: instrument } + } +} + +impl Default for ProbeRequiredObservable { + fn default() -> Self { Self::new(&super::meter::Meter::default(), |_| {}) } +} diff --git a/templates/code/rust/tests/allocations/expected/mod.rs b/templates/code/rust/tests/allocations/expected/mod.rs index afe3186..82c54f2 100644 --- a/templates/code/rust/tests/allocations/expected/mod.rs +++ b/templates/code/rust/tests/allocations/expected/mod.rs @@ -1,10 +1,10 @@ // Generated by OpenTelemetry Weaver. pub const SCHEMA_URL: &str = "https://example.com/schemas/allocations/1.0.0"; -pub mod probeattr; +pub mod attribute; pub mod scope; pub mod options; pub mod meter; pub mod logger; -pub mod probeevent; -pub mod probemetric; +pub mod event; +pub mod metric; diff --git a/templates/code/rust/tests/allocations/expected/probeevent.rs b/templates/code/rust/tests/allocations/expected/probeevent.rs deleted file mode 100644 index 5db4b38..0000000 --- a/templates/code/rust/tests/allocations/expected/probeevent.rs +++ /dev/null @@ -1,43 +0,0 @@ -#![allow(deprecated)] -use ::opentelemetry::logs::LogRecord; -use ::opentelemetry::trace::TraceContextExt; - -#[derive(Clone, Debug)] -pub enum RecordedOption { - Severity(::opentelemetry::logs::Severity), - Timestamp(::std::time::SystemTime), - Optional(super::probeattr::OptionalAttr), - Values(super::probeattr::ValuesAttr), -} -/// A measurement was recorded. -pub fn r#emit_recorded(context: &::opentelemetry::Context, logger: &super::logger::Logger, r#probe_required: super::probeattr::RequiredAttr, options: impl IntoIterator) { - let mut severity = ::opentelemetry::logs::Severity::Info; - let mut timestamp = None; - let mut attributes = ::smallvec::SmallVec::<[RecordedOption; 2]>::new(); - for option in options { - match option { - RecordedOption::Severity(value) => severity = value, - RecordedOption::Timestamp(value) => timestamp = Some(value), - attribute => attributes.push(attribute), - } - } - if !logger.inner().event_enabled(severity, "", Some("probe.recorded")) { return; } - let _context_guard = context.clone().attach(); - let mut record = logger.inner().create_log_record(); - record.set_event_name("probe.recorded"); - record.set_severity_number(severity); - record.set_observed_timestamp(::std::time::SystemTime::now()); - if let Some(timestamp) = timestamp { record.set_timestamp(timestamp); } - let span = context.span(); - let span_context = span.span_context(); - if span_context.is_valid() { record.set_trace_context(span_context.trace_id(), span_context.span_id(), Some(span_context.trace_flags())); } - record.add_attribute(super::probeattr::RequiredAttr::KEY, r#probe_required); - for option in attributes { - match option { - RecordedOption::Optional(value) => record.add_attribute(super::probeattr::OptionalAttr::KEY, value), - RecordedOption::Values(value) => record.add_attribute(super::probeattr::ValuesAttr::KEY, value), - RecordedOption::Severity(_) | RecordedOption::Timestamp(_) => continue, - } - } - logger.inner().emit(record); -} diff --git a/templates/code/rust/tests/allocations/expected/probemetric.rs b/templates/code/rust/tests/allocations/expected/probemetric.rs deleted file mode 100644 index 843bb72..0000000 --- a/templates/code/rust/tests/allocations/expected/probemetric.rs +++ /dev/null @@ -1,123 +0,0 @@ -#![allow(deprecated)] -#[derive(Clone, Debug)] -pub enum OptionalCounterAttr { - Optional(super::probeattr::OptionalAttr), -} - -impl From for ::opentelemetry::KeyValue { - fn from(value: OptionalCounterAttr) -> Self { - match value { - OptionalCounterAttr::Optional(value) => ::opentelemetry::KeyValue::from(value), - } - } -} -/// Measurements with optional numeric attributes. -#[derive(Clone)] -pub struct OptionalCounter { - instrument: ::opentelemetry::metrics::Counter, -} - -impl OptionalCounter { - pub fn new(meter: &super::meter::Meter) -> Self { - let instrument = meter.inner().u64_counter("probe.optional") - .with_description("Measurements with optional numeric attributes.") - .with_unit("{measurement}") - .build(); - Self { instrument } - } - pub fn add(&self, value: u64, r#probe_required: super::probeattr::RequiredAttr, options: impl IntoIterator) { - let mut attributes = ::smallvec::SmallVec::<[::opentelemetry::KeyValue; 2]>::new(); - attributes.extend([::opentelemetry::KeyValue::from(r#probe_required)]); - attributes.extend(options.into_iter().map(::opentelemetry::KeyValue::from)); - self.instrument.add(value, &attributes); - } -} - -impl Default for OptionalCounter { - fn default() -> Self { Self::new(&super::meter::Meter::default()) } -} -pub struct OptionalCounterObserver<'a> { - observer: &'a dyn ::opentelemetry::metrics::AsyncInstrument, -} - -impl OptionalCounterObserver<'_> { - pub fn observe(&self, value: u64, r#probe_required: super::probeattr::RequiredAttr, options: impl IntoIterator) { - let mut attributes = ::smallvec::SmallVec::<[::opentelemetry::KeyValue; 2]>::new(); - attributes.extend([::opentelemetry::KeyValue::from(r#probe_required)]); - attributes.extend(options.into_iter().map(::opentelemetry::KeyValue::from)); - self.observer.observe(value, &attributes); - } -} - -#[derive(Clone)] -pub struct OptionalObservableCounter { - _instrument: ::opentelemetry::metrics::ObservableCounter, -} - -impl OptionalObservableCounter { - pub fn new(meter: &super::meter::Meter, callback: impl Fn(OptionalCounterObserver<'_>) + Send + Sync + 'static) -> Self { - let instrument = meter.inner().u64_observable_counter("probe.optional") - .with_description("Measurements with optional numeric attributes.") - .with_unit("{measurement}") - .with_callback(move |observer| callback(OptionalCounterObserver { observer })) - .build(); - Self { _instrument: instrument } - } -} - -impl Default for OptionalObservableCounter { - fn default() -> Self { Self::new(&super::meter::Meter::default(), |_| {}) } -} -/// Measurements with a required numeric attribute. -#[derive(Clone)] -pub struct RequiredCounter { - instrument: ::opentelemetry::metrics::Counter, -} - -impl RequiredCounter { - pub fn new(meter: &super::meter::Meter) -> Self { - let instrument = meter.inner().u64_counter("probe.required") - .with_description("Measurements with a required numeric attribute.") - .with_unit("{measurement}") - .build(); - Self { instrument } - } - pub fn add(&self, value: u64, r#probe_required: super::probeattr::RequiredAttr) { - let attributes = [::opentelemetry::KeyValue::from(r#probe_required)]; - self.instrument.add(value, &attributes); - } -} - -impl Default for RequiredCounter { - fn default() -> Self { Self::new(&super::meter::Meter::default()) } -} -pub struct RequiredCounterObserver<'a> { - observer: &'a dyn ::opentelemetry::metrics::AsyncInstrument, -} - -impl RequiredCounterObserver<'_> { - pub fn observe(&self, value: u64, r#probe_required: super::probeattr::RequiredAttr) { - let attributes = [::opentelemetry::KeyValue::from(r#probe_required)]; - self.observer.observe(value, &attributes); - } -} - -#[derive(Clone)] -pub struct RequiredObservableCounter { - _instrument: ::opentelemetry::metrics::ObservableCounter, -} - -impl RequiredObservableCounter { - pub fn new(meter: &super::meter::Meter, callback: impl Fn(RequiredCounterObserver<'_>) + Send + Sync + 'static) -> Self { - let instrument = meter.inner().u64_observable_counter("probe.required") - .with_description("Measurements with a required numeric attribute.") - .with_unit("{measurement}") - .with_callback(move |observer| callback(RequiredCounterObserver { observer })) - .build(); - Self { _instrument: instrument } - } -} - -impl Default for RequiredObservableCounter { - fn default() -> Self { Self::new(&super::meter::Meter::default(), |_| {}) } -} diff --git a/templates/code/rust/tests/allocations/test.rs b/templates/code/rust/tests/allocations/test.rs index 9470ec4..55850fc 100644 --- a/templates/code/rust/tests/allocations/test.rs +++ b/templates/code/rust/tests/allocations/test.rs @@ -1,5 +1,5 @@ use generated_semconv::options::InstrumentationOptions; -use generated_semconv::{logger, meter, probeattr, probeevent, probemetric, scope}; +use generated_semconv::{attribute, event, logger, meter, metric, scope}; use opentelemetry::logs::{AnyValue, LogRecord, Logger, LoggerProvider, Severity}; use opentelemetry::metrics::{ AsyncInstrument, AsyncInstrumentBuilder, Callback, Counter, InstrumentBuilder, @@ -226,9 +226,9 @@ fn metrics_use_no_generated_heap_for_required_or_typical_optional_attributes() { &MetricProvider(state.clone()), InstrumentationOptions::default(), ); - let required = probemetric::RequiredCounter::new(&meter); - let optional = probemetric::OptionalCounter::new(&meter); - let required_count = allocations(|| required.add(1, probeattr::RequiredAttr::from(3))); + let required = metric::ProbeRequired::new(&meter); + let optional = metric::ProbeOptional::new(&meter); + let required_count = allocations(|| required.add(1, attribute::ProbeRequired::from(3))); assert_eq!( required_count, 0, "required metric attribute buffer allocated" @@ -236,9 +236,9 @@ fn metrics_use_no_generated_heap_for_required_or_typical_optional_attributes() { let optional_count = allocations(|| { optional.add( 1, - probeattr::RequiredAttr::from(3), - [probemetric::OptionalCounterAttr::Optional( - probeattr::OptionalAttr::from(5), + attribute::ProbeRequired::from(3), + [metric::ProbeOptionalAttr::Optional( + attribute::ProbeOptional::from(5), )], ) }); @@ -250,9 +250,9 @@ fn metrics_use_no_generated_heap_for_required_or_typical_optional_attributes() { assert_eq!(state.sum.load(Ordering::Relaxed), 8); optional.add( 1, - probeattr::RequiredAttr::from(3), + attribute::ProbeRequired::from(3), (0..20).map(|value| { - probemetric::OptionalCounterAttr::Optional(probeattr::OptionalAttr::from(value)) + metric::ProbeOptionalAttr::Optional(attribute::ProbeOptional::from(value)) }), ); assert_eq!(state.attribute_count.load(Ordering::Relaxed), 21); @@ -271,15 +271,15 @@ fn observable_measurements_use_stack_attribute_storage() { let state = Arc::new(MetricState::default()); let provider = MetricProvider(state.clone()); let meter = meter::Meter::new(&provider, InstrumentationOptions::default()); - let _required = probemetric::RequiredObservableCounter::new(&meter, |observer| { - observer.observe(1, probeattr::RequiredAttr::from(3)); + let _required = metric::ProbeRequiredObservable::new(&meter, |observer| { + observer.observe(1, attribute::ProbeRequired::from(3)); }); - let _optional = probemetric::OptionalObservableCounter::new(&meter, |observer| { + let _optional = metric::ProbeOptionalObservable::new(&meter, |observer| { observer.observe( 1, - probeattr::RequiredAttr::from(3), - [probemetric::OptionalCounterAttr::Optional( - probeattr::OptionalAttr::from(5), + attribute::ProbeRequired::from(3), + [metric::ProbeOptionalAttr::Optional( + attribute::ProbeOptional::from(5), )], ); }); @@ -390,12 +390,12 @@ fn default_options_apply_generated_identity() { #[test] fn direct_scalar_log_values_move_without_heap_allocations() { - let owned = probeattr::LabelAttr::from(String::from("owned text")); + let owned = attribute::ProbeLabel::from(String::from("owned text")); let count = allocations(|| { - black_box(AnyValue::from(probeattr::RequiredAttr::from(7))); - black_box(AnyValue::from(probeattr::FlagAttr::from(true))); - black_box(AnyValue::from(probeattr::FractionAttr::from(0.5))); - black_box(AnyValue::from(probeattr::LabelAttr::from("static text"))); + black_box(AnyValue::from(attribute::ProbeRequired::from(7))); + black_box(AnyValue::from(attribute::ProbeFlag::from(true))); + black_box(AnyValue::from(attribute::ProbeFraction::from(0.5))); + black_box(AnyValue::from(attribute::ProbeLabel::from("static text"))); black_box(AnyValue::from(owned)); }); assert_eq!(count, 0); @@ -411,26 +411,26 @@ fn enabled_events_use_no_generated_heap_and_preserve_duplicate_attributes() { InstrumentationOptions::default(), ); let context = Context::new(); - probeevent::emit_recorded(&context, &logger, probeattr::RequiredAttr::from(3), []); + event::emit_probe_recorded(&context, &logger, attribute::ProbeRequired::from(3), []); let count = allocations(|| { - probeevent::emit_recorded( + event::emit_probe_recorded( &context, &logger, - probeattr::RequiredAttr::from(3), - [probeevent::RecordedOption::Optional( - probeattr::OptionalAttr::from(5), + attribute::ProbeRequired::from(3), + [event::ProbeRecordedOption::Optional( + attribute::ProbeOptional::from(5), )], ) }); assert_eq!(count, 0, "ordinary enabled event attributes allocated"); assert_eq!(state.attribute_count.load(Ordering::Relaxed), 2); assert_eq!(state.attribute_sum.load(Ordering::Relaxed), 8); - probeevent::emit_recorded( + event::emit_probe_recorded( &context, &logger, - probeattr::RequiredAttr::from(3), + attribute::ProbeRequired::from(3), (0..20).map(|value| { - probeevent::RecordedOption::Optional(probeattr::OptionalAttr::from(value)) + event::ProbeRecordedOption::Optional(attribute::ProbeOptional::from(value)) }), ); assert_eq!(state.attribute_count.load(Ordering::Relaxed), 21); @@ -442,15 +442,15 @@ fn enabled_events_use_no_generated_heap_and_preserve_duplicate_attributes() { .wrapping_add(value)) ); let configuration_count = allocations(|| { - probeevent::emit_recorded( + event::emit_probe_recorded( &context, &logger, - probeattr::RequiredAttr::from(3), + attribute::ProbeRequired::from(3), [ - probeevent::RecordedOption::Severity(Severity::Warn), - probeevent::RecordedOption::Timestamp(UNIX_EPOCH + Duration::from_secs(10)), - probeevent::RecordedOption::Severity(Severity::Error), - probeevent::RecordedOption::Timestamp(UNIX_EPOCH + Duration::from_secs(20)), + event::ProbeRecordedOption::Severity(Severity::Warn), + event::ProbeRecordedOption::Timestamp(UNIX_EPOCH + Duration::from_secs(10)), + event::ProbeRecordedOption::Severity(Severity::Error), + event::ProbeRecordedOption::Timestamp(UNIX_EPOCH + Duration::from_secs(20)), ], ) }); @@ -471,19 +471,19 @@ fn disabled_events_defer_context_attachment_and_attribute_conversion() { InstrumentationOptions::default(), ); let context = Context::new().with_value(ExplicitContext); - let values = probeattr::ValuesAttr::from(vec![1, 2, 3]); - probeevent::emit_recorded( + let values = attribute::ProbeValues::from(vec![1, 2, 3]); + event::emit_probe_recorded( &Context::new(), &logger, - probeattr::RequiredAttr::from(0), + attribute::ProbeRequired::from(0), [], ); let count = allocations(|| { - probeevent::emit_recorded( + event::emit_probe_recorded( &context, &logger, - probeattr::RequiredAttr::from(3), - [probeevent::RecordedOption::Values(values)], + attribute::ProbeRequired::from(3), + [event::ProbeRecordedOption::Values(values)], ) }); assert_eq!(count, 0, "disabled event attributes allocated"); diff --git a/templates/code/rust/tests/attributes/compile-fail/dynamic_borrow.rs b/templates/code/rust/tests/attributes/compile-fail/dynamic_borrow.rs index 0816e72..e12cfc8 100644 --- a/templates/code/rust/tests/attributes/compile-fail/dynamic_borrow.rs +++ b/templates/code/rust/tests/attributes/compile-fail/dynamic_borrow.rs @@ -1,4 +1,4 @@ fn main() { let source = String::from("dynamic"); - let _ = generated_semconv::myappattr::TaskIdAttr::from(source.as_str()); + let _ = generated_semconv::attribute::MyappTaskId::from(source.as_str()); } diff --git a/templates/code/rust/tests/attributes/compile-fail/inherited_deprecation.rs b/templates/code/rust/tests/attributes/compile-fail/inherited_deprecation.rs index 2fdc518..3b643bf 100644 --- a/templates/code/rust/tests/attributes/compile-fail/inherited_deprecation.rs +++ b/templates/code/rust/tests/attributes/compile-fail/inherited_deprecation.rs @@ -1,4 +1,4 @@ #![deny(deprecated)] fn main() { - let _ = generated_semconv::myappattr::TaskLaneAttr::Fast; + let _ = generated_semconv::attribute::MyappTaskLane::Fast; } diff --git a/templates/code/rust/tests/attributes/compile-fail/unknown_enum.rs b/templates/code/rust/tests/attributes/compile-fail/unknown_enum.rs index fe8a0cc..3181e57 100644 --- a/templates/code/rust/tests/attributes/compile-fail/unknown_enum.rs +++ b/templates/code/rust/tests/attributes/compile-fail/unknown_enum.rs @@ -1,3 +1,3 @@ fn main() { - let _ = generated_semconv::myappattr::TaskStateAttr::Unknown; + let _ = generated_semconv::attribute::MyappTaskState::Unknown; } diff --git a/templates/code/rust/tests/attributes/compile-fail/wrong_scalar.expected-error.txt b/templates/code/rust/tests/attributes/compile-fail/wrong_scalar.expected-error.txt index d96698e..3d176c0 100644 --- a/templates/code/rust/tests/attributes/compile-fail/wrong_scalar.expected-error.txt +++ b/templates/code/rust/tests/attributes/compile-fail/wrong_scalar.expected-error.txt @@ -1 +1 @@ -the trait bound `TaskRetriesAttr: From<&str>` is not satisfied +the trait bound `MyappTaskRetries: From<&str>` is not satisfied diff --git a/templates/code/rust/tests/attributes/compile-fail/wrong_scalar.rs b/templates/code/rust/tests/attributes/compile-fail/wrong_scalar.rs index 1c753de..9a3f4d9 100644 --- a/templates/code/rust/tests/attributes/compile-fail/wrong_scalar.rs +++ b/templates/code/rust/tests/attributes/compile-fail/wrong_scalar.rs @@ -1,3 +1,3 @@ fn main() { - let _ = generated_semconv::myappattr::TaskRetriesAttr::from("three"); + let _ = generated_semconv::attribute::MyappTaskRetries::from("three"); } diff --git a/templates/code/rust/tests/attributes/expected/attribute.rs b/templates/code/rust/tests/attributes/expected/attribute.rs new file mode 100644 index 0000000..2f207c7 --- /dev/null +++ b/templates/code/rust/tests/attributes/expected/attribute.rs @@ -0,0 +1,999 @@ +// Generated by OpenTelemetry Weaver. +/// Assurance level of the authentication. +#[derive(Debug, Clone, PartialEq, Copy)] +pub enum AuthLevel { + /// Single factor. + Low, + /// Multiple factors. + High, +} + +#[allow(deprecated)] +impl AuthLevel { + pub const KEY: &'static str = "auth.level"; +} + +#[allow(deprecated)] +impl ::std::fmt::Display for AuthLevel { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + let value: i64 = match self { + AuthLevel::Low => 1, + AuthLevel::High => 2, + }; + ::std::fmt::Display::fmt(&value, formatter) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: AuthLevel) -> Self { + let value: i64 = match value { + AuthLevel::Low => 1, + AuthLevel::High => 2, + }; + ::opentelemetry::KeyValue::new(AuthLevel::KEY, value) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: AuthLevel) -> Self { + let value: i64 = match value { + AuthLevel::Low => 1, + AuthLevel::High => 2, + }; + value.into() + } +} + +/// How the user was authenticated. +#[derive(Debug, Clone, PartialEq, Copy)] +pub enum AuthMethod { + /// A password was checked. + Password, + /// A bearer token was checked. + Token, +} + +#[allow(deprecated)] +impl AuthMethod { + pub const KEY: &'static str = "auth.method"; +} + +#[allow(deprecated)] +impl AsRef for AuthMethod { + #[inline] + fn as_ref(&self) -> &str { + match self { + AuthMethod::Password => "password", + AuthMethod::Token => "token", + } + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for AuthMethod { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str(self.as_ref()) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: AuthMethod) -> Self { + let value: &'static str = match value { + AuthMethod::Password => "password", + AuthMethod::Token => "token", + }; + ::opentelemetry::KeyValue::new(AuthMethod::KEY, value) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: AuthMethod) -> Self { + let value: &'static str = match value { + AuthMethod::Password => "password", + AuthMethod::Token => "token", + }; + value.into() + } +} + +/// Identifier of the authenticated user. +#[derive(Debug, Clone, PartialEq)] +pub struct AuthUserId(::opentelemetry::StringValue); + +#[allow(deprecated)] +impl AuthUserId { + pub const KEY: &'static str = "auth.user.id"; +} + +#[allow(deprecated)] +impl From<::opentelemetry::StringValue> for AuthUserId { + #[inline] + fn from(value: ::opentelemetry::StringValue) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl From for AuthUserId { + #[inline] + fn from(value: String) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl From<&'static str> for AuthUserId { + #[inline] + fn from(value: &'static str) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl AsRef for AuthUserId { + #[inline] + fn as_ref(&self) -> &str { + self.0.as_str() + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for AuthUserId { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str(self.as_ref()) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: AuthUserId) -> Self { + ::opentelemetry::KeyValue::new(AuthUserId::KEY, value.0) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: AuthUserId) -> Self { + value.0.into() + } +} + +/// Who assigned the task. +/// +/// The scheduler sets it on every task it passes along to `myapp.task.state`. Workers never set it themselves. +#[derive(Debug, Clone, PartialEq)] +pub struct MyappTaskAssignedBy(::opentelemetry::StringValue); + +#[allow(deprecated)] +impl MyappTaskAssignedBy { + pub const KEY: &'static str = "myapp.task.assigned_by"; +} + +#[allow(deprecated)] +impl From<::opentelemetry::StringValue> for MyappTaskAssignedBy { + #[inline] + fn from(value: ::opentelemetry::StringValue) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl From for MyappTaskAssignedBy { + #[inline] + fn from(value: String) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl From<&'static str> for MyappTaskAssignedBy { + #[inline] + fn from(value: &'static str) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl AsRef for MyappTaskAssignedBy { + #[inline] + fn as_ref(&self) -> &str { + self.0.as_str() + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for MyappTaskAssignedBy { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str(self.as_ref()) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: MyappTaskAssignedBy) -> Self { + ::opentelemetry::KeyValue::new(MyappTaskAssignedBy::KEY, value.0) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: MyappTaskAssignedBy) -> Self { + value.0.into() + } +} + +/// Whether the task was cancelled. +#[derive(Debug, Clone, PartialEq, Copy)] +pub struct MyappTaskCancelled(bool); + +#[allow(deprecated)] +impl MyappTaskCancelled { + pub const KEY: &'static str = "myapp.task.cancelled"; +} + +#[allow(deprecated)] +impl From for MyappTaskCancelled { + #[inline] + fn from(value: bool) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for MyappTaskCancelled { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + ::std::fmt::Display::fmt(&self.0, formatter) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: MyappTaskCancelled) -> Self { + ::opentelemetry::KeyValue::new(MyappTaskCancelled::KEY, value.0) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: MyappTaskCancelled) -> Self { + value.0.into() + } +} + +/// Tests Rust string literals. +#[derive(Debug, Clone, PartialEq, Copy)] +pub enum MyappTaskEscaped { + /// Escaped text. + Quoted, +} + +#[allow(deprecated)] +impl MyappTaskEscaped { + pub const KEY: &'static str = "myapp.task.escaped"; +} + +#[allow(deprecated)] +impl AsRef for MyappTaskEscaped { + #[inline] + fn as_ref(&self) -> &str { + match self { + MyappTaskEscaped::Quoted => "quote\" slash\\ newline\n tab\t backspace\u{0008} formfeed\u{000c} null\u{0000} snowman☃", + } + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for MyappTaskEscaped { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str(self.as_ref()) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: MyappTaskEscaped) -> Self { + let value: &'static str = match value { + MyappTaskEscaped::Quoted => "quote\" slash\\ newline\n tab\t backspace\u{0008} formfeed\u{000c} null\u{0000} snowman☃", + }; + ::opentelemetry::KeyValue::new(MyappTaskEscaped::KEY, value) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: MyappTaskEscaped) -> Self { + let value: &'static str = match value { + MyappTaskEscaped::Quoted => "quote\" slash\\ newline\n tab\t backspace\u{0008} formfeed\u{000c} null\u{0000} snowman☃", + }; + value.into() + } +} + +/// Feature flags evaluated for the task. +#[derive(Debug, Clone, PartialEq)] +pub struct MyappTaskFlags(Vec); + +#[allow(deprecated)] +impl MyappTaskFlags { + pub const KEY: &'static str = "myapp.task.flags"; +} + +#[allow(deprecated)] +impl From> for MyappTaskFlags { + #[inline] + fn from(value: Vec) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl AsRef<[bool]> for MyappTaskFlags { + #[inline] + fn as_ref(&self) -> &[bool] { + &self.0 + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for MyappTaskFlags { + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str("[")?; + for (index, value) in self.0.iter().enumerate() { + if index != 0 { + formatter.write_str(",")?; + } + ::std::fmt::Display::fmt(value, formatter)?; + } + formatter.write_str("]") + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: MyappTaskFlags) -> Self { + ::opentelemetry::KeyValue::new(MyappTaskFlags::KEY, ::opentelemetry::Value::Array(::opentelemetry::Array::Bool(value.0))) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: MyappTaskFlags) -> Self { + value.0.into_iter().collect::<::opentelemetry::logs::AnyValue>() + } +} + +/// Unique identifier of the task. +/// +/// The identifier is assigned by the scheduler and stays stable across retries. +#[derive(Debug, Clone, PartialEq)] +pub struct MyappTaskId(::opentelemetry::StringValue); + +#[allow(deprecated)] +impl MyappTaskId { + pub const KEY: &'static str = "myapp.task.id"; +} + +#[allow(deprecated)] +impl From<::opentelemetry::StringValue> for MyappTaskId { + #[inline] + fn from(value: ::opentelemetry::StringValue) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl From for MyappTaskId { + #[inline] + fn from(value: String) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl From<&'static str> for MyappTaskId { + #[inline] + fn from(value: &'static str) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl AsRef for MyappTaskId { + #[inline] + fn as_ref(&self) -> &str { + self.0.as_str() + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for MyappTaskId { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str(self.as_ref()) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: MyappTaskId) -> Self { + ::opentelemetry::KeyValue::new(MyappTaskId::KEY, value.0) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: MyappTaskId) -> Self { + value.0.into() + } +} + +/// Lane the task was scheduled in. +#[deprecated(note = "Lanes were replaced by priorities.")] +#[derive(Debug, Clone, PartialEq, Copy)] +pub enum MyappTaskLane { + /// The fast lane. + #[deprecated(note = "Lanes were replaced by priorities.")] + Fast, + /// The slow lane. + #[deprecated(note = "Every task runs in the fast lane.")] + Slow, +} + +#[allow(deprecated)] +impl MyappTaskLane { + pub const KEY: &'static str = "myapp.task.lane"; +} + +#[allow(deprecated)] +impl AsRef for MyappTaskLane { + #[inline] + fn as_ref(&self) -> &str { + match self { + MyappTaskLane::Fast => "fast", + MyappTaskLane::Slow => "slow", + } + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for MyappTaskLane { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str(self.as_ref()) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: MyappTaskLane) -> Self { + let value: &'static str = match value { + MyappTaskLane::Fast => "fast", + MyappTaskLane::Slow => "slow", + }; + ::opentelemetry::KeyValue::new(MyappTaskLane::KEY, value) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: MyappTaskLane) -> Self { + let value: &'static str = match value { + MyappTaskLane::Fast => "fast", + MyappTaskLane::Slow => "slow", + }; + value.into() + } +} + +/// Owner of the task. +#[deprecated(note = "Replaced by `auth.user.id`.")] +#[derive(Debug, Clone, PartialEq)] +pub struct MyappTaskOwner(::opentelemetry::StringValue); + +#[allow(deprecated)] +impl MyappTaskOwner { + pub const KEY: &'static str = "myapp.task.owner"; +} + +#[allow(deprecated)] +impl From<::opentelemetry::StringValue> for MyappTaskOwner { + #[inline] + fn from(value: ::opentelemetry::StringValue) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl From for MyappTaskOwner { + #[inline] + fn from(value: String) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl From<&'static str> for MyappTaskOwner { + #[inline] + fn from(value: &'static str) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl AsRef for MyappTaskOwner { + #[inline] + fn as_ref(&self) -> &str { + self.0.as_str() + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for MyappTaskOwner { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str(self.as_ref()) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: MyappTaskOwner) -> Self { + ::opentelemetry::KeyValue::new(MyappTaskOwner::KEY, value.0) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: MyappTaskOwner) -> Self { + value.0.into() + } +} + +/// Whether the scheduler may preempt the task. +#[derive(Debug, Clone, PartialEq, Copy)] +pub enum MyappTaskPreemptible { + /// The scheduler may preempt the task. + Allowed, + /// The task runs to completion. + Forbidden, +} + +#[allow(deprecated)] +impl MyappTaskPreemptible { + pub const KEY: &'static str = "myapp.task.preemptible"; +} + +#[allow(deprecated)] +impl ::std::fmt::Display for MyappTaskPreemptible { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + let value: bool = match self { + MyappTaskPreemptible::Allowed => true, + MyappTaskPreemptible::Forbidden => false, + }; + ::std::fmt::Display::fmt(&value, formatter) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: MyappTaskPreemptible) -> Self { + let value: bool = match value { + MyappTaskPreemptible::Allowed => true, + MyappTaskPreemptible::Forbidden => false, + }; + ::opentelemetry::KeyValue::new(MyappTaskPreemptible::KEY, value) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: MyappTaskPreemptible) -> Self { + let value: bool = match value { + MyappTaskPreemptible::Allowed => true, + MyappTaskPreemptible::Forbidden => false, + }; + value.into() + } +} + +/// Fraction of the task that has completed, between 0 and 1. +#[derive(Debug, Clone, PartialEq, Copy)] +pub struct MyappTaskProgress(f64); + +#[allow(deprecated)] +impl MyappTaskProgress { + pub const KEY: &'static str = "myapp.task.progress"; +} + +#[allow(deprecated)] +impl From for MyappTaskProgress { + #[inline] + fn from(value: f64) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for MyappTaskProgress { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + ::std::fmt::Display::fmt(&self.0, formatter) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: MyappTaskProgress) -> Self { + ::opentelemetry::KeyValue::new(MyappTaskProgress::KEY, value.0) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: MyappTaskProgress) -> Self { + value.0.into() + } +} + +/// Number of times the task was retried. +#[derive(Debug, Clone, PartialEq, Copy)] +pub struct MyappTaskRetries(i64); + +#[allow(deprecated)] +impl MyappTaskRetries { + pub const KEY: &'static str = "myapp.task.retries"; +} + +#[allow(deprecated)] +impl From for MyappTaskRetries { + #[inline] + fn from(value: i64) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for MyappTaskRetries { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + ::std::fmt::Display::fmt(&self.0, formatter) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: MyappTaskRetries) -> Self { + ::opentelemetry::KeyValue::new(MyappTaskRetries::KEY, value.0) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: MyappTaskRetries) -> Self { + value.0.into() + } +} + +/// Fraction of tasks whose telemetry is sampled. +#[derive(Debug, Clone, PartialEq, Copy)] +pub enum MyappTaskSampleRate { + /// One task in ten is sampled. + Tenth, + /// Every task is sampled. + All, +} + +#[allow(deprecated)] +impl MyappTaskSampleRate { + pub const KEY: &'static str = "myapp.task.sample_rate"; +} + +#[allow(deprecated)] +impl ::std::fmt::Display for MyappTaskSampleRate { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + let value: f64 = match self { + MyappTaskSampleRate::Tenth => 0.1_f64, + MyappTaskSampleRate::All => 1_f64, + }; + ::std::fmt::Display::fmt(&value, formatter) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: MyappTaskSampleRate) -> Self { + let value: f64 = match value { + MyappTaskSampleRate::Tenth => 0.1_f64, + MyappTaskSampleRate::All => 1_f64, + }; + ::opentelemetry::KeyValue::new(MyappTaskSampleRate::KEY, value) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: MyappTaskSampleRate) -> Self { + let value: f64 = match value { + MyappTaskSampleRate::Tenth => 0.1_f64, + MyappTaskSampleRate::All => 1_f64, + }; + value.into() + } +} + +/// Shards the task touched. +#[derive(Debug, Clone, PartialEq)] +pub struct MyappTaskShardIds(Vec); + +#[allow(deprecated)] +impl MyappTaskShardIds { + pub const KEY: &'static str = "myapp.task.shard_ids"; +} + +#[allow(deprecated)] +impl From> for MyappTaskShardIds { + #[inline] + fn from(value: Vec) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl AsRef<[i64]> for MyappTaskShardIds { + #[inline] + fn as_ref(&self) -> &[i64] { + &self.0 + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for MyappTaskShardIds { + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str("[")?; + for (index, value) in self.0.iter().enumerate() { + if index != 0 { + formatter.write_str(",")?; + } + ::std::fmt::Display::fmt(value, formatter)?; + } + formatter.write_str("]") + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: MyappTaskShardIds) -> Self { + ::opentelemetry::KeyValue::new(MyappTaskShardIds::KEY, ::opentelemetry::Value::Array(::opentelemetry::Array::I64(value.0))) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: MyappTaskShardIds) -> Self { + value.0.into_iter().collect::<::opentelemetry::logs::AnyValue>() + } +} + +/// Current state of the task. +#[derive(Debug, Clone, PartialEq, Copy)] +pub enum MyappTaskState { + /// The task is waiting to run. + Queued, + /// The task is running. + /// + /// A task stays running until it finishes or is cancelled. + Running, + /// The task was paused. + #[deprecated(note = "Paused tasks are reported as queued.")] + Paused, +} + +#[allow(deprecated)] +impl MyappTaskState { + pub const KEY: &'static str = "myapp.task.state"; +} + +#[allow(deprecated)] +impl AsRef for MyappTaskState { + #[inline] + fn as_ref(&self) -> &str { + match self { + MyappTaskState::Queued => "queued", + MyappTaskState::Running => "running", + MyappTaskState::Paused => "paused", + } + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for MyappTaskState { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str(self.as_ref()) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: MyappTaskState) -> Self { + let value: &'static str = match value { + MyappTaskState::Queued => "queued", + MyappTaskState::Running => "running", + MyappTaskState::Paused => "paused", + }; + ::opentelemetry::KeyValue::new(MyappTaskState::KEY, value) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: MyappTaskState) -> Self { + let value: &'static str = match value { + MyappTaskState::Queued => "queued", + MyappTaskState::Running => "running", + MyappTaskState::Paused => "paused", + }; + value.into() + } +} + +/// Tags attached to the task. +#[derive(Debug, Clone, PartialEq)] +pub struct MyappTaskTags(Vec<::opentelemetry::StringValue>); + +#[allow(deprecated)] +impl MyappTaskTags { + pub const KEY: &'static str = "myapp.task.tags"; +} + +#[allow(deprecated)] +impl From> for MyappTaskTags { + #[inline] + fn from(value: Vec<::opentelemetry::StringValue>) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl From> for MyappTaskTags { + fn from(value: Vec) -> Self { + Self(value.into_iter().map(Into::into).collect()) + } +} + +#[allow(deprecated)] +impl AsRef<[::opentelemetry::StringValue]> for MyappTaskTags { + #[inline] + fn as_ref(&self) -> &[::opentelemetry::StringValue] { + &self.0 + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for MyappTaskTags { + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str("[")?; + for (index, value) in self.0.iter().enumerate() { + if index != 0 { + formatter.write_str(",")?; + } + write!(formatter, "\"{value}\"")?; + } + formatter.write_str("]") + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: MyappTaskTags) -> Self { + ::opentelemetry::KeyValue::new(MyappTaskTags::KEY, ::opentelemetry::Value::Array(::opentelemetry::Array::String(value.0))) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: MyappTaskTags) -> Self { + value.0.into_iter().collect::<::opentelemetry::logs::AnyValue>() + } +} + +/// Scheduling weights applied to the task. +#[derive(Debug, Clone, PartialEq)] +pub struct MyappTaskWeights(Vec); + +#[allow(deprecated)] +impl MyappTaskWeights { + pub const KEY: &'static str = "myapp.task.weights"; +} + +#[allow(deprecated)] +impl From> for MyappTaskWeights { + #[inline] + fn from(value: Vec) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl AsRef<[f64]> for MyappTaskWeights { + #[inline] + fn as_ref(&self) -> &[f64] { + &self.0 + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for MyappTaskWeights { + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str("[")?; + for (index, value) in self.0.iter().enumerate() { + if index != 0 { + formatter.write_str(",")?; + } + ::std::fmt::Display::fmt(value, formatter)?; + } + formatter.write_str("]") + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: MyappTaskWeights) -> Self { + ::opentelemetry::KeyValue::new(MyappTaskWeights::KEY, ::opentelemetry::Value::Array(::opentelemetry::Array::F64(value.0))) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: MyappTaskWeights) -> Self { + value.0.into_iter().collect::<::opentelemetry::logs::AnyValue>() + } +} diff --git a/templates/code/rust/tests/attributes/expected/authattr.rs b/templates/code/rust/tests/attributes/expected/authattr.rs deleted file mode 100644 index 5fba6c7..0000000 --- a/templates/code/rust/tests/attributes/expected/authattr.rs +++ /dev/null @@ -1,172 +0,0 @@ -// Generated by OpenTelemetry Weaver. -/// Assurance level of the authentication. -#[derive(Debug, Clone, PartialEq, Copy)] -pub enum LevelAttr { - /// Single factor. - Low, - /// Multiple factors. - High, -} - -#[allow(deprecated)] -impl LevelAttr { - pub const KEY: &'static str = "auth.level"; -} - -#[allow(deprecated)] -impl ::std::fmt::Display for LevelAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - let value: i64 = match self { - LevelAttr::Low => 1, - LevelAttr::High => 2, - }; - ::std::fmt::Display::fmt(&value, formatter) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: LevelAttr) -> Self { - let value: i64 = match value { - LevelAttr::Low => 1, - LevelAttr::High => 2, - }; - ::opentelemetry::KeyValue::new(LevelAttr::KEY, value) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: LevelAttr) -> Self { - let value: i64 = match value { - LevelAttr::Low => 1, - LevelAttr::High => 2, - }; - value.into() - } -} - -/// How the user was authenticated. -#[derive(Debug, Clone, PartialEq, Copy)] -pub enum MethodAttr { - /// A password was checked. - Password, - /// A bearer token was checked. - Token, -} - -#[allow(deprecated)] -impl MethodAttr { - pub const KEY: &'static str = "auth.method"; -} - -#[allow(deprecated)] -impl AsRef for MethodAttr { - #[inline] - fn as_ref(&self) -> &str { - match self { - MethodAttr::Password => "password", - MethodAttr::Token => "token", - } - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for MethodAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str(self.as_ref()) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: MethodAttr) -> Self { - let value: &'static str = match value { - MethodAttr::Password => "password", - MethodAttr::Token => "token", - }; - ::opentelemetry::KeyValue::new(MethodAttr::KEY, value) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: MethodAttr) -> Self { - let value: &'static str = match value { - MethodAttr::Password => "password", - MethodAttr::Token => "token", - }; - value.into() - } -} - -/// Identifier of the authenticated user. -#[derive(Debug, Clone, PartialEq)] -pub struct UserIdAttr(::opentelemetry::StringValue); - -#[allow(deprecated)] -impl UserIdAttr { - pub const KEY: &'static str = "auth.user.id"; -} - -#[allow(deprecated)] -impl From<::opentelemetry::StringValue> for UserIdAttr { - #[inline] - fn from(value: ::opentelemetry::StringValue) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl From for UserIdAttr { - #[inline] - fn from(value: String) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl From<&'static str> for UserIdAttr { - #[inline] - fn from(value: &'static str) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl AsRef for UserIdAttr { - #[inline] - fn as_ref(&self) -> &str { - self.0.as_str() - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for UserIdAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str(self.as_ref()) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: UserIdAttr) -> Self { - ::opentelemetry::KeyValue::new(UserIdAttr::KEY, value.0) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: UserIdAttr) -> Self { - value.0.into() - } -} diff --git a/templates/code/rust/tests/attributes/expected/mod.rs b/templates/code/rust/tests/attributes/expected/mod.rs index c487539..a0a57ad 100644 --- a/templates/code/rust/tests/attributes/expected/mod.rs +++ b/templates/code/rust/tests/attributes/expected/mod.rs @@ -1,4 +1,3 @@ // Generated by OpenTelemetry Weaver. pub const SCHEMA_URL: &str = "https://example.com/schemas/attributes/1.0.0"; -pub mod authattr; -pub mod myappattr; +pub mod attribute; diff --git a/templates/code/rust/tests/attributes/expected/myappattr.rs b/templates/code/rust/tests/attributes/expected/myappattr.rs deleted file mode 100644 index bd3bcf5..0000000 --- a/templates/code/rust/tests/attributes/expected/myappattr.rs +++ /dev/null @@ -1,827 +0,0 @@ -// Generated by OpenTelemetry Weaver. -/// Who assigned the task. -/// -/// The scheduler sets it on every task it passes along to `myapp.task.state`. Workers never set it themselves. -#[derive(Debug, Clone, PartialEq)] -pub struct TaskAssignedByAttr(::opentelemetry::StringValue); - -#[allow(deprecated)] -impl TaskAssignedByAttr { - pub const KEY: &'static str = "myapp.task.assigned_by"; -} - -#[allow(deprecated)] -impl From<::opentelemetry::StringValue> for TaskAssignedByAttr { - #[inline] - fn from(value: ::opentelemetry::StringValue) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl From for TaskAssignedByAttr { - #[inline] - fn from(value: String) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl From<&'static str> for TaskAssignedByAttr { - #[inline] - fn from(value: &'static str) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl AsRef for TaskAssignedByAttr { - #[inline] - fn as_ref(&self) -> &str { - self.0.as_str() - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for TaskAssignedByAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str(self.as_ref()) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: TaskAssignedByAttr) -> Self { - ::opentelemetry::KeyValue::new(TaskAssignedByAttr::KEY, value.0) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: TaskAssignedByAttr) -> Self { - value.0.into() - } -} - -/// Whether the task was cancelled. -#[derive(Debug, Clone, PartialEq, Copy)] -pub struct TaskCancelledAttr(bool); - -#[allow(deprecated)] -impl TaskCancelledAttr { - pub const KEY: &'static str = "myapp.task.cancelled"; -} - -#[allow(deprecated)] -impl From for TaskCancelledAttr { - #[inline] - fn from(value: bool) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for TaskCancelledAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - ::std::fmt::Display::fmt(&self.0, formatter) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: TaskCancelledAttr) -> Self { - ::opentelemetry::KeyValue::new(TaskCancelledAttr::KEY, value.0) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: TaskCancelledAttr) -> Self { - value.0.into() - } -} - -/// Tests Rust string literals. -#[derive(Debug, Clone, PartialEq, Copy)] -pub enum TaskEscapedAttr { - /// Escaped text. - Quoted, -} - -#[allow(deprecated)] -impl TaskEscapedAttr { - pub const KEY: &'static str = "myapp.task.escaped"; -} - -#[allow(deprecated)] -impl AsRef for TaskEscapedAttr { - #[inline] - fn as_ref(&self) -> &str { - match self { - TaskEscapedAttr::Quoted => "quote\" slash\\ newline\n tab\t backspace\u{0008} formfeed\u{000c} null\u{0000} snowman☃", - } - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for TaskEscapedAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str(self.as_ref()) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: TaskEscapedAttr) -> Self { - let value: &'static str = match value { - TaskEscapedAttr::Quoted => "quote\" slash\\ newline\n tab\t backspace\u{0008} formfeed\u{000c} null\u{0000} snowman☃", - }; - ::opentelemetry::KeyValue::new(TaskEscapedAttr::KEY, value) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: TaskEscapedAttr) -> Self { - let value: &'static str = match value { - TaskEscapedAttr::Quoted => "quote\" slash\\ newline\n tab\t backspace\u{0008} formfeed\u{000c} null\u{0000} snowman☃", - }; - value.into() - } -} - -/// Feature flags evaluated for the task. -#[derive(Debug, Clone, PartialEq)] -pub struct TaskFlagsAttr(Vec); - -#[allow(deprecated)] -impl TaskFlagsAttr { - pub const KEY: &'static str = "myapp.task.flags"; -} - -#[allow(deprecated)] -impl From> for TaskFlagsAttr { - #[inline] - fn from(value: Vec) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl AsRef<[bool]> for TaskFlagsAttr { - #[inline] - fn as_ref(&self) -> &[bool] { - &self.0 - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for TaskFlagsAttr { - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str("[")?; - for (index, value) in self.0.iter().enumerate() { - if index != 0 { - formatter.write_str(",")?; - } - ::std::fmt::Display::fmt(value, formatter)?; - } - formatter.write_str("]") - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: TaskFlagsAttr) -> Self { - ::opentelemetry::KeyValue::new(TaskFlagsAttr::KEY, ::opentelemetry::Value::Array(::opentelemetry::Array::Bool(value.0))) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: TaskFlagsAttr) -> Self { - value.0.into_iter().collect::<::opentelemetry::logs::AnyValue>() - } -} - -/// Unique identifier of the task. -/// -/// The identifier is assigned by the scheduler and stays stable across retries. -#[derive(Debug, Clone, PartialEq)] -pub struct TaskIdAttr(::opentelemetry::StringValue); - -#[allow(deprecated)] -impl TaskIdAttr { - pub const KEY: &'static str = "myapp.task.id"; -} - -#[allow(deprecated)] -impl From<::opentelemetry::StringValue> for TaskIdAttr { - #[inline] - fn from(value: ::opentelemetry::StringValue) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl From for TaskIdAttr { - #[inline] - fn from(value: String) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl From<&'static str> for TaskIdAttr { - #[inline] - fn from(value: &'static str) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl AsRef for TaskIdAttr { - #[inline] - fn as_ref(&self) -> &str { - self.0.as_str() - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for TaskIdAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str(self.as_ref()) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: TaskIdAttr) -> Self { - ::opentelemetry::KeyValue::new(TaskIdAttr::KEY, value.0) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: TaskIdAttr) -> Self { - value.0.into() - } -} - -/// Lane the task was scheduled in. -#[deprecated(note = "Lanes were replaced by priorities.")] -#[derive(Debug, Clone, PartialEq, Copy)] -pub enum TaskLaneAttr { - /// The fast lane. - #[deprecated(note = "Lanes were replaced by priorities.")] - Fast, - /// The slow lane. - #[deprecated(note = "Every task runs in the fast lane.")] - Slow, -} - -#[allow(deprecated)] -impl TaskLaneAttr { - pub const KEY: &'static str = "myapp.task.lane"; -} - -#[allow(deprecated)] -impl AsRef for TaskLaneAttr { - #[inline] - fn as_ref(&self) -> &str { - match self { - TaskLaneAttr::Fast => "fast", - TaskLaneAttr::Slow => "slow", - } - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for TaskLaneAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str(self.as_ref()) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: TaskLaneAttr) -> Self { - let value: &'static str = match value { - TaskLaneAttr::Fast => "fast", - TaskLaneAttr::Slow => "slow", - }; - ::opentelemetry::KeyValue::new(TaskLaneAttr::KEY, value) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: TaskLaneAttr) -> Self { - let value: &'static str = match value { - TaskLaneAttr::Fast => "fast", - TaskLaneAttr::Slow => "slow", - }; - value.into() - } -} - -/// Owner of the task. -#[deprecated(note = "Replaced by `auth.user.id`.")] -#[derive(Debug, Clone, PartialEq)] -pub struct TaskOwnerAttr(::opentelemetry::StringValue); - -#[allow(deprecated)] -impl TaskOwnerAttr { - pub const KEY: &'static str = "myapp.task.owner"; -} - -#[allow(deprecated)] -impl From<::opentelemetry::StringValue> for TaskOwnerAttr { - #[inline] - fn from(value: ::opentelemetry::StringValue) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl From for TaskOwnerAttr { - #[inline] - fn from(value: String) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl From<&'static str> for TaskOwnerAttr { - #[inline] - fn from(value: &'static str) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl AsRef for TaskOwnerAttr { - #[inline] - fn as_ref(&self) -> &str { - self.0.as_str() - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for TaskOwnerAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str(self.as_ref()) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: TaskOwnerAttr) -> Self { - ::opentelemetry::KeyValue::new(TaskOwnerAttr::KEY, value.0) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: TaskOwnerAttr) -> Self { - value.0.into() - } -} - -/// Whether the scheduler may preempt the task. -#[derive(Debug, Clone, PartialEq, Copy)] -pub enum TaskPreemptibleAttr { - /// The scheduler may preempt the task. - Allowed, - /// The task runs to completion. - Forbidden, -} - -#[allow(deprecated)] -impl TaskPreemptibleAttr { - pub const KEY: &'static str = "myapp.task.preemptible"; -} - -#[allow(deprecated)] -impl ::std::fmt::Display for TaskPreemptibleAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - let value: bool = match self { - TaskPreemptibleAttr::Allowed => true, - TaskPreemptibleAttr::Forbidden => false, - }; - ::std::fmt::Display::fmt(&value, formatter) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: TaskPreemptibleAttr) -> Self { - let value: bool = match value { - TaskPreemptibleAttr::Allowed => true, - TaskPreemptibleAttr::Forbidden => false, - }; - ::opentelemetry::KeyValue::new(TaskPreemptibleAttr::KEY, value) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: TaskPreemptibleAttr) -> Self { - let value: bool = match value { - TaskPreemptibleAttr::Allowed => true, - TaskPreemptibleAttr::Forbidden => false, - }; - value.into() - } -} - -/// Fraction of the task that has completed, between 0 and 1. -#[derive(Debug, Clone, PartialEq, Copy)] -pub struct TaskProgressAttr(f64); - -#[allow(deprecated)] -impl TaskProgressAttr { - pub const KEY: &'static str = "myapp.task.progress"; -} - -#[allow(deprecated)] -impl From for TaskProgressAttr { - #[inline] - fn from(value: f64) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for TaskProgressAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - ::std::fmt::Display::fmt(&self.0, formatter) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: TaskProgressAttr) -> Self { - ::opentelemetry::KeyValue::new(TaskProgressAttr::KEY, value.0) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: TaskProgressAttr) -> Self { - value.0.into() - } -} - -/// Number of times the task was retried. -#[derive(Debug, Clone, PartialEq, Copy)] -pub struct TaskRetriesAttr(i64); - -#[allow(deprecated)] -impl TaskRetriesAttr { - pub const KEY: &'static str = "myapp.task.retries"; -} - -#[allow(deprecated)] -impl From for TaskRetriesAttr { - #[inline] - fn from(value: i64) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for TaskRetriesAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - ::std::fmt::Display::fmt(&self.0, formatter) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: TaskRetriesAttr) -> Self { - ::opentelemetry::KeyValue::new(TaskRetriesAttr::KEY, value.0) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: TaskRetriesAttr) -> Self { - value.0.into() - } -} - -/// Fraction of tasks whose telemetry is sampled. -#[derive(Debug, Clone, PartialEq, Copy)] -pub enum TaskSampleRateAttr { - /// One task in ten is sampled. - Tenth, - /// Every task is sampled. - All, -} - -#[allow(deprecated)] -impl TaskSampleRateAttr { - pub const KEY: &'static str = "myapp.task.sample_rate"; -} - -#[allow(deprecated)] -impl ::std::fmt::Display for TaskSampleRateAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - let value: f64 = match self { - TaskSampleRateAttr::Tenth => 0.1_f64, - TaskSampleRateAttr::All => 1_f64, - }; - ::std::fmt::Display::fmt(&value, formatter) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: TaskSampleRateAttr) -> Self { - let value: f64 = match value { - TaskSampleRateAttr::Tenth => 0.1_f64, - TaskSampleRateAttr::All => 1_f64, - }; - ::opentelemetry::KeyValue::new(TaskSampleRateAttr::KEY, value) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: TaskSampleRateAttr) -> Self { - let value: f64 = match value { - TaskSampleRateAttr::Tenth => 0.1_f64, - TaskSampleRateAttr::All => 1_f64, - }; - value.into() - } -} - -/// Shards the task touched. -#[derive(Debug, Clone, PartialEq)] -pub struct TaskShardIdsAttr(Vec); - -#[allow(deprecated)] -impl TaskShardIdsAttr { - pub const KEY: &'static str = "myapp.task.shard_ids"; -} - -#[allow(deprecated)] -impl From> for TaskShardIdsAttr { - #[inline] - fn from(value: Vec) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl AsRef<[i64]> for TaskShardIdsAttr { - #[inline] - fn as_ref(&self) -> &[i64] { - &self.0 - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for TaskShardIdsAttr { - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str("[")?; - for (index, value) in self.0.iter().enumerate() { - if index != 0 { - formatter.write_str(",")?; - } - ::std::fmt::Display::fmt(value, formatter)?; - } - formatter.write_str("]") - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: TaskShardIdsAttr) -> Self { - ::opentelemetry::KeyValue::new(TaskShardIdsAttr::KEY, ::opentelemetry::Value::Array(::opentelemetry::Array::I64(value.0))) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: TaskShardIdsAttr) -> Self { - value.0.into_iter().collect::<::opentelemetry::logs::AnyValue>() - } -} - -/// Current state of the task. -#[derive(Debug, Clone, PartialEq, Copy)] -pub enum TaskStateAttr { - /// The task is waiting to run. - Queued, - /// The task is running. - /// - /// A task stays running until it finishes or is cancelled. - Running, - /// The task was paused. - #[deprecated(note = "Paused tasks are reported as queued.")] - Paused, -} - -#[allow(deprecated)] -impl TaskStateAttr { - pub const KEY: &'static str = "myapp.task.state"; -} - -#[allow(deprecated)] -impl AsRef for TaskStateAttr { - #[inline] - fn as_ref(&self) -> &str { - match self { - TaskStateAttr::Queued => "queued", - TaskStateAttr::Running => "running", - TaskStateAttr::Paused => "paused", - } - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for TaskStateAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str(self.as_ref()) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: TaskStateAttr) -> Self { - let value: &'static str = match value { - TaskStateAttr::Queued => "queued", - TaskStateAttr::Running => "running", - TaskStateAttr::Paused => "paused", - }; - ::opentelemetry::KeyValue::new(TaskStateAttr::KEY, value) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: TaskStateAttr) -> Self { - let value: &'static str = match value { - TaskStateAttr::Queued => "queued", - TaskStateAttr::Running => "running", - TaskStateAttr::Paused => "paused", - }; - value.into() - } -} - -/// Tags attached to the task. -#[derive(Debug, Clone, PartialEq)] -pub struct TaskTagsAttr(Vec<::opentelemetry::StringValue>); - -#[allow(deprecated)] -impl TaskTagsAttr { - pub const KEY: &'static str = "myapp.task.tags"; -} - -#[allow(deprecated)] -impl From> for TaskTagsAttr { - #[inline] - fn from(value: Vec<::opentelemetry::StringValue>) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl From> for TaskTagsAttr { - fn from(value: Vec) -> Self { - Self(value.into_iter().map(Into::into).collect()) - } -} - -#[allow(deprecated)] -impl AsRef<[::opentelemetry::StringValue]> for TaskTagsAttr { - #[inline] - fn as_ref(&self) -> &[::opentelemetry::StringValue] { - &self.0 - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for TaskTagsAttr { - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str("[")?; - for (index, value) in self.0.iter().enumerate() { - if index != 0 { - formatter.write_str(",")?; - } - write!(formatter, "\"{value}\"")?; - } - formatter.write_str("]") - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: TaskTagsAttr) -> Self { - ::opentelemetry::KeyValue::new(TaskTagsAttr::KEY, ::opentelemetry::Value::Array(::opentelemetry::Array::String(value.0))) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: TaskTagsAttr) -> Self { - value.0.into_iter().collect::<::opentelemetry::logs::AnyValue>() - } -} - -/// Scheduling weights applied to the task. -#[derive(Debug, Clone, PartialEq)] -pub struct TaskWeightsAttr(Vec); - -#[allow(deprecated)] -impl TaskWeightsAttr { - pub const KEY: &'static str = "myapp.task.weights"; -} - -#[allow(deprecated)] -impl From> for TaskWeightsAttr { - #[inline] - fn from(value: Vec) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl AsRef<[f64]> for TaskWeightsAttr { - #[inline] - fn as_ref(&self) -> &[f64] { - &self.0 - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for TaskWeightsAttr { - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str("[")?; - for (index, value) in self.0.iter().enumerate() { - if index != 0 { - formatter.write_str(",")?; - } - ::std::fmt::Display::fmt(value, formatter)?; - } - formatter.write_str("]") - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: TaskWeightsAttr) -> Self { - ::opentelemetry::KeyValue::new(TaskWeightsAttr::KEY, ::opentelemetry::Value::Array(::opentelemetry::Array::F64(value.0))) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: TaskWeightsAttr) -> Self { - value.0.into_iter().collect::<::opentelemetry::logs::AnyValue>() - } -} diff --git a/templates/code/rust/tests/attributes/test.rs b/templates/code/rust/tests/attributes/test.rs index bba8a21..cd6ccc3 100644 --- a/templates/code/rust/tests/attributes/test.rs +++ b/templates/code/rust/tests/attributes/test.rs @@ -1,54 +1,54 @@ -use generated_semconv::{authattr, myappattr, SCHEMA_URL}; +use generated_semconv::{attribute, SCHEMA_URL}; use opentelemetry::{Array, KeyValue, Value}; #[test] fn typed_attributes_preserve_keys_values_and_schema() { assert_eq!(SCHEMA_URL, "https://example.com/schemas/attributes/1.0.0"); - let value: KeyValue = myappattr::TaskIdAttr::from("task").into(); + let value: KeyValue = attribute::MyappTaskId::from("task").into(); assert_eq!(value, KeyValue::new("myapp.task.id", "task")); assert_eq!( - KeyValue::from(myappattr::TaskRetriesAttr::from(4)), + KeyValue::from(attribute::MyappTaskRetries::from(4)), KeyValue::new("myapp.task.retries", 4_i64) ); assert_eq!( - KeyValue::from(myappattr::TaskCancelledAttr::from(true)).value, + KeyValue::from(attribute::MyappTaskCancelled::from(true)).value, Value::Bool(true) ); assert_eq!( - KeyValue::from(myappattr::TaskProgressAttr::from(0.5)).value, + KeyValue::from(attribute::MyappTaskProgress::from(0.5)).value, Value::F64(0.5) ); assert_eq!( - KeyValue::from(myappattr::TaskTagsAttr::from(vec![String::from("tag")])).value, + KeyValue::from(attribute::MyappTaskTags::from(vec![String::from("tag")])).value, Value::Array(Array::String(vec!["tag".into()])) ); assert_eq!( - KeyValue::from(myappattr::TaskShardIdsAttr::from(vec![1, 2])).value, + KeyValue::from(attribute::MyappTaskShardIds::from(vec![1, 2])).value, Value::Array(Array::I64(vec![1, 2])) ); assert_eq!( - KeyValue::from(myappattr::TaskWeightsAttr::from(vec![0.25])).value, + KeyValue::from(attribute::MyappTaskWeights::from(vec![0.25])).value, Value::Array(Array::F64(vec![0.25])) ); assert_eq!( - KeyValue::from(myappattr::TaskFlagsAttr::from(vec![false])).value, + KeyValue::from(attribute::MyappTaskFlags::from(vec![false])).value, Value::Array(Array::Bool(vec![false])) ); assert_eq!( - KeyValue::from(myappattr::TaskStateAttr::Running).value, + KeyValue::from(attribute::MyappTaskState::Running).value, Value::String("running".into()) ); - assert_eq!(KeyValue::from(myappattr::TaskEscapedAttr::Quoted).value, Value::String("quote\" slash\\ newline\n tab\t backspace\u{0008} formfeed\u{000c} null\u{0000} snowman☃".into())); + assert_eq!(KeyValue::from(attribute::MyappTaskEscaped::Quoted).value, Value::String("quote\" slash\\ newline\n tab\t backspace\u{0008} formfeed\u{000c} null\u{0000} snowman☃".into())); assert_eq!( - KeyValue::from(authattr::LevelAttr::High).value, + KeyValue::from(attribute::AuthLevel::High).value, Value::I64(2) ); assert_eq!( - KeyValue::from(myappattr::TaskPreemptibleAttr::Allowed).value, + KeyValue::from(attribute::MyappTaskPreemptible::Allowed).value, Value::Bool(true) ); assert_eq!( - KeyValue::from(myappattr::TaskSampleRateAttr::All).value, + KeyValue::from(attribute::MyappTaskSampleRate::All).value, Value::F64(1.0) ); } @@ -56,26 +56,26 @@ fn typed_attributes_preserve_keys_values_and_schema() { #[test] fn string_attributes_accept_explicit_owned_and_inferred_conversions() { let owned = String::from("owned"); - let borrowed: myappattr::TaskIdAttr = { + let borrowed: attribute::MyappTaskId = { let source = String::from("borrowed"); source.into() }; assert_eq!( - KeyValue::from(myappattr::TaskIdAttr::from(owned)), + KeyValue::from(attribute::MyappTaskId::from(owned)), KeyValue::new("myapp.task.id", "owned") ); assert_eq!( KeyValue::from(borrowed), KeyValue::new("myapp.task.id", "borrowed") ); - let inferred: myappattr::TaskIdAttr = "inferred".into(); + let inferred: attribute::MyappTaskId = "inferred".into(); assert_eq!( KeyValue::from(inferred), KeyValue::new("myapp.task.id", "inferred") ); - let retries: myappattr::TaskRetriesAttr = 7_i64.into(); + let retries: attribute::MyappTaskRetries = 7_i64.into(); assert_eq!(KeyValue::from(retries).value, Value::I64(7)); - let tags: myappattr::TaskTagsAttr = vec![String::from("tag")].into(); + let tags: attribute::MyappTaskTags = vec![String::from("tag")].into(); assert_eq!( KeyValue::from(tags).value, Value::Array(Array::String(vec!["tag".into()])) @@ -85,20 +85,20 @@ fn string_attributes_accept_explicit_owned_and_inferred_conversions() { #[test] fn static_and_native_strings_preserve_their_storage() { const STATIC: &str = "static-task"; - let attribute = myappattr::TaskIdAttr::from(STATIC); + let attribute = attribute::MyappTaskId::from(STATIC); assert_eq!(attribute.as_ref().as_ptr(), STATIC.as_ptr()); let Value::String(text) = KeyValue::from(attribute).value else { panic!("expected string"); }; assert_eq!(text.as_str().as_ptr(), STATIC.as_ptr()); - let Value::String(text) = KeyValue::from(myappattr::TaskStateAttr::Running).value else { + let Value::String(text) = KeyValue::from(attribute::MyappTaskState::Running).value else { panic!("expected string"); }; - assert_eq!(text.as_str(), myappattr::TaskStateAttr::Running.as_ref()); + assert_eq!(text.as_str(), attribute::MyappTaskState::Running.as_ref()); let shared: std::sync::Arc = std::sync::Arc::from("shared-task"); let native = opentelemetry::StringValue::from(shared.clone()); - let attribute = myappattr::TaskIdAttr::from(native); + let attribute = attribute::MyappTaskId::from(native); assert_eq!(attribute.as_ref().as_ptr(), shared.as_ptr()); let Value::String(text) = KeyValue::from(attribute).value else { panic!("expected string"); @@ -109,7 +109,7 @@ fn static_and_native_strings_preserve_their_storage() { let native = vec![opentelemetry::StringValue::from("tag")]; let original = native.as_ptr(); let Value::Array(Array::String(values)) = - KeyValue::from(myappattr::TaskTagsAttr::from(native)).value + KeyValue::from(attribute::MyappTaskTags::from(native)).value else { panic!("expected string array"); }; @@ -119,26 +119,26 @@ fn static_and_native_strings_preserve_their_storage() { #[test] fn copy_scalars_and_borrowed_display_preserve_telemetry_formatting() { fn assert_copy() {} - assert_copy::(); - assert_copy::(); - assert_copy::(); - assert_copy::(); - let retries = myappattr::TaskRetriesAttr::from(7); + assert_copy::(); + assert_copy::(); + assert_copy::(); + assert_copy::(); + let retries = attribute::MyappTaskRetries::from(7); let _: KeyValue = retries.into(); assert_eq!(retries.to_string(), "7"); - assert_eq!(myappattr::TaskCancelledAttr::from(true).to_string(), "true"); - assert_eq!(myappattr::TaskProgressAttr::from(0.5).to_string(), "0.5"); - assert_eq!(myappattr::TaskStateAttr::Running.to_string(), "running"); - assert_eq!(authattr::LevelAttr::High.to_string(), "2"); - assert_eq!(myappattr::TaskSampleRateAttr::Tenth.to_string(), "0.1"); - let string = myappattr::TaskIdAttr::from(String::from("dynamic")); + assert_eq!(attribute::MyappTaskCancelled::from(true).to_string(), "true"); + assert_eq!(attribute::MyappTaskProgress::from(0.5).to_string(), "0.5"); + assert_eq!(attribute::MyappTaskState::Running.to_string(), "running"); + assert_eq!(attribute::AuthLevel::High.to_string(), "2"); + assert_eq!(attribute::MyappTaskSampleRate::Tenth.to_string(), "0.1"); + let string = attribute::MyappTaskId::from(String::from("dynamic")); assert_eq!(string.to_string(), string.as_ref()); - let array = myappattr::TaskTagsAttr::from(vec![String::from("a"), String::from("b")]); + let array = attribute::MyappTaskTags::from(vec![String::from("a"), String::from("b")]); assert_eq!(array.to_string(), KeyValue::from(array).value.to_string()); - let array = myappattr::TaskShardIdsAttr::from(vec![1, 2]); + let array = attribute::MyappTaskShardIds::from(vec![1, 2]); assert_eq!(array.to_string(), "[1,2]"); - let array = myappattr::TaskWeightsAttr::from(vec![0.25, 0.5]); + let array = attribute::MyappTaskWeights::from(vec![0.25, 0.5]); assert_eq!(array.to_string(), "[0.25,0.5]"); - let array = myappattr::TaskFlagsAttr::from(vec![true, false]); + let array = attribute::MyappTaskFlags::from(vec![true, false]); assert_eq!(array.to_string(), "[true,false]"); } diff --git a/templates/code/rust/tests/attributes/tests/allocations.rs b/templates/code/rust/tests/attributes/tests/allocations.rs index f415263..7ba0d05 100644 --- a/templates/code/rust/tests/attributes/tests/allocations.rs +++ b/templates/code/rust/tests/attributes/tests/allocations.rs @@ -1,4 +1,4 @@ -use generated_semconv::myappattr; +use generated_semconv::attribute; use opentelemetry::{KeyValue, Value}; use std::alloc::{GlobalAlloc, Layout, System}; use std::cell::Cell; @@ -40,7 +40,7 @@ fn allocations(operation: impl FnOnce() -> T) -> (T, usize) { #[test] fn string_enum_conversion_has_no_heap_allocation() { let (value, count) = - allocations(|| KeyValue::from(black_box(myappattr::TaskStateAttr::Running))); + allocations(|| KeyValue::from(black_box(attribute::MyappTaskState::Running))); assert_eq!(black_box(count), 0); assert_eq!(value.value, Value::String("running".into())); } @@ -48,7 +48,7 @@ fn string_enum_conversion_has_no_heap_allocation() { #[test] fn static_string_construction_and_conversion_have_no_heap_allocation() { let (value, count) = allocations(|| { - let attribute = myappattr::TaskIdAttr::from(black_box("static-task")); + let attribute = attribute::MyappTaskId::from(black_box("static-task")); black_box(KeyValue::from(attribute)) }); assert_eq!(black_box(count), 0); @@ -60,7 +60,7 @@ fn exact_capacity_owned_string_moves_without_another_allocation() { let mut text = String::from("owned-task"); text.shrink_to_fit(); let (value, count) = - allocations(|| KeyValue::from(myappattr::TaskIdAttr::from(black_box(text)))); + allocations(|| KeyValue::from(attribute::MyappTaskId::from(black_box(text)))); assert_eq!(black_box(count), 0); assert_eq!(value.value, Value::String("owned-task".into())); } @@ -69,6 +69,6 @@ fn exact_capacity_owned_string_moves_without_another_allocation() { fn native_string_array_moves_without_another_allocation() { let values = vec![opentelemetry::StringValue::from("static-tag")]; let (_, count) = - allocations(|| KeyValue::from(myappattr::TaskTagsAttr::from(black_box(values)))); + allocations(|| KeyValue::from(attribute::MyappTaskTags::from(black_box(values)))); assert_eq!(black_box(count), 0); } diff --git a/templates/code/rust/tests/attributes/tests/log_values.rs b/templates/code/rust/tests/attributes/tests/log_values.rs index e009bc3..33264e7 100644 --- a/templates/code/rust/tests/attributes/tests/log_values.rs +++ b/templates/code/rust/tests/attributes/tests/log_values.rs @@ -1,29 +1,29 @@ -use generated_semconv::{authattr, myappattr}; +use generated_semconv::{attribute}; use opentelemetry::logs::AnyValue; #[test] fn typed_attributes_convert_directly_to_log_values() { - let retries: AnyValue = myappattr::TaskRetriesAttr::from(4).into(); + let retries: AnyValue = attribute::MyappTaskRetries::from(4).into(); assert_eq!(retries, AnyValue::Int(4)); assert_eq!( - AnyValue::from(myappattr::TaskProgressAttr::from(0.5)), + AnyValue::from(attribute::MyappTaskProgress::from(0.5)), AnyValue::Double(0.5) ); assert_eq!( - AnyValue::from(myappattr::TaskCancelledAttr::from(true)), + AnyValue::from(attribute::MyappTaskCancelled::from(true)), AnyValue::Boolean(true) ); assert_eq!( - AnyValue::from(myappattr::TaskStateAttr::Running), + AnyValue::from(attribute::MyappTaskState::Running), AnyValue::String("running".into()) ); - assert_eq!(AnyValue::from(authattr::LevelAttr::High), AnyValue::Int(2)); + assert_eq!(AnyValue::from(attribute::AuthLevel::High), AnyValue::Int(2)); assert_eq!( - AnyValue::from(myappattr::TaskPreemptibleAttr::Allowed), + AnyValue::from(attribute::MyappTaskPreemptible::Allowed), AnyValue::Boolean(true) ); assert_eq!( - AnyValue::from(myappattr::TaskSampleRateAttr::Tenth), + AnyValue::from(attribute::MyappTaskSampleRate::Tenth), AnyValue::Double(0.1) ); } @@ -31,9 +31,9 @@ fn typed_attributes_convert_directly_to_log_values() { #[test] fn log_conversion_preserves_string_storage() { for attribute in [ - myappattr::TaskIdAttr::from("static-task"), - myappattr::TaskIdAttr::from(String::from("owned-task")), - myappattr::TaskIdAttr::from(opentelemetry::StringValue::from( + attribute::MyappTaskId::from("static-task"), + attribute::MyappTaskId::from(String::from("owned-task")), + attribute::MyappTaskId::from(opentelemetry::StringValue::from( std::sync::Arc::::from("shared-task"), )), ] { @@ -48,7 +48,7 @@ fn log_conversion_preserves_string_storage() { #[test] fn typed_arrays_export_log_lists_with_order_and_duplicates() { assert_eq!( - AnyValue::from(myappattr::TaskShardIdsAttr::from(vec![1, 1, 2])), + AnyValue::from(attribute::MyappTaskShardIds::from(vec![1, 1, 2])), AnyValue::ListAny(Box::new(vec![ AnyValue::Int(1), AnyValue::Int(1), @@ -56,14 +56,14 @@ fn typed_arrays_export_log_lists_with_order_and_duplicates() { ])) ); assert_eq!( - AnyValue::from(myappattr::TaskWeightsAttr::from(vec![0.25, 0.75])), + AnyValue::from(attribute::MyappTaskWeights::from(vec![0.25, 0.75])), AnyValue::ListAny(Box::new(vec![ AnyValue::Double(0.25), AnyValue::Double(0.75), ])) ); assert_eq!( - AnyValue::from(myappattr::TaskFlagsAttr::from(vec![true, false])), + AnyValue::from(attribute::MyappTaskFlags::from(vec![true, false])), AnyValue::ListAny(Box::new(vec![ AnyValue::Boolean(true), AnyValue::Boolean(false), @@ -71,7 +71,7 @@ fn typed_arrays_export_log_lists_with_order_and_duplicates() { ); let tag = opentelemetry::StringValue::from(String::from("owned-tag")); let pointer = tag.as_str().as_ptr(); - let AnyValue::ListAny(values) = AnyValue::from(myappattr::TaskTagsAttr::from(vec![tag])) else { + let AnyValue::ListAny(values) = AnyValue::from(attribute::MyappTaskTags::from(vec![tag])) else { panic!("expected string log list"); }; let AnyValue::String(value) = &values[0] else { @@ -80,7 +80,7 @@ fn typed_arrays_export_log_lists_with_order_and_duplicates() { assert_eq!(value.as_str(), "owned-tag"); assert_eq!(value.as_str().as_ptr(), pointer); assert_eq!( - AnyValue::from(myappattr::TaskTagsAttr::from(Vec::< + AnyValue::from(attribute::MyappTaskTags::from(Vec::< opentelemetry::StringValue, >::new())), AnyValue::ListAny(Box::default()) diff --git a/templates/code/rust/tests/codegen_exclusion/compile-fail/excluded_attribute.expected-error.txt b/templates/code/rust/tests/codegen_exclusion/compile-fail/excluded_attribute.expected-error.txt index a78250c..1319927 100644 --- a/templates/code/rust/tests/codegen_exclusion/compile-fail/excluded_attribute.expected-error.txt +++ b/templates/code/rust/tests/codegen_exclusion/compile-fail/excluded_attribute.expected-error.txt @@ -1 +1 @@ -could not find `HiddenAttr` +could not find `DemoHidden` diff --git a/templates/code/rust/tests/codegen_exclusion/compile-fail/excluded_attribute.rs b/templates/code/rust/tests/codegen_exclusion/compile-fail/excluded_attribute.rs index 85f82cf..cc0ed9d 100644 --- a/templates/code/rust/tests/codegen_exclusion/compile-fail/excluded_attribute.rs +++ b/templates/code/rust/tests/codegen_exclusion/compile-fail/excluded_attribute.rs @@ -1,3 +1,3 @@ fn main() { - let _ = generated_semconv::demoattr::HiddenAttr::from("value"); + let _ = generated_semconv::attribute::DemoHidden::from("value"); } diff --git a/templates/code/rust/tests/codegen_exclusion/compile-fail/excluded_member.rs b/templates/code/rust/tests/codegen_exclusion/compile-fail/excluded_member.rs index 0dfab52..7e3edd6 100644 --- a/templates/code/rust/tests/codegen_exclusion/compile-fail/excluded_member.rs +++ b/templates/code/rust/tests/codegen_exclusion/compile-fail/excluded_member.rs @@ -1,3 +1,3 @@ fn main() { - let _ = generated_semconv::demoattr::ModeAttr::Hidden; + let _ = generated_semconv::attribute::DemoMode::Hidden; } diff --git a/templates/code/rust/tests/codegen_exclusion/expected/demoattr.rs b/templates/code/rust/tests/codegen_exclusion/expected/attribute.rs similarity index 61% rename from templates/code/rust/tests/codegen_exclusion/expected/demoattr.rs rename to templates/code/rust/tests/codegen_exclusion/expected/attribute.rs index cfd8c00..3b5c65a 100644 --- a/templates/code/rust/tests/codegen_exclusion/expected/demoattr.rs +++ b/templates/code/rust/tests/codegen_exclusion/expected/attribute.rs @@ -1,15 +1,15 @@ // Generated by OpenTelemetry Weaver. /// Synthetic kept attribute. #[derive(Debug, Clone, PartialEq)] -pub struct KeptAttr(::opentelemetry::StringValue); +pub struct DemoKept(::opentelemetry::StringValue); #[allow(deprecated)] -impl KeptAttr { +impl DemoKept { pub const KEY: &'static str = "demo.kept"; } #[allow(deprecated)] -impl From<::opentelemetry::StringValue> for KeptAttr { +impl From<::opentelemetry::StringValue> for DemoKept { #[inline] fn from(value: ::opentelemetry::StringValue) -> Self { Self(value) @@ -17,7 +17,7 @@ impl From<::opentelemetry::StringValue> for KeptAttr { } #[allow(deprecated)] -impl From for KeptAttr { +impl From for DemoKept { #[inline] fn from(value: String) -> Self { Self(value.into()) @@ -25,7 +25,7 @@ impl From for KeptAttr { } #[allow(deprecated)] -impl From<&'static str> for KeptAttr { +impl From<&'static str> for DemoKept { #[inline] fn from(value: &'static str) -> Self { Self(value.into()) @@ -33,7 +33,7 @@ impl From<&'static str> for KeptAttr { } #[allow(deprecated)] -impl AsRef for KeptAttr { +impl AsRef for DemoKept { #[inline] fn as_ref(&self) -> &str { self.0.as_str() @@ -41,7 +41,7 @@ impl AsRef for KeptAttr { } #[allow(deprecated)] -impl ::std::fmt::Display for KeptAttr { +impl ::std::fmt::Display for DemoKept { #[inline] fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { formatter.write_str(self.as_ref()) @@ -49,45 +49,45 @@ impl ::std::fmt::Display for KeptAttr { } #[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { +impl From for ::opentelemetry::KeyValue { #[inline] - fn from(value: KeptAttr) -> Self { - ::opentelemetry::KeyValue::new(KeptAttr::KEY, value.0) + fn from(value: DemoKept) -> Self { + ::opentelemetry::KeyValue::new(DemoKept::KEY, value.0) } } #[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { +impl From for ::opentelemetry::logs::AnyValue { #[inline] - fn from(value: KeptAttr) -> Self { + fn from(value: DemoKept) -> Self { value.0.into() } } /// Synthetic mode. #[derive(Debug, Clone, PartialEq, Copy)] -pub enum ModeAttr { +pub enum DemoMode { /// Included mode. Kept, } #[allow(deprecated)] -impl ModeAttr { +impl DemoMode { pub const KEY: &'static str = "demo.mode"; } #[allow(deprecated)] -impl AsRef for ModeAttr { +impl AsRef for DemoMode { #[inline] fn as_ref(&self) -> &str { match self { - ModeAttr::Kept => "kept", + DemoMode::Kept => "kept", } } } #[allow(deprecated)] -impl ::std::fmt::Display for ModeAttr { +impl ::std::fmt::Display for DemoMode { #[inline] fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { formatter.write_str(self.as_ref()) @@ -95,22 +95,22 @@ impl ::std::fmt::Display for ModeAttr { } #[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { +impl From for ::opentelemetry::KeyValue { #[inline] - fn from(value: ModeAttr) -> Self { + fn from(value: DemoMode) -> Self { let value: &'static str = match value { - ModeAttr::Kept => "kept", + DemoMode::Kept => "kept", }; - ::opentelemetry::KeyValue::new(ModeAttr::KEY, value) + ::opentelemetry::KeyValue::new(DemoMode::KEY, value) } } #[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { +impl From for ::opentelemetry::logs::AnyValue { #[inline] - fn from(value: ModeAttr) -> Self { + fn from(value: DemoMode) -> Self { let value: &'static str = match value { - ModeAttr::Kept => "kept", + DemoMode::Kept => "kept", }; value.into() } diff --git a/templates/code/rust/tests/codegen_exclusion/expected/mod.rs b/templates/code/rust/tests/codegen_exclusion/expected/mod.rs index 162e747..60967a4 100644 --- a/templates/code/rust/tests/codegen_exclusion/expected/mod.rs +++ b/templates/code/rust/tests/codegen_exclusion/expected/mod.rs @@ -1,3 +1,3 @@ // Generated by OpenTelemetry Weaver. pub const SCHEMA_URL: &str = "https://example.com/schemas/exclusion/1.0.0"; -pub mod demoattr; +pub mod attribute; diff --git a/templates/code/rust/tests/codegen_exclusion/test.rs b/templates/code/rust/tests/codegen_exclusion/test.rs index 9ba5c22..19060a7 100644 --- a/templates/code/rust/tests/codegen_exclusion/test.rs +++ b/templates/code/rust/tests/codegen_exclusion/test.rs @@ -1,13 +1,13 @@ -use generated_semconv::demoattr::{KeptAttr, ModeAttr}; +use generated_semconv::attribute::{DemoKept, DemoMode}; use opentelemetry::KeyValue; #[test] fn explicit_false_keeps_attributes_and_enum_members() { assert_eq!( - KeyValue::from(KeptAttr::from("value")), + KeyValue::from(DemoKept::from("value")), KeyValue::new("demo.kept", "value") ); assert_eq!( - KeyValue::from(ModeAttr::Kept), + KeyValue::from(DemoMode::Kept), KeyValue::new("demo.mode", "kept") ); } diff --git a/templates/code/rust/tests/entities/compile-fail/missing_identity.rs b/templates/code/rust/tests/entities/compile-fail/missing_identity.rs index 86bfeb8..9b330ab 100644 --- a/templates/code/rust/tests/entities/compile-fail/missing_identity.rs +++ b/templates/code/rust/tests/entities/compile-fail/missing_identity.rs @@ -1,5 +1,5 @@ -use generated_semconv::myappentity::HostEntity; +use generated_semconv::resource::MyappHost; fn main() { - let _ = HostEntity::new([]); + let _ = MyappHost::new([]); } diff --git a/templates/code/rust/tests/entities/compile-fail/required_default.rs b/templates/code/rust/tests/entities/compile-fail/required_default.rs index 648643c..054e7d1 100644 --- a/templates/code/rust/tests/entities/compile-fail/required_default.rs +++ b/templates/code/rust/tests/entities/compile-fail/required_default.rs @@ -1,3 +1,3 @@ fn main() { - let _ = generated_semconv::myappentity::HostEntity::default(); + let _ = generated_semconv::resource::MyappHost::default(); } diff --git a/templates/code/rust/tests/entities/compile-fail/wrong_identity.expected-error.txt b/templates/code/rust/tests/entities/compile-fail/wrong_identity.expected-error.txt index 68cf9b6..86789b7 100644 --- a/templates/code/rust/tests/entities/compile-fail/wrong_identity.expected-error.txt +++ b/templates/code/rust/tests/entities/compile-fail/wrong_identity.expected-error.txt @@ -1 +1 @@ -expected `HostNameAttr`, found `QueueNameAttr` +expected `MyappHostName`, found `MyappQueueName` diff --git a/templates/code/rust/tests/entities/compile-fail/wrong_identity.rs b/templates/code/rust/tests/entities/compile-fail/wrong_identity.rs index 96041aa..4cdee8c 100644 --- a/templates/code/rust/tests/entities/compile-fail/wrong_identity.rs +++ b/templates/code/rust/tests/entities/compile-fail/wrong_identity.rs @@ -1,5 +1,5 @@ -use generated_semconv::{myappattr, myappentity}; +use generated_semconv::{attribute, resource}; fn main() { - let _ = myappentity::HostEntity::new(myappattr::QueueNameAttr::from("queue-1"), []); + let _ = resource::MyappHost::new(attribute::MyappQueueName::from("queue-1"), []); } diff --git a/templates/code/rust/tests/entities/expected/myappattr.rs b/templates/code/rust/tests/entities/expected/attribute.rs similarity index 57% rename from templates/code/rust/tests/entities/expected/myappattr.rs rename to templates/code/rust/tests/entities/expected/attribute.rs index 67e72ed..fbb748e 100644 --- a/templates/code/rust/tests/entities/expected/myappattr.rs +++ b/templates/code/rust/tests/entities/expected/attribute.rs @@ -2,15 +2,15 @@ /// Number of CPUs the host has. #[deprecated(note = "Use `myapp.host.cpu.logical_count` instead.")] #[derive(Debug, Clone, PartialEq, Copy)] -pub struct HostCpuCountAttr(i64); +pub struct MyappHostCpuCount(i64); #[allow(deprecated)] -impl HostCpuCountAttr { +impl MyappHostCpuCount { pub const KEY: &'static str = "myapp.host.cpu.count"; } #[allow(deprecated)] -impl From for HostCpuCountAttr { +impl From for MyappHostCpuCount { #[inline] fn from(value: i64) -> Self { Self(value) @@ -18,7 +18,7 @@ impl From for HostCpuCountAttr { } #[allow(deprecated)] -impl ::std::fmt::Display for HostCpuCountAttr { +impl ::std::fmt::Display for MyappHostCpuCount { #[inline] fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { ::std::fmt::Display::fmt(&self.0, formatter) @@ -26,32 +26,32 @@ impl ::std::fmt::Display for HostCpuCountAttr { } #[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { +impl From for ::opentelemetry::KeyValue { #[inline] - fn from(value: HostCpuCountAttr) -> Self { - ::opentelemetry::KeyValue::new(HostCpuCountAttr::KEY, value.0) + fn from(value: MyappHostCpuCount) -> Self { + ::opentelemetry::KeyValue::new(MyappHostCpuCount::KEY, value.0) } } #[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { +impl From for ::opentelemetry::logs::AnyValue { #[inline] - fn from(value: HostCpuCountAttr) -> Self { + fn from(value: MyappHostCpuCount) -> Self { value.0.into() } } /// Name of the host. #[derive(Debug, Clone, PartialEq)] -pub struct HostNameAttr(::opentelemetry::StringValue); +pub struct MyappHostName(::opentelemetry::StringValue); #[allow(deprecated)] -impl HostNameAttr { +impl MyappHostName { pub const KEY: &'static str = "myapp.host.name"; } #[allow(deprecated)] -impl From<::opentelemetry::StringValue> for HostNameAttr { +impl From<::opentelemetry::StringValue> for MyappHostName { #[inline] fn from(value: ::opentelemetry::StringValue) -> Self { Self(value) @@ -59,7 +59,7 @@ impl From<::opentelemetry::StringValue> for HostNameAttr { } #[allow(deprecated)] -impl From for HostNameAttr { +impl From for MyappHostName { #[inline] fn from(value: String) -> Self { Self(value.into()) @@ -67,7 +67,7 @@ impl From for HostNameAttr { } #[allow(deprecated)] -impl From<&'static str> for HostNameAttr { +impl From<&'static str> for MyappHostName { #[inline] fn from(value: &'static str) -> Self { Self(value.into()) @@ -75,7 +75,7 @@ impl From<&'static str> for HostNameAttr { } #[allow(deprecated)] -impl AsRef for HostNameAttr { +impl AsRef for MyappHostName { #[inline] fn as_ref(&self) -> &str { self.0.as_str() @@ -83,7 +83,7 @@ impl AsRef for HostNameAttr { } #[allow(deprecated)] -impl ::std::fmt::Display for HostNameAttr { +impl ::std::fmt::Display for MyappHostName { #[inline] fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { formatter.write_str(self.as_ref()) @@ -91,32 +91,32 @@ impl ::std::fmt::Display for HostNameAttr { } #[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { +impl From for ::opentelemetry::KeyValue { #[inline] - fn from(value: HostNameAttr) -> Self { - ::opentelemetry::KeyValue::new(HostNameAttr::KEY, value.0) + fn from(value: MyappHostName) -> Self { + ::opentelemetry::KeyValue::new(MyappHostName::KEY, value.0) } } #[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { +impl From for ::opentelemetry::logs::AnyValue { #[inline] - fn from(value: HostNameAttr) -> Self { + fn from(value: MyappHostName) -> Self { value.0.into() } } /// Role the host plays in the cluster. #[derive(Debug, Clone, PartialEq)] -pub struct HostRoleAttr(::opentelemetry::StringValue); +pub struct MyappHostRole(::opentelemetry::StringValue); #[allow(deprecated)] -impl HostRoleAttr { +impl MyappHostRole { pub const KEY: &'static str = "myapp.host.role"; } #[allow(deprecated)] -impl From<::opentelemetry::StringValue> for HostRoleAttr { +impl From<::opentelemetry::StringValue> for MyappHostRole { #[inline] fn from(value: ::opentelemetry::StringValue) -> Self { Self(value) @@ -124,7 +124,7 @@ impl From<::opentelemetry::StringValue> for HostRoleAttr { } #[allow(deprecated)] -impl From for HostRoleAttr { +impl From for MyappHostRole { #[inline] fn from(value: String) -> Self { Self(value.into()) @@ -132,7 +132,7 @@ impl From for HostRoleAttr { } #[allow(deprecated)] -impl From<&'static str> for HostRoleAttr { +impl From<&'static str> for MyappHostRole { #[inline] fn from(value: &'static str) -> Self { Self(value.into()) @@ -140,7 +140,7 @@ impl From<&'static str> for HostRoleAttr { } #[allow(deprecated)] -impl AsRef for HostRoleAttr { +impl AsRef for MyappHostRole { #[inline] fn as_ref(&self) -> &str { self.0.as_str() @@ -148,7 +148,7 @@ impl AsRef for HostRoleAttr { } #[allow(deprecated)] -impl ::std::fmt::Display for HostRoleAttr { +impl ::std::fmt::Display for MyappHostRole { #[inline] fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { formatter.write_str(self.as_ref()) @@ -156,24 +156,24 @@ impl ::std::fmt::Display for HostRoleAttr { } #[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { +impl From for ::opentelemetry::KeyValue { #[inline] - fn from(value: HostRoleAttr) -> Self { - ::opentelemetry::KeyValue::new(HostRoleAttr::KEY, value.0) + fn from(value: MyappHostRole) -> Self { + ::opentelemetry::KeyValue::new(MyappHostRole::KEY, value.0) } } #[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { +impl From for ::opentelemetry::logs::AnyValue { #[inline] - fn from(value: HostRoleAttr) -> Self { + fn from(value: MyappHostRole) -> Self { value.0.into() } } /// Type of the host. #[derive(Debug, Clone, PartialEq, Copy)] -pub enum HostTypeAttr { +pub enum MyappHostType { /// A physical host. Physical, /// A virtual host. @@ -181,23 +181,23 @@ pub enum HostTypeAttr { } #[allow(deprecated)] -impl HostTypeAttr { +impl MyappHostType { pub const KEY: &'static str = "myapp.host.type"; } #[allow(deprecated)] -impl AsRef for HostTypeAttr { +impl AsRef for MyappHostType { #[inline] fn as_ref(&self) -> &str { match self { - HostTypeAttr::Physical => "physical", - HostTypeAttr::Virtual => "virtual", + MyappHostType::Physical => "physical", + MyappHostType::Virtual => "virtual", } } } #[allow(deprecated)] -impl ::std::fmt::Display for HostTypeAttr { +impl ::std::fmt::Display for MyappHostType { #[inline] fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { formatter.write_str(self.as_ref()) @@ -205,24 +205,24 @@ impl ::std::fmt::Display for HostTypeAttr { } #[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { +impl From for ::opentelemetry::KeyValue { #[inline] - fn from(value: HostTypeAttr) -> Self { + fn from(value: MyappHostType) -> Self { let value: &'static str = match value { - HostTypeAttr::Physical => "physical", - HostTypeAttr::Virtual => "virtual", + MyappHostType::Physical => "physical", + MyappHostType::Virtual => "virtual", }; - ::opentelemetry::KeyValue::new(HostTypeAttr::KEY, value) + ::opentelemetry::KeyValue::new(MyappHostType::KEY, value) } } #[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { +impl From for ::opentelemetry::logs::AnyValue { #[inline] - fn from(value: HostTypeAttr) -> Self { + fn from(value: MyappHostType) -> Self { let value: &'static str = match value { - HostTypeAttr::Physical => "physical", - HostTypeAttr::Virtual => "virtual", + MyappHostType::Physical => "physical", + MyappHostType::Virtual => "virtual", }; value.into() } @@ -230,15 +230,15 @@ impl From for ::opentelemetry::logs::AnyValue { /// Name of the queue. #[derive(Debug, Clone, PartialEq)] -pub struct QueueNameAttr(::opentelemetry::StringValue); +pub struct MyappQueueName(::opentelemetry::StringValue); #[allow(deprecated)] -impl QueueNameAttr { +impl MyappQueueName { pub const KEY: &'static str = "myapp.queue.name"; } #[allow(deprecated)] -impl From<::opentelemetry::StringValue> for QueueNameAttr { +impl From<::opentelemetry::StringValue> for MyappQueueName { #[inline] fn from(value: ::opentelemetry::StringValue) -> Self { Self(value) @@ -246,7 +246,7 @@ impl From<::opentelemetry::StringValue> for QueueNameAttr { } #[allow(deprecated)] -impl From for QueueNameAttr { +impl From for MyappQueueName { #[inline] fn from(value: String) -> Self { Self(value.into()) @@ -254,7 +254,7 @@ impl From for QueueNameAttr { } #[allow(deprecated)] -impl From<&'static str> for QueueNameAttr { +impl From<&'static str> for MyappQueueName { #[inline] fn from(value: &'static str) -> Self { Self(value.into()) @@ -262,7 +262,7 @@ impl From<&'static str> for QueueNameAttr { } #[allow(deprecated)] -impl AsRef for QueueNameAttr { +impl AsRef for MyappQueueName { #[inline] fn as_ref(&self) -> &str { self.0.as_str() @@ -270,7 +270,7 @@ impl AsRef for QueueNameAttr { } #[allow(deprecated)] -impl ::std::fmt::Display for QueueNameAttr { +impl ::std::fmt::Display for MyappQueueName { #[inline] fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { formatter.write_str(self.as_ref()) @@ -278,32 +278,32 @@ impl ::std::fmt::Display for QueueNameAttr { } #[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { +impl From for ::opentelemetry::KeyValue { #[inline] - fn from(value: QueueNameAttr) -> Self { - ::opentelemetry::KeyValue::new(QueueNameAttr::KEY, value.0) + fn from(value: MyappQueueName) -> Self { + ::opentelemetry::KeyValue::new(MyappQueueName::KEY, value.0) } } #[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { +impl From for ::opentelemetry::logs::AnyValue { #[inline] - fn from(value: QueueNameAttr) -> Self { + fn from(value: MyappQueueName) -> Self { value.0.into() } } /// Number of items currently in the queue. #[derive(Debug, Clone, PartialEq, Copy)] -pub struct QueueSizeAttr(i64); +pub struct MyappQueueSize(i64); #[allow(deprecated)] -impl QueueSizeAttr { +impl MyappQueueSize { pub const KEY: &'static str = "myapp.queue.size"; } #[allow(deprecated)] -impl From for QueueSizeAttr { +impl From for MyappQueueSize { #[inline] fn from(value: i64) -> Self { Self(value) @@ -311,7 +311,7 @@ impl From for QueueSizeAttr { } #[allow(deprecated)] -impl ::std::fmt::Display for QueueSizeAttr { +impl ::std::fmt::Display for MyappQueueSize { #[inline] fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { ::std::fmt::Display::fmt(&self.0, formatter) @@ -319,17 +319,17 @@ impl ::std::fmt::Display for QueueSizeAttr { } #[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { +impl From for ::opentelemetry::KeyValue { #[inline] - fn from(value: QueueSizeAttr) -> Self { - ::opentelemetry::KeyValue::new(QueueSizeAttr::KEY, value.0) + fn from(value: MyappQueueSize) -> Self { + ::opentelemetry::KeyValue::new(MyappQueueSize::KEY, value.0) } } #[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { +impl From for ::opentelemetry::logs::AnyValue { #[inline] - fn from(value: QueueSizeAttr) -> Self { + fn from(value: MyappQueueSize) -> Self { value.0.into() } } diff --git a/templates/code/rust/tests/entities/expected/mod.rs b/templates/code/rust/tests/entities/expected/mod.rs index bab3903..f536bf2 100644 --- a/templates/code/rust/tests/entities/expected/mod.rs +++ b/templates/code/rust/tests/entities/expected/mod.rs @@ -1,5 +1,5 @@ // Generated by OpenTelemetry Weaver. pub const SCHEMA_URL: &str = "https://example.com/schemas/entities/1.0.0"; -pub mod myappattr; +pub mod attribute; -pub mod myappentity; +pub mod resource; diff --git a/templates/code/rust/tests/entities/expected/myappentity.rs b/templates/code/rust/tests/entities/expected/resource.rs similarity index 58% rename from templates/code/rust/tests/entities/expected/myappentity.rs rename to templates/code/rust/tests/entities/expected/resource.rs index 4971fe9..8fd95b9 100644 --- a/templates/code/rust/tests/entities/expected/myappentity.rs +++ b/templates/code/rust/tests/entities/expected/resource.rs @@ -1,17 +1,17 @@ // Code generated by weaver. DO NOT EDIT. #![allow(deprecated)] #[derive(Clone, Debug)] -pub enum HostEntityAttr { +pub enum MyappHostAttr { /// Opt-in: the convention records it only when a user asks for it. - HostCpuCount(super::myappattr::HostCpuCountAttr), - HostType(super::myappattr::HostTypeAttr), + HostCpuCount(super::attribute::MyappHostCpuCount), + HostType(super::attribute::MyappHostType), } -impl From for ::opentelemetry::KeyValue { - fn from(value: HostEntityAttr) -> Self { +impl From for ::opentelemetry::KeyValue { + fn from(value: MyappHostAttr) -> Self { match value { - HostEntityAttr::HostCpuCount(value) => ::opentelemetry::KeyValue::from(value), - HostEntityAttr::HostType(value) => ::opentelemetry::KeyValue::from(value), + MyappHostAttr::HostCpuCount(value) => ::opentelemetry::KeyValue::from(value), + MyappHostAttr::HostType(value) => ::opentelemetry::KeyValue::from(value), } } } @@ -21,13 +21,15 @@ impl From for ::opentelemetry::KeyValue { /// Identifies the entity: `myapp.host.name`. /// Describes the entity: `myapp.host.cpu.count`, `myapp.host.type`. #[derive(Clone, Debug)] -pub struct HostEntity { - r#myapp_host_name: super::myappattr::HostNameAttr, - options: ::smallvec::SmallVec<[HostEntityAttr; 2]>, +pub struct MyappHost { + r#myapp_host_name: super::attribute::MyappHostName, + options: ::smallvec::SmallVec<[MyappHostAttr; 2]>, } -impl HostEntity { - pub fn new(r#myapp_host_name: super::myappattr::HostNameAttr, options: impl IntoIterator) -> Self { +impl MyappHost { + pub const NAME: &'static str = "myapp.host"; + + pub fn new(r#myapp_host_name: super::attribute::MyappHostName, options: impl IntoIterator) -> Self { Self { r#myapp_host_name, options: options.into_iter().collect(), @@ -41,8 +43,8 @@ impl HostEntity { } } -impl From for ::opentelemetry_sdk::Resource { - fn from(value: HostEntity) -> Self { +impl From for ::opentelemetry_sdk::Resource { + fn from(value: MyappHost) -> Self { let attributes = [ ::opentelemetry::KeyValue::from(value.r#myapp_host_name), ].into_iter().chain(value.options.into_iter().map(::opentelemetry::KeyValue::from)); @@ -52,17 +54,17 @@ impl From for ::opentelemetry_sdk::Resource { } } #[derive(Clone, Debug)] -pub enum HostWorkerEntityAttr { +pub enum MyappHostWorkerAttr { /// Opt-in: the convention records it only when a user asks for it. - HostCpuCount(super::myappattr::HostCpuCountAttr), - HostType(super::myappattr::HostTypeAttr), + HostCpuCount(super::attribute::MyappHostCpuCount), + HostType(super::attribute::MyappHostType), } -impl From for ::opentelemetry::KeyValue { - fn from(value: HostWorkerEntityAttr) -> Self { +impl From for ::opentelemetry::KeyValue { + fn from(value: MyappHostWorkerAttr) -> Self { match value { - HostWorkerEntityAttr::HostCpuCount(value) => ::opentelemetry::KeyValue::from(value), - HostWorkerEntityAttr::HostType(value) => ::opentelemetry::KeyValue::from(value), + MyappHostWorkerAttr::HostCpuCount(value) => ::opentelemetry::KeyValue::from(value), + MyappHostWorkerAttr::HostType(value) => ::opentelemetry::KeyValue::from(value), } } } @@ -73,14 +75,16 @@ impl From for ::opentelemetry::KeyValue { /// Describes the entity: `myapp.host.cpu.count`, `myapp.host.role`, `myapp.host.type`. /// Refines `myapp.host`. #[derive(Clone, Debug)] -pub struct HostWorkerEntity { - r#myapp_host_name: super::myappattr::HostNameAttr, - r#myapp_host_role: super::myappattr::HostRoleAttr, - options: ::smallvec::SmallVec<[HostWorkerEntityAttr; 2]>, +pub struct MyappHostWorker { + r#myapp_host_name: super::attribute::MyappHostName, + r#myapp_host_role: super::attribute::MyappHostRole, + options: ::smallvec::SmallVec<[MyappHostWorkerAttr; 2]>, } -impl HostWorkerEntity { - pub fn new(r#myapp_host_name: super::myappattr::HostNameAttr, r#myapp_host_role: super::myappattr::HostRoleAttr, options: impl IntoIterator) -> Self { +impl MyappHostWorker { + pub const NAME: &'static str = "myapp.host"; + + pub fn new(r#myapp_host_name: super::attribute::MyappHostName, r#myapp_host_role: super::attribute::MyappHostRole, options: impl IntoIterator) -> Self { Self { r#myapp_host_name, r#myapp_host_role, @@ -96,8 +100,8 @@ impl HostWorkerEntity { } } -impl From for ::opentelemetry_sdk::Resource { - fn from(value: HostWorkerEntity) -> Self { +impl From for ::opentelemetry_sdk::Resource { + fn from(value: MyappHostWorker) -> Self { let attributes = [ ::opentelemetry::KeyValue::from(value.r#myapp_host_name), ::opentelemetry::KeyValue::from(value.r#myapp_host_role), @@ -108,16 +112,16 @@ impl From for ::opentelemetry_sdk::Resource { } } #[derive(Clone, Debug)] -pub enum OptionalEntityAttr { - QueueName(super::myappattr::QueueNameAttr), - QueueSize(super::myappattr::QueueSizeAttr), +pub enum MyappOptionalAttr { + QueueName(super::attribute::MyappQueueName), + QueueSize(super::attribute::MyappQueueSize), } -impl From for ::opentelemetry::KeyValue { - fn from(value: OptionalEntityAttr) -> Self { +impl From for ::opentelemetry::KeyValue { + fn from(value: MyappOptionalAttr) -> Self { match value { - OptionalEntityAttr::QueueName(value) => ::opentelemetry::KeyValue::from(value), - OptionalEntityAttr::QueueSize(value) => ::opentelemetry::KeyValue::from(value), + MyappOptionalAttr::QueueName(value) => ::opentelemetry::KeyValue::from(value), + MyappOptionalAttr::QueueSize(value) => ::opentelemetry::KeyValue::from(value), } } } @@ -125,12 +129,14 @@ impl From for ::opentelemetry::KeyValue { /// Identifies the entity: `myapp.queue.name`. /// Describes the entity: `myapp.queue.size`. #[derive(Clone, Debug, Default)] -pub struct OptionalEntity { - options: ::smallvec::SmallVec<[OptionalEntityAttr; 2]>, +pub struct MyappOptional { + options: ::smallvec::SmallVec<[MyappOptionalAttr; 2]>, } -impl OptionalEntity { - pub fn new(options: impl IntoIterator) -> Self { +impl MyappOptional { + pub const NAME: &'static str = "myapp.optional"; + + pub fn new(options: impl IntoIterator) -> Self { Self { options: options.into_iter().collect(), } @@ -142,8 +148,8 @@ impl OptionalEntity { } } -impl From for ::opentelemetry_sdk::Resource { - fn from(value: OptionalEntity) -> Self { +impl From for ::opentelemetry_sdk::Resource { + fn from(value: MyappOptional) -> Self { let attributes = [ ].into_iter().chain(value.options.into_iter().map(::opentelemetry::KeyValue::from)); ::opentelemetry_sdk::Resource::builder_empty() @@ -152,14 +158,14 @@ impl From for ::opentelemetry_sdk::Resource { } } #[derive(Clone, Debug)] -pub enum QueueEntityAttr { - QueueSize(super::myappattr::QueueSizeAttr), +pub enum MyappQueueAttr { + QueueSize(super::attribute::MyappQueueSize), } -impl From for ::opentelemetry::KeyValue { - fn from(value: QueueEntityAttr) -> Self { +impl From for ::opentelemetry::KeyValue { + fn from(value: MyappQueueAttr) -> Self { match value { - QueueEntityAttr::QueueSize(value) => ::opentelemetry::KeyValue::from(value), + MyappQueueAttr::QueueSize(value) => ::opentelemetry::KeyValue::from(value), } } } @@ -167,13 +173,15 @@ impl From for ::opentelemetry::KeyValue { /// Identifies the entity: `myapp.queue.name`. /// Describes the entity: `myapp.queue.size`. #[derive(Clone, Debug)] -pub struct QueueEntity { - r#myapp_queue_name: super::myappattr::QueueNameAttr, - options: ::smallvec::SmallVec<[QueueEntityAttr; 1]>, +pub struct MyappQueue { + r#myapp_queue_name: super::attribute::MyappQueueName, + options: ::smallvec::SmallVec<[MyappQueueAttr; 1]>, } -impl QueueEntity { - pub fn new(r#myapp_queue_name: super::myappattr::QueueNameAttr, options: impl IntoIterator) -> Self { +impl MyappQueue { + pub const NAME: &'static str = "myapp.queue"; + + pub fn new(r#myapp_queue_name: super::attribute::MyappQueueName, options: impl IntoIterator) -> Self { Self { r#myapp_queue_name, options: options.into_iter().collect(), @@ -187,8 +195,8 @@ impl QueueEntity { } } -impl From for ::opentelemetry_sdk::Resource { - fn from(value: QueueEntity) -> Self { +impl From for ::opentelemetry_sdk::Resource { + fn from(value: MyappQueue) -> Self { let attributes = [ ::opentelemetry::KeyValue::from(value.r#myapp_queue_name), ].into_iter().chain(value.options.into_iter().map(::opentelemetry::KeyValue::from)); diff --git a/templates/code/rust/tests/entities/test.rs b/templates/code/rust/tests/entities/test.rs index 71ad6be..16bd680 100644 --- a/templates/code/rust/tests/entities/test.rs +++ b/templates/code/rust/tests/entities/test.rs @@ -1,13 +1,13 @@ -use generated_semconv::{myappattr, myappentity, SCHEMA_URL}; +use generated_semconv::{attribute, resource, SCHEMA_URL}; use opentelemetry::{Key, Value}; use opentelemetry_sdk::Resource; #[test] fn entity_exports_identity_description_and_schema() { - let entity = myappentity::HostEntity::new( - myappattr::HostNameAttr::from("worker-1"), - [myappentity::HostEntityAttr::HostType( - myappattr::HostTypeAttr::Virtual, + let entity = resource::MyappHost::new( + attribute::MyappHostName::from("worker-1"), + [resource::MyappHostAttr::HostType( + attribute::MyappHostType::Virtual, )], ); let attributes: Vec<_> = entity.attributes().collect(); @@ -23,9 +23,9 @@ fn entity_exports_identity_description_and_schema() { #[test] fn refinement_requires_its_description_attribute() { - let entity = myappentity::HostWorkerEntity::new( - myappattr::HostNameAttr::from("worker-2"), - myappattr::HostRoleAttr::from("worker"), + let entity = resource::MyappHostWorker::new( + attribute::MyappHostName::from("worker-2"), + attribute::MyappHostRole::from("worker"), [], ); assert_eq!(entity.attributes().count(), 2); @@ -41,7 +41,7 @@ fn consuming_export_preserves_owned_string_storage() { let mut owned = String::from("dynamic-worker"); owned.shrink_to_fit(); let original = owned.as_ptr(); - let entity = myappentity::HostEntity::new(myappattr::HostNameAttr::from(owned), []); + let entity = resource::MyappHost::new(attribute::MyappHostName::from(owned), []); let resource: Resource = entity.into(); let value = resource .iter() @@ -56,7 +56,7 @@ fn consuming_export_preserves_owned_string_storage() { #[test] fn default_is_available_when_no_attributes_are_required() { - let empty = myappentity::OptionalEntity::default(); + let empty = resource::MyappOptional::default(); assert_eq!(empty.attributes().count(), 0); let resource = Resource::from(empty); assert_eq!(resource.len(), 0); @@ -66,13 +66,13 @@ fn default_is_available_when_no_attributes_are_required() { #[test] fn optional_attribute_overflow_preserves_values_and_order() { let options = (0..15).map(|index| { - myappentity::HostEntityAttr::HostType(if index == 14 { - myappattr::HostTypeAttr::Physical + resource::MyappHostAttr::HostType(if index == 14 { + attribute::MyappHostType::Physical } else { - myappattr::HostTypeAttr::Virtual + attribute::MyappHostType::Virtual }) }); - let entity = myappentity::HostEntity::new(myappattr::HostNameAttr::from("overflow"), options); + let entity = resource::MyappHost::new(attribute::MyappHostName::from("overflow"), options); let attributes: Vec<_> = entity.attributes().collect(); assert_eq!(attributes.len(), 16); assert_eq!( @@ -85,3 +85,11 @@ fn optional_attribute_overflow_preserves_values_and_order() { Some(Value::String("physical".into())) ); } + +const _: &str = resource::MyappHost::NAME; + +#[test] +fn entities_expose_their_type_as_a_constant() { + assert_eq!(resource::MyappHost::NAME, "myapp.host"); + assert_eq!(resource::MyappHostWorker::NAME, resource::MyappHost::NAME); +} diff --git a/templates/code/rust/tests/error_cross_namespace_collision/expected-error.txt b/templates/code/rust/tests/error_cross_namespace_collision/expected-error.txt new file mode 100644 index 0000000..b284487 --- /dev/null +++ b/templates/code/rust/tests/error_cross_namespace_collision/expected-error.txt @@ -0,0 +1 @@ +module attribute has attributes that render to the same Rust identifier: my.app_task and my_app.task diff --git a/templates/code/rust/tests/error_cross_namespace_collision/registry/manifest.yaml b/templates/code/rust/tests/error_cross_namespace_collision/registry/manifest.yaml new file mode 100644 index 0000000..5bddc29 --- /dev/null +++ b/templates/code/rust/tests/error_cross_namespace_collision/registry/manifest.yaml @@ -0,0 +1,2 @@ +name: demo +schema_url: https://example.com/schemas/1.0.0 diff --git a/templates/code/rust/tests/error_cross_namespace_collision/registry/model.yaml b/templates/code/rust/tests/error_cross_namespace_collision/registry/model.yaml new file mode 100644 index 0000000..0bfb698 --- /dev/null +++ b/templates/code/rust/tests/error_cross_namespace_collision/registry/model.yaml @@ -0,0 +1,10 @@ +file_format: definition/2 +attributes: + - key: my_app.task + stability: stable + brief: Synthetic attribute. + type: string + - key: my.app_task + stability: stable + brief: Synthetic attribute. + type: string diff --git a/templates/code/rust/tests/error_event_collision/expected-error.txt b/templates/code/rust/tests/error_event_collision/expected-error.txt index 5fd8cbf..4882bee 100644 --- a/templates/code/rust/tests/error_event_collision/expected-error.txt +++ b/templates/code/rust/tests/error_event_collision/expected-error.txt @@ -1 +1 @@ -package myappevent has events that render to the same Rust identifier: myapp.task.finished and myapp.task_finished +module event has events that render to the same Rust identifier: myapp.task.finished and myapp.task_finished diff --git a/templates/code/rust/tests/error_event_option_collision/expected-error.txt b/templates/code/rust/tests/error_event_option_collision/expected-error.txt deleted file mode 100644 index 4cc16a3..0000000 --- a/templates/code/rust/tests/error_event_option_collision/expected-error.txt +++ /dev/null @@ -1 +0,0 @@ -package exceptionevent has events that render to the same Rust identifier diff --git a/templates/code/rust/tests/error_event_option_collision/registry/manifest.yaml b/templates/code/rust/tests/error_event_option_collision/registry/manifest.yaml deleted file mode 100644 index 9f878f4..0000000 --- a/templates/code/rust/tests/error_event_option_collision/registry/manifest.yaml +++ /dev/null @@ -1,2 +0,0 @@ -name: event_option_collision -schema_url: https://example.com/schemas/event-option-collision/1.0.0 diff --git a/templates/code/rust/tests/error_event_option_collision/registry/model.yaml b/templates/code/rust/tests/error_event_option_collision/registry/model.yaml deleted file mode 100644 index d4fb4a2..0000000 --- a/templates/code/rust/tests/error_event_option_collision/registry/model.yaml +++ /dev/null @@ -1,10 +0,0 @@ -file_format: definition/2 -events: - - name: exception - stability: stable - requirement_level: recommended - brief: A synthetic exception occurred. - - name: exception.event - stability: stable - requirement_level: recommended - brief: Another synthetic exception occurred. diff --git a/templates/code/rust/tests/error_metric_attr_collision/expected-error.txt b/templates/code/rust/tests/error_metric_attr_collision/expected-error.txt new file mode 100644 index 0000000..aa4251e --- /dev/null +++ b/templates/code/rust/tests/error_metric_attr_collision/expected-error.txt @@ -0,0 +1 @@ +module metric has metrics that render to the same Rust identifier: myapp.task.duration and myapp.task.duration.attr diff --git a/templates/code/rust/tests/error_metric_attr_collision/registry/manifest.yaml b/templates/code/rust/tests/error_metric_attr_collision/registry/manifest.yaml new file mode 100644 index 0000000..831d7c5 --- /dev/null +++ b/templates/code/rust/tests/error_metric_attr_collision/registry/manifest.yaml @@ -0,0 +1,2 @@ +name: error_metric_attr_collision +schema_url: https://example.com/schemas/error_metric_attr_collision/1.0.0 diff --git a/templates/code/rust/tests/error_metric_attr_collision/registry/model.yaml b/templates/code/rust/tests/error_metric_attr_collision/registry/model.yaml new file mode 100644 index 0000000..456812d --- /dev/null +++ b/templates/code/rust/tests/error_metric_attr_collision/registry/model.yaml @@ -0,0 +1,18 @@ +file_format: definition/2 +metrics: + - name: myapp.task.duration + instrument: histogram + unit: s + stability: stable + brief: Synthetic task duration. + annotations: + code_generation: + metric_value_type: double + - name: myapp.task.duration.attr + instrument: counter + unit: "{task}" + stability: stable + brief: Synthetic counter whose name ends in attr. + annotations: + code_generation: + metric_value_type: int diff --git a/templates/code/rust/tests/error_metric_collision/expected-error.txt b/templates/code/rust/tests/error_metric_collision/expected-error.txt index de37c96..8828c16 100644 --- a/templates/code/rust/tests/error_metric_collision/expected-error.txt +++ b/templates/code/rust/tests/error_metric_collision/expected-error.txt @@ -1 +1 @@ -package myappmetric has metrics that render to the same Rust identifier: myapp.task.started and myapp.task_started +module metric has metrics that render to the same Rust identifier: myapp.task.started and myapp.task_started diff --git a/templates/code/rust/tests/error_observable_collision/expected-error.txt b/templates/code/rust/tests/error_observable_collision/expected-error.txt index 3470b15..45bb4b7 100644 --- a/templates/code/rust/tests/error_observable_collision/expected-error.txt +++ b/templates/code/rust/tests/error_observable_collision/expected-error.txt @@ -1 +1 @@ -package myappmetric has metrics that render to the same Rust identifier: myapp.task.started and myapp.task.started.observable +module metric has metrics that render to the same Rust identifier: myapp.task.started and myapp.task.started.observable diff --git a/templates/code/rust/tests/error_span_collision/expected-error.txt b/templates/code/rust/tests/error_span_collision/expected-error.txt index 15189b1..c42e5c2 100644 --- a/templates/code/rust/tests/error_span_collision/expected-error.txt +++ b/templates/code/rust/tests/error_span_collision/expected-error.txt @@ -1 +1 @@ -package myappspan has spans that render to the same Rust identifier: myapp.task.run and myapp.task_run +module trace has spans that render to the same Rust identifier: myapp.task.run and myapp.task_run diff --git a/templates/code/rust/tests/event_no_attributes/expected/probeevent.rs b/templates/code/rust/tests/event_no_attributes/expected/event.rs similarity index 59% rename from templates/code/rust/tests/event_no_attributes/expected/probeevent.rs rename to templates/code/rust/tests/event_no_attributes/expected/event.rs index 873ac71..75ce611 100644 --- a/templates/code/rust/tests/event_no_attributes/expected/probeevent.rs +++ b/templates/code/rust/tests/event_no_attributes/expected/event.rs @@ -2,25 +2,33 @@ use ::opentelemetry::logs::LogRecord; use ::opentelemetry::trace::TraceContextExt; +/// A synthetic tick occurred. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct ProbeTick; + +impl ProbeTick { + pub const NAME: &'static str = "probe.tick"; +} + #[derive(Clone, Debug)] -pub enum TickOption { +pub enum ProbeTickOption { Severity(::opentelemetry::logs::Severity), Timestamp(::std::time::SystemTime), } /// A synthetic tick occurred. -pub fn r#emit_tick(context: &::opentelemetry::Context, logger: &super::logger::Logger, options: impl IntoIterator) { +pub fn r#emit_probe_tick(context: &::opentelemetry::Context, logger: &super::logger::Logger, options: impl IntoIterator) { let mut severity = ::opentelemetry::logs::Severity::Info; let mut timestamp = None; for option in options { match option { - TickOption::Severity(value) => severity = value, - TickOption::Timestamp(value) => timestamp = Some(value), + ProbeTickOption::Severity(value) => severity = value, + ProbeTickOption::Timestamp(value) => timestamp = Some(value), } } - if !logger.inner().event_enabled(severity, "", Some("probe.tick")) { return; } + if !logger.inner().event_enabled(severity, "", Some(ProbeTick::NAME)) { return; } let _context_guard = context.clone().attach(); let mut record = logger.inner().create_log_record(); - record.set_event_name("probe.tick"); + record.set_event_name(ProbeTick::NAME); record.set_severity_number(severity); record.set_observed_timestamp(::std::time::SystemTime::now()); if let Some(timestamp) = timestamp { record.set_timestamp(timestamp); } diff --git a/templates/code/rust/tests/event_no_attributes/expected/mod.rs b/templates/code/rust/tests/event_no_attributes/expected/mod.rs index 86001b2..e8ed8f8 100644 --- a/templates/code/rust/tests/event_no_attributes/expected/mod.rs +++ b/templates/code/rust/tests/event_no_attributes/expected/mod.rs @@ -4,4 +4,4 @@ pub const SCHEMA_URL: &str = "https://example.com/schemas/event-no-attributes/1. pub mod scope; pub mod options; pub mod logger; -pub mod probeevent; +pub mod event; diff --git a/templates/code/rust/tests/event_no_attributes/test.rs b/templates/code/rust/tests/event_no_attributes/test.rs index 7483c37..6f4f092 100644 --- a/templates/code/rust/tests/event_no_attributes/test.rs +++ b/templates/code/rust/tests/event_no_attributes/test.rs @@ -1,5 +1,5 @@ use generated_semconv::options::InstrumentationOptions; -use generated_semconv::{logger, probeevent}; +use generated_semconv::{event, logger}; use opentelemetry::logs::Severity; use opentelemetry_sdk::logs::{InMemoryLogExporter, SdkLoggerProvider}; @@ -10,10 +10,10 @@ fn events_without_attributes_export_cleanly() { .with_simple_exporter(exporter.clone()) .build(); let logger = logger::Logger::new(&provider, InstrumentationOptions::default()); - probeevent::emit_tick( + event::emit_probe_tick( &opentelemetry::Context::new(), &logger, - [probeevent::TickOption::Severity(Severity::Debug)], + [event::ProbeTickOption::Severity(Severity::Debug)], ); provider.force_flush().unwrap(); let records = exporter.get_emitted_logs().unwrap(); diff --git a/templates/code/rust/tests/events/expected/myappattr.rs b/templates/code/rust/tests/events/expected/attribute.rs similarity index 51% rename from templates/code/rust/tests/events/expected/myappattr.rs rename to templates/code/rust/tests/events/expected/attribute.rs index 697c2d0..780d1ee 100644 --- a/templates/code/rust/tests/events/expected/myappattr.rs +++ b/templates/code/rust/tests/events/expected/attribute.rs @@ -1,15 +1,15 @@ // Generated by OpenTelemetry Weaver. /// Synthetic bool values. #[derive(Debug, Clone, PartialEq)] -pub struct BoolValuesAttr(Vec); +pub struct MyappBoolValues(Vec); #[allow(deprecated)] -impl BoolValuesAttr { +impl MyappBoolValues { pub const KEY: &'static str = "myapp.bool.values"; } #[allow(deprecated)] -impl From> for BoolValuesAttr { +impl From> for MyappBoolValues { #[inline] fn from(value: Vec) -> Self { Self(value) @@ -17,7 +17,7 @@ impl From> for BoolValuesAttr { } #[allow(deprecated)] -impl AsRef<[bool]> for BoolValuesAttr { +impl AsRef<[bool]> for MyappBoolValues { #[inline] fn as_ref(&self) -> &[bool] { &self.0 @@ -25,7 +25,7 @@ impl AsRef<[bool]> for BoolValuesAttr { } #[allow(deprecated)] -impl ::std::fmt::Display for BoolValuesAttr { +impl ::std::fmt::Display for MyappBoolValues { fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { formatter.write_str("[")?; for (index, value) in self.0.iter().enumerate() { @@ -39,32 +39,32 @@ impl ::std::fmt::Display for BoolValuesAttr { } #[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { +impl From for ::opentelemetry::KeyValue { #[inline] - fn from(value: BoolValuesAttr) -> Self { - ::opentelemetry::KeyValue::new(BoolValuesAttr::KEY, ::opentelemetry::Value::Array(::opentelemetry::Array::Bool(value.0))) + fn from(value: MyappBoolValues) -> Self { + ::opentelemetry::KeyValue::new(MyappBoolValues::KEY, ::opentelemetry::Value::Array(::opentelemetry::Array::Bool(value.0))) } } #[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { +impl From for ::opentelemetry::logs::AnyValue { #[inline] - fn from(value: BoolValuesAttr) -> Self { + fn from(value: MyappBoolValues) -> Self { value.0.into_iter().collect::<::opentelemetry::logs::AnyValue>() } } /// Synthetic double values. #[derive(Debug, Clone, PartialEq)] -pub struct DoubleValuesAttr(Vec); +pub struct MyappDoubleValues(Vec); #[allow(deprecated)] -impl DoubleValuesAttr { +impl MyappDoubleValues { pub const KEY: &'static str = "myapp.double.values"; } #[allow(deprecated)] -impl From> for DoubleValuesAttr { +impl From> for MyappDoubleValues { #[inline] fn from(value: Vec) -> Self { Self(value) @@ -72,7 +72,7 @@ impl From> for DoubleValuesAttr { } #[allow(deprecated)] -impl AsRef<[f64]> for DoubleValuesAttr { +impl AsRef<[f64]> for MyappDoubleValues { #[inline] fn as_ref(&self) -> &[f64] { &self.0 @@ -80,7 +80,7 @@ impl AsRef<[f64]> for DoubleValuesAttr { } #[allow(deprecated)] -impl ::std::fmt::Display for DoubleValuesAttr { +impl ::std::fmt::Display for MyappDoubleValues { fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { formatter.write_str("[")?; for (index, value) in self.0.iter().enumerate() { @@ -94,32 +94,32 @@ impl ::std::fmt::Display for DoubleValuesAttr { } #[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { +impl From for ::opentelemetry::KeyValue { #[inline] - fn from(value: DoubleValuesAttr) -> Self { - ::opentelemetry::KeyValue::new(DoubleValuesAttr::KEY, ::opentelemetry::Value::Array(::opentelemetry::Array::F64(value.0))) + fn from(value: MyappDoubleValues) -> Self { + ::opentelemetry::KeyValue::new(MyappDoubleValues::KEY, ::opentelemetry::Value::Array(::opentelemetry::Array::F64(value.0))) } } #[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { +impl From for ::opentelemetry::logs::AnyValue { #[inline] - fn from(value: DoubleValuesAttr) -> Self { + fn from(value: MyappDoubleValues) -> Self { value.0.into_iter().collect::<::opentelemetry::logs::AnyValue>() } } /// Synthetic int values. #[derive(Debug, Clone, PartialEq)] -pub struct IntValuesAttr(Vec); +pub struct MyappIntValues(Vec); #[allow(deprecated)] -impl IntValuesAttr { +impl MyappIntValues { pub const KEY: &'static str = "myapp.int.values"; } #[allow(deprecated)] -impl From> for IntValuesAttr { +impl From> for MyappIntValues { #[inline] fn from(value: Vec) -> Self { Self(value) @@ -127,7 +127,7 @@ impl From> for IntValuesAttr { } #[allow(deprecated)] -impl AsRef<[i64]> for IntValuesAttr { +impl AsRef<[i64]> for MyappIntValues { #[inline] fn as_ref(&self) -> &[i64] { &self.0 @@ -135,7 +135,7 @@ impl AsRef<[i64]> for IntValuesAttr { } #[allow(deprecated)] -impl ::std::fmt::Display for IntValuesAttr { +impl ::std::fmt::Display for MyappIntValues { fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { formatter.write_str("[")?; for (index, value) in self.0.iter().enumerate() { @@ -149,32 +149,32 @@ impl ::std::fmt::Display for IntValuesAttr { } #[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { +impl From for ::opentelemetry::KeyValue { #[inline] - fn from(value: IntValuesAttr) -> Self { - ::opentelemetry::KeyValue::new(IntValuesAttr::KEY, ::opentelemetry::Value::Array(::opentelemetry::Array::I64(value.0))) + fn from(value: MyappIntValues) -> Self { + ::opentelemetry::KeyValue::new(MyappIntValues::KEY, ::opentelemetry::Value::Array(::opentelemetry::Array::I64(value.0))) } } #[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { +impl From for ::opentelemetry::logs::AnyValue { #[inline] - fn from(value: IntValuesAttr) -> Self { + fn from(value: MyappIntValues) -> Self { value.0.into_iter().collect::<::opentelemetry::logs::AnyValue>() } } /// Synthetic string values. #[derive(Debug, Clone, PartialEq)] -pub struct StringValuesAttr(Vec<::opentelemetry::StringValue>); +pub struct MyappStringValues(Vec<::opentelemetry::StringValue>); #[allow(deprecated)] -impl StringValuesAttr { +impl MyappStringValues { pub const KEY: &'static str = "myapp.string.values"; } #[allow(deprecated)] -impl From> for StringValuesAttr { +impl From> for MyappStringValues { #[inline] fn from(value: Vec<::opentelemetry::StringValue>) -> Self { Self(value) @@ -182,14 +182,14 @@ impl From> for StringValuesAttr { } #[allow(deprecated)] -impl From> for StringValuesAttr { +impl From> for MyappStringValues { fn from(value: Vec) -> Self { Self(value.into_iter().map(Into::into).collect()) } } #[allow(deprecated)] -impl AsRef<[::opentelemetry::StringValue]> for StringValuesAttr { +impl AsRef<[::opentelemetry::StringValue]> for MyappStringValues { #[inline] fn as_ref(&self) -> &[::opentelemetry::StringValue] { &self.0 @@ -197,7 +197,7 @@ impl AsRef<[::opentelemetry::StringValue]> for StringValuesAttr { } #[allow(deprecated)] -impl ::std::fmt::Display for StringValuesAttr { +impl ::std::fmt::Display for MyappStringValues { fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { formatter.write_str("[")?; for (index, value) in self.0.iter().enumerate() { @@ -211,32 +211,32 @@ impl ::std::fmt::Display for StringValuesAttr { } #[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { +impl From for ::opentelemetry::KeyValue { #[inline] - fn from(value: StringValuesAttr) -> Self { - ::opentelemetry::KeyValue::new(StringValuesAttr::KEY, ::opentelemetry::Value::Array(::opentelemetry::Array::String(value.0))) + fn from(value: MyappStringValues) -> Self { + ::opentelemetry::KeyValue::new(MyappStringValues::KEY, ::opentelemetry::Value::Array(::opentelemetry::Array::String(value.0))) } } #[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { +impl From for ::opentelemetry::logs::AnyValue { #[inline] - fn from(value: StringValuesAttr) -> Self { + fn from(value: MyappStringValues) -> Self { value.0.into_iter().collect::<::opentelemetry::logs::AnyValue>() } } /// Number of the attempt, starting at 1. #[derive(Debug, Clone, PartialEq, Copy)] -pub struct TaskAttemptAttr(i64); +pub struct MyappTaskAttempt(i64); #[allow(deprecated)] -impl TaskAttemptAttr { +impl MyappTaskAttempt { pub const KEY: &'static str = "myapp.task.attempt"; } #[allow(deprecated)] -impl From for TaskAttemptAttr { +impl From for MyappTaskAttempt { #[inline] fn from(value: i64) -> Self { Self(value) @@ -244,7 +244,7 @@ impl From for TaskAttemptAttr { } #[allow(deprecated)] -impl ::std::fmt::Display for TaskAttemptAttr { +impl ::std::fmt::Display for MyappTaskAttempt { #[inline] fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { ::std::fmt::Display::fmt(&self.0, formatter) @@ -252,24 +252,24 @@ impl ::std::fmt::Display for TaskAttemptAttr { } #[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { +impl From for ::opentelemetry::KeyValue { #[inline] - fn from(value: TaskAttemptAttr) -> Self { - ::opentelemetry::KeyValue::new(TaskAttemptAttr::KEY, value.0) + fn from(value: MyappTaskAttempt) -> Self { + ::opentelemetry::KeyValue::new(MyappTaskAttempt::KEY, value.0) } } #[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { +impl From for ::opentelemetry::logs::AnyValue { #[inline] - fn from(value: TaskAttemptAttr) -> Self { + fn from(value: MyappTaskAttempt) -> Self { value.0.into() } } /// Current state of the task. #[derive(Debug, Clone, PartialEq, Copy)] -pub enum TaskStateAttr { +pub enum MyappTaskState { /// The task finished. Done, /// The task gave up. @@ -277,23 +277,23 @@ pub enum TaskStateAttr { } #[allow(deprecated)] -impl TaskStateAttr { +impl MyappTaskState { pub const KEY: &'static str = "myapp.task.state"; } #[allow(deprecated)] -impl AsRef for TaskStateAttr { +impl AsRef for MyappTaskState { #[inline] fn as_ref(&self) -> &str { match self { - TaskStateAttr::Done => "done", - TaskStateAttr::Failed => "failed", + MyappTaskState::Done => "done", + MyappTaskState::Failed => "failed", } } } #[allow(deprecated)] -impl ::std::fmt::Display for TaskStateAttr { +impl ::std::fmt::Display for MyappTaskState { #[inline] fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { formatter.write_str(self.as_ref()) @@ -301,25 +301,90 @@ impl ::std::fmt::Display for TaskStateAttr { } #[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { +impl From for ::opentelemetry::KeyValue { #[inline] - fn from(value: TaskStateAttr) -> Self { + fn from(value: MyappTaskState) -> Self { let value: &'static str = match value { - TaskStateAttr::Done => "done", - TaskStateAttr::Failed => "failed", + MyappTaskState::Done => "done", + MyappTaskState::Failed => "failed", }; - ::opentelemetry::KeyValue::new(TaskStateAttr::KEY, value) + ::opentelemetry::KeyValue::new(MyappTaskState::KEY, value) } } #[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { +impl From for ::opentelemetry::logs::AnyValue { #[inline] - fn from(value: TaskStateAttr) -> Self { + fn from(value: MyappTaskState) -> Self { let value: &'static str = match value { - TaskStateAttr::Done => "done", - TaskStateAttr::Failed => "failed", + MyappTaskState::Done => "done", + MyappTaskState::Failed => "failed", }; value.into() } } + +/// Name of the worker host. +#[derive(Debug, Clone, PartialEq)] +pub struct WorkerHostName(::opentelemetry::StringValue); + +#[allow(deprecated)] +impl WorkerHostName { + pub const KEY: &'static str = "worker.host.name"; +} + +#[allow(deprecated)] +impl From<::opentelemetry::StringValue> for WorkerHostName { + #[inline] + fn from(value: ::opentelemetry::StringValue) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl From for WorkerHostName { + #[inline] + fn from(value: String) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl From<&'static str> for WorkerHostName { + #[inline] + fn from(value: &'static str) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl AsRef for WorkerHostName { + #[inline] + fn as_ref(&self) -> &str { + self.0.as_str() + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for WorkerHostName { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str(self.as_ref()) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: WorkerHostName) -> Self { + ::opentelemetry::KeyValue::new(WorkerHostName::KEY, value.0) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: WorkerHostName) -> Self { + value.0.into() + } +} diff --git a/templates/code/rust/tests/events/expected/event.rs b/templates/code/rust/tests/events/expected/event.rs new file mode 100644 index 0000000..5156187 --- /dev/null +++ b/templates/code/rust/tests/events/expected/event.rs @@ -0,0 +1,199 @@ +#![allow(deprecated)] +use ::opentelemetry::logs::LogRecord; +use ::opentelemetry::trace::TraceContextExt; + +/// A task reached a final state. +/// +/// Emitted once per task, after its last attempt. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct MyappTaskFinished; + +impl MyappTaskFinished { + pub const NAME: &'static str = "myapp.task.finished"; +} + +#[derive(Clone, Debug)] +pub enum MyappTaskFinishedOption { + Severity(::opentelemetry::logs::Severity), + Timestamp(::std::time::SystemTime), + BoolValues(super::attribute::MyappBoolValues), + DoubleValues(super::attribute::MyappDoubleValues), + IntValues(super::attribute::MyappIntValues), + StringValues(super::attribute::MyappStringValues), + /// Recommended: When the task ran more than once. + TaskAttempt(super::attribute::MyappTaskAttempt), + /// Opt-in: the convention records it only when a user asks for it. + HostName(super::attribute::WorkerHostName), +} +/// A task reached a final state. +/// +/// Emitted once per task, after its last attempt. +pub fn r#emit_myapp_task_finished(context: &::opentelemetry::Context, logger: &super::logger::Logger, r#myapp_task_state: super::attribute::MyappTaskState, options: impl IntoIterator) { + let mut severity = ::opentelemetry::logs::Severity::Info; + let mut timestamp = None; + let mut attributes = ::smallvec::SmallVec::<[MyappTaskFinishedOption; 6]>::new(); + for option in options { + match option { + MyappTaskFinishedOption::Severity(value) => severity = value, + MyappTaskFinishedOption::Timestamp(value) => timestamp = Some(value), + attribute => attributes.push(attribute), + } + } + if !logger.inner().event_enabled(severity, "", Some(MyappTaskFinished::NAME)) { return; } + let _context_guard = context.clone().attach(); + let mut record = logger.inner().create_log_record(); + record.set_event_name(MyappTaskFinished::NAME); + record.set_severity_number(severity); + record.set_observed_timestamp(::std::time::SystemTime::now()); + if let Some(timestamp) = timestamp { record.set_timestamp(timestamp); } + let span = context.span(); + let span_context = span.span_context(); + if span_context.is_valid() { record.set_trace_context(span_context.trace_id(), span_context.span_id(), Some(span_context.trace_flags())); } + record.add_attribute(super::attribute::MyappTaskState::KEY, r#myapp_task_state); + for option in attributes { + match option { + MyappTaskFinishedOption::BoolValues(value) => record.add_attribute(super::attribute::MyappBoolValues::KEY, value), + MyappTaskFinishedOption::DoubleValues(value) => record.add_attribute(super::attribute::MyappDoubleValues::KEY, value), + MyappTaskFinishedOption::IntValues(value) => record.add_attribute(super::attribute::MyappIntValues::KEY, value), + MyappTaskFinishedOption::StringValues(value) => record.add_attribute(super::attribute::MyappStringValues::KEY, value), + MyappTaskFinishedOption::TaskAttempt(value) => record.add_attribute(super::attribute::MyappTaskAttempt::KEY, value), + MyappTaskFinishedOption::HostName(value) => record.add_attribute(super::attribute::WorkerHostName::KEY, value), + MyappTaskFinishedOption::Severity(_) | MyappTaskFinishedOption::Timestamp(_) => continue, + } + } + logger.inner().emit(record); +} +/// A task is about to run again. +/// Opt-in: record only when the user requests it. +#[deprecated(note = "Read the attempt from `myapp.task.finished` instead.")] +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct MyappTaskRetried; + +impl MyappTaskRetried { + pub const NAME: &'static str = "myapp.task.retried"; +} + +#[derive(Clone, Debug)] +pub enum MyappTaskRetriedOption { + Severity(::opentelemetry::logs::Severity), + Timestamp(::std::time::SystemTime), +} +/// A task is about to run again. +/// Opt-in: record only when the user requests it. +#[deprecated(note = "Read the attempt from `myapp.task.finished` instead.")] +pub fn r#emit_myapp_task_retried(context: &::opentelemetry::Context, logger: &super::logger::Logger, r#myapp_task_attempt: super::attribute::MyappTaskAttempt, options: impl IntoIterator) { + let mut severity = ::opentelemetry::logs::Severity::Info; + let mut timestamp = None; + for option in options { + match option { + MyappTaskRetriedOption::Severity(value) => severity = value, + MyappTaskRetriedOption::Timestamp(value) => timestamp = Some(value), + } + } + if !logger.inner().event_enabled(severity, "", Some(MyappTaskRetried::NAME)) { return; } + let _context_guard = context.clone().attach(); + let mut record = logger.inner().create_log_record(); + record.set_event_name(MyappTaskRetried::NAME); + record.set_severity_number(severity); + record.set_observed_timestamp(::std::time::SystemTime::now()); + if let Some(timestamp) = timestamp { record.set_timestamp(timestamp); } + let span = context.span(); + let span_context = span.span_context(); + if span_context.is_valid() { record.set_trace_context(span_context.trace_id(), span_context.span_id(), Some(span_context.trace_flags())); } + record.add_attribute(super::attribute::MyappTaskAttempt::KEY, r#myapp_task_attempt); + logger.inner().emit(record); +} +/// A worker host started taking tasks. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct WorkerHostStarted; + +impl WorkerHostStarted { + pub const NAME: &'static str = "worker.host.started"; +} + +#[derive(Clone, Debug)] +pub enum WorkerHostStartedOption { + Severity(::opentelemetry::logs::Severity), + Timestamp(::std::time::SystemTime), +} +/// A worker host started taking tasks. +pub fn r#emit_worker_host_started(context: &::opentelemetry::Context, logger: &super::logger::Logger, options: impl IntoIterator) { + let mut severity = ::opentelemetry::logs::Severity::Info; + let mut timestamp = None; + for option in options { + match option { + WorkerHostStartedOption::Severity(value) => severity = value, + WorkerHostStartedOption::Timestamp(value) => timestamp = Some(value), + } + } + if !logger.inner().event_enabled(severity, "", Some(WorkerHostStarted::NAME)) { return; } + let _context_guard = context.clone().attach(); + let mut record = logger.inner().create_log_record(); + record.set_event_name(WorkerHostStarted::NAME); + record.set_severity_number(severity); + record.set_observed_timestamp(::std::time::SystemTime::now()); + if let Some(timestamp) = timestamp { record.set_timestamp(timestamp); } + let span = context.span(); + let span_context = span.span_context(); + if span_context.is_valid() { record.set_trace_context(span_context.trace_id(), span_context.span_id(), Some(span_context.trace_flags())); } + logger.inner().emit(record); +} +/// A task reached a final state on a worker. +/// +/// Emitted once per task, after its last attempt. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct WorkerTaskFinished; + +impl WorkerTaskFinished { + pub const NAME: &'static str = "worker.task.finished"; +} + +#[derive(Clone, Debug)] +pub enum WorkerTaskFinishedOption { + Severity(::opentelemetry::logs::Severity), + Timestamp(::std::time::SystemTime), + BoolValues(super::attribute::MyappBoolValues), + DoubleValues(super::attribute::MyappDoubleValues), + IntValues(super::attribute::MyappIntValues), + StringValues(super::attribute::MyappStringValues), + /// Recommended: When the task ran more than once. + TaskAttempt(super::attribute::MyappTaskAttempt), +} +/// A task reached a final state on a worker. +/// +/// Emitted once per task, after its last attempt. +pub fn r#emit_worker_task_finished(context: &::opentelemetry::Context, logger: &super::logger::Logger, r#myapp_task_state: super::attribute::MyappTaskState, r#worker_host_name: super::attribute::WorkerHostName, options: impl IntoIterator) { + let mut severity = ::opentelemetry::logs::Severity::Info; + let mut timestamp = None; + let mut attributes = ::smallvec::SmallVec::<[WorkerTaskFinishedOption; 5]>::new(); + for option in options { + match option { + WorkerTaskFinishedOption::Severity(value) => severity = value, + WorkerTaskFinishedOption::Timestamp(value) => timestamp = Some(value), + attribute => attributes.push(attribute), + } + } + if !logger.inner().event_enabled(severity, "", Some(WorkerTaskFinished::NAME)) { return; } + let _context_guard = context.clone().attach(); + let mut record = logger.inner().create_log_record(); + record.set_event_name(WorkerTaskFinished::NAME); + record.set_severity_number(severity); + record.set_observed_timestamp(::std::time::SystemTime::now()); + if let Some(timestamp) = timestamp { record.set_timestamp(timestamp); } + let span = context.span(); + let span_context = span.span_context(); + if span_context.is_valid() { record.set_trace_context(span_context.trace_id(), span_context.span_id(), Some(span_context.trace_flags())); } + record.add_attribute(super::attribute::MyappTaskState::KEY, r#myapp_task_state); + record.add_attribute(super::attribute::WorkerHostName::KEY, r#worker_host_name); + for option in attributes { + match option { + WorkerTaskFinishedOption::BoolValues(value) => record.add_attribute(super::attribute::MyappBoolValues::KEY, value), + WorkerTaskFinishedOption::DoubleValues(value) => record.add_attribute(super::attribute::MyappDoubleValues::KEY, value), + WorkerTaskFinishedOption::IntValues(value) => record.add_attribute(super::attribute::MyappIntValues::KEY, value), + WorkerTaskFinishedOption::StringValues(value) => record.add_attribute(super::attribute::MyappStringValues::KEY, value), + WorkerTaskFinishedOption::TaskAttempt(value) => record.add_attribute(super::attribute::MyappTaskAttempt::KEY, value), + WorkerTaskFinishedOption::Severity(_) | WorkerTaskFinishedOption::Timestamp(_) => continue, + } + } + logger.inner().emit(record); +} diff --git a/templates/code/rust/tests/events/expected/mod.rs b/templates/code/rust/tests/events/expected/mod.rs index 2f1689e..816dac3 100644 --- a/templates/code/rust/tests/events/expected/mod.rs +++ b/templates/code/rust/tests/events/expected/mod.rs @@ -1,10 +1,8 @@ // Generated by OpenTelemetry Weaver. pub const SCHEMA_URL: &str = "https://example.com/schemas/events/1.0.0"; -pub mod myappattr; -pub mod workerattr; +pub mod attribute; pub mod scope; pub mod options; pub mod logger; -pub mod myappevent; -pub mod workerevent; +pub mod event; diff --git a/templates/code/rust/tests/events/expected/myappevent.rs b/templates/code/rust/tests/events/expected/myappevent.rs deleted file mode 100644 index 9138d5c..0000000 --- a/templates/code/rust/tests/events/expected/myappevent.rs +++ /dev/null @@ -1,85 +0,0 @@ -#![allow(deprecated)] -use ::opentelemetry::logs::LogRecord; -use ::opentelemetry::trace::TraceContextExt; - -#[derive(Clone, Debug)] -pub enum TaskFinishedOption { - Severity(::opentelemetry::logs::Severity), - Timestamp(::std::time::SystemTime), - BoolValues(super::myappattr::BoolValuesAttr), - DoubleValues(super::myappattr::DoubleValuesAttr), - IntValues(super::myappattr::IntValuesAttr), - StringValues(super::myappattr::StringValuesAttr), - /// Recommended: When the task ran more than once. - TaskAttempt(super::myappattr::TaskAttemptAttr), - /// Opt-in: the convention records it only when a user asks for it. - HostName(super::workerattr::HostNameAttr), -} -/// A task reached a final state. -/// -/// Emitted once per task, after its last attempt. -pub fn r#emit_task_finished(context: &::opentelemetry::Context, logger: &super::logger::Logger, r#myapp_task_state: super::myappattr::TaskStateAttr, options: impl IntoIterator) { - let mut severity = ::opentelemetry::logs::Severity::Info; - let mut timestamp = None; - let mut attributes = ::smallvec::SmallVec::<[TaskFinishedOption; 6]>::new(); - for option in options { - match option { - TaskFinishedOption::Severity(value) => severity = value, - TaskFinishedOption::Timestamp(value) => timestamp = Some(value), - attribute => attributes.push(attribute), - } - } - if !logger.inner().event_enabled(severity, "", Some("myapp.task.finished")) { return; } - let _context_guard = context.clone().attach(); - let mut record = logger.inner().create_log_record(); - record.set_event_name("myapp.task.finished"); - record.set_severity_number(severity); - record.set_observed_timestamp(::std::time::SystemTime::now()); - if let Some(timestamp) = timestamp { record.set_timestamp(timestamp); } - let span = context.span(); - let span_context = span.span_context(); - if span_context.is_valid() { record.set_trace_context(span_context.trace_id(), span_context.span_id(), Some(span_context.trace_flags())); } - record.add_attribute(super::myappattr::TaskStateAttr::KEY, r#myapp_task_state); - for option in attributes { - match option { - TaskFinishedOption::BoolValues(value) => record.add_attribute(super::myappattr::BoolValuesAttr::KEY, value), - TaskFinishedOption::DoubleValues(value) => record.add_attribute(super::myappattr::DoubleValuesAttr::KEY, value), - TaskFinishedOption::IntValues(value) => record.add_attribute(super::myappattr::IntValuesAttr::KEY, value), - TaskFinishedOption::StringValues(value) => record.add_attribute(super::myappattr::StringValuesAttr::KEY, value), - TaskFinishedOption::TaskAttempt(value) => record.add_attribute(super::myappattr::TaskAttemptAttr::KEY, value), - TaskFinishedOption::HostName(value) => record.add_attribute(super::workerattr::HostNameAttr::KEY, value), - TaskFinishedOption::Severity(_) | TaskFinishedOption::Timestamp(_) => continue, - } - } - logger.inner().emit(record); -} -#[derive(Clone, Debug)] -pub enum TaskRetriedOption { - Severity(::opentelemetry::logs::Severity), - Timestamp(::std::time::SystemTime), -} -/// A task is about to run again. -/// Opt-in: record only when the user requests it. -#[deprecated(note = "Read the attempt from `myapp.task.finished` instead.")] -pub fn r#emit_task_retried(context: &::opentelemetry::Context, logger: &super::logger::Logger, r#myapp_task_attempt: super::myappattr::TaskAttemptAttr, options: impl IntoIterator) { - let mut severity = ::opentelemetry::logs::Severity::Info; - let mut timestamp = None; - for option in options { - match option { - TaskRetriedOption::Severity(value) => severity = value, - TaskRetriedOption::Timestamp(value) => timestamp = Some(value), - } - } - if !logger.inner().event_enabled(severity, "", Some("myapp.task.retried")) { return; } - let _context_guard = context.clone().attach(); - let mut record = logger.inner().create_log_record(); - record.set_event_name("myapp.task.retried"); - record.set_severity_number(severity); - record.set_observed_timestamp(::std::time::SystemTime::now()); - if let Some(timestamp) = timestamp { record.set_timestamp(timestamp); } - let span = context.span(); - let span_context = span.span_context(); - if span_context.is_valid() { record.set_trace_context(span_context.trace_id(), span_context.span_id(), Some(span_context.trace_flags())); } - record.add_attribute(super::myappattr::TaskAttemptAttr::KEY, r#myapp_task_attempt); - logger.inner().emit(record); -} diff --git a/templates/code/rust/tests/events/expected/workerattr.rs b/templates/code/rust/tests/events/expected/workerattr.rs deleted file mode 100644 index 50da699..0000000 --- a/templates/code/rust/tests/events/expected/workerattr.rs +++ /dev/null @@ -1,65 +0,0 @@ -// Generated by OpenTelemetry Weaver. -/// Name of the worker host. -#[derive(Debug, Clone, PartialEq)] -pub struct HostNameAttr(::opentelemetry::StringValue); - -#[allow(deprecated)] -impl HostNameAttr { - pub const KEY: &'static str = "worker.host.name"; -} - -#[allow(deprecated)] -impl From<::opentelemetry::StringValue> for HostNameAttr { - #[inline] - fn from(value: ::opentelemetry::StringValue) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl From for HostNameAttr { - #[inline] - fn from(value: String) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl From<&'static str> for HostNameAttr { - #[inline] - fn from(value: &'static str) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl AsRef for HostNameAttr { - #[inline] - fn as_ref(&self) -> &str { - self.0.as_str() - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for HostNameAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str(self.as_ref()) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: HostNameAttr) -> Self { - ::opentelemetry::KeyValue::new(HostNameAttr::KEY, value.0) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: HostNameAttr) -> Self { - value.0.into() - } -} diff --git a/templates/code/rust/tests/events/expected/workerevent.rs b/templates/code/rust/tests/events/expected/workerevent.rs deleted file mode 100644 index 69a4c0f..0000000 --- a/templates/code/rust/tests/events/expected/workerevent.rs +++ /dev/null @@ -1,80 +0,0 @@ -#![allow(deprecated)] -use ::opentelemetry::logs::LogRecord; -use ::opentelemetry::trace::TraceContextExt; - -#[derive(Clone, Debug)] -pub enum HostStartedOption { - Severity(::opentelemetry::logs::Severity), - Timestamp(::std::time::SystemTime), -} -/// A worker host started taking tasks. -pub fn r#emit_host_started(context: &::opentelemetry::Context, logger: &super::logger::Logger, options: impl IntoIterator) { - let mut severity = ::opentelemetry::logs::Severity::Info; - let mut timestamp = None; - for option in options { - match option { - HostStartedOption::Severity(value) => severity = value, - HostStartedOption::Timestamp(value) => timestamp = Some(value), - } - } - if !logger.inner().event_enabled(severity, "", Some("worker.host.started")) { return; } - let _context_guard = context.clone().attach(); - let mut record = logger.inner().create_log_record(); - record.set_event_name("worker.host.started"); - record.set_severity_number(severity); - record.set_observed_timestamp(::std::time::SystemTime::now()); - if let Some(timestamp) = timestamp { record.set_timestamp(timestamp); } - let span = context.span(); - let span_context = span.span_context(); - if span_context.is_valid() { record.set_trace_context(span_context.trace_id(), span_context.span_id(), Some(span_context.trace_flags())); } - logger.inner().emit(record); -} -#[derive(Clone, Debug)] -pub enum TaskFinishedOption { - Severity(::opentelemetry::logs::Severity), - Timestamp(::std::time::SystemTime), - BoolValues(super::myappattr::BoolValuesAttr), - DoubleValues(super::myappattr::DoubleValuesAttr), - IntValues(super::myappattr::IntValuesAttr), - StringValues(super::myappattr::StringValuesAttr), - /// Recommended: When the task ran more than once. - TaskAttempt(super::myappattr::TaskAttemptAttr), -} -/// A task reached a final state on a worker. -/// -/// Emitted once per task, after its last attempt. -pub fn r#emit_task_finished(context: &::opentelemetry::Context, logger: &super::logger::Logger, r#myapp_task_state: super::myappattr::TaskStateAttr, r#worker_host_name: super::workerattr::HostNameAttr, options: impl IntoIterator) { - let mut severity = ::opentelemetry::logs::Severity::Info; - let mut timestamp = None; - let mut attributes = ::smallvec::SmallVec::<[TaskFinishedOption; 5]>::new(); - for option in options { - match option { - TaskFinishedOption::Severity(value) => severity = value, - TaskFinishedOption::Timestamp(value) => timestamp = Some(value), - attribute => attributes.push(attribute), - } - } - if !logger.inner().event_enabled(severity, "", Some("worker.task.finished")) { return; } - let _context_guard = context.clone().attach(); - let mut record = logger.inner().create_log_record(); - record.set_event_name("worker.task.finished"); - record.set_severity_number(severity); - record.set_observed_timestamp(::std::time::SystemTime::now()); - if let Some(timestamp) = timestamp { record.set_timestamp(timestamp); } - let span = context.span(); - let span_context = span.span_context(); - if span_context.is_valid() { record.set_trace_context(span_context.trace_id(), span_context.span_id(), Some(span_context.trace_flags())); } - record.add_attribute(super::myappattr::TaskStateAttr::KEY, r#myapp_task_state); - record.add_attribute(super::workerattr::HostNameAttr::KEY, r#worker_host_name); - for option in attributes { - match option { - TaskFinishedOption::BoolValues(value) => record.add_attribute(super::myappattr::BoolValuesAttr::KEY, value), - TaskFinishedOption::DoubleValues(value) => record.add_attribute(super::myappattr::DoubleValuesAttr::KEY, value), - TaskFinishedOption::IntValues(value) => record.add_attribute(super::myappattr::IntValuesAttr::KEY, value), - TaskFinishedOption::StringValues(value) => record.add_attribute(super::myappattr::StringValuesAttr::KEY, value), - TaskFinishedOption::TaskAttempt(value) => record.add_attribute(super::myappattr::TaskAttemptAttr::KEY, value), - TaskFinishedOption::Severity(_) | TaskFinishedOption::Timestamp(_) => continue, - } - } - logger.inner().emit(record); -} diff --git a/templates/code/rust/tests/events/test.rs b/templates/code/rust/tests/events/test.rs index 9fc78a0..ff92560 100644 --- a/templates/code/rust/tests/events/test.rs +++ b/templates/code/rust/tests/events/test.rs @@ -1,6 +1,10 @@ use generated_semconv::options::InstrumentationOptions; use generated_semconv::{ - logger, myappattr, myappevent, scope, workerattr, workerevent, SCHEMA_URL, + logger, + attribute, + event, + scope, + SCHEMA_URL, }; use opentelemetry::logs::{AnyValue, Severity}; use opentelemetry::trace::{SpanContext, SpanId, TraceContextExt, TraceFlags, TraceId, TraceState}; @@ -29,30 +33,30 @@ fn typed_events_have_schema_timestamps_severity_attributes_and_trace_context() { ); let context = opentelemetry::Context::new().with_remote_span_context(span.clone()); let timestamp = std::time::UNIX_EPOCH + std::time::Duration::from_secs(100); - myappevent::emit_task_finished( + event::emit_myapp_task_finished( &context, &logger, - myappattr::TaskStateAttr::Done, + attribute::MyappTaskState::Done, [ - myappevent::TaskFinishedOption::TaskAttempt(myappattr::TaskAttemptAttr::from(2)), - myappevent::TaskFinishedOption::HostName(workerattr::HostNameAttr::from("worker-1")), - myappevent::TaskFinishedOption::Severity(Severity::Warn), - myappevent::TaskFinishedOption::Timestamp(timestamp), - myappevent::TaskFinishedOption::BoolValues(myappattr::BoolValuesAttr::from(vec![true])), - myappevent::TaskFinishedOption::IntValues(myappattr::IntValuesAttr::from(vec![1])), - myappevent::TaskFinishedOption::DoubleValues(myappattr::DoubleValuesAttr::from(vec![ + event::MyappTaskFinishedOption::TaskAttempt(attribute::MyappTaskAttempt::from(2)), + event::MyappTaskFinishedOption::HostName(attribute::WorkerHostName::from("worker-1")), + event::MyappTaskFinishedOption::Severity(Severity::Warn), + event::MyappTaskFinishedOption::Timestamp(timestamp), + event::MyappTaskFinishedOption::BoolValues(attribute::MyappBoolValues::from(vec![true])), + event::MyappTaskFinishedOption::IntValues(attribute::MyappIntValues::from(vec![1])), + event::MyappTaskFinishedOption::DoubleValues(attribute::MyappDoubleValues::from(vec![ 1.5, ])), - myappevent::TaskFinishedOption::StringValues(myappattr::StringValuesAttr::from(vec![ + event::MyappTaskFinishedOption::StringValues(attribute::MyappStringValues::from(vec![ opentelemetry::StringValue::from("fetch"), ])), ], ); - workerevent::emit_task_finished( + event::emit_worker_task_finished( &context, &logger, - myappattr::TaskStateAttr::Done, - workerattr::HostNameAttr::from("worker-1"), + attribute::MyappTaskState::Done, + attribute::WorkerHostName::from("worker-1"), [], ); provider.force_flush().unwrap(); @@ -95,10 +99,10 @@ fn typed_events_have_schema_timestamps_severity_attributes_and_trace_context() { assert_eq!(logs[1].record.event_name(), Some("worker.task.finished")); assert_eq!(logs[1].record.severity_number(), Some(Severity::Info)); assert!(logs[1].record.timestamp().is_none()); - myappevent::emit_task_finished( + event::emit_myapp_task_finished( &context, &logger::Logger::default(), - myappattr::TaskStateAttr::Done, + attribute::MyappTaskState::Done, [], ); } @@ -128,10 +132,17 @@ impl opentelemetry::logs::Logger for DisabledLogger { } #[test] fn disabled_events_are_checked_before_record_creation() { - myappevent::emit_task_finished( + event::emit_myapp_task_finished( &opentelemetry::Context::new(), &logger::Logger::new(&DisabledProvider, InstrumentationOptions::default()), - myappattr::TaskStateAttr::Done, - [myappevent::TaskFinishedOption::Severity(Severity::Error)], + attribute::MyappTaskState::Done, + [event::MyappTaskFinishedOption::Severity(Severity::Error)], ); } + +const _: &str = event::MyappTaskFinished::NAME; + +#[test] +fn events_expose_their_name_as_a_constant() { + assert_eq!(event::MyappTaskFinished::NAME, "myapp.task.finished"); +} diff --git a/templates/code/rust/tests/filtering/expected/attribute.rs b/templates/code/rust/tests/filtering/expected/attribute.rs new file mode 100644 index 0000000..bc5f223 --- /dev/null +++ b/templates/code/rust/tests/filtering/expected/attribute.rs @@ -0,0 +1,614 @@ +// Generated by OpenTelemetry Weaver. +/// How the user was authenticated. +#[derive(Debug, Clone, PartialEq, Copy)] +pub enum AuthMethod { + /// A password was checked. + Password, + /// A bearer token was checked. + Token, +} + +#[allow(deprecated)] +impl AuthMethod { + pub const KEY: &'static str = "auth.method"; +} + +#[allow(deprecated)] +impl AsRef for AuthMethod { + #[inline] + fn as_ref(&self) -> &str { + match self { + AuthMethod::Password => "password", + AuthMethod::Token => "token", + } + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for AuthMethod { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str(self.as_ref()) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: AuthMethod) -> Self { + let value: &'static str = match value { + AuthMethod::Password => "password", + AuthMethod::Token => "token", + }; + ::opentelemetry::KeyValue::new(AuthMethod::KEY, value) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: AuthMethod) -> Self { + let value: &'static str = match value { + AuthMethod::Password => "password", + AuthMethod::Token => "token", + }; + value.into() + } +} + +/// Identifier of the authenticated user. +#[derive(Debug, Clone, PartialEq)] +pub struct AuthUserId(::opentelemetry::StringValue); + +#[allow(deprecated)] +impl AuthUserId { + pub const KEY: &'static str = "auth.user.id"; +} + +#[allow(deprecated)] +impl From<::opentelemetry::StringValue> for AuthUserId { + #[inline] + fn from(value: ::opentelemetry::StringValue) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl From for AuthUserId { + #[inline] + fn from(value: String) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl From<&'static str> for AuthUserId { + #[inline] + fn from(value: &'static str) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl AsRef for AuthUserId { + #[inline] + fn as_ref(&self) -> &str { + self.0.as_str() + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for AuthUserId { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str(self.as_ref()) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: AuthUserId) -> Self { + ::opentelemetry::KeyValue::new(AuthUserId::KEY, value.0) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: AuthUserId) -> Self { + value.0.into() + } +} + +/// Who assigned the task. +/// +/// The scheduler sets it on every task it passes along to `myapp.task.state`. Workers never set it themselves. +#[derive(Debug, Clone, PartialEq)] +pub struct TaskAssignedBy(::opentelemetry::StringValue); + +#[allow(deprecated)] +impl TaskAssignedBy { + pub const KEY: &'static str = "myapp.task.assigned_by"; +} + +#[allow(deprecated)] +impl From<::opentelemetry::StringValue> for TaskAssignedBy { + #[inline] + fn from(value: ::opentelemetry::StringValue) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl From for TaskAssignedBy { + #[inline] + fn from(value: String) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl From<&'static str> for TaskAssignedBy { + #[inline] + fn from(value: &'static str) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl AsRef for TaskAssignedBy { + #[inline] + fn as_ref(&self) -> &str { + self.0.as_str() + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for TaskAssignedBy { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str(self.as_ref()) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: TaskAssignedBy) -> Self { + ::opentelemetry::KeyValue::new(TaskAssignedBy::KEY, value.0) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: TaskAssignedBy) -> Self { + value.0.into() + } +} + +/// Whether the task was cancelled. +#[derive(Debug, Clone, PartialEq, Copy)] +pub struct TaskCancelled(bool); + +#[allow(deprecated)] +impl TaskCancelled { + pub const KEY: &'static str = "myapp.task.cancelled"; +} + +#[allow(deprecated)] +impl From for TaskCancelled { + #[inline] + fn from(value: bool) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for TaskCancelled { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + ::std::fmt::Display::fmt(&self.0, formatter) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: TaskCancelled) -> Self { + ::opentelemetry::KeyValue::new(TaskCancelled::KEY, value.0) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: TaskCancelled) -> Self { + value.0.into() + } +} + +/// Unique identifier of the task. +/// +/// The identifier is assigned by the scheduler and stays stable across retries. +#[derive(Debug, Clone, PartialEq)] +pub struct TaskId(::opentelemetry::StringValue); + +#[allow(deprecated)] +impl TaskId { + pub const KEY: &'static str = "myapp.task.id"; +} + +#[allow(deprecated)] +impl From<::opentelemetry::StringValue> for TaskId { + #[inline] + fn from(value: ::opentelemetry::StringValue) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl From for TaskId { + #[inline] + fn from(value: String) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl From<&'static str> for TaskId { + #[inline] + fn from(value: &'static str) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl AsRef for TaskId { + #[inline] + fn as_ref(&self) -> &str { + self.0.as_str() + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for TaskId { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str(self.as_ref()) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: TaskId) -> Self { + ::opentelemetry::KeyValue::new(TaskId::KEY, value.0) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: TaskId) -> Self { + value.0.into() + } +} + +/// Whether the scheduler may preempt the task. +#[derive(Debug, Clone, PartialEq, Copy)] +pub enum TaskPreemptible { + /// The scheduler may preempt the task. + Allowed, + /// The task runs to completion. + Forbidden, +} + +#[allow(deprecated)] +impl TaskPreemptible { + pub const KEY: &'static str = "myapp.task.preemptible"; +} + +#[allow(deprecated)] +impl ::std::fmt::Display for TaskPreemptible { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + let value: bool = match self { + TaskPreemptible::Allowed => true, + TaskPreemptible::Forbidden => false, + }; + ::std::fmt::Display::fmt(&value, formatter) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: TaskPreemptible) -> Self { + let value: bool = match value { + TaskPreemptible::Allowed => true, + TaskPreemptible::Forbidden => false, + }; + ::opentelemetry::KeyValue::new(TaskPreemptible::KEY, value) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: TaskPreemptible) -> Self { + let value: bool = match value { + TaskPreemptible::Allowed => true, + TaskPreemptible::Forbidden => false, + }; + value.into() + } +} + +/// Number of times the task was retried. +#[derive(Debug, Clone, PartialEq, Copy)] +pub struct TaskRetries(i64); + +#[allow(deprecated)] +impl TaskRetries { + pub const KEY: &'static str = "myapp.task.retries"; +} + +#[allow(deprecated)] +impl From for TaskRetries { + #[inline] + fn from(value: i64) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for TaskRetries { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + ::std::fmt::Display::fmt(&self.0, formatter) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: TaskRetries) -> Self { + ::opentelemetry::KeyValue::new(TaskRetries::KEY, value.0) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: TaskRetries) -> Self { + value.0.into() + } +} + +/// Fraction of tasks whose telemetry is sampled. +#[derive(Debug, Clone, PartialEq, Copy)] +pub enum TaskSampleRate { + /// One task in ten is sampled. + Tenth, + /// Every task is sampled. + All, +} + +#[allow(deprecated)] +impl TaskSampleRate { + pub const KEY: &'static str = "myapp.task.sample_rate"; +} + +#[allow(deprecated)] +impl ::std::fmt::Display for TaskSampleRate { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + let value: f64 = match self { + TaskSampleRate::Tenth => 0.1_f64, + TaskSampleRate::All => 1_f64, + }; + ::std::fmt::Display::fmt(&value, formatter) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: TaskSampleRate) -> Self { + let value: f64 = match value { + TaskSampleRate::Tenth => 0.1_f64, + TaskSampleRate::All => 1_f64, + }; + ::opentelemetry::KeyValue::new(TaskSampleRate::KEY, value) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: TaskSampleRate) -> Self { + let value: f64 = match value { + TaskSampleRate::Tenth => 0.1_f64, + TaskSampleRate::All => 1_f64, + }; + value.into() + } +} + +/// Shards the task touched. +#[derive(Debug, Clone, PartialEq)] +pub struct TaskShardIds(Vec); + +#[allow(deprecated)] +impl TaskShardIds { + pub const KEY: &'static str = "myapp.task.shard_ids"; +} + +#[allow(deprecated)] +impl From> for TaskShardIds { + #[inline] + fn from(value: Vec) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl AsRef<[i64]> for TaskShardIds { + #[inline] + fn as_ref(&self) -> &[i64] { + &self.0 + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for TaskShardIds { + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str("[")?; + for (index, value) in self.0.iter().enumerate() { + if index != 0 { + formatter.write_str(",")?; + } + ::std::fmt::Display::fmt(value, formatter)?; + } + formatter.write_str("]") + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: TaskShardIds) -> Self { + ::opentelemetry::KeyValue::new(TaskShardIds::KEY, ::opentelemetry::Value::Array(::opentelemetry::Array::I64(value.0))) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: TaskShardIds) -> Self { + value.0.into_iter().collect::<::opentelemetry::logs::AnyValue>() + } +} + +/// Current state of the task. +#[derive(Debug, Clone, PartialEq, Copy)] +pub enum TaskState { + /// The task is waiting to run. + Queued, + /// The task is running. + /// + /// A task stays running until it finishes or is cancelled. + Running, +} + +#[allow(deprecated)] +impl TaskState { + pub const KEY: &'static str = "myapp.task.state"; +} + +#[allow(deprecated)] +impl AsRef for TaskState { + #[inline] + fn as_ref(&self) -> &str { + match self { + TaskState::Queued => "queued", + TaskState::Running => "running", + } + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for TaskState { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str(self.as_ref()) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: TaskState) -> Self { + let value: &'static str = match value { + TaskState::Queued => "queued", + TaskState::Running => "running", + }; + ::opentelemetry::KeyValue::new(TaskState::KEY, value) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: TaskState) -> Self { + let value: &'static str = match value { + TaskState::Queued => "queued", + TaskState::Running => "running", + }; + value.into() + } +} + +/// Tags attached to the task. +#[derive(Debug, Clone, PartialEq)] +pub struct TaskTags(Vec<::opentelemetry::StringValue>); + +#[allow(deprecated)] +impl TaskTags { + pub const KEY: &'static str = "myapp.task.tags"; +} + +#[allow(deprecated)] +impl From> for TaskTags { + #[inline] + fn from(value: Vec<::opentelemetry::StringValue>) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl From> for TaskTags { + fn from(value: Vec) -> Self { + Self(value.into_iter().map(Into::into).collect()) + } +} + +#[allow(deprecated)] +impl AsRef<[::opentelemetry::StringValue]> for TaskTags { + #[inline] + fn as_ref(&self) -> &[::opentelemetry::StringValue] { + &self.0 + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for TaskTags { + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str("[")?; + for (index, value) in self.0.iter().enumerate() { + if index != 0 { + formatter.write_str(",")?; + } + write!(formatter, "\"{value}\"")?; + } + formatter.write_str("]") + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: TaskTags) -> Self { + ::opentelemetry::KeyValue::new(TaskTags::KEY, ::opentelemetry::Value::Array(::opentelemetry::Array::String(value.0))) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: TaskTags) -> Self { + value.0.into_iter().collect::<::opentelemetry::logs::AnyValue>() + } +} diff --git a/templates/code/rust/tests/filtering/expected/authattr.rs b/templates/code/rust/tests/filtering/expected/authattr.rs deleted file mode 100644 index c2c1df1..0000000 --- a/templates/code/rust/tests/filtering/expected/authattr.rs +++ /dev/null @@ -1,122 +0,0 @@ -// Generated by OpenTelemetry Weaver. -/// How the user was authenticated. -#[derive(Debug, Clone, PartialEq, Copy)] -pub enum MethodAttr { - /// A password was checked. - Password, - /// A bearer token was checked. - Token, -} - -#[allow(deprecated)] -impl MethodAttr { - pub const KEY: &'static str = "auth.method"; -} - -#[allow(deprecated)] -impl AsRef for MethodAttr { - #[inline] - fn as_ref(&self) -> &str { - match self { - MethodAttr::Password => "password", - MethodAttr::Token => "token", - } - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for MethodAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str(self.as_ref()) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: MethodAttr) -> Self { - let value: &'static str = match value { - MethodAttr::Password => "password", - MethodAttr::Token => "token", - }; - ::opentelemetry::KeyValue::new(MethodAttr::KEY, value) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: MethodAttr) -> Self { - let value: &'static str = match value { - MethodAttr::Password => "password", - MethodAttr::Token => "token", - }; - value.into() - } -} - -/// Identifier of the authenticated user. -#[derive(Debug, Clone, PartialEq)] -pub struct UserIdAttr(::opentelemetry::StringValue); - -#[allow(deprecated)] -impl UserIdAttr { - pub const KEY: &'static str = "auth.user.id"; -} - -#[allow(deprecated)] -impl From<::opentelemetry::StringValue> for UserIdAttr { - #[inline] - fn from(value: ::opentelemetry::StringValue) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl From for UserIdAttr { - #[inline] - fn from(value: String) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl From<&'static str> for UserIdAttr { - #[inline] - fn from(value: &'static str) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl AsRef for UserIdAttr { - #[inline] - fn as_ref(&self) -> &str { - self.0.as_str() - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for UserIdAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str(self.as_ref()) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: UserIdAttr) -> Self { - ::opentelemetry::KeyValue::new(UserIdAttr::KEY, value.0) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: UserIdAttr) -> Self { - value.0.into() - } -} diff --git a/templates/code/rust/tests/filtering/expected/mod.rs b/templates/code/rust/tests/filtering/expected/mod.rs index db0137c..9b263eb 100644 --- a/templates/code/rust/tests/filtering/expected/mod.rs +++ b/templates/code/rust/tests/filtering/expected/mod.rs @@ -1,4 +1,3 @@ // Generated by OpenTelemetry Weaver. pub const SCHEMA_URL: &str = "https://example.com/schemas/filtering/1.0.0"; -pub mod authattr; -pub mod taskattr; +pub mod attribute; diff --git a/templates/code/rust/tests/filtering/expected/taskattr.rs b/templates/code/rust/tests/filtering/expected/taskattr.rs deleted file mode 100644 index 2d388b5..0000000 --- a/templates/code/rust/tests/filtering/expected/taskattr.rs +++ /dev/null @@ -1,492 +0,0 @@ -// Generated by OpenTelemetry Weaver. -/// Who assigned the task. -/// -/// The scheduler sets it on every task it passes along to `myapp.task.state`. Workers never set it themselves. -#[derive(Debug, Clone, PartialEq)] -pub struct AssignedByAttr(::opentelemetry::StringValue); - -#[allow(deprecated)] -impl AssignedByAttr { - pub const KEY: &'static str = "myapp.task.assigned_by"; -} - -#[allow(deprecated)] -impl From<::opentelemetry::StringValue> for AssignedByAttr { - #[inline] - fn from(value: ::opentelemetry::StringValue) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl From for AssignedByAttr { - #[inline] - fn from(value: String) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl From<&'static str> for AssignedByAttr { - #[inline] - fn from(value: &'static str) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl AsRef for AssignedByAttr { - #[inline] - fn as_ref(&self) -> &str { - self.0.as_str() - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for AssignedByAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str(self.as_ref()) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: AssignedByAttr) -> Self { - ::opentelemetry::KeyValue::new(AssignedByAttr::KEY, value.0) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: AssignedByAttr) -> Self { - value.0.into() - } -} - -/// Whether the task was cancelled. -#[derive(Debug, Clone, PartialEq, Copy)] -pub struct CancelledAttr(bool); - -#[allow(deprecated)] -impl CancelledAttr { - pub const KEY: &'static str = "myapp.task.cancelled"; -} - -#[allow(deprecated)] -impl From for CancelledAttr { - #[inline] - fn from(value: bool) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for CancelledAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - ::std::fmt::Display::fmt(&self.0, formatter) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: CancelledAttr) -> Self { - ::opentelemetry::KeyValue::new(CancelledAttr::KEY, value.0) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: CancelledAttr) -> Self { - value.0.into() - } -} - -/// Unique identifier of the task. -/// -/// The identifier is assigned by the scheduler and stays stable across retries. -#[derive(Debug, Clone, PartialEq)] -pub struct IdAttr(::opentelemetry::StringValue); - -#[allow(deprecated)] -impl IdAttr { - pub const KEY: &'static str = "myapp.task.id"; -} - -#[allow(deprecated)] -impl From<::opentelemetry::StringValue> for IdAttr { - #[inline] - fn from(value: ::opentelemetry::StringValue) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl From for IdAttr { - #[inline] - fn from(value: String) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl From<&'static str> for IdAttr { - #[inline] - fn from(value: &'static str) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl AsRef for IdAttr { - #[inline] - fn as_ref(&self) -> &str { - self.0.as_str() - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for IdAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str(self.as_ref()) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: IdAttr) -> Self { - ::opentelemetry::KeyValue::new(IdAttr::KEY, value.0) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: IdAttr) -> Self { - value.0.into() - } -} - -/// Whether the scheduler may preempt the task. -#[derive(Debug, Clone, PartialEq, Copy)] -pub enum PreemptibleAttr { - /// The scheduler may preempt the task. - Allowed, - /// The task runs to completion. - Forbidden, -} - -#[allow(deprecated)] -impl PreemptibleAttr { - pub const KEY: &'static str = "myapp.task.preemptible"; -} - -#[allow(deprecated)] -impl ::std::fmt::Display for PreemptibleAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - let value: bool = match self { - PreemptibleAttr::Allowed => true, - PreemptibleAttr::Forbidden => false, - }; - ::std::fmt::Display::fmt(&value, formatter) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: PreemptibleAttr) -> Self { - let value: bool = match value { - PreemptibleAttr::Allowed => true, - PreemptibleAttr::Forbidden => false, - }; - ::opentelemetry::KeyValue::new(PreemptibleAttr::KEY, value) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: PreemptibleAttr) -> Self { - let value: bool = match value { - PreemptibleAttr::Allowed => true, - PreemptibleAttr::Forbidden => false, - }; - value.into() - } -} - -/// Number of times the task was retried. -#[derive(Debug, Clone, PartialEq, Copy)] -pub struct RetriesAttr(i64); - -#[allow(deprecated)] -impl RetriesAttr { - pub const KEY: &'static str = "myapp.task.retries"; -} - -#[allow(deprecated)] -impl From for RetriesAttr { - #[inline] - fn from(value: i64) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for RetriesAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - ::std::fmt::Display::fmt(&self.0, formatter) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: RetriesAttr) -> Self { - ::opentelemetry::KeyValue::new(RetriesAttr::KEY, value.0) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: RetriesAttr) -> Self { - value.0.into() - } -} - -/// Fraction of tasks whose telemetry is sampled. -#[derive(Debug, Clone, PartialEq, Copy)] -pub enum SampleRateAttr { - /// One task in ten is sampled. - Tenth, - /// Every task is sampled. - All, -} - -#[allow(deprecated)] -impl SampleRateAttr { - pub const KEY: &'static str = "myapp.task.sample_rate"; -} - -#[allow(deprecated)] -impl ::std::fmt::Display for SampleRateAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - let value: f64 = match self { - SampleRateAttr::Tenth => 0.1_f64, - SampleRateAttr::All => 1_f64, - }; - ::std::fmt::Display::fmt(&value, formatter) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: SampleRateAttr) -> Self { - let value: f64 = match value { - SampleRateAttr::Tenth => 0.1_f64, - SampleRateAttr::All => 1_f64, - }; - ::opentelemetry::KeyValue::new(SampleRateAttr::KEY, value) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: SampleRateAttr) -> Self { - let value: f64 = match value { - SampleRateAttr::Tenth => 0.1_f64, - SampleRateAttr::All => 1_f64, - }; - value.into() - } -} - -/// Shards the task touched. -#[derive(Debug, Clone, PartialEq)] -pub struct ShardIdsAttr(Vec); - -#[allow(deprecated)] -impl ShardIdsAttr { - pub const KEY: &'static str = "myapp.task.shard_ids"; -} - -#[allow(deprecated)] -impl From> for ShardIdsAttr { - #[inline] - fn from(value: Vec) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl AsRef<[i64]> for ShardIdsAttr { - #[inline] - fn as_ref(&self) -> &[i64] { - &self.0 - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for ShardIdsAttr { - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str("[")?; - for (index, value) in self.0.iter().enumerate() { - if index != 0 { - formatter.write_str(",")?; - } - ::std::fmt::Display::fmt(value, formatter)?; - } - formatter.write_str("]") - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: ShardIdsAttr) -> Self { - ::opentelemetry::KeyValue::new(ShardIdsAttr::KEY, ::opentelemetry::Value::Array(::opentelemetry::Array::I64(value.0))) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: ShardIdsAttr) -> Self { - value.0.into_iter().collect::<::opentelemetry::logs::AnyValue>() - } -} - -/// Current state of the task. -#[derive(Debug, Clone, PartialEq, Copy)] -pub enum StateAttr { - /// The task is waiting to run. - Queued, - /// The task is running. - /// - /// A task stays running until it finishes or is cancelled. - Running, -} - -#[allow(deprecated)] -impl StateAttr { - pub const KEY: &'static str = "myapp.task.state"; -} - -#[allow(deprecated)] -impl AsRef for StateAttr { - #[inline] - fn as_ref(&self) -> &str { - match self { - StateAttr::Queued => "queued", - StateAttr::Running => "running", - } - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for StateAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str(self.as_ref()) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: StateAttr) -> Self { - let value: &'static str = match value { - StateAttr::Queued => "queued", - StateAttr::Running => "running", - }; - ::opentelemetry::KeyValue::new(StateAttr::KEY, value) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: StateAttr) -> Self { - let value: &'static str = match value { - StateAttr::Queued => "queued", - StateAttr::Running => "running", - }; - value.into() - } -} - -/// Tags attached to the task. -#[derive(Debug, Clone, PartialEq)] -pub struct TagsAttr(Vec<::opentelemetry::StringValue>); - -#[allow(deprecated)] -impl TagsAttr { - pub const KEY: &'static str = "myapp.task.tags"; -} - -#[allow(deprecated)] -impl From> for TagsAttr { - #[inline] - fn from(value: Vec<::opentelemetry::StringValue>) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl From> for TagsAttr { - fn from(value: Vec) -> Self { - Self(value.into_iter().map(Into::into).collect()) - } -} - -#[allow(deprecated)] -impl AsRef<[::opentelemetry::StringValue]> for TagsAttr { - #[inline] - fn as_ref(&self) -> &[::opentelemetry::StringValue] { - &self.0 - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for TagsAttr { - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str("[")?; - for (index, value) in self.0.iter().enumerate() { - if index != 0 { - formatter.write_str(",")?; - } - write!(formatter, "\"{value}\"")?; - } - formatter.write_str("]") - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: TagsAttr) -> Self { - ::opentelemetry::KeyValue::new(TagsAttr::KEY, ::opentelemetry::Value::Array(::opentelemetry::Array::String(value.0))) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: TagsAttr) -> Self { - value.0.into_iter().collect::<::opentelemetry::logs::AnyValue>() - } -} diff --git a/templates/code/rust/tests/filtering/test.rs b/templates/code/rust/tests/filtering/test.rs index 8ee0762..d97c996 100644 --- a/templates/code/rust/tests/filtering/test.rs +++ b/templates/code/rust/tests/filtering/test.rs @@ -1,14 +1,14 @@ -use generated_semconv::taskattr::{IdAttr, StateAttr}; +use generated_semconv::attribute::{TaskId, TaskState}; use opentelemetry::{KeyValue, Value}; #[test] fn vendor_prefix_changes_types_but_preserves_telemetry_keys() { assert_eq!( - ::opentelemetry::KeyValue::from(IdAttr::from("task")), + ::opentelemetry::KeyValue::from(TaskId::from("task")), KeyValue::new("myapp.task.id", "task") ); assert_eq!( - ::opentelemetry::KeyValue::from(StateAttr::Queued).value, + ::opentelemetry::KeyValue::from(TaskState::Queued).value, Value::String("queued".into()) ); } diff --git a/templates/code/rust/tests/imported/expected/myappattr.rs b/templates/code/rust/tests/histogram_boundaries_by_unit/expected/attribute.rs similarity index 62% rename from templates/code/rust/tests/imported/expected/myappattr.rs rename to templates/code/rust/tests/histogram_boundaries_by_unit/expected/attribute.rs index c2a50dd..192012e 100644 --- a/templates/code/rust/tests/imported/expected/myappattr.rs +++ b/templates/code/rust/tests/histogram_boundaries_by_unit/expected/attribute.rs @@ -1,15 +1,15 @@ // Generated by OpenTelemetry Weaver. /// Unique identifier of the task. #[derive(Debug, Clone, PartialEq)] -pub struct TaskIdAttr(::opentelemetry::StringValue); +pub struct MyappTaskId(::opentelemetry::StringValue); #[allow(deprecated)] -impl TaskIdAttr { +impl MyappTaskId { pub const KEY: &'static str = "myapp.task.id"; } #[allow(deprecated)] -impl From<::opentelemetry::StringValue> for TaskIdAttr { +impl From<::opentelemetry::StringValue> for MyappTaskId { #[inline] fn from(value: ::opentelemetry::StringValue) -> Self { Self(value) @@ -17,7 +17,7 @@ impl From<::opentelemetry::StringValue> for TaskIdAttr { } #[allow(deprecated)] -impl From for TaskIdAttr { +impl From for MyappTaskId { #[inline] fn from(value: String) -> Self { Self(value.into()) @@ -25,7 +25,7 @@ impl From for TaskIdAttr { } #[allow(deprecated)] -impl From<&'static str> for TaskIdAttr { +impl From<&'static str> for MyappTaskId { #[inline] fn from(value: &'static str) -> Self { Self(value.into()) @@ -33,7 +33,7 @@ impl From<&'static str> for TaskIdAttr { } #[allow(deprecated)] -impl AsRef for TaskIdAttr { +impl AsRef for MyappTaskId { #[inline] fn as_ref(&self) -> &str { self.0.as_str() @@ -41,7 +41,7 @@ impl AsRef for TaskIdAttr { } #[allow(deprecated)] -impl ::std::fmt::Display for TaskIdAttr { +impl ::std::fmt::Display for MyappTaskId { #[inline] fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { formatter.write_str(self.as_ref()) @@ -49,17 +49,17 @@ impl ::std::fmt::Display for TaskIdAttr { } #[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { +impl From for ::opentelemetry::KeyValue { #[inline] - fn from(value: TaskIdAttr) -> Self { - ::opentelemetry::KeyValue::new(TaskIdAttr::KEY, value.0) + fn from(value: MyappTaskId) -> Self { + ::opentelemetry::KeyValue::new(MyappTaskId::KEY, value.0) } } #[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { +impl From for ::opentelemetry::logs::AnyValue { #[inline] - fn from(value: TaskIdAttr) -> Self { + fn from(value: MyappTaskId) -> Self { value.0.into() } } diff --git a/templates/code/rust/tests/histogram_boundaries_by_unit/expected/myappmetric.rs b/templates/code/rust/tests/histogram_boundaries_by_unit/expected/metric.rs similarity index 51% rename from templates/code/rust/tests/histogram_boundaries_by_unit/expected/myappmetric.rs rename to templates/code/rust/tests/histogram_boundaries_by_unit/expected/metric.rs index 8d23184..c64d31b 100644 --- a/templates/code/rust/tests/histogram_boundaries_by_unit/expected/myappmetric.rs +++ b/templates/code/rust/tests/histogram_boundaries_by_unit/expected/metric.rs @@ -1,96 +1,112 @@ #![allow(deprecated)] /// Time a task took from start to finish. #[derive(Clone)] -pub struct TaskDurationHistogram { +pub struct MyappTaskDuration { instrument: ::opentelemetry::metrics::Histogram, } -impl TaskDurationHistogram { +impl MyappTaskDuration { + pub const NAME: &'static str = "myapp.task.duration"; + pub const UNIT: &'static str = "s"; + pub const DESCRIPTION: &'static str = "Time a task took from start to finish."; + pub fn new(meter: &super::meter::Meter) -> Self { - let instrument = meter.inner().f64_histogram("myapp.task.duration") - .with_description("Time a task took from start to finish.") - .with_unit("s") + let instrument = meter.inner().f64_histogram(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) .with_boundaries(vec![0.005_f64, 0.01_f64, 0.025_f64, 0.05_f64, 0.075_f64, 0.1_f64, 0.25_f64, 0.5_f64, 0.75_f64, 1_f64, 2.5_f64, 5_f64, 7.5_f64, 10_f64]) .build(); Self { instrument } } - pub fn record(&self, value: f64, r#myapp_task_id: super::myappattr::TaskIdAttr) { + pub fn record(&self, value: f64, r#myapp_task_id: super::attribute::MyappTaskId) { let attributes = [::opentelemetry::KeyValue::from(r#myapp_task_id)]; self.instrument.record(value, &attributes); } } -impl Default for TaskDurationHistogram { +impl Default for MyappTaskDuration { fn default() -> Self { Self::new(&super::meter::Meter::default()) } } /// Time between a task being queued and started. #[derive(Clone)] -pub struct TaskLatencyHistogram { +pub struct MyappTaskLatency { instrument: ::opentelemetry::metrics::Histogram, } -impl TaskLatencyHistogram { +impl MyappTaskLatency { + pub const NAME: &'static str = "myapp.task.latency"; + pub const UNIT: &'static str = "s"; + pub const DESCRIPTION: &'static str = "Time between a task being queued and started."; + pub fn new(meter: &super::meter::Meter) -> Self { - let instrument = meter.inner().f64_histogram("myapp.task.latency") - .with_description("Time between a task being queued and started.") - .with_unit("s") + let instrument = meter.inner().f64_histogram(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) .with_boundaries(vec![1_f64, 10_f64, 100_f64]) .build(); Self { instrument } } - pub fn record(&self, value: f64, r#myapp_task_id: super::myappattr::TaskIdAttr) { + pub fn record(&self, value: f64, r#myapp_task_id: super::attribute::MyappTaskId) { let attributes = [::opentelemetry::KeyValue::from(r#myapp_task_id)]; self.instrument.record(value, &attributes); } } -impl Default for TaskLatencyHistogram { +impl Default for MyappTaskLatency { fn default() -> Self { Self::new(&super::meter::Meter::default()) } } /// Time a retried task took from start to finish. #[derive(Clone)] -pub struct TaskRetryDurationHistogram { +pub struct MyappTaskRetryDuration { instrument: ::opentelemetry::metrics::Histogram, } -impl TaskRetryDurationHistogram { +impl MyappTaskRetryDuration { + pub const NAME: &'static str = "myapp.task.duration"; + pub const UNIT: &'static str = "s"; + pub const DESCRIPTION: &'static str = "Time a task took from start to finish."; + pub fn new(meter: &super::meter::Meter) -> Self { - let instrument = meter.inner().f64_histogram("myapp.task.duration") - .with_description("Time a task took from start to finish.") - .with_unit("s") + let instrument = meter.inner().f64_histogram(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) .with_boundaries(vec![0.005_f64, 0.01_f64, 0.025_f64, 0.05_f64, 0.075_f64, 0.1_f64, 0.25_f64, 0.5_f64, 0.75_f64, 1_f64, 2.5_f64, 5_f64, 7.5_f64, 10_f64]) .build(); Self { instrument } } - pub fn record(&self, value: f64, r#myapp_task_id: super::myappattr::TaskIdAttr) { + pub fn record(&self, value: f64, r#myapp_task_id: super::attribute::MyappTaskId) { let attributes = [::opentelemetry::KeyValue::from(r#myapp_task_id)]; self.instrument.record(value, &attributes); } } -impl Default for TaskRetryDurationHistogram { +impl Default for MyappTaskRetryDuration { fn default() -> Self { Self::new(&super::meter::Meter::default()) } } /// Size of a task's payload. #[derive(Clone)] -pub struct TaskSizeHistogram { +pub struct MyappTaskSize { instrument: ::opentelemetry::metrics::Histogram, } -impl TaskSizeHistogram { +impl MyappTaskSize { + pub const NAME: &'static str = "myapp.task.size"; + pub const UNIT: &'static str = "By"; + pub const DESCRIPTION: &'static str = "Size of a task\u{0027}s payload."; + pub fn new(meter: &super::meter::Meter) -> Self { - let instrument = meter.inner().f64_histogram("myapp.task.size") - .with_description("Size of a task\u{0027}s payload.") - .with_unit("By") + let instrument = meter.inner().f64_histogram(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) .build(); Self { instrument } } - pub fn record(&self, value: f64, r#myapp_task_id: super::myappattr::TaskIdAttr) { + pub fn record(&self, value: f64, r#myapp_task_id: super::attribute::MyappTaskId) { let attributes = [::opentelemetry::KeyValue::from(r#myapp_task_id)]; self.instrument.record(value, &attributes); } } -impl Default for TaskSizeHistogram { +impl Default for MyappTaskSize { fn default() -> Self { Self::new(&super::meter::Meter::default()) } } diff --git a/templates/code/rust/tests/histogram_boundaries_by_unit/expected/mod.rs b/templates/code/rust/tests/histogram_boundaries_by_unit/expected/mod.rs index 834ced1..95e616b 100644 --- a/templates/code/rust/tests/histogram_boundaries_by_unit/expected/mod.rs +++ b/templates/code/rust/tests/histogram_boundaries_by_unit/expected/mod.rs @@ -1,8 +1,8 @@ // Generated by OpenTelemetry Weaver. pub const SCHEMA_URL: &str = "https://example.com/schemas/histogram_boundaries_by_unit/1.0.0"; -pub mod myappattr; +pub mod attribute; pub mod scope; pub mod options; pub mod meter; -pub mod myappmetric; +pub mod metric; diff --git a/templates/code/rust/tests/histogram_boundaries_by_unit/expected/myappattr.rs b/templates/code/rust/tests/histogram_boundaries_by_unit_params/expected/attribute.rs similarity index 62% rename from templates/code/rust/tests/histogram_boundaries_by_unit/expected/myappattr.rs rename to templates/code/rust/tests/histogram_boundaries_by_unit_params/expected/attribute.rs index c2a50dd..192012e 100644 --- a/templates/code/rust/tests/histogram_boundaries_by_unit/expected/myappattr.rs +++ b/templates/code/rust/tests/histogram_boundaries_by_unit_params/expected/attribute.rs @@ -1,15 +1,15 @@ // Generated by OpenTelemetry Weaver. /// Unique identifier of the task. #[derive(Debug, Clone, PartialEq)] -pub struct TaskIdAttr(::opentelemetry::StringValue); +pub struct MyappTaskId(::opentelemetry::StringValue); #[allow(deprecated)] -impl TaskIdAttr { +impl MyappTaskId { pub const KEY: &'static str = "myapp.task.id"; } #[allow(deprecated)] -impl From<::opentelemetry::StringValue> for TaskIdAttr { +impl From<::opentelemetry::StringValue> for MyappTaskId { #[inline] fn from(value: ::opentelemetry::StringValue) -> Self { Self(value) @@ -17,7 +17,7 @@ impl From<::opentelemetry::StringValue> for TaskIdAttr { } #[allow(deprecated)] -impl From for TaskIdAttr { +impl From for MyappTaskId { #[inline] fn from(value: String) -> Self { Self(value.into()) @@ -25,7 +25,7 @@ impl From for TaskIdAttr { } #[allow(deprecated)] -impl From<&'static str> for TaskIdAttr { +impl From<&'static str> for MyappTaskId { #[inline] fn from(value: &'static str) -> Self { Self(value.into()) @@ -33,7 +33,7 @@ impl From<&'static str> for TaskIdAttr { } #[allow(deprecated)] -impl AsRef for TaskIdAttr { +impl AsRef for MyappTaskId { #[inline] fn as_ref(&self) -> &str { self.0.as_str() @@ -41,7 +41,7 @@ impl AsRef for TaskIdAttr { } #[allow(deprecated)] -impl ::std::fmt::Display for TaskIdAttr { +impl ::std::fmt::Display for MyappTaskId { #[inline] fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { formatter.write_str(self.as_ref()) @@ -49,17 +49,17 @@ impl ::std::fmt::Display for TaskIdAttr { } #[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { +impl From for ::opentelemetry::KeyValue { #[inline] - fn from(value: TaskIdAttr) -> Self { - ::opentelemetry::KeyValue::new(TaskIdAttr::KEY, value.0) + fn from(value: MyappTaskId) -> Self { + ::opentelemetry::KeyValue::new(MyappTaskId::KEY, value.0) } } #[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { +impl From for ::opentelemetry::logs::AnyValue { #[inline] - fn from(value: TaskIdAttr) -> Self { + fn from(value: MyappTaskId) -> Self { value.0.into() } } diff --git a/templates/code/rust/tests/histogram_boundaries_by_unit_params/expected/metric.rs b/templates/code/rust/tests/histogram_boundaries_by_unit_params/expected/metric.rs new file mode 100644 index 0000000..d029edf --- /dev/null +++ b/templates/code/rust/tests/histogram_boundaries_by_unit_params/expected/metric.rs @@ -0,0 +1,56 @@ +#![allow(deprecated)] +/// Time a task took from start to finish. +#[derive(Clone)] +pub struct MyappTaskDuration { + instrument: ::opentelemetry::metrics::Histogram, +} + +impl MyappTaskDuration { + pub const NAME: &'static str = "myapp.task.duration"; + pub const UNIT: &'static str = "s"; + pub const DESCRIPTION: &'static str = "Time a task took from start to finish."; + + pub fn new(meter: &super::meter::Meter) -> Self { + let instrument = meter.inner().f64_histogram(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .build(); + Self { instrument } + } + pub fn record(&self, value: f64, r#myapp_task_id: super::attribute::MyappTaskId) { + let attributes = [::opentelemetry::KeyValue::from(r#myapp_task_id)]; + self.instrument.record(value, &attributes); + } +} + +impl Default for MyappTaskDuration { + fn default() -> Self { Self::new(&super::meter::Meter::default()) } +} +/// Time a task waited in the queue, in minutes. +#[derive(Clone)] +pub struct MyappTaskQueueWait { + instrument: ::opentelemetry::metrics::Histogram, +} + +impl MyappTaskQueueWait { + pub const NAME: &'static str = "myapp.task.queue_wait"; + pub const UNIT: &'static str = "min"; + pub const DESCRIPTION: &'static str = "Time a task waited in the queue, in minutes."; + + pub fn new(meter: &super::meter::Meter) -> Self { + let instrument = meter.inner().f64_histogram(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .with_boundaries(vec![1_f64, 5_f64, 10_f64, 30_f64, 60_f64]) + .build(); + Self { instrument } + } + pub fn record(&self, value: f64, r#myapp_task_id: super::attribute::MyappTaskId) { + let attributes = [::opentelemetry::KeyValue::from(r#myapp_task_id)]; + self.instrument.record(value, &attributes); + } +} + +impl Default for MyappTaskQueueWait { + fn default() -> Self { Self::new(&super::meter::Meter::default()) } +} diff --git a/templates/code/rust/tests/histogram_boundaries_by_unit_params/expected/mod.rs b/templates/code/rust/tests/histogram_boundaries_by_unit_params/expected/mod.rs index bf2567f..61b9bfa 100644 --- a/templates/code/rust/tests/histogram_boundaries_by_unit_params/expected/mod.rs +++ b/templates/code/rust/tests/histogram_boundaries_by_unit_params/expected/mod.rs @@ -1,8 +1,8 @@ // Generated by OpenTelemetry Weaver. pub const SCHEMA_URL: &str = "https://example.com/schemas/histogram_boundaries_by_unit_params/1.0.0"; -pub mod myappattr; +pub mod attribute; pub mod scope; pub mod options; pub mod meter; -pub mod myappmetric; +pub mod metric; diff --git a/templates/code/rust/tests/histogram_boundaries_by_unit_params/expected/myappmetric.rs b/templates/code/rust/tests/histogram_boundaries_by_unit_params/expected/myappmetric.rs deleted file mode 100644 index bd6280a..0000000 --- a/templates/code/rust/tests/histogram_boundaries_by_unit_params/expected/myappmetric.rs +++ /dev/null @@ -1,48 +0,0 @@ -#![allow(deprecated)] -/// Time a task took from start to finish. -#[derive(Clone)] -pub struct TaskDurationHistogram { - instrument: ::opentelemetry::metrics::Histogram, -} - -impl TaskDurationHistogram { - pub fn new(meter: &super::meter::Meter) -> Self { - let instrument = meter.inner().f64_histogram("myapp.task.duration") - .with_description("Time a task took from start to finish.") - .with_unit("s") - .build(); - Self { instrument } - } - pub fn record(&self, value: f64, r#myapp_task_id: super::myappattr::TaskIdAttr) { - let attributes = [::opentelemetry::KeyValue::from(r#myapp_task_id)]; - self.instrument.record(value, &attributes); - } -} - -impl Default for TaskDurationHistogram { - fn default() -> Self { Self::new(&super::meter::Meter::default()) } -} -/// Time a task waited in the queue, in minutes. -#[derive(Clone)] -pub struct TaskQueueWaitHistogram { - instrument: ::opentelemetry::metrics::Histogram, -} - -impl TaskQueueWaitHistogram { - pub fn new(meter: &super::meter::Meter) -> Self { - let instrument = meter.inner().f64_histogram("myapp.task.queue_wait") - .with_description("Time a task waited in the queue, in minutes.") - .with_unit("min") - .with_boundaries(vec![1_f64, 5_f64, 10_f64, 30_f64, 60_f64]) - .build(); - Self { instrument } - } - pub fn record(&self, value: f64, r#myapp_task_id: super::myappattr::TaskIdAttr) { - let attributes = [::opentelemetry::KeyValue::from(r#myapp_task_id)]; - self.instrument.record(value, &attributes); - } -} - -impl Default for TaskQueueWaitHistogram { - fn default() -> Self { Self::new(&super::meter::Meter::default()) } -} diff --git a/templates/code/rust/tests/histogram_boundaries_by_unit_params/expected/myappattr.rs b/templates/code/rust/tests/imported/expected/attribute.rs similarity index 62% rename from templates/code/rust/tests/histogram_boundaries_by_unit_params/expected/myappattr.rs rename to templates/code/rust/tests/imported/expected/attribute.rs index c2a50dd..192012e 100644 --- a/templates/code/rust/tests/histogram_boundaries_by_unit_params/expected/myappattr.rs +++ b/templates/code/rust/tests/imported/expected/attribute.rs @@ -1,15 +1,15 @@ // Generated by OpenTelemetry Weaver. /// Unique identifier of the task. #[derive(Debug, Clone, PartialEq)] -pub struct TaskIdAttr(::opentelemetry::StringValue); +pub struct MyappTaskId(::opentelemetry::StringValue); #[allow(deprecated)] -impl TaskIdAttr { +impl MyappTaskId { pub const KEY: &'static str = "myapp.task.id"; } #[allow(deprecated)] -impl From<::opentelemetry::StringValue> for TaskIdAttr { +impl From<::opentelemetry::StringValue> for MyappTaskId { #[inline] fn from(value: ::opentelemetry::StringValue) -> Self { Self(value) @@ -17,7 +17,7 @@ impl From<::opentelemetry::StringValue> for TaskIdAttr { } #[allow(deprecated)] -impl From for TaskIdAttr { +impl From for MyappTaskId { #[inline] fn from(value: String) -> Self { Self(value.into()) @@ -25,7 +25,7 @@ impl From for TaskIdAttr { } #[allow(deprecated)] -impl From<&'static str> for TaskIdAttr { +impl From<&'static str> for MyappTaskId { #[inline] fn from(value: &'static str) -> Self { Self(value.into()) @@ -33,7 +33,7 @@ impl From<&'static str> for TaskIdAttr { } #[allow(deprecated)] -impl AsRef for TaskIdAttr { +impl AsRef for MyappTaskId { #[inline] fn as_ref(&self) -> &str { self.0.as_str() @@ -41,7 +41,7 @@ impl AsRef for TaskIdAttr { } #[allow(deprecated)] -impl ::std::fmt::Display for TaskIdAttr { +impl ::std::fmt::Display for MyappTaskId { #[inline] fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { formatter.write_str(self.as_ref()) @@ -49,17 +49,17 @@ impl ::std::fmt::Display for TaskIdAttr { } #[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { +impl From for ::opentelemetry::KeyValue { #[inline] - fn from(value: TaskIdAttr) -> Self { - ::opentelemetry::KeyValue::new(TaskIdAttr::KEY, value.0) + fn from(value: MyappTaskId) -> Self { + ::opentelemetry::KeyValue::new(MyappTaskId::KEY, value.0) } } #[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { +impl From for ::opentelemetry::logs::AnyValue { #[inline] - fn from(value: TaskIdAttr) -> Self { + fn from(value: MyappTaskId) -> Self { value.0.into() } } diff --git a/templates/code/rust/tests/imported/expected/edgeevent.rs b/templates/code/rust/tests/imported/expected/edgeevent.rs deleted file mode 100644 index 0bcd626..0000000 --- a/templates/code/rust/tests/imported/expected/edgeevent.rs +++ /dev/null @@ -1,43 +0,0 @@ -#![allow(deprecated)] -use ::opentelemetry::logs::LogRecord; -use ::opentelemetry::trace::TraceContextExt; - -#[derive(Clone, Debug)] -pub enum UpstreamFailedOption { - Severity(::opentelemetry::logs::Severity), - Timestamp(::std::time::SystemTime), - HttpRequestMethodList(Vec<::opentelemetry::StringValue>), - ServerAddress(::opentelemetry::StringValue), -} -/// A request to an upstream server failed. -pub fn r#emit_upstream_failed(context: &::opentelemetry::Context, logger: &super::logger::Logger, r#error_type: ::opentelemetry::StringValue, options: impl IntoIterator) { - let mut severity = ::opentelemetry::logs::Severity::Info; - let mut timestamp = None; - let mut attributes = ::smallvec::SmallVec::<[UpstreamFailedOption; 2]>::new(); - for option in options { - match option { - UpstreamFailedOption::Severity(value) => severity = value, - UpstreamFailedOption::Timestamp(value) => timestamp = Some(value), - attribute => attributes.push(attribute), - } - } - if !logger.inner().event_enabled(severity, "", Some("edge.upstream.failed")) { return; } - let _context_guard = context.clone().attach(); - let mut record = logger.inner().create_log_record(); - record.set_event_name("edge.upstream.failed"); - record.set_severity_number(severity); - record.set_observed_timestamp(::std::time::SystemTime::now()); - if let Some(timestamp) = timestamp { record.set_timestamp(timestamp); } - let span = context.span(); - let span_context = span.span_context(); - if span_context.is_valid() { record.set_trace_context(span_context.trace_id(), span_context.span_id(), Some(span_context.trace_flags())); } - record.add_attribute("error.type", r#error_type); - for option in attributes { - match option { - UpstreamFailedOption::HttpRequestMethodList(value) => record.add_attribute("http.request.method_list", value.into_iter().collect::<::opentelemetry::logs::AnyValue>()), - UpstreamFailedOption::ServerAddress(value) => record.add_attribute("server.address", value), - UpstreamFailedOption::Severity(_) | UpstreamFailedOption::Timestamp(_) => continue, - } - } - logger.inner().emit(record); -} diff --git a/templates/code/rust/tests/imported/expected/edgemetric.rs b/templates/code/rust/tests/imported/expected/edgemetric.rs deleted file mode 100644 index 0df00c7..0000000 --- a/templates/code/rust/tests/imported/expected/edgemetric.rs +++ /dev/null @@ -1,39 +0,0 @@ -#![allow(deprecated)] -#[derive(Clone, Debug)] -pub enum UpstreamDurationHistogramAttr { - ServerPort(i64), -} - -impl From for ::opentelemetry::KeyValue { - fn from(value: UpstreamDurationHistogramAttr) -> Self { - match value { - UpstreamDurationHistogramAttr::ServerPort(value) => ::opentelemetry::KeyValue::new("server.port", value), - } - } -} -/// Time spent waiting on an upstream server. -#[derive(Clone)] -pub struct UpstreamDurationHistogram { - instrument: ::opentelemetry::metrics::Histogram, -} - -impl UpstreamDurationHistogram { - pub fn new(meter: &super::meter::Meter) -> Self { - let instrument = meter.inner().f64_histogram("edge.upstream.duration") - .with_description("Time spent waiting on an upstream server.") - .with_unit("s") - .with_boundaries(vec![0.005_f64, 0.01_f64, 0.025_f64, 0.05_f64, 0.075_f64, 0.1_f64, 0.25_f64, 0.5_f64, 0.75_f64, 1_f64, 2.5_f64, 5_f64, 7.5_f64, 10_f64]) - .build(); - Self { instrument } - } - pub fn record(&self, value: f64, r#server_address: ::opentelemetry::StringValue, options: impl IntoIterator) { - let mut attributes = ::smallvec::SmallVec::<[::opentelemetry::KeyValue; 2]>::new(); - attributes.extend([::opentelemetry::KeyValue::new("server.address", r#server_address)]); - attributes.extend(options.into_iter().map(::opentelemetry::KeyValue::from)); - self.instrument.record(value, &attributes); - } -} - -impl Default for UpstreamDurationHistogram { - fn default() -> Self { Self::new(&super::meter::Meter::default()) } -} diff --git a/templates/code/rust/tests/imported/expected/event.rs b/templates/code/rust/tests/imported/expected/event.rs new file mode 100644 index 0000000..06240ff --- /dev/null +++ b/templates/code/rust/tests/imported/expected/event.rs @@ -0,0 +1,51 @@ +#![allow(deprecated)] +use ::opentelemetry::logs::LogRecord; +use ::opentelemetry::trace::TraceContextExt; + +/// A request to an upstream server failed. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct EdgeUpstreamFailed; + +impl EdgeUpstreamFailed { + pub const NAME: &'static str = "edge.upstream.failed"; +} + +#[derive(Clone, Debug)] +pub enum EdgeUpstreamFailedOption { + Severity(::opentelemetry::logs::Severity), + Timestamp(::std::time::SystemTime), + HttpRequestMethodList(Vec<::opentelemetry::StringValue>), + ServerAddress(::opentelemetry::StringValue), +} +/// A request to an upstream server failed. +pub fn r#emit_edge_upstream_failed(context: &::opentelemetry::Context, logger: &super::logger::Logger, r#error_type: ::opentelemetry::StringValue, options: impl IntoIterator) { + let mut severity = ::opentelemetry::logs::Severity::Info; + let mut timestamp = None; + let mut attributes = ::smallvec::SmallVec::<[EdgeUpstreamFailedOption; 2]>::new(); + for option in options { + match option { + EdgeUpstreamFailedOption::Severity(value) => severity = value, + EdgeUpstreamFailedOption::Timestamp(value) => timestamp = Some(value), + attribute => attributes.push(attribute), + } + } + if !logger.inner().event_enabled(severity, "", Some(EdgeUpstreamFailed::NAME)) { return; } + let _context_guard = context.clone().attach(); + let mut record = logger.inner().create_log_record(); + record.set_event_name(EdgeUpstreamFailed::NAME); + record.set_severity_number(severity); + record.set_observed_timestamp(::std::time::SystemTime::now()); + if let Some(timestamp) = timestamp { record.set_timestamp(timestamp); } + let span = context.span(); + let span_context = span.span_context(); + if span_context.is_valid() { record.set_trace_context(span_context.trace_id(), span_context.span_id(), Some(span_context.trace_flags())); } + record.add_attribute("error.type", r#error_type); + for option in attributes { + match option { + EdgeUpstreamFailedOption::HttpRequestMethodList(value) => record.add_attribute("http.request.method_list", value.into_iter().collect::<::opentelemetry::logs::AnyValue>()), + EdgeUpstreamFailedOption::ServerAddress(value) => record.add_attribute("server.address", value), + EdgeUpstreamFailedOption::Severity(_) | EdgeUpstreamFailedOption::Timestamp(_) => continue, + } + } + logger.inner().emit(record); +} diff --git a/templates/code/rust/tests/imported/expected/metric.rs b/templates/code/rust/tests/imported/expected/metric.rs new file mode 100644 index 0000000..919929a --- /dev/null +++ b/templates/code/rust/tests/imported/expected/metric.rs @@ -0,0 +1,120 @@ +#![allow(deprecated)] +#[derive(Clone, Debug)] +pub enum EdgeUpstreamDurationAttr { + ServerPort(i64), +} + +impl From for ::opentelemetry::KeyValue { + fn from(value: EdgeUpstreamDurationAttr) -> Self { + match value { + EdgeUpstreamDurationAttr::ServerPort(value) => ::opentelemetry::KeyValue::new("server.port", value), + } + } +} +/// Time spent waiting on an upstream server. +#[derive(Clone)] +pub struct EdgeUpstreamDuration { + instrument: ::opentelemetry::metrics::Histogram, +} + +impl EdgeUpstreamDuration { + pub const NAME: &'static str = "edge.upstream.duration"; + pub const UNIT: &'static str = "s"; + pub const DESCRIPTION: &'static str = "Time spent waiting on an upstream server."; + + pub fn new(meter: &super::meter::Meter) -> Self { + let instrument = meter.inner().f64_histogram(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .with_boundaries(vec![0.005_f64, 0.01_f64, 0.025_f64, 0.05_f64, 0.075_f64, 0.1_f64, 0.25_f64, 0.5_f64, 0.75_f64, 1_f64, 2.5_f64, 5_f64, 7.5_f64, 10_f64]) + .build(); + Self { instrument } + } + pub fn record(&self, value: f64, r#server_address: ::opentelemetry::StringValue, options: impl IntoIterator) { + let mut attributes = ::smallvec::SmallVec::<[::opentelemetry::KeyValue; 2]>::new(); + attributes.extend([::opentelemetry::KeyValue::new("server.address", r#server_address)]); + attributes.extend(options.into_iter().map(::opentelemetry::KeyValue::from)); + self.instrument.record(value, &attributes); + } +} + +impl Default for EdgeUpstreamDuration { + fn default() -> Self { Self::new(&super::meter::Meter::default()) } +} +#[derive(Clone, Debug)] +pub enum MyappTaskFailedAttr { + HttpRequestMethodList(Vec<::opentelemetry::StringValue>), +} + +impl From for ::opentelemetry::KeyValue { + fn from(value: MyappTaskFailedAttr) -> Self { + match value { + MyappTaskFailedAttr::HttpRequestMethodList(value) => ::opentelemetry::KeyValue::new("http.request.method_list", ::opentelemetry::Value::Array(::opentelemetry::Array::String(value))), + } + } +} +/// Number of tasks that failed. +#[derive(Clone)] +pub struct MyappTaskFailed { + instrument: ::opentelemetry::metrics::Counter, +} + +impl MyappTaskFailed { + pub const NAME: &'static str = "myapp.task.failed"; + pub const UNIT: &'static str = "{task}"; + pub const DESCRIPTION: &'static str = "Number of tasks that failed."; + + pub fn new(meter: &super::meter::Meter) -> Self { + let instrument = meter.inner().u64_counter(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .build(); + Self { instrument } + } + pub fn add(&self, value: u64, r#error_type: ::opentelemetry::StringValue, r#myapp_task_id: super::attribute::MyappTaskId, options: impl IntoIterator) { + let mut attributes = ::smallvec::SmallVec::<[::opentelemetry::KeyValue; 3]>::new(); + attributes.extend([::opentelemetry::KeyValue::new("error.type", r#error_type), ::opentelemetry::KeyValue::from(r#myapp_task_id)]); + attributes.extend(options.into_iter().map(::opentelemetry::KeyValue::from)); + self.instrument.add(value, &attributes); + } +} + +impl Default for MyappTaskFailed { + fn default() -> Self { Self::new(&super::meter::Meter::default()) } +} +pub struct MyappTaskFailedObserver<'a> { + observer: &'a dyn ::opentelemetry::metrics::AsyncInstrument, +} + +impl MyappTaskFailedObserver<'_> { + pub fn observe(&self, value: u64, r#error_type: ::opentelemetry::StringValue, r#myapp_task_id: super::attribute::MyappTaskId, options: impl IntoIterator) { + let mut attributes = ::smallvec::SmallVec::<[::opentelemetry::KeyValue; 3]>::new(); + attributes.extend([::opentelemetry::KeyValue::new("error.type", r#error_type), ::opentelemetry::KeyValue::from(r#myapp_task_id)]); + attributes.extend(options.into_iter().map(::opentelemetry::KeyValue::from)); + self.observer.observe(value, &attributes); + } +} + +#[derive(Clone)] +pub struct MyappTaskFailedObservable { + _instrument: ::opentelemetry::metrics::ObservableCounter, +} + +impl MyappTaskFailedObservable { + pub const NAME: &'static str = MyappTaskFailed::NAME; + pub const UNIT: &'static str = MyappTaskFailed::UNIT; + pub const DESCRIPTION: &'static str = MyappTaskFailed::DESCRIPTION; + + pub fn new(meter: &super::meter::Meter, callback: impl Fn(MyappTaskFailedObserver<'_>) + Send + Sync + 'static) -> Self { + let instrument = meter.inner().u64_observable_counter(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .with_callback(move |observer| callback(MyappTaskFailedObserver { observer })) + .build(); + Self { _instrument: instrument } + } +} + +impl Default for MyappTaskFailedObservable { + fn default() -> Self { Self::new(&super::meter::Meter::default(), |_| {}) } +} diff --git a/templates/code/rust/tests/imported/expected/mod.rs b/templates/code/rust/tests/imported/expected/mod.rs index c1aaad3..b28f832 100644 --- a/templates/code/rust/tests/imported/expected/mod.rs +++ b/templates/code/rust/tests/imported/expected/mod.rs @@ -1,13 +1,12 @@ // Generated by OpenTelemetry Weaver. pub const SCHEMA_URL: &str = "https://example.com/schemas/myapp/1.0.0"; -pub mod myappattr; +pub mod attribute; pub mod scope; pub mod options; pub mod meter; pub mod tracer; pub mod logger; -pub mod edgeevent; -pub mod edgemetric; -pub mod edgespan; -pub mod myappmetric; +pub mod event; +pub mod metric; +pub mod trace; diff --git a/templates/code/rust/tests/imported/expected/myappmetric.rs b/templates/code/rust/tests/imported/expected/myappmetric.rs deleted file mode 100644 index cf876c8..0000000 --- a/templates/code/rust/tests/imported/expected/myappmetric.rs +++ /dev/null @@ -1,70 +0,0 @@ -#![allow(deprecated)] -#[derive(Clone, Debug)] -pub enum TaskFailedCounterAttr { - HttpRequestMethodList(Vec<::opentelemetry::StringValue>), -} - -impl From for ::opentelemetry::KeyValue { - fn from(value: TaskFailedCounterAttr) -> Self { - match value { - TaskFailedCounterAttr::HttpRequestMethodList(value) => ::opentelemetry::KeyValue::new("http.request.method_list", ::opentelemetry::Value::Array(::opentelemetry::Array::String(value))), - } - } -} -/// Number of tasks that failed. -#[derive(Clone)] -pub struct TaskFailedCounter { - instrument: ::opentelemetry::metrics::Counter, -} - -impl TaskFailedCounter { - pub fn new(meter: &super::meter::Meter) -> Self { - let instrument = meter.inner().u64_counter("myapp.task.failed") - .with_description("Number of tasks that failed.") - .with_unit("{task}") - .build(); - Self { instrument } - } - pub fn add(&self, value: u64, r#error_type: ::opentelemetry::StringValue, r#myapp_task_id: super::myappattr::TaskIdAttr, options: impl IntoIterator) { - let mut attributes = ::smallvec::SmallVec::<[::opentelemetry::KeyValue; 3]>::new(); - attributes.extend([::opentelemetry::KeyValue::new("error.type", r#error_type), ::opentelemetry::KeyValue::from(r#myapp_task_id)]); - attributes.extend(options.into_iter().map(::opentelemetry::KeyValue::from)); - self.instrument.add(value, &attributes); - } -} - -impl Default for TaskFailedCounter { - fn default() -> Self { Self::new(&super::meter::Meter::default()) } -} -pub struct TaskFailedCounterObserver<'a> { - observer: &'a dyn ::opentelemetry::metrics::AsyncInstrument, -} - -impl TaskFailedCounterObserver<'_> { - pub fn observe(&self, value: u64, r#error_type: ::opentelemetry::StringValue, r#myapp_task_id: super::myappattr::TaskIdAttr, options: impl IntoIterator) { - let mut attributes = ::smallvec::SmallVec::<[::opentelemetry::KeyValue; 3]>::new(); - attributes.extend([::opentelemetry::KeyValue::new("error.type", r#error_type), ::opentelemetry::KeyValue::from(r#myapp_task_id)]); - attributes.extend(options.into_iter().map(::opentelemetry::KeyValue::from)); - self.observer.observe(value, &attributes); - } -} - -#[derive(Clone)] -pub struct TaskFailedObservableCounter { - _instrument: ::opentelemetry::metrics::ObservableCounter, -} - -impl TaskFailedObservableCounter { - pub fn new(meter: &super::meter::Meter, callback: impl Fn(TaskFailedCounterObserver<'_>) + Send + Sync + 'static) -> Self { - let instrument = meter.inner().u64_observable_counter("myapp.task.failed") - .with_description("Number of tasks that failed.") - .with_unit("{task}") - .with_callback(move |observer| callback(TaskFailedCounterObserver { observer })) - .build(); - Self { _instrument: instrument } - } -} - -impl Default for TaskFailedObservableCounter { - fn default() -> Self { Self::new(&super::meter::Meter::default(), |_| {}) } -} diff --git a/templates/code/rust/tests/imported/expected/edgespan.rs b/templates/code/rust/tests/imported/expected/trace.rs similarity index 65% rename from templates/code/rust/tests/imported/expected/edgespan.rs rename to templates/code/rust/tests/imported/expected/trace.rs index a7ba98f..e3f1ac7 100644 --- a/templates/code/rust/tests/imported/expected/edgespan.rs +++ b/templates/code/rust/tests/imported/expected/trace.rs @@ -1,13 +1,13 @@ #![allow(deprecated)] -use ::opentelemetry::trace::{TraceContextExt, Tracer}; -use ::std::fmt::Write; +use ::opentelemetry::trace::{TraceContextExt as _, Tracer as _}; +use ::std::fmt::Write as _; /// A request named from attempted methods. -pub struct UpstreamMethodsSpan { +pub struct EdgeUpstreamMethods { span: S, } -impl UpstreamMethodsSpan { +impl EdgeUpstreamMethods { pub fn into_context(self, parent: &::opentelemetry::Context) -> ::opentelemetry::Context where S: Send + Sync + 'static, { @@ -20,13 +20,17 @@ impl UpstreamMethodsSpan { pub fn set_status(&mut self, status: ::opentelemetry::trace::Status) { ::opentelemetry::trace::Span::set_status(&mut self.span, status); } } -impl Default for UpstreamMethodsSpan { +impl EdgeUpstreamMethods { + pub const NAME: &'static str = "edge.upstream.methods"; +} + +impl Default for EdgeUpstreamMethods { fn default() -> Self { - Self { span: super::tracer::Tracer::default().inner().start("edge.upstream.methods") } + Self { span: super::tracer::Tracer::default().inner().start(Self::NAME) } } } -pub fn r#start_upstream_methods(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer, r#http_request_method_list: Vec<::opentelemetry::StringValue>) -> UpstreamMethodsSpan { +pub fn r#start_edge_upstream_methods(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer, r#http_request_method_list: Vec<::opentelemetry::StringValue>) -> EdgeUpstreamMethods { let mut name = String::with_capacity(r#http_request_method_list.iter().map(|value| value.as_str().len() + 3).sum::() + 2); name.push('['); for (index, value) in r#http_request_method_list.iter().enumerate() { @@ -39,41 +43,41 @@ pub fn r#start_upstream_methods(context: &::o .with_kind(::opentelemetry::trace::SpanKind::Client) .with_attributes(attributes) .start_with_context(tracer.inner(), context); - UpstreamMethodsSpan { span } + EdgeUpstreamMethods { span } } #[derive(Clone, Debug)] -pub enum UpstreamRequestStartAttr { +pub enum EdgeUpstreamRequestStartAttr { /// Conditionally required: If the request failed. ErrorType(::opentelemetry::StringValue), HttpRequestMethodList(Vec<::opentelemetry::StringValue>), } -impl From for ::opentelemetry::KeyValue { - fn from(value: UpstreamRequestStartAttr) -> Self { +impl From for ::opentelemetry::KeyValue { + fn from(value: EdgeUpstreamRequestStartAttr) -> Self { match value { - UpstreamRequestStartAttr::ErrorType(value) => ::opentelemetry::KeyValue::new("error.type", value), - UpstreamRequestStartAttr::HttpRequestMethodList(value) => ::opentelemetry::KeyValue::new("http.request.method_list", ::opentelemetry::Value::Array(::opentelemetry::Array::String(value))), + EdgeUpstreamRequestStartAttr::ErrorType(value) => ::opentelemetry::KeyValue::new("error.type", value), + EdgeUpstreamRequestStartAttr::HttpRequestMethodList(value) => ::opentelemetry::KeyValue::new("http.request.method_list", ::opentelemetry::Value::Array(::opentelemetry::Array::String(value))), } } } #[derive(Clone, Debug)] -pub enum UpstreamRequestAttr { +pub enum EdgeUpstreamRequestAttr { HttpRequestMethodList(Vec<::opentelemetry::StringValue>), } -impl From for UpstreamRequestStartAttr { - fn from(value: UpstreamRequestAttr) -> Self { +impl From for EdgeUpstreamRequestStartAttr { + fn from(value: EdgeUpstreamRequestAttr) -> Self { match value { - UpstreamRequestAttr::HttpRequestMethodList(value) => Self::HttpRequestMethodList(value), + EdgeUpstreamRequestAttr::HttpRequestMethodList(value) => Self::HttpRequestMethodList(value), } } } /// A request to an upstream server. -pub struct UpstreamRequestSpan { +pub struct EdgeUpstreamRequest { span: S, } -impl UpstreamRequestSpan { +impl EdgeUpstreamRequest { pub fn into_context(self, parent: &::opentelemetry::Context) -> ::opentelemetry::Context where S: Send + Sync + 'static, { @@ -84,18 +88,22 @@ impl UpstreamRequestSpan { pub fn end_with_timestamp(&mut self, timestamp: ::std::time::SystemTime) { ::opentelemetry::trace::Span::end_with_timestamp(&mut self.span, timestamp); } pub fn record_error(&mut self, error: &dyn ::std::error::Error) { ::opentelemetry::trace::Span::record_error(&mut self.span, error); } pub fn set_status(&mut self, status: ::opentelemetry::trace::Status) { ::opentelemetry::trace::Span::set_status(&mut self.span, status); } - pub fn set_attributes(&mut self, attributes: impl IntoIterator) { - for attribute in attributes { ::opentelemetry::trace::Span::set_attribute(&mut self.span, ::opentelemetry::KeyValue::from(UpstreamRequestStartAttr::from(attribute))); } + pub fn set_attributes(&mut self, attributes: impl IntoIterator) { + for attribute in attributes { ::opentelemetry::trace::Span::set_attribute(&mut self.span, ::opentelemetry::KeyValue::from(EdgeUpstreamRequestStartAttr::from(attribute))); } } } -impl Default for UpstreamRequestSpan { +impl EdgeUpstreamRequest { + pub const NAME: &'static str = "edge.upstream.request"; +} + +impl Default for EdgeUpstreamRequest { fn default() -> Self { - Self { span: super::tracer::Tracer::default().inner().start("edge.upstream.request") } + Self { span: super::tracer::Tracer::default().inner().start(Self::NAME) } } } -pub fn r#start_upstream_request(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer, r#server_address: ::opentelemetry::StringValue, r#server_port: i64, options: impl IntoIterator) -> UpstreamRequestSpan { +pub fn r#start_edge_upstream_request(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer, r#server_address: ::opentelemetry::StringValue, r#server_port: i64, options: impl IntoIterator) -> EdgeUpstreamRequest { let mut name = String::with_capacity(r#server_address.as_str().len() + ":".len() + 20); write!(&mut name, "{}", r#server_address).expect("writing a span name to String cannot fail"); name.push(':'); @@ -105,5 +113,5 @@ pub fn r#start_upstream_request(context: &::o .with_kind(::opentelemetry::trace::SpanKind::Client) .with_attributes(attributes.into_iter().chain(options.into_iter().map(::opentelemetry::KeyValue::from))) .start_with_context(tracer.inner(), context); - UpstreamRequestSpan { span } + EdgeUpstreamRequest { span } } diff --git a/templates/code/rust/tests/imported/test.rs b/templates/code/rust/tests/imported/test.rs index e1647e9..ff9ff7b 100644 --- a/templates/code/rust/tests/imported/test.rs +++ b/templates/code/rust/tests/imported/test.rs @@ -1,12 +1,12 @@ use generated_semconv::options::InstrumentationOptions; -use generated_semconv::{edgeevent, edgespan, logger, myappattr, myappmetric, tracer}; +use generated_semconv::{attribute, event, logger, metric, trace, tracer}; use opentelemetry::{Array, KeyValue, StringValue, Value}; #[test] fn imported_native_strings_and_arrays_keep_their_sdk_storage() { let methods = vec![StringValue::from("GET"), StringValue::from("POST")]; let pointer = methods.as_ptr(); - let attribute = KeyValue::from(myappmetric::TaskFailedCounterAttr::HttpRequestMethodList( + let attribute = KeyValue::from(metric::MyappTaskFailedAttr::HttpRequestMethodList( methods, )); assert_eq!(attribute.key.as_str(), "http.request.method_list"); @@ -18,24 +18,24 @@ fn imported_native_strings_and_arrays_keep_their_sdk_storage() { methods.iter().map(StringValue::as_str).collect::>(), ["GET", "POST"] ); - myappmetric::TaskFailedCounter::default().add( + metric::MyappTaskFailed::default().add( 1, StringValue::from("timeout"), - myappattr::TaskIdAttr::from("task-1"), - [myappmetric::TaskFailedCounterAttr::HttpRequestMethodList( + attribute::MyappTaskId::from("task-1"), + [metric::MyappTaskFailedAttr::HttpRequestMethodList( methods, )], ); let context = opentelemetry::Context::new(); - edgeevent::emit_upstream_failed( + event::emit_edge_upstream_failed( &context, &logger::Logger::default(), StringValue::from("timeout"), - [edgeevent::UpstreamFailedOption::ServerAddress( + [event::EdgeUpstreamFailedOption::ServerAddress( StringValue::from("example.com"), )], ); - let mut span = edgespan::start_upstream_request( + let mut span = trace::start_edge_upstream_request( &context, &tracer::Tracer::default(), StringValue::from("example.com"), @@ -52,7 +52,7 @@ fn imported_native_string_arrays_format_derived_span_names() { .with_simple_exporter(exporter.clone()) .build(); let tracer = tracer::Tracer::new(&provider, InstrumentationOptions::default()); - let mut span = edgespan::start_upstream_methods( + let mut span = trace::start_edge_upstream_methods( &opentelemetry::Context::new(), &tracer, vec![StringValue::from("GET"), StringValue::from("POST")], @@ -76,11 +76,11 @@ fn imported_native_string_array_events_preserve_order_and_duplicates() { let provider = opentelemetry_sdk::logs::SdkLoggerProvider::builder() .with_simple_exporter(exporter.clone()) .build(); - edgeevent::emit_upstream_failed( + event::emit_edge_upstream_failed( &opentelemetry::Context::new(), &logger::Logger::new(&provider, InstrumentationOptions::default()), StringValue::from("timeout"), - [edgeevent::UpstreamFailedOption::HttpRequestMethodList( + [event::EdgeUpstreamFailedOption::HttpRequestMethodList( vec![ StringValue::from("GET"), StringValue::from("GET"), diff --git a/templates/code/rust/tests/imported_typed/expected/myappattr.rs b/templates/code/rust/tests/imported_typed/expected/attribute.rs similarity index 62% rename from templates/code/rust/tests/imported_typed/expected/myappattr.rs rename to templates/code/rust/tests/imported_typed/expected/attribute.rs index c2a50dd..192012e 100644 --- a/templates/code/rust/tests/imported_typed/expected/myappattr.rs +++ b/templates/code/rust/tests/imported_typed/expected/attribute.rs @@ -1,15 +1,15 @@ // Generated by OpenTelemetry Weaver. /// Unique identifier of the task. #[derive(Debug, Clone, PartialEq)] -pub struct TaskIdAttr(::opentelemetry::StringValue); +pub struct MyappTaskId(::opentelemetry::StringValue); #[allow(deprecated)] -impl TaskIdAttr { +impl MyappTaskId { pub const KEY: &'static str = "myapp.task.id"; } #[allow(deprecated)] -impl From<::opentelemetry::StringValue> for TaskIdAttr { +impl From<::opentelemetry::StringValue> for MyappTaskId { #[inline] fn from(value: ::opentelemetry::StringValue) -> Self { Self(value) @@ -17,7 +17,7 @@ impl From<::opentelemetry::StringValue> for TaskIdAttr { } #[allow(deprecated)] -impl From for TaskIdAttr { +impl From for MyappTaskId { #[inline] fn from(value: String) -> Self { Self(value.into()) @@ -25,7 +25,7 @@ impl From for TaskIdAttr { } #[allow(deprecated)] -impl From<&'static str> for TaskIdAttr { +impl From<&'static str> for MyappTaskId { #[inline] fn from(value: &'static str) -> Self { Self(value.into()) @@ -33,7 +33,7 @@ impl From<&'static str> for TaskIdAttr { } #[allow(deprecated)] -impl AsRef for TaskIdAttr { +impl AsRef for MyappTaskId { #[inline] fn as_ref(&self) -> &str { self.0.as_str() @@ -41,7 +41,7 @@ impl AsRef for TaskIdAttr { } #[allow(deprecated)] -impl ::std::fmt::Display for TaskIdAttr { +impl ::std::fmt::Display for MyappTaskId { #[inline] fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { formatter.write_str(self.as_ref()) @@ -49,17 +49,17 @@ impl ::std::fmt::Display for TaskIdAttr { } #[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { +impl From for ::opentelemetry::KeyValue { #[inline] - fn from(value: TaskIdAttr) -> Self { - ::opentelemetry::KeyValue::new(TaskIdAttr::KEY, value.0) + fn from(value: MyappTaskId) -> Self { + ::opentelemetry::KeyValue::new(MyappTaskId::KEY, value.0) } } #[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { +impl From for ::opentelemetry::logs::AnyValue { #[inline] - fn from(value: TaskIdAttr) -> Self { + fn from(value: MyappTaskId) -> Self { value.0.into() } } diff --git a/templates/code/rust/tests/imported_typed/expected/event.rs b/templates/code/rust/tests/imported_typed/expected/event.rs new file mode 100644 index 0000000..4f1abf0 --- /dev/null +++ b/templates/code/rust/tests/imported_typed/expected/event.rs @@ -0,0 +1,49 @@ +#![allow(deprecated)] +use ::opentelemetry::logs::LogRecord; +use ::opentelemetry::trace::TraceContextExt; + +/// A task failed with an error. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct MyappTaskErrored; + +impl MyappTaskErrored { + pub const NAME: &'static str = "myapp.task.errored"; +} + +#[derive(Clone, Debug)] +pub enum MyappTaskErroredOption { + Severity(::opentelemetry::logs::Severity), + Timestamp(::std::time::SystemTime), + ServerPort(i64), +} +/// A task failed with an error. +pub fn r#emit_myapp_task_errored(context: &::opentelemetry::Context, logger: &super::logger::Logger, r#error_type: upstream::attribute::ErrorType, options: impl IntoIterator) { + let mut severity = ::opentelemetry::logs::Severity::Info; + let mut timestamp = None; + let mut attributes = ::smallvec::SmallVec::<[MyappTaskErroredOption; 1]>::new(); + for option in options { + match option { + MyappTaskErroredOption::Severity(value) => severity = value, + MyappTaskErroredOption::Timestamp(value) => timestamp = Some(value), + attribute => attributes.push(attribute), + } + } + if !logger.inner().event_enabled(severity, "", Some(MyappTaskErrored::NAME)) { return; } + let _context_guard = context.clone().attach(); + let mut record = logger.inner().create_log_record(); + record.set_event_name(MyappTaskErrored::NAME); + record.set_severity_number(severity); + record.set_observed_timestamp(::std::time::SystemTime::now()); + if let Some(timestamp) = timestamp { record.set_timestamp(timestamp); } + let span = context.span(); + let span_context = span.span_context(); + if span_context.is_valid() { record.set_trace_context(span_context.trace_id(), span_context.span_id(), Some(span_context.trace_flags())); } + record.add_attribute(upstream::attribute::ErrorType::KEY, r#error_type); + for option in attributes { + match option { + MyappTaskErroredOption::ServerPort(value) => record.add_attribute("server.port", value), + MyappTaskErroredOption::Severity(_) | MyappTaskErroredOption::Timestamp(_) => continue, + } + } + logger.inner().emit(record); +} diff --git a/templates/code/rust/tests/imported_typed/expected/metric.rs b/templates/code/rust/tests/imported_typed/expected/metric.rs new file mode 100644 index 0000000..f40eba9 --- /dev/null +++ b/templates/code/rust/tests/imported_typed/expected/metric.rs @@ -0,0 +1,78 @@ +#![allow(deprecated)] +#[derive(Clone, Debug)] +pub enum MyappTaskFailedAttr { + ServerPort(i64), +} + +impl From for ::opentelemetry::KeyValue { + fn from(value: MyappTaskFailedAttr) -> Self { + match value { + MyappTaskFailedAttr::ServerPort(value) => ::opentelemetry::KeyValue::new("server.port", value), + } + } +} +/// Number of tasks that failed. +#[derive(Clone)] +pub struct MyappTaskFailed { + instrument: ::opentelemetry::metrics::Counter, +} + +impl MyappTaskFailed { + pub const NAME: &'static str = "myapp.task.failed"; + pub const UNIT: &'static str = "{task}"; + pub const DESCRIPTION: &'static str = "Number of tasks that failed."; + + pub fn new(meter: &super::meter::Meter) -> Self { + let instrument = meter.inner().u64_counter(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .build(); + Self { instrument } + } + pub fn add(&self, value: u64, r#error_type: upstream::attribute::ErrorType, r#myapp_task_id: super::attribute::MyappTaskId, options: impl IntoIterator) { + let mut attributes = ::smallvec::SmallVec::<[::opentelemetry::KeyValue; 3]>::new(); + attributes.extend([::opentelemetry::KeyValue::from(r#error_type), ::opentelemetry::KeyValue::from(r#myapp_task_id)]); + attributes.extend(options.into_iter().map(::opentelemetry::KeyValue::from)); + self.instrument.add(value, &attributes); + } +} + +impl Default for MyappTaskFailed { + fn default() -> Self { Self::new(&super::meter::Meter::default()) } +} +pub struct MyappTaskFailedObserver<'a> { + observer: &'a dyn ::opentelemetry::metrics::AsyncInstrument, +} + +impl MyappTaskFailedObserver<'_> { + pub fn observe(&self, value: u64, r#error_type: upstream::attribute::ErrorType, r#myapp_task_id: super::attribute::MyappTaskId, options: impl IntoIterator) { + let mut attributes = ::smallvec::SmallVec::<[::opentelemetry::KeyValue; 3]>::new(); + attributes.extend([::opentelemetry::KeyValue::from(r#error_type), ::opentelemetry::KeyValue::from(r#myapp_task_id)]); + attributes.extend(options.into_iter().map(::opentelemetry::KeyValue::from)); + self.observer.observe(value, &attributes); + } +} + +#[derive(Clone)] +pub struct MyappTaskFailedObservable { + _instrument: ::opentelemetry::metrics::ObservableCounter, +} + +impl MyappTaskFailedObservable { + pub const NAME: &'static str = MyappTaskFailed::NAME; + pub const UNIT: &'static str = MyappTaskFailed::UNIT; + pub const DESCRIPTION: &'static str = MyappTaskFailed::DESCRIPTION; + + pub fn new(meter: &super::meter::Meter, callback: impl Fn(MyappTaskFailedObserver<'_>) + Send + Sync + 'static) -> Self { + let instrument = meter.inner().u64_observable_counter(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .with_callback(move |observer| callback(MyappTaskFailedObserver { observer })) + .build(); + Self { _instrument: instrument } + } +} + +impl Default for MyappTaskFailedObservable { + fn default() -> Self { Self::new(&super::meter::Meter::default(), |_| {}) } +} diff --git a/templates/code/rust/tests/imported_typed/expected/mod.rs b/templates/code/rust/tests/imported_typed/expected/mod.rs index 11c3f63..b28f832 100644 --- a/templates/code/rust/tests/imported_typed/expected/mod.rs +++ b/templates/code/rust/tests/imported_typed/expected/mod.rs @@ -1,12 +1,12 @@ // Generated by OpenTelemetry Weaver. pub const SCHEMA_URL: &str = "https://example.com/schemas/myapp/1.0.0"; -pub mod myappattr; +pub mod attribute; pub mod scope; pub mod options; pub mod meter; pub mod tracer; pub mod logger; -pub mod myappevent; -pub mod myappmetric; -pub mod myappspan; +pub mod event; +pub mod metric; +pub mod trace; diff --git a/templates/code/rust/tests/imported_typed/expected/myappevent.rs b/templates/code/rust/tests/imported_typed/expected/myappevent.rs deleted file mode 100644 index 832f6bd..0000000 --- a/templates/code/rust/tests/imported_typed/expected/myappevent.rs +++ /dev/null @@ -1,41 +0,0 @@ -#![allow(deprecated)] -use ::opentelemetry::logs::LogRecord; -use ::opentelemetry::trace::TraceContextExt; - -#[derive(Clone, Debug)] -pub enum TaskErroredOption { - Severity(::opentelemetry::logs::Severity), - Timestamp(::std::time::SystemTime), - ServerPort(i64), -} -/// A task failed with an error. -pub fn r#emit_task_errored(context: &::opentelemetry::Context, logger: &super::logger::Logger, r#error_type: upstream::errorattr::TypeAttr, options: impl IntoIterator) { - let mut severity = ::opentelemetry::logs::Severity::Info; - let mut timestamp = None; - let mut attributes = ::smallvec::SmallVec::<[TaskErroredOption; 1]>::new(); - for option in options { - match option { - TaskErroredOption::Severity(value) => severity = value, - TaskErroredOption::Timestamp(value) => timestamp = Some(value), - attribute => attributes.push(attribute), - } - } - if !logger.inner().event_enabled(severity, "", Some("myapp.task.errored")) { return; } - let _context_guard = context.clone().attach(); - let mut record = logger.inner().create_log_record(); - record.set_event_name("myapp.task.errored"); - record.set_severity_number(severity); - record.set_observed_timestamp(::std::time::SystemTime::now()); - if let Some(timestamp) = timestamp { record.set_timestamp(timestamp); } - let span = context.span(); - let span_context = span.span_context(); - if span_context.is_valid() { record.set_trace_context(span_context.trace_id(), span_context.span_id(), Some(span_context.trace_flags())); } - record.add_attribute(upstream::errorattr::TypeAttr::KEY, r#error_type); - for option in attributes { - match option { - TaskErroredOption::ServerPort(value) => record.add_attribute("server.port", value), - TaskErroredOption::Severity(_) | TaskErroredOption::Timestamp(_) => continue, - } - } - logger.inner().emit(record); -} diff --git a/templates/code/rust/tests/imported_typed/expected/myappmetric.rs b/templates/code/rust/tests/imported_typed/expected/myappmetric.rs deleted file mode 100644 index cfc1605..0000000 --- a/templates/code/rust/tests/imported_typed/expected/myappmetric.rs +++ /dev/null @@ -1,70 +0,0 @@ -#![allow(deprecated)] -#[derive(Clone, Debug)] -pub enum TaskFailedCounterAttr { - ServerPort(i64), -} - -impl From for ::opentelemetry::KeyValue { - fn from(value: TaskFailedCounterAttr) -> Self { - match value { - TaskFailedCounterAttr::ServerPort(value) => ::opentelemetry::KeyValue::new("server.port", value), - } - } -} -/// Number of tasks that failed. -#[derive(Clone)] -pub struct TaskFailedCounter { - instrument: ::opentelemetry::metrics::Counter, -} - -impl TaskFailedCounter { - pub fn new(meter: &super::meter::Meter) -> Self { - let instrument = meter.inner().u64_counter("myapp.task.failed") - .with_description("Number of tasks that failed.") - .with_unit("{task}") - .build(); - Self { instrument } - } - pub fn add(&self, value: u64, r#error_type: upstream::errorattr::TypeAttr, r#myapp_task_id: super::myappattr::TaskIdAttr, options: impl IntoIterator) { - let mut attributes = ::smallvec::SmallVec::<[::opentelemetry::KeyValue; 3]>::new(); - attributes.extend([::opentelemetry::KeyValue::from(r#error_type), ::opentelemetry::KeyValue::from(r#myapp_task_id)]); - attributes.extend(options.into_iter().map(::opentelemetry::KeyValue::from)); - self.instrument.add(value, &attributes); - } -} - -impl Default for TaskFailedCounter { - fn default() -> Self { Self::new(&super::meter::Meter::default()) } -} -pub struct TaskFailedCounterObserver<'a> { - observer: &'a dyn ::opentelemetry::metrics::AsyncInstrument, -} - -impl TaskFailedCounterObserver<'_> { - pub fn observe(&self, value: u64, r#error_type: upstream::errorattr::TypeAttr, r#myapp_task_id: super::myappattr::TaskIdAttr, options: impl IntoIterator) { - let mut attributes = ::smallvec::SmallVec::<[::opentelemetry::KeyValue; 3]>::new(); - attributes.extend([::opentelemetry::KeyValue::from(r#error_type), ::opentelemetry::KeyValue::from(r#myapp_task_id)]); - attributes.extend(options.into_iter().map(::opentelemetry::KeyValue::from)); - self.observer.observe(value, &attributes); - } -} - -#[derive(Clone)] -pub struct TaskFailedObservableCounter { - _instrument: ::opentelemetry::metrics::ObservableCounter, -} - -impl TaskFailedObservableCounter { - pub fn new(meter: &super::meter::Meter, callback: impl Fn(TaskFailedCounterObserver<'_>) + Send + Sync + 'static) -> Self { - let instrument = meter.inner().u64_observable_counter("myapp.task.failed") - .with_description("Number of tasks that failed.") - .with_unit("{task}") - .with_callback(move |observer| callback(TaskFailedCounterObserver { observer })) - .build(); - Self { _instrument: instrument } - } -} - -impl Default for TaskFailedObservableCounter { - fn default() -> Self { Self::new(&super::meter::Meter::default(), |_| {}) } -} diff --git a/templates/code/rust/tests/imported_typed/expected/myappspan.rs b/templates/code/rust/tests/imported_typed/expected/trace.rs similarity index 61% rename from templates/code/rust/tests/imported_typed/expected/myappspan.rs rename to templates/code/rust/tests/imported_typed/expected/trace.rs index abd5d30..bb99ce3 100644 --- a/templates/code/rust/tests/imported_typed/expected/myappspan.rs +++ b/templates/code/rust/tests/imported_typed/expected/trace.rs @@ -1,37 +1,37 @@ #![allow(deprecated)] -use ::opentelemetry::trace::{TraceContextExt, Tracer}; -use ::std::fmt::Write; +use ::opentelemetry::trace::{TraceContextExt as _, Tracer as _}; +use ::std::fmt::Write as _; #[derive(Clone, Debug)] -pub enum TaskDispatchStartAttr { +pub enum MyappTaskDispatchStartAttr { ServerPort(i64), } -impl From for ::opentelemetry::KeyValue { - fn from(value: TaskDispatchStartAttr) -> Self { +impl From for ::opentelemetry::KeyValue { + fn from(value: MyappTaskDispatchStartAttr) -> Self { match value { - TaskDispatchStartAttr::ServerPort(value) => ::opentelemetry::KeyValue::new("server.port", value), + MyappTaskDispatchStartAttr::ServerPort(value) => ::opentelemetry::KeyValue::new("server.port", value), } } } #[derive(Clone, Debug)] -pub enum TaskDispatchAttr { +pub enum MyappTaskDispatchAttr { ServerPort(i64), } -impl From for TaskDispatchStartAttr { - fn from(value: TaskDispatchAttr) -> Self { +impl From for MyappTaskDispatchStartAttr { + fn from(value: MyappTaskDispatchAttr) -> Self { match value { - TaskDispatchAttr::ServerPort(value) => Self::ServerPort(value), + MyappTaskDispatchAttr::ServerPort(value) => Self::ServerPort(value), } } } /// Dispatch of a task. -pub struct TaskDispatchSpan { +pub struct MyappTaskDispatch { span: S, } -impl TaskDispatchSpan { +impl MyappTaskDispatch { pub fn into_context(self, parent: &::opentelemetry::Context) -> ::opentelemetry::Context where S: Send + Sync + 'static, { @@ -42,18 +42,22 @@ impl TaskDispatchSpan { pub fn end_with_timestamp(&mut self, timestamp: ::std::time::SystemTime) { ::opentelemetry::trace::Span::end_with_timestamp(&mut self.span, timestamp); } pub fn record_error(&mut self, error: &dyn ::std::error::Error) { ::opentelemetry::trace::Span::record_error(&mut self.span, error); } pub fn set_status(&mut self, status: ::opentelemetry::trace::Status) { ::opentelemetry::trace::Span::set_status(&mut self.span, status); } - pub fn set_attributes(&mut self, attributes: impl IntoIterator) { - for attribute in attributes { ::opentelemetry::trace::Span::set_attribute(&mut self.span, ::opentelemetry::KeyValue::from(TaskDispatchStartAttr::from(attribute))); } + pub fn set_attributes(&mut self, attributes: impl IntoIterator) { + for attribute in attributes { ::opentelemetry::trace::Span::set_attribute(&mut self.span, ::opentelemetry::KeyValue::from(MyappTaskDispatchStartAttr::from(attribute))); } } } -impl Default for TaskDispatchSpan { +impl MyappTaskDispatch { + pub const NAME: &'static str = "myapp.task.dispatch"; +} + +impl Default for MyappTaskDispatch { fn default() -> Self { - Self { span: super::tracer::Tracer::default().inner().start("myapp.task.dispatch") } + Self { span: super::tracer::Tracer::default().inner().start(Self::NAME) } } } -pub fn r#start_task_dispatch(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer, r#error_type: upstream::errorattr::TypeAttr, r#myapp_task_id: super::myappattr::TaskIdAttr, options: impl IntoIterator) -> TaskDispatchSpan { +pub fn r#start_myapp_task_dispatch(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer, r#error_type: upstream::attribute::ErrorType, r#myapp_task_id: super::attribute::MyappTaskId, options: impl IntoIterator) -> MyappTaskDispatch { let mut name = String::with_capacity("task ".len() + ::std::convert::AsRef::::as_ref(&r#myapp_task_id).len() + " failed with ".len() + ::std::convert::AsRef::::as_ref(&r#error_type).len()); name.push_str("task "); write!(&mut name, "{}", r#myapp_task_id).expect("writing a span name to String cannot fail"); @@ -64,5 +68,5 @@ pub fn r#start_task_dispatch(context: &::open .with_kind(::opentelemetry::trace::SpanKind::Internal) .with_attributes(attributes.into_iter().chain(options.into_iter().map(::opentelemetry::KeyValue::from))) .start_with_context(tracer.inner(), context); - TaskDispatchSpan { span } + MyappTaskDispatch { span } } diff --git a/templates/code/rust/tests/imported_typed/test.rs b/templates/code/rust/tests/imported_typed/test.rs index 54a62ed..a8614b2 100644 --- a/templates/code/rust/tests/imported_typed/test.rs +++ b/templates/code/rust/tests/imported_typed/test.rs @@ -1,32 +1,32 @@ -use generated_semconv::{logger, myappattr, myappevent, myappmetric, myappspan, tracer}; +use generated_semconv::{attribute, event, logger, metric, trace, tracer}; use opentelemetry::KeyValue; #[test] fn typed_dependencies_and_plain_imported_values_work_together() { - let error = upstream::errorattr::TypeAttr::Timeout; + let error = upstream::attribute::ErrorType::Timeout; assert_eq!( KeyValue::from(error), KeyValue::new("error.type", "timeout") ); - myappmetric::TaskFailedCounter::default().add( + metric::MyappTaskFailed::default().add( 1, error, - myappattr::TaskIdAttr::from("task-1"), - [myappmetric::TaskFailedCounterAttr::ServerPort(443)], + attribute::MyappTaskId::from("task-1"), + [metric::MyappTaskFailedAttr::ServerPort(443)], ); let context = opentelemetry::Context::new(); - myappevent::emit_task_errored( + event::emit_myapp_task_errored( &context, &logger::Logger::default(), error, - [myappevent::TaskErroredOption::ServerPort(443)], + [event::MyappTaskErroredOption::ServerPort(443)], ); - let mut span = myappspan::start_task_dispatch( + let mut span = trace::start_myapp_task_dispatch( &context, &tracer::Tracer::default(), error, - myappattr::TaskIdAttr::from("task-1"), - [myappspan::TaskDispatchStartAttr::ServerPort(443)], + attribute::MyappTaskId::from("task-1"), + [trace::MyappTaskDispatchStartAttr::ServerPort(443)], ); span.end(); } diff --git a/templates/code/rust/tests/integer_boundaries/expected/demoattr.rs b/templates/code/rust/tests/integer_boundaries/expected/attribute.rs similarity index 50% rename from templates/code/rust/tests/integer_boundaries/expected/demoattr.rs rename to templates/code/rust/tests/integer_boundaries/expected/attribute.rs index 9ab9533..1c1bd13 100644 --- a/templates/code/rust/tests/integer_boundaries/expected/demoattr.rs +++ b/templates/code/rust/tests/integer_boundaries/expected/attribute.rs @@ -1,7 +1,7 @@ // Generated by OpenTelemetry Weaver. /// Synthetic integer limits. #[derive(Debug, Clone, PartialEq, Copy)] -pub enum BoundaryAttr { +pub enum DemoBoundary { /// Lowest signed 64-bit integer. Minimum, /// Highest signed 64-bit integer. @@ -9,41 +9,41 @@ pub enum BoundaryAttr { } #[allow(deprecated)] -impl BoundaryAttr { +impl DemoBoundary { pub const KEY: &'static str = "demo.boundary"; } #[allow(deprecated)] -impl ::std::fmt::Display for BoundaryAttr { +impl ::std::fmt::Display for DemoBoundary { #[inline] fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { let value: i64 = match self { - BoundaryAttr::Minimum => -9223372036854775808, - BoundaryAttr::Maximum => 9223372036854775807, + DemoBoundary::Minimum => -9223372036854775808, + DemoBoundary::Maximum => 9223372036854775807, }; ::std::fmt::Display::fmt(&value, formatter) } } #[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { +impl From for ::opentelemetry::KeyValue { #[inline] - fn from(value: BoundaryAttr) -> Self { + fn from(value: DemoBoundary) -> Self { let value: i64 = match value { - BoundaryAttr::Minimum => -9223372036854775808, - BoundaryAttr::Maximum => 9223372036854775807, + DemoBoundary::Minimum => -9223372036854775808, + DemoBoundary::Maximum => 9223372036854775807, }; - ::opentelemetry::KeyValue::new(BoundaryAttr::KEY, value) + ::opentelemetry::KeyValue::new(DemoBoundary::KEY, value) } } #[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { +impl From for ::opentelemetry::logs::AnyValue { #[inline] - fn from(value: BoundaryAttr) -> Self { + fn from(value: DemoBoundary) -> Self { let value: i64 = match value { - BoundaryAttr::Minimum => -9223372036854775808, - BoundaryAttr::Maximum => 9223372036854775807, + DemoBoundary::Minimum => -9223372036854775808, + DemoBoundary::Maximum => 9223372036854775807, }; value.into() } diff --git a/templates/code/rust/tests/integer_boundaries/expected/mod.rs b/templates/code/rust/tests/integer_boundaries/expected/mod.rs index 19656c6..b42e861 100644 --- a/templates/code/rust/tests/integer_boundaries/expected/mod.rs +++ b/templates/code/rust/tests/integer_boundaries/expected/mod.rs @@ -1,3 +1,3 @@ // Generated by OpenTelemetry Weaver. pub const SCHEMA_URL: &str = "https://example.com/schemas/1.0.0"; -pub mod demoattr; +pub mod attribute; diff --git a/templates/code/rust/tests/integer_boundaries/test.rs b/templates/code/rust/tests/integer_boundaries/test.rs index c320747..4a849de 100644 --- a/templates/code/rust/tests/integer_boundaries/test.rs +++ b/templates/code/rust/tests/integer_boundaries/test.rs @@ -1,13 +1,13 @@ -use generated_semconv::demoattr::BoundaryAttr; +use generated_semconv::attribute::DemoBoundary; use opentelemetry::Value; #[test] fn integer_enum_preserves_signed_64_bit_limits() { assert_eq!( - ::opentelemetry::KeyValue::from(BoundaryAttr::Minimum).value, + ::opentelemetry::KeyValue::from(DemoBoundary::Minimum).value, Value::I64(i64::MIN) ); assert_eq!( - ::opentelemetry::KeyValue::from(BoundaryAttr::Maximum).value, + ::opentelemetry::KeyValue::from(DemoBoundary::Maximum).value, Value::I64(i64::MAX) ); } diff --git a/templates/code/rust/tests/literal_escaping/expected/demoattr.rs b/templates/code/rust/tests/literal_escaping/expected/attribute.rs similarity index 57% rename from templates/code/rust/tests/literal_escaping/expected/demoattr.rs rename to templates/code/rust/tests/literal_escaping/expected/attribute.rs index 1a5a546..64360e0 100644 --- a/templates/code/rust/tests/literal_escaping/expected/demoattr.rs +++ b/templates/code/rust/tests/literal_escaping/expected/attribute.rs @@ -1,7 +1,7 @@ // Generated by OpenTelemetry Weaver. /// Literal escape sequences. #[derive(Debug, Clone, PartialEq, Copy)] -pub enum LiteralAttr { +pub enum DemoLiteral { /// Literal escape sequences. Literal, /// Actual controls and escaped text. @@ -9,23 +9,23 @@ pub enum LiteralAttr { } #[allow(deprecated)] -impl LiteralAttr { +impl DemoLiteral { pub const KEY: &'static str = "demo.literal"; } #[allow(deprecated)] -impl AsRef for LiteralAttr { +impl AsRef for DemoLiteral { #[inline] fn as_ref(&self) -> &str { match self { - LiteralAttr::Literal => "backspace\\b formfeed\\f unicode\\u1234 doubled\\\\b tripled\\\\\\u0000", - LiteralAttr::Controls => "backspace\u{0008} formfeed\u{000c} unicode\u{0001} slash\\b", + DemoLiteral::Literal => "backspace\\b formfeed\\f unicode\\u1234 doubled\\\\b tripled\\\\\\u0000", + DemoLiteral::Controls => "backspace\u{0008} formfeed\u{000c} unicode\u{0001} slash\\b", } } } #[allow(deprecated)] -impl ::std::fmt::Display for LiteralAttr { +impl ::std::fmt::Display for DemoLiteral { #[inline] fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { formatter.write_str(self.as_ref()) @@ -33,24 +33,24 @@ impl ::std::fmt::Display for LiteralAttr { } #[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { +impl From for ::opentelemetry::KeyValue { #[inline] - fn from(value: LiteralAttr) -> Self { + fn from(value: DemoLiteral) -> Self { let value: &'static str = match value { - LiteralAttr::Literal => "backspace\\b formfeed\\f unicode\\u1234 doubled\\\\b tripled\\\\\\u0000", - LiteralAttr::Controls => "backspace\u{0008} formfeed\u{000c} unicode\u{0001} slash\\b", + DemoLiteral::Literal => "backspace\\b formfeed\\f unicode\\u1234 doubled\\\\b tripled\\\\\\u0000", + DemoLiteral::Controls => "backspace\u{0008} formfeed\u{000c} unicode\u{0001} slash\\b", }; - ::opentelemetry::KeyValue::new(LiteralAttr::KEY, value) + ::opentelemetry::KeyValue::new(DemoLiteral::KEY, value) } } #[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { +impl From for ::opentelemetry::logs::AnyValue { #[inline] - fn from(value: LiteralAttr) -> Self { + fn from(value: DemoLiteral) -> Self { let value: &'static str = match value { - LiteralAttr::Literal => "backspace\\b formfeed\\f unicode\\u1234 doubled\\\\b tripled\\\\\\u0000", - LiteralAttr::Controls => "backspace\u{0008} formfeed\u{000c} unicode\u{0001} slash\\b", + DemoLiteral::Literal => "backspace\\b formfeed\\f unicode\\u1234 doubled\\\\b tripled\\\\\\u0000", + DemoLiteral::Controls => "backspace\u{0008} formfeed\u{000c} unicode\u{0001} slash\\b", }; value.into() } diff --git a/templates/code/rust/tests/literal_escaping/expected/demometric.rs b/templates/code/rust/tests/literal_escaping/expected/demometric.rs deleted file mode 100644 index 1b3a78b..0000000 --- a/templates/code/rust/tests/literal_escaping/expected/demometric.rs +++ /dev/null @@ -1,54 +0,0 @@ -#![allow(deprecated)] -/// literal \b \f \u1234 -#[derive(Clone)] -pub struct LiteralCountCounter { - instrument: ::opentelemetry::metrics::Counter, -} - -impl LiteralCountCounter { - pub fn new(meter: &super::meter::Meter) -> Self { - let instrument = meter.inner().u64_counter("demo.literal.count") - .with_description("literal \\b \\f \\u1234") - .with_unit("literal\\b\\u1234") - .build(); - Self { instrument } - } - pub fn add(&self, value: u64, r#demo_literal: super::demoattr::LiteralAttr) { - let attributes = [::opentelemetry::KeyValue::from(r#demo_literal)]; - self.instrument.add(value, &attributes); - } -} - -impl Default for LiteralCountCounter { - fn default() -> Self { Self::new(&super::meter::Meter::default()) } -} -pub struct LiteralCountCounterObserver<'a> { - observer: &'a dyn ::opentelemetry::metrics::AsyncInstrument, -} - -impl LiteralCountCounterObserver<'_> { - pub fn observe(&self, value: u64, r#demo_literal: super::demoattr::LiteralAttr) { - let attributes = [::opentelemetry::KeyValue::from(r#demo_literal)]; - self.observer.observe(value, &attributes); - } -} - -#[derive(Clone)] -pub struct LiteralCountObservableCounter { - _instrument: ::opentelemetry::metrics::ObservableCounter, -} - -impl LiteralCountObservableCounter { - pub fn new(meter: &super::meter::Meter, callback: impl Fn(LiteralCountCounterObserver<'_>) + Send + Sync + 'static) -> Self { - let instrument = meter.inner().u64_observable_counter("demo.literal.count") - .with_description("literal \\b \\f \\u1234") - .with_unit("literal\\b\\u1234") - .with_callback(move |observer| callback(LiteralCountCounterObserver { observer })) - .build(); - Self { _instrument: instrument } - } -} - -impl Default for LiteralCountObservableCounter { - fn default() -> Self { Self::new(&super::meter::Meter::default(), |_| {}) } -} diff --git a/templates/code/rust/tests/literal_escaping/expected/metric.rs b/templates/code/rust/tests/literal_escaping/expected/metric.rs new file mode 100644 index 0000000..f988321 --- /dev/null +++ b/templates/code/rust/tests/literal_escaping/expected/metric.rs @@ -0,0 +1,62 @@ +#![allow(deprecated)] +/// literal \b \f \u1234 +#[derive(Clone)] +pub struct DemoLiteralCount { + instrument: ::opentelemetry::metrics::Counter, +} + +impl DemoLiteralCount { + pub const NAME: &'static str = "demo.literal.count"; + pub const UNIT: &'static str = "literal\\b\\u1234"; + pub const DESCRIPTION: &'static str = "literal \\b \\f \\u1234"; + + pub fn new(meter: &super::meter::Meter) -> Self { + let instrument = meter.inner().u64_counter(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .build(); + Self { instrument } + } + pub fn add(&self, value: u64, r#demo_literal: super::attribute::DemoLiteral) { + let attributes = [::opentelemetry::KeyValue::from(r#demo_literal)]; + self.instrument.add(value, &attributes); + } +} + +impl Default for DemoLiteralCount { + fn default() -> Self { Self::new(&super::meter::Meter::default()) } +} +pub struct DemoLiteralCountObserver<'a> { + observer: &'a dyn ::opentelemetry::metrics::AsyncInstrument, +} + +impl DemoLiteralCountObserver<'_> { + pub fn observe(&self, value: u64, r#demo_literal: super::attribute::DemoLiteral) { + let attributes = [::opentelemetry::KeyValue::from(r#demo_literal)]; + self.observer.observe(value, &attributes); + } +} + +#[derive(Clone)] +pub struct DemoLiteralCountObservable { + _instrument: ::opentelemetry::metrics::ObservableCounter, +} + +impl DemoLiteralCountObservable { + pub const NAME: &'static str = DemoLiteralCount::NAME; + pub const UNIT: &'static str = DemoLiteralCount::UNIT; + pub const DESCRIPTION: &'static str = DemoLiteralCount::DESCRIPTION; + + pub fn new(meter: &super::meter::Meter, callback: impl Fn(DemoLiteralCountObserver<'_>) + Send + Sync + 'static) -> Self { + let instrument = meter.inner().u64_observable_counter(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .with_callback(move |observer| callback(DemoLiteralCountObserver { observer })) + .build(); + Self { _instrument: instrument } + } +} + +impl Default for DemoLiteralCountObservable { + fn default() -> Self { Self::new(&super::meter::Meter::default(), |_| {}) } +} diff --git a/templates/code/rust/tests/literal_escaping/expected/mod.rs b/templates/code/rust/tests/literal_escaping/expected/mod.rs index 86079ee..7b7f9c0 100644 --- a/templates/code/rust/tests/literal_escaping/expected/mod.rs +++ b/templates/code/rust/tests/literal_escaping/expected/mod.rs @@ -1,8 +1,8 @@ // Generated by OpenTelemetry Weaver. pub const SCHEMA_URL: &str = "https://example.com/schemas/escaping/1.0.0"; -pub mod demoattr; +pub mod attribute; pub mod scope; pub mod options; pub mod meter; -pub mod demometric; +pub mod metric; diff --git a/templates/code/rust/tests/literal_escaping/test.rs b/templates/code/rust/tests/literal_escaping/test.rs index a8cecfc..193f4dc 100644 --- a/templates/code/rust/tests/literal_escaping/test.rs +++ b/templates/code/rust/tests/literal_escaping/test.rs @@ -1,16 +1,16 @@ -use generated_semconv::demoattr::LiteralAttr; +use generated_semconv::attribute::DemoLiteral; use generated_semconv::options::InstrumentationOptions; -use generated_semconv::{demometric::LiteralCountCounter, meter::Meter}; +use generated_semconv::{metric::DemoLiteralCount, meter::Meter}; use opentelemetry::Value; use opentelemetry_sdk::metrics::{InMemoryMetricExporter, PeriodicReader, SdkMeterProvider}; #[test] fn literal_backslashes_and_actual_control_characters_are_distinct() { assert_eq!( - ::opentelemetry::KeyValue::from(LiteralAttr::Literal).value, + ::opentelemetry::KeyValue::from(DemoLiteral::Literal).value, Value::String(r"backspace\b formfeed\f unicode\u1234 doubled\\b tripled\\\u0000".into()) ); assert_eq!( - ::opentelemetry::KeyValue::from(LiteralAttr::Controls).value, + ::opentelemetry::KeyValue::from(DemoLiteral::Controls).value, Value::String("backspace\u{0008} formfeed\u{000c} unicode\u{0001} slash\\b".into()) ); } @@ -21,8 +21,8 @@ fn signal_metadata_preserves_literal_backslash_sequences() { let provider = SdkMeterProvider::builder() .with_reader(PeriodicReader::builder(exporter.clone()).build()) .build(); - LiteralCountCounter::new(&Meter::new(&provider, InstrumentationOptions::default())) - .add(1, LiteralAttr::Literal); + DemoLiteralCount::new(&Meter::new(&provider, InstrumentationOptions::default())) + .add(1, DemoLiteral::Literal); provider.force_flush().unwrap(); let exported = exporter.get_finished_metrics().unwrap(); let scope = exported[0].scope_metrics().next().unwrap(); @@ -42,3 +42,9 @@ fn signal_metadata_preserves_literal_backslash_sequences() { assert_eq!(metric.description(), r"literal \b \f \u1234"); assert_eq!(metric.unit(), r"literal\b\u1234"); } + +#[test] +fn metadata_constants_preserve_literal_backslash_sequences() { + assert_eq!(DemoLiteralCount::UNIT, r"literal\b\u1234"); + assert_eq!(DemoLiteralCount::DESCRIPTION, r"literal \b \f \u1234"); +} diff --git a/templates/code/rust/tests/metrics/compile-fail/missing_required.rs b/templates/code/rust/tests/metrics/compile-fail/missing_required.rs index a9918a9..81e41b6 100644 --- a/templates/code/rust/tests/metrics/compile-fail/missing_required.rs +++ b/templates/code/rust/tests/metrics/compile-fail/missing_required.rs @@ -1,5 +1,5 @@ -use generated_semconv::{authattr, authmetric}; +use generated_semconv::{attribute, metric}; fn main() { - authmetric::AttemptsCounter::default().add(1, authattr::MethodAttr::Password); + metric::AuthAttempts::default().add(1, attribute::AuthMethod::Password); } diff --git a/templates/code/rust/tests/metrics/compile-fail/signed_counter.rs b/templates/code/rust/tests/metrics/compile-fail/signed_counter.rs index 6826e64..3b92860 100644 --- a/templates/code/rust/tests/metrics/compile-fail/signed_counter.rs +++ b/templates/code/rust/tests/metrics/compile-fail/signed_counter.rs @@ -1,5 +1,5 @@ -use generated_semconv::myappmetric; +use generated_semconv::metric; fn main() { - myappmetric::TaskStartedCounter::default().add(-1_i64, []); + metric::MyappTaskStarted::default().add(-1_i64, []); } diff --git a/templates/code/rust/tests/metrics/compile-fail/unrelated_optional.rs b/templates/code/rust/tests/metrics/compile-fail/unrelated_optional.rs index 667cb94..79a5d49 100644 --- a/templates/code/rust/tests/metrics/compile-fail/unrelated_optional.rs +++ b/templates/code/rust/tests/metrics/compile-fail/unrelated_optional.rs @@ -1,5 +1,5 @@ -use generated_semconv::{authattr, myappmetric}; +use generated_semconv::{attribute, metric}; fn main() { - let _ = myappmetric::TaskDurationHistogramAttr::Success(authattr::SuccessAttr::from(true)); + let _ = metric::MyappTaskDurationAttr::Success(attribute::AuthSuccess::from(true)); } diff --git a/templates/code/rust/tests/metrics/compile-fail/wrong_required_type.expected-error.txt b/templates/code/rust/tests/metrics/compile-fail/wrong_required_type.expected-error.txt index f8fceb8..b689f72 100644 --- a/templates/code/rust/tests/metrics/compile-fail/wrong_required_type.expected-error.txt +++ b/templates/code/rust/tests/metrics/compile-fail/wrong_required_type.expected-error.txt @@ -1 +1 @@ -expected `TaskIdAttr`, found `TaskStateAttr` +expected `MyappTaskId`, found `MyappTaskState` diff --git a/templates/code/rust/tests/metrics/compile-fail/wrong_required_type.rs b/templates/code/rust/tests/metrics/compile-fail/wrong_required_type.rs index dfcf2cd..d891e19 100644 --- a/templates/code/rust/tests/metrics/compile-fail/wrong_required_type.rs +++ b/templates/code/rust/tests/metrics/compile-fail/wrong_required_type.rs @@ -1,5 +1,5 @@ -use generated_semconv::{myappattr, myappmetric}; +use generated_semconv::{attribute, metric}; fn main() { - myappmetric::TaskDurationHistogram::default().record(0.1, myappattr::TaskStateAttr::Done, []); + metric::MyappTaskDuration::default().record(0.1, attribute::MyappTaskState::Done, []); } diff --git a/templates/code/rust/tests/metrics/expected/attribute.rs b/templates/code/rust/tests/metrics/expected/attribute.rs new file mode 100644 index 0000000..733a24a --- /dev/null +++ b/templates/code/rust/tests/metrics/expected/attribute.rs @@ -0,0 +1,220 @@ +// Generated by OpenTelemetry Weaver. +/// How the user was authenticated. +#[derive(Debug, Clone, PartialEq, Copy)] +pub enum AuthMethod { + /// A password was checked. + Password, + /// A bearer token was checked. + Token, +} + +#[allow(deprecated)] +impl AuthMethod { + pub const KEY: &'static str = "auth.method"; +} + +#[allow(deprecated)] +impl AsRef for AuthMethod { + #[inline] + fn as_ref(&self) -> &str { + match self { + AuthMethod::Password => "password", + AuthMethod::Token => "token", + } + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for AuthMethod { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str(self.as_ref()) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: AuthMethod) -> Self { + let value: &'static str = match value { + AuthMethod::Password => "password", + AuthMethod::Token => "token", + }; + ::opentelemetry::KeyValue::new(AuthMethod::KEY, value) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: AuthMethod) -> Self { + let value: &'static str = match value { + AuthMethod::Password => "password", + AuthMethod::Token => "token", + }; + value.into() + } +} + +/// Whether the attempt succeeded. +#[derive(Debug, Clone, PartialEq, Copy)] +pub struct AuthSuccess(bool); + +#[allow(deprecated)] +impl AuthSuccess { + pub const KEY: &'static str = "auth.success"; +} + +#[allow(deprecated)] +impl From for AuthSuccess { + #[inline] + fn from(value: bool) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for AuthSuccess { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + ::std::fmt::Display::fmt(&self.0, formatter) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: AuthSuccess) -> Self { + ::opentelemetry::KeyValue::new(AuthSuccess::KEY, value.0) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: AuthSuccess) -> Self { + value.0.into() + } +} + +/// Unique identifier of the task. +#[derive(Debug, Clone, PartialEq)] +pub struct MyappTaskId(::opentelemetry::StringValue); + +#[allow(deprecated)] +impl MyappTaskId { + pub const KEY: &'static str = "myapp.task.id"; +} + +#[allow(deprecated)] +impl From<::opentelemetry::StringValue> for MyappTaskId { + #[inline] + fn from(value: ::opentelemetry::StringValue) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl From for MyappTaskId { + #[inline] + fn from(value: String) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl From<&'static str> for MyappTaskId { + #[inline] + fn from(value: &'static str) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl AsRef for MyappTaskId { + #[inline] + fn as_ref(&self) -> &str { + self.0.as_str() + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for MyappTaskId { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str(self.as_ref()) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: MyappTaskId) -> Self { + ::opentelemetry::KeyValue::new(MyappTaskId::KEY, value.0) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: MyappTaskId) -> Self { + value.0.into() + } +} + +/// Current state of the task. +#[derive(Debug, Clone, PartialEq, Copy)] +pub enum MyappTaskState { + /// The task is waiting to run. + Queued, + /// The task finished. + Done, +} + +#[allow(deprecated)] +impl MyappTaskState { + pub const KEY: &'static str = "myapp.task.state"; +} + +#[allow(deprecated)] +impl AsRef for MyappTaskState { + #[inline] + fn as_ref(&self) -> &str { + match self { + MyappTaskState::Queued => "queued", + MyappTaskState::Done => "done", + } + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for MyappTaskState { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str(self.as_ref()) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: MyappTaskState) -> Self { + let value: &'static str = match value { + MyappTaskState::Queued => "queued", + MyappTaskState::Done => "done", + }; + ::opentelemetry::KeyValue::new(MyappTaskState::KEY, value) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: MyappTaskState) -> Self { + let value: &'static str = match value { + MyappTaskState::Queued => "queued", + MyappTaskState::Done => "done", + }; + value.into() + } +} diff --git a/templates/code/rust/tests/metrics/expected/authattr.rs b/templates/code/rust/tests/metrics/expected/authattr.rs deleted file mode 100644 index ff9bba6..0000000 --- a/templates/code/rust/tests/metrics/expected/authattr.rs +++ /dev/null @@ -1,98 +0,0 @@ -// Generated by OpenTelemetry Weaver. -/// How the user was authenticated. -#[derive(Debug, Clone, PartialEq, Copy)] -pub enum MethodAttr { - /// A password was checked. - Password, - /// A bearer token was checked. - Token, -} - -#[allow(deprecated)] -impl MethodAttr { - pub const KEY: &'static str = "auth.method"; -} - -#[allow(deprecated)] -impl AsRef for MethodAttr { - #[inline] - fn as_ref(&self) -> &str { - match self { - MethodAttr::Password => "password", - MethodAttr::Token => "token", - } - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for MethodAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str(self.as_ref()) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: MethodAttr) -> Self { - let value: &'static str = match value { - MethodAttr::Password => "password", - MethodAttr::Token => "token", - }; - ::opentelemetry::KeyValue::new(MethodAttr::KEY, value) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: MethodAttr) -> Self { - let value: &'static str = match value { - MethodAttr::Password => "password", - MethodAttr::Token => "token", - }; - value.into() - } -} - -/// Whether the attempt succeeded. -#[derive(Debug, Clone, PartialEq, Copy)] -pub struct SuccessAttr(bool); - -#[allow(deprecated)] -impl SuccessAttr { - pub const KEY: &'static str = "auth.success"; -} - -#[allow(deprecated)] -impl From for SuccessAttr { - #[inline] - fn from(value: bool) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for SuccessAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - ::std::fmt::Display::fmt(&self.0, formatter) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: SuccessAttr) -> Self { - ::opentelemetry::KeyValue::new(SuccessAttr::KEY, value.0) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: SuccessAttr) -> Self { - value.0.into() - } -} diff --git a/templates/code/rust/tests/metrics/expected/authmetric.rs b/templates/code/rust/tests/metrics/expected/authmetric.rs deleted file mode 100644 index 7a2580e..0000000 --- a/templates/code/rust/tests/metrics/expected/authmetric.rs +++ /dev/null @@ -1,54 +0,0 @@ -#![allow(deprecated)] -/// Number of authentication attempts. -#[derive(Clone)] -pub struct AttemptsCounter { - instrument: ::opentelemetry::metrics::Counter, -} - -impl AttemptsCounter { - pub fn new(meter: &super::meter::Meter) -> Self { - let instrument = meter.inner().u64_counter("auth.attempts") - .with_description("Number of authentication attempts.") - .with_unit("{attempt}") - .build(); - Self { instrument } - } - pub fn add(&self, value: u64, r#auth_method: super::authattr::MethodAttr, r#auth_success: super::authattr::SuccessAttr) { - let attributes = [::opentelemetry::KeyValue::from(r#auth_method), ::opentelemetry::KeyValue::from(r#auth_success)]; - self.instrument.add(value, &attributes); - } -} - -impl Default for AttemptsCounter { - fn default() -> Self { Self::new(&super::meter::Meter::default()) } -} -pub struct AttemptsCounterObserver<'a> { - observer: &'a dyn ::opentelemetry::metrics::AsyncInstrument, -} - -impl AttemptsCounterObserver<'_> { - pub fn observe(&self, value: u64, r#auth_method: super::authattr::MethodAttr, r#auth_success: super::authattr::SuccessAttr) { - let attributes = [::opentelemetry::KeyValue::from(r#auth_method), ::opentelemetry::KeyValue::from(r#auth_success)]; - self.observer.observe(value, &attributes); - } -} - -#[derive(Clone)] -pub struct AttemptsObservableCounter { - _instrument: ::opentelemetry::metrics::ObservableCounter, -} - -impl AttemptsObservableCounter { - pub fn new(meter: &super::meter::Meter, callback: impl Fn(AttemptsCounterObserver<'_>) + Send + Sync + 'static) -> Self { - let instrument = meter.inner().u64_observable_counter("auth.attempts") - .with_description("Number of authentication attempts.") - .with_unit("{attempt}") - .with_callback(move |observer| callback(AttemptsCounterObserver { observer })) - .build(); - Self { _instrument: instrument } - } -} - -impl Default for AttemptsObservableCounter { - fn default() -> Self { Self::new(&super::meter::Meter::default(), |_| {}) } -} diff --git a/templates/code/rust/tests/metrics/expected/metric.rs b/templates/code/rust/tests/metrics/expected/metric.rs new file mode 100644 index 0000000..14e1ff2 --- /dev/null +++ b/templates/code/rust/tests/metrics/expected/metric.rs @@ -0,0 +1,614 @@ +#![allow(deprecated)] +/// Number of authentication attempts. +#[derive(Clone)] +pub struct AuthAttempts { + instrument: ::opentelemetry::metrics::Counter, +} + +impl AuthAttempts { + pub const NAME: &'static str = "auth.attempts"; + pub const UNIT: &'static str = "{attempt}"; + pub const DESCRIPTION: &'static str = "Number of authentication attempts."; + + pub fn new(meter: &super::meter::Meter) -> Self { + let instrument = meter.inner().u64_counter(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .build(); + Self { instrument } + } + pub fn add(&self, value: u64, r#auth_method: super::attribute::AuthMethod, r#auth_success: super::attribute::AuthSuccess) { + let attributes = [::opentelemetry::KeyValue::from(r#auth_method), ::opentelemetry::KeyValue::from(r#auth_success)]; + self.instrument.add(value, &attributes); + } +} + +impl Default for AuthAttempts { + fn default() -> Self { Self::new(&super::meter::Meter::default()) } +} +pub struct AuthAttemptsObserver<'a> { + observer: &'a dyn ::opentelemetry::metrics::AsyncInstrument, +} + +impl AuthAttemptsObserver<'_> { + pub fn observe(&self, value: u64, r#auth_method: super::attribute::AuthMethod, r#auth_success: super::attribute::AuthSuccess) { + let attributes = [::opentelemetry::KeyValue::from(r#auth_method), ::opentelemetry::KeyValue::from(r#auth_success)]; + self.observer.observe(value, &attributes); + } +} + +#[derive(Clone)] +pub struct AuthAttemptsObservable { + _instrument: ::opentelemetry::metrics::ObservableCounter, +} + +impl AuthAttemptsObservable { + pub const NAME: &'static str = AuthAttempts::NAME; + pub const UNIT: &'static str = AuthAttempts::UNIT; + pub const DESCRIPTION: &'static str = AuthAttempts::DESCRIPTION; + + pub fn new(meter: &super::meter::Meter, callback: impl Fn(AuthAttemptsObserver<'_>) + Send + Sync + 'static) -> Self { + let instrument = meter.inner().u64_observable_counter(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .with_callback(move |observer| callback(AuthAttemptsObserver { observer })) + .build(); + Self { _instrument: instrument } + } +} + +impl Default for AuthAttemptsObservable { + fn default() -> Self { Self::new(&super::meter::Meter::default(), |_| {}) } +} +/// Number of tasks waiting in the queue. +#[deprecated(note = "Replaced by `myapp.task.active`.")] +#[derive(Clone)] +pub struct MyappQueueDepth { + instrument: ::opentelemetry::metrics::Gauge, +} + +impl MyappQueueDepth { + pub const NAME: &'static str = "myapp.queue.depth"; + pub const UNIT: &'static str = "{task}"; + pub const DESCRIPTION: &'static str = "Number of tasks waiting in the queue."; + + pub fn new(meter: &super::meter::Meter) -> Self { + let instrument = meter.inner().i64_gauge(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .build(); + Self { instrument } + } + pub fn record(&self, value: i64) { + let attributes = []; + self.instrument.record(value, &attributes); + } +} + +impl Default for MyappQueueDepth { + fn default() -> Self { Self::new(&super::meter::Meter::default()) } +} +pub struct MyappQueueDepthObserver<'a> { + observer: &'a dyn ::opentelemetry::metrics::AsyncInstrument, +} + +impl MyappQueueDepthObserver<'_> { + pub fn observe(&self, value: i64) { + let attributes = []; + self.observer.observe(value, &attributes); + } +} +#[deprecated(note = "Replaced by `myapp.task.active`.")] +#[derive(Clone)] +pub struct MyappQueueDepthObservable { + _instrument: ::opentelemetry::metrics::ObservableGauge, +} + +impl MyappQueueDepthObservable { + pub const NAME: &'static str = MyappQueueDepth::NAME; + pub const UNIT: &'static str = MyappQueueDepth::UNIT; + pub const DESCRIPTION: &'static str = MyappQueueDepth::DESCRIPTION; + + pub fn new(meter: &super::meter::Meter, callback: impl Fn(MyappQueueDepthObserver<'_>) + Send + Sync + 'static) -> Self { + let instrument = meter.inner().i64_observable_gauge(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .with_callback(move |observer| callback(MyappQueueDepthObserver { observer })) + .build(); + Self { _instrument: instrument } + } +} + +impl Default for MyappQueueDepthObservable { + fn default() -> Self { Self::new(&super::meter::Meter::default(), |_| {}) } +} +/// Number of tasks currently running. +#[derive(Clone)] +pub struct MyappTaskActive { + instrument: ::opentelemetry::metrics::UpDownCounter, +} + +impl MyappTaskActive { + pub const NAME: &'static str = "myapp.task.active"; + pub const UNIT: &'static str = "{task}"; + pub const DESCRIPTION: &'static str = "Number of tasks currently running."; + + pub fn new(meter: &super::meter::Meter) -> Self { + let instrument = meter.inner().i64_up_down_counter(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .build(); + Self { instrument } + } + pub fn add(&self, value: i64, r#myapp_task_state: super::attribute::MyappTaskState) { + let attributes = [::opentelemetry::KeyValue::from(r#myapp_task_state)]; + self.instrument.add(value, &attributes); + } +} + +impl Default for MyappTaskActive { + fn default() -> Self { Self::new(&super::meter::Meter::default()) } +} +pub struct MyappTaskActiveObserver<'a> { + observer: &'a dyn ::opentelemetry::metrics::AsyncInstrument, +} + +impl MyappTaskActiveObserver<'_> { + pub fn observe(&self, value: i64, r#myapp_task_state: super::attribute::MyappTaskState) { + let attributes = [::opentelemetry::KeyValue::from(r#myapp_task_state)]; + self.observer.observe(value, &attributes); + } +} + +#[derive(Clone)] +pub struct MyappTaskActiveObservable { + _instrument: ::opentelemetry::metrics::ObservableUpDownCounter, +} + +impl MyappTaskActiveObservable { + pub const NAME: &'static str = MyappTaskActive::NAME; + pub const UNIT: &'static str = MyappTaskActive::UNIT; + pub const DESCRIPTION: &'static str = MyappTaskActive::DESCRIPTION; + + pub fn new(meter: &super::meter::Meter, callback: impl Fn(MyappTaskActiveObserver<'_>) + Send + Sync + 'static) -> Self { + let instrument = meter.inner().i64_observable_up_down_counter(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .with_callback(move |observer| callback(MyappTaskActiveObserver { observer })) + .build(); + Self { _instrument: instrument } + } +} + +impl Default for MyappTaskActiveObservable { + fn default() -> Self { Self::new(&super::meter::Meter::default(), |_| {}) } +} +#[derive(Clone, Debug)] +pub enum MyappTaskDurationAttr { + /// Opt-in: the convention records it only when a user asks for it. + Method(super::attribute::AuthMethod), + /// Conditionally required: If the task reached a final state. + TaskState(super::attribute::MyappTaskState), +} + +impl From for ::opentelemetry::KeyValue { + fn from(value: MyappTaskDurationAttr) -> Self { + match value { + MyappTaskDurationAttr::Method(value) => ::opentelemetry::KeyValue::from(value), + MyappTaskDurationAttr::TaskState(value) => ::opentelemetry::KeyValue::from(value), + } + } +} +/// Time a task took from start to finish. +/// +/// Measured by the worker that ran the task. +#[derive(Clone)] +pub struct MyappTaskDuration { + instrument: ::opentelemetry::metrics::Histogram, +} + +impl MyappTaskDuration { + pub const NAME: &'static str = "myapp.task.duration"; + pub const UNIT: &'static str = "s"; + pub const DESCRIPTION: &'static str = "Time a task took from start to finish."; + + pub fn new(meter: &super::meter::Meter) -> Self { + let instrument = meter.inner().f64_histogram(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .with_boundaries(vec![0_f64, 0.005_f64, 0.01_f64, 0.1_f64, 1_f64, 10_f64]) + .build(); + Self { instrument } + } + pub fn record(&self, value: f64, r#myapp_task_id: super::attribute::MyappTaskId, options: impl IntoIterator) { + let mut attributes = ::smallvec::SmallVec::<[::opentelemetry::KeyValue; 3]>::new(); + attributes.extend([::opentelemetry::KeyValue::from(r#myapp_task_id)]); + attributes.extend(options.into_iter().map(::opentelemetry::KeyValue::from)); + self.instrument.record(value, &attributes); + } +} + +impl Default for MyappTaskDuration { + fn default() -> Self { Self::new(&super::meter::Meter::default()) } +} +/// Fractional active task adjustment. +#[derive(Clone)] +pub struct MyappTaskFloatActive { + instrument: ::opentelemetry::metrics::UpDownCounter, +} + +impl MyappTaskFloatActive { + pub const NAME: &'static str = "myapp.task.float.active"; + pub const UNIT: &'static str = "{task}"; + pub const DESCRIPTION: &'static str = "Fractional active task adjustment."; + + pub fn new(meter: &super::meter::Meter) -> Self { + let instrument = meter.inner().f64_up_down_counter(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .build(); + Self { instrument } + } + pub fn add(&self, value: f64) { + let attributes = []; + self.instrument.add(value, &attributes); + } +} + +impl Default for MyappTaskFloatActive { + fn default() -> Self { Self::new(&super::meter::Meter::default()) } +} +pub struct MyappTaskFloatActiveObserver<'a> { + observer: &'a dyn ::opentelemetry::metrics::AsyncInstrument, +} + +impl MyappTaskFloatActiveObserver<'_> { + pub fn observe(&self, value: f64) { + let attributes = []; + self.observer.observe(value, &attributes); + } +} + +#[derive(Clone)] +pub struct MyappTaskFloatActiveObservable { + _instrument: ::opentelemetry::metrics::ObservableUpDownCounter, +} + +impl MyappTaskFloatActiveObservable { + pub const NAME: &'static str = MyappTaskFloatActive::NAME; + pub const UNIT: &'static str = MyappTaskFloatActive::UNIT; + pub const DESCRIPTION: &'static str = MyappTaskFloatActive::DESCRIPTION; + + pub fn new(meter: &super::meter::Meter, callback: impl Fn(MyappTaskFloatActiveObserver<'_>) + Send + Sync + 'static) -> Self { + let instrument = meter.inner().f64_observable_up_down_counter(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .with_callback(move |observer| callback(MyappTaskFloatActiveObserver { observer })) + .build(); + Self { _instrument: instrument } + } +} + +impl Default for MyappTaskFloatActiveObservable { + fn default() -> Self { Self::new(&super::meter::Meter::default(), |_| {}) } +} +/// Fractional queue depth. +#[derive(Clone)] +pub struct MyappTaskFloatDepth { + instrument: ::opentelemetry::metrics::Gauge, +} + +impl MyappTaskFloatDepth { + pub const NAME: &'static str = "myapp.task.float.depth"; + pub const UNIT: &'static str = "{task}"; + pub const DESCRIPTION: &'static str = "Fractional queue depth."; + + pub fn new(meter: &super::meter::Meter) -> Self { + let instrument = meter.inner().f64_gauge(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .build(); + Self { instrument } + } + pub fn record(&self, value: f64) { + let attributes = []; + self.instrument.record(value, &attributes); + } +} + +impl Default for MyappTaskFloatDepth { + fn default() -> Self { Self::new(&super::meter::Meter::default()) } +} +pub struct MyappTaskFloatDepthObserver<'a> { + observer: &'a dyn ::opentelemetry::metrics::AsyncInstrument, +} + +impl MyappTaskFloatDepthObserver<'_> { + pub fn observe(&self, value: f64) { + let attributes = []; + self.observer.observe(value, &attributes); + } +} + +#[derive(Clone)] +pub struct MyappTaskFloatDepthObservable { + _instrument: ::opentelemetry::metrics::ObservableGauge, +} + +impl MyappTaskFloatDepthObservable { + pub const NAME: &'static str = MyappTaskFloatDepth::NAME; + pub const UNIT: &'static str = MyappTaskFloatDepth::UNIT; + pub const DESCRIPTION: &'static str = MyappTaskFloatDepth::DESCRIPTION; + + pub fn new(meter: &super::meter::Meter, callback: impl Fn(MyappTaskFloatDepthObserver<'_>) + Send + Sync + 'static) -> Self { + let instrument = meter.inner().f64_observable_gauge(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .with_callback(move |observer| callback(MyappTaskFloatDepthObserver { observer })) + .build(); + Self { _instrument: instrument } + } +} + +impl Default for MyappTaskFloatDepthObservable { + fn default() -> Self { Self::new(&super::meter::Meter::default(), |_| {}) } +} +/// Fractional tasks started. +#[derive(Clone)] +pub struct MyappTaskFloatStarted { + instrument: ::opentelemetry::metrics::Counter, +} + +impl MyappTaskFloatStarted { + pub const NAME: &'static str = "myapp.task.float.started"; + pub const UNIT: &'static str = "{task}"; + pub const DESCRIPTION: &'static str = "Fractional tasks started."; + + pub fn new(meter: &super::meter::Meter) -> Self { + let instrument = meter.inner().f64_counter(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .build(); + Self { instrument } + } + pub fn add(&self, value: f64) { + let attributes = []; + self.instrument.add(value, &attributes); + } +} + +impl Default for MyappTaskFloatStarted { + fn default() -> Self { Self::new(&super::meter::Meter::default()) } +} +pub struct MyappTaskFloatStartedObserver<'a> { + observer: &'a dyn ::opentelemetry::metrics::AsyncInstrument, +} + +impl MyappTaskFloatStartedObserver<'_> { + pub fn observe(&self, value: f64) { + let attributes = []; + self.observer.observe(value, &attributes); + } +} + +#[derive(Clone)] +pub struct MyappTaskFloatStartedObservable { + _instrument: ::opentelemetry::metrics::ObservableCounter, +} + +impl MyappTaskFloatStartedObservable { + pub const NAME: &'static str = MyappTaskFloatStarted::NAME; + pub const UNIT: &'static str = MyappTaskFloatStarted::UNIT; + pub const DESCRIPTION: &'static str = MyappTaskFloatStarted::DESCRIPTION; + + pub fn new(meter: &super::meter::Meter, callback: impl Fn(MyappTaskFloatStartedObserver<'_>) + Send + Sync + 'static) -> Self { + let instrument = meter.inner().f64_observable_counter(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .with_callback(move |observer| callback(MyappTaskFloatStartedObserver { observer })) + .build(); + Self { _instrument: instrument } + } +} + +impl Default for MyappTaskFloatStartedObservable { + fn default() -> Self { Self::new(&super::meter::Meter::default(), |_| {}) } +} +/// Task payload size. +#[derive(Clone)] +pub struct MyappTaskPayload { + instrument: ::opentelemetry::metrics::Histogram, +} + +impl MyappTaskPayload { + pub const NAME: &'static str = "myapp.task.payload"; + pub const UNIT: &'static str = "By"; + pub const DESCRIPTION: &'static str = "Task payload size."; + + pub fn new(meter: &super::meter::Meter) -> Self { + let instrument = meter.inner().u64_histogram(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .with_boundaries(vec![128_f64, 256_f64, 1024_f64]) + .build(); + Self { instrument } + } + pub fn record(&self, value: u64) { + let attributes = []; + self.instrument.record(value, &attributes); + } +} + +impl Default for MyappTaskPayload { + fn default() -> Self { Self::new(&super::meter::Meter::default()) } +} +#[derive(Clone, Debug)] +pub enum MyappTaskRetryDurationAttr { + /// Opt-in: the convention records it only when a user asks for it. + Method(super::attribute::AuthMethod), +} + +impl From for ::opentelemetry::KeyValue { + fn from(value: MyappTaskRetryDurationAttr) -> Self { + match value { + MyappTaskRetryDurationAttr::Method(value) => ::opentelemetry::KeyValue::from(value), + } + } +} +/// Time a retried task took from start to finish. +/// +/// Recorded only for tasks that ran more than once. +#[derive(Clone)] +pub struct MyappTaskRetryDuration { + instrument: ::opentelemetry::metrics::Histogram, +} + +impl MyappTaskRetryDuration { + pub const NAME: &'static str = "myapp.task.duration"; + pub const UNIT: &'static str = "s"; + pub const DESCRIPTION: &'static str = "Time a task took from start to finish."; + + pub fn new(meter: &super::meter::Meter) -> Self { + let instrument = meter.inner().f64_histogram(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .with_boundaries(vec![0_f64, 0.005_f64, 0.01_f64, 0.1_f64, 1_f64, 10_f64]) + .build(); + Self { instrument } + } + pub fn record(&self, value: f64, r#myapp_task_id: super::attribute::MyappTaskId, r#myapp_task_state: super::attribute::MyappTaskState, options: impl IntoIterator) { + let mut attributes = ::smallvec::SmallVec::<[::opentelemetry::KeyValue; 3]>::new(); + attributes.extend([::opentelemetry::KeyValue::from(r#myapp_task_id), ::opentelemetry::KeyValue::from(r#myapp_task_state)]); + attributes.extend(options.into_iter().map(::opentelemetry::KeyValue::from)); + self.instrument.record(value, &attributes); + } +} + +impl Default for MyappTaskRetryDuration { + fn default() -> Self { Self::new(&super::meter::Meter::default()) } +} +#[derive(Clone, Debug)] +pub enum MyappTaskStartedAttr { + /// Recommended: When the scheduler assigned an id before the task started. + TaskId(super::attribute::MyappTaskId), +} + +impl From for ::opentelemetry::KeyValue { + fn from(value: MyappTaskStartedAttr) -> Self { + match value { + MyappTaskStartedAttr::TaskId(value) => ::opentelemetry::KeyValue::from(value), + } + } +} +/// Number of tasks started. +/// Opt-in: record only when the user requests it. +#[derive(Clone)] +pub struct MyappTaskStarted { + instrument: ::opentelemetry::metrics::Counter, +} + +impl MyappTaskStarted { + pub const NAME: &'static str = "myapp.task.started"; + pub const UNIT: &'static str = "{task}"; + pub const DESCRIPTION: &'static str = "Number of tasks started."; + + pub fn new(meter: &super::meter::Meter) -> Self { + let instrument = meter.inner().u64_counter(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .build(); + Self { instrument } + } + pub fn add(&self, value: u64, options: impl IntoIterator) { + let mut attributes = ::smallvec::SmallVec::<[::opentelemetry::KeyValue; 1]>::new(); + attributes.extend(options.into_iter().map(::opentelemetry::KeyValue::from)); + self.instrument.add(value, &attributes); + } +} + +impl Default for MyappTaskStarted { + fn default() -> Self { Self::new(&super::meter::Meter::default()) } +} +pub struct MyappTaskStartedObserver<'a> { + observer: &'a dyn ::opentelemetry::metrics::AsyncInstrument, +} + +impl MyappTaskStartedObserver<'_> { + pub fn observe(&self, value: u64, options: impl IntoIterator) { + let mut attributes = ::smallvec::SmallVec::<[::opentelemetry::KeyValue; 1]>::new(); + attributes.extend(options.into_iter().map(::opentelemetry::KeyValue::from)); + self.observer.observe(value, &attributes); + } +} + +#[derive(Clone)] +pub struct MyappTaskStartedObservable { + _instrument: ::opentelemetry::metrics::ObservableCounter, +} + +impl MyappTaskStartedObservable { + pub const NAME: &'static str = MyappTaskStarted::NAME; + pub const UNIT: &'static str = MyappTaskStarted::UNIT; + pub const DESCRIPTION: &'static str = MyappTaskStarted::DESCRIPTION; + + pub fn new(meter: &super::meter::Meter, callback: impl Fn(MyappTaskStartedObserver<'_>) + Send + Sync + 'static) -> Self { + let instrument = meter.inner().u64_observable_counter(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .with_callback(move |observer| callback(MyappTaskStartedObserver { observer })) + .build(); + Self { _instrument: instrument } + } +} + +impl Default for MyappTaskStartedObservable { + fn default() -> Self { Self::new(&super::meter::Meter::default(), |_| {}) } +} +#[derive(Clone, Debug)] +pub enum WorkerTaskDurationAttr { + /// Opt-in: the convention records it only when a user asks for it. + Method(super::attribute::AuthMethod), + /// Conditionally required: If the task reached a final state. + TaskState(super::attribute::MyappTaskState), +} + +impl From for ::opentelemetry::KeyValue { + fn from(value: WorkerTaskDurationAttr) -> Self { + match value { + WorkerTaskDurationAttr::Method(value) => ::opentelemetry::KeyValue::from(value), + WorkerTaskDurationAttr::TaskState(value) => ::opentelemetry::KeyValue::from(value), + } + } +} +/// Time a task took on the worker that ran it. +/// +/// Measured by the worker that ran the task. +#[derive(Clone)] +pub struct WorkerTaskDuration { + instrument: ::opentelemetry::metrics::Histogram, +} + +impl WorkerTaskDuration { + pub const NAME: &'static str = "myapp.task.duration"; + pub const UNIT: &'static str = "s"; + pub const DESCRIPTION: &'static str = "Time a task took from start to finish."; + + pub fn new(meter: &super::meter::Meter) -> Self { + let instrument = meter.inner().f64_histogram(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .with_boundaries(vec![0_f64, 0.005_f64, 0.01_f64, 0.1_f64, 1_f64, 10_f64]) + .build(); + Self { instrument } + } + pub fn record(&self, value: f64, r#myapp_task_id: super::attribute::MyappTaskId, options: impl IntoIterator) { + let mut attributes = ::smallvec::SmallVec::<[::opentelemetry::KeyValue; 3]>::new(); + attributes.extend([::opentelemetry::KeyValue::from(r#myapp_task_id)]); + attributes.extend(options.into_iter().map(::opentelemetry::KeyValue::from)); + self.instrument.record(value, &attributes); + } +} + +impl Default for WorkerTaskDuration { + fn default() -> Self { Self::new(&super::meter::Meter::default()) } +} diff --git a/templates/code/rust/tests/metrics/expected/mod.rs b/templates/code/rust/tests/metrics/expected/mod.rs index f85e525..6a139a0 100644 --- a/templates/code/rust/tests/metrics/expected/mod.rs +++ b/templates/code/rust/tests/metrics/expected/mod.rs @@ -1,11 +1,8 @@ // Generated by OpenTelemetry Weaver. pub const SCHEMA_URL: &str = "https://example.com/schemas/metrics/1.0.0"; -pub mod authattr; -pub mod myappattr; +pub mod attribute; pub mod scope; pub mod options; pub mod meter; -pub mod authmetric; -pub mod myappmetric; -pub mod workermetric; +pub mod metric; diff --git a/templates/code/rust/tests/metrics/expected/myappattr.rs b/templates/code/rust/tests/metrics/expected/myappattr.rs deleted file mode 100644 index 8928c88..0000000 --- a/templates/code/rust/tests/metrics/expected/myappattr.rs +++ /dev/null @@ -1,122 +0,0 @@ -// Generated by OpenTelemetry Weaver. -/// Unique identifier of the task. -#[derive(Debug, Clone, PartialEq)] -pub struct TaskIdAttr(::opentelemetry::StringValue); - -#[allow(deprecated)] -impl TaskIdAttr { - pub const KEY: &'static str = "myapp.task.id"; -} - -#[allow(deprecated)] -impl From<::opentelemetry::StringValue> for TaskIdAttr { - #[inline] - fn from(value: ::opentelemetry::StringValue) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl From for TaskIdAttr { - #[inline] - fn from(value: String) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl From<&'static str> for TaskIdAttr { - #[inline] - fn from(value: &'static str) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl AsRef for TaskIdAttr { - #[inline] - fn as_ref(&self) -> &str { - self.0.as_str() - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for TaskIdAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str(self.as_ref()) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: TaskIdAttr) -> Self { - ::opentelemetry::KeyValue::new(TaskIdAttr::KEY, value.0) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: TaskIdAttr) -> Self { - value.0.into() - } -} - -/// Current state of the task. -#[derive(Debug, Clone, PartialEq, Copy)] -pub enum TaskStateAttr { - /// The task is waiting to run. - Queued, - /// The task finished. - Done, -} - -#[allow(deprecated)] -impl TaskStateAttr { - pub const KEY: &'static str = "myapp.task.state"; -} - -#[allow(deprecated)] -impl AsRef for TaskStateAttr { - #[inline] - fn as_ref(&self) -> &str { - match self { - TaskStateAttr::Queued => "queued", - TaskStateAttr::Done => "done", - } - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for TaskStateAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str(self.as_ref()) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: TaskStateAttr) -> Self { - let value: &'static str = match value { - TaskStateAttr::Queued => "queued", - TaskStateAttr::Done => "done", - }; - ::opentelemetry::KeyValue::new(TaskStateAttr::KEY, value) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: TaskStateAttr) -> Self { - let value: &'static str = match value { - TaskStateAttr::Queued => "queued", - TaskStateAttr::Done => "done", - }; - value.into() - } -} diff --git a/templates/code/rust/tests/metrics/expected/myappmetric.rs b/templates/code/rust/tests/metrics/expected/myappmetric.rs deleted file mode 100644 index 8a269e4..0000000 --- a/templates/code/rust/tests/metrics/expected/myappmetric.rs +++ /dev/null @@ -1,445 +0,0 @@ -#![allow(deprecated)] -/// Number of tasks waiting in the queue. -#[deprecated(note = "Replaced by `myapp.task.active`.")] -#[derive(Clone)] -pub struct QueueDepthGauge { - instrument: ::opentelemetry::metrics::Gauge, -} - -impl QueueDepthGauge { - pub fn new(meter: &super::meter::Meter) -> Self { - let instrument = meter.inner().i64_gauge("myapp.queue.depth") - .with_description("Number of tasks waiting in the queue.") - .with_unit("{task}") - .build(); - Self { instrument } - } - pub fn record(&self, value: i64) { - let attributes = []; - self.instrument.record(value, &attributes); - } -} - -impl Default for QueueDepthGauge { - fn default() -> Self { Self::new(&super::meter::Meter::default()) } -} -pub struct QueueDepthGaugeObserver<'a> { - observer: &'a dyn ::opentelemetry::metrics::AsyncInstrument, -} - -impl QueueDepthGaugeObserver<'_> { - pub fn observe(&self, value: i64) { - let attributes = []; - self.observer.observe(value, &attributes); - } -} -#[deprecated(note = "Replaced by `myapp.task.active`.")] -#[derive(Clone)] -pub struct QueueDepthObservableGauge { - _instrument: ::opentelemetry::metrics::ObservableGauge, -} - -impl QueueDepthObservableGauge { - pub fn new(meter: &super::meter::Meter, callback: impl Fn(QueueDepthGaugeObserver<'_>) + Send + Sync + 'static) -> Self { - let instrument = meter.inner().i64_observable_gauge("myapp.queue.depth") - .with_description("Number of tasks waiting in the queue.") - .with_unit("{task}") - .with_callback(move |observer| callback(QueueDepthGaugeObserver { observer })) - .build(); - Self { _instrument: instrument } - } -} - -impl Default for QueueDepthObservableGauge { - fn default() -> Self { Self::new(&super::meter::Meter::default(), |_| {}) } -} -/// Number of tasks currently running. -#[derive(Clone)] -pub struct TaskActiveUpDownCounter { - instrument: ::opentelemetry::metrics::UpDownCounter, -} - -impl TaskActiveUpDownCounter { - pub fn new(meter: &super::meter::Meter) -> Self { - let instrument = meter.inner().i64_up_down_counter("myapp.task.active") - .with_description("Number of tasks currently running.") - .with_unit("{task}") - .build(); - Self { instrument } - } - pub fn add(&self, value: i64, r#myapp_task_state: super::myappattr::TaskStateAttr) { - let attributes = [::opentelemetry::KeyValue::from(r#myapp_task_state)]; - self.instrument.add(value, &attributes); - } -} - -impl Default for TaskActiveUpDownCounter { - fn default() -> Self { Self::new(&super::meter::Meter::default()) } -} -pub struct TaskActiveUpDownCounterObserver<'a> { - observer: &'a dyn ::opentelemetry::metrics::AsyncInstrument, -} - -impl TaskActiveUpDownCounterObserver<'_> { - pub fn observe(&self, value: i64, r#myapp_task_state: super::myappattr::TaskStateAttr) { - let attributes = [::opentelemetry::KeyValue::from(r#myapp_task_state)]; - self.observer.observe(value, &attributes); - } -} - -#[derive(Clone)] -pub struct TaskActiveObservableUpDownCounter { - _instrument: ::opentelemetry::metrics::ObservableUpDownCounter, -} - -impl TaskActiveObservableUpDownCounter { - pub fn new(meter: &super::meter::Meter, callback: impl Fn(TaskActiveUpDownCounterObserver<'_>) + Send + Sync + 'static) -> Self { - let instrument = meter.inner().i64_observable_up_down_counter("myapp.task.active") - .with_description("Number of tasks currently running.") - .with_unit("{task}") - .with_callback(move |observer| callback(TaskActiveUpDownCounterObserver { observer })) - .build(); - Self { _instrument: instrument } - } -} - -impl Default for TaskActiveObservableUpDownCounter { - fn default() -> Self { Self::new(&super::meter::Meter::default(), |_| {}) } -} -#[derive(Clone, Debug)] -pub enum TaskDurationHistogramAttr { - /// Opt-in: the convention records it only when a user asks for it. - Method(super::authattr::MethodAttr), - /// Conditionally required: If the task reached a final state. - TaskState(super::myappattr::TaskStateAttr), -} - -impl From for ::opentelemetry::KeyValue { - fn from(value: TaskDurationHistogramAttr) -> Self { - match value { - TaskDurationHistogramAttr::Method(value) => ::opentelemetry::KeyValue::from(value), - TaskDurationHistogramAttr::TaskState(value) => ::opentelemetry::KeyValue::from(value), - } - } -} -/// Time a task took from start to finish. -/// -/// Measured by the worker that ran the task. -#[derive(Clone)] -pub struct TaskDurationHistogram { - instrument: ::opentelemetry::metrics::Histogram, -} - -impl TaskDurationHistogram { - pub fn new(meter: &super::meter::Meter) -> Self { - let instrument = meter.inner().f64_histogram("myapp.task.duration") - .with_description("Time a task took from start to finish.") - .with_unit("s") - .with_boundaries(vec![0_f64, 0.005_f64, 0.01_f64, 0.1_f64, 1_f64, 10_f64]) - .build(); - Self { instrument } - } - pub fn record(&self, value: f64, r#myapp_task_id: super::myappattr::TaskIdAttr, options: impl IntoIterator) { - let mut attributes = ::smallvec::SmallVec::<[::opentelemetry::KeyValue; 3]>::new(); - attributes.extend([::opentelemetry::KeyValue::from(r#myapp_task_id)]); - attributes.extend(options.into_iter().map(::opentelemetry::KeyValue::from)); - self.instrument.record(value, &attributes); - } -} - -impl Default for TaskDurationHistogram { - fn default() -> Self { Self::new(&super::meter::Meter::default()) } -} -/// Fractional active task adjustment. -#[derive(Clone)] -pub struct TaskFloatActiveUpDownCounter { - instrument: ::opentelemetry::metrics::UpDownCounter, -} - -impl TaskFloatActiveUpDownCounter { - pub fn new(meter: &super::meter::Meter) -> Self { - let instrument = meter.inner().f64_up_down_counter("myapp.task.float.active") - .with_description("Fractional active task adjustment.") - .with_unit("{task}") - .build(); - Self { instrument } - } - pub fn add(&self, value: f64) { - let attributes = []; - self.instrument.add(value, &attributes); - } -} - -impl Default for TaskFloatActiveUpDownCounter { - fn default() -> Self { Self::new(&super::meter::Meter::default()) } -} -pub struct TaskFloatActiveUpDownCounterObserver<'a> { - observer: &'a dyn ::opentelemetry::metrics::AsyncInstrument, -} - -impl TaskFloatActiveUpDownCounterObserver<'_> { - pub fn observe(&self, value: f64) { - let attributes = []; - self.observer.observe(value, &attributes); - } -} - -#[derive(Clone)] -pub struct TaskFloatActiveObservableUpDownCounter { - _instrument: ::opentelemetry::metrics::ObservableUpDownCounter, -} - -impl TaskFloatActiveObservableUpDownCounter { - pub fn new(meter: &super::meter::Meter, callback: impl Fn(TaskFloatActiveUpDownCounterObserver<'_>) + Send + Sync + 'static) -> Self { - let instrument = meter.inner().f64_observable_up_down_counter("myapp.task.float.active") - .with_description("Fractional active task adjustment.") - .with_unit("{task}") - .with_callback(move |observer| callback(TaskFloatActiveUpDownCounterObserver { observer })) - .build(); - Self { _instrument: instrument } - } -} - -impl Default for TaskFloatActiveObservableUpDownCounter { - fn default() -> Self { Self::new(&super::meter::Meter::default(), |_| {}) } -} -/// Fractional queue depth. -#[derive(Clone)] -pub struct TaskFloatDepthGauge { - instrument: ::opentelemetry::metrics::Gauge, -} - -impl TaskFloatDepthGauge { - pub fn new(meter: &super::meter::Meter) -> Self { - let instrument = meter.inner().f64_gauge("myapp.task.float.depth") - .with_description("Fractional queue depth.") - .with_unit("{task}") - .build(); - Self { instrument } - } - pub fn record(&self, value: f64) { - let attributes = []; - self.instrument.record(value, &attributes); - } -} - -impl Default for TaskFloatDepthGauge { - fn default() -> Self { Self::new(&super::meter::Meter::default()) } -} -pub struct TaskFloatDepthGaugeObserver<'a> { - observer: &'a dyn ::opentelemetry::metrics::AsyncInstrument, -} - -impl TaskFloatDepthGaugeObserver<'_> { - pub fn observe(&self, value: f64) { - let attributes = []; - self.observer.observe(value, &attributes); - } -} - -#[derive(Clone)] -pub struct TaskFloatDepthObservableGauge { - _instrument: ::opentelemetry::metrics::ObservableGauge, -} - -impl TaskFloatDepthObservableGauge { - pub fn new(meter: &super::meter::Meter, callback: impl Fn(TaskFloatDepthGaugeObserver<'_>) + Send + Sync + 'static) -> Self { - let instrument = meter.inner().f64_observable_gauge("myapp.task.float.depth") - .with_description("Fractional queue depth.") - .with_unit("{task}") - .with_callback(move |observer| callback(TaskFloatDepthGaugeObserver { observer })) - .build(); - Self { _instrument: instrument } - } -} - -impl Default for TaskFloatDepthObservableGauge { - fn default() -> Self { Self::new(&super::meter::Meter::default(), |_| {}) } -} -/// Fractional tasks started. -#[derive(Clone)] -pub struct TaskFloatStartedCounter { - instrument: ::opentelemetry::metrics::Counter, -} - -impl TaskFloatStartedCounter { - pub fn new(meter: &super::meter::Meter) -> Self { - let instrument = meter.inner().f64_counter("myapp.task.float.started") - .with_description("Fractional tasks started.") - .with_unit("{task}") - .build(); - Self { instrument } - } - pub fn add(&self, value: f64) { - let attributes = []; - self.instrument.add(value, &attributes); - } -} - -impl Default for TaskFloatStartedCounter { - fn default() -> Self { Self::new(&super::meter::Meter::default()) } -} -pub struct TaskFloatStartedCounterObserver<'a> { - observer: &'a dyn ::opentelemetry::metrics::AsyncInstrument, -} - -impl TaskFloatStartedCounterObserver<'_> { - pub fn observe(&self, value: f64) { - let attributes = []; - self.observer.observe(value, &attributes); - } -} - -#[derive(Clone)] -pub struct TaskFloatStartedObservableCounter { - _instrument: ::opentelemetry::metrics::ObservableCounter, -} - -impl TaskFloatStartedObservableCounter { - pub fn new(meter: &super::meter::Meter, callback: impl Fn(TaskFloatStartedCounterObserver<'_>) + Send + Sync + 'static) -> Self { - let instrument = meter.inner().f64_observable_counter("myapp.task.float.started") - .with_description("Fractional tasks started.") - .with_unit("{task}") - .with_callback(move |observer| callback(TaskFloatStartedCounterObserver { observer })) - .build(); - Self { _instrument: instrument } - } -} - -impl Default for TaskFloatStartedObservableCounter { - fn default() -> Self { Self::new(&super::meter::Meter::default(), |_| {}) } -} -/// Task payload size. -#[derive(Clone)] -pub struct TaskPayloadHistogram { - instrument: ::opentelemetry::metrics::Histogram, -} - -impl TaskPayloadHistogram { - pub fn new(meter: &super::meter::Meter) -> Self { - let instrument = meter.inner().u64_histogram("myapp.task.payload") - .with_description("Task payload size.") - .with_unit("By") - .with_boundaries(vec![128_f64, 256_f64, 1024_f64]) - .build(); - Self { instrument } - } - pub fn record(&self, value: u64) { - let attributes = []; - self.instrument.record(value, &attributes); - } -} - -impl Default for TaskPayloadHistogram { - fn default() -> Self { Self::new(&super::meter::Meter::default()) } -} -#[derive(Clone, Debug)] -pub enum TaskRetryDurationHistogramAttr { - /// Opt-in: the convention records it only when a user asks for it. - Method(super::authattr::MethodAttr), -} - -impl From for ::opentelemetry::KeyValue { - fn from(value: TaskRetryDurationHistogramAttr) -> Self { - match value { - TaskRetryDurationHistogramAttr::Method(value) => ::opentelemetry::KeyValue::from(value), - } - } -} -/// Time a retried task took from start to finish. -/// -/// Recorded only for tasks that ran more than once. -#[derive(Clone)] -pub struct TaskRetryDurationHistogram { - instrument: ::opentelemetry::metrics::Histogram, -} - -impl TaskRetryDurationHistogram { - pub fn new(meter: &super::meter::Meter) -> Self { - let instrument = meter.inner().f64_histogram("myapp.task.duration") - .with_description("Time a task took from start to finish.") - .with_unit("s") - .with_boundaries(vec![0_f64, 0.005_f64, 0.01_f64, 0.1_f64, 1_f64, 10_f64]) - .build(); - Self { instrument } - } - pub fn record(&self, value: f64, r#myapp_task_id: super::myappattr::TaskIdAttr, r#myapp_task_state: super::myappattr::TaskStateAttr, options: impl IntoIterator) { - let mut attributes = ::smallvec::SmallVec::<[::opentelemetry::KeyValue; 3]>::new(); - attributes.extend([::opentelemetry::KeyValue::from(r#myapp_task_id), ::opentelemetry::KeyValue::from(r#myapp_task_state)]); - attributes.extend(options.into_iter().map(::opentelemetry::KeyValue::from)); - self.instrument.record(value, &attributes); - } -} - -impl Default for TaskRetryDurationHistogram { - fn default() -> Self { Self::new(&super::meter::Meter::default()) } -} -#[derive(Clone, Debug)] -pub enum TaskStartedCounterAttr { - /// Recommended: When the scheduler assigned an id before the task started. - TaskId(super::myappattr::TaskIdAttr), -} - -impl From for ::opentelemetry::KeyValue { - fn from(value: TaskStartedCounterAttr) -> Self { - match value { - TaskStartedCounterAttr::TaskId(value) => ::opentelemetry::KeyValue::from(value), - } - } -} -/// Number of tasks started. -/// Opt-in: record only when the user requests it. -#[derive(Clone)] -pub struct TaskStartedCounter { - instrument: ::opentelemetry::metrics::Counter, -} - -impl TaskStartedCounter { - pub fn new(meter: &super::meter::Meter) -> Self { - let instrument = meter.inner().u64_counter("myapp.task.started") - .with_description("Number of tasks started.") - .with_unit("{task}") - .build(); - Self { instrument } - } - pub fn add(&self, value: u64, options: impl IntoIterator) { - let mut attributes = ::smallvec::SmallVec::<[::opentelemetry::KeyValue; 1]>::new(); - attributes.extend(options.into_iter().map(::opentelemetry::KeyValue::from)); - self.instrument.add(value, &attributes); - } -} - -impl Default for TaskStartedCounter { - fn default() -> Self { Self::new(&super::meter::Meter::default()) } -} -pub struct TaskStartedCounterObserver<'a> { - observer: &'a dyn ::opentelemetry::metrics::AsyncInstrument, -} - -impl TaskStartedCounterObserver<'_> { - pub fn observe(&self, value: u64, options: impl IntoIterator) { - let mut attributes = ::smallvec::SmallVec::<[::opentelemetry::KeyValue; 1]>::new(); - attributes.extend(options.into_iter().map(::opentelemetry::KeyValue::from)); - self.observer.observe(value, &attributes); - } -} - -#[derive(Clone)] -pub struct TaskStartedObservableCounter { - _instrument: ::opentelemetry::metrics::ObservableCounter, -} - -impl TaskStartedObservableCounter { - pub fn new(meter: &super::meter::Meter, callback: impl Fn(TaskStartedCounterObserver<'_>) + Send + Sync + 'static) -> Self { - let instrument = meter.inner().u64_observable_counter("myapp.task.started") - .with_description("Number of tasks started.") - .with_unit("{task}") - .with_callback(move |observer| callback(TaskStartedCounterObserver { observer })) - .build(); - Self { _instrument: instrument } - } -} - -impl Default for TaskStartedObservableCounter { - fn default() -> Self { Self::new(&super::meter::Meter::default(), |_| {}) } -} diff --git a/templates/code/rust/tests/metrics/expected/workermetric.rs b/templates/code/rust/tests/metrics/expected/workermetric.rs deleted file mode 100644 index 21f03e7..0000000 --- a/templates/code/rust/tests/metrics/expected/workermetric.rs +++ /dev/null @@ -1,45 +0,0 @@ -#![allow(deprecated)] -#[derive(Clone, Debug)] -pub enum TaskDurationHistogramAttr { - /// Opt-in: the convention records it only when a user asks for it. - Method(super::authattr::MethodAttr), - /// Conditionally required: If the task reached a final state. - TaskState(super::myappattr::TaskStateAttr), -} - -impl From for ::opentelemetry::KeyValue { - fn from(value: TaskDurationHistogramAttr) -> Self { - match value { - TaskDurationHistogramAttr::Method(value) => ::opentelemetry::KeyValue::from(value), - TaskDurationHistogramAttr::TaskState(value) => ::opentelemetry::KeyValue::from(value), - } - } -} -/// Time a task took on the worker that ran it. -/// -/// Measured by the worker that ran the task. -#[derive(Clone)] -pub struct TaskDurationHistogram { - instrument: ::opentelemetry::metrics::Histogram, -} - -impl TaskDurationHistogram { - pub fn new(meter: &super::meter::Meter) -> Self { - let instrument = meter.inner().f64_histogram("myapp.task.duration") - .with_description("Time a task took from start to finish.") - .with_unit("s") - .with_boundaries(vec![0_f64, 0.005_f64, 0.01_f64, 0.1_f64, 1_f64, 10_f64]) - .build(); - Self { instrument } - } - pub fn record(&self, value: f64, r#myapp_task_id: super::myappattr::TaskIdAttr, options: impl IntoIterator) { - let mut attributes = ::smallvec::SmallVec::<[::opentelemetry::KeyValue; 3]>::new(); - attributes.extend([::opentelemetry::KeyValue::from(r#myapp_task_id)]); - attributes.extend(options.into_iter().map(::opentelemetry::KeyValue::from)); - self.instrument.record(value, &attributes); - } -} - -impl Default for TaskDurationHistogram { - fn default() -> Self { Self::new(&super::meter::Meter::default()) } -} diff --git a/templates/code/rust/tests/metrics/test.rs b/templates/code/rust/tests/metrics/test.rs index 35b5a17..b49171e 100644 --- a/templates/code/rust/tests/metrics/test.rs +++ b/templates/code/rust/tests/metrics/test.rs @@ -1,5 +1,5 @@ use generated_semconv::options::InstrumentationOptions; -use generated_semconv::{authattr, authmetric, meter, myappattr, myappmetric, scope, workermetric}; +use generated_semconv::{attribute, meter, metric, scope}; use opentelemetry::KeyValue; use opentelemetry_sdk::metrics::data::{AggregatedMetrics, MetricData}; use opentelemetry_sdk::metrics::{InMemoryMetricExporter, PeriodicReader, SdkMeterProvider}; @@ -29,39 +29,39 @@ fn synchronous_metrics_export_types_values_attributes_and_refinements() { }, }, ); - myappmetric::TaskDurationHistogram::new(&meter).record( + metric::MyappTaskDuration::new(&meter).record( 0.1, - myappattr::TaskIdAttr::from("base"), + attribute::MyappTaskId::from("base"), [ - myappmetric::TaskDurationHistogramAttr::TaskState(myappattr::TaskStateAttr::Queued), - myappmetric::TaskDurationHistogramAttr::Method(authattr::MethodAttr::Password), + metric::MyappTaskDurationAttr::TaskState(attribute::MyappTaskState::Queued), + metric::MyappTaskDurationAttr::Method(attribute::AuthMethod::Password), ], ); - myappmetric::TaskRetryDurationHistogram::new(&meter).record( + metric::MyappTaskRetryDuration::new(&meter).record( 0.2, - myappattr::TaskIdAttr::from("retry"), - myappattr::TaskStateAttr::Done, - [myappmetric::TaskRetryDurationHistogramAttr::Method( - authattr::MethodAttr::Token, + attribute::MyappTaskId::from("retry"), + attribute::MyappTaskState::Done, + [metric::MyappTaskRetryDurationAttr::Method( + attribute::AuthMethod::Token, )], ); - workermetric::TaskDurationHistogram::new(&meter).record( + metric::WorkerTaskDuration::new(&meter).record( 0.3, - myappattr::TaskIdAttr::from("worker"), + attribute::MyappTaskId::from("worker"), [], ); - myappmetric::TaskStartedCounter::new(&meter).add( + metric::MyappTaskStarted::new(&meter).add( 7, - [myappmetric::TaskStartedCounterAttr::TaskId( - myappattr::TaskIdAttr::from("started"), + [metric::MyappTaskStartedAttr::TaskId( + attribute::MyappTaskId::from("started"), )], ); - myappmetric::TaskActiveUpDownCounter::new(&meter).add(-2, myappattr::TaskStateAttr::Queued); - myappmetric::QueueDepthGauge::new(&meter).record(5); - authmetric::AttemptsCounter::new(&meter).add( + metric::MyappTaskActive::new(&meter).add(-2, attribute::MyappTaskState::Queued); + metric::MyappQueueDepth::new(&meter).record(5); + metric::AuthAttempts::new(&meter).add( 3, - authattr::MethodAttr::Password, - authattr::SuccessAttr::from(true), + attribute::AuthMethod::Password, + attribute::AuthSuccess::from(true), ); provider.force_flush().unwrap(); @@ -190,25 +190,25 @@ fn synchronous_metrics_export_types_values_attributes_and_refinements() { fn observable_callbacks_export_values_and_typed_attributes() { let (provider, exporter) = provider(); let meter = meter::Meter::new(&provider, InstrumentationOptions::default()); - let _started = myappmetric::TaskStartedObservableCounter::new(&meter, |observer| { + let _started = metric::MyappTaskStartedObservable::new(&meter, |observer| { observer.observe( 11, - [myappmetric::TaskStartedCounterAttr::TaskId( - myappattr::TaskIdAttr::from("observed"), + [metric::MyappTaskStartedAttr::TaskId( + attribute::MyappTaskId::from("observed"), )], ); }); - let _active = myappmetric::TaskActiveObservableUpDownCounter::new(&meter, |observer| { - observer.observe(-4, myappattr::TaskStateAttr::Queued); + let _active = metric::MyappTaskActiveObservable::new(&meter, |observer| { + observer.observe(-4, attribute::MyappTaskState::Queued); }); - let _depth = myappmetric::QueueDepthObservableGauge::new(&meter, |observer| { + let _depth = metric::MyappQueueDepthObservable::new(&meter, |observer| { observer.observe(9); }); - let _attempts = authmetric::AttemptsObservableCounter::new(&meter, |observer| { + let _attempts = metric::AuthAttemptsObservable::new(&meter, |observer| { observer.observe( 13, - authattr::MethodAttr::Token, - authattr::SuccessAttr::from(false), + attribute::AuthMethod::Token, + attribute::AuthSuccess::from(false), ); }); provider.force_flush().unwrap(); @@ -267,10 +267,10 @@ fn alternate_numeric_types_export_sync_and_observable_measurements() { }, }, ); - myappmetric::TaskFloatStartedCounter::new(&sync_meter).add(0.5); - myappmetric::TaskFloatActiveUpDownCounter::new(&sync_meter).add(-1.25); - myappmetric::TaskFloatDepthGauge::new(&sync_meter).record(2.5); - myappmetric::TaskPayloadHistogram::new(&sync_meter).record(512); + metric::MyappTaskFloatStarted::new(&sync_meter).add(0.5); + metric::MyappTaskFloatActive::new(&sync_meter).add(-1.25); + metric::MyappTaskFloatDepth::new(&sync_meter).record(2.5); + metric::MyappTaskPayload::new(&sync_meter).record(512); let async_meter = meter::Meter::new( &provider, InstrumentationOptions { @@ -279,14 +279,14 @@ fn alternate_numeric_types_export_sync_and_observable_measurements() { }, }, ); - let _started = myappmetric::TaskFloatStartedObservableCounter::new(&async_meter, |observer| { + let _started = metric::MyappTaskFloatStartedObservable::new(&async_meter, |observer| { observer.observe(0.75); }); let _active = - myappmetric::TaskFloatActiveObservableUpDownCounter::new(&async_meter, |observer| { + metric::MyappTaskFloatActiveObservable::new(&async_meter, |observer| { observer.observe(-2.5); }); - let _depth = myappmetric::TaskFloatDepthObservableGauge::new(&async_meter, |observer| { + let _depth = metric::MyappTaskFloatDepthObservable::new(&async_meter, |observer| { observer.observe(3.75); }); provider.force_flush().unwrap(); @@ -347,3 +347,21 @@ fn alternate_numeric_types_export_sync_and_observable_measurements() { } provider.shutdown().unwrap(); } + +const _: &str = metric::MyappTaskDuration::NAME; + +#[test] +fn instruments_expose_registry_metadata_as_constants() { + assert_eq!(metric::MyappTaskDuration::NAME, "myapp.task.duration"); + assert_eq!(metric::MyappTaskDuration::UNIT, "s"); + assert_eq!( + metric::MyappTaskDuration::DESCRIPTION, + "Time a task took from start to finish." + ); + assert_eq!(metric::AuthAttemptsObservable::NAME, metric::AuthAttempts::NAME); + assert_eq!(metric::AuthAttemptsObservable::UNIT, "{attempt}"); + assert_eq!( + metric::AuthAttemptsObservable::DESCRIPTION, + metric::AuthAttempts::DESCRIPTION + ); +} diff --git a/templates/code/rust/tests/naming/expected/capsattr.rs b/templates/code/rust/tests/naming/expected/attribute.rs similarity index 57% rename from templates/code/rust/tests/naming/expected/capsattr.rs rename to templates/code/rust/tests/naming/expected/attribute.rs index 66d2edf..5374318 100644 --- a/templates/code/rust/tests/naming/expected/capsattr.rs +++ b/templates/code/rust/tests/naming/expected/attribute.rs @@ -1,15 +1,15 @@ // Generated by OpenTelemetry Weaver. /// Synthetic identifier. #[derive(Debug, Clone, PartialEq)] -pub struct Http2STATUSApiIDAttr(::opentelemetry::StringValue); +pub struct CapsHttp2STATUSApiID(::opentelemetry::StringValue); #[allow(deprecated)] -impl Http2STATUSApiIDAttr { +impl CapsHttp2STATUSApiID { pub const KEY: &'static str = "caps.http2_STATUS.api_ID"; } #[allow(deprecated)] -impl From<::opentelemetry::StringValue> for Http2STATUSApiIDAttr { +impl From<::opentelemetry::StringValue> for CapsHttp2STATUSApiID { #[inline] fn from(value: ::opentelemetry::StringValue) -> Self { Self(value) @@ -17,7 +17,7 @@ impl From<::opentelemetry::StringValue> for Http2STATUSApiIDAttr { } #[allow(deprecated)] -impl From for Http2STATUSApiIDAttr { +impl From for CapsHttp2STATUSApiID { #[inline] fn from(value: String) -> Self { Self(value.into()) @@ -25,7 +25,7 @@ impl From for Http2STATUSApiIDAttr { } #[allow(deprecated)] -impl From<&'static str> for Http2STATUSApiIDAttr { +impl From<&'static str> for CapsHttp2STATUSApiID { #[inline] fn from(value: &'static str) -> Self { Self(value.into()) @@ -33,7 +33,7 @@ impl From<&'static str> for Http2STATUSApiIDAttr { } #[allow(deprecated)] -impl AsRef for Http2STATUSApiIDAttr { +impl AsRef for CapsHttp2STATUSApiID { #[inline] fn as_ref(&self) -> &str { self.0.as_str() @@ -41,7 +41,7 @@ impl AsRef for Http2STATUSApiIDAttr { } #[allow(deprecated)] -impl ::std::fmt::Display for Http2STATUSApiIDAttr { +impl ::std::fmt::Display for CapsHttp2STATUSApiID { #[inline] fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { formatter.write_str(self.as_ref()) @@ -49,45 +49,45 @@ impl ::std::fmt::Display for Http2STATUSApiIDAttr { } #[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { +impl From for ::opentelemetry::KeyValue { #[inline] - fn from(value: Http2STATUSApiIDAttr) -> Self { - ::opentelemetry::KeyValue::new(Http2STATUSApiIDAttr::KEY, value.0) + fn from(value: CapsHttp2STATUSApiID) -> Self { + ::opentelemetry::KeyValue::new(CapsHttp2STATUSApiID::KEY, value.0) } } #[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { +impl From for ::opentelemetry::logs::AnyValue { #[inline] - fn from(value: Http2STATUSApiIDAttr) -> Self { + fn from(value: CapsHttp2STATUSApiID) -> Self { value.0.into() } } /// Synthetic mode. #[derive(Debug, Clone, PartialEq, Copy)] -pub enum Mode2STATEAttr { +pub enum CapsMode2STATE { /// Synthetic state. HTTP2ReadySTATE, } #[allow(deprecated)] -impl Mode2STATEAttr { +impl CapsMode2STATE { pub const KEY: &'static str = "caps.mode2_STATE"; } #[allow(deprecated)] -impl AsRef for Mode2STATEAttr { +impl AsRef for CapsMode2STATE { #[inline] fn as_ref(&self) -> &str { match self { - Mode2STATEAttr::HTTP2ReadySTATE => "ready", + CapsMode2STATE::HTTP2ReadySTATE => "ready", } } } #[allow(deprecated)] -impl ::std::fmt::Display for Mode2STATEAttr { +impl ::std::fmt::Display for CapsMode2STATE { #[inline] fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { formatter.write_str(self.as_ref()) @@ -95,22 +95,22 @@ impl ::std::fmt::Display for Mode2STATEAttr { } #[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { +impl From for ::opentelemetry::KeyValue { #[inline] - fn from(value: Mode2STATEAttr) -> Self { + fn from(value: CapsMode2STATE) -> Self { let value: &'static str = match value { - Mode2STATEAttr::HTTP2ReadySTATE => "ready", + CapsMode2STATE::HTTP2ReadySTATE => "ready", }; - ::opentelemetry::KeyValue::new(Mode2STATEAttr::KEY, value) + ::opentelemetry::KeyValue::new(CapsMode2STATE::KEY, value) } } #[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { +impl From for ::opentelemetry::logs::AnyValue { #[inline] - fn from(value: Mode2STATEAttr) -> Self { + fn from(value: CapsMode2STATE) -> Self { let value: &'static str = match value { - Mode2STATEAttr::HTTP2ReadySTATE => "ready", + CapsMode2STATE::HTTP2ReadySTATE => "ready", }; value.into() } diff --git a/templates/code/rust/tests/naming/expected/capsmetric.rs b/templates/code/rust/tests/naming/expected/capsmetric.rs deleted file mode 100644 index eac6967..0000000 --- a/templates/code/rust/tests/naming/expected/capsmetric.rs +++ /dev/null @@ -1,54 +0,0 @@ -#![allow(deprecated)] -/// Synthetic count. -#[derive(Clone)] -pub struct Http2STATUSCountCounter { - instrument: ::opentelemetry::metrics::Counter, -} - -impl Http2STATUSCountCounter { - pub fn new(meter: &super::meter::Meter) -> Self { - let instrument = meter.inner().u64_counter("caps.http2_STATUS.count") - .with_description("Synthetic count.") - .with_unit("{item}") - .build(); - Self { instrument } - } - pub fn add(&self, value: u64, r#caps_http2_status_api_id: super::capsattr::Http2STATUSApiIDAttr, r#caps_mode2_state: super::capsattr::Mode2STATEAttr) { - let attributes = [::opentelemetry::KeyValue::from(r#caps_http2_status_api_id), ::opentelemetry::KeyValue::from(r#caps_mode2_state)]; - self.instrument.add(value, &attributes); - } -} - -impl Default for Http2STATUSCountCounter { - fn default() -> Self { Self::new(&super::meter::Meter::default()) } -} -pub struct Http2STATUSCountCounterObserver<'a> { - observer: &'a dyn ::opentelemetry::metrics::AsyncInstrument, -} - -impl Http2STATUSCountCounterObserver<'_> { - pub fn observe(&self, value: u64, r#caps_http2_status_api_id: super::capsattr::Http2STATUSApiIDAttr, r#caps_mode2_state: super::capsattr::Mode2STATEAttr) { - let attributes = [::opentelemetry::KeyValue::from(r#caps_http2_status_api_id), ::opentelemetry::KeyValue::from(r#caps_mode2_state)]; - self.observer.observe(value, &attributes); - } -} - -#[derive(Clone)] -pub struct Http2STATUSCountObservableCounter { - _instrument: ::opentelemetry::metrics::ObservableCounter, -} - -impl Http2STATUSCountObservableCounter { - pub fn new(meter: &super::meter::Meter, callback: impl Fn(Http2STATUSCountCounterObserver<'_>) + Send + Sync + 'static) -> Self { - let instrument = meter.inner().u64_observable_counter("caps.http2_STATUS.count") - .with_description("Synthetic count.") - .with_unit("{item}") - .with_callback(move |observer| callback(Http2STATUSCountCounterObserver { observer })) - .build(); - Self { _instrument: instrument } - } -} - -impl Default for Http2STATUSCountObservableCounter { - fn default() -> Self { Self::new(&super::meter::Meter::default(), |_| {}) } -} diff --git a/templates/code/rust/tests/naming/expected/metric.rs b/templates/code/rust/tests/naming/expected/metric.rs new file mode 100644 index 0000000..99a1fb9 --- /dev/null +++ b/templates/code/rust/tests/naming/expected/metric.rs @@ -0,0 +1,62 @@ +#![allow(deprecated)] +/// Synthetic count. +#[derive(Clone)] +pub struct CapsHttp2STATUSCount { + instrument: ::opentelemetry::metrics::Counter, +} + +impl CapsHttp2STATUSCount { + pub const NAME: &'static str = "caps.http2_STATUS.count"; + pub const UNIT: &'static str = "{item}"; + pub const DESCRIPTION: &'static str = "Synthetic count."; + + pub fn new(meter: &super::meter::Meter) -> Self { + let instrument = meter.inner().u64_counter(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .build(); + Self { instrument } + } + pub fn add(&self, value: u64, r#caps_http2_status_api_id: super::attribute::CapsHttp2STATUSApiID, r#caps_mode2_state: super::attribute::CapsMode2STATE) { + let attributes = [::opentelemetry::KeyValue::from(r#caps_http2_status_api_id), ::opentelemetry::KeyValue::from(r#caps_mode2_state)]; + self.instrument.add(value, &attributes); + } +} + +impl Default for CapsHttp2STATUSCount { + fn default() -> Self { Self::new(&super::meter::Meter::default()) } +} +pub struct CapsHttp2STATUSCountObserver<'a> { + observer: &'a dyn ::opentelemetry::metrics::AsyncInstrument, +} + +impl CapsHttp2STATUSCountObserver<'_> { + pub fn observe(&self, value: u64, r#caps_http2_status_api_id: super::attribute::CapsHttp2STATUSApiID, r#caps_mode2_state: super::attribute::CapsMode2STATE) { + let attributes = [::opentelemetry::KeyValue::from(r#caps_http2_status_api_id), ::opentelemetry::KeyValue::from(r#caps_mode2_state)]; + self.observer.observe(value, &attributes); + } +} + +#[derive(Clone)] +pub struct CapsHttp2STATUSCountObservable { + _instrument: ::opentelemetry::metrics::ObservableCounter, +} + +impl CapsHttp2STATUSCountObservable { + pub const NAME: &'static str = CapsHttp2STATUSCount::NAME; + pub const UNIT: &'static str = CapsHttp2STATUSCount::UNIT; + pub const DESCRIPTION: &'static str = CapsHttp2STATUSCount::DESCRIPTION; + + pub fn new(meter: &super::meter::Meter, callback: impl Fn(CapsHttp2STATUSCountObserver<'_>) + Send + Sync + 'static) -> Self { + let instrument = meter.inner().u64_observable_counter(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .with_callback(move |observer| callback(CapsHttp2STATUSCountObserver { observer })) + .build(); + Self { _instrument: instrument } + } +} + +impl Default for CapsHttp2STATUSCountObservable { + fn default() -> Self { Self::new(&super::meter::Meter::default(), |_| {}) } +} diff --git a/templates/code/rust/tests/naming/expected/mod.rs b/templates/code/rust/tests/naming/expected/mod.rs index dc64fde..8faa54c 100644 --- a/templates/code/rust/tests/naming/expected/mod.rs +++ b/templates/code/rust/tests/naming/expected/mod.rs @@ -1,8 +1,8 @@ // Generated by OpenTelemetry Weaver. pub const SCHEMA_URL: &str = "https://example.com/schemas/naming/1.0.0"; -pub mod capsattr; +pub mod attribute; pub mod scope; pub mod options; pub mod meter; -pub mod capsmetric; +pub mod metric; diff --git a/templates/code/rust/tests/naming/test.rs b/templates/code/rust/tests/naming/test.rs index 2d31a00..aa2d2f9 100644 --- a/templates/code/rust/tests/naming/test.rs +++ b/templates/code/rust/tests/naming/test.rs @@ -1,15 +1,15 @@ #![allow(non_camel_case_types, non_snake_case)] -use generated_semconv::{capsattr, capsmetric, meter}; +use generated_semconv::{attribute, meter, metric}; use opentelemetry::KeyValue; #[test] fn names_preserve_capitalization_and_digits_in_attributes_and_signals() { - let identifier = capsattr::Http2STATUSApiIDAttr::from("value"); + let identifier = attribute::CapsHttp2STATUSApiID::from("value"); assert_eq!( KeyValue::from(identifier.clone()), KeyValue::new("caps.http2_STATUS.api_ID", "value") ); - let mode = capsattr::Mode2STATEAttr::HTTP2ReadySTATE; - let metric = capsmetric::Http2STATUSCountCounter::new(&meter::Meter::default()); + let mode = attribute::CapsMode2STATE::HTTP2ReadySTATE; + let metric = metric::CapsHttp2STATUSCount::new(&meter::Meter::default()); metric.add(1, identifier, mode); } diff --git a/templates/code/rust/tests/no_namespace/expected/attribute.rs b/templates/code/rust/tests/no_namespace/expected/attribute.rs new file mode 100644 index 0000000..e64ab4a --- /dev/null +++ b/templates/code/rust/tests/no_namespace/expected/attribute.rs @@ -0,0 +1,366 @@ +// Generated by OpenTelemetry Weaver. +/// The exception message. +#[derive(Debug, Clone, PartialEq)] +pub struct ExceptionMessage(::opentelemetry::StringValue); + +#[allow(deprecated)] +impl ExceptionMessage { + pub const KEY: &'static str = "exception.message"; +} + +#[allow(deprecated)] +impl From<::opentelemetry::StringValue> for ExceptionMessage { + #[inline] + fn from(value: ::opentelemetry::StringValue) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl From for ExceptionMessage { + #[inline] + fn from(value: String) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl From<&'static str> for ExceptionMessage { + #[inline] + fn from(value: &'static str) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl AsRef for ExceptionMessage { + #[inline] + fn as_ref(&self) -> &str { + self.0.as_str() + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for ExceptionMessage { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str(self.as_ref()) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: ExceptionMessage) -> Self { + ::opentelemetry::KeyValue::new(ExceptionMessage::KEY, value.0) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: ExceptionMessage) -> Self { + value.0.into() + } +} + +/// The type of the exception. +#[derive(Debug, Clone, PartialEq)] +pub struct ExceptionType(::opentelemetry::StringValue); + +#[allow(deprecated)] +impl ExceptionType { + pub const KEY: &'static str = "exception.type"; +} + +#[allow(deprecated)] +impl From<::opentelemetry::StringValue> for ExceptionType { + #[inline] + fn from(value: ::opentelemetry::StringValue) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl From for ExceptionType { + #[inline] + fn from(value: String) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl From<&'static str> for ExceptionType { + #[inline] + fn from(value: &'static str) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl AsRef for ExceptionType { + #[inline] + fn as_ref(&self) -> &str { + self.0.as_str() + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for ExceptionType { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str(self.as_ref()) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: ExceptionType) -> Self { + ::opentelemetry::KeyValue::new(ExceptionType::KEY, value.0) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: ExceptionType) -> Self { + value.0.into() + } +} + +/// Sequence number of the heartbeat. +#[derive(Debug, Clone, PartialEq, Copy)] +pub struct HeartbeatSequence(i64); + +#[allow(deprecated)] +impl HeartbeatSequence { + pub const KEY: &'static str = "heartbeat.sequence"; +} + +#[allow(deprecated)] +impl From for HeartbeatSequence { + #[inline] + fn from(value: i64) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for HeartbeatSequence { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + ::std::fmt::Display::fmt(&self.0, formatter) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: HeartbeatSequence) -> Self { + ::opentelemetry::KeyValue::new(HeartbeatSequence::KEY, value.0) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: HeartbeatSequence) -> Self { + value.0.into() + } +} + +/// Name of the component that sent the heartbeat. +#[derive(Debug, Clone, PartialEq)] +pub struct HeartbeatSource(::opentelemetry::StringValue); + +#[allow(deprecated)] +impl HeartbeatSource { + pub const KEY: &'static str = "heartbeat.source"; +} + +#[allow(deprecated)] +impl From<::opentelemetry::StringValue> for HeartbeatSource { + #[inline] + fn from(value: ::opentelemetry::StringValue) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl From for HeartbeatSource { + #[inline] + fn from(value: String) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl From<&'static str> for HeartbeatSource { + #[inline] + fn from(value: &'static str) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl AsRef for HeartbeatSource { + #[inline] + fn as_ref(&self) -> &str { + self.0.as_str() + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for HeartbeatSource { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str(self.as_ref()) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: HeartbeatSource) -> Self { + ::opentelemetry::KeyValue::new(HeartbeatSource::KEY, value.0) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: HeartbeatSource) -> Self { + value.0.into() + } +} + +/// Unique identifier of the host. +#[derive(Debug, Clone, PartialEq)] +pub struct HostId(::opentelemetry::StringValue); + +#[allow(deprecated)] +impl HostId { + pub const KEY: &'static str = "host.id"; +} + +#[allow(deprecated)] +impl From<::opentelemetry::StringValue> for HostId { + #[inline] + fn from(value: ::opentelemetry::StringValue) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl From for HostId { + #[inline] + fn from(value: String) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl From<&'static str> for HostId { + #[inline] + fn from(value: &'static str) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl AsRef for HostId { + #[inline] + fn as_ref(&self) -> &str { + self.0.as_str() + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for HostId { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str(self.as_ref()) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: HostId) -> Self { + ::opentelemetry::KeyValue::new(HostId::KEY, value.0) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: HostId) -> Self { + value.0.into() + } +} + +/// Name of the host. +#[derive(Debug, Clone, PartialEq)] +pub struct HostName(::opentelemetry::StringValue); + +#[allow(deprecated)] +impl HostName { + pub const KEY: &'static str = "host.name"; +} + +#[allow(deprecated)] +impl From<::opentelemetry::StringValue> for HostName { + #[inline] + fn from(value: ::opentelemetry::StringValue) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl From for HostName { + #[inline] + fn from(value: String) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl From<&'static str> for HostName { + #[inline] + fn from(value: &'static str) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl AsRef for HostName { + #[inline] + fn as_ref(&self) -> &str { + self.0.as_str() + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for HostName { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str(self.as_ref()) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: HostName) -> Self { + ::opentelemetry::KeyValue::new(HostName::KEY, value.0) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: HostName) -> Self { + value.0.into() + } +} diff --git a/templates/code/rust/tests/no_namespace/expected/event.rs b/templates/code/rust/tests/no_namespace/expected/event.rs new file mode 100644 index 0000000..9500e80 --- /dev/null +++ b/templates/code/rust/tests/no_namespace/expected/event.rs @@ -0,0 +1,49 @@ +#![allow(deprecated)] +use ::opentelemetry::logs::LogRecord; +use ::opentelemetry::trace::TraceContextExt; + +/// A noteworthy exception occurred. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct Exception; + +impl Exception { + pub const NAME: &'static str = "exception"; +} + +#[derive(Clone, Debug)] +pub enum ExceptionOption { + Severity(::opentelemetry::logs::Severity), + Timestamp(::std::time::SystemTime), + Message(super::attribute::ExceptionMessage), +} +/// A noteworthy exception occurred. +pub fn r#emit_exception(context: &::opentelemetry::Context, logger: &super::logger::Logger, r#exception_type: super::attribute::ExceptionType, options: impl IntoIterator) { + let mut severity = ::opentelemetry::logs::Severity::Info; + let mut timestamp = None; + let mut attributes = ::smallvec::SmallVec::<[ExceptionOption; 1]>::new(); + for option in options { + match option { + ExceptionOption::Severity(value) => severity = value, + ExceptionOption::Timestamp(value) => timestamp = Some(value), + attribute => attributes.push(attribute), + } + } + if !logger.inner().event_enabled(severity, "", Some(Exception::NAME)) { return; } + let _context_guard = context.clone().attach(); + let mut record = logger.inner().create_log_record(); + record.set_event_name(Exception::NAME); + record.set_severity_number(severity); + record.set_observed_timestamp(::std::time::SystemTime::now()); + if let Some(timestamp) = timestamp { record.set_timestamp(timestamp); } + let span = context.span(); + let span_context = span.span_context(); + if span_context.is_valid() { record.set_trace_context(span_context.trace_id(), span_context.span_id(), Some(span_context.trace_flags())); } + record.add_attribute(super::attribute::ExceptionType::KEY, r#exception_type); + for option in attributes { + match option { + ExceptionOption::Message(value) => record.add_attribute(super::attribute::ExceptionMessage::KEY, value), + ExceptionOption::Severity(_) | ExceptionOption::Timestamp(_) => continue, + } + } + logger.inner().emit(record); +} diff --git a/templates/code/rust/tests/no_namespace/expected/exceptionattr.rs b/templates/code/rust/tests/no_namespace/expected/exceptionattr.rs deleted file mode 100644 index 35411bd..0000000 --- a/templates/code/rust/tests/no_namespace/expected/exceptionattr.rs +++ /dev/null @@ -1,130 +0,0 @@ -// Generated by OpenTelemetry Weaver. -/// The exception message. -#[derive(Debug, Clone, PartialEq)] -pub struct MessageAttr(::opentelemetry::StringValue); - -#[allow(deprecated)] -impl MessageAttr { - pub const KEY: &'static str = "exception.message"; -} - -#[allow(deprecated)] -impl From<::opentelemetry::StringValue> for MessageAttr { - #[inline] - fn from(value: ::opentelemetry::StringValue) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl From for MessageAttr { - #[inline] - fn from(value: String) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl From<&'static str> for MessageAttr { - #[inline] - fn from(value: &'static str) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl AsRef for MessageAttr { - #[inline] - fn as_ref(&self) -> &str { - self.0.as_str() - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for MessageAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str(self.as_ref()) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: MessageAttr) -> Self { - ::opentelemetry::KeyValue::new(MessageAttr::KEY, value.0) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: MessageAttr) -> Self { - value.0.into() - } -} - -/// The type of the exception. -#[derive(Debug, Clone, PartialEq)] -pub struct TypeAttr(::opentelemetry::StringValue); - -#[allow(deprecated)] -impl TypeAttr { - pub const KEY: &'static str = "exception.type"; -} - -#[allow(deprecated)] -impl From<::opentelemetry::StringValue> for TypeAttr { - #[inline] - fn from(value: ::opentelemetry::StringValue) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl From for TypeAttr { - #[inline] - fn from(value: String) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl From<&'static str> for TypeAttr { - #[inline] - fn from(value: &'static str) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl AsRef for TypeAttr { - #[inline] - fn as_ref(&self) -> &str { - self.0.as_str() - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for TypeAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str(self.as_ref()) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: TypeAttr) -> Self { - ::opentelemetry::KeyValue::new(TypeAttr::KEY, value.0) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: TypeAttr) -> Self { - value.0.into() - } -} diff --git a/templates/code/rust/tests/no_namespace/expected/exceptionevent.rs b/templates/code/rust/tests/no_namespace/expected/exceptionevent.rs deleted file mode 100644 index 4123d2c..0000000 --- a/templates/code/rust/tests/no_namespace/expected/exceptionevent.rs +++ /dev/null @@ -1,41 +0,0 @@ -#![allow(deprecated)] -use ::opentelemetry::logs::LogRecord; -use ::opentelemetry::trace::TraceContextExt; - -#[derive(Clone, Debug)] -pub enum EventOption { - Severity(::opentelemetry::logs::Severity), - Timestamp(::std::time::SystemTime), - Message(super::exceptionattr::MessageAttr), -} -/// A noteworthy exception occurred. -pub fn r#emit(context: &::opentelemetry::Context, logger: &super::logger::Logger, r#exception_type: super::exceptionattr::TypeAttr, options: impl IntoIterator) { - let mut severity = ::opentelemetry::logs::Severity::Info; - let mut timestamp = None; - let mut attributes = ::smallvec::SmallVec::<[EventOption; 1]>::new(); - for option in options { - match option { - EventOption::Severity(value) => severity = value, - EventOption::Timestamp(value) => timestamp = Some(value), - attribute => attributes.push(attribute), - } - } - if !logger.inner().event_enabled(severity, "", Some("exception")) { return; } - let _context_guard = context.clone().attach(); - let mut record = logger.inner().create_log_record(); - record.set_event_name("exception"); - record.set_severity_number(severity); - record.set_observed_timestamp(::std::time::SystemTime::now()); - if let Some(timestamp) = timestamp { record.set_timestamp(timestamp); } - let span = context.span(); - let span_context = span.span_context(); - if span_context.is_valid() { record.set_trace_context(span_context.trace_id(), span_context.span_id(), Some(span_context.trace_flags())); } - record.add_attribute(super::exceptionattr::TypeAttr::KEY, r#exception_type); - for option in attributes { - match option { - EventOption::Message(value) => record.add_attribute(super::exceptionattr::MessageAttr::KEY, value), - EventOption::Severity(_) | EventOption::Timestamp(_) => continue, - } - } - logger.inner().emit(record); -} diff --git a/templates/code/rust/tests/no_namespace/expected/heartbeatattr.rs b/templates/code/rust/tests/no_namespace/expected/heartbeatattr.rs deleted file mode 100644 index b43d822..0000000 --- a/templates/code/rust/tests/no_namespace/expected/heartbeatattr.rs +++ /dev/null @@ -1,106 +0,0 @@ -// Generated by OpenTelemetry Weaver. -/// Sequence number of the heartbeat. -#[derive(Debug, Clone, PartialEq, Copy)] -pub struct SequenceAttr(i64); - -#[allow(deprecated)] -impl SequenceAttr { - pub const KEY: &'static str = "heartbeat.sequence"; -} - -#[allow(deprecated)] -impl From for SequenceAttr { - #[inline] - fn from(value: i64) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for SequenceAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - ::std::fmt::Display::fmt(&self.0, formatter) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: SequenceAttr) -> Self { - ::opentelemetry::KeyValue::new(SequenceAttr::KEY, value.0) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: SequenceAttr) -> Self { - value.0.into() - } -} - -/// Name of the component that sent the heartbeat. -#[derive(Debug, Clone, PartialEq)] -pub struct SourceAttr(::opentelemetry::StringValue); - -#[allow(deprecated)] -impl SourceAttr { - pub const KEY: &'static str = "heartbeat.source"; -} - -#[allow(deprecated)] -impl From<::opentelemetry::StringValue> for SourceAttr { - #[inline] - fn from(value: ::opentelemetry::StringValue) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl From for SourceAttr { - #[inline] - fn from(value: String) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl From<&'static str> for SourceAttr { - #[inline] - fn from(value: &'static str) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl AsRef for SourceAttr { - #[inline] - fn as_ref(&self) -> &str { - self.0.as_str() - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for SourceAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str(self.as_ref()) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: SourceAttr) -> Self { - ::opentelemetry::KeyValue::new(SourceAttr::KEY, value.0) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: SourceAttr) -> Self { - value.0.into() - } -} diff --git a/templates/code/rust/tests/no_namespace/expected/hostattr.rs b/templates/code/rust/tests/no_namespace/expected/hostattr.rs deleted file mode 100644 index b8c90eb..0000000 --- a/templates/code/rust/tests/no_namespace/expected/hostattr.rs +++ /dev/null @@ -1,130 +0,0 @@ -// Generated by OpenTelemetry Weaver. -/// Unique identifier of the host. -#[derive(Debug, Clone, PartialEq)] -pub struct IdAttr(::opentelemetry::StringValue); - -#[allow(deprecated)] -impl IdAttr { - pub const KEY: &'static str = "host.id"; -} - -#[allow(deprecated)] -impl From<::opentelemetry::StringValue> for IdAttr { - #[inline] - fn from(value: ::opentelemetry::StringValue) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl From for IdAttr { - #[inline] - fn from(value: String) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl From<&'static str> for IdAttr { - #[inline] - fn from(value: &'static str) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl AsRef for IdAttr { - #[inline] - fn as_ref(&self) -> &str { - self.0.as_str() - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for IdAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str(self.as_ref()) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: IdAttr) -> Self { - ::opentelemetry::KeyValue::new(IdAttr::KEY, value.0) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: IdAttr) -> Self { - value.0.into() - } -} - -/// Name of the host. -#[derive(Debug, Clone, PartialEq)] -pub struct NameAttr(::opentelemetry::StringValue); - -#[allow(deprecated)] -impl NameAttr { - pub const KEY: &'static str = "host.name"; -} - -#[allow(deprecated)] -impl From<::opentelemetry::StringValue> for NameAttr { - #[inline] - fn from(value: ::opentelemetry::StringValue) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl From for NameAttr { - #[inline] - fn from(value: String) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl From<&'static str> for NameAttr { - #[inline] - fn from(value: &'static str) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl AsRef for NameAttr { - #[inline] - fn as_ref(&self) -> &str { - self.0.as_str() - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for NameAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str(self.as_ref()) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: NameAttr) -> Self { - ::opentelemetry::KeyValue::new(NameAttr::KEY, value.0) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: NameAttr) -> Self { - value.0.into() - } -} diff --git a/templates/code/rust/tests/no_namespace/expected/mod.rs b/templates/code/rust/tests/no_namespace/expected/mod.rs index fc6773d..b2d4661 100644 --- a/templates/code/rust/tests/no_namespace/expected/mod.rs +++ b/templates/code/rust/tests/no_namespace/expected/mod.rs @@ -1,13 +1,11 @@ // Generated by OpenTelemetry Weaver. pub const SCHEMA_URL: &str = "https://example.com/schemas/no_namespace/1.0.0"; -pub mod exceptionattr; -pub mod heartbeatattr; -pub mod hostattr; +pub mod attribute; pub mod scope; pub mod options; pub mod tracer; pub mod logger; -pub mod exceptionevent; -pub mod heartbeatspan; -pub mod hostentity; +pub mod event; +pub mod resource; +pub mod trace; diff --git a/templates/code/rust/tests/no_namespace/expected/hostentity.rs b/templates/code/rust/tests/no_namespace/expected/resource.rs similarity index 63% rename from templates/code/rust/tests/no_namespace/expected/hostentity.rs rename to templates/code/rust/tests/no_namespace/expected/resource.rs index 49100c6..7de8b12 100644 --- a/templates/code/rust/tests/no_namespace/expected/hostentity.rs +++ b/templates/code/rust/tests/no_namespace/expected/resource.rs @@ -1,14 +1,14 @@ // Code generated by weaver. DO NOT EDIT. #![allow(deprecated)] #[derive(Clone, Debug)] -pub enum EntityAttr { - Name(super::hostattr::NameAttr), +pub enum HostAttr { + Name(super::attribute::HostName), } -impl From for ::opentelemetry::KeyValue { - fn from(value: EntityAttr) -> Self { +impl From for ::opentelemetry::KeyValue { + fn from(value: HostAttr) -> Self { match value { - EntityAttr::Name(value) => ::opentelemetry::KeyValue::from(value), + HostAttr::Name(value) => ::opentelemetry::KeyValue::from(value), } } } @@ -16,13 +16,15 @@ impl From for ::opentelemetry::KeyValue { /// Identifies the entity: `host.id`. /// Describes the entity: `host.name`. #[derive(Clone, Debug)] -pub struct Entity { - r#host_id: super::hostattr::IdAttr, - options: ::smallvec::SmallVec<[EntityAttr; 1]>, +pub struct Host { + r#host_id: super::attribute::HostId, + options: ::smallvec::SmallVec<[HostAttr; 1]>, } -impl Entity { - pub fn new(r#host_id: super::hostattr::IdAttr, options: impl IntoIterator) -> Self { +impl Host { + pub const NAME: &'static str = "host"; + + pub fn new(r#host_id: super::attribute::HostId, options: impl IntoIterator) -> Self { Self { r#host_id, options: options.into_iter().collect(), @@ -36,8 +38,8 @@ impl Entity { } } -impl From for ::opentelemetry_sdk::Resource { - fn from(value: Entity) -> Self { +impl From for ::opentelemetry_sdk::Resource { + fn from(value: Host) -> Self { let attributes = [ ::opentelemetry::KeyValue::from(value.r#host_id), ].into_iter().chain(value.options.into_iter().map(::opentelemetry::KeyValue::from)); diff --git a/templates/code/rust/tests/no_namespace/expected/heartbeatspan.rs b/templates/code/rust/tests/no_namespace/expected/trace.rs similarity index 57% rename from templates/code/rust/tests/no_namespace/expected/heartbeatspan.rs rename to templates/code/rust/tests/no_namespace/expected/trace.rs index 4b05f1f..fc27f65 100644 --- a/templates/code/rust/tests/no_namespace/expected/heartbeatspan.rs +++ b/templates/code/rust/tests/no_namespace/expected/trace.rs @@ -1,50 +1,50 @@ #![allow(deprecated)] -use ::opentelemetry::trace::{TraceContextExt, Tracer}; +use ::opentelemetry::trace::{TraceContextExt as _, Tracer as _}; #[derive(Clone, Debug)] -pub enum StartAttr { - Source(super::heartbeatattr::SourceAttr), +pub enum HeartbeatStartAttr { + Source(super::attribute::HeartbeatSource), } -impl From for ::opentelemetry::KeyValue { - fn from(value: StartAttr) -> Self { +impl From for ::opentelemetry::KeyValue { + fn from(value: HeartbeatStartAttr) -> Self { match value { - StartAttr::Source(value) => ::opentelemetry::KeyValue::from(value), + HeartbeatStartAttr::Source(value) => ::opentelemetry::KeyValue::from(value), } } } #[derive(Clone, Debug)] -pub enum Attr { - Source(super::heartbeatattr::SourceAttr), +pub enum HeartbeatAttr { + Source(super::attribute::HeartbeatSource), } -impl From for StartAttr { - fn from(value: Attr) -> Self { +impl From for HeartbeatStartAttr { + fn from(value: HeartbeatAttr) -> Self { match value { - Attr::Source(value) => Self::Source(value), + HeartbeatAttr::Source(value) => Self::Source(value), } } } #[derive(Clone, Debug, Default)] -pub struct Name(::std::borrow::Cow<'static, str>); +pub struct HeartbeatName(::std::borrow::Cow<'static, str>); -impl From<&'static str> for Name { +impl From<&'static str> for HeartbeatName { fn from(value: &'static str) -> Self { Self(::std::borrow::Cow::Borrowed(value)) } } -impl From for Name { +impl From for HeartbeatName { fn from(value: String) -> Self { Self(::std::borrow::Cow::Owned(value)) } } -impl From<::std::borrow::Cow<'static, str>> for Name { +impl From<::std::borrow::Cow<'static, str>> for HeartbeatName { fn from(value: ::std::borrow::Cow<'static, str>) -> Self { Self(value) } } /// A periodic liveness signal. -pub struct Span { +pub struct Heartbeat { span: S, } -impl Span { +impl Heartbeat { pub fn into_context(self, parent: &::opentelemetry::Context) -> ::opentelemetry::Context where S: Send + Sync + 'static, { @@ -55,23 +55,27 @@ impl Span { pub fn end_with_timestamp(&mut self, timestamp: ::std::time::SystemTime) { ::opentelemetry::trace::Span::end_with_timestamp(&mut self.span, timestamp); } pub fn record_error(&mut self, error: &dyn ::std::error::Error) { ::opentelemetry::trace::Span::record_error(&mut self.span, error); } pub fn set_status(&mut self, status: ::opentelemetry::trace::Status) { ::opentelemetry::trace::Span::set_status(&mut self.span, status); } - pub fn set_attributes(&mut self, attributes: impl IntoIterator) { - for attribute in attributes { ::opentelemetry::trace::Span::set_attribute(&mut self.span, ::opentelemetry::KeyValue::from(StartAttr::from(attribute))); } + pub fn set_attributes(&mut self, attributes: impl IntoIterator) { + for attribute in attributes { ::opentelemetry::trace::Span::set_attribute(&mut self.span, ::opentelemetry::KeyValue::from(HeartbeatStartAttr::from(attribute))); } } } -impl Default for Span { +impl Heartbeat { + pub const NAME: &'static str = "heartbeat"; +} + +impl Default for Heartbeat { fn default() -> Self { - Self { span: super::tracer::Tracer::default().inner().start("heartbeat") } + Self { span: super::tracer::Tracer::default().inner().start(Self::NAME) } } } -pub fn r#start(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer, name: Name, r#heartbeat_sequence: super::heartbeatattr::SequenceAttr, options: impl IntoIterator) -> Span { - let name = if name.0.is_empty() { ::std::borrow::Cow::Borrowed("heartbeat") } else { name.0 }; +pub fn r#start_heartbeat(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer, name: HeartbeatName, r#heartbeat_sequence: super::attribute::HeartbeatSequence, options: impl IntoIterator) -> Heartbeat { + let name = if name.0.is_empty() { ::std::borrow::Cow::Borrowed(Heartbeat::NAME) } else { name.0 }; let attributes: [::opentelemetry::KeyValue; 1] = [::opentelemetry::KeyValue::from(r#heartbeat_sequence)]; let span = tracer.inner().span_builder(name) .with_kind(::opentelemetry::trace::SpanKind::Internal) .with_attributes(attributes.into_iter().chain(options.into_iter().map(::opentelemetry::KeyValue::from))) .start_with_context(tracer.inner(), context); - Span { span } + Heartbeat { span } } diff --git a/templates/code/rust/tests/no_namespace/test.rs b/templates/code/rust/tests/no_namespace/test.rs index cbc0731..0eba5d6 100644 --- a/templates/code/rust/tests/no_namespace/test.rs +++ b/templates/code/rust/tests/no_namespace/test.rs @@ -1,6 +1,10 @@ use generated_semconv::{ - exceptionattr, exceptionevent, heartbeatattr, heartbeatspan, logger, - options::InstrumentationOptions, tracer, + attribute, + event, + trace, + logger, + options::InstrumentationOptions, + tracer, }; use opentelemetry::logs::{AnyValue, Severity}; use opentelemetry_sdk::logs::{InMemoryLogExporter, SdkLoggerProvider}; @@ -14,13 +18,13 @@ fn empty_short_names_expose_bare_functions_and_unambiguous_options() { .with_simple_exporter(logs.clone()) .build(); let logger = logger::Logger::new(&logger_provider, InstrumentationOptions::default()); - exceptionevent::emit( + event::emit_exception( &context, &logger, - exceptionattr::TypeAttr::from("ValueError"), + attribute::ExceptionType::from("ValueError"), [ - exceptionevent::EventOption::Message(exceptionattr::MessageAttr::from("failed")), - exceptionevent::EventOption::Severity(Severity::Warn), + event::ExceptionOption::Message(attribute::ExceptionMessage::from("failed")), + event::ExceptionOption::Severity(Severity::Warn), ], ); logger_provider.force_flush().unwrap(); @@ -37,13 +41,13 @@ fn empty_short_names_expose_bare_functions_and_unambiguous_options() { .with_simple_exporter(spans.clone()) .build(); let tracer = tracer::Tracer::new(&tracer_provider, InstrumentationOptions::default()); - let mut span = heartbeatspan::start( + let mut span = trace::start_heartbeat( &context, &tracer, - heartbeatspan::Name::default(), - heartbeatattr::SequenceAttr::from(7), - [heartbeatspan::StartAttr::Source( - heartbeatattr::SourceAttr::from("worker"), + trace::HeartbeatName::default(), + attribute::HeartbeatSequence::from(7), + [trace::HeartbeatStartAttr::Source( + attribute::HeartbeatSource::from("worker"), )], ); span.end(); diff --git a/templates/code/rust/tests/params/expected/attribute.rs b/templates/code/rust/tests/params/expected/attribute.rs new file mode 100644 index 0000000..cced865 --- /dev/null +++ b/templates/code/rust/tests/params/expected/attribute.rs @@ -0,0 +1,195 @@ +// Generated by OpenTelemetry Weaver. +/// Identifier of the invoice. +#[derive(Debug, Clone, PartialEq)] +pub struct BillingInvoiceId(::opentelemetry::StringValue); + +#[allow(deprecated)] +impl BillingInvoiceId { + pub const KEY: &'static str = "acme.billing.invoice.id"; +} + +#[allow(deprecated)] +impl From<::opentelemetry::StringValue> for BillingInvoiceId { + #[inline] + fn from(value: ::opentelemetry::StringValue) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl From for BillingInvoiceId { + #[inline] + fn from(value: String) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl From<&'static str> for BillingInvoiceId { + #[inline] + fn from(value: &'static str) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl AsRef for BillingInvoiceId { + #[inline] + fn as_ref(&self) -> &str { + self.0.as_str() + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for BillingInvoiceId { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str(self.as_ref()) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: BillingInvoiceId) -> Self { + ::opentelemetry::KeyValue::new(BillingInvoiceId::KEY, value.0) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: BillingInvoiceId) -> Self { + value.0.into() + } +} + +/// ISO 4217 currency code of the amount. +#[derive(Debug, Clone, PartialEq)] +pub struct BillingCurrency(::opentelemetry::StringValue); + +#[allow(deprecated)] +impl BillingCurrency { + pub const KEY: &'static str = "billing.currency"; +} + +#[allow(deprecated)] +impl From<::opentelemetry::StringValue> for BillingCurrency { + #[inline] + fn from(value: ::opentelemetry::StringValue) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl From for BillingCurrency { + #[inline] + fn from(value: String) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl From<&'static str> for BillingCurrency { + #[inline] + fn from(value: &'static str) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl AsRef for BillingCurrency { + #[inline] + fn as_ref(&self) -> &str { + self.0.as_str() + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for BillingCurrency { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str(self.as_ref()) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: BillingCurrency) -> Self { + ::opentelemetry::KeyValue::new(BillingCurrency::KEY, value.0) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: BillingCurrency) -> Self { + value.0.into() + } +} + +/// URL the request was sent to. +#[derive(Debug, Clone, PartialEq)] +pub struct MyappRequestUrl(::opentelemetry::StringValue); + +#[allow(deprecated)] +impl MyappRequestUrl { + pub const KEY: &'static str = "myapp.request.url"; +} + +#[allow(deprecated)] +impl From<::opentelemetry::StringValue> for MyappRequestUrl { + #[inline] + fn from(value: ::opentelemetry::StringValue) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl From for MyappRequestUrl { + #[inline] + fn from(value: String) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl From<&'static str> for MyappRequestUrl { + #[inline] + fn from(value: &'static str) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl AsRef for MyappRequestUrl { + #[inline] + fn as_ref(&self) -> &str { + self.0.as_str() + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for MyappRequestUrl { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str(self.as_ref()) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: MyappRequestUrl) -> Self { + ::opentelemetry::KeyValue::new(MyappRequestUrl::KEY, value.0) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: MyappRequestUrl) -> Self { + value.0.into() + } +} diff --git a/templates/code/rust/tests/params/expected/billingattr.rs b/templates/code/rust/tests/params/expected/billingattr.rs deleted file mode 100644 index c00f2e5..0000000 --- a/templates/code/rust/tests/params/expected/billingattr.rs +++ /dev/null @@ -1,130 +0,0 @@ -// Generated by OpenTelemetry Weaver. -/// Identifier of the invoice. -#[derive(Debug, Clone, PartialEq)] -pub struct InvoiceIdAttr(::opentelemetry::StringValue); - -#[allow(deprecated)] -impl InvoiceIdAttr { - pub const KEY: &'static str = "acme.billing.invoice.id"; -} - -#[allow(deprecated)] -impl From<::opentelemetry::StringValue> for InvoiceIdAttr { - #[inline] - fn from(value: ::opentelemetry::StringValue) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl From for InvoiceIdAttr { - #[inline] - fn from(value: String) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl From<&'static str> for InvoiceIdAttr { - #[inline] - fn from(value: &'static str) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl AsRef for InvoiceIdAttr { - #[inline] - fn as_ref(&self) -> &str { - self.0.as_str() - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for InvoiceIdAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str(self.as_ref()) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: InvoiceIdAttr) -> Self { - ::opentelemetry::KeyValue::new(InvoiceIdAttr::KEY, value.0) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: InvoiceIdAttr) -> Self { - value.0.into() - } -} - -/// ISO 4217 currency code of the amount. -#[derive(Debug, Clone, PartialEq)] -pub struct CurrencyAttr(::opentelemetry::StringValue); - -#[allow(deprecated)] -impl CurrencyAttr { - pub const KEY: &'static str = "billing.currency"; -} - -#[allow(deprecated)] -impl From<::opentelemetry::StringValue> for CurrencyAttr { - #[inline] - fn from(value: ::opentelemetry::StringValue) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl From for CurrencyAttr { - #[inline] - fn from(value: String) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl From<&'static str> for CurrencyAttr { - #[inline] - fn from(value: &'static str) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl AsRef for CurrencyAttr { - #[inline] - fn as_ref(&self) -> &str { - self.0.as_str() - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for CurrencyAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str(self.as_ref()) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: CurrencyAttr) -> Self { - ::opentelemetry::KeyValue::new(CurrencyAttr::KEY, value.0) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: CurrencyAttr) -> Self { - value.0.into() - } -} diff --git a/templates/code/rust/tests/params/expected/billingmetric.rs b/templates/code/rust/tests/params/expected/billingmetric.rs deleted file mode 100644 index 7b20973..0000000 --- a/templates/code/rust/tests/params/expected/billingmetric.rs +++ /dev/null @@ -1,40 +0,0 @@ -#![allow(deprecated)] -#[derive(Clone, Debug)] -pub enum InvoiceAmountHistogramAttr { - Currency(super::billingattr::CurrencyAttr), - RequestUrl(super::myappattr::RequestUrlAttr), -} - -impl From for ::opentelemetry::KeyValue { - fn from(value: InvoiceAmountHistogramAttr) -> Self { - match value { - InvoiceAmountHistogramAttr::Currency(value) => ::opentelemetry::KeyValue::from(value), - InvoiceAmountHistogramAttr::RequestUrl(value) => ::opentelemetry::KeyValue::from(value), - } - } -} -/// Amount of each issued invoice. -#[derive(Clone)] -pub struct InvoiceAmountHistogram { - instrument: ::opentelemetry::metrics::Histogram, -} - -impl InvoiceAmountHistogram { - pub fn new(meter: &super::meter::Meter) -> Self { - let instrument = meter.inner().f64_histogram("acme.billing.invoice.amount") - .with_description("Amount of each issued invoice.") - .with_unit("{currency_unit}") - .build(); - Self { instrument } - } - pub fn record(&self, value: f64, r#billing_invoice_id: super::billingattr::InvoiceIdAttr, options: impl IntoIterator) { - let mut attributes = ::smallvec::SmallVec::<[::opentelemetry::KeyValue; 3]>::new(); - attributes.extend([::opentelemetry::KeyValue::from(r#billing_invoice_id)]); - attributes.extend(options.into_iter().map(::opentelemetry::KeyValue::from)); - self.instrument.record(value, &attributes); - } -} - -impl Default for InvoiceAmountHistogram { - fn default() -> Self { Self::new(&super::meter::Meter::default()) } -} diff --git a/templates/code/rust/tests/params/expected/billingevent.rs b/templates/code/rust/tests/params/expected/event.rs similarity index 50% rename from templates/code/rust/tests/params/expected/billingevent.rs rename to templates/code/rust/tests/params/expected/event.rs index d8ecae9..ca3ea2b 100644 --- a/templates/code/rust/tests/params/expected/billingevent.rs +++ b/templates/code/rust/tests/params/expected/event.rs @@ -2,31 +2,39 @@ use ::opentelemetry::logs::LogRecord; use ::opentelemetry::trace::TraceContextExt; +/// An invoice was issued. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +pub struct BillingInvoiceIssued; + +impl BillingInvoiceIssued { + pub const NAME: &'static str = "acme.billing.invoice.issued"; +} + #[derive(Clone, Debug)] -pub enum InvoiceIssuedOption { +pub enum BillingInvoiceIssuedOption { Severity(::opentelemetry::logs::Severity), Timestamp(::std::time::SystemTime), } /// An invoice was issued. -pub fn r#emit_invoice_issued(context: &::opentelemetry::Context, logger: &super::logger::Logger, r#billing_invoice_id: super::billingattr::InvoiceIdAttr, options: impl IntoIterator) { +pub fn r#emit_billing_invoice_issued(context: &::opentelemetry::Context, logger: &super::logger::Logger, r#billing_invoice_id: super::attribute::BillingInvoiceId, options: impl IntoIterator) { let mut severity = ::opentelemetry::logs::Severity::Info; let mut timestamp = None; for option in options { match option { - InvoiceIssuedOption::Severity(value) => severity = value, - InvoiceIssuedOption::Timestamp(value) => timestamp = Some(value), + BillingInvoiceIssuedOption::Severity(value) => severity = value, + BillingInvoiceIssuedOption::Timestamp(value) => timestamp = Some(value), } } - if !logger.inner().event_enabled(severity, "", Some("acme.billing.invoice.issued")) { return; } + if !logger.inner().event_enabled(severity, "", Some(BillingInvoiceIssued::NAME)) { return; } let _context_guard = context.clone().attach(); let mut record = logger.inner().create_log_record(); - record.set_event_name("acme.billing.invoice.issued"); + record.set_event_name(BillingInvoiceIssued::NAME); record.set_severity_number(severity); record.set_observed_timestamp(::std::time::SystemTime::now()); if let Some(timestamp) = timestamp { record.set_timestamp(timestamp); } let span = context.span(); let span_context = span.span_context(); if span_context.is_valid() { record.set_trace_context(span_context.trace_id(), span_context.span_id(), Some(span_context.trace_flags())); } - record.add_attribute(super::billingattr::InvoiceIdAttr::KEY, r#billing_invoice_id); + record.add_attribute(super::attribute::BillingInvoiceId::KEY, r#billing_invoice_id); logger.inner().emit(record); } diff --git a/templates/code/rust/tests/params/expected/metric.rs b/templates/code/rust/tests/params/expected/metric.rs new file mode 100644 index 0000000..21213a4 --- /dev/null +++ b/templates/code/rust/tests/params/expected/metric.rs @@ -0,0 +1,44 @@ +#![allow(deprecated)] +#[derive(Clone, Debug)] +pub enum BillingInvoiceAmountAttr { + Currency(super::attribute::BillingCurrency), + RequestUrl(super::attribute::MyappRequestUrl), +} + +impl From for ::opentelemetry::KeyValue { + fn from(value: BillingInvoiceAmountAttr) -> Self { + match value { + BillingInvoiceAmountAttr::Currency(value) => ::opentelemetry::KeyValue::from(value), + BillingInvoiceAmountAttr::RequestUrl(value) => ::opentelemetry::KeyValue::from(value), + } + } +} +/// Amount of each issued invoice. +#[derive(Clone)] +pub struct BillingInvoiceAmount { + instrument: ::opentelemetry::metrics::Histogram, +} + +impl BillingInvoiceAmount { + pub const NAME: &'static str = "acme.billing.invoice.amount"; + pub const UNIT: &'static str = "{currency_unit}"; + pub const DESCRIPTION: &'static str = "Amount of each issued invoice."; + + pub fn new(meter: &super::meter::Meter) -> Self { + let instrument = meter.inner().f64_histogram(Self::NAME) + .with_description(Self::DESCRIPTION) + .with_unit(Self::UNIT) + .build(); + Self { instrument } + } + pub fn record(&self, value: f64, r#billing_invoice_id: super::attribute::BillingInvoiceId, options: impl IntoIterator) { + let mut attributes = ::smallvec::SmallVec::<[::opentelemetry::KeyValue; 3]>::new(); + attributes.extend([::opentelemetry::KeyValue::from(r#billing_invoice_id)]); + attributes.extend(options.into_iter().map(::opentelemetry::KeyValue::from)); + self.instrument.record(value, &attributes); + } +} + +impl Default for BillingInvoiceAmount { + fn default() -> Self { Self::new(&super::meter::Meter::default()) } +} diff --git a/templates/code/rust/tests/params/expected/mod.rs b/templates/code/rust/tests/params/expected/mod.rs index bc8ad5f..5736ab1 100644 --- a/templates/code/rust/tests/params/expected/mod.rs +++ b/templates/code/rust/tests/params/expected/mod.rs @@ -3,14 +3,13 @@ // Source: model/ // Regenerate: mise run generate pub const SCHEMA_URL: &str = "https://example.com/schemas/params/1.0.0"; -pub mod billingattr; -pub mod myappattr; +pub mod attribute; pub mod scope; pub mod options; pub mod meter; pub mod tracer; pub mod logger; -pub mod billingevent; -pub mod billingmetric; -pub mod billingspan; +pub mod event; +pub mod metric; +pub mod trace; diff --git a/templates/code/rust/tests/params/expected/myappattr.rs b/templates/code/rust/tests/params/expected/myappattr.rs deleted file mode 100644 index a771ccb..0000000 --- a/templates/code/rust/tests/params/expected/myappattr.rs +++ /dev/null @@ -1,65 +0,0 @@ -// Generated by OpenTelemetry Weaver. -/// URL the request was sent to. -#[derive(Debug, Clone, PartialEq)] -pub struct RequestUrlAttr(::opentelemetry::StringValue); - -#[allow(deprecated)] -impl RequestUrlAttr { - pub const KEY: &'static str = "myapp.request.url"; -} - -#[allow(deprecated)] -impl From<::opentelemetry::StringValue> for RequestUrlAttr { - #[inline] - fn from(value: ::opentelemetry::StringValue) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl From for RequestUrlAttr { - #[inline] - fn from(value: String) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl From<&'static str> for RequestUrlAttr { - #[inline] - fn from(value: &'static str) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl AsRef for RequestUrlAttr { - #[inline] - fn as_ref(&self) -> &str { - self.0.as_str() - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for RequestUrlAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str(self.as_ref()) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: RequestUrlAttr) -> Self { - ::opentelemetry::KeyValue::new(RequestUrlAttr::KEY, value.0) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: RequestUrlAttr) -> Self { - value.0.into() - } -} diff --git a/templates/code/rust/tests/params/expected/billingspan.rs b/templates/code/rust/tests/params/expected/trace.rs similarity index 68% rename from templates/code/rust/tests/params/expected/billingspan.rs rename to templates/code/rust/tests/params/expected/trace.rs index d745290..26c676e 100644 --- a/templates/code/rust/tests/params/expected/billingspan.rs +++ b/templates/code/rust/tests/params/expected/trace.rs @@ -1,13 +1,13 @@ #![allow(deprecated)] -use ::opentelemetry::trace::{TraceContextExt, Tracer}; -use ::std::fmt::Write; +use ::opentelemetry::trace::{TraceContextExt as _, Tracer as _}; +use ::std::fmt::Write as _; /// An invoice is being issued. -pub struct InvoiceIssueSpan { +pub struct BillingInvoiceIssue { span: S, } -impl InvoiceIssueSpan { +impl BillingInvoiceIssue { pub fn into_context(self, parent: &::opentelemetry::Context) -> ::opentelemetry::Context where S: Send + Sync + 'static, { @@ -20,13 +20,17 @@ impl InvoiceIssueSpan { pub fn set_status(&mut self, status: ::opentelemetry::trace::Status) { ::opentelemetry::trace::Span::set_status(&mut self.span, status); } } -impl Default for InvoiceIssueSpan { +impl BillingInvoiceIssue { + pub const NAME: &'static str = "acme.billing.invoice.issue"; +} + +impl Default for BillingInvoiceIssue { fn default() -> Self { - Self { span: super::tracer::Tracer::default().inner().start("acme.billing.invoice.issue") } + Self { span: super::tracer::Tracer::default().inner().start(Self::NAME) } } } -pub fn r#start_invoice_issue(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer, r#billing_invoice_id: super::billingattr::InvoiceIdAttr) -> InvoiceIssueSpan { +pub fn r#start_billing_invoice_issue(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer, r#billing_invoice_id: super::attribute::BillingInvoiceId) -> BillingInvoiceIssue { let mut name = String::with_capacity("invoice ".len() + ::std::convert::AsRef::::as_ref(&r#billing_invoice_id).len()); name.push_str("invoice "); write!(&mut name, "{}", r#billing_invoice_id).expect("writing a span name to String cannot fail"); @@ -35,5 +39,5 @@ pub fn r#start_invoice_issue(context: &::open .with_kind(::opentelemetry::trace::SpanKind::Internal) .with_attributes(attributes) .start_with_context(tracer.inner(), context); - InvoiceIssueSpan { span } + BillingInvoiceIssue { span } } diff --git a/templates/code/rust/tests/params/test.rs b/templates/code/rust/tests/params/test.rs index b6ada57..70ad45e 100644 --- a/templates/code/rust/tests/params/test.rs +++ b/templates/code/rust/tests/params/test.rs @@ -1,6 +1,14 @@ use generated_semconv::{ - billingattr, billingevent, billingmetric, billingspan, logger, meter, - options::InstrumentationOptions, scope::Scope, tracer, SCHEMA_URL, + attribute, + event, + metric, + trace, + logger, + meter, + options::InstrumentationOptions, + scope::Scope, + tracer, + SCHEMA_URL, }; use opentelemetry::{InstrumentationScope, KeyValue}; use opentelemetry_sdk::logs::{InMemoryLogExporter, SdkLoggerProvider}; @@ -36,8 +44,8 @@ fn configured_identity_is_shared_by_metrics_spans_and_events() { .build(), ) .build(); - billingmetric::InvoiceAmountHistogram::new(&meter::Meter::new(&metric_provider, options())) - .record(12.5, billingattr::InvoiceIdAttr::from("invoice-1"), []); + metric::BillingInvoiceAmount::new(&meter::Meter::new(&metric_provider, options())) + .record(12.5, attribute::BillingInvoiceId::from("invoice-1"), []); metric_provider.force_flush().unwrap(); let metrics = metric_exporter.get_finished_metrics().unwrap(); configured_identity(metrics[0].scope_metrics().next().unwrap().scope()); @@ -48,10 +56,10 @@ fn configured_identity_is_shared_by_metrics_spans_and_events() { .build(); let tracer = tracer::Tracer::new(&span_provider, options()); let context = opentelemetry::Context::new(); - let mut span = billingspan::start_invoice_issue( + let mut span = trace::start_billing_invoice_issue( &context, &tracer, - billingattr::InvoiceIdAttr::from("invoice-1"), + attribute::BillingInvoiceId::from("invoice-1"), ); span.end(); span_provider.force_flush().unwrap(); @@ -63,10 +71,10 @@ fn configured_identity_is_shared_by_metrics_spans_and_events() { let log_provider = SdkLoggerProvider::builder() .with_simple_exporter(log_exporter.clone()) .build(); - billingevent::emit_invoice_issued( + event::emit_billing_invoice_issued( &context, &logger::Logger::new(&log_provider, options()), - billingattr::InvoiceIdAttr::from("invoice-1"), + attribute::BillingInvoiceId::from("invoice-1"), [], ); log_provider.force_flush().unwrap(); diff --git a/templates/code/rust/tests/spans/compile-fail/missing_required.rs b/templates/code/rust/tests/spans/compile-fail/missing_required.rs index 8cb0571..d1ce532 100644 --- a/templates/code/rust/tests/spans/compile-fail/missing_required.rs +++ b/templates/code/rust/tests/spans/compile-fail/missing_required.rs @@ -1,6 +1,6 @@ -use generated_semconv::{myappspan, tracer}; +use generated_semconv::{trace, tracer}; fn main() { - myappspan::start_task_dispatch( + trace::start_myapp_task_dispatch( &opentelemetry::Context::new(), &tracer::Tracer::default(), [], diff --git a/templates/code/rust/tests/spans/compile-fail/sampling_attribute_late.expected-error.txt b/templates/code/rust/tests/spans/compile-fail/sampling_attribute_late.expected-error.txt index ab8b948..401fc2e 100644 --- a/templates/code/rust/tests/spans/compile-fail/sampling_attribute_late.expected-error.txt +++ b/templates/code/rust/tests/spans/compile-fail/sampling_attribute_late.expected-error.txt @@ -1 +1 @@ -expected `TaskDispatchAttr`, found `TaskDispatchStartAttr` +expected `MyappTaskDispatchAttr`, found `MyappTaskDispatchStartAttr` diff --git a/templates/code/rust/tests/spans/compile-fail/sampling_attribute_late.rs b/templates/code/rust/tests/spans/compile-fail/sampling_attribute_late.rs index 7a50d5b..2310dab 100644 --- a/templates/code/rust/tests/spans/compile-fail/sampling_attribute_late.rs +++ b/templates/code/rust/tests/spans/compile-fail/sampling_attribute_late.rs @@ -1,7 +1,7 @@ -use generated_semconv::{myappattr, myappspan}; +use generated_semconv::{attribute, trace}; fn main() { - let mut span = myappspan::TaskDispatchSpan::default(); - span.set_attributes([myappspan::TaskDispatchStartAttr::TaskId( - myappattr::TaskIdAttr::from("task-1"), + let mut span = trace::MyappTaskDispatch::default(); + span.set_attributes([trace::MyappTaskDispatchStartAttr::TaskId( + attribute::MyappTaskId::from("task-1"), )]); } diff --git a/templates/code/rust/tests/spans/expected/attribute.rs b/templates/code/rust/tests/spans/expected/attribute.rs new file mode 100644 index 0000000..c3c4710 --- /dev/null +++ b/templates/code/rust/tests/spans/expected/attribute.rs @@ -0,0 +1,602 @@ +// Generated by OpenTelemetry Weaver. +/// Synthetic naming value. +#[derive(Debug, Clone, PartialEq)] +pub struct MyappArrayFlags(Vec); + +#[allow(deprecated)] +impl MyappArrayFlags { + pub const KEY: &'static str = "myapp.array.flags"; +} + +#[allow(deprecated)] +impl From> for MyappArrayFlags { + #[inline] + fn from(value: Vec) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl AsRef<[bool]> for MyappArrayFlags { + #[inline] + fn as_ref(&self) -> &[bool] { + &self.0 + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for MyappArrayFlags { + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str("[")?; + for (index, value) in self.0.iter().enumerate() { + if index != 0 { + formatter.write_str(",")?; + } + ::std::fmt::Display::fmt(value, formatter)?; + } + formatter.write_str("]") + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: MyappArrayFlags) -> Self { + ::opentelemetry::KeyValue::new(MyappArrayFlags::KEY, ::opentelemetry::Value::Array(::opentelemetry::Array::Bool(value.0))) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: MyappArrayFlags) -> Self { + value.0.into_iter().collect::<::opentelemetry::logs::AnyValue>() + } +} + +/// Synthetic naming value. +#[derive(Debug, Clone, PartialEq)] +pub struct MyappArrayIndices(Vec); + +#[allow(deprecated)] +impl MyappArrayIndices { + pub const KEY: &'static str = "myapp.array.indices"; +} + +#[allow(deprecated)] +impl From> for MyappArrayIndices { + #[inline] + fn from(value: Vec) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl AsRef<[i64]> for MyappArrayIndices { + #[inline] + fn as_ref(&self) -> &[i64] { + &self.0 + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for MyappArrayIndices { + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str("[")?; + for (index, value) in self.0.iter().enumerate() { + if index != 0 { + formatter.write_str(",")?; + } + ::std::fmt::Display::fmt(value, formatter)?; + } + formatter.write_str("]") + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: MyappArrayIndices) -> Self { + ::opentelemetry::KeyValue::new(MyappArrayIndices::KEY, ::opentelemetry::Value::Array(::opentelemetry::Array::I64(value.0))) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: MyappArrayIndices) -> Self { + value.0.into_iter().collect::<::opentelemetry::logs::AnyValue>() + } +} + +/// Synthetic naming value. +#[derive(Debug, Clone, PartialEq)] +pub struct MyappArraySamples(Vec); + +#[allow(deprecated)] +impl MyappArraySamples { + pub const KEY: &'static str = "myapp.array.samples"; +} + +#[allow(deprecated)] +impl From> for MyappArraySamples { + #[inline] + fn from(value: Vec) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl AsRef<[f64]> for MyappArraySamples { + #[inline] + fn as_ref(&self) -> &[f64] { + &self.0 + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for MyappArraySamples { + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str("[")?; + for (index, value) in self.0.iter().enumerate() { + if index != 0 { + formatter.write_str(",")?; + } + ::std::fmt::Display::fmt(value, formatter)?; + } + formatter.write_str("]") + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: MyappArraySamples) -> Self { + ::opentelemetry::KeyValue::new(MyappArraySamples::KEY, ::opentelemetry::Value::Array(::opentelemetry::Array::F64(value.0))) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: MyappArraySamples) -> Self { + value.0.into_iter().collect::<::opentelemetry::logs::AnyValue>() + } +} + +/// Synthetic naming value. +#[derive(Debug, Clone, PartialEq)] +pub struct MyappArrayTags(Vec<::opentelemetry::StringValue>); + +#[allow(deprecated)] +impl MyappArrayTags { + pub const KEY: &'static str = "myapp.array.tags"; +} + +#[allow(deprecated)] +impl From> for MyappArrayTags { + #[inline] + fn from(value: Vec<::opentelemetry::StringValue>) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl From> for MyappArrayTags { + fn from(value: Vec) -> Self { + Self(value.into_iter().map(Into::into).collect()) + } +} + +#[allow(deprecated)] +impl AsRef<[::opentelemetry::StringValue]> for MyappArrayTags { + #[inline] + fn as_ref(&self) -> &[::opentelemetry::StringValue] { + &self.0 + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for MyappArrayTags { + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str("[")?; + for (index, value) in self.0.iter().enumerate() { + if index != 0 { + formatter.write_str(",")?; + } + write!(formatter, "\"{value}\"")?; + } + formatter.write_str("]") + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: MyappArrayTags) -> Self { + ::opentelemetry::KeyValue::new(MyappArrayTags::KEY, ::opentelemetry::Value::Array(::opentelemetry::Array::String(value.0))) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: MyappArrayTags) -> Self { + value.0.into_iter().collect::<::opentelemetry::logs::AnyValue>() + } +} + +/// Synthetic naming value. +#[derive(Debug, Clone, PartialEq, Copy)] +pub struct MyappNumberValue(f64); + +#[allow(deprecated)] +impl MyappNumberValue { + pub const KEY: &'static str = "myapp.number.value"; +} + +#[allow(deprecated)] +impl From for MyappNumberValue { + #[inline] + fn from(value: f64) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for MyappNumberValue { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + ::std::fmt::Display::fmt(&self.0, formatter) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: MyappNumberValue) -> Self { + ::opentelemetry::KeyValue::new(MyappNumberValue::KEY, value.0) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: MyappNumberValue) -> Self { + value.0.into() + } +} + +/// Name of the queue the task came from. +#[derive(Debug, Clone, PartialEq)] +pub struct MyappQueueName(::opentelemetry::StringValue); + +#[allow(deprecated)] +impl MyappQueueName { + pub const KEY: &'static str = "myapp.queue.name"; +} + +#[allow(deprecated)] +impl From<::opentelemetry::StringValue> for MyappQueueName { + #[inline] + fn from(value: ::opentelemetry::StringValue) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl From for MyappQueueName { + #[inline] + fn from(value: String) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl From<&'static str> for MyappQueueName { + #[inline] + fn from(value: &'static str) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl AsRef for MyappQueueName { + #[inline] + fn as_ref(&self) -> &str { + self.0.as_str() + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for MyappQueueName { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str(self.as_ref()) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: MyappQueueName) -> Self { + ::opentelemetry::KeyValue::new(MyappQueueName::KEY, value.0) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: MyappQueueName) -> Self { + value.0.into() + } +} + +/// Number of the attempt, starting at one. +#[derive(Debug, Clone, PartialEq, Copy)] +pub struct MyappTaskAttempt(i64); + +#[allow(deprecated)] +impl MyappTaskAttempt { + pub const KEY: &'static str = "myapp.task.attempt"; +} + +#[allow(deprecated)] +impl From for MyappTaskAttempt { + #[inline] + fn from(value: i64) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for MyappTaskAttempt { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + ::std::fmt::Display::fmt(&self.0, formatter) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: MyappTaskAttempt) -> Self { + ::opentelemetry::KeyValue::new(MyappTaskAttempt::KEY, value.0) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: MyappTaskAttempt) -> Self { + value.0.into() + } +} + +/// Unique identifier of the task. +#[derive(Debug, Clone, PartialEq)] +pub struct MyappTaskId(::opentelemetry::StringValue); + +#[allow(deprecated)] +impl MyappTaskId { + pub const KEY: &'static str = "myapp.task.id"; +} + +#[allow(deprecated)] +impl From<::opentelemetry::StringValue> for MyappTaskId { + #[inline] + fn from(value: ::opentelemetry::StringValue) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl From for MyappTaskId { + #[inline] + fn from(value: String) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl From<&'static str> for MyappTaskId { + #[inline] + fn from(value: &'static str) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl AsRef for MyappTaskId { + #[inline] + fn as_ref(&self) -> &str { + self.0.as_str() + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for MyappTaskId { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str(self.as_ref()) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: MyappTaskId) -> Self { + ::opentelemetry::KeyValue::new(MyappTaskId::KEY, value.0) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: MyappTaskId) -> Self { + value.0.into() + } +} + +/// Current state of the task. +#[derive(Debug, Clone, PartialEq, Copy)] +pub enum MyappTaskState { + /// The task is waiting to run. + Queued, + /// The task finished. + Done, +} + +#[allow(deprecated)] +impl MyappTaskState { + pub const KEY: &'static str = "myapp.task.state"; +} + +#[allow(deprecated)] +impl AsRef for MyappTaskState { + #[inline] + fn as_ref(&self) -> &str { + match self { + MyappTaskState::Queued => "queued", + MyappTaskState::Done => "done", + } + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for MyappTaskState { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str(self.as_ref()) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: MyappTaskState) -> Self { + let value: &'static str = match value { + MyappTaskState::Queued => "queued", + MyappTaskState::Done => "done", + }; + ::opentelemetry::KeyValue::new(MyappTaskState::KEY, value) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: MyappTaskState) -> Self { + let value: &'static str = match value { + MyappTaskState::Queued => "queued", + MyappTaskState::Done => "done", + }; + value.into() + } +} + +/// Host name of the worker. +#[derive(Debug, Clone, PartialEq)] +pub struct WorkerHostName(::opentelemetry::StringValue); + +#[allow(deprecated)] +impl WorkerHostName { + pub const KEY: &'static str = "worker.host.name"; +} + +#[allow(deprecated)] +impl From<::opentelemetry::StringValue> for WorkerHostName { + #[inline] + fn from(value: ::opentelemetry::StringValue) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl From for WorkerHostName { + #[inline] + fn from(value: String) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl From<&'static str> for WorkerHostName { + #[inline] + fn from(value: &'static str) -> Self { + Self(value.into()) + } +} + +#[allow(deprecated)] +impl AsRef for WorkerHostName { + #[inline] + fn as_ref(&self) -> &str { + self.0.as_str() + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for WorkerHostName { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + formatter.write_str(self.as_ref()) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: WorkerHostName) -> Self { + ::opentelemetry::KeyValue::new(WorkerHostName::KEY, value.0) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: WorkerHostName) -> Self { + value.0.into() + } +} + +/// Port the worker listens on. +#[derive(Debug, Clone, PartialEq, Copy)] +pub struct WorkerHostPort(i64); + +#[allow(deprecated)] +impl WorkerHostPort { + pub const KEY: &'static str = "worker.host.port"; +} + +#[allow(deprecated)] +impl From for WorkerHostPort { + #[inline] + fn from(value: i64) -> Self { + Self(value) + } +} + +#[allow(deprecated)] +impl ::std::fmt::Display for WorkerHostPort { + #[inline] + fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { + ::std::fmt::Display::fmt(&self.0, formatter) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::KeyValue { + #[inline] + fn from(value: WorkerHostPort) -> Self { + ::opentelemetry::KeyValue::new(WorkerHostPort::KEY, value.0) + } +} + +#[allow(deprecated)] +impl From for ::opentelemetry::logs::AnyValue { + #[inline] + fn from(value: WorkerHostPort) -> Self { + value.0.into() + } +} diff --git a/templates/code/rust/tests/spans/expected/mod.rs b/templates/code/rust/tests/spans/expected/mod.rs index 2a8aae8..f2ade1c 100644 --- a/templates/code/rust/tests/spans/expected/mod.rs +++ b/templates/code/rust/tests/spans/expected/mod.rs @@ -1,10 +1,8 @@ // Generated by OpenTelemetry Weaver. pub const SCHEMA_URL: &str = "https://example.com/schemas/spans/1.0.0"; -pub mod myappattr; -pub mod workerattr; +pub mod attribute; pub mod scope; pub mod options; pub mod tracer; -pub mod myappspan; -pub mod workerspan; +pub mod trace; diff --git a/templates/code/rust/tests/spans/expected/myappattr.rs b/templates/code/rust/tests/spans/expected/myappattr.rs deleted file mode 100644 index f7c83c4..0000000 --- a/templates/code/rust/tests/spans/expected/myappattr.rs +++ /dev/null @@ -1,496 +0,0 @@ -// Generated by OpenTelemetry Weaver. -/// Synthetic naming value. -#[derive(Debug, Clone, PartialEq)] -pub struct ArrayFlagsAttr(Vec); - -#[allow(deprecated)] -impl ArrayFlagsAttr { - pub const KEY: &'static str = "myapp.array.flags"; -} - -#[allow(deprecated)] -impl From> for ArrayFlagsAttr { - #[inline] - fn from(value: Vec) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl AsRef<[bool]> for ArrayFlagsAttr { - #[inline] - fn as_ref(&self) -> &[bool] { - &self.0 - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for ArrayFlagsAttr { - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str("[")?; - for (index, value) in self.0.iter().enumerate() { - if index != 0 { - formatter.write_str(",")?; - } - ::std::fmt::Display::fmt(value, formatter)?; - } - formatter.write_str("]") - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: ArrayFlagsAttr) -> Self { - ::opentelemetry::KeyValue::new(ArrayFlagsAttr::KEY, ::opentelemetry::Value::Array(::opentelemetry::Array::Bool(value.0))) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: ArrayFlagsAttr) -> Self { - value.0.into_iter().collect::<::opentelemetry::logs::AnyValue>() - } -} - -/// Synthetic naming value. -#[derive(Debug, Clone, PartialEq)] -pub struct ArrayIndicesAttr(Vec); - -#[allow(deprecated)] -impl ArrayIndicesAttr { - pub const KEY: &'static str = "myapp.array.indices"; -} - -#[allow(deprecated)] -impl From> for ArrayIndicesAttr { - #[inline] - fn from(value: Vec) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl AsRef<[i64]> for ArrayIndicesAttr { - #[inline] - fn as_ref(&self) -> &[i64] { - &self.0 - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for ArrayIndicesAttr { - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str("[")?; - for (index, value) in self.0.iter().enumerate() { - if index != 0 { - formatter.write_str(",")?; - } - ::std::fmt::Display::fmt(value, formatter)?; - } - formatter.write_str("]") - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: ArrayIndicesAttr) -> Self { - ::opentelemetry::KeyValue::new(ArrayIndicesAttr::KEY, ::opentelemetry::Value::Array(::opentelemetry::Array::I64(value.0))) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: ArrayIndicesAttr) -> Self { - value.0.into_iter().collect::<::opentelemetry::logs::AnyValue>() - } -} - -/// Synthetic naming value. -#[derive(Debug, Clone, PartialEq)] -pub struct ArraySamplesAttr(Vec); - -#[allow(deprecated)] -impl ArraySamplesAttr { - pub const KEY: &'static str = "myapp.array.samples"; -} - -#[allow(deprecated)] -impl From> for ArraySamplesAttr { - #[inline] - fn from(value: Vec) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl AsRef<[f64]> for ArraySamplesAttr { - #[inline] - fn as_ref(&self) -> &[f64] { - &self.0 - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for ArraySamplesAttr { - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str("[")?; - for (index, value) in self.0.iter().enumerate() { - if index != 0 { - formatter.write_str(",")?; - } - ::std::fmt::Display::fmt(value, formatter)?; - } - formatter.write_str("]") - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: ArraySamplesAttr) -> Self { - ::opentelemetry::KeyValue::new(ArraySamplesAttr::KEY, ::opentelemetry::Value::Array(::opentelemetry::Array::F64(value.0))) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: ArraySamplesAttr) -> Self { - value.0.into_iter().collect::<::opentelemetry::logs::AnyValue>() - } -} - -/// Synthetic naming value. -#[derive(Debug, Clone, PartialEq)] -pub struct ArrayTagsAttr(Vec<::opentelemetry::StringValue>); - -#[allow(deprecated)] -impl ArrayTagsAttr { - pub const KEY: &'static str = "myapp.array.tags"; -} - -#[allow(deprecated)] -impl From> for ArrayTagsAttr { - #[inline] - fn from(value: Vec<::opentelemetry::StringValue>) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl From> for ArrayTagsAttr { - fn from(value: Vec) -> Self { - Self(value.into_iter().map(Into::into).collect()) - } -} - -#[allow(deprecated)] -impl AsRef<[::opentelemetry::StringValue]> for ArrayTagsAttr { - #[inline] - fn as_ref(&self) -> &[::opentelemetry::StringValue] { - &self.0 - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for ArrayTagsAttr { - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str("[")?; - for (index, value) in self.0.iter().enumerate() { - if index != 0 { - formatter.write_str(",")?; - } - write!(formatter, "\"{value}\"")?; - } - formatter.write_str("]") - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: ArrayTagsAttr) -> Self { - ::opentelemetry::KeyValue::new(ArrayTagsAttr::KEY, ::opentelemetry::Value::Array(::opentelemetry::Array::String(value.0))) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: ArrayTagsAttr) -> Self { - value.0.into_iter().collect::<::opentelemetry::logs::AnyValue>() - } -} - -/// Synthetic naming value. -#[derive(Debug, Clone, PartialEq, Copy)] -pub struct NumberValueAttr(f64); - -#[allow(deprecated)] -impl NumberValueAttr { - pub const KEY: &'static str = "myapp.number.value"; -} - -#[allow(deprecated)] -impl From for NumberValueAttr { - #[inline] - fn from(value: f64) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for NumberValueAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - ::std::fmt::Display::fmt(&self.0, formatter) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: NumberValueAttr) -> Self { - ::opentelemetry::KeyValue::new(NumberValueAttr::KEY, value.0) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: NumberValueAttr) -> Self { - value.0.into() - } -} - -/// Name of the queue the task came from. -#[derive(Debug, Clone, PartialEq)] -pub struct QueueNameAttr(::opentelemetry::StringValue); - -#[allow(deprecated)] -impl QueueNameAttr { - pub const KEY: &'static str = "myapp.queue.name"; -} - -#[allow(deprecated)] -impl From<::opentelemetry::StringValue> for QueueNameAttr { - #[inline] - fn from(value: ::opentelemetry::StringValue) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl From for QueueNameAttr { - #[inline] - fn from(value: String) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl From<&'static str> for QueueNameAttr { - #[inline] - fn from(value: &'static str) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl AsRef for QueueNameAttr { - #[inline] - fn as_ref(&self) -> &str { - self.0.as_str() - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for QueueNameAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str(self.as_ref()) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: QueueNameAttr) -> Self { - ::opentelemetry::KeyValue::new(QueueNameAttr::KEY, value.0) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: QueueNameAttr) -> Self { - value.0.into() - } -} - -/// Number of the attempt, starting at one. -#[derive(Debug, Clone, PartialEq, Copy)] -pub struct TaskAttemptAttr(i64); - -#[allow(deprecated)] -impl TaskAttemptAttr { - pub const KEY: &'static str = "myapp.task.attempt"; -} - -#[allow(deprecated)] -impl From for TaskAttemptAttr { - #[inline] - fn from(value: i64) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for TaskAttemptAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - ::std::fmt::Display::fmt(&self.0, formatter) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: TaskAttemptAttr) -> Self { - ::opentelemetry::KeyValue::new(TaskAttemptAttr::KEY, value.0) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: TaskAttemptAttr) -> Self { - value.0.into() - } -} - -/// Unique identifier of the task. -#[derive(Debug, Clone, PartialEq)] -pub struct TaskIdAttr(::opentelemetry::StringValue); - -#[allow(deprecated)] -impl TaskIdAttr { - pub const KEY: &'static str = "myapp.task.id"; -} - -#[allow(deprecated)] -impl From<::opentelemetry::StringValue> for TaskIdAttr { - #[inline] - fn from(value: ::opentelemetry::StringValue) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl From for TaskIdAttr { - #[inline] - fn from(value: String) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl From<&'static str> for TaskIdAttr { - #[inline] - fn from(value: &'static str) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl AsRef for TaskIdAttr { - #[inline] - fn as_ref(&self) -> &str { - self.0.as_str() - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for TaskIdAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str(self.as_ref()) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: TaskIdAttr) -> Self { - ::opentelemetry::KeyValue::new(TaskIdAttr::KEY, value.0) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: TaskIdAttr) -> Self { - value.0.into() - } -} - -/// Current state of the task. -#[derive(Debug, Clone, PartialEq, Copy)] -pub enum TaskStateAttr { - /// The task is waiting to run. - Queued, - /// The task finished. - Done, -} - -#[allow(deprecated)] -impl TaskStateAttr { - pub const KEY: &'static str = "myapp.task.state"; -} - -#[allow(deprecated)] -impl AsRef for TaskStateAttr { - #[inline] - fn as_ref(&self) -> &str { - match self { - TaskStateAttr::Queued => "queued", - TaskStateAttr::Done => "done", - } - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for TaskStateAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str(self.as_ref()) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: TaskStateAttr) -> Self { - let value: &'static str = match value { - TaskStateAttr::Queued => "queued", - TaskStateAttr::Done => "done", - }; - ::opentelemetry::KeyValue::new(TaskStateAttr::KEY, value) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: TaskStateAttr) -> Self { - let value: &'static str = match value { - TaskStateAttr::Queued => "queued", - TaskStateAttr::Done => "done", - }; - value.into() - } -} diff --git a/templates/code/rust/tests/spans/expected/myappspan.rs b/templates/code/rust/tests/spans/expected/trace.rs similarity index 59% rename from templates/code/rust/tests/spans/expected/myappspan.rs rename to templates/code/rust/tests/spans/expected/trace.rs index f144d17..93d4c48 100644 --- a/templates/code/rust/tests/spans/expected/myappspan.rs +++ b/templates/code/rust/tests/spans/expected/trace.rs @@ -1,13 +1,13 @@ #![allow(deprecated)] -use ::opentelemetry::trace::{TraceContextExt, Tracer}; -use ::std::fmt::Write; +use ::opentelemetry::trace::{TraceContextExt as _, Tracer as _}; +use ::std::fmt::Write as _; /// Synthetic escaped name. -pub struct NameApostropheSpan { +pub struct MyappNameApostrophe { span: S, } -impl NameApostropheSpan { +impl MyappNameApostrophe { pub fn into_context(self, parent: &::opentelemetry::Context) -> ::opentelemetry::Context where S: Send + Sync + 'static, { @@ -20,13 +20,17 @@ impl NameApostropheSpan { pub fn set_status(&mut self, status: ::opentelemetry::trace::Status) { ::opentelemetry::trace::Span::set_status(&mut self.span, status); } } -impl Default for NameApostropheSpan { +impl MyappNameApostrophe { + pub const NAME: &'static str = "myapp.name.apostrophe"; +} + +impl Default for MyappNameApostrophe { fn default() -> Self { - Self { span: super::tracer::Tracer::default().inner().start("myapp.name.apostrophe") } + Self { span: super::tracer::Tracer::default().inner().start(Self::NAME) } } } -pub fn r#start_name_apostrophe(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer, r#worker_host_port: super::workerattr::HostPortAttr) -> NameApostropheSpan { +pub fn r#start_myapp_name_apostrophe(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer, r#worker_host_port: super::attribute::WorkerHostPort) -> MyappNameApostrophe { let mut name = String::with_capacity("\u{0027}".len() + 20); name.push('\u{0027}'); write!(&mut name, "{}", r#worker_host_port).expect("writing a span name to String cannot fail"); @@ -35,14 +39,14 @@ pub fn r#start_name_apostrophe(context: &::op .with_kind(::opentelemetry::trace::SpanKind::Internal) .with_attributes(attributes) .start_with_context(tracer.inner(), context); - NameApostropheSpan { span } + MyappNameApostrophe { span } } /// A span named from array values. -pub struct NameArraysSpan { +pub struct MyappNameArrays { span: S, } -impl NameArraysSpan { +impl MyappNameArrays { pub fn into_context(self, parent: &::opentelemetry::Context) -> ::opentelemetry::Context where S: Send + Sync + 'static, { @@ -55,13 +59,17 @@ impl NameArraysSpan { pub fn set_status(&mut self, status: ::opentelemetry::trace::Status) { ::opentelemetry::trace::Span::set_status(&mut self.span, status); } } -impl Default for NameArraysSpan { +impl MyappNameArrays { + pub const NAME: &'static str = "myapp.name.arrays"; +} + +impl Default for MyappNameArrays { fn default() -> Self { - Self { span: super::tracer::Tracer::default().inner().start("myapp.name.arrays") } + Self { span: super::tracer::Tracer::default().inner().start(Self::NAME) } } } -pub fn r#start_name_arrays(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer, r#myapp_array_flags: super::myappattr::ArrayFlagsAttr, r#myapp_array_indices: super::myappattr::ArrayIndicesAttr, r#myapp_array_samples: super::myappattr::ArraySamplesAttr, r#myapp_array_tags: super::myappattr::ArrayTagsAttr) -> NameArraysSpan { +pub fn r#start_myapp_name_arrays(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer, r#myapp_array_flags: super::attribute::MyappArrayFlags, r#myapp_array_indices: super::attribute::MyappArrayIndices, r#myapp_array_samples: super::attribute::MyappArraySamples, r#myapp_array_tags: super::attribute::MyappArrayTags) -> MyappNameArrays { let mut name = String::with_capacity(::std::convert::AsRef::<[::opentelemetry::StringValue]>::as_ref(&r#myapp_array_tags).iter().map(|value| value.as_str().len() + 3).sum::() + 2 + ":".len() + ::std::convert::AsRef::<[i64]>::as_ref(&r#myapp_array_indices).len() * 21 + 2 + ":".len() + ::std::convert::AsRef::<[f64]>::as_ref(&r#myapp_array_samples).len() * 328 + 2 + ":".len() + ::std::convert::AsRef::<[bool]>::as_ref(&r#myapp_array_flags).len() * 6 + 2); write!(&mut name, "{}", r#myapp_array_tags).expect("writing a span name to String cannot fail"); name.push(':'); @@ -75,14 +83,14 @@ pub fn r#start_name_arrays(context: &::opente .with_kind(::opentelemetry::trace::SpanKind::Internal) .with_attributes(attributes) .start_with_context(tracer.inner(), context); - NameArraysSpan { span } + MyappNameArrays { span } } /// Synthetic escaped name. -pub struct NameBackslashSpan { +pub struct MyappNameBackslash { span: S, } -impl NameBackslashSpan { +impl MyappNameBackslash { pub fn into_context(self, parent: &::opentelemetry::Context) -> ::opentelemetry::Context where S: Send + Sync + 'static, { @@ -95,13 +103,17 @@ impl NameBackslashSpan { pub fn set_status(&mut self, status: ::opentelemetry::trace::Status) { ::opentelemetry::trace::Span::set_status(&mut self.span, status); } } -impl Default for NameBackslashSpan { +impl MyappNameBackslash { + pub const NAME: &'static str = "myapp.name.backslash"; +} + +impl Default for MyappNameBackslash { fn default() -> Self { - Self { span: super::tracer::Tracer::default().inner().start("myapp.name.backslash") } + Self { span: super::tracer::Tracer::default().inner().start(Self::NAME) } } } -pub fn r#start_name_backslash(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer, r#worker_host_port: super::workerattr::HostPortAttr) -> NameBackslashSpan { +pub fn r#start_myapp_name_backslash(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer, r#worker_host_port: super::attribute::WorkerHostPort) -> MyappNameBackslash { let mut name = String::with_capacity("\\".len() + 20); name.push('\\'); write!(&mut name, "{}", r#worker_host_port).expect("writing a span name to String cannot fail"); @@ -110,14 +122,14 @@ pub fn r#start_name_backslash(context: &::ope .with_kind(::opentelemetry::trace::SpanKind::Internal) .with_attributes(attributes) .start_with_context(tracer.inner(), context); - NameBackslashSpan { span } + MyappNameBackslash { span } } /// Synthetic escaped name. -pub struct NameControlSpan { +pub struct MyappNameControl { span: S, } -impl NameControlSpan { +impl MyappNameControl { pub fn into_context(self, parent: &::opentelemetry::Context) -> ::opentelemetry::Context where S: Send + Sync + 'static, { @@ -130,13 +142,17 @@ impl NameControlSpan { pub fn set_status(&mut self, status: ::opentelemetry::trace::Status) { ::opentelemetry::trace::Span::set_status(&mut self.span, status); } } -impl Default for NameControlSpan { +impl MyappNameControl { + pub const NAME: &'static str = "myapp.name.control"; +} + +impl Default for MyappNameControl { fn default() -> Self { - Self { span: super::tracer::Tracer::default().inner().start("myapp.name.control") } + Self { span: super::tracer::Tracer::default().inner().start(Self::NAME) } } } -pub fn r#start_name_control(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer, r#worker_host_port: super::workerattr::HostPortAttr) -> NameControlSpan { +pub fn r#start_myapp_name_control(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer, r#worker_host_port: super::attribute::WorkerHostPort) -> MyappNameControl { let mut name = String::with_capacity("\u{0008}".len() + 20); name.push('\u{0008}'); write!(&mut name, "{}", r#worker_host_port).expect("writing a span name to String cannot fail"); @@ -145,14 +161,14 @@ pub fn r#start_name_control(context: &::opent .with_kind(::opentelemetry::trace::SpanKind::Internal) .with_attributes(attributes) .start_with_context(tracer.inner(), context); - NameControlSpan { span } + MyappNameControl { span } } /// A span named from a floating point value. -pub struct NameFloatSpan { +pub struct MyappNameFloat { span: S, } -impl NameFloatSpan { +impl MyappNameFloat { pub fn into_context(self, parent: &::opentelemetry::Context) -> ::opentelemetry::Context where S: Send + Sync + 'static, { @@ -165,13 +181,17 @@ impl NameFloatSpan { pub fn set_status(&mut self, status: ::opentelemetry::trace::Status) { ::opentelemetry::trace::Span::set_status(&mut self.span, status); } } -impl Default for NameFloatSpan { +impl MyappNameFloat { + pub const NAME: &'static str = "myapp.name.float"; +} + +impl Default for MyappNameFloat { fn default() -> Self { - Self { span: super::tracer::Tracer::default().inner().start("myapp.name.float") } + Self { span: super::tracer::Tracer::default().inner().start(Self::NAME) } } } -pub fn r#start_name_float(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer, r#myapp_number_value: super::myappattr::NumberValueAttr) -> NameFloatSpan { +pub fn r#start_myapp_name_float(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer, r#myapp_number_value: super::attribute::MyappNumberValue) -> MyappNameFloat { let mut name = String::with_capacity(328); write!(&mut name, "{}", r#myapp_number_value).expect("writing a span name to String cannot fail"); let attributes: [::opentelemetry::KeyValue; 1] = [::opentelemetry::KeyValue::from(r#myapp_number_value)]; @@ -179,28 +199,28 @@ pub fn r#start_name_float(context: &::opentel .with_kind(::opentelemetry::trace::SpanKind::Internal) .with_attributes(attributes) .start_with_context(tracer.inner(), context); - NameFloatSpan { span } + MyappNameFloat { span } } #[derive(Clone, Debug, Default)] -pub struct NameStaticName(::std::borrow::Cow<'static, str>); +pub struct MyappNameStaticName(::std::borrow::Cow<'static, str>); -impl From<&'static str> for NameStaticName { +impl From<&'static str> for MyappNameStaticName { fn from(value: &'static str) -> Self { Self(::std::borrow::Cow::Borrowed(value)) } } -impl From for NameStaticName { +impl From for MyappNameStaticName { fn from(value: String) -> Self { Self(::std::borrow::Cow::Owned(value)) } } -impl From<::std::borrow::Cow<'static, str>> for NameStaticName { +impl From<::std::borrow::Cow<'static, str>> for MyappNameStaticName { fn from(value: ::std::borrow::Cow<'static, str>) -> Self { Self(value) } } /// A span with an unconstrained caller supplied name. -pub struct NameStaticSpan { +pub struct MyappNameStatic { span: S, } -impl NameStaticSpan { +impl MyappNameStatic { pub fn into_context(self, parent: &::opentelemetry::Context) -> ::opentelemetry::Context where S: Send + Sync + 'static, { @@ -213,27 +233,31 @@ impl NameStaticSpan { pub fn set_status(&mut self, status: ::opentelemetry::trace::Status) { ::opentelemetry::trace::Span::set_status(&mut self.span, status); } } -impl Default for NameStaticSpan { +impl MyappNameStatic { + pub const NAME: &'static str = "myapp.name.static"; +} + +impl Default for MyappNameStatic { fn default() -> Self { - Self { span: super::tracer::Tracer::default().inner().start("myapp.name.static") } + Self { span: super::tracer::Tracer::default().inner().start(Self::NAME) } } } -pub fn r#start_name_static(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer, name: NameStaticName) -> NameStaticSpan { - let name = if name.0.is_empty() { ::std::borrow::Cow::Borrowed("myapp.name.static") } else { name.0 }; +pub fn r#start_myapp_name_static(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer, name: MyappNameStaticName) -> MyappNameStatic { + let name = if name.0.is_empty() { ::std::borrow::Cow::Borrowed(MyappNameStatic::NAME) } else { name.0 }; let attributes: [::opentelemetry::KeyValue; 0] = []; let span = tracer.inner().span_builder(name) .with_kind(::opentelemetry::trace::SpanKind::Internal) .with_attributes(attributes) .start_with_context(tracer.inner(), context); - NameStaticSpan { span } + MyappNameStatic { span } } /// Synthetic escaped name. -pub struct NameUnicodeSpan { +pub struct MyappNameUnicode { span: S, } -impl NameUnicodeSpan { +impl MyappNameUnicode { pub fn into_context(self, parent: &::opentelemetry::Context) -> ::opentelemetry::Context where S: Send + Sync + 'static, { @@ -246,13 +270,17 @@ impl NameUnicodeSpan { pub fn set_status(&mut self, status: ::opentelemetry::trace::Status) { ::opentelemetry::trace::Span::set_status(&mut self.span, status); } } -impl Default for NameUnicodeSpan { +impl MyappNameUnicode { + pub const NAME: &'static str = "myapp.name.unicode"; +} + +impl Default for MyappNameUnicode { fn default() -> Self { - Self { span: super::tracer::Tracer::default().inner().start("myapp.name.unicode") } + Self { span: super::tracer::Tracer::default().inner().start(Self::NAME) } } } -pub fn r#start_name_unicode(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer, r#worker_host_port: super::workerattr::HostPortAttr) -> NameUnicodeSpan { +pub fn r#start_myapp_name_unicode(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer, r#worker_host_port: super::attribute::WorkerHostPort) -> MyappNameUnicode { let mut name = String::with_capacity("é".len() + 20); name.push('é'); write!(&mut name, "{}", r#worker_host_port).expect("writing a span name to String cannot fail"); @@ -261,30 +289,30 @@ pub fn r#start_name_unicode(context: &::opent .with_kind(::opentelemetry::trace::SpanKind::Internal) .with_attributes(attributes) .start_with_context(tracer.inner(), context); - NameUnicodeSpan { span } + MyappNameUnicode { span } } #[derive(Clone, Debug, Default)] -pub struct QueueDrainName(::std::borrow::Cow<'static, str>); +pub struct MyappQueueDrainName(::std::borrow::Cow<'static, str>); -impl From<&'static str> for QueueDrainName { +impl From<&'static str> for MyappQueueDrainName { fn from(value: &'static str) -> Self { Self(::std::borrow::Cow::Borrowed(value)) } } -impl From for QueueDrainName { +impl From for MyappQueueDrainName { fn from(value: String) -> Self { Self(::std::borrow::Cow::Owned(value)) } } -impl From<::std::borrow::Cow<'static, str>> for QueueDrainName { +impl From<::std::borrow::Cow<'static, str>> for MyappQueueDrainName { fn from(value: ::std::borrow::Cow<'static, str>) -> Self { Self(value) } } /// Removing every task from a queue. /// Opt-in: record only when the user requests it. #[deprecated(note = "Drain queues by dispatching their tasks instead.")] -pub struct QueueDrainSpan { +pub struct MyappQueueDrain { span: S, } -impl QueueDrainSpan { +impl MyappQueueDrain { pub fn into_context(self, parent: &::opentelemetry::Context) -> ::opentelemetry::Context where S: Send + Sync + 'static, { @@ -297,61 +325,65 @@ impl QueueDrainSpan { pub fn set_status(&mut self, status: ::opentelemetry::trace::Status) { ::opentelemetry::trace::Span::set_status(&mut self.span, status); } } -impl Default for QueueDrainSpan { +impl MyappQueueDrain { + pub const NAME: &'static str = "myapp.queue.drain"; +} + +impl Default for MyappQueueDrain { fn default() -> Self { - Self { span: super::tracer::Tracer::default().inner().start("myapp.queue.drain") } + Self { span: super::tracer::Tracer::default().inner().start(Self::NAME) } } } #[deprecated(note = "Drain queues by dispatching their tasks instead.")] -pub fn r#start_queue_drain(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer, name: QueueDrainName) -> QueueDrainSpan { - let name = if name.0.is_empty() { ::std::borrow::Cow::Borrowed("myapp.queue.drain") } else { name.0 }; +pub fn r#start_myapp_queue_drain(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer, name: MyappQueueDrainName) -> MyappQueueDrain { + let name = if name.0.is_empty() { ::std::borrow::Cow::Borrowed(MyappQueueDrain::NAME) } else { name.0 }; let attributes: [::opentelemetry::KeyValue; 0] = []; let span = tracer.inner().span_builder(name) .with_kind(::opentelemetry::trace::SpanKind::Consumer) .with_attributes(attributes) .start_with_context(tracer.inner(), context); - QueueDrainSpan { span } + MyappQueueDrain { span } } #[derive(Clone, Debug)] -pub enum TaskDispatchStartAttr { +pub enum MyappTaskDispatchStartAttr { /// Recommended: When the task came from a named queue. - QueueName(super::myappattr::QueueNameAttr), + QueueName(super::attribute::MyappQueueName), /// Opt-in: the convention records it only when a user asks for it. - TaskAttempt(super::myappattr::TaskAttemptAttr), - TaskId(super::myappattr::TaskIdAttr), + TaskAttempt(super::attribute::MyappTaskAttempt), + TaskId(super::attribute::MyappTaskId), } -impl From for ::opentelemetry::KeyValue { - fn from(value: TaskDispatchStartAttr) -> Self { +impl From for ::opentelemetry::KeyValue { + fn from(value: MyappTaskDispatchStartAttr) -> Self { match value { - TaskDispatchStartAttr::QueueName(value) => ::opentelemetry::KeyValue::from(value), - TaskDispatchStartAttr::TaskAttempt(value) => ::opentelemetry::KeyValue::from(value), - TaskDispatchStartAttr::TaskId(value) => ::opentelemetry::KeyValue::from(value), + MyappTaskDispatchStartAttr::QueueName(value) => ::opentelemetry::KeyValue::from(value), + MyappTaskDispatchStartAttr::TaskAttempt(value) => ::opentelemetry::KeyValue::from(value), + MyappTaskDispatchStartAttr::TaskId(value) => ::opentelemetry::KeyValue::from(value), } } } #[derive(Clone, Debug)] -pub enum TaskDispatchAttr { - QueueName(super::myappattr::QueueNameAttr), - TaskAttempt(super::myappattr::TaskAttemptAttr), +pub enum MyappTaskDispatchAttr { + QueueName(super::attribute::MyappQueueName), + TaskAttempt(super::attribute::MyappTaskAttempt), } -impl From for TaskDispatchStartAttr { - fn from(value: TaskDispatchAttr) -> Self { +impl From for MyappTaskDispatchStartAttr { + fn from(value: MyappTaskDispatchAttr) -> Self { match value { - TaskDispatchAttr::QueueName(value) => Self::QueueName(value), - TaskDispatchAttr::TaskAttempt(value) => Self::TaskAttempt(value), + MyappTaskDispatchAttr::QueueName(value) => Self::QueueName(value), + MyappTaskDispatchAttr::TaskAttempt(value) => Self::TaskAttempt(value), } } } /// The scheduler handing a task to a worker. /// /// Ends when the worker accepts the task. -pub struct TaskDispatchSpan { +pub struct MyappTaskDispatch { span: S, } -impl TaskDispatchSpan { +impl MyappTaskDispatch { pub fn into_context(self, parent: &::opentelemetry::Context) -> ::opentelemetry::Context where S: Send + Sync + 'static, { @@ -362,18 +394,22 @@ impl TaskDispatchSpan { pub fn end_with_timestamp(&mut self, timestamp: ::std::time::SystemTime) { ::opentelemetry::trace::Span::end_with_timestamp(&mut self.span, timestamp); } pub fn record_error(&mut self, error: &dyn ::std::error::Error) { ::opentelemetry::trace::Span::record_error(&mut self.span, error); } pub fn set_status(&mut self, status: ::opentelemetry::trace::Status) { ::opentelemetry::trace::Span::set_status(&mut self.span, status); } - pub fn set_attributes(&mut self, attributes: impl IntoIterator) { - for attribute in attributes { ::opentelemetry::trace::Span::set_attribute(&mut self.span, ::opentelemetry::KeyValue::from(TaskDispatchStartAttr::from(attribute))); } + pub fn set_attributes(&mut self, attributes: impl IntoIterator) { + for attribute in attributes { ::opentelemetry::trace::Span::set_attribute(&mut self.span, ::opentelemetry::KeyValue::from(MyappTaskDispatchStartAttr::from(attribute))); } } } -impl Default for TaskDispatchSpan { +impl MyappTaskDispatch { + pub const NAME: &'static str = "myapp.task.dispatch"; +} + +impl Default for MyappTaskDispatch { fn default() -> Self { - Self { span: super::tracer::Tracer::default().inner().start("myapp.task.dispatch") } + Self { span: super::tracer::Tracer::default().inner().start(Self::NAME) } } } -pub fn r#start_task_dispatch(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer, r#worker_host_name: super::workerattr::HostNameAttr, r#worker_host_port: super::workerattr::HostPortAttr, options: impl IntoIterator) -> TaskDispatchSpan { +pub fn r#start_myapp_task_dispatch(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer, r#worker_host_name: super::attribute::WorkerHostName, r#worker_host_port: super::attribute::WorkerHostPort, options: impl IntoIterator) -> MyappTaskDispatch { let mut name = String::with_capacity("dispatch ".len() + ::std::convert::AsRef::::as_ref(&r#worker_host_name).len() + ":".len() + 20); name.push_str("dispatch "); write!(&mut name, "{}", r#worker_host_name).expect("writing a span name to String cannot fail"); @@ -384,52 +420,52 @@ pub fn r#start_task_dispatch(context: &::open .with_kind(::opentelemetry::trace::SpanKind::Client) .with_attributes(attributes.into_iter().chain(options.into_iter().map(::opentelemetry::KeyValue::from))) .start_with_context(tracer.inner(), context); - TaskDispatchSpan { span } + MyappTaskDispatch { span } } #[derive(Clone, Debug)] -pub enum TaskRunStartAttr { - TaskId(super::myappattr::TaskIdAttr), +pub enum MyappTaskRunStartAttr { + TaskId(super::attribute::MyappTaskId), } -impl From for ::opentelemetry::KeyValue { - fn from(value: TaskRunStartAttr) -> Self { +impl From for ::opentelemetry::KeyValue { + fn from(value: MyappTaskRunStartAttr) -> Self { match value { - TaskRunStartAttr::TaskId(value) => ::opentelemetry::KeyValue::from(value), + MyappTaskRunStartAttr::TaskId(value) => ::opentelemetry::KeyValue::from(value), } } } #[derive(Clone, Debug)] -pub enum TaskRunAttr { - TaskId(super::myappattr::TaskIdAttr), +pub enum MyappTaskRunAttr { + TaskId(super::attribute::MyappTaskId), } -impl From for TaskRunStartAttr { - fn from(value: TaskRunAttr) -> Self { +impl From for MyappTaskRunStartAttr { + fn from(value: MyappTaskRunAttr) -> Self { match value { - TaskRunAttr::TaskId(value) => Self::TaskId(value), + MyappTaskRunAttr::TaskId(value) => Self::TaskId(value), } } } #[derive(Clone, Debug, Default)] -pub struct TaskRunName(::std::borrow::Cow<'static, str>); +pub struct MyappTaskRunName(::std::borrow::Cow<'static, str>); -impl From<&'static str> for TaskRunName { +impl From<&'static str> for MyappTaskRunName { fn from(value: &'static str) -> Self { Self(::std::borrow::Cow::Borrowed(value)) } } -impl From for TaskRunName { +impl From for MyappTaskRunName { fn from(value: String) -> Self { Self(::std::borrow::Cow::Owned(value)) } } -impl From<::std::borrow::Cow<'static, str>> for TaskRunName { +impl From<::std::borrow::Cow<'static, str>> for MyappTaskRunName { fn from(value: ::std::borrow::Cow<'static, str>) -> Self { Self(value) } } /// One run of a task. -pub struct TaskRunSpan { +pub struct MyappTaskRun { span: S, } -impl TaskRunSpan { +impl MyappTaskRun { pub fn into_context(self, parent: &::opentelemetry::Context) -> ::opentelemetry::Context where S: Send + Sync + 'static, { @@ -440,23 +476,100 @@ impl TaskRunSpan { pub fn end_with_timestamp(&mut self, timestamp: ::std::time::SystemTime) { ::opentelemetry::trace::Span::end_with_timestamp(&mut self.span, timestamp); } pub fn record_error(&mut self, error: &dyn ::std::error::Error) { ::opentelemetry::trace::Span::record_error(&mut self.span, error); } pub fn set_status(&mut self, status: ::opentelemetry::trace::Status) { ::opentelemetry::trace::Span::set_status(&mut self.span, status); } - pub fn set_attributes(&mut self, attributes: impl IntoIterator) { - for attribute in attributes { ::opentelemetry::trace::Span::set_attribute(&mut self.span, ::opentelemetry::KeyValue::from(TaskRunStartAttr::from(attribute))); } + pub fn set_attributes(&mut self, attributes: impl IntoIterator) { + for attribute in attributes { ::opentelemetry::trace::Span::set_attribute(&mut self.span, ::opentelemetry::KeyValue::from(MyappTaskRunStartAttr::from(attribute))); } } } -impl Default for TaskRunSpan { +impl MyappTaskRun { + pub const NAME: &'static str = "myapp.task.run"; +} + +impl Default for MyappTaskRun { fn default() -> Self { - Self { span: super::tracer::Tracer::default().inner().start("myapp.task.run") } + Self { span: super::tracer::Tracer::default().inner().start(Self::NAME) } } } -pub fn r#start_task_run(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer, name: TaskRunName, r#myapp_task_state: super::myappattr::TaskStateAttr, options: impl IntoIterator) -> TaskRunSpan { - let name = if name.0.is_empty() { ::std::borrow::Cow::Borrowed("myapp.task.run") } else { name.0 }; +pub fn r#start_myapp_task_run(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer, name: MyappTaskRunName, r#myapp_task_state: super::attribute::MyappTaskState, options: impl IntoIterator) -> MyappTaskRun { + let name = if name.0.is_empty() { ::std::borrow::Cow::Borrowed(MyappTaskRun::NAME) } else { name.0 }; let attributes: [::opentelemetry::KeyValue; 1] = [::opentelemetry::KeyValue::from(r#myapp_task_state)]; let span = tracer.inner().span_builder(name) .with_kind(::opentelemetry::trace::SpanKind::Internal) .with_attributes(attributes.into_iter().chain(options.into_iter().map(::opentelemetry::KeyValue::from))) .start_with_context(tracer.inner(), context); - TaskRunSpan { span } + MyappTaskRun { span } +} +#[derive(Clone, Debug)] +pub enum WorkerTaskDispatchStartAttr { + /// Recommended: When the task came from a named queue. + QueueName(super::attribute::MyappQueueName), + TaskId(super::attribute::MyappTaskId), +} + +impl From for ::opentelemetry::KeyValue { + fn from(value: WorkerTaskDispatchStartAttr) -> Self { + match value { + WorkerTaskDispatchStartAttr::QueueName(value) => ::opentelemetry::KeyValue::from(value), + WorkerTaskDispatchStartAttr::TaskId(value) => ::opentelemetry::KeyValue::from(value), + } + } +} +#[derive(Clone, Debug)] +pub enum WorkerTaskDispatchAttr { + QueueName(super::attribute::MyappQueueName), +} + +impl From for WorkerTaskDispatchStartAttr { + fn from(value: WorkerTaskDispatchAttr) -> Self { + match value { + WorkerTaskDispatchAttr::QueueName(value) => Self::QueueName(value), + } + } +} +/// The scheduler handing a task to a worker. +/// +/// Ends when the worker accepts the task. +pub struct WorkerTaskDispatch { + span: S, +} + +impl WorkerTaskDispatch { + pub fn into_context(self, parent: &::opentelemetry::Context) -> ::opentelemetry::Context + where S: Send + Sync + 'static, + { + parent.with_span(self.span) + } + pub fn span(&mut self) -> &mut S { &mut self.span } + pub fn end(&mut self) { ::opentelemetry::trace::Span::end(&mut self.span); } + pub fn end_with_timestamp(&mut self, timestamp: ::std::time::SystemTime) { ::opentelemetry::trace::Span::end_with_timestamp(&mut self.span, timestamp); } + pub fn record_error(&mut self, error: &dyn ::std::error::Error) { ::opentelemetry::trace::Span::record_error(&mut self.span, error); } + pub fn set_status(&mut self, status: ::opentelemetry::trace::Status) { ::opentelemetry::trace::Span::set_status(&mut self.span, status); } + pub fn set_attributes(&mut self, attributes: impl IntoIterator) { + for attribute in attributes { ::opentelemetry::trace::Span::set_attribute(&mut self.span, ::opentelemetry::KeyValue::from(WorkerTaskDispatchStartAttr::from(attribute))); } + } +} + +impl WorkerTaskDispatch { + pub const NAME: &'static str = "myapp.task.dispatch"; +} + +impl Default for WorkerTaskDispatch { + fn default() -> Self { + Self { span: super::tracer::Tracer::default().inner().start(Self::NAME) } + } +} + +pub fn r#start_worker_task_dispatch(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer, r#myapp_task_attempt: super::attribute::MyappTaskAttempt, r#worker_host_name: super::attribute::WorkerHostName, r#worker_host_port: super::attribute::WorkerHostPort, options: impl IntoIterator) -> WorkerTaskDispatch { + let mut name = String::with_capacity("dispatch ".len() + ::std::convert::AsRef::::as_ref(&r#worker_host_name).len() + ":".len() + 20); + name.push_str("dispatch "); + write!(&mut name, "{}", r#worker_host_name).expect("writing a span name to String cannot fail"); + name.push(':'); + write!(&mut name, "{}", r#worker_host_port).expect("writing a span name to String cannot fail"); + let attributes: [::opentelemetry::KeyValue; 3] = [::opentelemetry::KeyValue::from(r#myapp_task_attempt), ::opentelemetry::KeyValue::from(r#worker_host_name), ::opentelemetry::KeyValue::from(r#worker_host_port)]; + let span = tracer.inner().span_builder(name) + .with_kind(::opentelemetry::trace::SpanKind::Client) + .with_attributes(attributes.into_iter().chain(options.into_iter().map(::opentelemetry::KeyValue::from))) + .start_with_context(tracer.inner(), context); + WorkerTaskDispatch { span } } diff --git a/templates/code/rust/tests/spans/expected/workerattr.rs b/templates/code/rust/tests/spans/expected/workerattr.rs deleted file mode 100644 index 431c6c0..0000000 --- a/templates/code/rust/tests/spans/expected/workerattr.rs +++ /dev/null @@ -1,106 +0,0 @@ -// Generated by OpenTelemetry Weaver. -/// Host name of the worker. -#[derive(Debug, Clone, PartialEq)] -pub struct HostNameAttr(::opentelemetry::StringValue); - -#[allow(deprecated)] -impl HostNameAttr { - pub const KEY: &'static str = "worker.host.name"; -} - -#[allow(deprecated)] -impl From<::opentelemetry::StringValue> for HostNameAttr { - #[inline] - fn from(value: ::opentelemetry::StringValue) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl From for HostNameAttr { - #[inline] - fn from(value: String) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl From<&'static str> for HostNameAttr { - #[inline] - fn from(value: &'static str) -> Self { - Self(value.into()) - } -} - -#[allow(deprecated)] -impl AsRef for HostNameAttr { - #[inline] - fn as_ref(&self) -> &str { - self.0.as_str() - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for HostNameAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - formatter.write_str(self.as_ref()) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: HostNameAttr) -> Self { - ::opentelemetry::KeyValue::new(HostNameAttr::KEY, value.0) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: HostNameAttr) -> Self { - value.0.into() - } -} - -/// Port the worker listens on. -#[derive(Debug, Clone, PartialEq, Copy)] -pub struct HostPortAttr(i64); - -#[allow(deprecated)] -impl HostPortAttr { - pub const KEY: &'static str = "worker.host.port"; -} - -#[allow(deprecated)] -impl From for HostPortAttr { - #[inline] - fn from(value: i64) -> Self { - Self(value) - } -} - -#[allow(deprecated)] -impl ::std::fmt::Display for HostPortAttr { - #[inline] - fn fmt(&self, formatter: &mut ::std::fmt::Formatter<'_>) -> ::std::fmt::Result { - ::std::fmt::Display::fmt(&self.0, formatter) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::KeyValue { - #[inline] - fn from(value: HostPortAttr) -> Self { - ::opentelemetry::KeyValue::new(HostPortAttr::KEY, value.0) - } -} - -#[allow(deprecated)] -impl From for ::opentelemetry::logs::AnyValue { - #[inline] - fn from(value: HostPortAttr) -> Self { - value.0.into() - } -} diff --git a/templates/code/rust/tests/spans/expected/workerspan.rs b/templates/code/rust/tests/spans/expected/workerspan.rs deleted file mode 100644 index 7fc031f..0000000 --- a/templates/code/rust/tests/spans/expected/workerspan.rs +++ /dev/null @@ -1,73 +0,0 @@ -#![allow(deprecated)] -use ::opentelemetry::trace::{TraceContextExt, Tracer}; -use ::std::fmt::Write; - -#[derive(Clone, Debug)] -pub enum TaskDispatchStartAttr { - /// Recommended: When the task came from a named queue. - QueueName(super::myappattr::QueueNameAttr), - TaskId(super::myappattr::TaskIdAttr), -} - -impl From for ::opentelemetry::KeyValue { - fn from(value: TaskDispatchStartAttr) -> Self { - match value { - TaskDispatchStartAttr::QueueName(value) => ::opentelemetry::KeyValue::from(value), - TaskDispatchStartAttr::TaskId(value) => ::opentelemetry::KeyValue::from(value), - } - } -} -#[derive(Clone, Debug)] -pub enum TaskDispatchAttr { - QueueName(super::myappattr::QueueNameAttr), -} - -impl From for TaskDispatchStartAttr { - fn from(value: TaskDispatchAttr) -> Self { - match value { - TaskDispatchAttr::QueueName(value) => Self::QueueName(value), - } - } -} -/// The scheduler handing a task to a worker. -/// -/// Ends when the worker accepts the task. -pub struct TaskDispatchSpan { - span: S, -} - -impl TaskDispatchSpan { - pub fn into_context(self, parent: &::opentelemetry::Context) -> ::opentelemetry::Context - where S: Send + Sync + 'static, - { - parent.with_span(self.span) - } - pub fn span(&mut self) -> &mut S { &mut self.span } - pub fn end(&mut self) { ::opentelemetry::trace::Span::end(&mut self.span); } - pub fn end_with_timestamp(&mut self, timestamp: ::std::time::SystemTime) { ::opentelemetry::trace::Span::end_with_timestamp(&mut self.span, timestamp); } - pub fn record_error(&mut self, error: &dyn ::std::error::Error) { ::opentelemetry::trace::Span::record_error(&mut self.span, error); } - pub fn set_status(&mut self, status: ::opentelemetry::trace::Status) { ::opentelemetry::trace::Span::set_status(&mut self.span, status); } - pub fn set_attributes(&mut self, attributes: impl IntoIterator) { - for attribute in attributes { ::opentelemetry::trace::Span::set_attribute(&mut self.span, ::opentelemetry::KeyValue::from(TaskDispatchStartAttr::from(attribute))); } - } -} - -impl Default for TaskDispatchSpan { - fn default() -> Self { - Self { span: super::tracer::Tracer::default().inner().start("myapp.task.dispatch") } - } -} - -pub fn r#start_task_dispatch(context: &::opentelemetry::Context, tracer: &super::tracer::Tracer, r#myapp_task_attempt: super::myappattr::TaskAttemptAttr, r#worker_host_name: super::workerattr::HostNameAttr, r#worker_host_port: super::workerattr::HostPortAttr, options: impl IntoIterator) -> TaskDispatchSpan { - let mut name = String::with_capacity("dispatch ".len() + ::std::convert::AsRef::::as_ref(&r#worker_host_name).len() + ":".len() + 20); - name.push_str("dispatch "); - write!(&mut name, "{}", r#worker_host_name).expect("writing a span name to String cannot fail"); - name.push(':'); - write!(&mut name, "{}", r#worker_host_port).expect("writing a span name to String cannot fail"); - let attributes: [::opentelemetry::KeyValue; 3] = [::opentelemetry::KeyValue::from(r#myapp_task_attempt), ::opentelemetry::KeyValue::from(r#worker_host_name), ::opentelemetry::KeyValue::from(r#worker_host_port)]; - let span = tracer.inner().span_builder(name) - .with_kind(::opentelemetry::trace::SpanKind::Client) - .with_attributes(attributes.into_iter().chain(options.into_iter().map(::opentelemetry::KeyValue::from))) - .start_with_context(tracer.inner(), context); - TaskDispatchSpan { span } -} diff --git a/templates/code/rust/tests/spans/test.rs b/templates/code/rust/tests/spans/test.rs index 6941404..e562d60 100644 --- a/templates/code/rust/tests/spans/test.rs +++ b/templates/code/rust/tests/spans/test.rs @@ -1,4 +1,4 @@ -use generated_semconv::{myappattr, myappspan, tracer, workerattr, workerspan, SCHEMA_URL}; +use generated_semconv::{attribute, trace, tracer, SCHEMA_URL}; use opentelemetry::trace::{Span, TraceContextExt}; use opentelemetry_sdk::trace::{InMemorySpanExporter, SdkTracerProvider}; @@ -17,97 +17,97 @@ fn derived_names_refinements_parent_context_and_late_attributes() { }, ); let _: &opentelemetry_sdk::trace::SdkTracer = tracer.inner(); - let mut parent = myappspan::start_task_dispatch( + let mut parent = trace::start_myapp_task_dispatch( &opentelemetry::Context::new(), &tracer, - workerattr::HostNameAttr::from("worker-1"), - workerattr::HostPortAttr::from(8080), - [myappspan::TaskDispatchStartAttr::TaskId( - myappattr::TaskIdAttr::from("task-1"), + attribute::WorkerHostName::from("worker-1"), + attribute::WorkerHostPort::from(8080), + [trace::MyappTaskDispatchStartAttr::TaskId( + attribute::MyappTaskId::from("task-1"), )], ); let _: &mut opentelemetry_sdk::trace::Span = parent.span(); let context = parent.into_context(&opentelemetry::Context::new()); - let mut child = myappspan::start_task_run( + let mut child = trace::start_myapp_task_run( &context, &tracer, - myappspan::TaskRunName::from("run task-1"), - myappattr::TaskStateAttr::Done, + trace::MyappTaskRunName::from("run task-1"), + attribute::MyappTaskState::Done, [], ); - child.set_attributes([myappspan::TaskRunAttr::TaskId(myappattr::TaskIdAttr::from( + child.set_attributes([trace::MyappTaskRunAttr::TaskId(attribute::MyappTaskId::from( "task-1", ))]); child.set_status(opentelemetry::trace::Status::Ok); child.end(); context.span().end(); - let mut refined = workerspan::start_task_dispatch( + let mut refined = trace::start_worker_task_dispatch( &opentelemetry::Context::new(), &tracer, - myappattr::TaskAttemptAttr::from(3), - workerattr::HostNameAttr::from("worker-2"), - workerattr::HostPortAttr::from(9090), + attribute::MyappTaskAttempt::from(3), + attribute::WorkerHostName::from("worker-2"), + attribute::WorkerHostPort::from(9090), [], ); refined.end(); - let mut fallback = myappspan::start_task_run( + let mut fallback = trace::start_myapp_task_run( &opentelemetry::Context::new(), &tracer, - myappspan::TaskRunName::default(), - myappattr::TaskStateAttr::Done, + trace::MyappTaskRunName::default(), + attribute::MyappTaskState::Done, [], ); fallback.end(); - myappspan::start_name_apostrophe( + trace::start_myapp_name_apostrophe( &opentelemetry::Context::new(), &tracer, - workerattr::HostPortAttr::from(1), + attribute::WorkerHostPort::from(1), ) .end(); - myappspan::start_name_backslash( + trace::start_myapp_name_backslash( &opentelemetry::Context::new(), &tracer, - workerattr::HostPortAttr::from(1), + attribute::WorkerHostPort::from(1), ) .end(); - myappspan::start_name_unicode( + trace::start_myapp_name_unicode( &opentelemetry::Context::new(), &tracer, - workerattr::HostPortAttr::from(1), + attribute::WorkerHostPort::from(1), ) .end(); - myappspan::start_name_control( + trace::start_myapp_name_control( &opentelemetry::Context::new(), &tracer, - workerattr::HostPortAttr::from(1), + attribute::WorkerHostPort::from(1), ) .end(); for value in [f64::MAX, -f64::from_bits(1)] { - myappspan::start_name_float( + trace::start_myapp_name_float( &opentelemetry::Context::new(), &tracer, - myappattr::NumberValueAttr::from(value), + attribute::MyappNumberValue::from(value), ) .end(); } - myappspan::start_name_arrays( + trace::start_myapp_name_arrays( &opentelemetry::Context::new(), &tracer, - myappattr::ArrayFlagsAttr::from(vec![true, false]), - myappattr::ArrayIndicesAttr::from(vec![-1, 2]), - myappattr::ArraySamplesAttr::from(vec![1.5, 2.5]), - myappattr::ArrayTagsAttr::from(vec![ + attribute::MyappArrayFlags::from(vec![true, false]), + attribute::MyappArrayIndices::from(vec![-1, 2]), + attribute::MyappArraySamples::from(vec![1.5, 2.5]), + attribute::MyappArrayTags::from(vec![ opentelemetry::StringValue::from("a"), opentelemetry::StringValue::from("b"), ]), ) .end(); for name in [ - myappspan::NameStaticName::default(), - myappspan::NameStaticName::from("explicit static"), - myappspan::NameStaticName::from(String::from("owned dynamic")), + trace::MyappNameStaticName::default(), + trace::MyappNameStaticName::from("explicit static"), + trace::MyappNameStaticName::from(String::from("owned dynamic")), ] { - myappspan::start_name_static(&opentelemetry::Context::new(), &tracer, name).end(); + trace::start_myapp_name_static(&opentelemetry::Context::new(), &tracer, name).end(); } provider.force_flush().unwrap(); let spans = exporter.get_finished_spans().unwrap(); @@ -154,7 +154,15 @@ fn derived_names_refinements_parent_context_and_late_attributes() { for name in ["myapp.name.static", "explicit static", "owned dynamic"] { assert!(spans.iter().any(|span| span.name == name)); } - let mut noop = myappspan::TaskRunSpan::default(); + let mut noop = trace::MyappTaskRun::default(); assert!(!noop.span().is_recording()); noop.end(); } + +const _: &str = trace::MyappTaskRun::NAME; + +#[test] +fn spans_expose_their_type_as_a_constant() { + assert_eq!(trace::MyappTaskRun::NAME, "myapp.task.run"); + assert_eq!(trace::WorkerTaskDispatch::NAME, trace::MyappTaskDispatch::NAME); +} diff --git a/templates/code/rust/tests/spans/tests/allocations.rs b/templates/code/rust/tests/spans/tests/allocations.rs index 6c3b775..a99cb2b 100644 --- a/templates/code/rust/tests/spans/tests/allocations.rs +++ b/templates/code/rust/tests/spans/tests/allocations.rs @@ -1,4 +1,4 @@ -use generated_semconv::{myappattr, myappspan, tracer, workerattr}; +use generated_semconv::{attribute, trace, tracer}; use opentelemetry::trace::noop::NoopTracerProvider; use std::alloc::{GlobalAlloc, Layout, System}; use std::cell::Cell; @@ -49,10 +49,10 @@ fn fixed_scope_identity_has_no_generated_heap_allocations() { fn derived_name_only_allocates_output_and_attribute_vector() { let tracer = tracer::Tracer::default(); let context = opentelemetry::Context::new(); - let host = workerattr::HostNameAttr::from("worker-1"); - let port = workerattr::HostPortAttr::from(8080); + let host = attribute::WorkerHostName::from("worker-1"); + let port = attribute::WorkerHostPort::from(8080); let (_, count) = - allocations(|| myappspan::start_task_dispatch(&context, &tracer, host, port, [])); + allocations(|| trace::start_myapp_task_dispatch(&context, &tracer, host, port, [])); assert_eq!(count, 2); } @@ -61,8 +61,8 @@ fn extreme_float_names_do_not_reallocate_the_output() { let tracer = tracer::Tracer::default(); let context = opentelemetry::Context::new(); for value in [f64::MAX, -f64::from_bits(1)] { - let attribute = myappattr::NumberValueAttr::from(value); - let (_, count) = allocations(|| myappspan::start_name_float(&context, &tracer, attribute)); + let attribute = attribute::MyappNumberValue::from(value); + let (_, count) = allocations(|| trace::start_myapp_name_float(&context, &tracer, attribute)); assert_eq!(count, 2); } } @@ -70,25 +70,25 @@ fn extreme_float_names_do_not_reallocate_the_output() { fn long_owned_string_names_do_not_clone_or_reallocate() { let tracer = tracer::Tracer::default(); let context = opentelemetry::Context::new(); - let host = workerattr::HostNameAttr::from("worker".repeat(1000)); - let port = workerattr::HostPortAttr::from(8080); + let host = attribute::WorkerHostName::from("worker".repeat(1000)); + let port = attribute::WorkerHostPort::from(8080); let (_, count) = - allocations(|| myappspan::start_task_dispatch(&context, &tracer, host, port, [])); + allocations(|| trace::start_myapp_task_dispatch(&context, &tracer, host, port, [])); assert_eq!(count, 2); } #[test] fn array_names_only_allocate_output_and_builder_attributes() { let tracer = tracer::Tracer::default(); let context = opentelemetry::Context::new(); - let flags = myappattr::ArrayFlagsAttr::from(vec![true, false]); - let indices = myappattr::ArrayIndicesAttr::from(vec![-1, 2]); - let samples = myappattr::ArraySamplesAttr::from(vec![f64::MAX, -f64::from_bits(1)]); - let tags = myappattr::ArrayTagsAttr::from(vec![ + let flags = attribute::MyappArrayFlags::from(vec![true, false]); + let indices = attribute::MyappArrayIndices::from(vec![-1, 2]); + let samples = attribute::MyappArraySamples::from(vec![f64::MAX, -f64::from_bits(1)]); + let tags = attribute::MyappArrayTags::from(vec![ opentelemetry::StringValue::from("a"), opentelemetry::StringValue::from("b"), ]); let (_, count) = allocations(|| { - myappspan::start_name_arrays(&context, &tracer, flags, indices, samples, tags) + trace::start_myapp_name_arrays(&context, &tracer, flags, indices, samples, tags) }); assert_eq!(count, 2); } @@ -98,11 +98,11 @@ fn untemplated_names_move_or_borrow_without_heap_allocations() { let tracer = tracer::Tracer::default(); let context = opentelemetry::Context::new(); for name in [ - myappspan::NameStaticName::default(), - myappspan::NameStaticName::from("explicit static"), - myappspan::NameStaticName::from(String::from("owned dynamic")), + trace::MyappNameStaticName::default(), + trace::MyappNameStaticName::from("explicit static"), + trace::MyappNameStaticName::from(String::from("owned dynamic")), ] { - let (_, count) = allocations(|| myappspan::start_name_static(&context, &tracer, name)); + let (_, count) = allocations(|| trace::start_myapp_name_static(&context, &tracer, name)); assert_eq!(count, 0); } } diff --git a/templates/code/rust/weaver.yaml b/templates/code/rust/weaver.yaml index 8ca0cd8..5518b5b 100644 --- a/templates/code/rust/weaver.yaml +++ b/templates/code/rust/weaver.yaml @@ -39,17 +39,17 @@ templates: | (semconv_grouped_metrics($opts) | map(.metrics) | add // [] | map(.name)) as $metrics | (.registry.spans // [] | stability_filter($opts) | code_generation_exclude_filter($opts) | deprecated_filter($opts) | map(.type)) as $spans | (.registry.entities // [] | stability_filter($opts) | code_generation_exclude_filter($opts) | deprecated_filter($opts) | map(.type)) as $entities - | ([($metrics + (.refinements.metrics // [] | stability_filter($opts) | code_generation_exclude_filter($opts) | deprecated_filter($opts) | map(select(.id != .name and (.name as $base | $metrics | any(. == $base))) | .id)))[] | ns | .namespace + "metric"] - + [($spans + (.refinements.spans // [] | stability_filter($opts) | code_generation_exclude_filter($opts) | deprecated_filter($opts) | map(select(.id != .type and (.type as $base | $spans | any(. == $base))) | .id)))[] | ns | .namespace + "span"] - + [((.registry.events // [] | stability_filter($opts) | code_generation_exclude_filter($opts) | deprecated_filter($opts) | map(.name)) + (.refinements.events // [] | stability_filter($opts) | code_generation_exclude_filter($opts) | deprecated_filter($opts) | map(.id)))[] | ns | .namespace + "event"] - + [($entities + (.refinements.entities // [] | stability_filter($opts) | code_generation_exclude_filter($opts) | deprecated_filter($opts) | map(select(.id != .type and (.type as $base | $entities | any(. == $base))) | .id)))[] | ns | .namespace + "entity"] | unique) as $signal_modules + | ([($metrics + (.refinements.metrics // [] | stability_filter($opts) | code_generation_exclude_filter($opts) | deprecated_filter($opts) | map(select(.id != .name and (.name as $base | $metrics | any(. == $base))) | .id)))[] | "metric"] + + [($spans + (.refinements.spans // [] | stability_filter($opts) | code_generation_exclude_filter($opts) | deprecated_filter($opts) | map(select(.id != .type and (.type as $base | $spans | any(. == $base))) | .id)))[] | "trace"] + + [((.registry.events // [] | stability_filter($opts) | code_generation_exclude_filter($opts) | deprecated_filter($opts) | map(.name)) + (.refinements.events // [] | stability_filter($opts) | code_generation_exclude_filter($opts) | deprecated_filter($opts) | map(.id)))[] | "event"] + + [($entities + (.refinements.entities // [] | stability_filter($opts) | code_generation_exclude_filter($opts) | deprecated_filter($opts) | map(select(.id != .type and (.type as $base | $entities | any(. == $base))) | .id)))[] | "resource"] | unique) as $signal_modules | semconv_grouped_attributes($opts) - | map(.attributes) | add // [] | map(.key | ns | .namespace + "attr") | unique - | {signal_modules: $signal_modules, has_metrics: ($signal_modules | any(endswith("metric"))), has_spans: ($signal_modules | any(endswith("span"))), has_events: ($signal_modules | any(endswith("event"))), schema_literal: ($schema | rust_literal), namespaces: .} + | map(.attributes) | add // [] | map(.key | ns) + | {signal_modules: $signal_modules, has_metrics: ($signal_modules | any(. == "metric")), has_spans: ($signal_modules | any(. == "trace")), has_events: ($signal_modules | any(. == "event")), schema_literal: ($schema | rust_literal), has_attributes: (length > 0)} - template: attributes.rs.j2 application_mode: each - file_name: "{{ ctx.name }}.rs" + file_name: attribute.rs filter: |- def title: split(".") | map(split("_")) | flatten | map(.[0:1] as $first | ($first | ascii_upcase) + .[1:]) | join(""); def keyword: . as $name | ["as", "break", "const", "continue", "crate", "else", "enum", "extern", "false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return", "self", "Self", "static", "struct", "super", "trait", "true", "type", "unsafe", "use", "where", "while", "async", "await", "dyn", "abstract", "become", "box", "do", "final", "gen", "macro", "override", "priv", "try", "typeof", "unsized", "virtual", "yield"] | any(. == $name); @@ -76,7 +76,7 @@ templates: | map(if (.key | valid_name | not) then error("attribute \(.key) is not a supported Rust attribute name") else . end) | map(. + (.key | ns)) | map(if .short_name == "" then error("attribute \(.key) has no name after its namespace") else . end) - | map(. + {name: ((.short_name | title) + "Attr"), value_type: (.key as $key | .type | value_type($key)), key_literal: (.key | rust_literal), deprecated_literal: (if .deprecated then (.deprecated.note // .deprecated.renamed_to // .deprecated.reason | rust_literal) else null end)}) + | map(. + {name: (.namespace + "." + .short_name | title), value_type: (.key as $key | .type | value_type($key)), key_literal: (.key | rust_literal), deprecated_literal: (if .deprecated then (.deprecated.note // .deprecated.renamed_to // .deprecated.reason | rust_literal) else null end)}) | map(if (.value_type as $t | ["string", "int", "double", "boolean", "string[]", "int[]", "double[]", "boolean[]"] | any(. == $t) | not) then error("attribute \(.key) has an unsupported Rust value type") else . end) | map(if .value_type == "int" and (.type | type) == "object" @@ -90,10 +90,9 @@ templates: | (.type.members | group_by(.name) | map(select(length > 1))) as $collisions | if ($collisions | length) > 0 then error("attribute \($key) has enum members that render to the same Rust identifier") else . end else . end) - | group_by(.namespace) - | map(if (group_by(.name) | any(length > 1)) then error("namespace \(.[0].namespace) has attributes that render to the same Rust identifier") else . end) - - | map({name: (.[0].namespace + "attr"), attributes: sort_by(.key)}) + | (group_by(.name) | map(select(length > 1) | map(.key) | join(" and "))) as $collisions + | if ($collisions | length) > 0 then error("module attribute has attributes that render to the same Rust identifier: \($collisions | join("; "))") else . end + | if length == 0 then [] else [{attributes: sort_by(.key)}] end - template: metrics.rs.j2 filter: |- @@ -172,7 +171,7 @@ templates: then error("metric \($metric) resolves histogram_boundaries_by_unit for unit \($unit) to boundaries that are not in strictly increasing order") else . + {bucket_boundaries: $default_bounds} end else . end) - | map(. + (.name | ns | {namespace, prefix, short_name})) + | map(. + (.name | ns | {namespace, short_name, qualified: .param})) | map(if .short_name == "" then error("metric \(.name) has no name left after its namespace, so it cannot become a Rust identifier") else . end) @@ -188,7 +187,7 @@ templates: then error("metric \($metric) references imported attribute \(.key) of type \(.type | tostring), which the Rust template does not render") else . end | . + {attr_namespace: $attr_ns.namespace, attr_short_name: $attr_ns.short_name, attr_param: $attr_ns.param, - attr_import_path: ($imported_crate_paths[$attr_ns.namespace] + "::" + $attr_ns.namespace + "attr")}) + attr_import_path: ($imported_crate_paths[$attr_ns.namespace] + "::attribute")}) else . + {imported: true, attr_short_name: .key, attr_param: .key, attr_type: (if (.type | type) == "object" then (.key as $key | .type | enum_value_type($key)) @@ -222,23 +221,22 @@ templates: ) | map(if (.required | any(.attr_param == "value" or .attr_param == "options" or .attr_param == "attributes")) then error("metric \(.name) has a required attribute whose parameter shadows its generated method") else . end) - | group_by(.namespace) + | if length == 0 then [] else [.] end | map( - ([.[] | .name as $metric | (.short_name | gsub("[._]"; "") | ascii_downcase) as $short | .instrument as $kind - | ([$short + $kind, $short + $kind + "attr", $short + $kind + "observer", $short + $kind + "callback"] - + (if $kind == "histogram" then [] else [$short + "observable" + $kind] end))[] + ([.[] | .name as $metric | (.qualified | gsub("[._]"; "") | ascii_downcase) as $short | .instrument as $kind + | ([$short, $short + "attr", $short + "observer", $short + "callback"] + + (if $kind == "histogram" then [] else [$short + "observable"] end))[] | {identifier: ., name: $metric}] | group_by(.identifier) | map(select(length > 1) | map(.name) | unique | join(" and ")) | unique) as $collisions | if ($collisions | length) > 0 - then error("package \(.[0].namespace)metric has metrics that render to the same Rust identifier: \($collisions | join("; "))") + then error("module metric has metrics that render to the same Rust identifier: \($collisions | join("; "))") else . end ) - | map({namespace: .[0].namespace, prefix: .[0].prefix, metrics: sort_by(.name), - uses_attributes: ([.[] | .attributes[]] | length > 0)}) + | map({metrics: sort_by(.name)}) application_mode: each - file_name: "{{ ctx.namespace }}metric.rs" + file_name: metric.rs - template: spans.rs.j2 filter: |- @@ -296,7 +294,7 @@ templates: | if ($dropped | length) > 0 then error("span \($span) requires \($dropped | join(", ")), which exclude_deprecated or stable_only leaves out, so its generated starter could not set them") else . end) - | map(. + (.id | ns | {namespace, prefix, short_name})) + | map(. + (.id | ns | {namespace, short_name, qualified: .param})) | map(.id as $span | .attributes |= ((. // []) | sort_by(.key) | map( (.key | ns) as $attr_ns @@ -309,7 +307,7 @@ templates: then error("span \($span) references imported attribute \(.key) of type \(.type | tostring), which the Rust template does not render") else . end | . + {attr_namespace: $attr_ns.namespace, attr_short_name: $attr_ns.short_name, attr_param: $attr_ns.param, - attr_import_path: ($imported_crate_paths[$attr_ns.namespace] + "::" + $attr_ns.namespace + "attr")}) + attr_import_path: ($imported_crate_paths[$attr_ns.namespace] + "::attribute")}) else . + {imported: true, attr_short_name: .key, attr_param: .key, attr_type: (if (.type | type) == "object" then (.key as $key | .type | enum_value_type($key)) @@ -347,26 +345,24 @@ templates: then error("span \(.id) has required attributes whose Rust parameter would shadow a name its starter declares: \($shadowing | join(", "))") else . end ) - | group_by(.namespace) + | if length == 0 then [] else [.] end | map( - ([.[] | . as $def | .id as $span | (.short_name | norm) as $short - | (["P:start" + $short, "P:" + $short + "span"] - + (if $def.name_parts then [] else ["P:" + $short + "name", "P:new" + $short + "name"] end) - + (if ($def.optional | length) > 0 then ["P:" + $short + "startattr"] else [] end) - + (if $def.has_late_attrs then ["P:" + $short + "attr"] else [] end) - + ($def.optional | map(.attr_short_name | norm) | map("P:with" + $short + ., "p:" + $short + "span" + .)))[] + ([.[] | . as $def | .id as $span | (.qualified | norm) as $short + | (["start" + $short, $short] + + (if $def.name_parts then [] else [$short + "name"] end) + + (if ($def.optional | length) > 0 then [$short + "startattr"] else [] end) + + (if $def.has_late_attrs then [$short + "attr"] else [] end))[] | {identifier: ., name: $span}] | group_by(.identifier) | map(select(length > 1) | map(.name) | unique | join(" and ")) | unique) as $collisions | if ($collisions | length) > 0 - then error("package \(.[0].namespace)span has spans that render to the same Rust identifier: \($collisions | join("; "))") + then error("module trace has spans that render to the same Rust identifier: \($collisions | join("; "))") else . end ) - | map({namespace: .[0].namespace, prefix: .[0].prefix, spans: sort_by(.id), - uses_attributes: ([.[] | .attributes[]] | length > 0)}) + | map({spans: sort_by(.id)}) application_mode: each - file_name: "{{ ctx.namespace }}span.rs" + file_name: trace.rs - template: events.rs.j2 filter: |- @@ -407,7 +403,7 @@ templates: | if ($dropped | length) > 0 then error("event \($event) requires \($dropped | join(", ")), which exclude_deprecated or stable_only leaves out, so its generated Emit function could not set them") else . end) - | map(. + (.id | ns | {namespace, prefix, short_name})) + | map(. + (.id | ns | {namespace, short_name, qualified: .param})) | map(.id as $event | .attributes |= ((. // []) | sort_by(.key) | map( (.key | ns) as $attr_ns @@ -420,7 +416,7 @@ templates: then error("event \($event) references imported attribute \(.key) of type \(.type | tostring), which the Rust template does not render") else . end | . + {attr_namespace: $attr_ns.namespace, attr_short_name: $attr_ns.short_name, attr_param: $attr_ns.param, - attr_import_path: ($imported_crate_paths[$attr_ns.namespace] + "::" + $attr_ns.namespace + "attr")}) + attr_import_path: ($imported_crate_paths[$attr_ns.namespace] + "::attribute")}) else . + {imported: true, attr_short_name: .key, attr_param: .key, attr_type: (if (.type | type) == "object" then (.key as $key | .type | enum_value_type($key)) @@ -458,10 +454,10 @@ templates: then error("event \(.id) has required attributes whose Rust parameter would shadow a name its Emit function declares: \($shadowing | join(", "))") else . end ) - | group_by(.namespace) + | if length == 0 then [] else [.] end | map( - ([.[] | . as $def | .id as $event | (.short_name | norm) as $short - | (["P:emit" + $short, "P:" + (if $short == "" then "event" else $short end) + "option", + ([.[] | . as $def | .id as $event | (.qualified | norm) as $short + | (["P:emit" + $short, "P:" + (if $short == "" then "event" else $short end), "P:" + (if $short == "" then "event" else $short end) + "option", "P:with" + $short + "severity", "P:with" + $short + "timestamp", "p:" + $short + "option", "p:" + $short + "eventseverity", "p:" + $short + "eventtimestamp"] + ($def.optional | map(.attr_short_name | norm) | map("P:with" + $short + ., "p:" + $short + "event" + .)))[] @@ -470,13 +466,12 @@ templates: | map(select(length > 1) | map(.name) | unique | join(" and ")) | unique) as $collisions | if ($collisions | length) > 0 - then error("package \(.[0].namespace)event has events that render to the same Rust identifier: \($collisions | join("; "))") + then error("module event has events that render to the same Rust identifier: \($collisions | join("; "))") else . end ) - | map({namespace: .[0].namespace, prefix: .[0].prefix, events: sort_by(.id), - uses_attributes: ([.[] | .attributes[] | select(.imported)] | length > 0)}) + | map({events: sort_by(.id)}) application_mode: each - file_name: "{{ ctx.namespace }}event.rs" + file_name: event.rs - template: entities.rs.j2 filter: |- @@ -519,7 +514,7 @@ templates: then error("entity \($entity) references imported attribute \(.key) of type \(.type | tostring), which the Rust template does not render") else . end | . + {attr_namespace: $attr_ns.namespace, attr_short_name: $attr_ns.short_name, attr_param: $attr_ns.param, - attr_import_path: ($imported_crate_paths[$attr_ns.namespace] + "::" + $attr_ns.namespace + "attr")}) + attr_import_path: ($imported_crate_paths[$attr_ns.namespace] + "::attribute")}) else . + {imported: true, attr_short_name: .key, attr_param: .key, attr_type: (if (.type | type) == "object" then (.key as $key | .type | enum_value_type($key)) @@ -538,7 +533,7 @@ templates: | if ($dropped | length) > 0 then error("entity \($entity) requires \($dropped | join(", ")), which exclude_deprecated or stable_only leaves out, so its generated constructor could not set them") else . end) - | map(. + (.id | ns | {namespace, prefix, short_name})) + | map(. + (.id | ns | {namespace, short_name, qualified: .param})) | map(.id as $entity | .identity = ((.identity // []) | sort_by(.key) | map(resolved($entity; $rendered))) | .description = ((.description // []) | sort_by(.key) | map(resolved($entity; $rendered))) @@ -572,24 +567,22 @@ templates: then error("entity \(.id) has required attributes whose Rust parameter would shadow a name its constructor declares: \($shadowing | join(", "))") else . end ) - | group_by(.namespace) + | if length == 0 then [] else [.] end | map( - ([.[] | . as $def | .id as $entity | (.short_name | norm) as $short - | (["P:new" + $short + "entity", "P:" + $short + "entity"] - + (if ($def.optional | length) > 0 then ["P:" + $short + "entityattr"] else [] end) - + ($def.optional | map(.attr_short_name | norm) | map("P:with" + $short + "entity" + ., "p:" + $short + "entity" + .)))[] + ([.[] | . as $def | .id as $entity | (.qualified | norm) as $short + | ([$short] + + (if ($def.optional | length) > 0 then [$short + "attr"] else [] end))[] | {identifier: ., name: $entity}] | group_by(.identifier) | map(select(length > 1) | map(.name) | unique | join(" and ")) | unique) as $collisions | if ($collisions | length) > 0 - then error("package \(.[0].namespace)entity has entities that render to the same Rust identifier: \($collisions | join("; "))") + then error("module resource has entities that render to the same Rust identifier: \($collisions | join("; "))") else . end ) - | map({namespace: .[0].namespace, prefix: .[0].prefix, entities: sort_by(.id), - uses_attributes: ([.[] | .attributes[]] | length > 0)}) + | map({entities: sort_by(.id)}) application_mode: each - file_name: "{{ ctx.namespace }}entity.rs" + file_name: resource.rs - template: scope.rs.j2 filter: &instrumentation_filter |-