From b856c2c44e1ab468dca2efa5c6eccc0712101c34 Mon Sep 17 00:00:00 2001 From: Marcin Grzejszczak Date: Thu, 1 Sep 2022 11:01:19 +0200 Subject: [PATCH] Ensures that we close the scope when working with Kotlin; fixes gh-2197 --- .../cloud/sleuth/instrument/kotlin/KotlinContextElement.java | 5 ++++- .../sleuth/instrument/kotlin/AsContextElementKtTests.kt | 5 +++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/spring-cloud-sleuth-instrumentation/src/main/kotlin/org/springframework/cloud/sleuth/instrument/kotlin/KotlinContextElement.java b/spring-cloud-sleuth-instrumentation/src/main/kotlin/org/springframework/cloud/sleuth/instrument/kotlin/KotlinContextElement.java index c1b9129bb..5057dd2ae 100644 --- a/spring-cloud-sleuth-instrumentation/src/main/kotlin/org/springframework/cloud/sleuth/instrument/kotlin/KotlinContextElement.java +++ b/spring-cloud-sleuth-instrumentation/src/main/kotlin/org/springframework/cloud/sleuth/instrument/kotlin/KotlinContextElement.java @@ -65,7 +65,10 @@ class KotlinContextElement implements ThreadContextElement { @Override public void restoreThreadContext(CoroutineContext coroutineContext, SpanAndScope spanAndScope) { - spanAndScope.close(); + Tracer.SpanInScope scope = spanAndScope.getScope(); + if (scope != null) { + scope.close(); + } } @Override diff --git a/spring-cloud-sleuth-instrumentation/src/test/kotlin/org/springframework/cloud/sleuth/instrument/kotlin/AsContextElementKtTests.kt b/spring-cloud-sleuth-instrumentation/src/test/kotlin/org/springframework/cloud/sleuth/instrument/kotlin/AsContextElementKtTests.kt index cfefbec86..1e1abf52e 100644 --- a/spring-cloud-sleuth-instrumentation/src/test/kotlin/org/springframework/cloud/sleuth/instrument/kotlin/AsContextElementKtTests.kt +++ b/spring-cloud-sleuth-instrumentation/src/test/kotlin/org/springframework/cloud/sleuth/instrument/kotlin/AsContextElementKtTests.kt @@ -29,6 +29,7 @@ import org.springframework.cloud.sleuth.Span import org.springframework.cloud.sleuth.TraceContext import org.springframework.cloud.sleuth.Tracer import org.springframework.cloud.sleuth.tracer.SimpleCurrentTraceContext +import org.springframework.cloud.sleuth.tracer.SimpleSpan import org.springframework.cloud.sleuth.tracer.SimpleTracer import reactor.util.context.Context @@ -45,15 +46,19 @@ internal class AsContextElementKtTests { GlobalScope.launch(asContextElement) { spanInGlobalScopeLaunch = coroutineContext.currentSpan() + then((spanInGlobalScopeLaunch as SimpleSpan).ended).isFalse() } GlobalScope.async(asContextElement) { spanInGlobalScopeAsync = coroutineContext.currentSpan() + then((spanInGlobalScopeAsync as SimpleSpan).ended).isFalse() }.await() inScope.close(); then(spanInGlobalScopeLaunch).isSameAs(nextSpan) then(spanInGlobalScopeAsync).isSameAs(nextSpan) + then((spanInGlobalScopeLaunch as SimpleSpan).ended).isFalse() + then((spanInGlobalScopeAsync as SimpleSpan).ended).isFalse() } @Test