The Limen Book Playground limen-lang.org
Chapter 17

gRPC

gRPC is how many services inside a company talk to each other, and how a lot of infrastructure exposes its API: etcd, container runtimes, most cloud SDKs underneath. A call is an HTTP/2 request whose body is a protobuf message, and whose answer is another message followed by a status. Limen has all three layers in the standard library, written in Limen: protobuf for the messages, http2 for the transport, and grpc on top. This chapter builds a few small services with them, a server and a client in one program each, the way chapter 14 did for HTTP.

Messages

A protobuf message is a struct whose fields each carry a number, written after the type with @field:

use hex
use protobuf

pub enum Shelf {
    Unsorted,
    Fiction,
    Science,
}

pub struct Book {
    id: Int @field(1),
    title: Str @field(2),
    tags: List[Str] @field(3),
    shelf: Shelf @field(4),
    note: Option[Str] @field(5),
}

// An older version of the message, without the shelf and the note.
pub struct OldBook {
    id: Int @field(1),
    title: Str @field(2),
}

fn main(root: Root) -> Result[(), Str] {
    let b = Book { id: 7, title: "Dune", tags: ["sf", "classic"], shelf: Fiction, note: None }
    let wire = protobuf.encode(b)
    root.stdout.print("{wire.len()} bytes: {hex.encode(wire)}")

    let back: Book = protobuf.decode(wire)?
    root.stdout.print("back: {back.title}, {back.tags}, {back.shelf}, {back.note}")

    // an old reader skips the fields it doesn't know
    let old: OldBook = protobuf.decode(wire)?
    root.stdout.print("old reader: {old.id} {old.title}")

    // a field left out reads as its zero value
    let empty: Book = protobuf.decode(bytes([]))?
    root.stdout.print("empty: id {empty.id}, title \"{empty.title}\", shelf {empty.shelf}")

    // bytes that don't fit the type are an error that says where
    let bad: Result[Book, Str] = protobuf.decode(bytes([16, 1]))
    root.stdout.print("bad: {bad.map(|x| x.id)}")
    Ok(())
}
Listing 17-1: A message, encoded and decoded examples/ch17-01-messages/main.lmn
$ limen run main.lmn
23 bytes: 0807120444756e651a0273661a07636c61737369632001
back: Dune, ["sf", "classic"], Fiction, None
old reader: 7 Dune
empty: id 0, title "", shelf Unsorted
bad: Err("`title`: expected length-delimited bytes, found a varint")

There's no .proto compiler. You write the struct yourself, numbers and all, and the compiler writes the conversion for each type you encode or decode, as it does for json. The struct above is the same message as this .proto:

syntax = "proto3";

enum Shelf {
  UNSORTED = 0;
  FICTION = 1;
  SCIENCE = 2;
}

message Book {
  int64 id = 1;
  string title = 2;
  repeated string tags = 3;
  Shelf shelf = 4;
  optional string note = 5;
}

Int is int64, Str is string, List[T] is repeated T, Option[T] is optional T, and an enum without payloads is a protobuf enum, numbered by position unless its variants have @field numbers of their own. A nested struct with numbered fields is a nested message. The rest of the table is in the protobuf section of the specification: the fixed-size integers, Float, Bytes, maps and oneof.

The bytes are the ones protobuf's own libraries write for the same message. Read the hex in pairs: 08 07 is field 1 with the value 7, 12 04 starts field 2, four bytes long, Dune; then two 1a fields for the tags and 20 01 for the shelf. The note is None, so nothing is written for it.

The numbers, not the names, are what goes over the wire, and that's what lets a message change over time. OldBook is the message as an older program knew it, before shelves and notes. It reads the new bytes without complaint, skipping fields 3 to 5, and a new program reading old bytes gets zero values for the fields it doesn't find: 0, "", the first variant. That's why the first variant of an enum is usually a "not set" value like Unsorted. So once a number is in use, keep it for that field for good, and give a new field a new number.

When the bytes don't fit the type, decode says where: field 2 was meant to hold a string, and it held a number.

A unary call

Most gRPC methods are unary: one message in, one message out. Here are a server and a client for the classic greeter:

use grpc
use http
use http2
use protobuf

pub struct HelloRequest {
    name: Str @field(1),
}

pub struct HelloReply {
    message: Str @field(1),
}

