org.apache.servicecomb.swagger.invocation.AsyncResponse Java Examples

The following examples show how to use org.apache.servicecomb.swagger.invocation.AsyncResponse. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PackProviderHandler.java    From servicecomb-pack with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(Invocation invocation, AsyncResponse asyncResponse) throws Exception {
  if (omegaContext != null) {
    String globalTxId = invocation.getContext().get(GLOBAL_TX_ID_KEY);
    if (globalTxId == null) {
      LOG.debug("Cannot inject transaction ID, no such header: {}", GLOBAL_TX_ID_KEY);
    } else {
      omegaContext.setGlobalTxId(globalTxId);
      omegaContext.setLocalTxId(invocation.getContext().get(LOCAL_TX_ID_KEY));
    }
  } else {
    LOG.debug("Cannot inject transaction ID, as the OmegaContext is null.");
  }
  try {
    invocation.next(asyncResponse);
  } finally {
    // Clean up the OmegaContext
    if(omegaContext != null) {
      omegaContext.clear();
    }
  }
}
 
Example #2
Source File: DelayFault.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Override
public void injectFault(Invocation invocation, FaultParam faultParam, AsyncResponse asynResponse) {
  if (!shouldDelay(invocation, faultParam, asynResponse)) {
    asynResponse.success(SUCCESS_RESPONSE);
    return;
  }

  LOGGER.debug("Fault injection: delay is added for the request by fault inject handler");
  long delay = FaultInjectionUtil.getFaultInjectionConfig(invocation,
      "delay.fixedDelay");
  if (delay == FaultInjectionConst.FAULT_INJECTION_DEFAULT_VALUE) {
    LOGGER.debug("Fault injection: delay is not configured");
    asynResponse.success(SUCCESS_RESPONSE);
    return;
  }

  executeDelay(faultParam, asynResponse, delay);
}
 
Example #3
Source File: FaultExecutor.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
private void next(AsyncResponse asyncResponse) {
  if (handlerIndex >= faultInjectList.size()) {
    asyncResponse.complete(Response.succResp("success"));
    return;
  }

  int runIndex = handlerIndex;
  handlerIndex++;
  faultInjectList.get(runIndex).injectFault(invocation, param, response -> {
    if (response.isFailed()) {
      asyncResponse.complete(response);
    } else {
      FaultExecutor.this.next(asyncResponse);
    }
  });
}
 
Example #4
Source File: TestVertxRestTransport.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendException() {
  boolean validAssert;
  Invocation invocation = Mockito.mock(Invocation.class);
  AsyncResponse asyncResp = Mockito.mock(AsyncResponse.class);
  URIEndpointObject endpoint = Mockito.mock(URIEndpointObject.class);
  Endpoint end = Mockito.mock(Endpoint.class);
  Mockito.when(invocation.getEndpoint()).thenReturn(end);
  Mockito.when(invocation.getEndpoint().getAddress()).thenReturn(endpoint);
  try {
    validAssert = true;
    instance.send(invocation, asyncResp);
  } catch (Exception e) {

    validAssert = false;
  }
  Assert.assertFalse(validAssert);
}
 
Example #5
Source File: AbortFault.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Override
public void injectFault(Invocation invocation, FaultParam faultParam, AsyncResponse asyncResponse) {
  if (!shouldAbort(invocation, faultParam)) {
    asyncResponse.success(SUCCESS_RESPONSE);
    return;
  }

  // get the config values related to abort percentage.
  int errorCode = FaultInjectionUtil.getFaultInjectionConfig(invocation, "abort.httpStatus");
  if (errorCode == FaultInjectionConst.FAULT_INJECTION_DEFAULT_VALUE) {
    LOGGER.debug("Fault injection: Abort error code is not configured");
    asyncResponse.success(SUCCESS_RESPONSE);
    return;
  }

  // if request need to be abort then return failure with given error code
  CommonExceptionData errorData = new CommonExceptionData(ABORTED_ERROR_MSG);
  asyncResponse.consumerFail(new InvocationException(errorCode, ABORTED_ERROR_MSG, errorData));
}
 
