wsc

package
v0.25.3 Latest Latest
Warning

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

Go to latest
Published: Nov 1, 2026 License: Apache-2.0 Imports: 7 Imported by: 0

Documentation

Index

Constants

View Source
const (
	BrokerDriverNats   = "nats"   // NATS(core + JetStream 分级,生产选型)
	BrokerDriverMemory = "memory" // 进程内实现(契约测试与本地开发)
)

MessageBroker 消息总线驱动类型

Variables

View Source
var DefaultNonRetryableErrors = []string{
	"user_offline",
	"permission",
	"validation",
}

默认不可重试错误类型

View Source
var DefaultRetryableErrors = []string{
	"queue_full",
	"timeout",
	"conn_error",
	"channel_closed",
}

默认可重试错误类型

Functions

func DefaultLogging

func DefaultLogging() *logging.Logging

DefaultLogging 创建默认日志配置

Types

type AccessControl

type AccessControl struct {
	MaxMessageSize    int      `mapstructure:"max-message-size" yaml:"max-message-size" json:"maxMessageSize"`          // 最大消息大小(KB)
	BlockedIPs        []string `mapstructure:"blocked-ips" yaml:"blocked-ips" json:"blockedIps"`                        // 黑名单IP
	WhitelistIPs      []string `mapstructure:"whitelist-ips" yaml:"whitelist-ips" json:"whitelistIps"`                  // 白名单IP
	EnableIPWhitelist bool     `mapstructure:"enable-ip-whitelist" yaml:"enable-ip-whitelist" json:"enableIpWhitelist"` // 是否启用IP白名单
}

AccessControl 访问控制配置 连接握手期的静态校验:消息大小上限、IP 黑白名单

func DefaultAccessControl

func DefaultAccessControl() *AccessControl

DefaultAccessControl 默认访问控制配置

type AggregatorConfig

type AggregatorConfig struct {
	// DrainInterval drain 窗口节拍(默认 500ms):每窗口 Flush 一次全部群组,产出每群组一条数组帧;窗口越小端到端延迟越低、合帧率越低
	DrainInterval time.Duration `mapstructure:"drain-interval" yaml:"drain-interval" json:"drainInterval"`
	// BatchSize 单群组窗口攒批上限(默认 64 条):超限新消息直通降级单发;弹幕洪峰场景按 峰值消息速率 × DrainInterval 估算上调
	BatchSize int `mapstructure:"batch-size" yaml:"batch-size" json:"batchSize"`
	// MaxGroups 并发活跃群组数上限(默认 65536):防群组风暴(恶意/爬虫建群)内存膨胀;空群组在 Flush 换出空批时惰性删除,上限仅约束同时有在途消息的群组数
	MaxGroups int `mapstructure:"max-groups" yaml:"max-groups" json:"maxGroups"`
}

AggregatorConfig 消息聚合器配置 可聚合档群组消息(弹幕/跑马灯/滚动通知等容忍百毫秒延迟的全保留合并流)的窗口攒批参数: drain 节拍决定每连接帧率(帧率 = 1/DrainInterval),BatchSize 决定单窗口数据量上限(超限直通降级单发)

func DefaultAggregatorConfig

func DefaultAggregatorConfig() *AggregatorConfig

DefaultAggregatorConfig 默认消息聚合器配置

type BatchProcessing

type BatchProcessing struct {
	OfflineMessageBatchSize int `mapstructure:"offline-message-batch-size" yaml:"offline-message-batch-size" json:"offlineMessageBatchSize"` // 离线消息批次大小
	MessagePoolBufferSize   int `mapstructure:"message-pool-buffer-size" yaml:"message-pool-buffer-size" json:"messagePoolBufferSize"`       // 消息池缓冲区大小
	ConnectionBatchSize     int `mapstructure:"connection-batch-size" yaml:"connection-batch-size" json:"connectionBatchSize"`               // 连接记录批量操作大小
}

BatchProcessing 批处理配置

func DefaultBatchProcessing

func DefaultBatchProcessing() *BatchProcessing

DefaultBatchProcessing 默认批处理配置

func (*BatchProcessing) WithConnectionBatchSize

func (b *BatchProcessing) WithConnectionBatchSize(size int) *BatchProcessing

WithConnectionBatchSize 设置连接记录批量操作大小

func (*BatchProcessing) WithMessagePoolBufferSize

func (b *BatchProcessing) WithMessagePoolBufferSize(size int) *BatchProcessing

WithMessagePoolBufferSize 设置消息池缓冲区大小

func (*BatchProcessing) WithOfflineMessageBatchSize

func (b *BatchProcessing) WithOfflineMessageBatchSize(size int) *BatchProcessing

WithOfflineMessageBatchSize 设置离线消息批次大小

type BatcherConfig

type BatcherConfig struct {
	MessageStatus   *BatcherParams `mapstructure:"message-status" yaml:"message-status" json:"messageStatus"`       // 消息状态更新(广播万人=1次UPDATE)
	HeartbeatStats  *BatcherParams `mapstructure:"heartbeat-stats" yaml:"heartbeat-stats" json:"heartbeatStats"`    // 心跳统计批量更新
	MessageStats    *BatcherParams `mapstructure:"message-stats" yaml:"message-stats" json:"messageStats"`          // 消息统计批量更新(广播939人=1次事务)
	ObserverNotify  *BatcherParams `mapstructure:"observer-notify" yaml:"observer-notify" json:"observerNotify"`    // 观察者通知批量处理
	ClusterDispatch *BatcherParams `mapstructure:"cluster-dispatch" yaml:"cluster-dispatch" json:"clusterDispatch"` // 跨节点分发批量处理
	ErrorStats      *BatcherParams `mapstructure:"error-stats" yaml:"error-stats" json:"errorStats"`                // 连接错误统计批量更新(断连风暴=1次事务)
}

BatcherConfig 批量处理器配置 控制 Hub 内部所有 BatchProcessor 的队列大小、批次大小、flush 间隔 每个子配置对应一个 BatchProcessor,nil 或零值时使用默认值

func DefaultBatcherConfig

func DefaultBatcherConfig() *BatcherConfig

DefaultBatcherConfig 默认批量处理器配置 针对 8C16G 节点调优,可按实际负载通过 YAML/链式方法调整

func (*BatcherConfig) GetClusterDispatchParams

func (b *BatcherConfig) GetClusterDispatchParams() BatcherParams

GetClusterDispatchParams 获取跨节点分发参数(nil/零值时返回默认值)

func (*BatcherConfig) GetErrorStatsParams

func (b *BatcherConfig) GetErrorStatsParams() BatcherParams

GetErrorStatsParams 获取连接错误统计参数(nil/零值时返回默认值)

func (*BatcherConfig) GetHeartbeatStatsParams

func (b *BatcherConfig) GetHeartbeatStatsParams() BatcherParams

GetHeartbeatStatsParams 获取心跳统计参数(nil/零值时返回默认值)

func (*BatcherConfig) GetMessageStatsParams

func (b *BatcherConfig) GetMessageStatsParams() BatcherParams

GetMessageStatsParams 获取消息统计参数(nil/零值时返回默认值)

func (*BatcherConfig) GetMessageStatusParams

func (b *BatcherConfig) GetMessageStatusParams() BatcherParams

GetMessageStatusParams 获取消息状态更新参数(nil/零值时返回默认值)

func (*BatcherConfig) GetObserverNotifyParams

func (b *BatcherConfig) GetObserverNotifyParams() BatcherParams

GetObserverNotifyParams 获取观察者通知参数(nil/零值时返回默认值)

type BatcherParams

type BatcherParams struct {
	QueueSize     int           `mapstructure:"queue-size" yaml:"queue-size" json:"queueSize"`             // 队列缓冲大小(channel buffer)
	BatchSize     int           `mapstructure:"batch-size" yaml:"batch-size" json:"batchSize"`             // 每批最大条数,达到即 flush
	FlushInterval time.Duration `mapstructure:"flush-interval" yaml:"flush-interval" json:"flushInterval"` // 定时 flush 间隔
}

BatcherParams 单个批量处理器的参数(队列大小、批次大小、flush 间隔)

type BrokerConsumerParams

type BrokerConsumerParams struct {
	BatchSize     int `mapstructure:"batch-size" yaml:"batch-size" json:"batchSize"`               // 单次批量拉取上限(摊薄 RTT)
	MaxAckPending int `mapstructure:"max-ack-pending" yaml:"max-ack-pending" json:"maxAckPending"` // 在途未 ack 上限(背压闸门,超限暂停拉取)
}

BrokerConsumerParams 消费端批量拉取参数

type CapacityEstimation

type CapacityEstimation struct {
	// Nodes 预估的节点数量
	// 用于优化 nodes map 的初始容量
	// 默认值:10
	// 建议:根据实际部署规模设置
	//   - 单机部署:1
	//   - 小型集群:3-5
	//   - 中型集群:10-20
	//   - 大型集群:50+
	Nodes int `mapstructure:"nodes" yaml:"nodes" json:"nodes"`

	// Clients 预估的客户端连接数
	// 用于优化内存分配,减少 map 扩容次数
	// 默认值:1000
	// 建议:根据实际业务场景设置
	//   - 小型应用:100-500
	//   - 中型应用:1000-5000
	//   - 大型应用:10000+
	Clients int `mapstructure:"clients" yaml:"clients" json:"clients"`

	// AgentRatio 预估客服连接占比
	// 用于计算 agentClients map 的初始容量
	// 默认值:0.1(10%)
	// 说明:客服通常占总连接数的 5-15%
	AgentRatio float64 `mapstructure:"agent-ratio" yaml:"agent-ratio" json:"agentRatio"`

	// ObserverRatio 预估观察者(管理员)连接占比
	// 用于计算 observerClients map 的初始容量
	// 默认值:0.05(5%)
	// 说明:观察者通常占总连接数的 2-10%
	ObserverRatio float64 `mapstructure:"observer-ratio" yaml:"observer-ratio" json:"observerRatio"`

	// SSERatio 预估 SSE 连接占比
	// 用于计算 sseClients map 的初始容量
	// 默认值:0.1(10%)
	// 说明:SSE 连接通常占总连接数的 5-20%
	SSERatio float64 `mapstructure:"sse-ratio" yaml:"sse-ratio" json:"sseRatio"`
}

CapacityEstimation Hub 容量估算配置 用于优化 Hub 内部 map 的初始容量,减少扩容次数,提升性能

func DefaultCapacityEstimation

func DefaultCapacityEstimation() *CapacityEstimation

DefaultCapacityEstimation 返回默认的容量估算配置

func (*CapacityEstimation) CalculateCapacities

func (c *CapacityEstimation) CalculateCapacities() (int, int, int, int, int)

CalculateCapacities 计算各个 map 的初始容量 返回值:clients, userToClients, agentClients, observerClients, sseClients 的容量

func (*CapacityEstimation) GetAgentRatio

func (c *CapacityEstimation) GetAgentRatio() float64

GetAgentRatio 获取预估客服连接占比

func (*CapacityEstimation) GetClients

func (c *CapacityEstimation) GetClients() int

GetClients 获取预估客户端连接数

func (*CapacityEstimation) GetObserverRatio

func (c *CapacityEstimation) GetObserverRatio() float64

GetObserverRatio 获取预估观察者连接占比

func (*CapacityEstimation) GetSSERatio

func (c *CapacityEstimation) GetSSERatio() float64

GetSSERatio 获取预估 SSE 连接占比

type ChannelBuffers

type ChannelBuffers struct {
	BroadcastBufferMultiplier   int `mapstructure:"broadcast-buffer-multiplier" yaml:"broadcast-buffer-multiplier" json:"broadcastBufferMultiplier"`         // broadcast通道倍数
	NodeMessageBufferMultiplier int `mapstructure:"node-message-buffer-multiplier" yaml:"node-message-buffer-multiplier" json:"nodeMessageBufferMultiplier"` // nodeMessage通道倍数
}

ChannelBuffers 通道缓冲区配置

func DefaultChannelBuffers

func DefaultChannelBuffers() *ChannelBuffers

DefaultChannelBuffers 默认通道缓冲配置