// The server's side of SayHello: bytes in, bytes out.
fn say_hello(req: Bytes, md: List[http.Header]) -> Result[Bytes, grpc.Status] {
    let r: HelloRequest = grpc.decode_request(protobuf.decode(req))?
    Ok(protobuf.encode(HelloReply { message: "hello, {r.name}" }))
}

fn client(net: Net, address: Str) -> Result[List[Str], grpc.Status] {
    let c = grpc.connect_plain(net, address).map_error(|e| grpc.fail(grpc.Unavailable, e.message()))?
    defer c.close()
    let mut lines: List[Str] = []
    for name in ["Ada", "Grace"] {
        let r: HelloReply = c.call("/helloworld.Greeter/SayHello", HelloRequest { name })?
        lines.push(r.message)
    }
    Ok(lines)
}

fn main(root: Root) -> Result[(), IoError] {
    let l = root.listen.on("127.0.0.1:0")?
    let address = "127.0.0.1:{l.port()}"
    let net = root.net.only("127.0.0.1")
    let methods = [grpc.unary("/helloworld.Greeter/SayHello", say_hello)]
    let server = http2.server(root.clock)
    let results = group g {
        g.go(|| {
            let _ = grpc.serve_forever(server, l, methods)
        })
        g.go(|| {
            // closing the listener stops the server once the client is done
            defer l.close()
            client(net, address)
        })
    }
    match results[0] {
        Ok(lines) => {
            for line in lines {
                root.stdout.print(line)
            }
        },
        Err(e) => root.stdout.print(e.message()),
    }
    Ok(())
}
Listing 17-2: A greeter, served and called over loopback examples/ch17-02-unary/main.lmn
$ limen run main.lmn --grant listen=127.0.0.1:0 --grant net=127.0.0.1
hello, Ada
hello, Grace

A method is named by a path, /package.Service/Method, the same path a .proto's service Greeter { rpc SayHello ... } gives it in any language, so a Limen client can call a Go server and the other way round.

On the server, grpc.unary(path, f) makes a grpc.Method from a function that gets the request's bytes and its metadata, and returns the response's bytes or a status. The function decodes and encodes itself, which keeps the server's types out of the server's machinery. grpc.decode_request turns a request that doesn't decode into an INVALID_ARGUMENT status, which is what the client should hear when it sends garbage. say_hello holds no capability, like an HTTP handler: whatever a request contains, it can only compute an answer.

grpc.serve_forever takes an http2.Server, which holds the time limits for each connection and so needs the Clock, a listener, and the list of methods. It serves each connection in a task of its own, and each call in another, until the listener closes. Here the client closes it when it's done, so the server's task ends and the group with it.

On the client, grpc.connect_plain(net, address) opens one HTTP/2 connection without TLS (h2c), the way services inside a cluster or tests talk. c.call(path, req) sends one request on it and waits for the answer. Calls from many tasks can share one client, each on a stream of its own.

call is generic in both message types, and the compiler writes the conversion for the pair it's used with, so it needs to know them where you call it. Req comes from the argument. Resp comes from what you do with the result: let r: HelloReply = c.call(...)? says it. Leave the annotation off, and the compiler stops with E0212 and shows you the line to write, rather than guessing.

connect_plain fails with an IoError, and call with a grpc.Status, so client turns the first into the second with map_error to use ? on both. UNAVAILABLE is the code gRPC uses for a server that can't be reached.

Errors

Every call ends with a status. OK comes with the response; anything else is Err(grpc.Status), with a code and a message:

use grpc
use http
use http2
use protobuf

pub struct GetBook {
    id: Int @field(1),
}

pub struct Book {
    id: Int @field(1),
    title: Str @field(2),
}

fn get_book(req: Bytes, md: List[http.Header]) -> Result[Bytes, grpc.Status] {
    let r: GetBook = grpc.decode_request(protobuf.decode(req))?
    if r.id <= 0 {
        return Err(grpc.fail(grpc.InvalidArgument, "an id is positive, not {r.id}"))
    }
    let titles = map([(1, "Dune"), (2, "Solaris")])
    match titles.get(r.id) {
        Some(title) => Ok(protobuf.encode(Book { id: r.id, title })),
        None => Err(grpc.fail(grpc.NotFound, "no book {r.id}")),
    }
}

fn describe(r: Result[Book, grpc.Status]) -> Str {
    match r {
        Ok(b) => "found {b.title}",
        Err(e) => match e.code {
            grpc.NotFound => "not there, so offer to order it",
            grpc.InvalidArgument => "our bug: {e.message}",
            _ => "{e.code.name()} ({e.code.number()}): try again later",
        },
    }
}

