errors

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Sep 4, 2025 License: Apache-2.0 Imports: 23 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExtractOperationContext

func ExtractOperationContext(ctx context.Context) (service, component, operation string)

func FormatStackTrace

func FormatStackTrace(frames []StackFrame, includeSource bool) string

func GetCallerInfo

func GetCallerInfo(skip int) (file string, line int, function string, ok bool)

func GetCorrelationID

func GetCorrelationID(ctx context.Context) string

func GetCurrentStackDepth

func GetCurrentStackDepth() int

func GetRequestID

func GetRequestID(ctx context.Context) string

func GetUserID

func GetUserID(ctx context.Context) string

func IsInPackage

func IsInPackage(packageName string, maxDepth int) bool

func WithContext

func WithContext(err error, message string) error

WithContext wraps an error with additional context information This is compatible with pkg/errors.WithContext usage

func WithCorrelationID

func WithCorrelationID(ctx context.Context, correlationID string) context.Context

func WithOperationContext

func WithOperationContext(ctx context.Context, service, component, operation string) context.Context

func WithRequestID

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

func WithUserID

func WithUserID(ctx context.Context, userID string) context.Context

Types

type AdvancedRecoveryCallback

type AdvancedRecoveryCallback func(request *AdvancedRecoveryRequest, result *AdvancedRecoveryResult)

type AdvancedRecoveryConfig

type AdvancedRecoveryConfig struct {
	MaxConcurrentRecoveries int `json:"maxConcurrentRecoveries"`

	RecoveryTimeout time.Duration `json:"recoveryTimeout"`

	MonitoringInterval time.Duration `json:"monitoringInterval"`

	QueueSize int `json:"queueSize"`

	ErrorCorrelationWindow time.Duration `json:"errorCorrelationWindow"`

	ErrorCorrelationThreshold int `json:"errorCorrelationThreshold"`

	AutoRecoveryEnabled bool `json:"autoRecoveryEnabled"`

	AutoRecoveryDelay time.Duration `json:"autoRecoveryDelay"`

	MaxAutoRecoveryAttempts int `json:"maxAutoRecoveryAttempts"`

	CascadeProtectionEnabled bool `json:"cascadeProtectionEnabled"`

	CascadeDetectionWindow time.Duration `json:"cascadeDetectionWindow"`

	CascadeThreshold int `json:"cascadeThreshold"`

	HealthCheckInterval time.Duration `json:"healthCheckInterval"`

	HealthCheckTimeout time.Duration `json:"healthCheckTimeout"`

	MaxMemoryUsage int64 `json:"maxMemoryUsage"`

	MaxCPUUsage float64 `json:"maxCpuUsage"`
}

type AdvancedRecoveryManager

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

func NewAdvancedRecoveryManager

func NewAdvancedRecoveryManager(config *AdvancedRecoveryConfig, errorAggregator *ErrorAggregator, logger logr.Logger) *AdvancedRecoveryManager

func (*AdvancedRecoveryManager) GetAdvancedMetrics

func (arm *AdvancedRecoveryManager) GetAdvancedMetrics() *AdvancedRecoveryMetrics

func (*AdvancedRecoveryManager) RequestAdvancedRecovery

func (arm *AdvancedRecoveryManager) RequestAdvancedRecovery(req *AdvancedRecoveryRequest) error

func (*AdvancedRecoveryManager) Start

func (arm *AdvancedRecoveryManager) Start(ctx context.Context) error

func (*AdvancedRecoveryManager) Stop

func (arm *AdvancedRecoveryManager) Stop() error

type AdvancedRecoveryMetrics

type AdvancedRecoveryMetrics struct {
	TotalRequests int64 `json:"totalRequests"`

	SuccessfulRecoveries int64 `json:"successfulRecoveries"`

	FailedRecoveries int64 `json:"failedRecoveries"`

	AverageRecoveryTime time.Duration `json:"averageRecoveryTime"`

	P95RecoveryTime time.Duration `json:"p95RecoveryTime"`

	P99RecoveryTime time.Duration `json:"p99RecoveryTime"`

	StrategyStats map[RecoveryStrategy]*StrategyMetrics `json:"strategyStats"`

	ComponentStats map[string]*ComponentRecoveryStats `json:"componentStats"`

	CorrelationStats *CorrelationMetrics `json:"correlationStats"`

	ResourceStats *ResourceUtilizationStats `json:"resourceStats"`

	LastUpdated time.Time `json:"lastUpdated"`
	// contains filtered or unexported fields
}

func NewAdvancedRecoveryMetrics

func NewAdvancedRecoveryMetrics() *AdvancedRecoveryMetrics

type AdvancedRecoveryRequest

type AdvancedRecoveryRequest struct {
	ID string `json:"id"`

	Error *ProcessingError `json:"error"`

	Context context.Context `json:"-"`

	Strategy RecoveryStrategy `json:"strategy"`

	Priority int `json:"priority"`

	Component string `json:"component"`

	Operation string `json:"operation"`

	Phase string `json:"phase"`

	MaxRetries int `json:"maxRetries"`

	Timeout time.Duration `json:"timeout"`

	BackoffStrategy string `json:"backoffStrategy"`

	Callback AdvancedRecoveryCallback `json:"-"`

	ResultChan chan *AdvancedRecoveryResult `json:"-"`

	CreatedAt time.Time `json:"createdAt"`

	StartedAt *time.Time `json:"startedAt,omitempty"`

	CompletedAt *time.Time `json:"completedAt,omitempty"`

	CorrelationID string `json:"correlationId"`

	ParentRequestID string `json:"parentRequestId,omitempty"`

	GroupID string `json:"groupId,omitempty"`
}

