interceptors

package module
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2026 License: Apache-2.0 Imports: 31 Imported by: 1

README

CI Go Report Card GoDoc

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. Any direct mutation (replacing the slice
    // or editing it in place) is detected via a content hash.
    // SetFilterMethods is the supported API for updating the filter list.
    FilterMethods = []string{"healthcheck", "readycheck", "serverreflectioninfo"}
)

func AddStreamClientInterceptor

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

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

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

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

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

func DebugLoggingInterceptor() grpc.UnaryServerInterceptor

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

func DefaultClientInterceptor

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

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

func DefaultClientInterceptors

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

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

func DefaultClientStreamInterceptor

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

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

func DefaultClientStreamInterceptors

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

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

func DefaultInterceptors

func DefaultInterceptors() []grpc.UnaryServerInterceptor

DefaultInterceptors returns the default unary server interceptor chain. The ordering is defined by the unaryPos* constants above; this function assigns each interceptor to its named slot and drops any slot that is disabled via configuration. See the ordering contract above for semantics.

func DefaultStreamInterceptors

func DefaultStreamInterceptors() []grpc.StreamServerInterceptor

DefaultStreamInterceptors returns the default stream server interceptor chain. The ordering is defined by the streamPos* constants above; this function assigns each interceptor to its named slot and drops any slot that is disabled via configuration. See the ordering contract above for semantics.

func DefaultTimeoutInterceptor

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

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 ExecutorClientInterceptor

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

ExecutorClientInterceptor returns a unary client interceptor that wraps each RPC in an Executor. The executor provides resilience logic such as circuit breaking, retries, or bulkheading.

Executor resolution order: per-call [WithExecutor] > global SetDefaultExecutor. When no executor is configured, the interceptor falls back to HystrixClientInterceptor for backward compatibility. When the caller explicitly opts out via [WithoutExecutor] or [WithoutHystrix], the RPC is invoked directly as a passthrough.

Excluded errors and codes (set via [WithExcludedErrors] / [WithExcludedCodes]) are reported as nil to the executor, preventing them from tripping circuit breakers or retry logic. The original error is still returned to the caller.

func FilterMethodsFunc

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

FilterMethodsFunc is the default implementation of Filter function

func GRPCClientInterceptor

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

func GetDebugLogHeaderName() string

GetDebugLogHeaderName returns the current debug log header name.

func HystrixClientInterceptor

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

Deprecated: HystrixClientInterceptor wraps the unmaintained hystrix-go library. Use SetDefaultExecutor with a failsafe-go executor instead. Will be removed in v1.

See ExecutorClientInterceptor for the replacement.

func NRHttpTracer

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

NRHttpTracer wraps an HTTP handler with New Relic tracing. The configured filterFunc (see SetFilterFunc) is consulted on every request: paths it rejects run the underlying handler without starting a New Relic transaction. When pattern is non-empty, newrelic.WrapHandleFunc is used so its route-level instrumentation stays intact for non-filtered paths.

func NewRelicClientInterceptor

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

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

func OptionsInterceptor() grpc.UnaryServerInterceptor

func PanicRecoveryInterceptor

func PanicRecoveryInterceptor() grpc.UnaryServerInterceptor

func PanicRecoveryStreamInterceptor

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

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

func ProtoValidateStreamInterceptor() grpc.StreamServerInterceptor

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

func ResponseTimeLoggingInterceptor

func ResponseTimeLoggingInterceptor(ff FilterFunc) grpc.UnaryServerInterceptor

ResponseTimeLoggingInterceptor logs response time for each request on server

func ResponseTimeLoggingStreamInterceptor

func ResponseTimeLoggingStreamInterceptor() grpc.StreamServerInterceptor

ResponseTimeLoggingStreamInterceptor logs response time for stream RPCs.

func ServerErrorInterceptor

func ServerErrorInterceptor() grpc.UnaryServerInterceptor

ServerErrorInterceptor intercepts all server actions and reports them to error notifier

func ServerErrorStreamInterceptor

func ServerErrorStreamInterceptor() grpc.StreamServerInterceptor

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

func SetClientMetricsOptions

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

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 SetDefaultExecutor

func SetDefaultExecutor(e Executor)

SetDefaultExecutor sets the default Executor used by ExecutorClientInterceptor for outbound unary RPCs when ColdBrew client interceptors are enabled (the default). In that configuration, when no executor is configured (neither global via SetDefaultExecutor nor per-call via [WithExecutor]), ExecutorClientInterceptor falls back to HystrixClientInterceptor for backward compatibility. Must be called during initialization, before any RPCs are made. Not safe for concurrent use.

func SetDefaultRateLimit

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

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

func SetDisableDebugLogInterceptor(disable bool)

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

func SetDisableProtoValidate

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

func SetDisableRateLimit(disable bool)

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

func SetFilterFunc

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

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

func SetProtoValidateOptions(opts ...protovalidate.ValidatorOption) error

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.

The combined option set (existing + new) is validated immediately by constructing a protovalidate.Validator. If construction fails, the new options are NOT appended and the error is returned so the caller can surface it (typically by failing process startup). Callers that ignore the error keep working with whatever option set was last accepted — the lazy getProtoValidator path still falls back to GlobalValidator on error as a defensive backstop.

