-
Notifications
You must be signed in to change notification settings - Fork 0
/
bus.go
78 lines (69 loc) · 1.58 KB
/
bus.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
package main
import (
"code.google.com/p/go-uuid/uuid"
"encoding/hex"
"net/url"
"strconv"
"sync"
)
func MessageBus(sub <-chan MessageBusSubscription) {
clientID := hex.EncodeToString(uuid.NewRandom())
type messageBusSubscription struct {
Call []MessageBusCallback
Last int
}
subscriptions := make(map[string]*messageBusSubscription)
var lock sync.Mutex
go func() {
for s := range sub {
lock.Lock()
if v, ok := subscriptions[s.Channel]; ok {
v.Call = append(v.Call, s.Call)
} else {
subscriptions[s.Channel] = &messageBusSubscription{Call: []MessageBusCallback{s.Call}, Last: -1}
}
lock.Unlock()
}
}()
for {
TryTryAgain("message bus poll", func() {
data := make(url.Values)
lock.Lock()
for c, s := range subscriptions {
data.Set(c, strconv.Itoa(s.Last))
}
lock.Unlock()
j, err := PostArray("/message-bus/"+clientID+"/poll?", data)
if err != nil {
panic(err)
}
for _, m := range j {
msg := m.(map[string]interface{})
c := msg["channel"].(string)
msgdata := msg["data"].(map[string]interface{})
lock.Lock()
if c == "/__status" {
for ch, id := range msgdata {
if v, ok := subscriptions[ch]; ok {
v.Last = int(id.(float64))
}
}
} else {
s := subscriptions[c]
if s != nil {
for _, call := range s.Call {
go call(msgdata)
}
s.Last = int(msg["message_id"].(float64))
}
}
lock.Unlock()
}
})
}
}
type MessageBusSubscription struct {
Channel string
Call MessageBusCallback
}
type MessageBusCallback func(map[string]interface{})