A gRPC server and client over HTTP/2: unary and streaming calls, metadata and status codes.
import grpc
gRPC is a way of calling a remote procedure that runs over HTTP/2, and it is common in microservices. On the server side you register each method under its path, like /demo.Greeter/SayHello; the method routine reads the client's message with Recv, answers with Send and ends it with SetStatus or Fail.
On the client side, UnaryCall is a plain request, and for streams you use StartCall, SendMessage, RecvMessage and FinishCall. Messages are bytes; you usually build them with protobuf.
Choose gRPC when the other side already speaks it, or when you want typed messages and streams between services. For a simpler protocol that also works over plain TCP, standard input and output or an HTTP route, see rpc (JSON-RPC and MessagePack-RPC).
Limits of the server side to know before you build on it:
•
The server handles one connection at a time, and on that connection one call at a time: each method runs to the end before the next stream is read. A long streaming call holds up every other caller. That suits internal tools, tests and light services.
•
The server speaks plaintext HTTP/2 (h2c) only. To accept TLS, put a proxy such as nginx or Envoy in front. The client can use TLS with DialTLS.
•
The connection state lives in one global, so ServeConn must not run in several threads at once.
A unary call with protobuf messages
Real gRPC services exchange protobuf messages, not plain strings. A message is a list of fields, each written as a tag (field number and wire type) followed by the value; encoding.protobuf writes and reads them. The example defines a Users.Get method that takes a message with the user id in field 1 and answers with a user message: the id in field 1 and the name in field 2. Server and client run in one program, with the server on a port the system picks.
grpc-guide-protobuf.salam
import grpc
import encoding.protobuf
import compress
import sync
mut server := grpc.NewServer(0)
mut ready := sync.NewWaitGroup()
funcencode_user(id: int, name: str): compress.ByteBuf:
mut b := compress.NewByteBuf()
protobuf.WriteTag(b, 1, protobuf.WT_VARINT)
protobuf.WriteVarint(b, id asu64)
protobuf.WriteTag(b, 2, protobuf.WT_LEN)
protobuf.WriteLenPrefixedStr(b, name)
ret b
endfuncget_user(c: i64):
mut ok := false
req := grpc.Recv(c, ok)
mut r := compress.ReaderFromBuf(req)
mut field := 0mut wire := 0mut id := 0try:
protobuf.ReadTag(r, field, wire)
id = protobuf.ReadVarint(r) asintcatch e:
grpc.Fail(c, grpc.GRPC_INVALID_ARGUMENT, e.ToStr())
retendif field != 1:
grpc.Fail(c, grpc.GRPC_INVALID_ARGUMENT, "expected field 1 with the user id")
retendif id != 7:
grpc.Fail(c, grpc.GRPC_NOT_FOUND, "no user " + id)
retendmut reply := encode_user(7, "Maryam")
_ := grpc.Send(c, reply)
compress.BufFree(reply)
grpc.SetStatus(c, grpc.GRPC_OK, "")
endfuncrun_server():
_ := grpc.Listen(server)
sync.Done(ready)
_ := grpc.ServeCount(server, 1)
endfuncask(ch &: grpc.Channel, id: int) throw:
mut req := compress.NewByteBuf()
protobuf.WriteTag(req, 1, protobuf.WT_VARINT)
protobuf.WriteVarint(req, id asu64)
mut st := grpc.Status {}
answer := grpc.UnaryCall(ch, "/users.Users/Get", req, grpc.NewMetadata(), st)
compress.BufFree(req)
ifnot grpc.StatusOk(st):
println"user", id, "->", grpc.StatusString(st)
retendmut r := compress.ReaderFromBuf(answer)
mut field := 0mut wire := 0try protobuf.ReadTag(r, field, wire)
uid := try protobuf.ReadVarint(r)
try protobuf.ReadTag(r, field, wire)
println"user", uid, "is", try protobuf.ReadLenPrefixedStr(r)
endfuncmain throw:
grpc.RegisterMethod(grpc.MethodPath("users.Users", "Get"), get_user)
sync.Add(ready, 1)
t := spawn(run_server)
sync.Wait(ready)
mut ch := grpc.Dial("127.0.0.1", grpc.Port(server))
grpc.SetTimeout(ch, 5000)
tryask(ch, 7)
tryask(ch, 8)
grpc.CloseChannel(ch)
join(t)
grpc.StopServer(server)
end
Output
user 7 is Maryam
user 8 -> NOT_FOUND: no user 8
MethodPath builds the path /users.Users/Get from the service and method names, which must match what the other side's .proto file says. When the request is wrong or the record does not exist, the method calls Fail with a status code instead of sending a message. The client checks StatusOk before it reads the answer, and StatusString gives a one line description such as NOT_FOUND: no user 8.
Writing the fields by hand is fine for small messages. For a larger API, protobuf.GenerateWithServices turns a .proto file into Salam structs with Marshal and Unmarshal functions plus the service code, so the field numbers live in one place.
Tokens in metadata and error status codes
gRPC sends credentials and other per call values as metadata, the gRPC name for HTTP/2 headers. The client adds an entry with MDAdd, and the method reads it with MDGet(CallMetadata(c), ...). Choose the status code by what went wrong: GRPC_UNAUTHENTICATED when no valid credential came, GRPC_PERMISSION_DENIED when the caller is known but not allowed.
Metadata keys are lower case. A value that is binary must use a key ending in -bin and is added with MDAddBinary. Clients often retry automatically on GRPC_UNAVAILABLE but never on an authentication error, so using the right code matters to the caller, not just to the logs.
Client streaming: many messages in, one answer out
A method registered with RegisterStreamMethod(path, fn, true, false) receives a stream from the client and answers once, which suits uploads and batches of readings. The method calls Recv in a loop until ok turns false, which happens when the client has sent its last message. On the client side, StartCall opens the call, SendMessage sends each message and its last argument marks the final one, then RecvMessage reads the answer and FinishCall returns the status.
grpc-guide-stream.salam
import grpc
import compress
import sync
mut server := grpc.NewServer(0)
mut ready := sync.NewWaitGroup()
functotal(c: i64):
mut sum := 0mut count := 0mut more := trueuntil more:
mut ok := false
reading := grpc.RecvStr(c, ok)
ifnot ok:
more = falseelse:
sum += reading.ToInt()
count++
endend
_ := grpc.SendStr(c, "" + count + " readings, total " + sum)
grpc.SetStatus(c, grpc.GRPC_OK, "")
endfuncrun_server():
_ := grpc.Listen(server)
sync.Done(ready)
_ := grpc.ServeCount(server, 1)
endfuncmain:
grpc.RegisterStreamMethod("/meter.Meter/Upload", total, true, false)
sync.Add(ready, 1)
t := spawn(run_server)
sync.Wait(ready)
mut ch := grpc.Dial("127.0.0.1", grpc.Port(server))
grpc.SetTimeout(ch, 5000)
call := grpc.StartCall(ch, "/meter.Meter/Upload", grpc.NewMetadata())
readings := ["12", "7", "30", "1"]
each i, r in readings:
mut msg := compress.BufFromStr(r)
_ := grpc.SendMessage(ch, call, msg, i == len(readings) - 1)
compress.BufFree(msg)
endmut ok := false
answer := grpc.RecvMessage(ch, call, ok)
println compress.BufToStrUnsafe(answer)
println grpc.StatusString(grpc.FinishCall(ch, call))
grpc.CloseChannel(ch)
join(t)
grpc.StopServer(server)
end
Output
4 readings, total 50
OK
If you do not know in advance which message is the last, send every message with false and call CloseSend at the end. For the other direction, a server stream, register with false, true, call Send several times in the method and read on the client with RecvMessage until ok is false.
Which call shape for which job
Shape
Register with
Client calls
One request, one answer
RegisterMethod
UnaryCall, or UnaryCallStr for text
Many requests, one answer
RegisterStreamMethod(path, fn, true, false)
StartCall, SendMessage, RecvMessage, FinishCall
One request, many answers
RegisterStreamMethod(path, fn, false, true)
StartCall, SendMessage with true, then RecvMessage in a loop
Both directions
RegisterStreamMethod(path, fn, true, true)
the same functions, sending and reading in turn
To reach a public service over TLS, open the channel with DialTLS(host, 443); everything else stays the same. SetGzip compresses the messages the client sends.