grpc

module
v1.6.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 22, 2026 License: MIT

README

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
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 {
	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 and attaches failure detail
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) 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

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 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 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. traceparent is whatever the tracing interceptor last put on the context, 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.

Directories

Path Synopsis
cmd
echo-client command
pb

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL