interceptor

package
v1.22.0 Latest Latest
Warning

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

Go to latest
Published: Aug 12, 2025 License: MIT Imports: 20 Imported by: 0

README

grpcserver/interceptor

A collection of gRPC interceptors for logging, metrics collection, panic recovery, request ID handling, rate limiting, and in-flight limiting. These interceptors enhance gRPC services with observability, reliability, and traffic control features.

See complete working example of using these interceptors in the Echo Service Example.

Table of Contents

Available Interceptors

Logging Interceptor

Provides comprehensive logging for gRPC calls with configurable options.

Features:

  • Call start and finish logging
  • Slow call detection
  • Custom header logging
  • Method exclusion
  • Custom logger providers
  • Request ID and trace ID integration

Usage:

import "github.com/acronis/go-appkit/grpcserver/interceptor"

// Basic usage
unaryInterceptor := interceptor.LoggingUnaryInterceptor(logger)
streamInterceptor := interceptor.LoggingStreamInterceptor(logger)

// With options
unaryInterceptor := interceptor.LoggingUnaryInterceptor(logger,
    interceptor.WithLoggingCallStart(true),
    interceptor.WithLoggingSlowCallThreshold(2*time.Second),
    interceptor.WithLoggingExcludedMethods("/health/check", "/metrics"),
    interceptor.WithLoggingCallHeaders(map[string]string{
        "x-tenant-id": "tenant_id",
        "x-user-id": "user_id",
    }),
)

Configuration Options:

  • WithLoggingCallStart(bool): Enable/disable call start logging
  • WithLoggingSlowCallThreshold(time.Duration): Set slow call threshold
  • WithLoggingExcludedMethods(...string): Exclude specific methods from logging
  • WithLoggingCallHeaders(map[string]string): Log custom headers
  • WithLoggingUnaryCustomLoggerProvider(func): Custom logger provider for unary calls
  • WithLoggingStreamCustomLoggerProvider(func): Custom logger provider for stream calls
Metrics Interceptor

Collects Prometheus metrics for gRPC calls.

Features:

  • Call duration histograms
  • In-flight call gauges
  • Method and service labels
  • User agent type classification
  • Custom label support

Usage:

// Create metrics collector
metrics := interceptor.NewPrometheusMetrics(
    interceptor.WithPrometheusNamespace("myapp"),
    interceptor.WithPrometheusDurationBuckets([]float64{0.1, 0.5, 1.0, 5.0}),
    interceptor.WithPrometheusConstLabels(prometheus.Labels{"version": "1.0"}),
)

// Register metrics
metrics.MustRegister()

// Create interceptors
unaryInterceptor := interceptor.MetricsUnaryInterceptor(metrics)
streamInterceptor := interceptor.MetricsStreamInterceptor(metrics)

// With user agent type provider
unaryInterceptor := interceptor.MetricsUnaryInterceptor(metrics,
    interceptor.WithMetricsUnaryUserAgentTypeProvider(func(ctx context.Context, info *grpc.UnaryServerInfo) string {
        // Return user agent type based on context
        return "c2c_agent" // or "mobile", "api", etc.
    }),
)

Metrics Collected:

  • grpc_call_duration_seconds: Histogram of call durations
  • grpc_calls_in_flight: Gauge of currently active calls

Labels:

  • grpc_service: Service name
  • grpc_method: Method name
  • grpc_method_type: "unary" or "stream"
  • grpc_code: gRPC status code
  • user_agent_type: Classification of user agent (if provided)
Recovery Interceptor

Recovers from panics and returns proper gRPC errors.

Features:

  • Panic recovery with stack trace logging
  • Configurable stack size
  • Proper gRPC error responses

Usage:

// Basic usage
unaryInterceptor := interceptor.RecoveryUnaryInterceptor()
streamInterceptor := interceptor.RecoveryStreamInterceptor()

// With custom stack size
unaryInterceptor := interceptor.RecoveryUnaryInterceptor(
    interceptor.WithRecoveryStackSize(16384),
)

Configuration Options:

  • WithRecoveryStackSize(int): Set stack trace size for logging (default: 8192)
Request ID Interceptor

Manages request IDs for call tracing and correlation.

Features:

  • Extracts request ID from incoming headers
  • Generates new request IDs if missing
  • Generates internal request IDs
  • Sets response headers
  • Context integration

Usage:

// Basic usage
unaryInterceptor := interceptor.RequestIDUnaryInterceptor()
streamInterceptor := interceptor.RequestIDStreamInterceptor()

// With custom ID generators
unaryInterceptor := interceptor.RequestIDUnaryInterceptor(
    interceptor.WithRequestIDGenerator(func() string {
        return uuid.New().String()
    }),
    interceptor.WithInternalRequestIDGenerator(func() string {
        return fmt.Sprintf("internal-%d", time.Now().UnixNano())
    }),
)

Headers:

  • x-request-id: External request ID (extracted or generated)
  • x-int-request-id: Internal request ID (always generated)
Rate Limiting Interceptor

Provides comprehensive rate limiting for gRPC calls with multiple algorithms and extensive customization options.

Features:

  • Multiple rate limiting algorithms (leaky bucket, sliding window)
  • Per-client rate limiting with custom key extraction
  • Backlog support for queuing requests
  • Dry run mode for testing without enforcement
  • Customizable callbacks for rejection and error handling
  • Retry-After header support
  • Comprehensive logging and error handling

Usage:

import "github.com/acronis/go-appkit/grpcserver/interceptor"

// Basic usage with 10 requests per second
rate := interceptor.Rate{Count: 10, Duration: time.Second}
unaryInterceptor, err := interceptor.RateLimitUnaryInterceptor(rate)
streamInterceptor, err := interceptor.RateLimitStreamInterceptor(rate)

// With advanced configuration
unaryInterceptor, err := interceptor.RateLimitUnaryInterceptor(rate,
    // Algorithm selection
    interceptor.WithRateLimitAlg(interceptor.RateLimitAlgLeakyBucket),
    interceptor.WithRateLimitMaxBurst(20),
    
    // Per-client rate limiting
    interceptor.WithRateLimitUnaryGetKey(func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo) (string, bool, error) {
        if md, ok := metadata.FromIncomingContext(ctx); ok {
            if clientIDs := md.Get("client-id"); len(clientIDs) > 0 {
                return clientIDs[0], false, nil
            }
        }
        return "", true, nil // bypass if no client-id
    }),
    
    // Backlog configuration
    interceptor.WithRateLimitBacklogLimit(100),
    interceptor.WithRateLimitBacklogTimeout(5*time.Second),
    
    // Dry run mode
    interceptor.WithRateLimitDryRun(true),
    
    // Custom callbacks
    interceptor.WithRateLimitUnaryOnReject(func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, params interceptor.RateLimitParams) (interface{}, error) {
        // Custom rejection logic
        return nil, status.Error(codes.ResourceExhausted, "Rate limit exceeded: "+params.Key)
    }),
)

Rate Limiting Algorithms:

  • RateLimitAlgLeakyBucket: Token bucket algorithm with burst support
  • RateLimitAlgSlidingWindow: Sliding window algorithm

Key Extraction Examples:

