Search in sources :

Example 6 with AsyncResponse

use of org.apache.servicecomb.swagger.invocation.AsyncResponse in project incubator-servicecomb-java-chassis by apache.

the class TestAbstractRestInvocation method doInvoke.

@Test
public void doInvoke(@Mocked Endpoint endpoint, @Mocked OperationMeta operationMeta, @Mocked Object[] swaggerArguments, @Mocked SchemaMeta schemaMeta) throws Throwable {
    Response response = Response.ok("ok");
    Handler handler = new Handler() {

        @Override
        public void handle(Invocation invocation, AsyncResponse asyncResp) {
            asyncResp.complete(response);
        }
    };
    List<Handler> handlerChain = Arrays.asList(handler);
    Deencapsulation.setField(invocation, "handlerList", handlerChain);
    Holder<Response> result = new Holder<>();
    restInvocation = new AbstractRestInvocationForTest() {

        @Override
        protected void sendResponseQuietly(Response response) {
            result.value = response;
        }
    };
    restInvocation.invocation = invocation;
    restInvocation.doInvoke();
    Assert.assertSame(response, result.value);
}
Also used : AsyncResponse(org.apache.servicecomb.swagger.invocation.AsyncResponse) Response(org.apache.servicecomb.swagger.invocation.Response) Invocation(org.apache.servicecomb.core.Invocation) Holder(javax.xml.ws.Holder) Handler(org.apache.servicecomb.core.Handler) AsyncResponse(org.apache.servicecomb.swagger.invocation.AsyncResponse) Test(org.junit.Test)

Example 7 with AsyncResponse

use of org.apache.servicecomb.swagger.invocation.AsyncResponse in project incubator-servicecomb-java-chassis by apache.

the class TestLoadbalanceHandler method send_success.

@Test
public void send_success() {
    CacheEndpoint cacheEndpoint = new CacheEndpoint("rest://localhost:8080", null);
    CseServer server = new CseServer(restTransport, cacheEndpoint);
    new MockUp<System>() {

        @Mock
        long currentTimeMillis() {
            return 123;
        }
    };
    new Expectations(loadBalancer) {

        {
            loadBalancer.chooseServer(invocation);
            result = server;
        }
    };
    server.incrementContinuousFailureCount();
    sendResponse = Response.ok("success");
    Holder<String> result = new Holder<>();
    Deencapsulation.invoke(handler, "send", invocation, (AsyncResponse) resp -> {
        result.value = resp.getResult();
    }, loadBalancer);
    Assert.assertEquals(123, server.getLastVisitTime());
    Assert.assertEquals(1, loadBalancer.getLoadBalancerStats().getSingleServerStat(server).getActiveRequestsCount());
    Assert.assertEquals("success", result.value);
    Assert.assertEquals(0, server.getCountinuousFailureCount());
}
Also used : Expectations(mockit.Expectations) BeforeClass(org.junit.BeforeClass) Transport(org.apache.servicecomb.core.Transport) RegistryUtils(org.apache.servicecomb.serviceregistry.RegistryUtils) Expectations(mockit.Expectations) ArchaiusUtils(org.apache.servicecomb.foundation.test.scaffolding.config.ArchaiusUtils) HashMap(java.util.HashMap) AsyncResponse(org.apache.servicecomb.swagger.invocation.AsyncResponse) SimpleTransactionControlFilter(org.apache.servicecomb.loadbalance.filter.SimpleTransactionControlFilter) ArrayList(java.util.ArrayList) AbstractConfiguration(org.apache.commons.configuration.AbstractConfiguration) Map(java.util.Map) After(org.junit.After) Mock(mockit.Mock) Status(javax.ws.rs.core.Response.Status) InstanceCacheManager(org.apache.servicecomb.serviceregistry.cache.InstanceCacheManager) Response(org.apache.servicecomb.swagger.invocation.Response) ExpectedException(org.junit.rules.ExpectedException) Before(org.junit.Before) AfterClass(org.junit.AfterClass) MockUp(mockit.MockUp) Server(com.netflix.loadbalancer.Server) VersionedCache(org.apache.servicecomb.foundation.common.cache.VersionedCache) ConfigUtil(org.apache.servicecomb.config.ConfigUtil) Matchers(org.hamcrest.Matchers) Test(org.junit.Test) Deencapsulation(mockit.Deencapsulation) DynamicPropertyFactory(com.netflix.config.DynamicPropertyFactory) Invocation(org.apache.servicecomb.core.Invocation) CacheEndpoint(org.apache.servicecomb.serviceregistry.cache.CacheEndpoint) Mockito(org.mockito.Mockito) List(java.util.List) MicroserviceInstance(org.apache.servicecomb.serviceregistry.api.registry.MicroserviceInstance) Rule(org.junit.Rule) ServiceRegistry(org.apache.servicecomb.serviceregistry.ServiceRegistry) IRule(com.netflix.loadbalancer.IRule) Holder(javax.xml.ws.Holder) TransportManager(org.apache.servicecomb.core.transport.TransportManager) Injectable(mockit.Injectable) CseContext(org.apache.servicecomb.core.CseContext) Assert(org.junit.Assert) Mocked(mockit.Mocked) CacheEndpoint(org.apache.servicecomb.serviceregistry.cache.CacheEndpoint) Holder(javax.xml.ws.Holder) MockUp(mockit.MockUp) Test(org.junit.Test)

