Kest

Search

Search the documentation

Microservices

gRPC

Services from .proto files, all four call types, metadata, guards, TLS and mutual TLS.

microservices-grpc serves and calls gRPC with your own classes as messages. The .proto file is read when the server starts; there is no code generation step to run.

syntax = "proto3";
package demo;
service Greeter {
  rpc SayHello (HelloRequest) returns (HelloReply);
  rpc Count (CountRequest) returns (stream Num);
  rpc Sum (stream Num) returns (Num);
  rpc Chat (stream ChatMsg) returns (stream ChatMsg);
}
@Injectable
class GreeterService {
    @GrpcMethod fun sayHello(req: HelloRequest, meta: GrpcMetadata) = HelloReply("Hello ${req.name} trace=${meta.headers["x-trace"]}")
    @GrpcMethod fun count(req: CountRequest): Sequence<Num> = (1..req.upTo).asSequence().map { Num(it) }      // server stream
    @GrpcMethod fun sum(numbers: Sequence<Num>): Num = Num(numbers.sumOf { it.value })                          // client stream
    @GrpcMethod fun chat(messages: Iterator<ChatMsg>): Sequence<ChatMsg> = sequence { for (m in messages) yield(ChatMsg("server", "echo: ${m.text}")) }   // bidirectional
    @UseGuards(TokenGuard::class) @Role("ADMIN") @GrpcMethod fun secret(req: HelloRequest) = HelloReply("top secret")
}
 
val schema = ProtoSchema.load("greeter.proto")
val server = app.grpc(9090, schema) { usePipes(ValidationPipe::class) }

The service name defaults to the class name without Service or Controller; @GrpcMethod(service = "...", method = "...") overrides. Guards, roles, interceptors, filters and pipes run as on HTTP, with gRPC metadata as the request headers. Exceptions become gRPC statuses (NotFoundException is NOT_FOUND, a failed guard PERMISSION_DENIED, a rpc with no handler UNIMPLEMENTED).

Client

val client = GrpcClient("localhost", 9090, schema) { app.get(Codec::class) }
client.headers["authorization"] = "Bearer ..."                                   // sent with every call
val reply = client.unary<HelloReply>("Greeter", "SayHello", HelloRequest("Ann"))
client.serverStream<Num>("Greeter", "Count", CountRequest(5)).forEach { ... }    // lazy
val total = client.clientStream<Num>("Greeter", "Sum", listOf(Num(1), Num(2)))
val chat = client.bidi<ChatMsg>("Greeter", "Chat"); chat.send(ChatMsg("me", "hi")); chat.receive()

TLS and mutual TLS

val server = app.grpc(8443, schema, GrpcTls(File("server.crt"), File("server.key")))                // PEM certificate chain, PKCS#8 key
 
val client = GrpcClient("api.example.com", 8443, schema, GrpcClientTls(trustCerts = File("ca.crt"))) { codec }   // null trusts the JDK's roots
 
// mutual TLS: the server demands a client certificate signed by your CA
app.grpc(8443, schema, GrpcTls(File("server.crt"), File("server.key"), trustCerts = File("ca.crt"), requireClientCert = true))
GrpcClient(host, 8443, schema, GrpcClientTls(File("ca.crt"), File("client.crt"), File("client.key"))) { codec }

Convert a traditional key with openssl pkcs8 -topk8 -nocrypt -in server.pem -out server.key. A client that does not trust the CA, a plaintext client, and (with mutual TLS) a client with no certificate are all refused.

What is tested

All four call types, metadata, guards and statuses, and grpcurl (a Go client) calling the server. TLS and mutual TLS use real certificates from a throwaway CA built with openssl.

Not built

Reflection and health services, load balancing and name resolution, and deadlines propagated from server to client. The package reads .proto files with a Wire class that is internal to Kotlin, reached through a small Java bridge, so the Wire version is pinned; upgrading it is a deliberate step.

gRPC docs: a reference site and sandbox from your .proto files

Like trpc-ui for tRPC, and the OpenAPI site for REST: every service and RPC with its comments, field tables, a request skeleton, and a sandbox that calls the real server.

val proto = ProtoSchema.load("protos/shop.proto")
container.http(NettyHttpAdapter(8080)) {
    useGrpcDocs(proto) { title = "Shop gRPC API"; targetHost = "localhost"; targetPort = 5000 }       // http://localhost:8080/grpc-docs
}
  • // comments above a service, RPC, message or field become the documentation. GET /grpc-docs/schema.json returns the same model.
  • The sandbox sends requests through this application (browsers cannot speak gRPC) to targetHost:targetPort: unary, server-streaming (cut after maxStreamMessages) and client-streaming calls (a list of messages), with metadata such as authorization. Bidirectional streams are documented but cannot be called.
  • Without targetHost the page is documentation only and no proxy endpoint exists. In production set sandbox = false or authorize = { request -> ... }: the sandbox lets whoever opens the page call your gRPC server.