Search in sources :

Example 1 with RoutingHandler

use of com.nike.riposte.server.handler.RoutingHandler in project riposte by Nike-Inc.

the class HttpChannelInitializerTest method initChannel_adds_before_and_after_RequestFilterHandler_appropriately_before_and_after_security_filter.

@Test
public void initChannel_adds_before_and_after_RequestFilterHandler_appropriately_before_and_after_security_filter() {
    // given
    RequestAndResponseFilter beforeSecurityRequestFilter = mock(RequestAndResponseFilter.class);
    doReturn(true).when(beforeSecurityRequestFilter).shouldExecuteBeforeSecurityValidation();
    RequestAndResponseFilter afterSecurityRequestFilter = mock(RequestAndResponseFilter.class);
    doReturn(false).when(afterSecurityRequestFilter).shouldExecuteBeforeSecurityValidation();
    List<RequestAndResponseFilter> requestAndResponseFilters = Arrays.asList(beforeSecurityRequestFilter, afterSecurityRequestFilter);
    HttpChannelInitializer hci = basicHttpChannelInitializer(null, 0, 42, false, null, requestAndResponseFilters);
    // when
    hci.initChannel(socketChannelMock);
    // then
    ArgumentCaptor<ChannelHandler> channelHandlerArgumentCaptor = ArgumentCaptor.forClass(ChannelHandler.class);
    verify(channelPipelineMock, atLeastOnce()).addLast(anyString(), channelHandlerArgumentCaptor.capture());
    List<ChannelHandler> handlers = channelHandlerArgumentCaptor.getAllValues();
    Pair<Integer, AccessLogStartHandler> accessLogStartHandler = findChannelHandler(handlers, AccessLogStartHandler.class);
    Pair<Integer, RequestFilterHandler> beforeSecurityRequestFilterHandler = findChannelHandler(handlers, RequestFilterHandler.class);
    Pair<Integer, RequestFilterHandler> afterSecurityRequestFilterHandler = findChannelHandler(handlers, RequestFilterHandler.class, true);
    Pair<Integer, RoutingHandler> routingHandler = findChannelHandler(handlers, RoutingHandler.class);
    Pair<Integer, SecurityValidationHandler> securityValidationHandler = findChannelHandler(handlers, SecurityValidationHandler.class);
    Pair<Integer, RequestContentDeserializerHandler> requestContentDeserializerHandler = findChannelHandler(handlers, RequestContentDeserializerHandler.class);
    assertThat(accessLogStartHandler, notNullValue());
    assertThat(beforeSecurityRequestFilterHandler, notNullValue());
    assertThat(routingHandler, notNullValue());
    assertThat(afterSecurityRequestFilterHandler, notNullValue());
    assertThat(securityValidationHandler, notNullValue());
    assertThat(requestContentDeserializerHandler, notNullValue());
    Assertions.assertThat(beforeSecurityRequestFilterHandler.getLeft()).isGreaterThan(accessLogStartHandler.getLeft());
    Assertions.assertThat(beforeSecurityRequestFilterHandler.getLeft()).isLessThan(securityValidationHandler.getLeft());
    // beforeSecurityRequestFilterHandler must come before RoutingHandler as well (so that it is executed before any 404 gets thrown)
    Assertions.assertThat(beforeSecurityRequestFilterHandler.getLeft()).isLessThan(routingHandler.getLeft());
    Assertions.assertThat(afterSecurityRequestFilterHandler.getLeft()).isGreaterThan(securityValidationHandler.getLeft());
    Assertions.assertThat(afterSecurityRequestFilterHandler.getLeft()).isLessThan(requestContentDeserializerHandler.getLeft());
    // and then
    RequestFilterHandler beforeSecurityCachedHandler = extractField(hci, "beforeSecurityRequestFilterHandler");
    Assertions.assertThat(beforeSecurityRequestFilterHandler.getRight()).isSameAs(beforeSecurityCachedHandler);
    RequestFilterHandler afterSecurityCachedHandler = extractField(hci, "afterSecurityRequestFilterHandler");
    Assertions.assertThat(afterSecurityRequestFilterHandler.getRight()).isSameAs(afterSecurityCachedHandler);
}
Also used : AccessLogStartHandler(com.nike.riposte.server.handler.AccessLogStartHandler) RequestAndResponseFilter(com.nike.riposte.server.http.filter.RequestAndResponseFilter) RequestContentDeserializerHandler(com.nike.riposte.server.handler.RequestContentDeserializerHandler) ChannelHandler(io.netty.channel.ChannelHandler) RequestFilterHandler(com.nike.riposte.server.handler.RequestFilterHandler) RoutingHandler(com.nike.riposte.server.handler.RoutingHandler) SecurityValidationHandler(com.nike.riposte.server.handler.SecurityValidationHandler) Test(org.junit.Test)