Example 8 with AsyncResponse

use of org.apache.servicecomb.swagger.invocation.AsyncResponse in project incubator-servicecomb-java-chassis by apache.

the class TestLoadbalanceHandler method send_failed.

@Test
public void send_failed() {
    CacheEndpoint cacheEndpoint = new CacheEndpoint("rest://localhost:8080", null);
    CseServer server = new CseServer(restTransport, cacheEndpoint);
    new MockUp<System>() {

        @Mock
        long currentTimeMillis() {
            return 123;
        }
    };
    new Expectations(loadBalancer) {

        {
            loadBalancer.chooseServer(invocation);
            result = server;
        }
    };
    int continuousFailureCount = server.getCountinuousFailureCount();
    sendResponse = Response.create(Status.BAD_REQUEST, "send failed");
    Holder<Throwable> result = new Holder<>();
    Deencapsulation.invoke(handler, "send", invocation, (AsyncResponse) resp -> {
        result.value = (Throwable) resp.getResult();
    }, loadBalancer);
    Assert.assertEquals(123, server.getLastVisitTime());
    Assert.assertEquals(1, loadBalancer.getLoadBalancerStats().getSingleServerStat(server).getSuccessiveConnectionFailureCount());
    Assert.assertEquals("InvocationException: code=400;msg=send failed", result.value.getMessage());
    Assert.assertEquals(continuousFailureCount + 1, server.getCountinuousFailureCount());
}
Also used : Expectations(mockit.Expectations) BeforeClass(org.junit.BeforeClass) Transport(org.apache.servicecomb.core.Transport) RegistryUtils(org.apache.servicecomb.serviceregistry.RegistryUtils) Expectations(mockit.Expectations) ArchaiusUtils(org.apache.servicecomb.foundation.test.scaffolding.config.ArchaiusUtils) HashMap(java.util.HashMap) AsyncResponse(org.apache.servicecomb.swagger.invocation.AsyncResponse) SimpleTransactionControlFilter(org.apache.servicecomb.loadbalance.filter.SimpleTransactionControlFilter) ArrayList(java.util.ArrayList) AbstractConfiguration(org.apache.commons.configuration.AbstractConfiguration) Map(java.util.Map) After(org.junit.After) Mock(mockit.Mock) Status(javax.ws.rs.core.Response.Status) InstanceCacheManager(org.apache.servicecomb.serviceregistry.cache.InstanceCacheManager) Response(org.apache.servicecomb.swagger.invocation.Response) ExpectedException(org.junit.rules.ExpectedException) Before(org.junit.Before) AfterClass(org.junit.AfterClass) MockUp(mockit.MockUp) Server(com.netflix.loadbalancer.Server) VersionedCache(org.apache.servicecomb.foundation.common.cache.VersionedCache) ConfigUtil(org.apache.servicecomb.config.ConfigUtil) Matchers(org.hamcrest.Matchers) Test(org.junit.Test) Deencapsulation(mockit.Deencapsulation) DynamicPropertyFactory(com.netflix.config.DynamicPropertyFactory) Invocation(org.apache.servicecomb.core.Invocation) CacheEndpoint(org.apache.servicecomb.serviceregistry.cache.CacheEndpoint) Mockito(org.mockito.Mockito) List(java.util.List) MicroserviceInstance(org.apache.servicecomb.serviceregistry.api.registry.MicroserviceInstance) Rule(org.junit.Rule) ServiceRegistry(org.apache.servicecomb.serviceregistry.ServiceRegistry) IRule(com.netflix.loadbalancer.IRule) Holder(javax.xml.ws.Holder) TransportManager(org.apache.servicecomb.core.transport.TransportManager) Injectable(mockit.Injectable) CseContext(org.apache.servicecomb.core.CseContext) Assert(org.junit.Assert) Mocked(mockit.Mocked) CacheEndpoint(org.apache.servicecomb.serviceregistry.cache.CacheEndpoint) Holder(javax.xml.ws.Holder) MockUp(mockit.MockUp) CacheEndpoint(org.apache.servicecomb.serviceregistry.cache.CacheEndpoint) Test(org.junit.Test)