type AdvancedRecoveryResult

type AdvancedRecoveryResult struct {
	Success bool `json:"success"`

	RequestID string `json:"requestId"`

	Strategy RecoveryStrategy `json:"strategy"`

	AttemptsUsed int `json:"attemptsUsed"`

	Duration time.Duration `json:"duration"`

	FinalError error `json:"-"`

	ErrorMessage string `json:"errorMessage,omitempty"`

	ErrorCode string `json:"errorCode,omitempty"`

	Data map[string]interface{} `json:"data,omitempty"`

	RecoveredState map[string]interface{} `json:"recoveredState,omitempty"`

	Metrics *RecoveryPerformanceMetrics `json:"metrics"`

	RecoveryPath []string `json:"recoveryPath,omitempty"`

	FallbacksUsed []string `json:"fallbacksUsed,omitempty"`

	CircuitBreakers []string `json:"circuitBreakers,omitempty"`

	ComponentHealth map[string]string `json:"componentHealth,omitempty"`
}

type Bulkhead

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

func NewBulkhead

func NewBulkhead(config *BulkheadConfig) *Bulkhead

func (*Bulkhead) Close

func (b *Bulkhead) Close()

func (*Bulkhead) Execute

func (b *Bulkhead) Execute(ctx context.Context, fn func() error) error

func (*Bulkhead) GetMetrics

func (b *Bulkhead) GetMetrics() map[string]interface{}

type BulkheadConfig

type BulkheadConfig struct {
	Name string `json:"name"`

	MaxConcurrent int `json:"max_concurrent"`

	QueueSize int `json:"queue_size"`

	Timeout time.Duration `json:"timeout"`

	RejectOverflow bool `json:"reject_overflow"`
}

func DefaultBulkheadConfig

func DefaultBulkheadConfig(name string) *BulkheadConfig

type CircuitBreaker

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

func NewCircuitBreaker

func NewCircuitBreaker(config *CircuitBreakerConfig) *CircuitBreaker

func (*CircuitBreaker) Execute

func (cb *CircuitBreaker) Execute(ctx context.Context, fn func() error) error

func (*CircuitBreaker) GetMetrics

func (cb *CircuitBreaker) GetMetrics() map[string]interface{}

func (*CircuitBreaker) GetState

func (cb *CircuitBreaker) GetState() CircuitBreakerState

func (*CircuitBreaker) Reset

func (cb *CircuitBreaker) Reset()

func (*CircuitBreaker) SetStateChangeCallback

func (cb *CircuitBreaker) SetStateChangeCallback(callback func(string, CircuitBreakerState, CircuitBreakerState))

type CircuitBreakerConfig

type CircuitBreakerConfig struct {
	Name string `json:"name"`

	MaxFailures int `json:"max_failures"`

	Timeout time.Duration `json:"timeout"`

	ResetTimeout time.Duration `json:"reset_timeout"`

	HalfOpenMaxCalls int `json:"half_open_max_calls"`

	FailureThresholdRatio float64 `json:"failure_threshold_ratio"`

	MinRequestThreshold int `json:"min_request_threshold"`

	SlidingWindowSize time.Duration `json:"sliding_window_size"`

	ConsecutiveFailures bool `json:"consecutive_failures"`
}

func DefaultCircuitBreakerConfig

func DefaultCircuitBreakerConfig(name string) *CircuitBreakerConfig

type CircuitBreakerState

type CircuitBreakerState int32
const (
	CircuitBreakerClosed CircuitBreakerState = iota

	CircuitBreakerOpen

	CircuitBreakerHalfOpen
)

func (CircuitBreakerState) String

func (s CircuitBreakerState) String() string

type ComponentRecoveryStats

type ComponentRecoveryStats struct {
	RecoveryCount int64 `json:"recoveryCount"`

	SuccessRate float64 `json:"successRate"`

	AverageRecoveryTime time.Duration `json:"averageRecoveryTime"`

	CommonErrors map[string]int64 `json:"commonErrors"`

	LastRecovery time.Time `json:"lastRecovery"`
}

type ContextAwareErrorBuilder

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

func NewContextAwareErrorBuilder

func NewContextAwareErrorBuilder(service, operation, component string, config *ErrorConfiguration) *ContextAwareErrorBuilder

func (*ContextAwareErrorBuilder) NewError

func (b *ContextAwareErrorBuilder) NewError(errType ErrorType, code, message string) *ServiceError

func (*ContextAwareErrorBuilder) NewErrorWithContext

func (b *ContextAwareErrorBuilder) NewErrorWithContext(ctx context.Context, errType ErrorType, code, message string) *ServiceError

func (*ContextAwareErrorBuilder) NewErrorWithHTTPRequest

func (b *ContextAwareErrorBuilder) NewErrorWithHTTPRequest(req *http.Request, errType ErrorType, code, message string) *ServiceError

func (*ContextAwareErrorBuilder) NewErrorWithSources

func (b *ContextAwareErrorBuilder) NewErrorWithSources(ctx context.Context, errType ErrorType, code, message string, sources ...interface{}) *ServiceError

