grpc

package
v0.27.0 Latest Latest
Warning

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

Go to latest
Published: Jun 27, 2026 License: MIT Imports: 32 Imported by: 0

Documentation

Overview

Package grpc provides a gRPC server toolkit for GTB services: a server bootstrap that integrates with the pkg/controls lifecycle and the standard gRPC health protocol, plus a suite of composable server interceptors — authentication (AuthInterceptor), logging, OpenTelemetry stats handlers, rate limiting, and circuit breaking — and TLS credential helpers.

Index

Constants

View Source
const (
	// StateClosed admits all RPCs; failures are counted.
	StateClosed = CircuitState(circuitbreaker.StateClosed)
	// StateOpen rejects all RPCs immediately with codes.Unavailable until the
	// cooldown elapses, then transitions to StateHalfOpen.
	StateOpen = CircuitState(circuitbreaker.StateOpen)
	// StateHalfOpen admits a limited number of trial RPCs; success closes the
	// breaker, failure re-opens it.
	StateHalfOpen = CircuitState(circuitbreaker.StateHalfOpen)
)

The public states are derived from the shared core so the two enumerations can never silently drift out of order.

View Source
const ConfigKeySharedPort = "server.port"

ConfigKeySharedPort is the shared fallback port used when the per-server port key (<prefix>.port) is unset.

View Source
const DefaultConfigPrefix = "server.grpc"

DefaultConfigPrefix is the config prefix a gRPC server reads (port, reflection, TLS) unless overridden with WithConfigPrefix. Use it to run a second gRPC server on its own config block, e.g. "server.internal".

View Source
const DefaultMaxGRPCMessageBytes = 1 << 20 // 1 MiB

DefaultMaxGRPCMessageBytes caps both send and receive message sizes on servers constructed via NewServer. Closes M-2 from docs/development/reports/security-audit-2026-04-17.md. Set to 1 MiB — tools with extraordinary message sizes can override via the explicit grpc.MaxRecvMsgSize / grpc.MaxSendMsgSize options passed to NewServer.

Variables

This section is empty.

Functions

func CircuitBreakerInterceptor added in v0.23.0

func CircuitBreakerInterceptor(log logger.Logger, cfg CircuitBreakerConfig) grpc.UnaryClientInterceptor

CircuitBreakerInterceptor returns a unary client interceptor that opens when a downstream is consistently failing and rejects calls with codes.Unavailable while open, avoiding wasted calls against a service known to be down. Install it via grpc.WithChainUnaryInterceptor.

func CircuitBreakerStreamInterceptor added in v0.23.0

func CircuitBreakerStreamInterceptor(log logger.Logger, cfg CircuitBreakerConfig) grpc.StreamClientInterceptor

CircuitBreakerStreamInterceptor returns a stream client interceptor with the same breaker semantics. Unlike a naive establishment-only breaker, it wraps the ClientStream so per-message errors (a RecvMsg/SendMsg that returns a classified failure) also count against the breaker; a clean io.EOF closes the stream as a success.

func DialLocal added in v0.6.0

func DialLocal(cfg config.Containable, opts ...any) (*grpc.ClientConn, error)

DialLocal dials the gRPC server described by cfg over the loopback interface, using transport security that matches the server's own TLS config (server.grpc.tls -> server.tls). Intended for in-process callers such as the grpc-gateway, so they connect to the local server without re-deriving the endpoint or credentials by hand. The opts variadic accepts both ServerOption values (e.g. WithConfigPrefix to dial a non-default gRPC server) and grpc.DialOption values; other types are ignored.

func IdentityFromContext added in v0.23.0

func IdentityFromContext(ctx context.Context) (*authn.Identity, bool)

IdentityFromContext returns the verified Identity set by AuthInterceptor. The same key is shared with the HTTP middleware.

func NewServer

func NewServer(cfg config.Containable, opts ...any) (*grpc.Server, error)

NewServer returns a new preconfigured grpc.Server.

Default gRPC options applied (before caller-supplied opts):

  • grpc.MaxRecvMsgSize(DefaultMaxGRPCMessageBytes)
  • grpc.MaxSendMsgSize(DefaultMaxGRPCMessageBytes)

Caller-supplied grpc.ServerOption values override the defaults (gRPC applies later options last, so a caller can raise or lower the limits explicitly).

The opts variadic accepts both ServerOption values (e.g. WithConfigPrefix, which selects the config block the reflection flag is read from) and grpc.ServerOption values; other types are ignored.

func OTelClientHandler added in v0.7.1

func OTelClientHandler(opts ...otelgrpc.Option) grpc.DialOption

