Skip to content

Commit dced93e

Browse files
committed
refactor Baggage with Context interaction
1 parent 1ddecb0 commit dced93e

File tree

4 files changed

+47
-45
lines changed

4 files changed

+47
-45
lines changed

opentelemetry-sdk/src/propagation/baggage.rs

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
use opentelemetry::{
2-
baggage::{BaggageExt, KeyValueMetadata},
2+
baggage::{Baggage, BaggageExt, KeyValueMetadata},
33
otel_warn,
44
propagation::{text_map_propagator::FieldIter, Extractor, Injector, TextMapPropagator},
55
Context,
@@ -30,7 +30,7 @@ fn baggage_fields() -> &'static [String; 1] {
3030
/// # Examples
3131
///
3232
/// ```
33-
/// use opentelemetry::{baggage::BaggageExt, KeyValue, propagation::TextMapPropagator};
33+
/// use opentelemetry::{baggage::{Baggage, BaggageExt}, propagation::TextMapPropagator};
3434
/// use opentelemetry_sdk::propagation::BaggagePropagator;
3535
/// use std::collections::HashMap;
3636
///
@@ -48,14 +48,17 @@ fn baggage_fields() -> &'static [String; 1] {
4848
/// }
4949
///
5050
/// // Add new baggage
51-
/// let cx_with_additions = cx.with_baggage(vec![KeyValue::new("server_id", 42)]);
51+
/// let mut baggage = Baggage::new();
52+
/// let _ = baggage.insert("server_id", "42");
53+
///
54+
/// let cx_with_additions = cx.with_baggage(baggage);
5255
///
5356
/// // Inject baggage into http request
5457
/// propagator.inject_context(&cx_with_additions, &mut headers);
5558
///
5659
/// let header_value = headers.get("baggage").expect("header is injected");
57-
/// assert!(header_value.contains("user_id=1"), "still contains previous name-value");
58-
/// assert!(header_value.contains("server_id=42"), "contains new name-value pair");
60+
/// assert!(!header_value.contains("user_id=1"), "still contains previous name-value");
61+
/// assert!(header_value.contains("server_id=42"), "does not contain new name-value pair");
5962
/// ```
6063
///
6164
/// [W3C Baggage]: https://w3c.github.io/baggage
@@ -98,7 +101,7 @@ impl TextMapPropagator for BaggagePropagator {
98101
/// Extracts a `Context` with baggage values from a `Extractor`.
99102
fn extract_with_context(&self, cx: &Context, extractor: &dyn Extractor) -> Context {
100103
if let Some(header_value) = extractor.get(BAGGAGE_HEADER) {
101-
let baggage = header_value.split(',').flat_map(|context_value| {
104+
let baggage = header_value.split(',').filter_map(|context_value| {
102105
if let Some((name_and_value, props)) = context_value
103106
.split(';')
104107
.collect::<Vec<&str>>()
@@ -148,7 +151,7 @@ impl TextMapPropagator for BaggagePropagator {
148151
None
149152
}
150153
});
151-
cx.with_baggage(baggage)
154+
cx.with_baggage(Baggage::from_iter(baggage))
152155
} else {
153156
cx.clone()
154157
}
@@ -275,7 +278,7 @@ mod tests {
275278

276279
for (kvm, header_parts) in valid_inject_data() {
277280
let mut injector = HashMap::new();
278-
let cx = Context::current_with_baggage(kvm);
281+
let cx = Context::current_with_baggage(Baggage::from_iter(kvm));
279282
propagator.inject_context(&cx, &mut injector);
280283
let header_value = injector.get(BAGGAGE_HEADER).unwrap();
281284
assert_eq!(header_parts.join(",").len(), header_value.len(),);
@@ -307,7 +310,7 @@ mod tests {
307310

308311
for (kvm, header_parts) in valid_inject_data_metadata() {
309312
let mut injector = HashMap::new();
310-
let cx = Context::current_with_baggage(kvm);
313+
let cx = Context::current_with_baggage(Baggage::from_iter(kvm));
311314
propagator.inject_context(&cx, &mut injector);
312315
let header_value = injector.get(BAGGAGE_HEADER).unwrap();
313316

opentelemetry/CHANGELOG.md

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,12 @@
77
- *Breaking* Moved `TraceResult` type alias from `opentelemetry::trace::TraceResult` to `opentelemetry_sdk::trace::TraceResult`
88
- {PLACEHOLDER} - Remove the above completely. // TODO fill this when changes are actually in.
99
- Bug Fix: `InstrumentationScope` implementation for `PartialEq` and `Hash` fixed to include Attributes also.
10-
- *Breaking* Changed value type of `Baggage` from `Value` to `StringValue`
11-
- Updated `Baggage` constants to reflect latest standard (`MAX_KEY_VALUE_PAIRS` - 180 -> 64, `MAX_BYTES_FOR_ONE_PAIR` - removed) and increased insert performance see #[2284](https://github.com/open-telemetry/opentelemetry-rust/pull/2284).
12-
- *Breaking* Align `Baggage.remove()` signature with `.get()` to take the key as a reference
10+
- **Breaking changes for baggage users**: [#2717](https://github.com/open-telemetry/opentelemetry-rust/issues/2717)
11+
- Changed value type of `Baggage` from `Value` to `StringValue`
12+
- Updated `Baggage` constants to reflect latest standard (`MAX_KEY_VALUE_PAIRS` - 180 -> 64, `MAX_BYTES_FOR_ONE_PAIR` - removed) and increased insert performance see #[2284](https://github.com/open-telemetry/opentelemetry-rust/pull/2284).
13+
- Align `Baggage.remove()` signature with `.get()` to take the key as a reference
14+
- `Baggage` can't be retrieved from the `Context` directly anymore and needs to be accessed via `context.baggage()`
15+
- `with_baggage()` and `current_with_baggage()` only accept a `Baggage` instance and override any existing `Baggage` in the `Context`
1316

1417
## 0.28.0
1518

opentelemetry/src/baggage.rs

Lines changed: 22 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -308,39 +308,40 @@ pub trait BaggageExt {
308308
/// # Examples
309309
///
310310
/// ```
311-
/// use opentelemetry::{baggage::BaggageExt, Context, KeyValue, StringValue};
311+
/// use opentelemetry::{baggage::{Baggage, BaggageExt}, Context, StringValue};
312+
///
313+
/// let mut baggage = Baggage::new();
314+
/// let _ = baggage.insert("my-name", "my-value");
312315
///
313316
/// let cx = Context::map_current(|cx| {
314-
/// cx.with_baggage(vec![KeyValue::new("my-name", "my-value")])
317+
/// cx.with_baggage(baggage)
315318
/// });
316319
///
317320
/// assert_eq!(
318321
/// cx.baggage().get("my-name"),
319322
/// Some(&StringValue::from("my-value")),
320323
/// )
321324
/// ```
322-
fn with_baggage<T: IntoIterator<Item = I>, I: Into<KeyValueMetadata>>(
323-
&self,
324-
baggage: T,
325-
) -> Self;
325+
fn with_baggage(&self, baggage: Baggage) -> Self;
326326

327327
/// Returns a clone of the current context with the included name/value pairs.
328328
///
329329
/// # Examples
330330
///
331331
/// ```
332-
/// use opentelemetry::{baggage::BaggageExt, Context, KeyValue, StringValue};
332+
/// use opentelemetry::{baggage::{Baggage, BaggageExt}, Context, StringValue};
333333
///
334-
/// let cx = Context::current_with_baggage(vec![KeyValue::new("my-name", "my-value")]);
334+
/// let mut baggage = Baggage::new();
335+
/// let _ = baggage.insert("my-name", "my-value");
336+
///
337+
/// let cx = Context::current_with_baggage(baggage);
335338
///
336339
/// assert_eq!(
337340
/// cx.baggage().get("my-name"),
338341
/// Some(&StringValue::from("my-value")),
339342
/// )
340343
/// ```
341-
fn current_with_baggage<T: IntoIterator<Item = I>, I: Into<KeyValueMetadata>>(
342-
baggage: T,
343-
) -> Self;
344+
fn current_with_baggage(baggage: Baggage) -> Self;
344345

345346
/// Returns a clone of the given context with no baggage.
346347
///
@@ -360,33 +361,26 @@ pub trait BaggageExt {
360361
fn baggage(&self) -> &Baggage;
361362
}
362363

363-
impl BaggageExt for Context {
364-
fn with_baggage<T: IntoIterator<Item = I>, I: Into<KeyValueMetadata>>(
365-
&self,
366-
baggage: T,
367-
) -> Self {
368-
let old = self.baggage();
369-
let mut merged = Baggage {
370-
inner: old.inner.clone(),
371-
kv_content_len: old.kv_content_len,
372-
};
373-
for kvm in baggage.into_iter().map(|kv| kv.into()) {
374-
merged.insert_with_metadata(kvm.key, kvm.value, kvm.metadata);
375-
}
364+
/// Solely used to store `Baggage` in the `Context` without allowing direct access
365+
#[derive(Debug)]
366+
struct BaggageContextValue(Baggage);
376367

377-
self.with_value(merged)
368+
impl BaggageExt for Context {
369+
fn with_baggage(&self, baggage: Baggage) -> Self {
370+
self.with_value(BaggageContextValue(baggage))
378371
}
379372

380-
fn current_with_baggage<T: IntoIterator<Item = I>, I: Into<KeyValueMetadata>>(kvs: T) -> Self {
381-
Context::map_current(|cx| cx.with_baggage(kvs))
373+
fn current_with_baggage(baggage: Baggage) -> Self {
374+
Context::map_current(|cx| cx.with_baggage(baggage))
382375
}
383376

384377
fn with_cleared_baggage(&self) -> Self {
385378
self.with_value(Baggage::new())
386379
}
387380

388381
fn baggage(&self) -> &Baggage {
389-
self.get::<Baggage>().unwrap_or(get_default_baggage())
382+
self.get::<BaggageContextValue>()
383+
.map_or(get_default_baggage(), |b| &b.0)
390384
}
391385
}
392386

opentelemetry/src/propagation/composite.rs

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ use std::collections::HashSet;
2323
///
2424
/// ```
2525
/// use opentelemetry::{
26-
/// baggage::BaggageExt,
26+
/// baggage::{Baggage, BaggageExt},
2727
/// propagation::{TextMapPropagator, TextMapCompositePropagator},
2828
///
2929
/// trace::{TraceContextExt, Tracer, TracerProvider},
@@ -56,7 +56,7 @@ use std::collections::HashSet;
5656
/// // with the current context, call inject to add the headers
5757
/// composite_propagator.inject_context(
5858
/// &Context::current_with_span(example_span)
59-
/// .with_baggage(vec![KeyValue::new("test", "example")]),
59+
/// .with_baggage(Baggage::from_iter([KeyValue::new("test", "example")])),
6060
/// &mut injector,
6161
/// );
6262
///
@@ -115,7 +115,7 @@ impl TextMapPropagator for TextMapCompositePropagator {
115115

116116
#[cfg(all(test, feature = "trace"))]
117117
mod tests {
118-
use crate::baggage::BaggageExt;
118+
use crate::baggage::{Baggage, BaggageExt};
119119
use crate::propagation::TextMapCompositePropagator;
120120
use crate::testing::trace::TestSpan;
121121
use crate::{
@@ -162,7 +162,9 @@ mod tests {
162162
false,
163163
TraceState::default(),
164164
)),
165-
("baggage", Some(_)) => cx.with_baggage(vec![KeyValue::new("baggagekey", "value")]),
165+
("baggage", Some(_)) => {
166+
cx.with_baggage(Baggage::from_iter([KeyValue::new("baggagekey", "value")]))
167+
}
166168
_ => cx.clone(),
167169
}
168170
}
@@ -182,7 +184,7 @@ mod tests {
182184
TraceState::default(),
183185
)));
184186
// setup for baggage propagator
185-
cx.with_baggage(vec![KeyValue::new("baggagekey", "value")])
187+
cx.with_baggage(Baggage::from_iter([KeyValue::new("baggagekey", "value")]))
186188
}
187189

188190
fn test_data() -> Vec<(&'static str, &'static str)> {

0 commit comments

Comments
 (0)