Debian Codegraph @

pubsub.go

raw
1 package redis
2
3 import (
4 "fmt"
5 "net"
6 "sync"
7 "time"
8
9 "gopkg.in/redis.v5/internal"
10 "gopkg.in/redis.v5/internal/pool"
11 )
12
13 // PubSub implements Pub/Sub commands as described in
14 // http://redis.io/topics/pubsub. It's NOT safe for concurrent use by
15 // multiple goroutines.
16 type PubSub struct {
17 base baseClient
18 cmd *Cmd
19
20 mu sync.Mutex
21 channels []string
22 patterns []string
23 }
24
25 func (c *PubSub) conn() (*pool.Conn, bool, error) {
26 cn, isNew, err := c.base.conn()
27 if err != nil {
28 return nil, false, err
29 }
30 if isNew {
31 c.resubscribe()
32 }
33 return cn, isNew, nil
34 }
35
36 func (c *PubSub) putConn(cn *pool.Conn, err error) {
37 c.base.putConn(cn, err, true)
38 }
39
40 func (c *PubSub) subscribe(redisCmd string, channels ...string) error {
41 args := make([]interface{}, 1+len(channels))
42 args[0] = redisCmd
43 for i, channel := range channels {
44 args[1+i] = channel
45 }
46 cmd := NewSliceCmd(args...)
47
48 cn, _, err := c.conn()
49 if err != nil {
50 return err
51 }
52
53 cn.SetWriteTimeout(c.base.opt.WriteTimeout)
54 err = writeCmd(cn, cmd)
55 c.putConn(cn, err)
56 return err
57 }
58
59 // Subscribes the client to the specified channels.
60 func (c *PubSub) Subscribe(channels ...string) error {
61 err := c.subscribe("SUBSCRIBE", channels...)
62 if err == nil {
63 c.channels = appendIfNotExists(c.channels, channels...)
64 }
65 return err
66 }
67
68 // Subscribes the client to the given patterns.
69 func (c *PubSub) PSubscribe(patterns ...string) error {
70 err := c.subscribe("PSUBSCRIBE", patterns...)
71 if err == nil {
72 c.patterns = appendIfNotExists(c.patterns, patterns...)
73 }
74 return err
75 }
76
77 // Unsubscribes the client from the given channels, or from all of
78 // them if none is given.
79 func (c *PubSub) Unsubscribe(channels ...string) error {
80 err := c.subscribe("UNSUBSCRIBE", channels...)
81 if err == nil {
82 c.channels = remove(c.channels, channels...)
83 }
84 return err
85 }
86
87 // Unsubscribes the client from the given patterns, or from all of
88 // them if none is given.
89 func (c *PubSub) PUnsubscribe(patterns ...string) error {
90 err := c.subscribe("PUNSUBSCRIBE", patterns...)
91 if err == nil {
92 c.patterns = remove(c.patterns, patterns...)
93 }
94 return err
95 }
96
97 func (c *PubSub) Close() error {
98 return c.base.Close()
99 }
100
101 func (c *PubSub) Ping(payload ...string) error {
102 args := []interface{}{"PING"}
103 if len(payload) == 1 {
104 args = append(args, payload[0])
105 }
106 cmd := NewCmd(args...)
107
108 cn, _, err := c.conn()
109 if err != nil {
110 return err
111 }
112
113 cn.SetWriteTimeout(c.base.opt.WriteTimeout)
114 err = writeCmd(cn, cmd)
115 c.putConn(cn, err)
116 return err
117 }
118
119 // Message received after a successful subscription to channel.
120 type Subscription struct {
121 // Can be "subscribe", "unsubscribe", "psubscribe" or "punsubscribe".
122 Kind string
123 // Channel name we have subscribed to.
124 Channel string
125 // Number of channels we are currently subscribed to.
126 Count int
127 }
128
129 func (m *Subscription) String() string {
130 return fmt.Sprintf("%s: %s", m.Kind, m.Channel)
131 }
132
133 // Message received as result of a PUBLISH command issued by another client.
134 type Message struct {
135 Channel string
136 Pattern string
137 Payload string
138 }
139
140 func (m *Message) String() string {
141 return fmt.Sprintf("Message<%s: %s>", m.Channel, m.Payload)
142 }
143
144 // Pong received as result of a PING command issued by another client.
145 type Pong struct {
146 Payload string
147 }
148
149 func (p *Pong) String() string {
150 if p.Payload != "" {
151 return fmt.Sprintf("Pong<%s>", p.Payload)
152 }
153 return "Pong"
154 }
155
156 func (c *PubSub) newMessage(reply interface{}) (interface{}, error) {
157 switch reply := reply.(type) {
158 case string:
159 return &Pong{
160 Payload: reply,
161 }, nil
162 case []interface{}:
163 switch kind := reply[0].(string); kind {
164 case "subscribe", "unsubscribe", "psubscribe", "punsubscribe":
165 return &Subscription{
166 Kind: kind,
167 Channel: reply[1].(string),
168 Count: int(reply[2].(int64)),
169 }, nil
170 case "message":
171 return &Message{
172 Channel: reply[1].(string),
173 Payload: reply[2].(string),
174 }, nil
175 case "pmessage":
176 return &Message{
177 Pattern: reply[1].(string),
178 Channel: reply[2].(string),
179 Payload: reply[3].(string),
180 }, nil
181 case "pong":
182 return &Pong{
183 Payload: reply[1].(string),
184 }, nil
185 default:
186 return nil, fmt.Errorf("redis: unsupported pubsub message: %q", kind)
187 }
188 default:
189 return nil, fmt.Errorf("redis: unsupported pubsub message: %#v", reply)
190 }
191 }
192
193 // ReceiveTimeout acts like Receive but returns an error if message
194 // is not received in time. This is low-level API and most clients
195 // should use ReceiveMessage.
196 func (c *PubSub) ReceiveTimeout(timeout time.Duration) (interface{}, error) {
197 if c.cmd == nil {
198 c.cmd = NewCmd()
199 }
200
201 cn, _, err := c.conn()
202 if err != nil {
203 return nil, err
204 }
205
206 cn.SetReadTimeout(timeout)
207 err = c.cmd.readReply(cn)
208 c.putConn(cn, err)
209 if err != nil {
210 return nil, err
211 }
212
213 return c.newMessage(c.cmd.Val())
214 }
215
216 // Receive returns a message as a Subscription, Message, Pong or error.
217 // See PubSub example for details. This is low-level API and most clients
218 // should use ReceiveMessage.
219 func (c *PubSub) Receive() (interface{}, error) {
220 return c.ReceiveTimeout(0)
221 }
222
223 // ReceiveMessage returns a Message or error ignoring Subscription or Pong
224 // messages. It automatically reconnects to Redis Server and resubscribes
225 // to channels in case of network errors.
226 func (c *PubSub) ReceiveMessage() (*Message, error) {
227 return c.receiveMessage(5 * time.Second)
228 }
229
230 func (c *PubSub) receiveMessage(timeout time.Duration) (*Message, error) {
231 var errNum uint
232 for {
233 msgi, err := c.ReceiveTimeout(timeout)
234 if err != nil {
235 if !internal.IsNetworkError(err) {
236 return nil, err
237 }
238
239 errNum++
240 if errNum < 3 {
241 if netErr, ok := err.(net.Error); ok && netErr.Timeout() {
242 err := c.Ping()
243 if err != nil {
244 internal.Logf("PubSub.Ping failed: %s", err)
245 }
246 }
247 } else {
248 // 3 consequent errors - connection is broken or
249 // Redis Server is down.
250 // Sleep to not exceed max number of open connections.
251 time.Sleep(time.Second)
252 }
253 continue
254 }
255
256 // Reset error number, because we received a message.
257 errNum = 0
258
259 switch msg := msgi.(type) {
260 case *Subscription:
261 // Ignore.
262 case *Pong:
263 // Ignore.
264 case *Message:
265 return msg, nil
266 default:
267 return nil, fmt.Errorf("redis: unknown message: %T", msgi)
268 }
269 }
270 }
271
272 func (c *PubSub) resubscribe() {
273 if len(c.channels) > 0 {
274 if err := c.Subscribe(c.channels...); err != nil {
275 internal.Logf("Subscribe failed: %s", err)
276 }
277 }
278 if len(c.patterns) > 0 {
279 if err := c.PSubscribe(c.patterns...); err != nil {
280 internal.Logf("PSubscribe failed: %s", err)
281 }
282 }
283 }
284
285 func remove(ss []string, es ...string) []string {
286 if len(es) == 0 {
287 return ss[:0]
288 }
289 for _, e := range es {
290 for i, s := range ss {
291 if s == e {
292 ss = append(ss[:i], ss[i+1:]...)
293 break
294 }
295 }
296 }
297 return ss
298 }
299
300 func appendIfNotExists(ss []string, es ...string) []string {
301 loop:
302 for _, e := range es {
303 for _, s := range ss {
304 if s == e {
305 continue loop
306 }
307 }
308 ss = append(ss, e)
309 }
310 return ss
311 }