// Rate limit by client IP
func rateLimitByIP(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo) (string, bool, error) {
    if p, ok := peer.FromContext(ctx); ok {
        if host, _, err := net.SplitHostPort(p.Addr.String()); err == nil {
            return host, false, nil
        }
        return p.Addr.String(), false, nil
    }
    return "", true, nil // bypass if no peer info
}

// Rate limit by user ID from JWT
func rateLimitByUserID(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo) (string, bool, error) {
    userID := getUserIDFromJWT(ctx)
    if userID != "" {
        return userID, false, nil
    }
    return "", true, nil // bypass for unauthenticated requests
}

// Rate limit by tenant ID from metadata
func rateLimitByTenant(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo) (string, bool, error) {
    if md, ok := metadata.FromIncomingContext(ctx); ok {
        if tenantIDs := md.Get("x-tenant-id"); len(tenantIDs) > 0 {
            return tenantIDs[0], false, nil
        }
    }
    return "", true, nil // bypass if no tenant
}

Error Responses:

  • Rate limit exceeded: codes.ResourceExhausted with "Too many requests" message
  • Rate limiting errors: codes.Internal with "Internal server error" message
  • Custom responses: Configurable via callback functions

Headers:

  • retry-after: Number of seconds to wait before retrying (set automatically)
In-Flight Limiting Interceptor

Controls the number of concurrent requests being processed, preventing server overload by limiting in-flight requests.

Features:

  • Maximum concurrent request limiting
  • Per-client in-flight limiting with custom key extraction
  • Backlog support for queuing requests when limit is reached
  • Dry run mode for testing without enforcement
  • Customizable callbacks for rejection and error handling
  • Retry-After header support
  • Comprehensive logging and error handling

Usage:

import "github.com/acronis/go-appkit/grpcserver/interceptor"

// Basic usage with maximum 10 concurrent requests
unaryInterceptor, err := interceptor.InFlightLimitUnaryInterceptor(10)
streamInterceptor, err := interceptor.InFlightLimitStreamInterceptor(10)

// With advanced configuration
unaryInterceptor, err := interceptor.InFlightLimitUnaryInterceptor(10,
    // Per-client in-flight limiting
    interceptor.WithInFlightLimitUnaryGetKey(func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo) (string, bool, error) {
        if md, ok := metadata.FromIncomingContext(ctx); ok {
            if clientIDs := md.Get("client-id"); len(clientIDs) > 0 {
                return clientIDs[0], false, nil
            }
        }
        return "", true, nil // bypass if no client-id
    }),
    
    // Backlog configuration
    interceptor.WithInFlightLimitBacklogLimit(50),
    interceptor.WithInFlightLimitBacklogTimeout(30*time.Second),
    
    // Dry run mode
    interceptor.WithInFlightLimitDryRun(true),
    
    // Custom rejection handler
    interceptor.WithInFlightLimitUnaryOnReject(func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, params interceptor.InFlightLimitParams) (interface{}, error) {
        // Custom rejection logic
        return nil, status.Error(codes.ResourceExhausted, "Too many concurrent requests for key: "+params.Key)
    }),
    
    // Retry-After calculation
    interceptor.WithInFlightLimitUnaryGetRetryAfter(func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo) time.Duration {
        return 30 * time.Second
    }),
)

Key Extraction Examples:

// In-flight limit by client IP
func inFlightLimitByIP(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo) (string, bool, error) {
    if p, ok := peer.FromContext(ctx); ok {
        if host, _, err := net.SplitHostPort(p.Addr.String()); err == nil {
            return host, false, nil
        }
        return p.Addr.String(), false, nil
    }
    return "", true, nil // bypass if no peer info
}

// In-flight limit by user ID from JWT
func inFlightLimitByUserID(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo) (string, bool, error) {
    userID := getUserIDFromJWT(ctx)
    if userID != "" {
        return userID, false, nil
    }
    return "", true, nil // bypass for unauthenticated requests
}

// In-flight limit by tenant ID from metadata
func inFlightLimitByTenant(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo) (string, bool, error) {
    if md, ok := metadata.FromIncomingContext(ctx); ok {
        if tenantIDs := md.Get("x-tenant-id"); len(tenantIDs) > 0 {
            return tenantIDs[0], false, nil
        }
    }
    return "", true, nil // bypass if no tenant
}

Configuration Options:

  • WithInFlightLimitUnaryGetKey(func): Extract key from unary requests for per-client limiting
  • WithInFlightLimitStreamGetKey(func): Extract key from stream requests for per-client limiting
  • WithInFlightLimitMaxKeys(int): Maximum number of keys to track (default: 10000)
  • WithInFlightLimitDryRun(bool): Enable dry run mode for testing
  • WithInFlightLimitBacklogLimit(int): Number of requests to queue when limit is reached
  • WithInFlightLimitBacklogTimeout(time.Duration): Maximum time to wait in backlog
  • WithInFlightLimitUnaryOnReject(func): Custom handler for rejected unary requests
  • WithInFlightLimitStreamOnReject(func): Custom handler for rejected stream requests
  • WithInFlightLimitUnaryOnRejectInDryRun(func): Custom handler for dry run rejections
  • WithInFlightLimitStreamOnRejectInDryRun(func): Custom handler for dry run rejections
  • WithInFlightLimitUnaryOnError(func): Custom handler for in-flight limiting errors
  • WithInFlightLimitStreamOnError(func): Custom handler for in-flight limiting errors
  • WithInFlightLimitUnaryGetRetryAfter(func): Calculate retry-after value for unary requests
  • WithInFlightLimitStreamGetRetryAfter(func): Calculate retry-after value for stream requests

Error Responses:

  • In-flight limit exceeded: codes.ResourceExhausted with "Too many in-flight requests" message
  • In-flight limiting errors: codes.Internal with "Internal server error" message
  • Custom responses: Configurable via callback functions

Headers:

  • retry-after: Number of seconds to wait before retrying (set automatically)

Differences from Rate Limiting:

  • In-flight limiting: Controls concurrent processing, focuses on server capacity
  • Rate limiting: Controls request frequency over time, focuses on traffic shaping
  • Use together: Rate limiting for traffic control, in-flight limiting for overload protection

Context Utilities

The package provides utilities for working with context values:

Call Start Time
// Get call start time
startTime := interceptor.GetCallStartTimeFromContext(ctx)

// Set call start time
ctx = interceptor.NewContextWithCallStartTime(ctx, time.Now())
Request IDs
// Get request ID
requestID := interceptor.GetRequestIDFromContext(ctx)

// Get internal request ID
internalRequestID := interceptor.GetInternalRequestIDFromContext(ctx)

// Set request IDs
ctx = interceptor.NewContextWithRequestID(ctx, "req-123")
ctx = interceptor.NewContextWithInternalRequestID(ctx, "int-456")
Trace ID
// Get trace ID (from OpenTelemetry or similar)
traceID := interceptor.GetTraceIDFromContext(ctx)
Logger
// Get logger from context
logger := interceptor.GetLoggerFromContext(ctx)

// Set logger in context
ctx = interceptor.NewContextWithLogger(ctx, logger)
Logging Parameters
// Get logging parameters
params := interceptor.GetLoggingParamsFromContext(ctx)

// Add custom log fields
params.AddFields(log.String("custom", "value"))

// Set logging parameters
ctx = interceptor.NewContextWithLoggingParams(ctx, params)

