From c8e133cbb3f7f1123f5ce27131c779bbd291bf67 Mon Sep 17 00:00:00 2001 From: msilezin Date: Wed, 17 Jul 2024 18:13:40 +0000 Subject: [PATCH] remove std dependency from opentelemetry package and add BUILD file skeleton this removes most [but not all, yet] std dependencies for OTEL primitives. Notably, error handling is proving tricky to modify. In the interim, robust error messages/handling could probably be omitted. Change-Id: I8461c913dbad643e0035d064a2942ff45fa6d9a6 --- .../opentelemetry-rust/Cargo.toml | 26 +----- .../opentelemetry-rust/opentelemetry/BUILD | 44 ++++++++++ .../opentelemetry/Cargo.toml | 37 +++++--- .../opentelemetry/src/baggage.rs | 86 ++++++------------- .../opentelemetry/src/common.rs | 80 +++++++++-------- .../opentelemetry/src/context.rs | 34 ++++---- .../opentelemetry/src/global/metrics.rs | 40 +++++---- .../opentelemetry/src/global/mod.rs | 18 ++-- .../opentelemetry/src/lib.rs | 34 ++------ .../src/metrics/instruments/counter.rs | 10 ++- .../src/metrics/instruments/gauge.rs | 10 ++- .../src/metrics/instruments/histogram.rs | 6 +- .../src/metrics/instruments/mod.rs | 13 +-- .../metrics/instruments/up_down_counter.rs | 12 +-- .../opentelemetry/src/metrics/meter.rs | 13 +-- .../opentelemetry/src/metrics/mod.rs | 38 ++++---- .../opentelemetry/src/metrics/noop.rs | 5 +- .../opentelemetry/src/propagation/mod.rs | 60 ++++++------- 18 files changed, 285 insertions(+), 281 deletions(-) create mode 100644 third_party/opentelemetry/opentelemetry-rust/opentelemetry/BUILD diff --git a/third_party/opentelemetry/opentelemetry-rust/Cargo.toml b/third_party/opentelemetry/opentelemetry-rust/Cargo.toml index 4ae28e5821..0ee852b932 100644 --- a/third_party/opentelemetry/opentelemetry-rust/Cargo.toml +++ b/third_party/opentelemetry/opentelemetry-rust/Cargo.toml @@ -1,12 +1,8 @@ [workspace] members = [ - "opentelemetry", - "opentelemetry-*", - "opentelemetry-*/examples/*", - "opentelemetry-otlp/tests/*", - "examples/*", - "stress", + "opentelemetry/", ] + resolver = "2" [profile.bench] @@ -16,35 +12,17 @@ resolver = "2" debug = 1 [workspace.dependencies] -async-std = "1.10" -async-trait = "0.1" bytes = "1" criterion = "0.5" -futures-core = "0.3" -futures-executor = "0.3" -futures-util = { version = "0.3", default-features = false } -http = { version = "1.1", default-features = false, features = ["std"] } -http-body-util = "0.1" -hyper = { version = "1.3", default-features = false } hyper-util = "0.1" log = "0.4.21" once_cell = "1.13" ordered-float = "4.0" -pin-project-lite = "0.2" prost = "0.13" prost-build = "0.13" prost-types = "0.13" rand = { version = "0.8", default-features = false } -reqwest = { version = "0.12", default-features = false } serde = { version = "1.0", default-features = false } serde_json = "1.0" temp-env = "0.3.6" -thiserror = { version = "1", default-features = false } -tonic = { version = "0.12", default-features = false } -tonic-build = "0.12" -tokio = { version = "1", default-features = false } -tokio-stream = "0.1.1" -tracing = { version = "0.1", default-features = false } -tracing-core = { version = "0.1", default-features = false } -tracing-subscriber = { version = "0.3", default-features = false } url = { version = "2.5", default-features = false } diff --git a/third_party/opentelemetry/opentelemetry-rust/opentelemetry/BUILD b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/BUILD new file mode 100644 index 0000000000..aa1e9cf5f9 --- /dev/null +++ b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/BUILD @@ -0,0 +1,44 @@ +# +# Copyright 2024 The Project Oak Authors +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +load("@rules_rust//rust:defs.bzl", "rust_library", "rust_test") + +package( + default_visibility = ["//visibility:public"], +) + +rust_library( + name = "opentelemetry_rk", + srcs = glob(["src/metrics/**"]) + + [ + "src/global/metrics.rs", + "src/global/mod.rs", + "src/baggage.rs", + "src/common.rs", + "src/context.rs", + "src/lib.rs", + ], + deps = [ + "//oak_core", + ], +) + +rust_test( + name = "opentelemetry_rk_test", + size = "small", + crate = ":opentelemetry_rk", + features = ["testing"], +) diff --git a/third_party/opentelemetry/opentelemetry-rust/opentelemetry/Cargo.toml b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/Cargo.toml index 3d181fce76..38af09db7f 100644 --- a/third_party/opentelemetry/opentelemetry-rust/opentelemetry/Cargo.toml +++ b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/Cargo.toml @@ -1,5 +1,5 @@ [package] -name = "opentelemetry" +name = "opentelemetry_rk" version = "0.23.0" description = "OpenTelemetry API for Rust" homepage = "https://github.com/open-telemetry/opentelemetry-rust" @@ -11,6 +11,23 @@ categories = [ "api-bindings", "asynchronous", ] +include = [ + "src/lib.rs", + "src/baggage.rs", + "src/context.rs", + "src/common.rs", + "src/metrics/*", + "src/global/metrics.rs", + "src/global/mod.rs", + "benches/*", +] +exclude = [ + "src/global/trace.rs", + "src/trace/context.rs", + "src/logs/*", + "src/propagation/*", + "src/global/propagation.rs", +] keywords = ["opentelemetry", "logging", "tracing", "metrics", "async"] license = "Apache-2.0" edition = "2021" @@ -21,28 +38,26 @@ all-features = true rustdoc-args = ["--cfg", "docsrs"] [dependencies] -futures-core = { workspace = true } -futures-sink = "0.3" -once_cell = { workspace = true } -pin-project-lite = { workspace = true, optional = true } -thiserror = { workspace = true } +pin-project-lite = { version = "0.2", optional = true } +oak_core = { path = "../../../../oak_core" } +once_cell = { version = "1.13" } [target.'cfg(all(target_arch = "wasm32", not(target_os = "wasi")))'.dependencies] js-sys = "0.3.63" [features] -default = ["trace", "metrics", "logs"] +default = ["metrics"] trace = ["pin-project-lite"] metrics = [] -testing = ["trace", "metrics"] +testing = ["metrics"] logs = [] logs_level_enabled = ["logs"] otel_unstable = [] [dev-dependencies] -opentelemetry_sdk = { path = "../opentelemetry-sdk", features = ["logs_level_enabled"]} # for documentation tests -criterion = { workspace = true } -rand = { workspace = true } +# opentelemetry_sdk = { path = "../opentelemetry-sdk", features = ["logs_level_enabled"]} # for documentation tests +criterion = { version = "0.5" } +rand = { version = "0.8", default-features = false , features = ["std", "std_rng"] } [[bench]] name = "metrics" diff --git a/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/baggage.rs b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/baggage.rs index 37ba28e682..fb29c3e684 100644 --- a/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/baggage.rs +++ b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/baggage.rs @@ -14,12 +14,17 @@ //! accordance with the [W3C Baggage] specification. //! //! [W3C Baggage]: https://w3c.github.io/baggage +extern crate alloc; + use crate::{Context, Key, KeyValue, Value}; -use once_cell::sync::Lazy; -use std::collections::{hash_map, HashMap}; -use std::fmt; +use alloc::collections::btree_map; +use alloc::collections::BTreeMap; +use alloc::string::String; +use core::fmt; + +use oak_core::sync::OnceCell; -static DEFAULT_BAGGAGE: Lazy = Lazy::new(Baggage::default); +static DEFAULT_BAGGAGE: OnceCell = OnceCell::new(); const MAX_KEY_VALUE_PAIRS: usize = 180; const MAX_BYTES_FOR_ONE_PAIR: usize = 4096; @@ -50,7 +55,7 @@ const MAX_LEN_OF_ALL_PAIRS: usize = 8192; /// [RFC2616, Section 2.2]: https://tools.ietf.org/html/rfc2616#section-2.2 #[derive(Debug, Default)] pub struct Baggage { - inner: HashMap, + inner: BTreeMap, kv_content_len: usize, // the length of key-value-metadata string in `inner` } @@ -58,39 +63,17 @@ impl Baggage { /// Creates an empty `Baggage`. pub fn new() -> Self { Baggage { - inner: HashMap::default(), + inner: BTreeMap::default(), kv_content_len: 0, } } /// Returns a reference to the value associated with a given name - /// - /// # Examples - /// - /// ``` - /// use opentelemetry::{baggage::Baggage, Value}; - /// - /// let mut cc = Baggage::new(); - /// let _ = cc.insert("my-name", "my-value"); - /// - /// assert_eq!(cc.get("my-name"), Some(&Value::from("my-value"))) - /// ``` pub fn get>(&self, key: K) -> Option<&Value> { self.inner.get(key.as_ref()).map(|(value, _metadata)| value) } /// Returns a reference to the value and metadata associated with a given name - /// - /// # Examples - /// ``` - /// use opentelemetry::{baggage::{Baggage, BaggageMetadata}, Value}; - /// - /// let mut cc = Baggage::new(); - /// let _ = cc.insert("my-name", "my-value"); - /// - /// // By default, the metadata is empty - /// assert_eq!(cc.get_with_metadata("my-name"), Some(&(Value::from("my-value"), BaggageMetadata::from("")))) - /// ``` pub fn get_with_metadata>(&self, key: K) -> Option<&(Value, BaggageMetadata)> { self.inner.get(key.as_ref()) } @@ -103,7 +86,7 @@ impl Baggage { /// # Examples /// /// ``` - /// use opentelemetry::{baggage::Baggage, Value}; + /// use opentelemetry_rk::{baggage::Baggage, Value}; /// /// let mut cc = Baggage::new(); /// let _ = cc.insert("my-name", "my-value"); @@ -127,7 +110,7 @@ impl Baggage { /// # Examples /// /// ``` - /// use opentelemetry::{baggage::{Baggage, BaggageMetadata}, Value}; + /// use opentelemetry_rk::{baggage::{Baggage, BaggageMetadata}, Value}; /// /// let mut cc = Baggage::new(); /// let _ = cc.insert_with_metadata("my-name", "my-value", "test"); @@ -231,7 +214,7 @@ fn key_value_metadata_bytes_size(key: &str, value: &str, metadata: &str) -> usiz /// An iterator over the entries of a [`Baggage`]. #[derive(Debug)] -pub struct Iter<'a>(hash_map::Iter<'a, Key, (Value, BaggageMetadata)>); +pub struct Iter<'a>(btree_map::Iter<'a, Key, (Value, BaggageMetadata)>); impl<'a> Iterator for Iter<'a> { type Item = (&'a Key, &'a (Value, BaggageMetadata)); @@ -296,7 +279,7 @@ fn encode(s: &str) -> String { } impl fmt::Display for Baggage { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { for (i, (k, v)) in self.into_iter().enumerate() { write!(f, "{}={}", k, encode(v.0.as_str().as_ref()))?; if !v.1.as_str().is_empty() { @@ -315,40 +298,12 @@ impl fmt::Display for Baggage { /// Methods for sorting and retrieving baggage data in a context. pub trait BaggageExt { /// Returns a clone of the given context with the included name/value pairs. - /// - /// # Examples - /// - /// ``` - /// use opentelemetry::{baggage::BaggageExt, Context, KeyValue, Value}; - /// - /// let cx = Context::map_current(|cx| { - /// cx.with_baggage(vec![KeyValue::new("my-name", "my-value")]) - /// }); - /// - /// assert_eq!( - /// cx.baggage().get("my-name"), - /// Some(&Value::from("my-value")), - /// ) - /// ``` fn with_baggage, I: Into>( &self, baggage: T, ) -> Self; /// Returns a clone of the current context with the included name/value pairs. - /// - /// # Examples - /// - /// ``` - /// use opentelemetry::{baggage::BaggageExt, Context, KeyValue, Value}; - /// - /// let cx = Context::current_with_baggage(vec![KeyValue::new("my-name", "my-value")]); - /// - /// assert_eq!( - /// cx.baggage().get("my-name"), - /// Some(&Value::from("my-value")), - /// ) - /// ``` fn current_with_baggage, I: Into>( baggage: T, ) -> Self; @@ -358,7 +313,7 @@ pub trait BaggageExt { /// # Examples /// /// ``` - /// use opentelemetry::{baggage::BaggageExt, Context, KeyValue, Value}; + /// use opentelemetry_rk::{baggage::BaggageExt, Context, KeyValue, Value}; /// /// let cx = Context::map_current(|cx| cx.with_cleared_baggage()); /// @@ -399,7 +354,14 @@ impl BaggageExt for Context { } fn baggage(&self) -> &Baggage { - self.get::().unwrap_or(&DEFAULT_BAGGAGE) + if let Some(baggage) = DEFAULT_BAGGAGE.get() { + return baggage; + } + + match DEFAULT_BAGGAGE.set(Baggage::new()) { + Ok(_) => DEFAULT_BAGGAGE.get().unwrap(), + Err(_) => panic!("Failed to initialize DEFAULT_BAGGAGE"), + } } } diff --git a/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/common.rs b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/common.rs index 9b03ab0374..0d12de3cfd 100644 --- a/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/common.rs +++ b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/common.rs @@ -1,6 +1,7 @@ -use std::borrow::{Borrow, Cow}; -use std::sync::Arc; -use std::{fmt, hash}; +extern crate alloc; + +use alloc::{borrow::Cow, boxed::Box, string::String, sync::Arc, vec::Vec}; +use core::{borrow::Borrow, fmt, hash}; /// The key part of attribute [KeyValue] pairs. /// @@ -16,8 +17,10 @@ impl Key { /// # Examples /// /// ``` - /// use opentelemetry::Key; - /// use std::sync::Arc; + /// extern crate alloc; + /// + /// use opentelemetry_rk::Key; + /// use alloc::sync::Arc; /// /// let key1 = Key::new("my_static_str"); /// let key2 = Key::new(String::from("my_owned_string")); @@ -165,13 +168,13 @@ impl OtelString { } impl PartialOrd for OtelString { - fn partial_cmp(&self, other: &Self) -> Option { + fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl Ord for OtelString { - fn cmp(&self, other: &Self) -> std::cmp::Ordering { + fn cmp(&self, other: &Self) -> core::cmp::Ordering { self.as_str().cmp(other.as_str()) } } @@ -233,15 +236,15 @@ fn display_array_str(slice: &[T], fmt: &mut fmt::Formatter<'_>) } macro_rules! into_array { - ($(($t:ty, $val:expr),)+) => { - $( - impl From<$t> for Array { - fn from(t: $t) -> Self { - $val(t) - } - } - )+ - } + ($(($t:ty, $val:expr),)+) => { + $( + impl From<$t> for Array { + fn from(t: $t) -> Self { + $val(t) + } + } + )+ + } } into_array!( @@ -352,26 +355,26 @@ impl Value { } macro_rules! from_values { - ( - $( - ($t:ty, $val:expr); - )+ - ) => { - $( - impl From<$t> for Value { - fn from(t: $t) -> Self { - $val(t) - } - } - )+ - } + ( + $( + ($t:ty, $val:expr); + )+ + ) => { + $( + impl From<$t> for Value { + fn from(t: $t) -> Self { + $val(t) + } + } + )+ + } } from_values!( - (bool, Value::Bool); - (i64, Value::I64); - (f64, Value::F64); - (StringValue, Value::String); + (bool, Value::Bool); + (i64, Value::I64); + (f64, Value::F64); + (StringValue, Value::String); ); impl From<&'static str> for Value { @@ -434,6 +437,7 @@ impl KeyValue { } } +// (TODO) Port errors to no_std /// Marker trait for errors returned by exporters pub trait ExportError: std::error::Error + Send + Sync + 'static { /// The name of exporter that returned this error @@ -461,7 +465,7 @@ pub struct InstrumentationLibrary { /// # Examples /// /// ``` - /// let library = opentelemetry::InstrumentationLibrary::builder("my-crate"). + /// let library = opentelemetry_rk::InstrumentationLibrary::builder("my-crate"). /// with_version(env!("CARGO_PKG_VERSION")). /// with_schema_url("https://opentelemetry.io/schemas/1.17.0"). /// build(); @@ -554,7 +558,7 @@ impl InstrumentationLibraryBuilder { /// # Examples /// /// ``` - /// let library = opentelemetry::InstrumentationLibrary::builder("my-crate") + /// let library = opentelemetry_rk::InstrumentationLibrary::builder("my-crate") /// .with_version("v0.1.0") /// .build(); /// ``` @@ -568,7 +572,7 @@ impl InstrumentationLibraryBuilder { /// # Examples /// /// ``` - /// let library = opentelemetry::InstrumentationLibrary::builder("my-crate") + /// let library = opentelemetry_rk::InstrumentationLibrary::builder("my-crate") /// .with_schema_url("https://opentelemetry.io/schemas/1.17.0") /// .build(); /// ``` @@ -582,9 +586,9 @@ impl InstrumentationLibraryBuilder { /// # Examples /// /// ``` - /// use opentelemetry::KeyValue; + /// use opentelemetry_rk::KeyValue; /// - /// let library = opentelemetry::InstrumentationLibrary::builder("my-crate") + /// let library = opentelemetry_rk::InstrumentationLibrary::builder("my-crate") /// .with_attributes(vec![KeyValue::new("k", "v")]) /// .build(); /// ``` diff --git a/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/context.rs b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/context.rs index 67eae958f6..74924eaac4 100644 --- a/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/context.rs +++ b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/context.rs @@ -1,12 +1,14 @@ #[cfg(feature = "trace")] use crate::trace::context::SynchronizedSpan; -use std::any::{Any, TypeId}; -use std::cell::RefCell; -use std::collections::HashMap; -use std::fmt; -use std::hash::{BuildHasherDefault, Hasher}; -use std::marker::PhantomData; -use std::sync::Arc; +extern crate alloc; +use alloc::{collections::BTreeMap, sync::Arc}; +use core::{ + any::{Any, TypeId}, + cell::RefCell, + fmt, + hash::Hasher, + marker::PhantomData, +}; thread_local! { static CURRENT_CONTEXT: RefCell = RefCell::new(Context::default()); @@ -46,7 +48,7 @@ thread_local! { /// # Examples /// /// ``` -/// use opentelemetry::Context; +/// use opentelemetry_rk::Context; /// /// // Application-specific `a` and `b` values /// #[derive(Debug, PartialEq)] @@ -78,7 +80,7 @@ thread_local! { pub struct Context { #[cfg(feature = "trace")] pub(super) span: Option>, - entries: HashMap, BuildHasherDefault>, + entries: BTreeMap>, } impl Context { @@ -97,7 +99,7 @@ impl Context { /// # Examples /// /// ``` - /// use opentelemetry::Context; + /// use opentelemetry_rk::Context; /// /// #[derive(Debug, PartialEq)] /// struct ValueA(&'static str); @@ -133,7 +135,7 @@ impl Context { /// # Examples /// /// ``` - /// use opentelemetry::Context; + /// use opentelemetry_rk::Context; /// /// // Given some value types defined in your application /// #[derive(Debug, PartialEq)] @@ -165,7 +167,7 @@ impl Context { /// # Examples /// /// ``` - /// use opentelemetry::Context; + /// use opentelemetry_rk::Context; /// /// // Given some value types defined in your application /// #[derive(Debug, PartialEq)] @@ -192,7 +194,7 @@ impl Context { /// # Examples /// /// ``` - /// use opentelemetry::Context; + /// use opentelemetry_rk::Context; /// /// // Given some value types defined in your application /// #[derive(Debug, PartialEq)] @@ -232,7 +234,7 @@ impl Context { /// # Examples /// /// ``` - /// use opentelemetry::Context; + /// use opentelemetry_rk::Context; /// /// #[derive(Debug, PartialEq)] /// struct ValueA(&'static str); @@ -251,7 +253,7 @@ impl Context { /// Guards do not need to be explicitly dropped: /// /// ``` - /// use opentelemetry::Context; + /// use opentelemetry_rk::Context; /// /// #[derive(Debug, PartialEq)] /// struct ValueA(&'static str); @@ -278,7 +280,7 @@ impl Context { /// entered: /// /// ``` - /// use opentelemetry::Context; + /// use opentelemetry_rk::Context; /// /// #[derive(Debug, PartialEq)] /// struct ValueA(&'static str); diff --git a/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/global/metrics.rs b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/global/metrics.rs index b85354bee4..a01be13bdf 100644 --- a/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/global/metrics.rs +++ b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/global/metrics.rs @@ -1,18 +1,17 @@ +extern crate alloc; + use crate::metrics::{self, Meter, MeterProvider}; use crate::KeyValue; use core::fmt; -use once_cell::sync::Lazy; -use std::{ - borrow::Cow, - sync::{Arc, RwLock}, +use oak_core::sync::OnceCell; +use alloc::{ + borrow::Cow, + vec::Vec, + sync::Arc, }; /// The global `MeterProvider` singleton. -static GLOBAL_METER_PROVIDER: Lazy> = Lazy::new(|| { - RwLock::new(GlobalMeterProvider::new( - metrics::noop::NoopMeterProvider::new(), - )) -}); +static GLOBAL_METER_PROVIDER: OnceCell = OnceCell::new(); /// Allows a specific [MeterProvider] to be used generically by the /// [GlobalMeterProvider] by mirroring the interface and boxing the return types. @@ -91,20 +90,23 @@ impl GlobalMeterProvider { pub fn set_meter_provider