Example 9 with AsyncResponse

use of org.apache.servicecomb.swagger.invocation.AsyncResponse in project incubator-servicecomb-java-chassis by apache.

the class LoadbalanceHandler method sendWithRetry.

private void sendWithRetry(Invocation invocation, AsyncResponse asyncResp, final LoadBalancer chosenLB) throws Exception {
    long time = System.currentTimeMillis();
    // retry in loadbalance, 2.0 feature
    final int currentHandler = invocation.getHandlerIndex();
    final SyncResponseExecutor orginExecutor;
    final Executor newExecutor;
    if (invocation.getResponseExecutor() instanceof SyncResponseExecutor) {
        orginExecutor = (SyncResponseExecutor) invocation.getResponseExecutor();
        newExecutor = new Executor() {

            @Override
            public void execute(Runnable command) {
                // retry的场景,对于同步调用, 同步调用的主线程已经被挂起,无法再主线程中进行重试;
                // 重试也不能在网络线程(event-loop)中进行,未被保护的阻塞操作会导致网络线程挂起
                RETRY_POOL.submit(command);
            }
        };
        invocation.setResponseExecutor(newExecutor);
    } else {
        orginExecutor = null;
        newExecutor = null;
    }
    ExecutionListener<Invocation, Response> listener = new ExecutionListener<Invocation, Response>() {

        @Override
        public void onExecutionStart(ExecutionContext<Invocation> context) throws AbortExecutionException {
        }

        @Override
        public void onStartWithServer(ExecutionContext<Invocation> context, ExecutionInfo info) throws AbortExecutionException {
        }

        @Override
        public void onExceptionWithServer(ExecutionContext<Invocation> context, Throwable exception, ExecutionInfo info) {
            LOGGER.error("onExceptionWithServer msg {}; server {}", exception.getMessage(), context.getRequest().getEndpoint());
        }

        @Override
        public void onExecutionSuccess(ExecutionContext<Invocation> context, Response response, ExecutionInfo info) {
            if (orginExecutor != null) {
                orginExecutor.execute(() -> {
                    asyncResp.complete(response);
                });
            } else {
                asyncResp.complete(response);
            }
        }

        @Override
        public void onExecutionFailed(ExecutionContext<Invocation> context, Throwable finalException, ExecutionInfo info) {
            if (orginExecutor != null) {
                orginExecutor.execute(() -> {
                    asyncResp.consumerFail(finalException);
                });
            } else {
                asyncResp.consumerFail(finalException);
            }
        }
    };
    List<ExecutionListener<Invocation, Response>> listeners = new ArrayList<>(0);
    listeners.add(listener);
    ExecutionContext<Invocation> context = new ExecutionContext<>(invocation, null, null, null);
    LoadBalancerCommand<Response> command = LoadBalancerCommand.<Response>builder().withLoadBalancer(chosenLB).withServerLocator(invocation).withRetryHandler(ExtensionsManager.createRetryHandler(invocation.getMicroserviceName())).withListeners(listeners).withExecutionContext(context).build();
    Observable<Response> observable = command.submit(new ServerOperation<Response>() {

        public Observable<Response> call(Server s) {
            return Observable.create(f -> {
                try {
                    ((CseServer) s).setLastVisitTime(time);
                    chosenLB.getLoadBalancerStats().incrementNumRequests(s);
                    // for retry
                    invocation.setHandlerIndex(currentHandler);
                    invocation.setEndpoint(((CseServer) s).getEndpoint());
                    invocation.next(resp -> {
                        if (resp.isFailed()) {
                            LOGGER.error("service call error, msg is {}, server is {} ", ((Throwable) resp.getResult()).getMessage(), s);
                            chosenLB.getLoadBalancerStats().incrementSuccessiveConnectionFailureCount(s);
                            ((CseServer) s).incrementContinuousFailureCount();
                            f.onError(resp.getResult());
                        } else {
                            chosenLB.getLoadBalancerStats().incrementActiveRequestsCount(s);
                            ((CseServer) s).clearContinuousFailure();
                            chosenLB.getLoadBalancerStats().noteResponseTime(s, (System.currentTimeMillis() - time));
                            f.onNext(resp);
                            f.onCompleted();
                        }
                    });
                } catch (Exception e) {
                    LOGGER.error("execution error, msg is " + e.getMessage());
                    f.onError(e);
                }
            });
        }
    });
    observable.subscribe(response -> {
    }, error -> {
    }, () -> {
    });
}
Also used : LoggerFactory(org.slf4j.LoggerFactory) DiscoveryTree(org.apache.servicecomb.serviceregistry.discovery.DiscoveryTree) AsyncResponse(org.apache.servicecomb.swagger.invocation.AsyncResponse) StringUtils(org.apache.commons.lang3.StringUtils) ArrayList(java.util.ArrayList) Observable(rx.Observable) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) TransactionControlFilter(org.apache.servicecomb.loadbalance.filter.TransactionControlFilter) CseServerDiscoveryFilter(org.apache.servicecomb.loadbalance.filter.CseServerDiscoveryFilter) Map(java.util.Map) LoadBalancerCommand(com.netflix.loadbalancer.reactive.LoadBalancerCommand) ConcurrentHashMapEx(org.apache.servicecomb.foundation.common.concurrent.ConcurrentHashMapEx) ThreadFactory(java.util.concurrent.ThreadFactory) Response(org.apache.servicecomb.swagger.invocation.Response) ExecutorService(java.util.concurrent.ExecutorService) DiscoveryFilter(org.apache.servicecomb.serviceregistry.discovery.DiscoveryFilter) SyncResponseExecutor(org.apache.servicecomb.core.provider.consumer.SyncResponseExecutor) Logger(org.slf4j.Logger) ExecutionListener(com.netflix.loadbalancer.reactive.ExecutionListener) Executor(java.util.concurrent.Executor) Handler(org.apache.servicecomb.core.Handler) ExceptionUtils(org.apache.servicecomb.core.exception.ExceptionUtils) Server(com.netflix.loadbalancer.Server) VersionedCache(org.apache.servicecomb.foundation.common.cache.VersionedCache) Executors(java.util.concurrent.Executors) Invocation(org.apache.servicecomb.core.Invocation) ExecutionContext(com.netflix.loadbalancer.reactive.ExecutionContext) List(java.util.List) IsolationServerListFilter(org.apache.servicecomb.loadbalance.filter.IsolationServerListFilter) DiscoveryContext(org.apache.servicecomb.serviceregistry.discovery.DiscoveryContext) IRule(com.netflix.loadbalancer.IRule) ExecutionInfo(com.netflix.loadbalancer.reactive.ExecutionInfo) ServerOperation(com.netflix.loadbalancer.reactive.ServerOperation) Invocation(org.apache.servicecomb.core.Invocation) Server(com.netflix.loadbalancer.Server) SyncResponseExecutor(org.apache.servicecomb.core.provider.consumer.SyncResponseExecutor) ArrayList(java.util.ArrayList) ExecutionInfo(com.netflix.loadbalancer.reactive.ExecutionInfo) Observable(rx.Observable) ExecutionListener(com.netflix.loadbalancer.reactive.ExecutionListener) AsyncResponse(org.apache.servicecomb.swagger.invocation.AsyncResponse) Response(org.apache.servicecomb.swagger.invocation.Response) SyncResponseExecutor(org.apache.servicecomb.core.provider.consumer.SyncResponseExecutor) Executor(java.util.concurrent.Executor) ExecutionContext(com.netflix.loadbalancer.reactive.ExecutionContext)