func (*ChannelBuffers) WithBroadcastBufferMultiplier

func (c *ChannelBuffers) WithBroadcastBufferMultiplier(multiplier int) *ChannelBuffers

WithBroadcastBufferMultiplier 设置broadcast通道缓冲倍数

func (*ChannelBuffers) WithNodeMessageBufferMultiplier

func (c *ChannelBuffers) WithNodeMessageBufferMultiplier(multiplier int) *ChannelBuffers

WithNodeMessageBufferMultiplier 设置nodeMessage通道缓冲倍数

type ClientAttributes

type ClientAttributes struct {
	// ClientID 提取配置
	ClientIDSources []common.AttributeSource `mapstructure:"client-id-sources" yaml:"client-id-sources" json:"clientIdSources"` // ClientID 提取来源(按优先级排序)

	// UserID 提取配置
	UserIDSources []common.AttributeSource `mapstructure:"user-id-sources" yaml:"user-id-sources" json:"userIdSources"` // UserID 提取来源(按优先级排序)

	// UserType 提取配置
	UserTypeSources []common.AttributeSource `mapstructure:"user-type-sources" yaml:"user-type-sources" json:"userTypeSources"` // UserType 提取来源(按优先级排序)

	// DeviceID 提取配置
	DeviceIdSources []common.AttributeSource `mapstructure:"device-id-sources" yaml:"device-id-sources" json:"deviceIdSources"` // DeviceID 提取来源(按优先级排序)

	// AppID 提取配置(应用ID,最上层隔离维度,默认 "__default_app__")
	AppIDSources []common.AttributeSource `mapstructure:"app-id-sources" yaml:"app-id-sources" json:"appIdSources"` // AppID 提取来源(按优先级排序)

	// Namespace 提取配置(命名空间隔离,默认 "default")
	NamespaceSources []common.AttributeSource `mapstructure:"namespace-sources" yaml:"namespace-sources" json:"namespaceSources"` // Namespace 提取来源(按优先级排序)

	// GroupID 提取配置(默认群组,连接后自动加入,为空不自动加入;支持逗号分隔多群组)
	GroupIDSources []common.AttributeSource `mapstructure:"group-id-sources" yaml:"group-id-sources" json:"groupIdSources"` // GroupID 提取来源(按优先级排序)
}

ClientAttributes 客户端属性提取配置

func DefaultClientAttributes

func DefaultClientAttributes() *ClientAttributes

DefaultClientAttributes 默认客户端属性提取配置

func (*ClientAttributes) Validate

func (c *ClientAttributes) Validate() error

Validate 验证客户端属性配置

type ClientCapacity

type ClientCapacity struct {
	// 代理:高优先级,消息频率高,不能丢失
	// 预期消息频率:1000+ msg/s
	// 处理延迟:100ms
	// 缓冲消息数:100+
	Agent int `mapstructure:"agent" yaml:"agent" json:"agent"`

	// 机器人:消息频率很高,需要较大缓冲
	// 预期消息频率:100-500 msg/s
	// 处理延迟:100ms
	// 缓冲消息数:10-50
	Bot int `mapstructure:"bot" yaml:"bot" json:"bot"`

	// 普通客户:消息频率中等,中等优先级
	// 预期消息频率:20-80 msg/s
	// 处理延迟:100ms
	// 缓冲消息数:2-8
	Customer int `mapstructure:"customer" yaml:"customer" json:"customer"`

	// 观察者:消息频率低,低优先级,可以丢失
	// 预期消息频率:1-5 msg/s
	// 处理延迟:100ms
	// 缓冲消息数:0-1
	Observer int `mapstructure:"observer" yaml:"observer" json:"observer"`

	// 管理员:高优先级,类似代理
	// 预期消息频率:500+ msg/s
	// 处理延迟:100ms
	// 缓冲消息数:50+
	Admin int `mapstructure:"admin" yaml:"admin" json:"admin"`

	// VIP 客户:高优先级
	// 预期消息频率:100-200 msg/s
	// 处理延迟:100ms
	// 缓冲消息数:10-20
	VIP int `mapstructure:"vip" yaml:"vip" json:"vip"`

	// 访客:低优先级,但可能有突发流量
	// 预期消息频率:10-40 msg/s
	// 处理延迟:100ms
	// 缓冲消息数:1-4
	Visitor int `mapstructure:"visitor" yaml:"visitor" json:"visitor"`

	// 系统消息:高优先级,不能丢失
	// 预期消息频率:100+ msg/s
	// 处理延迟:100ms
	// 缓冲消息数:10+
	System int `mapstructure:"system" yaml:"system" json:"system"`

	// 默认容量:用于未知类型的客户端
	Default int `mapstructure:"default" yaml:"default" json:"default"`
}

ClientCapacity WebSocket 客户端容量配置 用于根据客户端类型优化 SendChan 缓冲区大小,节省内存并提高性能 第一阶段优化:根据客户端类型调整容量,节省 40-50% 内存

func DefaultClientCapacity

func DefaultClientCapacity() *ClientCapacity

DefaultClientCapacity 返回默认的客户端容量配置

type Compensation

type Compensation struct {
	EnableAutoCompensate bool          `mapstructure:"enable-auto-compensate" yaml:"enable-auto-compensate" json:"enableAutoCompensate"` // 是否启用自动补偿
	ScanInterval         time.Duration `mapstructure:"scan-interval" yaml:"scan-interval" json:"scanInterval"`                           // 扫描间隔
	BatchSize            int           `mapstructure:"batch-size" yaml:"batch-size" json:"batchSize"`                                    // 每批处理数量
	MaxConcurrent        int           `mapstructure:"max-concurrent" yaml:"max-concurrent" json:"maxConcurrent"`                        // 最大并发数
	DefaultMaxRetry      int           `mapstructure:"default-max-retry" yaml:"default-max-retry" json:"defaultMaxRetry"`                // 默认最大重试次数
	DefaultRetryInterval int           `mapstructure:"default-retry-interval" yaml:"default-retry-interval" json:"defaultRetryInterval"` // 默认重试间隔(秒)
	DefaultPriority      int           `mapstructure:"default-priority" yaml:"default-priority" json:"defaultPriority"`                  // 默认优先级(1-10)
	LockTimeout          time.Duration `mapstructure:"lock-timeout" yaml:"lock-timeout" json:"lockTimeout"`                              // 锁定超时时间
	CleanupDaysAgo       int           `mapstructure:"cleanup-days-ago" yaml:"cleanup-days-ago" json:"cleanupDaysAgo"`                   // 启动时清理N天前的数据(0表示不清理)
	EnableAutoCleanup    bool          `mapstructure:"enable-auto-cleanup" yaml:"enable-auto-cleanup" json:"enableAutoCleanup"`          // 是否启用自动清理
}

Compensation 补偿队列配置

func DefaultCompensation

func DefaultCompensation() *Compensation

DefaultCompensation 默认补偿队列配置

func (*Compensation) GetBatchSize

func (c *Compensation) GetBatchSize() int

GetBatchSize 获取每批处理数量

func (*Compensation) GetCleanupDaysAgo

func (c *Compensation) GetCleanupDaysAgo(globalDaysAgo int) int

GetCleanupDaysAgo 获取清理天数(优先使用自己的配置,否则使用全局配置)

func (*Compensation) GetDefaultMaxRetry

func (c *Compensation) GetDefaultMaxRetry() int

GetDefaultMaxRetry 获取默认最大重试次数

func (*Compensation) GetDefaultPriority

func (c *Compensation) GetDefaultPriority() int

GetDefaultPriority 获取默认优先级

func (*Compensation) GetDefaultRetryInterval

func (c *Compensation) GetDefaultRetryInterval() int

GetDefaultRetryInterval 获取默认重试间隔

func (*Compensation) GetEnableAutoCleanup

func (c *Compensation) GetEnableAutoCleanup(globalEnable bool) bool

GetEnableAutoCleanup 获取是否启用自动清理(优先使用自己的配置,否则使用全局配置)

func (*Compensation) GetEnableAutoCompensate

func (c *Compensation) GetEnableAutoCompensate() bool

GetEnableAutoCompensate 获取是否启用自动补偿

func (*Compensation) GetLockTimeout

func (c *Compensation) GetLockTimeout() time.Duration

GetLockTimeout 获取锁定超时时间

func (*Compensation) GetMaxConcurrent

func (c *Compensation) GetMaxConcurrent() int

GetMaxConcurrent 获取最大并发数

func (*Compensation) GetScanInterval

func (c *Compensation) GetScanInterval() time.Duration

GetScanInterval 获取扫描间隔

type ConnectionRecord

type ConnectionRecord struct {
	CleanupDaysAgo    int  `mapstructure:"cleanup-days-ago" yaml:"cleanup-days-ago" json:"cleanupDaysAgo"`          // 启动时清理N天前的数据(0表示不清理)
	EnableAutoCleanup bool `mapstructure:"enable-auto-cleanup" yaml:"enable-auto-cleanup" json:"enableAutoCleanup"` // 是否启用自动清理
}

ConnectionRecord 连接记录配置

func DefaultConnectionRecord

func DefaultConnectionRecord() *ConnectionRecord

DefaultConnectionRecord 默认连接记录配置

func (*ConnectionRecord) GetCleanupDaysAgo

func (c *ConnectionRecord) GetCleanupDaysAgo(globalDaysAgo int) int

GetCleanupDaysAgo 获取清理天数(优先使用自己的配置,否则使用全局配置)

func (*ConnectionRecord) GetEnableAutoCleanup

func (c *ConnectionRecord) GetEnableAutoCleanup(globalEnable bool) bool

GetEnableAutoCleanup 获取是否启用自动清理(优先使用自己的配置,否则使用全局配置)

type ConnectionToken

type ConnectionToken struct {
	Enabled        bool   `mapstructure:"enabled" yaml:"enabled" json:"enabled"`                          // 是否启用连接 Token(默认 false,向后兼容明文参数方式)
	TokenParamName string `mapstructure:"token-param-name" yaml:"token-param-name" json:"tokenParamName"` // Token 在请求中的参数名(默认 "token")
	TokenSource    string `mapstructure:"token-source" yaml:"token-source" json:"tokenSource"`            // Token 来源: query, header(默认 query)

	// 密钥与有效期(AES-256-GCM:密钥经 sha256(SigningKey) 派生为 32 字节)
	SigningKey  string        `mapstructure:"signing-key" yaml:"signing-key" json:"signingKey"`    // 加密密钥派生源(生产环境必须配置,任意非空字符串)
	ExpiresTime time.Duration `mapstructure:"expires-time" yaml:"expires-time" json:"expiresTime"` // Token 默认过期时间(仅 Issue 时使用,验证时由载荷加密的 exp 控制,默认 5m)

	// 容错控制
	AllowFallback bool `mapstructure:"allow-fallback" yaml:"allow-fallback" json:"allowFallback"` // Token 解析失败时是否回退到明文参数提取(默认 false,更安全)

	// 多 appid 配置(多租户隔离)
	// 兼容策略:Tokens 为空时使用上方顶层旧字段作为单 Default 配置(向后兼容)
	DefaultAppID string                         `mapstructure:"default-app-id" yaml:"default-app-id" json:"defaultAppId"` // 兜底 appid(claims.aid 为空或未知时使用)
	Tokens       map[string]*ConnectionTokenSet `mapstructure:"tokens" yaml:"tokens" json:"tokens"`                       // 按 appid 索引的多套配置
}

ConnectionToken 连接 Token 配置 启用后客户端通过单一 AES-256-GCM 加密 token 参数连接,避免 user_id/user_type/device_id 明文暴露 token 自包含(exp 随载荷加密,GCM 认证标签防篡改),无服务端会话状态

func DefaultConnectionToken

func DefaultConnectionToken() *ConnectionToken

DefaultConnectionToken 默认连接 Token 配置(默认关闭,向后兼容明文参数)

func (*ConnectionToken) GetExpiresTime

func (c *ConnectionToken) GetExpiresTime() time.Duration

GetExpiresTime 获取 Token 默认过期时间

func (*ConnectionToken) GetSigningKey