Example #6
Source File: ProviderQpsFlowControlHandler.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(Invocation invocation, AsyncResponse asyncResp) throws Exception {
  if (invocation.getHandlerIndex() > 0) {
    // handlerIndex > 0, which means this handler is executed in handler chain.
    // As this flow control logic has been executed in advance, this time it should be ignored.
    invocation.next(asyncResp);
    return;
  }

  // The real executing position of this handler is no longer in handler chain, but in AbstractRestInvocation.
  // Therefore, the Invocation#next() method should not be called below.
  if (!Config.INSTANCE.isProviderEnabled()) {
    return;
  }

  String microserviceName = invocation.getContext(Const.SRC_MICROSERVICE);
  QpsController qpsController =
      StringUtils.isEmpty(microserviceName)
          ? qpsControllerMgr.getGlobalQpsController()
          : qpsControllerMgr.getOrCreate(microserviceName, invocation);
  isLimitNewRequest(qpsController, asyncResp);
}
 
Example #7
Source File: ConsumerQpsFlowControlHandler.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(Invocation invocation, AsyncResponse asyncResp) throws Exception {
  if (!Config.INSTANCE.isConsumerEnabled()) {
    invocation.next(asyncResp);
    return;
  }

  QpsController qpsController = qpsControllerMgr.getOrCreate(invocation.getMicroserviceName(), invocation);
  if (qpsController.isLimitNewRequest()) {
    // return http status 429
    CommonExceptionData errorData = new CommonExceptionData("rejected by qps flowcontrol");
    asyncResp.consumerFail(
        new InvocationException(QpsConst.TOO_MANY_REQUESTS_STATUS, errorData));
    return;
  }

  invocation.next(asyncResp);
}
 
Example #8
Source File: ZipkinTracingHandler.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings({"try", "unused"})
@Override
public void handle(Invocation invocation, AsyncResponse asyncResp) throws Exception {
  Span span = tracingDelegate.createSpan(invocation);
  try (SpanInScope scope = tracer.tracer().withSpanInScope(span)) {
    LOGGER.debug("{}: Generated tracing span for {}",
        tracingDelegate.name(),
        invocation.getOperationName());

    invocation.next(onResponse(invocation, asyncResp, span));
  } catch (Exception e) {
    LOGGER.debug("{}: Failed invocation on {}",
        tracingDelegate.name(),
        invocation.getOperationName(),
        e);

    tracingDelegate.onResponse(span, null, e);
    throw e;
  }
}
 
Example #9
Source File: AuthHandler.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
protected void doHandle(Invocation invocation, AsyncResponse asyncResp, Boolean authSucc, Throwable authException) {
  if (authException != null) {
    asyncResp.consumerFail(new InvocationException(Status.UNAUTHORIZED, (Object) authException.getMessage()));
    return;
  }

  if (!authSucc) {
    asyncResp.consumerFail(new InvocationException(Status.UNAUTHORIZED, (Object) "auth failed"));
  }

  LOGGER.debug("auth success.");
  try {
    invocation.next(asyncResp);
  } catch (Throwable e) {
    asyncResp.consumerFail(e);
  }
}
 
Example #10
Source File: LoadbalanceHandler.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
private void send(Invocation invocation, AsyncResponse asyncResp, LoadBalancer chosenLB) throws Exception {
  long time = System.currentTimeMillis();
  ServiceCombServer server = chosenLB.chooseServer(invocation);
  if (null == server) {
    asyncResp.consumerFail(new InvocationException(Status.INTERNAL_SERVER_ERROR, "No available address found."));
    return;
  }
  chosenLB.getLoadBalancerStats().incrementNumRequests(server);
  invocation.setEndpoint(server.getEndpoint());
  invocation.next(resp -> {
    // this stats is for WeightedResponseTimeRule
    chosenLB.getLoadBalancerStats().noteResponseTime(server, (System.currentTimeMillis() - time));
    if (isFailedResponse(resp)) {
      chosenLB.getLoadBalancerStats().incrementSuccessiveConnectionFailureCount(server);
      ServiceCombLoadBalancerStats.INSTANCE.markFailure(server);
    } else {
      chosenLB.getLoadBalancerStats().incrementActiveRequestsCount(server);
      ServiceCombLoadBalancerStats.INSTANCE.markSuccess(server);
    }
    asyncResp.handle(resp);
  });
}
 
Example #11
Source File: LoadbalanceHandler.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
private boolean defineEndpointAndHandle(Invocation invocation, AsyncResponse asyncResp) throws Exception {
  Object endpoint = invocation.getLocalContext(SERVICECOMB_SERVER_ENDPOINT);
  if (endpoint == null) {
    return false;
  }
  if (endpoint instanceof String) {
    // compatible to old usage
    endpoint = parseEndpoint((String) endpoint);
  }

  invocation.setEndpoint((Endpoint) endpoint);
  invocation.next(resp -> {
    asyncResp.handle(resp);
  });
  return true;
}
 