func (*ContextAwareErrorBuilder) RegisterExtractor

func (b *ContextAwareErrorBuilder) RegisterExtractor(extractor ContextExtractor)

func (*ContextAwareErrorBuilder) WrapErrorWithContext

func (b *ContextAwareErrorBuilder) WrapErrorWithContext(ctx context.Context, cause error, message string, sources ...interface{}) *ServiceError

type ContextExtractor

type ContextExtractor interface {
	ExtractContext(source interface{}) map[string]interface{}

	GetContextKeys() []string
}

type ContextKey

type ContextKey string
const (
	RequestIDKey ContextKey = "request_id"

	CorrelationIDKey ContextKey = "correlation_id"

	UserIDKey ContextKey = "user_id"

	SessionIDKey ContextKey = "session_id"

	TraceIDKey ContextKey = "trace_id"

	SpanIDKey ContextKey = "span_id"

	TenantIDKey ContextKey = "tenant_id"

	ComponentKey ContextKey = "component"

	OperationKey ContextKey = "operation"

	ServiceKey ContextKey = "service"

	VersionKey ContextKey = "version"

	EnvironmentKey ContextKey = "environment"
)

type ContextualError

type ContextualError struct {
	*ServiceError
	// contains filtered or unexported fields
}

func NewContextualError

func NewContextualError(serviceErr *ServiceError, builder *ContextAwareErrorBuilder) *ContextualError

func (*ContextualError) ToServiceError

func (ce *ContextualError) ToServiceError() *ServiceError

func (*ContextualError) WithCustomContext

func (ce *ContextualError) WithCustomContext(key string, value interface{}) *ContextualError

func (*ContextualError) WithGoContext

func (ce *ContextualError) WithGoContext(ctx context.Context) *ContextualError

func (*ContextualError) WithHTTPRequest

func (ce *ContextualError) WithHTTPRequest(req *http.Request) *ContextualError

func (*ContextualError) WithLatency

func (ce *ContextualError) WithLatency(latency time.Duration) *ContextualError

func (*ContextualError) WithResource

func (ce *ContextualError) WithResource(resourceType, resourceID string) *ContextualError

type CorrelationMetrics

type CorrelationMetrics struct {
	CorrelatedGroups int64 `json:"correlatedGroups"`

	AverageGroupSize float64 `json:"averageGroupSize"`

	LargestGroup int `json:"largestGroup"`

	CorrelationPatterns map[string]int64 `json:"correlationPatterns"`
}

type DegradationConfig

type DegradationConfig struct {
	EnableDegradation bool `json:"enableDegradation"`

	AutoDegradation bool `json:"autoDegradation"`

	DegradationThreshold float64 `json:"degradationThreshold"`

	RecoveryThreshold float64 `json:"recoveryThreshold"`

	EvaluationWindow time.Duration `json:"evaluationWindow"`
}

type DegradationLevel

type DegradationLevel struct {
	Level int `json:"level"`

	Name string `json:"name"`

	Description string `json:"description"`

	Features []string `json:"features"`

	Limits map[string]interface{} `json:"limits,omitempty"`
}

type DegradationManager

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

func NewDegradationManager

func NewDegradationManager(config *DegradationConfig, logger logr.Logger) *DegradationManager

func (*DegradationManager) ApplyDegradation

func (dm *DegradationManager) ApplyDegradation(component string, level int) error

func (*DegradationManager) CalculateDegradationLevel

func (dm *DegradationManager) CalculateDegradationLevel(err *ProcessingError) int

func (*DegradationManager) GetDegradedFeatures

func (dm *DegradationManager) GetDegradedFeatures(component string) []string

type ErrorAggregationConfig

type ErrorAggregationConfig struct {
	MaxErrors int `json:"max_errors"`

	DeduplicationWindow time.Duration `json:"deduplication_window"`

	PatternAnalysis bool `json:"pattern_analysis"`

	CorrelationAnalysis bool `json:"correlation_analysis"`

	RetentionPeriod time.Duration `json:"retention_period"`

	MinPatternCount int `json:"min_pattern_count"`

	CorrelationThreshold float64 `json:"correlation_threshold"`
}

func DefaultErrorAggregationConfig

func DefaultErrorAggregationConfig() *ErrorAggregationConfig

type ErrorAggregator

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

func NewErrorAggregator

func NewErrorAggregator(config *ErrorAggregationConfig) *ErrorAggregator

func (*ErrorAggregator) AddError

func (ea *ErrorAggregator) AddError(err *ServiceError)

func (*ErrorAggregator) AddErrors

func (ea *ErrorAggregator) AddErrors(errors []*ServiceError)

func (*ErrorAggregator) GetCorrelations

func (ea *ErrorAggregator) GetCorrelations() []*ErrorCorrelation

func (*ErrorAggregator) GetErrors

func (ea *ErrorAggregator) GetErrors() []*ServiceError

func (*ErrorAggregator) GetErrorsByService

func (ea *ErrorAggregator) GetErrorsByService(service string) []*ServiceError

func (*ErrorAggregator) GetErrorsByType

func (ea *ErrorAggregator) GetErrorsByType(errorType ErrorType) []*ServiceError

func (*ErrorAggregator) GetErrorsInTimeRange

func (ea *ErrorAggregator) GetErrorsInTimeRange(start, end time.Time) []*ServiceError

func (*ErrorAggregator) GetPatterns

func (ea *ErrorAggregator) GetPatterns() []*ErrorPattern

func (*ErrorAggregator) GetStatistics

func (ea *ErrorAggregator) GetStatistics() *ErrorStatistics

func (*ErrorAggregator) GetTopPatterns

func (ea *ErrorAggregator) GetTopPatterns(n int) []*ErrorPattern

func (*ErrorAggregator) GetTrendAnalysis

func (ea *ErrorAggregator) GetTrendAnalysis(timeWindow time.Duration) *TrendAnalysis

type ErrorBuilder

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

func NewErrorBuilder

func NewErrorBuilder(service, operation string, logger *slog.Logger) *ErrorBuilder

func (*ErrorBuilder) ConfigError

func (eb *ErrorBuilder) ConfigError(ctx context.Context, setting, reason string) *ServiceError

func (*ErrorBuilder) ContextCancelledError

func (eb *ErrorBuilder) ContextCancelledError(ctx context.Context) *ServiceError

func (*ErrorBuilder) ExternalServiceError

func (eb *ErrorBuilder) ExternalServiceError(ctx context.Context, service string, cause error) *ServiceError

func (*ErrorBuilder) InternalError

func (eb *ErrorBuilder) InternalError(ctx context.Context, message string, cause error) *ServiceError

func (*ErrorBuilder) InvalidFieldError

func (eb *ErrorBuilder) InvalidFieldError(ctx context.Context, field, reason string) *ServiceError

func (*ErrorBuilder) NetworkError

func (eb *ErrorBuilder) NetworkError(ctx context.Context, code, message string, cause error) *ServiceError

func (*ErrorBuilder) NotFoundError

func (eb *ErrorBuilder) NotFoundError(ctx context.Context, resource, id string) *ServiceError

func (*ErrorBuilder) RequiredFieldError

func (eb *ErrorBuilder) RequiredFieldError(ctx context.Context, field string) *ServiceError

func (*ErrorBuilder) TimeoutError

func (eb *ErrorBuilder) TimeoutError(ctx context.Context, operation string, timeout time.Duration) *ServiceError

func (*ErrorBuilder) ValidationError

func (eb *ErrorBuilder) ValidationError(ctx context.Context, code, message string) *ServiceError

func (*ErrorBuilder) WrapError

func (eb *ErrorBuilder) WrapError(ctx context.Context, cause error, message string) *ServiceError

type ErrorCategory

type ErrorCategory string
const (
	CategoryBusiness ErrorCategory = "business"

	CategorySystem ErrorCategory = "system"

	CategorySecurity ErrorCategory = "security"

	CategoryNetwork ErrorCategory = "network"

	CategoryData ErrorCategory = "data"

	CategoryValidation ErrorCategory = "validation"

	CategoryPermission ErrorCategory = "permission"

	CategoryResource ErrorCategory = "resource"

	CategoryConfig ErrorCategory = "config"

	CategoryInternal ErrorCategory = "internal"

	CategoryCapacity ErrorCategory = "capacity"

	CategoryRateLimit ErrorCategory = "rate_limit"

	CategoryCircuitBreaker ErrorCategory = "circuit_breaker"
)

type ErrorCollector

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

func NewErrorCollector

func NewErrorCollector(maxErrors int) *ErrorCollector

func (*ErrorCollector) Clear

func (ec *ErrorCollector) Clear()

func (*ErrorCollector) Collect

func (ec *ErrorCollector) Collect(err error)

func (*ErrorCollector) CollectMultiple

func (ec *ErrorCollector) CollectMultiple(errors ...error)

func (*ErrorCollector) Count

func (ec *ErrorCollector) Count() int

func (*ErrorCollector) GetErrors

func (ec *ErrorCollector) GetErrors() []error

func (*ErrorCollector) HasErrors

func (ec *ErrorCollector) HasErrors() bool

func (*ErrorCollector) Result

func (ec *ErrorCollector) Result() error

func (*ErrorCollector) SetErrorCallback

func (ec *ErrorCollector) SetErrorCallback(callback func(error))

type ErrorConfiguration

type ErrorConfiguration struct {
	StackTraceEnabled bool `json:"stack_trace_enabled"`

	StackTraceDepth int `json:"stack_trace_depth"`

	SourceCodeEnabled bool `json:"source_code_enabled"`

	SourceCodeLines int `json:"source_code_lines"`

	RetryableTypes []ErrorType `json:"retryable_types"`

	TemporaryTypes []ErrorType `json:"temporary_types"`

	MaxCauseChainDepth int `json:"max_cause_chain_depth"`

	DefaultRetryAfter time.Duration `json:"default_retry_after"`

	CircuitBreakerEnabled bool `json:"circuit_breaker_enabled"`

	MetricsEnabled bool `json:"metrics_enabled"`
}

func DefaultErrorConfiguration

func DefaultErrorConfiguration() *ErrorConfiguration

type ErrorContextFunc

type ErrorContextFunc func(*ServiceError)

type ErrorCorrelation

type ErrorCorrelation struct {
	ID string `json:"id"`

	ErrorA string `json:"error_a"`

	ErrorB string `json:"error_b"`

	CorrelationScore float64 `json:"correlation_score"`

	TimeWindow time.Duration `json:"time_window"`

	Count int `json:"count"`

	FirstSeen time.Time `json:"first_seen"`

	LastSeen time.Time `json:"last_seen"`

	CausationType string `json:"causation_type"` // "cascade", "common_cause", "coincident"
}

type ErrorHandler

type ErrorHandler func(*ServiceError) error

type ErrorImpact

type ErrorImpact string
const (
	ImpactNone ErrorImpact = "none"

	ImpactMinimal ErrorImpact = "minimal"

	ImpactModerate ErrorImpact = "moderate"

	ImpactSevere ErrorImpact = "severe"

	ImpactCritical ErrorImpact = "critical"
)

type ErrorMetrics

type ErrorMetrics struct {
	TotalCount int64 `json:"total_count"`

	CountByType map[string]int64 `json:"count_by_type"`

	CountByCode map[string]int64 `json:"count_by_code"`

	MeanLatency float64 `json:"mean_latency"`

	P95Latency float64 `json:"p95_latency"`

	P99Latency float64 `json:"p99_latency"`

	LastOccurrence time.Time `json:"last_occurrence"`

	RatePerSecond float64 `json:"rate_per_second"`
}

type ErrorPattern

type ErrorPattern struct {
	ID string `json:"id"`

	Hash string `json:"hash"`

	Count int `json:"count"`

	FirstSeen time.Time `json:"first_seen"`

	LastSeen time.Time `json:"last_seen"`

	ErrorType ErrorType `json:"error_type"`

	Service string `json:"service"`

	Operation string `json:"operation"`

	Component string `json:"component"`

	Message string `json:"message"`

	Frequency float64 `json:"frequency"`

	TrendDirection string `json:"trend_direction"` // \"increasing\", \"decreasing\", \"stable\"

	Impact ErrorImpact `json:"impact"`

	Severity ErrorSeverity `json:"severity"`

	Examples []*ServiceError `json:"examples"`

	RelatedPatterns []string `json:"related_patterns"`

	Metadata map[string]interface{} `json:"metadata,omitempty"`
}

type ErrorPredicate

type ErrorPredicate func(*ServiceError) bool

type ErrorSeverity

type ErrorSeverity string
const (
	SeverityLow ErrorSeverity = "low"

	SeverityMedium ErrorSeverity = "medium"

	SeverityHigh ErrorSeverity = "high"

	SeverityCritical ErrorSeverity = "critical"
)

func (ErrorSeverity) String

func (es ErrorSeverity) String() string

type ErrorStatistics

type ErrorStatistics struct {
	TotalErrors int `json:"total_errors"`

	ErrorsByType map[string]int `json:"errors_by_type"`

	ErrorsByService map[string]int `json:"errors_by_service"`

	ErrorsBySeverity map[string]int `json:"errors_by_severity"`

	ErrorsByCategory map[string]int `json:"errors_by_category"`

	Patterns int `json:"patterns"`

	Correlations int `json:"correlations"`

	OldestError time.Time `json:"oldest_error"`

	NewestError time.Time `json:"newest_error"`

	ErrorsPerSecond float64 `json:"errors_per_second"`

	ErrorsPerMinute float64 `json:"errors_per_minute"`

	ErrorsPerHour float64 `json:"errors_per_hour"`
}

type ErrorTransformer

type ErrorTransformer func(*ServiceError) *ServiceError

type ErrorType

type ErrorType string
const (
	ErrorTypeValidation ErrorType = "validation"

	ErrorTypeRequired ErrorType = "required"

	ErrorTypeInvalid ErrorType = "invalid"

	ErrorTypeFormat ErrorType = "format"

	ErrorTypeRange ErrorType = "range"

	ErrorTypeNetwork ErrorType = "network"

	ErrorTypeDatabase ErrorType = "database"

	ErrorTypeExternal ErrorType = "external"

	ErrorTypeTimeout ErrorType = "timeout"

	ErrorTypeRateLimit ErrorType = "rate_limit"

	ErrorTypeQuota ErrorType = "quota"

	ErrorTypeAuth ErrorType = "authentication"

	ErrorTypeUnauthorized ErrorType = "unauthorized"

	ErrorTypeForbidden ErrorType = "forbidden"

	ErrorTypeExpired ErrorType = "expired"

	ErrorTypeBusiness ErrorType = "business"

	ErrorTypeConflict ErrorType = "conflict"

	ErrorTypeNotFound ErrorType = "not_found"

	ErrorTypeDuplicate ErrorType = "duplicate"

	ErrorTypePrecondition ErrorType = "precondition"

	ErrorTypeInternal ErrorType = "internal"

	ErrorTypeConfig ErrorType = "configuration"

	ErrorTypeResource ErrorType = "resource"

	ErrorTypeDisk ErrorType = "disk"

	ErrorTypeMemory ErrorType = "memory"

	ErrorTypeCPU ErrorType = "cpu"

	ErrorTypeORANA1 ErrorType = "oran_a1"

	ErrorTypeORANO1 ErrorType = "oran_o1"

	ErrorTypeORANO2 ErrorType = "oran_o2"

	ErrorTypeORANE2 ErrorType = "oran_e2"

	ErrorTypeRIC ErrorType = "ric"

	ErrorTypeNetworkSlice ErrorType = "network_slice"

	ErrorTypeK8sResource ErrorType = "k8s_resource"

	ErrorTypeK8sAPI ErrorType = "k8s_api"

	ErrorTypeK8sOperator ErrorType = "k8s_operator"

	ErrorTypeK8sController ErrorType = "k8s_controller"

	ErrorTypeLLM ErrorType = "llm"

	ErrorTypeRAG ErrorType = "rag"

	ErrorTypeEmbedding ErrorType = "embedding"

	ErrorTypeVector ErrorType = "vector"
)

type FallbackHandler

type FallbackHandler func(ctx context.Context, originalError error, originalData map[string]interface{}) (interface{}, error)

type FallbackManager

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

func NewFallbackManager

func NewFallbackManager(logger logr.Logger) *FallbackManager

func (*FallbackManager) GetFallback

func (fm *FallbackManager) GetFallback(component, operation string) *FallbackStrategy

func (*FallbackManager) RegisterFallback

func (fm *FallbackManager) RegisterFallback(strategy *FallbackStrategy)

type FallbackStrategy

type FallbackStrategy struct {
	Name string `json:"name"`

	Component string `json:"component"`

	Operation string `json:"operation"`

	Handler FallbackHandler `json:"-"`

	Priority int `json:"priority"`

	Timeout time.Duration `json:"timeout"`

	Conditions []string `json:"conditions"`

	Metadata map[string]interface{} `json:"metadata,omitempty"`
}

type GoContextExtractor

type GoContextExtractor struct{}

func (*GoContextExtractor) ExtractContext

func (g *GoContextExtractor) ExtractContext(source interface{}) map[string]interface{}

func (*GoContextExtractor) GetContextKeys

func (g *GoContextExtractor) GetContextKeys() []string

type HTTPContextExtractor

type HTTPContextExtractor struct{}

func (*HTTPContextExtractor) ExtractContext

func (h *HTTPContextExtractor) ExtractContext(source interface{}) map[string]interface{}

func (*HTTPContextExtractor) GetContextKeys

func (h *HTTPContextExtractor) GetContextKeys() []string

type KubernetesContextExtractor

type KubernetesContextExtractor struct{}

func (*KubernetesContextExtractor) ExtractContext

func (k *KubernetesContextExtractor) ExtractContext(source interface{}) map[string]interface{}

func (*KubernetesContextExtractor) GetContextKeys

func (k *KubernetesContextExtractor) GetContextKeys() []string

type MultiError

type MultiError struct {
	Errors []error `json:"errors"`
	// contains filtered or unexported fields
}

func NewMultiError

func NewMultiError() *MultiError

func (*MultiError) Add

func (me *MultiError) Add(err error)

func (*MultiError) AddMultiple

func (me *MultiError) AddMultiple(errors ...error)

func (*MultiError) Clear

func (me *MultiError) Clear()

func (*MultiError) Count

func (me *MultiError) Count() int

func (*MultiError) Error

func (me *MultiError) Error() string

func (*MultiError) GetErrors

func (me *MultiError) GetErrors() []error

func (*MultiError) HasErrors

func (me *MultiError) HasErrors() bool

func (*MultiError) Unwrap

func (me *MultiError) Unwrap() error

type ORANContextExtractor

type ORANContextExtractor struct{}

func (*ORANContextExtractor) ExtractContext

func (o *ORANContextExtractor) ExtractContext(source interface{}) map[string]interface{}

func (*ORANContextExtractor) GetContextKeys

func (o *ORANContextExtractor) GetContextKeys() []string

type ProcessingError

type ProcessingError struct {
	ID string `json:"id"`

	Code string `json:"code"`

	Message string `json:"message"`

	Details string `json:"details,omitempty"`

	Timestamp time.Time `json:"timestamp"`

	Type ErrorType `json:"type"`

	Category ErrorCategory `json:"category"`

	Severity ErrorSeverity `json:"severity"`

	Component string `json:"component,omitempty"`

	Operation string `json:"operation,omitempty"`

	Phase string `json:"phase,omitempty"`

	CorrelationID string `json:"correlation_id,omitempty"`

	TraceID string `json:"trace_id,omitempty"`

	SpanID string `json:"span_id,omitempty"`

	Metadata json.RawMessage `json:"metadata,omitempty"`

	Cause error `json:"-"`

	CauseChain []*ProcessingError `json:"cause_chain,omitempty"`

	StackTrace []StackFrame `json:"stack_trace,omitempty"`

	Recoverable bool `json:"recoverable"`

	RetryCount int `json:"retry_count"`

	MaxRetries int `json:"max_retries"`

	BackoffStrategy string `json:"backoff_strategy,omitempty"`

	NextRetryTime *time.Time `json:"next_retry_time,omitempty"`

	RecoveryStrategy RecoveryStrategy `json:"recovery_strategy,omitempty"`
}

func (*ProcessingError) Error

func (pe *ProcessingError) Error() string

func (*ProcessingError) Unwrap

func (pe *ProcessingError) Unwrap() error

type RateLimiter

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

func NewRateLimiter

func NewRateLimiter(name string, rate, capacity float64, logger logr.Logger) *RateLimiter

func (*RateLimiter) Allow

func (rl *RateLimiter) Allow() bool

type RecoveryPerformanceMetrics

type RecoveryPerformanceMetrics struct {
	TotalDuration time.Duration `json:"totalDuration"`

	RetryDuration time.Duration `json:"retryDuration"`

	CircuitBreakerTime time.Duration `json:"circuitBreakerTime"`

	FallbackTime time.Duration `json:"fallbackTime"`

	HealthCheckTime time.Duration `json:"healthCheckTime"`

	MemoryUsage int64 `json:"memoryUsage"`

	CPUUsage float64 `json:"cpuUsage"`

	NetworkCalls int `json:"networkCalls"`

	DatabaseCalls int `json:"databaseCalls"`

	CustomMetrics map[string]float64 `json:"customMetrics,omitempty"`
}

type RecoveryStrategy

type RecoveryStrategy string
const (
	StrategyRetry RecoveryStrategy = "retry"

	StrategyBackoff RecoveryStrategy = "backoff"

	StrategyExponential RecoveryStrategy = "exponential"

	StrategyJittered RecoveryStrategy = "jittered"

	StrategyCircuitBreaker RecoveryStrategy = "circuit_breaker"

	StrategyFallback RecoveryStrategy = "fallback"

	StrategyBulkhead RecoveryStrategy = "bulkhead"

	StrategyTimeout RecoveryStrategy = "timeout"

	StrategyRateLimit RecoveryStrategy = "rate_limit"

	StrategyDegradation RecoveryStrategy = "degradation"

	StrategyComposite RecoveryStrategy = "composite"
)

type ResourceUtilizationStats

type ResourceUtilizationStats struct {
	PeakMemoryUsage int64 `json:"peakMemoryUsage"`

	AverageMemoryUsage int64 `json:"averageMemoryUsage"`

	PeakCPUUsage float64 `json:"peakCpuUsage"`

	AverageCPUUsage float64 `json:"averageCpuUsage"`

	NetworkTraffic int64 `json:"networkTraffic"`

	DiskIO int64 `json:"diskIo"`
}

type RetryExecutor

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

func NewRetryExecutor

func NewRetryExecutor(policy *RetryPolicy, circuitBreaker *CircuitBreaker) *RetryExecutor

func (*RetryExecutor) Execute

func (re *RetryExecutor) Execute(ctx context.Context, operation RetryableOperation) error

type RetryPolicy

type RetryPolicy struct {
	MaxRetries int `json:"max_retries"`

	InitialDelay time.Duration `json:"initial_delay"`

	MaxDelay time.Duration `json:"max_delay"`

	BackoffMultiplier float64 `json:"backoff_multiplier"`

	Jitter bool `json:"jitter"`

	RetryableErrors []ErrorType `json:"retryable_errors"`

	NonRetryableErrors []ErrorType `json:"non_retryable_errors"`
}

func DefaultRetryPolicy

func DefaultRetryPolicy() *RetryPolicy

type RetryableOperation

type RetryableOperation func() error

type ServiceError

type ServiceError struct {
	Type ErrorType `json:"type"`

	Code string `json:"code"`

	Message string `json:"message"`

	Details string `json:"details,omitempty"`

	Service string `json:"service"`

	Operation string `json:"operation"`

	Component string `json:"component,omitempty"`

	Timestamp time.Time `json:"timestamp"`

	RequestID string `json:"request_id,omitempty"`

	UserID string `json:"user_id,omitempty"`

	CorrelationID string `json:"correlation_id,omitempty"`

	SessionID string `json:"session_id,omitempty"`

	Category ErrorCategory `json:"category"`

	Severity ErrorSeverity `json:"severity"`

	Impact ErrorImpact `json:"impact"`

	Retryable bool `json:"retryable"`

	Temporary bool `json:"temporary"`

	Cause error `json:"-"`

	CauseChain []*ServiceError `json:"cause_chain,omitempty"`

	StackTrace []StackFrame `json:"stack_trace,omitempty"`

	Metadata map[string]interface{} `json:"metadata,omitempty"`

	Tags []string `json:"tags,omitempty"`

	RetryCount int `json:"retry_count,omitempty"`

	RetryAfter time.Duration `json:"retry_after,omitempty"`

	CircuitBreaker string `json:"circuit_breaker,omitempty"`

	Latency time.Duration `json:"latency,omitempty"`

	Resources map[string]string `json:"resources,omitempty"`

	HTTPStatus int `json:"http_status,omitempty"`

	HTTPMethod string `json:"http_method,omitempty"`

	HTTPPath string `json:"http_path,omitempty"`

	RemoteAddr string `json:"remote_addr,omitempty"`

	UserAgent string `json:"user_agent,omitempty"`

	Hostname string `json:"hostname,omitempty"`

	PID int `json:"pid,omitempty"`

	GoroutineID string `json:"goroutine_id,omitempty"`

	DebugInfo map[string]interface{} `json:"debug_info,omitempty"`
	// contains filtered or unexported fields
}

func NewProcessingError

func NewProcessingError(message string, category ErrorCategory) *ServiceError

func (*ServiceError) AddTag

func (e *ServiceError) AddTag(tag string)

func (*ServiceError) Error

func (e *ServiceError) Error() string

func (*ServiceError) GetHTTPStatus

func (e *ServiceError) GetHTTPStatus() int

func (*ServiceError) GetStackTraceStrings

func (e *ServiceError) GetStackTraceStrings() []string

func (*ServiceError) Is

func (e *ServiceError) Is(target error) bool

func (*ServiceError) IsRetryable

func (e *ServiceError) IsRetryable() bool

func (*ServiceError) IsTemporary

