-
Notifications
You must be signed in to change notification settings - Fork 0
/
entitymgr.go
105 lines (86 loc) · 2.7 KB
/
entitymgr.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package service
import (
"fmt"
"git.golaxy.org/core/ec"
"git.golaxy.org/core/internal/exception"
"git.golaxy.org/core/util/iface"
"git.golaxy.org/core/util/uid"
"sync"
)
// EntityMgr 实体管理器接口
type EntityMgr interface {
// GetContext 获取服务上下文
GetContext() Context
// GetEntity 查询实体
GetEntity(id uid.Id) (ec.ConcurrentEntity, bool)
// GetOrAddEntity 查询或添加实体
GetOrAddEntity(entity ec.ConcurrentEntity) (ec.ConcurrentEntity, bool, error)
// AddEntity 添加实体
AddEntity(entity ec.ConcurrentEntity) error
// GetAndRemoveEntity 查询并删除实体
GetAndRemoveEntity(id uid.Id) (ec.ConcurrentEntity, bool)
// RemoveEntity 删除实体
RemoveEntity(id uid.Id)
}
type _EntityMgrBehavior struct {
ctx Context
entityIdx sync.Map
}
func (mgr *_EntityMgrBehavior) init(ctx Context) {
if ctx == nil {
panic(fmt.Errorf("%w: %w: ctx is nil", ErrEntityMgr, exception.ErrArgs))
}
mgr.ctx = ctx
}
// GetContext 获取服务上下文
func (mgr *_EntityMgrBehavior) GetContext() Context {
return mgr.ctx
}
// GetEntity 查询实体
func (mgr *_EntityMgrBehavior) GetEntity(id uid.Id) (ec.ConcurrentEntity, bool) {
v, ok := mgr.entityIdx.Load(id)
if !ok {
return nil, false
}
return v.(ec.ConcurrentEntity), true
}
// GetOrAddEntity 查询或添加实体
func (mgr *_EntityMgrBehavior) GetOrAddEntity(entity ec.ConcurrentEntity) (ec.ConcurrentEntity, bool, error) {
if entity == nil {
return nil, false, fmt.Errorf("%w: %w: entity is nil", ErrEntityMgr, exception.ErrArgs)
}
if entity.GetId().IsNil() {
return nil, false, fmt.Errorf("%w: entity id is nil", ErrEntityMgr)
}
if entity.GetConcurrentContext() == iface.NilCache {
return nil, false, fmt.Errorf("%w: entity context is nil", ErrEntityMgr)
}
actual, loaded := mgr.entityIdx.LoadOrStore(entity.GetId(), entity)
return actual.(ec.ConcurrentEntity), loaded, nil
}
// GetAndRemoveEntity 查询并删除实体
func (mgr *_EntityMgrBehavior) GetAndRemoveEntity(id uid.Id) (ec.ConcurrentEntity, bool) {
v, loaded := mgr.entityIdx.LoadAndDelete(id)
if !loaded {
return nil, false
}
return v.(ec.ConcurrentEntity), true
}
// AddEntity 添加实体
func (mgr *_EntityMgrBehavior) AddEntity(entity ec.ConcurrentEntity) error {
if entity == nil {
return fmt.Errorf("%w: %w: entity is nil", ErrEntityMgr, exception.ErrArgs)
}
if entity.GetId().IsNil() {
return fmt.Errorf("%w: entity id is nil", ErrEntityMgr)
}
if entity.GetConcurrentContext() == iface.NilCache {
return fmt.Errorf("%w: entity context is nil", ErrEntityMgr)
}
mgr.entityIdx.Store(entity.GetId(), entity)
return nil
}
// RemoveEntity 删除实体
func (mgr *_EntityMgrBehavior) RemoveEntity(id uid.Id) {
mgr.entityIdx.Delete(id)
}