Example #12
Source File: SagaProviderHandler.java    From txle with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(Invocation invocation, AsyncResponse asyncResponse) throws Exception {
  if (omegaContext != null) {
    String globalTxId = invocation.getContext().get(GLOBAL_TX_ID_KEY);
    if (globalTxId == null) {
      LOG.debug("no such header: {}", GLOBAL_TX_ID_KEY);
    } else {

      omegaContext.setGlobalTxId(globalTxId);
      omegaContext.setLocalTxId(invocation.getContext().get(LOCAL_TX_ID_KEY));
    }
  } else {
    LOG.info("Cannot inject transaction ID, as the OmegaContext is null or cannot get the globalTxId.");
  }

  invocation.next(asyncResponse);
}
 
Example #13
Source File: SagaConsumerHandler.java    From txle with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(Invocation invocation, AsyncResponse asyncResponse) throws Exception {
  if (omegaContext != null && omegaContext.globalTxId() != null) {
    invocation.getContext().put(GLOBAL_TX_ID_KEY, omegaContext.globalTxId());
    invocation.getContext().put(LOCAL_TX_ID_KEY, omegaContext.localTxId());

    LOG.debug("Added {} {} and {} {} to request header",
        GLOBAL_TX_ID_KEY,
        omegaContext.globalTxId(),
        LOCAL_TX_ID_KEY,
        omegaContext.localTxId());
  } else {
    LOG.info("Cannot inject transaction ID, as the OmegaContext is null or cannot get the globalTxId.");
  }

  invocation.next(asyncResponse);
}
 
Example #14
Source File: AuthHandler.java    From servicecomb-java-chassis with Apache License 2.0 6 votes vote down vote up
protected void doHandle(Invocation invocation, AsyncResponse asyncResp, Boolean authSucc, Throwable authException) {
  if (authException != null) {
    asyncResp.consumerFail(new InvocationException(Status.UNAUTHORIZED, (Object) authException.getMessage()));
    return;
  }

  if (!authSucc) {
    asyncResp.consumerFail(new InvocationException(Status.UNAUTHORIZED, (Object) "auth failed"));
  }

  LOGGER.debug("auth success.");
  try {
    invocation.next(asyncResp);
  } catch (Throwable e) {
    asyncResp.consumerFail(e);
  }
}
 
Example #15
Source File: PackConsumerHandler.java    From servicecomb-pack with Apache License 2.0 6 votes vote down vote up
@Override
public void handle(Invocation invocation, AsyncResponse asyncResponse) throws Exception {
  if (omegaContext != null && omegaContext.globalTxId() != null) {
    invocation.getContext().put(GLOBAL_TX_ID_KEY, omegaContext.globalTxId());
    invocation.getContext().put(LOCAL_TX_ID_KEY, omegaContext.localTxId());

    LOG.debug("Added {} {} and {} {} to request header",
        GLOBAL_TX_ID_KEY,
        omegaContext.globalTxId(),
        LOCAL_TX_ID_KEY,
        omegaContext.localTxId());
  } else {
    LOG.debug("Cannot inject transaction ID, as the OmegaContext is null or cannot get the globalTxId.");
  }

  invocation.next(asyncResponse);
}
 
Example #16
Source File: LoadbalanceHandler.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Invocation invocation, AsyncResponse asyncResp) throws Exception {
  AsyncResponse response = asyncResp;
  asyncResp = async -> {
    if (Boolean.TRUE.equals(invocation.getLocalContext(IsolationDiscoveryFilter.TRYING_INSTANCES_EXISTING))) {
      ServiceCombServerStats.releaseTryingChance();
    }
    response.handle(async);
  };

  if (handleSuppliedEndpoint(invocation, asyncResp)) {
    return;
  }

  String strategy = Configuration.INSTANCE.getRuleStrategyName(invocation.getMicroserviceName());
  if (!Objects.equals(strategy, this.strategy)) {
    //配置变化,需要重新生成所有的lb实例
    synchronized (lock) {
      clearLoadBalancer();
    }
  }
  this.strategy = strategy;

  LoadBalancer loadBalancer = getOrCreateLoadBalancer(invocation);

  if (!Configuration.INSTANCE.isRetryEnabled(invocation.getMicroserviceName())) {
    send(invocation, asyncResp, loadBalancer);
  } else {
    sendWithRetry(invocation, asyncResp, loadBalancer);
  }
}
 
