-
Notifications
You must be signed in to change notification settings - Fork 414
/
broker.go
69 lines (59 loc) · 1.35 KB
/
broker.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
package websocket
import (
"context"
"time"
"github.com/rockbears/log"
"github.com/ovh/cds/engine/cache"
"github.com/ovh/cds/sdk"
)
func NewBroker() *Broker {
return &Broker{chanMessages: make(chan []byte)}
}
type Broker struct {
chanMessages chan []byte
onMessage func(m []byte)
}
func (b *Broker) OnMessage(f func(m []byte)) { b.onMessage = f }
//Init the websocketBroker
func (b *Broker) Init(ctx context.Context, gorts *sdk.GoRoutines, pubSub cache.PubSub) {
// Start cache Subscription
gorts.Run(ctx, "websocket.Broker.Init.cacheSubscribe", func(ctx context.Context) {
b.subscribe(ctx, pubSub)
})
gorts.Run(ctx, "websocket.Broker.Init.start", func(ctx context.Context) {
b.start(ctx)
})
}
// Start the broker
func (b *Broker) start(ctx context.Context) {
for {
select {
case <-ctx.Done():
return
case msg := <-b.chanMessages:
if b.onMessage != nil {
b.onMessage(msg)
}
}
}
}
func (b *Broker) subscribe(ctx context.Context, pubSub cache.PubSub) {
tick := time.NewTicker(50 * time.Millisecond)
defer tick.Stop()
for {
select {
case <-ctx.Done():
return
case <-tick.C:
if ctx.Err() != nil {
continue
}
msg, err := pubSub.GetMessage(ctx)
if err != nil {
log.Warn(ctx, "websocket.Broker> cannot get message from pubsub %s: %s", msg, err)
continue
}
b.chanMessages <- []byte(msg)
}
}
}