Example 2 with RoutingHandler

use of com.nike.riposte.server.handler.RoutingHandler in project riposte by Nike-Inc.

the class HttpChannelInitializerTest method initChannel_adds_RequestContentDeserializerHandler_after_RequestInfoSetterHandler_and_RoutingHandler_and_uses_requestContentDeserializer.

@Test
public void initChannel_adds_RequestContentDeserializerHandler_after_RequestInfoSetterHandler_and_RoutingHandler_and_uses_requestContentDeserializer() {
    // given
    HttpChannelInitializer hci = basicHttpChannelInitializerNoUtilityHandlers();
    ObjectMapper expectedRequestContentDeserializer = mock(ObjectMapper.class);
    Whitebox.setInternalState(hci, "requestContentDeserializer", expectedRequestContentDeserializer);
    // when
    hci.initChannel(socketChannelMock);
    // then
    ArgumentCaptor<ChannelHandler> channelHandlerArgumentCaptor = ArgumentCaptor.forClass(ChannelHandler.class);
    verify(channelPipelineMock, atLeastOnce()).addLast(anyString(), channelHandlerArgumentCaptor.capture());
    List<ChannelHandler> handlers = channelHandlerArgumentCaptor.getAllValues();
    Pair<Integer, RequestInfoSetterHandler> requestInfoSetterHandler = findChannelHandler(handlers, RequestInfoSetterHandler.class);
    Pair<Integer, RoutingHandler> routingHandler = findChannelHandler(handlers, RoutingHandler.class);
    Pair<Integer, RequestContentDeserializerHandler> requestContentDeserializerHandler = findChannelHandler(handlers, RequestContentDeserializerHandler.class);
    assertThat(requestInfoSetterHandler, notNullValue());
    assertThat(routingHandler, notNullValue());
    assertThat(requestContentDeserializerHandler, notNullValue());
    assertThat(requestContentDeserializerHandler.getLeft(), is(greaterThan(requestInfoSetterHandler.getLeft())));
    assertThat(requestContentDeserializerHandler.getLeft(), is(greaterThan(routingHandler.getLeft())));
    // and then
    ObjectMapper actualRequestContentDeserializer = (ObjectMapper) Whitebox.getInternalState(requestContentDeserializerHandler.getRight(), "defaultRequestContentDeserializer");
    assertThat(actualRequestContentDeserializer, is(expectedRequestContentDeserializer));
}
Also used : RoutingHandler(com.nike.riposte.server.handler.RoutingHandler) RequestInfoSetterHandler(com.nike.riposte.server.handler.RequestInfoSetterHandler) RequestContentDeserializerHandler(com.nike.riposte.server.handler.RequestContentDeserializerHandler) ChannelHandler(io.netty.channel.ChannelHandler) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Test(org.junit.Test)

Example 3 with RoutingHandler

use of com.nike.riposte.server.handler.RoutingHandler in project riposte by Nike-Inc.

the class HttpChannelInitializer method initChannel.

