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
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
/*
* Copyright 2026 Google LLC
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google LLC nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package com.google.showcase.v1beta1.it;

import static com.google.common.truth.Truth.assertThat;

import com.google.api.gax.tracing.ApiTracerFactory;
import com.google.api.gax.tracing.CompositeTracerFactory;
import com.google.api.gax.tracing.OpenTelemetryMetricsFactory;
import com.google.api.gax.tracing.OpenTelemetryTracingFactory;
import com.google.showcase.v1beta1.EchoClient;
import com.google.showcase.v1beta1.EchoRequest;
import com.google.showcase.v1beta1.it.util.TestClientInitializer;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.SpanKind;
import io.opentelemetry.sdk.OpenTelemetrySdk;
import io.opentelemetry.sdk.metrics.ExemplarFilter;
import io.opentelemetry.sdk.metrics.SdkMeterProvider;
import io.opentelemetry.sdk.metrics.data.ExemplarData;
import io.opentelemetry.sdk.metrics.data.HistogramPointData;
import io.opentelemetry.sdk.metrics.data.MetricData;
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.data.SpanData;
import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor;
import java.time.Duration;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;
import org.awaitility.Awaitility;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

/**
* Integration tests for Feature 3 (F3.1–F3.2): T3 Tracing and M3 Metrics Exemplar Correlation.
*
* <p>T3 is the logical client-operation trace span ({@link SpanKind#INTERNAL}) and M3 is the
* client-level request duration metric ({@code gcp.client.request.duration}). These tests verify
* that M3 histogram data points attach an exemplar referencing the corresponding T3 span.
*/
class ITOtelT3MetricsExemplar {
private InMemorySpanExporter spanExporter;
private InMemoryMetricReader metricReader;
private OpenTelemetrySdk openTelemetrySdk;

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

SdkTracerProvider tracerProvider =
SdkTracerProvider.builder()
.addSpanProcessor(SimpleSpanProcessor.create(spanExporter))
.build();

SdkMeterProvider meterProvider =
SdkMeterProvider.builder()
.registerMetricReader(metricReader)
.setExemplarFilter(ExemplarFilter.traceBased())
Comment thread
lqiu96 marked this conversation as resolved.
Resolved
.build();

openTelemetrySdk =
OpenTelemetrySdk.builder()
.setTracerProvider(tracerProvider)
.setMeterProvider(meterProvider)
.build();
}

@AfterEach
void tearDown() {
if (openTelemetrySdk != null) {
openTelemetrySdk.close();
}
}

// F3.1: HTTP M3 metric records T3 span as exemplar
@Test
void testHttpJson_m3ExemplarMatchesT3Span() throws Exception {
ApiTracerFactory compositeTracerFactory = createCompositeTracerFactory();

try (EchoClient client =
TestClientInitializer.createHttpJsonEchoClientOpentelemetry(compositeTracerFactory)) {
client.echo(EchoRequest.newBuilder().setContent("exemplar-test-http").build());
assertThat(Span.current().getSpanContext().isValid()).isFalse();

assertM3ExemplarMatchesT3Span();
}
}

// F3.2: gRPC M3 metric records T3 span as exemplar
@Test
void testGrpc_m3ExemplarMatchesT3Span() throws Exception {
ApiTracerFactory compositeTracerFactory = createCompositeTracerFactory();

try (EchoClient client =
TestClientInitializer.createGrpcEchoClientOpentelemetry(compositeTracerFactory)) {
client.echo(EchoRequest.newBuilder().setContent("exemplar-test-grpc").build());
assertThat(Span.current().getSpanContext().isValid()).isFalse();

assertM3ExemplarMatchesT3Span();
}
}

/**
* Waits for both T3 and T4 spans to finish, then collects M3 metrics once and asserts that the
* duration histogram exemplar references the single T3 span.
*/
private void assertM3ExemplarMatchesT3Span() {
List<SpanData> spans = waitAndCollectSpans(2);
assertThat(spans).hasSize(2);

List<SpanData> t3Spans =
spans.stream().filter(s -> s.getKind() == SpanKind.INTERNAL).collect(Collectors.toList());
assertThat(t3Spans).hasSize(1);
SpanData t3Span = t3Spans.get(0);

// Collect metrics once after span completion; repeated collectAllMetrics() calls reset
// InMemoryMetricReader's ExemplarReservoir.
Collection<MetricData> metrics = metricReader.collectAllMetrics();
MetricData durationMetric =
metrics.stream()
.filter(m -> m.getName().equals("gcp.client.request.duration"))
.findFirst()
.orElseThrow(() -> new AssertionError("Duration metric not found in: " + metrics));

Collection<HistogramPointData> points = durationMetric.getHistogramData().getPoints();
assertThat(points).hasSize(1);
HistogramPointData point = points.iterator().next();
List<? extends ExemplarData> exemplars = point.getExemplars();
assertThat(exemplars).isNotEmpty();

ExemplarData exemplar = exemplars.get(0);
assertThat(exemplar.getSpanContext().getTraceId()).isEqualTo(t3Span.getTraceId());
assertThat(exemplar.getSpanContext().getSpanId()).isEqualTo(t3Span.getSpanId());
}

/**
* Creates a composite tracer factory combining both OpenTelemetry tracing and metrics factories.
*
* @return the configured {@link CompositeTracerFactory}
*/
private CompositeTracerFactory createCompositeTracerFactory() {
OpenTelemetryTracingFactory tracingFactory = new OpenTelemetryTracingFactory(openTelemetrySdk);
OpenTelemetryMetricsFactory metricsFactory = new OpenTelemetryMetricsFactory(openTelemetrySdk);
return new CompositeTracerFactory(Arrays.asList(tracingFactory, metricsFactory));
}

/**
* Waits until the in-memory span exporter records at least {@code minSpans} completed spans.
*
* @param minSpans the minimum number of spans expected
* @return the list of completed {@link SpanData} items
*/
private List<SpanData> waitAndCollectSpans(int minSpans) {
Awaitility.await()
.atMost(Duration.ofSeconds(5))
.until(() -> spanExporter.getFinishedSpanItems().size() >= minSpans);
return spanExporter.getFinishedSpanItems();
}
Comment on lines +185 to +190

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.

Maybe in a follow up PR: I think I see waitAndCollectSpans() and potentially some other helpers that could be re-used across the additional ITs. Maybe it may be helpful for a central place for the OtelHelpers?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for the suggestion. Will follow-up with a separate PR.

}
Loading
Loading