-
Notifications
You must be signed in to change notification settings - Fork 1
/
blackboard.go
381 lines (353 loc) · 9.6 KB
/
blackboard.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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
package bcore
import (
stderr "errors"
"reflect"
"sync"
"time"
"go.uber.org/zap"
"github.com/alkaid/behavior/logger"
"github.com/alkaid/behavior/thread"
"github.com/samber/lo"
)
var ErrBlackboardAlreadyStarted = stderr.New("blackboard already started")
var ErrBlackboardAlreadyStopped = stderr.New("blackboard already stopped")
type OpType int // 操作类型
const (
OpAdd OpType = iota + 1 // 添加kv
OpDel // 删除kv
OpChange // 修改value
)
// Blackboard.observers 的元素无法存储范型方法,只能先改用any,未来go支持以后再改为范型方法
// type Observer[T any] func(op OpType, key string, oldValue T, newValue T)
type Observer func(op OpType, key string, oldValue any, newValue any)
// Blackboard
//
// @implement IBlackboard
// @implement IBlackboardInternal
// get和set为线程安全,其他方法均为非线程安全,请在树自己的线程内调用
// 黑板的[生命周期调用,监听添加移除,监听函数的执行]必须派发到AI独立线程
// 黑板的kv读写可以在任意线程
// 黑板为树形结构,实例化时可指定父黑板,将继承父黑板的KV.父黑板,一般来说是AI集群的共享黑板。想实现AI间通信时这将很有用.
type Blackboard struct {
memoryMutex sync.RWMutex
threadID int // 监听函数执行的线程ID
treesMemory map[string]Memory // 索引为行为树ID(rootID),元素为对应行为树的数据<行为树域>.仅允许框架内部CRUD
nodesData map[string]*NodeMemory // 索引为节点ID,元素为对应节点的数据<节点域>.仅允许节点内部CRUD
userMemory Memory // 作用域为<用户域>的数据.仅允许业务方CRUD
enable bool // 是否开启
observers map[string][]Observer // 监听列表
parent *Blackboard // 父黑板,一般来说是AI集群的共享黑板
children []*Blackboard // 子黑板
}
func (b *Blackboard) ThreadID() int {
return b.threadID
}
// TreeMemory
//
// @implement IBlackboardInternal.TreeMemory
// @receiver b
// @param rootID
// @return Memory
func (b *Blackboard) TreeMemory(rootID string) Memory {
mem, ok := b.treesMemory[rootID]
if !ok {
mem = make(Memory)
b.treesMemory[rootID] = mem
}
return mem
}
// NodeExt
//
// @implement IBlackboardInternal.NodeExt
// @receiver b
// @param nodeID
// @return Memory
func (b *Blackboard) NodeExt(nodeID string) Memory {
return b.NodeMemory(nodeID).Ext
}
// NodeMemory
//
// @implement IBlackboardInternal.NodeMemory
// @receiver b
// @param nodeID
// @return *NodeMemory
func (b *Blackboard) NodeMemory(nodeID string) *NodeMemory {
mem, ok := b.nodesData[nodeID]
if !ok {
mem = NewNodeMemory()
b.nodesData[nodeID] = mem
}
return mem
}
// NewBlackboard 实例化一个黑板
//
// @param threadID AI工作线程ID
// @param parent 父黑板,一般来说是AI集群的共享黑板
// @return *Blackboard
func NewBlackboard(threadID int, parent *Blackboard) *Blackboard {
if threadID <= 0 {
logger.Log.Fatal("threadID cannot <=0")
}
b := &Blackboard{
threadID: threadID,
treesMemory: make(map[string]Memory),
nodesData: make(map[string]*NodeMemory),
userMemory: make(Memory),
observers: make(map[string][]Observer),
parent: parent,
children: make([]*Blackboard, 0),
}
return b
}
// Start
//
// @implement IBlackboardInternal.Start
// @receiver b
func (b *Blackboard) Start() {
if b.enable {
logger.Log.Warn("blackboard already stared")
return
}
b.enable = true
if b.parent != nil {
b.parent.children = append(b.parent.children, b)
}
}
// Stop
//
// @implement IBlackboardInternal.Stop
// @receiver b
func (b *Blackboard) Stop() {
if !b.enable {
logger.Log.Warn("blackboard already stopped")
return
}
b.enable = false
// 销毁所有树和节点数据,销毁所有监听
b.observers = map[string][]Observer{}
b.treesMemory = map[string]Memory{}
b.nodesData = map[string]*NodeMemory{}
// 从父黑板中移除自己
if b.parent != nil {
b.parent.children = lo.DropWhile(b.parent.children, func(v *Blackboard) bool { return v == b })
}
}
// AddObserver
//
// @implement IBlackboardInternal.AddObserver
// @receiver b
// @param key
// @param observer
func (b *Blackboard) AddObserver(key string, observer Observer) {
b.addOrRmObserver(true, key, observer)
}
// RemoveObserver
//
// @implement IBlackboardInternal.RemoveObserver
// @receiver b
// @param key
// @param observer
func (b *Blackboard) RemoveObserver(key string, observer Observer) {
b.addOrRmObserver(false, key, observer)
}
// addOrRmObserver
//
// @receiver b
// @param add
// @param key
// @param observer
func (b *Blackboard) addOrRmObserver(add bool, key string, observer Observer) {
// 无论调用方是否在AI线程里,都兜底派发到AI线程,避免和监听函数并行
thread.GoByID(b.threadID, func() {
if !b.enable {
return
}
observers, ok := b.observers[key]
contains := false
if !ok {
observers = make([]Observer, 0)
b.observers[key] = observers
} else {
observerPtr := reflect.ValueOf(observer).Pointer()
contains = lo.ContainsBy(observers, func(v Observer) bool { return observerPtr == reflect.ValueOf(v).Pointer() })
}
if !add {
if contains {
observerPtr := reflect.ValueOf(observer).Pointer()
b.observers[key] = lo.DropWhile(observers, func(v Observer) bool {
return observerPtr == reflect.ValueOf(v).Pointer()
})
return
}
logger.Log.Debug("[blackboard]remove observer failed. observers not contained this observer", zap.String("key", key))
return
}
if !contains {
b.observers[key] = append(b.observers[key], observer)
return
}
logger.Log.Debug("[blackboard]add observer failed. observers already contained this observer", zap.String("key", key))
})
}
// notify 黑板数据(用户域)改变时通知监听函数执行
//
// @receiver b
// @param op
// @param key
// @param oldVal
// @param newVal
func (b *Blackboard) notify(op OpType, key string, oldVal any, newVal any) {
// 无论调用方是否在AI线程里,都兜底派发到AI线程,使监听函数在AI线程里串行
thread.GoByID(b.threadID, func() {
if !b.enable {
return
}
for _, ob := range b.observers[key] {
ob(op, key, oldVal, newVal)
}
})
}
// Get
//
// @implement IBlackboard.Get
// @receiver b
// @param key
// @return any
// @return bool
func (b *Blackboard) Get(key string) (any, bool) {
b.memoryMutex.RLock()
defer b.memoryMutex.RUnlock()
val, ok := b.userMemory[key]
if ok || b.parent == nil {
return val, ok
}
// 找不到时回溯父黑板
val, ok = b.parent.Get(key)
return val, ok
}
// GetDuration
//
// @implement IBlackboard.GetDuration
// @receiver b
// @param key
// @return time.Duration
// @return bool
func (b *Blackboard) GetDuration(key string) (time.Duration, bool) {
val, ok := b.Get(key)
switch v := val.(type) {
case time.Duration:
return v, ok
case int64:
return time.Duration(v), ok
case string:
tm, err := time.ParseDuration(v)
if err != nil {
logger.Log.Error("convert duration error", zap.Error(err), zap.String("key", key), zap.Any("value", val))
return tm, false
}
return tm, true
}
logger.Log.Error("convert duration error,unsupport type", zap.String("key", key), zap.Any("value", val))
return 0, false
}
// Set
//
// @implement IBlackboard.Set
// @receiver b
// @param key
// @param val
func (b *Blackboard) Set(key string, val any) {
b.memoryMutex.Lock()
defer b.memoryMutex.Unlock()
// 优先设置父黑板
if b.parent != nil {
_, ok := b.parent.Get(key)
if ok {
b.parent.Set(key, val)
return
}
}
op := OpAdd
oldVal, ok := b.userMemory[key]
if ok {
op = OpChange
}
b.userMemory[key] = val
b.notify(op, key, oldVal, val)
}
// Del
//
// @implement IBlackboard.Del
// @receiver b
// @param key
func (b *Blackboard) Del(key string) {
b.memoryMutex.Lock()
defer b.memoryMutex.Unlock()
op := OpDel
oldVal, ok := b.userMemory[key]
if ok {
delete(b.userMemory, key)
b.notify(op, key, oldVal, nil)
}
}
var _ IBlackboard = (*Blackboard)(nil)
var _ IBlackboardInternal = (*Blackboard)(nil)
// IBlackboard 黑板,AI行为树实例的记忆
type IBlackboard interface {
// Get 获取Value,可链式传给 ConvertAnyValue[T]来转换类型
// @receiver b
// @param key
// @return any
// @return bool
Get(key string) (any, bool)
// GetDuration 获取 time.Duration 类型的值,支持 int64 | string | time.Duration. string 格式参考 time.ParseDuration
// @receiver b
// @param key
// @return time.Duration
// @return bool
GetDuration(key string) (time.Duration, bool)
// Set 设置KV(用户域)
// 线程安全
// @receiver b
// @param key
// @param val
Set(key string, val any)
// Del 删除KV
// 线程安全
// @receiver b
// @param key
Del(key string)
}
// IBlackboardInternal 框架内或自定义节点时使用的黑板,从 IBlackboard 转化来
//
// 含有私有API,业务层请勿调用,避免引发不可预期的后果
type IBlackboardInternal interface {
IBlackboard
// ThreadID 获取线程ID
// @return int
ThreadID() int
// Start 启动,将会开始监听kv
// 私有,框架内部使用
// 非线程安全
// @receiver b
Start()
// Stop 停止,将会停止监听kv
// 私有,框架内部使用
// 非线程安全
// @receiver b
Stop()
AddObserver(key string, observer Observer)
RemoveObserver(key string, observer Observer)
// TreeMemory 树数据
// @param rootID
// @return Memory
TreeMemory(rootID string) Memory
// NodeExt 节点的数据(扩展)
// @param nodeID
// @return Memory
NodeExt(nodeID string) Memory
// NodeMemory 节点的数据(固定)
// @param nodeID
// @return *NodeMemory
NodeMemory(nodeID string) *NodeMemory
}