Example 10 with AsyncResponse

use of org.apache.servicecomb.swagger.invocation.AsyncResponse in project incubator-servicecomb-java-chassis by apache.

the class TestVertxHttpMethod method testDoMethodNullPointerException.

@Test
public void testDoMethodNullPointerException(@Mocked HttpClient httpClient) throws Exception {
    Context context = new MockUp<Context>() {

        @Mock
        public void runOnContext(Handler<Void> action) {
            action.handle(null);
        }
    }.getMockInstance();
    HttpClientWithContext httpClientWithContext = new HttpClientWithContext(httpClient, context);
    Invocation invocation = mock(Invocation.class);
    AsyncResponse asyncResp = mock(AsyncResponse.class);
    try {
        this.doMethod(httpClientWithContext, invocation, asyncResp);
        fail("Expect to throw NullPointerException, but got none");
    } catch (NullPointerException e) {
    }
}
Also used : Context(io.vertx.core.Context) HttpClientWithContext(org.apache.servicecomb.foundation.vertx.client.http.HttpClientWithContext) Invocation(org.apache.servicecomb.core.Invocation) HttpClientWithContext(org.apache.servicecomb.foundation.vertx.client.http.HttpClientWithContext) AsyncResponse(org.apache.servicecomb.swagger.invocation.AsyncResponse) Mock(mockit.Mock) Test(org.junit.Test)

Aggregations

AsyncResponse (org.apache.servicecomb.swagger.invocation.AsyncResponse)17 Test (org.junit.Test)14 Invocation (org.apache.servicecomb.core.Invocation)13 Response (org.apache.servicecomb.swagger.invocation.Response)8 MockUp (mockit.MockUp)6 ArrayList (java.util.ArrayList)5 Mock (mockit.Mock)5 OperationMeta (org.apache.servicecomb.core.definition.OperationMeta)5 Holder (javax.xml.ws.Holder)4 IRule (com.netflix.loadbalancer.IRule)3 Server (com.netflix.loadbalancer.Server)3 HashMap (java.util.HashMap)3 List (java.util.List)3 Map (java.util.Map)3 Expectations (mockit.Expectations)3 RestOperationMeta (org.apache.servicecomb.common.rest.definition.RestOperationMeta)3 Endpoint (org.apache.servicecomb.core.Endpoint)3 VersionedCache (org.apache.servicecomb.foundation.common.cache.VersionedCache)3 CacheEndpoint (org.apache.servicecomb.serviceregistry.cache.CacheEndpoint)3 DynamicPropertyFactory (com.netflix.config.DynamicPropertyFactory)2