middleware

package
v1.0.49 Latest Latest
Warning

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

Go to latest
Published: Jul 11, 2025 License: Apache-2.0 Imports: 36 Imported by: 0

Documentation

Index

Constants

View Source
const (
	LoadSheddingRandom   LoadSheddingStrategy = "random"   // Random shedding based on probability
	LoadSheddingPriority LoadSheddingStrategy = "priority" // Priority-based shedding
	LoadSheddingAdaptive LoadSheddingStrategy = "adaptive" // Adaptive shedding based on system metrics
	LoadSheddingCircuit  LoadSheddingStrategy = "circuit"  // Circuit breaker style shedding
	LoadSheddingCustom   LoadSheddingStrategy = "custom"   // Custom shedding algorithm

	// Backward compatibility aliases
	LoadSheddingStrategyRandom   = LoadSheddingRandom
	LoadSheddingStrategyPriority = LoadSheddingPriority
	LoadSheddingStrategyAdaptive = LoadSheddingAdaptive
	LoadSheddingStrategyCircuit  = LoadSheddingCircuit
	LoadSheddingStrategyCustom   = LoadSheddingCustom
)

Variables

This section is empty.

Functions

func APISecurityHeaders

func APISecurityHeaders() lift.Middleware

APISecurityHeaders returns security headers optimized for API endpoints

func AdaptiveRateLimitMiddleware

func AdaptiveRateLimitMiddleware(config RateLimitConfig) lift.Middleware

AdaptiveRateLimitMiddleware creates an adaptive rate limiting middleware

func AdaptiveTimeoutCalculator

func AdaptiveTimeoutCalculator(baseTimeout time.Duration) func(*lift.Context) time.Duration

AdaptiveTimeoutCalculator creates a timeout calculator that adapts based on request complexity

func BulkheadMiddleware

func BulkheadMiddleware(config BulkheadConfig) lift.Middleware

BulkheadMiddleware creates a bulkhead pattern middleware

func BurstRateLimitMiddleware

func BurstRateLimitMiddleware(config RateLimitConfig) lift.Middleware

BurstRateLimitMiddleware creates a burst-aware rate limiting middleware

func CircuitBreakerMiddleware

func CircuitBreakerMiddleware(config CircuitBreakerConfig) lift.Middleware

CircuitBreakerMiddleware creates a circuit breaker middleware

func CleanupExpiredEntries

func CleanupExpiredEntries(ctx context.Context, config RateLimitConfig) error

CleanupExpiredEntries removes expired rate limit entries

func CompositeRateLimit

func CompositeRateLimit(config RateLimitConfig) lift.Middleware

CompositeRateLimit creates a composite rate limiting middleware with multiple strategies

func EndpointRateLimit

func EndpointRateLimit(limit int, window time.Duration) lift.Middleware

EndpointRateLimit creates an endpoint-specific rate limiting middleware

func EnhancedObservabilityMiddleware

func EnhancedObservabilityMiddleware(config EnhancedObservabilityConfig) lift.Middleware

EnhancedObservabilityMiddleware provides comprehensive observability with logging, metrics, and tracing

func FeatureFlagMiddleware added in v1.0.37

func FeatureFlagMiddleware(ff *features.FeatureFlags) lift.Middleware

FeatureFlagMiddleware injects feature flags into the request context

func GetFeatureFlags added in v1.0.37

func GetFeatureFlags(ctx *lift.Context) *features.FeatureFlags

GetFeatureFlags retrieves the feature flags from context

func HealthCheckMiddleware

func HealthCheckMiddleware(config HealthCheckConfig) lift.Middleware

HealthCheckMiddleware creates a health check middleware

func HealthCheckObservability

func HealthCheckObservability(config EnhancedObservabilityConfig) func() error

HealthCheckObservability creates a health check for the observability stack

func HealthMiddleware

func HealthMiddleware(config HealthConfig) lift.Middleware

HealthMiddleware is an alias for HealthCheckMiddleware for backward compatibility

func IPRateLimit

func IPRateLimit(limit int, window time.Duration) lift.Middleware

IPRateLimit creates an IP-based rate limiting middleware

func IPRateLimitWithLimited added in v1.0.35

func IPRateLimitWithLimited(limit int, window time.Duration) (lift.Middleware, error)

IPRateLimitWithLimited creates an IP-based rate limiter

func InputValidation

func InputValidation(config ValidationConfig) lift.Middleware

InputValidation creates comprehensive input validation middleware

func IsFeatureEnabled added in v1.0.37

func IsFeatureEnabled(ctx *lift.Context, flag string) bool

IsFeatureEnabled checks if a feature is enabled from context

func JWT

func JWT(config security.JWTConfig) lift.Middleware

JWT creates JWT authentication middleware

func JWTAuth

func JWTAuth(config JWTConfig) lift.Middleware

JWTAuth creates a JWT authentication middleware

func JWTOptional

func JWTOptional(config security.JWTConfig) lift.Middleware

JWTOptional creates optional JWT authentication middleware If no token is provided, continues with anonymous principal

func LimitedRateLimit added in v1.0.35

func LimitedRateLimit(config LimitedConfig) (lift.Middleware, error)

LimitedRateLimit creates a rate limiting middleware using the limited library This is the CORRECT way to do rate limiting with DynamoDB in Lift

func LoadBasedTimeoutCalculator

func LoadBasedTimeoutCalculator(baseTimeout time.Duration, loadMetrics *LoadMetrics) func(*lift.Context) time.Duration

LoadBasedTimeoutCalculator creates a timeout calculator that adjusts based on system load

func LoadSheddingMiddleware

func LoadSheddingMiddleware(config LoadSheddingConfig) lift.Middleware

LoadSheddingMiddleware creates a load shedding middleware

func MetricsOnlyMiddleware

func MetricsOnlyMiddleware(metrics lift.MetricsCollector) lift.Middleware

MetricsOnlyMiddleware provides lightweight metrics collection without logging

func ObservabilityMiddleware

func ObservabilityMiddleware(config ObservabilityConfig) lift.Middleware

ObservabilityMiddleware provides comprehensive logging and metrics collection

func PriorityTimeoutCalculator

func PriorityTimeoutCalculator(baseTimeout time.Duration) func(*lift.Context) time.Duration

PriorityTimeoutCalculator creates a timeout calculator based on request priority

func PropagateTraceHeaders added in v1.0.37

func PropagateTraceHeaders() lift.Middleware

PropagateTraceHeaders is a helper middleware that propagates trace headers to outgoing requests

func RateLimit

func RateLimit(config RateLimitConfig) lift.Middleware

RateLimit creates a rate limiting middleware with the given configuration

func RateLimitMiddleware

func RateLimitMiddleware(config RateLimitConfig) lift.Middleware

RateLimitMiddleware creates a rate limiting middleware with DynamORM backend