OTelClientHandler returns a grpc.DialOption that instruments a client connection with OpenTelemetry: a client span per RPC, and — using the global propagator — the trace context injected into the outgoing metadata, so a downstream gRPC server continues the same trace rather than starting a new one. It reads the globally-installed providers (see telemetry.Setup) and is a noop until those are installed. The gateway applies it by default, so a REST request and the gRPC call it proxies land in one trace.

func OTelStatsHandler added in v0.7.0

func OTelStatsHandler(opts ...otelgrpc.Option) grpc.ServerOption

OTelStatsHandler returns a grpc.ServerOption that installs OpenTelemetry instrumentation for every RPC — server spans and the standard server metrics (rpc.server.*) — reading whichever TracerProvider and MeterProvider are installed as the OTel globals (see telemetry.Setup). It is a stats handler rather than an interceptor because that is the instrumentation the OTel gRPC contrib library ships and the shape the semantic conventions are defined against.

Pass it to Register alongside any other server options:

grpc.Register(ctx, "grpc", controller, cfg, log, grpc.OTelStatsHandler())

func PeerKey added in v0.23.0

func PeerKey(ctx context.Context, _ string) string

PeerKey is a ready-made KeyFunc keying on the RPC peer address. RPCs with no resolvable peer share a single bucket under the empty key.

func Register

func Register(ctx context.Context, id string, controller controls.Controllable, cfg config.Containable, logger logger.Logger, opts ...any) (*grpc.Server, error)

Register creates a new gRPC server and registers it with the controller under the given id. The opts variadic accepts ServerOption values (port, prefix), RegisterOption values (interceptors) and grpc.ServerOption values.

func RegisterHealthService

func RegisterHealthService(srv *grpc.Server, controller healthSource)

RegisterHealthService registers the standard gRPC health service with the provided server, wired to the controller's status.

func Start

func Start(cfg config.Containable, logger logger.Logger, srv *grpc.Server, opts ...ServerOption) controls.StartFunc

Start returns a curried function suitable for use with the controls package. With no options it reads its port and TLS from the default "server.grpc" config block; pass WithConfigPrefix/WithPort to target a custom server. TLS configuration cascades: <prefix>.tls.* overrides server.tls.* shared defaults.

func Status

func Status(srv *grpc.Server) controls.StatusFunc

Status returns a curried health function for a manually-wired server. It reports an error only when srv is nil; use the controller wiring (Serve) for serve-goroutine death detection.

func Stop

func Stop(logger logger.Logger, srv *grpc.Server) controls.StopFunc

Stop returns a curried function suitable for use with the controls package. GracefulStop is attempted first to allow in-flight RPCs to finish. If the shutdown context expires (or if Serve has not been called yet, which would cause GracefulStop to block indefinitely), the server is force-stopped.

func TLSClientCredentials added in v0.6.0

func TLSClientCredentials(caFiles ...string) (credentials.TransportCredentials, error)

TLSClientCredentials returns gRPC client transport credentials that trust the given CA/cert files. It is the client-side mirror of TLSServerCredentials — e.g. for the grpc-gateway dialing a gRPC server that presents a self-signed or private-CA certificate. With no files it trusts the system roots.

func TLSServerCredentials

func TLSServerCredentials(certFile, keyFile string) (credentials.TransportCredentials, error)

TLSServerCredentials returns gRPC server credentials using the shared hardened TLS config. Use this when you need to pass credentials directly to grpc.NewServer via grpc.Creds() instead of using the Start function. (credentials.NewTLS advertises h2 itself, so no explicit ALPN is needed.)

Types

type CircuitBreakerConfig added in v0.23.0

type CircuitBreakerConfig struct {
	// FailureThreshold is the number of consecutive failures (in Closed) that
	// trips the breaker open. Must be >= 1. Default: 5.
	FailureThreshold int
	// Cooldown is how long the breaker stays Open before a trial. Default: 30s.
	Cooldown time.Duration
	// HalfOpenMaxRequests is the number of trial RPCs allowed in HalfOpen.
	// Must be >= 1. Default: 1.
	HalfOpenMaxRequests int

	// IsFailure classifies an RPC outcome. When nil, the default treats
	// Unavailable and DeadlineExceeded as failures and every other code
	// (including OK and ResourceExhausted) as a success.
	//
	// ResourceExhausted is deliberately NOT a failure: like an HTTP 429 it means
	// "you are being rate-limited", which is the retry/backoff layer's concern,
	// not a signal that the downstream is unhealthy. Counting it would let a
	// server's own rate limiter trip its callers' breakers. Supply a custom
	// IsFailure to change this.
	IsFailure func(err error) bool

	// OnStateChange is invoked on every state transition. Optional; transitions
	// are also logged via the constructor's logger.
	OnStateChange func(from, to CircuitState)
}

