-
Notifications
You must be signed in to change notification settings - Fork 13
/
controller.go
94 lines (71 loc) · 1.9 KB
/
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
93
94
package dispatchers
import (
"log"
"sync"
"github.com/CyCoreSystems/dispatchers/v2/sets"
)
// An Exporter handles the export of the set of dispatcher sets.
type Exporter interface {
Export([]*sets.State) error
}
// A Notifier handles the notification of interested parties of the change of dispatcher sets.
type Notifier interface {
Notify([]*sets.State) error
}
// Controller manages the processing of dispatcher sets
type Controller struct{
Exporter Exporter
Notifier Notifier
Logger *log.Logger
sets []sets.DispatcherSet
mu sync.RWMutex
}
// AddSet adds a DispatcherSet to the Controller
func (c *Controller) AddSet(set sets.DispatcherSet) {
c.mu.Lock()
set.RegisterChangeFunc(c.ChangeFunc)
c.sets = append(c.sets, set)
c.mu.Unlock()
}
func (c *Controller) CurrentState() (currentState []*sets.State) {
c.mu.RLock()
for _, s := range c.sets {
currentState = append(currentState, s.State())
}
c.mu.RUnlock()
return currentState
}
// Export tells the Controller to export its current dispatcher sets
func (c *Controller) Export() error {
if c.Exporter == nil {
return nil
}
return c.Exporter.Export(c.CurrentState())
}
// Notify tells the Controller to send a notification to its notifier
func (c *Controller) Notify() error {
if c.Notifier == nil {
return nil
}
return c.Notifier.Notify(c.CurrentState())
}
// ChangeFunc provides a change handler for managing dispatcher set changes
func (c *Controller) ChangeFunc(state *sets.State) {
currentState := c.CurrentState()
log.Println("exporting...")
if c.Exporter != nil {
if err := c.Exporter.Export(currentState); err != nil {
if c.Logger != nil {
c.Logger.Println("failed to export current state:", err)
}
}
}
log.Println("notifying...")
if c.Notifier != nil {
if err := c.Notifier.Notify(currentState); err != nil {
if c.Logger != nil {
c.Logger.Println("failed to notify current state:", err)
}
}
}
}