func RequireRole

func RequireRole(roles ...string) lift.Middleware

RequireRole creates middleware that requires specific roles

func RequireScope

func RequireScope(scopes ...string) lift.Middleware

RequireScope creates middleware that requires specific scopes

func RequireTenant

func RequireTenant(tenantID string) lift.Middleware

RequireTenant creates middleware that validates tenant access

func RetryMiddleware

func RetryMiddleware(config RetryConfig) lift.Middleware

RetryMiddleware creates a retry middleware

func SecurityAuditHeaders

func SecurityAuditHeaders() lift.Middleware

SecurityAuditHeaders returns middleware that adds headers for security auditing

func SecurityHeaders

func SecurityHeaders(config SecurityHeadersConfig) lift.Middleware

SecurityHeaders returns the security headers middleware

func SecurityHeadersWithNonce

func SecurityHeadersWithNonce() lift.Middleware

SecurityHeadersWithNonce creates security headers with a nonce for CSP

func ServiceMesh added in v1.0.37

func ServiceMesh(config ServiceMeshConfig) (lift.Middleware, error)

ServiceMesh creates a service mesh middleware with the given configuration

func SlidingWindowRateLimit added in v1.0.37

func SlidingWindowRateLimit(limit int, window time.Duration) (lift.Middleware, error)

SlidingWindowRateLimit creates a sliding window rate limiter

func StrictSecurityHeaders

func StrictSecurityHeaders() lift.Middleware

StrictSecurityHeaders returns a middleware with very strict security settings

func TenantRateLimit

func TenantRateLimit(limit int, window time.Duration) lift.Middleware

TenantRateLimit creates a tenant-specific rate limiting middleware

func TenantRateLimitWithLimited added in v1.0.35

func TenantRateLimitWithLimited(limit int, window time.Duration) (lift.Middleware, error)

TenantRateLimitWithLimited creates a tenant-based rate limiter

func TimeoutMiddleware

func TimeoutMiddleware(config TimeoutConfig) lift.Middleware

TimeoutMiddleware creates a timeout middleware

func UpdateRateLimitStats

func UpdateRateLimitStats(ctx context.Context, config RateLimitConfig, allowed bool, hasError bool) error

UpdateRateLimitStats updates aggregate statistics (called by rate limiter)

func UserRateLimit

func UserRateLimit(limit int, window time.Duration) lift.Middleware

UserRateLimit creates a user-specific rate limiting middleware

func UserRateLimitWithLimited added in v1.0.35

func UserRateLimitWithLimited(limit int, window time.Duration) (lift.Middleware, error)

UserRateLimitWithLimited creates a user-based rate limiter

func ValidateAlphaNumeric

func ValidateAlphaNumeric(value string) error

ValidateAlphaNumeric validates that a string contains only alphanumeric characters

func ValidateEmail

func ValidateEmail(email string) error

ValidateEmail validates email format

func ValidateLength

func ValidateLength(min, max int) func(string) error

ValidateLength validates string length

func ValidateNumeric

func ValidateNumeric(value string) error

ValidateNumeric validates that a string contains only numeric characters

func ValidateUUID

func ValidateUUID(uuid string) error

ValidateUUID validates UUID format

func WebSocketAuth

func WebSocketAuth(config WebSocketAuthConfig) lift.Middleware

WebSocketAuth creates authentication middleware for WebSocket connections

func WebSocketAuthFromHeader

func WebSocketAuthFromHeader(headerName string) func(ctx *lift.Context) string

WebSocketAuthFromHeader is a token extractor that gets the token from headers

func WebSocketAuthFromQuery

func WebSocketAuthFromQuery(paramName string) func(ctx *lift.Context) string

WebSocketAuthFromQuery is a simple token extractor that gets the token from query parameters

func WebSocketConnectionMetrics

func WebSocketConnectionMetrics(metrics lift.MetricsCollector, store lift.ConnectionStore) lift.Middleware

WebSocketConnectionMetrics creates middleware that tracks connection lifecycle

func WebSocketMetrics

func WebSocketMetrics(metrics lift.MetricsCollector) lift.Middleware

WebSocketMetrics creates metrics middleware for WebSocket operations

func WithJWTAuth

func WithJWTAuth(secret string) lift.Middleware

WithJWTAuth is a convenience function for creating JWT middleware with minimal config

Types

type BulkheadConfig

type BulkheadConfig struct {
	// Resource limits
	MaxConcurrentRequests int           `json:"max_concurrent_requests"` // Global concurrent request limit
	MaxWaitTime           time.Duration `json:"max_wait_time"`           // Max time to wait for resource

	// Tenant isolation
	PerTenantLimits       map[string]int `json:"per_tenant_limits"`       // Per-tenant concurrent limits
	DefaultTenantLimit    int            `json:"default_tenant_limit"`    // Default limit for unlisted tenants
	EnableTenantIsolation bool           `json:"enable_tenant_isolation"` // Enable per-tenant bulkheads

	// Operation isolation
	PerOperationLimits       map[string]int `json:"per_operation_limits"`       // Per-operation concurrent limits
	DefaultOperationLimit    int            `json:"default_operation_limit"`    // Default limit for unlisted operations
	EnableOperationIsolation bool           `json:"enable_operation_isolation"` // Enable per-operation bulkheads

	// Priority handling
	EnablePriority        bool                    `json:"enable_priority"`         // Enable priority-based queuing
	PriorityExtractor     func(*lift.Context) int `json:"-"`                       // Extract priority from context
	HighPriorityThreshold int                     `json:"high_priority_threshold"` // Threshold for high priority

	// Rejection handling
	RejectionHandler func(*lift.Context, string) error `json:"-"` // Custom rejection handler

	// Observability
	Logger        observability.StructuredLogger `json:"-"`
	Metrics       observability.MetricsCollector `json:"-"`
	EnableMetrics bool                           `json:"enable_metrics"`

	// Naming
	Name string `json:"name"` // Bulkhead name for metrics
}

BulkheadConfig holds configuration for the bulkhead pattern

func NewBasicBulkhead

func NewBasicBulkhead(name string, maxConcurrent int) BulkheadConfig

NewBasicBulkhead creates a basic bulkhead with sensible defaults

func NewOperationBulkhead

func NewOperationBulkhead(name string, maxConcurrent int, operationLimits map[string]int) BulkheadConfig

NewOperationBulkhead creates an operation-isolated bulkhead

func NewPriorityBulkhead

func NewPriorityBulkhead(name string, maxConcurrent int, priorityExtractor func(*lift.Context) int) BulkheadConfig

NewPriorityBulkhead creates a priority-aware bulkhead

func NewTenantBulkhead

func NewTenantBulkhead(name string, maxConcurrent int, tenantLimits map[string]int) BulkheadConfig