CircuitBreakerConfig configures the client-side circuit breaker for gRPC.

func CircuitBreakerConfigFromConfig added in v0.23.0

func CircuitBreakerConfigFromConfig(cfg config.Containable, prefix string) CircuitBreakerConfig

CircuitBreakerConfigFromConfig builds a CircuitBreakerConfig from the config layer under "<prefix>.circuitbreaker.*" (prefix defaults to "server.grpc"), mirroring the HTTP helper. Recognised keys: failure_threshold (int), cooldown (duration), half_open_max_requests (int). Unset keys keep their defaults; IsFailure/OnStateChange are never read from config.

func DefaultCircuitBreakerConfig added in v0.23.0

func DefaultCircuitBreakerConfig() CircuitBreakerConfig

DefaultCircuitBreakerConfig returns: threshold 5, cooldown 30s, half-open trial 1, default Unavailable/DeadlineExceeded failure classification.

type CircuitState added in v0.23.0

type CircuitState int

CircuitState is the client circuit breaker's state.

func (CircuitState) String added in v0.23.0

func (s CircuitState) String() string

String renders the state for logging.

type GRPCAuthOption added in v0.23.0

type GRPCAuthOption func(*grpcAuthConfig)

GRPCAuthOption configures AuthInterceptor.

func WithGRPCAPIKeyMetadata added in v0.23.0

func WithGRPCAPIKeyMetadata(key string, v authn.Verifier) GRPCAuthOption

WithGRPCAPIKeyMetadata extracts the credential from the named metadata key.

func WithGRPCAuthLogger added in v0.23.0

func WithGRPCAuthLogger(l logger.Logger) GRPCAuthOption

WithGRPCAuthLogger sets the logger for redacted server-side failure logging.

func WithGRPCAuthorize added in v0.23.0

func WithGRPCAuthorize(fn authn.AuthorizeFunc) GRPCAuthOption

WithGRPCAuthorize installs an authorization predicate run after verification.

func WithGRPCBearerVerifier added in v0.23.0

func WithGRPCBearerVerifier(v authn.Verifier) GRPCAuthOption

WithGRPCBearerVerifier extracts the token from the "authorization" metadata ("Bearer <token>") and verifies it.

func WithGRPCMTLSVerifier added in v0.23.0

func WithGRPCMTLSVerifier(v authn.CertVerifier) GRPCAuthOption

WithGRPCMTLSVerifier authenticates the RPC from its verified client certificate when no metadata credential is presented.

func WithGRPCMethodSkipper added in v0.23.0

func WithGRPCMethodSkipper(pred func(fullMethod string) bool) GRPCAuthOption

WithGRPCMethodSkipper skips auth for additional full method names. The standard health and reflection services are ALWAYS skipped so k8s gRPC probes keep working; this skipper adds to that set, it does not replace it.

type GRPCLoggingOption

type GRPCLoggingOption func(*grpcLoggingConfig)

GRPCLoggingOption configures gRPC transport logging behaviour.

func WithGRPCLogLevel

func WithGRPCLogLevel(level logger.Level) GRPCLoggingOption

WithGRPCLogLevel sets the log level for successful RPCs. Errors always log at logger.ErrorLevel.

func WithGRPCPathFilter

func WithGRPCPathFilter(methods ...string) GRPCLoggingOption

WithGRPCPathFilter excludes RPCs matching the given full method names from logging.

func WithoutGRPCLatency

func WithoutGRPCLatency() GRPCLoggingOption

WithoutGRPCLatency disables the "latency" field.

type Interceptor

type Interceptor struct {
	Unary  grpc.UnaryServerInterceptor
	Stream grpc.StreamServerInterceptor
}

Interceptor groups a paired unary and stream interceptor. Either field may be nil if the interceptor only applies to one RPC type.

func AuthInterceptor added in v0.23.0

func AuthInterceptor(opts ...GRPCAuthOption) (Interceptor, error)

AuthInterceptor returns an Interceptor (unary + stream) that authenticates each RPC and stores the Identity in the RPC context. With no verifier it is a construction error (fail-closed).

