-
-
Notifications
You must be signed in to change notification settings - Fork 468
Expand file tree
/
Copy pathSentryKafkaProducer.java
More file actions
264 lines (239 loc) · 9.62 KB
/
SentryKafkaProducer.java
File metadata and controls
264 lines (239 loc) · 9.62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
package io.sentry.kafka;
import io.sentry.BaggageHeader;
import io.sentry.DateUtils;
import io.sentry.IScopes;
import io.sentry.ISpan;
import io.sentry.ScopesAdapter;
import io.sentry.SentryLevel;
import io.sentry.SentryTraceHeader;
import io.sentry.SpanDataConvention;
import io.sentry.SpanOptions;
import io.sentry.SpanStatus;
import io.sentry.util.SpanUtils;
import io.sentry.util.TracingUtils;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import org.apache.kafka.clients.producer.Callback;
import org.apache.kafka.clients.producer.Producer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.apache.kafka.common.header.Header;
import org.apache.kafka.common.header.Headers;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
/**
* Wraps a Kafka {@link Producer} via {@link Proxy} to record a {@code queue.publish} span around
* each {@code send} and to inject Sentry trace propagation headers into the produced record.
*
* <p>Only the two {@code send} overloads are intercepted; every other {@link Producer} method is
* forwarded directly to the delegate. Because the wrapper is a dynamic proxy, it is compatible with
* any Kafka client version — new methods added to the {@link Producer} interface in future Kafka
* releases are forwarded automatically without recompilation.
*
* <p>For raw Kafka usage:
*
* <pre>{@code
* Producer<String, String> producer =
* SentryKafkaProducer.wrap(new KafkaProducer<>(props));
* }</pre>
*
* <p>For Spring Kafka, the {@code SentryKafkaProducerBeanPostProcessor} in {@code
* sentry-spring-jakarta} installs this wrapper automatically via {@code
* ProducerFactory.addPostProcessor(...)}.
*/
@ApiStatus.Experimental
public final class SentryKafkaProducer {
public static final @NotNull String TRACE_ORIGIN = "auto.queue.kafka.producer";
public static final @NotNull String SENTRY_ENQUEUED_TIME_HEADER = "sentry-task-enqueued-time";
private SentryKafkaProducer() {}
/**
* Wraps the given producer with Sentry instrumentation using the global scopes.
*
* @param delegate the Kafka producer to wrap
* @return an instrumented producer that records {@code queue.publish} spans
* @param <K> the Kafka record key type
* @param <V> the Kafka record value type
*/
public static <K, V> @NotNull Producer<K, V> wrap(final @NotNull Producer<K, V> delegate) {
return wrap(delegate, ScopesAdapter.getInstance(), TRACE_ORIGIN);
}
/**
* Wraps the given producer with Sentry instrumentation using the provided scopes.
*
* @param delegate the Kafka producer to wrap
* @param scopes the Sentry scopes to use for span creation and header injection
* @return an instrumented producer that records {@code queue.publish} spans
* @param <K> the Kafka record key type
* @param <V> the Kafka record value type
*/
public static <K, V> @NotNull Producer<K, V> wrap(
final @NotNull Producer<K, V> delegate, final @NotNull IScopes scopes) {
return wrap(delegate, scopes, TRACE_ORIGIN);
}
/**
* Wraps the given producer with Sentry instrumentation.
*
* @param delegate the Kafka producer to wrap
* @param scopes the Sentry scopes to use for span creation and header injection
* @param traceOrigin the trace origin to set on created spans
* @return an instrumented producer that records {@code queue.publish} spans
* @param <K> the Kafka record key type
* @param <V> the Kafka record value type
*/
@SuppressWarnings("unchecked")
public static <K, V> @NotNull Producer<K, V> wrap(
final @NotNull Producer<K, V> delegate,
final @NotNull IScopes scopes,
final @NotNull String traceOrigin) {
return (Producer<K, V>)
Proxy.newProxyInstance(
delegate.getClass().getClassLoader(),
new Class<?>[] {Producer.class},
new SentryProducerHandler<>(delegate, scopes, traceOrigin));
}
static final class SentryProducerHandler<K, V> implements InvocationHandler {
final @NotNull Producer<K, V> delegate;
private final @NotNull IScopes scopes;
private final @NotNull String traceOrigin;
SentryProducerHandler(
final @NotNull Producer<K, V> delegate,
final @NotNull IScopes scopes,
final @NotNull String traceOrigin) {
this.delegate = delegate;
this.scopes = scopes;
this.traceOrigin = traceOrigin;
}
@Override
@SuppressWarnings("unchecked")
public @Nullable Object invoke(
final @NotNull Object proxy, final @NotNull Method method, final @Nullable Object[] args)
throws Throwable {
if ("send".equals(method.getName()) && args != null) {
if (args.length == 1) {
return instrumentedSend((ProducerRecord<K, V>) args[0], null);
} else if (args.length == 2) {
return instrumentedSend((ProducerRecord<K, V>) args[0], (Callback) args[1]);
}
}
if ("toString".equals(method.getName()) && (args == null || args.length == 0)) {
return "SentryKafkaProducer[delegate=" + delegate + "]";
}
try {
return method.invoke(delegate, args);
} catch (InvocationTargetException e) {
throw e.getCause();
}
}
@SuppressWarnings("unchecked")
private @NotNull Object instrumentedSend(
final @NotNull ProducerRecord<K, V> record, final @Nullable Callback callback) {
if (!scopes.getOptions().isEnableQueueTracing() || isIgnored()) {
return delegate.send(record, callback);
}
final @Nullable ISpan activeSpan = scopes.getSpan();
if (activeSpan == null || activeSpan.isNoOp()) {
maybeInjectHeaders(record.headers(), null);
return delegate.send(record, callback);
}
final @NotNull SpanOptions spanOptions = new SpanOptions();
spanOptions.setOrigin(traceOrigin);
final @NotNull ISpan span =
activeSpan.startChild("queue.publish", record.topic(), spanOptions);
span.setData(SpanDataConvention.MESSAGING_SYSTEM, "kafka");
span.setData(SpanDataConvention.MESSAGING_DESTINATION_NAME, record.topic());
maybeInjectHeaders(record.headers(), span);
try {
return delegate.send(record, wrapCallback(callback, span));
} catch (Throwable t) {
finishWithError(span, t);
throw t;
}
}
private @NotNull Callback wrapCallback(
final @Nullable Callback userCallback, final @NotNull ISpan span) {
return (metadata, exception) -> {
try {
if (exception != null) {
span.setThrowable(exception);
span.setStatus(SpanStatus.INTERNAL_ERROR);
} else {
span.setStatus(SpanStatus.OK);
}
} catch (Throwable t) {
scopes
.getOptions()
.getLogger()
.log(SentryLevel.ERROR, "Failed to set status on Kafka producer span.", t);
} finally {
try {
span.finish();
} finally {
if (userCallback != null) {
userCallback.onCompletion(metadata, exception);
}
}
}
};
}
private void finishWithError(final @NotNull ISpan span, final @NotNull Throwable t) {
span.setThrowable(t);
span.setStatus(SpanStatus.INTERNAL_ERROR);
span.finish();
}
private boolean isIgnored() {
return SpanUtils.isIgnored(scopes.getOptions().getIgnoredSpanOrigins(), traceOrigin);
}
private void maybeInjectHeaders(final @NotNull Headers headers, final @Nullable ISpan span) {
try {
final @Nullable List<String> existingBaggageHeaders =
readHeaderValues(headers, BaggageHeader.BAGGAGE_HEADER);
final @Nullable TracingUtils.TracingHeaders tracingHeaders =
TracingUtils.trace(scopes, existingBaggageHeaders, span);
if (tracingHeaders != null) {
final @NotNull SentryTraceHeader sentryTraceHeader =
tracingHeaders.getSentryTraceHeader();
headers.remove(sentryTraceHeader.getName());
headers.add(
sentryTraceHeader.getName(),
sentryTraceHeader.getValue().getBytes(StandardCharsets.UTF_8));
final @Nullable BaggageHeader baggageHeader = tracingHeaders.getBaggageHeader();
if (baggageHeader != null) {
headers.remove(baggageHeader.getName());
headers.add(
baggageHeader.getName(), baggageHeader.getValue().getBytes(StandardCharsets.UTF_8));
}
}
headers.remove(SENTRY_ENQUEUED_TIME_HEADER);
headers.add(
SENTRY_ENQUEUED_TIME_HEADER,
DateUtils.doubleToBigDecimal(DateUtils.millisToSeconds(System.currentTimeMillis()))
.toString()
.getBytes(StandardCharsets.UTF_8));
} catch (Throwable t) {
scopes
.getOptions()
.getLogger()
.log(SentryLevel.ERROR, "Failed to inject Sentry headers into Kafka record.", t);
}
}
private static @Nullable List<String> readHeaderValues(
final @NotNull Headers headers, final @NotNull String name) {
@Nullable List<String> values = null;
for (final @NotNull Header header : headers.headers(name)) {
final byte @Nullable [] value = header.value();
if (value != null) {
if (values == null) {
values = new ArrayList<>();
}
values.add(new String(value, StandardCharsets.UTF_8));
}
}
return values;
}
}
}