Java Code Examples for io.grpc.MethodDescriptor#getType()

The following examples show how to use io.grpc.MethodDescriptor#getType() . 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: ClientCallImpl.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
ClientCallImpl(
    MethodDescriptor<ReqT, RespT> method, Executor executor, CallOptions callOptions,
    ClientTransportProvider clientTransportProvider,
    ScheduledExecutorService deadlineCancellationExecutor,
    CallTracer channelCallsTracer,
    boolean retryEnabled) {
  this.method = method;
  // If we know that the executor is a direct executor, we don't need to wrap it with a
  // SerializingExecutor. This is purely for performance reasons.
  // See https://github.com/grpc/grpc-java/issues/368
  this.callExecutor = executor == directExecutor()
      ? new SerializeReentrantCallsDirectExecutor()
      : new SerializingExecutor(executor);
  this.channelCallsTracer = channelCallsTracer;
  // Propagate the context from the thread which initiated the call to all callbacks.
  this.context = Context.current();
  this.unaryRequest = method.getType() == MethodType.UNARY
      || method.getType() == MethodType.SERVER_STREAMING;
  this.callOptions = callOptions;
  this.clientTransportProvider = clientTransportProvider;
  this.deadlineCancellationExecutor = deadlineCancellationExecutor;
  this.retryEnabled = retryEnabled;
}
 
Example 2
Source File: CronetClientStream.java    From grpc-nebula-java with Apache License 2.0 5 votes vote down vote up
CronetClientStream(
    final String url,
    @Nullable String userAgent,
    Executor executor,
    final Metadata headers,
    CronetClientTransport transport,
    Runnable startCallback,
    Object lock,
    int maxMessageSize,
    boolean alwaysUsePut,
    MethodDescriptor<?, ?> method,
    StatsTraceContext statsTraceCtx,
    CallOptions callOptions,
    TransportTracer transportTracer) {
  super(
      new CronetWritableBufferAllocator(), statsTraceCtx, transportTracer, headers, callOptions,
      method.isSafe());
  this.url = Preconditions.checkNotNull(url, "url");
  this.userAgent = Preconditions.checkNotNull(userAgent, "userAgent");
  this.statsTraceCtx = Preconditions.checkNotNull(statsTraceCtx, "statsTraceCtx");
  this.executor = Preconditions.checkNotNull(executor, "executor");
  this.headers = Preconditions.checkNotNull(headers, "headers");
  this.transport = Preconditions.checkNotNull(transport, "transport");
  this.startCallback = Preconditions.checkNotNull(startCallback, "startCallback");
  this.idempotent = method.isIdempotent() || alwaysUsePut;
  // Only delay flushing header for unary rpcs.
  this.delayRequestHeader = (method.getType() == MethodDescriptor.MethodType.UNARY);
  this.annotation = callOptions.getOption(CronetCallOptions.CRONET_ANNOTATION_KEY);
  this.annotations = callOptions.getOption(CronetCallOptions.CRONET_ANNOTATIONS_KEY);
  this.state = new TransportState(maxMessageSize, statsTraceCtx, lock, transportTracer);
}
 
Example 3
Source File: GrpcHelperImpl.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public Transaction startTransaction(ElasticApmTracer tracer, ClassLoader cl, ServerCall<?, ?> serverCall, Metadata headers) {
    MethodDescriptor<?, ?> methodDescriptor = serverCall.getMethodDescriptor();

    // ignore non-unary method calls for now
    if (methodDescriptor.getType() != MethodDescriptor.MethodType.UNARY) {
        return null;
    }

    if (tracer.getActive() != null) {
        // don't create nested transactions for nested calls
        // this might be something to do on tracer level instead
        return null;
    }

    Transaction transaction = tracer.startChildTransaction(headers, headerGetter, cl);
    if (transaction == null) {
        return null;
    }

    transaction.withName(methodDescriptor.getFullMethodName())
        .withType("request")
        .setFrameworkName(FRAMEWORK_NAME);

    return transaction.activate();
}
 
Example 4
Source File: GrpcHelperImpl.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
@Override
@Nullable
public Span startSpan(@Nullable AbstractSpan<?> parent,
                      @Nullable MethodDescriptor<?, ?> method,
                      @Nullable String authority) {

    if (null == parent) {
        return null;
    }

    // we only support unary method calls and ignore others for now
    if (method != null && method.getType() != MethodDescriptor.MethodType.UNARY) {
        return null;
    }

    Span span = parent.createExitSpan();
    if (span == null) {
        // as it's an external call, we only need a single span for nested calls
        return null;
    }

    span.withName(method == null ? null : method.getFullMethodName())
        .withType("external")
        .withSubtype(GRPC);

    if (authority != null) {
        Destination destination = span.getContext().getDestination()
            .withAddressPort(authority);

        destination.getService()
            .withName(GRPC)
            .withResource(authority)
            .withType(GRPC);
    }
    return span.activate();
}
 
