forked from HeinOldewage/Hyades
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwork_observers.go
124 lines (105 loc) · 1.99 KB
/
work_observers.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
package Hyades
import (
"log"
"sync"
"sync/atomic"
"time"
)
type Observable interface {
AddObserver() *Observer
GetChanges(uint32) ([]interface{}, bool)
}
type Observer struct {
Id uint32
events chan interface{}
ol *ObserverList
}
type ObserverList struct {
lock *sync.Mutex
observers map[uint32]*Observer
nextid uint32
}
func NewObserverList() *ObserverList {
return &ObserverList{
&sync.Mutex{},
make(map[uint32]*Observer, 0),
0,
}
}
func (ol *ObserverList) AddObserver() *Observer {
ol.lock.Lock()
defer ol.lock.Unlock()
res := &Observer{
atomic.AddUint32(&ol.nextid, 1),
make(chan interface{}, 100),
ol,
}
ol.observers[res.Id] = res
return res
}
func (ol *ObserverList) GetChanges(id uint32) ([]interface{}, bool) {
ob, ok := ol.GetObserver(id)
if !ok {
return nil, false
}
return ob.GetEvents(), true
}
func (ol *ObserverList) GetObserver(id uint32) (ob *Observer, ok bool) {
ol.lock.Lock()
defer ol.lock.Unlock()
ob, ok = ol.observers[id]
return
}
func (ol *ObserverList) RemoveObserver(ob *Observer) {
ol.lock.Lock()
defer ol.lock.Unlock()
delete(ol.observers, ob.Id)
}
func (ol *ObserverList) Callback(e interface{}) {
ol.lock.Lock()
defer ol.lock.Unlock()
for _, ob := range ol.observers {
ob.Callback(e)
}
}
func (wo *Observer) Callback(e interface{}) {
select {
case wo.events <- e:
{
//log.Println("observer", wo.Id, " got an event")
}
default:
{
//If the observer fails to retrive events we delete it
log.Println("Removing observer", wo.Id)
go wo.ol.RemoveObserver(wo)
}
}
}
func (wo *Observer) GetEvents() []interface{} {
res := make([]interface{}, 0)
timer := time.After(time.Second * 30)
//Wait for at least 1 event or 30 seconds to pass
select {
case event := <-wo.events:
{
res = append(res, event)
}
case <-timer:
{
}
}
//Get the rest of the events, if any exist
for {
select {
case event := <-wo.events:
{
res = append(res, event)
}
default:
{
return res
}
}
}
}