fn client(net: Net, address: Str) -> Result[List[Str], IoError] {
    let c = grpc.connect_plain(net, address)?
    defer c.close()
    let mut lines: List[Str] = []
    for id in [2, 9, -1] {
        let r: Result[Book, grpc.Status] = c.call("/library.Shelf/GetBook", GetBook { id })
        lines.push("{id}: {describe(r)}")
    }
    // a method the server doesn't have
    let r: Result[Book, grpc.Status] = c.call("/library.Shelf/Burn", GetBook { id: 1 })
    lines.push("Burn: {describe(r)}")
    match r {
        Ok(_) => {},
        Err(e) => lines.push("as an Error: {e.message()}"),
    }
    Ok(lines)
}

fn main(root: Root) -> Result[(), IoError] {
    let l = root.listen.on("127.0.0.1:0")?
    let address = "127.0.0.1:{l.port()}"
    let net = root.net.only("127.0.0.1")
    let server = http2.server(root.clock)
    let results = group g {
        g.go(|| {
            let _ = grpc.serve_forever(server, l, [grpc.unary("/library.Shelf/GetBook", get_book)])
        })
        g.go(|| {
            defer l.close()
            client(net, address)
        })
    }
    for line in results[0]? {
        root.stdout.print(line)
    }
    Ok(())
}
Listing 17-3: Statuses from the server, handled by code on the client examples/ch17-03-errors/main.lmn
$ limen run main.lmn --grant listen=127.0.0.1:0 --grant net=127.0.0.1
2: found Solaris
9: not there, so offer to order it
-1: our bug: an id is positive, not -1
Burn: UNIMPLEMENTED (12): try again later
as an Error: grpc: UNIMPLEMENTED: unknown method /library.Shelf/Burn

grpc.Code is an enum with gRPC's seventeen codes, and they mean the same thing in every language, so pick the one that tells the caller what to do. NOT_FOUND says the thing isn't there; INVALID_ARGUMENT says the request was wrong and sending it again won't help; UNAVAILABLE says try again later. A server returns one with Err(grpc.fail(code, message)), and the client matches on it like any enum. Outside the module the variants are written grpc.NotFound, and code.name() and code.number() give the name and number gRPC uses on the wire.

The server doesn't need a method for every path. A call to a path no method has ends UNIMPLEMENTED with the path in its message, which is what Burn got.

A Status is an Error, in the sense of chapter 8: e.message() is the whole story, grpc: UNIMPLEMENTED: unknown method ..., ready for a log, while the message field is the server's text alone. The client sees exactly what the server wrote, percent-encoding and all handled for you.

Deadlines and metadata

A call that waits for ever holds a task for ever. gRPC's answer is a deadline that travels with the call: the client says how long it will wait, and the server can see it.

use grpc
use http
use http2
use protobuf

pub struct Empty {}

pub struct Note {
    text: Str @field(1),
}

fn methods(clock: Clock) -> List[grpc.Method] {
    [
        // reports what the call carried: a header and the deadline
        grpc.method("/demo.Info/Report", |mut c: grpc.ServerCall| {
            let user = c.header("x-user") ?? "nobody"
            c.send(protobuf.encode(Note { text: "user {user}, deadline {c.deadline_ms()}" }))
        }),
        // takes a second, whatever the client asked for
        grpc.method("/demo.Info/Slow", |mut c: grpc.ServerCall| {
            clock.sleep(1000)
            c.send(protobuf.encode(Note { text: "done at last" }))
        }),
    ]
}

fn show(r: Result[Note, grpc.Status]) -> Str {
    match r {
        Ok(n) => n.text,
        Err(e) => e.message(),
    }
}

fn client(net: Net, clock: Clock, address: Str) -> Result[List[Str], IoError] {
    let c = grpc.connect_plain(net, address)?
    defer c.close()
    let md = [http.Header { name: "x-user", value: "ada" }]
    let plain: Result[Note, grpc.Status] = c.call("/demo.Info/Report", Empty {}, md)
    let timed: Result[Note, grpc.Status] = c.call_within(clock, 5000, "/demo.Info/Report", Empty {}, md)
    let slow: Result[Note, grpc.Status] = c.call_within(clock, 100, "/demo.Info/Slow", Empty {})
    let bad: Result[Note, grpc.Status] = c.call("/demo.Info/Report", Empty {}, [http.Header { name: "grpc-timeout", value: "1S" }])
    Ok(["call: {show(plain)}", "call_within 5000: {show(timed)}", "call_within 100: {show(slow)}", "reserved name: {show(bad)}"])
}

