-
Notifications
You must be signed in to change notification settings - Fork 13
/
data-controller.go
92 lines (81 loc) · 1.93 KB
/
data-controller.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
package process_master
import (
"context"
"sync"
"github.com/eolinker/eosc/process-master/extender"
"github.com/eolinker/eosc"
"github.com/eolinker/eosc/log"
"github.com/eolinker/eosc/common/dispatcher"
)
type DataController struct {
ctx context.Context
cancel context.CancelFunc
closeOnce sync.Once
extenderManager *extender.Manager
dispatcherService *DispatcherServer
}
func NewDataController(raftData dispatcher.IDispatchCenter, extenderManager *extender.Manager, dispatcherService *DispatcherServer) *DataController {
ctx, cancel := context.WithCancel(context.Background())
dc := &DataController{
ctx: ctx,
cancel: cancel,
closeOnce: sync.Once{},
extenderManager: extenderManager,
dispatcherService: dispatcherService,
}
listener := raftData.Listener()
go dc.doLoop(listener)
return dc
}
func (c *DataController) Close() {
c.closeOnce.Do(func() {
c.cancel()
c.dispatcherService.Close()
})
}
func (c *DataController) doLoop(listener dispatcher.IListener) {
// 监听raft的事件
defer listener.Leave()
for {
select {
case e, ok := <-listener.Event():
if !ok {
return
}
err := c.doEvent(e)
if err != nil {
log.Errorf("[%s:%s] data error: %w", e.Event(), e.Namespace(), err)
}
c.dispatcherService.Dispatch(e)
case <-c.ctx.Done():
return
}
}
}
func (c *DataController) doEvent(event dispatcher.IEvent) error {
if event.Namespace() != eosc.NamespaceExtender && event.Namespace() != "" {
return nil
}
switch event.Event() {
case eosc.EventSet:
{
err := c.extenderManager.Set(event.Key(), string(event.Data()))
if err != nil {
return err
}
}
case eosc.EventDel:
{
err := c.extenderManager.Del(event.Key())
if err != nil {
return err
}
}
case eosc.EventInit, eosc.EventReset:
{
tmp := event.All()
return c.extenderManager.Reset(tmp[eosc.NamespaceExtender])
}
}
return nil
}