transport

package
v0.0.8 Latest Latest
Warning

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

Go to latest
Published: Dec 31, 2025 License: Apache-2.0 Imports: 20 Imported by: 0

Documentation

Overview

Package transport 提供 gRPC 传输层功能

Package transport 提供 gRPC 传输层功能

Index

Constants

View Source
const (
	MetadataKeyRequestID = "x-request-id"
	MetadataKeyTraceID   = "x-trace-id"
	MetadataKeySpanID    = "x-span-id"
)

元数据 key 常量

Variables

View Source
var IdempotentMethodConfig = &MethodConfig{
	Timeout: 30 * time.Second,
	Retry: &MethodRetryConfig{
		MaxAttempts:       4,
		InitialBackoff:    100 * time.Millisecond,
		MaxBackoff:        5 * time.Second,
		BackoffMultiplier: 2.0,
		RetryableCodes:    IdempotentRetryableCodes(),
	},
}

IdempotentMethodConfig 幂等方法配置(激进重试)

View Source
var LongRunningMethodConfig = &MethodConfig{
	Timeout: 5 * time.Minute,
	Retry: &MethodRetryConfig{
		MaxAttempts:       2,
		InitialBackoff:    1 * time.Second,
		MaxBackoff:        30 * time.Second,
		BackoffMultiplier: 2.0,
		RetryableCodes: []codes.Code{
			codes.Unavailable,
		},
	},
}

LongRunningMethodConfig 长时间运行方法配置

View Source
var ReadOnlyMethodConfig = &MethodConfig{
	Timeout: 10 * time.Second,
	Retry: &MethodRetryConfig{
		MaxAttempts:       3,
		InitialBackoff:    50 * time.Millisecond,
		MaxBackoff:        2 * time.Second,
		BackoffMultiplier: 2.0,
		RetryableCodes: []codes.Code{
			codes.Unavailable,
			codes.ResourceExhausted,
			codes.Aborted,
			codes.DeadlineExceeded,
		},
	},
}

ReadOnlyMethodConfig 只读方法配置(可重试)

View Source
var WriteMethodConfig = &MethodConfig{
	Timeout: 30 * time.Second,
	Retry:   nil,
}

WriteMethodConfig 写方法配置(不重试)

Functions

func BuildDialOptions

func BuildDialOptions(cfg *config.Config, opts *config.ClientOptions) ([]grpc.DialOption, error)

BuildDialOptions 构建 gRPC DialOption(不包含拦截器,拦截器由 Dial 统一处理)

func BuildServiceConfig

func BuildServiceConfig(cfg *config.Config) string

BuildServiceConfig 构建 gRPC ServiceConfig

func BuildTLSConfig

func BuildTLSConfig(cfg *config.TLSConfig) (*tls.Config, error)

BuildTLSConfig 构建 tls.Config

func BuildTLSCredentials

func BuildTLSCredentials(tlsCfg *config.TLSConfig) (grpc.DialOption, error)

BuildTLSCredentials 构建 TLS 凭证

func DefaultRetryableCodes

func DefaultRetryableCodes() []codes.Code

DefaultRetryableCodes 默认可重试的状态码

func Dial

Dial 创建 gRPC 连接

func ErrorAnalysisInterceptor

func ErrorAnalysisInterceptor(analyzer ErrorAnalyzer) grpc.UnaryClientInterceptor

ErrorAnalysisInterceptor 错误分析拦截器(用于观测)

func ErrorHandlerInterceptor

func ErrorHandlerInterceptor(cfg *ErrorHandlerConfig) grpc.UnaryClientInterceptor

ErrorHandlerInterceptor 错误处理拦截器

func ErrorWrappingInterceptor

func ErrorWrappingInterceptor() grpc.UnaryClientInterceptor

ErrorWrappingInterceptor 错误包装拦截器,将 gRPC 错误转换为 IAMError

func ErrorWrappingStreamInterceptor

func ErrorWrappingStreamInterceptor() grpc.StreamClientInterceptor

ErrorWrappingStreamInterceptor 流式调用的错误包装拦截器

func GetRequestID

func GetRequestID(ctx context.Context) string

GetRequestID 获取请求 ID。

从 context 或 gRPC metadata 中提取 request-id。

参数:

  • ctx: 上下文

返回:

  • string: 请求 ID,如果不存在则返回空字符串

func GetTraceID

func GetTraceID(ctx context.Context) string

GetTraceID 获取追踪 ID。

从 context 或 gRPC metadata 中提取 trace-id。