On success the cached validator is invalidated so the next getProtoValidator() rebuilds with the updated option set; this matters when SetProtoValidateOptions is called after DefaultInterceptors() has already constructed ProtoValidateInterceptor.

func SetRateLimiter

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

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

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

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

func TraceIdInterceptor() grpc.UnaryServerInterceptor

TraceIdInterceptor allows injecting trace id from request objects

func UseColdBrewClientInterceptors

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

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.

type Executor

Executor wraps an RPC invocation with resilience logic (circuit breaking, retries, bulkheading, etc.). The method parameter is the full gRPC method name (e.g., "/package.Service/Method"), enabling per-method state such as per-method circuit breakers. The executor is responsible for invoking fn and may call it multiple times when implementing retries.

type Executor func(ctx context.Context, method string, fn func(ctx context.Context) error) error

type FilterFunc

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

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

Generated by gomarkdoc

Documentation

Overview

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

View Source
const SupportPackageIsVersion1 = true

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.

Variables

View Source
var (
	// Deprecated: FilterMethods is the list of methods that are filtered by default.
	// Use SetFilterMethods instead. Any direct mutation (replacing the slice
	// or editing it in place) is detected via a content hash.
	// SetFilterMethods is the supported API for updating the filter list.
	FilterMethods = []string{"healthcheck", "readycheck", "serverreflectioninfo"}
)

Functions

func AddStreamClientInterceptor added in v0.1.5

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 added in v0.1.5

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 added in v0.1.5

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 added in v0.1.5

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 added in v0.1.23

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

func DebugLoggingInterceptor() grpc.UnaryServerInterceptor

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

func DefaultClientInterceptor

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

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

func DefaultClientInterceptors

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

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

func DefaultClientStreamInterceptor added in v0.1.4

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

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

func DefaultClientStreamInterceptors added in v0.1.4

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

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

func DefaultInterceptors

func DefaultInterceptors() []grpc.UnaryServerInterceptor

DefaultInterceptors returns the default unary server interceptor chain. The ordering is defined by the unaryPos* constants above; this function assigns each interceptor to its named slot and drops any slot that is disabled via configuration. See the ordering contract above for semantics.

func DefaultStreamInterceptors

func DefaultStreamInterceptors() []grpc.StreamServerInterceptor

DefaultStreamInterceptors returns the default stream server interceptor chain. The ordering is defined by the streamPos* constants above; this function assigns each interceptor to its named slot and drops any slot that is disabled via configuration. See the ordering contract above for semantics.

func DefaultTimeoutInterceptor added in v0.1.22

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 added in v0.1.2

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 ExecutorClientInterceptor added in v0.1.26

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

ExecutorClientInterceptor returns a unary client interceptor that wraps each RPC in an Executor. The executor provides resilience logic such as circuit breaking, retries, or bulkheading.

Executor resolution order: per-call WithExecutor > global SetDefaultExecutor. When no executor is configured, the interceptor falls back to HystrixClientInterceptor for backward compatibility. When the caller explicitly opts out via WithoutExecutor or WithoutHystrix, the RPC is invoked directly as a passthrough.

Excluded errors and codes (set via WithExcludedErrors / WithExcludedCodes) are reported as nil to the executor, preventing them from tripping circuit breakers or retry logic. The original error is still returned to the caller.

func FilterMethodsFunc

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

FilterMethodsFunc is the default implementation of Filter function

func GRPCClientInterceptor deprecated

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 added in v0.1.23

func GetDebugLogHeaderName() string

GetDebugLogHeaderName returns the current debug log header name.

func HystrixClientInterceptor deprecated

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

Deprecated: HystrixClientInterceptor wraps the unmaintained hystrix-go library. Use SetDefaultExecutor with a failsafe-go executor instead. Will be removed in v1.

See ExecutorClientInterceptor for the replacement.

func NRHttpTracer

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

NRHttpTracer wraps an HTTP handler with New Relic tracing. The configured filterFunc (see SetFilterFunc) is consulted on every request: paths it rejects run the underlying handler without starting a New Relic transaction. When pattern is non-empty, newrelic.WrapHandleFunc is used so its route-level instrumentation stays intact for non-filtered paths.

func NewRelicClientInterceptor

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

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

func OptionsInterceptor() grpc.UnaryServerInterceptor

func PanicRecoveryInterceptor

func PanicRecoveryInterceptor() grpc.UnaryServerInterceptor

func PanicRecoveryStreamInterceptor added in v0.1.25

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 added in v0.1.20

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 added in v0.1.20

func ProtoValidateStreamInterceptor() grpc.StreamServerInterceptor

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

func ResponseTimeLoggingInterceptor

func ResponseTimeLoggingInterceptor(ff FilterFunc) grpc.UnaryServerInterceptor

ResponseTimeLoggingInterceptor logs response time for each request on server

func ResponseTimeLoggingStreamInterceptor

func ResponseTimeLoggingStreamInterceptor() grpc.StreamServerInterceptor

ResponseTimeLoggingStreamInterceptor logs response time for stream RPCs.

