Skip to content

go-coldbrew/interceptors

CI Go Report Card GoDoc License: MIT

interceptors

import "github.com/go-coldbrew/interceptors"

Package interceptors provides gRPC server and client interceptors for the ColdBrew framework.

Interceptor configuration functions (AddUnaryServerInterceptor, SetFilterFunc, etc.) must be called during program initialization, before the gRPC server starts. They are not safe for concurrent use.

Index

Constants

SupportPackageIsVersion1 is a compile-time assertion constant. Downstream packages (e.g. core) reference this constant to enforce version compatibility. When interceptors makes a breaking change, export a new constant and remove this one to force coordinated updates.

const SupportPackageIsVersion1 = true

Variables

var (
    // Deprecated: FilterMethods is the list of methods that are filtered by default.
    // Use SetFilterMethods instead. Only some direct mutations (replacing the slice
    // or changing the first element) are detected by internal change detection;
    // other in-place changes may not invalidate caches correctly.
    FilterMethods = []string{"healthcheck", "readycheck", "serverreflectioninfo"}
)

func AddStreamClientInterceptor(ctx context.Context, i ...grpc.StreamClientInterceptor)

AddStreamClientInterceptor adds a client stream interceptor to default client stream interceptors. Must be called during initialization, before any RPCs are made. Not safe for concurrent use.

func AddStreamServerInterceptor(ctx context.Context, i ...grpc.StreamServerInterceptor)

AddStreamServerInterceptor adds a server interceptor to default server interceptors. Must be called during initialization, before the server starts. Not safe for concurrent use.

func AddUnaryClientInterceptor(ctx context.Context, i ...grpc.UnaryClientInterceptor)

AddUnaryClientInterceptor adds a client interceptor to default client interceptors. Must be called during initialization, before any RPCs are made. Not safe for concurrent use.

func AddUnaryServerInterceptor(ctx context.Context, i ...grpc.UnaryServerInterceptor)

AddUnaryServerInterceptor adds a server interceptor to default server interceptors. Must be called during initialization, before the server starts. Not safe for concurrent use.

func DebugLogInterceptor() grpc.UnaryServerInterceptor

DebugLogInterceptor enables per-request log level override based on a proto field or gRPC metadata header. It checks (in order):

  1. Proto field: GetDebug() bool or GetEnableDebug() bool — always sets DebugLevel
  2. Metadata header: configurable via SetDebugLogHeaderName (default "x-debug-log-level") — the header value is parsed as a log level, allowing any valid level (debug, info, warn, error)

Combined with ColdBrew's trace ID propagation, this allows enabling debug logging for a single request and following it across services via trace ID.

func DebugLoggingInterceptor() grpc.UnaryServerInterceptor

DebugLoggingInterceptor is the interceptor that logs all request/response from a handler

func DefaultClientInterceptor(defaultOpts ...any) grpc.UnaryClientInterceptor

DefaultClientInterceptor are the set of default interceptors that should be applied to all client calls

func DefaultClientInterceptors(defaultOpts ...any) []grpc.UnaryClientInterceptor

DefaultClientInterceptors are the set of default interceptors that should be applied to all client calls

func DefaultClientStreamInterceptor(defaultOpts ...any) grpc.StreamClientInterceptor

DefaultClientStreamInterceptor are the set of default interceptors that should be applied to all stream client calls

func DefaultClientStreamInterceptors(defaultOpts ...any) []grpc.StreamClientInterceptor

DefaultClientStreamInterceptors are the set of default interceptors that should be applied to all stream client calls

func DefaultInterceptors() []grpc.UnaryServerInterceptor

DefaultInterceptors are the set of default interceptors that are applied to all coldbrew methods

func DefaultStreamInterceptors() []grpc.StreamServerInterceptor

DefaultStreamInterceptors are the set of default interceptors that should be applied to all coldbrew streams

func DefaultTimeoutInterceptor() grpc.UnaryServerInterceptor

DefaultTimeoutInterceptor returns a unary server interceptor that applies a default deadline to incoming requests that have no deadline set. If the incoming context already has a deadline (regardless of duration), it is left unchanged. When defaultTimeout is <= 0, the interceptor is a no-op pass-through.

func DoHTTPtoGRPC(ctx context.Context, svr any, handler func(ctx context.Context, req any) (any, error), in any) (any, error)

