Java Code Examples for io.grpc.MethodDescriptor.MethodType#UNARY

The following examples show how to use io.grpc.MethodDescriptor.MethodType#UNARY . 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: OkHttpClientTransport.java    From grpc-nebula-java with Apache License 2.0 6 votes vote down vote up
@GuardedBy("lock")
private void startStream(OkHttpClientStream stream) {
  Preconditions.checkState(
      stream.id() == OkHttpClientStream.ABSENT_ID, "StreamId already assigned");
  streams.put(nextStreamId, stream);
  setInUse(stream);
  stream.transportState().start(nextStreamId);
  // For unary and server streaming, there will be a data frame soon, no need to flush the header.
  if ((stream.getType() != MethodType.UNARY && stream.getType() != MethodType.SERVER_STREAMING)
      || stream.useGet()) {
    frameWriter.flush();
  }
  if (nextStreamId >= Integer.MAX_VALUE - 2) {
    // Make sure nextStreamId greater than all used id, so that mayHaveCreatedStream() performs
    // correctly.
    nextStreamId = Integer.MAX_VALUE;
    startGoAway(Integer.MAX_VALUE, ErrorCode.NO_ERROR,
        Status.UNAVAILABLE.withDescription("Stream ids exhausted"));
  } else {
    nextStreamId += 2;
  }
}
 
Example 2
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 3
Source File: OkHttpClientTransport.java    From grpc-java with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("GuardedBy")
@GuardedBy("lock")
private void startStream(OkHttpClientStream stream) {
  Preconditions.checkState(
      stream.id() == OkHttpClientStream.ABSENT_ID, "StreamId already assigned");
  streams.put(nextStreamId, stream);
  setInUse(stream);
  // TODO(b/145386688): This access should be guarded by 'stream.transportState().lock'; instead
  // found: 'this.lock'
  stream.transportState().start(nextStreamId);
  // For unary and server streaming, there will be a data frame soon, no need to flush the header.
  if ((stream.getType() != MethodType.UNARY && stream.getType() != MethodType.SERVER_STREAMING)
      || stream.useGet()) {
    frameWriter.flush();
  }
  if (nextStreamId >= Integer.MAX_VALUE - 2) {
    // Make sure nextStreamId greater than all used id, so that mayHaveCreatedStream() performs
    // correctly.
    nextStreamId = Integer.MAX_VALUE;
    startGoAway(Integer.MAX_VALUE, ErrorCode.NO_ERROR,
        Status.UNAVAILABLE.withDescription("Stream ids exhausted"));
  } else {
    nextStreamId += 2;
  }
}
 
Example 4
Source File: GrpcReflectionUtils.java    From grpc-swagger with MIT License 5 votes vote down vote up
public static MethodType fetchMethodType(MethodDescriptor methodDescriptor) {
    boolean clientStreaming = methodDescriptor.toProto().getClientStreaming();
    boolean serverStreaming = methodDescriptor.toProto().getServerStreaming();
    if (clientStreaming && serverStreaming) {
        return MethodType.BIDI_STREAMING;
    } else if (!clientStreaming && !serverStreaming) {
        return MethodType.UNARY;
    } else if (!clientStreaming) {
        return MethodType.SERVER_STREAMING;
    } else {
        return MethodType.SERVER_STREAMING;
    }
}
 
Example 5
Source File: DynamicGrpcClient.java    From milkman with MIT License 5 votes vote down vote up
/**
 * Makes an rpc to the remote endpoint and respects the supplied callback. Returns a future which
 * terminates once the call has ended. For calls which are single-request, this throws
 * {@link IllegalArgumentException} if the size of {@code requests} is not exactly 1.
 */