func ServerErrorInterceptor

func ServerErrorInterceptor() grpc.UnaryServerInterceptor

ServerErrorInterceptor intercepts all server actions and reports them to error notifier

func ServerErrorStreamInterceptor

func ServerErrorStreamInterceptor() grpc.StreamServerInterceptor

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

func SetClientMetricsOptions added in v0.1.12

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 added in v0.1.23

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 SetDefaultExecutor added in v0.1.26

func SetDefaultExecutor(e Executor)

SetDefaultExecutor sets the default Executor used by ExecutorClientInterceptor for outbound unary RPCs when ColdBrew client interceptors are enabled (the default). In that configuration, when no executor is configured (neither global via SetDefaultExecutor nor per-call via WithExecutor), ExecutorClientInterceptor falls back to HystrixClientInterceptor for backward compatibility. Must be called during initialization, before any RPCs are made. Not safe for concurrent use.

func SetDefaultRateLimit added in v0.1.24

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 added in v0.1.22

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 added in v0.1.23

func SetDisableDebugLogInterceptor(disable bool)

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

func SetDisableProtoValidate added in v0.1.20

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 added in v0.1.24

func SetDisableRateLimit(disable bool)

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

func SetFilterFunc

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 added in v0.1.14

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 added in v0.1.20

func SetProtoValidateOptions(opts ...protovalidate.ValidatorOption) error

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.

The combined option set (existing + new) is validated immediately by constructing a protovalidate.Validator. If construction fails, the new options are NOT appended and the error is returned so the caller can surface it (typically by failing process startup). Callers that ignore the error keep working with whatever option set was last accepted — the lazy getProtoValidator path still falls back to GlobalValidator on error as a defensive backstop.

On success the cached validator is invalidated so the next getProtoValidator() rebuilds with the updated option set; this matters when SetProtoValidateOptions is called after DefaultInterceptors() has already constructed ProtoValidateInterceptor.

func SetRateLimiter added in v0.1.24

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 added in v0.1.15

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 added in v0.1.11

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 added in v0.1.12

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 added in v0.1.2

func TraceIdInterceptor() grpc.UnaryServerInterceptor

TraceIdInterceptor allows injecting trace id from request objects

func UseColdBrewClientInterceptors added in v0.1.5

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 added in v0.1.5

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.

func WithExcludedCodes added in v0.1.26

func WithExcludedCodes(codes ...codes.Code) clientOption

WithExcludedCodes returns a clientOption that appends the provided gRPC status codes to the exclusion list. Excluded codes are reported as success to the executor (not tripping circuit breakers), but the original error is still returned to the caller.

func WithExcludedErrors added in v0.1.26

func WithExcludedErrors(errors ...error) clientOption

WithExcludedErrors returns a clientOption that adds the provided errors to the exclusion list. Excluded errors are reported as success to the executor (not tripping circuit breakers), but the original error is still returned to the caller.

func WithExecutor added in v0.1.26

func WithExecutor(e Executor) clientOption

WithExecutor returns a clientOption that sets a custom Executor for resilience logic (circuit breaking, retries, etc.). The executor wraps the RPC invocation. This overrides the global executor set via SetDefaultExecutor for this call.

func WithHystrix deprecated

func WithHystrix() clientOption

Deprecated: WithHystrix enables hystrix. The executor is enabled by default when configured via SetDefaultExecutor. Will be removed in v1.

func WithHystrixExcludedCodes deprecated added in v0.1.9

func WithHystrixExcludedCodes(codes ...codes.Code) clientOption

Deprecated: WithHystrixExcludedCodes appends gRPC codes excluded from the Hystrix circuit breaker. Use WithExcludedCodes instead. Will be removed in v1.

func WithHystrixExcludedErrors deprecated added in v0.1.8

func WithHystrixExcludedErrors(errors ...error) clientOption

Deprecated: WithHystrixExcludedErrors adds errors excluded from the Hystrix circuit breaker. Use WithExcludedErrors instead. Will be removed in v1.

func WithHystrixName deprecated

func WithHystrixName(name string) clientOption

Deprecated: WithHystrixName sets the Hystrix command name. Use WithExecutor with a per-method executor instead. Will be removed in v1.

func WithoutExecutor added in v0.1.26

func WithoutExecutor() clientOption

WithoutExecutor returns a clientOption that disables the executor for this call, even if a global executor is set via SetDefaultExecutor. The RPC is invoked directly as a passthrough.

func WithoutHystrix deprecated

func WithoutHystrix() clientOption

Deprecated: WithoutHystrix disables hystrix and the executor. Use WithoutExecutor instead. Will be removed in v1.

Types

type Executor added in v0.1.26

type Executor func(ctx context.Context, method string, fn func(ctx context.Context) error) error

Executor wraps an RPC invocation with resilience logic (circuit breaking, retries, bulkheading, etc.). The method parameter is the full gRPC method name (e.g., "/package.Service/Method"), enabling per-method state such as per-method circuit breakers. The executor is responsible for invoking fn and may call it multiple times when implementing retries.

type FilterFunc

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

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

Jump to

Keyboard shortcuts

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