@Override
public void initChannel(SocketChannel ch) {
    ChannelPipeline p = ch.pipeline();
    // request/response payloads, etc.
    if (debugChannelLifecycleLoggingEnabled) {
        p.addLast(SERVER_WORKER_CHANNEL_DEBUG_LOGGING_HANDLER_NAME, new LoggingHandler(SERVER_WORKER_CHANNEL_DEBUG_SLF4J_LOGGER_NAME, LogLevel.DEBUG));
    }
    // order).
    if (sslCtx != null)
        p.addLast(SSL_HANDLER_NAME, sslCtx.newHandler(ch.alloc()));
    // IN/OUT - Add the HttpServerCodec to decode requests into the appropriate HttpObjects and encode responses
    // from HttpObjects into bytes. This MUST be the earliest "outbound" handler after the SSL handler
    // since outbound handlers are processed in reverse order.
    p.addLast(HTTP_SERVER_CODEC_HANDLER_NAME, new HttpServerCodec(httpRequestDecoderConfig.maxInitialLineLength(), httpRequestDecoderConfig.maxHeaderSize(), httpRequestDecoderConfig.maxChunkSize()));
    // OUTBOUND - Add ProcessFinalResponseOutputHandler to get the final response headers, calculate the final
    // content length (after compression/gzip and/or any other modifications), etc, and set those values
    // on the channel's HttpProcessingState.
    p.addLast(PROCESS_FINAL_RESPONSE_OUTPUT_HANDLER_NAME, new ProcessFinalResponseOutputHandler());
    // INBOUND - Now that the message is translated into HttpObjects we can add RequestStateCleanerHandler to
    // setup/clean state for the rest of the pipeline.
    p.addLast(REQUEST_STATE_CLEANER_HANDLER_NAME, new RequestStateCleanerHandler(metricsListener, incompleteHttpCallTimeoutMillis, distributedTracingConfig));
    // INBOUND - Add DTraceStartHandler to start the distributed tracing for this request
    p.addLast(DTRACE_START_HANDLER_NAME, new DTraceStartHandler(userIdHeaderKeys, distributedTracingConfig));
    // INBOUND - Access log start
    p.addLast(ACCESS_LOG_START_HANDLER_NAME, new AccessLogStartHandler());
    // IN/OUT - Add SmartHttpContentCompressor for automatic content compression (if appropriate for the
    // request/response/size threshold). This must be added after HttpServerCodec so that it can process
    // after the request on the incoming pipeline and before the response on the outbound pipeline.
    p.addLast(SMART_HTTP_CONTENT_COMPRESSOR_HANDLER_NAME, new SmartHttpContentCompressor(responseCompressionThresholdBytes));
    // before RoutingHandler throws 404s/405s.
    if (beforeSecurityRequestFilterHandler != null)
        p.addLast(REQUEST_FILTER_BEFORE_SECURITY_HANDLER_NAME, beforeSecurityRequestFilterHandler);
    // INBOUND - Add RoutingHandler to figure out which endpoint should handle the request and set it on our request
    // state for later execution
    p.addLast(ROUTING_HANDLER_NAME, new RoutingHandler(endpoints, maxRequestSizeInBytes, distributedTracingConfig));
    // INBOUND - Add SmartHttpContentDecompressor for automatic content decompression if the request indicates it
    // is compressed *and* the target endpoint (determined by the previous RoutingHandler) is one that
    // is eligible for auto-decompression.
    p.addLast(SMART_HTTP_CONTENT_DECOMPRESSOR_HANDLER_NAME, new SmartHttpContentDecompressor());
    // INBOUND - Add RequestInfoSetterHandler to populate our RequestInfo's content.
    p.addLast(REQUEST_INFO_SETTER_HANDLER_NAME, new RequestInfoSetterHandler(maxRequestSizeInBytes));
    // maxOpenChannelsThreshold is not -1.
    if (maxOpenChannelsThreshold != -1) {
        p.addLast(OPEN_CHANNEL_LIMIT_HANDLER_NAME, new OpenChannelLimitHandler(openChannelsGroup, maxOpenChannelsThreshold));
    }
    // INBOUND - Add SecurityValidationHandler to validate the RequestInfo object for the matching endpoint
    p.addLast(SECURITY_VALIDATION_HANDLER_NAME, new SecurityValidationHandler(requestSecurityValidator));
    // INBOUND - Add the RequestFilterHandler for after security (if we have any filters to apply).
    if (afterSecurityRequestFilterHandler != null)
        p.addLast(REQUEST_FILTER_AFTER_SECURITY_HANDLER_NAME, afterSecurityRequestFilterHandler);
    // INBOUND - Now that the request state knows which endpoint will be called we can try to deserialize the
    // request content (if desired by the endpoint)
    p.addLast(REQUEST_CONTENT_DESERIALIZER_HANDLER_NAME, new RequestContentDeserializerHandler(requestContentDeserializer));
    // deserialized content (if desired by the endpoint and if we have a non-null validator)
    if (validationService != null)
        p.addLast(REQUEST_CONTENT_VALIDATION_HANDLER_NAME, new RequestContentValidationHandler(validationService));
    // INBOUND - Add NonblockingEndpointExecutionHandler to perform execution of async/nonblocking endpoints
    p.addLast(NONBLOCKING_ENDPOINT_EXECUTION_HANDLER_NAME, new NonblockingEndpointExecutionHandler(longRunningTaskExecutor, defaultCompletableFutureTimeoutMillis, distributedTracingConfig));
    // INBOUND - Add ProxyRouterEndpointExecutionHandler to perform execution of proxy routing endpoints
    p.addLast(PROXY_ROUTER_ENDPOINT_EXECUTION_HANDLER_NAME, new ProxyRouterEndpointExecutionHandler(longRunningTaskExecutor, streamingAsyncHttpClientForProxyRouterEndpoints, defaultCompletableFutureTimeoutMillis, distributedTracingConfig));
    // INBOUND - Add RequestHasBeenHandledVerificationHandler to verify that one of the endpoint handlers took care
    // of the request. This makes sure that the messages coming into channelRead are correctly typed for
    // the rest of the pipeline.
    p.addLast(REQUEST_HAS_BEEN_HANDLED_VERIFICATION_HANDLER_NAME, new RequestHasBeenHandledVerificationHandler());
    // INBOUND - Add ExceptionHandlingHandler to catch and deal with any exceptions or requests that fell through
    // the cracks.
    ExceptionHandlingHandler exceptionHandlingHandler = new ExceptionHandlingHandler(riposteErrorHandler, riposteUnhandledErrorHandler, distributedTracingConfig);
    p.addLast(EXCEPTION_HANDLING_HANDLER_NAME, exceptionHandlingHandler);
    // INBOUND - Add the ResponseFilterHandler (if we have any filters to apply).
    if (cachedResponseFilterHandler != null)
        p.addLast(RESPONSE_FILTER_HANDLER_NAME, cachedResponseFilterHandler);
    // INBOUND - Add ResponseSenderHandler to send the response that got put into the request state
    p.addLast(RESPONSE_SENDER_HANDLER_NAME, new ResponseSenderHandler(responseSender));
    // INBOUND - Access log end
    p.addLast(ACCESS_LOG_END_HANDLER_NAME, new AccessLogEndHandler(accessLogger));
    // INBOUND - Add DTraceEndHandler to finish up our distributed trace for this request.
    p.addLast(DTRACE_END_HANDLER_NAME, new DTraceEndHandler());
    // INBOUND - Add ChannelPipelineFinalizerHandler to stop the request processing.
    p.addLast(CHANNEL_PIPELINE_FINALIZER_HANDLER_NAME, new ChannelPipelineFinalizerHandler(exceptionHandlingHandler, responseSender, metricsListener, accessLogger, workerChannelIdleTimeoutMillis));
    // pipeline create hooks
    if (pipelineCreateHooks != null) {
        for (PipelineCreateHook hook : pipelineCreateHooks) {
            hook.executePipelineCreateHook(p);
        }
    }
}
Also used : ExceptionHandlingHandler(com.nike.riposte.server.handler.ExceptionHandlingHandler) LoggingHandler(io.netty.handler.logging.LoggingHandler) AccessLogStartHandler(com.nike.riposte.server.handler.AccessLogStartHandler) RequestContentValidationHandler(com.nike.riposte.server.handler.RequestContentValidationHandler) ProxyRouterEndpointExecutionHandler(com.nike.riposte.server.handler.ProxyRouterEndpointExecutionHandler) RequestContentDeserializerHandler(com.nike.riposte.server.handler.RequestContentDeserializerHandler) RequestStateCleanerHandler(com.nike.riposte.server.handler.RequestStateCleanerHandler) PipelineCreateHook(com.nike.riposte.server.hooks.PipelineCreateHook) ChannelPipeline(io.netty.channel.ChannelPipeline) SmartHttpContentCompressor(com.nike.riposte.server.handler.SmartHttpContentCompressor) DTraceEndHandler(com.nike.riposte.server.handler.DTraceEndHandler) RoutingHandler(com.nike.riposte.server.handler.RoutingHandler) AccessLogEndHandler(com.nike.riposte.server.handler.AccessLogEndHandler) SecurityValidationHandler(com.nike.riposte.server.handler.SecurityValidationHandler) DTraceStartHandler(com.nike.riposte.server.handler.DTraceStartHandler) RequestHasBeenHandledVerificationHandler(com.nike.riposte.server.handler.RequestHasBeenHandledVerificationHandler) RequestInfoSetterHandler(com.nike.riposte.server.handler.RequestInfoSetterHandler) ChannelPipelineFinalizerHandler(com.nike.riposte.server.handler.ChannelPipelineFinalizerHandler) HttpServerCodec(io.netty.handler.codec.http.HttpServerCodec) NonblockingEndpointExecutionHandler(com.nike.riposte.server.handler.NonblockingEndpointExecutionHandler) OpenChannelLimitHandler(com.nike.riposte.server.handler.OpenChannelLimitHandler) ProcessFinalResponseOutputHandler(com.nike.riposte.server.handler.ProcessFinalResponseOutputHandler) ResponseSenderHandler(com.nike.riposte.server.handler.ResponseSenderHandler) SmartHttpContentDecompressor(com.nike.riposte.server.handler.SmartHttpContentDecompressor)