Stream Utilities

WrappedServerStream

A utility for wrapping gRPC server streams with custom context:

wrappedStream := &interceptor.WrappedServerStream{
    ServerStream: originalStream,
    Ctx:          customContext,
}

Integration Example

Here's how to use multiple interceptors together:

func createGRPCServer(logger log.FieldLogger) *grpc.Server {
    // Create metrics collector
    metrics := interceptor.NewPrometheusMetrics(
        interceptor.WithPrometheusNamespace("myapp"),
    )
    metrics.MustRegister()
    
    // Create rate limiting interceptor
    rate := interceptor.Rate{Count: 100, Duration: time.Second}
    rateLimitUnary, err := interceptor.RateLimitUnaryInterceptor(rate,
        interceptor.WithRateLimitAlg(interceptor.RateLimitAlgLeakyBucket),
        interceptor.WithRateLimitMaxBurst(100),
        interceptor.WithRateLimitUnaryGetKey(func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo) (string, bool, error) {
            // Rate limit by client IP
            if p, ok := peer.FromContext(ctx); ok {
                if host, _, err := net.SplitHostPort(p.Addr.String()); err == nil {
                    return host, false, nil
                }
            }
            return "", true, nil
        }),
    )
    if err != nil {
        panic(err)
    }
    
    rateLimitStream, err := interceptor.RateLimitStreamInterceptor(rate,
        interceptor.WithRateLimitAlg(interceptor.RateLimitAlgLeakyBucket),
        interceptor.WithRateLimitMaxBurst(100),
        interceptor.WithRateLimitStreamGetKey(func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo) (string, bool, error) {
            // Rate limit by client IP
            if p, ok := peer.FromContext(ss.Context()); ok {
                if host, _, err := net.SplitHostPort(p.Addr.String()); err == nil {
                    return host, false, nil
                }
            }
            return "", true, nil
        }),
    )
    if err != nil {
        panic(err)
    }
    
    // Create in-flight limiting interceptor
    inFlightUnary, err := interceptor.InFlightLimitUnaryInterceptor(50,
        interceptor.WithInFlightLimitUnaryGetKey(func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo) (string, bool, error) {
            // In-flight limit by client IP
            if p, ok := peer.FromContext(ctx); ok {
                if host, _, err := net.SplitHostPort(p.Addr.String()); err == nil {
                    return host, false, nil
                }
            }
            return "", true, nil
        }),
        interceptor.WithInFlightLimitBacklogLimit(100),
        interceptor.WithInFlightLimitBacklogTimeout(30*time.Second),
    )
    if err != nil {
        panic(err)
    }
    
    inFlightStream, err := interceptor.InFlightLimitStreamInterceptor(50,
        interceptor.WithInFlightLimitStreamGetKey(func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo) (string, bool, error) {
            // In-flight limit by client IP
            if p, ok := peer.FromContext(ss.Context()); ok {
                if host, _, err := net.SplitHostPort(p.Addr.String()); err == nil {
                    return host, false, nil
                }
            }
            return "", true, nil
        }),
        interceptor.WithInFlightLimitBacklogLimit(100),
        interceptor.WithInFlightLimitBacklogTimeout(30*time.Second),
    )
    if err != nil {
        panic(err)
    }
    
    // Create interceptor chain
    unaryInterceptors := []grpc.UnaryServerInterceptor{
        // Set call start time first
        func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) {
            ctx = interceptor.NewContextWithCallStartTime(ctx, time.Now())
            return handler(ctx, req)
        },
        // Request ID handling
        interceptor.RequestIDUnaryInterceptor(),
        // Logging
        interceptor.LoggingUnaryInterceptor(logger,
            interceptor.WithLoggingCallStart(true),
            interceptor.WithLoggingSlowCallThreshold(time.Second),
        ),
        // Recovery
        interceptor.RecoveryUnaryInterceptor(),
        // Metrics
        interceptor.MetricsUnaryInterceptor(metrics),
        // Rate limiting
        rateLimitUnary,
        // In-flight limiting
        inFlightUnary,
    }
    
    streamInterceptors := []grpc.StreamServerInterceptor{
        // Set call start time first
        func(srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler) error {
            ctx := interceptor.NewContextWithCallStartTime(ss.Context(), time.Now())
            wrappedStream := &interceptor.WrappedServerStream{ServerStream: ss, Ctx: ctx}
            return handler(srv, wrappedStream)
        },
        // Request ID handling
        interceptor.RequestIDStreamInterceptor(),
        // Logging
        interceptor.LoggingStreamInterceptor(logger,
            interceptor.WithLoggingCallStart(true),
            interceptor.WithLoggingSlowCallThreshold(time.Second),
        ),
        // Recovery
        interceptor.RecoveryStreamInterceptor(),
        // Metrics
        interceptor.MetricsStreamInterceptor(metrics),
        // In-flight limiting
        inFlightStream,
        // Rate limiting
        rateLimitStream,
    }
    
    return grpc.NewServer(
        grpc.ChainUnaryInterceptor(unaryInterceptors...),
        grpc.ChainStreamInterceptor(streamInterceptors...),
    )
}

Best Practices

  1. Interceptor Order: Place interceptors in the correct order:

    • Call start time (first)
    • Request ID
    • Logging
    • Recovery
    • Metrics
    • In-flight limiting
    • Rate limiting
    • Custom interceptors (last)
  2. Rate Limiting:

    • Use appropriate algorithms: leaky bucket for burst tolerance, sliding window for precise limits
    • Implement per-client rate limiting using IP, user ID, or client ID as keys
    • Use dry run mode to test rate limits in production without enforcement
    • Configure appropriate backlog limits and timeouts based on your service capacity
    • Monitor rate limiting metrics and adjust limits based on traffic patterns
  3. In-Flight Limiting:

    • Set limits based on your server's actual processing capacity and available resources
    • Use per-client limiting to prevent single clients from consuming all capacity
    • Configure appropriate backlog limits to handle temporary spikes without rejecting requests
    • Use dry run mode to test limits in production before enforcement
    • Combine with rate limiting: rate limiting for traffic shaping, in-flight limiting for overload protection
    • Monitor in-flight counts and adjust limits based on server performance metrics
  4. Performance: Use method exclusion for high-frequency health checks and metrics endpoints

  5. Security: Be careful with custom header logging to avoid logging sensitive information

  6. Metrics: Use appropriate duration buckets for your use case

  7. Error Handling: Always use the recovery interceptor to prevent panics from crashing the server

  8. Context: Use the provided context utilities for consistent data access across interceptors

  9. Rate Limiting Key Selection:

    • Choose keys that provide fair distribution (e.g., client IP, user ID)
    • Avoid keys that could lead to hot spots (e.g., constant values)
    • Consider using multiple levels of rate limiting (global + per-client)
    • Implement bypass logic for internal or privileged clients

Documentation

Overview

Package interceptor provides gRPC interceptors for logging, metrics collection, panic recovery, and request ID handling. These interceptors can be used to enhance gRPC services with observability and reliability features.

Index

Constants

View Source
const DefaultInFlightLimitMaxKeys = 10000

DefaultInFlightLimitMaxKeys is a default value of maximum keys number for the InFlightLimit interceptor.

View Source
const DefaultRateLimitBacklogTimeout = ratelimit.DefaultRateLimitBacklogTimeout

DefaultRateLimitBacklogTimeout determines how long the gRPC request may be in the backlog status.

View Source
const DefaultRateLimitMaxKeys = 10000

DefaultRateLimitMaxKeys is a default value of maximum keys number for the RateLimit interceptor.

View Source
const InFlightLimitLogFieldBacklogged = "in_flight_limit_backlogged"

InFlightLimitLogFieldBacklogged is the name of the logged field that indicates if the request was backlogged.

View Source
const InFlightLimitLogFieldKey = "in_flight_limit_key"

InFlightLimitLogFieldKey is the name of the logged field that contains a key for the in-flight limiting.

View Source
const RateLimitLogFieldKey = "rate_limit_key"

RateLimitLogFieldKey it is the name of the logged field that contains a key for the requests rate limiter.

View Source
const (
	// RecoveryDefaultStackSize defines the default size of stack part which will be logged.
	RecoveryDefaultStackSize = 8192
)

Variables

View Source
var DefaultPrometheusDurationBuckets = []float64{0.01, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60, 150, 300, 600}

DefaultPrometheusDurationBuckets is default buckets into which observations of serving gRPC calls are counted.

View Source
var InternalError = status.Error(codes.Internal, "Internal error")

InternalError is the default error returned when a panic is recovered.

Functions

func DefaultInFlightLimitStreamOnError added in v1.21.0

func DefaultInFlightLimitStreamOnError(
	srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler, params InFlightLimitParams, err error,
) error

DefaultInFlightLimitStreamOnError sends gRPC error response when an error occurs during in-flight limiting in stream requests.

func DefaultInFlightLimitStreamOnReject added in v1.21.0

func DefaultInFlightLimitStreamOnReject(
	srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler, params InFlightLimitParams,
) error

DefaultInFlightLimitStreamOnReject sends gRPC error response when the in-flight limit is exceeded for stream requests.

func DefaultInFlightLimitStreamOnRejectInDryRun added in v1.21.0

func DefaultInFlightLimitStreamOnRejectInDryRun(
	srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler, params InFlightLimitParams,
) error

DefaultInFlightLimitStreamOnRejectInDryRun continues processing stream requests when in-flight limit is exceeded in dry run mode.

func DefaultInFlightLimitUnaryOnError added in v1.21.0

func DefaultInFlightLimitUnaryOnError(
	ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, params InFlightLimitParams, err error,
) (interface{}, error)

DefaultInFlightLimitUnaryOnError sends gRPC error response when an error occurs during in-flight limiting in unary requests.

func DefaultInFlightLimitUnaryOnReject added in v1.21.0

func DefaultInFlightLimitUnaryOnReject(
	ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, params InFlightLimitParams,
) (interface{}, error)

DefaultInFlightLimitUnaryOnReject sends gRPC error response when the in-flight limit is exceeded for unary requests.

func DefaultInFlightLimitUnaryOnRejectInDryRun added in v1.21.0

func DefaultInFlightLimitUnaryOnRejectInDryRun(
	ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, params InFlightLimitParams,
) (interface{}, error)

DefaultInFlightLimitUnaryOnRejectInDryRun continues processing unary requests when in-flight limit is exceeded in dry run mode.

func DefaultRateLimitStreamOnError added in v1.21.0

func DefaultRateLimitStreamOnError(
	srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler, params RateLimitParams, err error,
) error

DefaultRateLimitStreamOnError sends gRPC error response when an error occurs during rate limiting in stream requests.

func DefaultRateLimitStreamOnReject added in v1.21.0

func DefaultRateLimitStreamOnReject(
	srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler, params RateLimitParams,
) error

DefaultRateLimitStreamOnReject sends gRPC error response when the rate limit is exceeded for stream requests.

func DefaultRateLimitStreamOnRejectInDryRun added in v1.21.0

func DefaultRateLimitStreamOnRejectInDryRun(
	srv interface{}, ss grpc.ServerStream, info *grpc.StreamServerInfo, handler grpc.StreamHandler, params RateLimitParams,
) error

DefaultRateLimitStreamOnRejectInDryRun continues processing stream requests when rate limit is exceeded in dry run mode.

func DefaultRateLimitUnaryOnError added in v1.21.0

func DefaultRateLimitUnaryOnError(
	ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, params RateLimitParams, err error,
) (interface{}, error)

DefaultRateLimitUnaryOnError sends gRPC error response when an error occurs during rate limiting in unary requests.

func DefaultRateLimitUnaryOnReject added in v1.21.0

func DefaultRateLimitUnaryOnReject(
	ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, params RateLimitParams,
) (interface{}, error)

DefaultRateLimitUnaryOnReject sends gRPC error response when the rate limit is exceeded for unary requests.

func DefaultRateLimitUnaryOnRejectInDryRun added in v1.21.0

func DefaultRateLimitUnaryOnRejectInDryRun(
	ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, params RateLimitParams,
) (interface{}, error)

DefaultRateLimitUnaryOnRejectInDryRun continues processing unary requests when rate limit is exceeded in dry run mode.

func GetCallStartTimeFromContext

func GetCallStartTimeFromContext(ctx context.Context) time.Time

GetCallStartTimeFromContext extracts request start time from the context.

func GetInternalRequestIDFromContext

func GetInternalRequestIDFromContext(ctx context.Context) string

GetInternalRequestIDFromContext extracts internal request id from the context.

func GetLoggerFromContext

func GetLoggerFromContext(ctx context.Context) log.FieldLogger

GetLoggerFromContext extracts logger from the context.

func GetRequestIDFromContext

func GetRequestIDFromContext(ctx context.Context) string

GetRequestIDFromContext extracts external request id from the context.

func GetTraceIDFromContext

func GetTraceIDFromContext(ctx context.Context) string

GetTraceIDFromContext extracts trace id from the context.

func InFlightLimitStreamInterceptor added in v1.21.0

func InFlightLimitStreamInterceptor(limit int, options ...InFlightLimitOption) (func(
	srv interface{},
	ss grpc.ServerStream,
	info *grpc.StreamServerInfo,
	handler grpc.StreamHandler,
) error, error)

InFlightLimitStreamInterceptor is a gRPC stream interceptor that limits the number of in-flight requests.

func InFlightLimitUnaryInterceptor added in v1.21.0

func InFlightLimitUnaryInterceptor(limit int, options ...InFlightLimitOption) (func(
	ctx context.Context,
	req interface{},
	info *grpc.UnaryServerInfo,
	handler grpc.UnaryHandler,
) (interface{}, error), error)

InFlightLimitUnaryInterceptor is a gRPC unary interceptor that limits the number of in-flight requests.

func LoggingStreamInterceptor

func LoggingStreamInterceptor(logger log.FieldLogger, options ...LoggingOption) func(
	srv interface{},
	ss grpc.ServerStream,
	info *grpc.StreamServerInfo,
	handler grpc.StreamHandler,
) error

LoggingStreamInterceptor is a gRPC stream interceptor that logs the start and end of each RPC call.

func LoggingUnaryInterceptor

func LoggingUnaryInterceptor(logger log.FieldLogger, options ...LoggingOption) func(
	ctx context.Context,
	req interface{},
	info *grpc.UnaryServerInfo,
	handler grpc.UnaryHandler,
) (interface{}, error)

LoggingUnaryInterceptor is a gRPC unary interceptor that logs the start and end of each RPC call.

func MetricsStreamInterceptor

func MetricsStreamInterceptor(
	collector MetricsCollector,
	opts ...MetricsOption,
) grpc.StreamServerInterceptor

MetricsStreamInterceptor is an interceptor that collects metrics for incoming gRPC stream calls.

func MetricsUnaryInterceptor

func MetricsUnaryInterceptor(
	collector MetricsCollector,
	opts ...MetricsOption,
) grpc.UnaryServerInterceptor

MetricsUnaryInterceptor is an interceptor that collects metrics for incoming gRPC calls.

func NewContextWithCallStartTime

func NewContextWithCallStartTime(ctx context.Context, startTime time.Time) context.Context

NewContextWithCallStartTime creates a new context with request start time.

func NewContextWithInternalRequestID

func NewContextWithInternalRequestID(ctx context.Context, internalRequestID string) context.Context

NewContextWithInternalRequestID creates a new context with internal request id.

func NewContextWithLogger

func NewContextWithLogger(ctx context.Context, logger log.FieldLogger) context.Context

NewContextWithLogger creates a new context with logger.

func NewContextWithLoggingParams

func NewContextWithLoggingParams(ctx context.Context, loggingParams *LoggingParams) context.Context

NewContextWithLoggingParams creates a new context with logging params.

func NewContextWithRequestID

func NewContextWithRequestID(ctx context.Context, requestID string) context.Context

NewContextWithRequestID creates a new context with external request id.

func NewContextWithTraceID

func NewContextWithTraceID(ctx context.Context, traceID string) context.Context

NewContextWithTraceID creates a new context with trace id.

func RateLimitStreamInterceptor added in v1.21.0

func RateLimitStreamInterceptor(maxRate Rate, options ...RateLimitOption) (func(
	srv interface{},
	ss grpc.ServerStream,
	info *grpc.StreamServerInfo,
	handler grpc.StreamHandler,
) error, error)

RateLimitStreamInterceptor is a gRPC stream interceptor that limits the rate of requests.

func RateLimitUnaryInterceptor added in v1.21.0

func RateLimitUnaryInterceptor(maxRate Rate, options ...RateLimitOption) (func(
	ctx context.Context,
	req interface{},
	info *grpc.UnaryServerInfo,
	handler grpc.UnaryHandler,
) (interface{}, error), error)

RateLimitUnaryInterceptor is a gRPC unary interceptor that limits the rate of requests.

func RecoveryStreamInterceptor

func RecoveryStreamInterceptor(options ...RecoveryOption) func(
	srv interface{},
	ss grpc.ServerStream,
	_ *grpc.StreamServerInfo,
	handler grpc.StreamHandler,
) error

RecoveryStreamInterceptor is a gRPC stream interceptor that recovers from panics and returns Internal error.

func RecoveryUnaryInterceptor

func RecoveryUnaryInterceptor(options ...RecoveryOption) func(
	ctx context.Context,
	req interface{},
	_ *grpc.UnaryServerInfo,
	handler grpc.UnaryHandler,
) (interface{}, error)

RecoveryUnaryInterceptor is a gRPC unary interceptor that recovers from panics and returns Internal error.

func RequestIDStreamInterceptor

func RequestIDStreamInterceptor(options ...RequestIDOption) func(
	srv interface{},
	ss grpc.ServerStream,
	_ *grpc.StreamServerInfo,
	handler grpc.StreamHandler,
) error

RequestIDStreamInterceptor is a gRPC stream interceptor that extracts the request ID from the incoming context metadata and attaches it to the context. If the request ID is missing, a new one is generated.

func RequestIDUnaryInterceptor

func RequestIDUnaryInterceptor(options ...RequestIDOption) func(
	ctx context.Context,
	req interface{},
	_ *grpc.UnaryServerInfo,
	handler grpc.UnaryHandler,
) (interface{}, error)

RequestIDUnaryInterceptor is a gRPC unary interceptor that extracts the request ID from the incoming context metadata and attaches it to the context. If the request ID is missing, a new one is generated.

Types

type CallInfoMetrics

type CallInfoMetrics struct {
	Service       string
	Method        string
	UserAgentType string
}

CallInfoMetrics represents a call info for collecting metrics.

type CallMethodType

type CallMethodType string

CallMethodType represents the type of gRPC method call.

const (
	// CallMethodTypeUnary represents a unary gRPC method call.
	CallMethodTypeUnary CallMethodType = "unary"
	// CallMethodTypeStream represents a streaming gRPC method call.
	CallMethodTypeStream CallMethodType = "stream"
)

type InFlightLimitOption added in v1.21.0

type InFlightLimitOption func(*inFlightLimitOptions)

InFlightLimitOption represents a configuration option for the in-flight limit interceptor.

func WithInFlightLimitBacklogLimit added in v1.21.0

func WithInFlightLimitBacklogLimit(backlogLimit int) InFlightLimitOption

WithInFlightLimitBacklogLimit sets the backlog limit for queuing requests.

func WithInFlightLimitBacklogTimeout added in v1.21.0

func WithInFlightLimitBacklogTimeout(backlogTimeout time.Duration) InFlightLimitOption

WithInFlightLimitBacklogTimeout sets the timeout for backlogged requests.

func WithInFlightLimitDryRun added in v1.21.0

func WithInFlightLimitDryRun(dryRun bool) InFlightLimitOption

WithInFlightLimitDryRun enables dry run mode where limits are checked but not enforced.

func WithInFlightLimitMaxKeys added in v1.21.0

func WithInFlightLimitMaxKeys(maxKeys int) InFlightLimitOption

WithInFlightLimitMaxKeys sets the maximum number of keys to track.

func WithInFlightLimitStreamGetKey added in v1.21.0

func WithInFlightLimitStreamGetKey(getKey InFlightLimitStreamGetKeyFunc) InFlightLimitOption

WithInFlightLimitStreamGetKey sets the function to extract in-flight limiting key from stream gRPC requests.

func WithInFlightLimitStreamGetRetryAfter added in v1.21.0

func WithInFlightLimitStreamGetRetryAfter(getRetryAfter InFlightLimitStreamGetRetryAfterFunc) InFlightLimitOption

WithInFlightLimitStreamGetRetryAfter sets the function to calculate retry-after value for stream requests.

func WithInFlightLimitStreamOnError added in v1.21.0

func WithInFlightLimitStreamOnError(onError InFlightLimitStreamOnErrorFunc) InFlightLimitOption

WithInFlightLimitStreamOnError sets the callback for handling in-flight limiting errors in stream requests.

func WithInFlightLimitStreamOnReject added in v1.21.0

func WithInFlightLimitStreamOnReject(onReject InFlightLimitStreamOnRejectFunc) InFlightLimitOption

WithInFlightLimitStreamOnReject sets the callback for handling rejected stream requests.

func WithInFlightLimitStreamOnRejectInDryRun added in v1.21.0

func WithInFlightLimitStreamOnRejectInDryRun(onReject InFlightLimitStreamOnRejectFunc) InFlightLimitOption

WithInFlightLimitStreamOnRejectInDryRun sets the callback for handling rejected stream requests in dry run mode.