NewTenantBulkhead creates a tenant-isolated bulkhead

type BulkheadStats

type BulkheadStats struct {
	Name                string                    `json:"name"`
	ActiveRequests      int                       `json:"active_requests"`
	QueuedRequests      int                       `json:"queued_requests"`
	TotalRequests       int64                     `json:"total_requests"`
	RejectedRequests    int64                     `json:"rejected_requests"`
	CompletedRequests   int64                     `json:"completed_requests"`
	AverageWaitTime     time.Duration             `json:"average_wait_time"`
	MaxWaitTime         time.Duration             `json:"max_wait_time"`
	ResourceUtilization float64                   `json:"resource_utilization"`
	TenantStats         map[string]*ResourceStats `json:"tenant_stats,omitempty"`
	OperationStats      map[string]*ResourceStats `json:"operation_stats,omitempty"`
}

BulkheadStats provides statistics about bulkhead performance

type CircuitBreakerConfig

type CircuitBreakerConfig struct {
	// Failure detection
	FailureThreshold int           `json:"failure_threshold"` // Failures before opening
	SuccessThreshold int           `json:"success_threshold"` // Successes to close from half-open
	Timeout          time.Duration `json:"timeout"`           // How long to stay open

	// Advanced failure detection
	ErrorRateThreshold  float64       `json:"error_rate_threshold"`  // Error rate (0.0-1.0) to trigger
	MinRequestThreshold int           `json:"min_request_threshold"` // Minimum requests before rate calculation
	SlidingWindowSize   time.Duration `json:"sliding_window_size"`   // Window for error rate calculation

	// Recovery settings
	MaxRetryAttempts int           `json:"max_retry_attempts"` // Max attempts in half-open
	RetryBackoff     time.Duration `json:"retry_backoff"`      // Backoff between retry attempts

	// Customization
	ShouldTrip      func(error) bool                               `json:"-"` // Custom failure detection
	FallbackHandler func(*lift.Context) error                      `json:"-"` // Custom fallback
	OnStateChange   func(CircuitBreakerState, CircuitBreakerState) `json:"-"` // State change callback

	// Multi-tenant settings
	PerTenant             bool `json:"per_tenant"`              // Separate circuit breakers per tenant
	PerOperation          bool `json:"per_operation"`           // Separate circuit breakers per operation
	EnableTenantIsolation bool `json:"enable_tenant_isolation"` // Enable tenant isolation (alias for PerTenant)

	// Observability
	Logger        observability.StructuredLogger `json:"-"`
	Metrics       observability.MetricsCollector `json:"-"`
	EnableMetrics bool                           `json:"enable_metrics"`

	// Naming
	Name string `json:"name"` // Circuit breaker name for metrics
}

CircuitBreakerConfig holds configuration for the circuit breaker

func NewAdvancedCircuitBreaker

func NewAdvancedCircuitBreaker(name string, shouldTrip func(error) bool, fallback func(*lift.Context) error) CircuitBreakerConfig

NewAdvancedCircuitBreaker creates a circuit breaker with custom failure detection

func NewBasicCircuitBreaker

func NewBasicCircuitBreaker(name string) CircuitBreakerConfig

NewBasicCircuitBreaker creates a basic circuit breaker with sensible defaults

func NewOperationCircuitBreaker

func NewOperationCircuitBreaker(name string) CircuitBreakerConfig

NewOperationCircuitBreaker creates a per-operation circuit breaker

func NewTenantCircuitBreaker

func NewTenantCircuitBreaker(name string) CircuitBreakerConfig

NewTenantCircuitBreaker creates a per-tenant circuit breaker

type CircuitBreakerState

type CircuitBreakerState string

CircuitBreakerState represents the current state of the circuit breaker

const (
	CircuitBreakerClosed   CircuitBreakerState = "closed"    // Normal operation
	CircuitBreakerOpen     CircuitBreakerState = "open"      // Failing fast
	CircuitBreakerHalfOpen CircuitBreakerState = "half_open" // Testing recovery
)

type CircuitBreakerStats

type CircuitBreakerStats struct {
	State                CircuitBreakerState `json:"state"`
	FailureCount         int64               `json:"failure_count"`
	SuccessCount         int64               `json:"success_count"`
	TotalRequests        int64               `json:"total_requests"`
	ErrorRate            float64             `json:"error_rate"`
	LastFailure          time.Time           `json:"last_failure"`
	LastSuccess          time.Time           `json:"last_success"`
	StateChangedAt       time.Time           `json:"state_changed_at"`
	NextRetryAt          time.Time           `json:"next_retry_at,omitempty"`
	ConsecutiveFailures  int                 `json:"consecutive_failures"`
	ConsecutiveSuccesses int                 `json:"consecutive_successes"`
}

CircuitBreakerStats provides statistics about circuit breaker performance

type CookieToken

type CookieToken struct {
	Name     string
	Value    string
	HttpOnly bool
	Secure   bool
	SameSite string
	Path     string
	Domain   string
	MaxAge   int
}

CookieToken represents a parsed HTTP cookie

type DatabaseHealthChecker

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

DatabaseHealthChecker checks database connectivity

func NewDatabaseHealthChecker

func NewDatabaseHealthChecker(name string, required bool, testFunc func(context.Context) error) *DatabaseHealthChecker

func (*DatabaseHealthChecker) Check

func (*DatabaseHealthChecker) IsRequired

func (d *DatabaseHealthChecker) IsRequired() bool

func (*DatabaseHealthChecker) Name

func (d *DatabaseHealthChecker) Name() string

type DynamORMIdempotencyStore added in v1.0.37

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

DynamORMIdempotencyStore implements IdempotencyStore using DynamORM

func NewDynamORMIdempotencyStore added in v1.0.37

func NewDynamORMIdempotencyStore() *DynamORMIdempotencyStore

NewDynamORMIdempotencyStore creates a new DynamORM-based idempotency store This assumes the DynamORM middleware has been configured in the Lift app

func NewDynamORMIdempotencyStoreWithWrapper added in v1.0.37

func NewDynamORMIdempotencyStoreWithWrapper(wrapper *dynamorm.DynamORMWrapper) *DynamORMIdempotencyStore

NewDynamORMIdempotencyStoreWithWrapper creates a store with a specific DynamORM wrapper

func (*DynamORMIdempotencyStore) Delete added in v1.0.37

func (d *DynamORMIdempotencyStore) Delete(ctx context.Context, key string) error

Delete removes a key from the store

func (*DynamORMIdempotencyStore) Get added in v1.0.37

Get retrieves a stored response by key

func (*DynamORMIdempotencyStore) Set added in v1.0.37

Set stores a response with the given key

func (*DynamORMIdempotencyStore) SetProcessing added in v1.0.37