The standard health (/grpc.health.v1.Health/*) and reflection (/grpc.reflection.v1*) services are auto-skipped so probes keep working. Credential precedence mirrors the HTTP middleware: a bearer token and an API-key metadata value presented together are rejected as ambiguous; mTLS authenticates only when no metadata credential is presented. Failures yield a generic codes.Unauthenticated / codes.PermissionDenied; the cause is logged WARN with the credential redacted.

func LoggingInterceptor

func LoggingInterceptor(l logger.Logger, opts ...GRPCLoggingOption) Interceptor

LoggingInterceptor returns an Interceptor (unary + stream) that logs each completed RPC.

func RateLimitInterceptor added in v0.23.0

func RateLimitInterceptor(log logger.Logger, cfg RateLimitConfig) Interceptor

RateLimitInterceptor returns an Interceptor (unary + stream) that admits RPCs under a token-bucket limiter and rejects excess with codes.ResourceExhausted. It composes into any InterceptorChain. Per-method or per-client scoping is achieved by setting KeyFunc (e.g. PeerKey, or a func keying on fullMethod).

Like the HTTP limiter, admission is non-blocking (Allow, not Wait): ingress must reject excess, never queue it, or a flood would exhaust memory.

type InterceptorChain

type InterceptorChain struct {
	// contains filtered or unexported fields
}

InterceptorChain composes zero or more gRPC interceptors into ordered slices suitable for grpc.ChainUnaryInterceptor and grpc.ChainStreamInterceptor.

func NewInterceptorChain

func NewInterceptorChain(interceptors ...Interceptor) InterceptorChain

NewInterceptorChain creates a new interceptor chain. Each Interceptor argument provides a unary interceptor, a stream interceptor, or both. Nil entries in either field are silently skipped.

func (InterceptorChain) Append

func (c InterceptorChain) Append(interceptors ...Interceptor) InterceptorChain

Append returns a new InterceptorChain with additional interceptors appended. The original chain is not modified.

func (InterceptorChain) ServerOptions

func (c InterceptorChain) ServerOptions() []grpc.ServerOption

ServerOptions returns grpc.ServerOption values that install the chain. This is the primary integration point — pass the result to grpc.NewServer or to NewServer's variadic options.

chain := NewInterceptorChain(logging, recovery)
srv, _ := NewServer(cfg, chain.ServerOptions()...)

type RateLimitConfig added in v0.23.0

type RateLimitConfig struct {
	// RequestsPerSecond is the sustained fill rate. Must be > 0. Default: 50.
	RequestsPerSecond float64
	// Burst is the bucket capacity. Must be >= 1. Default: 100.
	Burst int
	// MaxTrackedKeys bounds the per-key bucket store (ignored when KeyFunc is
	// nil). Must be >= 1. Default: 8192.
	MaxTrackedKeys int
	// KeyFunc derives the limiter key from the RPC context and full method name,
	// enabling per-client or per-method limiting. When nil, a single global
	// bucket is used. See PeerKey.
	KeyFunc func(ctx context.Context, fullMethod string) string
	// OnLimited is invoked when an RPC is rejected. Optional.
	OnLimited func(ctx context.Context, fullMethod string)
}

RateLimitConfig configures the server-side token-bucket rate limiter for gRPC ingress, mirroring the HTTP server limiter.

func DefaultRateLimitConfig added in v0.23.0

func DefaultRateLimitConfig() RateLimitConfig

DefaultRateLimitConfig returns a limiter suitable for a modest management server: 50 rps sustained, burst 100, single global bucket.

func RateLimitConfigFromConfig added in v0.23.0

func RateLimitConfigFromConfig(cfg config.Containable, prefix string) RateLimitConfig

RateLimitConfigFromConfig builds a RateLimitConfig from the config layer under "<prefix>.ratelimit.*" (prefix defaults to "server.grpc"), mirroring the HTTP helper. Recognised keys: requests_per_second (float), burst (int), max_tracked_keys (int). Unset keys keep their defaults; KeyFunc/OnLimited are never read from config.

type RegisterOption

type RegisterOption func(*registerConfig)

RegisterOption configures optional behaviour for gRPC server registration.

func WithInterceptors

func WithInterceptors(chain InterceptorChain) RegisterOption

WithInterceptors prepends the given interceptor chain before any grpc.ServerOption interceptors passed via the variadic opts.

type ServerOption added in v0.9.0

type ServerOption func(*serverConfig)

ServerOption configures the config prefix and port a gRPC server reads. ServerOption values are accepted by NewServer, Start, DialLocal and Register (alongside grpc.ServerOption / grpc.DialOption values).

func WithConfigPrefix added in v0.9.0

func WithConfigPrefix(prefix string) ServerOption

WithConfigPrefix sets the config prefix the server reads its port, reflection and TLS settings from (default "server.grpc"). Pass the SAME prefix to NewServer, Start and DialLocal to keep a non-default server consistent.

func WithPort added in v0.9.0

func WithPort(port int) ServerOption

WithPort sets the listen (or dial) port explicitly, bypassing config lookup. It overrides both <prefix>.port and the server.port shared fallback.

Jump to

Keyboard shortcuts

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