Standard library · Network

grpc

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()

func encode_user(id: int, name: str): compress.ByteBuf:
    mut b := compress.NewByteBuf()
    protobuf.WriteTag(b, 1, protobuf.WT_VARINT)
    protobuf.WriteVarint(b, id as u64)
    protobuf.WriteTag(b, 2, protobuf.WT_LEN)
    protobuf.WriteLenPrefixedStr(b, name)
    ret b
end

func get_user(c: i64):
    mut ok := false
    req := grpc.Recv(c, ok)
    mut r := compress.ReaderFromBuf(req)
    mut field := 0
    mut wire := 0
    mut id := 0
    try:
        protobuf.ReadTag(r, field, wire)
        id = protobuf.ReadVarint(r) as int
    catch e:
        grpc.Fail(c, grpc.GRPC_INVALID_ARGUMENT, e.ToStr())
        ret
    end
    if field != 1:
        grpc.Fail(c, grpc.GRPC_INVALID_ARGUMENT, "expected field 1 with the user id")
        ret
    end
    if id != 7:
        grpc.Fail(c, grpc.GRPC_NOT_FOUND, "no user " + id)
        ret
    end
    mut reply := encode_user(7, "Maryam")
    _ := grpc.Send(c, reply)
    compress.BufFree(reply)
    grpc.SetStatus(c, grpc.GRPC_OK, "")
end

func run_server():
    _ := grpc.Listen(server)
    sync.Done(ready)
    _ := grpc.ServeCount(server, 1)
end

func ask(ch &: grpc.Channel, id: int) throw:
    mut req := compress.NewByteBuf()
    protobuf.WriteTag(req, 1, protobuf.WT_VARINT)
    protobuf.WriteVarint(req, id as u64)
    mut st := grpc.Status {}
    answer := grpc.UnaryCall(ch, "/users.Users/Get", req, grpc.NewMetadata(), st)
    compress.BufFree(req)
    if not grpc.StatusOk(st):
        println "user", id, "->", grpc.StatusString(st)
        ret
    end
    mut r := compress.ReaderFromBuf(answer)
    mut field := 0
    mut wire := 0
    try protobuf.ReadTag(r, field, wire)
    uid := try protobuf.ReadVarint(r)
    try protobuf.ReadTag(r, field, wire)
    println "user", uid, "is", try protobuf.ReadLenPrefixedStr(r)
end

func main 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)
    try ask(ch, 7)
    try ask(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.

grpc-guide-auth.salam
import grpc
import sync
import compress

mut server := grpc.NewServer(0)
mut ready := sync.NewWaitGroup()

func balance(c: i64):
    mut ok := false
    account := grpc.RecvStr(c, ok)
    token := grpc.MDGet(grpc.CallMetadata(c), "authorization")
    if token == "":
        grpc.Fail(c, grpc.GRPC_UNAUTHENTICATED, "missing token")
        ret
    end
    if token != "Bearer good-token":
        grpc.Fail(c, grpc.GRPC_PERMISSION_DENIED, "this token cannot read " + account)
        ret
    end
    _ := grpc.SendStr(c, account + ": 1250")
    grpc.SetStatus(c, grpc.GRPC_OK, "")
end

func run_server():
    _ := grpc.Listen(server)
    sync.Done(ready)
    _ := grpc.ServeCount(server, 1)
end

func main:
    grpc.RegisterMethod("/bank.Accounts/Balance", balance)
    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)
    each token in ["", "Bearer old-token", "Bearer good-token"]:
        mut md := grpc.NewMetadata()
        if token != "":
            _ := grpc.MDAdd(md, "authorization", token)
        end
        mut st := grpc.Status {}
        answer := grpc.UnaryCall(
            ch, "/bank.Accounts/Balance", compress.BufFromStr("acc-42"), md, st
        )
        if grpc.StatusOk(st):
            println "ok:", compress.BufToStrUnsafe(answer)
        else:
            println grpc.StatusName(st.code), "(" + st.code + "):", st.message
        end
    end
    grpc.CloseChannel(ch)
    join(t)
    grpc.StopServer(server)