func (d *DynamORMIdempotencyStore) SetProcessing(ctx context.Context, key string, expiresAt time.Time) error

SetProcessing marks a key as being processed

type EnhancedObservabilityConfig

type EnhancedObservabilityConfig struct {
	// Core components
	Logger  observability.StructuredLogger
	Metrics observability.MetricsCollector
	Tracer  *xray.XRayTracer

	// Feature flags
	EnableLogging bool `json:"enable_logging"`
	EnableMetrics bool `json:"enable_metrics"`
	EnableTracing bool `json:"enable_tracing"`

	// Custom extractors
	OperationNameFunc func(*lift.Context) string
	TenantIDFunc      func(*lift.Context) string
	UserIDFunc        func(*lift.Context) string

	// Performance settings
	LogRequestBody  bool    `json:"log_request_body"`
	LogResponseBody bool    `json:"log_response_body"`
	MaxBodyLogSize  int     `json:"max_body_log_size"`
	SampleRate      float64 `json:"sample_rate"` // 0.0 to 1.0

	// Custom dimensions/tags
	DefaultTags map[string]string `json:"default_tags"`
}

EnhancedObservabilityConfig holds configuration for the complete observability stack

type HTTPHealthChecker

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

HTTPHealthChecker checks HTTP endpoint health

func NewHTTPHealthChecker

func NewHTTPHealthChecker(name, url string, required bool, timeout time.Duration) *HTTPHealthChecker

func (*HTTPHealthChecker) Check

func (h *HTTPHealthChecker) Check(ctx context.Context) error

func (*HTTPHealthChecker) IsRequired

func (h *HTTPHealthChecker) IsRequired() bool

func (*HTTPHealthChecker) Name

func (h *HTTPHealthChecker) Name() string

type HealthCheckConfig

type HealthCheckConfig struct {
	// Endpoint configuration
	Path       string `json:"path"`        // Health check endpoint path (default: /health)
	DetailPath string `json:"detail_path"` // Detailed health check path (default: /health/detail)
	ReadyPath  string `json:"ready_path"`  // Readiness check path (default: /ready)
	LivePath   string `json:"live_path"`   // Liveness check path (default: /live)

	// Check configuration
	Timeout     time.Duration `json:"timeout"`      // Timeout for individual checks
	Interval    time.Duration `json:"interval"`     // How often to run background checks
	GracePeriod time.Duration `json:"grace_period"` // Grace period during startup

	// Circuit breaker settings
	FailureThreshold int           `json:"failure_threshold"` // Failures before marking unhealthy
	RecoveryTime     time.Duration `json:"recovery_time"`     // Time to wait before retry

	// Dependencies
	Dependencies []HealthChecker `json:"-"` // External dependencies to check

	// Observability
	Logger  observability.StructuredLogger `json:"-"`
	Metrics observability.MetricsCollector `json:"-"`

	// Feature flags
	EnableDetailedChecks bool `json:"enable_detailed_checks"`
	EnableMetrics        bool `json:"enable_metrics"`
	EnableBackgroundRuns bool `json:"enable_background_runs"`
}

HealthCheckConfig holds configuration for health checks

type HealthCheckResult

type HealthCheckResult struct {
	Name      string         `json:"name"`
	Status    HealthStatus   `json:"status"`
	Message   string         `json:"message,omitempty"`
	Duration  time.Duration  `json:"duration"`
	Timestamp time.Time      `json:"timestamp"`
	Details   map[string]any `json:"details,omitempty"`
	Required  bool           `json:"required"`
}

HealthCheckResult represents the result of a health check

type HealthChecker

type HealthChecker interface {
	Name() string
	Check(ctx context.Context) error
	IsRequired() bool // If true, failure marks entire system as unhealthy
}

HealthChecker interface for dependency health checks

type HealthConfig

type HealthConfig = HealthCheckConfig

Backward compatibility aliases

type HealthStatus

type HealthStatus string

HealthStatus represents the health status of a component

const (
	HealthStatusHealthy   HealthStatus = "healthy"
	HealthStatusUnhealthy HealthStatus = "unhealthy"
	HealthStatusDegraded  HealthStatus = "degraded"
	HealthStatusUnknown   HealthStatus = "unknown"
)

type HealthSummary

type HealthSummary struct {
	Total     int `json:"total"`
	Healthy   int `json:"healthy"`
	Unhealthy int `json:"unhealthy"`
	Degraded  int `json:"degraded"`
	Unknown   int `json:"unknown"`
}

HealthSummary provides a summary of health check results

type IdempotencyOptions added in v1.0.27

type IdempotencyOptions struct {
	// Store is the backend for storing idempotency records
	Store IdempotencyStore
	// HeaderName is the header to check for idempotency key (default: "Idempotency-Key")
	HeaderName string
	// TTL is how long to store successful responses (default: 24 hours)
	TTL time.Duration
	// ProcessingTimeout is how long to wait for in-flight requests (default: 30 seconds)
	ProcessingTimeout time.Duration
	// IncludeRequestHash includes request body hash for stricter validation
	IncludeRequestHash bool
	// OnDuplicate is called when a duplicate request is detected
	OnDuplicate func(ctx *lift.Context, record *IdempotencyRecord)
}

IdempotencyOptions configures the idempotency middleware

type IdempotencyRecord added in v1.0.27

type IdempotencyRecord struct {
	Key          string    `json:"key"`
	Status       string    `json:"status"` // "processing", "completed", "error"
	Response     any       `json:"response,omitempty"`
	StatusCode   int       `json:"status_code,omitempty"`
	Error        string    `json:"error,omitempty"`
	CreatedAt    time.Time `json:"created_at"`
	ExpiresAt    time.Time `json:"expires_at"`
	RequestHash  string    `json:"request_hash,omitempty"`
	FunctionName string    `json:"function_name,omitempty"`
	TenantID     string    `json:"tenant_id,omitempty"`
	UserID       string    `json:"user_id,omitempty"`
}

IdempotencyRecord represents a stored idempotent response

type IdempotencyStore added in v1.0.27

type IdempotencyStore interface {
	// Get retrieves a stored response by key
	Get(ctx context.Context, key string) (*IdempotencyRecord, error)
	// Set stores a response with the given key
	Set(ctx context.Context, key string, record *IdempotencyRecord) error
	// SetProcessing marks a key as being processed (prevents concurrent duplicates)
	SetProcessing(ctx context.Context, key string, expiresAt time.Time) error
	// Delete removes a key from the store
	Delete(ctx context.Context, key string) error
}

IdempotencyStore defines the interface for storing idempotency keys and responses

type JWTClaims

type JWTClaims struct {
	jwt.RegisteredClaims
	TenantID  string   `json:"tenant_id"`
	AccountID string   `json:"account_id"`
	Roles     []string `json:"roles"`
	Scopes    []string `json:"scopes"`
}

