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/heathcheck |
which methods are health probes |
client |
dialling with the default interceptor chain |
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.
Interceptor order
type Interceptor interface {
Name() string
Order() int
Run() grpc.UnaryServerInterceptor
}
Chained by Order() ascending — smaller is further out. The five that ship
with the package occupy fixed positions:
| Order |
Middleware |
What |
| 100 |
session |
builds a session.Session from incoming metadata; SourceIp falls back to peer, UserAgent to gRPC's own header; serializes the request into Body |
| 200 |
tracing |
extracts W3C trace context, starts a SERVER span, puts the provider in ctx, records rpc.server.duration and rpc.server.active_calls |
| 300 |
log |
puts the logger in ctx, traces request and response, chooses trace vs error level by status code |
| 400 |
status |
maps a domain error to a gRPC code and attaches failure detail |
| 500 |
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 rather than the raw error
— 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) with the same
orders. 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
status leaves an error that is already a status.Status alone. Otherwise it
looks the 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 client interceptor reverses it: on a status carrying that detail it rebuilds
the failure.Error from the JSON and wraps the status alongside it, so the
caller can errors.Is and errors.As against its own domain errors and still
read the code. Without the detail it falls back to reconstructing a failure
from the status message.
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, source ip and the W3C pair are appended to the outgoing
metadata under the names in model. traceparent is whatever the tracing
middleware last wrote into the session, which is the current span — the callee
becomes its child.
Compression is unconditional: every request is gzipped. The server accepts it
via the blank import of the gzip encoder in server.
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.
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.