From 51d9f7b67d1a74411c5db416d05d68ab5773b405 Mon Sep 17 00:00:00 2001 From: Pavel Lavreshin Date: Sat, 14 Nov 2026 09:13:54 +0200 Subject: [PATCH 01/12] feat(micronaut): add Micronaut 4 and 5 support --- .github/workflows/ci.yml | 25 ++- .github/workflows/release.yml | 4 +- CHANGELOG.md | 11 + README.md | 74 ++++++- settings.gradle.kts | 2 +- .../main/java/dev/tracepanel/core/Stacks.java | 2 +- tracepanel-micronaut/build.gradle.kts | 92 +++++++++ .../dev/tracepanel/micronaut/DataSources.java | 26 +++ .../tracepanel/micronaut/TraceContext.java | 18 ++ .../micronaut/TracepanelClientFilter.java | 41 ++++ .../micronaut/TracepanelConfiguration.java | 28 +++ .../micronaut/TracepanelEnabled.java | 28 +++ .../micronaut/TracepanelServerFilter.java | 191 ++++++++++++++++++ .../tracepanel/micronaut/DataSourcesTest.java | 85 ++++++++ .../dev/tracepanel/micronaut/FilterTest.java | 162 +++++++++++++++ .../micronaut/TracepanelEnabledTest.java | 34 ++++ .../test/java/shop/MicronautTracingTest.java | 129 ++++++++++++ 17 files changed, 937 insertions(+), 15 deletions(-) create mode 100644 tracepanel-micronaut/build.gradle.kts create mode 100644 tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/DataSources.java create mode 100644 tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TraceContext.java create mode 100644 tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelClientFilter.java create mode 100644 tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelConfiguration.java create mode 100644 tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelEnabled.java create mode 100644 tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelServerFilter.java create mode 100644 tracepanel-micronaut/src/test/java/dev/tracepanel/micronaut/DataSourcesTest.java create mode 100644 tracepanel-micronaut/src/test/java/dev/tracepanel/micronaut/FilterTest.java create mode 100644 tracepanel-micronaut/src/test/java/dev/tracepanel/micronaut/TracepanelEnabledTest.java create mode 100644 tracepanel-micronaut/src/test/java/shop/MicronautTracingTest.java diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 5514cde..9a2e26c 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -85,10 +85,27 @@ jobs: - if: matrix.java == '21' run: ./gradlew publishToMavenLocal --console=plain + micronaut5: + name: Micronaut 5 on Java 25 + needs: changes + if: needs.changes.outputs.code == 'true' + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-java@v6 + with: + distribution: temurin + java-version: | + 25 + 21 + - uses: gradle/actions/setup-gradle@v6 + - run: ./gradlew :tracepanel-micronaut:testMicronaut5 :tracepanel-micronaut:testMicronaut5Integration --console=plain -Porg.gradle.java.installations.fromEnv=JAVA_HOME_25_X64 + # The branch's required check: every Java's tests passed, or the build was skipped. check: name: Build and test - needs: [changes, test] + needs: [changes, test, micronaut5] if: always() runs-on: ubuntu-latest timeout-minutes: 5 @@ -96,4 +113,8 @@ jobs: - env: CHANGES: ${{ needs.changes.result }} TEST: ${{ needs.test.result }} - run: test "$CHANGES" = success && { test "$TEST" = success || test "$TEST" = skipped; } + MICRONAUT: ${{ needs.micronaut5.result }} + run: >- + test "$CHANGES" = success && + { test "$TEST" = success || test "$TEST" = skipped; } && + { test "$MICRONAUT" = success || test "$MICRONAUT" = skipped; } diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 5f1d5c3..a4c7e1c 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -110,8 +110,8 @@ jobs: run: | unzip -q bundle/*.zip -d files find files -type f \( -name '*.jar' -o -name '*.pom' -o -name '*.module' \) | sort | tee subjects.txt - # Five of each module: tracepanel-core, tracepanel-spring-boot, tracepanel-ktor and tracepanel-junit. - [ "$(wc -l < subjects.txt)" -ge 20 ] || { echo "::error::fewer than 20 files in the bundle" && exit 1; } + # Five of each module: tracepanel-core, tracepanel-spring-boot, tracepanel-ktor, tracepanel-junit and tracepanel-micronaut. + [ "$(wc -l < subjects.txt)" -ge 25 ] || { echo "::error::fewer than 25 files in the bundle" && exit 1; } - uses: actions/attest@v4 with: subject-path: | diff --git a/CHANGELOG.md b/CHANGELOG.md index a12020c..7042c60 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## Unreleased + +### Added + +- `tracepanel-micronaut` for Micronaut 4 and 5: route-named request traces, + JDBC statements and transactions, declarative HTTP clients, Logback, + request principals, the badge and the console. The SDK starts in dev, + development or local environments, or with `TRACEPANEL_ENABLED=1`. +- A Micronaut 5 test suite on Java 25 in CI. The module still compiles for + Java 17 for Micronaut 4 applications. + ## 0.16.0 (2026-11-10) ### Changed diff --git a/README.md b/README.md index 043b82e..c23a81f 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ [![Maven Central](https://img.shields.io/maven-central/v/dev.tracepanel/tracepanel-core)](https://central.sonatype.com/namespace/dev.tracepanel) [![Java](https://img.shields.io/badge/java-17%2B-blue)](https://github.com/tracepanel/tracepanel-java#tracepanel-for-java) -**See what your Spring Boot or Ktor app is really doing.** Tracepanel records +**See what your Spring Boot, Micronaut or Ktor app is doing.** Tracepanel records each request, `@Async` task, scheduled job and message of your app, in Java or Kotlin, with its SQL queries, Redis and MongoDB commands, outgoing HTTP calls, logs and errors. It points out N+1 queries, duplicates, slow SQL and long @@ -22,11 +22,11 @@ It runs while you develop, and everything stays on your machine. | | Supported | | --- | --- | | **Java** | 17 and later, apps in Java or Kotlin. | -| **Frameworks** | Spring Boot 3.5 and 4 with Spring MVC, Kotlin suspend functions, `Callable` and `DeferredResult` handlers included. Ktor 3. WebFlux apps aren't supported yet. | +| **Frameworks** | Spring Boot 3.5 and 4 with Spring MVC, Kotlin suspend functions, `Callable` and `DeferredResult` handlers included. Ktor 3. Micronaut 4.10 and 5 with Netty and declarative HTTP clients. Micronaut 5 requires Java 25. WebFlux apps aren't supported yet. | | **Databases** | SQL through JDBC, whatever runs it: Spring Data JPA, Hibernate, `JdbcTemplate`, jOOQ, Exposed. Transactions. EXPLAIN on PostgreSQL, MySQL, H2 and SQLite of a SELECT or a `WITH … SELECT` that changes no data (ANALYZE rolled back). | | **Redis and MongoDB** | Lettuce (Spring Data Redis, the cache) and Spring Data MongoDB, with their own N+1 and duplicates. | | **Messaging** | Kafka and RabbitMQ: what a `KafkaTemplate` or a `RabbitTemplate` sends, and each message a `@KafkaListener` or `@RabbitListener` receives as a trace of its own, linked to the one that sent it. | -| **HTTP clients** | `RestClient`, `RestTemplate`, `WebClient` and the JDK's `HttpClient`, each call with a `traceparent`. Ktor's client through `TracepanelClient`. | +| **HTTP clients** | `RestClient`, `RestTemplate`, `WebClient` and the JDK's `HttpClient`, each call with a `traceparent`. Ktor's client through `TracepanelClient`. Micronaut declarative `@Client` calls. | | **Background work** | `@Async` methods as tasks, linked to the request that queued them; `@Scheduled` methods, `CommandLineRunner`s and `ApplicationRunner`s as jobs; the tasks in flight listed live. | | **Logs** | Logback and Log4j 2, each record on the request or task that made it, with its line, MDC and exception. | | **Errors** | Thrown in a handler, with your frames and the source around them. | @@ -96,6 +96,30 @@ off, even if the dependency reached the build by mistake, and says so once in the log. `TRACEPANEL_ENABLED=1` turns it on anyway, `TRACEPANEL_ENABLED=0` off. +### Micronaut + +The new `tracepanel-micronaut` module is available from this checkout. It has +not been published yet. See the [Micronaut store example](https://github.com/tracepanel/tracepanel-examples/tree/main/micronaut-app) +for a composite build with the local SDK. + +With the Micronaut Gradle plugin, add the module for development only: + +```kotlin +dependencies { + developmentOnly("dev.tracepanel:tracepanel-micronaut:0.16.0") +} +``` + +Use your app's Micronaut platform BOM so its Reactor integration matches +its framework version. Run with `micronaut.environments=dev`, for example +`MICRONAUT_ENVIRONMENTS=dev ./gradlew run`. The SDK also starts in the +`development` and `local` environments. `TRACEPANEL_ENABLED=1` enables it +in another environment. `TRACEPANEL_ENABLED=0` disables it in every environment. + +Micronaut finds the SDK's beans without application code. Open an HTML page +for the badge, or `/__tracepanel__/` for the console. Micronaut 4 uses the +SDK's Java 17 baseline. Micronaut 5 requires Java 25. + ### Ktor Install the plugin. Ktor has no dependency injection to find your DataSource @@ -152,6 +176,29 @@ fix: - The signed-in user from Spring Security, or `Tracepanel.setUser(id, username)`. +### Micronaut + +- Each request, named by its matched route and controller method. +- JDBC statements and transactions through `DataSource` beans, including + Micronaut Hikari pools and `JdbcTemplate`. +- Declarative `@Client` calls, with W3C `traceparent` and profile headers. +- Logback records and controller errors on the current trace. +- A user set through Micronaut's request principal. +- Context across Micronaut's blocking executors and Reactor publishers. +- The console, response headers, and the badge on HTML held as a `String` + or `byte[]`. Streaming responses and static file bodies are not buffered + for badge injection. + +Declare custom data source factory return types as `DataSource`. A bean +exposed as a concrete pool class cannot accept the SDK's interface wrapper; +the SDK leaves it unchanged and logs a warning. Request capture records +headers, query parameters and cookies. It captures an already decoded +`String` or `byte[]` body, without reading application request streams. + +Redis, messaging, scheduled jobs and detached application tasks are outside +this module's current scope. The Spring integrations listed above do not imply +Micronaut support for those APIs. + ### Ktor - Each call, named by its route (`GET /books/{id}`), its coroutines included. @@ -360,8 +407,8 @@ The same environment variables as the other Tracepanel SDKs: | Variable | Default | What it sets | | --- | --- | --- | -| `TRACEPANEL_ENABLED` | in development (a `dev` or `local` profile or DevTools; Ktor's development mode) | `0` turns Tracepanel off, `1` on | -| `TRACEPANEL_SERVICE` | `spring.application.name`, or Ktor's `ktor.application.id` | the app's name in the console | +| `TRACEPANEL_ENABLED` | in development (Spring's dev profiles or DevTools, Micronaut's dev environments, or Ktor's development mode) | `0` turns Tracepanel off, `1` on | +| `TRACEPANEL_SERVICE` | `spring.application.name`, `micronaut.application.name`, or `ktor.application.id` | the app's name in the console | | `TRACEPANEL_DIR` | `.tracepanel` | the project's store, where the agent keeps the traces | | `TRACEPANEL_AGENT_BIN` | the one the SDK downloads | the agent to start, such as a build of your own | | `TRACEPANEL_AGENT` | `auto` | an agent elsewhere (`tcp:host:port`), never started | @@ -439,8 +486,17 @@ the same in every framework, under ./gradlew check ``` -It runs the tests on Spring Boot 4 and on 3.5, and on Ktor. The tests of -MongoDB, Redis, Kafka and RabbitMQ need a server of each: +It runs the tests on Spring Boot 4 and on 3.5, Ktor and Micronaut 4. +With Java 25 installed, test the same module against Micronaut 5: + +```bash +./gradlew :tracepanel-micronaut:testMicronaut5 :tracepanel-micronaut:testMicronaut5Integration +``` + +CI runs both Micronaut versions. Integration tests use a local fake agent +and run in a separate JVM from unit tests. + +The tests of MongoDB, Redis, Kafka and RabbitMQ need a server of each: `TEST_MONGODB_URI=mongodb://127.0.0.1:27017/test`, `TEST_REDIS_PORT=6379`, `TEST_KAFKA_BOOTSTRAP=localhost:9092` and `TEST_RABBITMQ_PORT=5672`. The tests of the console's Live and EXPLAIN with the real agent need its @@ -450,8 +506,8 @@ writes the checksums of that version's downloads. `tracepanel-core` records traces and talks to the agent, with no framework and no dependencies. `tracepanel-spring-boot` is the Spring Boot -integration, `tracepanel-ktor` the Ktor one, and `tracepanel-junit` the -JUnit extension. The extension's tests with the real agent download it, as +integration, `tracepanel-micronaut` the Micronaut one, `tracepanel-ktor` the +Ktor one, and `tracepanel-junit` the JUnit extension. The extension's tests with the real agent download it, as a project does, unless `TEST_AGENT_BIN` names one. ## License diff --git a/settings.gradle.kts b/settings.gradle.kts index ff17e7f..9205858 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -3,4 +3,4 @@ // tracepanel-junit runs each test as a trace, failed by what the agent finds in it. rootProject.name = "tracepanel-java" -include("tracepanel-core", "tracepanel-spring-boot", "tracepanel-ktor", "tracepanel-junit") +include("tracepanel-core", "tracepanel-spring-boot", "tracepanel-ktor", "tracepanel-junit", "tracepanel-micronaut") diff --git a/tracepanel-core/src/main/java/dev/tracepanel/core/Stacks.java b/tracepanel-core/src/main/java/dev/tracepanel/core/Stacks.java index 1d4e6fa..b600fb5 100644 --- a/tracepanel-core/src/main/java/dev/tracepanel/core/Stacks.java +++ b/tracepanel-core/src/main/java/dev/tracepanel/core/Stacks.java @@ -25,7 +25,7 @@ public final class Stacks { private static final List LIBRARIES = List.of( "java.", "javax.", "jakarta.", "jdk.", "sun.", "com.sun.", "kotlin.", "kotlinx.", "scala.", "groovy.", "org.springframework.", "org.hibernate.", "com.zaxxer.", "org.postgresql.", "com.mysql.", "org.mariadb.", - "org.h2.", "org.hsqldb.", "org.apache.", "org.eclipse.", "io.netty.", "reactor.", "io.micrometer.", + "org.h2.", "org.hsqldb.", "org.apache.", "org.eclipse.", "io.netty.", "io.micronaut.", "reactor.", "io.micrometer.", "ch.qos.logback.", "org.slf4j.", "org.thymeleaf.", "com.fasterxml.", "org.jboss.", "net.bytebuddy.", "org.junit.", "dev.tracepanel.", "io.opentelemetry.", "io.ktor.", "org.jetbrains.", "com.google.", "okhttp3.", "okio.", "io.grpc.", "io.undertow.", "io.vertx.", "org.aspectj.", "org.glassfish.", "org.jooq.", diff --git a/tracepanel-micronaut/build.gradle.kts b/tracepanel-micronaut/build.gradle.kts new file mode 100644 index 0000000..d51ab78 --- /dev/null +++ b/tracepanel-micronaut/build.gradle.kts @@ -0,0 +1,92 @@ +description = "Tracepanel for Micronaut: request traces, JDBC, declarative HTTP clients, logs, a badge and the local console." + +val micronaut4 = "4.10.24" +val micronaut5 = "5.2.6" + +dependencies { + api(project(":tracepanel-core")) + compileOnly(platform("io.micronaut.platform:micronaut-platform:$micronaut4")) + compileOnly("io.micronaut:micronaut-http-server") + compileOnly("io.micronaut:micronaut-http-client-core") + compileOnly("io.micronaut:micronaut-core-reactive") + implementation("io.micronaut.reactor:micronaut-reactor:3.9.1") + compileOnly("ch.qos.logback:logback-classic:1.5.18") + annotationProcessor(platform("io.micronaut.platform:micronaut-platform:$micronaut4")) + annotationProcessor("io.micronaut:micronaut-inject-java") + + testImplementation(platform("io.micronaut.platform:micronaut-platform:$micronaut4")) + testImplementation("io.micronaut.test:micronaut-test-junit5") + testImplementation("io.micronaut:micronaut-http-server-netty") + testImplementation("io.micronaut:micronaut-http-client") + testImplementation("io.micronaut:micronaut-jackson-databind") + testImplementation("io.micronaut.reactor:micronaut-reactor") + testImplementation("io.micronaut.sql:micronaut-jdbc-hikari") + testImplementation("io.projectreactor:reactor-core") + testImplementation("com.h2database:h2:2.4.240") + testImplementation("ch.qos.logback:logback-classic:1.5.18") + testImplementation(testFixtures(project(":tracepanel-core"))) + testAnnotationProcessor(platform("io.micronaut.platform:micronaut-platform:$micronaut4")) + testAnnotationProcessor("io.micronaut:micronaut-inject-java") +} + +// Compile against Micronaut 4's Java 17 API; exercise the same integration on Micronaut 5 and Java 25. +val micronaut5Tests = testing.suites.register("testMicronaut5") { + useJUnitJupiter("6.1.3") + sources.java.setSrcDirs(listOf("src/test/java")) + dependencies { + implementation(project()) + implementation(platform("io.micronaut.platform:micronaut-platform:$micronaut5")) + implementation("io.micronaut.test:micronaut-test-junit5") + implementation("io.micronaut:micronaut-http-server-netty") + implementation("io.micronaut:micronaut-http-client") + implementation("io.micronaut:micronaut-jackson-databind") + implementation("io.micronaut.reactor:micronaut-reactor") + implementation("io.micronaut.sql:micronaut-jdbc-hikari") + implementation("io.projectreactor:reactor-core") + implementation("com.h2database:h2:2.4.240") + implementation("ch.qos.logback:logback-classic:1.5.18") + implementation(testFixtures(project(":tracepanel-core"))) + } + targets.all { + testTask.configure { + javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) } + useJUnitPlatform { excludeTags("integration") } + } + } +} +dependencies { + "testMicronaut5AnnotationProcessor"(platform("io.micronaut.platform:micronaut-platform:$micronaut5")) + "testMicronaut5AnnotationProcessor"("io.micronaut:micronaut-inject-java") +} +tasks.named("compileTestMicronaut5Java") { + javaCompiler = javaToolchains.compilerFor { languageVersion = JavaLanguageVersion.of(25) } + options.release = 25 +} +tasks.withType().configureEach { + options.compilerArgs.add("-Xlint:-processing") + options.compilerArgs.addAll(listOf("-Amicronaut.processing.group=dev.tracepanel", "-Amicronaut.processing.module=tracepanel-micronaut")) +} +tasks.withType().configureEach { + environment("TRACEPANEL_DIR", layout.buildDirectory.dir("tracepanel-test/$name").get().asFile.absolutePath) + environment("TRACEPANEL_AGENT", "off") +} + +// Separate JVMs keep the core's process-wide recorder and fake agent out of unit tests. +tasks.test { useJUnitPlatform { excludeTags("integration") } } +val integrationTest by tasks.registering(Test::class) { + testClassesDirs = sourceSets.test.get().output.classesDirs + classpath = sourceSets.test.get().runtimeClasspath + useJUnitPlatform { includeTags("integration") } + environment("TRACEPANEL_AGENT", "auto") + shouldRunAfter(tasks.test) +} +tasks.register("testMicronaut5Integration") { + val sources = micronaut5Tests.get().sources + testClassesDirs = sources.output.classesDirs + classpath = sources.runtimeClasspath + javaLauncher = javaToolchains.launcherFor { languageVersion = JavaLanguageVersion.of(25) } + useJUnitPlatform { includeTags("integration") } + environment("TRACEPANEL_AGENT", "auto") + shouldRunAfter(tasks.named("testMicronaut5")) +} +tasks.check { dependsOn(integrationTest) } diff --git a/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/DataSources.java b/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/DataSources.java new file mode 100644 index 0000000..6f79613 --- /dev/null +++ b/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/DataSources.java @@ -0,0 +1,26 @@ +package dev.tracepanel.micronaut; + +import dev.tracepanel.core.Jdbc; +import io.micronaut.context.annotation.Requires; +import io.micronaut.context.event.BeanCreatedEvent; +import io.micronaut.context.event.BeanCreatedEventListener; +import jakarta.inject.Singleton; +import javax.sql.DataSource; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +@Singleton +@Requires(condition = TracepanelEnabled.class) +final class DataSources implements BeanCreatedEventListener { + private static final Logger LOG = LoggerFactory.getLogger(DataSources.class); + + @Override + public DataSource onCreated(BeanCreatedEvent event) { + DataSource original = event.getBean(); + String alias = event.getBeanIdentifier().getName(); + DataSource wrapped = Jdbc.dataSource(original, alias); + if (event.getBeanDefinition().getBeanType().isInstance(wrapped)) return wrapped; + LOG.warn("Tracepanel cannot wrap concrete DataSource bean {}. Declare the factory return type as DataSource.", alias); + return original; + } +} diff --git a/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TraceContext.java b/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TraceContext.java new file mode 100644 index 0000000..162b56f --- /dev/null +++ b/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TraceContext.java @@ -0,0 +1,18 @@ +package dev.tracepanel.micronaut; + +import dev.tracepanel.core.Trace; +import dev.tracepanel.core.Tracepanel; +import io.micronaut.core.annotation.Nullable; +import io.micronaut.core.propagation.ThreadPropagatedContextElement; + +record TraceContext(Trace trace) implements ThreadPropagatedContextElement { + @Override + public Trace updateThreadContext() { + return Tracepanel.bind(trace); + } + + @Override + public void restoreThreadContext(@Nullable Trace previous) { + Tracepanel.bind(previous); + } +} diff --git a/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelClientFilter.java b/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelClientFilter.java new file mode 100644 index 0000000..0e0e6d6 --- /dev/null +++ b/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelClientFilter.java @@ -0,0 +1,41 @@ +package dev.tracepanel.micronaut; + +import dev.tracepanel.core.HttpCalls; +import dev.tracepanel.core.Profiler; +import dev.tracepanel.core.W3c; +import io.micronaut.context.annotation.Requires; +import io.micronaut.http.HttpResponse; +import io.micronaut.http.MutableHttpRequest; +import io.micronaut.http.annotation.Filter; +import io.micronaut.http.filter.ClientFilterChain; +import io.micronaut.http.filter.HttpClientFilter; +import java.util.concurrent.CancellationException; +import java.util.concurrent.atomic.AtomicBoolean; +import org.reactivestreams.Publisher; +import reactor.core.publisher.Flux; + +@Filter("/**") +@Requires(classes = HttpClientFilter.class, condition = TracepanelEnabled.class) +final class TracepanelClientFilter implements HttpClientFilter { + @Override + public Publisher> doFilter(MutableHttpRequest request, ClientFilterChain chain) { + return Flux.>defer(() -> { + HttpCalls.Call call = HttpCalls.start(request.getMethodName(), request.getUri()); + if (call == null) return Flux.defer(() -> Flux.>from(chain.proceed(request))); + if (!request.getHeaders().contains(W3c.HEADER)) request.header(W3c.HEADER, call.traceparent()); + if (call.profile() != null && !request.getHeaders().contains(Profiler.HEADER)) { + request.header(Profiler.HEADER, call.profile()); + } + AtomicBoolean finished = new AtomicBoolean(); + return Flux.defer(() -> Flux.>from(chain.proceed(request))) + .doOnNext(response -> { if (finished.compareAndSet(false, true)) call.end(response.code()); }) + .doOnError(error -> { if (finished.compareAndSet(false, true)) call.failed(error); }) + .doOnComplete(() -> { + if (finished.compareAndSet(false, true)) call.failed(new IllegalStateException("HTTP call completed without a response")); + }) + .doOnCancel(() -> { + if (finished.compareAndSet(false, true)) call.failed(new CancellationException("HTTP call cancelled")); + }); + }); + } +} diff --git a/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelConfiguration.java b/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelConfiguration.java new file mode 100644 index 0000000..68d25b9 --- /dev/null +++ b/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelConfiguration.java @@ -0,0 +1,28 @@ +package dev.tracepanel.micronaut; + +import dev.tracepanel.core.Config; +import dev.tracepanel.core.Tracepanel; +import io.micronaut.context.annotation.Factory; +import io.micronaut.context.annotation.Requires; +import io.micronaut.context.env.Environment; +import io.micronaut.core.reflect.ClassUtils; +import io.micronaut.core.version.VersionUtils; +import jakarta.inject.Singleton; +import java.util.List; + +@Factory +@Requires(condition = TracepanelEnabled.class) +final class TracepanelConfiguration { + @Singleton + Tracepanel tracepanel(Environment environment) { + Config config = Config.load(name -> environment.getProperty(name, String.class) + .or(() -> environment.getProperty(Config.property(name), String.class)).orElse(null), + environment.getProperty("micronaut.application.name", String.class).orElse(null)); + Tracepanel tracepanel = Tracepanel.start(config, List.of()); + tracepanel.framework("Micronaut " + VersionUtils.MICRONAUT_VERSION); + if (ClassUtils.isPresent("ch.qos.logback.classic.LoggerContext", getClass().getClassLoader())) { + dev.tracepanel.integrations.LogbackRecorder.install(tracepanel); + } + return tracepanel; + } +} diff --git a/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelEnabled.java b/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelEnabled.java new file mode 100644 index 0000000..0515c12 --- /dev/null +++ b/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelEnabled.java @@ -0,0 +1,28 @@ +package dev.tracepanel.micronaut; + +import io.micronaut.context.ApplicationContext; +import io.micronaut.context.condition.Condition; +import io.micronaut.context.condition.ConditionContext; +import io.micronaut.context.env.Environment; +import java.util.Locale; +import java.util.Set; + +final class TracepanelEnabled implements Condition { + private static final Set OFF = Set.of("0", "false", "no", "off"); + private static final Set DEVELOPMENT = Set.of("dev", "development", "local"); + + @Override + @SuppressWarnings("rawtypes") + public boolean matches(ConditionContext context) { + if (!(context.getBeanContext() instanceof ApplicationContext application)) return false; + return enabled(application.getEnvironment()); + } + + static boolean enabled(Environment environment) { + String explicit = environment.getProperty("TRACEPANEL_ENABLED", String.class) + .or(() -> environment.getProperty("tracepanel.enabled", String.class)).orElse("").trim(); + if (!explicit.isEmpty()) return !OFF.contains(explicit.toLowerCase(Locale.ROOT)); + return environment.getActiveNames().stream() + .map(name -> name.toLowerCase(Locale.ROOT)).anyMatch(DEVELOPMENT::contains); + } +} diff --git a/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelServerFilter.java b/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelServerFilter.java new file mode 100644 index 0000000..d923554 --- /dev/null +++ b/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelServerFilter.java @@ -0,0 +1,191 @@ +package dev.tracepanel.micronaut; + +import dev.tracepanel.core.Console; +import dev.tracepanel.core.Profiler; +import dev.tracepanel.core.RequestDetails; +import dev.tracepanel.core.Trace; +import dev.tracepanel.core.Tracepanel; +import dev.tracepanel.core.W3c; +import dev.tracepanel.core.Widget; +import io.micronaut.context.annotation.Requires; +import io.micronaut.context.annotation.Value; +import io.micronaut.core.async.propagation.ReactivePropagation; +import io.micronaut.core.propagation.PropagatedContext; +import io.micronaut.http.HttpHeaders; +import io.micronaut.http.HttpRequest; +import io.micronaut.http.HttpResponse; +import io.micronaut.http.MutableHttpResponse; +import io.micronaut.http.ServerHttpRequest; +import io.micronaut.http.annotation.Filter; +import io.micronaut.http.filter.HttpServerFilter; +import io.micronaut.http.filter.ServerFilterChain; +import io.micronaut.http.filter.ServerFilterPhase; +import io.micronaut.http.server.util.HttpHostResolver; +import io.micronaut.web.router.MethodBasedRouteMatch; +import io.micronaut.web.router.RouteAttributes; +import io.micronaut.web.router.UriRouteMatch; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import org.reactivestreams.Publisher; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.core.publisher.SignalType; +import reactor.core.scheduler.Schedulers; + +@Filter("/**") +@Requires(classes = HttpServerFilter.class, condition = TracepanelEnabled.class) +final class TracepanelServerFilter implements HttpServerFilter { + private final Tracepanel tracepanel; + private final String prefix; + private final HttpHostResolver hosts; + + TracepanelServerFilter(Tracepanel tracepanel, @Value("${micronaut.server.context-path:}") String contextPath, HttpHostResolver hosts) { + this.tracepanel = tracepanel; + this.hosts = hosts; + this.prefix = contextPath.replaceAll("/+$", "") + tracepanel.config().prefix(); + } + + @Override + public int getOrder() { + return ServerFilterPhase.FIRST.order(); + } + + @Override + public Publisher> doFilter(HttpRequest request, ServerFilterChain chain) { + String path = request.getPath(); + if (path.equals(prefix.substring(0, prefix.length() - 1)) || path.startsWith(prefix)) { + return console(request, path.length() < prefix.length() ? "" : path.substring(prefix.length())); + } + if (request.getMethodName().equals("OPTIONS") && request.getHeaders().contains(HttpHeaders.ORIGIN) + && request.getHeaders().contains(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD)) { + return chain.proceed(request); + } + return Flux.defer(() -> traced(request, chain)); + } + + @SuppressWarnings("try") + private Publisher> traced(HttpRequest request, ServerFilterChain chain) { + Map attrs = new LinkedHashMap<>(W3c.incoming(request.getHeaders().get(W3c.HEADER))); + attrs.put("http.method", request.getMethodName()); + attrs.put("http.path", request.getPath()); + if (tracepanel.config().captureRequest()) { + attrs.putAll(RequestDetails.query(request.getUri().getRawQuery())); + attrs.putAll(RequestDetails.cookies(request.getHeaders().get(HttpHeaders.COOKIE))); + attrs.putAll(RequestDetails.requestHeaders(headers(request.getHeaders()))); + } + Trace previous = Tracepanel.current(); + Trace trace = tracepanel.begin("http", request.getMethodName() + " " + request.getPath(), attrs); + String profile = request.getHeaders().get(Profiler.HEADER); + String cookies = request.getHeaders().get(HttpHeaders.COOKIE); + tracepanel.profile(trace, Profiler.asked(profile, cookies), + Profiler.reason(profile, cookies, attrs.containsKey("w3c.parent_span_id"))); + Tracepanel.bind(previous); + PropagatedContext context = PropagatedContext.getOrEmpty().plus(new TraceContext(trace)); + return ReactivePropagation.propagate(context, Flux.defer(() -> { + try (PropagatedContext.Scope ignored = context.propagate()) { + return Flux.from(chain.proceed(request)); + } + }).doOnNext(response -> response(request, response, trace)) + .doOnError(error -> { + trace.failed(); + trace.attr("http.status_code", 500); + trace.error(error, tracepanel.stacks(), false); + }) + .doFinally(signal -> { + try (PropagatedContext.Scope ignored = context.propagate()) { + if (signal == SignalType.CANCEL) trace.failed(); + route(request, trace); + tracepanel.finish(trace); + } + })); + } + + private void response(HttpRequest request, MutableHttpResponse response, Trace trace) { + route(request, trace); + request.getUserPrincipal().ifPresent(principal -> trace.user(principal.getName(), null)); + trace.attr("http.status_code", response.code()); + if (response.code() >= 500) { + trace.failed(); + RouteAttributes.getException(response).ifPresent(error -> trace.error(error, tracepanel.stacks(), false)); + } + String origin = hosts.resolve(request); + Widget.headers(trace, origin, prefix).forEach(response::header); + if (request.getHeaders().contains(HttpHeaders.ORIGIN)) { + String exposed = response.getHeaders().get(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS); + response.header(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, + exposed == null ? Widget.EXPOSED : exposed + ", " + Widget.EXPOSED); + } + if (tracepanel.config().captureRequest()) { + RequestDetails.responseHeaders(headers(response.getHeaders())).forEach(trace::attr); + Object body = request.getBody().orElse(null); + byte[] bytes = body instanceof byte[] data ? data + : body instanceof String text ? text.getBytes(StandardCharsets.UTF_8) : null; + if (bytes != null) RequestDetails.body(request.getContentType().map(Object::toString).orElse(""), bytes, true) + .forEach((key, value) -> trace.attr("http.request." + key, value)); + } + if (response.getContentType().filter(type -> type.getName().equals("text/html")).isEmpty() + || response.getHeaders().contains(HttpHeaders.CONTENT_ENCODING)) return; + Object body = response.getBody().orElse(null); + String html = body instanceof String text ? text + : body instanceof byte[] bytes ? new String(bytes, response.getCharacterEncoding()) : null; + if (html == null) return; + String decorated = Widget.decorate(html, trace, request.getMethodName(), response.code(), + prefix, "java"); + response.body(body instanceof byte[] ? decorated.getBytes(response.getCharacterEncoding()) : decorated); + response.getHeaders().remove(HttpHeaders.CONTENT_LENGTH); + response.getHeaders().remove(HttpHeaders.ETAG); + response.getHeaders().remove("Content-MD5"); + response.getHeaders().remove("Content-Digest"); + } + + private static void route(HttpRequest request, Trace trace) { + RouteAttributes.getRouteMatch(request).ifPresent(match -> { + if (match instanceof UriRouteMatch uri) { + String pattern = uri.getRouteInfo().getUriMatchTemplate().toString(); + trace.attr("http.route", pattern); + trace.name(request.getMethodName() + " " + pattern); + } + if (match instanceof MethodBasedRouteMatch method) { + var executable = method.getExecutableMethod(); + trace.attr("code.view", executable.getDeclaringType().getSimpleName() + "#" + executable.getMethodName()); + } + }); + } + + private Publisher> console(HttpRequest request, String path) { + return Mono.>fromCallable(() -> { + byte[] body = consoleBody(request); + if (body.length > Console.MAX_BODY) body = null; + String query = request.getUri().getRawQuery(); + var remote = request.getRemoteAddress(); + String address = remote.getAddress() == null ? remote.getHostString() : remote.getAddress().getHostAddress(); + Console.Answer answer = Console.forward(tracepanel, request.getMethodName(), + path + (query == null ? "" : "?" + query), request.getContentType().map(Object::toString).orElse(null), + body, address); + MutableHttpResponse response = HttpResponse.status(io.micronaut.http.HttpStatus.valueOf(answer.status())) + .body(answer.body()).contentType(answer.contentType()); + answer.headers().forEach(response::header); + return response; + }).subscribeOn(Schedulers.boundedElastic()); + } + + private static byte[] consoleBody(HttpRequest request) throws IOException { + if (request instanceof ServerHttpRequest server) { + try (InputStream input = server.byteBody().toInputStream()) { + return input.readNBytes(Console.MAX_BODY + 1); + } + } + return request.getBody(byte[].class).orElse(new byte[0]); + } + + private static List> headers(HttpHeaders headers) { + List> values = new ArrayList<>(); + headers.forEach((name, entries) -> entries.forEach(value -> values.add(Map.entry(name, value)))); + return values; + } +} diff --git a/tracepanel-micronaut/src/test/java/dev/tracepanel/micronaut/DataSourcesTest.java b/tracepanel-micronaut/src/test/java/dev/tracepanel/micronaut/DataSourcesTest.java new file mode 100644 index 0000000..02a37f7 --- /dev/null +++ b/tracepanel-micronaut/src/test/java/dev/tracepanel/micronaut/DataSourcesTest.java @@ -0,0 +1,85 @@ +package dev.tracepanel.micronaut; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import dev.tracepanel.core.Trace; +import dev.tracepanel.core.Tracepanel; +import io.micronaut.context.ApplicationContext; +import io.micronaut.http.HttpRequest; +import io.micronaut.http.HttpResponse; +import io.micronaut.inject.qualifiers.Qualifiers; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import javax.sql.DataSource; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; + +class DataSourcesTest { + @Test + void namedPoolsAreWrappedAndTheirQueriesAreRecorded() throws Exception { + try (ApplicationContext context = ApplicationContext.builder().deduceEnvironment(false).environments("test") + .properties(Map.of("tracepanel.enabled", true, + "datasources.default.url", "jdbc:h2:mem:first;DB_CLOSE_DELAY=-1", + "datasources.default.driver-class-name", "org.h2.Driver", + "datasources.second.url", "jdbc:h2:mem:second;DB_CLOSE_DELAY=-1", + "datasources.second.driver-class-name", "org.h2.Driver")).start()) { + Tracepanel recorder = context.getBean(Tracepanel.class); + assertNotNull(recorder); + List traces = new CopyOnWriteArrayList<>(); + CountDownLatch finished = new CountDownLatch(2); + Tracepanel.tests(new Tracepanel.Tests() { + public void begun(Trace trace) {} + public Trace caller() { return null; } + public boolean finished(Trace trace, Map document) { traces.add(trace); finished.countDown(); return false; } + }); + try { + Trace trace = recorder.begin("command", "two databases", Map.of()); + for (String name : List.of("default", "second")) { + DataSource pool = context.getBean(DataSource.class, Qualifiers.byName(name)); + try (var connection = pool.getConnection(); var query = connection.prepareStatement("SELECT 1"); + var rows = query.executeQuery()) { + assertTrue(rows.next()); + } + } + recorder.finish(trace); + long queries = trace.spans().stream().filter(span -> "sql".equals(span.get("kind"))).count(); + assertEquals(2, queries); + TracepanelServerFilter filter = new TracepanelServerFilter(recorder, "", request -> "http://localhost"); + Flux.from(filter.doFilter(HttpRequest.GET("/reactive"), request -> Mono.>fromCallable(() -> { + assertNotNull(Tracepanel.current()); + DataSource pool = context.getBean(DataSource.class); + try (var connection = pool.getConnection(); var query = connection.prepareStatement("SELECT 2"); + var rows = query.executeQuery()) { + assertTrue(rows.next()); + } + return HttpResponse.ok("reactive"); + }).subscribeOn(Schedulers.boundedElastic()))).blockLast(); + assertNull(Tracepanel.current()); + assertTrue(finished.await(5, TimeUnit.SECONDS)); + assertEquals(2, traces.size()); + assertEquals(1, traces.get(1).spans().stream().filter(span -> "sql".equals(span.get("kind"))).count()); + } finally { + Tracepanel.bind(null); + Tracepanel.tests(null); + } + } + } + + @Test + void productionContextHasNoSdkBeans() { + try (ApplicationContext context = ApplicationContext.builder().deduceEnvironment(false) + .environments("production").start()) { + assertTrue(context.findBean(Tracepanel.class).isEmpty()); + assertTrue(context.findBean(TracepanelServerFilter.class).isEmpty()); + assertTrue(context.findBean(TracepanelClientFilter.class).isEmpty()); + } + } +} diff --git a/tracepanel-micronaut/src/test/java/dev/tracepanel/micronaut/FilterTest.java b/tracepanel-micronaut/src/test/java/dev/tracepanel/micronaut/FilterTest.java new file mode 100644 index 0000000..e88ab37 --- /dev/null +++ b/tracepanel-micronaut/src/test/java/dev/tracepanel/micronaut/FilterTest.java @@ -0,0 +1,162 @@ +package dev.tracepanel.micronaut; + +import static org.junit.jupiter.api.Assertions.*; + +import dev.tracepanel.core.Config; +import dev.tracepanel.core.Trace; +import dev.tracepanel.core.Tracepanel; +import io.micronaut.core.async.propagation.ReactivePropagation; +import io.micronaut.core.propagation.PropagatedContext; +import io.micronaut.http.HttpRequest; +import io.micronaut.http.HttpResponse; +import java.util.List; +import java.util.Map; +import java.util.concurrent.CopyOnWriteArrayList; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import reactor.core.publisher.Flux; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; + +class FilterTest { + private static final List> DOCUMENTS = new CopyOnWriteArrayList<>(); + private static Tracepanel recorder; + private static final Tracepanel.Tests CAPTURE = new Tracepanel.Tests() { + public void begun(Trace trace) {} + public Trace caller() { return null; } + public boolean finished(Trace trace, Map document) { + DOCUMENTS.add(document); + return false; + } + }; + + @BeforeAll + static void recorder() { + recorder = Tracepanel.start(Config.load(Map.of("TRACEPANEL_PROFILE_ENABLED", "0"), "micronaut-test"), List.of("shop")); + Tracepanel.tests(CAPTURE); + } + + @AfterAll + static void restore() { Tracepanel.tests(null); } + + @BeforeEach + void clear() { DOCUMENTS.clear(); Tracepanel.bind(null); } + + @Test + void contextRestoresThePreviousTraceAcrossThreads() { + Trace parent = recorder.begin("command", "parent", Map.of()); + Trace child = recorder.begin("command", "child", Map.of()); + Tracepanel.bind(parent); + PropagatedContext context = PropagatedContext.getOrEmpty().plus(new TraceContext(child)); + Flux.from(ReactivePropagation.propagate(context, Mono.just(1).subscribeOn(Schedulers.boundedElastic()))) + .doOnNext(value -> assertSame(child, Tracepanel.current())).blockLast(); + assertSame(parent, Tracepanel.current()); + recorder.finish(child); + recorder.finish(parent); + assertNull(Tracepanel.current()); + } + + @Test + void serverRecordsErrorsAndRestoresThreadContext() { + TracepanelServerFilter filter = new TracepanelServerFilter(recorder, "", request -> "http://localhost"); + assertThrows(IllegalStateException.class, () -> Flux.from(filter.doFilter(HttpRequest.GET("/fail"), request -> { + assertNotNull(Tracepanel.current()); + return Mono.error(new IllegalStateException("broken")); + })).blockLast()); + assertNull(Tracepanel.current()); + assertEquals("error", DOCUMENTS.get(0).get("status")); + } + + @Test + void cancellationFinishesTheTraceExactlyOnce() { + TracepanelServerFilter filter = new TracepanelServerFilter(recorder, "", request -> "http://localhost"); + var subscription = Flux.from(filter.doFilter(HttpRequest.GET("/cancel"), request -> Mono.never())).subscribe(); + subscription.dispose(); + assertEquals(1, DOCUMENTS.size()); + assertEquals("error", DOCUMENTS.get(0).get("status")); + assertNull(Tracepanel.current()); + } + + @Test + void preflightBypassesTracingButOrdinaryOptionsDoesNot() { + TracepanelServerFilter filter = new TracepanelServerFilter(recorder, "", request -> "http://localhost"); + Flux.from(filter.doFilter(HttpRequest.OPTIONS("/cors").header("Origin", "https://shop.test") + .header("Access-Control-Request-Method", "GET"), request -> Mono.just(HttpResponse.ok()))).blockLast(); + assertTrue(DOCUMENTS.isEmpty()); + Flux.from(filter.doFilter(HttpRequest.OPTIONS("/options"), request -> Mono.just(HttpResponse.ok()))).blockLast(); + assertEquals(1, DOCUMENTS.size()); + } + + @Test + void clientAddsPropagationAndPreservesExplicitHeaders() { + Trace trace = recorder.begin("http", "outgoing", Map.of()); + TracepanelClientFilter filter = new TracepanelClientFilter(); + Flux.from(filter.doFilter(HttpRequest.GET("http://localhost/items"), request -> { + assertNotNull(request.getHeaders().get("traceparent")); + return Mono.just(HttpResponse.ok()); + })).blockLast(); + Flux.from(filter.doFilter(HttpRequest.GET("http://localhost/explicit").header("traceparent", "own"), request -> { + assertEquals("own", request.getHeaders().get("traceparent")); + return Mono.just(HttpResponse.ok()); + })).blockLast(); + recorder.finish(trace); + assertEquals(3, trace.spans().size()); + } + @Test + void clientRecordsSynchronousFailuresAndCancellationOnce() { + Trace trace = recorder.begin("http", "outgoing failures", Map.of()); + TracepanelClientFilter filter = new TracepanelClientFilter(); + assertThrows(IllegalStateException.class, () -> Flux.from(filter.doFilter(HttpRequest.GET("http://localhost/fail"), + request -> { throw new IllegalStateException("client failure"); })).blockLast()); + var subscription = Flux.from(filter.doFilter(HttpRequest.GET("http://localhost/cancel"), request -> Mono.never())).subscribe(); + subscription.dispose(); + recorder.finish(trace); + assertEquals(2, trace.spans().stream().filter(span -> "http.client".equals(span.get("kind"))).count()); + assertEquals(2, trace.spans().stream().filter(span -> "error".equals(span.get("status"))).count()); + } + + @Test + void handledClientErrorsKeepTheirStatusWithoutAnException() { + TracepanelServerFilter filter = new TracepanelServerFilter(recorder, "", request -> "http://localhost"); + Flux.from(filter.doFilter(HttpRequest.GET("/invalid"), request -> Mono.just(HttpResponse.unprocessableEntity()))).blockLast(); + Map trace = DOCUMENTS.get(0); + assertEquals("ok", trace.get("status")); + assertTrue(trace.get("attrs") instanceof Map attrs && Integer.valueOf(422).equals(attrs.get("http.status_code"))); + } + + @Test + void htmlInjectionPreservesCharsetAndDropsStaleEntityHeaders() { + TracepanelServerFilter filter = new TracepanelServerFilter(recorder, "/shop/", request -> "http://localhost"); + var response = HttpResponse.ok("Café".getBytes(java.nio.charset.StandardCharsets.ISO_8859_1)) + .contentType("text/html; charset=ISO-8859-1").header("ETag", "old").header("Content-Length", "55"); + io.micronaut.http.MutableHttpResponse result; + Tracepanel.tests(null); // The core disables badge injection while a test recorder is installed. + try { + result = Flux.from(filter.doFilter(HttpRequest.GET("/shop/page"), request -> Mono.just(response))).blockLast(); + } finally { + Tracepanel.tests(CAPTURE); + } + assertNotNull(result); + assertTrue(result.getBody().orElseThrow() instanceof byte[] bytes + && new String(bytes, java.nio.charset.StandardCharsets.ISO_8859_1).contains("Café")); + assertTrue(result.getBody().orElseThrow() instanceof byte[] bytes + && new String(bytes, java.nio.charset.StandardCharsets.ISO_8859_1).contains("/shop/__tracepanel__/widget.min.js")); + assertFalse(result.getHeaders().contains("ETag")); + assertFalse(result.getHeaders().contains("Content-Length")); + } + + @Test + void encodedAndStreamingResponsesStayUnchanged() { + TracepanelServerFilter filter = new TracepanelServerFilter(recorder, "", request -> "http://localhost"); + var compressed = HttpResponse.ok("compressed").contentType("text/html").header("Content-Encoding", "gzip"); + assertSame(compressed, Flux.from(filter.doFilter(HttpRequest.GET("/gzip"), request -> Mono.just(compressed))).blockLast()); + assertEquals("compressed", compressed.body()); + var body = Mono.just("stream"); + var streaming = HttpResponse.ok(body).contentType("text/html"); + Flux.from(filter.doFilter(HttpRequest.GET("/stream"), request -> Mono.just(streaming))).blockLast(); + assertSame(body, streaming.body()); + } + +} diff --git a/tracepanel-micronaut/src/test/java/dev/tracepanel/micronaut/TracepanelEnabledTest.java b/tracepanel-micronaut/src/test/java/dev/tracepanel/micronaut/TracepanelEnabledTest.java new file mode 100644 index 0000000..9c77cff --- /dev/null +++ b/tracepanel-micronaut/src/test/java/dev/tracepanel/micronaut/TracepanelEnabledTest.java @@ -0,0 +1,34 @@ +package dev.tracepanel.micronaut; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import io.micronaut.context.ApplicationContext; +import io.micronaut.context.env.Environment; +import java.util.Map; +import org.junit.jupiter.api.Test; + +class TracepanelEnabledTest { + @Test + void developmentEnvironmentsEnableTracingButProductionDoesNot() { + for (String name : new String[] {"dev", "development", "local", "production", "test"}) { + assertEquals(!name.equals("production") && !name.equals("test"), enabled(name, Map.of())); + } + } + + @Test + void explicitSettingsWinOverEnvironmentNames() { + for (String off : new String[] {"0", "false", "no", "OFF"}) { + assertEquals(false, enabled("dev", Map.of("TRACEPANEL_ENABLED", off))); + } + assertEquals(true, enabled("production", Map.of("tracepanel.enabled", "true"))); + assertEquals(false, enabled("dev", Map.of("TRACEPANEL_ENABLED", "0", "tracepanel.enabled", "1"))); + } + + private static boolean enabled(String name, Map properties) { + try (ApplicationContext context = ApplicationContext.builder().deduceEnvironment(false) + .environments(name).properties(properties).build()) { + Environment environment = context.getEnvironment().start(); + return TracepanelEnabled.enabled(environment); + } + } +} diff --git a/tracepanel-micronaut/src/test/java/shop/MicronautTracingTest.java b/tracepanel-micronaut/src/test/java/shop/MicronautTracingTest.java new file mode 100644 index 0000000..146b5a0 --- /dev/null +++ b/tracepanel-micronaut/src/test/java/shop/MicronautTracingTest.java @@ -0,0 +1,129 @@ +package shop; + +import static org.junit.jupiter.api.Assertions.*; + +import dev.tracepanel.testing.FakeAgent; +import io.micronaut.context.annotation.Property; +import io.micronaut.http.HttpRequest; +import io.micronaut.http.annotation.Controller; +import io.micronaut.http.annotation.Get; +import io.micronaut.http.client.HttpClient; +import io.micronaut.http.client.annotation.Client; +import io.micronaut.http.client.exceptions.HttpClientResponseException; +import io.micronaut.scheduling.TaskExecutors; +import io.micronaut.scheduling.annotation.ExecuteOn; +import io.micronaut.test.extensions.junit5.annotation.MicronautTest; +import io.micronaut.test.support.TestPropertyProvider; +import jakarta.inject.Inject; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.sql.SQLException; +import java.util.List; +import java.util.Map; +import javax.sql.DataSource; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; +import reactor.core.publisher.Mono; +import reactor.core.scheduler.Schedulers; + +@Tag("integration") +@MicronautTest(environments = "dev", transactional = false) +@Property(name = "datasources.default.url", value = "jdbc:h2:mem:micronaut;DB_CLOSE_DELAY=-1") +@Property(name = "datasources.default.driver-class-name", value = "org.h2.Driver") +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class MicronautTracingTest implements TestPropertyProvider { + @Inject @Client("/") HttpClient http; + + @Override + public Map getProperties() { + try { + FakeAgent.start(); + } catch (IOException error) { + throw new UncheckedIOException(error); + } + return Map.of(); + } + + @Test + void routeHasSqlClientCallLogsAndTraceHeaders() throws Exception { + var response = http.toBlocking().exchange(HttpRequest.GET("/probe/books/7"), String.class); + assertNotNull(response.header("Tracepanel-Id")); + assertEquals("book 7 echo", response.body()); + Map trace = FakeAgent.traceAt("/probe/books/7"); + assertEquals("GET /probe/books/{id}", trace.get("name")); + assertTrue(trace.get("spans") instanceof List spans && spans.stream().anyMatch(value -> + value instanceof Map span && "sql".equals(span.get("kind")))); + assertTrue(trace.get("spans") instanceof List spans && spans.stream().anyMatch(value -> + value instanceof Map span && "http.client".equals(span.get("kind")))); + assertTrue(trace.get("logs") instanceof List logs && !logs.isEmpty()); + Map echoed = FakeAgent.traceAt("/probe/echo"); + assertTrue(echoed.get("attrs") instanceof Map attrs && attrs.containsKey("w3c.parent_span_id")); + } + + @Test + void reactiveControllerKeepsItsTraceAfterSwitchingThreads() throws Exception { + assertEquals("reactive", http.toBlocking().retrieve("/probe/reactive/8")); + Map trace = FakeAgent.traceAt("/probe/reactive/8"); + assertEquals("GET /probe/reactive/{id}", trace.get("name")); + assertTrue(trace.get("spans") instanceof List spans && spans.size() > 1); + } + + @Test + void frameworkErrorResponseKeepsTheException() throws Exception { + assertThrows(HttpClientResponseException.class, () -> http.toBlocking().retrieve("/probe/failure")); + Map trace = FakeAgent.traceAt("/probe/failure"); + assertEquals("error", trace.get("status")); + assertTrue(trace.get("errors") instanceof List errors && !errors.isEmpty()); + } + + @Test + void htmlHasTheBadgeAndTheConsoleDoesNotTraceItself() { + String page = http.toBlocking().retrieve("/probe/page"); + assertTrue(page.contains("/__tracepanel__/widget.min.js")); + String answer = http.toBlocking().retrieve("/__tracepanel__/api/services"); + assertTrue(answer.startsWith("console ")); + String posted = http.toBlocking().retrieve(HttpRequest.POST("/__tracepanel__/api/settings", "{\"theme\":\"dark\"}") + .contentType("application/json")); + assertTrue(posted.startsWith("console ")); + assertTrue(FakeAgent.CONSOLE_CALLS.stream().anyMatch(call -> call.equals("POST /api/settings {\"theme\":\"dark\"}"))); + assertTrue(FakeAgent.TRACES.stream().noneMatch(trace -> String.valueOf(trace.get("name")).contains("__tracepanel__"))); + } + + @Client("/") + interface EchoClient { + @Get("/probe/echo") String echo(); + } + + @Controller("/probe") + @ExecuteOn(TaskExecutors.BLOCKING) + static class ProbeController { + private final DataSource database; + private final EchoClient client; + + ProbeController(DataSource database, EchoClient client) { this.database = database; this.client = client; } + + @Get("/books/{id}") + String book(long id) throws SQLException { + query(); + org.slf4j.LoggerFactory.getLogger(ProbeController.class).info("loaded book {}", id); + return "book " + id + " " + client.echo(); + } + + @Get("/reactive/{id}") + Mono reactive(long id) { + return Mono.fromCallable(() -> { query(); return "reactive"; }).subscribeOn(Schedulers.boundedElastic()); + } + + @Get("/echo") String echo() { return "echo"; } + @Get("/failure") String failure() { throw new IllegalStateException("broken controller"); } + @Get(value = "/page", produces = "text/html") String page() { return "Shop"; } + + private void query() throws SQLException { + try (var connection = database.getConnection(); var statement = connection.prepareStatement("SELECT 1"); + var rows = statement.executeQuery()) { + assertTrue(rows.next()); + } + } + } +} From b1516de1ecddb76846002510d45d80c075d53ee4 Mon Sep 17 00:00:00 2001 From: Pavel Lavreshin Date: Sat, 14 Nov 2026 09:35:26 +0200 Subject: [PATCH 02/12] fix(micronaut): resolve response media types and complete CI coverage --- .github/workflows/ci.yml | 16 ++++++++++++++++ tracepanel-micronaut/build.gradle.kts | 18 +++++++++++------- .../micronaut/TracepanelServerFilter.java | 13 ++++++++++--- .../tracepanel/micronaut/DataSourcesTest.java | 3 ++- .../dev/tracepanel/micronaut/FilterTest.java | 18 ++++++++++++------ .../test/java/shop/MicronautTracingTest.java | 2 +- 6 files changed, 52 insertions(+), 18 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9a2e26c..e920909 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -84,6 +84,14 @@ jobs: -Porg.gradle.java.installations.fromEnv=JAVA_HOME_${{ matrix.java }}_X64 - if: matrix.java == '21' run: ./gradlew publishToMavenLocal --console=plain + - uses: actions/upload-artifact@v7 + if: failure() + with: + name: test-reports-java-${{ matrix.java }} + path: | + **/build/reports/tests/** + **/build/test-results/** + retention-days: 7 micronaut5: name: Micronaut 5 on Java 25 @@ -101,6 +109,14 @@ jobs: 21 - uses: gradle/actions/setup-gradle@v6 - run: ./gradlew :tracepanel-micronaut:testMicronaut5 :tracepanel-micronaut:testMicronaut5Integration --console=plain -Porg.gradle.java.installations.fromEnv=JAVA_HOME_25_X64 + - uses: actions/upload-artifact@v7 + if: failure() + with: + name: test-reports-micronaut5 + path: | + tracepanel-micronaut/build/reports/tests/** + tracepanel-micronaut/build/test-results/** + retention-days: 7 # The branch's required check: every Java's tests passed, or the build was skipped. check: diff --git a/tracepanel-micronaut/build.gradle.kts b/tracepanel-micronaut/build.gradle.kts index d51ab78..daf7be8 100644 --- a/tracepanel-micronaut/build.gradle.kts +++ b/tracepanel-micronaut/build.gradle.kts @@ -2,6 +2,8 @@ description = "Tracepanel for Micronaut: request traces, JDBC, declarative HTTP val micronaut4 = "4.10.24" val micronaut5 = "5.2.6" +val h2 = "2.5.252" +val logback = "1.6.6" dependencies { api(project(":tracepanel-core")) @@ -9,8 +11,10 @@ dependencies { compileOnly("io.micronaut:micronaut-http-server") compileOnly("io.micronaut:micronaut-http-client-core") compileOnly("io.micronaut:micronaut-core-reactive") + compileOnly("org.jetbrains:annotations:26.1.0") implementation("io.micronaut.reactor:micronaut-reactor:3.9.1") - compileOnly("ch.qos.logback:logback-classic:1.5.18") + implementation("io.projectreactor:reactor-core:3.7.19") + compileOnly("ch.qos.logback:logback-classic:$logback") annotationProcessor(platform("io.micronaut.platform:micronaut-platform:$micronaut4")) annotationProcessor("io.micronaut:micronaut-inject-java") @@ -22,8 +26,8 @@ dependencies { testImplementation("io.micronaut.reactor:micronaut-reactor") testImplementation("io.micronaut.sql:micronaut-jdbc-hikari") testImplementation("io.projectreactor:reactor-core") - testImplementation("com.h2database:h2:2.4.240") - testImplementation("ch.qos.logback:logback-classic:1.5.18") + testImplementation("com.h2database:h2:$h2") + testImplementation("ch.qos.logback:logback-classic:$logback") testImplementation(testFixtures(project(":tracepanel-core"))) testAnnotationProcessor(platform("io.micronaut.platform:micronaut-platform:$micronaut4")) testAnnotationProcessor("io.micronaut:micronaut-inject-java") @@ -42,9 +46,9 @@ val micronaut5Tests = testing.suites.register("testMicronaut5") { implementation("io.micronaut:micronaut-jackson-databind") implementation("io.micronaut.reactor:micronaut-reactor") implementation("io.micronaut.sql:micronaut-jdbc-hikari") - implementation("io.projectreactor:reactor-core") - implementation("com.h2database:h2:2.4.240") - implementation("ch.qos.logback:logback-classic:1.5.18") + implementation("io.projectreactor:reactor-core:3.8.8") + implementation("com.h2database:h2:$h2") + implementation("ch.qos.logback:logback-classic:$logback") implementation(testFixtures(project(":tracepanel-core"))) } targets.all { @@ -73,7 +77,7 @@ tasks.withType().configureEach { // Separate JVMs keep the core's process-wide recorder and fake agent out of unit tests. tasks.test { useJUnitPlatform { excludeTags("integration") } } -val integrationTest by tasks.registering(Test::class) { +val integrationTest = tasks.register("integrationTest") { testClassesDirs = sourceSets.test.get().output.classesDirs classpath = sourceSets.test.get().runtimeClasspath useJUnitPlatform { includeTags("integration") } diff --git a/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelServerFilter.java b/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelServerFilter.java index d923554..6d407e6 100644 --- a/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelServerFilter.java +++ b/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelServerFilter.java @@ -15,6 +15,9 @@ import io.micronaut.http.HttpRequest; import io.micronaut.http.HttpResponse; import io.micronaut.http.MutableHttpResponse; +import io.micronaut.http.MediaType; +import io.micronaut.http.server.RouteExecutor; +import jakarta.inject.Provider; import io.micronaut.http.ServerHttpRequest; import io.micronaut.http.annotation.Filter; import io.micronaut.http.filter.HttpServerFilter; @@ -43,10 +46,12 @@ final class TracepanelServerFilter implements HttpServerFilter { private final Tracepanel tracepanel; private final String prefix; private final HttpHostResolver hosts; + private final Provider routes; - TracepanelServerFilter(Tracepanel tracepanel, @Value("${micronaut.server.context-path:}") String contextPath, HttpHostResolver hosts) { + TracepanelServerFilter(Tracepanel tracepanel, @Value("${micronaut.server.context-path:}") String contextPath, HttpHostResolver hosts, Provider routes) { this.tracepanel = tracepanel; this.hosts = hosts; + this.routes = routes; this.prefix = contextPath.replaceAll("/+$", "") + tracepanel.config().prefix(); } @@ -128,8 +133,10 @@ private void response(HttpRequest request, MutableHttpResponse response, T if (bytes != null) RequestDetails.body(request.getContentType().map(Object::toString).orElse(""), bytes, true) .forEach((key, value) -> trace.attr("http.request." + key, value)); } - if (response.getContentType().filter(type -> type.getName().equals("text/html")).isEmpty() - || response.getHeaders().contains(HttpHeaders.CONTENT_ENCODING)) return; + // Netty applies the route's content type after response filters have run. + MediaType contentType = response.getContentType().orElseGet(() -> RouteAttributes.getRouteInfo(response) + .map(info -> routes.get().resolveDefaultResponseContentType(request, info)).orElse(MediaType.APPLICATION_JSON_TYPE)); + if (!contentType.getName().equals("text/html") || response.getHeaders().contains(HttpHeaders.CONTENT_ENCODING)) return; Object body = response.getBody().orElse(null); String html = body instanceof String text ? text : body instanceof byte[] bytes ? new String(bytes, response.getCharacterEncoding()) : null; diff --git a/tracepanel-micronaut/src/test/java/dev/tracepanel/micronaut/DataSourcesTest.java b/tracepanel-micronaut/src/test/java/dev/tracepanel/micronaut/DataSourcesTest.java index 02a37f7..c9c2e38 100644 --- a/tracepanel-micronaut/src/test/java/dev/tracepanel/micronaut/DataSourcesTest.java +++ b/tracepanel-micronaut/src/test/java/dev/tracepanel/micronaut/DataSourcesTest.java @@ -52,7 +52,8 @@ public void begun(Trace trace) {} recorder.finish(trace); long queries = trace.spans().stream().filter(span -> "sql".equals(span.get("kind"))).count(); assertEquals(2, queries); - TracepanelServerFilter filter = new TracepanelServerFilter(recorder, "", request -> "http://localhost"); + TracepanelServerFilter filter = new TracepanelServerFilter(recorder, "", request -> "http://localhost", + () -> { throw new AssertionError("No route lookup expected for a synthetic response"); }); Flux.from(filter.doFilter(HttpRequest.GET("/reactive"), request -> Mono.>fromCallable(() -> { assertNotNull(Tracepanel.current()); DataSource pool = context.getBean(DataSource.class); diff --git a/tracepanel-micronaut/src/test/java/dev/tracepanel/micronaut/FilterTest.java b/tracepanel-micronaut/src/test/java/dev/tracepanel/micronaut/FilterTest.java index e88ab37..c140a01 100644 --- a/tracepanel-micronaut/src/test/java/dev/tracepanel/micronaut/FilterTest.java +++ b/tracepanel-micronaut/src/test/java/dev/tracepanel/micronaut/FilterTest.java @@ -60,7 +60,8 @@ void contextRestoresThePreviousTraceAcrossThreads() { @Test void serverRecordsErrorsAndRestoresThreadContext() { - TracepanelServerFilter filter = new TracepanelServerFilter(recorder, "", request -> "http://localhost"); + TracepanelServerFilter filter = new TracepanelServerFilter(recorder, "", request -> "http://localhost", + () -> { throw new AssertionError("No route lookup expected for a synthetic response"); }); assertThrows(IllegalStateException.class, () -> Flux.from(filter.doFilter(HttpRequest.GET("/fail"), request -> { assertNotNull(Tracepanel.current()); return Mono.error(new IllegalStateException("broken")); @@ -71,7 +72,8 @@ void serverRecordsErrorsAndRestoresThreadContext() { @Test void cancellationFinishesTheTraceExactlyOnce() { - TracepanelServerFilter filter = new TracepanelServerFilter(recorder, "", request -> "http://localhost"); + TracepanelServerFilter filter = new TracepanelServerFilter(recorder, "", request -> "http://localhost", + () -> { throw new AssertionError("No route lookup expected for a synthetic response"); }); var subscription = Flux.from(filter.doFilter(HttpRequest.GET("/cancel"), request -> Mono.never())).subscribe(); subscription.dispose(); assertEquals(1, DOCUMENTS.size()); @@ -81,7 +83,8 @@ void cancellationFinishesTheTraceExactlyOnce() { @Test void preflightBypassesTracingButOrdinaryOptionsDoesNot() { - TracepanelServerFilter filter = new TracepanelServerFilter(recorder, "", request -> "http://localhost"); + TracepanelServerFilter filter = new TracepanelServerFilter(recorder, "", request -> "http://localhost", + () -> { throw new AssertionError("No route lookup expected for a synthetic response"); }); Flux.from(filter.doFilter(HttpRequest.OPTIONS("/cors").header("Origin", "https://shop.test") .header("Access-Control-Request-Method", "GET"), request -> Mono.just(HttpResponse.ok()))).blockLast(); assertTrue(DOCUMENTS.isEmpty()); @@ -119,7 +122,8 @@ void clientRecordsSynchronousFailuresAndCancellationOnce() { @Test void handledClientErrorsKeepTheirStatusWithoutAnException() { - TracepanelServerFilter filter = new TracepanelServerFilter(recorder, "", request -> "http://localhost"); + TracepanelServerFilter filter = new TracepanelServerFilter(recorder, "", request -> "http://localhost", + () -> { throw new AssertionError("No route lookup expected for a synthetic response"); }); Flux.from(filter.doFilter(HttpRequest.GET("/invalid"), request -> Mono.just(HttpResponse.unprocessableEntity()))).blockLast(); Map trace = DOCUMENTS.get(0); assertEquals("ok", trace.get("status")); @@ -128,7 +132,8 @@ void handledClientErrorsKeepTheirStatusWithoutAnException() { @Test void htmlInjectionPreservesCharsetAndDropsStaleEntityHeaders() { - TracepanelServerFilter filter = new TracepanelServerFilter(recorder, "/shop/", request -> "http://localhost"); + TracepanelServerFilter filter = new TracepanelServerFilter(recorder, "/shop/", request -> "http://localhost", + () -> { throw new AssertionError("No route lookup expected for a synthetic response"); }); var response = HttpResponse.ok("Café".getBytes(java.nio.charset.StandardCharsets.ISO_8859_1)) .contentType("text/html; charset=ISO-8859-1").header("ETag", "old").header("Content-Length", "55"); io.micronaut.http.MutableHttpResponse result; @@ -149,7 +154,8 @@ void htmlInjectionPreservesCharsetAndDropsStaleEntityHeaders() { @Test void encodedAndStreamingResponsesStayUnchanged() { - TracepanelServerFilter filter = new TracepanelServerFilter(recorder, "", request -> "http://localhost"); + TracepanelServerFilter filter = new TracepanelServerFilter(recorder, "", request -> "http://localhost", + () -> { throw new AssertionError("No route lookup expected for a synthetic response"); }); var compressed = HttpResponse.ok("compressed").contentType("text/html").header("Content-Encoding", "gzip"); assertSame(compressed, Flux.from(filter.doFilter(HttpRequest.GET("/gzip"), request -> Mono.just(compressed))).blockLast()); assertEquals("compressed", compressed.body()); diff --git a/tracepanel-micronaut/src/test/java/shop/MicronautTracingTest.java b/tracepanel-micronaut/src/test/java/shop/MicronautTracingTest.java index 146b5a0..d912242 100644 --- a/tracepanel-micronaut/src/test/java/shop/MicronautTracingTest.java +++ b/tracepanel-micronaut/src/test/java/shop/MicronautTracingTest.java @@ -80,7 +80,7 @@ void frameworkErrorResponseKeepsTheException() throws Exception { @Test void htmlHasTheBadgeAndTheConsoleDoesNotTraceItself() { String page = http.toBlocking().retrieve("/probe/page"); - assertTrue(page.contains("/__tracepanel__/widget.min.js")); + assertTrue(page.contains("/__tracepanel__/widget.min.js"), page); String answer = http.toBlocking().retrieve("/__tracepanel__/api/services"); assertTrue(answer.startsWith("console ")); String posted = http.toBlocking().retrieve(HttpRequest.POST("/__tracepanel__/api/settings", "{\"theme\":\"dark\"}") From 1f442915a7910b2cb14dd9bb1d67005c7dac417b Mon Sep 17 00:00:00 2001 From: Pavel Lavreshin Date: Sat, 14 Nov 2026 09:40:12 +0200 Subject: [PATCH 03/12] fix(micronaut): package documentation for internal beans --- tracepanel-micronaut/build.gradle.kts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tracepanel-micronaut/build.gradle.kts b/tracepanel-micronaut/build.gradle.kts index daf7be8..148e824 100644 --- a/tracepanel-micronaut/build.gradle.kts +++ b/tracepanel-micronaut/build.gradle.kts @@ -94,3 +94,8 @@ tasks.register("testMicronaut5Integration") { shouldRunAfter(tasks.named("testMicronaut5")) } tasks.check { dependsOn(integrationTest) } + +// The auto-configured integration has package-private beans rather than a public API. +tasks.javadoc { + (options as StandardJavadocDocletOptions).memberLevel = JavadocMemberLevel.PACKAGE +} From b9929e60f14b49668a069012bcf3d0101ff21a16 Mon Sep 17 00:00:00 2001 From: antonrh Date: Tue, 17 Nov 2026 07:55:27 +0200 Subject: [PATCH 04/12] Micronaut: Reactor from the app, not pinned by the SDK reactor-core comes with Micronaut's Netty server and HTTP client, of the app's own version: compileOnly. micronaut-reactor is no longer forced on every app (Micronaut 5 runs micronaut-reactor 4.x; a Maven build without the platform BOM got 3.9.1). A reactive app has it already, and it carries the trace across Reactor's threads. --- tracepanel-micronaut/build.gradle.kts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tracepanel-micronaut/build.gradle.kts b/tracepanel-micronaut/build.gradle.kts index 148e824..a5c618e 100644 --- a/tracepanel-micronaut/build.gradle.kts +++ b/tracepanel-micronaut/build.gradle.kts @@ -12,8 +12,8 @@ dependencies { compileOnly("io.micronaut:micronaut-http-client-core") compileOnly("io.micronaut:micronaut-core-reactive") compileOnly("org.jetbrains:annotations:26.1.0") - implementation("io.micronaut.reactor:micronaut-reactor:3.9.1") - implementation("io.projectreactor:reactor-core:3.7.19") + // Reactor comes with Micronaut's Netty server and HTTP client, of the app's own version. + compileOnly("io.projectreactor:reactor-core") compileOnly("ch.qos.logback:logback-classic:$logback") annotationProcessor(platform("io.micronaut.platform:micronaut-platform:$micronaut4")) annotationProcessor("io.micronaut:micronaut-inject-java") From d3ef19b73b6a6c1cee0bb2cd1471d819571da526 Mon Sep 17 00:00:00 2001 From: antonrh Date: Tue, 17 Nov 2026 07:56:09 +0200 Subject: [PATCH 05/12] Micronaut: the app's packages in stacks, Log4j 2, and once in the log when it's off As the Spring and Ktor integrations do: Tracepanel.start gets the packages Micronaut.run(Application.class) names, so its generated classes aren't the app's frames; Log4j 2 records are recorded beside Logback's; outside a dev environment it says once why it's off. The classes say what they are, as the other modules' do. --- tracepanel-micronaut/build.gradle.kts | 1 + .../micronaut/TracepanelConfiguration.java | 25 ++++++++++++++----- .../micronaut/TracepanelEnabled.java | 23 ++++++++++++++--- 3 files changed, 39 insertions(+), 10 deletions(-) diff --git a/tracepanel-micronaut/build.gradle.kts b/tracepanel-micronaut/build.gradle.kts index a5c618e..ccb8b3f 100644 --- a/tracepanel-micronaut/build.gradle.kts +++ b/tracepanel-micronaut/build.gradle.kts @@ -15,6 +15,7 @@ dependencies { // Reactor comes with Micronaut's Netty server and HTTP client, of the app's own version. compileOnly("io.projectreactor:reactor-core") compileOnly("ch.qos.logback:logback-classic:$logback") + compileOnly("org.apache.logging.log4j:log4j-core:2.24.3") annotationProcessor(platform("io.micronaut.platform:micronaut-platform:$micronaut4")) annotationProcessor("io.micronaut:micronaut-inject-java") diff --git a/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelConfiguration.java b/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelConfiguration.java index 68d25b9..c7d36b9 100644 --- a/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelConfiguration.java +++ b/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelConfiguration.java @@ -2,6 +2,8 @@ import dev.tracepanel.core.Config; import dev.tracepanel.core.Tracepanel; +import dev.tracepanel.integrations.Log4j2Recorder; +import dev.tracepanel.integrations.LogbackRecorder; import io.micronaut.context.annotation.Factory; import io.micronaut.context.annotation.Requires; import io.micronaut.context.env.Environment; @@ -10,19 +12,30 @@ import jakarta.inject.Singleton; import java.util.List; +/** + * Tracepanel in a Micronaut app, from the dependency alone: each request, SQL through its DataSources, calls through + * its HTTP clients, logs, the widget and the console. Meant for development: add it as developmentOnly (Gradle) or an + * optional dependency the app's production build leaves out; TRACEPANEL_ENABLED=0 turns it off. + */ @Factory @Requires(condition = TracepanelEnabled.class) final class TracepanelConfiguration { @Singleton Tracepanel tracepanel(Environment environment) { - Config config = Config.load(name -> environment.getProperty(name, String.class) - .or(() -> environment.getProperty(Config.property(name), String.class)).orElse(null), + // Each setting from its variable (TRACEPANEL_SLOW_SQL_MS), else from the app's properties (tracepanel.slow-sql-ms). + Config config = Config.load( + name -> environment.getProperty(name, String.class) + .or(() -> environment.getProperty(Config.property(name), String.class)).orElse(null), environment.getProperty("micronaut.application.name", String.class).orElse(null)); - Tracepanel tracepanel = Tracepanel.start(config, List.of()); + // The app's packages, as Micronaut.run(Application.class) names them: its frames in stacks. + Tracepanel tracepanel = Tracepanel.start(config, List.copyOf(environment.getPackages())); tracepanel.framework("Micronaut " + VersionUtils.MICRONAUT_VERSION); - if (ClassUtils.isPresent("ch.qos.logback.classic.LoggerContext", getClass().getClassLoader())) { - dev.tracepanel.integrations.LogbackRecorder.install(tracepanel); - } + if (isPresent("ch.qos.logback.classic.LoggerContext")) LogbackRecorder.install(tracepanel); + if (isPresent("org.apache.logging.log4j.core.LoggerContext")) Log4j2Recorder.install(tracepanel); return tracepanel; } + + private static boolean isPresent(String name) { + return ClassUtils.isPresent(name, TracepanelConfiguration.class.getClassLoader()); + } } diff --git a/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelEnabled.java b/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelEnabled.java index 0515c12..920fd2a 100644 --- a/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelEnabled.java +++ b/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelEnabled.java @@ -6,23 +6,38 @@ import io.micronaut.context.env.Environment; import java.util.Locale; import java.util.Set; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +/** + * On in development only: when TRACEPANEL_ENABLED (or tracepanel.enabled) says so, else when an environment names + * development (dev, development, local). A dependency that reached a production build by mistake records nothing and + * serves no console there. + */ final class TracepanelEnabled implements Condition { private static final Set OFF = Set.of("0", "false", "no", "off"); private static final Set DEVELOPMENT = Set.of("dev", "development", "local"); + private static final Logger LOG = LoggerFactory.getLogger(TracepanelEnabled.class); + private static volatile boolean told; @Override @SuppressWarnings("rawtypes") public boolean matches(ConditionContext context) { if (!(context.getBeanContext() instanceof ApplicationContext application)) return false; - return enabled(application.getEnvironment()); + boolean on = enabled(application.getEnvironment()); + if (!on && !told) { + told = true; + LOG.info("Tracepanel is off: no dev or local environment, so this may not be development. " + + "TRACEPANEL_ENABLED=1 turns it on."); + } + return on; } static boolean enabled(Environment environment) { - String explicit = environment.getProperty("TRACEPANEL_ENABLED", String.class) + String value = environment.getProperty("TRACEPANEL_ENABLED", String.class) .or(() -> environment.getProperty("tracepanel.enabled", String.class)).orElse("").trim(); - if (!explicit.isEmpty()) return !OFF.contains(explicit.toLowerCase(Locale.ROOT)); + if (!value.isEmpty()) return !OFF.contains(value.toLowerCase(Locale.ROOT)); return environment.getActiveNames().stream() - .map(name -> name.toLowerCase(Locale.ROOT)).anyMatch(DEVELOPMENT::contains); + .anyMatch(name -> DEVELOPMENT.contains(name.toLowerCase(Locale.ROOT))); } } From 4eed8f3b6f1f466e400fa3d3654401e652777c82 Mon Sep 17 00:00:00 2001 From: antonrh Date: Tue, 17 Nov 2026 07:56:46 +0200 Subject: [PATCH 06/12] Micronaut: each class says what it records; imports sorted, no qualified names in code --- .../dev/tracepanel/micronaut/DataSources.java | 4 ++++ .../dev/tracepanel/micronaut/TraceContext.java | 1 + .../micronaut/TracepanelClientFilter.java | 9 +++++++-- .../micronaut/TracepanelServerFilter.java | 17 ++++++++++++----- 4 files changed, 24 insertions(+), 7 deletions(-) diff --git a/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/DataSources.java b/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/DataSources.java index 6f79613..faa12d7 100644 --- a/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/DataSources.java +++ b/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/DataSources.java @@ -9,6 +9,10 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +/** + * The app's DataSources, each wrapped as it is made: SQL, transactions and EXPLAIN on its connections. A bean whose + * type is a pool class can't take the wrapper: it stays as it is, and the log says how to have it recorded. + */ @Singleton @Requires(condition = TracepanelEnabled.class) final class DataSources implements BeanCreatedEventListener { diff --git a/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TraceContext.java b/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TraceContext.java index 162b56f..add121d 100644 --- a/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TraceContext.java +++ b/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TraceContext.java @@ -5,6 +5,7 @@ import io.micronaut.core.annotation.Nullable; import io.micronaut.core.propagation.ThreadPropagatedContextElement; +/** The request's trace on whichever thread Micronaut runs its work: its executors, Reactor's schedulers. */ record TraceContext(Trace trace) implements ThreadPropagatedContextElement { @Override public Trace updateThreadContext() { diff --git a/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelClientFilter.java b/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelClientFilter.java index 0e0e6d6..93c028b 100644 --- a/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelClientFilter.java +++ b/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelClientFilter.java @@ -14,6 +14,10 @@ import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; +/** + * Calls through Micronaut's HTTP clients, declarative (@Client) or not: each a span of the trace, the call carrying it + * on (traceparent), and the profile asked for when the trace is profiled. A header the app set stays. + */ @Filter("/**") @Requires(classes = HttpClientFilter.class, condition = TracepanelEnabled.class) final class TracepanelClientFilter implements HttpClientFilter { @@ -26,15 +30,16 @@ public Publisher> doFilter(MutableHttpRequest reque if (call.profile() != null && !request.getHeaders().contains(Profiler.HEADER)) { request.header(Profiler.HEADER, call.profile()); } + // Ended once: by its answer, its error, a stream that ended with no answer, or the caller giving up. AtomicBoolean finished = new AtomicBoolean(); return Flux.defer(() -> Flux.>from(chain.proceed(request))) .doOnNext(response -> { if (finished.compareAndSet(false, true)) call.end(response.code()); }) .doOnError(error -> { if (finished.compareAndSet(false, true)) call.failed(error); }) .doOnComplete(() -> { - if (finished.compareAndSet(false, true)) call.failed(new IllegalStateException("HTTP call completed without a response")); + if (finished.compareAndSet(false, true)) call.failed(new IllegalStateException("no answer")); }) .doOnCancel(() -> { - if (finished.compareAndSet(false, true)) call.failed(new CancellationException("HTTP call cancelled")); + if (finished.compareAndSet(false, true)) call.failed(new CancellationException("cancelled")); }); }); } diff --git a/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelServerFilter.java b/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelServerFilter.java index 6d407e6..3162275 100644 --- a/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelServerFilter.java +++ b/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelServerFilter.java @@ -14,19 +14,20 @@ import io.micronaut.http.HttpHeaders; import io.micronaut.http.HttpRequest; import io.micronaut.http.HttpResponse; -import io.micronaut.http.MutableHttpResponse; +import io.micronaut.http.HttpStatus; import io.micronaut.http.MediaType; -import io.micronaut.http.server.RouteExecutor; -import jakarta.inject.Provider; +import io.micronaut.http.MutableHttpResponse; import io.micronaut.http.ServerHttpRequest; import io.micronaut.http.annotation.Filter; import io.micronaut.http.filter.HttpServerFilter; import io.micronaut.http.filter.ServerFilterChain; import io.micronaut.http.filter.ServerFilterPhase; +import io.micronaut.http.server.RouteExecutor; import io.micronaut.http.server.util.HttpHostResolver; import io.micronaut.web.router.MethodBasedRouteMatch; import io.micronaut.web.router.RouteAttributes; import io.micronaut.web.router.UriRouteMatch; +import jakarta.inject.Provider; import java.io.IOException; import java.io.InputStream; import java.nio.charset.StandardCharsets; @@ -40,6 +41,11 @@ import reactor.core.publisher.SignalType; import reactor.core.scheduler.Schedulers; +/** + * Each request a trace, named by its route (GET /books/{id}) and the controller method that ran it, its time and + * status; the badge on the app's HTML pages; the console under its prefix (/__tracepanel__/), answered by the agent. + * First of the filters: the trace holds what the others and the route do. + */ @Filter("/**") @Requires(classes = HttpServerFilter.class, condition = TracepanelEnabled.class) final class TracepanelServerFilter implements HttpServerFilter { @@ -48,7 +54,8 @@ final class TracepanelServerFilter implements HttpServerFilter { private final HttpHostResolver hosts; private final Provider routes; - TracepanelServerFilter(Tracepanel tracepanel, @Value("${micronaut.server.context-path:}") String contextPath, HttpHostResolver hosts, Provider routes) { + TracepanelServerFilter(Tracepanel tracepanel, @Value("${micronaut.server.context-path:}") String contextPath, + HttpHostResolver hosts, Provider routes) { this.tracepanel = tracepanel; this.hosts = hosts; this.routes = routes; @@ -174,7 +181,7 @@ private Publisher> console(HttpRequest request, String Console.Answer answer = Console.forward(tracepanel, request.getMethodName(), path + (query == null ? "" : "?" + query), request.getContentType().map(Object::toString).orElse(null), body, address); - MutableHttpResponse response = HttpResponse.status(io.micronaut.http.HttpStatus.valueOf(answer.status())) + MutableHttpResponse response = HttpResponse.status(HttpStatus.valueOf(answer.status())) .body(answer.body()).contentType(answer.contentType()); answer.headers().forEach(response::header); return response; From 5074e249d4b6cbf7d6292c6b3ba2cd61fb6a427b Mon Sep 17 00:00:00 2001 From: antonrh Date: Tue, 17 Nov 2026 08:01:00 +0200 Subject: [PATCH 07/12] Micronaut: a request that answered isn't failed by the cancel after it Micronaut takes the response and cancels the rest of the filter chain: every answered request was recorded failed (status error with a 200). A cancel fails the trace only before its answer. The tests now check the status of an answered request. --- .../tracepanel/micronaut/TracepanelServerFilter.java | 10 ++++++++-- .../java/dev/tracepanel/micronaut/FilterTest.java | 11 +++++++++++ .../src/test/java/shop/MicronautTracingTest.java | 1 + 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelServerFilter.java b/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelServerFilter.java index 3162275..69643f5 100644 --- a/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelServerFilter.java +++ b/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/TracepanelServerFilter.java @@ -35,6 +35,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.concurrent.atomic.AtomicBoolean; import org.reactivestreams.Publisher; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -98,11 +99,15 @@ private Publisher> traced(HttpRequest request, ServerF Profiler.reason(profile, cookies, attrs.containsKey("w3c.parent_span_id"))); Tracepanel.bind(previous); PropagatedContext context = PropagatedContext.getOrEmpty().plus(new TraceContext(trace)); + AtomicBoolean answered = new AtomicBoolean(); return ReactivePropagation.propagate(context, Flux.defer(() -> { try (PropagatedContext.Scope ignored = context.propagate()) { return Flux.from(chain.proceed(request)); } - }).doOnNext(response -> response(request, response, trace)) + }).doOnNext(response -> { + answered.set(true); + response(request, response, trace); + }) .doOnError(error -> { trace.failed(); trace.attr("http.status_code", 500); @@ -110,7 +115,8 @@ private Publisher> traced(HttpRequest request, ServerF }) .doFinally(signal -> { try (PropagatedContext.Scope ignored = context.propagate()) { - if (signal == SignalType.CANCEL) trace.failed(); + // Micronaut cancels the chain once it has the response: only a request cut before its answer failed. + if (signal == SignalType.CANCEL && !answered.get()) trace.failed(); route(request, trace); tracepanel.finish(trace); } diff --git a/tracepanel-micronaut/src/test/java/dev/tracepanel/micronaut/FilterTest.java b/tracepanel-micronaut/src/test/java/dev/tracepanel/micronaut/FilterTest.java index c140a01..1037fa8 100644 --- a/tracepanel-micronaut/src/test/java/dev/tracepanel/micronaut/FilterTest.java +++ b/tracepanel-micronaut/src/test/java/dev/tracepanel/micronaut/FilterTest.java @@ -70,6 +70,17 @@ void serverRecordsErrorsAndRestoresThreadContext() { assertEquals("error", DOCUMENTS.get(0).get("status")); } + @Test + void theCancelAfterTheResponseLeavesTheTraceOk() { + TracepanelServerFilter filter = new TracepanelServerFilter(recorder, "", request -> "http://localhost", + () -> { throw new AssertionError("No route lookup expected for a synthetic response"); }); + // As Micronaut takes the response: the first one, then it cancels the rest of the chain. + Mono.from(filter.doFilter(HttpRequest.GET("/ok"), request -> Flux.just(HttpResponse.ok(), HttpResponse.ok()))) + .block(); + assertEquals(1, DOCUMENTS.size()); + assertEquals("ok", DOCUMENTS.get(0).get("status")); + } + @Test void cancellationFinishesTheTraceExactlyOnce() { TracepanelServerFilter filter = new TracepanelServerFilter(recorder, "", request -> "http://localhost", diff --git a/tracepanel-micronaut/src/test/java/shop/MicronautTracingTest.java b/tracepanel-micronaut/src/test/java/shop/MicronautTracingTest.java index d912242..a806caf 100644 --- a/tracepanel-micronaut/src/test/java/shop/MicronautTracingTest.java +++ b/tracepanel-micronaut/src/test/java/shop/MicronautTracingTest.java @@ -52,6 +52,7 @@ void routeHasSqlClientCallLogsAndTraceHeaders() throws Exception { assertEquals("book 7 echo", response.body()); Map trace = FakeAgent.traceAt("/probe/books/7"); assertEquals("GET /probe/books/{id}", trace.get("name")); + assertEquals("ok", trace.get("status")); assertTrue(trace.get("spans") instanceof List spans && spans.stream().anyMatch(value -> value instanceof Map span && "sql".equals(span.get("kind")))); assertTrue(trace.get("spans") instanceof List spans && spans.stream().anyMatch(value -> From 3425903d916ea104c8bc4a7b643944efa337d725 Mon Sep 17 00:00:00 2001 From: antonrh Date: Tue, 17 Nov 2026 08:01:00 +0200 Subject: [PATCH 08/12] Micronaut: the SDK's DataSource wrapper under Micronaut Data's Both wrap each DataSource as it is made, in no set order. Over Micronaut Data's contextual proxy, its transaction manager held one connection and the proxy looked for another: a @Transactional method failed with NoConnectionException, now and then. The SDK's listener goes first, so it wraps the pool. A suite on Micronaut Data's classpath (testMicronautData) checks a @Transactional method: one committed transaction holding its statements. --- tracepanel-micronaut/build.gradle.kts | 29 +++++- .../dev/tracepanel/micronaut/DataSources.java | 10 ++- .../java/data/MicronautDataTest.java | 88 +++++++++++++++++++ 3 files changed, 125 insertions(+), 2 deletions(-) create mode 100644 tracepanel-micronaut/src/testMicronautData/java/data/MicronautDataTest.java diff --git a/tracepanel-micronaut/build.gradle.kts b/tracepanel-micronaut/build.gradle.kts index ccb8b3f..96f6eda 100644 --- a/tracepanel-micronaut/build.gradle.kts +++ b/tracepanel-micronaut/build.gradle.kts @@ -94,7 +94,34 @@ tasks.register("testMicronaut5Integration") { environment("TRACEPANEL_AGENT", "auto") shouldRunAfter(tasks.named("testMicronaut5")) } -tasks.check { dependsOn(integrationTest) } +// Micronaut Data makes the app's DataSource transaction-aware: its own classpath, with the SDK's wrapper under it. +val micronautDataTests = testing.suites.register("testMicronautData") { + useJUnitJupiter("6.1.3") + dependencies { + implementation(project()) + implementation(platform("io.micronaut.platform:micronaut-platform:$micronaut4")) + implementation("io.micronaut.test:micronaut-test-junit5") + implementation("io.micronaut:micronaut-http-server-netty") + implementation("io.micronaut:micronaut-http-client") + implementation("io.micronaut:micronaut-jackson-databind") + implementation("io.micronaut.sql:micronaut-jdbc-hikari") + implementation("io.micronaut.data:micronaut-data-tx-jdbc") + implementation("ch.qos.logback:logback-classic:$logback") + implementation("com.h2database:h2:$h2") + implementation(testFixtures(project(":tracepanel-core"))) + } + targets.all { + testTask.configure { + environment("TRACEPANEL_AGENT", "auto") + shouldRunAfter(integrationTest) + } + } +} +dependencies { + "testMicronautDataAnnotationProcessor"(platform("io.micronaut.platform:micronaut-platform:$micronaut4")) + "testMicronautDataAnnotationProcessor"("io.micronaut:micronaut-inject-java") +} +tasks.check { dependsOn(integrationTest, micronautDataTests) } // The auto-configured integration has package-private beans rather than a public API. tasks.javadoc { diff --git a/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/DataSources.java b/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/DataSources.java index faa12d7..59c0b5e 100644 --- a/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/DataSources.java +++ b/tracepanel-micronaut/src/main/java/dev/tracepanel/micronaut/DataSources.java @@ -4,6 +4,7 @@ import io.micronaut.context.annotation.Requires; import io.micronaut.context.event.BeanCreatedEvent; import io.micronaut.context.event.BeanCreatedEventListener; +import io.micronaut.core.order.Ordered; import jakarta.inject.Singleton; import javax.sql.DataSource; import org.slf4j.Logger; @@ -15,9 +16,16 @@ */ @Singleton @Requires(condition = TracepanelEnabled.class) -final class DataSources implements BeanCreatedEventListener { +final class DataSources implements BeanCreatedEventListener, Ordered { private static final Logger LOG = LoggerFactory.getLogger(DataSources.class); + // First: the pool itself is wrapped, and Micronaut Data's contextual DataSource goes over it. Over that proxy, its + // transaction manager would hold one connection and the proxy look for another (NoConnectionException). + @Override + public int getOrder() { + return Ordered.HIGHEST_PRECEDENCE; + } + @Override public DataSource onCreated(BeanCreatedEvent event) { DataSource original = event.getBean(); diff --git a/tracepanel-micronaut/src/testMicronautData/java/data/MicronautDataTest.java b/tracepanel-micronaut/src/testMicronautData/java/data/MicronautDataTest.java new file mode 100644 index 0000000..a171a46 --- /dev/null +++ b/tracepanel-micronaut/src/testMicronautData/java/data/MicronautDataTest.java @@ -0,0 +1,88 @@ +package data; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +import dev.tracepanel.testing.FakeAgent; +import io.micronaut.context.annotation.Property; +import io.micronaut.http.annotation.Controller; +import io.micronaut.http.annotation.Get; +import io.micronaut.http.client.HttpClient; +import io.micronaut.http.client.annotation.Client; +import io.micronaut.scheduling.TaskExecutors; +import io.micronaut.scheduling.annotation.ExecuteOn; +import io.micronaut.test.extensions.junit5.annotation.MicronautTest; +import io.micronaut.test.support.TestPropertyProvider; +import io.micronaut.transaction.annotation.Transactional; +import jakarta.inject.Inject; +import java.io.IOException; +import java.io.UncheckedIOException; +import java.sql.SQLException; +import java.util.List; +import java.util.Map; +import javax.sql.DataSource; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.TestInstance; + +// A @Transactional method's statements, through Micronaut Data's transaction-aware DataSource: one transaction holds +// them, committed. +@MicronautTest(environments = "dev", transactional = false) +@Property(name = "datasources.default.url", value = "jdbc:h2:mem:data;DB_CLOSE_DELAY=-1") +@Property(name = "datasources.default.driver-class-name", value = "org.h2.Driver") +@TestInstance(TestInstance.Lifecycle.PER_CLASS) +class MicronautDataTest implements TestPropertyProvider { + @Inject @Client("/") HttpClient http; + + @Override + public Map getProperties() { + try { + FakeAgent.start(); + } catch (IOException error) { + throw new UncheckedIOException(error); + } + return Map.of(); + } + + @Test + void aTransactionHoldsItsStatements() throws Exception { + assertEquals("moved", http.toBlocking().retrieve("/accounts/transfer")); + Map trace = FakeAgent.traceAt("/accounts/transfer"); + + assertEquals("ok", trace.get("status")); + assertEquals(List.of( + "http GET /accounts/transfer", + "transaction commit", + "sql SELECT 1", + "sql SELECT 2"), ((List) trace.get("spans")).stream().map(MicronautDataTest::said).toList()); + } + + /** A span as the test reads it: its kind and what it is (a transaction's outcome, a statement). */ + private static String said(Object value) { + Map span = (Map) value; + Map attrs = (Map) span.get("attrs"); + return span.get("kind") + " " + switch (String.valueOf(span.get("kind"))) { + case "transaction" -> attrs.get("db.transaction.outcome"); + case "sql" -> attrs.get("db.statement"); + default -> span.get("name"); + }; + } + + @Controller("/accounts") + @ExecuteOn(TaskExecutors.BLOCKING) + static class AccountsController { + private final DataSource database; + + AccountsController(DataSource database) { this.database = database; } + + @Get("/transfer") + @Transactional + String transfer() throws SQLException { + for (String statement : List.of("SELECT 1", "SELECT 2")) { + try (var connection = database.getConnection(); var query = connection.prepareStatement(statement); + var rows = query.executeQuery()) { + rows.next(); + } + } + return "moved"; + } + } +} From 99b5df6ed92f53753b378dc7e0e3107b3106a3f0 Mon Sep 17 00:00:00 2001 From: antonrh Date: Tue, 17 Nov 2026 08:02:23 +0200 Subject: [PATCH 09/12] Stacks: Micronaut's compiled bean definitions are generated, not the app's $BookController$Definition$Exec sits in the app's package with no line to point at: an error's nearest app frame was it, not the controller's method. --- .../src/main/java/dev/tracepanel/core/Stacks.java | 5 +++-- .../src/test/java/dev/tracepanel/core/CoreTest.java | 3 ++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/tracepanel-core/src/main/java/dev/tracepanel/core/Stacks.java b/tracepanel-core/src/main/java/dev/tracepanel/core/Stacks.java index b600fb5..d2821ab 100644 --- a/tracepanel-core/src/main/java/dev/tracepanel/core/Stacks.java +++ b/tracepanel-core/src/main/java/dev/tracepanel/core/Stacks.java @@ -80,12 +80,13 @@ public boolean inApp(String className) { /** * Classes made at runtime in the app's packages: Hibernate's lazy proxies (Author$HibernateProxy, Hibernate 6's * name, or Author$HibernateProxy$…), Spring's CGLIB subclasses (…$$SpringCGLIB$$0), lambdas (…$$Lambda/0x…), - * ByteBuddy's, and the JDK's interface proxies ($Proxy172). Their frames have no line of the app's to point at. + * ByteBuddy's, the JDK's interface proxies ($Proxy172), and what Micronaut generates as it compiles + * ($BookController$Definition$Exec). Their frames have no line of the app's to point at. */ private static boolean generated(String className) { String simple = className.substring(className.lastIndexOf('.') + 1); return className.contains("$$") || className.contains("$HibernateProxy") || className.contains("$ByteBuddy$") - || simple.startsWith("$Proxy"); + || simple.startsWith("$"); } /** The app's frame nearest to the call being made now, as "path:line in method", or null when none is the app's. */ diff --git a/tracepanel-core/src/test/java/dev/tracepanel/core/CoreTest.java b/tracepanel-core/src/test/java/dev/tracepanel/core/CoreTest.java index eb57f15..0677782 100644 --- a/tracepanel-core/src/test/java/dev/tracepanel/core/CoreTest.java +++ b/tracepanel-core/src/test/java/dev/tracepanel/core/CoreTest.java @@ -122,12 +122,13 @@ void the_app_s_code_is_its_own_packages_not_the_libraries() { assertTrue(!stacks.inApp("com.shopping.Other")); assertTrue(!stacks.inApp("org.springframework.web.Servlet")); // Made at runtime in the app's package: a lazy relation's proxy (Hibernate 6 names it Author$HibernateProxy), - // a Spring subclass, a lambda, an interface's proxy. + // a Spring subclass, a lambda, an interface's proxy, Micronaut's compiled bean definitions. assertTrue(!stacks.inApp("com.shop.Author$HibernateProxy$Xyz")); assertTrue(!stacks.inApp("com.shop.Author$HibernateProxy")); assertTrue(!stacks.inApp("com.shop.BookService$$SpringCGLIB$$0")); assertTrue(!stacks.inApp("com.shop.BookService$$Lambda/0x000001f001234567")); assertTrue(!stacks.inApp("com.shop.$Proxy172")); + assertTrue(!stacks.inApp("com.shop.$BookController$Definition$Exec")); assertTrue(stacks.inApp("com.shop.BookService$Page")); assertEquals("com/shop/BookService.java:42 in list", stacks.where("com.shop.BookService", "BookService.java", 42, "list")); } From b90c8bb1846c2bef57a4177c4cc6e85fe896ac8d Mon Sep 17 00:00:00 2001 From: antonrh Date: Tue, 17 Nov 2026 08:02:23 +0200 Subject: [PATCH 10/12] Micronaut: the tests read each trace whole The spans as kind and what each is, the logs, the error's type, message and nearest app frame, and the call's span named as the parent of the trace it reached; explicit imports. --- .../tracepanel/micronaut/DataSourcesTest.java | 3 +- .../dev/tracepanel/micronaut/FilterTest.java | 19 ++++-- .../test/java/shop/MicronautTracingTest.java | 59 +++++++++++++++---- 3 files changed, 62 insertions(+), 19 deletions(-) diff --git a/tracepanel-micronaut/src/test/java/dev/tracepanel/micronaut/DataSourcesTest.java b/tracepanel-micronaut/src/test/java/dev/tracepanel/micronaut/DataSourcesTest.java index c9c2e38..a5dda9d 100644 --- a/tracepanel-micronaut/src/test/java/dev/tracepanel/micronaut/DataSourcesTest.java +++ b/tracepanel-micronaut/src/test/java/dev/tracepanel/micronaut/DataSourcesTest.java @@ -10,6 +10,7 @@ import io.micronaut.context.ApplicationContext; import io.micronaut.http.HttpRequest; import io.micronaut.http.HttpResponse; +import io.micronaut.http.MutableHttpResponse; import io.micronaut.inject.qualifiers.Qualifiers; import java.util.List; import java.util.Map; @@ -54,7 +55,7 @@ public void begun(Trace trace) {} assertEquals(2, queries); TracepanelServerFilter filter = new TracepanelServerFilter(recorder, "", request -> "http://localhost", () -> { throw new AssertionError("No route lookup expected for a synthetic response"); }); - Flux.from(filter.doFilter(HttpRequest.GET("/reactive"), request -> Mono.>fromCallable(() -> { + Flux.from(filter.doFilter(HttpRequest.GET("/reactive"), request -> Mono.>fromCallable(() -> { assertNotNull(Tracepanel.current()); DataSource pool = context.getBean(DataSource.class); try (var connection = pool.getConnection(); var query = connection.prepareStatement("SELECT 2"); diff --git a/tracepanel-micronaut/src/test/java/dev/tracepanel/micronaut/FilterTest.java b/tracepanel-micronaut/src/test/java/dev/tracepanel/micronaut/FilterTest.java index 1037fa8..2a7adfe 100644 --- a/tracepanel-micronaut/src/test/java/dev/tracepanel/micronaut/FilterTest.java +++ b/tracepanel-micronaut/src/test/java/dev/tracepanel/micronaut/FilterTest.java @@ -1,6 +1,12 @@ package dev.tracepanel.micronaut; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertSame; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import dev.tracepanel.core.Config; import dev.tracepanel.core.Trace; @@ -9,6 +15,8 @@ import io.micronaut.core.propagation.PropagatedContext; import io.micronaut.http.HttpRequest; import io.micronaut.http.HttpResponse; +import io.micronaut.http.MutableHttpResponse; +import java.nio.charset.StandardCharsets; import java.util.List; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; @@ -118,6 +126,7 @@ void clientAddsPropagationAndPreservesExplicitHeaders() { recorder.finish(trace); assertEquals(3, trace.spans().size()); } + @Test void clientRecordsSynchronousFailuresAndCancellationOnce() { Trace trace = recorder.begin("http", "outgoing failures", Map.of()); @@ -145,9 +154,9 @@ void handledClientErrorsKeepTheirStatusWithoutAnException() { void htmlInjectionPreservesCharsetAndDropsStaleEntityHeaders() { TracepanelServerFilter filter = new TracepanelServerFilter(recorder, "/shop/", request -> "http://localhost", () -> { throw new AssertionError("No route lookup expected for a synthetic response"); }); - var response = HttpResponse.ok("Café".getBytes(java.nio.charset.StandardCharsets.ISO_8859_1)) + var response = HttpResponse.ok("Café".getBytes(StandardCharsets.ISO_8859_1)) .contentType("text/html; charset=ISO-8859-1").header("ETag", "old").header("Content-Length", "55"); - io.micronaut.http.MutableHttpResponse result; + MutableHttpResponse result; Tracepanel.tests(null); // The core disables badge injection while a test recorder is installed. try { result = Flux.from(filter.doFilter(HttpRequest.GET("/shop/page"), request -> Mono.just(response))).blockLast(); @@ -156,9 +165,9 @@ void htmlInjectionPreservesCharsetAndDropsStaleEntityHeaders() { } assertNotNull(result); assertTrue(result.getBody().orElseThrow() instanceof byte[] bytes - && new String(bytes, java.nio.charset.StandardCharsets.ISO_8859_1).contains("Café")); + && new String(bytes, StandardCharsets.ISO_8859_1).contains("Café")); assertTrue(result.getBody().orElseThrow() instanceof byte[] bytes - && new String(bytes, java.nio.charset.StandardCharsets.ISO_8859_1).contains("/shop/__tracepanel__/widget.min.js")); + && new String(bytes, StandardCharsets.ISO_8859_1).contains("/shop/__tracepanel__/widget.min.js")); assertFalse(result.getHeaders().contains("ETag")); assertFalse(result.getHeaders().contains("Content-Length")); } diff --git a/tracepanel-micronaut/src/test/java/shop/MicronautTracingTest.java b/tracepanel-micronaut/src/test/java/shop/MicronautTracingTest.java index a806caf..445ece1 100644 --- a/tracepanel-micronaut/src/test/java/shop/MicronautTracingTest.java +++ b/tracepanel-micronaut/src/test/java/shop/MicronautTracingTest.java @@ -1,6 +1,8 @@ package shop; -import static org.junit.jupiter.api.Assertions.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; import dev.tracepanel.testing.FakeAgent; import io.micronaut.context.annotation.Property; @@ -17,6 +19,7 @@ import jakarta.inject.Inject; import java.io.IOException; import java.io.UncheckedIOException; +import java.net.URI; import java.sql.SQLException; import java.util.List; import java.util.Map; @@ -48,34 +51,49 @@ public Map getProperties() { @Test void routeHasSqlClientCallLogsAndTraceHeaders() throws Exception { var response = http.toBlocking().exchange(HttpRequest.GET("/probe/books/7"), String.class); - assertNotNull(response.header("Tracepanel-Id")); - assertEquals("book 7 echo", response.body()); Map trace = FakeAgent.traceAt("/probe/books/7"); + Map echoed = FakeAgent.traceAt("/probe/echo"); + Map client = spans(trace).get(2); + + assertEquals("book 7 echo", response.body()); + assertEquals(trace.get("id"), response.header("Tracepanel-Id")); + assertEquals("GET /probe/books/{id}", trace.get("name")); assertEquals("ok", trace.get("status")); - assertTrue(trace.get("spans") instanceof List spans && spans.stream().anyMatch(value -> - value instanceof Map span && "sql".equals(span.get("kind")))); - assertTrue(trace.get("spans") instanceof List spans && spans.stream().anyMatch(value -> - value instanceof Map span && "http.client".equals(span.get("kind")))); - assertTrue(trace.get("logs") instanceof List logs && !logs.isEmpty()); - Map echoed = FakeAgent.traceAt("/probe/echo"); - assertTrue(echoed.get("attrs") instanceof Map attrs && attrs.containsKey("w3c.parent_span_id")); + assertEquals(List.of("http GET /probe/books/{id}", "sql SELECT 1", "http.client GET /probe/echo 200"), + spans(trace).stream().map(MicronautTracingTest::said).toList()); + assertEquals(List.of("info loaded book 7"), ((List) trace.get("logs")).stream() + .map(value -> (Map) value).map(log -> log.get("level") + " " + log.get("message")).toList()); + + // The call carried the trace on: the echo's trace names the client span as its parent. + assertEquals(((Map) client.get("attrs")).get("w3c.span_id"), + ((Map) echoed.get("attrs")).get("w3c.parent_span_id")); } @Test void reactiveControllerKeepsItsTraceAfterSwitchingThreads() throws Exception { assertEquals("reactive", http.toBlocking().retrieve("/probe/reactive/8")); Map trace = FakeAgent.traceAt("/probe/reactive/8"); + assertEquals("GET /probe/reactive/{id}", trace.get("name")); - assertTrue(trace.get("spans") instanceof List spans && spans.size() > 1); + assertEquals(List.of("http GET /probe/reactive/{id}", "sql SELECT 1"), + spans(trace).stream().map(MicronautTracingTest::said).toList()); } @Test void frameworkErrorResponseKeepsTheException() throws Exception { assertThrows(HttpClientResponseException.class, () -> http.toBlocking().retrieve("/probe/failure")); Map trace = FakeAgent.traceAt("/probe/failure"); + Map error = (Map) ((List) trace.get("errors")).get(0); + // The app's frame nearest the throw: the controller's method, not the bean definition Micronaut compiled. + Map own = ((List) error.get("frames")).stream().map(value -> (Map) value) + .filter(frame -> Boolean.TRUE.equals(frame.get("in_app"))).findFirst().orElseThrow(); + assertEquals("error", trace.get("status")); - assertTrue(trace.get("errors") instanceof List errors && !errors.isEmpty()); + assertEquals(List.of("java.lang.IllegalStateException", "broken controller", false), + List.of(error.get("type"), error.get("message"), error.get("handled"))); + assertEquals(List.of("shop.MicronautTracingTest$ProbeController", "failure"), + List.of(own.get("module"), own.get("function"))); } @Test @@ -87,10 +105,25 @@ void htmlHasTheBadgeAndTheConsoleDoesNotTraceItself() { String posted = http.toBlocking().retrieve(HttpRequest.POST("/__tracepanel__/api/settings", "{\"theme\":\"dark\"}") .contentType("application/json")); assertTrue(posted.startsWith("console ")); - assertTrue(FakeAgent.CONSOLE_CALLS.stream().anyMatch(call -> call.equals("POST /api/settings {\"theme\":\"dark\"}"))); + assertTrue(FakeAgent.CONSOLE_CALLS.contains("POST /api/settings {\"theme\":\"dark\"}")); assertTrue(FakeAgent.TRACES.stream().noneMatch(trace -> String.valueOf(trace.get("name")).contains("__tracepanel__"))); } + private static List> spans(Map trace) { + return ((List) trace.get("spans")).stream().>map(value -> (Map) value).toList(); + } + + /** A span as the test reads it: its kind and what it is (a statement, a call's path and status). */ + private static String said(Map span) { + Map attrs = (Map) span.get("attrs"); + return span.get("kind") + " " + switch (String.valueOf(span.get("kind"))) { + case "sql" -> attrs.get("db.statement"); + case "http.client" -> attrs.get("http.request.method") + " " + URI.create(String.valueOf(attrs.get("url.full"))) + .getPath() + " " + attrs.get("http.response.status_code"); + default -> span.get("name"); + }; + } + @Client("/") interface EchoClient { @Get("/probe/echo") String echo(); From 3f655c963e32db62198bd9cd60b042e26ffa5dbd Mon Sep 17 00:00:00 2001 From: antonrh Date: Tue, 17 Nov 2026 08:02:58 +0200 Subject: [PATCH 11/12] Micronaut: the README and the changelog as the other integrations have them Install and what it records in the Spring Boot and Ktor sections' shape; no link to a private repository, no word of it being unpublished (the release names its version); the changelog's entry in three lines. --- CHANGELOG.md | 8 ++---- README.md | 74 ++++++++++++++++++---------------------------------- 2 files changed, 27 insertions(+), 55 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7042c60..8f3a5e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,12 +4,8 @@ ### Added -- `tracepanel-micronaut` for Micronaut 4 and 5: route-named request traces, - JDBC statements and transactions, declarative HTTP clients, Logback, - request principals, the badge and the console. The SDK starts in dev, - development or local environments, or with `TRACEPANEL_ENABLED=1`. -- A Micronaut 5 test suite on Java 25 in CI. The module still compiles for - Java 17 for Micronaut 4 applications. +- `tracepanel-micronaut`, for Micronaut 4.10 and 5: each request, SQL and + transactions, calls through its HTTP clients, logs, errors and the console. ## 0.16.0 (2026-11-10) diff --git a/README.md b/README.md index c23a81f..ccf6768 100644 --- a/README.md +++ b/README.md @@ -4,12 +4,12 @@ [![Maven Central](https://img.shields.io/maven-central/v/dev.tracepanel/tracepanel-core)](https://central.sonatype.com/namespace/dev.tracepanel) [![Java](https://img.shields.io/badge/java-17%2B-blue)](https://github.com/tracepanel/tracepanel-java#tracepanel-for-java) -**See what your Spring Boot, Micronaut or Ktor app is doing.** Tracepanel records -each request, `@Async` task, scheduled job and message of your app, in Java or -Kotlin, with its SQL queries, Redis and MongoDB commands, outgoing HTTP calls, -logs and errors. It points out N+1 queries, duplicates, slow SQL and long -transactions, and names the line of code to fix. You read it in a panel on -your pages and in a console. +**See what your Spring Boot, Micronaut or Ktor app is really doing.** +Tracepanel records each request, `@Async` task, scheduled job and message of +your app, in Java or Kotlin, with its SQL queries, Redis and MongoDB commands, +outgoing HTTP calls, logs and errors. It points out N+1 queries, duplicates, +slow SQL and long transactions, and names the line of code to fix. You read it +in a panel on your pages and in a console. It runs while you develop, and everything stays on your machine. @@ -22,11 +22,11 @@ It runs while you develop, and everything stays on your machine. | | Supported | | --- | --- | | **Java** | 17 and later, apps in Java or Kotlin. | -| **Frameworks** | Spring Boot 3.5 and 4 with Spring MVC, Kotlin suspend functions, `Callable` and `DeferredResult` handlers included. Ktor 3. Micronaut 4.10 and 5 with Netty and declarative HTTP clients. Micronaut 5 requires Java 25. WebFlux apps aren't supported yet. | +| **Frameworks** | Spring Boot 3.5 and 4 with Spring MVC, Kotlin suspend functions, `Callable` and `DeferredResult` handlers included. Ktor 3. Micronaut 4.10 and 5 (on Java 25). WebFlux apps aren't supported yet. | | **Databases** | SQL through JDBC, whatever runs it: Spring Data JPA, Hibernate, `JdbcTemplate`, jOOQ, Exposed. Transactions. EXPLAIN on PostgreSQL, MySQL, H2 and SQLite of a SELECT or a `WITH … SELECT` that changes no data (ANALYZE rolled back). | | **Redis and MongoDB** | Lettuce (Spring Data Redis, the cache) and Spring Data MongoDB, with their own N+1 and duplicates. | | **Messaging** | Kafka and RabbitMQ: what a `KafkaTemplate` or a `RabbitTemplate` sends, and each message a `@KafkaListener` or `@RabbitListener` receives as a trace of its own, linked to the one that sent it. | -| **HTTP clients** | `RestClient`, `RestTemplate`, `WebClient` and the JDK's `HttpClient`, each call with a `traceparent`. Ktor's client through `TracepanelClient`. Micronaut declarative `@Client` calls. | +| **HTTP clients** | `RestClient`, `RestTemplate`, `WebClient` and the JDK's `HttpClient`, each call with a `traceparent`. Ktor's client through `TracepanelClient`. Micronaut's clients, `@Client` interfaces included. | | **Background work** | `@Async` methods as tasks, linked to the request that queued them; `@Scheduled` methods, `CommandLineRunner`s and `ApplicationRunner`s as jobs; the tasks in flight listed live. | | **Logs** | Logback and Log4j 2, each record on the request or task that made it, with its line, MDC and exception. | | **Errors** | Thrown in a handler, with your frames and the source around them. | @@ -98,11 +98,8 @@ off. ### Micronaut -The new `tracepanel-micronaut` module is available from this checkout. It has -not been published yet. See the [Micronaut store example](https://github.com/tracepanel/tracepanel-examples/tree/main/micronaut-app) -for a composite build with the local SDK. - -With the Micronaut Gradle plugin, add the module for development only: +Add the dependency for development only. Micronaut finds Tracepanel's beans +by itself: each request, your DataSources and your HTTP clients. ```kotlin dependencies { @@ -110,15 +107,10 @@ dependencies { } ``` -Use your app's Micronaut platform BOM so its Reactor integration matches -its framework version. Run with `micronaut.environments=dev`, for example -`MICRONAUT_ENVIRONMENTS=dev ./gradlew run`. The SDK also starts in the -`development` and `local` environments. `TRACEPANEL_ENABLED=1` enables it -in another environment. `TRACEPANEL_ENABLED=0` disables it in every environment. - -Micronaut finds the SDK's beans without application code. Open an HTML page -for the badge, or `/__tracepanel__/` for the console. Micronaut 4 uses the -SDK's Java 17 baseline. Micronaut 5 requires Java 25. +Tracepanel is on in a `dev`, `development` or `local` environment +(`MICRONAUT_ENVIRONMENTS=dev ./gradlew run`), or with +`TRACEPANEL_ENABLED=1`. The console is at `/__tracepanel__/` on your app. +Micronaut 4.10 runs on Java 17, Micronaut 5 on Java 25. ### Ktor @@ -178,26 +170,12 @@ fix: ### Micronaut -- Each request, named by its matched route and controller method. -- JDBC statements and transactions through `DataSource` beans, including - Micronaut Hikari pools and `JdbcTemplate`. -- Declarative `@Client` calls, with W3C `traceparent` and profile headers. -- Logback records and controller errors on the current trace. -- A user set through Micronaut's request principal. -- Context across Micronaut's blocking executors and Reactor publishers. -- The console, response headers, and the badge on HTML held as a `String` - or `byte[]`. Streaming responses and static file bodies are not buffered - for badge injection. - -Declare custom data source factory return types as `DataSource`. A bean -exposed as a concrete pool class cannot accept the SDK's interface wrapper; -the SDK leaves it unchanged and logs a warning. Request capture records -headers, query parameters and cookies. It captures an already decoded -`String` or `byte[]` body, without reading application request streams. - -Redis, messaging, scheduled jobs and detached application tasks are outside -this module's current scope. The Spring integrations listed above do not imply -Micronaut support for those APIs. +- Each request, named by its route (`GET /books/{id}`) and its controller + method, on Micronaut's executors and, with `micronaut-reactor`, Reactor's. +- SQL and transactions through your `DataSource` beans, Micronaut Data's + `@Transactional` included, and calls through its HTTP clients. +- Logs and errors as in Spring Boot, and the user from the request's + principal. ### Ktor @@ -486,16 +464,13 @@ the same in every framework, under ./gradlew check ``` -It runs the tests on Spring Boot 4 and on 3.5, Ktor and Micronaut 4. -With Java 25 installed, test the same module against Micronaut 5: +It runs the tests on Spring Boot 4 and on 3.5, on Ktor, and on Micronaut 4 +with and without Micronaut Data. Micronaut 5's need Java 25: ```bash ./gradlew :tracepanel-micronaut:testMicronaut5 :tracepanel-micronaut:testMicronaut5Integration ``` -CI runs both Micronaut versions. Integration tests use a local fake agent -and run in a separate JVM from unit tests. - The tests of MongoDB, Redis, Kafka and RabbitMQ need a server of each: `TEST_MONGODB_URI=mongodb://127.0.0.1:27017/test`, `TEST_REDIS_PORT=6379`, `TEST_KAFKA_BOOTSTRAP=localhost:9092` and `TEST_RABBITMQ_PORT=5672`. The @@ -507,8 +482,9 @@ writes the checksums of that version's downloads. `tracepanel-core` records traces and talks to the agent, with no framework and no dependencies. `tracepanel-spring-boot` is the Spring Boot integration, `tracepanel-micronaut` the Micronaut one, `tracepanel-ktor` the -Ktor one, and `tracepanel-junit` the JUnit extension. The extension's tests with the real agent download it, as -a project does, unless `TEST_AGENT_BIN` names one. +Ktor one, and `tracepanel-junit` the JUnit extension. The extension's tests +with the real agent download it, as a project does, unless `TEST_AGENT_BIN` +names one. ## License From cb08f55f5df3ea55e441830bca1144f2d2fd3b4f Mon Sep 17 00:00:00 2001 From: antonrh Date: Tue, 17 Nov 2026 08:04:37 +0200 Subject: [PATCH 12/12] Micronaut: the tests log at INFO, as an app does Without a config Logback logs at DEBUG: on Micronaut 5 the HTTP client's own DEBUG record joined the trace's logs. The Micronaut 5 suite reads the same test resources. --- tracepanel-micronaut/build.gradle.kts | 1 + tracepanel-micronaut/src/test/resources/logback-test.xml | 7 +++++++ 2 files changed, 8 insertions(+) create mode 100644 tracepanel-micronaut/src/test/resources/logback-test.xml diff --git a/tracepanel-micronaut/build.gradle.kts b/tracepanel-micronaut/build.gradle.kts index 96f6eda..c4ad775 100644 --- a/tracepanel-micronaut/build.gradle.kts +++ b/tracepanel-micronaut/build.gradle.kts @@ -38,6 +38,7 @@ dependencies { val micronaut5Tests = testing.suites.register("testMicronaut5") { useJUnitJupiter("6.1.3") sources.java.setSrcDirs(listOf("src/test/java")) + sources.resources.setSrcDirs(listOf("src/test/resources")) dependencies { implementation(project()) implementation(platform("io.micronaut.platform:micronaut-platform:$micronaut5")) diff --git a/tracepanel-micronaut/src/test/resources/logback-test.xml b/tracepanel-micronaut/src/test/resources/logback-test.xml new file mode 100644 index 0000000..c0252d4 --- /dev/null +++ b/tracepanel-micronaut/src/test/resources/logback-test.xml @@ -0,0 +1,7 @@ + + + + %d{HH:mm:ss.SSS} %-5level %logger{36} - %msg%n + + +