JWTClaims represents the claims in a JWT token

type JWTConfig

type JWTConfig struct {
	// Secret key for HMAC algorithms
	Secret string

	// Public key for RSA/ECDSA algorithms
	PublicKey any

	// Algorithm to use (HS256, RS256, etc)
	Algorithm string

	// Token lookup string (e.g., "header:Authorization,query:token")
	TokenLookup string

	// Claims validator function
	Validator func(claims jwt.MapClaims) error

	// Error handler
	ErrorHandler func(ctx *lift.Context, err error) error

	// Skip authentication for these paths
	SkipPaths []string

	// Optional: custom claims type
	Claims jwt.Claims

	// Optional: custom token extractor
	Extractor func(ctx *lift.Context) (string, error)
}

JWTConfig holds configuration for JWT middleware

func DefaultJWTConfig

func DefaultJWTConfig() JWTConfig

DefaultJWTConfig returns a default JWT configuration

type JWTValidator

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

JWTValidator handles JWT token validation

func NewJWTValidator

func NewJWTValidator(config security.JWTConfig) (*JWTValidator, error)

NewJWTValidator creates a new JWT validator

func (*JWTValidator) ValidateToken

func (v *JWTValidator) ValidateToken(tokenString string) (*JWTClaims, error)

ValidateToken validates a JWT token and returns the claims

type LimitedConfig added in v1.0.35

type LimitedConfig struct {
	// DynamoDB configuration
	Region    string
	TableName string
	Endpoint  string // Optional, for local testing

	// Rate limiting parameters
	Window time.Duration
	Limit  int

	// Strategy type
	Strategy string // "fixed", "sliding", "token", "leaky"

	// Logger
	Logger *zap.Logger
}

LimitedConfig holds configuration for the limited-based rate limiter

type LoadMetrics

type LoadMetrics struct {
	// System metrics
	CPUUsage    float64 `json:"cpu_usage"`
	MemoryUsage float64 `json:"memory_usage"`

	// Application metrics
	ActiveRequests int64         `json:"active_requests"`
	RequestRate    float64       `json:"request_rate"`
	AverageLatency time.Duration `json:"average_latency"`
	P95Latency     time.Duration `json:"p95_latency"`
	P99Latency     time.Duration `json:"p99_latency"`
	ErrorRate      float64       `json:"error_rate"`

	// Load shedding metrics
	CurrentSheddingRate float64 `json:"current_shedding_rate"`
	TotalRequests       int64   `json:"total_requests"`
	ShedRequests        int64   `json:"shed_requests"`

	// Timestamps
	LastUpdated time.Time `json:"last_updated"`
	WindowStart time.Time `json:"window_start"`
}

LoadMetrics provides real-time system and application metrics

type LoadSheddingConfig

type LoadSheddingConfig struct {
	// Basic settings
	Strategy LoadSheddingStrategy `json:"strategy"` // Load shedding strategy
	Enabled  bool                 `json:"enabled"`  // Enable/disable load shedding

	// Threshold settings
	CPUThreshold       float64       `json:"cpu_threshold"`        // CPU usage threshold (0.0-1.0)
	MemoryThreshold    float64       `json:"memory_threshold"`     // Memory usage threshold (0.0-1.0)
	LatencyThreshold   time.Duration `json:"latency_threshold"`    // Response time threshold
	ErrorRateThreshold float64       `json:"error_rate_threshold"` // Error rate threshold (0.0-1.0)

	// Adaptive settings
	TargetLatency   time.Duration `json:"target_latency"`    // Target response time
	MaxSheddingRate float64       `json:"max_shedding_rate"` // Maximum shedding rate (0.0-1.0)
	MinSheddingRate float64       `json:"min_shedding_rate"` // Minimum shedding rate (0.0-1.0)
	SheddingRate    float64       `json:"shedding_rate"`     // Fixed shedding rate (for simple strategies)
	AdaptationRate  float64       `json:"adaptation_rate"`   // How quickly to adapt (0.0-1.0)

	// Priority settings
	PriorityExtractor  func(*lift.Context) int `json:"-"`                   // Extract priority from request
	PriorityThresholds map[int]float64         `json:"priority_thresholds"` // Shedding rates by priority

	// Custom algorithm
	CustomShedder func(*lift.Context, *LoadMetrics) bool `json:"-"` // Custom shedding function

	// Monitoring settings
	MetricsWindow time.Duration `json:"metrics_window"` // Window for metrics calculation
	SamplingRate  float64       `json:"sampling_rate"`  // Rate of requests to sample for metrics

	// Response settings
	SheddingHandler    func(*lift.Context) error `json:"-"`                    // Custom shedding response
	SheddingStatusCode int                       `json:"shedding_status_code"` // HTTP status for shed requests
	SheddingMessage    string                    `json:"shedding_message"`     // Message for shed requests

	// Observability
	Logger        observability.StructuredLogger `json:"-"`
	Metrics       observability.MetricsCollector `json:"-"`
	EnableMetrics bool                           `json:"enable_metrics"`

	// Naming
	Name string `json:"name"` // Load shedding name for metrics
}

LoadSheddingConfig holds configuration for load shedding

func NewAdaptiveLoadShedding

func NewAdaptiveLoadShedding(name string, targetLatency time.Duration) LoadSheddingConfig

NewAdaptiveLoadShedding creates an adaptive load shedding configuration

func NewBasicLoadShedding

func NewBasicLoadShedding(name string) LoadSheddingConfig

NewBasicLoadShedding creates a basic load shedding configuration

func NewCustomLoadShedding

func NewCustomLoadShedding(name string, customShedder func(*lift.Context, *LoadMetrics) bool) LoadSheddingConfig

NewCustomLoadShedding creates a custom load shedding configuration

func NewPriorityLoadShedding

func NewPriorityLoadShedding(name string, priorityThresholds map[int]float64) LoadSheddingConfig

NewPriorityLoadShedding creates a priority-based load shedding configuration

type LoadSheddingStats

type LoadSheddingStats struct {
	Name                string               `json:"name"`
	Strategy            LoadSheddingStrategy `json:"strategy"`
	Enabled             bool                 `json:"enabled"`
	CurrentSheddingRate float64              `json:"current_shedding_rate"`
	TotalRequests       int64                `json:"total_requests"`
	ShedRequests        int64                `json:"shed_requests"`
	SheddingRatio       float64              `json:"shedding_ratio"`
	AverageLatency      time.Duration        `json:"average_latency"`
	SystemMetrics       LoadMetrics          `json:"system_metrics"`
}

LoadSheddingStats provides statistics about load shedding performance

type LoadSheddingStrategy

type LoadSheddingStrategy string

LoadSheddingStrategy defines different load shedding strategies

type MemoryHealthChecker

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

MemoryHealthChecker checks memory usage

func NewMemoryHealthChecker

func NewMemoryHealthChecker(name string, threshold float64) *MemoryHealthChecker

func (*MemoryHealthChecker) Check

func (m *MemoryHealthChecker) Check(ctx context.Context) error

func (*MemoryHealthChecker) IsRequired

func (m *MemoryHealthChecker) IsRequired() bool

func (*MemoryHealthChecker) Name

func (m *MemoryHealthChecker) Name() string

type MemoryIdempotencyStore added in v1.0.27

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

MemoryIdempotencyStore provides an in-memory implementation of IdempotencyStore This is suitable for single-instance applications or testing

func NewMemoryIdempotencyStore added in v1.0.27

func NewMemoryIdempotencyStore() *MemoryIdempotencyStore

NewMemoryIdempotencyStore creates a new in-memory idempotency store

func (*MemoryIdempotencyStore) Delete added in v1.0.27

func (m *MemoryIdempotencyStore) Delete(ctx context.Context, key string) error

Delete removes a record

func (*MemoryIdempotencyStore) Get added in v1.0.27

Get retrieves a record by key

func (*MemoryIdempotencyStore) Set added in v1.0.27

Set stores a record

func (*MemoryIdempotencyStore) SetProcessing added in v1.0.27

func (m *MemoryIdempotencyStore) SetProcessing(ctx context.Context, key string, expiresAt time.Time) error

SetProcessing marks a key as being processed

type Middleware

type Middleware func(lift.Handler) lift.Handler

Middleware represents a middleware function

func CORS

func CORS(allowedOrigins []string) Middleware

CORS provides cross-origin resource sharing headers

func Chain

func Chain(middlewares ...Middleware) Middleware

Chain combines multiple middleware into a single middleware

func ErrorHandler

func ErrorHandler() Middleware

ErrorHandler converts errors to appropriate HTTP responses

func Idempotency added in v1.0.27

func Idempotency(opts IdempotencyOptions) Middleware

Idempotency creates middleware that provides idempotent request handling

func Logger

func Logger() Middleware

Logger provides structured request/response logging

func Metrics

func Metrics() Middleware

Metrics collects basic performance metrics

func Recover

func Recover() Middleware

Recover provides panic recovery and graceful error handling

func RequestID

func RequestID() Middleware

RequestID generates and sets a unique request ID

func Timeout

func Timeout(duration time.Duration) Middleware

Timeout adds request timeout handling

type ObservabilityConfig

type ObservabilityConfig struct {
	Logger  observability.StructuredLogger
	Metrics observability.MetricsCollector
	// Optional: custom operation name extractor
	OperationNameFunc func(*lift.Context) string
}

ObservabilityConfig holds configuration for observability middleware

type ObservabilityStats

type ObservabilityStats struct {
	Logger  *observability.LoggerStats  `json:"logger,omitempty"`
	Metrics *observability.MetricsStats `json:"metrics,omitempty"`
	Tracing *TracingStats               `json:"tracing,omitempty"`
}

ObservabilityStats provides comprehensive statistics about observability performance

func GetObservabilityStats

func GetObservabilityStats(config EnhancedObservabilityConfig) ObservabilityStats

GetObservabilityStats returns comprehensive observability statistics

type OverallHealthResult

type OverallHealthResult struct {
	Status      HealthStatus                  `json:"status"`
	Timestamp   time.Time                     `json:"timestamp"`
	Duration    time.Duration                 `json:"duration"`
	Version     string                        `json:"version,omitempty"`
	Environment string                        `json:"environment,omitempty"`
	Checks      map[string]*HealthCheckResult `json:"checks,omitempty"`
	Summary     *HealthSummary                `json:"summary,omitempty"`
}

OverallHealthResult represents the overall system health

type RateLimitConfig

type RateLimitConfig struct {
	// DynamORM configuration
	DynamORM *dynamorm.DynamORMWrapper `json:"-"`

	// Rate limiting settings
	DefaultLimit  int           `json:"default_limit"`  // Requests per window
	DefaultWindow time.Duration `json:"default_window"` // Time window
	Window        time.Duration `json:"window"`         // Alias for DefaultWindow (backward compatibility)
	BurstLimit    int           `json:"burst_limit"`    // Burst allowance

	// Strategy settings
	Strategy    string        `json:"strategy"`    // fixed_window, sliding_window, multi_window
	Granularity time.Duration `json:"granularity"` // For sliding window strategy

	// Multi-tenant settings
	TenantLimits map[string]int `json:"tenant_limits"` // Per-tenant limits
	UserLimits   map[string]int `json:"user_limits"`   // Per-user limits

	// Key generation
	KeyPrefix     string                            `json:"key_prefix"`
	KeyFunc       func(*lift.Context) *RateLimitKey `json:"-"` // Custom key function
	IncludePath   bool                              `json:"include_path"`
	IncludeMethod bool                              `json:"include_method"`

	// Error handling
	ErrorHandler func(*lift.Context, *RateLimitResult) error `json:"-"` // Custom error handler

	// Behavior settings
	SkipSuccessful bool `json:"skip_successful"` // Only count failed requests
	SkipOptions    bool `json:"skip_options"`    // Skip OPTIONS requests

	// Headers
	HeaderPrefix string `json:"header_prefix"` // X-RateLimit prefix

	// Storage settings
	TableName       string        `json:"table_name"`
	TTL             time.Duration `json:"ttl"`              // How long to keep records
	CleanupInterval time.Duration `json:"cleanup_interval"` // How often to cleanup
}

RateLimitConfig holds configuration for rate limiting

type RateLimitEntry

type RateLimitEntry struct {
	Key         string    `json:"key"`
	Count       int       `json:"count"`
	WindowStart time.Time `json:"window_start"`
	LastRequest time.Time `json:"last_request"`
	TTL         int64     `json:"ttl"`
}

RateLimitEntry represents a rate limit record in DynamoDB

type RateLimitKey

type RateLimitKey struct {
	Identifier string            `json:"identifier"` // Primary identifier (tenant:user, IP, etc.)
	Resource   string            `json:"resource"`   // Resource being accessed (path)
	Operation  string            `json:"operation"`  // Operation being performed (method)
	Metadata   map[string]string `json:"metadata"`   // Additional metadata
}

RateLimitKey represents a rate limiting key with metadata

type RateLimitResult

type RateLimitResult struct {
	Allowed     bool          `json:"allowed"`
	Limit       int           `json:"limit"`
	Remaining   int           `json:"remaining"`
	ResetAt     time.Time     `json:"reset_at"`
	RetryAfter  time.Duration `json:"retry_after"`
	WindowStart time.Time     `json:"window_start"`
}

RateLimitResult contains the result of a rate limit check

type RateLimitStats