Example 5
Source File: GrpcMethod.java    From java-grpc-prometheus with Apache License 2.0 5 votes vote down vote up
static GrpcMethod of(MethodDescriptor<?, ?> method) {
  String serviceName = MethodDescriptor.extractFullServiceName(method.getFullMethodName());

  // Full method names are of the form: "full.serviceName/MethodName". We extract the last part.
  String methodName = method.getFullMethodName().substring(serviceName.length() + 1);
  return new GrpcMethod(serviceName, methodName, method.getType());
}
 
Example 6
Source File: TracingServerCallListener.java    From skywalking with Apache License 2.0 5 votes vote down vote up
protected TracingServerCallListener(ServerCall.Listener<REQUEST> delegate, MethodDescriptor<REQUEST, ?> descriptor,
    ContextSnapshot contextSnapshot) {
    super(delegate);
    this.contextSnapshot = contextSnapshot;
    this.methodType = descriptor.getType();
    this.operationPrefix = OperationNameFormatUtil.formatOperationName(descriptor) + SERVER;
}
 
Example 7
Source File: DiscardClientInterceptor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
    if (MethodDescriptor.MethodType.CLIENT_STREAMING == method.getType()) {
        if (logger.isDebugEnabled()) {
            logger.debug("interceptCall {}", method.getFullMethodName());
        }
        final ClientCall<ReqT, RespT> newCall = next.newCall(method, callOptions);
        return new DiscardClientCall<ReqT, RespT>(newCall, this.listener, maxPendingThreshold);
    } else {
        return next.newCall(method, callOptions);
    }
}
 
Example 8
Source File: UnaryCallDeadlineInterceptor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Override
public <ReqT, RespT> ClientCall<ReqT, RespT> interceptCall(MethodDescriptor<ReqT, RespT> method, CallOptions callOptions, Channel next) {
    if (MethodDescriptor.MethodType.UNARY == method.getType()) {
        if (logger.isDebugEnabled()) {
            logger.debug("interceptCall {}", method.getFullMethodName());
        }
        return next.newCall(method, callOptions.withDeadlineAfter(timeoutMillis, TimeUnit.MILLISECONDS));
    } else {
        return next.newCall(method, callOptions);
    }
}
 
Example 9
Source File: CronetClientStream.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
CronetClientStream(
    final String url,
    @Nullable String userAgent,
    Executor executor,
    final Metadata headers,
    CronetClientTransport transport,
    Runnable startCallback,
    Object lock,
    int maxMessageSize,
    boolean alwaysUsePut,
    MethodDescriptor<?, ?> method,
    StatsTraceContext statsTraceCtx,
    CallOptions callOptions,
    TransportTracer transportTracer,
    boolean useGetForSafeMethods,
    boolean usePutForIdempotentMethods) {
  super(
      new CronetWritableBufferAllocator(), statsTraceCtx, transportTracer, headers, callOptions,
      useGetForSafeMethods && method.isSafe());
  this.url = Preconditions.checkNotNull(url, "url");
  this.userAgent = Preconditions.checkNotNull(userAgent, "userAgent");
  this.statsTraceCtx = Preconditions.checkNotNull(statsTraceCtx, "statsTraceCtx");
  this.executor = Preconditions.checkNotNull(executor, "executor");
  this.headers = Preconditions.checkNotNull(headers, "headers");
  this.transport = Preconditions.checkNotNull(transport, "transport");
  this.startCallback = Preconditions.checkNotNull(startCallback, "startCallback");
  this.idempotent = (usePutForIdempotentMethods && method.isIdempotent()) || alwaysUsePut;
  // Only delay flushing header for unary rpcs.
  this.delayRequestHeader = (method.getType() == MethodDescriptor.MethodType.UNARY);
  this.annotation = callOptions.getOption(CRONET_ANNOTATION_KEY);
  this.annotations = callOptions.getOption(CRONET_ANNOTATIONS_KEY);
  this.state = new TransportState(maxMessageSize, statsTraceCtx, lock, transportTracer);

  // Tests expect the "plain" deframer behavior, not MigratingDeframer
  // https://github.com/grpc/grpc-java/issues/7140
  optimizeForDirectExecutor();
}
 
