in java microservices api ~ read.
Thrift API Gateway. Part 2: Spring Domination

Thrift API Gateway. Part 2: Spring Domination

In the first part we investigated how to prepare thrift packets for exchanging security token by user information. Library was written and its time to move forward.

one annotation to rule them all

Annotation-driven development is Spring-way. Spring can be configured by many and many annotations that incapsulate tons of logic from your eyes. First step consists in annotation creation that loads configuration with beans and properties.

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@Import(ThriftGatewayConfiguration.class)
public @interface EnableThriftGateway {  
}

ThriftGatewayConfiguration consists some beans for our needs. It will be created some later.

intro to zuul

Netflix Zuul is the edge service that can routes and processes any http requests from frontend or mobile device and streams theirs to the backend. It has the system of chaining filters. Each filter adds new functionality. Even writing response is a filter. There are three filter types:

  • pre-filters
  • route
  • post-filters

Each type has an order. Pre filters are executing first. Next, route filters and post filters are executing last. Each filter has an own order too.

Lets create it.

public class AuthenticationZuulFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 6;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequestWrapper request = (HttpServletRequestWrapper) ctx.getRequest();

        //actions are here

        return null;
    }
}

Connect it to Spring container as a bean.

@Configuration
public class ThriftGatewayConfiguration {  
    @Bean
    public AuthenticationZuulFilter authenticationZuulFilter() {
        return new AuthenticationZuulFilter();
    }
}

magic configuration

Ok, lets do some magic. Remember configuration that we've described in first part of article? Implement it as write below:

@Configuration
public class ThriftGatewayConfiguration {  
    @Bean
    @ConditionalOnMissingBean(AuthTokenExchanger.class)
    AuthTokenExchanger authTokenExchanger() {
        throw new UnsupportedOperationException("You should implement AuthTokenExchanger bean");
    }

    @Bean
    @ConditionalOnMissingBean(TProtocolFactory.class)
    TProtocolFactory thriftProtocolFactory() {
        return new TBinaryProtocol.Factory();
    }

    @Bean
    public AuthenticationZuulFilter authenticationZuulFilter() {
        return new AuthenticationZuulFilter();
    }
}

Annotation ConditionalOnMissingBean prevents default bean creation if bean with conditional class is defined in you project. AuthTokenExchanger is needed for exchange external token to internal that we considered in previous article. By default for security reasons we can't implement any logic and raise exception. So, in project developer must implement own logic and it is its responsibility. Protocol translation is not supported yet, so only one protocol is needed to be registered as a thriftProtocolFactory bean. AuthenticationZuulFilter have been registered early.

filter internals

It's time to dive deeper to AuthenticationZuulFilter realization. First, request context should be got:

RequestContext ctx = RequestContext.getCurrentContext();  
HttpServletRequestWrapper request = (HttpServletRequestWrapper) ctx.getRequest();  

Next step is creating MessageTranslator:

MessageTransalator messageTransalator = new MessageTransalator(protocolFactory, authTokenExchanger);  

Positive scenario contains process request data, write it to requestEntity property of context and set new content length instead of origin:

byte[] processed = messageTransalator.process(request.getContentData());  
ctx.set("requestEntity", new ByteArrayInputStream(processed));  
ctx.setOriginContentLength(processed.length);  

If authentification or other thrift specific exception is raised we need process this exception with MessageTranslator and return it to client:

ctx.setSendZuulResponse(false);  
ctx.setResponseDataStream(new ByteArrayInputStream(new byte[]{}));

try {  
                ctx.getResponse().getOutputStream().write(messageTransalator.processError(e));
} catch (Exception e1) {
                log.error("unexpected error", e1);
                ctx.setResponseStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);

There some tricks with context properties are needed for preventing further service call processing. First, ctx.setSendZuulResponse(false) prevents GZIPping response. Thrift clients may fail from this type of package. And second, ctx.setResponseDataStream(new ByteArrayInputStream(new byte[]{})) is needed to pass should filter in zuul response filter.

If any not-thrift exception is raised then we need to do same things without writing response cause nothing to return.

examples

You can find examples in this repository on GitHub. In our example very simple logic is implemented:

@Bean
AuthTokenExchanger authTokenExchanger() {  
    return new AuthTokenExchanger<Token, TName>() {
        @Override
        public Token createEmptyAuthToken() {
            return new Token();
        }

        @Override
        public TName process(Token authToken) throws TException {
            if (authToken.getValue().equals("heisours")) {
                return new TName("John", "Smith");
            }

            throw new UnauthorizedException(ErrorCode.WRONG_LOGIN_OR_PASSWORD);
        }
    };
}

And we may test it in very native java way (thanks thrift):

@Test
public void testSimpleCall() throws Exception {  
    assertEquals("Hello John Smith", client.greet(new Token("heisours")));
}

@Test(expected = UnauthorizedException.class)
public void testUnauthorizedCall() throws Exception {  
    client.greet(new Token("heisnot"));
}

You can discovery and fork project on GitHub: https://github.com/aatarasoff/spring-thrift-api-gateway

comments powered by Disqus