Skip to content
Closed
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
Expand Up @@ -85,15 +85,16 @@ private CompletableFuture<ClientHttpResponse> trace(
.setParent(context)
.startSpan();

spanDecorator.onRequest(span, arguments);
final RequestArguments decoratedArguments = spanDecorator.decorateRequest(span, arguments);
spanDecorator.onRequest(span, decoratedArguments);

final Map<String, String> headers = new HashMap<>();
try (final Scope ignored = context.with(span).makeCurrent()) {
this.propagator.inject(Context.current(), headers, Map::put);

return execution.execute(arguments.withHeaders(Multimaps.forMap(headers).asMap()))
.whenComplete(decorateOnResponse(span, arguments))
.whenComplete(decorateOnError(span, arguments))
return execution.execute(decoratedArguments.withHeaders(Multimaps.forMap(headers).asMap()))
.whenComplete(decorateOnResponse(span, decoratedArguments))
.whenComplete(decorateOnError(span, decoratedArguments))
.whenComplete((r, t) -> span.end());
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,15 @@ public class CompositeSpanDecorator implements SpanDecorator {

private final Iterable<SpanDecorator> decorators;

@Override
public RequestArguments decorateRequest(final Span span, final RequestArguments arguments) {
RequestArguments decoratedArguments = arguments;
for (final SpanDecorator decorator : decorators) {
decoratedArguments = decorator.decorateRequest(span, decoratedArguments);
}
return decoratedArguments;
}

@Override
public void onRequest(Span span, RequestArguments arguments) {
decorators.forEach(decorator -> decorator.onRequest(span, arguments));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,32 @@
import org.zalando.riptide.RequestArguments;

import java.util.Optional;

import lombok.RequiredArgsConstructor;
import java.util.UUID;

import static org.zalando.riptide.opentelemetry.span.ExtensionAttributes.FLOW_ID;

@RequiredArgsConstructor
public class FlowIdSpanDecorator implements SpanDecorator {

public static final String FLOW_ID_HEADER = "X-Flow-ID";

private final boolean propagateFlowId;
@Override
public RequestArguments decorateRequest(final Span span, final RequestArguments arguments) {
return arguments.withHeader(FLOW_ID_HEADER, flowId(span));
}

@Override
public void onRequest(Span span, RequestArguments arguments) {
Optional.ofNullable(Baggage.current().getEntryValue(FLOW_ID.getKey()))
.ifPresent(flowId -> {
span.setAttribute(FLOW_ID, flowId);

if (propagateFlowId) {
arguments.withHeader(FLOW_ID_HEADER, flowId);
}
});
public void onRequest(final Span span, final RequestArguments arguments) {
// withHeader appends the Flow ID, so the last value is the one sent to the downstream service.
arguments.getHeaders().getOrDefault(FLOW_ID_HEADER, java.util.List.of()).stream()
.reduce((first, second) -> second)
.ifPresent(flowId -> span.setAttribute(FLOW_ID, flowId));
}

private String flowId(final Span span) {
return Optional.ofNullable(Baggage.current().getEntryValue(FLOW_ID.getKey()))
.orElseGet(() -> span.getSpanContext().isValid()
? span.getSpanContext().getTraceId()
// An invalid context reports a non-unique trace ID for every request.
: UUID.randomUUID().toString());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@
import java.io.IOException;

public interface SpanDecorator {
default RequestArguments decorateRequest(final Span span, final RequestArguments arguments) {
return arguments;
}

default void onRequest(final Span span, final RequestArguments arguments) {
// nothing to do
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package org.zalando.riptide.opentelemetry;

import com.google.common.collect.ImmutableMap;
import io.opentelemetry.api.baggage.Baggage;
import io.opentelemetry.api.common.AttributeKey;
import io.opentelemetry.api.common.Attributes;
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.testing.junit5.OpenTelemetryExtension;
import io.opentelemetry.sdk.trace.data.EventData;
Expand All @@ -23,12 +25,15 @@
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.mockito.ArgumentCaptor;
import org.mockito.Mockito;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.zalando.riptide.*;
import org.zalando.riptide.opentelemetry.span.ExtensionAttributes;
import org.zalando.riptide.opentelemetry.span.FlowIdSpanDecorator;
import org.zalando.riptide.opentelemetry.span.HttpHostSpanDecorator;
import org.zalando.riptide.opentelemetry.span.SpanDecorator;
import org.zalando.riptide.opentelemetry.span.StaticSpanDecorator;
Expand Down Expand Up @@ -269,6 +274,60 @@ void shouldActivateScope() throws IOException {
otelTesting.assertTraces().singleElement().singleElement().hasName(newName);
}

@Test
void shouldUseBaggageFlowIdForFlowIdHeaderWhenAvailable() throws IOException {
final RequestExecution execution = Mockito.mock(RequestExecution.class);
final RequestArguments arguments = RequestArguments.create()
.withMethod(HttpMethod.GET)
.withUri(URI.create("https://example.com"));

Mockito.when(execution.execute(Mockito.any()))
.thenReturn(CompletableFuture.completedFuture(null));

final OpenTelemetryPlugin plugin = new OpenTelemetryPlugin(
otelTesting.getOpenTelemetry(), new FlowIdSpanDecorator());
final Baggage baggage = Baggage.builder()
.put(ExtensionAttributes.FLOW_ID.getKey(), "flow-id-value")
.build();

try (final Scope ignored = baggage.storeInContext(Context.current()).makeCurrent()) {
plugin.aroundAsync(execution).execute(arguments).join();
}

final ArgumentCaptor<RequestArguments> forwardedArguments =
ArgumentCaptor.forClass(RequestArguments.class);
Mockito.verify(execution).execute(forwardedArguments.capture());

assertThat(forwardedArguments.getValue().getHeaders().get(FlowIdSpanDecorator.FLOW_ID_HEADER),
is(List.of("flow-id-value")));
assertThat(otelTesting.getSpans().get(0).getAttributes()
.get(ExtensionAttributes.FLOW_ID), is("flow-id-value"));
}

@Test
void shouldUseTraceIdForFlowIdHeaderWhenFlowIdIsAbsent() throws IOException {
final RequestExecution execution = Mockito.mock(RequestExecution.class);
final RequestArguments arguments = RequestArguments.create()
.withMethod(HttpMethod.GET)
.withUri(URI.create("https://example.com"));

Mockito.when(execution.execute(Mockito.any()))
.thenReturn(CompletableFuture.completedFuture(null));

final OpenTelemetryPlugin plugin = new OpenTelemetryPlugin(
otelTesting.getOpenTelemetry(), new FlowIdSpanDecorator());

plugin.aroundAsync(execution).execute(arguments).join();

final ArgumentCaptor<RequestArguments> forwardedArguments =
ArgumentCaptor.forClass(RequestArguments.class);
Mockito.verify(execution).execute(forwardedArguments.capture());

assertThat(otelTesting.getSpans(), hasSize(1));
assertThat(forwardedArguments.getValue().getHeaders().get(FlowIdSpanDecorator.FLOW_ID_HEADER),
is(List.of(otelTesting.getSpans().get(0).getTraceId())));
}

@Test
void shouldOverwriteDefaultSetOfDecorators() {
final Http unit = Http.builder()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package org.zalando.riptide.opentelemetry.span;

import io.opentelemetry.api.trace.Span;
import org.junit.jupiter.api.Test;
import org.springframework.http.HttpMethod;
import org.zalando.riptide.RequestArguments;

import java.net.URI;
import java.util.List;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.mockito.Mockito.mock;

class CompositeSpanDecoratorTest {

@Test
void shouldPassDecoratedRequestToFollowingDecorator() {
final RequestArguments arguments = RequestArguments.create()
.withMethod(HttpMethod.GET)
.withUri(URI.create("https://example.com"));
final Span span = mock(Span.class);

final SpanDecorator firstDecorator = new SpanDecorator() {
@Override
public RequestArguments decorateRequest(final Span ignored, final RequestArguments requestArguments) {
return requestArguments.withHeader("X-First", "first-value");
}
};
final SpanDecorator secondDecorator = new SpanDecorator() {
@Override
public RequestArguments decorateRequest(final Span ignored, final RequestArguments requestArguments) {
assertThat(requestArguments.getHeaders().get("X-First"), is(List.of("first-value")));
return requestArguments.withHeader("X-Second", "second-value");
}
};

final RequestArguments decoratedArguments =
CompositeSpanDecorator.composite(firstDecorator, secondDecorator).decorateRequest(span, arguments);

assertThat(decoratedArguments.getHeaders().get("X-First"), is(List.of("first-value")));
assertThat(decoratedArguments.getHeaders().get("X-Second"), is(List.of("second-value")));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,72 +2,120 @@

import io.opentelemetry.api.baggage.Baggage;
import io.opentelemetry.api.trace.Span;
import io.opentelemetry.api.trace.SpanContext;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.MockedStatic;
import org.zalando.riptide.RequestArguments;

import java.util.List;
import java.util.Map;
import java.util.UUID;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.notNullValue;
import static org.mockito.Mockito.*;

class FlowIdSpanDecoratorTest {

private static final String FLOW_ID = "flow-id-value";
private static final String TRACE_ID = "trace-id-value";
private static final String FLOW_ID_HEADER = "X-Flow-ID";

private Span span;
private SpanContext spanContext;
private RequestArguments arguments;

@BeforeEach
void setUp() {
span = mock(Span.class);
arguments = mock(RequestArguments.class);

spanContext = mock(SpanContext.class);
when(span.getSpanContext()).thenReturn(spanContext);
when(spanContext.isValid()).thenReturn(true);
when(spanContext.getTraceId()).thenReturn(TRACE_ID);
}

@Test
void shouldSetFlowIdAttributeAndPropagateHeaderWhenEnabled() {
final FlowIdSpanDecorator decorator = new FlowIdSpanDecorator(true);
final Baggage baggage = mock(Baggage.class);
when(baggage.getEntryValue(ExtensionAttributes.FLOW_ID.getKey())).thenReturn(FLOW_ID);
void shouldUseBaggageFlowIdForHeaderWhenAvailable() {
final FlowIdSpanDecorator decorator = new FlowIdSpanDecorator();

try (MockedStatic<Baggage> mockedBaggage = mockStatic(Baggage.class)) {
mockedBaggage.when(Baggage::current).thenReturn(baggage);
withBaggage(FLOW_ID, () -> decorator.decorateRequest(span, arguments));

decorator.onRequest(span, arguments);
verify(arguments).withHeader(FLOW_ID_HEADER, FLOW_ID);
}

verify(span).setAttribute(ExtensionAttributes.FLOW_ID, FLOW_ID);
verify(arguments).withHeader(FLOW_ID_HEADER, FLOW_ID);
}
@Test
void shouldUseBaggageFlowIdForHeaderWhenSpanContextIsInvalid() {
final FlowIdSpanDecorator decorator = new FlowIdSpanDecorator();
when(spanContext.isValid()).thenReturn(false);

withBaggage(FLOW_ID, () -> decorator.decorateRequest(span, arguments));

verify(arguments).withHeader(FLOW_ID_HEADER, FLOW_ID);
verify(spanContext, never()).getTraceId();
}

@Test
void shouldSetFlowIdAttributeWithoutPropagatingHeaderWhenDisabled() {
final FlowIdSpanDecorator decorator = new FlowIdSpanDecorator(false);
final Baggage baggage = mock(Baggage.class);
when(baggage.getEntryValue(ExtensionAttributes.FLOW_ID.getKey())).thenReturn(FLOW_ID);
void shouldUseTraceIdForHeaderWhenBaggageFlowIdIsAbsentAndSpanContextIsValid() {
final FlowIdSpanDecorator decorator = new FlowIdSpanDecorator();

try (MockedStatic<Baggage> mockedBaggage = mockStatic(Baggage.class)) {
mockedBaggage.when(Baggage::current).thenReturn(baggage);
withBaggage(null, () -> decorator.decorateRequest(span, arguments));

decorator.onRequest(span, arguments);
verify(arguments).withHeader(FLOW_ID_HEADER, TRACE_ID);
}

verify(span).setAttribute(ExtensionAttributes.FLOW_ID, FLOW_ID);
verify(arguments, never()).withHeader(FLOW_ID_HEADER, FLOW_ID);
}
@Test
void shouldUseRandomFlowIdForHeaderWhenBaggageFlowIdIsAbsentAndSpanContextIsInvalid() {
final FlowIdSpanDecorator decorator = new FlowIdSpanDecorator();
when(span.getSpanContext().isValid()).thenReturn(false);

withBaggage(null, () -> decorator.decorateRequest(span, arguments));

final org.mockito.ArgumentCaptor<String> flowId = org.mockito.ArgumentCaptor.forClass(String.class);
verify(arguments).withHeader(eq(FLOW_ID_HEADER), flowId.capture());
assertThat(UUID.fromString(flowId.getValue()), notNullValue());
}

@Test
void shouldSetFlowIdAttributeFromRequestHeader() {
final FlowIdSpanDecorator decorator = new FlowIdSpanDecorator();
when(arguments.getHeaders()).thenReturn(Map.of(FLOW_ID_HEADER, List.of("previous-flow-id", FLOW_ID)));

decorator.onRequest(span, arguments);

verify(span).setAttribute(ExtensionAttributes.FLOW_ID, FLOW_ID);
}

@Test
void shouldDoNothingWhenFlowIdIsAbsent() {
final FlowIdSpanDecorator decorator = new FlowIdSpanDecorator(true);
void shouldSetSameRandomFlowIdOnSpanAsInRequestHeader() {
final FlowIdSpanDecorator decorator = new FlowIdSpanDecorator();
final RequestArguments originalArguments = RequestArguments.create();
when(spanContext.isValid()).thenReturn(false);

final Baggage baggage = mock(Baggage.class);
when(baggage.getEntryValue(ExtensionAttributes.FLOW_ID.getKey())).thenReturn(null);

try (MockedStatic<Baggage> mockedBaggage = mockStatic(Baggage.class)) {
mockedBaggage.when(Baggage::current).thenReturn(baggage);

decorator.onRequest(span, arguments);
final RequestArguments decoratedArguments = decorator.decorateRequest(span, originalArguments);
final String flowId = decoratedArguments.getHeaders().get(FLOW_ID_HEADER).get(0);
decorator.onRequest(span, decoratedArguments);

verify(span, never()).setAttribute(anyString(), anyString());
verify(arguments, never()).withHeader(anyString(), anyString());
assertThat(UUID.fromString(flowId), notNullValue());
verify(span).setAttribute(ExtensionAttributes.FLOW_ID, flowId);
}
}

private static void withBaggage(final String flowId, final Runnable action) {
final Baggage baggage = mock(Baggage.class);
when(baggage.getEntryValue(ExtensionAttributes.FLOW_ID.getKey())).thenReturn(flowId);

try (MockedStatic<Baggage> mockedBaggage = mockStatic(Baggage.class)) {
mockedBaggage.when(Baggage::current).thenReturn(baggage);
action.run();
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -344,8 +344,7 @@ private static <K, V> Map<K, V> merge(final Map<K, V> base, final Map<K, V> defa
private static Telemetry merge(final Telemetry base, final Telemetry defaults) {
return new Telemetry(
either(base.getEnabled(), defaults.getEnabled()),
merge(base.getAttributes(), defaults.getAttributes(), Defaulting::merge),
either(base.getPropagateFlowId(), defaults.getPropagateFlowId())
merge(base.getAttributes(), defaults.getAttributes(), Defaulting::merge)
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public static Plugin create(final RiptideProperties.Client client) {
if (client.getRetry().getEnabled()) {
decorators.add(new RetrySpanDecorator());
}
decorators.add(new FlowIdSpanDecorator(clientTelemetryConfig.getPropagateFlowId()));
decorators.add(new FlowIdSpanDecorator());
return new OpenTelemetryPlugin(decorators.toArray(new SpanDecorator[0]));
}
}
Loading
Loading