Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Resource method blacklist #23

Open
wants to merge 10 commits into
base: revolver-callback
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

<groupId>io.revolver</groupId>
<artifactId>dropwizard-callback-resilience4j</artifactId>
<version>1.0.5</version>
<version>1.0.5-SNAPSHOT</version>
<packaging>jar</packaging>

<name>dropwizard-revolver</name>
Expand Down
52 changes: 26 additions & 26 deletions src/main/java/io/dropwizard/revolver/RevolverBundle.java
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,7 @@
import io.dropwizard.revolver.aeroapike.AerospikeConnectionManager;
import io.dropwizard.revolver.callback.InlineCallbackHandler;
import io.dropwizard.revolver.core.RevolverExecutionException;
import io.dropwizard.revolver.core.config.AerospikeMailBoxConfig;
import io.dropwizard.revolver.core.config.InMemoryMailBoxConfig;
import io.dropwizard.revolver.core.config.RevolverConfig;
import io.dropwizard.revolver.core.config.RevolverServiceConfig;
import io.dropwizard.revolver.core.config.ServiceDiscoveryConfig;
import io.dropwizard.revolver.core.config.*;
import io.dropwizard.revolver.core.config.hystrix.HystrixUtil;
import io.dropwizard.revolver.core.config.hystrix.ThreadPoolConfig;
import io.dropwizard.revolver.core.model.RevolverExecutorType;
Expand Down Expand Up @@ -66,33 +62,28 @@
import io.dropwizard.revolver.persistence.AeroSpikePersistenceProvider;
import io.dropwizard.revolver.persistence.InMemoryPersistenceProvider;
import io.dropwizard.revolver.persistence.PersistenceProvider;
import io.dropwizard.revolver.resource.RevolverApiManageResource;
import io.dropwizard.revolver.resource.RevolverConfigResource;
import io.dropwizard.revolver.resource.RevolverMailboxResource;
import io.dropwizard.revolver.resource.RevolverMailboxResourceV2;
import io.dropwizard.revolver.resource.RevolverMetadataResource;
import io.dropwizard.revolver.provider.BlacklistMethodData;
import io.dropwizard.revolver.provider.BlacklistProcessor;
import io.dropwizard.revolver.resource.*;
import io.dropwizard.revolver.splitting.PathExpressionSplitConfig;
import io.dropwizard.revolver.splitting.SplitConfig;
import io.dropwizard.riemann.RiemannBundle;
import io.dropwizard.riemann.RiemannConfig;
import io.dropwizard.setup.Bootstrap;
import io.dropwizard.setup.Environment;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.curator.framework.CuratorFramework;
import org.msgpack.jackson.dataformat.MessagePackFactory;

import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.MultivaluedMap;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.curator.framework.CuratorFramework;
import org.msgpack.jackson.dataformat.MessagePackFactory;

