-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredis.go
99 lines (87 loc) · 1.78 KB
/
redis.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
package main
import (
"fmt"
"time"
"github.com/garyburd/redigo/redis"
)
const (
timerTick = time.Second * 10
heartbeat = ":heartbeat signal\n\n"
)
// Db represents all the connected clients
type Db map[*Client]interface{}
// Client is a connected client
type Client struct {
out chan []byte
subs map[string]bool
}
func ping(opsCh chan<- func(Db)) {
t := time.Tick(timerTick)
for _ = range t {
Debug("ping")
opsCh <- func(db Db) {
for c := range db {
c.out <- []byte(heartbeat)
}
}
}
}
func redisLoop(opsCh chan<- func(Db)) {
for {
switch v := psc.Receive().(type) {
case redis.Message:
Debug("Message [%s] %s\n", v.Channel, v.Data)
msg := fmt.Sprintf("data: %s\n\n", v.Data)
opsCh <- func(msg string) func(Db) {
return func(db Db) {
for c := range db {
if _, do := c.subs[v.Channel]; do {
c.out <- []byte(msg)
}
}
}
}(msg)
case redis.Subscription:
Debug("[%s] %s -> #%d\n", v.Channel, v.Kind, v.Count)
case error:
Error("%s", v)
}
}
}
func loop(ops <-chan func(Db)) {
// Client and list of channels
db := make(map[*Client]interface{})
for op := range ops {
op(db)
}
}
// ChannelManager atomically manages clients subscriptions
type ChannelManager map[string]uint
// Subscribe guess what
func (stats ChannelManager) Subscribe(ops chan<- func(Db), c *Client) {
ops <- func(db Db) {
db[c] = true
for s := range c.subs {
if _, ex := stats[s]; ex {
stats[s]++
} else {
stats[s] = 1
psc.Subscribe(s)
}
}
}
}
// Unsubscribe guess what
func (stats ChannelManager) Unsubscribe(ops chan<- func(Db), c *Client) {
ops <- func(db Db) {
delete(db, c)
for s := range c.subs {
if v, _ := stats[s]; v != 1 {
stats[s]--
} else {
delete(stats, s)
psc.Unsubscribe(s)
}
}
}
}