func WithInFlightLimitUnaryGetKey added in v1.21.0

func WithInFlightLimitUnaryGetKey(getKey InFlightLimitUnaryGetKeyFunc) InFlightLimitOption

WithInFlightLimitUnaryGetKey sets the function to extract in-flight limiting key from unary gRPC requests.

func WithInFlightLimitUnaryGetRetryAfter added in v1.21.0

func WithInFlightLimitUnaryGetRetryAfter(getRetryAfter InFlightLimitUnaryGetRetryAfterFunc) InFlightLimitOption

WithInFlightLimitUnaryGetRetryAfter sets the function to calculate retry-after value for unary requests.

func WithInFlightLimitUnaryOnError added in v1.21.0

func WithInFlightLimitUnaryOnError(onError InFlightLimitUnaryOnErrorFunc) InFlightLimitOption

WithInFlightLimitUnaryOnError sets the callback for handling in-flight limiting errors in unary requests.

func WithInFlightLimitUnaryOnReject added in v1.21.0

func WithInFlightLimitUnaryOnReject(onReject InFlightLimitUnaryOnRejectFunc) InFlightLimitOption

WithInFlightLimitUnaryOnReject sets the callback for handling rejected unary requests.

func WithInFlightLimitUnaryOnRejectInDryRun added in v1.21.0

func WithInFlightLimitUnaryOnRejectInDryRun(onReject InFlightLimitUnaryOnRejectFunc) InFlightLimitOption

WithInFlightLimitUnaryOnRejectInDryRun sets the callback for handling rejected unary requests in dry run mode.

type InFlightLimitParams added in v1.21.0

type InFlightLimitParams struct {
	UnaryGetRetryAfter  InFlightLimitUnaryGetRetryAfterFunc
	StreamGetRetryAfter InFlightLimitStreamGetRetryAfterFunc
	Key                 string
	RequestBacklogged   bool
}

InFlightLimitParams contains data that relates to the in-flight limiting procedure and could be used for rejecting or handling an occurred error.

type InFlightLimitStreamGetKeyFunc added in v1.21.0

type InFlightLimitStreamGetKeyFunc func(srv interface{}, ss grpc.ServerStream,
	info *grpc.StreamServerInfo) (key string, bypass bool, err error)

InFlightLimitStreamGetKeyFunc is a function that is called for getting key for in-flight limiting in stream requests.

type InFlightLimitStreamGetRetryAfterFunc added in v1.21.0

type InFlightLimitStreamGetRetryAfterFunc func(srv interface{}, ss grpc.ServerStream,
	info *grpc.StreamServerInfo) time.Duration

InFlightLimitStreamGetRetryAfterFunc is a function that is called to get a value for retry-after header when the in-flight limit is exceeded in stream requests.

type InFlightLimitStreamOnErrorFunc added in v1.21.0

type InFlightLimitStreamOnErrorFunc func(srv interface{}, ss grpc.ServerStream,
	info *grpc.StreamServerInfo, handler grpc.StreamHandler, params InFlightLimitParams, err error) error

InFlightLimitStreamOnErrorFunc is a function that is called when an error occurs during in-flight limiting in stream requests.

type InFlightLimitStreamOnRejectFunc added in v1.21.0

type InFlightLimitStreamOnRejectFunc func(srv interface{}, ss grpc.ServerStream,
	info *grpc.StreamServerInfo, handler grpc.StreamHandler, params InFlightLimitParams) error

InFlightLimitStreamOnRejectFunc is a function that is called for rejecting gRPC stream request when the in-flight limit is exceeded.

type InFlightLimitUnaryGetKeyFunc added in v1.21.0

type InFlightLimitUnaryGetKeyFunc func(ctx context.Context, req interface{},
	info *grpc.UnaryServerInfo) (key string, bypass bool, err error)

InFlightLimitUnaryGetKeyFunc is a function that is called for getting key for in-flight limiting in unary requests.

type InFlightLimitUnaryGetRetryAfterFunc added in v1.21.0

type InFlightLimitUnaryGetRetryAfterFunc func(ctx context.Context, req interface{},
	info *grpc.UnaryServerInfo) time.Duration

InFlightLimitUnaryGetRetryAfterFunc is a function that is called to get a value for retry-after header when the in-flight limit is exceeded in unary requests.

type InFlightLimitUnaryOnErrorFunc added in v1.21.0

type InFlightLimitUnaryOnErrorFunc func(ctx context.Context, req interface{},
	info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, params InFlightLimitParams, err error) (interface{}, error)

InFlightLimitUnaryOnErrorFunc is a function that is called when an error occurs during in-flight limiting in unary requests.

type InFlightLimitUnaryOnRejectFunc added in v1.21.0

type InFlightLimitUnaryOnRejectFunc func(ctx context.Context, req interface{},
	info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, params InFlightLimitParams) (interface{}, error)

InFlightLimitUnaryOnRejectFunc is a function that is called for rejecting gRPC unary request when the in-flight limit is exceeded.

type LoggingOption

type LoggingOption func(*loggingOptions)

LoggingOption represents a configuration option for the logging interceptor.

func WithLoggingAddCallInfoToLogger

func WithLoggingAddCallInfoToLogger(addCallInfo bool) LoggingOption

WithLoggingAddCallInfoToLogger adds call information to the logger context.

func WithLoggingCallHeaders

func WithLoggingCallHeaders(headers map[string]string) LoggingOption

WithLoggingCallHeaders specifies custom headers to log from gRPC metadata.

func WithLoggingCallStart

func WithLoggingCallStart(logCallStart bool) LoggingOption

WithLoggingCallStart enables logging of call start events.

func WithLoggingExcludedMethods

func WithLoggingExcludedMethods(methods ...string) LoggingOption

WithLoggingExcludedMethods specifies gRPC methods to exclude from logging.

func WithLoggingSlowCallThreshold

func WithLoggingSlowCallThreshold(threshold time.Duration) LoggingOption

WithLoggingSlowCallThreshold sets the threshold for slow call detection.

func WithLoggingStreamCustomLoggerProvider

func WithLoggingStreamCustomLoggerProvider(provider StreamCustomLoggerProvider) LoggingOption

WithLoggingStreamCustomLoggerProvider sets a custom logger provider function for stream interceptors.

func WithLoggingUnaryCustomLoggerProvider

func WithLoggingUnaryCustomLoggerProvider(provider UnaryCustomLoggerProvider) LoggingOption

WithLoggingUnaryCustomLoggerProvider sets a custom logger provider function.

type LoggingParams

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

LoggingParams stores parameters for the gRPC logging interceptor that may be modified dynamically by the other underlying interceptors/handlers.

func GetLoggingParamsFromContext

func GetLoggingParamsFromContext(ctx context.Context) *LoggingParams

GetLoggingParamsFromContext extracts logging params from the context.

func (*LoggingParams) AddTimeSlotDurationInMs

func (lp *LoggingParams) AddTimeSlotDurationInMs(name string, dur time.Duration)

AddTimeSlotDurationInMs sets (if new) or adds duration value in milliseconds to the element of the time_slots map

func (*LoggingParams) AddTimeSlotInt

func (lp *LoggingParams) AddTimeSlotInt(name string, dur int64)

AddTimeSlotInt sets (if new) or adds duration value to the element of the time_slots map