end
Output
UNAUTHENTICATED (16): missing token
PERMISSION_DENIED (7): this token cannot read acc-42
ok: acc-42: 1250

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()

func total(c: i64):
    mut sum := 0
    mut count := 0
    mut more := true
    until more:
        mut ok := false
        reading := grpc.RecvStr(c, ok)
        if not ok:
            more = false
        else:
            sum += reading.ToInt()
            count++
        end
    end
    _ := grpc.SendStr(c, "" + count + " readings, total " + sum)
    grpc.SetStatus(c, grpc.GRPC_OK, "")
end

func run_server():
    _ := grpc.Listen(server)
    sync.Done(ready)
    _ := grpc.ServeCount(server, 1)
end

func main:
    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)
    end
    mut 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

ShapeRegister withClient calls
One request, one answerRegisterMethodUnaryCall, or UnaryCallStr for text
Many requests, one answerRegisterStreamMethod(path, fn, true, false)StartCall, SendMessage, RecvMessage, FinishCall
One request, many answersRegisterStreamMethod(path, fn, false, true)StartCall, SendMessage with true, then RecvMessage in a loop
Both directionsRegisterStreamMethod(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.

Types

Server

#
struct Server

A gRPC server over plaintext HTTP/2.

NameTypeDescription
portint = 0The port.
listen_fdi64 = -1The listening socket.
runningbool = falseIt is running.
servedint = 0The number of connections answered.
grpc-Calls.salam
import grpc
import compress
import sync

mut server := grpc.NewServer(0)
mut ready := sync.NewWaitGroup()

func hello(c: i64):
    mut ok := false
    name := grpc.RecvStr(c, ok)
    _ := grpc.SendStr(c, "hello " + name)
    grpc.SetStatus(c, grpc.GRPC_OK, "")
end

func countdown(c: i64):
    mut ok := false
    _ := grpc.Recv(c, ok)
    repeat 3 in i:
        _ := grpc.Send(c, compress.BufFromStr("" + (3 - i)))
    end
    grpc.SetStatus(c, grpc.GRPC_OK, "")
end

func trace(c: i64):
    mut ok := false
    _ := grpc.RecvStr(c, ok)
    _ := grpc.SendStr(c, grpc.MDGet(grpc.CallMetadata(c), "x-trace") + " " + grpc.CallPath(c))
    grpc.SetStatus(c, grpc.GRPC_OK, "")
end

func forbidden(c: i64):
    grpc.Fail(c, grpc.GRPC_PERMISSION_DENIED, "the token expired")
end

func run_server():
    _ := grpc.Listen(server)
    sync.Done(ready)
    _ := grpc.ServeCount(server, 1)
end

func main:
    hello_path := grpc.MethodPath("demo.Greeter", "SayHello")
    println hello_path
    grpc.RegisterMethod(hello_path, hello)
    grpc.RegisterStreamMethod("/demo.Greeter/Countdown", countdown, false, true)
    grpc.RegisterMethod("/demo.Greeter/Trace", trace)
    grpc.RegisterMethod("/demo.Greeter/Admin", forbidden)
    println grpc.MethodCount(), grpc.HasMethod(hello_path)
    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)
    println grpc.ChannelOk(ch)
    mut result := grpc.Status {}
    println grpc.UnaryCallStr(ch, hello_path, "Maryam", result), grpc.StatusOk(result)

    call := grpc.StartCall(ch, "/demo.Greeter/Countdown", grpc.NewMetadata())
    _ := grpc.SendMessage(ch, call, compress.BufFromStr("go"), true)
    mut more := true
    until more:
        mut ok := false
        msg := grpc.RecvMessage(ch, call, ok)
        if not ok:
            more = false
        else:
            println "message:", compress.BufToStrUnsafe(msg)
        end
    end
    println grpc.MDCount(grpc.CallHeaders(ch, call))
    println grpc.StatusString(grpc.FinishCall(ch, call))

    mut md := grpc.NewMetadata()
    _ := grpc.MDAdd(md, "x-trace", "t-42")
    mut result2 := grpc.Status {}
    answer := grpc.UnaryCall(ch, "/demo.Greeter/Trace", compress.BufFromStr("x"), md, result2)
    println compress.BufToStrUnsafe(answer)

    call2 := grpc.StartCall(ch, "/demo.Greeter/Trace", md)
    _ := grpc.SendMessage(ch, call2, compress.BufFromStr("y"), false)
    _ := grpc.CloseSend(ch, call2)
    mut ok2 := false
    _ := grpc.RecvMessage(ch, call2, ok2)
    _ := grpc.FinishCall(ch, call2)
    println ok2, grpc.CallTrailers(ch, call2).items.Len() >= 0

    mut result3 := grpc.Status {}
    _ := grpc.UnaryCallStr(ch, "/demo.Greeter/Admin", "", result3)
    println result3.code, result3.message, grpc.StatusName(result3.code)
    mut result4 := grpc.Status {}
    _ := grpc.UnaryCallStr(ch, "/demo.Greeter/Nope", "", result4)
    println grpc.StatusString(result4)
    grpc.CloseChannel(ch)
    join(t)
    grpc.StopServer(server)
    grpc.ResetMethods()
    println grpc.MethodCount()