func (e *ServiceError) IsTemporary() bool

func (*ServiceError) ToLogAttributes

func (e *ServiceError) ToLogAttributes() []slog.Attr

func (*ServiceError) Unwrap

func (e *ServiceError) Unwrap() error

func (*ServiceError) WithDetails

func (e *ServiceError) WithDetails(details string) *ServiceError

func (*ServiceError) WithMetadata

func (e *ServiceError) WithMetadata(key string, value interface{}) *ServiceError

func (*ServiceError) WithRequestID

func (e *ServiceError) WithRequestID(requestID string) *ServiceError

func (*ServiceError) WithUserID

func (e *ServiceError) WithUserID(userID string) *ServiceError

type StackFrame

type StackFrame struct {
	File string `json:"file"`

	Line int `json:"line"`

	Function string `json:"function"`

	Source string `json:"source,omitempty"`

	Package string `json:"package"`
}

func CaptureStackTrace

func CaptureStackTrace(opts *StackTraceOptions) []StackFrame

func CaptureStackTraceForError

func CaptureStackTraceForError(skip int) []StackFrame

func FilterStackTrace

func FilterStackTrace(frames []StackFrame, predicate func(StackFrame) bool) []StackFrame

func (StackFrame) String

func (sf StackFrame) String() string

type StackFrameFilter

type StackFrameFilter func(StackFrame) bool
var (
	SkipRuntimeFrames StackFrameFilter = func(frame StackFrame) bool {
		return !strings.HasPrefix(frame.Package, "runtime")
	}

	SkipTestingFrames StackFrameFilter = func(frame StackFrame) bool {
		return !strings.Contains(frame.Function, "testing") &&

			!strings.Contains(frame.Function, "ginkgo") &&

			!strings.Contains(frame.Function, "gomega")
	}

	OnlyApplicationFrames StackFrameFilter = func(frame StackFrame) bool {
		return !strings.Contains(frame.File, "$GOROOT/") &&

			!strings.HasPrefix(frame.Package, "runtime") &&

			!strings.HasPrefix(frame.Package, "net/") &&

			!strings.HasPrefix(frame.Package, "os/") &&

			!strings.HasPrefix(frame.Package, "io/") &&

			!strings.HasPrefix(frame.Package, "fmt") &&

			!strings.HasPrefix(frame.Package, "log")
	}
)

func CombineFilters

func CombineFilters(filters ...StackFrameFilter) StackFrameFilter

type StackTraceAnalyzer

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

func NewStackTraceAnalyzer

func NewStackTraceAnalyzer() *StackTraceAnalyzer

func (*StackTraceAnalyzer) Analyze

func (sta *StackTraceAnalyzer) Analyze(frames []StackFrame)

func (*StackTraceAnalyzer) GetFileStats

func (sta *StackTraceAnalyzer) GetFileStats() map[string]int

func (*StackTraceAnalyzer) GetFunctionStats

func (sta *StackTraceAnalyzer) GetFunctionStats() map[string]int

func (*StackTraceAnalyzer) GetPackageStats

func (sta *StackTraceAnalyzer) GetPackageStats() map[string]int

func (*StackTraceAnalyzer) Reset

func (sta *StackTraceAnalyzer) Reset()

type StackTraceOptions

type StackTraceOptions struct {
	MaxDepth int

	IncludeSource bool

	SourceContext int

	SkipFrames int

	FilterPackages []string

	ExcludePackages []string

	IncludeRuntime bool

	SimplifyPaths bool
}

func DefaultStackTraceOptions

func DefaultStackTraceOptions() *StackTraceOptions

type StrategyMetrics

type StrategyMetrics struct {
	UsageCount int64 `json:"usageCount"`

	SuccessRate float64 `json:"successRate"`

	AverageLatency time.Duration `json:"averageLatency"`

	FailureReasons map[string]int64 `json:"failureReasons"`
}

type SystemContextExtractor

type SystemContextExtractor struct{}

func (*SystemContextExtractor) ExtractContext

func (s *SystemContextExtractor) ExtractContext(source interface{}) map[string]interface{}

func (*SystemContextExtractor) GetContextKeys

func (s *SystemContextExtractor) GetContextKeys() []string

type TimeoutConfig

type TimeoutConfig struct {
	DefaultTimeout time.Duration `json:"default_timeout"`

	MaxTimeout time.Duration `json:"max_timeout"`

	MinTimeout time.Duration `json:"min_timeout"`
}

func DefaultTimeoutConfig

func DefaultTimeoutConfig() *TimeoutConfig

type TimeoutExecutor

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

func NewTimeoutExecutor

func NewTimeoutExecutor(config *TimeoutConfig) *TimeoutExecutor

func (*TimeoutExecutor) ExecuteWithTimeout

func (te *TimeoutExecutor) ExecuteWithTimeout(ctx context.Context, timeout time.Duration, operation func(context.Context) error) error

type TrendAnalysis

type TrendAnalysis struct {
	TimeWindow time.Duration `json:"time_window"`

	TotalErrors int `json:"total_errors"`

	FirstHalfErrors int `json:"first_half_errors"`

	SecondHalfErrors int `json:"second_half_errors"`

	Trend string `json:"trend"`

	TrendPercentage float64 `json:"trend_percentage"`

	AnalyzedAt time.Time `json:"analyzed_at"`
}

Jump to

Keyboard shortcuts

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