Documentation
¶
Overview ¶
Application scenarios: - Define the shared governance-mode and policy-provider contracts used by bootstrap and runtime assembly. - Centralize timeout, retry, breaker, and load-shedding policy lookup behind one provider-neutral interface. - Keep monolith and microservice mode selection explicit and testable.
适用场景: - 定义 bootstrap 与运行时装配共用的治理模式与策略提供器契约。 - 将 timeout、retry、breaker、load shedding 的策略读取统一收口到一个 provider-neutral 接口。 - 让 monolith 与 microservice 两种模式的选择显式、可测试。
Application scenarios: - Define one mode-aware default governance feature set shared by bootstrap, summaries, and docs. - Separate “which governance capabilities are on by default” from concrete provider-backend selection. - Keep monolith and microservice default behavior explicit and testable.
适用场景: - 定义一套按模式生效的默认治理能力集合,供 bootstrap、生效摘要和文档共用。 - 将”默认启用哪些治理能力”与”选择哪个 provider backend”解耦。 - 让 monolith 与 microservice 两种模式的默认行为显式且可测试。
Application scenarios: - Define the provider-neutral load-shedding contract used by HTTP, gRPC, and RPC client governance. - Separate "should reject now" semantics from concrete adaptive or static implementations. - Provide one shared policy/config model for overload protection.
适用场景: - 定义 HTTP、gRPC 与 RPC client 治理共用的 provider-neutral 过载保护契约。 - 将“当前是否应立即拒绝”语义与具体静态或自适应实现分离。 - 为过载保护提供统一的策略与配置模型。
Application scenarios: - Define the retry contract shared by middleware, providers, and service code. - Standardize retry execution, retryability checks, policy lookup, and delay calculation. - Provide one reusable policy/config model for HTTP, gRPC, and generic operation retries.
适用场景: - 定义中间件、provider 和 service 代码共享的重试契约。 - 统一重试执行、可重试判断、策略查找和退避延迟计算语义。 - 为 HTTP、gRPC 和通用操作重试提供复用型策略/配置模型。
Index ¶
- Constants
- func Code(err error) int
- func ErrorMessage(err error) string
- type AppError
- func BadRequest(reason ErrorReason, message string) AppError
- func Conflict(message string) AppError
- func Forbidden(message string) AppError
- func FromError(err error) AppError
- func InternalError(message string) AppError
- func NewError(code int, reason ErrorReason, message string) AppError
- func NewErrorf(code int, reason ErrorReason, format string, args ...any) AppError
- func NotFound(message string) AppError
- func RateLimited(message string) AppError
- func ServiceUnavailable(message string) AppError
- func Timeout(message string) AppError
- func Unauthorized(message string) AppError
- type BreakerPolicy
- type CORSDefaults
- type CircuitBreaker
- type CircuitBreakerConfig
- type CircuitBreakerState
- type ErrorReason
- type ErrorReport
- type ErrorReporter
- type ErrorReporterConfig
- type ErrorRequest
- type ErrorUser
- type GovernanceDefaultsTable
- type GovernanceFeatureSet
- type GovernanceMode
- type GovernancePolicyProvider
- type HTTPMode
- type LoadShedder
- type LoadSheddingConfig
- type LoadSheddingPolicy
- type LocaleDefaults
- type MiddlewareDefaults
- type RPCClientDefaults
- type RateLimiter
- type RateLimiterConfig
- type RateResourceConfig
- type Reservation
- type ResourceConfig
- type Retry
- type RetryConfig
- type RetryPolicy
- type SecurityHeaderDefaults
- type Status
- type TimeoutPolicy
Constants ¶
const ( ErrorsKey = "framework.errors" ErrorCodeOK = 200 ErrorCodeBadRequest = 400 ErrorCodeForbidden = 403 ErrorCodeNotFound = 404 ErrorCodeConflict = 409 ErrorCodeTooManyRequests = 429 ErrorCodeInternalServerError = 500 ErrorCodeGatewayTimeout = 504 )
const CircuitBreakerKey = "framework.circuit_breaker"
CircuitBreakerKey is the container key for the circuit breaker capability.
CircuitBreakerKey 是熔断器能力的容器键。
const ErrorReporterKey = "framework.error_reporter"
const LoadShedderKey = "framework.load_shedder"
LoadShedderKey is the container key for the load-shedding capability.
LoadShedderKey 是过载保护能力的容器键。
const RateLimiterKey = "framework.rate_limiter"
RateLimiterKey is the container key for the rate limiter capability.
RateLimiterKey 是限流器能力的容器键。
const RetryKey = "framework.retry"
RetryKey is the container key for the retry capability.
RetryKey 是重试能力的容器键。
Variables ¶
This section is empty.
Functions ¶
func ErrorMessage ¶
Types ¶
type AppError ¶
type AppError interface {
Error() string
Unwrap() error
Is(target error) bool
GetStatus() *Status
WithCause(cause error) AppError
WithMetadata(md map[string]string) AppError
GRPCStatus() any
}
func BadRequest ¶
func BadRequest(reason ErrorReason, message string) AppError
func InternalError ¶
func RateLimited ¶
func ServiceUnavailable ¶
func Unauthorized ¶
type BreakerPolicy ¶
type BreakerPolicy struct {
Enabled bool
Strategy string
Threshold float64
MinRequestCount int64
MaxConcurrentRequests int64
RetryTimeoutMs int64
}
BreakerPolicy describes one circuit-breaker strategy.
BreakerPolicy 描述一条熔断策略。
type CORSDefaults ¶
type CORSDefaults struct {
AllowOrigins []string `json:"allow_origins"`
MaxAgeSeconds int `json:"max_age_seconds"`
}
CORSDefaults captures CORS-specific default values (applied when CORS is explicitly enabled).
CORSDefaults 捕获 CORS 相关默认值(显式启用 CORS 时生效)。
type CircuitBreaker ¶
type CircuitBreaker interface {
Allow(ctx context.Context, resource string) error
RecordSuccess(ctx context.Context, resource string)
RecordFailure(ctx context.Context, resource string, err error)
Do(ctx context.Context, resource string, fn func() error) error
State(ctx context.Context, resource string) CircuitBreakerState
}
type CircuitBreakerConfig ¶
type CircuitBreakerConfig struct {
Enabled bool
Strategy string
ResourceConfigs map[string]ResourceConfig
DefaultConfig ResourceConfig
}
type CircuitBreakerState ¶
type CircuitBreakerState int
const ( CircuitBreakerStateClosed CircuitBreakerState = iota CircuitBreakerStateOpen CircuitBreakerStateHalfOpen )
func (CircuitBreakerState) String ¶
func (s CircuitBreakerState) String() string
type ErrorReason ¶
type ErrorReason string
const ( ErrorReasonUnknown ErrorReason = "UNKNOWN" ErrorReasonBadRequest ErrorReason = "BAD_REQUEST" ErrorReasonForbidden ErrorReason = "FORBIDDEN" ErrorReasonNotFound ErrorReason = "NOT_FOUND" ErrorReasonConflict ErrorReason = "CONFLICT" ErrorReasonRateLimited ErrorReason = "RATE_LIMITED" ErrorReasonInternal ErrorReason = "INTERNAL" ErrorReasonTimeout ErrorReason = "TIMEOUT" )
func Reason ¶
func Reason(err error) ErrorReason
type ErrorReport ¶
type ErrorReport struct {
Error error
Message string
Tags map[string]string
Context map[string]any
StackTrace string
User *ErrorUser
Request *ErrorRequest
}
ErrorReport 错误报告结构。
type ErrorReporter ¶
type ErrorReporter interface {
ReportSync(ctx context.Context, report *ErrorReport) error
ReportAsync(ctx context.Context, report *ErrorReport)
Flush()
}
ErrorReporter 错误上报接口。
type ErrorReporterConfig ¶
type ErrorReporterConfig struct {
Enabled bool
DSN string
Environment string
Release string
SampleRate float64
Tags map[string]string
}
ErrorReporterConfig 错误上报配置。
type ErrorRequest ¶
ErrorRequest 请求信息。
type GovernanceDefaultsTable ¶
type GovernanceDefaultsTable struct {
Mode GovernanceMode `json:"mode"`
FeatureDefaults map[string]bool `json:"feature_defaults"`
ProviderDefaults map[string]string `json:"provider_defaults"`
MiddlewareDefaults MiddlewareDefaults `json:"middleware_defaults"`
RPCClientDefaults RPCClientDefaults `json:"rpc_client_defaults"`
}
GovernanceDefaultsTable captures all governance default values for one mode, projected into a serializable, inspection-friendly format. This struct is populated lazily (only when view=defaults is requested) to avoid bloating the default GovernanceSummary JSON output.
GovernanceDefaultsTable 捕获某个治理模式下所有默认值, 以可序列化、可检查的格式呈现。 此结构体按需填充(仅在 view=defaults 时请求), 避免撑大默认的 GovernanceSummary JSON 输出。
type GovernanceFeatureSet ¶
type GovernanceFeatureSet struct {
RequestIdentity bool
Logging bool
Recovery bool
Timeout bool
Metrics bool
MetadataPropagation bool
Tracing bool
Selector bool
ServiceAuth bool
CircuitBreaker bool
Retry bool
LoadShedding bool
Discovery bool
}
GovernanceFeatureSet describes which governance capabilities are enabled by default.
GovernanceFeatureSet 描述某个治理模式下默认启用的治理能力集合。
func DefaultGovernanceFeatureSet ¶
func DefaultGovernanceFeatureSet(mode GovernanceMode) GovernanceFeatureSet
DefaultGovernanceFeatureSet returns the mode-aware default governance feature set.
DefaultGovernanceFeatureSet 返回按治理模式生效的默认治理能力集合。
type GovernanceMode ¶
type GovernanceMode string
GovernanceMode identifies the runtime governance mode.
GovernanceMode 标识运行时治理模式。
const ( // GovernanceModeMono keeps the runtime lightweight and local-first. // // GovernanceModeMono 表示继续走轻量、本地优先的单体主线。 GovernanceModeMono GovernanceMode = "mono" // GovernanceModeMicro enables the default microservice governance mainline. // // GovernanceModeMicro 表示启用默认微服务治理主线。 GovernanceModeMicro GovernanceMode = "micro" )
type GovernancePolicyProvider ¶
type GovernancePolicyProvider interface {
Mode() GovernanceMode
TimeoutPolicy(resource string) TimeoutPolicy
RetryPolicy(resource string) RetryPolicy
BreakerPolicy(resource string) BreakerPolicy
LoadSheddingPolicy(resource string) LoadSheddingPolicy
}
GovernancePolicyProvider exposes unified policy lookups for runtime governance.
GovernancePolicyProvider 暴露统一的运行时治理策略读取入口。
type HTTPMode ¶
type HTTPMode string
HTTPMode identifies the HTTP handling abstraction mode. This is an orthogonal dimension to GovernanceMode: HTTP mode controls handler signature style (gorp.Context vs gin.Context), while GovernanceMode controls governance capability set.
HTTPMode 标识 HTTP 处理抽象模式。 这是与 GovernanceMode 正交的维度:HTTP 模式控制 handler 签名风格 (gorp.Context vs gin.Context),GovernanceMode 控制治理能力集。
type LoadShedder ¶
type LoadShedder interface {
Allow(ctx context.Context, resource string) error
Done(ctx context.Context, resource string, err error)
}
LoadShedder decides whether a request should be shed immediately.
LoadShedder 用于判断一个请求是否应被立即丢弃。
type LoadSheddingConfig ¶
type LoadSheddingConfig struct {
Enabled bool
Strategy string
MaxConcurrency int
ResourcePolicies map[string]LoadSheddingPolicy
DefaultPolicy LoadSheddingPolicy
}
LoadSheddingConfig describes runtime overload-protection settings.
LoadSheddingConfig 描述运行时过载保护配置。
func (*LoadSheddingConfig) GetPolicy ¶
func (c *LoadSheddingConfig) GetPolicy(resource string) LoadSheddingPolicy
GetPolicy returns the resource-specific policy or falls back to the default one.
GetPolicy 返回资源级策略;若未命中,则回退到默认策略。
type LoadSheddingPolicy ¶
LoadSheddingPolicy describes one overload-protection policy.
LoadSheddingPolicy 描述一条过载保护策略。
type LocaleDefaults ¶
type LocaleDefaults struct {
Supported []string `json:"supported"`
Default string `json:"default"`
QueryKeys []string `json:"query_keys"`
}
LocaleDefaults captures locale-specific default values.
LocaleDefaults 捕获本地化相关默认值。
type MiddlewareDefaults ¶
type MiddlewareDefaults struct {
Timeout string `json:"timeout"`
BodyLimit string `json:"body_limit"`
MaxConcurrent int `json:"max_concurrent"`
EnableMetrics bool `json:"enable_metrics"`
EnableCompression bool `json:"enable_compression"`
CORS CORSDefaults `json:"cors"`
SecurityHeaders SecurityHeaderDefaults `json:"security_headers"`
Locale LocaleDefaults `json:"locale"`
}
MiddlewareDefaults captures the default middleware option values.
MiddlewareDefaults 捕获中间件的默认选项值。
type RPCClientDefaults ¶
type RPCClientDefaults struct {
Timeout string `json:"timeout"`
}
RPCClientDefaults captures the default RPC client option values.
RPCClientDefaults 捕获 RPC 客户端默认选项值。
type RateLimiter ¶
type RateLimiter interface {
Allow(ctx context.Context, resource string) error
AllowN(ctx context.Context, resource string, n int) error
Reserve(ctx context.Context, resource string) Reservation
Wait(ctx context.Context, resource string) error
WaitTimeout(ctx context.Context, resource string, timeout time.Duration) error
}
type RateLimiterConfig ¶
type RateLimiterConfig struct {
Enabled bool
Strategy string
ResourceConfigs map[string]RateResourceConfig
DefaultConfig RateResourceConfig
}
type RateResourceConfig ¶
type Reservation ¶
type ResourceConfig ¶
type Retry ¶
type Retry interface {
Do(ctx context.Context, fn func() error) error
DoForResource(ctx context.Context, resource string, fn func() error) error
DoWithResult(ctx context.Context, fn func() (any, error)) (any, error)
IsRetryable(err error) bool
}
Retry defines the retry execution contract.
Retry 定义重试执行契约。
type RetryConfig ¶
type RetryConfig struct {
Enabled bool
Strategy string
DefaultPolicy RetryPolicy
ResourcePolicies map[string]RetryPolicy
}
RetryConfig describes retry-related runtime configuration.
RetryConfig 描述重试相关运行时配置。
func (*RetryConfig) GetPolicy ¶
func (c *RetryConfig) GetPolicy(resource string) RetryPolicy
GetPolicy returns the policy for one resource, falling back to the default policy.
GetPolicy 返回指定资源的策略,未命中时回退到默认策略。
type RetryPolicy ¶
type RetryPolicy struct {
MaxAttempts int
InitialDelay time.Duration
MaxDelay time.Duration
Multiplier float64
RetryableErrors []ErrorReason
RetryableCodes []int
RetryableGRPCCodes []string
}
RetryPolicy describes one retry strategy.
RetryPolicy 描述一条重试策略。
func DefaultRetryPolicy ¶
func DefaultRetryPolicy() RetryPolicy
DefaultRetryPolicy returns the framework default retry policy.
DefaultRetryPolicy 返回框架默认重试策略。
func (*RetryPolicy) CalculateDelay ¶
func (p *RetryPolicy) CalculateDelay(attempt int, jitter float64) time.Duration
CalculateDelay calculates the delay for one retry attempt with jitter applied.
CalculateDelay 计算某次重试的退避延迟,并附加抖动。
type SecurityHeaderDefaults ¶
type SecurityHeaderDefaults struct {
XFrameOptions string `json:"x_frame_options"`
XContentTypeOptions string `json:"x_content_type_options"`
ReferrerPolicy string `json:"referrer_policy"`
}
SecurityHeaderDefaults captures security-header-specific default values.
SecurityHeaderDefaults 捕获安全头相关默认值。
type Status ¶
type Status struct {
Code int32 `json:"code"`
Reason ErrorReason `json:"reason"`
Message string `json:"message"`
Metadata map[string]string `json:"metadata,omitempty"`
}