Quality: Platinum Tier.
🐙 userver provides a gRPC driver as userver-grpc library. It uses namespace ugrpc::client and namespace ugrpc::server.
The driver wraps grpcpp in the userver asynchronous interface.
See also:
Generate and link a library from .proto schemas and link to it in your CMakeLists.txt:
userver_add_grpc_library will link userver::grpc transitively and will generate the usual .pb.h + .pb.cc files. For service definitions, it will additionally generate asynchronous interfaces foo_client.usrv.pb.hpp and foo_service.usrv.pb.hpp.
To create gRPC clients in your microservice, register the provided ugrpc::client::ClientFactoryComponent and add the corresponding component section to the static config.
To create gRPC services in your microservice, register the provided ugrpc::server::ServerComponent and add the corresponding component section to the static config.
See gRPC client and service for a tutorial.
In a component constructor, find ugrpc::client::ClientFactoryComponent and store a reference to its ugrpc::client::ClientFactory. Using it, you can create gRPC clients of code-generated YourServiceClient types.
Client creation is an expensive operation! Either create them once at the server boot time or cache them. An automated solution for client creation and caching is the ugrpc::client::SimpleClientComponent. It also allows you to specify dynamic config for ugrpc::client::ClientQos :
Typical steps include:
Read the documentation on gRPC streams:
On errors, exceptions from userver/ugrpc/client/exceptions.hpp are thrown. It is recommended to catch them outside the entire stream interaction. You can catch exceptions for specific gRPC error codes or all at once.
If a unary request cannot be serialized, the call throws ugrpc::client::RpcSerializationError before sending the request. Userver does not retry this local failure. Previously, the serializer's failure status was reported as ugrpc::client::ErrorWithStatus, typically ugrpc::client::InternalError. Code that handles serialization failures must catch ugrpc::client::RpcSerializationError explicitly or use the common ugrpc::client::RpcError base class.
For unary RPCs, access ugrpc::client::CallContext::GetClientContext and response metadata only after the call completes successfully or with ugrpc::client::ErrorWithStatus.
gRPC metadata allows you to send additional information along with requests and responses. Metadata consists of key-value pairs that are transmitted as HTTP/2 headers.
To send metadata with a request, use ugrpc::client::CallOptions and its ugrpc::client::CallOptions::AddMetadata method:
Response metadata can be accessed through the ugrpc::client::CallContext obtained from ugrpc::client::ResponseFuture or stream objects:
The server can read metadata sent by the client:
The server can send two types of metadata back to the client:
May be enabled for gRPC client via ugrpc::client::ClientFactoryComponent static config option:
Available auth-type values are:
Default (system) authentication keys are used by default. To change that provide the ssl-credentials-options static config options with the following options:
SSL has to be disabled in tests, because it requires the server to have a public domain name, which it does not in tests. In testsuite, SSL in gRPC clients is disabled automatically.
Main page: gRPC client middlewares.
Client behaviour can be modified with a middleware. Middleware code is executed before or after the client code. Use ugrpc::client::MiddlewareBase to implement new middlewares.
A service implementation is a class derived from a code-generated YourServiceBase interface class. Each service method from the schema corresponds to a method of the interface class. If you don't override some of the methods, UNIMPLEMENTED error code will be reported for those.
To register your service:
Server services use completion queues by default. Set grpc-server.use-callback-api to true to select the gRPC callback/reactor API.
The corresponding C++ option is ugrpc::server::ServerConfig::use_callback_api. Both backends support typed and generic services. User handlers and middlewares run in userver coroutine tasks in either mode.
With completion queues, grpc-server.completion-queue-count configures the server queues that clients can also use. With the callback API and registered services, clients have their own queues, configured through grpc-client-common.completion-queue-count. An empty callback server still creates fallback completion queues.
With the callback API, a server can run gRPC's socket I/O and timers on a userver task processor instead of gRPC's own threads. This backend is disabled by default. Set both grpc-server.use-callback-api and grpc-server.event-engine.enabled to true to enable it for a particular server.
The corresponding C++ option is ugrpc::server::ServerConfig::event_engine. The engine cannot be switched at runtime. It is not available in CMake builds yet: there the server refuses to start with the engine enabled.
By default the engine runs on the task processor that constructs the server. For the component that is components_manager.default_task_processor, which is main-task-processor unless configured otherwise. If the service handlers run on another task processor, set grpc-server.event-engine.task-processor to its name. That option has no effect unless the engine is enabled.
Enabling the engine for one server changes gRPC settings for the whole process:
These settings can only be applied before gRPC is first used in the process:
Set use-protobuf-arena to true on a gRPC service component to enable an arena per typed RPC. Set grpc-server.service-defaults.use-protobuf-arena to configure the default for all services; individual services can override it in either direction. It is disabled by default and supported by both server backends. Generic RPCs are unaffected.
ugrpc::server::CallContextBase::GetArena returns the call arena, or an empty reference when unavailable. Initial unary and server-streaming requests use this arena. Allocate a response with protobuf::CreateArenaMessage, fill it, and return it using ugrpc::server::Result::BorrowArenaResponse or ugrpc::server::StreamingResult::BorrowArenaResponse. The arena must outlive serialization and middleware finish hooks. The ordinary result constructors own the response, including when it was allocated on a handler-local arena.
Proto-struct final responses use the call arena automatically. Streaming grpc_proto_structs::server::Reader::Read, grpc_proto_structs::server::Writer::Write, and grpc_proto_structs::server::Writer::WriteCopy use a temporary local arena for each operation. Its allocations are released when the operation completes.
Handlers and middleware can share ownership through ugrpc::server::CallContextBase::GetArenaSharedPtr. Keep the returned shared pointer alive to retain arena messages beyond the call's lifetime.
Each method receives:
Read the documentation on gRPC streams:
On connection errors, exceptions from userver/ugrpc/server/exceptions.hpp are thrown. It is recommended not to catch them, leading to RPC interruption. You can catch exceptions for specific gRPC error codes or all at once.
TLS for gRPC server may be enabled via:
SSL has to be disabled in tests, because it requires the server to have a public domain name, which it does not in tests. In testsuite, SSL in gRPC server can be disabled manually using service config patches.
By default, gRPC server uses grpc::InsecureServerCredentials. To pass a custom credentials:
Main page: gRPC server middlewares.
Use ugrpc::server::MiddlewareBase to implement new middlewares.
For an uninterrupted handler, completion queues classify the RPC as finished when the final completion event has ok=true. The callback backend samples IsCancelled() immediately after the Finish/WriteAndFinish call returns. These calls initiate completion without waiting for OnDone. If cancellation is observed, the RPC is classified as interrupted, and OnCallFinish receives std::nullopt. Otherwise, the RPC is accounted with its final gRPC status, including error statuses. Cancellation concurrent with or after this snapshot may still leave the RPC classified as finished. Neither backend guarantees delivery of the final status to the client.
Userver doesn't compress messages by default. You can enable compression using the channel-args option on a client and a server. See static options of ugrpc::server::ServerComponent and ugrpc::client::ClientFactoryComponent components. See gRPC channel arguments docs: GRPC_COMPRESSION_CHANNEL_DEFAULT_ALGORITHM and GRPC_COMPRESSION_CHANNEL_DEFAULT_LEVEL.
See native docs about compression.
Config example:
Each gRPC call generates a span ( tracing::Span ) containing tags which are inherited by all child logs.
Additionally, if logging is activated, a separate log is generated for every gRPC request-response in grpc-server-logging and grpc-client-logging middlewares.
gRPC logs are listed below.
| Middleware component name | Key | Value |
|---|---|---|
| builtin | error | error flag, true |
| builtin | grpc_code | error code grpc::StatusCode, list |
| builtin | error_msg | error message |
| grpc-client-logging | meta_type | call name |
| grpc-client-logging | grpc_type | request or response |
| grpc-client-logging | body | logged message body |
| grpc-client-deadline-propagation | deadline_updated | error flag, true |
| grpc-client-deadline-propagation | timeout_ms | amount of time before request deadline |
| Middleware component name | Key | Value |
|---|---|---|
| builtin | error | error flag true |
| builtin | error_msg | error message |
| grpc-server-logging | meta_type | call name |
| grpc-server-logging | body | logged message body |
| grpc-server-logging | type | request or response |
| grpc-server-logging | grpc_type | request or response |
| grpc-server-deadline-propagation | received_deadline_ms | deadline |
| grpc-server-deadline-propagation | cancelled_by_deadline | true or false |
| grpc-server-congestion-control | limit | rate limit when request is throttled (tokens per second) |
| grpc-server-congestion-control | service/method | method name when request is throttled |
| grpc-server-baggage | Got baggage header: | baggage header |
The gRPC driver provides log fields hiding in request-response logs. You need to do the following:
1) Add userver/field_options.proto to your service. Generate a library from this proto file and link against it in your CMakeLists.txt.
2) Import userver/field_options.proto in your proto file.
3) Use [debug_redact = true] opposite to the filds that you want to hide. In the following example the fields password and secret_code will be hidden in the logs:
If a google.protobuf.Any cannot be expanded, the log keeps the other fields and does not write the raw value bytes: until the payload is parsed, debug_redact cannot be applied to them. An unknown type is written as {"@type":"<type_url>","@error":"unresolved_any_type"}, and a known type whose payload fails to parse as {"@type":"<type_url>","@error":"invalid_payload"}. This is a diagnostic representation for logs, not standard ProtoJSON. Link the payload type into the binary to see its fields.
grpc-core is a lower level library, its logs are forwarded to the userver default logger. In this process only error level logs get through from grpc-core to the userver default logger if the default settings are used. However, the default settings can be overridden and more verbose logging can be achieved.
To do this you need to change the value of native-log-level in the static config file in the components grpc-client-common and grpc-server:
There are 3 possible logging levels: error, info, debug. If logging level is set in several components then the most verbose logging level is used.
gRPC generic API allows you to call and accept RPCs with dynamic service and method names. The other side will see this as a normal RPC, it does not need to use generic API.
Intended mainly for use in proxies. Metadata can be used to proxy the request without parsing it.
See details in:
Full example showing the usage of both:
Based on:
Each metric has the following labels:
These are the metrics provided for each gRPC method:
An example of userver gRPC metrics.