Skip to content

Commit

Permalink
remove std dependency from opentelemetry package and add BUILD file s…
Browse files Browse the repository at this point in the history
…keleton

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
  • Loading branch information
msilezin committed Jul 22, 2024
1 parent 0c13105 commit c8e133c
Show file tree
Hide file tree
Showing 18 changed files with 285 additions and 281 deletions.
26 changes: 2 additions & 24 deletions third_party/opentelemetry/opentelemetry-rust/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
[workspace]
members = [
"opentelemetry",
"opentelemetry-*",
"opentelemetry-*/examples/*",
"opentelemetry-otlp/tests/*",
"examples/*",
"stress",
"opentelemetry/",
]

resolver = "2"

[profile.bench]
Expand All @@ -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 }
44 changes: 44 additions & 0 deletions third_party/opentelemetry/opentelemetry-rust/opentelemetry/BUILD
Original file line number Diff line number Diff line change
@@ -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"],
)
Original file line number Diff line number Diff line change
@@ -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"
Expand All @@ -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"
Expand All @@ -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"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<Baggage> = Lazy::new(Baggage::default);
static DEFAULT_BAGGAGE: OnceCell<Baggage> = OnceCell::new();

const MAX_KEY_VALUE_PAIRS: usize = 180;
const MAX_BYTES_FOR_ONE_PAIR: usize = 4096;
Expand Down Expand Up @@ -50,47 +55,25 @@ 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<Key, (Value, BaggageMetadata)>,
inner: BTreeMap<Key, (Value, BaggageMetadata)>,
kv_content_len: usize, // the length of key-value-metadata string in `inner`
}

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<K: AsRef<str>>(&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<K: AsRef<str>>(&self, key: K) -> Option<&(Value, BaggageMetadata)> {
self.inner.get(key.as_ref())
}
Expand All @@ -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");
Expand All @@ -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");
Expand Down Expand Up @@ -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));
Expand Down Expand Up @@ -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() {
Expand All @@ -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<T: IntoIterator<Item = I>, I: Into<KeyValueMetadata>>(
&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<T: IntoIterator<Item = I>, I: Into<KeyValueMetadata>>(
baggage: T,
) -> Self;
Expand All @@ -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());
///
Expand Down Expand Up @@ -399,7 +354,14 @@ impl BaggageExt for Context {
}

fn baggage(&self) -> &Baggage {
self.get::<Baggage>().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"),
}
}
}

Expand Down
Loading

0 comments on commit c8e133c

Please sign in to comment.