fn main(root: Root) -> Result[(), IoError] {
    let l = root.listen.on("127.0.0.1:0")?
    let address = "127.0.0.1:{l.port()}"
    let net = root.net.only("127.0.0.1")
    let clock = root.clock
    let results = group g {
        g.go(|| {
            let _ = grpc.serve_forever(http2.server(clock), l, methods(clock))
        })
        g.go(|| {
            defer l.close()
            client(net, clock, address)
        })
    }
    for line in results[0]? {
        root.stdout.print(line)
    }
    Ok(())
}
Listing 17-4: Metadata and deadlines, seen from both sides examples/ch17-04-deadlines/main.lmn
$ limen run main.lmn --grant listen=127.0.0.1:0 --grant net=127.0.0.1
call: user ada, deadline None
call_within 5000: user ada, deadline Some(5000)
call_within 100: grpc: DEADLINE_EXCEEDED: the deadline of 100 ms passed
reserved name: grpc: INTERNAL: `grpc-timeout` is not metadata a call may send

Metadata is a list of http.Headers sent with the request, as the third argument of call. It's how a call carries what isn't part of the message: an authentication token, a request id for tracing. On the server, c.header(name) finds one by name in any case, and grpc.unary's function gets the whole list as its second argument. Names that belong to gRPC or HTTP/2 itself, such as grpc-timeout or content-type, are refused before anything is sent, as the last line shows: a client can't forge a deadline or break the framing by accident.

c.call_within(clock, ms, path, req) is call with a deadline. The server is told it, and c.deadline_ms() on a grpc.ServerCall reads it back: None for the plain call, Some(5000) for the other. A server can use it to give up early on work that can't finish in time, or pass what's left on to the services it calls itself.

If the answer hasn't come when the time runs out, the call ends DEADLINE_EXCEEDED and its stream is reset, so the server learns the client has gone. The connection stays open for other calls. Slow takes a second; the client waited 100 ms. The deadline is measured on the Clock you pass, so code that sets one takes a Clock, and a test can run it on virtual time as chapter 11 showed.

The methods here use grpc.method rather than grpc.unary, because deadline_ms belongs to the ServerCall that method hands over. That's the general form, which the next section is about.

Streaming

A unary call is one message each way. gRPC also lets either side send a stream of them: the server (a list of results, a feed of updates), the client (an upload, a batch of measurements), or both at once.

use grpc
use http
use http2
use protobuf

pub struct Num {
    n: Int @field(1),
}

pub struct Line {
    text: Str @field(1),
}

fn num(b: Bytes) -> Result[Num, grpc.Status] {
    grpc.decode_request(protobuf.decode(b))
}

fn methods() -> List[grpc.Method] {
    [
        // server streaming: one request, then n numbers
        grpc.method("/demo.Nums/Count", |mut c: grpc.ServerCall| {
            let x = match c.recv()? {
                Some(b) => num(b)?,
                None => {
                    return Err(grpc.fail(grpc.InvalidArgument, "no request"))
                },
            }
            for i in 1..<x.n + 1 {
                c.send(protobuf.encode(Num { n: i }))?
            }
            Ok(())
        }),
        // client streaming: numbers until the client stops, then their sum
        grpc.method("/demo.Nums/Sum", |mut c: grpc.ServerCall| {
            let mut total = 0
            while true {
                match c.recv()? {
                    Some(b) => {
                        total = total + (num(b)?).n
                    },
                    None => { break },
                }
            }
            c.send(protobuf.encode(Num { n: total }))
        }),
        // both ways: each line back in capitals, with a header first
        grpc.method("/demo.Nums/Shout", |mut c: grpc.ServerCall| {
            c.send_headers([http.Header { name: "x-mood", value: "loud" }])?
            while true {
                match c.recv()? {
                    Some(b) => {
                        let l: Line = grpc.decode_request(protobuf.decode(b))?
                        c.send(protobuf.encode(Line { text: l.text.to_upper() }))?
                    },
                    None => { break },
                }
            }
            Ok(())
        }),
    ]
}