Example 4 with RoutingHandler

use of com.nike.riposte.server.handler.RoutingHandler in project riposte by Nike-Inc.

the class HttpChannelInitializerTest method initChannel_adds_NonblockingEndpointExecutionHandler_after_RoutingHandler_and_RequestContentDeserializerHandler_and_RequestContentValidationHandler_and_uses_longRunningTaskExecutor_and_defaultCompletableFutureTimeoutMillis.

@Test
public void initChannel_adds_NonblockingEndpointExecutionHandler_after_RoutingHandler_and_RequestContentDeserializerHandler_and_RequestContentValidationHandler_and_uses_longRunningTaskExecutor_and_defaultCompletableFutureTimeoutMillis() {
    // given
    HttpChannelInitializer hci = basicHttpChannelInitializerNoUtilityHandlers();
    Whitebox.setInternalState(hci, "validationService", mock(RequestValidator.class));
    Executor expectedLongRunningTaskExecutor = extractField(hci, "longRunningTaskExecutor");
    long expectedDefaultCompletableFutureTimeoutMillis = extractField(hci, "defaultCompletableFutureTimeoutMillis");
    DistributedTracingConfig<Span> distributedTracingConfigMock = mock(DistributedTracingConfig.class);
    ServerSpanNamingAndTaggingStrategy<Span> expectedServerSpanNamingAndTaggingStrategy = mock(ServerSpanNamingAndTaggingStrategy.class);
    Whitebox.setInternalState(hci, "distributedTracingConfig", distributedTracingConfigMock);
    doReturn(expectedServerSpanNamingAndTaggingStrategy).when(distributedTracingConfigMock).getServerSpanNamingAndTaggingStrategy();
    // when
    hci.initChannel(socketChannelMock);
    // then
    ArgumentCaptor<ChannelHandler> channelHandlerArgumentCaptor = ArgumentCaptor.forClass(ChannelHandler.class);
    verify(channelPipelineMock, atLeastOnce()).addLast(anyString(), channelHandlerArgumentCaptor.capture());
    List<ChannelHandler> handlers = channelHandlerArgumentCaptor.getAllValues();
    Pair<Integer, RoutingHandler> routingHandler = findChannelHandler(handlers, RoutingHandler.class);
    Pair<Integer, RequestContentDeserializerHandler> requestContentDeserializerHandler = findChannelHandler(handlers, RequestContentDeserializerHandler.class);
    Pair<Integer, RequestContentValidationHandler> requestContentValidationHandler = findChannelHandler(handlers, RequestContentValidationHandler.class);
    Pair<Integer, NonblockingEndpointExecutionHandler> nonblockingEndpointExecutionHandler = findChannelHandler(handlers, NonblockingEndpointExecutionHandler.class);
    assertThat(routingHandler, notNullValue());
    assertThat(requestContentDeserializerHandler, notNullValue());
    assertThat(requestContentValidationHandler, notNullValue());
    assertThat(nonblockingEndpointExecutionHandler, notNullValue());
    assertThat(nonblockingEndpointExecutionHandler.getLeft(), is(greaterThan(routingHandler.getLeft())));
    assertThat(nonblockingEndpointExecutionHandler.getLeft(), is(greaterThan(requestContentDeserializerHandler.getLeft())));
    assertThat(nonblockingEndpointExecutionHandler.getLeft(), is(greaterThan(requestContentValidationHandler.getLeft())));
    // and then
    Executor actualLongRunningTaskExecutor = (Executor) Whitebox.getInternalState(nonblockingEndpointExecutionHandler.getRight(), "longRunningTaskExecutor");
    long actualDefaultCompletableFutureTimeoutMillis = (long) Whitebox.getInternalState(nonblockingEndpointExecutionHandler.getRight(), "defaultCompletableFutureTimeoutMillis");
    ServerSpanNamingAndTaggingStrategy<Span> actualTaggingStrategy = (ServerSpanNamingAndTaggingStrategy<Span>) Whitebox.getInternalState(nonblockingEndpointExecutionHandler.getRight(), "spanTaggingStrategy");
    assertThat(actualLongRunningTaskExecutor, is(expectedLongRunningTaskExecutor));
    assertThat(actualDefaultCompletableFutureTimeoutMillis, is(expectedDefaultCompletableFutureTimeoutMillis));
    assertThat(actualTaggingStrategy, is(expectedServerSpanNamingAndTaggingStrategy));
}
Also used : RequestContentValidationHandler(com.nike.riposte.server.handler.RequestContentValidationHandler) RequestContentDeserializerHandler(com.nike.riposte.server.handler.RequestContentDeserializerHandler) ServerSpanNamingAndTaggingStrategy(com.nike.riposte.server.config.distributedtracing.ServerSpanNamingAndTaggingStrategy) ChannelHandler(io.netty.channel.ChannelHandler) Span(com.nike.wingtips.Span) ThreadPoolExecutor(java.util.concurrent.ThreadPoolExecutor) Executor(java.util.concurrent.Executor) RequestValidator(com.nike.riposte.server.error.validation.RequestValidator) RoutingHandler(com.nike.riposte.server.handler.RoutingHandler) NonblockingEndpointExecutionHandler(com.nike.riposte.server.handler.NonblockingEndpointExecutionHandler) Test(org.junit.Test)

