|
|
package connection
|
|
|
|
|
|
// GroupStrategy 分组策略接口
|
|
|
// 用于定义如何将连接分配到分组
|
|
|
type GroupStrategy interface {
|
|
|
// GetGroupID 获取连接所属的分组ID
|
|
|
// 如果连接不属于任何分组,返回空字符串
|
|
|
GetGroupID(conn ConnectionInterface) string
|
|
|
|
|
|
// Match 检查连接是否匹配指定的分组ID
|
|
|
Match(conn ConnectionInterface, groupID string) bool
|
|
|
}
|
|
|
|
|
|
// StringGroupStrategy 字符串分组策略(现有实现)
|
|
|
// 直接使用字符串作为分组ID
|
|
|
type StringGroupStrategy struct{}
|
|
|
|
|
|
// NewStringGroupStrategy 创建字符串分组策略
|
|
|
func NewStringGroupStrategy() GroupStrategy {
|
|
|
return &StringGroupStrategy{}
|
|
|
}
|
|
|
|
|
|
// GetGroupID 字符串策略不支持自动获取分组ID
|
|
|
// 需要通过AddToGroup手动添加
|
|
|
func (s *StringGroupStrategy) GetGroupID(conn ConnectionInterface) string {
|
|
|
// 字符串策略不支持自动分组,返回空
|
|
|
return ""
|
|
|
}
|
|
|
|
|
|
// Match 字符串策略不支持匹配检查
|
|
|
// 分组关系由管理器维护
|
|
|
func (s *StringGroupStrategy) Match(conn ConnectionInterface, groupID string) bool {
|
|
|
// 字符串策略的匹配由管理器维护的groups map决定
|
|
|
// 这里返回false,由管理器自己处理
|
|
|
return false
|
|
|
}
|
|
|
|
|
|
// TagGroupStrategy 标签分组策略
|
|
|
// 基于连接的attributes中的标签进行分组
|
|
|
type TagGroupStrategy struct {
|
|
|
tagKey string // 标签键(如 "group"、"room"等)
|
|
|
}
|
|
|
|
|
|
// NewTagGroupStrategy 创建标签分组策略
|
|
|
// tagKey: 用于分组的标签键名
|
|
|
func NewTagGroupStrategy(tagKey string) GroupStrategy {
|
|
|
return &TagGroupStrategy{
|
|
|
tagKey: tagKey,
|
|
|
}
|
|
|
}
|
|
|
|
|
|
// GetGroupID 从连接的attributes中获取分组ID
|
|
|
func (s *TagGroupStrategy) GetGroupID(conn ConnectionInterface) string {
|
|
|
// 检查连接是否有GetAttribute方法
|
|
|
if attrConn, ok := conn.(interface{ GetAttribute(key string) interface{} }); ok {
|
|
|
if tagValue := attrConn.GetAttribute(s.tagKey); tagValue != nil {
|
|
|
if groupID, ok := tagValue.(string); ok {
|
|
|
return groupID
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
return ""
|
|
|
}
|
|
|
|
|
|
// Match 检查连接的标签是否匹配分组ID
|
|
|
func (s *TagGroupStrategy) Match(conn ConnectionInterface, groupID string) bool {
|
|
|
return s.GetGroupID(conn) == groupID
|
|
|
}
|
|
|
|
|
|
// ConditionGroupStrategy 条件分组策略
|
|
|
// 基于连接属性的条件表达式进行分组
|
|
|
type ConditionGroupStrategy struct {
|
|
|
condition func(conn ConnectionInterface) string // 条件函数,返回分组ID
|
|
|
}
|
|
|
|
|
|
// NewConditionGroupStrategy 创建条件分组策略
|
|
|
// condition: 条件函数,根据连接属性返回分组ID
|
|
|
func NewConditionGroupStrategy(condition func(conn ConnectionInterface) string) GroupStrategy {
|
|
|
return &ConditionGroupStrategy{
|
|
|
condition: condition,
|
|
|
}
|
|
|
}
|
|
|
|
|
|
// GetGroupID 通过条件函数获取分组ID
|
|
|
func (s *ConditionGroupStrategy) GetGroupID(conn ConnectionInterface) string {
|
|
|
if s.condition != nil {
|
|
|
return s.condition(conn)
|
|
|
}
|
|
|
return ""
|
|
|
}
|
|
|
|
|
|
// Match 通过条件函数检查是否匹配
|
|
|
func (s *ConditionGroupStrategy) Match(conn ConnectionInterface, groupID string) bool {
|
|
|
return s.GetGroupID(conn) == groupID
|
|
|
}
|
|
|
|