// Every number the server sends, until it ends the call.
fn read_nums(mut s: grpc.Stream) -> Result[List[Int], grpc.Status] {
    let mut got: List[Int] = []
    while true {
        match s.recv()? {
            Some(b) => got.push((num(b)?).n),
            None => { break },
        }
    }
    Ok(got)
}

fn client(net: Net, address: Str) -> Result[List[Str], grpc.Status] {
    let c = grpc.connect_plain(net, address).map_error(|e| grpc.fail(grpc.Unavailable, e.message()))?
    defer c.close()
    let mut lines: List[Str] = []

    let mut count = c.open("/demo.Nums/Count")?
    defer count.end()
    count.send(protobuf.encode(Num { n: 5 }))?
    count.close_send()?
    lines.push("count: {read_nums(mut count)?}")

    let mut sum = c.open("/demo.Nums/Sum")?
    defer sum.end()
    for i in 1..<101 {
        sum.send(protobuf.encode(Num { n: i }))?
    }
    sum.close_send()?
    lines.push("sum: {read_nums(mut sum)?}")

    let mut shout = c.open("/demo.Nums/Shout")?
    defer shout.end()
    for word in ["one", "two", "three"] {
        shout.send(protobuf.encode(Line { text: word }))?
        match shout.recv()? {
            Some(b) => {
                let l: Line = grpc.decode_request(protobuf.decode(b))?
                lines.push("shout: {word} -> {l.text}")
            },
            None => lines.push("shout: the server stopped early"),
        }
    }
    shout.close_send()?
    lines.push("shout ends: {shout.recv()?}, mood {http.find_header(shout.headers(), "x-mood")}")
    Ok(lines)
}

fn main(root: Root) -> Result[(), IoError] {
    let l = root.listen.on("127.0.0.1:0")?
    let address = "127.0.0.1:{l.port()}"
    let net = root.net.only("127.0.0.1")
    let server = http2.server(root.clock)
    let results = group g {
        g.go(|| {
            let _ = grpc.serve_forever(server, l, methods())
        })
        g.go(|| {
            defer l.close()
            client(net, address)
        })
    }
    match results[0] {
        Ok(lines) => {
            for line in lines {
                root.stdout.print(line)
            }
        },
        Err(e) => root.stdout.print(e.message()),
    }
    Ok(())
}
Listing 17-5: Server, client and bidirectional streaming examples/ch17-05-streaming/main.lmn
$ limen run main.lmn --grant listen=127.0.0.1:0 --grant net=127.0.0.1
count: [1, 2, 3, 4, 5]
sum: [5050]
shout: one -> ONE
shout: two -> TWO
shout: three -> THREE
shout ends: None, mood Some("loud")

On the server, grpc.method(path, run) gives run a mut grpc.ServerCall for the whole call. c.recv() is the client's next message, or None once it has sent its last; c.send(msg) sends one back. When run returns, the call ends with its status: OK for Ok(()), or the status of the Err. The three methods are three loops: Count reads one request and sends several answers, Sum reads until None and sends one, and Shout answers each message as it comes.

On the client, c.open(path) starts a streaming call and returns a grpc.Stream. It has the same three moves: send, close_send to say there are no more, and recv, which gives each message the server sends and then None once the server has ended the call with OK. Any other status comes out of recv as an Err, read the way call reads one. end() is done with the stream, cancelling the call if the server is still going, so the defer after each open makes sure no call is left running however the function returns.

Stream messages are Bytes, encoded and decoded by hand. The compiler can't yet tie a stream to its message types the way it does for call, so protobuf.encode and protobuf.decode do it at each end, and grpc.decode_request gives the usual INVALID_ARGUMENT for a message that doesn't fit.

The bidirectional call here is in lock step: the client sends a line, waits for its answer, then sends the next. That keeps the output in a fixed order. A chat-like stream would send from one task and receive in another, and then the order of what arrives depends on timing, which is fine for a program and not for a book.

Metadata can go the other way too. c.send_headers(metadata) sends the response's headers before the first message, and the client reads them with s.headers(); s.trailers() gives what came after the last message. send sends plain headers if you never called send_headers.

Serving for real

The examples so far listened on a loopback port and spoke h2c. A real service wants TLS, and a real client wants to reach only the services it's meant to:

use grpc
use http
use http2
use protobuf

pub struct HelloRequest {
    name: Str @field(1),
}