end
Output
/demo.Greeter/SayHello
4 true
true
hello Maryam true
message: 3
message: 2
message: 1
0
OK
t-42 /demo.Greeter/Trace
true true
7 the token expired PERMISSION_DENIED
UNIMPLEMENTED: unknown method /demo.Greeter/Nope
0

Status

#
struct Status

The final status of a call.

NameTypeDescription
codeint = 0The code.
messagestr = ""The message.

The example for this item is shown with the ones above: grpc-Calls.salam

MDEntry

#
struct MDEntry

One metadata entry.

NameTypeDescription
keystr = ""The key.
valuestr = ""The value.
binarybool = falseIt is binary.
grpc-Wire.salam
import grpc
import compress
import net.http2

func main:
    one := grpc.FrameMessageStr("hello")
    println one.len, compress.BufGet(one, 0), compress.BufGet(one, 4)
    mut all := compress.NewByteBuf()
    compress.BufPushBuf(all, one)
    compress.BufPushBuf(all, grpc.FrameMessage(compress.BufFromStr("two"), false))
    compress.BufPushBuf(all, grpc.FrameMessageGzip(compress.BufFromStr("three three three"), true))
    println grpc.MessageCount(all), grpc.HasMessage(all, 0)
    mut pos := 0
    mut ok := false
    until grpc.HasMessage(all, pos):
        msg := grpc.NextMessage(all, pos, ok)
        println ok, compress.BufToStrUnsafe(msg)
    end

    mut md := grpc.NewMetadata()
    _ := grpc.MDAdd(md, "authorization", "Bearer abc")
    _ := grpc.MDAdd(md, "x-tag", "a")
    _ := grpc.MDAdd(md, "x-tag", "b")
    _ := grpc.MDAddBinary(md, "trace-bin", "\x01\x02")
    println grpc.MDCount(md), grpc.MDHas(md, "x-tag"), grpc.MDGet(md, "authorization")
    println grpc.MDGetAll(md, "x-tag").Len()
    println grpc.MDKeyAt(md, 3), grpc.MDValueAt(md, 3).Len()
    mut headers := http2.HeaderList {}
    grpc.MDToHeaders(md, headers)
    println http2.HeadersCount(headers), http2.HeadersGet(headers, "trace-bin")
    println grpc.MDCount(grpc.MDFromHeaders(headers))

    bad := grpc.NewStatus(grpc.GRPC_NOT_FOUND, "there is no user 42")
    println grpc.StatusOk(bad), grpc.StatusString(bad)
    message := grpc.EncodeStatusMessage("100% done")
    println message, grpc.DecodeStatusMessage(message)
    println grpc.FormatStatusCode(14), grpc.ParseStatusCode("14"), grpc.ParseStatusCode("x")
    println grpc.StatusName(grpc.GRPC_DEADLINE_EXCEEDED), grpc.StatusName(grpc.GRPC_UNAUTHENTICATED)
    println grpc.GRPC_CANCELLED,
        grpc.GRPC_UNKNOWN,
        grpc.GRPC_INVALID_ARGUMENT,
        grpc.GRPC_ALREADY_EXISTS
    println grpc.GRPC_RESOURCE_EXHAUSTED,
        grpc.GRPC_FAILED_PRECONDITION,
        grpc.GRPC_ABORTED,
        grpc.GRPC_OUT_OF_RANGE
    println grpc.GRPC_UNIMPLEMENTED, grpc.GRPC_INTERNAL, grpc.GRPC_UNAVAILABLE, grpc.GRPC_DATA_LOSS
    println grpc.GRPC_CONTENT_TYPE, grpc.GRPC_CONTENT_TYPE_PROTO, grpc.GRPC_CONTENT_TYPE_JSON
    println grpc.GRPC_COMP_NONE, grpc.GRPC_COMP_GZIP, grpc.GRPC_MAX_FRAMES, grpc.GRPC_MAX_MESSAGE
