diff --git a/dd-java-agent/agent-bootstrap/src/main/java/datadog/trace/bootstrap/instrumentation/decorator/BaseDecorator.java b/dd-java-agent/agent-bootstrap/src/main/java/datadog/trace/bootstrap/instrumentation/decorator/BaseDecorator.java index 5c6628c5d35..4621d251729 100644 --- a/dd-java-agent/agent-bootstrap/src/main/java/datadog/trace/bootstrap/instrumentation/decorator/BaseDecorator.java +++ b/dd-java-agent/agent-bootstrap/src/main/java/datadog/trace/bootstrap/instrumentation/decorator/BaseDecorator.java @@ -8,6 +8,7 @@ import datadog.trace.api.Config; import datadog.trace.api.DDTags; import datadog.trace.api.Functions; +import datadog.trace.api.KnownTags; import datadog.trace.api.TagMap; import datadog.trace.api.cache.QualifiedClassNameCache; import datadog.trace.bootstrap.instrumentation.api.AgentSpan; @@ -194,12 +195,12 @@ public final void onPeerConnection( if (remoteAddress != null) { String ip = remoteAddress.getHostAddress(); if (resolved && Config.get().isPeerHostNameEnabled()) { - span.setTag(Tags.PEER_HOSTNAME, hostName(remoteAddress, ip)); + span.setTag(KnownTags.PEER_HOSTNAME_ID, hostName(remoteAddress, ip)); } if (remoteAddress instanceof Inet4Address) { - span.setTag(Tags.PEER_HOST_IPV4, ip); + span.setTag(KnownTags.PEER_IPV4_ID, ip); } else if (remoteAddress instanceof Inet6Address) { - span.setTag(Tags.PEER_HOST_IPV6, ip); + span.setTag(KnownTags.PEER_IPV6_ID, ip); } } } diff --git a/dd-java-agent/agent-bootstrap/src/test/groovy/datadog/trace/bootstrap/instrumentation/decorator/BaseDecoratorTest.groovy b/dd-java-agent/agent-bootstrap/src/test/groovy/datadog/trace/bootstrap/instrumentation/decorator/BaseDecoratorTest.groovy index 3151d655739..a04a75712f0 100644 --- a/dd-java-agent/agent-bootstrap/src/test/groovy/datadog/trace/bootstrap/instrumentation/decorator/BaseDecoratorTest.groovy +++ b/dd-java-agent/agent-bootstrap/src/test/groovy/datadog/trace/bootstrap/instrumentation/decorator/BaseDecoratorTest.groovy @@ -24,7 +24,16 @@ class BaseDecoratorTest extends DDSpecification { @Shared def errorPriority = null as Byte - def span = Mock(AgentSpan) + def span = mockSpan() + + /** + * Mocks an {@link AgentSpan} that reports every id-keyed {@code setTag} as the name-keyed call, + * so expectations are written by tag name however the code under test sets the tag. See + * {@link NameKeyedAgentSpan}. + */ + AgentSpan mockSpan() { + return Mock(NameKeyedAgentSpan) + } def spanContext = Mock(AgentSpanContext) def "test afterStart"() { diff --git a/dd-java-agent/agent-bootstrap/src/test/groovy/datadog/trace/bootstrap/instrumentation/decorator/ClientDecoratorTest.groovy b/dd-java-agent/agent-bootstrap/src/test/groovy/datadog/trace/bootstrap/instrumentation/decorator/ClientDecoratorTest.groovy index fec5748f089..a1568c81af5 100644 --- a/dd-java-agent/agent-bootstrap/src/test/groovy/datadog/trace/bootstrap/instrumentation/decorator/ClientDecoratorTest.groovy +++ b/dd-java-agent/agent-bootstrap/src/test/groovy/datadog/trace/bootstrap/instrumentation/decorator/ClientDecoratorTest.groovy @@ -8,7 +8,7 @@ import datadog.trace.bootstrap.instrumentation.api.Tags class ClientDecoratorTest extends BaseDecoratorTest { - def span = Mock(AgentSpan) + def span = mockSpan() def "test afterStart"() { setup: diff --git a/dd-java-agent/agent-bootstrap/src/test/groovy/datadog/trace/bootstrap/instrumentation/decorator/DBTypeProcessingDatabaseClientDecoratorTest.groovy b/dd-java-agent/agent-bootstrap/src/test/groovy/datadog/trace/bootstrap/instrumentation/decorator/DBTypeProcessingDatabaseClientDecoratorTest.groovy index 624100fcc50..efe550ee1bf 100644 --- a/dd-java-agent/agent-bootstrap/src/test/groovy/datadog/trace/bootstrap/instrumentation/decorator/DBTypeProcessingDatabaseClientDecoratorTest.groovy +++ b/dd-java-agent/agent-bootstrap/src/test/groovy/datadog/trace/bootstrap/instrumentation/decorator/DBTypeProcessingDatabaseClientDecoratorTest.groovy @@ -2,14 +2,13 @@ package datadog.trace.bootstrap.instrumentation.decorator import datadog.trace.api.DDTags import datadog.trace.api.TagMap -import datadog.trace.bootstrap.instrumentation.api.AgentSpan import datadog.trace.bootstrap.instrumentation.api.Tags import datadog.trace.bootstrap.instrumentation.api.UTF8BytesString import spock.lang.Ignore class DBTypeProcessingDatabaseClientDecoratorTest extends ClientDecoratorTest { - def span = Mock(AgentSpan) + def span = mockSpan() @Ignore("https://github.com/DataDog/dd-trace-java/pull/5213") def "test afterStart"() { diff --git a/dd-java-agent/agent-bootstrap/src/test/groovy/datadog/trace/bootstrap/instrumentation/decorator/DatabaseClientDecoratorTest.groovy b/dd-java-agent/agent-bootstrap/src/test/groovy/datadog/trace/bootstrap/instrumentation/decorator/DatabaseClientDecoratorTest.groovy index 93852ccc88c..b8d38b32f0d 100644 --- a/dd-java-agent/agent-bootstrap/src/test/groovy/datadog/trace/bootstrap/instrumentation/decorator/DatabaseClientDecoratorTest.groovy +++ b/dd-java-agent/agent-bootstrap/src/test/groovy/datadog/trace/bootstrap/instrumentation/decorator/DatabaseClientDecoratorTest.groovy @@ -12,7 +12,7 @@ import static datadog.trace.api.config.TraceInstrumentationConfig.DB_CLIENT_HOST class DatabaseClientDecoratorTest extends ClientDecoratorTest { - def span = Mock(AgentSpan) + def span = mockSpan() def "test afterStart"() { setup: diff --git a/dd-java-agent/agent-bootstrap/src/test/groovy/datadog/trace/bootstrap/instrumentation/decorator/HttpClientDecoratorTest.groovy b/dd-java-agent/agent-bootstrap/src/test/groovy/datadog/trace/bootstrap/instrumentation/decorator/HttpClientDecoratorTest.groovy index 1bc83457bd0..92f709a5d79 100644 --- a/dd-java-agent/agent-bootstrap/src/test/groovy/datadog/trace/bootstrap/instrumentation/decorator/HttpClientDecoratorTest.groovy +++ b/dd-java-agent/agent-bootstrap/src/test/groovy/datadog/trace/bootstrap/instrumentation/decorator/HttpClientDecoratorTest.groovy @@ -52,7 +52,7 @@ class HttpClientDecoratorTest extends ClientDecoratorTest { AgentTracer.forceRegister(ORIGINAL_TRACER) } - def span = Mock(AgentSpan) + def span = mockSpan() def "test onRequest"() { setup: diff --git a/dd-java-agent/agent-bootstrap/src/test/groovy/datadog/trace/bootstrap/instrumentation/decorator/HttpServerDecoratorTest.groovy b/dd-java-agent/agent-bootstrap/src/test/groovy/datadog/trace/bootstrap/instrumentation/decorator/HttpServerDecoratorTest.groovy index da411dc2431..5ac781b913b 100644 --- a/dd-java-agent/agent-bootstrap/src/test/groovy/datadog/trace/bootstrap/instrumentation/decorator/HttpServerDecoratorTest.groovy +++ b/dd-java-agent/agent-bootstrap/src/test/groovy/datadog/trace/bootstrap/instrumentation/decorator/HttpServerDecoratorTest.groovy @@ -36,7 +36,7 @@ import static datadog.trace.api.gateway.Events.EVENTS class HttpServerDecoratorTest extends ServerDecoratorTest { - def span = Mock(AgentSpan) + def span = mockSpan() static class MapCarrierVisitor implements AgentPropagation.ContextVisitor { diff --git a/dd-java-agent/agent-bootstrap/src/test/groovy/datadog/trace/bootstrap/instrumentation/decorator/ServerDecoratorTest.groovy b/dd-java-agent/agent-bootstrap/src/test/groovy/datadog/trace/bootstrap/instrumentation/decorator/ServerDecoratorTest.groovy index d60c1534627..0e096772976 100644 --- a/dd-java-agent/agent-bootstrap/src/test/groovy/datadog/trace/bootstrap/instrumentation/decorator/ServerDecoratorTest.groovy +++ b/dd-java-agent/agent-bootstrap/src/test/groovy/datadog/trace/bootstrap/instrumentation/decorator/ServerDecoratorTest.groovy @@ -12,7 +12,7 @@ import static datadog.trace.bootstrap.instrumentation.api.Tags.SPAN_KIND class ServerDecoratorTest extends BaseDecoratorTest { - def span = Mock(AgentSpan) + def span = mockSpan() def "test afterStart"() { def decorator = newDecorator() diff --git a/dd-java-agent/agent-bootstrap/src/test/java/datadog/trace/bootstrap/instrumentation/decorator/NameKeyedAgentSpan.java b/dd-java-agent/agent-bootstrap/src/test/java/datadog/trace/bootstrap/instrumentation/decorator/NameKeyedAgentSpan.java new file mode 100644 index 00000000000..435ef32cdb5 --- /dev/null +++ b/dd-java-agent/agent-bootstrap/src/test/java/datadog/trace/bootstrap/instrumentation/decorator/NameKeyedAgentSpan.java @@ -0,0 +1,52 @@ +package datadog.trace.bootstrap.instrumentation.decorator; + +import datadog.trace.api.KnownTagCodec; +import datadog.trace.bootstrap.instrumentation.api.AgentSpan; + +/** + * An {@link AgentSpan} to mock in tests whose id-keyed {@code setTag} overloads are {@code final} + * and delegate to the name-keyed ones. A mock cannot override a final method, so it never sees the + * id-keyed call: tests keep expecting {@code setTag(name, value)} whether the code under test sets + * a tag by name or by {@code KnownTags} id. + */ +public abstract class NameKeyedAgentSpan implements AgentSpan { + @Override + public final AgentSpan setTag(long tagId, boolean value) { + return setTag(KnownTagCodec.nameOf(tagId), value); + } + + @Override + public final AgentSpan setTag(long tagId, int value) { + return setTag(KnownTagCodec.nameOf(tagId), value); + } + + @Override + public final AgentSpan setTag(long tagId, long value) { + return setTag(KnownTagCodec.nameOf(tagId), value); + } + + @Override + public final AgentSpan setTag(long tagId, float value) { + return setTag(KnownTagCodec.nameOf(tagId), value); + } + + @Override + public final AgentSpan setTag(long tagId, double value) { + return setTag(KnownTagCodec.nameOf(tagId), value); + } + + @Override + public final AgentSpan setTag(long tagId, String value) { + return setTag(KnownTagCodec.nameOf(tagId), value); + } + + @Override + public final AgentSpan setTag(long tagId, CharSequence value) { + return setTag(KnownTagCodec.nameOf(tagId), value); + } + + @Override + public final AgentSpan setTag(long tagId, Object value) { + return setTag(KnownTagCodec.nameOf(tagId), value); + } +} diff --git a/dd-trace-core/src/main/java/datadog/trace/core/DDSpan.java b/dd-trace-core/src/main/java/datadog/trace/core/DDSpan.java index f44cbf71242..0910907aadb 100644 --- a/dd-trace-core/src/main/java/datadog/trace/core/DDSpan.java +++ b/dd-trace-core/src/main/java/datadog/trace/core/DDSpan.java @@ -18,6 +18,7 @@ import datadog.trace.api.DDTags; import datadog.trace.api.DDTraceId; import datadog.trace.api.EndpointTracker; +import datadog.trace.api.KnownTags; import datadog.trace.api.TagMap; import datadog.trace.api.TraceConfig; import datadog.trace.api.debugger.DebuggerConfigBridge; @@ -527,6 +528,67 @@ public DDSpan setTag(final String tag, final Object value) { return this; } + // Id-keyed overrides: same behavior as the String family above, including interception and the + // http.status_code quirk, but the tag is stored by id with no name lookup. + @Override + public DDSpan setTag(final long tagId, final String value) { + if (value == null || value.isEmpty()) { + context.removeTag(tagId); + } else { + context.setTag(tagId, value); + } + return this; + } + + @Override + public DDSpan setTag(final long tagId, final boolean value) { + context.setTag(tagId, value); + return this; + } + + @Override + public DDSpan setTag(final long tagId, final int value) { + if (tagId == KnownTags.HTTP_STATUS_CODE_ID) { + context.setHttpStatusCode((short) value); + } + context.setTag(tagId, value); + return this; + } + + @Override + public DDSpan setTag(final long tagId, final long value) { + context.setTag(tagId, value); + return this; + } + + @Override + public DDSpan setTag(final long tagId, final float value) { + context.setTag(tagId, value); + return this; + } + + @Override + public DDSpan setTag(final long tagId, final double value) { + context.setTag(tagId, value); + return this; + } + + @Override + public DDSpan setTag(final long tagId, final CharSequence value) { + if (value == null || value.length() == 0) { + context.setTag(tagId, (Object) null); + } else { + context.setTag(tagId, value); + } + return this; + } + + @Override + public DDSpan setTag(final long tagId, final Object value) { + context.setTag(tagId, value); + return this; + } + @Override public AgentSpan setAllTags(Map map) { context.setAllTags(map); diff --git a/dd-trace-core/src/main/java/datadog/trace/core/DDSpanContext.java b/dd-trace-core/src/main/java/datadog/trace/core/DDSpanContext.java index 5fe3aad59cd..0f14d412a84 100644 --- a/dd-trace-core/src/main/java/datadog/trace/core/DDSpanContext.java +++ b/dd-trace-core/src/main/java/datadog/trace/core/DDSpanContext.java @@ -15,6 +15,7 @@ import datadog.trace.api.DDTags; import datadog.trace.api.DDTraceId; import datadog.trace.api.Functions; +import datadog.trace.api.KnownTagCodec; import datadog.trace.api.KnownTags; import datadog.trace.api.ProcessTags; import datadog.trace.api.TagMap; @@ -1000,6 +1001,22 @@ public void removeTag(String tag) { } } + /** + * Removes a known tag by id, rather than by its name, which need not resolve back to the id. An + * id that names no known tag is ignored, like the id-keyed setters do. + */ + public void removeTag(long tagId) { + if (KnownTagCodec.nameOf(tagId) == null) { + return; + } + if (tagId == KnownTags.SPAN_KIND_ID) { + spanKindOrdinal = SPAN_KIND_UNSET; + } + synchronized (unsafeTags) { + unsafeTags.getAndRemove(tagId); + } + } + /** * Sets a tag to the span. Tags are not propagated to the children. * @@ -1035,6 +1052,109 @@ public void setTag(final String tag, final String value) { } } + /* + * Id-keyed setters, mirroring the String setters above: interception still runs on the tag's + * name (TagInterceptor is name-keyed), but a stored tag is set by id, skipping the name lookup. + * An id that names no known tag is ignored, like a null tag. + */ + public void setTag(final long tagId, final Object value) { + final String tag = KnownTagCodec.nameOf(tagId); + if (null == tag) { + return; + } + if (null == value) { + removeTag(tagId); + } else if (!tagInterceptor.interceptTag(this, tag, value)) { + synchronized (unsafeTags) { + unsafeTags.set(tagId, value); + } + } + } + + public void setTag(final long tagId, final CharSequence value) { + final String tag = KnownTagCodec.nameOf(tagId); + if (null == tag) { + return; + } + if (null == value) { + removeTag(tagId); + } else if (!tagInterceptor.interceptTag(this, tag, value)) { + synchronized (unsafeTags) { + unsafeTags.set(tagId, value); + } + } + } + + public void setTag(final long tagId, final boolean value) { + final String tag = KnownTagCodec.nameOf(tagId); + if (null == tag) { + return; + } + if (precheckIntercept(tag)) { + this.setBox(tag, value); + } else { + synchronized (unsafeTags) { + unsafeTags.set(tagId, value); + } + } + } + + public void setTag(final long tagId, final int value) { + final String tag = KnownTagCodec.nameOf(tagId); + if (null == tag) { + return; + } + if (precheckIntercept(tag)) { + this.setBox(tag, value); + } else { + synchronized (unsafeTags) { + unsafeTags.set(tagId, value); + } + } + } + + public void setTag(final long tagId, final long value) { + final String tag = KnownTagCodec.nameOf(tagId); + if (null == tag) { + return; + } + if (precheckIntercept(tag)) { + this.setBox(tag, value); + } else { + synchronized (unsafeTags) { + unsafeTags.set(tagId, value); + } + } + } + + public void setTag(final long tagId, final float value) { + final String tag = KnownTagCodec.nameOf(tagId); + if (null == tag) { + return; + } + if (precheckIntercept(tag)) { + this.setBox(tag, value); + } else { + synchronized (unsafeTags) { + unsafeTags.set(tagId, value); + } + } + } + + public void setTag(final long tagId, final double value) { + final String tag = KnownTagCodec.nameOf(tagId); + if (null == tag) { + return; + } + if (precheckIntercept(tag)) { + this.setBox(tag, value); + } else { + synchronized (unsafeTags) { + unsafeTags.set(tagId, value); + } + } + } + public void setTag(TagMap.EntryReader entry) { if (entry == null) { return; @@ -1110,10 +1230,9 @@ public void setTag(final String tag, final long value) { if (null == tag) { return; } - // check needsIntercept first to avoid unnecessary boxing - boolean intercepted = - tagInterceptor.needsIntercept(tag) && tagInterceptor.interceptTag(this, tag, value); - if (!intercepted) { + if (precheckIntercept(tag)) { + this.setBox(tag, value); + } else { synchronized (unsafeTags) { unsafeTags.set(tag, value); } diff --git a/dd-trace-core/src/test/java/datadog/trace/core/DDSpanSetTagByIdTest.java b/dd-trace-core/src/test/java/datadog/trace/core/DDSpanSetTagByIdTest.java new file mode 100644 index 00000000000..0c953fa5b65 --- /dev/null +++ b/dd-trace-core/src/test/java/datadog/trace/core/DDSpanSetTagByIdTest.java @@ -0,0 +1,102 @@ +package datadog.trace.core; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; + +import datadog.trace.api.KnownTags; +import datadog.trace.common.writer.ListWriter; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +/** + * {@code DDSpan.setTag(long, ...)}: setting a known tag by id behaves exactly like setting it by + * name, including interception. + */ +class DDSpanSetTagByIdTest extends DDCoreJavaSpecification { + private CoreTracer tracer; + private DDSpan span; + + @BeforeEach + void setup() { + tracer = tracerBuilder().writer(new ListWriter()).build(); + span = (DDSpan) tracer.buildSpan("datadog", "fakeOperation").start(); + } + + @AfterEach + void tearDown() { + span.finish(); + tracer.close(); + } + + @Test + void storesTheTagUnderItsName() { + span.setTag(KnownTags.HTTP_RESEND_COUNT_ID, 2); + span.setTag(KnownTags.PEER_HOSTNAME_ID, "db.internal"); + span.setTag(KnownTags.DD_PROFILING_ENABLED_ID, true); + + assertEquals(2, span.getTag(KnownTags.HTTP_RESEND_COUNT_NAME)); + assertEquals("db.internal", span.getTag(KnownTags.PEER_HOSTNAME_NAME)); + assertEquals(true, span.getTag(KnownTags.DD_PROFILING_ENABLED_NAME)); + } + + @Test + void aNullOrEmptyValueRemovesTheTagById() { + span.setTag(KnownTags.PEER_HOSTNAME_ID, "db.internal"); + span.setTag(KnownTags.COMPONENT_ID, "okhttp"); + + span.setTag(KnownTags.PEER_HOSTNAME_ID, (String) null); + span.setTag(KnownTags.COMPONENT_ID, ""); + + assertNull(span.getTag(KnownTags.PEER_HOSTNAME_NAME)); + assertNull(span.getTag(KnownTags.COMPONENT_NAME)); + } + + @Test + void clearingAnUnknownIdIsIgnored() { + span.setTag(0L, (String) null); + span.setTag(0L, ""); + span.setTag(0L, (Object) null); + + assertNull(span.getTag(KnownTags.PEER_HOSTNAME_NAME)); + } + + @Test + void removingTheSpanKindByIdClearsTheKind() { + span.setTag(KnownTags.SPAN_KIND_ID, "client"); + assertEquals("client", span.getSpanKindString()); + + span.setTag(KnownTags.SPAN_KIND_ID, (String) null); + + assertNull(span.getSpanKindString()); + assertNull(span.getTag(KnownTags.SPAN_KIND_NAME)); + } + + @Test + void interceptedTagsAreStillIntercepted() { + span.setTag(KnownTags.DB_STATEMENT_ID, "select 1"); + span.setTag(KnownTags.SERVICE_ID, "orders-db"); + + assertEquals("select 1", span.getResourceName().toString()); + assertNull(span.getTag(KnownTags.DB_STATEMENT_NAME)); + assertEquals("orders-db", span.getServiceName()); + } + + @Test + void httpStatusCodeSetsTheStatusField() { + span.setTag(KnownTags.HTTP_STATUS_CODE_ID, 503); + + assertEquals(503, span.getHttpStatusCode()); + } + + @Test + void anEmptyOrNullValueRemovesTheTag() { + span.setTag(KnownTags.PEER_HOSTNAME_ID, "db.internal"); + span.setTag(KnownTags.PEER_HOSTNAME_ID, ""); + assertNull(span.getTag(KnownTags.PEER_HOSTNAME_NAME)); + + span.setTag(KnownTags.PEER_HOSTNAME_ID, (CharSequence) "db.internal"); + span.setTag(KnownTags.PEER_HOSTNAME_ID, (CharSequence) null); + assertNull(span.getTag(KnownTags.PEER_HOSTNAME_NAME)); + } +} diff --git a/internal-api/src/jmh/java/datadog/trace/api/TagMapInsertBenchmark.java b/internal-api/src/jmh/java/datadog/trace/api/TagMapInsertBenchmark.java new file mode 100644 index 00000000000..628d711a9e6 --- /dev/null +++ b/internal-api/src/jmh/java/datadog/trace/api/TagMapInsertBenchmark.java @@ -0,0 +1,108 @@ +package datadog.trace.api; + +import java.util.concurrent.TimeUnit; +import org.openjdk.jmh.annotations.Benchmark; +import org.openjdk.jmh.annotations.BenchmarkMode; +import org.openjdk.jmh.annotations.Fork; +import org.openjdk.jmh.annotations.Measurement; +import org.openjdk.jmh.annotations.Mode; +import org.openjdk.jmh.annotations.OutputTimeUnit; +import org.openjdk.jmh.annotations.Scope; +import org.openjdk.jmh.annotations.State; +import org.openjdk.jmh.annotations.Threads; +import org.openjdk.jmh.annotations.Warmup; + +/** + * Inserting a span's worth of tags into a fresh {@link TagMap}, the way span decoration does: known + * tags by Datadog name, the same known tags by id, and custom tags by name. + * + *

Single-threaded: each invocation builds its own map, so more threads would mostly measure + * allocation bandwidth. Run with {@code -prof gc} for allocation per operation. Tag names are + * string constants, as the tracer's are. + * + *

Results (MacBook, JDK 21, default flags, {@code @Fork(2)} triage), 12 tags per op: + * + *

+ * Benchmark      ns/op         B/op
+ * knownByName    121.1 +- 3.8  736
+ * knownById       94.7 +- 1.7  736
+ * customByName    80.6 +- 2.4  736
+ * 
+ */ +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +@Fork(2) +@Warmup(iterations = 5, time = 1) +@Measurement(iterations = 5, time = 1) +@Threads(1) +@State(Scope.Benchmark) +public class TagMapInsertBenchmark { + // Per-span tags a client or server decorator typically sets. + static final String[] KNOWN_NAMES = { + KnownTags.COMPONENT_NAME, + KnownTags.SPAN_KIND_NAME, + KnownTags.HTTP_METHOD_NAME, + KnownTags.HTTP_URL_NAME, + KnownTags.HTTP_ROUTE_NAME, + KnownTags.HTTP_HOSTNAME_NAME, + KnownTags.HTTP_USERAGENT_NAME, + KnownTags.HTTP_CLIENT_IP_NAME, + KnownTags.PEER_HOSTNAME_NAME, + KnownTags.PEER_IPV4_NAME, + KnownTags.PEER_IPV6_NAME, + KnownTags.DD_INTEGRATION_NAME, + }; + + static final long[] KNOWN_IDS = { + KnownTags.COMPONENT_ID, + KnownTags.SPAN_KIND_ID, + KnownTags.HTTP_METHOD_ID, + KnownTags.HTTP_URL_ID, + KnownTags.HTTP_ROUTE_ID, + KnownTags.HTTP_HOSTNAME_ID, + KnownTags.HTTP_USERAGENT_ID, + KnownTags.HTTP_CLIENT_IP_ID, + KnownTags.PEER_HOSTNAME_ID, + KnownTags.PEER_IPV4_ID, + KnownTags.PEER_IPV6_ID, + KnownTags.DD_INTEGRATION_ID, + }; + + static final String[] CUSTOM_NAMES = new String[KNOWN_NAMES.length]; + + static final Object[] VALUES = new Object[KNOWN_NAMES.length]; + + static { + for (int i = 0; i < KNOWN_NAMES.length; ++i) { + CUSTOM_NAMES[i] = ("app.custom.tag." + i).intern(); + VALUES[i] = "value-" + i; + } + } + + @Benchmark + public TagMap knownByName() { + TagMap map = TagMap.create(); + for (int i = 0; i < KNOWN_NAMES.length; ++i) { + map.set(KNOWN_NAMES[i], VALUES[i]); + } + return map; + } + + @Benchmark + public TagMap knownById() { + TagMap map = TagMap.create(); + for (int i = 0; i < KNOWN_IDS.length; ++i) { + map.set(KNOWN_IDS[i], VALUES[i]); + } + return map; + } + + @Benchmark + public TagMap customByName() { + TagMap map = TagMap.create(); + for (int i = 0; i < CUSTOM_NAMES.length; ++i) { + map.set(CUSTOM_NAMES[i], VALUES[i]); + } + return map; + } +} diff --git a/internal-api/src/main/java/datadog/trace/api/TagMap.java b/internal-api/src/main/java/datadog/trace/api/TagMap.java index 52d2ef32a2b..59dec3eb961 100644 --- a/internal-api/src/main/java/datadog/trace/api/TagMap.java +++ b/internal-api/src/main/java/datadog/trace/api/TagMap.java @@ -280,6 +280,44 @@ public static final Entry create(@Nonnull String tag, double value) { return TagMap.Entry.newDoubleEntry(tag, value); } + /* + * Id-keyed counterparts of the create overloads above, for a KnownTags.*_ID: same contract (a + * null or empty value yields no entry), without the name lookup. An id that names no known tag + * is rejected. + */ + + /** Entry for a known tag id, or null when {@code value} is null or an empty CharSequence. */ + @Nullable + public static final Entry create(long tagId, Object value) { + return isEmptyValue(value) ? null : TagMap.Entry.newAnyEntry(tagId, value); + } + + /** Entry for a known tag id, or null when {@code value} is null or empty. */ + @Nullable + public static final Entry create(long tagId, CharSequence value) { + return isEmptyValue(value) ? null : TagMap.Entry.newObjectEntry(tagId, value); + } + + public static final Entry create(long tagId, boolean value) { + return TagMap.Entry.newBooleanEntry(tagId, value); + } + + public static final Entry create(long tagId, int value) { + return TagMap.Entry.newIntEntry(tagId, value); + } + + public static final Entry create(long tagId, long value) { + return TagMap.Entry.newLongEntry(tagId, value); + } + + public static final Entry create(long tagId, float value) { + return TagMap.Entry.newFloatEntry(tagId, value); + } + + public static final Entry create(long tagId, double value) { + return TagMap.Entry.newDoubleEntry(tagId, value); + } + static Entry newAnyEntry(Map.Entry entry) { return newAnyEntry(entry.getKey(), entry.getValue()); } @@ -299,6 +337,36 @@ static Entry newObjectEntry(String tag, Object value) { return new Entry(tag, OBJECT, 0, value); } + // Id-keyed factories: the tag id already names a canonical tag, so these skip the + // canonicalizing name lookup the String factories pay. + static Entry newAnyEntry(long tagId, Object value) { + return new Entry(tagId, ANY, 0L, value); + } + + static Entry newObjectEntry(long tagId, Object value) { + return new Entry(tagId, OBJECT, 0, value); + } + + static Entry newBooleanEntry(long tagId, boolean value) { + return new Entry(tagId, BOOLEAN, boolean2Prim(value), Boolean.valueOf(value)); + } + + static Entry newIntEntry(long tagId, int value) { + return new Entry(tagId, INT, int2Prim(value), null); + } + + static Entry newLongEntry(long tagId, long value) { + return new Entry(tagId, LONG, long2Prim(value), null); + } + + static Entry newFloatEntry(long tagId, float value) { + return new Entry(tagId, FLOAT, float2Prim(value), null); + } + + static Entry newDoubleEntry(long tagId, double value) { + return new Entry(tagId, DOUBLE, double2Prim(value), null); + } + static Entry newBooleanEntry(String tag, boolean value) { return new Entry(tag, BOOLEAN, boolean2Prim(value), Boolean.valueOf(value)); } @@ -340,10 +408,12 @@ static Entry newDoubleEntry(String tag, Double box) { } /* - * hash is stored in line for fast handling of Entry-s coming from another TagMap - * However, hash is lazily computed using the same trick as {@link java.lang.String}. + * The tag's 64-bit hash, computed once at construction. For a known tag it is the tag id, whose + * serial sits in the high bits, so the upper 32 bits are never zero; for a custom tag it is the + * name's hash in the low 32 bits, with the upper 32 bits zero. The two can never collide, and + * tagId() is a field read. See tagHashOf. */ - int lazyTagHash; + final long tagHash; // To optimize construction of Entry around boxed primitives and Object entries, // no type checks are done during construction. @@ -368,35 +438,72 @@ static Entry newDoubleEntry(String tag, Double box) { private Entry(String tag, byte type, long prim, Object obj) { /* * Canonicalize known names at the single Entry construction point, so Datadog and - * OpenTelemetry spellings use the same TagMap key. This adds a StringIndex lookup to every - * new entry, including on the application thread. + * OpenTelemetry spellings use the same TagMap key. The one StringIndex lookup this costs also + * yields the tag id, which becomes the tag hash. */ - super(KnownTagCodec.canonicalTagName(tag)); - this.lazyTagHash = 0; // lazily computed + this(KnownTagCodec.keyOf(tag), tag, type, prim, obj); + } + + private Entry(long tagId, byte type, long prim, Object obj) { + // Resolve the name once: it both validates the id and names the entry. + super(requireKnownName(tagId)); + this.tagHash = tagId; this.rawType = type; this.rawPrim = prim; this.rawObj = obj; } - int hash() { - // If value of hash read in this thread is zero, then hash is computed. - // hash is not held as a volatile, since this computation can safely be repeated as any time - int hash = this.lazyTagHash; - if (hash != 0) return hash; + /** {@code tagId} is a known id, or 0 for the custom tag {@code customTag}. */ + private Entry(long tagId, String customTag, byte type, long prim, Object obj) { + super(tagId != 0 ? KnownTagCodec.nameOf(tagId) : customTag); + this.tagHash = tagId != 0 ? tagId : customHash(customTag); - hash = _hash(this.tag); - this.lazyTagHash = hash; - return hash; + this.rawType = type; + this.rawPrim = prim; + this.rawObj = obj; + } + + private static String requireKnownName(long tagId) { + String name = tagId == 0 ? null : KnownTagCodec.nameOf(tagId); + if (name == null) { + throw new IllegalArgumentException("not a known tag id: " + Long.toHexString(tagId)); + } + return name; + } + + /** The tag hash a name maps to: its id when known, else its {@link #customHash}. */ + static long tagHashOf(String tag) { + long tagId = KnownTagCodec.keyOf(tag); + return tagId != 0 ? tagId : customHash(tag); + } + + /** A custom tag's hash: the name hash in the low 32 bits, never colliding with a tag id. */ + static long customHash(String tag) { + return _hash(tag) & 0xFFFFFFFFL; + } + + /** + * Folds a tag hash to the 32-bit bucket hash. A tag id's serial is in bits 63-48, so it is + * folded down from there rather than from bit 32, where a bucket mask would discard it. + * + *

Never zero: BucketGroup treats a zero hash as a vacant slot. The fold can produce zero + * when a serial equals the id's flag bits (serial 4 with the trace-level bit, 4), so zero maps + * to the same nonzero sentinel {@link #_hash} uses. + */ + static int bucketHash(long tagHash) { + int hash = (int) (tagHash >>> 48) ^ (int) tagHash; + return hash == 0 ? 0xDD06 : hash; + } + + int hash() { + return bucketHash(this.tagHash); } @Override public long tagId() { - /* - * Resolve on demand. Only OTLP serialization currently needs the ID, so caching it here - * would add a field to every Entry to save a lookup on exported tags. - */ - return KnownTagCodec.keyOf(this.tag); + // A known tag's hash is its id, whose upper 32 bits are never zero; a custom tag's are. + return (this.tagHash >>> 32) != 0 ? this.tagHash : 0L; } @Override @@ -1301,9 +1408,18 @@ public Entry getEntry(String tag) { // Entries are stored under their canonical Datadog name (see Entry's constructor); a lookup by // an OpenTelemetry rename must canonicalize the same way, or it would hash to the wrong bucket // and silently miss the entry stored under the Datadog name. - String canonicalTag = KnownTagCodec.canonicalTagName(tag); + long tagHash = Entry.tagHashOf(tag); + String canonicalTag = (tagHash >>> 32) != 0 ? KnownTagCodec.nameOf(tagHash) : tag; + return this.getEntry(canonicalTag, tagHash); + } - Entry local = this.getLocalEntry(canonicalTag); + /** The entry for a known tag id, found by the id itself rather than by resolving a name. */ + public Entry getEntry(long tagId) { + return this.getEntry(Entry.requireKnownName(tagId), tagId); + } + + private Entry getEntry(String canonicalTag, long tagHash) { + Entry local = this.getLocalEntry(canonicalTag, tagHash); if (local != null) { // Local entry shadows the parent (local-wins) — unchanged hot path. return local; @@ -1318,13 +1434,13 @@ public Entry getEntry(String tag) { if (this.removedFromParent != null && this.removedFromParent.contains(canonicalTag)) { return null; // tombstoned: removed locally, do not read through } - return parent.getEntry(canonicalTag); + return parent.getEntry(canonicalTag, tagHash); } /** Looks up an entry in this map's own buckets only — no read-through to the parent. */ - private Entry getLocalEntry(String tag) { + private Entry getLocalEntry(String tag, long tagHash) { Object[] thisBuckets = this.buckets; - int hash = TagMap.Entry._hash(tag); + int hash = Entry.bucketHash(tagHash); return findInBucket(thisBuckets[hash & (thisBuckets.length - 1)], hash, tag); } @@ -1416,6 +1532,39 @@ public void set(@Nonnull String tag, double value) { this.putEntry(Entry.newDoubleEntry(tag, value)); } + /* + * Id-keyed setters: the caller passes a KnownTags.*_ID, so the entry is built under the tag's + * canonical name without the name lookup the String setters pay. The id must name a known tag; + * custom tags have no id and use the String setters. + */ + public void set(long tagId, @Nonnull Object value) { + this.putEntry(Entry.newAnyEntry(tagId, value)); + } + + public void set(long tagId, @Nonnull CharSequence value) { + this.putEntry(Entry.newObjectEntry(tagId, value)); + } + + public void set(long tagId, boolean value) { + this.putEntry(Entry.newBooleanEntry(tagId, value)); + } + + public void set(long tagId, int value) { + this.putEntry(Entry.newIntEntry(tagId, value)); + } + + public void set(long tagId, long value) { + this.putEntry(Entry.newLongEntry(tagId, value)); + } + + public void set(long tagId, float value) { + this.putEntry(Entry.newFloatEntry(tagId, value)); + } + + public void set(long tagId, double value) { + this.putEntry(Entry.newDoubleEntry(tagId, value)); + } + /** * Places an Entry directly into the map, avoiding a new Entry allocation. Null-tolerant: a null * {@code newEntry} is a no-op returning null, so an Entry producer (e.g. {@link @@ -1785,9 +1934,20 @@ public Entry getAndRemove(String tag) { // See getEntry: entries are stored under their canonical Datadog name, so a removal by an // OpenTelemetry rename must canonicalize first to find (and tombstone) the right entry. - String canonicalTag = KnownTagCodec.canonicalTagName(tag); + long tagHash = Entry.tagHashOf(tag); + String canonicalTag = (tagHash >>> 32) != 0 ? KnownTagCodec.nameOf(tagHash) : tag; + return this.getAndRemove(canonicalTag, tagHash); + } + + /** Removes the entry for a known tag id; see {@link #getEntry(long)}. */ + public Entry getAndRemove(long tagId) { + this.checkWriteAccess(); + + return this.getAndRemove(Entry.requireKnownName(tagId), tagId); + } - Entry localRemoved = this.removeLocal(canonicalTag); + private Entry getAndRemove(String canonicalTag, long tagHash) { + Entry localRemoved = this.removeLocal(canonicalTag, tagHash); TagMap parent = this.parent; if (parent != null) { @@ -1798,7 +1958,7 @@ public Entry getAndRemove(String tag) { boolean alreadyTombstoned = this.removedFromParent != null && this.removedFromParent.contains(canonicalTag); if (!alreadyTombstoned) { - Entry parentEntry = parent.getEntry(canonicalTag); + Entry parentEntry = parent.getEntry(canonicalTag, tagHash); if (parentEntry != null) { if (this.removedFromParent == null) { // Small initial capacity: this set is rare and almost always holds only a handful of @@ -1814,10 +1974,10 @@ public Entry getAndRemove(String tag) { } /** Removes an entry from this map's own buckets only — no parent/tombstone handling. */ - private Entry removeLocal(String tag) { + private Entry removeLocal(String tag, long tagHash) { Object[] thisBuckets = this.buckets; - int hash = TagMap.Entry._hash(tag); + int hash = Entry.bucketHash(tagHash); int bucketIndex = hash & (thisBuckets.length - 1); Object bucket = thisBuckets[bucketIndex]; diff --git a/internal-api/src/main/java/datadog/trace/bootstrap/instrumentation/api/AgentSpan.java b/internal-api/src/main/java/datadog/trace/bootstrap/instrumentation/api/AgentSpan.java index 6a338659934..2adf0b2e609 100644 --- a/internal-api/src/main/java/datadog/trace/bootstrap/instrumentation/api/AgentSpan.java +++ b/internal-api/src/main/java/datadog/trace/bootstrap/instrumentation/api/AgentSpan.java @@ -9,6 +9,7 @@ import datadog.context.ImplicitContextKeyed; import datadog.trace.api.DDSpanId; import datadog.trace.api.DDTraceId; +import datadog.trace.api.KnownTagCodec; import datadog.trace.api.TagMap; import datadog.trace.api.TraceConfig; import datadog.trace.api.gateway.IGSpanInfo; @@ -104,6 +105,43 @@ default boolean isValid() { AgentSpan setTag(String key, Object value); + /* + * Id-keyed setTag family: the caller passes a KnownTags.*_ID instead of a name. The default + * resolves the id to its name and delegates to the String setter, which is correct for every + * implementation; the core span overrides these to skip the name lookup when storing the tag. + */ + default AgentSpan setTag(long tagId, boolean value) { + return setTag(KnownTagCodec.nameOf(tagId), value); + } + + default AgentSpan setTag(long tagId, int value) { + return setTag(KnownTagCodec.nameOf(tagId), value); + } + + default AgentSpan setTag(long tagId, long value) { + return setTag(KnownTagCodec.nameOf(tagId), value); + } + + default AgentSpan setTag(long tagId, float value) { + return setTag(KnownTagCodec.nameOf(tagId), value); + } + + default AgentSpan setTag(long tagId, double value) { + return setTag(KnownTagCodec.nameOf(tagId), value); + } + + default AgentSpan setTag(long tagId, String value) { + return setTag(KnownTagCodec.nameOf(tagId), value); + } + + default AgentSpan setTag(long tagId, CharSequence value) { + return setTag(KnownTagCodec.nameOf(tagId), value); + } + + default AgentSpan setTag(long tagId, Object value) { + return setTag(KnownTagCodec.nameOf(tagId), value); + } + /** entry may be null - in which case the tags remained unchanged */ AgentSpan setTag(TagMap.EntryReader entry); diff --git a/internal-api/src/test/java/datadog/trace/api/TagMapEntryCreateByIdTest.java b/internal-api/src/test/java/datadog/trace/api/TagMapEntryCreateByIdTest.java new file mode 100644 index 00000000000..f970855c212 --- /dev/null +++ b/internal-api/src/test/java/datadog/trace/api/TagMapEntryCreateByIdTest.java @@ -0,0 +1,59 @@ +package datadog.trace.api; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import org.junit.jupiter.api.Test; + +/** {@link TagMap.Entry#create(long, Object)} and its overloads: creating an entry by tag id. */ +class TagMapEntryCreateByIdTest { + @Test + void matchesCreateByNameForEveryValueType() { + assertEquivalent( + TagMap.Entry.create(KnownTags.COMPONENT_NAME, (Object) "okhttp"), + TagMap.Entry.create(KnownTags.COMPONENT_ID, (Object) "okhttp")); + assertEquivalent( + TagMap.Entry.create(KnownTags.PEER_HOSTNAME_NAME, (CharSequence) "db.internal"), + TagMap.Entry.create(KnownTags.PEER_HOSTNAME_ID, (CharSequence) "db.internal")); + assertEquivalent( + TagMap.Entry.create(KnownTags.DD_PROFILING_ENABLED_NAME, true), + TagMap.Entry.create(KnownTags.DD_PROFILING_ENABLED_ID, true)); + assertEquivalent( + TagMap.Entry.create(KnownTags.HTTP_STATUS_CODE_NAME, 5432), + TagMap.Entry.create(KnownTags.HTTP_STATUS_CODE_ID, 5432)); + assertEquivalent( + TagMap.Entry.create(KnownTags.HTTP_RESEND_COUNT_NAME, 2L), + TagMap.Entry.create(KnownTags.HTTP_RESEND_COUNT_ID, 2L)); + assertEquivalent( + TagMap.Entry.create(KnownTags.DB_USER_NAME, 1.5f), + TagMap.Entry.create(KnownTags.DB_USER_ID, 1.5f)); + assertEquivalent( + TagMap.Entry.create(KnownTags.DB_POOL_NAME, 2.5d), + TagMap.Entry.create(KnownTags.DB_POOL_NAME_ID, 2.5d)); + } + + @Test + void aNullOrEmptyValueCreatesNoEntry() { + assertNull(TagMap.Entry.create(KnownTags.COMPONENT_ID, (Object) null)); + assertNull(TagMap.Entry.create(KnownTags.COMPONENT_ID, (Object) "")); + assertNull(TagMap.Entry.create(KnownTags.COMPONENT_ID, (CharSequence) null)); + assertNull(TagMap.Entry.create(KnownTags.COMPONENT_ID, (CharSequence) "")); + } + + @Test + void anUnknownIdIsRejected() { + assertThrows(IllegalArgumentException.class, () -> TagMap.Entry.create(0L, (Object) "value")); + assertThrows( + IllegalArgumentException.class, + () -> TagMap.Entry.create(KnownTagCodec.makeTagId(9999), 1)); + } + + /** Same tag, id, type and value -- the two creation paths build equivalent entries. */ + private static void assertEquivalent(TagMap.Entry byName, TagMap.Entry byId) { + assertEquals(byName.tag(), byId.tag()); + assertEquals(byName.tagId(), byId.tagId()); + assertEquals(byName.type(), byId.type()); + assertEquals(byName.objectValue(), byId.objectValue()); + } +} diff --git a/internal-api/src/test/java/datadog/trace/api/TagMapSetByIdTest.java b/internal-api/src/test/java/datadog/trace/api/TagMapSetByIdTest.java new file mode 100644 index 00000000000..ecef85afdd4 --- /dev/null +++ b/internal-api/src/test/java/datadog/trace/api/TagMapSetByIdTest.java @@ -0,0 +1,75 @@ +package datadog.trace.api; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; + +import java.util.HashMap; +import org.junit.jupiter.api.Test; + +/** {@link TagMap#set(long, Object)} and its overloads: setting a known tag by its id. */ +class TagMapSetByIdTest { + @Test + void storesUnderTheCanonicalName() { + TagMap map = TagMap.create(); + + map.set(KnownTags.PEER_HOSTNAME_ID, "db.internal"); + + assertEquals("db.internal", map.getObject(KnownTags.PEER_HOSTNAME_NAME)); + assertEquals(KnownTags.PEER_HOSTNAME_ID, map.getEntry(KnownTags.PEER_HOSTNAME_NAME).tagId()); + } + + @Test + void anOpenTelemetryRenameIsStoredUnderTheDatadogName() { + TagMap byId = TagMap.create(); + TagMap byOtelName = TagMap.create(); + + byId.set(KnownTags.HTTP_METHOD_ID, "GET"); + byOtelName.set(KnownTags.HTTP_METHOD_OTEL_NAME, "GET"); + + assertEquals(new HashMap<>(byOtelName), new HashMap<>(byId)); + } + + @Test + void matchesTheNameKeyedSettersForEveryValueType() { + TagMap byId = TagMap.create(); + byId.set(KnownTags.HTTP_STATUS_CODE_ID, 5432); + byId.set(KnownTags.HTTP_RESEND_COUNT_ID, 2L); + byId.set(KnownTags.PEER_HOSTNAME_ID, (CharSequence) "db.internal"); + byId.set(KnownTags.DB_INSTANCE_ID, (Object) "orders"); + byId.set(KnownTags.DD_PROFILING_ENABLED_ID, true); + byId.set(KnownTags.DB_USER_ID, 1.5f); + byId.set(KnownTags.DB_POOL_NAME_ID, 2.5d); + + TagMap byName = TagMap.create(); + byName.set(KnownTags.HTTP_STATUS_CODE_NAME, 5432); + byName.set(KnownTags.HTTP_RESEND_COUNT_NAME, 2L); + byName.set(KnownTags.PEER_HOSTNAME_NAME, (CharSequence) "db.internal"); + byName.set(KnownTags.DB_INSTANCE_NAME, (Object) "orders"); + byName.set(KnownTags.DD_PROFILING_ENABLED_NAME, true); + byName.set(KnownTags.DB_USER_NAME, 1.5f); + byName.set(KnownTags.DB_POOL_NAME, 2.5d); + + assertEquals(new HashMap<>(byName), new HashMap<>(byId)); + assertEquals(5432, byId.getEntry(KnownTags.HTTP_STATUS_CODE_NAME).intValue()); + } + + @Test + void getsAndRemovesById() { + TagMap map = TagMap.create(); + map.set(KnownTags.HTTP_METHOD_NAME, "GET"); + + assertEquals("GET", map.getEntry(KnownTags.HTTP_METHOD_ID).stringValue()); + assertEquals("GET", map.getAndRemove(KnownTags.HTTP_METHOD_ID).stringValue()); + assertNull(map.getEntry(KnownTags.HTTP_METHOD_ID)); + assertNull(map.getAndRemove(KnownTags.HTTP_METHOD_ID)); + } + + @Test + void anUnknownIdIsRejected() { + TagMap map = TagMap.create(); + + assertThrows(IllegalArgumentException.class, () -> map.set(0L, "value")); + assertThrows(IllegalArgumentException.class, () -> map.set(KnownTagCodec.makeTagId(9999), 1)); + } +} diff --git a/internal-api/src/test/java/datadog/trace/api/TagMapTagHashTest.java b/internal-api/src/test/java/datadog/trace/api/TagMapTagHashTest.java new file mode 100644 index 00000000000..5a5e56b7c78 --- /dev/null +++ b/internal-api/src/test/java/datadog/trace/api/TagMapTagHashTest.java @@ -0,0 +1,104 @@ +package datadog.trace.api; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotEquals; + +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Test; + +/** + * The 64-bit tag hash on {@link TagMap.Entry}: a known tag's hash is its id, a custom tag's is its + * name hash in the low 32 bits. + */ +class TagMapTagHashTest { + @Test + void aKnownTagHashesToItsIdHoweverItIsSet() { + TagMap.Entry byId = TagMap.Entry.newAnyEntry(KnownTags.HTTP_METHOD_ID, "GET"); + TagMap.Entry byName = TagMap.Entry.newAnyEntry(KnownTags.HTTP_METHOD_NAME, "GET"); + TagMap.Entry byOtelName = TagMap.Entry.newAnyEntry(KnownTags.HTTP_METHOD_OTEL_NAME, "GET"); + + assertEquals(KnownTags.HTTP_METHOD_ID, byId.tagHash); + assertEquals(KnownTags.HTTP_METHOD_ID, byName.tagHash); + assertEquals(KnownTags.HTTP_METHOD_ID, byOtelName.tagHash); + assertEquals(KnownTags.HTTP_METHOD_ID, byName.tagId()); + } + + @Test + void aCustomTagHashesToItsNameWithNoId() { + TagMap.Entry custom = TagMap.Entry.newAnyEntry("my.custom.tag", "value"); + + assertEquals(0L, custom.tagHash >>> 32); + assertEquals(0L, custom.tagId()); + assertEquals(TagMap.Entry.tagHashOf("my.custom.tag"), custom.tagHash); + } + + @Test + void theBucketHashOfACustomTagIsUnchanged() { + assertEquals( + TagMap.Entry._hash("my.custom.tag"), + TagMap.Entry.bucketHash(TagMap.Entry.tagHashOf("my.custom.tag"))); + } + + @Test + void theBucketHashOfAKnownTagCarriesItsSerial() { + // Folding from bit 32 would leave the serial above any bucket mask; it must come from bit 48. + assertNotEquals( + TagMap.Entry.bucketHash(KnownTags.HTTP_METHOD_ID) & 0xFF, + TagMap.Entry.bucketHash(KnownTags.HTTP_ROUTE_ID) & 0xFF); + } + + @Test + void noKnownTagFoldsToTheVacantSlotHash() throws IllegalAccessException { + // BucketGroup treats a zero hash as a vacant slot; _dd.djm.enabled once folded to zero. + for (long tagId : knownTagIds()) { + assertNotEquals(0, TagMap.Entry.bucketHash(tagId), Long.toHexString(tagId)); + } + assertNotEquals(0, TagMap.Entry.bucketHash(KnownTags.DD_DJM_ENABLED_ID)); + } + + @Test + void everyKnownTagSurvivesBucketCollisionsAndCopies() throws IllegalAccessException { + List tagIds = knownTagIds(); + TagMap map = TagMap.create(); + for (long tagId : tagIds) { + map.set(tagId, "value"); + } + TagMap copy = map.copy(); + + assertEquals(tagIds.size(), map.size()); + assertEquals(tagIds.size(), copy.size()); + for (long tagId : tagIds) { + String name = KnownTagCodec.nameOf(tagId); + if (KnownTagCodec.keyOf(name) != tagId) { + continue; // a name declared per direction does not resolve to either direction's id + } + assertEquals("value", map.getObject(name), name); + assertEquals("value", copy.getObject(name), name); + } + } + + private static List knownTagIds() throws IllegalAccessException { + List tagIds = new ArrayList<>(); + for (Field field : KnownTags.class.getFields()) { + if (field.getType() == long.class && Modifier.isStatic(field.getModifiers())) { + tagIds.add(field.getLong(null)); + } + } + return tagIds; + } + + @Test + void lookupsFindEntriesSetEitherWay() { + TagMap map = TagMap.create(); + map.set(KnownTags.HTTP_STATUS_CODE_ID, 5432); + map.set("my.custom.tag", "value"); + + assertEquals(5432, map.getEntry(KnownTags.HTTP_STATUS_CODE_NAME).intValue()); + assertEquals("value", map.getString("my.custom.tag")); + assertEquals(5432, map.getAndRemove(KnownTags.HTTP_STATUS_CODE_NAME).intValue()); + assertEquals(null, map.getEntry(KnownTags.HTTP_STATUS_CODE_NAME)); + } +}