pub struct HelloReply {
    message: Str @field(1),
}

fn say_hello(req: Bytes, md: List[http.Header]) -> Result[Bytes, grpc.Status] {
    let r: HelloRequest = grpc.decode_request(protobuf.decode(req))?
    Ok(protobuf.encode(HelloReply { message: "hello, {r.name}" }))
}

// The server: TLS with a certificate read through a read-only Fs, h2
// agreed by ALPN, and time limits from the clock.
fn serve(listen: Listen, certs: Fs, clock: Clock) -> Result[(), IoError] {
    let cert = certs.read("cert.pem")?
    let key = certs.read("key.pem")?
    let l = (listen.offering(["h2"])?).on_tls("0.0.0.0:8443", cert, key)?
    Err(grpc.serve_forever(http2.server(clock), l, [grpc.unary("/helloworld.Greeter/SayHello", say_hello)]))
}

// A client that can reach the greeter and nothing else.
fn greet(net: Net, address: Str) -> Str {
    let c = match grpc.connect(net, address) {
        Ok(c) => c,
        Err(e) => {
            return "{address}: {e}"
        },
    }
    defer c.close()
    let r: Result[HelloReply, grpc.Status] = c.call("/helloworld.Greeter/SayHello", HelloRequest { name: "Ada" })
    match r {
        Ok(reply) => "{address}: {reply.message}",
        Err(e) => "{address}: {e.message()}",
    }
}

fn main(root: Root) {
    let net = root.net.only("greeter.example.com")
    root.stdout.print(greet(net, "greeter.example.com:443"))
    root.stdout.print(greet(net, "billing.example.com:443"))
    if root.args().contains("serve") {
        match serve(root.listen, root.fs.read_only(), root.clock) {
            Ok(()) => (),
            Err(e) => root.stdout.print("{e}"),
        }
    }
}
Listing 17-6: A TLS server, and a client limited to one service examples/ch17-06-for-real/main.lmn
$ limen run main.lmn
greeter.example.com:443: Denied("net: greeter.example.com:443 is not granted")
billing.example.com:443: Denied("net: billing.example.com:443 is not granted")
$ limen caps main.lmn
say_hello  pure
serve      Fs, Clock, Listen
greet      Net
main       Root

serve reads the certificate and key through a read-only Fs, as chapter 14's HTTPS server did. listen.offering(["h2"]) returns a Listen that agrees to HTTP/2 through ALPN, which is how a TLS client and server decide to speak it, and on_tls listens with the certificate. From there it's the same grpc.serve_forever. The http2.Server made from the clock closes connections that stay idle too long or take too long to send, which matters once anyone on the network can connect. Its limits are fields: idle_ms, wait_ms, max_streams and max_body.

grpc.connect(net, "host:port") is the client over TLS. It checks the server's certificate through the Net's trust, like every TLS connection in Limen, so a service with its own certificate authority takes net.trusting(ca) from chapter 14, and one that wants a client certificate takes net.presenting(cert, key).

The book runs this program with no network grant, so both calls are denied before anything leaves the machine. Run with --grant net=greeter.example.com, the first call would go through. The second still wouldn't: greet holds a Net narrowed with only("greeter.example.com"), and no grant on the command line widens what a function was handed. A client built this way can call the greeter and nothing else, however it's changed later, and limen caps shows it: greet holds a Net, serve a Listen, an Fs and a Clock, and say_hello nothing at all.

The grants are the ones you already know. A server needs listen= for its address and fs= for its certificate; a client needs net= for the hosts it calls. gRPC adds no capability of its own, because it's built entirely from these.

A few things gRPC libraries elsewhere do aren't here yet: compression, typed streams, and channels that spread calls over several connections with load balancing and retries. A grpc.Client is one connection to one address.

Summary

A protobuf message is a struct with @field numbers, and protobuf.encode and decode write the same bytes as protobuf's own libraries. A server is a list of methods, grpc.unary for one message each way and grpc.method with a ServerCall for streams, served by grpc.serve_forever. A client calls with c.call, which infers the response's type from where the result goes, or opens a stream with c.open. Calls end with a grpc.Status whose code the client matches on, deadlines travel with the call and end it with DEADLINE_EXCEEDED, and metadata rides along as headers. The capabilities are the usual ones: Listen and Fs to serve, a Net to call, narrowed to the services a client may reach.

Next: calling C, for the libraries that only exist there.