end
Output
10 0 5
3 true
true hello
true two
true three three three
4 true Bearer abc
2
trace-bin 2
4 AQI=
4
false NOT_FOUND: there is no user 42
100%25 done 100% done
14 14 2
DEADLINE_EXCEEDED UNAUTHENTICATED
1 2 3 6
8 9 10 11
12 13 14 15
application/grpc application/grpc+proto application/grpc+json
0 1 100000 4194304

Metadata

#
struct Metadata

The metadata of a call, like HTTP headers.

NameTypeDescription
itemsVector<MDEntry>The entries.

The example for this item is shown with the ones above: grpc-Calls.salam

CallCtx

#
struct CallCtx

The state of a call on the server.

NameTypeDescription
stream_idint = 0The stream id.
methodstr = ""The method path.
headershttp2.HeaderListThe headers.
recvcompress.ByteBufThe received data.
recv_posint = 0The read position.
client_donebool = falseThe client closed its sending side.
sent_headersbool = falseThe response headers were sent.
statusStatusThe status.
busybool = falseIt is in use.
failedbool = falseIt failed.

The example for this item is shown with the ones above: grpc-Calls.salam

CallTable

#
struct CallTable

The table of calls.

NameTypeDescription
itemsVector<CallCtx>The calls.

The example for this item is shown with the ones above: grpc-Calls.salam

MethodDesc

#
struct MethodDesc

The description of a registered method.

NameTypeDescription
pathstr = ""The path.
fni64 = 0The routine.
client_streambool = falseThe client sends a stream.
server_streambool = falseThe server sends a stream.

The example for this item is shown with the ones above: grpc-Calls.salam

MethodTable

#
struct MethodTable

The table of methods.

NameTypeDescription
itemsVector<MethodDesc>The methods.

The example for this item is shown with the ones above: grpc-Calls.salam

Cursor

#
struct Cursor

The read position of a stream.

NameTypeDescription
stream_idint = 0The stream id.
posint = 0The read position.

The example for this item is shown with the ones above: grpc-Calls.salam

CursorTable

#
struct CursorTable

The table of cursors.

NameTypeDescription
itemsVector<Cursor>The cursors.

The example for this item is shown with the ones above: grpc-Calls.salam

Channel

#
struct Channel

A channel to a gRPC server over HTTP/2.

NameTypeDescription
connhttp2.ConnThe HTTP/2 connection.
authoritystr = ""The host and port.
schemestr = "http"The scheme: http or https.
user_agentstr = "salam-grpc/1.0"The client identifier.
timeout_msint = 0The timeout of each call.
use_gzipbool = falseSend the messages compressed.
cursorsCursorTableThe read position of each stream.
okbool = falseIt is healthy.
last_errorstr = ""The last error.

The example for this item is shown with the ones above: grpc-Calls.salam

Constants and variables

GRPC_OK

#
const GRPC_OK: i32 = 0

Status code: success.

The example for this item is shown with the ones above: grpc-Calls.salam

GRPC_CANCELLED

#
const GRPC_CANCELLED: i32 = 1