Example #17
Source File: ProducerOperationHandler.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
private void invoke(Invocation invocation, SwaggerProducerOperation producerOperation, AsyncResponse asyncResp) {
  if (CompletableFuture.class.equals(producerOperation.getProducerMethod().getReturnType())) {
    completableFutureInvoke(invocation, producerOperation, asyncResp);
    return;
  }

  syncInvoke(invocation, producerOperation, asyncResp);
}
 
Example #18
Source File: SimpleLoadBalanceHandler.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Invocation invocation, AsyncResponse asyncResp) throws Exception {
  if (invocation.getEndpoint() != null) {
    invocation.next(asyncResp);
    return;
  }

  DiscoveryContext context = new DiscoveryContext();
  context.setInputParameters(invocation);
  VersionedCache endpointsVersionedCache = discoveryTree.discovery(context,
      invocation.getAppId(),
      invocation.getMicroserviceName(),
      invocation.getMicroserviceVersionRule());
  if (endpointsVersionedCache.isEmpty()) {
    asyncResp.consumerFail(ExceptionUtils.lbAddressNotFound(invocation.getMicroserviceName(),
        invocation.getMicroserviceVersionRule(),
        endpointsVersionedCache.name()));
    return;
  }

  List<Endpoint> endpoints = endpointsVersionedCache.data();
  AtomicInteger index = indexMap.computeIfAbsent(endpointsVersionedCache.name(), name -> {
    LOGGER.info("Create loadBalancer for {}.", name);
    return new AtomicInteger();
  });
  LOGGER.debug("invocation {} use discoveryGroup {}.",
      invocation.getMicroserviceQualifiedName(),
      endpointsVersionedCache.name());

  int idx = Math.abs(index.getAndIncrement());
  idx = idx % endpoints.size();
  Endpoint endpoint = endpoints.get(idx);

  invocation.setEndpoint(endpoint);

  invocation.next(asyncResp);
}
 
Example #19
Source File: InvokerUtils.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
public static void reactiveInvoke(String microserviceName, String microserviceVersion, String transport,
    String schemaId, String operationId, Map<String, Object> swaggerArguments, Type responseType,
    AsyncResponse asyncResp) {
  Invocation invocation = createInvocation(microserviceName, microserviceVersion, transport, schemaId, operationId,
      swaggerArguments, responseType);
  reactiveInvoke(invocation, asyncResp);
}
 
Example #20
Source File: InvokerUtils.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
/**
 * This is an internal API, caller make sure already invoked SCBEngine.ensureStatusUp
 * @param invocation
 * @param asyncResp
 */
public static void reactiveInvoke(Invocation invocation, AsyncResponse asyncResp) {
  try {
    invocation.onStart(null, System.nanoTime());
    invocation.setSync(false);

    ReactiveResponseExecutor respExecutor = new ReactiveResponseExecutor();
    invocation.setResponseExecutor(respExecutor);

    invocation.getInvocationStageTrace().startHandlersRequest();
    invocation.next(ar -> {
      ContextUtils.setInvocationContext(invocation.getParentContext());
      try {
        invocation.getInvocationStageTrace().finishHandlersResponse();
        invocation.onFinish(ar);
        asyncResp.handle(ar);
      } finally {
        ContextUtils.removeInvocationContext();
      }
    });
  } catch (Throwable e) {
    invocation.getInvocationStageTrace().finishHandlersResponse();
    //if throw exception,we can use 500 for status code ?
    Response response = Response.createConsumerFail(e);
    invocation.onFinish(response);
    LOGGER.error("invoke failed, {}", invocation.getOperationMeta().getMicroserviceQualifiedName());
    asyncResp.handle(response);
  }
}
 