DoHTTPtoGRPC allows calling the interceptors when you use the Register<svc-name>HandlerServer in grpc-gateway. This enables in-process HTTP-to-gRPC calls with the full interceptor chain (logging, tracing, metrics, panic recovery) without a network hop — the fastest option for gateway performance. The interceptor chain is cached on first invocation. All interceptor configuration (AddUnaryServerInterceptor, SetFilterFunc, etc.) must be finalized before the first call. See example below for reference.

func (s *svc) Echo(ctx context.Context, req *proto.EchoRequest) (*proto.EchoResponse, error) {
    handler := func(ctx context.Context, req interface{}) (interface{}, error) {
        return s.echo(ctx, req.(*proto.EchoRequest))
    }
    r, err := DoHTTPtoGRPC(ctx, s, handler, req)
    if err != nil {
        return nil, err
    }
    return r.(*proto.EchoResponse), nil
}

func (s *svc) echo(ctx context.Context, req *proto.EchoRequest) (*proto.EchoResponse, error) {
       .... implementation ....
}

func FilterMethodsFunc(ctx context.Context, fullMethodName string) bool

FilterMethodsFunc is the default implementation of Filter function

func GRPCClientInterceptor(_ ...any) grpc.UnaryClientInterceptor

Deprecated: GRPCClientInterceptor is no longer needed. gRPC tracing is now handled by google.golang.org/grpc/stats/opentelemetry, configured via opentelemetry.DialOption() at the client level. This function is retained for backwards compatibility but returns a no-op interceptor.

func GetDebugLogHeaderName() string

GetDebugLogHeaderName returns the current debug log header name.

func HystrixClientInterceptor(defaultOpts ...grpc.CallOption) grpc.UnaryClientInterceptor

HystrixClientInterceptor returns a unary client interceptor that executes the RPC inside a Hystrix command.

Note: This interceptor wraps github.com/afex/hystrix-go which has been unmaintained since 2018. Consider migrating to github.com/failsafe-go/failsafe-go for circuit breaker functionality.

The interceptor applies provided default and per-call client options to configure Hystrix behavior (for example the command name, disabled flag, excluded errors, and excluded gRPC status codes). If Hystrix is disabled via options, the RPC is invoked directly. If the underlying RPC returns an error that matches any configured excluded error or whose gRPC status code matches any configured excluded code, Hystrix fallback is skipped and the RPC error is returned. Panics raised during the RPC invocation are captured and reported to the notifier before being converted into an error. If the RPC itself returns an error, that error is returned; otherwise any error produced by Hystrix is returned.

func NRHttpTracer(pattern string, h http.HandlerFunc) (string, http.HandlerFunc)

NRHttpTracer adds newrelic tracing to this http function

func NewRelicClientInterceptor() grpc.UnaryClientInterceptor

NewRelicClientInterceptor intercepts all client actions and reports them to newrelic. When NewRelic app is nil (no license key configured), returns a pass-through interceptor to avoid overhead.

func NewRelicInterceptor() grpc.UnaryServerInterceptor

NewRelicInterceptor intercepts all server actions and reports them to newrelic. When NewRelic app is nil (no license key configured), returns a pass-through interceptor to avoid overhead.

func OptionsInterceptor() grpc.UnaryServerInterceptor

func PanicRecoveryInterceptor() grpc.UnaryServerInterceptor

func PanicRecoveryStreamInterceptor() grpc.StreamServerInterceptor

PanicRecoveryStreamInterceptor recovers from panics in stream handlers, logs the panic and stack trace, and reports it to the error notifier.

func ProtoValidateInterceptor() grpc.UnaryServerInterceptor

ProtoValidateInterceptor returns a unary server interceptor that validates incoming messages using protovalidate annotations. Returns InvalidArgument on validation failure. Uses GlobalValidator by default; if custom options are set via SetProtoValidateOptions, creates a new validator with those options.

func ProtoValidateStreamInterceptor() grpc.StreamServerInterceptor

ProtoValidateStreamInterceptor returns a stream server interceptor that validates incoming messages using protovalidate annotations.

func ResponseTimeLoggingInterceptor(ff FilterFunc) grpc.UnaryServerInterceptor

ResponseTimeLoggingInterceptor logs response time for each request on server

func ResponseTimeLoggingStreamInterceptor() grpc.StreamServerInterceptor

ResponseTimeLoggingStreamInterceptor logs response time for stream RPCs.

func ServerErrorInterceptor() grpc.UnaryServerInterceptor

ServerErrorInterceptor intercepts all server actions and reports them to error notifier

func ServerErrorStreamInterceptor() grpc.StreamServerInterceptor

