diff --git a/sentry-jdbc/build.gradle.kts b/sentry-jdbc/build.gradle.kts index f58175c703d..6ccd959911e 100644 --- a/sentry-jdbc/build.gradle.kts +++ b/sentry-jdbc/build.gradle.kts @@ -32,6 +32,7 @@ dependencies { testImplementation(projects.sentryTestSupport) testImplementation(kotlin(Config.kotlinStdLib)) testImplementation(libs.awaitility.kotlin) + testImplementation(libs.google.truth) testImplementation(libs.hsqldb) testImplementation(libs.kotlin.test.junit) testImplementation(libs.mockito.kotlin) diff --git a/sentry-jdbc/src/main/java/io/sentry/jdbc/DatabaseUtils.java b/sentry-jdbc/src/main/java/io/sentry/jdbc/DatabaseUtils.java index 6325105205c..a782e4970ef 100644 --- a/sentry-jdbc/src/main/java/io/sentry/jdbc/DatabaseUtils.java +++ b/sentry-jdbc/src/main/java/io/sentry/jdbc/DatabaseUtils.java @@ -65,12 +65,10 @@ public static DatabaseDetails parse(final @Nullable String databaseConnectionUrl return parseAsUri(dbSystem, StringUtils.removePrefix(urlString, dbSystem + ":")); } if (urlParts.length > 2) { - String dbNameAndMaybeMore = urlParts[2]; - return new DatabaseDetails(dbSystem, StringUtils.substringBefore(dbNameAndMaybeMore, ";")); + return new DatabaseDetails(dbSystem, fileDbNameWithoutProperties(urlParts[2])); } if (urlParts.length > 1) { - String dbNameAndMaybeMore = urlParts[1]; - return new DatabaseDetails(dbSystem, StringUtils.substringBefore(dbNameAndMaybeMore, ";")); + return new DatabaseDetails(dbSystem, fileDbNameWithoutProperties(urlParts[1])); } } if ("mariadb".equalsIgnoreCase(dbSystem) @@ -119,13 +117,32 @@ public static DatabaseDetails parse(final @Nullable String databaseConnectionUrl return new DatabaseDetails(dbSystem, null); } + private static final char[] FILE_DB_NAME_PROPERTY_SEPARATORS = {';', '?', '#'}; + + /** + * Cuts connection properties off a database name: {@code ;} (H2, HSQLDB, Derby) and {@code ?} or + * {@code #} (SQLite and HSQLDB URIs). The properties can hold a database key or password. + */ + private static @Nullable String fileDbNameWithoutProperties( + final @NotNull String dbNameAndMaybeMore) { + int end = dbNameAndMaybeMore.length(); + for (final char separator : FILE_DB_NAME_PROPERTY_SEPARATORS) { + final int index = dbNameAndMaybeMore.indexOf(separator); + if (index >= 0 && index < end) { + end = index; + } + } + return end == 0 ? null : dbNameAndMaybeMore.substring(0, end); + } + private static @NotNull DatabaseDetails parseAsUri( final @NotNull String dbSystem, final @NotNull String urlString) { try { final @NotNull URI url = new URI(urlString); String path = StringUtils.removePrefix(url.getPath(), "/"); String pathWithoutProperties = StringUtils.substringBefore(path, ";"); - return new DatabaseDetails(dbSystem, pathWithoutProperties); + return new DatabaseDetails( + dbSystem, pathWithoutProperties.isEmpty() ? null : pathWithoutProperties); } catch (Throwable t) { // ignore } diff --git a/sentry-jdbc/src/main/java/io/sentry/jdbc/SentryJdbcEventListener.java b/sentry-jdbc/src/main/java/io/sentry/jdbc/SentryJdbcEventListener.java index 4206de18002..72558a06cc3 100644 --- a/sentry-jdbc/src/main/java/io/sentry/jdbc/SentryJdbcEventListener.java +++ b/sentry-jdbc/src/main/java/io/sentry/jdbc/SentryJdbcEventListener.java @@ -1,7 +1,9 @@ package io.sentry.jdbc; +import static io.sentry.SpanDataConvention.DB_NAMESPACE_KEY; import static io.sentry.SpanDataConvention.DB_NAME_KEY; import static io.sentry.SpanDataConvention.DB_SYSTEM_KEY; +import static io.sentry.SpanDataConvention.DB_SYSTEM_NAME_KEY; import com.jakewharton.nopen.annotation.Open; import com.p6spy.engine.common.ConnectionInformation; @@ -16,18 +18,36 @@ import io.sentry.SpanStatus; import io.sentry.util.AutoClosableReentrantLock; import io.sentry.util.Objects; +import io.sentry.util.SpanUtils; +import io.sentry.util.sql.SqlSpanData; import java.sql.SQLException; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @Open public class SentryJdbcEventListener extends SimpleJdbcEventListener { private static final String TRACE_ORIGIN = "auto.db.jdbc"; + + /** Maximum length of the sanitized query text, OpenTelemetry Java's value. */ + private static final int MAX_QUERY_TEXT_LENGTH = 32 * 1024; + private final @NotNull IScopes scopes; private static final @NotNull ThreadLocal CURRENT_QUERY_SPAN = new ThreadLocal<>(); private static final @NotNull ThreadLocal CURRENT_TRANSACTION_SPAN = new ThreadLocal<>(); - private volatile @Nullable DatabaseUtils.DatabaseDetails cachedDatabaseDetails = null; + /** + * p6spy shares one listener across all datasources of the JVM, so details are cached per + * connection URL. Bounded; URLs beyond the bound are parsed on every query. The keys are full + * connection URLs and may contain credentials: never log them. + */ + private static final int MAX_CACHED_DATABASE_DETAILS = 64; + + private final @NotNull Map databaseDetailsByUrl = + new ConcurrentHashMap<>(); + + /** Guards insertion into the details cache. */ protected final @NotNull AutoClosableReentrantLock databaseDetailsLock = new AutoClosableReentrantLock(); @@ -47,7 +67,21 @@ public SentryJdbcEventListener() { @Override public void onBeforeAnyExecute(final @NotNull StatementInformation statementInformation) { - startSpan(CURRENT_QUERY_SPAN, "db.query", statementInformation.getSql()); + final @Nullable ISpan parent = getActiveParent(); + if (parent == null) { + return; + } + final @NotNull DatabaseUtils.DatabaseDetails databaseDetails = + getOrComputeDatabaseDetails(statementInformation.getConnectionInformation()); + final @NotNull SqlSpanData queryData = + SqlSpanData.analyze( + statementInformation.getSql(), + databaseDetails.getDbSystem(), + MAX_QUERY_TEXT_LENGTH, + scopes.getOptions().getLogger()); + final @NotNull ISpan span = + startChild(parent, CURRENT_QUERY_SPAN, "db.query", queryData.getDescription()); + queryData.applyTo(span); } @Override @@ -133,13 +167,35 @@ private void startSpan( final @NotNull ThreadLocal spanHolder, final @NotNull String operation, final @Nullable String description) { - final @Nullable ISpan parent = scopes.getSpan(); - if (parent != null && !parent.isNoOp()) { - final @NotNull SpanOptions spanOptions = new SpanOptions(); - spanOptions.setOrigin(TRACE_ORIGIN); - final @NotNull ISpan span = parent.startChild(operation, description, spanOptions); - spanHolder.set(span); + final @Nullable ISpan parent = getActiveParent(); + if (parent != null) { + startChild(parent, spanHolder, operation, description); + } + } + + /** + * Returns the parent for a JDBC span, or {@code null} if no span would be recorded: no active + * span, or our origin is ignored (the default under OpenTelemetry), which would only yield a + * no-op child after the statement was analyzed. + */ + private @Nullable ISpan getActiveParent() { + if (SpanUtils.isIgnored(scopes.getOptions().getIgnoredSpanOriginFilters(), TRACE_ORIGIN)) { + return null; } + final @Nullable ISpan parent = scopes.getSpan(); + return parent != null && !parent.isNoOp() ? parent : null; + } + + private @NotNull ISpan startChild( + final @NotNull ISpan parent, + final @NotNull ThreadLocal spanHolder, + final @NotNull String operation, + final @Nullable String description) { + final @NotNull SpanOptions spanOptions = new SpanOptions(); + spanOptions.setOrigin(TRACE_ORIGIN); + final @NotNull ISpan span = parent.startChild(operation, description, spanOptions); + spanHolder.set(span); + return span; } private void finishSpan( @@ -171,25 +227,47 @@ private void applyDatabaseDetailsToSpan( final @NotNull DatabaseUtils.DatabaseDetails databaseDetails = getOrComputeDatabaseDetails(connectionInformation); - if (databaseDetails.getDbSystem() != null) { - span.setData(DB_SYSTEM_KEY, databaseDetails.getDbSystem()); + final @Nullable String dbSystem = databaseDetails.getDbSystem(); + if (dbSystem != null) { + span.setData(DB_SYSTEM_KEY, dbSystem); + final @Nullable String dbSystemName = SqlSpanData.toDbSystemName(dbSystem); + if (dbSystemName != null) { + span.setData(DB_SYSTEM_NAME_KEY, dbSystemName); + } } - if (databaseDetails.getDbName() != null) { - span.setData(DB_NAME_KEY, databaseDetails.getDbName()); + final @Nullable String dbName = databaseDetails.getDbName(); + if (dbName != null) { + span.setData(DB_NAME_KEY, dbName); + span.setData(DB_NAMESPACE_KEY, dbName); } } private @NotNull DatabaseUtils.DatabaseDetails getOrComputeDatabaseDetails( final @Nullable ConnectionInformation connectionInformation) { - if (cachedDatabaseDetails == null) { - try (final @NotNull ISentryLifecycleToken ignored = databaseDetailsLock.acquire()) { - if (cachedDatabaseDetails == null) { - cachedDatabaseDetails = DatabaseUtils.readFrom(connectionInformation); - } + final @Nullable String url = + connectionInformation == null ? null : connectionInformation.getUrl(); + if (url == null) { + return DatabaseUtils.readFrom(connectionInformation); + } + final @Nullable DatabaseUtils.DatabaseDetails cached = databaseDetailsByUrl.get(url); + if (cached != null) { + return cached; + } + if (databaseDetailsByUrl.size() >= MAX_CACHED_DATABASE_DETAILS) { + return DatabaseUtils.readFrom(connectionInformation); + } + try (final @NotNull ISentryLifecycleToken ignored = databaseDetailsLock.acquire()) { + final @Nullable DatabaseUtils.DatabaseDetails existing = databaseDetailsByUrl.get(url); + if (existing != null) { + return existing; } + final @NotNull DatabaseUtils.DatabaseDetails details = + DatabaseUtils.readFrom(connectionInformation); + if (databaseDetailsByUrl.size() < MAX_CACHED_DATABASE_DETAILS) { + databaseDetailsByUrl.put(url, details); + } + return details; } - - return cachedDatabaseDetails; } } diff --git a/sentry-jdbc/src/test/kotlin/io/sentry/jdbc/DatabaseUtilsTest.kt b/sentry-jdbc/src/test/kotlin/io/sentry/jdbc/DatabaseUtilsTest.kt index 27a6ac69708..cdde38e9573 100644 --- a/sentry-jdbc/src/test/kotlin/io/sentry/jdbc/DatabaseUtilsTest.kt +++ b/sentry-jdbc/src/test/kotlin/io/sentry/jdbc/DatabaseUtilsTest.kt @@ -1,5 +1,6 @@ package io.sentry.jdbc +import com.google.common.truth.Truth.assertWithMessage import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNotNull @@ -109,7 +110,14 @@ class DatabaseUtilsTest { fun `detects db system for mongo no db`() { val details = DatabaseUtils.parse("jdbc:mongo://some-server.com:1234") assertEquals("mongo", details.dbSystem) - assertEquals("", details.dbName) + assertNull(details.dbName) + } + + @Test + fun `detects db system for postgres without database`() { + val details = DatabaseUtils.parse("jdbc:postgresql://localhost:5432/") + assertEquals("postgresql", details.dbSystem) + assertNull(details.dbName) } @Test @@ -264,4 +272,24 @@ class DatabaseUtilsTest { assertEquals("sqlserver", details.dbSystem) assertEquals("my_database", details.dbName) } + + @Test + fun `keeps connection properties out of file-based database names`() { + // url to expected db.name; the properties may hold the database key or password + val cases = + listOf( + "jdbc:sqlite:sample.db?journal_mode=WAL&password=secret" to "sample.db", + "jdbc:sqlite:/data/app.db?key=secret" to "/data/app.db", + "jdbc:sqlite:file:/data/app.db?key=secret#frag" to "/data/app.db", + "jdbc:sqlite:file:/data/app.db#secret" to "/data/app.db", + "jdbc:sqlite:file::memory:?cache=shared" to null, + "jdbc:p6spy:sqlite:sample.db?password=secret" to "sample.db", + "jdbc:hsqldb:file:db?password=secret" to "db", + "jdbc:h2:file:/data/app?key=secret" to "/data/app", + ) + + cases.forEach { (url, dbName) -> + assertWithMessage(url).that(DatabaseUtils.parse(url).dbName).isEqualTo(dbName) + } + } } diff --git a/sentry-jdbc/src/test/kotlin/io/sentry/jdbc/SentryJdbcEventListenerTest.kt b/sentry-jdbc/src/test/kotlin/io/sentry/jdbc/SentryJdbcEventListenerTest.kt index 22ee97e5d47..85366f906b3 100644 --- a/sentry-jdbc/src/test/kotlin/io/sentry/jdbc/SentryJdbcEventListenerTest.kt +++ b/sentry-jdbc/src/test/kotlin/io/sentry/jdbc/SentryJdbcEventListenerTest.kt @@ -1,16 +1,27 @@ package io.sentry.jdbc +import com.google.common.truth.Truth.assertThat +import com.google.common.truth.Truth.assertWithMessage import com.p6spy.engine.common.ConnectionInformation +import com.p6spy.engine.common.StatementInformation import com.p6spy.engine.spy.P6DataSource import io.sentry.IScopes import io.sentry.SentryOptions import io.sentry.SentryTracer +import io.sentry.SpanDataConvention.DB_NAMESPACE_KEY import io.sentry.SpanDataConvention.DB_NAME_KEY +import io.sentry.SpanDataConvention.DB_QUERY_SUMMARY_KEY +import io.sentry.SpanDataConvention.DB_QUERY_TEXT_KEY +import io.sentry.SpanDataConvention.DB_STORED_PROCEDURE_NAME_KEY import io.sentry.SpanDataConvention.DB_SYSTEM_KEY +import io.sentry.SpanDataConvention.DB_SYSTEM_NAME_KEY import io.sentry.SpanStatus import io.sentry.TransactionContext import io.sentry.jdbc.DatabaseUtils.DatabaseDetails import io.sentry.protocol.SdkVersion +import io.sentry.util.sql.SqlQueryAnalyzer +import io.sentry.vendor.otel.sql.OtelSqlSanitizer +import java.sql.Driver import javax.sql.DataSource import kotlin.test.AfterTest import kotlin.test.Test @@ -21,6 +32,8 @@ import org.hsqldb.jdbc.JDBCDataSource import org.mockito.Mockito import org.mockito.kotlin.any import org.mockito.kotlin.mock +import org.mockito.kotlin.never +import org.mockito.kotlin.verify import org.mockito.kotlin.whenever class SentryJdbcEventListenerTest { @@ -29,7 +42,7 @@ class SentryJdbcEventListenerTest { val scopes = mock().apply { whenever(this.options).thenAnswer { this@Fixture.options } } lateinit var tx: SentryTracer - val actualDataSource = JDBCDataSource() + val actualDataSource = JDBCDataSource().apply { setURL("jdbc:hsqldb:mem:testdb") } fun getSut( withRunningTransaction: Boolean = true, @@ -45,8 +58,6 @@ class SentryJdbcEventListenerTest { if (withRunningTransaction) { whenever(scopes.span).thenReturn(tx) } - actualDataSource.setURL("jdbc:hsqldb:mem:testdb") - actualDataSource.connection.use { it.prepareStatement("CREATE TABLE foo (id int unique)").execute() } @@ -63,13 +74,125 @@ class SentryJdbcEventListenerTest { p6spyDataSource.setJdbcEventListenerFactory { sentryQueryExecutionListener } return p6spyDataSource } + + /** A listener under a running transaction, driven through its p6spy callbacks directly. */ + fun getListener(): SentryJdbcEventListener { + options = SentryOptions().apply { sdkVersion = SdkVersion("test", "1.2.3") } + tx = SentryTracer(TransactionContext("name", "op"), scopes) + whenever(scopes.span).thenReturn(tx) + return SentryJdbcEventListener(scopes) + } } private val fixture = Fixture() @AfterTest fun clean() { - fixture.actualDataSource.connection.use { it.prepareStatement("drop table foo").execute() } + fixture.actualDataSource.connection.use { + it.prepareStatement("drop table foo if exists").execute() + } + } + + /** Runs one statement the way p6spy reports it: before and after execute, same connection. */ + private fun SentryJdbcEventListener.execute(url: String?, sql: String) { + val connection = ConnectionInformation.fromDriver(null as Driver?).apply { setUrl(url) } + val statement = StatementInformation(connection).apply { statementQuery = sql } + onBeforeAnyExecute(statement) + onAfterAnyExecute(statement, 0, null) + } + + @Test + fun `analyzes each statement in the dialect of its connection URL`() { + // Double quotes delimit strings in MySQL and identifiers in PostgreSQL. + val sql = "SELECT a FROM t WHERE p = \"secret\"" + val asPostgres = SqlQueryAnalyzer.analyze(sql, "postgresql", LIMIT).queryText + val asMysql = SqlQueryAnalyzer.analyze(sql, "mysql", LIMIT).queryText + assertThat(asMysql).isNotEqualTo(asPostgres) + val sut = fixture.getListener() + + sut.execute("jdbc:postgresql://localhost:5432/orders", sql) + sut.execute("jdbc:mysql://localhost:3306/users", sql) + + assertThat(fixture.tx.children).hasSize(2) + val (postgres, mysql) = fixture.tx.children + assertThat(postgres.description).isEqualTo(asPostgres) + assertThat(postgres.data).containsAtLeast(DB_SYSTEM_KEY, "postgresql", DB_NAME_KEY, "orders") + assertThat(mysql.description).isEqualTo(asMysql) + assertThat(mysql.data).containsAtLeast(DB_SYSTEM_KEY, "mysql", DB_NAME_KEY, "users") + } + + @Test + fun `does not read the statement when the jdbc span origin is ignored`() { + // OpenTelemetry's AGENT and AGENTLESS_SPRING modes ignore auto.db.jdbc by default + val sut = fixture.getListener() + fixture.options.setIgnoredSpanOrigins(listOf("auto.db.jdbc")) + val connection = mock() + val statement = + mock().apply { + whenever(connectionInformation).thenReturn(connection) + } + + sut.onBeforeAnyExecute(statement) + sut.onAfterAnyExecute(statement, 0, null) + + verify(statement, never()).sql + verify(connection, never()).url + assertThat(fixture.tx.children).isEmpty() + } + + @Test + fun `resolves database details for more connection URLs than are cached`() { + // 65 URLs (url, db.system, db.name), alternating systems so a wrong entry shows + val connections = + (0..64).map { + if (it % 2 == 0) Triple("jdbc:postgresql://h/db$it", "postgresql", "db$it") + else Triple("jdbc:mysql://h/db$it", "mysql", "db$it") + } + val sut = fixture.getListener() + + repeat(2) { connections.forEach { (url, _, _) -> sut.execute(url, "SELECT 1") } } + + assertThat(fixture.tx.children).hasSize(2 * connections.size) + (connections + connections).zip(fixture.tx.children).forEach { (connection, span) -> + val (url, dbSystem, dbName) = connection + assertWithMessage(url).that(span.data[DB_SYSTEM_KEY]).isEqualTo(dbSystem) + assertWithMessage(url).that(span.data[DB_NAME_KEY]).isEqualTo(dbName) + } + } + + @Test + fun `analyzes statements on a connection without URL`() { + val sql = "SELECT * FROM users WHERE email = 'Zq9xK7@x.io'" + val sut = fixture.getListener() + + sut.execute(null, sql) + + val span = fixture.tx.children.single() + assertThat(span.description).isEqualTo(SqlQueryAnalyzer.analyze(sql, null, LIMIT).queryText) + assertThat(span.data).doesNotContainKey(DB_SYSTEM_KEY) + } + + @Test + fun `keeps the raw statement off the span when the analysis fails`() { + val sql = "SELECT * FROM users WHERE email = 'Zq9xK7@x.io'" + val sut = fixture.getListener() + + Mockito.mockStatic(OtelSqlSanitizer::class.java).use { sanitizer -> + sanitizer + .`when` { OtelSqlSanitizer.sanitize(any(), any()) } + .thenThrow(IllegalStateException("lexer bug")) + + sut.execute("jdbc:postgresql://localhost/app", sql) + } + + val span = fixture.tx.children.single() + assertThat(span.description).isNull() + assertThat(span.data.keys) + .containsNoneOf(DB_QUERY_TEXT_KEY, DB_QUERY_SUMMARY_KEY, DB_STORED_PROCEDURE_NAME_KEY) + span.data.forEach { (key, value) -> + assertWithMessage(key).that(value.toString()).doesNotContain("Zq9xK7") + } + assertThat(span.data).containsEntry(DB_SYSTEM_KEY, "postgresql") } @Test @@ -86,8 +209,8 @@ class SentryJdbcEventListenerTest { assertEquals(SpanStatus.OK, it.status) assertEquals("db.query", it.operation) } - assertEquals("INSERT INTO foo VALUES (1)", fixture.tx.children[0].description) - assertEquals("INSERT INTO foo VALUES (2)", fixture.tx.children[1].description) + assertEquals(hsqldbText("INSERT INTO foo VALUES (1)"), fixture.tx.children[0].description) + assertEquals(hsqldbText("INSERT INTO foo VALUES (2)"), fixture.tx.children[1].description) } @Test @@ -100,7 +223,7 @@ class SentryJdbcEventListenerTest { assertEquals(1, fixture.tx.children.size) assertEquals(SpanStatus.INTERNAL_ERROR, fixture.tx.children[0].status) - assertEquals("INSERT INTO foo VALUES (1)", fixture.tx.children[0].description) + assertEquals(hsqldbText("INSERT INTO foo VALUES (1)"), fixture.tx.children[0].description) assertEquals("db.query", fixture.tx.children[0].operation) } @@ -139,13 +262,28 @@ class SentryJdbcEventListenerTest { } @Test - fun `sets database details`() { + fun `sets database details and query data`() { + val sql = "INSERT INTO foo VALUES (1)" + val expected = SqlQueryAnalyzer.analyze(sql, "hsqldb", LIMIT) val sut = fixture.getSut() - sut.connection.use { it.prepareStatement("INSERT INTO foo VALUES (1)").executeUpdate() } - - assertEquals("hsqldb", fixture.tx.children.first().data[DB_SYSTEM_KEY]) - assertEquals("testdb", fixture.tx.children.first().data[DB_NAME_KEY]) + sut.connection.use { it.prepareStatement(sql).executeUpdate() } + + assertThat(fixture.tx.children.first().data) + .containsAtLeast( + DB_SYSTEM_KEY, + "hsqldb", + DB_SYSTEM_NAME_KEY, + "hsqldb", + DB_NAME_KEY, + "testdb", + DB_NAMESPACE_KEY, + "testdb", + DB_QUERY_TEXT_KEY, + expected.queryText, + DB_QUERY_SUMMARY_KEY, + expected.querySummary, + ) } @Test @@ -368,4 +506,12 @@ class SentryJdbcEventListenerTest { val querySpans = fixture.tx.children.filter { it.operation == "db.query" } assertEquals(1, querySpans.size) } + + private fun hsqldbText(sql: String): String? = + SqlQueryAnalyzer.analyze(sql, "hsqldb", LIMIT).queryText + + private companion object { + /** The listener's limit for the sanitized text. */ + const val LIMIT = 32 * 1024 + } } diff --git a/sentry-spring-boot-4/src/integrationTest/kotlin/io/sentry/spring/boot4/integrationtest/PersonIntegrationTest.kt b/sentry-spring-boot-4/src/integrationTest/kotlin/io/sentry/spring/boot4/integrationtest/PersonIntegrationTest.kt index 320bf002be4..24050bb8a3d 100644 --- a/sentry-spring-boot-4/src/integrationTest/kotlin/io/sentry/spring/boot4/integrationtest/PersonIntegrationTest.kt +++ b/sentry-spring-boot-4/src/integrationTest/kotlin/io/sentry/spring/boot4/integrationtest/PersonIntegrationTest.kt @@ -14,6 +14,7 @@ import io.sentry.test.hasSpanWithOpAndDescription import io.sentry.test.logs import io.sentry.test.profileChunk import io.sentry.test.transaction +import io.sentry.util.sql.SqlQueryAnalyzer import kotlin.test.Test class PersonIntegrationTest : IntegrationTest() { @@ -93,10 +94,17 @@ class PersonIntegrationTest : IntegrationTest() { assertThat(transaction.contexts.trace!!.data[SpanDataConvention.HTTP_STATUS_CODE_KEY]) .isEqualTo(200) assertThat(transaction.hasSpanWithOp("PersonService.create")).isTrue() + val insert = + SqlQueryAnalyzer.analyze( + "insert into person (firstName, lastName) values (?, ?)", + "hsqldb", + 32 * 1024, + ) assertThat( transaction.hasSpanWithOpAndDescription( "db.query", - "insert into person (firstName, lastName) values (?, ?)", + insert.queryText!!, + mapOf("db.query.summary" to insert.querySummary!!, "db.system.name" to "hsqldb"), ), ) .isTrue() diff --git a/sentry-spring-boot-4/src/integrationTestOtlp/kotlin/io/sentry/spring/boot4/otlpintegrationtest/PersonIntegrationTest.kt b/sentry-spring-boot-4/src/integrationTestOtlp/kotlin/io/sentry/spring/boot4/otlpintegrationtest/PersonIntegrationTest.kt index 5cf00447acb..35d59357075 100644 --- a/sentry-spring-boot-4/src/integrationTestOtlp/kotlin/io/sentry/spring/boot4/otlpintegrationtest/PersonIntegrationTest.kt +++ b/sentry-spring-boot-4/src/integrationTestOtlp/kotlin/io/sentry/spring/boot4/otlpintegrationtest/PersonIntegrationTest.kt @@ -14,6 +14,7 @@ import io.sentry.test.hasSpanWithOpAndDescription import io.sentry.test.logs import io.sentry.test.profileChunk import io.sentry.test.transaction +import io.sentry.util.sql.SqlQueryAnalyzer import kotlin.test.Test import org.springframework.http.HttpEntity import org.springframework.http.HttpHeaders @@ -113,10 +114,17 @@ class PersonIntegrationTest : IntegrationTest() { val transaction = server.awaitEnvelope { it.transaction()?.transaction == "POST /person/" }.transaction()!! assertThat(transaction.hasSpanWithOp("PersonService.create")).isTrue() + val insert = + SqlQueryAnalyzer.analyze( + "insert into person (firstName, lastName) values (?, ?)", + "hsqldb", + 32 * 1024, + ) assertThat( transaction.hasSpanWithOpAndDescription( "db.query", - "insert into person (firstName, lastName) values (?, ?)", + insert.queryText!!, + mapOf("db.query.summary" to insert.querySummary!!, "db.system.name" to "hsqldb"), ), ) .isTrue() diff --git a/sentry-spring-boot-jakarta/src/integrationTest/kotlin/io/sentry/spring/boot/jakarta/integrationtest/PersonIntegrationTest.kt b/sentry-spring-boot-jakarta/src/integrationTest/kotlin/io/sentry/spring/boot/jakarta/integrationtest/PersonIntegrationTest.kt index bb4e3a985c0..1e3091f8540 100644 --- a/sentry-spring-boot-jakarta/src/integrationTest/kotlin/io/sentry/spring/boot/jakarta/integrationtest/PersonIntegrationTest.kt +++ b/sentry-spring-boot-jakarta/src/integrationTest/kotlin/io/sentry/spring/boot/jakarta/integrationtest/PersonIntegrationTest.kt @@ -14,6 +14,7 @@ import io.sentry.test.hasSpanWithOpAndDescription import io.sentry.test.logs import io.sentry.test.profileChunk import io.sentry.test.transaction +import io.sentry.util.sql.SqlQueryAnalyzer import kotlin.test.Test class PersonIntegrationTest : IntegrationTest() { @@ -93,10 +94,17 @@ class PersonIntegrationTest : IntegrationTest() { assertThat(transaction.contexts.trace!!.data[SpanDataConvention.HTTP_STATUS_CODE_KEY]) .isEqualTo(200) assertThat(transaction.hasSpanWithOp("PersonService.create")).isTrue() + val insert = + SqlQueryAnalyzer.analyze( + "insert into person (firstName, lastName) values (?, ?)", + "hsqldb", + 32 * 1024, + ) assertThat( transaction.hasSpanWithOpAndDescription( "db.query", - "insert into person (firstName, lastName) values (?, ?)", + insert.queryText!!, + mapOf("db.query.summary" to insert.querySummary!!, "db.system.name" to "hsqldb"), ), ) .isTrue() diff --git a/sentry-spring-boot/src/integrationTest/kotlin/io/sentry/spring/boot/integrationtest/PersonIntegrationTest.kt b/sentry-spring-boot/src/integrationTest/kotlin/io/sentry/spring/boot/integrationtest/PersonIntegrationTest.kt index 6636c4fe28f..a16b35dd7f7 100644 --- a/sentry-spring-boot/src/integrationTest/kotlin/io/sentry/spring/boot/integrationtest/PersonIntegrationTest.kt +++ b/sentry-spring-boot/src/integrationTest/kotlin/io/sentry/spring/boot/integrationtest/PersonIntegrationTest.kt @@ -14,6 +14,7 @@ import io.sentry.test.hasSpanWithOpAndDescription import io.sentry.test.logs import io.sentry.test.profileChunk import io.sentry.test.transaction +import io.sentry.util.sql.SqlQueryAnalyzer import kotlin.test.Test class PersonIntegrationTest : IntegrationTest() { @@ -93,10 +94,17 @@ class PersonIntegrationTest : IntegrationTest() { assertThat(transaction.contexts.trace!!.data[SpanDataConvention.HTTP_STATUS_CODE_KEY]) .isEqualTo(200) assertThat(transaction.hasSpanWithOp("PersonService.create")).isTrue() + val insert = + SqlQueryAnalyzer.analyze( + "insert into person (firstName, lastName) values (?, ?)", + "hsqldb", + 32 * 1024, + ) assertThat( transaction.hasSpanWithOpAndDescription( "db.query", - "insert into person (firstName, lastName) values (?, ?)", + insert.queryText!!, + mapOf("db.query.summary" to insert.querySummary!!, "db.system.name" to "hsqldb"), ), ) .isTrue() diff --git a/sentry-test-support/src/main/kotlin/io/sentry/test/EnvelopeMatchers.kt b/sentry-test-support/src/main/kotlin/io/sentry/test/EnvelopeMatchers.kt index 16f7642f358..dc684d3092a 100644 --- a/sentry-test-support/src/main/kotlin/io/sentry/test/EnvelopeMatchers.kt +++ b/sentry-test-support/src/main/kotlin/io/sentry/test/EnvelopeMatchers.kt @@ -69,13 +69,25 @@ fun SentryTransaction.hasSpanWithOp( return featureFlag == null || matchesFlag(data, featureFlag) } -fun SentryTransaction.hasSpanWithOpAndDescription(op: String, description: String): Boolean { - if (spans.none { it.op == op && it.description == description }) { +/** Matches a span with [op] and [description] whose data contains every entry of [data]. */ +fun SentryTransaction.hasSpanWithOpAndDescription( + op: String, + description: String, + data: Map = emptyMap(), +): Boolean { + val candidates = spans.filter { it.op == op && it.description == description } + if (candidates.isEmpty()) { return mismatch( "Unable to find span with op $op and description $description in transaction:", this, ) } + if (candidates.none { span -> data.all { (key, value) -> span.data?.get(key) == value } }) { + return mismatch( + "No span with op $op and description $description has data $data in transaction:", + this, + ) + } return true } diff --git a/sentry-test-support/src/test/kotlin/io/sentry/test/EnvelopeMatchersTest.kt b/sentry-test-support/src/test/kotlin/io/sentry/test/EnvelopeMatchersTest.kt index f5e56d31a1c..31604cca149 100644 --- a/sentry-test-support/src/test/kotlin/io/sentry/test/EnvelopeMatchersTest.kt +++ b/sentry-test-support/src/test/kotlin/io/sentry/test/EnvelopeMatchersTest.kt @@ -47,6 +47,38 @@ class EnvelopeMatchersTest { assertThat(received.hasSpanWithOp("db.query", noFeatureFlags = true)).isFalse() } + @Test + fun `matches span data on any span with the op and description`() { + val transaction = Sentry.startTransaction("name", "http.server") + for (system in listOf("postgresql", "mysql")) { + transaction.startChild("db.query", "select 1").apply { + setData("db.system.name", system) + finish() + } + } + transaction.finish() + Sentry.flush(5000) + + val received = server.awaitEnvelope { it.transaction() != null }.transaction()!! + + assertThat( + received.hasSpanWithOpAndDescription( + "db.query", + "select 1", + mapOf("db.system.name" to "mysql"), + ), + ) + .isTrue() + assertThat( + received.hasSpanWithOpAndDescription( + "db.query", + "select 1", + mapOf("db.system.name" to "h2"), + ), + ) + .isFalse() + } + @Test fun `matches an event by exception message and feature flag`() { Sentry.addFeatureFlag("my-flag", true)