Status code: cancelled.

The example for this item is shown with the ones above: grpc-Wire.salam

GRPC_UNKNOWN

#
const GRPC_UNKNOWN: i32 = 2

Status code: an unknown error.

The example for this item is shown with the ones above: grpc-Wire.salam

GRPC_INVALID_ARGUMENT

#
const GRPC_INVALID_ARGUMENT: i32 = 3

Status code: an invalid argument.

The example for this item is shown with the ones above: grpc-Wire.salam

GRPC_DEADLINE_EXCEEDED

#
const GRPC_DEADLINE_EXCEEDED: i32 = 4

Status code: the deadline passed.

The example for this item is shown with the ones above: grpc-Wire.salam

GRPC_NOT_FOUND

#
const GRPC_NOT_FOUND: i32 = 5

Status code: not found.

The example for this item is shown with the ones above: grpc-Wire.salam

GRPC_ALREADY_EXISTS

#
const GRPC_ALREADY_EXISTS: i32 = 6

Status code: it already exists.

The example for this item is shown with the ones above: grpc-Wire.salam

GRPC_PERMISSION_DENIED

#
const GRPC_PERMISSION_DENIED: i32 = 7

Status code: you are not allowed.

The example for this item is shown with the ones above: grpc-Calls.salam

GRPC_RESOURCE_EXHAUSTED

#
const GRPC_RESOURCE_EXHAUSTED: i32 = 8

Status code: a resource or a quota ran out.

The example for this item is shown with the ones above: grpc-Wire.salam

GRPC_FAILED_PRECONDITION

#
const GRPC_FAILED_PRECONDITION: i32 = 9

Status code: the system is not in the state needed.

The example for this item is shown with the ones above: grpc-Wire.salam

GRPC_ABORTED

#
const GRPC_ABORTED: i32 = 10

Status code: aborted because of a conflict.

The example for this item is shown with the ones above: grpc-Wire.salam

GRPC_OUT_OF_RANGE

#
const GRPC_OUT_OF_RANGE: i32 = 11

Status code: out of range.

The example for this item is shown with the ones above: grpc-Wire.salam

GRPC_UNIMPLEMENTED

#
const GRPC_UNIMPLEMENTED: i32 = 12

Status code: the method is not implemented.

The example for this item is shown with the ones above: grpc-Wire.salam

GRPC_INTERNAL

#
const GRPC_INTERNAL: i32 = 13

Status code: an internal error.

The example for this item is shown with the ones above: grpc-Wire.salam

GRPC_UNAVAILABLE

#
const GRPC_UNAVAILABLE: i32 = 14

Status code: the service is unavailable; it can be retried.

The example for this item is shown with the ones above: grpc-Wire.salam

GRPC_DATA_LOSS

#
const GRPC_DATA_LOSS: i32 = 15

Status code: data was lost.

The example for this item is shown with the ones above: grpc-Wire.salam

GRPC_UNAUTHENTICATED

#
const GRPC_UNAUTHENTICATED: i32 = 16

Status code: not authenticated.

The example for this item is shown with the ones above: grpc-Wire.salam

GRPC_CONTENT_TYPE

#
const GRPC_CONTENT_TYPE: str = "application/grpc"

The gRPC content type.

The example for this item is shown with the ones above: grpc-Wire.salam

GRPC_CONTENT_TYPE_PROTO

#
const GRPC_CONTENT_TYPE_PROTO: str = "application/grpc+proto"

The content type with protobuf.

The example for this item is shown with the ones above: grpc-Wire.salam

GRPC_CONTENT_TYPE_JSON

#
const GRPC_CONTENT_TYPE_JSON: str = "application/grpc+json"

The content type with JSON.

The example for this item is shown with the ones above: grpc-Wire.salam

GRPC_COMP_NONE

#
const GRPC_COMP_NONE: i32 = 0

No compression.

The example for this item is shown with the ones above: grpc-Wire.salam

GRPC_COMP_GZIP

#
const GRPC_COMP_GZIP: i32 = 1

gzip compression.

The example for this item is shown with the ones above: grpc-Wire.salam

