Documentation
¶
Index ¶
- Constants
- Variables
- func ConnManagerWithConfig(cfg *ConnConfig) option.Opt[ConnManager]
- func ConnRegistryWithKeyPrefix(keyPrefix string) option.Opt[ConnRegistry]
- func ConnRegistryWithTTL(ttl time.Duration) option.Opt[ConnRegistry]
- func ConnWithAutoClose(autoClose bool) option.Opt[Conn]
- func ConnWithCompression(state *compression.State) option.Opt[Conn]
- func ConnWithEstablishedReadTimeout(timeout time.Duration) option.Opt[Conn]
- func ConnWithMaxFrameBytes(maxFrameBytes int64) option.Opt[Conn]
- func ConnWithRateLimit(rate int) option.Opt[Conn]
- func ConnWithReadBuffer(receiveBufferSize int) option.Opt[Conn]
- func ConnWithReadTimeout(readTimeout time.Duration) option.Opt[Conn]
- func ConnWithRetry(initRetryInterval, maxRetryInterval time.Duration, maxRetryCount int32) option.Opt[Conn]
- func ConnWithWriteBuffer(sendBufferSize int) option.Opt[Conn]
- func ConnWithWriteTimeout(writeTimeout time.Duration) option.Opt[Conn]
- type Conn
- func (c *Conn) Authenticated() <-chan struct{}
- func (c *Conn) BindSession(sess session.Session)
- func (c *Conn) Close() error
- func (c *Conn) Closed() <-chan struct{}
- func (c *Conn) ID() string
- func (c *Conn) MarkAuthenticated()
- func (c *Conn) Receive() <-chan []byte
- func (c *Conn) Send(ctx context.Context, payload []byte) error
- func (c *Conn) Session() session.Session
- func (c *Conn) TryCloseIfIdle(idleTimeout time.Duration) bool
- func (c *Conn) TryCloseIfSlow(minOverflow int32) bool
- func (c *Conn) UpdateActivityTime()
- type ConnConfig
- type ConnManager
- func (m *ConnManager) BindUser(conn synp.Conn, user session.User) error
- func (m *ConnManager) ConnCount() int64
- func (m *ConnManager) FindConn(user session.User) (synp.Conn, bool)
- func (m *ConnManager) FindUserConn(user session.User) ([]synp.Conn, bool)
- func (m *ConnManager) NewConn(ctx context.Context, netConn net.Conn, sess session.Session, ...) (synp.Conn, error)
- func (m *ConnManager) RangeConns(fn func(synp.Conn) bool)
- func (m *ConnManager) RangeConnsShard(shard, shards uint64, fn func(synp.Conn) bool)
- func (m *ConnManager) RemoveConn(user session.User) bool
- func (m *ConnManager) RemoveConnByID(connID string) bool
- func (m *ConnManager) RemoveUserConn(user session.User) bool
- func (m *ConnManager) UserCount() int64
- type ConnRegistry
- func (r *ConnRegistry) FindNodes(ctx context.Context, bid, uid uint64) ([]synp.ConnNode, error)
- func (r *ConnRegistry) Heartbeat(ctx context.Context, user session.User, connID string) error
- func (r *ConnRegistry) Register(ctx context.Context, user session.User, connID string) error
- func (r *ConnRegistry) Unregister(ctx context.Context, user session.User, connID string) error
- type DeviceConns
- type ReadWriteConn
- func (c *ReadWriteConn) Authenticated() <-chan struct{}
- func (c *ReadWriteConn) BindSession(sess session.Session)
- func (c *ReadWriteConn) Close() error
- func (c *ReadWriteConn) Closed() <-chan struct{}
- func (c *ReadWriteConn) ID() string
- func (c *ReadWriteConn) MarkAuthenticated()
- func (c *ReadWriteConn) Receive() <-chan []byte
- func (c *ReadWriteConn) Send(ctx context.Context, payload []byte) error
- func (c *ReadWriteConn) Session() session.Session
- func (c *ReadWriteConn) TryCloseIfIdle(idleTimeout time.Duration) bool
- func (c *ReadWriteConn) TryCloseIfSlow(_ int32) bool
- func (c *ReadWriteConn) UpdateActivityTime()
- type WriteFirstConn
- func (c *WriteFirstConn) Authenticated() <-chan struct{}
- func (c *WriteFirstConn) BindSession(sess session.Session)
- func (c *WriteFirstConn) Close() error
- func (c *WriteFirstConn) Closed() <-chan struct{}
- func (c *WriteFirstConn) ID() string
- func (c *WriteFirstConn) MarkAuthenticated()
- func (c *WriteFirstConn) Receive() <-chan []byte
- func (c *WriteFirstConn) Send(ctx context.Context, payload []byte) error
- func (c *WriteFirstConn) Session() session.Session
- func (c *WriteFirstConn) TryCloseIfIdle(idleTimeout time.Duration) bool
- func (c *WriteFirstConn) TryCloseIfSlow(_ int32) bool
- func (c *WriteFirstConn) UpdateActivityTime()
Constants ¶
const ( // 默认读写超时时间 DefaultReadTiemout = 15 * time.Second DefaultWriteTiemout = 10 * time.Second // 默认缓冲大小 DefaultSendBufferSize = 256 DefaultReceiveBufferSize = 256 // 默认重试策略 DefaultInitRetryInterval = 1 * time.Second DefaultMaxRetryInterval = 5 * time.Second DefaultMaxRetryCount = 3 DefaultCloseTimeout = time.Second DefaultRateLimit = 10 // DefaultEstablishedReadTimeout 为鉴权完成后的连接读超时。 // 鉴权前使用短超时 ( DefaultReadTiemout ) 保障 AUTH 超时及时生效; // 鉴权后连接由应用层心跳保活,长超时显著减少空闲连接的 // 周期性 deadline 唤醒 ( 10 万连接下从 ~6.7k 次/s 降至 ~1.1k 次/s )。 DefaultEstablishedReadTimeout = 90 * time.Second )
Variables ¶
var ConnFxModule = fx.Module( "ws-conn", fx.Provide( fx.Annotate( newConnRegistry, fx.As(new(synp.ConnRegistry)), ), ), fx.Provide( fx.Annotate( newConnManager, fx.As(new(synp.ConnManager)), ), ), )
var ErrConnClosed = errors.New("connection closed")
Functions ¶
func ConnManagerWithConfig ¶
func ConnManagerWithConfig(cfg *ConnConfig) option.Opt[ConnManager]
func ConnRegistryWithKeyPrefix ¶
func ConnRegistryWithKeyPrefix(keyPrefix string) option.Opt[ConnRegistry]
func ConnRegistryWithTTL ¶
func ConnRegistryWithTTL(ttl time.Duration) option.Opt[ConnRegistry]
func ConnWithCompression ¶
func ConnWithCompression(state *compression.State) option.Opt[Conn]
func ConnWithEstablishedReadTimeout ¶
ConnWithEstablishedReadTimeout 设置鉴权完成后的读超时。
func ConnWithMaxFrameBytes ¶
ConnWithMaxFrameBytes 设置入站数据帧大小上限。
func ConnWithRateLimit ¶
ConnWithRateLimit 限流器 option。 rate 为每秒请求上限。
func ConnWithRetry ¶
Types ¶
type Conn ¶
type Conn struct {
// contains filtered or unexported fields
}
Conn 代表一个 WebSocket 连接,封装了 net.Conn。 同时负责 WebSocket 消息的读写。 读写操作分别由独立的 goroutine 负责。
func (*Conn) Authenticated ¶
func (c *Conn) Authenticated() <-chan struct{}
Authenticated 返回鉴权完成信号。 channel 关闭表示连接已完成首帧 AUTH 鉴权。
func (*Conn) BindSession ¶
BindSession 在首帧 AUTH 鉴权成功后,将匿名 Session 替换为携带真实身份的 Session。
func (*Conn) MarkAuthenticated ¶
func (c *Conn) MarkAuthenticated()
MarkAuthenticated 标记连接鉴权完成,重复调用是安全的。 鉴权完成后立即把读超时切换为长超时, 避免空闲连接在每个短超时周期被无效唤醒。
func (*Conn) TryCloseIfSlow ¶
TryCloseIfSlow 出站入队连续超时达到 minOverflow 时关闭连接 ( 慢客户端隔离 )。
func (*Conn) UpdateActivityTime ¶
func (c *Conn) UpdateActivityTime()
type ConnConfig ¶
type ConnConfig struct {
ReadTimeout time.Duration
WriteTimeout time.Duration
// EstablishedReadTimeout 为鉴权完成后的读超时 ( 0 使用默认 90s )。
EstablishedReadTimeout time.Duration
InitRetryInterval time.Duration
MaxRetryInterval time.Duration
MaxRetryCount int32
SendBufferSize int
ReceiveBufferSize int
CloseTimeout time.Duration
RateLimit int
// MaxFrameBytes 为入站数据帧大小上限 ( 0 使用 xws 默认值 64KiB )。
MaxFrameBytes int64
}
type ConnManager ¶
type ConnManager struct {
// contains filtered or unexported fields
}
ConnManager 管理网关节点上的全部连接。
连接在建立时身份未知 ( 新协议鉴权在连接建立后的首帧 AUTH 完成 ), 先进入 pending 区;鉴权成功后由 BindUser 绑定到用户索引。
connIndex 为 connID → connKey 的反向索引, 使断开清理 ( RemoveConnByID ) 无需遍历用户索引,复杂度 O(1)。
func NewConnManager ¶
func NewConnManager(opts ...option.Opt[ConnManager]) *ConnManager
func (*ConnManager) ConnCount ¶
func (m *ConnManager) ConnCount() int64
ConnCount 返回当前连接总数 ( 含未鉴权连接 )。
func (*ConnManager) FindUserConn ¶
FindUserConn 查找用户所有连接 ( 多设备 )。
func (*ConnManager) NewConn ¶
func (m *ConnManager) NewConn(ctx context.Context, netConn net.Conn, sess session.Session, compressionState *compression.State) (synp.Conn, error)
NewConn 创建连接。 新协议下连接建立时身份未知,连接先注册到 pending 区, 完成首帧 AUTH 鉴权后由 BindUser 绑定到用户索引。
连接计数语义: connCnt 为当前在线连接总数 ( 含未鉴权连接 ), 在 NewConn 时 +1、断开清理时 -1,BindUser 仅移动归属不计新增。
func (*ConnManager) RangeConns ¶
func (m *ConnManager) RangeConns(fn func(synp.Conn) bool)
RangeConns 遍历当前节点全部连接 ( 含未鉴权连接 ), fn 返回 false 时提前终止。供关停排空等全量巡检使用。
func (*ConnManager) RangeConnsShard ¶
func (m *ConnManager) RangeConnsShard(shard, shards uint64, fn func(synp.Conn) bool)
RangeConnsShard 分片遍历: 仅对 hash(connID) % shards == shard 的连接调用 fn。 空闲扫描等周期性巡检按分片摊薄单次开销, 大规模连接下避免单次扫描集中获取全部连接锁。
func (*ConnManager) RemoveConn ¶
func (m *ConnManager) RemoveConn(user session.User) bool
RemoveConn 移除并关闭用户指定设备的连接 ( 顶号等场景 )。
func (*ConnManager) RemoveConnByID ¶
func (m *ConnManager) RemoveConnByID(connID string) bool
RemoveConnByID 按连接 ID 移除连接。 经反向索引 O(1) 定位,同时覆盖 pending 区与用户索引区。 连接断开的统一清理入口。
func (*ConnManager) RemoveUserConn ¶
func (m *ConnManager) RemoveUserConn(user session.User) bool
type ConnRegistry ¶
type ConnRegistry struct {
// contains filtered or unexported fields
}
ConnRegistry 是连接注册表。 使用 Redis ZSET 存储用户连接所在网关节点及其过期时间 ( score )。
TODO: 注册结构需要调整。
┌──────────────────────────────────────┐ │ Redis │ │ user → zset ( node member, expire ) │ │ ├─ v1:<name>:<addr>: 1710000001000 │ ← 手机连接 │ └─ v1:<name>:<addr>: 1710000002000 │ ← PC连接 └──────────────────────────────────────┘
说明:
- 每个节点有自己的过期时间,避免 key 级 TTL 导致脏节点被续命。
- FindNodes 时会先清理过期节点,再返回当前有效节点。
注:更优方案是独立出一个 Route Service。
- 网关节点 -> gRPC -> Route Service -> Redis ( 用户建立连接时注册 )。
- 业务服务端 -> gRPC -> Route Service ( 下行消息转发时查询目标网关集群 )。
func NewConnRegistry ¶
func NewConnRegistry(rdb redis.Cmdable, node synp.ConnNode, opts ...option.Opt[ConnRegistry]) *ConnRegistry
func (*ConnRegistry) Register ¶
Register 注册用户连接到当前网关节点。
使用 Redis ZSET 结构存储,member 为连接粒度:
- key: key_prefix:{bid}:{uid}
- member: v2:{base64url(service_name)}:{base64url(service_addr)}:{connID}
- score: 该连接路由记录的过期时间戳 ( unix ms )
func (*ConnRegistry) Unregister ¶
Unregister 注销用户连接 ( 连接粒度,不影响同节点的其它连接 )。
type DeviceConns ¶
type DeviceConns struct {
// contains filtered or unexported fields
}
DeviceConns 管理单个用户的多设备连接。 这里不直接使用 sync.Map 是因为一个用户最多只会有 3 个设备连接。 相比起直接使用 sync.Map 性能更好且内存占用更低。
type ReadWriteConn ¶
type ReadWriteConn struct {
// contains filtered or unexported fields
}
ReadWriteConn 代表一个 WebSocket 连接,封装了 net.Conn。 使用单个 goroutine 同时负责读写操作。
func NewReadWriteConn ¶
func (*ReadWriteConn) Authenticated ¶
func (c *ReadWriteConn) Authenticated() <-chan struct{}
Authenticated 返回鉴权完成信号。
func (*ReadWriteConn) BindSession ¶
func (c *ReadWriteConn) BindSession(sess session.Session)
BindSession 在首帧 AUTH 鉴权成功后,将匿名 Session 替换为携带真实身份的 Session。
func (*ReadWriteConn) Close ¶
func (c *ReadWriteConn) Close() error
func (*ReadWriteConn) Closed ¶
func (c *ReadWriteConn) Closed() <-chan struct{}
func (*ReadWriteConn) ID ¶
func (c *ReadWriteConn) ID() string
func (*ReadWriteConn) MarkAuthenticated ¶
func (c *ReadWriteConn) MarkAuthenticated()
MarkAuthenticated 标记连接鉴权完成,重复调用是安全的。
func (*ReadWriteConn) Receive ¶
func (c *ReadWriteConn) Receive() <-chan []byte
func (*ReadWriteConn) Send ¶
func (c *ReadWriteConn) Send(ctx context.Context, payload []byte) error
func (*ReadWriteConn) Session ¶
func (c *ReadWriteConn) Session() session.Session
func (*ReadWriteConn) TryCloseIfIdle ¶
func (c *ReadWriteConn) TryCloseIfIdle(idleTimeout time.Duration) bool
func (*ReadWriteConn) TryCloseIfSlow ¶
func (c *ReadWriteConn) TryCloseIfSlow(_ int32) bool
TryCloseIfSlow 未启用 ( 实验连接类型,无入队超时计数 )。
func (*ReadWriteConn) UpdateActivityTime ¶
func (c *ReadWriteConn) UpdateActivityTime()
type WriteFirstConn ¶
type WriteFirstConn struct {
// contains filtered or unexported fields
}
WriteFirstConn 代表一个 WebSocket 连接,封装了 net.Conn。 使用单个 goroutine 同时负责读写操作。 与 ReadWriteConn 不同的是, WriteFirstConn 在每次循环时会先批量执行写操作。
func NewWriteFirstConn ¶
func (*WriteFirstConn) Authenticated ¶
func (c *WriteFirstConn) Authenticated() <-chan struct{}
Authenticated 返回鉴权完成信号。
func (*WriteFirstConn) BindSession ¶
func (c *WriteFirstConn) BindSession(sess session.Session)
BindSession 在首帧 AUTH 鉴权成功后,将匿名 Session 替换为携带真实身份的 Session。
func (*WriteFirstConn) Close ¶
func (c *WriteFirstConn) Close() error
func (*WriteFirstConn) Closed ¶
func (c *WriteFirstConn) Closed() <-chan struct{}
func (*WriteFirstConn) ID ¶
func (c *WriteFirstConn) ID() string
func (*WriteFirstConn) MarkAuthenticated ¶
func (c *WriteFirstConn) MarkAuthenticated()
MarkAuthenticated 标记连接鉴权完成,重复调用是安全的。
func (*WriteFirstConn) Receive ¶
func (c *WriteFirstConn) Receive() <-chan []byte
func (*WriteFirstConn) Send ¶
func (c *WriteFirstConn) Send(ctx context.Context, payload []byte) error
func (*WriteFirstConn) Session ¶
func (c *WriteFirstConn) Session() session.Session
func (*WriteFirstConn) TryCloseIfIdle ¶
func (c *WriteFirstConn) TryCloseIfIdle(idleTimeout time.Duration) bool
func (*WriteFirstConn) TryCloseIfSlow ¶
func (c *WriteFirstConn) TryCloseIfSlow(_ int32) bool
TryCloseIfSlow 未启用 ( 实验连接类型,无入队超时计数 )。
func (*WriteFirstConn) UpdateActivityTime ¶
func (c *WriteFirstConn) UpdateActivityTime()