gRPC
gRPC calls methods on another program: its messages are protocol buffers, sent over HTTP/2, and a .proto file describes the service. luma proto writes a client and a server for each service in it:
syntax = "proto3";
package shop;
message OrderRequest { int32 id = 1; }
message Order { int32 id = 1; string item = 2; }
message Filter { int32 min_id = 1; }
service Shop {
rpc GetOrder(OrderRequest) returns (Order); // one message there, one back
rpc Watch(Filter) returns (stream Order); // the server streams
rpc Upload(stream Order) returns (Summary); // the client streams
rpc Chat(stream Msg) returns (stream Msg); // both ways
}luma proto shop.proto writes shop.luma: the messages, and for the service ShopClient, the trait ShopServer and shop_routes.
Client
import "shop"
conn: grpc.conn = grpc.connect("localhost:50051")
conn.header("authorization", "Bearer abc123")
shop_c: shop.ShopClient = shop.ShopClient { conn: conn }
order: shop.Order = shop_c.get_order(shop.OrderRequest { id: 7 })
print(order.item)
w: shop.Shop_Watch = shop_c.watch(shop.Filter { min_id: 1 })
while true {
o: ?shop.Order = w.next()
if o == nil {
stop
}
print(o.id)
}grpc.connect(address):"host:port"talks HTTP/2 without encryption (what gRPC calls insecure, for services inside a network);"https://host"(port 443, orhttps://host:port) over TLS, its certificate checked as for https. It connects at the first call, and again if the connection closed. Calls at the same time (fromwaitorspawn) share the connection.- A method is its rpc’s name in snake case:
GetOrderisget_order. A unary one gives its answer; one withstreamgives a reader whosenext()gives each message, thennil(close()stops early). - When the client streams, the method gives a call to
sendon, one message at a time, right away:
up: shop.Shop_Upload = shop_c.upload()
up.send(shop.Order { id: 1 })
up.send(shop.Order { id: 2 })
total: shop.Summary = up.end() // done sending: the answer
chat: shop.Shop_Chat = shop_c.chat()
chat.send(shop.Msg { text: "hi" })
reply: ?shop.Msg = chat.next() // what the server sends, nil at the end
chat.end() // done sending; the server may still sendSending and reading can take turns in one coroutine, or happen in two (a spawned one reading while the program sends). close() cancels the call. A send after the server has answered raises its status (or CANCELLED).
conn.header(name, value)adds metadata to every call (an API key, a token).conn.timeout(seconds)gives each call a deadline: longer raisesDEADLINE_EXCEEDED.
Server
The trait ShopServer has a method for each rpc. An obj that is it answers them; shop_routes makes its routes for http.server, which speaks HTTP/2 to gRPC clients by itself (h2c on plain connections, h2 over https):
import "shop"
obj MyShop: shop.ShopServer {
fn get_order(req: shop.OrderRequest): shop.Order {
if req.id == 0 {
throw error(grpc.NOT_FOUND, "no order 0")
}
return shop.Order { id: req.id, item: "tea" }
}
fn watch(req: shop.Filter, out: shop.Shop_WatchOut) {
(1..3).walk(i) {
out.send(shop.Order { id: i }) // sent right away
}
}
}
http.serve(50051, shop.shop_routes(MyShop {}))- When the client streams, a method reads its messages with
in.next()(nilwhen the client is done), and answers when it returns, or sends without.send(...)as it goes:
fn upload(in: shop.Shop_UploadIn): shop.Summary {
n: int = 0
while true {
o: ?shop.Order = in.next()
if o == nil {
stop
}
n = n + 1
}
return shop.Summary { count: n }
}
fn chat(in: shop.Shop_ChatIn, out: shop.Shop_ChatOut) {
while true {
m: ?shop.Msg = in.next()
if m == nil {
stop
}
out.send(shop.Msg { text: "echo: ${m.text}" })
}
}A method can answer (or raise a status) before the client is done: the client is told to stop sending.
- They are routes like any other: a server can have gRPC methods, a REST API and web pages side by side (
shop.shop_routes(...)and other routes in one list), and middleware runs before each call: a check ofreq.headers["authorization"]that answershttp.status(401, ...)isUNAUTHENTICATEDto the client. - A method that doesn’t exist on the server answers
UNIMPLEMENTED.
Health checks
Kubernetes, load balancers and grpc_health_probe ask a gRPC server whether it is serving, with gRPC’s standard health service. grpc.health(routes) adds it to a server’s routes, and says what to answer:
routes: [http.route] = shop.shop_routes(MyShop {})
health: grpc.health = grpc.health(routes)
health.down("shop.Shop") // starting: not ready yet
...
health.up("shop.Shop") // ready
http.serve(50051, routes)up(service)anddown(service)set a service’s status (by its full name,shop.Shop);""is the server as a whole, which is serving unlessdown("")says otherwise.CheckanswersSERVINGorNOT_SERVING, andNOT_FOUNDfor a service it was never told about.Watchsends the status, then each change, as long as the client listens.
Reflection
Tools like grpcurl, Postman and Evans can call a server without having its .proto: they ask the server, with gRPC’s reflection service. grpc.reflection(routes, files) adds it:
grpc.reflection(routes, shop.proto_files())grpcurl -plaintext localhost:50051 list
grpcurl -plaintext -d '{"id": 7}' localhost:50051 shop.Shop/GetOrderproto_files()is written byluma proto: the descriptors of the file and the files it imports (the.protoin the compiled form tools read). With several services, give each one’s:files[] = ....- Add it after the other services: it lists the gRPC services the routes have at that moment (health’s too, which it can describe).
- It shows the whole API to anyone who can connect: add it on purpose, often only in development.
- Both versions tools ask for:
grpc.reflection.v1and the olderv1alpha.
Errors and status
A call that fails has a status: NOT_FOUND, PERMISSION_DENIED, … In Luma it is error 1000 + its code (the codes below 100 are Luma’s own), and grpc.NOT_FOUND and the others name them:
err: error = nil
try err {
o: shop.Order = shop_c.get_order(shop.OrderRequest { id: 0 })
}
if err != nil && err.code == grpc.NOT_FOUND {
print(err.message) // NOT_FOUND: no order 0
}| Name | Code | Means |
|---|---|---|
grpc.CANCELLED | 1001 | the call was cancelled |
grpc.INVALID_ARGUMENT | 1003 | the request is wrong (also: a message that isn’t valid protobuf) |
grpc.DEADLINE_EXCEEDED | 1004 | the deadline (timeout) passed |
grpc.NOT_FOUND | 1005 | what was asked for isn’t there |
grpc.ALREADY_EXISTS | 1006 | it is there already |
grpc.PERMISSION_DENIED | 1007 | not allowed |
grpc.UNIMPLEMENTED | 1012 | the server has no such method |
grpc.INTERNAL | 1013 | the server failed |
grpc.UNAVAILABLE | 1014 | the server can’t be reached |
grpc.UNAUTHENTICATED | 1016 | who is calling isn’t known |
The others: UNKNOWN 1002, RESOURCE_EXHAUSTED 1008, FAILED_PRECONDITION 1009, ABORTED 1010, OUT_OF_RANGE 1011, DATA_LOSS 1015 (grpc.OK is 1000).
On a server, a method answers with a status by raising its error: throw error(grpc.PERMISSION_DENIED, "admins only"). Any other error is INTERNAL, with its message, and is reported on the server’s stderr as an HTTP handler’s is.
Details
- It is gRPC as other languages speak it: Luma’s clients call servers written with Go’s (and others’) gRPC, and theirs call Luma’s.
- Compression:
conn.compress()makes a client send its messages gzipped (grpc-encoding: gzip); a server answers a gzipped call in gzip. Both take gzipped messages from others (Go’sgrpc.UseCompressor(gzip.Name)); another compression is answeredUNIMPLEMENTED. - Calls are answered from their headers on, so middleware sees the headers but not the messages.
- Under the generated code are
grpc.conn(call(path, data),stream(path, data),pipe(path)),grpc.reader,grpc.senderandgrpc.pipe, andgrpc.unary,grpc.stream,grpc.collectandgrpc.bidi, which make routes; they work with the message bytes.