GRPC_MAX_FRAMES

#
const GRPC_MAX_FRAMES: i32 = 100000

The most frames read for one call.

The example for this item is shown with the ones above: grpc-Wire.salam

GRPC_MAX_MESSAGE

#
const GRPC_MAX_MESSAGE: i32 = 4194304

The largest size of one message: 4 megabytes.

The example for this item is shown with the ones above: grpc-Wire.salam

Functions

NewMetadata

#
func NewMetadata(): Metadata

Empty metadata.

The example for this item is shown with the ones above: grpc-Calls.salam

MDAdd

#
func MDAdd(md &: Metadata, key: str, value: str): bool

Adds a text entry; the key is stored in lower case and reserved keys, like content-type, are rejected.

The example for this item is shown with the ones above: grpc-Calls.salam

MDAddBinary

#
func MDAddBinary(md &: Metadata, key: str, value: str): bool

Adds a binary entry; the key must end in -bin and the value is sent in base64.

The example for this item is shown with the ones above: grpc-Wire.salam

MDGet

#
func MDGet(md: Metadata, key: str): str

The first value of a key.

The example for this item is shown with the ones above: grpc-Calls.salam

MDHas

#
func MDHas(md: Metadata, key: str): bool

The key is there.

The example for this item is shown with the ones above: grpc-Wire.salam

MDGetAll

#
func MDGetAll(md: Metadata, key: str): Vector<str>

Every value of a key.

The example for this item is shown with the ones above: grpc-Wire.salam

MDCount

#
func MDCount(md: Metadata): int

The number of entries.

The example for this item is shown with the ones above: grpc-Calls.salam

MDKeyAt

#
func MDKeyAt(md: Metadata, i: int): str

The key of entry n.

The example for this item is shown with the ones above: grpc-Wire.salam

MDValueAt

#
func MDValueAt(md: Metadata, i: int): str

The value of entry n.

The example for this item is shown with the ones above: grpc-Wire.salam

MDToHeaders

#
func MDToHeaders(md: Metadata, hl &: http2.HeaderList)

Adds the metadata to the HTTP/2 headers.

The example for this item is shown with the ones above: grpc-Wire.salam

MDFromHeaders

#
func MDFromHeaders(hl: http2.HeaderList): Metadata

Takes the metadata out of the HTTP/2 headers.

The example for this item is shown with the ones above: grpc-Wire.salam

NewServer

#
func NewServer(port: int): Server

A new server; port zero means a free port.

The example for this item is shown with the ones above: grpc-Calls.salam

RegisterMethod

#
func RegisterMethod(path: str, fn: i64)

Registers a routine for a plain method.

The example for this item is shown with the ones above: grpc-Calls.salam

RegisterStreamMethod

#
func RegisterStreamMethod(path: str, fn: i64, client_stream: bool, server_stream: bool)

Registers a routine for a streaming method and says which side streams.

The example for this item is shown with the ones above: grpc-Calls.salam

MethodCount

#
func MethodCount(): int

The number of methods.

The example for this item is shown with the ones above: grpc-Calls.salam

HasMethod

#
func HasMethod(path: str): bool

The method is registered.

The example for this item is shown with the ones above: grpc-Calls.salam

ResetMethods

#
func ResetMethods()

Removes every method.

The example for this item is shown with the ones above: grpc-Calls.salam

CallPath

#
func CallPath(slot: i64): str

The method path of the current call.

The example for this item is shown with the ones above: grpc-Calls.salam

CallMetadata

#
func CallMetadata(slot: i64): Metadata

The metadata the client sent.

The example for this item is shown with the ones above: grpc-Calls.salam

Recv

#
func Recv(slot: i64, ok &: bool): compress.ByteBuf

Reads the client's next message.

The example for this item is shown with the ones above: grpc-Calls.salam

RecvStr

#
func RecvStr(slot: i64, ok &: bool): str

The next message as text.

The example for this item is shown with the ones above: grpc-Calls.salam

Send

#
func Send(slot: i64, msg: compress.ByteBuf): bool

