Documentation
¶
Overview ¶
Package grpcserver bootstraps a gRPC server with the SDK's cross-cutting concerns and exposes it as a worker.Runnable.
It opens a server span per RPC (otelgrpc), then applies the same chain of unary interceptors as the REST stack — Prometheus metrics, panic recovery, structured access logging, and errs->status mapping — and registers a health service and, optionally, server reflection. Because Server implements worker.Runnable (Name/Start/Stop), it is supervised alongside the HTTP server and background workers.
Interceptor order is metrics (outermost) -> recovery -> logging -> errormap -> application interceptors -> handler, so metrics and logging observe the already-mapped status code, and metrics count a panic as Internal.
Tracing ¶
The server span is opened before the interceptors, so every interceptor and the handler run inside it and their log records carry its trace id. It continues the W3C trace context of the request metadata. Health checks, reflection and methods the server does not serve get no span: a scanner cannot fill the trace UI with spans of made-up names.
Metrics ¶
With Config.Metrics set, the server records on that registry:
- skit_grpc_server_handled_total by method and code;
- skit_grpc_server_handling_seconds by method;
- skit_grpc_server_in_flight.
The method is recorded without its leading "/" ("pkg.Service/Method"), the code by its canonical name ("NOT_FOUND"), and the duration of a sampled RPC carries its trace as the exemplar. Like spans, health checks and reflection are not recorded.
Logging ¶
Every RPC is one info record, "grpc.request" ("grpc.stream" for a stream), with the fields of the RPC semantic conventions and the values the metrics record: rpc.method without its leading "/", rpc.response.status_code by its canonical name and rpc.server.call.duration in seconds.
Usage ¶
srv := grpcserver.New(log, grpcserver.Config{
Addr: ":9090",
EnableReflection: true,
Metrics: d.Metrics,
TracerProvider: tp,
})
srv.Install(handler) // each feature's Register owns its RegisterXxxServer call
group.Add(srv) // worker.Runnable: Start binds the listener, Stop drains
In tests, Serve runs the server on a caller-provided listener (e.g. a bufconn listener) instead of binding a TCP port.
Config ¶
- Addr: listen address, e.g. ":9090".
- ShutdownTimeout: bounds graceful drain before a hard stop (default 10s).
- EnableReflection: turns on server reflection (handy for grpcurl in dev).
- Metrics: the registry of the RPC metrics; nil disables them.
- TracerProvider: records the server spans; nil → the global provider.
- MaxRecvMsgSize / MaxSendMsgSize: override the 4 MiB defaults.
- NumStreamWorkers: stream-serving tuning (shared write buffers are gRPC's default since v1.84).
- Keepalive (KeepaliveConfig): server keepalive parameters and enforcement policy; zero values fall back to gRPC defaults.
Options ¶
- WithUnaryInterceptors(in...): appends application interceptors, applied after the built-in ones (closest to the handler).
Index ¶
- type Config
- type KeepaliveConfig
- type Option
- type Server
- func (s *Server) Addr() string
- func (s *Server) Install(svcs ...Service)
- func (s *Server) Name() string
- func (s *Server) Serve(lis net.Listener) error
- func (s *Server) ServiceRegistrar() grpc.ServiceRegistrar
- func (s *Server) Start(ctx context.Context) error
- func (s *Server) Stop(ctx context.Context) error
- type Service
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Config ¶
type Config struct {
// Addr is the listen address, e.g. ":9090".
Addr string
// ShutdownTimeout bounds graceful shutdown before a hard stop (default 10s).
ShutdownTimeout time.Duration
// EnableReflection turns on server reflection (handy for grpcurl in dev).
EnableReflection bool
// Metrics is the registry of the RPC metrics (skit_grpc_server_*); nil
// disables them.
Metrics prometheus.Registerer
// TracerProvider records a server span per RPC (otelgrpc); nil → the global
// provider.
TracerProvider trace.TracerProvider
// MaxRecvMsgSize / MaxSendMsgSize override the 4 MiB defaults (bytes).
MaxRecvMsgSize int
MaxSendMsgSize int
// NumStreamWorkers bounds the pool of goroutines serving streams; 0 spawns
// one goroutine per stream (the gRPC default).
NumStreamWorkers uint32
// Keepalive tunes connection liveness; zero values fall back to gRPC defaults.
Keepalive KeepaliveConfig
}
Config configures the gRPC server.
type KeepaliveConfig ¶
type KeepaliveConfig struct {
MaxConnectionIdle time.Duration
MaxConnectionAge time.Duration
Time time.Duration
Timeout time.Duration
MinTime time.Duration
PermitWithoutStream bool
}
KeepaliveConfig mirrors the gRPC keepalive server parameters and enforcement policy. Zero values are left at gRPC defaults.
type Option ¶
type Option func(*options)
Option customizes the server.
func WithProtoValidate ¶ added in v0.6.0
func WithProtoValidate() Option
WithProtoValidate installs a unary interceptor that validates every request message against its buf.validate rules (protovalidate) before the handler runs. A violation is returned as errs.InvalidArgument, which the built-in error-map interceptor turns into a gRPC InvalidArgument status — so handlers need not re-check the constraints declared in the .proto.
The validator is built once and is safe for concurrent use. If the CEL environment fails to build (a misconfiguration), the interceptor fails every request with Internal rather than silently skipping validation.
func WithStreamInterceptors ¶ added in v0.6.0
func WithStreamInterceptors(in ...grpc.StreamServerInterceptor) Option
WithStreamInterceptors appends application STREAM interceptors, applied after the built-in ones (closest to the handler) — symmetric to WithUnaryInterceptors.
func WithUnaryInterceptors ¶
func WithUnaryInterceptors(in ...grpc.UnaryServerInterceptor) Option
WithUnaryInterceptors appends application interceptors, applied after the built-in ones (closest to the handler).
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server wraps a *grpc.Server and implements worker.Runnable.
func (*Server) Install ¶
Install registers each Service on the server's registrar. Call it once, before Start, with the feature handlers — the equivalent of the REST Install function:
gs.Install(d.WidgetGRPC(ctx), d.OrderGRPC(ctx))
func (*Server) Serve ¶
Serve serves on the provided listener until Stop. It is useful for tests (e.g. a bufconn listener) and for callers that manage their own listener.
func (*Server) ServiceRegistrar ¶
func (s *Server) ServiceRegistrar() grpc.ServiceRegistrar
ServiceRegistrar returns the registrar used to register gRPC services, e.g. widgetv1.RegisterWidgetServiceServer(s.ServiceRegistrar(), handler).
type Service ¶
type Service interface {
Register(reg grpc.ServiceRegistrar)
}
Service is the registration seam a gRPC feature implements so the server need not know which concrete services exist or import their generated packages: the feature owns the generated RegisterXxxServer call, the server just hands it the registrar. It mirrors the REST rest.Handle seam, but as an interface because a gRPC service registers as a whole unit rather than per route.
func (h *Handler) Register(reg grpc.ServiceRegistrar) {
widgetv1.RegisterWidgetServiceServer(reg, h)
}