Support context propagation for Spring MVC controllers

Closes gh-29056
This commit is contained in:
rstoyanchev
2022-10-06 12:42:34 +01:00
parent d581d48d24
commit b6c2e8de23
6 changed files with 105 additions and 3 deletions

View File

@@ -1,5 +1,5 @@
/*
* Copyright 2002-2021 the original author or authors.
* Copyright 2002-2022 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -26,11 +26,14 @@ import java.util.Optional;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import io.micrometer.context.ContextSnapshot;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import org.springframework.core.MethodParameter;
import org.springframework.core.ReactiveAdapter;
@@ -126,8 +129,18 @@ class ReactiveTypeHandler {
ModelAndViewContainer mav, NativeWebRequest request) throws Exception {
Assert.notNull(returnValue, "Expected return value");
ReactiveAdapter adapter = this.adapterRegistry.getAdapter(returnValue.getClass());
Assert.state(adapter != null, () -> "Unexpected return value: " + returnValue);
Class<?> clazz = returnValue.getClass();
ReactiveAdapter adapter = this.adapterRegistry.getAdapter(clazz);
Assert.state(adapter != null, () -> "Unexpected return value type: " + clazz);
if (Mono.class.isAssignableFrom(clazz)) {
ContextSnapshot snapshot = ContextSnapshot.captureAll();
returnValue = ((Mono<?>) returnValue).contextWrite(snapshot::updateContext);
}
else if (Flux.class.isAssignableFrom(clazz)) {
ContextSnapshot snapshot = ContextSnapshot.captureAll();
returnValue = ((Flux<?>) returnValue).contextWrite(snapshot::updateContext);
}
ResolvableType elementType = ResolvableType.forMethodParameter(returnType).getGeneric();
Class<?> elementClass = elementType.toClass();

View File

@@ -18,13 +18,19 @@ package org.springframework.web.servlet.mvc.method.annotation;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import io.micrometer.context.ContextRegistry;
import io.micrometer.context.ContextSnapshot;
import io.micrometer.context.ContextSnapshot.Scope;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Sinks;
import reactor.core.scheduler.Schedulers;
import org.springframework.core.MethodParameter;
import org.springframework.core.ResolvableType;
@@ -239,6 +245,46 @@ public class ResponseBodyEmitterReturnValueHandlerTests {
assertThat(this.response.getContentAsString()).isEqualTo("data:foo\n\ndata:bar\n\ndata:baz\n\n");
}
@SuppressWarnings({"try","unused"})
@Test
public void responseBodyFluxWithThreadLocal() throws Exception {
this.request.addHeader("Accept", "text/event-stream");
ThreadLocal<String> threadLocal = new ThreadLocal<>();
ContextRegistry.getInstance().registerThreadLocalAccessor("key", threadLocal);
CountDownLatch latch = new CountDownLatch(1);
Flux<String> flux = Flux.just("foo", "bar", "baz")
.publishOn(Schedulers.boundedElastic())
.transformDeferredContextual((theFlux, contextView) ->
theFlux.map(s -> {
try (Scope scope = ContextSnapshot.setThreadLocalsFrom(contextView, "key")) {
return s + threadLocal.get();
}
}))
.doOnTerminate(latch::countDown);
try {
threadLocal.set("123");
this.handler.handleReturnValue(flux,
on(TestController.class).resolveReturnType(Flux.class, String.class),
this.mavContainer, this.webRequest);
}
finally {
threadLocal.remove();
}
latch.await(5, TimeUnit.SECONDS);
assertThat(this.request.isAsyncStarted()).isTrue();
assertThat(this.response.getStatus()).isEqualTo(200);
assertThat(this.response.getContentType()).isEqualTo("text/event-stream");
assertThat(this.response.getContentAsString()).isEqualTo("data:foo123\n\ndata:bar123\n\ndata:baz123\n\n");
}
@Test // gh-21972
public void responseBodyFluxWithError() throws Exception {