Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions api/incubator/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,11 @@ Features:
* Utility methods to reduce boilerplate using span API, including extracting context, and wrapping runnables / callables with spans

See [ExtendedTraceApiUsageTest](./src/test/java/io/opentelemetry/api/incubator/trace/ExtendedTraceApiUsageTest.java).

## Context-Scoped Attributes

Features:

* Associate attributes with a context for automatic stamping across telemetry signals

See [ContextAttributesUsageTest](./src/test/java/io/opentelemetry/api/incubator/common/ContextAttributesUsageTest.java).
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.api.incubator.common;

import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.common.impl.ApiUsageLogger;
import io.opentelemetry.context.Context;
import io.opentelemetry.context.ContextKey;

// TODO (jack-berg): delete after 2027-07-01 if progress hasn't been made on
// https://github.com/open-telemetry/opentelemetry-specification/pull/4931
/**
* Utility for associating {@link Attributes} with a {@link Context} for automatic propagation to
* telemetry signals produced within that context.
*
* <p>SDKs can be configured to stamp context-scoped attributes across telemetry signals, with the
* ability to filter based on signal, instrumentation scope, and attribute key.
*
* <h2>Cardinality Considerations</h2>
*
* <p>The cardinality of context-scoped attributes requires special consideration with metrics,
* since metric cardinality limits can quickly be exceeded by high-cardinality attributes, putting
* the metric into an error state.
*
* <h2>Bound Instruments</h2>
*
* <p>Bound instruments do not inherit dynamic context-scoped attributes.
*/
public final class ContextAttributes {
Comment thread
jack-berg marked this conversation as resolved.
Resolved

private static final ContextKey<Attributes> CONTEXT_ATTRIBUTES_KEY =
ContextKey.named("opentelemetry-context-attributes");

private ContextAttributes() {}

/**
* Sets the {@link Attributes} on the given {@link Context}, completely replacing any previously
* associated context-scoped attributes.
*
* @param context the context to attach attributes to.
* @param attributes the authoritative attributes to associate. Pass {@link Attributes#empty()} to
* logically clear context-scoped attributes.
* @return a new context containing the specified attributes.
*/
public static Context set(Context context, Attributes attributes) {
if (context == null) {
ApiUsageLogger.logNullParam(ContextAttributes.class, "set", "context");
return Context.root();
}
if (attributes == null) {
ApiUsageLogger.logNullParam(ContextAttributes.class, "set", "attributes");
return context;
}
if (attributes.isEmpty()) {
Attributes existing = context.get(CONTEXT_ATTRIBUTES_KEY);
if (existing == null || existing.isEmpty()) {
return context;
}
return context.with(CONTEXT_ATTRIBUTES_KEY, Attributes.empty());
}
return context.with(CONTEXT_ATTRIBUTES_KEY, attributes);
}

/**
* Returns the {@link Attributes} associated with the given {@code context}, or {@link
* Attributes#empty()} if none are present.
*
* <p>This method is intended primarily for telemetry pipeline components such as SDKs, samplers,
* processors, and exporters. Application code should treat context-scoped attributes as
* write-only via {@link #set(Context, Attributes)}.
*/
public static Attributes get(Context context) {
if (context == null) {
return Attributes.empty();
}
Attributes attributes = context.get(CONTEXT_ATTRIBUTES_KEY);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I see usefulness in this feature but I find it hard to understand how to decide with instrumentations should include the attributes.

How to assert or qualify the carnality of the attribute?
Which instrumentations should skip an attribute?
Should we have a handler to decide which instrumentations opt to an attribute?
Are there attributes that make no sense across an entire context lifespan?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Instrumentations are advised against including attributes (see javadoc at top).

Think about the core use cases: tenant id / user id. An application would add these to context early in request lifecycle via interceptor or filter. They would also configure the SDK to include the attributes as needed based on signal, scope, and and attribute key.

The OTEP left a lot of questions unanswered with the intent of discovering more via prototyping. If you have general feedback (i.e. not related to the java implementation), please add it to open-telemetry/opentelemetry-specification#5170 so all languages can benefit.

return attributes != null ? attributes : Attributes.empty();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.api.incubator.common;

import static io.opentelemetry.api.common.AttributeKey.longKey;
import static io.opentelemetry.api.common.AttributeKey.stringKey;
import static org.assertj.core.api.Assertions.assertThat;

import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.context.Context;
import io.opentelemetry.context.Scope;
import org.junit.jupiter.api.Test;

class ContextAttributesTest {

@Test
void emptyContext_returnsEmptyAttributes() {
assertThat(ContextAttributes.get(Context.root())).isEqualTo(Attributes.empty());
assertThat(ContextAttributes.get(null)).isEqualTo(Attributes.empty());
}

@Test
void setNullValidation() {
Context root = Context.root();
Attributes attrs = Attributes.of(stringKey("k"), "v");
assertThat(ContextAttributes.set(null, attrs)).isEqualTo(Context.root());
assertThat(ContextAttributes.set(root, null)).isSameAs(root);
}

@Test
void setReplacesExistingAndClearsWithEmpty() {
Context ctx1 =
ContextAttributes.set(
Context.root(), Attributes.of(stringKey("k1"), "v1", longKey("k2"), 2L));
assertThat(ContextAttributes.get(ctx1))
.isEqualTo(Attributes.of(stringKey("k1"), "v1", longKey("k2"), 2L));

// set() completely replaces previous attributes
Context ctx2 = ContextAttributes.set(ctx1, Attributes.of(stringKey("k3"), "v3"));
assertThat(ContextAttributes.get(ctx2)).isEqualTo(Attributes.of(stringKey("k3"), "v3"));

// set() with empty clears attributes
Context ctxCleared = ContextAttributes.set(ctx2, Attributes.empty());
assertThat(ContextAttributes.get(ctxCleared)).isEqualTo(Attributes.empty());

// set() with empty on already empty returns same context
assertThat(ContextAttributes.set(Context.root(), Attributes.empty())).isSameAs(Context.root());
}

@Test
void setAndGet_singleLayer() {
Attributes attrs = Attributes.of(stringKey("user.id"), "u123", longKey("retry"), 1L);
Context ctx = ContextAttributes.set(Context.root(), attrs);

assertThat(ContextAttributes.get(ctx)).isEqualTo(attrs);
assertThat(ContextAttributes.get(Context.root())).isEqualTo(Attributes.empty());
}

@Test
void scopeAttachment_restoresOuterContextAttributesOnClose() {
Context outer = ContextAttributes.set(Context.root(), Attributes.of(stringKey("env"), "prod"));
try (Scope ignoredOuter = outer.makeCurrent()) {
assertThat(ContextAttributes.get(Context.current()))
.isEqualTo(Attributes.of(stringKey("env"), "prod"));

Context inner =
ContextAttributes.set(
Context.current(),
Attributes.of(stringKey("env"), "staging", stringKey("req"), "r1"));
try (Scope ignoredInner = inner.makeCurrent()) {
assertThat(ContextAttributes.get(Context.current()))
.isEqualTo(Attributes.of(stringKey("env"), "staging", stringKey("req"), "r1"));
}

assertThat(ContextAttributes.get(Context.current()))
.isEqualTo(Attributes.of(stringKey("env"), "prod"));
}
assertThat(ContextAttributes.get(Context.current())).isEqualTo(Attributes.empty());
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
/*
* Copyright The OpenTelemetry Authors
* SPDX-License-Identifier: Apache-2.0
*/

package io.opentelemetry.api.incubator.common;

import static io.opentelemetry.api.common.AttributeKey.stringKey;
import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.assertThat;
import static io.opentelemetry.sdk.testing.assertj.OpenTelemetryAssertions.attributeEntry;

import io.opentelemetry.api.common.Attributes;
import io.opentelemetry.api.logs.Logger;
import io.opentelemetry.api.metrics.LongCounter;
import io.opentelemetry.api.metrics.Meter;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.Tracer;
import io.opentelemetry.context.Context;
import io.opentelemetry.context.Scope;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.logs.SdkLoggerProvider;
import io.opentelemetry.sdk.logs.SdkLoggerProviderBuilder;
import io.opentelemetry.sdk.logs.export.SimpleLogRecordProcessor;
import io.opentelemetry.sdk.logs.internal.SdkLoggerProviderUtil;
import io.opentelemetry.sdk.metrics.SdkMeterProvider;
import io.opentelemetry.sdk.metrics.SdkMeterProviderBuilder;
import io.opentelemetry.sdk.metrics.internal.SdkMeterProviderUtil;
import io.opentelemetry.sdk.testing.exporter.InMemoryLogRecordExporter;
import io.opentelemetry.sdk.testing.exporter.InMemoryMetricReader;
import io.opentelemetry.sdk.testing.exporter.InMemorySpanExporter;
import io.opentelemetry.sdk.trace.SdkTracerProvider;
import io.opentelemetry.sdk.trace.SdkTracerProviderBuilder;
import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor;
import io.opentelemetry.sdk.trace.internal.SdkTracerProviderUtil;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

/** Demonstrating usage of {@link ContextAttributes}. */
class ContextAttributesUsageTest {

private InMemorySpanExporter spanExporter;
private InMemoryLogRecordExporter logExporter;
private InMemoryMetricReader metricReader;

private Tracer tracer;
private Logger logger;
private LongCounter counter;

@BeforeEach
void setUp() {
spanExporter = InMemorySpanExporter.create();
logExporter = InMemoryLogRecordExporter.create();
metricReader = InMemoryMetricReader.create();

SdkTracerProviderBuilder tracerProviderBuilder =
SdkTracerProvider.builder().addSpanProcessor(SimpleSpanProcessor.create(spanExporter));
SdkTracerProviderUtil.setContextScopedAttributesFilter(
tracerProviderBuilder, (scope, key) -> true);

SdkLoggerProviderBuilder loggerProviderBuilder =
SdkLoggerProvider.builder()
.addLogRecordProcessor(SimpleLogRecordProcessor.create(logExporter));
SdkLoggerProviderUtil.setContextScopedAttributesFilter(
loggerProviderBuilder, (scope, key) -> true);

SdkMeterProviderBuilder meterProviderBuilder =
SdkMeterProvider.builder().registerMetricReader(metricReader);
SdkMeterProviderUtil.setContextScopedAttributesFilter(
meterProviderBuilder, (scope, key) -> true);

OpenTelemetrySdk sdk =
OpenTelemetrySdk.builder()
.setTracerProvider(tracerProviderBuilder.build())
.setLoggerProvider(loggerProviderBuilder.build())
.setMeterProvider(meterProviderBuilder.build())
.build();

tracer = sdk.getTracer("usage-test");
logger = sdk.getLogsBridge().get("usage-test");
Meter meter = sdk.getMeter("usage-test");
counter = meter.counterBuilder("orders_total").build();
}

@Test
void multiSignalPropagation() {
Context ctx =
ContextAttributes.set(
Context.current(),
Attributes.of(stringKey("tenant.id"), "t-123", stringKey("environment"), "production"));

try (Scope ignored = ctx.makeCurrent()) {
Span span =
tracer
.spanBuilder("process-checkout")
.setAttribute("operation.type", "checkout")
.startSpan();
span.end();

logger.logRecordBuilder().setBody("checkout initiated").emit();

counter.add(1, Attributes.of(stringKey("currency"), "USD"));
}

assertThat(spanExporter.getFinishedSpanItems())
.satisfiesExactly(span ->
assertThat(span)
.hasName("process-checkout")
.hasAttributes(
attributeEntry("operation.type", "checkout"),
attributeEntry("tenant.id", "t-123"),
attributeEntry("environment", "production")));

assertThat(logExporter.getFinishedLogRecordItems())
.satisfiesExactly(log ->
assertThat(log)
.hasBody("checkout initiated")
.hasAttributes(
attributeEntry("tenant.id", "t-123"),
attributeEntry("environment", "production")));

assertThat(metricReader.collectAllMetrics())
.satisfiesExactly(metric ->
assertThat(metric)
.hasName("orders_total")
.hasLongSumPointsSatisfying(point ->
point
.hasValue(1)
.hasAttributes(
attributeEntry("currency", "USD"),
attributeEntry("tenant.id", "t-123"),
attributeEntry("environment", "production"))));
}

@Test
void selectiveFiltering() {
InMemorySpanExporter localSpanExporter = InMemorySpanExporter.create();
InMemoryMetricReader localMetricReader = InMemoryMetricReader.create();

SdkTracerProviderBuilder tracerBuilder =
SdkTracerProvider.builder().addSpanProcessor(SimpleSpanProcessor.create(localSpanExporter));
SdkTracerProviderUtil.setContextScopedAttributesFilter(
tracerBuilder, (scope, key) -> key.getKey().equals("tenant.id"));

SdkMeterProviderBuilder meterBuilder =
SdkMeterProvider.builder().registerMetricReader(localMetricReader);
SdkMeterProviderUtil.setContextScopedAttributesFilter(
meterBuilder, (scope, key) -> key.getKey().equals("region"));

OpenTelemetrySdk sdk =
OpenTelemetrySdk.builder()
.setTracerProvider(tracerBuilder.build())
.setMeterProvider(meterBuilder.build())
.build();

Tracer localTracer = sdk.getTracer("usage-test");
LongCounter localCounter = sdk.getMeter("usage-test").counterBuilder("requests").build();

Context ctx =
ContextAttributes.set(
Context.current(),
Attributes.of(stringKey("tenant.id"), "t-999", stringKey("region"), "us-west-2"));

try (Scope ignored = ctx.makeCurrent()) {
localTracer.spanBuilder("request").startSpan().end();
localCounter.add(1);
}

assertThat(localSpanExporter.getFinishedSpanItems())
.satisfiesExactly(
span -> assertThat(span).hasAttributes(attributeEntry("tenant.id", "t-999")));

assertThat(localMetricReader.collectAllMetrics())
.satisfiesExactly(metric ->
assertThat(metric)
.hasLongSumPointsSatisfying(point ->
point.hasValue(1).hasAttributes(attributeEntry("region", "us-west-2"))));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,17 @@ public <T> T get(AttributeKey<T> key) {
return (T) entryValues[idx];
}

/**
* Returns whether an attribute with the given key name exists in this map, regardless of type.
*
* <p>Runs with expected/amortized O(1) complexity using the internal open-addressing table.
*
* @param key the attribute key name to look up. Must not be null.
*/
public boolean containsKey(String key) {
return hashTable[findSlot(key)] != EMPTY;
}

@Override
public int size() {
return size;
Expand Down
Loading
Loading