参数:

  • ctx: 上下文

返回:

  • string: 追踪 ID,如果不存在则返回空字符串

func IdempotentRetryableCodes

func IdempotentRetryableCodes() []codes.Code

IdempotentRetryableCodes 幂等操作可重试的状态码(更宽松)

func MetadataInterceptor

func MetadataInterceptor(defaultMeta map[string]string) grpc.UnaryClientInterceptor

MetadataInterceptor 注入默认元数据的拦截器。

将配置中的默认 metadata 注入到每个请求中,已存在的 key 不会被覆盖。

参数:

  • defaultMeta: 默认元数据键值对

返回:

  • grpc.UnaryClientInterceptor: gRPC 客户端拦截器

func NonIdempotentRetryableCodes

func NonIdempotentRetryableCodes() []codes.Code

NonIdempotentRetryableCodes 非幂等操作可重试的状态码(更严格)

func RequestIDInterceptor

func RequestIDInterceptor() grpc.UnaryClientInterceptor

RequestIDInterceptor 自动注入 request-id 的拦截器。

如果请求上下文中没有 request-id,则自动生成 UUID。

返回:

  • grpc.UnaryClientInterceptor: gRPC 客户端拦截器

func RetryPredicateUnaryInterceptor

func RetryPredicateUnaryInterceptor(configs map[string]*RetryPredicateConfig, defaultCfg *RetryPredicateConfig) grpc.UnaryClientInterceptor

RetryPredicateUnaryInterceptor 带自定义判断的重试拦截器

func RetryUnaryInterceptor

func RetryUnaryInterceptor(configs *MethodConfigs) grpc.UnaryClientInterceptor

RetryUnaryInterceptor 按方法重试拦截器

func TimeoutInterceptor

func TimeoutInterceptor(timeout interface{}) grpc.UnaryClientInterceptor

TimeoutInterceptor 请求超时拦截器

func TimeoutUnaryInterceptor

func TimeoutUnaryInterceptor(configs *MethodConfigs) grpc.UnaryClientInterceptor

TimeoutInterceptor 按方法超时拦截器

func WithRequestID

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

WithRequestID 设置请求 ID。

将 request-id 添加到 context 和 gRPC metadata 中。

参数:

  • ctx: 上下文
  • requestID: 请求 ID

返回:

  • context.Context: 包含 request-id 的新上下文

示例:

ctx := sdk.WithRequestID(ctx, "req-123456")
resp, err := client.Auth().VerifyToken(ctx, req)

func WithTraceID

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

WithTraceID 设置追踪 ID。

将 trace-id 添加到 context 和 gRPC metadata 中,用于分布式追踪。

参数:

  • ctx: 上下文
  • traceID: 追踪 ID

返回:

  • context.Context: 包含 trace-id 的新上下文

示例:

ctx := sdk.WithTraceID(ctx, "trace-abc123")
resp, err := client.Identity().GetUser(ctx, "user-123")

Types

type DialResult

type DialResult struct {
	Conn           *grpc.ClientConn
	Metrics        *observability.PrometheusMetrics
	CircuitBreaker *observability.CircuitBreaker
}

DialResult Dial 的返回结果,包含连接和可观测性组件

func DialWithObservability

func DialWithObservability(ctx context.Context, cfg *config.Config, opts *config.ClientOptions) (*DialResult, error)

DialWithObservability 创建 gRPC 连接,并返回可观测性组件

type ErrorAnalyzer

type ErrorAnalyzer func(ctx context.Context, method string, details *sdkerrors.ErrorDetails)

ErrorAnalyzer 错误分析回调

type ErrorHandlerConfig

type ErrorHandlerConfig struct {
	// OnError 错误处理回调
	OnError func(ctx context.Context, method string, err error)

	// TransformError 错误转换函数
	TransformError func(err error) error

	// IgnoreErrors 忽略的错误匹配器
	IgnoreErrors sdkerrors.ErrorMatcher
}

ErrorHandlerConfig 错误处理拦截器配置

func DefaultErrorHandlerConfig

func DefaultErrorHandlerConfig() *ErrorHandlerConfig

DefaultErrorHandlerConfig 默认错误处理配置

func IgnoreNotFoundConfig

func IgnoreNotFoundConfig() *ErrorHandlerConfig

IgnoreNotFoundConfig 忽略 NotFound 错误的配置

func LoggingErrorHandlerConfig

func LoggingErrorHandlerConfig(logger func(method string, err error)) *ErrorHandlerConfig