Example #21
Source File: TestTransport.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void testEndpoint() throws Exception {
  Endpoint oEndpoint = new Endpoint(new Transport() {
    @Override
    public void send(Invocation invocation, AsyncResponse asyncResp) {
    }

    @Override
    public Object parseAddress(String address) {
      return "127.0.0.1";
    }

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

    @Override
    public String getName() {
      return "test";
    }

    @Override
    public Endpoint getEndpoint() {
      return (new Endpoint(this, "testEndpoint"));
    }

    @Override
    public Endpoint getPublishEndpoint() {
      return (new Endpoint(this, "testEndpoint"));
    }
  }, "rest://127.0.0.1:8080");
  oEndpoint.getTransport().init();
  Assert.assertEquals("rest://127.0.0.1:8080", oEndpoint.getEndpoint());
  Assert.assertEquals("127.0.0.1", oEndpoint.getAddress());
  Assert.assertEquals("test", oEndpoint.getTransport().getName());
  Assert.assertEquals("rest://127.0.0.1:8080", oEndpoint.getEndpoint());
}
 
Example #22
Source File: TestServiceProviderHandler.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  serviceProviderHandler = new ProducerOperationHandler();
  invocation = Mockito.mock(Invocation.class);
  asyncResp = Mockito.mock(AsyncResponse.class);
  OperationMeta = Mockito.mock(OperationMeta.class);
}
 
Example #23
Source File: TransportClientHandler.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Invocation invocation, AsyncResponse asyncResp) throws Exception {
  Transport transport = invocation.getTransport();

  log.debug(
      "Sending request {} to {}",
      invocation.getMicroserviceQualifiedName(),
      invocation.getEndpoint().getEndpoint());

  transport.send(invocation, asyncResp);
}
 
Example #24
Source File: TestProviderAuthHanlder.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  ConfigUtil.installDynamicConfig();
  invocation = Mockito.mock(Invocation.class);
  asyncResp = Mockito.mock(AsyncResponse.class);
  Mockito.when(invocation.getContext(Const.AUTH_TOKEN)).thenReturn("testtoken");
}
 
Example #25
Source File: MyHandler.java    From servicecomb-samples with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Invocation invocation, AsyncResponse asyncResponse) throws Exception {
  //code before

  LOGGER.info("It's my handler! \r\n");

  invocation.next(response -> {
    // code after
    asyncResponse.handle(response);
  });
}
 
Example #26
Source File: TestBizkeeperHandler.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void testHandlNextException() throws Exception {
  Mockito.when(invocation.getMicroserviceName()).thenReturn("testHandlNextException");
  Mockito.when(invocation.getOperationMeta()).thenReturn(Mockito.mock(OperationMeta.class));
  Mockito.when(invocation.getOperationMeta().getMicroserviceQualifiedName())
      .thenReturn("testHandlNextException");
  Mockito.doThrow(new Exception("testHandlNextException")).when(invocation).next(Mockito.any(AsyncResponse.class));
  bizkeeperHandler.handle(invocation, f -> {
    Assert.assertTrue(f.isFailed());
  });
}
 
Example #27
Source File: TestBizkeeperHandler.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  bizkeeperHandler = new TestBizkeeperHandler();
  invocation = Mockito.mock(Invocation.class);
  asyncResp = Mockito.mock(AsyncResponse.class);

  FallbackPolicyManager.addPolicy(new ReturnNullFallbackPolicy());
  FallbackPolicyManager.addPolicy(new ThrowExceptionFallbackPolicy());
  FallbackPolicyManager.addPolicy(new FromCacheFallbackPolicy());
}
 
Example #28
Source File: BizkeeperHandler.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Override
public void handle(Invocation invocation, AsyncResponse asyncResp) {
  HystrixObservable<Response> command = delegate.createBizkeeperCommand(invocation);

  Observable<Response> observable = command.toObservable();
  observable.subscribe(asyncResp::complete, error -> {
    LOG.warn("catch error in bizkeeper:" + error.getMessage());
    asyncResp.fail(invocation.getInvocationType(), error);
  }, () -> {

  });
}
 
Example #29
Source File: LoadbalanceHandler.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
private boolean handleSuppliedEndpoint(Invocation invocation,
    AsyncResponse asyncResp) throws Exception {
  if (invocation.getEndpoint() != null) {
    invocation.next(asyncResp);
    return true;
  }

  if (supportDefinedEndpoint) {
    return defineEndpointAndHandle(invocation, asyncResp);
  }

  return false;
}
 
Example #30
Source File: TestLoadbalanceHandler.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void sendWithRetry(@Injectable LoadBalancer loadBalancer) {
  Holder<String> result = new Holder<>();
  Deencapsulation.invoke(handler, "sendWithRetry", invocation, (AsyncResponse) resp -> {
    result.value = resp.getResult();
  }, loadBalancer);

  // no exception
}