Sends a message to the client; in a streaming method, several times.

The example for this item is shown with the ones above: grpc-Calls.salam

SendStr

#
func SendStr(slot: i64, msg: str): bool

Sends a text message.

The example for this item is shown with the ones above: grpc-Calls.salam

SetStatus

#
func SetStatus(slot: i64, code: int, message: str)

Sets the final status of the call.

The example for this item is shown with the ones above: grpc-Calls.salam

Fail

#
func Fail(slot: i64, code: int, message: str)

Ends the call with an error code and message.

The example for this item is shown with the ones above: grpc-Calls.salam

Listen

#
func Listen(s &: Server): bool

Starts listening.

The example for this item is shown with the ones above: grpc-Calls.salam

Port

#
func Port(s: Server): int

The port actually taken.

The example for this item is shown with the ones above: grpc-Calls.salam

ServeConn

#
func ServeConn(fd: i64): int

Answers the calls on one connection, one after another, until the client closes it or sends GOAWAY.

grpc-TLS.salam
import grpc
import net.tcp

func echo(c: i64):
    mut ok := false
    _ := grpc.SendStr(c, grpc.RecvStr(c, ok))
end

func main:
    mut ch := grpc.DialTLS("api.example.com", 443)
    if not grpc.ChannelOk(ch):
        println grpc.ChannelError(ch)
        ret
    end
    grpc.SetGzip(ch, true)
    mut result := grpc.Status {}
    println grpc.UnaryCallStr(ch, "/demo.Echo/Say", "hello", result)
    grpc.CloseChannel(ch)

    grpc.RegisterMethod("/demo.Echo/Say", echo)
    mut s := grpc.NewServer(50051)
    if grpc.Listen(s):
        grpc.Serve(s)
    end
    conn := tcp.Dial("127.0.0.1", 50052)
    _ := grpc.ServeConn(conn.fd)
end

ServeCount

#
func ServeCount(s &: Server, n: int): int

Answers n connections, one after another, and returns the total served. It calls Listen first if needed.

The example for this item is shown with the ones above: grpc-Calls.salam

Serve

#
func Serve(s &: Server)

Answers connections one at a time until StopServer is called.

The example for this item is shown with the ones above: grpc-Calls.salam

StopServer

#
func StopServer(s &: Server)

Stops the server.

The example for this item is shown with the ones above: grpc-Calls.salam

NewStatus

#
func NewStatus(code: int, message: str): Status

A status with a code and a message.

The example for this item is shown with the ones above: grpc-Wire.salam

StatusOk

#
func StatusOk(s: Status): bool

The status is a success.

The example for this item is shown with the ones above: grpc-Calls.salam

MethodPath

#
func MethodPath(service: str, method: str): str

A method path from a service name and a method name, like /demo.Greeter/SayHello.

The example for this item is shown with the ones above: grpc-Calls.salam

Dial

#
func Dial(host: str, port: int): Channel

A plaintext channel (h2c), for internal servers.

The example for this item is shown with the ones above: grpc-Calls.salam

DialTLS

#
func DialTLS(host: str, port: int): Channel

A secure channel with TLS and ALPN h2.

The example for this item is shown with the ones above: grpc-TLS.salam

ChannelOk

#
func ChannelOk(ch: Channel): bool

The channel is healthy.

The example for this item is shown with the ones above: grpc-Calls.salam

ChannelError

#
func ChannelError(ch: Channel): str

The channel's last error.

The example for this item is shown with the ones above: grpc-TLS.salam

SetTimeout

#
func SetTimeout(ch &: Channel, ms: int)

The timeout of the calls in milliseconds; the server is told too, through the grpc-timeout header.

The example for this item is shown with the ones above: grpc-Calls.salam

SetGzip

#
func SetGzip(ch &: Channel, enable: bool)

Turns gzip compression of the messages on or off.

The example for this item is shown with the ones above: grpc-TLS.salam

CloseChannel

#
func CloseChannel(ch &: Channel)

Closes the channel.

The example for this item is shown with the ones above: grpc-Calls.salam

StartCall

