Skip to content

Commit

Permalink
Parse manually, don't use Moshi
Browse files Browse the repository at this point in the history
  • Loading branch information
nhulston committed Sep 17, 2024
1 parent c351a45 commit 89df39f
Show file tree
Hide file tree
Showing 6 changed files with 76 additions and 82 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,12 @@
import static datadog.trace.core.datastreams.TagsProcessor.TYPE_TAG;
import static datadog.trace.instrumentation.aws.v2.eventbridge.TextMapInjectAdapter.SETTER;

import datadog.trace.api.JsonAdapter;
import datadog.trace.api.TracePropagationStyle;
import datadog.trace.bootstrap.InstanceStore;
import datadog.trace.bootstrap.instrumentation.api.AgentSpan;
import datadog.trace.bootstrap.instrumentation.api.AgentTracer;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.core.SdkRequest;
Expand All @@ -28,7 +25,6 @@
import software.amazon.awssdk.services.eventbridge.model.PutEventsRequestEntry;

public class EventBridgeInterceptor implements ExecutionInterceptor {
private final JsonAdapter jsonAdapter;
private static final Logger log = LoggerFactory.getLogger(EventBridgeInterceptor.class);

public static final ExecutionAttribute<AgentSpan> SPAN_ATTRIBUTE =
Expand All @@ -39,10 +35,6 @@ public class EventBridgeInterceptor implements ExecutionInterceptor {
private static final String BUS_NAME_KEY = "BusName";
private static final String DATADOG_KEY = "_datadog";

public EventBridgeInterceptor() {
this.jsonAdapter = AgentTracer.get().getJsonAdapter();
}

@Override
public SdkRequest modifyRequest(
Context.ModifyRequest context, ExecutionAttributes executionAttributes) {
Expand All @@ -58,22 +50,44 @@ public SdkRequest modifyRequest(
String eventBusName = entry.eventBusName();
String traceContext = getTraceContextToInject(executionAttributes, eventBusName);

try {
Map<String, Object> detailMap = jsonAdapter.fromJson(entry.detail());

// Add new fields and trace context
detailMap.put(SENT_TIMESTAMP_KEY, String.valueOf(startTime));
detailMap.put(BUS_NAME_KEY, eventBusName);
detailMap.put(DATADOG_KEY, jsonAdapter.fromJson(traceContext));

// Modify entry
String modifiedDetail = jsonAdapter.toJson(detailMap);
PutEventsRequestEntry modifiedEntry = entry.toBuilder().detail(modifiedDetail).build();
modifiedEntries.add(modifiedEntry);
} catch (Exception e) {
log.warn("Failed to process detail JSON for entry: {}. Using original entry.", entry, e);
StringBuilder detailBuilder = new StringBuilder(entry.detail().trim());
if (detailBuilder.length() == 0) {
detailBuilder.append("{}");
}
if (detailBuilder.charAt(detailBuilder.length() - 1) != '}') {
log.debug(
"Unable to parse detail JSON. Not injecting trace context into EventBridge payload.");
modifiedEntries.add(entry); // Add the original entry without modification
continue;
}

detailBuilder.setLength(detailBuilder.length() - 1); // Remove the last bracket
if (detailBuilder.length() > 1) {
detailBuilder.append(", "); // Only add a comma if detail is not empty.
}

detailBuilder
.append("\"")
.append(SENT_TIMESTAMP_KEY)
.append("\": \"")
.append(startTime)
.append("\"");
detailBuilder
.append(", \"")
.append(BUS_NAME_KEY)
.append("\": \"")
.append(eventBusName)
.append("\"");
detailBuilder
.append(", \"")
.append(DATADOG_KEY)
.append("\": ")
.append(traceContext)
.append("}");

String modifiedDetail = detailBuilder.toString();
PutEventsRequestEntry modifiedEntry = entry.toBuilder().detail(modifiedDetail).build();
modifiedEntries.add(modifiedEntry);
}

return request.toBuilder().entries(modifiedEntries).build();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -313,4 +313,44 @@ class EventBridgeClientTest extends AgentTestRunner {
cleanup:
injectSysConfig(GeneralConfig.DATA_STREAMS_ENABLED, "true")
}

def "test behavior with empty detail fields"() {
setup:
sqsClient.purgeQueue { it.queueUrl(testQueueURL) }

when:
TEST_WRITER.clear()
eventBridgeClient.putEvents { req ->
req.entries(
PutEventsRequestEntry.builder()
.source("com.example")
.detailType("test-empty")
.detail('{}')
.eventBusName(testBusARN)
.build(),
)
}

def messages = sqsClient.receiveMessage { it.queueUrl(testQueueURL).maxNumberOfMessages(2).waitTimeSeconds(5) }.messages()

then:
assertTraces(1) {
trace(1) {
span {
serviceName "java-aws-sdk"
operationName "aws.http"
resourceName "EventBridge.PutEvents"
spanType DDSpanTypes.HTTP_CLIENT
}
}
}
assert messages.size() == 1

def message = messages[0]
assert message != null
def emptyDetailBody = new JsonSlurper().parseText(message.body())
assert emptyDetailBody["detail"]["_datadog"] != null // Datadog context should be injected
assert emptyDetailBody["detail"]["_datadog"]["x-datadog-trace-id"] != null
assert emptyDetailBody["detail"]["_datadog"]["x-datadog-parent-id"] != null
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
import datadog.trace.api.EndpointTracker;
import datadog.trace.api.IdGenerationStrategy;
import datadog.trace.api.InstrumenterConfig;
import datadog.trace.api.JsonAdapter;
import datadog.trace.api.StatsDClient;
import datadog.trace.api.TraceConfig;
import datadog.trace.api.TracePropagationStyle;
Expand Down Expand Up @@ -90,7 +89,6 @@
import datadog.trace.core.taginterceptor.RuleFlags;
import datadog.trace.core.taginterceptor.TagInterceptor;
import datadog.trace.lambda.LambdaHandler;
import datadog.trace.lambda.MoshiJsonAdapter;
import datadog.trace.relocate.api.RatelimitedLogger;
import datadog.trace.util.AgentTaskScheduler;
import java.io.IOException;
Expand Down Expand Up @@ -238,11 +236,6 @@ public void updatePreferredServiceName(String serviceName) {
ServiceNameCollector.get().addService(serviceName);
}

@Override
public JsonAdapter getJsonAdapter() {
return new MoshiJsonAdapter();
}

PropagationTags.Factory getPropagationTagsFactory() {
return propagationTagsFactory;
}
Expand Down

This file was deleted.

10 changes: 0 additions & 10 deletions internal-api/src/main/java/datadog/trace/api/JsonAdapter.java

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import datadog.trace.api.DDTraceId;
import datadog.trace.api.EndpointCheckpointer;
import datadog.trace.api.EndpointTracker;
import datadog.trace.api.JsonAdapter;
import datadog.trace.api.TraceConfig;
import datadog.trace.api.TracePropagationStyle;
import datadog.trace.api.experimental.DataStreamsCheckpointer;
Expand Down Expand Up @@ -292,8 +291,6 @@ default SpanBuilder buildSpan(CharSequence spanName) {
* @param serviceName
*/
void updatePreferredServiceName(String serviceName);

JsonAdapter getJsonAdapter();
}

public interface SpanBuilder {
Expand Down Expand Up @@ -528,11 +525,6 @@ public AgentHistogram newHistogram(double relativeAccuracy, int maxNumBins) {
public void updatePreferredServiceName(String serviceName) {
// no ops
}

@Override
public JsonAdapter getJsonAdapter() {
return null;
}
}

public static final class BlackholeAgentSpan extends NoopAgentSpan {
Expand Down

0 comments on commit 89df39f

Please sign in to comment.