package io.vertx.kafka.client.common.tracing;
import io.vertx.core.Context;
import io.vertx.core.spi.tracing.SpanKind;
import io.vertx.core.spi.tracing.TagExtractor;
import io.vertx.core.spi.tracing.VertxTracer;
import io.vertx.core.tracing.TracingPolicy;
import io.vertx.kafka.client.common.KafkaClientOptions;
import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.common.header.Headers;
import org.apache.kafka.common.utils.Utils;
import java.util.AbstractMap;
import java.util.Collections;
import java.util.Map;
import java.util.stream.StreamSupport;
public class ConsumerTracer<S> {
private final VertxTracer<S, Void> tracer;
private final String address;
private final String hostname;
private final String port;
private final TracingPolicy policy;
public static <S> ConsumerTracer create(VertxTracer tracer, KafkaClientOptions opts) {
TracingPolicy policy = opts.getTracingPolicy() != null ? opts.getTracingPolicy() : TracingPolicy.ALWAYS;
if (policy == TracingPolicy.IGNORE || tracer == null) {
return null;
}
String address = opts.getTracePeerAddress();
if (address == null) {
if (opts.getConfig() != null) {
address = (String) opts.getConfig().getOrDefault(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "");
} else {
address = "";
}
}
return new ConsumerTracer<S>(tracer, policy, address);
}
private ConsumerTracer(VertxTracer<S, Void> tracer, TracingPolicy policy, String bootstrapServer) {
this.tracer = tracer;
this.address = bootstrapServer;
this.hostname = Utils.getHost(bootstrapServer);
Integer port = Utils.getPort(bootstrapServer);
this.port = port == null ? null : port.toString();
this.policy = policy;
}
private static Iterable<Map.Entry<String, String>> (Headers headers) {
if (headers == null) {
return Collections.emptyList();
}
return () -> StreamSupport.stream(headers.spliterator(), false)
.map(h -> (Map.Entry<String, String>) new AbstractMap.SimpleEntry<>(h.key(), new String(h.value()))).iterator();
}
public StartedSpan prepareMessageReceived(Context context, ConsumerRecord rec) {
TraceContext tc = new TraceContext("consumer", address, hostname, port, rec.topic());
S span = tracer.receiveRequest(context, SpanKind.MESSAGING, policy, tc, "kafka_receive", convertHeaders(rec.headers()), TraceTags.TAG_EXTRACTOR);
return new StartedSpan(span);
}
public class StartedSpan {
private final S span;
private StartedSpan(S span) {
this.span = span;
}
public void finish(Context context) {
tracer.sendResponse(context, null, span, null, TagExtractor.empty());
}
public void fail(Context context, Throwable failure) {
tracer.sendResponse(context, null, span, failure, TagExtractor.empty());
}
}
}