Example 10
Source File: ClientCallImpl.java    From grpc-java with Apache License 2.0 5 votes vote down vote up
ClientCallImpl(
    MethodDescriptor<ReqT, RespT> method, Executor executor, CallOptions callOptions,
    ClientTransportProvider clientTransportProvider,
    ScheduledExecutorService deadlineCancellationExecutor,
    CallTracer channelCallsTracer,
    boolean retryEnabled) {
  this.method = method;
  // TODO(carl-mastrangelo): consider moving this construction to ManagedChannelImpl.
  this.tag = PerfMark.createTag(method.getFullMethodName(), System.identityHashCode(this));
  // If we know that the executor is a direct executor, we don't need to wrap it with a
  // SerializingExecutor. This is purely for performance reasons.
  // See https://github.com/grpc/grpc-java/issues/368
  if (executor == directExecutor()) {
    this.callExecutor = new SerializeReentrantCallsDirectExecutor();
    callExecutorIsDirect = true;
  } else {
    this.callExecutor = new SerializingExecutor(executor);
    callExecutorIsDirect = false;
  }
  this.channelCallsTracer = channelCallsTracer;
  // Propagate the context from the thread which initiated the call to all callbacks.
  this.context = Context.current();
  this.unaryRequest = method.getType() == MethodType.UNARY
      || method.getType() == MethodType.SERVER_STREAMING;
  this.callOptions = callOptions;
  this.clientTransportProvider = clientTransportProvider;
  this.deadlineCancellationExecutor = deadlineCancellationExecutor;
  this.retryEnabled = retryEnabled;
  PerfMark.event("ClientCall.<init>", tag);
}
 
Example 11
Source File: UnframedGrpcService.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
public HttpResponse serve(
        PooledHttpService delegate, ServiceRequestContext ctx, PooledHttpRequest req) throws Exception {
    final RequestHeaders clientHeaders = req.headers();
    final MediaType contentType = clientHeaders.contentType();
    if (contentType == null) {
        // All gRPC requests, whether framed or non-framed, must have content-type. If it's not sent, let
        // the delegate return its usual error message.
        return delegate.serve(ctx, req);
    }

    for (SerializationFormat format : GrpcSerializationFormats.values()) {
        if (format.isAccepted(contentType)) {
            // Framed request, so just delegate.
            return delegate.serve(ctx, req);
        }
    }

    final String methodName = GrpcRequestUtil.determineMethod(ctx);
    final MethodDescriptor<?, ?> method = methodName != null ? methodsByName.get(methodName) : null;
    if (method == null) {
        // Unknown method, let the delegate return a usual error.
        return delegate.serve(ctx, req);
    }

    if (method.getType() != MethodType.UNARY) {
        return HttpResponse.of(HttpStatus.BAD_REQUEST,
                               MediaType.PLAIN_TEXT_UTF_8,
                               "Only unary methods can be used with non-framed requests.");
    }

    final RequestHeadersBuilder grpcHeaders = clientHeaders.toBuilder();

    final MediaType framedContentType;
    if (contentType.is(MediaType.PROTOBUF)) {
        framedContentType = GrpcSerializationFormats.PROTO.mediaType();
    } else if (contentType.is(MediaType.JSON_UTF_8)) {
        framedContentType = GrpcSerializationFormats.JSON.mediaType();
    } else {
        return HttpResponse.of(HttpStatus.UNSUPPORTED_MEDIA_TYPE,
                               MediaType.PLAIN_TEXT_UTF_8,
                               "Unsupported media type. Only application/protobuf is supported.");
    }
    grpcHeaders.contentType(framedContentType);

    if (grpcHeaders.get(GrpcHeaderNames.GRPC_ENCODING) != null) {
        return HttpResponse.of(HttpStatus.UNSUPPORTED_MEDIA_TYPE,
                               MediaType.PLAIN_TEXT_UTF_8,
                               "gRPC encoding is not supported for non-framed requests.");
    }

    // All clients support no encoding, and we don't support gRPC encoding for non-framed requests, so just
    // clear the header if it's present.
    grpcHeaders.remove(GrpcHeaderNames.GRPC_ACCEPT_ENCODING);

    ctx.logBuilder().defer(RequestLogProperty.REQUEST_CONTENT,
                           RequestLogProperty.RESPONSE_CONTENT);

    final CompletableFuture<HttpResponse> responseFuture = new CompletableFuture<>();
    req.aggregateWithPooledObjects(ctx.eventLoop(), ctx.alloc()).handle((clientRequest, t) -> {
        if (t != null) {
            responseFuture.completeExceptionally(t);
        } else {
            frameAndServe(ctx, grpcHeaders.build(), clientRequest, responseFuture);
        }
        return null;
    });
    return HttpResponse.from(responseFuture);
}