type RateLimitStats struct {
	TotalRequests   int64 `json:"total_requests"`
	AllowedRequests int64 `json:"allowed_requests"`
	BlockedRequests int64 `json:"blocked_requests"`
	ErrorCount      int64 `json:"error_count"`
}

RateLimitStats provides statistics about rate limiting

func GetRateLimitStats

func GetRateLimitStats(config RateLimitConfig) (*RateLimitStats, error)

GetRateLimitStats returns rate limiting statistics from actual usage data

type ResourceStats

type ResourceStats struct {
	ActiveRequests   int     `json:"active_requests"`
	QueuedRequests   int     `json:"queued_requests"`
	TotalRequests    int64   `json:"total_requests"`
	RejectedRequests int64   `json:"rejected_requests"`
	Utilization      float64 `json:"utilization"`
	Limit            int     `json:"limit"`
}

ResourceStats provides statistics for a specific resource pool

type RetryConfig

type RetryConfig struct {
	// Basic retry settings
	MaxAttempts  int           `json:"max_attempts"`  // Maximum number of retry attempts
	InitialDelay time.Duration `json:"initial_delay"` // Initial delay before first retry
	MaxDelay     time.Duration `json:"max_delay"`     // Maximum delay between retries
	Strategy     RetryStrategy `json:"strategy"`      // Retry strategy to use

	// Backoff configuration
	BackoffMultiplier float64 `json:"backoff_multiplier"` // Multiplier for exponential backoff
	Jitter            bool    `json:"jitter"`             // Add random jitter to delays
	JitterRange       float64 `json:"jitter_range"`       // Jitter range (0.0-1.0)

	// Custom strategy
	CustomBackoff func(attempt int, lastDelay time.Duration) time.Duration `json:"-"` // Custom backoff function

	// Retry conditions
	RetryableErrors    []string         `json:"retryable_errors"`     // Specific error types to retry
	RetryCondition     func(error) bool `json:"-"`                    // Custom retry condition
	NonRetryableErrors []string         `json:"non_retryable_errors"` // Errors that should never be retried

	// HTTP-specific settings
	RetryableStatusCodes    []int `json:"retryable_status_codes"`     // HTTP status codes to retry
	NonRetryableStatusCodes []int `json:"non_retryable_status_codes"` // HTTP status codes to never retry

	// Context and timeouts
	PerAttemptTimeout time.Duration `json:"per_attempt_timeout"` // Timeout per individual attempt
	TotalTimeout      time.Duration `json:"total_timeout"`       // Total timeout for all attempts

	// Observability
	Logger        observability.StructuredLogger `json:"-"`
	Metrics       observability.MetricsCollector `json:"-"`
	EnableMetrics bool                           `json:"enable_metrics"`

	// Callbacks
	OnRetry  func(attempt int, err error, delay time.Duration) `json:"-"` // Called before each retry
	OnGiveUp func(attempts int, lastErr error)                 `json:"-"` // Called when giving up

	// Naming
	Name string `json:"name"` // Retry middleware name for metrics
}

RetryConfig holds configuration for the retry middleware

func NewBasicRetry

func NewBasicRetry(name string, maxAttempts int) RetryConfig

NewBasicRetry creates a basic retry configuration with exponential backoff

func NewCustomRetry

func NewCustomRetry(name string, maxAttempts int, backoffFunc func(int, time.Duration) time.Duration) RetryConfig

NewCustomRetry creates a retry configuration with custom backoff

func NewDatabaseRetry

func NewDatabaseRetry(name string, maxAttempts int) RetryConfig

NewDatabaseRetry creates a retry configuration optimized for database operations

func NewHTTPRetry

func NewHTTPRetry(name string, maxAttempts int) RetryConfig

NewHTTPRetry creates a retry configuration optimized for HTTP requests

type RetryStats

type RetryStats struct {
	Name              string        `json:"name"`
	TotalRequests     int64         `json:"total_requests"`
	RetriedRequests   int64         `json:"retried_requests"`
	SuccessfulRetries int64         `json:"successful_retries"`
	FailedRetries     int64         `json:"failed_retries"`
	TotalAttempts     int64         `json:"total_attempts"`
	AverageAttempts   float64       `json:"average_attempts"`
	MaxAttempts       int           `json:"max_attempts"`
	AverageDelay      time.Duration `json:"average_delay"`
	TotalDelay        time.Duration `json:"total_delay"`
}

RetryStats provides statistics about retry performance

type RetryStrategy

type RetryStrategy string

RetryStrategy defines different retry strategies

const (
	RetryStrategyFixed       RetryStrategy = "fixed"       // Fixed delay between retries
	RetryStrategyLinear      RetryStrategy = "linear"      // Linear backoff
	RetryStrategyExponential RetryStrategy = "exponential" // Exponential backoff
	RetryStrategyCustom      RetryStrategy = "custom"      // Custom backoff function
)

type SecurityHeadersConfig

type SecurityHeadersConfig struct {
	// Content Security Policy
	ContentSecurityPolicy string

	// X-Frame-Options: DENY, SAMEORIGIN, or ALLOW-FROM uri
	XFrameOptions string

	// X-Content-Type-Options: nosniff
	XContentTypeOptions bool

	// X-XSS-Protection: 1; mode=block
	XXSSProtection string

	// Strict-Transport-Security
	StrictTransportSecurity string

	// Referrer-Policy
	ReferrerPolicy string

	// Permissions-Policy (formerly Feature-Policy)
	PermissionsPolicy string

	// Custom headers to add
	CustomHeaders map[string]string

	// Whether to include security headers in development
	IncludeInDevelopment bool
}

SecurityHeadersConfig configures the security headers middleware

func DefaultSecurityHeadersConfig

func DefaultSecurityHeadersConfig() SecurityHeadersConfig

DefaultSecurityHeadersConfig returns secure default configuration

type ServiceMeshAdapter added in v1.0.37

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

ServiceMeshAdapter provides AWS App Mesh integration

func NewServiceMeshAdapter added in v1.0.37

func NewServiceMeshAdapter(meshConfig ServiceMeshConfig) (*ServiceMeshAdapter, error)

NewServiceMeshAdapter creates a new service mesh adapter

func (*ServiceMeshAdapter) DeregisterService added in v1.0.37

func (s *ServiceMeshAdapter) DeregisterService(ctx context.Context) error

DeregisterService removes the service instance from AWS Cloud Map

func (*ServiceMeshAdapter) HealthCheckHandler added in v1.0.37

func (s *ServiceMeshAdapter) HealthCheckHandler() lift.Handler

HealthCheckHandler returns a health check handler

func (*ServiceMeshAdapter) Middleware added in v1.0.37

func (s *ServiceMeshAdapter) Middleware() lift.Middleware

Middleware returns the service mesh middleware

func (*ServiceMeshAdapter) RegisterService added in v1.0.37