LoggingErrorHandlerConfig 带日志的错误处理配置

type InterceptorChainBuilder

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

InterceptorChainBuilder 拦截器链构建器

func NewInterceptorChainBuilder

func NewInterceptorChainBuilder() *InterceptorChainBuilder

NewInterceptorChainBuilder 创建拦截器链构建器

func (*InterceptorChainBuilder) Add

Add 添加拦截器

func (*InterceptorChainBuilder) Build

Build 构建拦截器切片

func (*InterceptorChainBuilder) BuildDialOption

func (b *InterceptorChainBuilder) BuildDialOption() grpc.DialOption

BuildDialOption 构建为 DialOption

func (*InterceptorChainBuilder) WithErrorAnalysis

func (b *InterceptorChainBuilder) WithErrorAnalysis(analyzer ErrorAnalyzer) *InterceptorChainBuilder

WithErrorAnalysis 添加错误分析

func (*InterceptorChainBuilder) WithErrorHandler

WithErrorHandler 添加错误处理

func (*InterceptorChainBuilder) WithErrorWrapping

func (b *InterceptorChainBuilder) WithErrorWrapping() *InterceptorChainBuilder

WithErrorWrapping 添加错误包装

func (*InterceptorChainBuilder) WithRetry

WithRetry 添加重试拦截器

func (*InterceptorChainBuilder) WithTimeout

WithTimeout 添加超时拦截器

type MethodConfig

type MethodConfig struct {
	// Timeout 方法超时时间
	Timeout time.Duration

	// Retry 重试配置
	Retry *MethodRetryConfig
}

MethodConfig 方法级别配置

type MethodConfigs

type MethodConfigs struct {
	// 默认配置
	Default *MethodConfig

	// 按服务配置
	Services map[string]*MethodConfig

	// 按完整方法名配置(优先级最高)
	Methods map[string]*MethodConfig
}

MethodConfigs 方法配置表

func NewMethodConfigs

func NewMethodConfigs() *MethodConfigs

NewMethodConfigs 创建方法配置表

func (*MethodConfigs) GetConfig

func (mc *MethodConfigs) GetConfig(fullMethod string) *MethodConfig

GetConfig 获取方法配置

func (*MethodConfigs) SetMethodConfig

func (mc *MethodConfigs) SetMethodConfig(method string, cfg *MethodConfig)

SetMethodConfig 设置方法配置

func (*MethodConfigs) SetServiceConfig

func (mc *MethodConfigs) SetServiceConfig(service string, cfg *MethodConfig)

SetServiceConfig 设置服务配置

type MethodRetryConfig

type MethodRetryConfig struct {
	// MaxAttempts 最大重试次数
	MaxAttempts int

	// InitialBackoff 初始退避时间
	InitialBackoff time.Duration

	// MaxBackoff 最大退避时间
	MaxBackoff time.Duration

	// BackoffMultiplier 退避乘数
	BackoffMultiplier float64

	// RetryableCodes 可重试的状态码
	RetryableCodes []codes.Code
}

MethodRetryConfig 方法级别重试配置

func DefaultMethodRetryConfig

func DefaultMethodRetryConfig() *MethodRetryConfig

DefaultMethodRetryConfig 默认重试配置

type RetryPredicate

type RetryPredicate func(err error, attempt int) bool

RetryPredicate 重试判断函数

func CombinePredicates

func CombinePredicates(predicates ...RetryPredicate) RetryPredicate

CombinePredicates 组合多个重试判断

func RetryOnNetworkError

func RetryOnNetworkError() RetryPredicate

RetryOnNetworkError 网络错误时重试

func RetryOnRateLimit

func RetryOnRateLimit(maxAttempts int) RetryPredicate

RetryOnRateLimit 限流时重试(可配置最大尝试次数)

func RetryOnServerError

func RetryOnServerError() RetryPredicate

RetryOnServerError 服务端错误时重试

type RetryPredicateConfig

type RetryPredicateConfig struct {
	*MethodRetryConfig

	// Predicate 自定义重试判断(优先级高于 RetryableCodes)
	Predicate RetryPredicate

	// OnRetry 重试时回调
	OnRetry func(attempt int, err error, backoff time.Duration)
}

RetryPredicateConfig 带自定义判断的重试配置

func WithRetryPredicate

func WithRetryPredicate(cfg *MethodRetryConfig, predicate RetryPredicate) *RetryPredicateConfig

WithRetryPredicate 包装重试配置添加自定义判断

Jump to

Keyboard shortcuts

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