ServerErrorStreamInterceptor intercepts server errors for stream RPCs and reports them to the error notifier.

func SetClientMetricsOptions(opts ...grpcprom.ClientMetricsOption)

SetClientMetricsOptions appends gRPC client metrics options. Must be called during initialization, before any RPCs are made. Not safe for concurrent use.

func SetDebugLogHeaderName(name string)

SetDebugLogHeaderName sets the gRPC metadata header name that triggers per-request log level override. Default is "x-debug-log-level". The header value should be a valid log level (e.g., "debug"). Empty names are ignored. Must be called during initialization.

func SetDefaultRateLimit(rps float64, burst int)

SetDefaultRateLimit configures the built-in token bucket rate limiter. rps is requests per second, burst is the maximum burst size. This is a per-pod in-memory limit — with N pods, the effective cluster-wide limit is N × rps. For distributed rate limiting, use SetRateLimiter() with a custom implementation (e.g., Redis-backed). Must be called during initialization.

func SetDefaultTimeout(d time.Duration)

SetDefaultTimeout sets the default timeout applied to incoming unary RPCs that arrive without a deadline. When set to <= 0, the timeout interceptor is disabled (pass-through). Default is 60s. Must be called during initialization, before the server starts. Not safe for concurrent use.

func SetDisableDebugLogInterceptor(disable bool)

SetDisableDebugLogInterceptor disables the DebugLogInterceptor in the default interceptor chain. Must be called during initialization, before the server starts.

func SetDisableProtoValidate(disable bool)

SetDisableProtoValidate disables the protovalidate interceptor in the default chain. Must be called during init() — not safe for concurrent use.

func SetDisableRateLimit(disable bool)

SetDisableRateLimit disables the rate limiting interceptor in the default interceptor chain. Must be called during initialization.

func SetFilterFunc(ctx context.Context, ff FilterFunc)

SetFilterFunc sets the default filter function to be used by interceptors. Must be called during initialization, before the server starts. Not safe for concurrent use.

func SetFilterMethods(ctx context.Context, methods []string)

SetFilterMethods sets the list of method substrings to exclude from tracing/logging. It rebuilds the internal cache. Must be called during initialization, before the server starts. Not safe for concurrent use.

func SetProtoValidateOptions(opts ...protovalidate.ValidatorOption)

SetProtoValidateOptions configures custom protovalidate options (e.g., custom constraints). Must be called during init() — not safe for concurrent use. Follows ColdBrew's init-only config pattern.

func SetRateLimiter(limiter ratelimit_middleware.Limiter)

SetRateLimiter sets a custom rate limiter implementation. This overrides the built-in token bucket limiter. Must be called during initialization.

func SetResponseTimeLogErrorOnly(errorOnly bool)

SetResponseTimeLogErrorOnly when set to true, only logs response time when the request returns an error. Successful requests are not logged. Must be called during initialization, before the server starts. Not safe for concurrent use.

func SetResponseTimeLogLevel(ctx context.Context, level loggers.Level)

SetResponseTimeLogLevel sets the log level for response time logging. Default is InfoLevel. Must be called during initialization, before the server starts. Not safe for concurrent use.

func SetServerMetricsOptions(opts ...grpcprom.ServerMetricsOption)

SetServerMetricsOptions appends gRPC server metrics options (histogram, labels, namespace, etc.). Must be called during initialization, before the server starts. Not safe for concurrent use.

func TraceIdInterceptor() grpc.UnaryServerInterceptor

TraceIdInterceptor allows injecting trace id from request objects

func UseColdBrewClientInterceptors(ctx context.Context, flag bool)

UseColdBrewClientInterceptors allows enabling/disabling coldbrew client interceptors. When set to false, the coldbrew client interceptors will not be used. Must be called during initialization, before any RPCs are made. Not safe for concurrent use.

func UseColdBrewServerInterceptors(ctx context.Context, flag bool)

UseColdBrewServerInterceptors allows enabling/disabling coldbrew server interceptors. When set to false, the coldbrew server interceptors will not be used. Must be called during initialization, before the server starts. Not safe for concurrent use.

If it returns false, the given request will not be traced.

type FilterFunc func(ctx context.Context, fullMethodName string) bool

Generated by gomarkdoc

About

Chained gRPC interceptors for logging, tracing, Prometheus metrics, circuit breaking, and retries

Topics

Resources

License

Code of conduct

Contributing

Security policy

Stars

Watchers

Forks

Contributors