func (c *ConnectionToken) GetSigningKey() string

GetSigningKey 获取签名密钥

func (*ConnectionToken) GetTokenParamName

func (c *ConnectionToken) GetTokenParamName() string

GetTokenParamName 获取 Token 参数名

func (*ConnectionToken) GetTokenSource

func (c *ConnectionToken) GetTokenSource() string

GetTokenSource 获取 Token 来源类型

func (*ConnectionToken) IsEnabled

func (c *ConnectionToken) IsEnabled() bool

IsEnabled 检查是否启用

func (*ConnectionToken) ResolveTokens

func (c *ConnectionToken) ResolveTokens() (map[string]*ConnectionTokenSet, string, error)

ResolveTokens 解析配置为 appid→set 映射 兼容策略:

  • tokens 为空时用旧顶层字段构造单 Default set(向后兼容)
  • tokens 非空时以 tokens 为准,回填 AppID
  • 同时配置时 tokens 优先,旧字段忽略

返回 (appid→set, defaultAppID, error)

func (*ConnectionToken) ValidateMultiAppID

func (c *ConnectionToken) ValidateMultiAppID() error

ValidateMultiAppID 跨 appid 校验(NewHub 调用) 校验项:

  1. 每套 set 自身 Validate 通过
  2. DefaultAppID 非空且存在于 tokens map
  3. 跨 appid 的 (Issuer, SigningKey) 二元组不重复(防止误用同一密钥签不同 appid)
  4. TokenSource ∈ {query, header}

func (*ConnectionToken) WithAllowFallback

func (c *ConnectionToken) WithAllowFallback(allow bool) *ConnectionToken

WithAllowFallback 设置是否允许回退到明文

func (*ConnectionToken) WithEnabled

func (c *ConnectionToken) WithEnabled(enabled bool) *ConnectionToken

WithEnabled 设置启用状态

func (*ConnectionToken) WithExpiresTime

func (c *ConnectionToken) WithExpiresTime(d time.Duration) *ConnectionToken

WithExpiresTime 设置过期时间

func (*ConnectionToken) WithSigningKey

func (c *ConnectionToken) WithSigningKey(key string) *ConnectionToken

WithSigningKey 设置签名密钥

func (*ConnectionToken) WithTokenSource

func (c *ConnectionToken) WithTokenSource(source, paramName string) *ConnectionToken

WithTokenSource 设置 Token 来源和参数名

type ConnectionTokenSet

type ConnectionTokenSet struct {
	AppID          string        `mapstructure:"-" yaml:"-" json:"-"`                                            // 由 map key 回填,不参与序列化
	SigningKey     string        `mapstructure:"signing-key" yaml:"signing-key" json:"signingKey"`               // AES-256-GCM 密钥派生源(sha256 派生 32 字节,必填)
	ExpiresTime    time.Duration `mapstructure:"expires-time" yaml:"expires-time" json:"expiresTime"`            // Token 默认过期时间
	TokenSource    string        `mapstructure:"token-source" yaml:"token-source" json:"tokenSource"`            // Token 来源: query, header
	TokenParamName string        `mapstructure:"token-param-name" yaml:"token-param-name" json:"tokenParamName"` // Token 参数名
}

ConnectionTokenSet 单个 appid 的连接 Token 配置 每个 appid 拥有独立的加密密钥与有效期;鉴权时按密钥遍历解密,命中即归属该 appid 字段与 ConnectionToken 顶层旧字段一一对应,便于 ResolveTokens 包装

func (*ConnectionTokenSet) GetAppID

func (s *ConnectionTokenSet) GetAppID() string

GetAppID 获取 appid

func (*ConnectionTokenSet) GetExpiresTime

func (s *ConnectionTokenSet) GetExpiresTime() time.Duration

GetExpiresTime 获取 Token 默认过期时间

func (*ConnectionTokenSet) GetSigningKey

func (s *ConnectionTokenSet) GetSigningKey() string

GetSigningKey 获取签名密钥

func (*ConnectionTokenSet) GetTokenParamName

func (s *ConnectionTokenSet) GetTokenParamName() string

GetTokenParamName 获取 Token 参数名(默认 token)

func (*ConnectionTokenSet) GetTokenSource

func (s *ConnectionTokenSet) GetTokenSource() string

GetTokenSource 获取 Token 来源(默认 query)

func (*ConnectionTokenSet) Validate

func (s *ConnectionTokenSet) Validate() error

Validate 校验单套配置合法性

type ConnectionValidation

type ConnectionValidation struct {
	// 是否启用连接验证
	Enabled bool `mapstructure:"enabled" yaml:"enabled" json:"enabled"` // 是否启用连接验证(默认: true)

	// 必需参数配置
	RequireUserID   bool `mapstructure:"require-user-id" yaml:"require-user-id" json:"requireUserId"`       // 是否要求 UserID(默认: true)
	RequireUserType bool `mapstructure:"require-user-type" yaml:"require-user-type" json:"requireUserType"` // 是否要求 UserType(默认: true)

	// 错误消息模板
	MissingUserIDMessage   string `mapstructure:"missing-user-id-message" yaml:"missing-user-id-message" json:"missingUserIdMessage"`       // 缺少 UserID 的错误消息
	MissingUserTypeMessage string `mapstructure:"missing-user-type-message" yaml:"missing-user-type-message" json:"missingUserTypeMessage"` // 缺少 UserType 的错误消息
	MissingBothMessage     string `mapstructure:"missing-both-message" yaml:"missing-both-message" json:"missingBothMessage"`               // 同时缺少的错误消息
}

ConnectionValidation 连接验证配置

func DefaultConnectionValidation

func DefaultConnectionValidation() *ConnectionValidation

DefaultConnectionValidation 默认连接验证配置

func (*ConnectionValidation) GetMissingBothMessage

func (c *ConnectionValidation) GetMissingBothMessage() string

GetMissingBothMessage 获取同时缺少的错误消息

func (*ConnectionValidation) GetMissingUserIDMessage

func (c *ConnectionValidation) GetMissingUserIDMessage() string

GetMissingUserIDMessage 获取缺少 UserID 的错误消息

func (*ConnectionValidation) GetMissingUserTypeMessage

func (c *ConnectionValidation) GetMissingUserTypeMessage() string

GetMissingUserTypeMessage 获取缺少 UserType 的错误消息

func (*ConnectionValidation) ValidateConnection

func (c *ConnectionValidation) ValidateConnection(userID, userType string) (bool, string)

ValidateConnection 验证连接参数

type Database

type Database struct {
	Enabled          bool              `mapstructure:"enabled" yaml:"enabled" json:"enabled"`                              // 是否启用数据库持久化
	AutoMigrate      bool              `mapstructure:"auto-migrate" yaml:"auto-migrate" json:"autoMigrate"`                // 是否自动迁移表结构
	TablePrefix      string            `mapstructure:"table-prefix" yaml:"table-prefix" json:"tablePrefix"`                // 表前缀
	LogLevel         string            `mapstructure:"log-level" yaml:"log-level" json:"logLevel"`                         // 日志级别
	SlowThreshold    time.Duration     `mapstructure:"slow-threshold" yaml:"slow-threshold" json:"slowThreshold"`          // 慢查询阈值
	ConnectionRecord *ConnectionRecord `mapstructure:"connection-record" yaml:"connection-record" json:"connectionRecord"` // 连接记录配置
	MessageRecord    *MessageRecord    `mapstructure:"message-record" yaml:"message-record" json:"messageRecord"`          // 消息发送记录配置
	Compensation     *Compensation     `mapstructure:"compensation" yaml:"compensation" json:"compensation"`               // 补偿队列配置
}

Database 数据库持久化配置

func DefaultDatabase

func DefaultDatabase() *Database

DefaultDatabase 创建默认数据库配置

func (*Database) Enable

func (d *Database) Enable() *Database

Enable 启用数据库

func (*Database) WithLogging

func (d *Database) WithLogging(logLevel string, slowThreshold time.Duration) *Database

WithLogging 设置数据库日志

func (*Database) WithMigration

func (d *Database) WithMigration(autoMigrate bool, tablePrefix string) *Database

WithMigration 设置自动迁移和表前缀

type DeadLetterQueue

type DeadLetterQueue struct {
	Enabled           bool          `mapstructure:"enabled" yaml:"enabled" json:"enabled"`                                 // 是否启用死信队列
	KeyPrefix         string        `mapstructure:"key-prefix" yaml:"key-prefix" json:"keyPrefix"`                         // Redis键前缀
	MaxSize           int64         `mapstructure:"max-size" yaml:"max-size" json:"maxSize"`                               // 队列最大长度
	TTL               time.Duration `mapstructure:"ttl" yaml:"ttl" json:"ttl"`                                             // 过期时间
	MaxRetries        int           `mapstructure:"max-retries" yaml:"max-retries" json:"maxRetries"`                      // 最大重试次数(超过后移入死信队列)
	RetryDelay        time.Duration `mapstructure:"retry-delay" yaml:"retry-delay" json:"retryDelay"`                      // 重试延迟
	WarningThreshold  float64       `mapstructure:"warning-threshold" yaml:"warning-threshold" json:"warningThreshold"`    // 警告阈值(队列长度百分比,如 0.6 表示 60%)
	ErrorThreshold    float64       `mapstructure:"error-threshold" yaml:"error-threshold" json:"errorThreshold"`          // 错误阈值(队列长度百分比,如 0.8 表示 80%)
	CriticalThreshold float64       `mapstructure:"critical-threshold" yaml:"critical-threshold" json:"criticalThreshold"` // 严重阈值(队列长度百分比,如 0.95 表示 95%)
	BatchSize         int           `mapstructure:"batch-size" yaml:"batch-size" json:"batchSize"`                         // 批处理大小
	LockTimeout       time.Duration `mapstructure:"lock-timeout" yaml:"lock-timeout" json:"lockTimeout"`                   // 锁超时时间
	CleanupInterval   time.Duration `mapstructure:"cleanup-interval" yaml:"cleanup-interval" json:"cleanupInterval"`       // 清理间隔
}

DeadLetterQueue 死信队列配置

func DefaultDeadLetterQueue

func DefaultDeadLetterQueue() *DeadLetterQueue

DefaultDeadLetterQueue 默认死信队列配置

func (*DeadLetterQueue) GetBatchSize

func (d *DeadLetterQueue) GetBatchSize() int

GetBatchSize 获取批处理大小

func (*DeadLetterQueue) GetCleanupInterval

func (d *DeadLetterQueue) GetCleanupInterval() time.Duration

GetCleanupInterval 获取清理间隔

func (*DeadLetterQueue) GetCriticalThreshold

func (d *DeadLetterQueue) GetCriticalThreshold() float64

GetCriticalThreshold 获取严重阈值

func (*DeadLetterQueue) GetEnabled

func (d *DeadLetterQueue) GetEnabled() bool

GetEnabled 获取是否启用死信队列

func (*DeadLetterQueue) GetErrorThreshold

func (d *DeadLetterQueue) GetErrorThreshold() float64

GetErrorThreshold 获取错误阈值

func (*DeadLetterQueue) GetKeyPrefix

func (d *DeadLetterQueue) GetKeyPrefix() string

GetKeyPrefix 获取死信队列Redis键前缀

func (*DeadLetterQueue) GetLockTimeout

func (d *DeadLetterQueue) GetLockTimeout() time.Duration

GetLockTimeout 获取锁超时时间

func (*DeadLetterQueue) GetMaxRetries

func (d *DeadLetterQueue) GetMaxRetries() int

GetMaxRetries 获取最大重试次数

func (*DeadLetterQueue) GetMaxSize

func (d *DeadLetterQueue) GetMaxSize() int64

GetMaxSize 获取死信队列最大长度

func (*DeadLetterQueue) GetRetryDelay

func (d *DeadLetterQueue) GetRetryDelay() time.Duration

GetRetryDelay 获取重试延迟

func (*DeadLetterQueue) GetTTL

func (d *DeadLetterQueue) GetTTL() time.Duration

GetTTL 获取死信队列过期时间

func (*DeadLetterQueue) GetWarningThreshold

