Class GrpcServiceBuilder

java.lang.Object
com.linecorp.armeria.server.grpc.GrpcServiceBuilder

public final class GrpcServiceBuilder extends Object
Constructs a GrpcService to serve gRPC services from within Armeria.
  • Method Details

    • addService

      public GrpcServiceBuilder addService(io.grpc.ServerServiceDefinition service)
      Adds a gRPC ServerServiceDefinition to this GrpcServiceBuilder, such as what's returned by BindableService.bindService().
    • addService

      public GrpcServiceBuilder addService(String path, io.grpc.ServerServiceDefinition service)
      Adds a gRPC ServerServiceDefinition to this GrpcServiceBuilder, such as what's returned by BindableService.bindService().

      Note that the specified path replaces the normal gRPC service path. Let's say you have the following gRPC service definition.

      
       package example.grpc.hello;
      
       service HelloService {
         rpc Hello (HelloRequest) returns (HelloReply) {}
       }
      The normal gRPC service path for the Hello method is "/example.grpc.hello.HelloService/Hello". However, if you set "/foo" to path, the Hello method will be served at "/foo/Hello". This is useful for supporting unframed gRPC with HTTP idiomatic path.
    • addService

      public GrpcServiceBuilder addService(String path, io.grpc.ServerServiceDefinition service, io.grpc.MethodDescriptor<?,?> methodDescriptor)
      Adds a method of gRPC ServerServiceDefinition to this GrpcServiceBuilder. You can get MethodDescriptors from the enclosing class of your generated stub.

      Note that the specified path replaces the normal gRPC service path. Let's say you have the following gRPC service definition.

      
       package example.grpc.hello;
      
       service HelloService {
         rpc Hello (HelloRequest) returns (HelloReply) {}
       }
      The normal gRPC service path for the Hello method is "/example.grpc.hello.HelloService/Hello". However, if you set "/fooHello" to path, the Hello method will be served at "/fooHello". This is useful for supporting unframed gRPC with HTTP idiomatic path.
    • addService

      public GrpcServiceBuilder addService(io.grpc.BindableService bindableService)
      Adds a gRPC BindableService to this GrpcServiceBuilder. Most gRPC service implementations are BindableServices.
    • addService

      @UnstableApi public GrpcServiceBuilder addService(io.grpc.BindableService bindableService, Iterable<? extends Function<? super HttpService,? extends HttpService>> decorators)
      Decorates a gRPC BindableService with the given decorators, in the order of iteration. For more details on decorator behavior, please refer to the following document.
      See Also:
    • addService

      public GrpcServiceBuilder addService(String path, io.grpc.BindableService bindableService)
      Adds a gRPC BindableService to this GrpcServiceBuilder. Most gRPC service implementations are BindableServices.

      Note that the specified path replaces the normal gRPC service path. Let's say you have the following gRPC service definition.

      
       package example.grpc.hello;
      
       service HelloService {
         rpc Hello (HelloRequest) returns (HelloReply) {}
       }
      The normal gRPC service path for the Hello method is "/example.grpc.hello.HelloService/Hello". However, if you set "/foo" to path, the Hello method will be served at "/foo/Hello". This is useful for supporting unframed gRPC with HTTP idiomatic path.
    • addService

      @UnstableApi public GrpcServiceBuilder addService(String path, io.grpc.BindableService bindableService, Iterable<? extends Function<? super HttpService,? extends HttpService>> decorators)
      Decorates a gRPC BindableService with the given decorators, in the order of iteration. For more details on decorator behavior, please refer to the following document.
      See Also:
    • addService

      public <T> GrpcServiceBuilder addService(T implementation, Function<? super T,io.grpc.ServerServiceDefinition> serviceDefinitionFactory)
      Adds an implementation of gRPC service to this GrpcServiceBuilder. Most gRPC service implementations are BindableServices. This method is useful in cases like the followings.

      Used for ScalaPB gRPC stubs

      
       GrpcService.builder()
                  .addService(new HelloServiceImpl,
                              HelloServiceGrpc.bindService(_,
                                                           ExecutionContext.global))
       

      Used for intercepted gRPC-Java stubs

      
       GrpcService.builder()
                  .addService(new TestServiceImpl,
                              impl -> ServerInterceptors.intercept(impl, interceptors));
       
    • addService

      @UnstableApi public <T> GrpcServiceBuilder addService(T implementation, Function<? super T,io.grpc.ServerServiceDefinition> serviceDefinitionFactory, Iterable<? extends Function<? super HttpService,? extends HttpService>> decorators)
      Decorates an implementation of gRPC service with the given decorators, in the order of iteration.

      Most gRPC service implementations are BindableServices. This method is useful in cases like the followings.

      Used for ScalaPB gRPC stubs

      
       GrpcService.builder()
                  .addService(new HelloServiceImpl,
                              HelloServiceGrpc.bindService(_,
                                                           ExecutionContext.global))
       

      Used for intercepted gRPC-Java stubs

      
       GrpcService.builder()
                  .addService(new TestServiceImpl,
                              impl -> ServerInterceptors.intercept(impl, interceptors));
       

      For more details on decorator behavior, please refer to the following document.

      See Also:
    • addService

      public GrpcServiceBuilder addService(String path, io.grpc.BindableService bindableService, io.grpc.MethodDescriptor<?,?> methodDescriptor)
      Adds a method of gRPC BindableService to this GrpcServiceBuilder. You can get MethodDescriptors from the enclosing class of your generated stub.

      Note that the specified path replaces the normal gRPC service path. Let's say you have the following gRPC service definition.

      
       package example.grpc.hello;
      
       service HelloService {
         rpc Hello (HelloRequest) returns (HelloReply) {}
       }
      The normal gRPC service path for the Hello method is "/example.grpc.hello.HelloService/Hello". However, if you set "/fooHello" to path, the Hello method will be served at "/fooHello". This is useful for supporting unframed gRPC with HTTP idiomatic path.
    • addService

      @UnstableApi public GrpcServiceBuilder addService(String path, io.grpc.BindableService bindableService, io.grpc.MethodDescriptor<?,?> methodDescriptor, Iterable<? extends Function<? super HttpService,? extends HttpService>> decorators)
      Decorates a method of gRPC BindableService with the given decorators, in the order of iteration. For more details on decorator behavior, please refer to the following document.
      See Also:
    • intercept

      public GrpcServiceBuilder intercept(io.grpc.ServerInterceptor... interceptors)
      Adds server interceptors into the gRPC service. The last interceptor will have its ServerInterceptor.interceptCall(io.grpc.ServerCall<ReqT, RespT>, io.grpc.Metadata, io.grpc.ServerCallHandler<ReqT, RespT>) called first.
      Parameters:
      interceptors - array of interceptors to apply to the service.
    • intercept

      public GrpcServiceBuilder intercept(Iterable<? extends io.grpc.ServerInterceptor> interceptors)
      Adds server interceptors into the gRPC service. The last interceptor will have its ServerInterceptor.interceptCall(io.grpc.ServerCall<ReqT, RespT>, io.grpc.Metadata, io.grpc.ServerCallHandler<ReqT, RespT>) called first.
      Parameters:
      interceptors - list of interceptors to apply to the service.
    • addServices

      public GrpcServiceBuilder addServices(io.grpc.BindableService... bindableServices)
      Adds gRPC BindableServices to this GrpcServiceBuilder. Most gRPC service implementations are BindableServices.
    • addServices

      public GrpcServiceBuilder addServices(Iterable<io.grpc.BindableService> bindableServices)
      Adds gRPC BindableServices to this GrpcServiceBuilder. Most gRPC service implementations are BindableServices.
    • addServiceDefinitions

      public GrpcServiceBuilder addServiceDefinitions(io.grpc.ServerServiceDefinition... services)
      Adds gRPC ServerServiceDefinitions to this GrpcServiceBuilder.
    • addServiceDefinitions

      public GrpcServiceBuilder addServiceDefinitions(Iterable<io.grpc.ServerServiceDefinition> services)
      Adds gRPC ServerServiceDefinitions to this GrpcServiceBuilder.
    • decompressorRegistry

      public GrpcServiceBuilder decompressorRegistry(io.grpc.DecompressorRegistry registry)
      Sets the DecompressorRegistry to use when decompressing messages. If not set, will use the default, which supports gzip only.
    • compressorRegistry

      public GrpcServiceBuilder compressorRegistry(io.grpc.CompressorRegistry registry)
      Sets the CompressorRegistry to use when compressing messages. If not set, will use the default, which supports gzip only.
    • supportedSerializationFormats

      public GrpcServiceBuilder supportedSerializationFormats(SerializationFormat... formats)
      Sets the SerializationFormats supported by this server. If not set, defaults to support all GrpcSerializationFormats.values().
    • supportedSerializationFormats

      public GrpcServiceBuilder supportedSerializationFormats(Iterable<SerializationFormat> formats)
      Sets the SerializationFormats supported by this server. If not set, defaults to support all GrpcSerializationFormats.values().
    • setMaxInboundMessageSizeBytes

      @Deprecated public GrpcServiceBuilder setMaxInboundMessageSizeBytes(int maxInboundMessageSizeBytes)
      Deprecated.
      Sets the maximum size in bytes of an individual incoming message. If not set, will use VirtualHost.maxRequestLength(). To support long-running RPC streams, it is recommended to set ServerBuilder.maxRequestLength(long) (or VirtualHostBuilder.maxRequestLength(long)) and ServerBuilder.requestTimeoutMillis(long) (or VirtualHostBuilder.requestTimeoutMillis(long)) to very high values and set this to the expected limit of individual messages in the stream.
    • setMaxOutboundMessageSizeBytes

      @Deprecated public GrpcServiceBuilder setMaxOutboundMessageSizeBytes(int maxOutboundMessageSizeBytes)
      Deprecated.
      Sets the maximum size in bytes of an individual outgoing message. If not set, all messages will be sent. This can be a safety valve to prevent overflowing network connections with large messages due to business logic bugs.
    • maxRequestMessageLength

      public GrpcServiceBuilder maxRequestMessageLength(int maxRequestMessageLength)
      Sets the maximum size in bytes of an individual request message. If not set, will use VirtualHost.maxRequestLength(). To support long-running RPC streams, it is recommended to set ServerBuilder.maxRequestLength(long) (or VirtualHostBuilder.maxRequestLength(long)) and ServerBuilder.requestTimeoutMillis(long) (or VirtualHostBuilder.requestTimeoutMillis(long)) to very high values and set this to the expected limit of individual messages in the stream.
    • maxResponseMessageLength

      public GrpcServiceBuilder maxResponseMessageLength(int maxResponseMessageLength)
      Sets the maximum size in bytes of an individual response message. If not set, all messages will be sent. This can be a safety valve to prevent overflowing network connections with large messages due to business logic bugs.
    • enableUnframedRequests

      public GrpcServiceBuilder enableUnframedRequests(boolean enableUnframedRequests)
      Sets whether the service handles requests not framed using the gRPC wire protocol. Such requests should only have the serialized message as the request content, and the response content will only have the serialized response message. Supporting unframed requests can be useful, for example, when migrating an existing service to gRPC.

      Limitations:

      • Only unary methods (single request, single response) are supported.
      • Message compression is not supported. EncodingService should be used instead for transport level encoding.
    • unframedGrpcErrorHandler

      @UnstableApi public GrpcServiceBuilder unframedGrpcErrorHandler(UnframedGrpcErrorHandler unframedGrpcErrorHandler)
      Set a custom error response mapper. This is useful to serve custom response when using unframed gRPC service.
      Parameters:
      unframedGrpcErrorHandler - The function which maps the error response to an HttpResponse.
    • enableHttpJsonTranscoding

      @UnstableApi public GrpcServiceBuilder enableHttpJsonTranscoding(boolean enableHttpJsonTranscoding)
      Sets whether the service handles HTTP/JSON requests using the gRPC wire protocol.

      Limitations:

      When custom supportedSerializationFormats(SerializationFormat...) are used, GrpcSerializationFormats.JSON must be included to enable HTTP/JSON transcoding. Otherwise, service builder will throw IllegalStateException when building the service.

      See Also:
    • enableHttpJsonTranscoding

      @UnstableApi public GrpcServiceBuilder enableHttpJsonTranscoding(HttpJsonTranscodingOptions httpJsonTranscodingOptions)
      Enables HTTP/JSON transcoding using the gRPC wire protocol. Provide HttpJsonTranscodingOptions to customize HttpJsonTranscoding.

      Example:

      
       HttpJsonTranscodingOptions options =
         HttpJsonTranscodingOptions.builder()
                                   .queryParamMatchRules(ORIGINAL_FIELD)
                                   ...
                                   .build();
      
       GrpcService.builder()
                  // Enable HttpJsonTranscoding and use the specified HttpJsonTranscodingOption
                  .enableHttpJsonTranscoding(options)
                  .build();
       

      Limitations:

      See Also:
    • httpJsonTranscodingErrorHandler

      @UnstableApi @Deprecated public GrpcServiceBuilder httpJsonTranscodingErrorHandler(UnframedGrpcErrorHandler httpJsonTranscodingErrorHandler)
      Sets an error handler which handles an exception raised while serving a gRPC request transcoded from an HTTP/JSON request. By default, UnframedGrpcErrorHandler.ofJson() would be set.
    • useBlockingTaskExecutor

      public GrpcServiceBuilder useBlockingTaskExecutor(boolean useBlockingTaskExecutor)
      Sets whether the service executes service methods using the blocking executor. By default, service methods are executed directly on the event loop for implementing fully asynchronous services. If your service uses blocking logic, you should either execute such logic in a separate thread using something like Executors.newCachedThreadPool() or enable this setting.
    • unsafeWrapRequestBuffers

      public GrpcServiceBuilder unsafeWrapRequestBuffers(boolean unsafeWrapRequestBuffers)
      Enables unsafe retention of request buffers. Can improve performance when working with very large (i.e., several megabytes) payloads.

      DISCLAIMER: Do not use this if you don't know what you are doing. It is very easy to introduce memory leaks when using this method. You will probably spend much time debugging memory leaks during development if this is enabled. You will probably spend much time debugging memory leaks in production if this is enabled. You probably don't want to do this and should turn back now.

      When enabled, the reference-counted buffer received from the client will be stored into RequestContext instead of being released. All ByteString in a protobuf message will reference sections of this buffer instead of having their own copies. When done with a request message, call GrpcUnsafeBufferUtil.releaseBuffer(Object, RequestContext) with the message and the request's context to release the buffer. The message must be the same reference as what was passed to the service stub - a message with the same contents will not work. If GrpcUnsafeBufferUtil.releaseBuffer(Object, RequestContext) is not called, the memory will be leaked.

      Note that this isn't working if the payloads are compressed or the SerializationFormat is GrpcSerializationFormats.PROTO_WEB_TEXT.

    • jsonMarshallerFactory

      public GrpcServiceBuilder jsonMarshallerFactory(Function<? super io.grpc.ServiceDescriptor,? extends GrpcJsonMarshaller> jsonMarshallerFactory)
      Sets the factory that creates a GrpcJsonMarshaller that serializes and deserializes request or response messages to and from JSON depending on the SerializationFormat. The returned GrpcJsonMarshaller from the factory replaces the built-in GrpcJsonMarshaller.

      This is commonly used to:

    • useClientTimeoutHeader

      public GrpcServiceBuilder useClientTimeoutHeader(boolean useClientTimeoutHeader)
      Sets whether to use a grpc-timeout header sent by the client to control the timeout for request processing. If disabled, the request timeout will be the one configured for the Armeria server, e.g., using ServerBuilder.requestTimeout(Duration).

      It is recommended to disable this when clients are not trusted code, e.g., for gRPC-Web clients that can come from arbitrary browsers.

    • enableHealthCheckService

      public GrpcServiceBuilder enableHealthCheckService(boolean enableHealthCheckService)
      Sets the default GrpcHealthCheckService to this GrpcServiceBuilder. The gRPC health check service manages only the health checker that determines the healthiness of the Server.
      See Also:
    • autoCompression

      @UnstableApi public GrpcServiceBuilder autoCompression(boolean autoCompression)
      Sets whether the gRPC response is compressed automatically when a client sends the grpc-accept-encoding header with the encoding registered in the CompressorRegistry.
    • exceptionHandler

      @UnstableApi public GrpcServiceBuilder exceptionHandler(GrpcExceptionHandlerFunction exceptionHandler)
      Sets the specified GrpcExceptionHandlerFunction that maps a Throwable to a gRPC Status.

      Note that this method and addExceptionMapping(Class, Status) are mutually exclusive.

    • exceptionMapping

      @Deprecated public GrpcServiceBuilder exceptionMapping(GrpcStatusFunction statusFunction)
      Sets the specified GrpcExceptionHandlerFunction that maps a Throwable to a gRPC Status.

      Note that this method and addExceptionMapping(Class, Status) are mutually exclusive.

    • addExceptionMapping

      @Deprecated public GrpcServiceBuilder addExceptionMapping(Class<? extends Throwable> exceptionType, io.grpc.Status status)
      Adds the specified exception mapping that maps a Throwable to a gRPC Status. The mapping is used to handle a Throwable when it is raised.

      Note that this method and exceptionHandler(GrpcExceptionHandlerFunction) are mutually exclusive.

    • addExceptionMapping

      @Deprecated public <T extends Throwable> GrpcServiceBuilder addExceptionMapping(Class<T> exceptionType, BiFunction<T,io.grpc.Metadata,io.grpc.Status> statusFunction)
      Adds the specified exception mapping that maps a Throwable to a gRPC Status. The mapping is used to handle a Throwable when it is raised.

      Note that this method and exceptionMapping(GrpcStatusFunction) are mutually exclusive.

    • addExceptionMapping

      @Deprecated public GrpcServiceBuilder addExceptionMapping(Class<? extends Throwable> exceptionType, GrpcStatusFunction statusFunction)
      Adds the specified exception mapping that maps a Throwable to a gRPC Status. The mapping is used to handle a Throwable when it is raised.

      Note that this method and exceptionMapping(GrpcStatusFunction) are mutually exclusive.

    • build

      public GrpcService build()
      Constructs a new GrpcService that can be bound to ServerBuilder. It is recommended to bind the service to a server using ServerBuilder.service(HttpServiceWithRoutes) to mount all service paths without interfering with other services.