func (s *ServiceMeshAdapter) RegisterService(ctx context.Context) error

RegisterService registers the service with AWS Cloud Map

type ServiceMeshConfig added in v1.0.37

type ServiceMeshConfig struct {
	// AWS App Mesh configuration
	MeshName    string `json:"mesh_name"`
	VirtualNode string `json:"virtual_node"`

	// Service Discovery configuration
	ServiceName string `json:"service_name"`
	Namespace   string `json:"namespace"`

	// Health check configuration
	HealthCheckPath     string        `json:"health_check_path"`
	HealthCheckInterval time.Duration `json:"health_check_interval"`
	HealthCheckTimeout  time.Duration `json:"health_check_timeout"`

	// Port configuration
	Port string `json:"port"`

	// AWS Region
	Region string `json:"region"`
}

ServiceMeshConfig holds configuration for service mesh integration

type ServiceMeshHealthStatus added in v1.0.37

type ServiceMeshHealthStatus struct {
	Healthy      bool                   `json:"healthy"`
	Service      string                 `json:"service"`
	VirtualNode  string                 `json:"virtual_node"`
	Dependencies map[string]bool        `json:"dependencies,omitempty"`
	Metadata     map[string]interface{} `json:"metadata,omitempty"`
}

ServiceMeshHealthStatus represents the health check response for service mesh

type SlidingWindowRateLimiter added in v1.0.37

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

func NewSlidingWindowRateLimiter added in v1.0.37

func NewSlidingWindowRateLimiter(config RateLimitConfig) (*SlidingWindowRateLimiter, error)

func (*SlidingWindowRateLimiter) Middleware added in v1.0.37

func (r *SlidingWindowRateLimiter) Middleware() lift.Middleware

type TimeoutConfig

type TimeoutConfig struct {
	// Basic timeout settings
	DefaultTimeout time.Duration `json:"default_timeout"` // Default timeout for all requests
	ReadTimeout    time.Duration `json:"read_timeout"`    // Timeout for reading request body
	WriteTimeout   time.Duration `json:"write_timeout"`   // Timeout for writing response
	IdleTimeout    time.Duration `json:"idle_timeout"`    // Timeout for idle connections

	// Per-operation timeouts
	OperationTimeouts map[string]time.Duration `json:"operation_timeouts"` // Timeouts per operation

	// Per-tenant timeouts
	TenantTimeouts map[string]time.Duration `json:"tenant_timeouts"` // Timeouts per tenant

	// Dynamic timeout settings
	EnableDynamicTimeout bool                              `json:"enable_dynamic_timeout"` // Enable dynamic timeout adjustment
	TimeoutCalculator    func(*lift.Context) time.Duration `json:"-"`                      // Custom timeout calculator

	// Graceful handling
	GracefulShutdown bool          `json:"graceful_shutdown"` // Enable graceful shutdown
	ShutdownTimeout  time.Duration `json:"shutdown_timeout"`  // Timeout for graceful shutdown

	// Response settings
	TimeoutHandler    func(*lift.Context) error `json:"-"`                   // Custom timeout response handler
	TimeoutStatusCode int                       `json:"timeout_status_code"` // HTTP status for timeout
	TimeoutMessage    string                    `json:"timeout_message"`     // Message for timeout response

	// Observability
	Logger        observability.StructuredLogger `json:"-"`
	Metrics       observability.MetricsCollector `json:"-"`
	EnableMetrics bool                           `json:"enable_metrics"`

	// Naming
	Name string `json:"name"` // Timeout middleware name for metrics
}

TimeoutConfig holds configuration for request timeouts

func NewBasicTimeout

func NewBasicTimeout(name string, defaultTimeout time.Duration) TimeoutConfig

NewBasicTimeout creates a basic timeout configuration

func NewDynamicTimeout

func NewDynamicTimeout(name string, defaultTimeout time.Duration, calculator func(*lift.Context) time.Duration) TimeoutConfig

NewDynamicTimeout creates a timeout configuration with dynamic timeout calculation

func NewOperationTimeout

func NewOperationTimeout(name string, defaultTimeout time.Duration, operationTimeouts map[string]time.Duration) TimeoutConfig

NewOperationTimeout creates a timeout configuration with per-operation timeouts

func NewTenantTimeout

func NewTenantTimeout(name string, defaultTimeout time.Duration, tenantTimeouts map[string]time.Duration) TimeoutConfig

NewTenantTimeout creates a timeout configuration with per-tenant timeouts

type TimeoutStats

type TimeoutStats struct {
	Name            string        `json:"name"`
	TotalRequests   int64         `json:"total_requests"`
	TimeoutRequests int64         `json:"timeout_requests"`
	TimeoutRatio    float64       `json:"timeout_ratio"`
	AverageTimeout  time.Duration `json:"average_timeout"`
	MaxTimeout      time.Duration `json:"max_timeout"`
	MinTimeout      time.Duration `json:"min_timeout"`
	AverageDuration time.Duration `json:"average_duration"`
}

TimeoutStats provides statistics about timeout performance

type TracingStats

type TracingStats struct {
	TracesGenerated int64     `json:"traces_generated"`
	LastTrace       time.Time `json:"last_trace"`
	ErrorCount      int64     `json:"error_count"`
}

TracingStats provides statistics about tracing performance

type ValidationConfig

type ValidationConfig struct {
	MaxBodySize              int64                         `json:"max_body_size"`         // Maximum request body size in bytes
	MaxHeaderSize            int                           `json:"max_header_size"`       // Maximum header value size
	MaxQueryParamSize        int                           `json:"max_query_param_size"`  // Maximum query parameter size
	MaxPathParamSize         int                           `json:"max_path_param_size"`   // Maximum path parameter size
	AllowedContentTypes      []string                      `json:"allowed_content_types"` // Allowed content types
	BlockedUserAgents        []string                      `json:"blocked_user_agents"`   // Blocked user agent patterns
	CustomValidators         map[string]func(string) error `json:"-"`                     // Custom field validators
	EnableSQLInjectionCheck  bool                          `json:"enable_sql_injection_check"`
	EnableXSSCheck           bool                          `json:"enable_xss_check"`
	EnablePathTraversalCheck bool                          `json:"enable_path_traversal_check"`
}

ValidationConfig configures input validation middleware

func DefaultValidationConfig

func DefaultValidationConfig() ValidationConfig

DefaultValidationConfig returns a secure default configuration

type WebSocketAuthConfig

type WebSocketAuthConfig struct {
	JWTConfig      security.JWTConfig
	TokenExtractor func(ctx *lift.Context) string
	OnError        func(ctx *lift.Context, err error) error
	SkipRoutes     []string // Routes to skip authentication (e.g., health checks)
}

WebSocketAuthConfig configures WebSocket authentication

Jump to

Keyboard shortcuts

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