+ * It is registered like any other recorder: + *
{@code
+ * Client client = new Client.Builder()
+ * .addEndpoint("http://localhost:8123")
+ * .setSpanRecorder(new OpenTelemetrySpanRecorder(openTelemetry))
+ * .build();
+ * }
+ * Every span is a {@link SpanKind#CLIENT} span and carries the client's standard name and
+ * attributes, which are derived by {@link SpanSupport} - so the recorded keys are the ones listed in
+ * {@link SpanAttribute} and mean the same as for every other recorder.
+ * + * An operation span is started as a child of the {@linkplain Context#current() current context}, so + * it appears under the application's own span when the operation is started on a thread that has + * one. A request span is a child of the operation span it was started for. The recorder does not + * make any span current: the client hands the response to the caller before the response body is + * read, so a span is ended on a thread the recorder does not control. + *
+ * Instances are thread-safe and can be shared by several clients. + */ +public class OpenTelemetrySpanRecorder implements SpanRecorder { + + /** + * Default instrumentation scope name. It is reported for the spans of a recorder created by the + * no-argument constructor or by {@link #OpenTelemetrySpanRecorder(OpenTelemetry)}. A recorder + * created by {@link #OpenTelemetrySpanRecorder(Tracer)} reports the scope of the given tracer + * instead. + */ + public static final String INSTRUMENTATION_SCOPE_NAME = "com.clickhouse.client"; + + private final SpanSupport spanSupport = SpanSupport.DEFAULT; + + /** + * Tracer the spans are created with, or {@code null} when they are created with the tracer of the + * global OpenTelemetry instance, which is then read every time a span is started. + */ + private final Tracer tracer; + + /** + * Creates a recorder that reports to the {@linkplain GlobalOpenTelemetry#get() global} + * OpenTelemetry instance. Use it when the application configures OpenTelemetry globally, for + * example through the OpenTelemetry Java agent or the autoconfigure SDK extension. + *
+ * The global instance is read when a span is started, not here, so a client may be created before
+ * the application installs its OpenTelemetry SDK.
+ */
+ public OpenTelemetrySpanRecorder() {
+ this.tracer = null;
+ }
+
+ /**
+ * Creates a recorder that reports to the given OpenTelemetry instance.
+ *
+ * @param openTelemetry - OpenTelemetry instance to report to; must not be {@code null}
+ */
+ public OpenTelemetrySpanRecorder(OpenTelemetry openTelemetry) {
+ this(tracerOf(openTelemetry));
+ }
+
+ /**
+ * Creates a recorder that reports to the given tracer. Use it to report the client's spans under
+ * an instrumentation scope of the application's choice.
+ *
+ * @param tracer - tracer to create spans with; must not be {@code null}
+ */
+ public OpenTelemetrySpanRecorder(Tracer tracer) {
+ if (tracer == null) {
+ throw new IllegalArgumentException("tracer must not be null");
+ }
+ this.tracer = tracer;
+ }
+
+ private static Tracer tracerOf(OpenTelemetry openTelemetry) {
+ if (openTelemetry == null) {
+ throw new IllegalArgumentException("openTelemetry must not be null");
+ }
+ return openTelemetry.getTracer(INSTRUMENTATION_SCOPE_NAME);
+ }
+
+ /**
+ * Returns the tracer the next span is created with - the one given to this recorder, or the tracer
+ * of the global OpenTelemetry instance as it is installed now.
+ *
+ * @return tracer; never {@code null}
+ */
+ protected Tracer getTracer() {
+ return tracer != null ? tracer : GlobalOpenTelemetry.get().getTracer(INSTRUMENTATION_SCOPE_NAME);
+ }
+
+ @Override
+ public Span startQuerySpan(QuerySettings settings, String sqlQuery, Endpoint endpoint) {
+ OpenTelemetrySpan span = startSpan(spanSupport.querySpanName(settings), Context.current());
+ spanSupport.fillQueryAttributes(span, settings, sqlQuery, endpoint);
+ return span;
+ }
+
+ @Override
+ public Span startInsertSpan(InsertSettings settings, String tableName, int batchSize, Endpoint endpoint) {
+ OpenTelemetrySpan span = startSpan(spanSupport.insertSpanName(settings, tableName), Context.current());
+ spanSupport.fillInsertAttributes(span, settings, tableName, batchSize, endpoint);
+ return span;
+ }
+
+ @Override
+ public Span startRequestSpan(Span operationSpan, String host, int port) {
+ OpenTelemetrySpan span = startSpan(spanSupport.requestSpanName(), parentContextOf(operationSpan));
+ spanSupport.fillRequestAttributes(span, host, port);
+ return span;
+ }
+
+ @Override
+ public void recordHttpStatus(Span requestSpan, int statusCode) {
+ spanSupport.recordHttpStatus(requestSpan, statusCode);
+ }
+
+ @Override
+ public void recordSuccess(Span operationSpan, OperationMetrics metrics) {
+ spanSupport.recordSuccess(operationSpan, metrics);
+ }
+
+ @Override
+ public void recordFailure(Span operationSpan, Throwable t) {
+ spanSupport.recordFailure(operationSpan, t);
+ recordException(operationSpan, t);
+ }
+
+ @Override
+ public void recordRequestFailure(Span requestSpan, Throwable t) {
+ spanSupport.recordRequestFailure(requestSpan, t);
+ recordException(requestSpan, t);
+ }
+
+ /**
+ * Records the failure itself as an OpenTelemetry exception event, so that its message and stack
+ * trace are reported next to the {@link SpanAttribute#ERROR_TYPE} attribute.
+ *
+ * @param span - span the failure was reported on
+ * @param t - failure, may be {@code null}
+ */
+ protected void recordException(Span span, Throwable t) {
+ if (t != null && span instanceof OpenTelemetrySpan) {
+ ((OpenTelemetrySpan) span).getSpan().recordException(t);
+ }
+ }
+
+ /**
+ * Starts a client span with the given name under the given parent context.
+ *
+ * @param spanName - name of the span
+ * @param parentContext - context the span is started under
+ * @return new span
+ */
+ protected OpenTelemetrySpan startSpan(String spanName, Context parentContext) {
+ io.opentelemetry.api.trace.Span span = getTracer().spanBuilder(spanName)
+ .setSpanKind(SpanKind.CLIENT)
+ .setParent(parentContext)
+ .startSpan();
+ return new OpenTelemetrySpan(span, parentContext.with(span));
+ }
+
+ /**
+ * Returns the context a request span is started under - the context of its operation span, or the
+ * current context when the operation span was not created by this recorder.
+ */
+ private static Context parentContextOf(Span operationSpan) {
+ return operationSpan instanceof OpenTelemetrySpan
+ ? ((OpenTelemetrySpan) operationSpan).getContext()
+ : Context.current();
+ }
+
+ /**
+ * {@link Span} backed by an OpenTelemetry span.
+ */
+ public static class OpenTelemetrySpan implements Span {
+
+ private final io.opentelemetry.api.trace.Span span;
+
+ private final Context context;
+
+ private final AtomicBoolean ended = new AtomicBoolean();
+
+ OpenTelemetrySpan(io.opentelemetry.api.trace.Span span, Context context) {
+ this.span = span;
+ this.context = context;
+ }
+
+ /**
+ * Returns the OpenTelemetry span this span records on.
+ *
+ * @return OpenTelemetry span
+ */
+ public io.opentelemetry.api.trace.Span getSpan() {
+ return span;
+ }
+
+ /**
+ * Returns the context that holds this span. It is the parent context of the spans started for
+ * the same operation.
+ *
+ * @return context holding this span
+ */
+ public Context getContext() {
+ return context;
+ }
+
+ @Override
+ public void setAttribute(String key, Object value) {
+ if (key == null || value == null) {
+ return;
+ }
+ if (value instanceof String) {
+ span.setAttribute(AttributeKey.stringKey(key), (String) value);
+ } else if (value instanceof Boolean) {
+ span.setAttribute(AttributeKey.booleanKey(key), (Boolean) value);
+ } else if (value instanceof Double || value instanceof Float) {
+ span.setAttribute(AttributeKey.doubleKey(key), ((Number) value).doubleValue());
+ } else if (value instanceof Number) {
+ span.setAttribute(AttributeKey.longKey(key), ((Number) value).longValue());
+ } else {
+ span.setAttribute(AttributeKey.stringKey(key), String.valueOf(value));
+ }
+ }
+
+ @Override
+ public void setError(String errorType) {
+ span.setStatus(StatusCode.ERROR);
+ if (errorType != null) {
+ span.setAttribute(AttributeKey.stringKey(SpanAttribute.ERROR_TYPE.getKey()), errorType);
+ }
+ }
+
+ @Override
+ public void end() {
+ if (ended.compareAndSet(false, true)) {
+ span.end();
+ }
+ }
+
+ @Override
+ public String toString() {
+ return "OpenTelemetrySpan[" + span.getSpanContext().getSpanId() + "]";
+ }
+ }
+}
diff --git a/client-v2/src/test/java/com/clickhouse/client/api/observability/otel/OpenTelemetrySpanRecorderUnitTest.java b/client-v2/src/test/java/com/clickhouse/client/api/observability/otel/OpenTelemetrySpanRecorderUnitTest.java
new file mode 100644
index 000000000..fbad6152b
--- /dev/null
+++ b/client-v2/src/test/java/com/clickhouse/client/api/observability/otel/OpenTelemetrySpanRecorderUnitTest.java
@@ -0,0 +1,430 @@
+package com.clickhouse.client.api.observability.otel;
+
+import com.clickhouse.client.api.ServerException;
+import com.clickhouse.client.api.insert.InsertSettings;
+import com.clickhouse.client.api.internal.ClientStatisticsHolder;
+import com.clickhouse.client.api.metrics.OperationMetrics;
+import com.clickhouse.client.api.metrics.ServerMetrics;
+import com.clickhouse.client.api.observability.DefaultSpanRecorder;
+import com.clickhouse.client.api.observability.Span;
+import com.clickhouse.client.api.observability.SpanAttribute;
+import com.clickhouse.client.api.observability.SpanRecorder;
+import com.clickhouse.client.api.query.QuerySettings;
+import com.clickhouse.client.api.transport.Endpoint;
+import io.opentelemetry.api.GlobalOpenTelemetry;
+import io.opentelemetry.api.OpenTelemetry;
+import io.opentelemetry.api.common.AttributeKey;
+import io.opentelemetry.api.common.AttributeType;
+import io.opentelemetry.api.trace.SpanKind;
+import io.opentelemetry.api.trace.StatusCode;
+import io.opentelemetry.api.trace.Tracer;
+import io.opentelemetry.context.Scope;
+import io.opentelemetry.sdk.OpenTelemetrySdk;
+import io.opentelemetry.sdk.testing.exporter.InMemorySpanExporter;
+import io.opentelemetry.sdk.trace.SdkTracerProvider;
+import io.opentelemetry.sdk.trace.data.EventData;
+import io.opentelemetry.sdk.trace.data.SpanData;
+import io.opentelemetry.sdk.trace.export.SimpleSpanProcessor;
+import org.testng.Assert;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import java.net.URI;
+import java.util.List;
+
+public class OpenTelemetrySpanRecorderUnitTest {
+
+ private static final String DATABASE = "spans_db";
+
+ private InMemorySpanExporter exporter;
+ private OpenTelemetrySdk openTelemetry;
+ private OpenTelemetrySpanRecorder recorder;
+
+ @BeforeMethod
+ void setUp() {
+ exporter = InMemorySpanExporter.create();
+ openTelemetry = OpenTelemetrySdk.builder()
+ .setTracerProvider(SdkTracerProvider.builder()
+ .addSpanProcessor(SimpleSpanProcessor.create(exporter))
+ .build())
+ .build();
+ recorder = new OpenTelemetrySpanRecorder(openTelemetry);
+ }
+
+ @AfterMethod
+ void tearDown() {
+ openTelemetry.close();
+ }
+
+ @Test
+ public void testQuerySpanReportsStandardNameAndAttributes() {
+ Span span = recorder.startQuerySpan(querySettings("q-42"), "SELECT 1", endpoint("ch-host", 8123));
+ span.end();
+
+ SpanData exported = onlySpan();
+ Assert.assertEquals(exported.getName(), "query " + DATABASE);
+ Assert.assertEquals(exported.getKind(), SpanKind.CLIENT);
+ Assert.assertEquals(exported.getInstrumentationScopeInfo().getName(),
+ OpenTelemetrySpanRecorder.INSTRUMENTATION_SCOPE_NAME);
+ Assert.assertEquals(stringAttribute(exported, SpanAttribute.DB_SYSTEM_NAME), "clickhouse");
+ Assert.assertEquals(stringAttribute(exported, SpanAttribute.DB_NAMESPACE), DATABASE);
+ Assert.assertEquals(stringAttribute(exported, SpanAttribute.DB_QUERY_TEXT), "SELECT 1");
+ Assert.assertEquals(stringAttribute(exported, SpanAttribute.CLICKHOUSE_QUERY_ID), "q-42");
+ Assert.assertEquals(stringAttribute(exported, SpanAttribute.SERVER_ADDRESS), "ch-host");
+ Assert.assertEquals(longAttribute(exported, SpanAttribute.SERVER_PORT), Long.valueOf(8123L));
+ Assert.assertEquals(exported.getStatus().getStatusCode(), StatusCode.UNSET);
+ }
+
+ @Test
+ public void testInsertSpanReportsCollectionAndBatchSize() {
+ Span span = recorder.startInsertSpan(insertSettings("i-1"), "events", 5, endpoint("ch-host", 8123));
+ span.end();
+
+ SpanData exported = onlySpan();
+ Assert.assertEquals(exported.getName(), "insert " + DATABASE + ".events");
+ Assert.assertEquals(exported.getKind(), SpanKind.CLIENT);
+ Assert.assertEquals(stringAttribute(exported, SpanAttribute.DB_OPERATION_NAME), "insert");
+ Assert.assertEquals(stringAttribute(exported, SpanAttribute.DB_COLLECTION_NAME), "events");
+ Assert.assertEquals(longAttribute(exported, SpanAttribute.DB_OPERATION_BATCH_SIZE), Long.valueOf(5L));
+ Assert.assertNull(stringAttribute(exported, SpanAttribute.DB_QUERY_TEXT),
+ "an insert sends no user statement");
+ }
+
+ @Test
+ public void testInsertSpanOmitsUnknownBatchSize() {
+ Span span = recorder.startInsertSpan(insertSettings("i-2"), "events", SpanRecorder.BATCH_SIZE_UNKNOWN,
+ endpoint("ch-host", 8123));
+ span.end();
+
+ SpanData exported = onlySpan();
+ Assert.assertEquals(exported.getName(), "insert " + DATABASE + ".events");
+ Assert.assertNull(longAttribute(exported, SpanAttribute.DB_OPERATION_BATCH_SIZE));
+ }
+
+ @Test
+ public void testRequestSpanIsChildOfOperationSpan() {
+ Span operationSpan = recorder.startQuerySpan(querySettings("q-1"), "SELECT 1", endpoint("ch-host", 8123));
+ Span requestSpan = recorder.startRequestSpan(operationSpan, "node-2", 8443);
+ recorder.recordHttpStatus(requestSpan, 200);
+ requestSpan.end();
+ operationSpan.end();
+
+ SpanData request = spanByName("POST");
+ SpanData operation = spanByName("query " + DATABASE);
+ Assert.assertEquals(request.getTraceId(), operation.getTraceId());
+ Assert.assertEquals(request.getParentSpanId(), operation.getSpanId());
+ Assert.assertEquals(request.getKind(), SpanKind.CLIENT);
+ Assert.assertEquals(stringAttribute(request, SpanAttribute.HTTP_REQUEST_METHOD), "POST");
+ Assert.assertEquals(longAttribute(request, SpanAttribute.HTTP_RESPONSE_STATUS_CODE), Long.valueOf(200L));
+ Assert.assertEquals(stringAttribute(request, SpanAttribute.SERVER_ADDRESS), "node-2",
+ "the attempt reports the endpoint it used");
+ Assert.assertEquals(longAttribute(request, SpanAttribute.SERVER_PORT), Long.valueOf(8443L));
+ }
+
+ @Test
+ public void testOperationSpanJoinsAmbientTrace() {
+ io.opentelemetry.api.trace.Span ambient = openTelemetry.getTracer("test").spanBuilder("application")
+ .startSpan();
+ Span operationSpan;
+ try (Scope scope = ambient.makeCurrent()) {
+ operationSpan = recorder.startQuerySpan(querySettings("q-1"), "SELECT 1", null);
+ }
+ operationSpan.end();
+ ambient.end();
+
+ SpanData operation = spanByName("query " + DATABASE);
+ Assert.assertEquals(operation.getTraceId(), ambient.getSpanContext().getTraceId());
+ Assert.assertEquals(operation.getParentSpanId(), ambient.getSpanContext().getSpanId());
+ }
+
+ @Test
+ public void testRequestSpanFallsBackToCurrentContextWhenOperationSpanIsForeign() {
+ Span requestSpan = recorder.startRequestSpan(DefaultSpanRecorder.NOOP_SPAN, "node-1", 8123);
+ requestSpan.end();
+
+ SpanData request = onlySpan();
+ Assert.assertEquals(request.getName(), "POST");
+ Assert.assertFalse(request.getParentSpanContext().isValid(),
+ "without an operation span and without an ambient context there is no parent to attach to");
+
+ io.opentelemetry.api.trace.Span ambient = openTelemetry.getTracer("test").spanBuilder("application")
+ .startSpan();
+ Span secondRequestSpan;
+ try (Scope scope = ambient.makeCurrent()) {
+ secondRequestSpan = recorder.startRequestSpan(DefaultSpanRecorder.NOOP_SPAN, "node-1", 8123);
+ }
+ secondRequestSpan.end();
+ ambient.end();
+
+ Assert.assertEquals(exporter.getFinishedSpanItems().get(1).getParentSpanId(),
+ ambient.getSpanContext().getSpanId(),
+ "with an ambient context the request span is started under it");
+ }
+
+ @Test
+ public void testEveryAttemptReportsItsOwnRequestSpanUnderOneOperationSpan() {
+ Span operationSpan = recorder.startQuerySpan(querySettings("q-1"), "SELECT 1", null);
+ Span firstAttempt = recorder.startRequestSpan(operationSpan, "node-1", 8123);
+ recorder.recordRequestFailure(firstAttempt, new IllegalStateException("first attempt failed"));
+ firstAttempt.end();
+ Span secondAttempt = recorder.startRequestSpan(operationSpan, "node-2", 8123);
+ recorder.recordHttpStatus(secondAttempt, 200);
+ secondAttempt.end();
+ operationSpan.end();
+
+ List`, a request span is named `POST`, and the recorded keys are the ones listed in `SpanAttribute`.
+
+Compatibility-sensitive traits:
+
+- Span kind and nesting should not drift: every span is a `CLIENT` span, an operation span is started as a child of the current OpenTelemetry context (so it joins the application's ambient trace), and each request span - including one per retry - is a child of its operation span. A request span whose operation span was not created by this recorder is started under the current OpenTelemetry context instead of failing.
+- Attribute value typing is part of the contract, because a backend indexes by type: a `String` value is recorded as a string attribute, a `Boolean` as a boolean, a `Double`/`Float` as a double, any other `Number` as a long, and any other value as its `String.valueOf` form. A `null` key or value records nothing.
+- A failure sets the OpenTelemetry span status to `ERROR`, records `error.type`, and records the failure itself as an OpenTelemetry exception event, so its message and stack trace are reported too; the ClickHouse error code and the HTTP status are recorded as separate attributes, not as the status description.
+- `Span#end()` is idempotent: a span is exported once even if it is ended more than once.
+- The recorder does not make any span current. The client hands its response to the caller before the response body is read, so spans are ended on threads the recorder does not control and an application that wants the client's span in its own context must make it current itself.
diff --git a/pom.xml b/pom.xml
index 7e402d341..66c9077c9 100644
--- a/pom.xml
+++ b/pom.xml
@@ -93,6 +93,7 @@