func (d *DeadLetterQueue) GetWarningThreshold() float64

GetWarningThreshold 获取警告阈值

type Group

type Group struct {
	KeyPrefix string `mapstructure:"key-prefix" yaml:"key-prefix" json:"keyPrefix"` // Redis键前缀
}

Group 群组配置

func DefaultGroup

func DefaultGroup() *Group

DefaultGroup 默认群组配置

func (*Group) GetKeyPrefix

func (g *Group) GetKeyPrefix() string

GetKeyPrefix 获取群组Redis键前缀

type HealthCheck

type HealthCheck struct {
	// 是否启用健康检查端点
	Enabled bool `mapstructure:"enabled" yaml:"enabled" json:"enabled"` // 是否启用健康检查(默认: true)

	// 健康检查参数名
	QueryParamName string `mapstructure:"query-param-name" yaml:"query-param-name" json:"queryParamName"` // 健康检查查询参数名(默认: health)

	// 健康检查参数值
	QueryParamValue string `mapstructure:"query-param-value" yaml:"query-param-value" json:"queryParamValue"` // 健康检查参数值(默认: true)

	// 响应消息配置
	SendResponseMessage bool `mapstructure:"send-response-message" yaml:"send-response-message" json:"sendResponseMessage"` // 是否发送响应消息(默认: true)

	// 是否立即关闭连接
	CloseImmediately bool `mapstructure:"close-immediately" yaml:"close-immediately" json:"closeImmediately"` // 是否立即关闭连接(默认: true)
}

HealthCheck 健康检查配置

func DefaultHealthCheck

func DefaultHealthCheck() *HealthCheck

DefaultHealthCheck 默认健康检查配置

func (*HealthCheck) GetQueryParamName

func (h *HealthCheck) GetQueryParamName() string

GetQueryParamName 获取健康检查参数名

func (*HealthCheck) GetQueryParamValue

func (h *HealthCheck) GetQueryParamValue() string

GetQueryParamValue 获取健康检查参数值

func (*HealthCheck) IsHealthCheckRequest

func (h *HealthCheck) IsHealthCheckRequest(queryValue string) bool

IsHealthCheckRequest 判断是否为健康检查请求

type MessageBrokerConfig

type MessageBrokerConfig struct {
	Enabled     bool                  `mapstructure:"enabled" yaml:"enabled" json:"enabled"`               // 总开关(false = 直调模式,broker 域零初始化零开销)
	Driver      string                `mapstructure:"driver" yaml:"driver" json:"driver"`                  // 驱动:nats | memory(空 = 不启用)
	TopicPrefix string                `mapstructure:"topic-prefix" yaml:"topic-prefix" json:"topicPrefix"` // topic 前缀(wsc.{app}.deliver / .broadcast / .x)
	Group       string                `mapstructure:"group" yaml:"group" json:"group"`                     // consumer group(广播语义自动按 nodeID 派生独立 group)
	ShardCount  int                   `mapstructure:"shard-count" yaml:"shard-count" json:"shardCount"`    // JetStream deliver 分片数(顺序并行度,分片内串行保序)
	Consumer    *BrokerConsumerParams `mapstructure:"consumer" yaml:"consumer" json:"consumer"`            // 消费端批量拉取参数
}

MessageBrokerConfig 消息总线配置(投递指令的发布/订阅通道编排参数)

NATS 连接配置不在本结构:宿主从 queue.Nats 模块取用,装配期传给 natsadapter.BuildConn 建连后注入适配器(NewEventBus(conn))

func DefaultMessageBrokerConfig

func DefaultMessageBrokerConfig() *MessageBrokerConfig

DefaultMessageBrokerConfig 返回默认消息总线配置(禁用态,直调模式)

func (*MessageBrokerConfig) IsEnabled

func (m *MessageBrokerConfig) IsEnabled() bool

IsEnabled 消息总线启用判定(nil 安全)

func (*MessageBrokerConfig) IsNats

func (m *MessageBrokerConfig) IsNats() bool

IsNats 是否 NATS 驱动(装配侧据此取用 Nats 连接配置)

func (*MessageBrokerConfig) ResolveConsumer

func (m *MessageBrokerConfig) ResolveConsumer() *BrokerConsumerParams

ResolveConsumer 消费参数兜底(nil 或零值 = 默认)

func (*MessageBrokerConfig) ResolveShardCount

func (m *MessageBrokerConfig) ResolveShardCount() int

ResolveShardCount 分片数兜底(0 = 默认 64)

func (*MessageBrokerConfig) WithConsumer

WithConsumer 设置消费端批量拉取参数

func (*MessageBrokerConfig) WithDriver

func (m *MessageBrokerConfig) WithDriver(driver string) *MessageBrokerConfig

WithDriver 设置驱动类型(nats | memory)

func (*MessageBrokerConfig) WithEnabled

func (m *MessageBrokerConfig) WithEnabled(enabled bool) *MessageBrokerConfig

WithEnabled 设置总开关

func (*MessageBrokerConfig) WithGroup

func (m *MessageBrokerConfig) WithGroup(group string) *MessageBrokerConfig

WithGroup 设置 consumer group

func (*MessageBrokerConfig) WithShardCount

func (m *MessageBrokerConfig) WithShardCount(count int) *MessageBrokerConfig

WithShardCount 设置 JetStream deliver 分片数

func (*MessageBrokerConfig) WithTopicPrefix

func (m *MessageBrokerConfig) WithTopicPrefix(prefix string) *MessageBrokerConfig

WithTopicPrefix 设置 topic 前缀

type MessageEncryption

type MessageEncryption struct {
	Enabled         bool   `mapstructure:"enabled" yaml:"enabled" json:"enabled"`                             // 是否启用消息数据加密
	Algorithm       string `mapstructure:"algorithm" yaml:"algorithm" json:"algorithm"`                       // 加密算法: AES-256-GCM, AES-128-GCM
	Key             string `mapstructure:"key" yaml:"key" json:"key"`                                         // 加密密钥 (32字节用于AES-256, 16字节用于AES-128)
	EnableKeyRotate bool   `mapstructure:"enable-key-rotate" yaml:"enable-key-rotate" json:"enableKeyRotate"` // 是否启用密钥轮换
	KeyRotateHours  int    `mapstructure:"key-rotate-hours" yaml:"key-rotate-hours" json:"keyRotateHours"`    // 密钥轮换间隔(小时)
	Compress        bool   `mapstructure:"compress" yaml:"compress" json:"compress"`                          // 加密前是否压缩数据
	EncryptPrefix   string `mapstructure:"encrypt-prefix" yaml:"encrypt-prefix" json:"encryptPrefix"`         // 加密数据前缀标识
	BackupKeys      int    `mapstructure:"backup-keys" yaml:"backup-keys" json:"backupKeys"`                  // 保留的备份密钥数量
}

MessageEncryption 消息加密配置

func DefaultMessageEncryption

func DefaultMessageEncryption() *MessageEncryption

DefaultMessageEncryption 默认消息加密配置

type MessageRecord

type MessageRecord struct {
	CleanupDaysAgo     int  `mapstructure:"cleanup-days-ago" yaml:"cleanup-days-ago" json:"cleanupDaysAgo"`             // 启动时清理N天前的数据(0表示不清理)
	EnableAutoCleanup  bool `mapstructure:"enable-auto-cleanup" yaml:"enable-auto-cleanup" json:"enableAutoCleanup"`    // 是否启用自动清理
	EnableCompression  bool `mapstructure:"enable-compression" yaml:"enable-compression" json:"enableCompression"`      // 是否启用压缩
	CompressionMinSize int  `mapstructure:"compression-min-size" yaml:"compression-min-size" json:"compressionMinSize"` // 最小压缩大小(字节,小于此值不压缩)
}

MessageRecord 消息发送记录配置

func DefaultMessageRecord

func DefaultMessageRecord() *MessageRecord

DefaultMessageRecord 默认消息发送记录配置

func (*MessageRecord) GetCleanupDaysAgo

func (m *MessageRecord) GetCleanupDaysAgo(globalDaysAgo int) int

GetCleanupDaysAgo 获取清理天数(优先使用自己的配置,否则使用全局配置)

func (*MessageRecord) GetCompressionMinSize

func (m *MessageRecord) GetCompressionMinSize() int

GetCompressionMinSize 获取最小压缩大小(默认1024字节=1KB)

func (*MessageRecord) GetEnableAutoCleanup

func (m *MessageRecord) GetEnableAutoCleanup(globalEnable bool) bool

GetEnableAutoCleanup 获取是否启用自动清理(优先使用自己的配置,否则使用全局配置)

func (*MessageRecord) GetEnableCompression

func (m *MessageRecord) GetEnableCompression() bool

GetEnableCompression 获取是否启用压缩

type NodeGRPC

type NodeGRPC struct {
	Enabled          bool   `mapstructure:"enabled" yaml:"enabled" json:"enabled"`                                // 是否启用 gRPC 节点通信
	Host             string `mapstructure:"host" yaml:"host" json:"host"`                                         // gRPC 监听地址
	Port             int    `mapstructure:"port" yaml:"port" json:"port"`                                         // gRPC 监听端口
	TLSEnabled       bool   `mapstructure:"tls-enabled" yaml:"tls-enabled" json:"tlsEnabled"`                     // 是否启用 TLS
	TLSCertFile      string `mapstructure:"tls-cert-file" yaml:"tls-cert-file" json:"tlsCertFile"`                // TLS 证书文件
	TLSKeyFile       string `mapstructure:"tls-key-file" yaml:"tls-key-file" json:"tlsKeyFile"`                   // TLS 私钥文件
	NodeGRPCKey      string `mapstructure:"node-grpc-key" yaml:"node-grpc-key" json:"nodeGrpcKey"`                // 节点 gRPC 地址 Hash key,默认 "wsc:nodes:grpc"
	NodeHeartbeatKey string `mapstructure:"node-heartbeat-key" yaml:"node-heartbeat-key" json:"nodeHeartbeatKey"` // 节点心跳 Hash key,默认 "wsc:nodes:heartbeat"
}

NodeGRPC 节点间 gRPC 通信配置

func DefaultNodeGRPC

func DefaultNodeGRPC() *NodeGRPC

DefaultNodeGRPC 默认 gRPC 节点通信配置

func (*NodeGRPC) GetAddress

func (n *NodeGRPC) GetAddress() string

GetAddress 获取 gRPC 监听地址

func (*NodeGRPC) GetNodeGRPCKey

func (n *NodeGRPC) GetNodeGRPCKey() string

GetNodeGRPCKey 获取节点 gRPC 地址 Hash key

func (*NodeGRPC) GetNodeHeartbeatKey

func (n *NodeGRPC) GetNodeHeartbeatKey() string

GetNodeHeartbeatKey 获取节点心跳 Hash key

func (*NodeGRPC) IsEnabled

func (n *NodeGRPC) IsEnabled() bool

IsEnabled 是否启用 gRPC 节点通信

type OfflineMessage

type OfflineMessage struct {
	KeyPrefix         string        `mapstructure:"key-prefix" yaml:"key-prefix" json:"keyPrefix"`                           // Redis键前缀
	QueueTTL          time.Duration `mapstructure:"queue-ttl" yaml:"queue-ttl" json:"queueTTL"`                              // 队列过期时间
	AutoStore         bool          `mapstructure:"auto-store" yaml:"auto-store" json:"autoStore"`                           // 是否自动存储离线消息
	AutoPush          bool          `mapstructure:"auto-push" yaml:"auto-push" json:"autoPush"`                              // 是否自动推送离线消息
	MaxCount          int           `mapstructure:"max-count" yaml:"max-count" json:"maxCount"`                              // 单次推送最大离线消息数
	CleanupDaysAgo    int           `mapstructure:"cleanup-days-ago" yaml:"cleanup-days-ago" json:"cleanupDaysAgo"`          // 启动时清理N天前的数据(0表示不清理)
	EnableAutoCleanup bool          `mapstructure:"enable-auto-cleanup" yaml:"enable-auto-cleanup" json:"enableAutoCleanup"` // 是否启用自动清理
}