(new_provider: P) where P: metrics::MeterProvider + Send + Sync + 'static, + { - let mut global_provider = GLOBAL_METER_PROVIDER - .write() - .expect("GLOBAL_METER_PROVIDER RwLock poisoned"); - *global_provider = GlobalMeterProvider::new(new_provider); + let _ = GLOBAL_METER_PROVIDER.set(GlobalMeterProvider::new(new_provider)); } /// Returns an instance of the currently configured global [`MeterProvider`] /// through [`GlobalMeterProvider`]. pub fn meter_provider() -> GlobalMeterProvider { - GLOBAL_METER_PROVIDER - .read() - .expect("GLOBAL_METER_PROVIDER RwLock poisoned") - .clone() + if GLOBAL_METER_PROVIDER.get().is_none() { + let _ = GLOBAL_METER_PROVIDER.set( + GlobalMeterProvider::new(metrics::noop::NoopMeterProvider::new())); +} + + GLOBAL_METER_PROVIDER + .get() + .expect("GLOBAL_METER_PROVIDER not initialized") + .clone() } /// Creates a named [`Meter`] via the configured [`GlobalMeterProvider`]. @@ -127,8 +129,8 @@ pub fn meter(name: impl Into>) -> Meter { /// # Example /// /// ``` -/// use opentelemetry::global::meter_with_version; -/// use opentelemetry::KeyValue; +/// use opentelemetry_rk::global::meter_with_version; +/// use opentelemetry_rk::KeyValue; /// /// let meter = meter_with_version( /// "io.opentelemetry", diff --git a/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/global/mod.rs b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/global/mod.rs index a1e7b1da72..00640d5fa7 100644 --- a/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/global/mod.rs +++ b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/global/mod.rs @@ -18,8 +18,8 @@ //! ``` //! # #[cfg(feature="trace")] //! # { -//! use opentelemetry::trace::{Tracer, noop::NoopTracerProvider}; -//! use opentelemetry::global; +//! use opentelemetry_rk::trace::{Tracer, noop::NoopTracerProvider}; +//! use opentelemetry_rk::global; //! //! fn init_tracer() { //! // Swap this no-op provider for your tracing service of choice (jaeger, zipkin, etc) @@ -50,8 +50,8 @@ //! ``` //! # #[cfg(feature="trace")] //! # { -//! use opentelemetry::trace::{Tracer, TracerProvider}; -//! use opentelemetry::global; +//! use opentelemetry_rk::trace::{Tracer, TracerProvider}; +//! use opentelemetry_rk::global; //! //! pub fn my_traced_library_function() { //! // End users of your library will configure their global tracer provider @@ -89,8 +89,8 @@ //! ``` //! # #[cfg(feature="metrics")] //! # { -//! use opentelemetry::metrics::{Meter}; -//! use opentelemetry::{global, KeyValue}; +//! use opentelemetry_rk::metrics::{Meter}; +//! use opentelemetry_rk::{global, KeyValue}; //! //! fn do_something_instrumented() { //! let meter = global::meter("my-component"); @@ -113,7 +113,7 @@ //! ``` //! # #[cfg(feature="metrics")] //! # { -//! use opentelemetry::{global, KeyValue}; +//! use opentelemetry_rk::{global, KeyValue}; //! //! fn main() { //! // Set the global meter provider @@ -125,7 +125,7 @@ //! [`MeterProvider`]: crate::metrics::MeterProvider //! [`set_meter_provider`]: crate::global::set_meter_provider -mod error_handler; +// mod error_handler; #[cfg(feature = "metrics")] mod metrics; #[cfg(feature = "trace")] @@ -133,7 +133,7 @@ mod propagation; #[cfg(feature = "trace")] mod trace; -pub use error_handler::{handle_error, set_error_handler, Error}; +// pub use error_handler::{handle_error, set_error_handler, Error}; #[cfg(feature = "metrics")] #[cfg_attr(docsrs, doc(cfg(feature = "metrics")))] pub use metrics::*; diff --git a/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/lib.rs b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/lib.rs index d1283e3f09..df8a1b2ec1 100644 --- a/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/lib.rs +++ b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/lib.rs @@ -11,7 +11,7 @@ //! ```no_run //! # #[cfg(feature = "trace")] //! # { -//! use opentelemetry::{global, trace::{TraceContextExt, Tracer}, Context }; +//! use opentelemetry_rk::{global, trace::{TraceContextExt, Tracer}, Context }; //! //! fn do_something() { //! let tracer = global::tracer("my_component"); @@ -38,7 +38,7 @@ //! ``` //! # #[cfg(feature = "trace")] //! # { -//! use opentelemetry::{global, trace::{Span, Tracer}, KeyValue}; +//! use opentelemetry_rk::{global, trace::{Span, Tracer}, KeyValue}; //! //! // get a tracer from a provider //! let tracer = global::tracer("my_service"); @@ -72,7 +72,7 @@ //! ``` //! # #[cfg(feature = "metrics")] //! # { -//! use opentelemetry::{global, KeyValue}; +//! use opentelemetry_rk::{global, KeyValue}; //! //! // get a meter from a provider //! let meter = global::meter("my_service"); @@ -197,9 +197,9 @@ pub use context::{Context, ContextGuard}; mod common; -#[cfg(any(feature = "testing", test))] -#[doc(hidden)] -pub mod testing; +// #[cfg(any(feature = "testing", test))] +// #[doc(hidden)] +// pub mod testing; pub use common::{ Array, ExportError, InstrumentationLibrary, InstrumentationLibraryBuilder, Key, KeyValue, @@ -210,7 +210,7 @@ pub use common::{ #[cfg_attr(docsrs, doc(cfg(feature = "metrics")))] pub mod metrics; -pub mod propagation; +// pub mod propagation; #[cfg(feature = "trace")] #[cfg_attr(docsrs, doc(cfg(feature = "trace")))] @@ -220,23 +220,3 @@ pub mod trace; #[cfg_attr(docsrs, doc(cfg(feature = "logs")))] pub mod logs; -#[doc(hidden)] -#[cfg(any(feature = "metrics", feature = "trace"))] -pub mod time { - use std::time::SystemTime; - - #[doc(hidden)] - #[cfg(any( - not(target_arch = "wasm32"), - all(target_arch = "wasm32", target_os = "wasi") - ))] - pub fn now() -> SystemTime { - SystemTime::now() - } - - #[doc(hidden)] - #[cfg(all(target_arch = "wasm32", not(target_os = "wasi")))] - pub fn now() -> SystemTime { - SystemTime::UNIX_EPOCH + std::time::Duration::from_millis(js_sys::Date::now() as u64) - } -} diff --git a/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/metrics/instruments/counter.rs b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/metrics/instruments/counter.rs index 3972580628..b7e92b19c2 100644 --- a/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/metrics/instruments/counter.rs +++ b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/metrics/instruments/counter.rs @@ -1,10 +1,12 @@ +extern crate alloc; + use crate::{ metrics::{AsyncInstrument, AsyncInstrumentBuilder, InstrumentBuilder, MetricsError}, KeyValue, }; +use alloc::sync::Arc; +use core::any::Any; use core::fmt; -use std::any::Any; -use std::sync::Arc; /// An SDK implemented instrument that records increasing values. pub trait SyncCounter { @@ -21,7 +23,7 @@ where T: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_fmt(format_args!("Counter<{}>", std::any::type_name::())) + f.write_fmt(format_args!("Counter<{}>", core::any::type_name::())) } } @@ -72,7 +74,7 @@ impl fmt::Debug for ObservableCounter { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_fmt(format_args!( "ObservableCounter<{}>", - std::any::type_name::() + core::any::type_name::() )) } } diff --git a/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/metrics/instruments/gauge.rs b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/metrics/instruments/gauge.rs index 274134aaba..b8ad20c1d7 100644 --- a/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/metrics/instruments/gauge.rs +++ b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/metrics/instruments/gauge.rs @@ -1,10 +1,12 @@ +extern crate alloc; + use crate::{ metrics::{AsyncInstrument, AsyncInstrumentBuilder, InstrumentBuilder, MetricsError}, KeyValue, }; use core::fmt; -use std::any::Any; -use std::sync::Arc; +use core::any::Any; +use alloc::sync::Arc; /// An SDK implemented instrument that records independent values pub trait SyncGauge { @@ -21,7 +23,7 @@ where T: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_fmt(format_args!("Gauge<{}>", std::any::type_name::())) + f.write_fmt(format_args!("Gauge<{}>", core::any::type_name::())) } } @@ -78,7 +80,7 @@ where fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_fmt(format_args!( "ObservableGauge<{}>", - std::any::type_name::() + core::any::type_name::() )) } } diff --git a/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/metrics/instruments/histogram.rs b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/metrics/instruments/histogram.rs index 167da10f7c..04f7de5be3 100644 --- a/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/metrics/instruments/histogram.rs +++ b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/metrics/instruments/histogram.rs @@ -1,9 +1,11 @@ +extern crate alloc; + use crate::{ metrics::{InstrumentBuilder, MetricsError}, KeyValue, }; +use alloc::sync::Arc; use core::fmt; -use std::sync::Arc; /// An SDK implemented instrument that records a distribution of values. pub trait SyncHistogram { @@ -20,7 +22,7 @@ where T: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.write_fmt(format_args!("Histogram<{}>", std::any::type_name::())) + f.write_fmt(format_args!("Histogram<{}>", core::any::type_name::())) } } diff --git a/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/metrics/instruments/mod.rs b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/metrics/instruments/mod.rs index 3ee530453a..f3718dff6e 100644 --- a/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/metrics/instruments/mod.rs +++ b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/metrics/instruments/mod.rs @@ -1,10 +1,11 @@ +extern crate alloc; + use crate::metrics::{Meter, MetricsError, Result}; use crate::KeyValue; +use alloc::{borrow::Cow, boxed::Box, sync::Arc, vec::Vec}; +use core::any::Any; use core::fmt; -use std::any::Any; -use std::borrow::Cow; -use std::marker; -use std::sync::Arc; +use core::marker; use super::InstrumentProvider; @@ -90,7 +91,7 @@ impl fmt::Debug for InstrumentBuilder<'_, T> { .field("name", &self.name) .field("description", &self.description) .field("unit", &self.unit) - .field("kind", &std::any::type_name::()) + .field("kind", &core::any::type_name::()) .finish() } } @@ -188,7 +189,7 @@ where .field("name", &self.name) .field("description", &self.description) .field("unit", &self.unit) - .field("kind", &std::any::type_name::()) + .field("kind", &core::any::type_name::()) .field("callbacks_len", &self.callbacks.len()) .finish() } diff --git a/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/metrics/instruments/up_down_counter.rs b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/metrics/instruments/up_down_counter.rs index f7a2b5e8c2..e16da6e532 100644 --- a/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/metrics/instruments/up_down_counter.rs +++ b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/metrics/instruments/up_down_counter.rs @@ -1,10 +1,12 @@ +extern crate alloc; + use crate::{ metrics::{InstrumentBuilder, MetricsError}, KeyValue, }; +use alloc::sync::Arc; +use core::any::Any; use core::fmt; -use std::any::Any; -use std::sync::Arc; use super::{AsyncInstrument, AsyncInstrumentBuilder}; @@ -25,7 +27,7 @@ where fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_fmt(format_args!( "UpDownCounter<{}>", - std::any::type_name::() + core::any::type_name::() )) } } @@ -77,7 +79,7 @@ where fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_fmt(format_args!( "ObservableUpDownCounter<{}>", - std::any::type_name::() + core::any::type_name::() )) } } @@ -108,7 +110,7 @@ impl AsyncInstrument for ObservableUpDownCounter { self.0.observe(measurement, attributes) } - fn as_any(&self) -> Arc { + fn as_any(&self) -> Arc { self.0.as_any() } } diff --git a/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/metrics/meter.rs b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/metrics/meter.rs index 71bc453eba..c7386642b0 100644 --- a/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/metrics/meter.rs +++ b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/metrics/meter.rs @@ -1,7 +1,8 @@ +extern crate alloc; + +use alloc::{borrow::Cow, sync::Arc}; +use core::any::Any; use core::fmt; -use std::any::Any; -use std::borrow::Cow; -use std::sync::Arc; use crate::metrics::{ AsyncInstrumentBuilder, Counter, Gauge, Histogram, InstrumentBuilder, InstrumentProvider, @@ -26,8 +27,8 @@ pub trait MeterProvider { /// # Examples /// /// ``` - /// use opentelemetry::{global, metrics::MeterProvider}; - /// use opentelemetry::KeyValue; + /// use opentelemetry_rk::{global, metrics::MeterProvider}; + /// use opentelemetry_rk::KeyValue; /// /// let provider = global::meter_provider(); /// @@ -69,7 +70,7 @@ pub trait MeterProvider { /// Provides access to instrument instances for recording measurements. /// /// ``` -/// use opentelemetry::{global, KeyValue}; +/// use opentelemetry_rk::{global, KeyValue}; /// /// let meter = global::meter("my-meter"); /// diff --git a/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/metrics/mod.rs b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/metrics/mod.rs index 1bc17e476e..f947675542 100644 --- a/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/metrics/mod.rs +++ b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/metrics/mod.rs @@ -1,12 +1,15 @@ //! # OpenTelemetry Metrics API -use std::any::Any; -use std::cmp::Ordering; -use std::hash::{Hash, Hasher}; -use std::result; -use std::sync::PoisonError; -use std::{borrow::Cow, sync::Arc}; -use thiserror::Error; +extern crate alloc; + +use alloc::{borrow::Cow, boxed::Box, string::String, sync::Arc, vec::Vec}; +use core::any::Any; +use core::{ + cmp::Ordering, + hash::{Hash, Hasher}, + result, +}; +// use thiserror::Error; mod instruments; mod meter; @@ -25,23 +28,24 @@ pub use meter::{CallbackRegistration, Meter, MeterProvider, Observer}; /// A specialized `Result` type for metric operations. pub type Result = result::Result; +// (TODO) Port errors to no_std /// Errors returned by the metrics API. -#[derive(Error, Debug)] +#[derive(Debug)] #[non_exhaustive] pub enum MetricsError { /// Other errors not covered by specific cases. - #[error("Metrics error: {0}")] + // #[error("Metrics error: {0}")] Other(String), /// Invalid configuration - #[error("Config error {0}")] + // #[error("Config error {0}")] Config(String), /// Fail to export metrics - #[error("Metrics exporter {} failed with {0}", .0.exporter_name())] + // #[error("Metrics exporter {} failed with {0}", .0.exporter_name())] ExportErr(Box), /// Invalid instrument configuration such invalid instrument name, invalid instrument description, invalid instrument unit, etc. /// See [spec](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/metrics/api.md#general-characteristics) /// for full list of requirements. - #[error("Invalid instrument configuration: {0}")] + // #[error("Invalid instrument configuration: {0}")] InvalidInstrumentConfiguration(&'static str), } @@ -51,11 +55,11 @@ impl From for MetricsError { } } -impl From> for MetricsError { - fn from(err: PoisonError) -> Self { - MetricsError::Other(err.to_string()) - } -} +// impl From> for MetricsError { +// fn from(err: PoisonError) -> Self { +// MetricsError::Other(err.to_string()) +// } +// } struct F64Hashable(f64); diff --git a/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/metrics/noop.rs b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/metrics/noop.rs index 68cc3bdcc9..2e4a42a500 100644 --- a/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/metrics/noop.rs +++ b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/metrics/noop.rs @@ -3,6 +3,8 @@ //! This implementation is returned as the global Meter if no `MeterProvider` //! has been set. It is expected to have minimal resource utilization and //! runtime impact. +extern crate alloc; + use crate::{ metrics::{ AsyncInstrument, CallbackRegistration, InstrumentProvider, Meter, MeterProvider, Observer, @@ -10,7 +12,8 @@ use crate::{ }, KeyValue, }; -use std::{any::Any, borrow::Cow, sync::Arc}; +use alloc::{borrow::Cow, sync::Arc}; +use core::any::Any; /// A no-op instance of a `MetricProvider` #[derive(Debug, Default)] diff --git a/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/propagation/mod.rs b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/propagation/mod.rs index 35005f881a..3014e69cc6 100644 --- a/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/propagation/mod.rs +++ b/third_party/opentelemetry/opentelemetry-rust/opentelemetry/src/propagation/mod.rs @@ -20,7 +20,7 @@ //! [`Context`]: crate::Context use std::collections::HashMap; -use thiserror::Error; +// use thiserror::Error; pub mod composite; pub mod text_map_propagator; @@ -63,35 +63,35 @@ impl Extractor for HashMap { } /// Error when extracting or injecting context data(i.e propagating) across application boundaries. -#[derive(Error, Debug)] -#[error("Cannot {} from {}, {}", ops, message, propagator_name)] -pub struct PropagationError { - message: &'static str, - // which propagator does this error comes from - propagator_name: &'static str, - // are we extracting or injecting information across application boundaries - ops: &'static str, -} - -impl PropagationError { - /// Error happens when extracting information - pub fn extract(message: &'static str, propagator_name: &'static str) -> Self { - PropagationError { - message, - propagator_name, - ops: "extract", - } - } - - /// Error happens when extracting information - pub fn inject(message: &'static str, propagator_name: &'static str) -> Self { - PropagationError { - message, - propagator_name, - ops: "inject", - } - } -} +// #[derive(Debug)] +// #[error("Cannot {} from {}, {}", ops, message, propagator_name)] +// pub struct PropagationError { +// message: &'static str, +// // which propagator does this error comes from +// propagator_name: &'static str, +// // are we extracting or injecting information across application boundaries +// ops: &'static str, +// } + +// impl PropagationError { +// /// Error happens when extracting information +// pub fn extract(message: &'static str, propagator_name: &'static str) -> Self { +// PropagationError { +// message, +// propagator_name, +// ops: "extract", +// } +// } + +// /// Error happens when extracting information +// pub fn inject(message: &'static str, propagator_name: &'static str) -> Self { +// PropagationError { +// message, +// propagator_name, +// ops: "inject", +// } +// } +// } #[cfg(test)] mod tests {