func (*LoggingParams) ExtendFields

func (lp *LoggingParams) ExtendFields(fields ...log.Field)

ExtendFields extends list of fields that will be logged by the logging interceptor.

type MetricsCollector

type MetricsCollector interface {
	// IncInFlightCalls increments the counter of in-flight calls.
	IncInFlightCalls(callInfo CallInfoMetrics, methodType CallMethodType)

	// DecInFlightCalls decrements the counter of in-flight calls.
	DecInFlightCalls(callInfo CallInfoMetrics, methodType CallMethodType)

	// ObserveCallFinish observes the duration of the call and the status code.
	ObserveCallFinish(callInfo CallInfoMetrics, methodType CallMethodType, code codes.Code, startTime time.Time)
}

MetricsCollector is an interface for collecting metrics for incoming gRPC calls.

type MetricsOption

type MetricsOption func(*metricsOptions)

MetricsOption is a function type for configuring the metrics interceptor.

func WithMetricsExcludedMethods

func WithMetricsExcludedMethods(methods ...string) MetricsOption

WithMetricsExcludedMethods returns an option that excludes the specified methods from metrics collection.

func WithMetricsStreamUserAgentTypeProvider

func WithMetricsStreamUserAgentTypeProvider(provider StreamUserAgentTypeProvider) MetricsOption

WithMetricsStreamUserAgentTypeProvider sets a user agent type provider for stream interceptors.

func WithMetricsUnaryUserAgentTypeProvider

func WithMetricsUnaryUserAgentTypeProvider(provider UnaryUserAgentTypeProvider) MetricsOption

WithMetricsUnaryUserAgentTypeProvider sets a user agent type provider for unary interceptors.

type PrometheusMetrics

type PrometheusMetrics struct {
	Durations *prometheus.HistogramVec
	InFlight  *prometheus.GaugeVec
}

PrometheusMetrics represents collector of metrics for incoming gRPC calls.

func NewPrometheusMetrics

func NewPrometheusMetrics(opts ...PrometheusOption) *PrometheusMetrics

NewPrometheusMetrics creates a new instance of PrometheusMetrics with the provided options.

func (*PrometheusMetrics) DecInFlightCalls

func (pm *PrometheusMetrics) DecInFlightCalls(callInfo CallInfoMetrics, methodType CallMethodType)

DecInFlightCalls decrements the counter of in-flight calls.

func (*PrometheusMetrics) IncInFlightCalls

func (pm *PrometheusMetrics) IncInFlightCalls(callInfo CallInfoMetrics, methodType CallMethodType)

IncInFlightCalls increments the counter of in-flight calls.

func (*PrometheusMetrics) MustCurryWith

func (pm *PrometheusMetrics) MustCurryWith(labels prometheus.Labels) *PrometheusMetrics

MustCurryWith curries the metrics collector with the provided labels.

func (*PrometheusMetrics) MustRegister

func (pm *PrometheusMetrics) MustRegister()

MustRegister does registration of metrics collector in Prometheus and panics if any error occurs.

func (*PrometheusMetrics) ObserveCallFinish

func (pm *PrometheusMetrics) ObserveCallFinish(
	callInfo CallInfoMetrics, methodType CallMethodType, code codes.Code, startTime time.Time,
)

ObserveCallFinish observes the duration of the call and the status code.

func (*PrometheusMetrics) Unregister

func (pm *PrometheusMetrics) Unregister()

Unregister cancels registration of metrics collector in Prometheus.

type PrometheusOption

type PrometheusOption func(*prometheusOptions)

PrometheusOption is a function type for configuring the metrics collector.

func WithPrometheusConstLabels

func WithPrometheusConstLabels(labels prometheus.Labels) PrometheusOption

WithPrometheusConstLabels sets constant labels that will be applied to all metrics.

func WithPrometheusCurriedLabelNames

func WithPrometheusCurriedLabelNames(labelNames []string) PrometheusOption

WithPrometheusCurriedLabelNames sets label names that will be curried.

func WithPrometheusDurationBuckets

func WithPrometheusDurationBuckets(buckets []float64) PrometheusOption

WithPrometheusDurationBuckets sets the duration buckets for histogram metrics.

func WithPrometheusNamespace

func WithPrometheusNamespace(namespace string) PrometheusOption

WithPrometheusNamespace sets the namespace for metrics.

type Rate added in v1.21.0

type Rate = ratelimit.Rate

Rate describes the frequency of requests.

type RateLimitAlg added in v1.21.0

type RateLimitAlg int

RateLimitAlg represents a type for specifying rate-limiting algorithm.

const (
	RateLimitAlgLeakyBucket RateLimitAlg = iota
	RateLimitAlgSlidingWindow
)

Supported rate-limiting algorithms.

type RateLimitOption added in v1.21.0

type RateLimitOption func(*rateLimitOptions)

RateLimitOption represents a configuration option for the rate limit interceptor.

func WithRateLimitAlg added in v1.21.0

func WithRateLimitAlg(alg RateLimitAlg) RateLimitOption

WithRateLimitAlg sets the rate limiting algorithm.

func WithRateLimitBacklogLimit added in v1.21.0

func WithRateLimitBacklogLimit(backlogLimit int) RateLimitOption

WithRateLimitBacklogLimit sets the backlog limit for queuing requests.

func WithRateLimitBacklogTimeout added in v1.21.0

func WithRateLimitBacklogTimeout(backlogTimeout time.Duration) RateLimitOption

WithRateLimitBacklogTimeout sets the timeout for backlogged requests.

func WithRateLimitDryRun added in v1.21.0

func WithRateLimitDryRun(dryRun bool) RateLimitOption

WithRateLimitDryRun enables dry run mode where limits are checked but not enforced.

func WithRateLimitMaxBurst added in v1.21.0

func WithRateLimitMaxBurst(maxBurst int) RateLimitOption

WithRateLimitMaxBurst sets the maximum burst size for leaky bucket algorithm.

func WithRateLimitMaxKeys added in v1.21.0

func WithRateLimitMaxKeys(maxKeys int) RateLimitOption

WithRateLimitMaxKeys sets the maximum number of keys to track.

func WithRateLimitStreamGetKey added in v1.21.0

func WithRateLimitStreamGetKey(getKey RateLimitStreamGetKeyFunc) RateLimitOption

WithRateLimitStreamGetKey sets the function to extract rate limiting key from stream gRPC requests.

func WithRateLimitStreamGetRetryAfter added in v1.21.0

func WithRateLimitStreamGetRetryAfter(getRetryAfter RateLimitStreamGetRetryAfterFunc) RateLimitOption

WithRateLimitStreamGetRetryAfter sets the function to calculate retry-after value for stream requests.

func WithRateLimitStreamOnError added in v1.21.0

func WithRateLimitStreamOnError(onError RateLimitStreamOnErrorFunc) RateLimitOption

WithRateLimitStreamOnError sets the callback for handling rate limiting errors in stream requests.

func WithRateLimitStreamOnReject added in v1.21.0

func WithRateLimitStreamOnReject(onReject RateLimitStreamOnRejectFunc) RateLimitOption

WithRateLimitStreamOnReject sets the callback for handling rejected stream requests.

func WithRateLimitStreamOnRejectInDryRun added in v1.21.0

