You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
nnet/conn/group.go

246 lines
4.7 KiB
Go

package conn
2 years ago
import (
"errors"
"git.noahlan.cn/noahlan/ntool/nlog"
2 years ago
"sync"
"sync/atomic"
)
const groupKey = "NNET_GROUP#"
const DefaultGroupName = "DEFAULT_GROUP"
const (
groupStatusWorking = 0
groupStatusClosed = 1
)
var (
ErrCloseClosedGroup = errors.New("close closed group")
ErrClosedGroup = errors.New("group closed")
DeleteDefaultGroupNotAllow = errors.New("delete default group not allow")
)
type Group struct {
mu sync.RWMutex
status int32 // group current status
name string // group name
conns map[int64]*Connection
2 years ago
}
func NewGroup(name string) *Group {
return &Group{
mu: sync.RWMutex{},
status: groupStatusWorking,
name: name,
conns: make(map[int64]*Connection),
2 years ago
}
}
// Member returns connection by specified uid
func (g *Group) Member(uid string) (*Connection, bool) {
g.mu.RLock()
defer g.mu.RUnlock()
2 years ago
for _, e := range g.conns {
2 years ago
if e.Session().UID() == uid {
return e, true
}
}
return nil, false
}
// MemberBySID returns specified sId's connection
func (g *Group) MemberBySID(id int64) (*Connection, bool) {
g.mu.RLock()
defer g.mu.RUnlock()
2 years ago
e, ok := g.conns[id]
2 years ago
return e, ok
}
func (g *Group) Members() []*Connection {
var resp []*Connection
g.PeekMembers(func(_ int64, c *Connection) bool {
resp = append(resp, c)
2 years ago
return false
})
return resp
}
// PeekMembers returns all members in current group
// fn 返回true跳过循环反之一直循环
func (g *Group) PeekMembers(fn func(sId int64, c *Connection) bool) {
g.mu.RLock()
defer g.mu.RUnlock()
2 years ago
for sId, c := range g.conns {
if fn(sId, c) {
2 years ago
break
}
}
}
// Contains check whether a UID is contained in current group or not
func (g *Group) Contains(uid string) bool {
_, ok := g.Member(uid)
2 years ago
return ok
}
// Add session to group
func (g *Group) Add(c *Connection) error {
if g.isClosed() {
2 years ago
return ErrClosedGroup
}
g.mu.Lock()
defer g.mu.Unlock()
2 years ago
sess := c.Session()
2 years ago
id := sess.ID()
// group attribute
if sess.Exists(groupKey) {
groups, ok := sess.Attribute(groupKey).([]string)
if !ok {
groups = make([]string, 0)
sess.SetAttribute(groupKey, groups)
}
contains := false
for _, group := range groups {
if group == g.name {
2 years ago
contains = true
break
}
}
if !contains {
groups = append(groups, g.name)
2 years ago
sess.SetAttribute(groupKey, groups)
}
} else {
sess.SetAttribute(groupKey, []string{g.name})
2 years ago
}
if _, ok := g.conns[id]; !ok {
g.conns[id] = c
2 years ago
}
nlog.Debugf("Add connection to group %s, ID=%d, UID=%s", g.name, sess.ID(), sess.UID())
2 years ago
return nil
}
// Leave remove specified UID related session from group
func (g *Group) Leave(c *Connection) error {
if g.isClosed() {
2 years ago
return ErrClosedGroup
}
if c == nil {
2 years ago
return nil
}
sess := c.Session()
nlog.Debugf("Remove connection from group %s, UID=%s", g.name, sess.UID())
2 years ago
g.mu.Lock()
defer g.mu.Unlock()
2 years ago
if sess.Exists(groupKey) {
groups, ok := sess.Attribute(groupKey).([]string)
if !ok {
groups = make([]string, 0)
sess.SetAttribute(groupKey, groups)
}
groups = g.removeGroupAttr(groups)
2 years ago
if len(groups) == 0 {
sess.RemoveAttribute(groupKey)
} else {
sess.SetAttribute(groupKey, groups)
}
}
delete(g.conns, sess.ID())
2 years ago
return nil
}
func (g *Group) LeaveByUID(uid string) error {
if g.isClosed() {
2 years ago
return ErrClosedGroup
}
member, _ := g.Member(uid)
return g.Leave(member)
2 years ago
}
// LeaveAll clear all sessions in the group
func (g *Group) LeaveAll() error {
if g.isClosed() {
2 years ago
return ErrClosedGroup
}
g.mu.Lock()
defer g.mu.Unlock()
2 years ago
for _, e := range g.conns {
2 years ago
sess := e.Session()
groups, ok := sess.Attribute(groupKey).([]string)
if !ok {
groups = make([]string, 0)
sess.SetAttribute(groupKey, groups)
}
groups = g.removeGroupAttr(groups)
2 years ago
if len(groups) == 0 {
sess.RemoveAttribute(groupKey)
} else {
sess.SetAttribute(groupKey, groups)
}
}
g.conns = make(map[int64]*Connection)
2 years ago
return nil
}
// 使用移位法移除group中与name匹配的元素
func (g *Group) removeGroupAttr(groups []string) []string {
2 years ago
j := 0
for _, v := range groups {
if v != g.name {
groups[j] = v
2 years ago
j++
}
}
return groups[:j]
2 years ago
}
// Count get current member amount in the group
func (g *Group) Count() int {
g.mu.RLock()
defer g.mu.RUnlock()
2 years ago
return len(g.conns)
2 years ago
}
func (g *Group) isClosed() bool {
if atomic.LoadInt32(&g.status) == groupStatusClosed {
2 years ago
return true
}
return false
}
// Close destroy group, which will release all resource in the group
func (g *Group) Close() error {
if g.isClosed() {
2 years ago
return ErrCloseClosedGroup
}
if g.name == DefaultGroupName {
2 years ago
// 默认分组不允许删除
return DeleteDefaultGroupNotAllow
}
_ = g.LeaveAll()
2 years ago
atomic.StoreInt32(&g.status, groupStatusClosed)
2 years ago
return nil
}