OfflineMessage 离线消息配置

func DefaultOfflineMessage

func DefaultOfflineMessage() *OfflineMessage

DefaultOfflineMessage 默认离线消息配置

func (*OfflineMessage) GetAutoPush

func (o *OfflineMessage) GetAutoPush() bool

GetAutoPush 获取是否自动推送离线消息

func (*OfflineMessage) GetAutoStore

func (o *OfflineMessage) GetAutoStore() bool

GetAutoStore 获取是否自动存储离线消息

func (*OfflineMessage) GetCleanupDaysAgo

func (o *OfflineMessage) GetCleanupDaysAgo(globalDaysAgo int) int

GetCleanupDaysAgo 获取清理天数(优先使用自己的配置,否则使用全局配置)

func (*OfflineMessage) GetEnableAutoCleanup

func (o *OfflineMessage) GetEnableAutoCleanup(globalEnable bool) bool

GetEnableAutoCleanup 获取是否启用自动清理(优先使用自己的配置,否则使用全局配置)

func (*OfflineMessage) GetKeyPrefix

func (o *OfflineMessage) GetKeyPrefix() string

GetKeyPrefix 获取离线消息Redis键前缀

func (*OfflineMessage) GetMaxCount

func (o *OfflineMessage) GetMaxCount() int

GetMaxCount 获取单次推送最大离线消息数

func (*OfflineMessage) GetQueueTTL

func (o *OfflineMessage) GetQueueTTL() time.Duration

GetQueueTTL 获取离线消息队列TTL

type OnlineStatus

type OnlineStatus struct {
	KeyPrefix                string        `mapstructure:"key-prefix" yaml:"key-prefix" json:"keyPrefix"`                                                // Redis键前缀
	TTL                      time.Duration `mapstructure:"ttl" yaml:"ttl" json:"ttl"`                                                                    // 过期时间
	CleanupDaysAgo           int           `mapstructure:"cleanup-days-ago" yaml:"cleanup-days-ago" json:"cleanupDaysAgo"`                               // 启动时清理N天前的数据(0表示不清理)
	EnableAutoCleanup        bool          `mapstructure:"enable-auto-cleanup" yaml:"enable-auto-cleanup" json:"enableAutoCleanup"`                      // 是否启用自动清理
	StatusRefreshInterval    time.Duration `mapstructure:"status-refresh-interval" yaml:"status-refresh-interval" json:"statusRefreshInterval"`          // 状态刷新间隔
	HeartbeatRefreshInterval time.Duration `mapstructure:"heartbeat-refresh-interval" yaml:"heartbeat-refresh-interval" json:"heartbeatRefreshInterval"` // 心跳批量重建在线索引的 flush 间隔(processHeartbeatRedisUpdates 用,默认 2s)
	EnableCompression        bool          `mapstructure:"enable-compression" yaml:"enable-compression" json:"enableCompression"`                        // 是否启用压缩
	CompressionMinSize       int           `mapstructure:"compression-min-size" yaml:"compression-min-size" json:"compressionMinSize"`                   // 压缩阈值(字节)
}

OnlineStatus 在线状态配置

func DefaultOnlineStatus

func DefaultOnlineStatus() *OnlineStatus

DefaultOnlineStatus 默认在线状态配置

func (*OnlineStatus) GetCleanupDaysAgo

func (o *OnlineStatus) GetCleanupDaysAgo(globalDaysAgo int) int

GetCleanupDaysAgo 获取清理天数(优先使用自己的配置,否则使用全局配置)

func (*OnlineStatus) GetEnableAutoCleanup

func (o *OnlineStatus) GetEnableAutoCleanup(globalEnable bool) bool

GetEnableAutoCleanup 获取是否启用自动清理(优先使用自己的配置,否则使用全局配置)

func (*OnlineStatus) GetKeyPrefix

func (o *OnlineStatus) GetKeyPrefix() string

GetKeyPrefix 获取在线状态Redis键前缀

type Performance

type Performance struct {
	MaxConnectionsPerNode int  `mapstructure:"max-connections-per-node" yaml:"max-connections-per-node" json:"maxConnectionsPerNode"` // 每个节点最大连接数
	ReadBufferSize        int  `mapstructure:"read-buffer-size" yaml:"read-buffer-size" json:"readBufferSize"`                        // 读缓冲区大小(KB)
	WriteBufferSize       int  `mapstructure:"write-buffer-size" yaml:"write-buffer-size" json:"writeBufferSize"`                     // 写缓冲区大小(KB)
	EnableCompression     bool `mapstructure:"enable-compression" yaml:"enable-compression" json:"enableCompression"`                 // 是否启用压缩
	CompressionLevel      int  `mapstructure:"compression-level" yaml:"compression-level" json:"compressionLevel"`                    // 压缩级别(1-9)
	EnableMetrics         bool `mapstructure:"enable-metrics" yaml:"enable-metrics" json:"enableMetrics"`                             // 是否启用性能指标
	MetricsInterval       int  `mapstructure:"metrics-interval" yaml:"metrics-interval" json:"metricsInterval"`                       // 指标采集间隔(秒)
	EnableSlowLog         bool `mapstructure:"enable-slow-log" yaml:"enable-slow-log" json:"enableSlowLog"`                           // 是否启用慢日志
	SlowLogThreshold      int  `mapstructure:"slow-log-threshold" yaml:"slow-log-threshold" json:"slowLogThreshold"`                  // 慢日志阈值(毫秒)
}

Performance 性能配置

func DefaultPerformance

func DefaultPerformance() *Performance

DefaultPerformance 默认性能配置

func (*Performance) WithBufferSize

func (p *Performance) WithBufferSize(readSize, writeSize int) *Performance

WithBufferSize 设置缓冲区大小

func (*Performance) WithCompression

func (p *Performance) WithCompression(enabled bool, level int) *Performance

WithCompression 设置压缩配置

func (*Performance) WithMaxConnections

func (p *Performance) WithMaxConnections(maxConnections int) *Performance

WithMaxConnections 设置最大连接数

func (*Performance) WithMetrics

func (p *Performance) WithMetrics(enabled bool, intervalSeconds int) *Performance

WithMetrics 设置性能指标配置

func (*Performance) WithSlowLog

func (p *Performance) WithSlowLog(enabled bool, thresholdMs int) *Performance

WithSlowLog 设置慢日志配置

type PubSub

type PubSub struct {
	Enabled            bool          `mapstructure:"enabled" yaml:"enabled" json:"enabled"`                                      // 是否启用分布式消息订阅
	Namespace          string        `mapstructure:"namespace" yaml:"namespace" json:"namespace"`                                // 命名空间
	MaxRetries         int           `mapstructure:"max-retries" yaml:"max-retries" json:"maxRetries"`                           // 最大重试次数
	RetryDelay         time.Duration `mapstructure:"retry-delay" yaml:"retry-delay" json:"retryDelay"`                           // 重试延迟
	BufferSize         int           `mapstructure:"buffer-size" yaml:"buffer-size" json:"bufferSize"`                           // 消息缓冲区大小
	PingInterval       time.Duration `mapstructure:"ping-interval" yaml:"ping-interval" json:"pingInterval"`                     // 心跳间隔
	EnableCompression  bool          `mapstructure:"enable-compression" yaml:"enable-compression" json:"enableCompression"`      // 是否启用消息压缩
	CompressionMinSize int           `mapstructure:"compression-min-size" yaml:"compression-min-size" json:"compressionMinSize"` // 压缩阈值(字节)

	// Channel/Key 前缀配置(消除 hub 包中的硬编码 Redis key)
	NodeChannelPrefix string `mapstructure:"node-channel-prefix" yaml:"node-channel-prefix" json:"nodeChannelPrefix"` // 节点消息 channel 前缀,默认 "wsc:node:"
	BroadcastChannel  string `mapstructure:"broadcast-channel" yaml:"broadcast-channel" json:"broadcastChannel"`      // 广播 channel 名称,默认 "wsc:broadcast"
	ObserverChannel   string `mapstructure:"observer-channel" yaml:"observer-channel" json:"observerChannel"`         // 观察者 channel 名称,默认 "wsc:observers"
	LockKeyPrefix     string `mapstructure:"lock-key-prefix" yaml:"lock-key-prefix" json:"lockKeyPrefix"`             // 分布式锁 key 前缀,默认 "wsc:lock:"
}

PubSub 分布式消息订阅配置

func DefaultPubSub

func DefaultPubSub() *PubSub

DefaultPubSub 默认分布式消息订阅配置

func (*PubSub) GetBroadcastChannel

func (p *PubSub) GetBroadcastChannel() string

GetBroadcastChannel 获取广播 channel 名称

func (*PubSub) GetBufferSize

func (p *PubSub) GetBufferSize() int

GetBufferSize 获取消息缓冲区大小

func (*PubSub) GetCompressionMinSize

func (p *PubSub) GetCompressionMinSize() int

GetCompressionMinSize 获取压缩阈值

func (*PubSub) GetEnableCompression

func (p *PubSub) GetEnableCompression() bool

GetEnableCompression 获取是否启用消息压缩

func (*PubSub) GetEnabled

func (p *PubSub) GetEnabled() bool

GetEnabled 获取是否启用分布式消息订阅

func (*PubSub) GetLockKeyPrefix

func (p *PubSub) GetLockKeyPrefix() string

GetLockKeyPrefix 获取分布式锁 key 前缀

func (*PubSub) GetMaxRetries

func (p *PubSub) GetMaxRetries() int

GetMaxRetries 获取最大重试次数

func (*PubSub) GetNamespace

func (p *PubSub) GetNamespace() string

GetNamespace 获取命名空间

func (*PubSub) GetNodeChannelPrefix

func (p *PubSub) GetNodeChannelPrefix() string

GetNodeChannelPrefix 获取节点消息 channel 前缀

func (*PubSub) GetObserverChannel

func (p *PubSub) GetObserverChannel() string

GetObserverChannel 获取观察者 channel 名称

func (*PubSub) GetPingInterval

func (p *PubSub) GetPingInterval() time.Duration

GetPingInterval 获取心跳间隔

func (*PubSub) GetRetryDelay

func (p *PubSub) GetRetryDelay() time.Duration

GetRetryDelay 获取重试延迟

type RedisRepository

type RedisRepository struct {
	// 全局清理配置(所有子模块的默认值)
	CleanupDaysAgo    int  `mapstructure:"cleanup-days-ago" yaml:"cleanup-days-ago" json:"cleanupDaysAgo"`          // 全局:启动时清理N天前的数据(0表示不清理)
	EnableAutoCleanup bool `mapstructure:"enable-auto-cleanup" yaml:"enable-auto-cleanup" json:"enableAutoCleanup"` // 全局:是否启用自动清理

	// 子模块配置
	OnlineStatus    *OnlineStatus    `mapstructure:"online-status" yaml:"online-status" json:"onlineStatus"`            // 在线状态配置
	Stats           *Stats           `mapstructure:"stats" yaml:"stats" json:"stats"`                                   // 统计数据配置
	Workload        *Workload        `mapstructure:"workload" yaml:"workload" json:"workload"`                          // 负载管理配置
	OfflineMessage  *OfflineMessage  `mapstructure:"offline-message" yaml:"offline-message" json:"offlineMessage"`      // 离线消息配置
	PubSub          *PubSub          `mapstructure:"pubsub" yaml:"pubsub" json:"pubsub"`                                // 分布式消息订阅配置
	DeadLetterQueue *DeadLetterQueue `mapstructure:"dead-letter-queue" yaml:"dead-letter-queue" json:"deadLetterQueue"` // 死信队列配置
	Group           *Group           `mapstructure:"group" yaml:"group" json:"group"`                                   // 群组配置
}

RedisRepository Redis仓库配置

func DefaultRedisRepository

func DefaultRedisRepository() *RedisRepository

DefaultRedisRepository 默认Redis仓库配置

type ResponseHeaders

