gorib/grpc
gRPC for gorib services: a server with an ordered interceptor chain, a client
with the matching chain, and a translation of domain errors into gRPC statuses
that survives the round trip — a failure.Error raised in one service is a
failure.Error again in the caller.
For the service side — registering handlers, declaring the error map, running
the server as a command — see docs/tools/grpc.md and
docs/tools/grpc-handler.md in gitlab.com/gorib/waffle. This file documents
the package itself.
| Path |
What's in it |
server |
the server, the Interceptor contract, the built-in echo service |
server/interceptor |
session, tracing, log, status, recover |
server/route |
Forward, the convert→call→convert handler shape |
server/healthcheck |
which methods are health probes |
client |
dialling with the default interceptor chain, and Dead, a placeholder connection for tests |
client/interceptor |
session propagation, gzip, error reconstruction |
model |
metadata key names |
echo |
the echo.EchoService proto and generated code |
Server
srv := server.NewServer(handler, unary, stream, addr, logger)
err := srv.Serve(ctx) // blocks
_ = srv.Close() // GracefulStop
Handler is a single Setup(*grpc.Server) — whatever registers the service
implementations. Two services are registered afterwards unless Setup already
provided them: echo.EchoService and the standard gRPC health service. A service
therefore always answers a probe, even before it has any endpoints of its own.
Anything else the server takes — a message size limit, keepalive — goes after
the logger as grpc.ServerOptions:
srv := server.NewServer(handler, unary, stream, addr, logger, grpc.MaxRecvMsgSize(16<<20))
Interceptor order
type Interceptor interface {
Run() grpc.UnaryServerInterceptor
}
type Interceptors []Interceptor
The caller lists them, first is outermost. The package carries no order of its
own — an interceptor does not know where it belongs, only the assembled chain
does. The five that ship belong in this order:
| Middleware |
What |
session |
builds a session.Session from incoming metadata and puts the incoming trace context on the ctx; SourceIp falls back to peer, UserAgent to gRPC's own header; serializes the request into Body |
tracing |
extracts W3C trace context, starts a SERVER span, puts the provider in ctx, records rpc.server.duration and rpc.server.active_calls |
log |
puts the logger in ctx, traces request and response, chooses trace vs error level by status code; warns when an answer still carries a neighbour's transport |
status |
maps a domain error to a gRPC code, attaches failure detail, and hangs the status on the error as its transport |
recover |
turns a panic into failure.Panic |
The ordering is load-bearing in both directions. status sits inside
tracing and log so that both observe the mapped code — outside, every failure
would be recorded as Unknown. recover sits inside status so a panic
becomes an error that status can then map, instead of killing the process.
Health-check methods (grpc.health.v1.Health/Check, /Watch and
echo.EchoService/Check) skip tracing and logging. A probe every few seconds
would otherwise dominate both.
Streams have a parallel set (NewStreamTracingMW and friends) belonging in the
same order. Each wraps grpc.ServerStream to replace its context, which is the
only way to make ctx changes visible to a streaming handler.
Errors on the wire
A call whose context has already ended — the caller cancelled, its deadline
passed, the connection closed — is answered with that context's own code,
Canceled or DeadlineExceeded, whatever the handler returned: the error is a
consequence, and the caller is the one to report it. A cancel the handler fires
on a context of its own does not end the call's context, so it is mapped like
any other error.
Otherwise status leaves an error that is already a status.Status alone, and
looks any other error up in the mapper — map[error]codes.Code, matched with
errors.Is — defaulting to Internal, and if the error is a failure.Error
it attaches an errdetails.ErrorInfo:
| Field |
Value |
Reason |
the failure type, upper-cased |
Domain |
failure.Kind |
Metadata["json"] |
the failure serialized as JSON |
The status does not replace the error. status attaches it with
failure.AttachTransport, and grpc-go, tracing and log find it with
errors.As, so the code on the wire is the mapped one while the logger gets the
failure the handler raised — its type, stack and payload — rather than
rpc error: code = … desc = …. A plain error becomes a failure typed by the
slug of its message.
The client interceptor reverses it: on a status carrying that detail it rebuilds
the failure.Error from the JSON and attaches the status as its transport, so
the caller can errors.Is against its own domain errors and still reach the
code with errors.As. Without the detail it reconstructs a failure from the
status message and attaches the status to that.
Either way the status belongs to the neighbour's hop, not to the caller's
answer: whoever answers for the error calls failure.DetachTransport first, and
log warns when one goes out still carrying it. The status status attached
itself is the service's own answer and does not warn.
The mapper is per-service: waffle collects ErrorMapper contributions by DI
tag and merges them into one map, so each domain declares only its own errors.
Handlers
route.Forward is for the handler that only converts, calls and converts back:
func (s *contractService) GetContract(ctx context.Context, req *proto.GetContractRequest) (*proto.Contract, error) {
return route.Forward(ctx, req,
s.converter.GetContractRequestToCommand,
s.contractManagement.GetContract,
s.converter.ContractToProto)
}
Errors from the call propagate untouched, so the status interceptor still sees
the domain error. Anything that does not fit the shape — several calls, a
conditional, a partial response — is written by hand; Forward is a
convenience, not a requirement.
Client
conn, err := client.New(host, port)
Dials with insecure credentials and a fixed chain — session propagation, gzip
compression, error reconstruction, tracing — for both unary and stream calls.
Extra grpc.DialOptions are appended, so they override the defaults.
Session propagation is the mirror of the server side: correlation id,
user-agent, language and source ip come from session.Session, the W3C pair
from the context, and all of them are appended to the outgoing metadata under
the names in model. The tracing interceptor, last in the chain, then replaces
traceparent with its own CLIENT span's — the callee becomes that span's child.
Compression is unconditional: every request is gzipped. The server accepts it
via the blank import of the gzip encoder in server.
Testing
A test replaces an outbound dependency at the typed client, never at the
connection: it supplies its own implementation of the generated client, not a
grpc.ClientConnInterface. The connection under a client the test leaves real
is still built; client.Dead(name) fills it, and panics naming name if a call
reaches it.
Logging levels
An error is logged at trace level, not error level, when its status code is one
a client can legitimately provoke: InvalidArgument, NotFound,
AlreadyExists, Unauthenticated, PermissionDenied, OutOfRange,
ResourceExhausted, Aborted. The check also consults the error map, so a
domain error mapped to one of those codes is quiet even before status has
converted it. A call whose context has ended is quiet too, and its span is not
marked failed.
Protobuf messages are rendered by a hand-written formatter rather than
protojson: fields in tag order, enums by name, maps sorted by key, and bytes
as <binary: N bytes> instead of a screenful of base64.
What it does not do
- No TLS.
client.New dials insecurely; transport security is the platform's
job (service mesh, sidecar).
- No retry, no backoff, no load-balancing policy beyond the gRPC defaults.
- No reflection service.
- No request validation — that is
whisk's.
- The server's
Serve blocks until the listener fails; there is no restart.