-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
RouteExecutor.java
863 lines (792 loc) · 39.6 KB
/
RouteExecutor.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
/*
* Copyright 2017-2021 original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.micronaut.http.server;
import io.micronaut.context.BeanContext;
import io.micronaut.context.exceptions.BeanCreationException;
import io.micronaut.core.annotation.Internal;
import io.micronaut.core.annotation.NonNull;
import io.micronaut.core.annotation.Nullable;
import io.micronaut.core.async.publisher.Publishers;
import io.micronaut.core.io.buffer.ReferenceCounted;
import io.micronaut.core.type.Argument;
import io.micronaut.core.type.ReturnType;
import io.micronaut.http.HttpAttributes;
import io.micronaut.http.HttpHeaders;
import io.micronaut.http.HttpMethod;
import io.micronaut.http.HttpRequest;
import io.micronaut.http.HttpResponse;
import io.micronaut.http.HttpStatus;
import io.micronaut.http.MediaType;
import io.micronaut.http.MutableHttpHeaders;
import io.micronaut.http.MutableHttpResponse;
import io.micronaut.http.bind.binders.ContinuationArgumentBinder;
import io.micronaut.http.context.ServerRequestContext;
import io.micronaut.http.exceptions.HttpStatusException;
import io.micronaut.http.filter.HttpFilter;
import io.micronaut.http.filter.ServerFilterChain;
import io.micronaut.http.server.binding.RequestArgumentSatisfier;
import io.micronaut.http.server.exceptions.ExceptionHandler;
import io.micronaut.http.server.exceptions.response.ErrorContext;
import io.micronaut.http.server.exceptions.response.ErrorResponseProcessor;
import io.micronaut.inject.BeanDefinition;
import io.micronaut.inject.BeanType;
import io.micronaut.inject.ExecutableMethod;
import io.micronaut.inject.MethodReference;
import io.micronaut.inject.qualifiers.Qualifiers;
import io.micronaut.scheduling.executor.ExecutorSelector;
import io.micronaut.web.router.MethodBasedRouteMatch;
import io.micronaut.web.router.RouteInfo;
import io.micronaut.web.router.RouteMatch;
import io.micronaut.web.router.Router;
import io.micronaut.web.router.exceptions.UnsatisfiedRouteException;
import jakarta.inject.Singleton;
import org.reactivestreams.Publisher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;
import java.io.IOException;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.regex.Pattern;
import static io.micronaut.core.util.KotlinUtils.isKotlinCoroutineSuspended;
import static io.micronaut.inject.util.KotlinExecutableMethodUtils.isKotlinFunctionReturnTypeUnit;
/**
* A class responsible for executing routes.
*
* @author James Kleeh
* @since 3.0.0
*/
@Singleton
public final class RouteExecutor {
private static final Logger LOG = LoggerFactory.getLogger(RouteExecutor.class);
/**
* Also present in netty RoutingInBoundHandler.
*/
private static final Pattern IGNORABLE_ERROR_MESSAGE = Pattern.compile(
"^.*(?:connection (?:reset|closed|abort|broken)|broken pipe).*$", Pattern.CASE_INSENSITIVE);
private final Router router;
private final BeanContext beanContext;
private final RequestArgumentSatisfier requestArgumentSatisfier;
private final HttpServerConfiguration serverConfiguration;
private final ErrorResponseProcessor<?> errorResponseProcessor;
private final ExecutorSelector executorSelector;
private final Optional<CoroutineHelper> coroutineHelper;
/**
* Default constructor.
*
* @param router The router
* @param beanContext The bean context
* @param requestArgumentSatisfier The request argument satisfier
* @param serverConfiguration The server configuration
* @param errorResponseProcessor The error response processor
* @param executorSelector The executor selector
*/
public RouteExecutor(Router router,
BeanContext beanContext,
RequestArgumentSatisfier requestArgumentSatisfier,
HttpServerConfiguration serverConfiguration,
ErrorResponseProcessor<?> errorResponseProcessor,
ExecutorSelector executorSelector) {
this.router = router;
this.beanContext = beanContext;
this.requestArgumentSatisfier = requestArgumentSatisfier;
this.serverConfiguration = serverConfiguration;
this.errorResponseProcessor = errorResponseProcessor;
this.executorSelector = executorSelector;
this.coroutineHelper = beanContext.findBean(CoroutineHelper.class);
}
/**
* @return The router
*/
public @NonNull Router getRouter() {
return router;
}
/**
* @return The request argument satisfier
*/
@Internal
public @NonNull RequestArgumentSatisfier getRequestArgumentSatisfier() {
return requestArgumentSatisfier;
}
/**
* @return The error response processor
*/
public @NonNull ErrorResponseProcessor<?> getErrorResponseProcessor() {
return errorResponseProcessor;
}
/**
* @return The executor selector
*/
public @NonNull ExecutorSelector getExecutorSelector() {
return executorSelector;
}
/**
* @return The kotlin coroutine helper
*/
public Optional<CoroutineHelper> getCoroutineHelper() {
return coroutineHelper;
}
/**
* Creates a response publisher to represent the response after being handled
* by any available error route or exception handler.
*
* @param t The exception that occurred
* @param httpRequest The request that caused the exception
* @return A response publisher
*/
public Flux<MutableHttpResponse<?>> onError(Throwable t, HttpRequest<?> httpRequest) {
// find the origination of of the route
Class declaringType = httpRequest.getAttribute(HttpAttributes.ROUTE_INFO, RouteInfo.class).map(RouteInfo::getDeclaringType).orElse(null);
final Throwable cause;
// top level exceptions returned by CompletableFutures. These always wrap the real exception thrown.
if ((t instanceof CompletionException || t instanceof ExecutionException) && t.getCause() != null) {
cause = t.getCause();
} else {
cause = t;
}
RouteMatch<?> errorRoute = findErrorRoute(cause, declaringType, httpRequest);
if (errorRoute != null) {
if (serverConfiguration.isLogHandledExceptions()) {
logException(cause);
}
try {
AtomicReference<HttpRequest<?>> requestReference = new AtomicReference<>(httpRequest);
return buildRouteResponsePublisher(
requestReference,
Flux.just(errorRoute))
.doOnNext(response -> response.setAttribute(HttpAttributes.EXCEPTION, cause))
.onErrorResume(throwable -> createDefaultErrorResponsePublisher(requestReference.get(), throwable));
} catch (Throwable e) {
return createDefaultErrorResponsePublisher(httpRequest, e).flux();
}
} else {
Optional<BeanDefinition<ExceptionHandler>> optionalDefinition = beanContext.findBeanDefinition(ExceptionHandler.class, Qualifiers.byTypeArgumentsClosest(cause.getClass(), Object.class));
if (optionalDefinition.isPresent()) {
BeanDefinition<ExceptionHandler> handlerDefinition = optionalDefinition.get();
final Optional<ExecutableMethod<ExceptionHandler, Object>> optionalMethod = handlerDefinition.findPossibleMethods("handle").findFirst();
RouteInfo<Object> routeInfo;
if (optionalMethod.isPresent()) {
routeInfo = new ExecutableRouteInfo(optionalMethod.get(), true);
} else {
routeInfo = new RouteInfo<Object>() {
@Override
public ReturnType<?> getReturnType() {
return ReturnType.of(Object.class);
}
@Override
public Class<?> getDeclaringType() {
return handlerDefinition.getBeanType();
}
@Override
public boolean isErrorRoute() {
return true;
}
@Override
public List<MediaType> getProduces() {
return MediaType.fromType(getDeclaringType())
.map(Collections::singletonList)
.orElse(Collections.emptyList());
}
};
}
Flux<MutableHttpResponse<?>> reactiveSequence = Flux.defer(() -> {
ExceptionHandler handler = beanContext.getBean(handlerDefinition);
try {
if (serverConfiguration.isLogHandledExceptions()) {
logException(cause);
}
Object result = handler.handle(httpRequest, cause);
return createResponseForBody(httpRequest, result, routeInfo);
} catch (Throwable e) {
return createDefaultErrorResponsePublisher(httpRequest, e);
}
});
final ExecutorService executor = findExecutor(routeInfo);
if (executor != null) {
reactiveSequence = applyExecutorToPublisher(reactiveSequence, executor);
}
return reactiveSequence
.doOnNext(response -> response.setAttribute(HttpAttributes.EXCEPTION, cause))
.onErrorResume(throwable -> createDefaultErrorResponsePublisher(httpRequest, throwable));
} else {
if (isIgnorable(cause)) {
logIgnoredException(cause);
return Flux.empty();
} else {
return createDefaultErrorResponsePublisher(
httpRequest,
cause).flux();
}
}
}
}
/**
* Creates a default error response. Should be used when a response could not be retrieved
* from any other method.
*
* @param httpRequest The request that case the exception
* @param cause The exception that occurred
* @return A response to represent the exception
*/
public MutableHttpResponse<?> createDefaultErrorResponse(HttpRequest<?> httpRequest,
Throwable cause) {
logException(cause);
final MutableHttpResponse<Object> response = HttpResponse.serverError();
response.setAttribute(HttpAttributes.EXCEPTION, cause);
response.setAttribute(HttpAttributes.ROUTE_INFO, new RouteInfo<MutableHttpResponse>() {
@Override
public ReturnType<MutableHttpResponse> getReturnType() {
return ReturnType.of(MutableHttpResponse.class, Argument.OBJECT_ARGUMENT);
}
@Override
public Class<?> getDeclaringType() {
return Object.class;
}
@Override
public boolean isErrorRoute() {
return true;
}
});
MutableHttpResponse<?> mutableHttpResponse = errorResponseProcessor.processResponse(
ErrorContext.builder(httpRequest)
.cause(cause)
.errorMessage("Internal Server Error: " + cause.getMessage())
.build(), response);
applyConfiguredHeaders(mutableHttpResponse.getHeaders());
if (!mutableHttpResponse.getContentType().isPresent() && httpRequest.getMethod() != HttpMethod.HEAD) {
return mutableHttpResponse.contentType(MediaType.APPLICATION_JSON_TYPE);
}
return mutableHttpResponse;
}
/**
* @param request The request
* @param finalRoute The route
* @return The default content type declared on the route
*/
public MediaType resolveDefaultResponseContentType(HttpRequest<?> request, RouteInfo<?> finalRoute) {
final List<MediaType> producesList = finalRoute.getProduces();
if (request != null) {
final Iterator<MediaType> i = request.accept().iterator();
if (i.hasNext()) {
final MediaType mt = i.next();
if (producesList.contains(mt)) {
return mt;
}
}
}
MediaType defaultResponseMediaType;
final Iterator<MediaType> produces = producesList.iterator();
if (produces.hasNext()) {
defaultResponseMediaType = produces.next();
} else {
defaultResponseMediaType = MediaType.APPLICATION_JSON_TYPE;
}
return defaultResponseMediaType;
}
/**
* Executes a route.
*
* @param request The request that matched to the route
* @param executeFilters Whether or not to execute server filters
* @param routePublisher The route match publisher
* @return A response publisher
*/
public Flux<MutableHttpResponse<?>> executeRoute(
HttpRequest<?> request,
boolean executeFilters,
Flux<RouteMatch<?>> routePublisher) {
AtomicReference<HttpRequest<?>> requestReference = new AtomicReference<>(request);
return buildResultEmitter(
requestReference,
executeFilters,
routePublisher
);
}
/**
* Applies server filters to a request/response.
*
* @param requestReference The request reference
* @param upstreamResponsePublisher The original response publisher
* @return A new response publisher that executes server filters
*/
public Publisher<MutableHttpResponse<?>> filterPublisher(
AtomicReference<HttpRequest<?>> requestReference,
Publisher<MutableHttpResponse<?>> upstreamResponsePublisher) {
List<HttpFilter> httpFilters = router.findFilters(requestReference.get());
if (httpFilters.isEmpty()) {
return upstreamResponsePublisher;
}
List<HttpFilter> filters = new ArrayList<>(httpFilters);
AtomicInteger integer = new AtomicInteger();
int len = filters.size();
final Function<MutableHttpResponse<?>, Publisher<MutableHttpResponse<?>>> handleStatusException = (response) ->
handleStatusException(requestReference.get(), response);
final Function<Throwable, Publisher<MutableHttpResponse<?>>> onError = (t) ->
onError(t, requestReference.get());
ServerFilterChain filterChain = new ServerFilterChain() {
@SuppressWarnings("unchecked")
@Override
public Publisher<MutableHttpResponse<?>> proceed(io.micronaut.http.HttpRequest<?> request) {
int pos = integer.incrementAndGet();
if (pos > len) {
throw new IllegalStateException("The FilterChain.proceed(..) method should be invoked exactly once per filter execution. The method has instead been invoked multiple times by an erroneous filter definition.");
}
if (pos == len) {
return upstreamResponsePublisher;
}
HttpFilter httpFilter = filters.get(pos);
requestReference.set(request);
try {
return Flux.from((Publisher<MutableHttpResponse<?>>) httpFilter.doFilter(request, this))
.flatMap(handleStatusException)
.onErrorResume(onError);
} catch (Throwable t) {
return onError.apply(t);
}
}
};
HttpFilter httpFilter = filters.get(0);
HttpRequest<?> request = requestReference.get();
try {
return Flux.from((Publisher<MutableHttpResponse<?>>) httpFilter.doFilter(request, filterChain))
.flatMap(handleStatusException)
.onErrorResume(onError);
} catch (Throwable t) {
return onError.apply(t);
}
}
private Mono<MutableHttpResponse<?>> createDefaultErrorResponsePublisher(HttpRequest<?> httpRequest,
Throwable cause) {
return Mono.fromCallable(() -> createDefaultErrorResponse(httpRequest, cause));
}
private MutableHttpResponse<?> newNotFoundError(HttpRequest<?> request) {
MutableHttpResponse<?> response = errorResponseProcessor.processResponse(
ErrorContext.builder(request)
.errorMessage("Page Not Found")
.build(), HttpResponse.notFound());
if (!response.getContentType().isPresent() && request.getMethod() != HttpMethod.HEAD) {
return response.contentType(MediaType.APPLICATION_JSON_TYPE);
}
return response;
}
private Mono<MutableHttpResponse<?>> createNotFoundErrorResponsePublisher(HttpRequest<?> httpRequest) {
return Mono.fromCallable(() -> newNotFoundError(httpRequest));
}
private void logException(Throwable cause) {
//handling connection reset by peer exceptions
if (isIgnorable(cause)) {
logIgnoredException(cause);
} else {
if (LOG.isErrorEnabled()) {
LOG.error("Unexpected error occurred: " + cause.getMessage(), cause);
}
}
}
private boolean isIgnorable(Throwable cause) {
String message = cause.getMessage();
return cause instanceof IOException && message != null && IGNORABLE_ERROR_MESSAGE.matcher(message).matches();
}
private void logIgnoredException(Throwable cause) {
if (LOG.isDebugEnabled()) {
LOG.debug("Swallowed an IOException caused by client connectivity: " + cause.getMessage(), cause);
}
}
private RouteMatch<?> findErrorRoute(Throwable cause,
Class<?> declaringType,
HttpRequest<?> httpRequest) {
RouteMatch<?> errorRoute = null;
if (cause instanceof BeanCreationException && declaringType != null) {
// If the controller could not be instantiated, don't look for a local error route
Optional<Class> rootBeanType = ((BeanCreationException) cause).getRootBeanType().map(BeanType::getBeanType);
if (rootBeanType.isPresent() && declaringType == rootBeanType.get()) {
if (LOG.isDebugEnabled()) {
LOG.debug("Failed to instantiate [{}]. Skipping lookup of a local error route", declaringType.getName());
}
declaringType = null;
}
}
// First try to find an error route by the exception
if (declaringType != null) {
// handle error with a method that is non global with exception
errorRoute = router.findErrorRoute(declaringType, cause, httpRequest).orElse(null);
}
if (errorRoute == null) {
// handle error with a method that is global with exception
errorRoute = router.findErrorRoute(cause, httpRequest).orElse(null);
}
if (errorRoute == null) {
// Second try is by status route if the status is known
HttpStatus errorStatus = null;
if (cause instanceof UnsatisfiedRouteException) {
// when arguments do not match, then there is UnsatisfiedRouteException, we can handle this with a routed bad request
errorStatus = HttpStatus.BAD_REQUEST;
} else if (cause instanceof HttpStatusException) {
errorStatus = ((HttpStatusException) cause).getStatus();
}
if (errorStatus != null) {
if (declaringType != null) {
// handle error with a method that is non global with bad request
errorRoute = router.findStatusRoute(declaringType, errorStatus, httpRequest).orElse(null);
}
if (errorRoute == null) {
// handle error with a method that is global with bad request
errorRoute = router.findStatusRoute(errorStatus, httpRequest).orElse(null);
}
}
}
if (errorRoute != null) {
if (LOG.isDebugEnabled()) {
LOG.debug("Found matching exception handler for exception [{}]: {}", cause.getMessage(), errorRoute);
}
errorRoute = requestArgumentSatisfier.fulfillArgumentRequirements(errorRoute, httpRequest, false);
}
return errorRoute;
}
private Publisher<MutableHttpResponse<?>> handleStatusException(HttpRequest<?> request,
MutableHttpResponse<?> response) {
HttpStatus status = response.status();
RouteInfo<?> routeInfo = response.getAttribute(HttpAttributes.ROUTE_INFO, RouteInfo.class).orElse(null);
if (status.getCode() >= 400 && routeInfo != null && !routeInfo.isErrorRoute()) {
RouteMatch<Object> statusRoute = findStatusRoute(request, status, routeInfo);
if (statusRoute != null) {
return executeRoute(
request,
false,
Flux.just(statusRoute)
);
}
}
return Flux.just(response);
}
private RouteMatch<Object> findStatusRoute(HttpRequest<?> incomingRequest, HttpStatus status, RouteInfo<?> finalRoute) {
Class<?> declaringType = finalRoute.getDeclaringType();
// handle re-mapping of errors
RouteMatch<Object> statusRoute = null;
// if declaringType is not null, this means its a locally marked method handler
if (declaringType != null) {
statusRoute = router.findStatusRoute(declaringType, status, incomingRequest)
.orElseGet(() -> router.findStatusRoute(status, incomingRequest).orElse(null));
}
return statusRoute;
}
private ExecutorService findExecutor(RouteInfo<?> routeMatch) {
// Select the most appropriate Executor
ExecutorService executor;
if (routeMatch instanceof MethodReference) {
executor = executorSelector.select((MethodReference<?, ?>) routeMatch, serverConfiguration.getThreadSelection()).orElse(null);
} else {
executor = null;
}
return executor;
}
private <T> Flux<T> applyExecutorToPublisher(
Publisher<T> publisher,
@Nullable ExecutorService executor) {
if (executor != null) {
final Scheduler scheduler = Schedulers.fromExecutorService(executor);
return Flux.from(publisher)
.subscribeOn(scheduler)
.publishOn(scheduler);
} else {
return Flux.from(publisher);
}
}
private boolean isSingle(RouteInfo<?> finalRoute, Class<?> bodyClass) {
return finalRoute.isSpecifiedSingle() || (finalRoute.isSingleResult() &&
(finalRoute.isAsync() || finalRoute.isSuspended() || Publishers.isSingle(bodyClass)));
}
private MutableHttpResponse<?> toMutableResponse(HttpResponse<?> message) {
MutableHttpResponse<?> mutableHttpResponse;
if (message instanceof MutableHttpResponse) {
mutableHttpResponse = (MutableHttpResponse<?>) message;
} else {
HttpStatus httpStatus = message.status();
mutableHttpResponse = HttpResponse.status(httpStatus, httpStatus.getReason());
mutableHttpResponse.body(message.body());
message.getHeaders().forEach((name, value) -> {
for (String val : value) {
mutableHttpResponse.header(name, val);
}
});
mutableHttpResponse.getAttributes().putAll(message.getAttributes());
}
return mutableHttpResponse;
}
private Mono<MutableHttpResponse<?>> toMutableResponse(HttpRequest<?> request, RouteInfo<?> routeInfo, HttpStatus defaultHttpStatus, Object body) {
if (body instanceof HttpResponse) {
MutableHttpResponse<?> outgoingResponse = toMutableResponse((HttpResponse<?>) body);
final Argument<?> bodyArgument = routeInfo.getReturnType().getFirstTypeVariable().orElse(Argument.OBJECT_ARGUMENT);
if (bodyArgument.isAsyncOrReactive()) {
return processPublisherBody(request, outgoingResponse, routeInfo);
} else {
return Mono.just(outgoingResponse);
}
} else {
return Mono.just(forStatus(routeInfo, defaultHttpStatus)
.body(body));
}
}
private Flux<MutableHttpResponse<?>> buildRouteResponsePublisher(AtomicReference<HttpRequest<?>> requestReference,
Flux<RouteMatch<?>> routeMatchPublisher) {
// build the result emitter. This result emitter emits the response from a controller action
return routeMatchPublisher
.flatMap((route) -> {
final ExecutorService executor = findExecutor(route);
Flux<MutableHttpResponse<?>> reactiveSequence = executeRoute(requestReference, route);
if (executor != null) {
reactiveSequence = applyExecutorToPublisher(reactiveSequence, executor);
}
return reactiveSequence;
});
}
private Flux<MutableHttpResponse<?>> buildResultEmitter(
AtomicReference<HttpRequest<?>> requestReference,
boolean executeFilters,
Flux<RouteMatch<?>> routeMatchPublisher) {
Publisher<MutableHttpResponse<?>> executeRoutePublisher = buildRouteResponsePublisher(requestReference, routeMatchPublisher)
.flatMap((response) -> handleStatusException(requestReference.get(), response))
.onErrorResume((t) -> onError(t, requestReference.get()));
if (executeFilters) {
executeRoutePublisher = filterPublisher(requestReference, executeRoutePublisher);
}
return Flux.from(executeRoutePublisher);
}
private Flux<MutableHttpResponse<?>> executeRoute(AtomicReference<HttpRequest<?>> requestReference,
RouteMatch<?> routeMatch) {
return Flux.deferContextual(contextView -> {
try {
final RouteMatch<?> finalRoute;
// ensure the route requirements are completely satisfied
final HttpRequest<?> httpRequest = requestReference.get();
if (!routeMatch.isExecutable()) {
finalRoute = requestArgumentSatisfier
.fulfillArgumentRequirements(routeMatch, httpRequest, true);
} else {
finalRoute = routeMatch;
}
if (finalRoute.isSuspended() && coroutineHelper.isPresent()) {
coroutineHelper.get().setupCoroutineContext(httpRequest, contextView);
}
Object body = ServerRequestContext.with(httpRequest, (Supplier<Object>) finalRoute::execute);
if (body instanceof Optional) {
body = ((Optional<?>) body).orElse(null);
}
return createResponseForBody(httpRequest, body, finalRoute);
} catch (Throwable e) {
return Flux.error(e);
}
});
}
private Flux<MutableHttpResponse<?>> createResponseForBody(HttpRequest<?> request,
Object body,
RouteInfo<?> routeInfo) {
return Flux.<MutableHttpResponse<?>>defer(() -> {
Mono<MutableHttpResponse<?>> outgoingResponse;
if (body == null) {
if (routeInfo.isVoid()) {
MutableHttpResponse<Object> data = forStatus(routeInfo);
if (HttpMethod.permitsRequestBody(request.getMethod())) {
data.header(HttpHeaders.CONTENT_LENGTH, "0");
}
outgoingResponse = Mono.just(data);
} else {
outgoingResponse = Mono.just(newNotFoundError(request));
}
} else {
HttpStatus defaultHttpStatus = routeInfo.isErrorRoute() ? HttpStatus.INTERNAL_SERVER_ERROR : HttpStatus.OK;
boolean isReactive = routeInfo.isAsyncOrReactive() || Publishers.isConvertibleToPublisher(body);
if (isReactive) {
Class<?> bodyClass = body.getClass();
boolean isSingle = isSingle(routeInfo, bodyClass);
boolean isCompletable = !isSingle && routeInfo.isVoid() && Publishers.isCompletable(bodyClass);
if (isSingle || isCompletable) {
// full response case
Publisher<Object> publisher = Publishers.convertPublisher(body, Publisher.class);
Supplier<MutableHttpResponse<?>> emptyResponse = () -> {
MutableHttpResponse<?> singleResponse;
if (isCompletable || routeInfo.isVoid()) {
singleResponse = forStatus(routeInfo, HttpStatus.OK)
.header(HttpHeaders.CONTENT_LENGTH, "0");
} else {
singleResponse = newNotFoundError(request);
}
return singleResponse;
};
return Flux.from(publisher)
.flatMap(o -> {
MutableHttpResponse<?> singleResponse;
if (o instanceof Optional) {
Optional optional = (Optional) o;
if (optional.isPresent()) {
o = ((Optional<?>) o).get();
} else {
return Flux.just(emptyResponse.get());
}
}
if (o instanceof HttpResponse) {
singleResponse = toMutableResponse((HttpResponse<?>) o);
final Argument<?> bodyArgument = routeInfo.getReturnType() //Mono
.getFirstTypeVariable().orElse(Argument.OBJECT_ARGUMENT) //HttpResponse
.getFirstTypeVariable().orElse(Argument.OBJECT_ARGUMENT); //Mono
if (bodyArgument.isAsyncOrReactive()) {
return processPublisherBody(request, singleResponse, routeInfo);
}
} else if (o instanceof HttpStatus) {
singleResponse = forStatus(routeInfo, (HttpStatus) o);
} else {
singleResponse = forStatus(routeInfo, defaultHttpStatus)
.body(o);
}
return Flux.just(singleResponse);
})
.switchIfEmpty(Mono.fromSupplier(emptyResponse));
} else {
// streaming case
Argument<?> typeArgument = routeInfo.getReturnType().getFirstTypeVariable().orElse(Argument.OBJECT_ARGUMENT);
if (HttpResponse.class.isAssignableFrom(typeArgument.getType())) {
// a response stream
Publisher<HttpResponse<?>> bodyPublisher = Publishers.convertPublisher(body, Publisher.class);
Flux<MutableHttpResponse<?>> response = Flux.from(bodyPublisher)
.map(this::toMutableResponse);
Argument<?> bodyArgument = typeArgument.getFirstTypeVariable().orElse(Argument.OBJECT_ARGUMENT);
if (bodyArgument.isAsyncOrReactive()) {
return response.flatMap((resp) ->
processPublisherBody(request, resp, routeInfo));
}
return response;
} else {
MutableHttpResponse<?> response = forStatus(routeInfo, defaultHttpStatus).body(body);
return processPublisherBody(request, response, routeInfo);
}
}
}
// now we have the raw result, transform it as necessary
if (body instanceof HttpStatus) {
outgoingResponse = Mono.just(HttpResponse.status((HttpStatus) body));
} else {
if (routeInfo.isSuspended()) {
boolean isKotlinFunctionReturnTypeUnit =
routeInfo instanceof MethodBasedRouteMatch &&
isKotlinFunctionReturnTypeUnit(((MethodBasedRouteMatch) routeInfo).getExecutableMethod());
final Supplier<CompletableFuture<?>> supplier = ContinuationArgumentBinder.extractContinuationCompletableFutureSupplier(request);
if (isKotlinCoroutineSuspended(body)) {
return Mono.fromCompletionStage(supplier)
.<MutableHttpResponse<?>>flatMap(obj -> {
MutableHttpResponse<?> response;
if (obj instanceof HttpResponse) {
response = toMutableResponse((HttpResponse<?>) obj);
final Argument<?> bodyArgument = routeInfo.getReturnType().getFirstTypeVariable().orElse(Argument.OBJECT_ARGUMENT);
if (bodyArgument.isAsyncOrReactive()) {
return processPublisherBody(request, response, routeInfo);
}
} else {
response = forStatus(routeInfo, defaultHttpStatus);
if (!isKotlinFunctionReturnTypeUnit) {
response = response.body(obj);
}
}
return Mono.just(response);
})
.switchIfEmpty(createNotFoundErrorResponsePublisher(request));
} else {
Object suspendedBody;
if (isKotlinFunctionReturnTypeUnit) {
suspendedBody = Mono.empty();
} else {
suspendedBody = body;
}
outgoingResponse = toMutableResponse(request, routeInfo, defaultHttpStatus, suspendedBody);
}
} else {
outgoingResponse = toMutableResponse(request, routeInfo, defaultHttpStatus, body);
}
}
}
// for head request we never emit the body
if (request != null && request.getMethod().equals(HttpMethod.HEAD)) {
outgoingResponse = outgoingResponse.map(r -> {
final Object o = r.getBody().orElse(null);
if (o instanceof ReferenceCounted) {
((ReferenceCounted) o).release();
}
r.body(null);
return r;
});
}
return outgoingResponse;
})
.doOnNext((response) -> {
applyConfiguredHeaders(response.getHeaders());
if (routeInfo instanceof RouteMatch) {
response.setAttribute(HttpAttributes.ROUTE_MATCH, routeInfo);
}
response.setAttribute(HttpAttributes.ROUTE_INFO, routeInfo);
});
}
private Mono<MutableHttpResponse<?>> processPublisherBody(HttpRequest<?> request,
MutableHttpResponse<?> response,
RouteInfo<?> routeInfo) {
Object body = response.body();
if (body == null) {
return Mono.just(response);
} else if (Publishers.isSingle(body.getClass())) {
return Mono.from(Publishers.convertPublisher(body, Publisher.class)).map(b -> {
response.body(b);
return response;
});
} else {
MediaType mediaType = response.getContentType().orElseGet(() -> resolveDefaultResponseContentType(request, routeInfo));
Flux<Object> bodyPublisher = applyExecutorToPublisher(
Publishers.convertPublisher(body, Publisher.class),
findExecutor(routeInfo));
return Mono.just(response
.header(HttpHeaders.TRANSFER_ENCODING, "chunked")
.header(HttpHeaders.CONTENT_TYPE, mediaType)
.body(bodyPublisher));
}
}
private void applyConfiguredHeaders(MutableHttpHeaders headers) {
if (serverConfiguration.isDateHeader() && !headers.contains(HttpHeaders.DATE)) {
headers.date(LocalDateTime.now());
}
if (!headers.contains(HttpHeaders.SERVER)) {
serverConfiguration.getServerHeader()
.ifPresent(header -> headers.add(HttpHeaders.SERVER, header));
}
}
private MutableHttpResponse<Object> forStatus(RouteInfo<?> routeMatch) {
return forStatus(routeMatch, HttpStatus.OK);
}
private MutableHttpResponse<Object> forStatus(RouteInfo<?> routeMatch, HttpStatus defaultStatus) {
HttpStatus status = routeMatch.findStatus(defaultStatus);
return HttpResponse.status(status);
}
}