#
func StartCall(ch &: Channel, path: str, md: Metadata): int

Starts a call on a method path and returns the stream id; for streaming calls.

The example for this item is shown with the ones above: grpc-Calls.salam

SendMessage

#
func SendMessage(ch &: Channel, sid: int, msg: compress.ByteBuf, last: bool): bool

Sends one message; with true on the last message, the sending side is closed.

The example for this item is shown with the ones above: grpc-Calls.salam

CloseSend

#
func CloseSend(ch &: Channel, sid: int): bool

Tells the server no more messages are coming.

The example for this item is shown with the ones above: grpc-Calls.salam

RecvMessage

#
func RecvMessage(ch &: Channel, sid: int, ok &: bool): compress.ByteBuf

Reads the next message; if none is left, ok becomes false.

The example for this item is shown with the ones above: grpc-Calls.salam

FinishCall

#
func FinishCall(ch &: Channel, sid: int): Status

Ends the call and returns the server's final status.

The example for this item is shown with the ones above: grpc-Calls.salam

CallHeaders

#
func CallHeaders(ch: Channel, sid: int): Metadata

The metadata the server sent in the headers.

The example for this item is shown with the ones above: grpc-Calls.salam

CallTrailers

#
func CallTrailers(ch: Channel, sid: int): Metadata

The metadata the server sent at the end.

The example for this item is shown with the ones above: grpc-Calls.salam

UnaryCall

#
func UnaryCall(ch &: Channel, path: str, req: compress.ByteBuf, md: Metadata, st &: Status): compress.ByteBuf

A plain call: sends one message and gets one answer.

The example for this item is shown with the ones above: grpc-Calls.salam

UnaryCallStr

#
func UnaryCallStr(ch &: Channel, path: str, req: str, st &: Status): str

Like the routine above, with a text message.

The example for this item is shown with the ones above: grpc-Calls.salam

StatusName

#
func StatusName(code: int): str

The name of a status code, like NOT_FOUND.

The example for this item is shown with the ones above: grpc-Calls.salam

EncodeStatusMessage

#
func EncodeStatusMessage(msg: str): str

Percent encodes a status message for the grpc-message header.

The example for this item is shown with the ones above: grpc-Wire.salam

DecodeStatusMessage

#
func DecodeStatusMessage(msg: str): str

Decodes a status message.

The example for this item is shown with the ones above: grpc-Wire.salam

FormatStatusCode

#
func FormatStatusCode(code: int): str

A status code as text.

The example for this item is shown with the ones above: grpc-Wire.salam

ParseStatusCode

#
func ParseStatusCode(text: str): int

A status code from text; if it is invalid, UNKNOWN.

The example for this item is shown with the ones above: grpc-Wire.salam

StatusString

#
func StatusString(s: Status): str

A status in the form NAME: message.

The example for this item is shown with the ones above: grpc-Calls.salam

FrameMessage

#
func FrameMessage(msg: compress.ByteBuf, compressed: bool): compress.ByteBuf

Frames a message with the 5 byte gRPC header.

The example for this item is shown with the ones above: grpc-Wire.salam

FrameMessageGzip

#
func FrameMessageGzip(msg: compress.ByteBuf, use_gzip: bool): compress.ByteBuf

Frames a message, compressed if you want.

The example for this item is shown with the ones above: grpc-Wire.salam

FrameMessageStr

#
func FrameMessageStr(msg: str): compress.ByteBuf

Frames a text.

The example for this item is shown with the ones above: grpc-Wire.salam

HasMessage

#
func HasMessage(data: compress.ByteBuf, pos: int): bool

From this position there is a whole message in the data.

The example for this item is shown with the ones above: grpc-Wire.salam

NextMessage

#
func NextMessage(data: compress.ByteBuf, pos &: int, ok &: bool): compress.ByteBuf

Reads the next message and moves the position forward; a compressed message is decompressed.

The example for this item is shown with the ones above: grpc-Wire.salam

MessageCount

#
func MessageCount(data: compress.ByteBuf): int

The number of whole messages.

The example for this item is shown with the ones above: grpc-Wire.salam