type ResponseHeaders struct {
	// 是否启用响应头
	Enabled bool `mapstructure:"enabled" yaml:"enabled" json:"enabled"` // 是否在 WebSocket 升级响应中返回客户端信息

	// 服务端分配的信息(有意义的响应头)
	ClientIDKey string `mapstructure:"client-id-key" yaml:"client-id-key" json:"clientIdKey"` // 客户端ID响应头键名(服务端生成或确认,默认: X-WSC-Client-ID)
	NodeIDKey   string `mapstructure:"node-id-key" yaml:"node-id-key" json:"nodeIdKey"`       // 节点ID响应头键名(服务端分配,默认: X-WSC-Node-ID)

	// 自定义响应头前缀
	CustomPrefix string `mapstructure:"custom-prefix" yaml:"custom-prefix" json:"customPrefix"` // 自定义响应头前缀(默认: X-WSC-)

	// 额外的自定义响应头(静态值)
	CustomHeaders map[string]string `mapstructure:"custom-headers" yaml:"custom-headers" json:"customHeaders"` // 额外的自定义响应头,如 {"X-Server-Version": "1.0.0", "X-Region": "us-west", "X-Protocol-Version": "1.0"}

	// 客户端注册成功消息配置
	SendRegisteredMessage    bool   `mapstructure:"send-registered-message" yaml:"send-registered-message" json:"sendRegisteredMessage"`          // 是否发送客户端注册成功消息(默认: true)
	RegisteredMessageContent string `mapstructure:"registered-message-content" yaml:"registered-message-content" json:"registeredMessageContent"` // 注册成功消息内容(默认: "Client registered successfully")
}

ResponseHeaders WebSocket 升级响应头配置

func DefaultResponseHeaders

func DefaultResponseHeaders() *ResponseHeaders

DefaultResponseHeaders 默认响应头配置

func (*ResponseHeaders) GetClientIDKey

func (r *ResponseHeaders) GetClientIDKey() string

GetClientIDKey 获取客户端ID响应头键名

func (*ResponseHeaders) GetNodeIDKey

func (r *ResponseHeaders) GetNodeIDKey() string

GetNodeIDKey 获取节点ID响应头键名

type RetryPolicy

type RetryPolicy struct {
	MaxRetries         int           `mapstructure:"max-retries" yaml:"max-retries" json:"maxRetries"`                           // 最大重试次数
	BaseDelay          time.Duration `mapstructure:"base-delay" yaml:"base-delay" json:"baseDelay"`                              // 基本重试延迟
	MaxDelay           time.Duration `mapstructure:"max-delay" yaml:"max-delay" json:"maxDelay"`                                 // 最大重试延迟
	BackoffFactor      float64       `mapstructure:"backoff-factor" yaml:"backoff-factor" json:"backoffFactor"`                  // 重试退避倍数
	Jitter             bool          `mapstructure:"jitter" yaml:"jitter" json:"jitter"`                                         // 是否添加随机抖动
	JitterPercent      float64       `mapstructure:"jitter-percent" yaml:"jitter-percent" json:"jitterPercent"`                  // 抖动百分比(0-1)
	RetryableErrors    []string      `mapstructure:"retryable-errors" yaml:"retryable-errors" json:"retryableErrors"`            // 可重试的错误类型
	NonRetryableErrors []string      `mapstructure:"non-retryable-errors" yaml:"non-retryable-errors" json:"nonRetryableErrors"` // 不可重试的错误类型
}

RetryPolicy 重试策略配置

func DefaultRetryPolicy

func DefaultRetryPolicy() *RetryPolicy

DefaultRetryPolicy 默认重试策略配置

func (*RetryPolicy) WithBackoff

func (r *RetryPolicy) WithBackoff(factor float64, jitter bool, jitterPercent float64) *RetryPolicy

WithBackoff 设置退避配置

func (*RetryPolicy) WithDelay

func (r *RetryPolicy) WithDelay(baseDelay, maxDelay time.Duration) *RetryPolicy

WithDelay 设置重试延迟

func (*RetryPolicy) WithMaxRetries

func (r *RetryPolicy) WithMaxRetries(maxRetries int) *RetryPolicy

WithMaxRetries 设置最大重试次数

func (*RetryPolicy) WithNonRetryableErrors

func (r *RetryPolicy) WithNonRetryableErrors(errors []string) *RetryPolicy

WithNonRetryableErrors 设置不可重试错误列表

func (*RetryPolicy) WithRetryableErrors

func (r *RetryPolicy) WithRetryableErrors(errors []string) *RetryPolicy

WithRetryableErrors 设置可重试错误列表

type RouterCacheConfig

type RouterCacheConfig struct {
	// TTL 缓存过期时间(默认 5 分钟)
	TTL time.Duration `mapstructure:"ttl" yaml:"ttl" json:"ttl"`
	// MaxLocalCacheSize 本地缓存最大条目数(默认 50000,约 5 万用户)
	MaxLocalCacheSize int `mapstructure:"max-local-cache-size" yaml:"max-local-cache-size" json:"maxLocalCacheSize"`
	// Namespace Redis 命名空间(默认 "wsc")
	Namespace string `mapstructure:"namespace" yaml:"namespace" json:"namespace"`
}

RouterCacheConfig 路由缓存配置 基于 go-cachex KVCache 实现 user→nodeIDs 三层兜底缓存

func DefaultRouterCacheConfig

func DefaultRouterCacheConfig() *RouterCacheConfig

DefaultRouterCacheConfig 默认路由缓存配置

type Security

type Security struct {
	// 访问控制配置(消息大小/用户类型白名单/IP 黑白名单)
	AccessControl *AccessControl `mapstructure:"access-control" yaml:"access-control" json:"accessControl"` // 访问控制配置

	// 消息加密配置
	MessageEncryption *MessageEncryption `mapstructure:"message-encryption" yaml:"message-encryption" json:"messageEncryption"` // 消息加密配置

	// 连接 Token 配置(将 user_id/user_type/device_id 加密为单一 token,避免明文暴露)
	ConnectionToken *ConnectionToken `mapstructure:"connection-token" yaml:"connection-token" json:"connectionToken"` // 连接 Token 配置(可选启用,默认关闭向后兼容明文参数)
}

Security 安全配置

func DefaultSecurity

func DefaultSecurity() *Security

DefaultSecurity 默认安全配置

type Stats

type Stats struct {
	KeyPrefix         string        `mapstructure:"key-prefix" yaml:"key-prefix" json:"keyPrefix"`                           // Redis键前缀
	TTL               time.Duration `mapstructure:"ttl" yaml:"ttl" json:"ttl"`                                               // 过期时间
	CleanupDaysAgo    int           `mapstructure:"cleanup-days-ago" yaml:"cleanup-days-ago" json:"cleanupDaysAgo"`          // 启动时清理N天前的数据(0表示不清理)
	EnableAutoCleanup bool          `mapstructure:"enable-auto-cleanup" yaml:"enable-auto-cleanup" json:"enableAutoCleanup"` // 是否启用自动清理
}

Stats 统计数据配置

func DefaultStats

func DefaultStats() *Stats

DefaultStats 默认统计数据配置

func (*Stats) GetCleanupDaysAgo

func (s *Stats) GetCleanupDaysAgo(globalDaysAgo int) int

GetCleanupDaysAgo 获取清理天数(优先使用自己的配置,否则使用全局配置)

func (*Stats) GetEnableAutoCleanup

func (s *Stats) GetEnableAutoCleanup(globalEnable bool) bool

GetEnableAutoCleanup 获取是否启用自动清理(优先使用自己的配置,否则使用全局配置)

func (*Stats) GetKeyPrefix

func (s *Stats) GetKeyPrefix() string

GetKeyPrefix 获取统计数据Redis键前缀

func (*Stats) GetTTL

func (s *Stats) GetTTL() time.Duration

GetTTL 获取统计数据TTL

type TemporalHasherConfig

type TemporalHasherConfig struct {
	WindowMinutes int    `mapstructure:"window-minutes" yaml:"window-minutes" json:"windowMinutes"` // 时间窗口(分钟,默认: 5)
	HashLength    int    `mapstructure:"hash-length" yaml:"hash-length" json:"hashLength"`          // 哈希长度(默认: 12)
	Separator     string `mapstructure:"separator" yaml:"separator" json:"separator"`               // 分隔符(默认: ":")
}

TemporalHasherConfig 时间窗口哈希生成器配置

func DefaultTemporalHasher

func DefaultTemporalHasher() *TemporalHasherConfig

DefaultTemporalHasher 默认时间窗口哈希生成器配置

func (*TemporalHasherConfig) GetHashLength

func (t *TemporalHasherConfig) GetHashLength() int

GetHashLength 获取哈希长度

func (*TemporalHasherConfig) GetSeparator

func (t *TemporalHasherConfig) GetSeparator() string

GetSeparator 获取分隔符

func (*TemporalHasherConfig) GetWindowMinutes

func (t *TemporalHasherConfig) GetWindowMinutes() int

GetWindowMinutes 获取时间窗口(分钟)

type TimerConfig

type TimerConfig struct {
	// TickInterval tick 间隔(默认 10ms)
	// 心跳/ACK 超时均为秒级语义,无需 1ms 精度;tick 越小空转 CPU 越高(每分片每 tick 一次锁检查)
	TickInterval time.Duration `mapstructure:"tick-interval" yaml:"tick-interval" json:"tickInterval"`
	// ShardCount 分片数(默认 16,需为 2 的幂)
	// 总 tick 频率 = ShardCount × (1s / TickInterval),默认 16 × 100 = 1600 tick/s
	ShardCount int `mapstructure:"shard-count" yaml:"shard-count" json:"shardCount"`
}

TimerConfig 心跳/ACK 超时时间轮配置(基于 go-toolbox/syncx.HashedWheelTimer) 默认值与库默认一致(10ms × 16 分片);仅极端场景(十万级以上活跃任务、亚秒级精度)需要覆盖 注意:分片是任务的存储地址(hash 定位),创建后不可动态调整,仅创建时生效

func DefaultTimerConfig

func DefaultTimerConfig() *TimerConfig

DefaultTimerConfig 默认时间轮配置(与 go-toolbox 库默认对齐)

func (*TimerConfig) GetTimerOptions

func (c *TimerConfig) GetTimerOptions() []syncx.TimerOption

GetTimerOptions 转换为 go-toolbox 时间轮选项(供 go-wsc 创建 timer 时直接使用) 非法值兜底为默认配置,保证构造出的时间轮始终可用

type WSC

