diff --git a/spring-cloud-function-context/src/main/java/org/springframework/cloud/function/context/catalog/FunctionAroundWrapper.java b/spring-cloud-function-context/src/main/java/org/springframework/cloud/function/context/catalog/FunctionAroundWrapper.java index a065247ae..2ef927f7d 100644 --- a/spring-cloud-function-context/src/main/java/org/springframework/cloud/function/context/catalog/FunctionAroundWrapper.java +++ b/spring-cloud-function-context/src/main/java/org/springframework/cloud/function/context/catalog/FunctionAroundWrapper.java @@ -46,12 +46,7 @@ public final Object apply(Object input, FunctionInvocationWrapper targetFunction || Boolean.parseBoolean(functionalTracingEnabledStr); if (functionalTracingEnabled && !(input instanceof Publisher) && input instanceof Message && !FunctionTypeUtils.isCollectionOfMessage(targetFunction.getOutputType())) { - try { - return this.doApply(input, targetFunction); - } - finally { - targetFunction.wrapped = false; - } + return this.doApply(input, targetFunction); } else { return targetFunction.apply(input); diff --git a/spring-cloud-function-context/src/main/java/org/springframework/cloud/function/context/catalog/SimpleFunctionRegistry.java b/spring-cloud-function-context/src/main/java/org/springframework/cloud/function/context/catalog/SimpleFunctionRegistry.java index 67f56e3b2..93b5696f8 100644 --- a/spring-cloud-function-context/src/main/java/org/springframework/cloud/function/context/catalog/SimpleFunctionRegistry.java +++ b/spring-cloud-function-context/src/main/java/org/springframework/cloud/function/context/catalog/SimpleFunctionRegistry.java @@ -465,7 +465,7 @@ public class FunctionInvocationWrapper implements Function, Cons private boolean propagateInputHeaders; - protected boolean wrapped; + private final ThreadLocal wrapped = new ThreadLocal<>(); private final ThreadLocal> unconvertedResult = new ThreadLocal<>(); @@ -661,13 +661,13 @@ public Object apply(Object input) { } Object result; - if (functionAroundWrapper != null && !this.wrapped) { - this.wrapped = true; + if (functionAroundWrapper != null && !Boolean.TRUE.equals(this.wrapped.get())) { + this.wrapped.set(Boolean.TRUE); try { result = functionAroundWrapper.apply(input, this); } finally { - this.wrapped = false; + this.wrapped.remove(); } } else { diff --git a/spring-cloud-function-context/src/test/java/org/springframework/cloud/function/context/catalog/SimpleFunctionRegistryTests.java b/spring-cloud-function-context/src/test/java/org/springframework/cloud/function/context/catalog/SimpleFunctionRegistryTests.java index 11e2f05f4..5e2f687a8 100644 --- a/spring-cloud-function-context/src/test/java/org/springframework/cloud/function/context/catalog/SimpleFunctionRegistryTests.java +++ b/spring-cloud-function-context/src/test/java/org/springframework/cloud/function/context/catalog/SimpleFunctionRegistryTests.java @@ -28,8 +28,11 @@ import java.util.Map; import java.util.Map.Entry; import java.util.UUID; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; +import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiConsumer; import java.util.function.Consumer; @@ -40,6 +43,8 @@ import com.google.gson.Gson; import com.google.protobuf.StringValue; +import io.micrometer.observation.tck.TestObservationRegistry; +import io.micrometer.observation.tck.TestObservationRegistryAssert; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Disabled; @@ -63,6 +68,7 @@ import org.springframework.cloud.function.json.GsonMapper; import org.springframework.cloud.function.json.JacksonMapper; import org.springframework.cloud.function.json.JsonMapper; +import org.springframework.cloud.function.observability.ObservationFunctionAroundWrapper; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -138,6 +144,111 @@ protected Object doApply(Object input, FunctionInvocationWrapper targetFunction) assertThat(aroundInvocations.get()).isEqualTo(2); } + @Test + public void testAroundWrapperAppliedToConcurrentInvocations() throws Exception { + SimpleFunctionRegistry catalog = new SimpleFunctionRegistry(this.conversionService, this.messageConverter, + new GsonMapper(new Gson())); + AtomicInteger aroundInvocations = new AtomicInteger(); + CountDownLatch firstEnteredAround = new CountDownLatch(1); + CountDownLatch secondCallCompleted = new CountDownLatch(1); + ReflectionTestUtils.setField(catalog, "functionAroundWrapper", new FunctionAroundWrapper() { + @Override + protected Object doApply(Object input, FunctionInvocationWrapper targetFunction) { + if (aroundInvocations.incrementAndGet() == 1) { + firstEnteredAround.countDown(); + try { + assertThat(secondCallCompleted.await(5, TimeUnit.SECONDS)).isTrue(); + } + catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(ex); + } + } + return targetFunction.apply(input); + } + }); + Function uppercase = value -> value.toUpperCase(Locale.ROOT); + catalog.register(new FunctionRegistration<>(uppercase, "uppercase") + .type(ResolvableType.forClassWithGenerics(Function.class, String.class, String.class).getType())); + FunctionInvocationWrapper function = catalog.lookup("uppercase"); + + ExecutorService executor = Executors.newSingleThreadExecutor(); + try { + CompletableFuture firstResult = CompletableFuture.supplyAsync( + () -> (String) function.apply(MessageBuilder.withPayload("first").build()), executor); + + assertThat(firstEnteredAround.await(5, TimeUnit.SECONDS)).isTrue(); + + String secondResult; + try { + secondResult = (String) function.apply(MessageBuilder.withPayload("second").build()); + } + finally { + secondCallCompleted.countDown(); + } + + assertThat(secondResult).isEqualTo("SECOND"); + assertThat(firstResult.get(5, TimeUnit.SECONDS)).isEqualTo("FIRST"); + assertThat(aroundInvocations.get()).isEqualTo(2); + + String thirdResult = (String) function.apply(MessageBuilder.withPayload("third").build()); + assertThat(thirdResult).isEqualTo("THIRD"); + assertThat(aroundInvocations.get()).isEqualTo(3); + } + finally { + executor.shutdownNow(); + } + } + + @Test + public void testObservationAroundWrapperAppliedUnderConcurrentLoad() throws Exception { + SimpleFunctionRegistry catalog = new SimpleFunctionRegistry(this.conversionService, this.messageConverter, + new GsonMapper(new Gson())); + TestObservationRegistry observationRegistry = TestObservationRegistry.create(); + ReflectionTestUtils.setField(catalog, "functionAroundWrapper", + new ObservationFunctionAroundWrapper(observationRegistry, null)); + Function uppercase = value -> { + Thread.yield(); + return value.toUpperCase(Locale.ROOT); + }; + catalog.register(new FunctionRegistration<>(uppercase, "uppercase") + .type(ResolvableType.forClassWithGenerics(Function.class, String.class, String.class).getType())); + FunctionInvocationWrapper function = catalog.lookup("uppercase"); + + int threadCount = 8; + int invocationsPerThread = 25; + int totalInvocations = threadCount * invocationsPerThread; + CountDownLatch startGate = new CountDownLatch(1); + ExecutorService executor = Executors.newFixedThreadPool(threadCount); + try { + List> futures = IntStream.range(0, threadCount) + .mapToObj(threadIdx -> CompletableFuture.runAsync(() -> { + try { + assertThat(startGate.await(5, TimeUnit.SECONDS)).isTrue(); + } + catch (InterruptedException ex) { + Thread.currentThread().interrupt(); + throw new IllegalStateException(ex); + } + for (int i = 0; i < invocationsPerThread; i++) { + String payload = "msg-" + threadIdx + "-" + i; + String result = (String) function + .apply(MessageBuilder.withPayload(payload).build()); + assertThat(result).isEqualTo(payload.toUpperCase(Locale.ROOT)); + } + }, executor)) + .toList(); + startGate.countDown(); + CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).get(15, TimeUnit.SECONDS); + + TestObservationRegistryAssert.assertThat(observationRegistry) + .hasNumberOfObservationsWithNameEqualTo("spring.cloud.function", totalInvocations); + } + finally { + executor.shutdownNow(); + } + } + @Test public void testWrappedFunctionCacheEvictsLeastRecentlyUsed() { SimpleFunctionRegistry catalog = new SimpleFunctionRegistry(this.conversionService, this.messageConverter,