Aggregations

RequestContentDeserializerHandler (com.nike.riposte.server.handler.RequestContentDeserializerHandler)4 RoutingHandler (com.nike.riposte.server.handler.RoutingHandler)4 ChannelHandler (io.netty.channel.ChannelHandler)3 Test (org.junit.Test)3 AccessLogStartHandler (com.nike.riposte.server.handler.AccessLogStartHandler)2 NonblockingEndpointExecutionHandler (com.nike.riposte.server.handler.NonblockingEndpointExecutionHandler)2 RequestContentValidationHandler (com.nike.riposte.server.handler.RequestContentValidationHandler)2 RequestInfoSetterHandler (com.nike.riposte.server.handler.RequestInfoSetterHandler)2 SecurityValidationHandler (com.nike.riposte.server.handler.SecurityValidationHandler)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 ServerSpanNamingAndTaggingStrategy (com.nike.riposte.server.config.distributedtracing.ServerSpanNamingAndTaggingStrategy)1 RequestValidator (com.nike.riposte.server.error.validation.RequestValidator)1 AccessLogEndHandler (com.nike.riposte.server.handler.AccessLogEndHandler)1 ChannelPipelineFinalizerHandler (com.nike.riposte.server.handler.ChannelPipelineFinalizerHandler)1 DTraceEndHandler (com.nike.riposte.server.handler.DTraceEndHandler)1 DTraceStartHandler (com.nike.riposte.server.handler.DTraceStartHandler)1 ExceptionHandlingHandler (com.nike.riposte.server.handler.ExceptionHandlingHandler)1 OpenChannelLimitHandler (com.nike.riposte.server.handler.OpenChannelLimitHandler)1 ProcessFinalResponseOutputHandler (com.nike.riposte.server.handler.ProcessFinalResponseOutputHandler)1 ProxyRouterEndpointExecutionHandler (com.nike.riposte.server.handler.ProxyRouterEndpointExecutionHandler)1