type WSC struct {
	// === 基础配置 ===
	Enabled                    bool          `mapstructure:"enabled" yaml:"enabled" json:"enabled"`                                                              // 是否启用
	EnableAgent                bool          `mapstructure:"enable-agent" yaml:"enable-agent" json:"enableAgent"`                                                // 是否启用客服(Agent/Bot)连接管理(禁用时不维护 agentClients 映射,适用于纯通知场景)
	EnableObserver             bool          `mapstructure:"enable-observer" yaml:"enable-observer" json:"enableObserver"`                                       // 是否启用观察者模块(禁用时不维护 observerClients 映射且跳过观察者通知)
	EnableWorkload             bool          `mapstructure:"enable-workload" yaml:"enable-workload" json:"enableWorkload"`                                       // 是否启用客服负载管理(禁用时不初始化 workloadRepo)
	Network                    string        `mapstructure:"network" yaml:"network" json:"network"`                                                              // 网络类型: tcp, tcp4, tcp6
	NodeIP                     string        `mapstructure:"node-ip" yaml:"node-ip" json:"nodeIp"`                                                               // 节点IP
	NodePort                   int           `mapstructure:"node-port" yaml:"node-port" json:"nodePort"`                                                         // 节点端口
	Path                       string        `mapstructure:"path" yaml:"path" json:"path"`                                                                       // WebSocket服务路径
	AllowMultiLogin            bool          `mapstructure:"allow-multi-login" yaml:"allow-multi-login" json:"allowMultiLogin"`                                  // 是否允许多端登录(异地多活)
	MaxConnectionsPerUser      int           `mapstructure:"max-connections-per-user" yaml:"max-connections-per-user" json:"maxConnectionsPerUser"`              // 每个用户最大连接数(0表示不限制)
	ConnectionPolicy           string        `mapstructure:"connection-policy" yaml:"connection-policy" json:"connectionPolicy"`                                 // 连接冲突策略: kick_old(踢掉旧连接), kick_new(拒绝新连接), allow_all(允许所有)
	SendKickNotification       bool          `mapstructure:"send-kick-notification" yaml:"send-kick-notification" json:"sendKickNotification"`                   // 踢出时是否发送通知
	KickNotificationMsg        string        `mapstructure:"kick-notification-msg" yaml:"kick-notification-msg" json:"kickNotificationMsg"`                      // 踢出通知自定义消息
	HeartbeatInterval          time.Duration `mapstructure:"heartbeat-interval" yaml:"heartbeat-interval" json:"heartbeatInterval"`                              // 心跳间隔
	PerformanceMetricsInterval time.Duration `mapstructure:"performance-metrics-interval" yaml:"performance-metrics-interval" json:"performanceMetricsInterval"` // 性能监控间隔
	AckCleanupInterval         time.Duration `mapstructure:"ack-cleanup-interval" yaml:"ack-cleanup-interval" json:"ackCleanupInterval"`                         // ACK清理间隔
	ClientTimeout              time.Duration `mapstructure:"client-timeout" yaml:"client-timeout" json:"clientTimeout"`                                          // 客户端超时
	ShutdownBaseTimeout        time.Duration `mapstructure:"shutdown-base-timeout" yaml:"shutdown-base-timeout" json:"shutdownBaseTimeout"`                      // Hub关闭基础超时(5秒)
	ShutdownMaxTimeout         time.Duration `mapstructure:"shutdown-max-timeout" yaml:"shutdown-max-timeout" json:"shutdownMaxTimeout"`                         // Hub关闭最大超时(60秒)
	MessageBufferSize          int           `mapstructure:"message-buffer-size" yaml:"message-buffer-size" json:"messageBufferSize"`                            // 消息缓冲区大小
	MaxPendingQueueSize        int           `mapstructure:"max-pending-queue-size" yaml:"max-pending-queue-size" json:"maxPendingQueueSize"`                    // 最大待发送消息队列大小
	WebSocketOrigins           []string      `mapstructure:"websocket-origins" yaml:"websocket-origins" json:"websocketOrigins"`                                 // 允许的WebSocket Origin
	ReadTimeout                time.Duration `mapstructure:"read-timeout" yaml:"read-timeout" json:"readTimeout"`                                                // 读取超时
	WriteTimeout               time.Duration `mapstructure:"write-timeout" yaml:"write-timeout" json:"writeTimeout"`                                             // 写入超时
	IdleTimeout                time.Duration `mapstructure:"idle-timeout" yaml:"idle-timeout" json:"idleTimeout"`                                                // 空闲超时
	MaxMessageSize             int64         `mapstructure:"max-message-size" yaml:"max-message-size" json:"maxMessageSize"`                                     // 最大消息长度
	MinRecTime                 time.Duration `mapstructure:"min-rec-time" yaml:"min-rec-time" json:"minRecTime"`                                                 // 最小重连时间
	MaxRecTime                 time.Duration `mapstructure:"max-rec-time" yaml:"max-rec-time" json:"maxRecTime"`                                                 // 最大重连时间
	RecFactor                  float64       `mapstructure:"rec-factor" yaml:"rec-factor" json:"recFactor"`                                                      // 重连因子
	AutoReconnect              bool          `mapstructure:"auto-reconnect" yaml:"auto-reconnect" json:"autoReconnect"`                                          // 是否自动重连
	AckTimeout                 time.Duration `mapstructure:"ack-timeout" yaml:"ack-timeout" json:"ackTimeout"`                                                   // 消息确认超时
	AckMaxRetries              int           `mapstructure:"ack-max-retries" yaml:"ack-max-retries" json:"ackMaxRetries"`                                        // 消息确认最大重试次数
	EnableAck                  bool          `mapstructure:"enable-ack" yaml:"enable-ack" json:"enableAck"`                                                      // 是否启用消息确认
	MessageRecordTTL           time.Duration `mapstructure:"message-record-ttl" yaml:"message-record-ttl" json:"messageRecordTtl"`                               // 消息发送记录过期时间
	RecordCleanupInterval      time.Duration `mapstructure:"record-cleanup-interval" yaml:"record-cleanup-interval" json:"recordCleanupInterval"`                // 消息记录清理间隔

	// === SSE 配置 ===
	SSEPath          string        `mapstructure:"sse-path" yaml:"sse-path" json:"ssePath"`                              // SSE 服务路径(网关层注册的 HTTP 路由)
	SSEHeartbeat     time.Duration `mapstructure:"sse-heartbeat" yaml:"sse-heartbeat" json:"sseHeartbeat"`               // SSE心跳间隔
	SSETimeout       time.Duration `mapstructure:"sse-timeout" yaml:"sse-timeout" json:"sseTimeout"`                     // SSE超时
	SSEMessageBuffer int           `mapstructure:"sse-message-buffer" yaml:"sse-message-buffer" json:"sseMessageBuffer"` // SSE消息缓冲区大小

	// === Redis 仓库配置 ===
	RedisRepository *RedisRepository `mapstructure:"redis-repository" yaml:"redis-repository" json:"redisRepository"` // Redis仓库配置

	// === 节点间 gRPC 通信配置 ===
	NodeGRPC *NodeGRPC `mapstructure:"node-grpc" yaml:"node-grpc" json:"nodeGrpc"` // 节点间 gRPC 通信配置

	// === 性能配置 ===
	Performance *Performance `mapstructure:"performance" yaml:"performance" json:"performance"` // 性能配置

	// === 安全配置 ===
	Security *Security `mapstructure:"security" yaml:"security" json:"security"` // 安全配置

	// === 客户端属性提取配置 ===
	ClientAttributes *ClientAttributes `mapstructure:"client-attributes" yaml:"client-attributes" json:"clientAttributes"` // 客户端属性提取配置

	// === 时间窗口哈希生成器配置 ===
	TemporalHasher *TemporalHasherConfig `mapstructure:"temporal-hasher" yaml:"temporal-hasher" json:"temporalHasher"` // 时间窗口哈希生成器配置(用于生成基于时间窗口的 ClientID)

	// === WebSocket 升级响应头配置 ===
	ResponseHeaders *ResponseHeaders `mapstructure:"response-headers" yaml:"response-headers" json:"responseHeaders"` // WebSocket 升级响应头配置

	// === 健康检查配置 ===
	HealthCheck *HealthCheck `mapstructure:"health-check" yaml:"health-check" json:"healthCheck"` // 健康检查配置

	// === 连接验证配置 ===
	ConnectionValidation *ConnectionValidation `mapstructure:"connection-validation" yaml:"connection-validation" json:"connectionValidation"` // 连接验证配置

	// === 数据库配置 ===
	Database *Database `mapstructure:"database" yaml:"database" json:"database"`

	// === 日志配置 ===
	Logging *logging.Logging `mapstructure:"logging" yaml:"logging" json:"logging"` // 日志配置

	// === 批处理配置 ===
	BatchProcessing *BatchProcessing `mapstructure:"batch-processing" yaml:"batch-processing" json:"batchProcessing"` // 批处理配置

	// === 通道缓冲配置 ===
	ChannelBuffers *ChannelBuffers `mapstructure:"channel-buffers" yaml:"channel-buffers" json:"channelBuffers"` // 通道缓冲配置

	// === 重试策略配置 ===
	RetryPolicy *RetryPolicy `mapstructure:"retry-policy" yaml:"retry-policy" json:"retryPolicy"` // 重试策略配置

	// === 客户端容量配置 ===
	ClientCapacity *ClientCapacity `mapstructure:"client-capacity" yaml:"client-capacity" json:"clientCapacity"` // 客户端容量配置

	// === Hub 容量估算配置 ===
	CapacityEstimation *CapacityEstimation `mapstructure:"capacity-estimation" yaml:"capacity-estimation" json:"capacityEstimation"` // Hub 容量估算配置

	// === Hub 工作池配置 ===
	WorkerPool *WorkerPoolConfig `mapstructure:"worker-pool" yaml:"worker-pool" json:"workerPool"` // Hub 工作池配置(消息/回调/记录/分布式分池)

	// === 时间轮配置 ===
	Timer *TimerConfig `mapstructure:"timer" yaml:"timer" json:"timer"` // 心跳/ACK 超时时间轮配置(tick 精度与分片数)

	// === 路由缓存配置 ===
	RouterCache *RouterCacheConfig `mapstructure:"router-cache" yaml:"router-cache" json:"routerCache"` // 分布式路由缓存配置

	// === 批量处理器配置 ===
	Batcher *BatcherConfig `mapstructure:"batcher" yaml:"batcher" json:"batcher"` // 批量处理器配置(队列/批次/flush 间隔)

	// === 消息聚合器配置 ===
	Aggregator *AggregatorConfig `mapstructure:"aggregator" yaml:"aggregator" json:"aggregator"` // 消息聚合器配置(弹幕等可聚合档群组消息 N 条合 1 条数组帧)

	// === 消息总线配置 ===
	MessageBroker *MessageBrokerConfig `mapstructure:"message-broker" yaml:"message-broker" json:"messageBroker"` // 消息总线配置(MQ 入口与内部传输统一通道,禁用即直调模式)
}

WSC WebSocket 通信核心配置

func Default

func Default() *WSC

Default 创建默认 WSC 配置

func (*WSC) Clone

func (c *WSC) Clone() internal.Configurable

Clone 返回配置的副本

func (*WSC) Disable

func (c *WSC) Disable() *WSC

Disable 禁用 WebSocket 通信

func (*WSC) Enable

func (c *WSC) Enable() *WSC

Enable 启用 WebSocket 通信

func (*WSC) Get

func (c *WSC) Get() interface{}

Get 返回配置接口

func (*WSC) GetSSEPath

func (c *WSC) GetSSEPath() string

GetSSEPath 获取 SSE 路径,空值回退默认 "/sse"

func (*WSC) IsAgentEnabled

func (c *WSC) IsAgentEnabled() bool

IsAgentEnabled 检查是否启用客服连接管理

func (*WSC) IsEnabled

func (c *WSC) IsEnabled() bool

IsEnabled 检查是否启用

func (*WSC) IsObserverEnabled

func (c *WSC) IsObserverEnabled() bool

IsObserverEnabled 检查是否启用观察者模块

func (*WSC) IsWorkloadEnabled

func (c *WSC) IsWorkloadEnabled() bool

IsWorkloadEnabled 检查是否启用客服负载管理

func (*WSC) Set

func (c *WSC) Set(data interface{})

Set 设置配置数据

func (*WSC) Validate

func (c *WSC) Validate() error

Validate 验证配置

func (*WSC) WithAck

func (c *WSC) WithAck(d time.Duration) *WSC

WithAck 设置消息确认相关配置

func (*WSC) WithAckCleanupInterval

func (c *WSC) WithAckCleanupInterval(interval time.Duration) *WSC

WithAckCleanupInterval 设置ACK清理间隔

func (*WSC) WithAckMaxRetries

func (c *WSC) WithAckMaxRetries(maxRetries int) *WSC

WithAckMaxRetries 设置ACK最大重试次数(别名方法)

func (*WSC) WithAckRetries

func (c *WSC) WithAckRetries(maxRetries int) *WSC

WithAckRetries 设置ACK最大重试次数

func (*WSC) WithAckTimeout

func (c *WSC) WithAckTimeout(timeout time.Duration) *WSC

WithAckTimeout 设置消息确认超时时间

func (*WSC) WithAggregator

func (c *WSC) WithAggregator(aggregator *AggregatorConfig) *WSC

WithAggregator 设置消息聚合器配置

func (*WSC) WithAllowMultiLogin

func (c *WSC) WithAllowMultiLogin(allow bool) *WSC

WithAllowMultiLogin 设置是否允许多端登录

func (*WSC) WithAutoReconnect

func (c *WSC) WithAutoReconnect(enabled bool) *WSC

WithAutoReconnect 设置自动重连开关

func (*WSC) WithBatcher

func (c *WSC) WithBatcher(batcher *BatcherConfig) *WSC

