pubsub.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. package redis
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "strings"
  7. "sync"
  8. "time"
  9. "github.com/go-redis/redis/internal"
  10. "github.com/go-redis/redis/internal/pool"
  11. "github.com/go-redis/redis/internal/proto"
  12. )
  13. const pingTimeout = 30 * time.Second
  14. var errPingTimeout = errors.New("redis: ping timeout")
  15. // PubSub implements Pub/Sub commands as described in
  16. // http://redis.io/topics/pubsub. Message receiving is NOT safe
  17. // for concurrent use by multiple goroutines.
  18. //
  19. // PubSub automatically reconnects to Redis Server and resubscribes
  20. // to the channels in case of network errors.
  21. type PubSub struct {
  22. opt *Options
  23. newConn func([]string) (*pool.Conn, error)
  24. closeConn func(*pool.Conn) error
  25. mu sync.Mutex
  26. cn *pool.Conn
  27. channels map[string]struct{}
  28. patterns map[string]struct{}
  29. closed bool
  30. exit chan struct{}
  31. cmd *Cmd
  32. chOnce sync.Once
  33. msgCh chan *Message
  34. allCh chan interface{}
  35. ping chan struct{}
  36. }
  37. func (c *PubSub) String() string {
  38. channels := mapKeys(c.channels)
  39. channels = append(channels, mapKeys(c.patterns)...)
  40. return fmt.Sprintf("PubSub(%s)", strings.Join(channels, ", "))
  41. }
  42. func (c *PubSub) init() {
  43. c.exit = make(chan struct{})
  44. }
  45. func (c *PubSub) connWithLock() (*pool.Conn, error) {
  46. c.mu.Lock()
  47. cn, err := c.conn(nil)
  48. c.mu.Unlock()
  49. return cn, err
  50. }
  51. func (c *PubSub) conn(newChannels []string) (*pool.Conn, error) {
  52. if c.closed {
  53. return nil, pool.ErrClosed
  54. }
  55. if c.cn != nil {
  56. return c.cn, nil
  57. }
  58. channels := mapKeys(c.channels)
  59. channels = append(channels, newChannels...)
  60. cn, err := c.newConn(channels)
  61. if err != nil {
  62. return nil, err
  63. }
  64. if err := c.resubscribe(cn); err != nil {
  65. _ = c.closeConn(cn)
  66. return nil, err
  67. }
  68. c.cn = cn
  69. return cn, nil
  70. }
  71. func (c *PubSub) writeCmd(ctx context.Context, cn *pool.Conn, cmd Cmder) error {
  72. return cn.WithWriter(ctx, c.opt.WriteTimeout, func(wr *proto.Writer) error {
  73. return writeCmd(wr, cmd)
  74. })
  75. }
  76. func (c *PubSub) resubscribe(cn *pool.Conn) error {
  77. var firstErr error
  78. if len(c.channels) > 0 {
  79. firstErr = c._subscribe(cn, "subscribe", mapKeys(c.channels))
  80. }
  81. if len(c.patterns) > 0 {
  82. err := c._subscribe(cn, "psubscribe", mapKeys(c.patterns))
  83. if err != nil && firstErr == nil {
  84. firstErr = err
  85. }
  86. }
  87. return firstErr
  88. }
  89. func mapKeys(m map[string]struct{}) []string {
  90. s := make([]string, len(m))
  91. i := 0
  92. for k := range m {
  93. s[i] = k
  94. i++
  95. }
  96. return s
  97. }
  98. func (c *PubSub) _subscribe(
  99. cn *pool.Conn, redisCmd string, channels []string,
  100. ) error {
  101. args := make([]interface{}, 0, 1+len(channels))
  102. args = append(args, redisCmd)
  103. for _, channel := range channels {
  104. args = append(args, channel)
  105. }
  106. cmd := NewSliceCmd(args...)
  107. return c.writeCmd(context.TODO(), cn, cmd)
  108. }
  109. func (c *PubSub) releaseConnWithLock(cn *pool.Conn, err error, allowTimeout bool) {
  110. c.mu.Lock()
  111. c.releaseConn(cn, err, allowTimeout)
  112. c.mu.Unlock()
  113. }
  114. func (c *PubSub) releaseConn(cn *pool.Conn, err error, allowTimeout bool) {
  115. if c.cn != cn {
  116. return
  117. }
  118. if isBadConn(err, allowTimeout) {
  119. c.reconnect(err)
  120. }
  121. }
  122. func (c *PubSub) reconnect(reason error) {
  123. _ = c.closeTheCn(reason)
  124. _, _ = c.conn(nil)
  125. }
  126. func (c *PubSub) closeTheCn(reason error) error {
  127. if c.cn == nil {
  128. return nil
  129. }
  130. if !c.closed {
  131. internal.Logger.Printf("redis: discarding bad PubSub connection: %s", reason)
  132. }
  133. err := c.closeConn(c.cn)
  134. c.cn = nil
  135. return err
  136. }
  137. func (c *PubSub) Close() error {
  138. c.mu.Lock()
  139. defer c.mu.Unlock()
  140. if c.closed {
  141. return pool.ErrClosed
  142. }
  143. c.closed = true
  144. close(c.exit)
  145. return c.closeTheCn(pool.ErrClosed)
  146. }
  147. // Subscribe the client to the specified channels. It returns
  148. // empty subscription if there are no channels.
  149. func (c *PubSub) Subscribe(channels ...string) error {
  150. c.mu.Lock()
  151. defer c.mu.Unlock()
  152. err := c.subscribe("subscribe", channels...)
  153. if c.channels == nil {
  154. c.channels = make(map[string]struct{})
  155. }
  156. for _, s := range channels {
  157. c.channels[s] = struct{}{}
  158. }
  159. return err
  160. }
  161. // PSubscribe the client to the given patterns. It returns
  162. // empty subscription if there are no patterns.
  163. func (c *PubSub) PSubscribe(patterns ...string) error {
  164. c.mu.Lock()
  165. defer c.mu.Unlock()
  166. err := c.subscribe("psubscribe", patterns...)
  167. if c.patterns == nil {
  168. c.patterns = make(map[string]struct{})
  169. }
  170. for _, s := range patterns {
  171. c.patterns[s] = struct{}{}
  172. }
  173. return err
  174. }
  175. // Unsubscribe the client from the given channels, or from all of
  176. // them if none is given.
  177. func (c *PubSub) Unsubscribe(channels ...string) error {
  178. c.mu.Lock()
  179. defer c.mu.Unlock()
  180. for _, channel := range channels {
  181. delete(c.channels, channel)
  182. }
  183. err := c.subscribe("unsubscribe", channels...)
  184. return err
  185. }
  186. // PUnsubscribe the client from the given patterns, or from all of
  187. // them if none is given.
  188. func (c *PubSub) PUnsubscribe(patterns ...string) error {
  189. c.mu.Lock()
  190. defer c.mu.Unlock()
  191. for _, pattern := range patterns {
  192. delete(c.patterns, pattern)
  193. }
  194. err := c.subscribe("punsubscribe", patterns...)
  195. return err
  196. }
  197. func (c *PubSub) subscribe(redisCmd string, channels ...string) error {
  198. cn, err := c.conn(channels)
  199. if err != nil {
  200. return err
  201. }
  202. err = c._subscribe(cn, redisCmd, channels)
  203. c.releaseConn(cn, err, false)
  204. return err
  205. }
  206. func (c *PubSub) Ping(payload ...string) error {
  207. args := []interface{}{"ping"}
  208. if len(payload) == 1 {
  209. args = append(args, payload[0])
  210. }
  211. cmd := NewCmd(args...)
  212. cn, err := c.connWithLock()
  213. if err != nil {
  214. return err
  215. }
  216. err = c.writeCmd(context.TODO(), cn, cmd)
  217. c.releaseConnWithLock(cn, err, false)
  218. return err
  219. }
  220. // Subscription received after a successful subscription to channel.
  221. type Subscription struct {
  222. // Can be "subscribe", "unsubscribe", "psubscribe" or "punsubscribe".
  223. Kind string
  224. // Channel name we have subscribed to.
  225. Channel string
  226. // Number of channels we are currently subscribed to.
  227. Count int
  228. }
  229. func (m *Subscription) String() string {
  230. return fmt.Sprintf("%s: %s", m.Kind, m.Channel)
  231. }
  232. // Message received as result of a PUBLISH command issued by another client.
  233. type Message struct {
  234. Channel string
  235. Pattern string
  236. Payload string
  237. }
  238. func (m *Message) String() string {
  239. return fmt.Sprintf("Message<%s: %s>", m.Channel, m.Payload)
  240. }
  241. // Pong received as result of a PING command issued by another client.
  242. type Pong struct {
  243. Payload string
  244. }
  245. func (p *Pong) String() string {
  246. if p.Payload != "" {
  247. return fmt.Sprintf("Pong<%s>", p.Payload)
  248. }
  249. return "Pong"
  250. }
  251. func (c *PubSub) newMessage(reply interface{}) (interface{}, error) {
  252. switch reply := reply.(type) {
  253. case string:
  254. return &Pong{
  255. Payload: reply,
  256. }, nil
  257. case []interface{}:
  258. switch kind := reply[0].(string); kind {
  259. case "subscribe", "unsubscribe", "psubscribe", "punsubscribe":
  260. return &Subscription{
  261. Kind: kind,
  262. Channel: reply[1].(string),
  263. Count: int(reply[2].(int64)),
  264. }, nil
  265. case "message":
  266. return &Message{
  267. Channel: reply[1].(string),
  268. Payload: reply[2].(string),
  269. }, nil
  270. case "pmessage":
  271. return &Message{
  272. Pattern: reply[1].(string),
  273. Channel: reply[2].(string),
  274. Payload: reply[3].(string),
  275. }, nil
  276. case "pong":
  277. return &Pong{
  278. Payload: reply[1].(string),
  279. }, nil
  280. default:
  281. return nil, fmt.Errorf("redis: unsupported pubsub message: %q", kind)
  282. }
  283. default:
  284. return nil, fmt.Errorf("redis: unsupported pubsub message: %#v", reply)
  285. }
  286. }
  287. // ReceiveTimeout acts like Receive but returns an error if message
  288. // is not received in time. This is low-level API and in most cases
  289. // Channel should be used instead.
  290. func (c *PubSub) ReceiveTimeout(timeout time.Duration) (interface{}, error) {
  291. if c.cmd == nil {
  292. c.cmd = NewCmd()
  293. }
  294. cn, err := c.connWithLock()
  295. if err != nil {
  296. return nil, err
  297. }
  298. err = cn.WithReader(context.TODO(), timeout, func(rd *proto.Reader) error {
  299. return c.cmd.readReply(rd)
  300. })
  301. c.releaseConnWithLock(cn, err, timeout > 0)
  302. if err != nil {
  303. return nil, err
  304. }
  305. return c.newMessage(c.cmd.Val())
  306. }
  307. // Receive returns a message as a Subscription, Message, Pong or error.
  308. // See PubSub example for details. This is low-level API and in most cases
  309. // Channel should be used instead.
  310. func (c *PubSub) Receive() (interface{}, error) {
  311. return c.ReceiveTimeout(0)
  312. }
  313. // ReceiveMessage returns a Message or error ignoring Subscription and Pong
  314. // messages. This is low-level API and in most cases Channel should be used
  315. // instead.
  316. func (c *PubSub) ReceiveMessage() (*Message, error) {
  317. for {
  318. msg, err := c.Receive()
  319. if err != nil {
  320. return nil, err
  321. }
  322. switch msg := msg.(type) {
  323. case *Subscription:
  324. // Ignore.
  325. case *Pong:
  326. // Ignore.
  327. case *Message:
  328. return msg, nil
  329. default:
  330. err := fmt.Errorf("redis: unknown message: %T", msg)
  331. return nil, err
  332. }
  333. }
  334. }
  335. // Channel returns a Go channel for concurrently receiving messages.
  336. // The channel is closed together with the PubSub. If the Go channel
  337. // is blocked full for 30 seconds the message is dropped.
  338. // Receive* APIs can not be used after channel is created.
  339. //
  340. // go-redis periodically sends ping messages to test connection health
  341. // and re-subscribes if ping can not not received for 30 seconds.
  342. func (c *PubSub) Channel() <-chan *Message {
  343. return c.ChannelSize(100)
  344. }
  345. // ChannelSize is like Channel, but creates a Go channel
  346. // with specified buffer size.
  347. func (c *PubSub) ChannelSize(size int) <-chan *Message {
  348. c.chOnce.Do(func() {
  349. c.initPing()
  350. c.initMsgChan(size)
  351. })
  352. if c.msgCh == nil {
  353. err := fmt.Errorf("redis: Channel can't be called after ChannelWithSubscriptions")
  354. panic(err)
  355. }
  356. if cap(c.msgCh) != size {
  357. err := fmt.Errorf("redis: PubSub.Channel size can not be changed once created")
  358. panic(err)
  359. }
  360. return c.msgCh
  361. }
  362. // ChannelWithSubscriptions is like Channel, but message type can be either
  363. // *Subscription or *Message. Subscription messages can be used to detect
  364. // reconnections.
  365. //
  366. // ChannelWithSubscriptions can not be used together with Channel or ChannelSize.
  367. func (c *PubSub) ChannelWithSubscriptions(size int) <-chan interface{} {
  368. c.chOnce.Do(func() {
  369. c.initPing()
  370. c.initAllChan(size)
  371. })
  372. if c.allCh == nil {
  373. err := fmt.Errorf("redis: ChannelWithSubscriptions can't be called after Channel")
  374. panic(err)
  375. }
  376. if cap(c.allCh) != size {
  377. err := fmt.Errorf("redis: PubSub.Channel size can not be changed once created")
  378. panic(err)
  379. }
  380. return c.allCh
  381. }
  382. func (c *PubSub) initPing() {
  383. c.ping = make(chan struct{}, 1)
  384. go func() {
  385. timer := time.NewTimer(pingTimeout)
  386. timer.Stop()
  387. healthy := true
  388. for {
  389. timer.Reset(pingTimeout)
  390. select {
  391. case <-c.ping:
  392. healthy = true
  393. if !timer.Stop() {
  394. <-timer.C
  395. }
  396. case <-timer.C:
  397. pingErr := c.Ping()
  398. if healthy {
  399. healthy = false
  400. } else {
  401. if pingErr == nil {
  402. pingErr = errPingTimeout
  403. }
  404. c.mu.Lock()
  405. c.reconnect(pingErr)
  406. healthy = true
  407. c.mu.Unlock()
  408. }
  409. case <-c.exit:
  410. return
  411. }
  412. }
  413. }()
  414. }
  415. // initMsgChan must be in sync with initAllChan.
  416. func (c *PubSub) initMsgChan(size int) {
  417. c.msgCh = make(chan *Message, size)
  418. go func() {
  419. timer := time.NewTimer(pingTimeout)
  420. timer.Stop()
  421. var errCount int
  422. for {
  423. msg, err := c.Receive()
  424. if err != nil {
  425. if err == pool.ErrClosed {
  426. close(c.msgCh)
  427. return
  428. }
  429. if errCount > 0 {
  430. time.Sleep(c.retryBackoff(errCount))
  431. }
  432. errCount++
  433. continue
  434. }
  435. errCount = 0
  436. // Any message is as good as a ping.
  437. select {
  438. case c.ping <- struct{}{}:
  439. default:
  440. }
  441. switch msg := msg.(type) {
  442. case *Subscription:
  443. // Ignore.
  444. case *Pong:
  445. // Ignore.
  446. case *Message:
  447. timer.Reset(pingTimeout)
  448. select {
  449. case c.msgCh <- msg:
  450. if !timer.Stop() {
  451. <-timer.C
  452. }
  453. case <-timer.C:
  454. internal.Logger.Printf(
  455. "redis: %s channel is full for %s (message is dropped)", c, pingTimeout)
  456. }
  457. default:
  458. internal.Logger.Printf("redis: unknown message type: %T", msg)
  459. }
  460. }
  461. }()
  462. }
  463. // initAllChan must be in sync with initMsgChan.
  464. func (c *PubSub) initAllChan(size int) {
  465. c.allCh = make(chan interface{}, size)
  466. go func() {
  467. timer := time.NewTimer(pingTimeout)
  468. timer.Stop()
  469. var errCount int
  470. for {
  471. msg, err := c.Receive()
  472. if err != nil {
  473. if err == pool.ErrClosed {
  474. close(c.allCh)
  475. return
  476. }
  477. if errCount > 0 {
  478. time.Sleep(c.retryBackoff(errCount))
  479. }
  480. errCount++
  481. continue
  482. }
  483. errCount = 0
  484. // Any message is as good as a ping.
  485. select {
  486. case c.ping <- struct{}{}:
  487. default:
  488. }
  489. switch msg := msg.(type) {
  490. case *Subscription:
  491. c.sendMessage(msg, timer)
  492. case *Pong:
  493. // Ignore.
  494. case *Message:
  495. c.sendMessage(msg, timer)
  496. default:
  497. internal.Logger.Printf("redis: unknown message type: %T", msg)
  498. }
  499. }
  500. }()
  501. }
  502. func (c *PubSub) sendMessage(msg interface{}, timer *time.Timer) {
  503. timer.Reset(pingTimeout)
  504. select {
  505. case c.allCh <- msg:
  506. if !timer.Stop() {
  507. <-timer.C
  508. }
  509. case <-timer.C:
  510. internal.Logger.Printf(
  511. "redis: %s channel is full for %s (message is dropped)", c, pingTimeout)
  512. }
  513. }
  514. func (c *PubSub) retryBackoff(attempt int) time.Duration {
  515. return internal.RetryBackoff(attempt, c.opt.MinRetryBackoff, c.opt.MaxRetryBackoff)
  516. }