func WithRateLimitStreamOnRejectInDryRun(onReject RateLimitStreamOnRejectFunc) RateLimitOption

WithRateLimitStreamOnRejectInDryRun sets the callback for handling rejected stream requests in dry run mode.

func WithRateLimitUnaryGetKey added in v1.21.0

func WithRateLimitUnaryGetKey(getKey RateLimitUnaryGetKeyFunc) RateLimitOption

WithRateLimitUnaryGetKey sets the function to extract rate limiting key from unary gRPC requests.

func WithRateLimitUnaryGetRetryAfter added in v1.21.0

func WithRateLimitUnaryGetRetryAfter(getRetryAfter RateLimitUnaryGetRetryAfterFunc) RateLimitOption

WithRateLimitUnaryGetRetryAfter sets the function to calculate retry-after value for unary requests.

func WithRateLimitUnaryOnError added in v1.21.0

func WithRateLimitUnaryOnError(onError RateLimitUnaryOnErrorFunc) RateLimitOption

WithRateLimitUnaryOnError sets the callback for handling rate limiting errors in unary requests.

func WithRateLimitUnaryOnReject added in v1.21.0

func WithRateLimitUnaryOnReject(onReject RateLimitUnaryOnRejectFunc) RateLimitOption

WithRateLimitUnaryOnReject sets the callback for handling rejected unary requests.

func WithRateLimitUnaryOnRejectInDryRun added in v1.21.0

func WithRateLimitUnaryOnRejectInDryRun(onReject RateLimitUnaryOnRejectFunc) RateLimitOption

WithRateLimitUnaryOnRejectInDryRun sets the callback for handling rejected unary requests in dry run mode.

type RateLimitParams added in v1.21.0

type RateLimitParams struct {
	Key                 string
	RequestBacklogged   bool
	EstimatedRetryAfter time.Duration
	UnaryGetRetryAfter  RateLimitUnaryGetRetryAfterFunc
	StreamGetRetryAfter RateLimitStreamGetRetryAfterFunc
}

RateLimitParams contains data that relates to the rate limiting procedure and could be used for rejecting or handling an occurred error.

type RateLimitStreamGetKeyFunc added in v1.21.0

type RateLimitStreamGetKeyFunc func(srv interface{}, ss grpc.ServerStream,
	info *grpc.StreamServerInfo) (key string, bypass bool, err error)

RateLimitStreamGetKeyFunc is a function that is called for getting key for rate limiting in stream requests.

type RateLimitStreamGetRetryAfterFunc added in v1.21.0

type RateLimitStreamGetRetryAfterFunc func(srv interface{}, ss grpc.ServerStream,
	info *grpc.StreamServerInfo, estimatedTime time.Duration) time.Duration

RateLimitStreamGetRetryAfterFunc is a function that is called to get a value for retry-after header when the rate limit is exceeded in stream requests.

type RateLimitStreamOnErrorFunc added in v1.21.0

type RateLimitStreamOnErrorFunc func(srv interface{}, ss grpc.ServerStream,
	info *grpc.StreamServerInfo, handler grpc.StreamHandler, params RateLimitParams, err error) error

RateLimitStreamOnErrorFunc is a function that is called when an error occurs during rate limiting in stream requests.

type RateLimitStreamOnRejectFunc added in v1.21.0

type RateLimitStreamOnRejectFunc func(srv interface{}, ss grpc.ServerStream,
	info *grpc.StreamServerInfo, handler grpc.StreamHandler, params RateLimitParams) error

RateLimitStreamOnRejectFunc is a function that is called for rejecting gRPC stream request when the rate limit is exceeded.

type RateLimitUnaryGetKeyFunc added in v1.21.0

type RateLimitUnaryGetKeyFunc func(ctx context.Context, req interface{},
	info *grpc.UnaryServerInfo) (key string, bypass bool, err error)

RateLimitUnaryGetKeyFunc is a function that is called for getting key for rate limiting in unary requests.

type RateLimitUnaryGetRetryAfterFunc added in v1.21.0

type RateLimitUnaryGetRetryAfterFunc func(ctx context.Context, req interface{},
	info *grpc.UnaryServerInfo, estimatedTime time.Duration) time.Duration

RateLimitUnaryGetRetryAfterFunc is a function that is called to get a value for retry-after header when the rate limit is exceeded in unary requests.

type RateLimitUnaryOnErrorFunc added in v1.21.0

type RateLimitUnaryOnErrorFunc func(ctx context.Context, req interface{},
	info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, params RateLimitParams, err error) (interface{}, error)

RateLimitUnaryOnErrorFunc is a function that is called when an error occurs during rate limiting in unary requests.

type RateLimitUnaryOnRejectFunc added in v1.21.0

type RateLimitUnaryOnRejectFunc func(ctx context.Context, req interface{},
	info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, params RateLimitParams) (interface{}, error)

RateLimitUnaryOnRejectFunc is a function that is called for rejecting gRPC unary request when the rate limit is exceeded.

type RecoveryOption

type RecoveryOption func(*recoveryOptions)

RecoveryOption is a function type for configuring recoveryOptions.

func WithRecoveryStackSize

func WithRecoveryStackSize(size int) RecoveryOption

WithRecoveryStackSize sets the stack size for logging stack traces.

type RequestIDOption

type RequestIDOption func(*requestIDOptions)

RequestIDOption is a function type for configuring requestIDOptions.

func WithInternalRequestIDGenerator

func WithInternalRequestIDGenerator(generator func() string) RequestIDOption

WithInternalRequestIDGenerator sets the function for generating internal request IDs.

func WithRequestIDGenerator

func WithRequestIDGenerator(generator func() string) RequestIDOption

WithRequestIDGenerator sets the function for generating request IDs.

type StreamCustomLoggerProvider

type StreamCustomLoggerProvider func(ctx context.Context, info *grpc.StreamServerInfo) log.FieldLogger

StreamCustomLoggerProvider returns a custom logger or nil based on the gRPC context and stream method info.

type StreamUserAgentTypeProvider

type StreamUserAgentTypeProvider func(ctx context.Context, info *grpc.StreamServerInfo) string

StreamUserAgentTypeProvider returns a user agent type or empty string based on the gRPC context and stream method info.

type UnaryCustomLoggerProvider

type UnaryCustomLoggerProvider func(ctx context.Context, info *grpc.UnaryServerInfo) log.FieldLogger

UnaryCustomLoggerProvider returns a custom logger or nil based on the gRPC context and method info.

type UnaryUserAgentTypeProvider

type UnaryUserAgentTypeProvider func(ctx context.Context, info *grpc.UnaryServerInfo) string

UnaryUserAgentTypeProvider returns a user agent type or empty string based on the gRPC context and method info.

type WrappedServerStream

type WrappedServerStream struct {
	grpc.ServerStream
	Ctx context.Context
}

WrappedServerStream wraps grpc.ServerStream to provide a custom context for the stream.

func (*WrappedServerStream) Context

func (ss *WrappedServerStream) Context() context.Context

Context returns the custom context for the wrapped server stream.

Directories

Path Synopsis
Package throttle provides configurable gRPC interceptors for rate limiting and in-flight request limiting.
Package throttle provides configurable gRPC interceptors for rate limiting and in-flight request limiting.

Jump to

Keyboard shortcuts

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