| 1 |
package centrifuge |
| 2 |
|
| 3 |
import ( |
| 4 |
"errors" |
| 5 |
"fmt" |
| 6 |
"time" |
| 7 |
|
| 8 |
"github.com/centrifugal/protocol" |
| 9 |
"github.com/gomodule/redigo/redis" |
| 10 |
) |
| 11 |
|
| 12 |
var _ PresenceManager = (*RedisPresenceManager)(nil) |
| 13 |
|
| 14 |
// RedisPresenceManager keeps presence in Redis thus allows scaling nodes. |
| 15 |
type RedisPresenceManager struct { |
| 16 |
node *Node |
| 17 |
sharding bool |
| 18 |
config RedisPresenceManagerConfig |
| 19 |
shards []*RedisShard |
| 20 |
addPresenceScript *redis.Script |
| 21 |
remPresenceScript *redis.Script |
| 22 |
presenceScript *redis.Script |
| 23 |
} |
| 24 |
|
| 25 |
const ( |
| 26 |
// DefaultRedisPresenceTTL is a default value for presence TTL in Redis. |
| 27 |
DefaultRedisPresenceTTL = 60 * time.Second |
| 28 |
// DefaultRedisPresenceManagerPrefix is a default value for RedisPresenceManagerConfig.Prefix. |
| 29 |
DefaultRedisPresenceManagerPrefix = "centrifuge" |
| 30 |
) |
| 31 |
|
| 32 |
// RedisPresenceManagerConfig is a config for RedisPresenceManager. |
| 33 |
type RedisPresenceManagerConfig struct { |
| 34 |
// Prefix to use before every channel name and key in Redis. By default |
| 35 |
// DefaultRedisPresenceManagerPrefix will be used. |
| 36 |
Prefix string |
| 37 |
|
| 38 |
// PresenceTTL is an interval how long to consider presence info |
| 39 |
// valid after receiving presence update. This allows to automatically |
| 40 |
// clean up unnecessary presence entries after TTL passed. Zero value |
| 41 |
// means that DefaultRedisPresenceTTL will be used. |
| 42 |
PresenceTTL time.Duration |
| 43 |
|
| 44 |
// Shards is a list of Redis shards to use. At least one shard must be provided. |
| 45 |
Shards []*RedisShard |
| 46 |
} |
| 47 |
|
| 48 |
const ( |
| 49 |
// Add/update client presence information. |
| 50 |
// KEYS[1] - presence set key |
| 51 |
// KEYS[2] - presence hash key |
| 52 |
// ARGV[1] - key expire seconds |
| 53 |
// ARGV[2] - expire at for set member |
| 54 |
// ARGV[3] - client ID |
| 55 |
// ARGV[4] - info payload |
| 56 |
addPresenceSource = ` |
| 57 |
redis.call("zadd", KEYS[1], ARGV[2], ARGV[3]) |
| 58 |
redis.call("hset", KEYS[2], ARGV[3], ARGV[4]) |
| 59 |
redis.call("expire", KEYS[1], ARGV[1]) |
| 60 |
redis.call("expire", KEYS[2], ARGV[1]) |
| 61 |
` |
| 62 |
|
| 63 |
// Remove client presence. |
| 64 |
// KEYS[1] - presence set key |
| 65 |
// KEYS[2] - presence hash key |
| 66 |
// ARGV[1] - client ID |
| 67 |
remPresenceSource = ` |
| 68 |
redis.call("hdel", KEYS[2], ARGV[1]) |
| 69 |
redis.call("zrem", KEYS[1], ARGV[1]) |
| 70 |
` |
| 71 |
|
| 72 |
// Get presence information. |
| 73 |
// KEYS[1] - presence set key |
| 74 |
// KEYS[2] - presence hash key |
| 75 |
// ARGV[1] - current timestamp in seconds |
| 76 |
presenceSource = ` |
| 77 |
local expired = redis.call("zrangebyscore", KEYS[1], "0", ARGV[1]) |
| 78 |
if #expired > 0 then |
| 79 |
for num = 1, #expired do |
| 80 |
redis.call("hdel", KEYS[2], expired[num]) |
| 81 |
end |
| 82 |
redis.call("zremrangebyscore", KEYS[1], "0", ARGV[1]) |
| 83 |
end |
| 84 |
return redis.call("hgetall", KEYS[2]) |
| 85 |
` |
| 86 |
) |
| 87 |
|
| 88 |
// NewRedisPresenceManager creates new RedisPresenceManager. |
| 89 |
func NewRedisPresenceManager(n *Node, config RedisPresenceManagerConfig) (*RedisPresenceManager, error) { |
| 90 |
if len(config.Shards) == 0 { |
| 91 |
return nil, errors.New("presence: no Redis shards provided in configuration") |
| 92 |
} |
| 93 |
|
| 94 |
if len(config.Shards) > 1 { |
| 95 |
n.Log(NewLogEntry(LogLevelInfo, fmt.Sprintf("presence: Redis sharding enabled: %d shards", len(config.Shards)))) |
| 96 |
} |
| 97 |
|
| 98 |
if config.Prefix == "" { |
| 99 |
config.Prefix = DefaultRedisPresenceManagerPrefix |
| 100 |
} |
| 101 |
|
| 102 |
if config.PresenceTTL == 0 { |
| 103 |
config.PresenceTTL = DefaultRedisPresenceTTL |
| 104 |
} |
| 105 |
|
| 106 |
m := &RedisPresenceManager{ |
| 107 |
node: n, |
| 108 |
shards: config.Shards, |
| 109 |
config: config, |
| 110 |
sharding: len(config.Shards) > 1, |
| 111 |
addPresenceScript: redis.NewScript(2, addPresenceSource), |
| 112 |
remPresenceScript: redis.NewScript(2, remPresenceSource), |
| 113 |
presenceScript: redis.NewScript(2, presenceSource), |
| 114 |
} |
| 115 |
|
| 116 |
for i := range config.Shards { |
| 117 |
config.Shards[i].registerScripts( |
| 118 |
m.addPresenceScript, |
| 119 |
m.remPresenceScript, |
| 120 |
m.presenceScript, |
| 121 |
) |
| 122 |
} |
| 123 |
|
| 124 |
return m, nil |
| 125 |
} |
| 126 |
|
| 127 |
func (m *RedisPresenceManager) getShard(channel string) *RedisShard { |
| 128 |
if !m.sharding { |
| 129 |
return m.shards[0] |
| 130 |
} |
| 131 |
return m.shards[consistentIndex(channel, len(m.shards))] |
| 132 |
} |
| 133 |
|
| 134 |
// AddPresence - see PresenceManager interface description. |
| 135 |
func (m *RedisPresenceManager) AddPresence(ch string, uid string, info *ClientInfo) error { |
| 136 |
return m.addPresence(m.getShard(ch), ch, uid, info) |
| 137 |
} |
| 138 |
|
| 139 |
func (m *RedisPresenceManager) addPresence(s *RedisShard, ch string, uid string, info *ClientInfo) error { |
| 140 |
expire := int(m.config.PresenceTTL.Seconds()) |
| 141 |
infoJSON, err := infoToProto(info).Marshal() |
| 142 |
if err != nil { |
| 143 |
return err |
| 144 |
} |
| 145 |
expireAt := time.Now().Unix() + int64(expire) |
| 146 |
hashKey := m.presenceHashKey(s, ch) |
| 147 |
setKey := m.presenceSetKey(s, ch) |
| 148 |
dr := s.newDataRequest("", m.addPresenceScript, setKey, []interface{}{setKey, hashKey, expire, expireAt, uid, infoJSON}) |
| 149 |
resp := s.getDataResponse(dr) |
| 150 |
return resp.err |
| 151 |
} |
| 152 |
|
| 153 |
// RemovePresence - see PresenceManager interface description. |
| 154 |
func (m *RedisPresenceManager) RemovePresence(ch string, uid string) error { |
| 155 |
return m.removePresence(m.getShard(ch), ch, uid) |
| 156 |
} |
| 157 |
|
| 158 |
func (m *RedisPresenceManager) removePresence(s *RedisShard, ch string, uid string) error { |
| 159 |
hashKey := m.presenceHashKey(s, ch) |
| 160 |
setKey := m.presenceSetKey(s, ch) |
| 161 |
dr := s.newDataRequest("", m.remPresenceScript, setKey, []interface{}{setKey, hashKey, uid}) |
| 162 |
resp := s.getDataResponse(dr) |
| 163 |
return resp.err |
| 164 |
} |
| 165 |
|
| 166 |
// Presence - see PresenceManager interface description. |
| 167 |
func (m *RedisPresenceManager) Presence(ch string) (map[string]*ClientInfo, error) { |
| 168 |
return m.presence(m.getShard(ch), ch) |
| 169 |
} |
| 170 |
|
| 171 |
// Presence - see PresenceManager interface description. |
| 172 |
func (m *RedisPresenceManager) presence(s *RedisShard, ch string) (map[string]*ClientInfo, error) { |
| 173 |
hashKey := m.presenceHashKey(s, ch) |
| 174 |
setKey := m.presenceSetKey(s, ch) |
| 175 |
now := int(time.Now().Unix()) |
| 176 |
dr := s.newDataRequest("", m.presenceScript, setKey, []interface{}{setKey, hashKey, now}) |
| 177 |
resp := s.getDataResponse(dr) |
| 178 |
if resp.err != nil { |
| 179 |
return nil, resp.err |
| 180 |
} |
| 181 |
return mapStringClientInfo(resp.reply, nil) |
| 182 |
} |
| 183 |
|
| 184 |
func mapStringClientInfo(result interface{}, err error) (map[string]*ClientInfo, error) { |
| 185 |
values, err := redis.Values(result, err) |
| 186 |
if err != nil { |
| 187 |
return nil, err |
| 188 |
} |
| 189 |
if len(values)%2 != 0 { |
| 190 |
return nil, errors.New("mapStringClientInfo expects even number of values result") |
| 191 |
} |
| 192 |
m := make(map[string]*ClientInfo, len(values)/2) |
| 193 |
for i := 0; i < len(values); i += 2 { |
| 194 |
key, okKey := values[i].([]byte) |
| 195 |
value, okValue := values[i+1].([]byte) |
| 196 |
if !okKey || !okValue { |
| 197 |
return nil, errors.New("scanMap key not a bulk string value") |
| 198 |
} |
| 199 |
var f protocol.ClientInfo |
| 200 |
err = f.Unmarshal(value) |
| 201 |
if err != nil { |
| 202 |
return nil, errors.New("can not unmarshal value to ClientInfo") |
| 203 |
} |
| 204 |
m[string(key)] = infoFromProto(&f) |
| 205 |
} |
| 206 |
return m, nil |
| 207 |
} |
| 208 |
|
| 209 |
// PresenceStats - see PresenceManager interface description. |
| 210 |
func (m *RedisPresenceManager) PresenceStats(ch string) (PresenceStats, error) { |
| 211 |
presence, err := m.Presence(ch) |
| 212 |
if err != nil { |
| 213 |
return PresenceStats{}, err |
| 214 |
} |
| 215 |
|
| 216 |
numClients := len(presence) |
| 217 |
numUsers := 0 |
| 218 |
uniqueUsers := map[string]struct{}{} |
| 219 |
|
| 220 |
for _, info := range presence { |
| 221 |
userID := info.UserID |
| 222 |
if _, ok := uniqueUsers[userID]; !ok { |
| 223 |
uniqueUsers[userID] = struct{}{} |
| 224 |
numUsers++ |
| 225 |
} |
| 226 |
} |
| 227 |
|
| 228 |
return PresenceStats{ |
| 229 |
NumClients: numClients, |
| 230 |
NumUsers: numUsers, |
| 231 |
}, nil |
| 232 |
} |
| 233 |
|
| 234 |
func (m *RedisPresenceManager) presenceHashKey(s *RedisShard, ch string) channelID { |
| 235 |
if s.useCluster { |
| 236 |
ch = "{" + ch + "}" |
| 237 |
} |
| 238 |
return channelID(m.config.Prefix + ".presence.data." + ch) |
| 239 |
} |
| 240 |
|
| 241 |
func (m *RedisPresenceManager) presenceSetKey(s *RedisShard, ch string) channelID { |
| 242 |
if s.useCluster { |
| 243 |
ch = "{" + ch + "}" |
| 244 |
} |
| 245 |
return channelID(m.config.Prefix + ".presence.expire." + ch) |
| 246 |
} |