public ListenableFuture<Void> call(
    ImmutableList<DynamicMessage> requests,
    StreamObserver<DynamicMessage> responseObserver,
    CallOptions callOptions) {
  Preconditions.checkArgument(!requests.isEmpty(), "Can't make call without any requests");
  MethodType methodType = getMethodType();
  long numRequests = requests.size();
  if (methodType == MethodType.UNARY) {
    logger.info("Making unary call");
    Preconditions.checkArgument(numRequests == 1,
        "Need exactly 1 request for unary call, but got: " + numRequests);
    return callUnary(requests.get(0), responseObserver, callOptions);
  } else if (methodType == MethodType.SERVER_STREAMING) {
    logger.info("Making server streaming call");
    Preconditions.checkArgument(numRequests == 1,
        "Need exactly 1 request for server streaming call, but got: " + numRequests);
    return callServerStreaming(requests.get(0), responseObserver, callOptions);
  } else if (methodType == MethodType.CLIENT_STREAMING) {
    logger.info("Making client streaming call with " + requests.size() + " requests");
    return callClientStreaming(requests, responseObserver, callOptions);
  } else {
    // Bidi streaming.
    logger.info("Making bidi streaming call with " + requests.size() + " requests");
    return callBidiStreaming(requests, responseObserver, callOptions);
  }
}
 
Example 6
Source File: DynamicGrpcClient.java    From milkman with MIT License 5 votes vote down vote up
/** Returns the appropriate method type based on whether the client or server expect streams. */
private MethodType getMethodType() {
  boolean clientStreaming = protoMethodDescriptor.toProto().getClientStreaming();
  boolean serverStreaming = protoMethodDescriptor.toProto().getServerStreaming();

  if (!clientStreaming && !serverStreaming) {
    return MethodType.UNARY;
  } else if (!clientStreaming && serverStreaming) {
    return MethodType.SERVER_STREAMING;
  } else if (clientStreaming && !serverStreaming) {
    return MethodType.CLIENT_STREAMING;
  } else {
    return MethodType.BIDI_STREAMING;
  }
}
 
Example 7
Source File: GrpcReflectionUtils.java    From grpc-swagger with MIT License 5 votes vote down vote up
public static MethodType fetchMethodType(MethodDescriptor methodDescriptor) {
    boolean clientStreaming = methodDescriptor.toProto().getClientStreaming();
    boolean serverStreaming = methodDescriptor.toProto().getServerStreaming();
    if (clientStreaming && serverStreaming) {
        return MethodType.BIDI_STREAMING;
    } else if (!clientStreaming && !serverStreaming) {
        return MethodType.UNARY;
    } else if (!clientStreaming) {
        return MethodType.SERVER_STREAMING;
    } else {
        return MethodType.SERVER_STREAMING;
    }
}
 
Example 8
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 9
Source File: ArmeriaServerCall.java    From armeria with Apache License 2.0 4 votes vote down vote up
@Override
public void messageRead(DeframedMessage message) {

    final I request;
    final ByteBuf buf = message.buf();

    boolean success = false;
    try {
        // Special case for unary calls.
        if (messageReceived && method.getType() == MethodType.UNARY) {
            closeListener(Status.INTERNAL.withDescription(
                    "More than one request messages for unary call or server streaming call"));
            return;
        }
        messageReceived = true;

        if (isCancelled()) {
            return;
        }
        success = true;
    } finally {
        if (buf != null && !success) {
            buf.release();
        }
    }

    try {
        request = marshaller.deserializeRequest(message);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }

    if (!ctx.log().isAvailable(RequestLogProperty.REQUEST_CONTENT)) {
        ctx.logBuilder().requestContent(GrpcLogUtil.rpcRequest(method, request), null);
    }

    if (unsafeWrapRequestBuffers && buf != null) {
        GrpcUnsafeBufferUtil.storeBuffer(buf, request, ctx);
    }

    if (blockingExecutor != null) {
        blockingExecutor.execute(() -> invokeOnMessage(request));
    } else {
        invokeOnMessage(request);
    }
}
 
Example 10
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);
}