WithBatcher 设置批量处理器配置

func (*WSC) WithClientAttributes

func (c *WSC) WithClientAttributes(clientAttributes *ClientAttributes) *WSC

WithClientAttributes 设置客户端属性提取配置

func (*WSC) WithClientCapacity

func (c *WSC) WithClientCapacity(capacity *ClientCapacity) *WSC

WithClientCapacity 设置客户端容量配置

func (*WSC) WithClientTimeout

func (c *WSC) WithClientTimeout(timeout time.Duration) *WSC

WithClientTimeout 设置客户端超时

func (*WSC) WithConnectionPolicy

func (c *WSC) WithConnectionPolicy(policy string) *WSC

WithConnectionPolicy 设置连接策略

func (*WSC) WithEnableAgent

func (c *WSC) WithEnableAgent(enable bool) *WSC

WithEnableAgent 设置是否启用客服连接管理

func (*WSC) WithEnableObserver

func (c *WSC) WithEnableObserver(enable bool) *WSC

WithEnableObserver 设置是否启用观察者模块

func (*WSC) WithEnableWorkload

func (c *WSC) WithEnableWorkload(enable bool) *WSC

WithEnableWorkload 设置是否启用客服负载管理

func (*WSC) WithHeartbeatInterval

func (c *WSC) WithHeartbeatInterval(interval time.Duration) *WSC

WithHeartbeatInterval 设置心跳间隔

func (*WSC) WithIdleTimeout

func (c *WSC) WithIdleTimeout(timeout time.Duration) *WSC

WithIdleTimeout 设置空闲超时

func (*WSC) WithKickNotification

func (c *WSC) WithKickNotification(send bool, msg string) *WSC

WithKickNotification 设置踢出通知配置

func (*WSC) WithLogging

func (c *WSC) WithLogging(logging *logging.Logging) *WSC

WithLogging 设置日志配置

func (*WSC) WithMaxConnectionsPerUser

func (c *WSC) WithMaxConnectionsPerUser(max int) *WSC

WithMaxConnectionsPerUser 设置每个用户最大连接数

func (*WSC) WithMaxMessageSize

func (c *WSC) WithMaxMessageSize(size int64) *WSC

WithMaxMessageSize 设置最大消息长度

func (*WSC) WithMaxPendingQueueSize

func (c *WSC) WithMaxPendingQueueSize(size int) *WSC

WithMaxPendingQueueSize 设置最大待处理队列大小

func (*WSC) WithMaxRecTime

func (c *WSC) WithMaxRecTime(d time.Duration) *WSC

WithMaxRecTime 设置最大重连时间

func (*WSC) WithMessageBufferSize

func (c *WSC) WithMessageBufferSize(size int) *WSC

WithMessageBufferSize 设置消息缓冲区大小

func (*WSC) WithMinRecTime

func (c *WSC) WithMinRecTime(d time.Duration) *WSC

WithMinRecTime 设置最小重连时间

func (*WSC) WithNetwork

func (g *WSC) WithNetwork(network string) *WSC

WithNetwork 设置网络类型

func (*WSC) WithNodeIP

func (c *WSC) WithNodeIP(ip string) *WSC

WithNodeIP 设置节点IP

func (*WSC) WithNodeInfo

func (c *WSC) WithNodeInfo(ip string, port int) *WSC

WithNodeInfo 设置节点IP和端口

func (*WSC) WithNodePort

func (c *WSC) WithNodePort(port int) *WSC

WithNodePort 设置节点端口

func (*WSC) WithPath

func (c *WSC) WithPath(path string) *WSC

WithPath 设置WebSocket路径

func (*WSC) WithPerformance

func (c *WSC) WithPerformance(performance *Performance) *WSC

WithPerformance 设置性能配置

func (*WSC) WithPerformanceMetricsInterval

func (c *WSC) WithPerformanceMetricsInterval(interval time.Duration) *WSC

WithPerformanceMetricsInterval 设置性能监控间隔

func (*WSC) WithReadTimeout

func (c *WSC) WithReadTimeout(timeout time.Duration) *WSC

WithReadTimeout 设置读超时

func (*WSC) WithRecFactor

func (c *WSC) WithRecFactor(factor float64) *WSC

WithRecFactor 设置重连因子

func (*WSC) WithRetryPolicy

func (c *WSC) WithRetryPolicy(policy *RetryPolicy) *WSC

WithRetryPolicy 设置重试策略配置

func (*WSC) WithSSEHeartbeat

func (c *WSC) WithSSEHeartbeat(interval time.Duration) *WSC

WithSSEHeartbeat 设置 SSE 心跳间隔

func (*WSC) WithSSEMessageBuffer

func (c *WSC) WithSSEMessageBuffer(size int) *WSC

WithSSEMessageBuffer 设置 SSE 消息缓冲区大小

func (*WSC) WithSSEPath

func (c *WSC) WithSSEPath(path string) *WSC

WithSSEPath 设置 SSE 路径

func (*WSC) WithSSETimeout

func (c *WSC) WithSSETimeout(timeout time.Duration) *WSC

WithSSETimeout 设置 SSE 超时

func (*WSC) WithSecurity

func (c *WSC) WithSecurity(security *Security) *WSC

WithSecurity 设置安全配置

func (*WSC) WithShutdownBaseTimeout

func (c *WSC) WithShutdownBaseTimeout(timeout time.Duration) *WSC

WithShutdownBaseTimeout 设置Hub关闭基础超时

func (*WSC) WithShutdownMaxTimeout

func (c *WSC) WithShutdownMaxTimeout(timeout time.Duration) *WSC

WithShutdownMaxTimeout 设置Hub关闭最大超时

func (*WSC) WithWebSocketOrigins

func (c *WSC) WithWebSocketOrigins(origins []string) *WSC

WithWebSocketOrigins 设置允许的 WebSocket Origin

func (*WSC) WithWriteTimeout

func (c *WSC) WithWriteTimeout(timeout time.Duration) *WSC

WithWriteTimeout 设置写超时

type WorkStatus

type WorkStatus struct {
	Enabled       bool                    `mapstructure:"enabled" yaml:"enabled" json:"enabled"`                     // 是否启用工作状态统计(Bitmap)
	Granularities []WorkStatusGranularity `mapstructure:"granularities" yaml:"granularities" json:"granularities"`   // 统计粒度: hour, day, month, year
	RetentionDays int                     `mapstructure:"retention-days" yaml:"retention-days" json:"retentionDays"` // 数据保留天数(0表示永久保留)
	AsyncRecord   bool                    `mapstructure:"async-record" yaml:"async-record" json:"asyncRecord"`       // 是否异步记录(默认true)
	RecordTimeout int                     `mapstructure:"record-timeout" yaml:"record-timeout" json:"recordTimeout"` // 记录超时时间(秒,默认2秒)
	SyncToDB      bool                    `mapstructure:"sync-to-db" yaml:"sync-to-db" json:"syncToDb"`              // 是否同步到数据库(默认true)
	SyncInterval  int                     `mapstructure:"sync-interval" yaml:"sync-interval" json:"syncInterval"`    // 同步到数据库的间隔(秒,默认300秒=5分钟)
}

WorkStatus 工作状态统计配置

func DefaultWorkStatus

func DefaultWorkStatus() *WorkStatus

DefaultWorkStatus 默认工作状态统计配置

func (*WorkStatus) GetAsyncRecord

func (ws *WorkStatus) GetAsyncRecord() bool

GetAsyncRecord 获取是否异步记录

func (*WorkStatus) GetEnabled

func (ws *WorkStatus) GetEnabled() bool

GetEnabled 获取是否启用工作状态统计

func (*WorkStatus) GetGranularities

func (ws *WorkStatus) GetGranularities() []WorkStatusGranularity

GetGranularities 获取统计粒度列表

func (*WorkStatus) GetRecordTimeout

func (ws *WorkStatus) GetRecordTimeout() int

GetRecordTimeout 获取记录超时时间

func (*WorkStatus) GetRetentionDays

func (ws *WorkStatus) GetRetentionDays() int

GetRetentionDays 获取数据保留天数

type WorkStatusGranularity

type WorkStatusGranularity string

WorkStatusGranularity 工作状态统计粒度

const (
	// GranularityHour 按小时统计
	GranularityHour WorkStatusGranularity = "hour"
	// GranularityDay 按天统计
	GranularityDay WorkStatusGranularity = "day"
	// GranularityMonth 按月统计
	GranularityMonth WorkStatusGranularity = "month"
	// GranularityYear 按年统计
	GranularityYear WorkStatusGranularity = "year"
)

func (WorkStatusGranularity) IsValid

func (g WorkStatusGranularity) IsValid() bool

IsValid 验证统计粒度是否有效

func (WorkStatusGranularity) String

func (g WorkStatusGranularity) String() string

String 返回字符串表示

type WorkerPoolConfig

type WorkerPoolConfig struct {
	// MessageWorkers 消息发送 worker 数(默认 64)
	MessageWorkers int `mapstructure:"message-workers" yaml:"message-workers" json:"messageWorkers"`
	// MessageQueueSize 消息发送队列大小(默认 4096)
	MessageQueueSize int `mapstructure:"message-queue-size" yaml:"message-queue-size" json:"messageQueueSize"`
	// CallbackWorkers 业务回调 worker 数(默认 32)
	CallbackWorkers int `mapstructure:"callback-workers" yaml:"callback-workers" json:"callbackWorkers"`
	// CallbackQueueSize 业务回调队列大小(默认 2048)
	CallbackQueueSize int `mapstructure:"callback-queue-size" yaml:"callback-queue-size" json:"callbackQueueSize"`
	// RecordWorkers 数据库记录 worker 数(默认 16)
	RecordWorkers int `mapstructure:"record-workers" yaml:"record-workers" json:"recordWorkers"`
	// RecordQueueSize 数据库记录队列大小(默认 2048)
	RecordQueueSize int `mapstructure:"record-queue-size" yaml:"record-queue-size" json:"recordQueueSize"`
	// DistributedWorkers 跨节点消息 worker 数(默认 32)
	DistributedWorkers int `mapstructure:"distributed-workers" yaml:"distributed-workers" json:"distributedWorkers"`
	// DistributedQueueSize 跨节点消息队列大小(默认 2048)
	DistributedQueueSize int `mapstructure:"distributed-queue-size" yaml:"distributed-queue-size" json:"distributedQueueSize"`
	// IdleTimeout worker 空闲自动回收超时(默认 60s)
	// 弹性池按队列积压扩容 worker,空闲超过该时长自动回收至保底数量
	IdleTimeout time.Duration `mapstructure:"idle-timeout" yaml:"idle-timeout" json:"idleTimeout"`
}

WorkerPoolConfig WorkerPool 配置 基于 go-toolbox/syncx.WorkerPool,按任务类型分池控制并发

func DefaultWorkerPoolConfig

func DefaultWorkerPoolConfig() *WorkerPoolConfig

DefaultWorkerPoolConfig 默认 WorkerPool 配置 针对 8C16G 节点调优,可按实际负载调整

type Workload

type Workload struct {
	KeyPrefix     string      `mapstructure:"key-prefix" yaml:"key-prefix" json:"keyPrefix"`             // Redis键前缀
	MaxCandidates int         `mapstructure:"max-candidates" yaml:"max-candidates" json:"maxCandidates"` // 获取负载最小客服时的最大候选数量
	WorkStatus    *WorkStatus `mapstructure:"work-status" yaml:"work-status" json:"workStatus"`          // 工作状态统计配置
}

Workload 负载管理配置

func DefaultWorkload

func DefaultWorkload() *Workload

DefaultWorkload 默认负载管理配置

func (*Workload) GetKeyPrefix

func (w *Workload) GetKeyPrefix() string

GetKeyPrefix 获取负载管理Redis键前缀

func (*Workload) GetMaxCandidates

func (w *Workload) GetMaxCandidates() int

GetMaxCandidates 获取最大候选数量

func (*Workload) GetWorkStatus

func (w *Workload) GetWorkStatus() *WorkStatus

GetWorkStatus 获取工作状态统计配置

Jump to

Keyboard shortcuts

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