/**
* @author phaneesh
Expand Down Expand Up @@ -167,6 +158,8 @@ public void run(T configuration, Environment environment) {

public abstract ConfigSource getConfigSource();

public abstract Set<BlacklistMethodData> getBlacklistData();

public void onConfigChange(String configData) {
log.info("Config changed! Override to propagate config changes to other bundles");
}
Expand Down Expand Up @@ -295,7 +288,7 @@ private static void registerHttpsCommand(RevolverServiceConfig config) {
}

private static void registerCommand(RevolverServiceConfig config,
RevolverHttpServiceConfig revolverHttpServiceConfig) {
RevolverHttpServiceConfig revolverHttpServiceConfig) {

if (config instanceof RevolverHttpServiceConfig) {

Expand Down Expand Up @@ -424,9 +417,9 @@ private void initializeRevolver(T configuration, Environment environment) {
.resolverConfig(revolverConfig.getServiceResolverConfig())
.serviceDiscoveryConfig(serviceDiscoveryConfig).build()
: RevolverServiceResolver.builder()
.resolverConfig(revolverConfig.getServiceResolverConfig())
.objectMapper(environment.getObjectMapper()).
serviceDiscoveryConfig(serviceDiscoveryConfig).build();
.resolverConfig(revolverConfig.getServiceResolverConfig())
.objectMapper(environment.getObjectMapper()).
serviceDiscoveryConfig(serviceDiscoveryConfig).build();
} else {
serviceNameResolver = RevolverServiceResolver.builder()
.objectMapper(environment.getObjectMapper())
Expand Down Expand Up @@ -518,7 +511,7 @@ private void registerTypes(Bootstrap<?> bootstrap) {


private void registerResources(Environment environment, MetricRegistry metrics,
PersistenceProvider persistenceProvider, InlineCallbackHandler callbackHandler) {
PersistenceProvider persistenceProvider, InlineCallbackHandler callbackHandler) {
environment.jersey().register(new RevolverMetadataResource(revolverConfig));
environment.jersey().register(
new RevolverMailboxResource(persistenceProvider, environment.getObjectMapper(),
Expand All @@ -535,6 +528,13 @@ private void registerResources(Environment environment, MetricRegistry metrics,
}
environment.jersey().register(new RevolverConfigResource(dynamicConfigHandler));
environment.jersey().register(new RevolverApiManageResource());
environment.jersey().register(new RevolverCallbackResource(persistenceProvider, callbackHandler));
environment.jersey().register(
new RevolverRequestResource(environment.getObjectMapper(), MSG_PACK_OBJECT_MAPPER,
persistenceProvider, callbackHandler, metrics, revolverConfig));

// Register blacklist processor
environment.jersey().register(new BlacklistProcessor(getBlacklistData()));
}

private void registerFilters(Environment environment) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package io.dropwizard.revolver.provider;

import lombok.*;

@Getter
@Builder
@ToString
@AllArgsConstructor
@EqualsAndHashCode
public class BlacklistMethodData {
private final String httpMethod;
private final String relativePath; // path of the method excluding parent resource path
private final String resourceClassName;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
package io.dropwizard.revolver.provider;

import lombok.extern.slf4j.Slf4j;
import org.glassfish.jersey.server.model.ModelProcessor;
import org.glassfish.jersey.server.model.Resource;
import org.glassfish.jersey.server.model.Resource.Builder;
import org.glassfish.jersey.server.model.ResourceMethod;
import org.glassfish.jersey.server.model.ResourceModel;

import javax.ws.rs.core.Configuration;
import javax.ws.rs.ext.Provider;
import java.util.List;
import java.util.Set;

@Provider
@Slf4j
public class BlacklistProcessor implements ModelProcessor {

private final Set<BlacklistMethodData> blacklistMethods;

public BlacklistProcessor(final Set<BlacklistMethodData> blacklistMethods) {
this.blacklistMethods = blacklistMethods;
}

@Override
public ResourceModel processResourceModel(final ResourceModel resourceModel, final Configuration configuration) {
if (blacklistMethods == null || blacklistMethods.isEmpty()) {
log.info("No API end-point to blacklist");
return resourceModel;
}

ResourceModel.Builder newResourceModelBuilder = new ResourceModel.Builder(false);
for (final Resource resource : resourceModel.getResources()) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

refactor to reduce cyclomatic complexity for the nested for and if branches. probably use java 8 streams and collectors with filters

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Streams would be difficult to use here.

final Resource.Builder resourceBuilder;

final List<Resource> childResources = resource.getChildResources();

resourceBuilder = childResources.isEmpty()
? Resource.builder(resource)
: Resource.builder(resource.getPath());

// Add child resources with non-blacklisted child resource methods only
childResources.forEach(childResource -> {
final Builder childResourceBuilder = Resource.builder(childResource.getPath());
childResource.getResourceMethods().stream()
.filter(this::shouldAddMethod)
.forEach(childResourceBuilder::addMethod);
resourceBuilder.addChildResource(childResourceBuilder.build());
});

newResourceModelBuilder.addResource(resourceBuilder.build());
}

return newResourceModelBuilder.build();
}

@Override
public ResourceModel processSubResource(final ResourceModel subResourceModel, final Configuration configuration) {
return subResourceModel;
}

private boolean shouldAddMethod(final ResourceMethod method) {

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

probably use as a predicate for filter to check if resource method is blacklisted

// This is slightly sub-optimal,
// but given that blacklist count will be small, not creating a complex Map to match Jersey resource structure
return blacklistMethods.stream()
.noneMatch(blacklistData -> {
if (method.getInvocable().getHandler().getHandlerClass().getName().equals(blacklistData.getResourceClassName()) &&
method.getHttpMethod().equalsIgnoreCase(blacklistData.getHttpMethod()) &&
method.getParent().getPath().equals(blacklistData.getRelativePath())) {
log.info("Blacklisting method with path: {}, http method: {}, resource: {}",
blacklistData.getRelativePath(),
blacklistData.getHttpMethod(),
blacklistData.getResourceClassName());
return true;
}
return false;
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
/*
* Copyright 2016 Phaneesh Nagaraja <[email protected]>.
*
* 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
*
* http://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.dropwizard.revolver.resource;

import com.codahale.metrics.annotation.Metered;
import com.google.common.base.Strings;
import io.dropwizard.msgpack.MsgPackMediaType;
import io.dropwizard.revolver.base.core.RevolverCallbackResponse;
import io.dropwizard.revolver.callback.InlineCallbackHandler;
import io.dropwizard.revolver.http.RevolverHttpCommand;
import io.dropwizard.revolver.persistence.PersistenceProvider;
import io.dropwizard.revolver.util.HeaderUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import javax.inject.Singleton;
import javax.ws.rs.Consumes;
import javax.ws.rs.HeaderParam;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import lombok.extern.slf4j.Slf4j;
import lombok.val;

/**
* @author phaneesh
*/
@Path("/revolver")
@Slf4j
@Singleton
@Api(value = "RequestCallback", description = "Revolver gateway api for callbacks on mailbox requests")
public class RevolverCallbackResource {

private static final String RESPONSE_CODE_HEADER = "X-RESPONSE-CODE";

private final PersistenceProvider persistenceProvider;

private final InlineCallbackHandler callbackHandler;

public RevolverCallbackResource(PersistenceProvider persistenceProvider,
InlineCallbackHandler callbackHandler) {
this.persistenceProvider = persistenceProvider;
this.callbackHandler = callbackHandler;
}

@Path("/v1/callback/{requestId}")
@POST
@Metered
@ApiOperation(value = "Callback for updating responses for a given mailbox request")
@Produces({MediaType.APPLICATION_JSON, MsgPackMediaType.APPLICATION_MSGPACK,
MediaType.APPLICATION_XML})
@Consumes({MediaType.APPLICATION_JSON, MsgPackMediaType.APPLICATION_MSGPACK,
MediaType.APPLICATION_XML})
public Response handleCallback(@PathParam("requestId") String requestId,
@HeaderParam(RESPONSE_CODE_HEADER) String responseCode,
@Context HttpHeaders headers, byte[] responseBody) {
long start = System.currentTimeMillis();
try {
val callbackRequest = persistenceProvider.request(requestId);
log.debug("Callback request in handleCallback : " + callbackRequest);
if (callbackRequest == null) {
return Response.status(Response.Status.BAD_REQUEST).build();
}
val response = RevolverCallbackResponse.builder().body(responseBody)
.headers(headers.getRequestHeaders()).statusCode(
responseCode != null ? Integer.parseInt(responseCode)
: Response.Status.OK.getStatusCode()).build();
val mailboxTtl = HeaderUtil.getTTL(callbackRequest);
persistenceProvider.saveResponse(requestId, response, mailboxTtl);
if (callbackRequest.getMode() != null && (
callbackRequest.getMode().equals(RevolverHttpCommand.CALL_MODE_CALLBACK)
|| callbackRequest.getMode()
.equals(RevolverHttpCommand.CALL_MODE_CALLBACK_SYNC)) && !Strings
.isNullOrEmpty(callbackRequest.getCallbackUri())) {
callbackHandler.handle(requestId, response);
}
log.info(
"Callback processing for request id: {} with response size: {} bytes completed in {} ms",
requestId, responseBody.length, (System.currentTimeMillis() - start));
return Response.accepted().build();
} catch (Exception e) {
log.error("Callback error", e);
return Response.serverError().build();
}
}
}
Loading