consumer.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  1. package consumer
  2. import (
  3. "errors"
  4. "fmt"
  5. "git.beejay.kim/tool/service"
  6. "github.com/confluentinc/confluent-kafka-go/v2/kafka"
  7. "github.com/google/uuid"
  8. "github.com/kelindar/bitmap"
  9. "github.com/rs/zerolog/log"
  10. "strings"
  11. "sync"
  12. "time"
  13. )
  14. const (
  15. flagSubscribed uint32 = iota
  16. flagPaused
  17. )
  18. //goland:noinspection ALL
  19. type _consumer struct {
  20. config *Config
  21. state bitmap.Bitmap
  22. handlers []service.ConsumerHandler
  23. session *kafka.Consumer
  24. }
  25. func New(cfg *Config) (service.Consumer, error) {
  26. var (
  27. c = &_consumer{
  28. config: cfg,
  29. }
  30. err error
  31. )
  32. if cfg == nil {
  33. return nil, fmt.Errorf("config must be provided")
  34. }
  35. opts := &kafka.ConfigMap{
  36. "broker.address.family": "v4",
  37. "bootstrap.servers": strings.Join(c.config.Hosts, ","),
  38. "group.id": c.config.Group,
  39. "partition.assignment.strategy": "cooperative-sticky",
  40. "auto.offset.reset": "earliest",
  41. "log_level": 0,
  42. }
  43. if c.session, err = kafka.NewConsumer(opts); err != nil {
  44. return nil, err
  45. }
  46. return c, nil
  47. }
  48. func (c *_consumer) ID() uuid.UUID {
  49. return uuid.NewSHA1(uuid.NameSpaceDNS, []byte("consumer.kafka"))
  50. }
  51. func (c *_consumer) Subscribed() bool {
  52. return c.state.Contains(flagSubscribed)
  53. }
  54. func (c *_consumer) Paused() bool {
  55. return c.state.Contains(flagPaused)
  56. }
  57. func (c *_consumer) SetPause(is bool) error {
  58. if is {
  59. c.state.Set(flagPaused)
  60. } else {
  61. c.state.Remove(flagPaused)
  62. }
  63. return nil
  64. }
  65. func (c *_consumer) RegisterHandlers(handlers ...service.ConsumerHandler) {
  66. c.handlers = append(c.handlers, handlers...)
  67. }
  68. func (c *_consumer) Subscribe(topics []string, ch chan *kafka.Message) error {
  69. if c.Subscribed() {
  70. return fmt.Errorf("illegal state: already subscribed")
  71. }
  72. if err := c.session.SubscribeTopics(topics, rebalanceCallback); err != nil {
  73. return err
  74. }
  75. c.state.Set(flagSubscribed)
  76. for c.Subscribed() {
  77. for c.Paused() {
  78. time.Sleep(100 * time.Millisecond)
  79. }
  80. message, err := c.poll()
  81. if err != nil {
  82. // silently wait for a next message
  83. if errors.Is(err, ErrNoMessage) {
  84. continue
  85. }
  86. log.Debug().
  87. Str("service", "consumer").
  88. Err(err).
  89. Send()
  90. c.state.Remove(flagSubscribed)
  91. return err
  92. }
  93. if message != nil {
  94. ch <- message
  95. }
  96. }
  97. log.Debug().
  98. Str("service", "consumer").
  99. Msg("consumer gracefully closed")
  100. return nil
  101. }
  102. func (c *_consumer) Close() error {
  103. if c.Subscribed() {
  104. c.state.Remove(flagSubscribed)
  105. }
  106. var wg sync.WaitGroup
  107. wg.Add(1)
  108. go func() {
  109. defer wg.Done()
  110. if c.session != nil {
  111. time.Sleep(time.Second)
  112. _ = c.session.Close() //nolint:errcheck
  113. }
  114. }()
  115. wg.Wait()
  116. return nil
  117. }
  118. func (c *_consumer) poll() (*kafka.Message, error) {
  119. var (
  120. ev = c.session.Poll(c.config.Timeout)
  121. err error
  122. )
  123. switch e := ev.(type) {
  124. case *kafka.Message:
  125. for i := range c.handlers {
  126. if err = c.handlers[i](e); err != nil {
  127. return nil, err
  128. }
  129. }
  130. return e, nil
  131. case kafka.Error:
  132. log.Debug().
  133. Str("service", "consumer").
  134. Err(e).
  135. Send()
  136. if e.Code() == kafka.ErrAllBrokersDown {
  137. c.state.Remove(flagSubscribed)
  138. }
  139. return nil, e
  140. default:
  141. if e != nil {
  142. log.Debug().
  143. Str("service", "consumer").
  144. Any("event", e).
  145. Send()
  146. }
  147. return nil, ErrNoMessage
  148. }
  149. }
  150. // rebalanceCallback is called on each group rebalance to assign additional
  151. // partitions, or remove existing partitions, from the consumer's current
  152. // assignment.
  153. //
  154. // The application may use this optional callback to inspect the assignment,
  155. // alter the initial start offset (the .Offset field of each assigned partition),
  156. // and read/write offsets to commit to an alternative store outside of Kafka.
  157. func rebalanceCallback(c *kafka.Consumer, event kafka.Event) error {
  158. switch ev := event.(type) {
  159. case kafka.AssignedPartitions:
  160. log.Debug().
  161. Str("service", "consumer").
  162. Msgf("%s rebalance: %d new partition(s) assigned: %v",
  163. c.GetRebalanceProtocol(),
  164. len(ev.Partitions),
  165. ev.Partitions)
  166. // The application may update the start .Offset of each
  167. // assigned partition and then call IncrementalAssign().
  168. if err := c.IncrementalAssign(ev.Partitions); err != nil {
  169. panic(err)
  170. }
  171. case kafka.RevokedPartitions:
  172. log.Debug().
  173. Str("service", "consumer").
  174. Msgf("%s rebalance: %d partition(s) revoked: %v",
  175. c.GetRebalanceProtocol(),
  176. len(ev.Partitions),
  177. ev.Partitions)
  178. // Usually, the rebalance callback for `RevokedPartitions` is called
  179. // just before the partitions are revoked. We can be certain that a
  180. // partition being revoked is not yet owned by any other consumer.
  181. // This way, logic like storing any pending offsets or committing
  182. // offsets can be handled.
  183. // However, there can be cases where the assignment is lost
  184. // involuntarily. In this case, the partition might already be owned
  185. // by another consumer, and operations including committing
  186. // offsets may not work.
  187. if c.AssignmentLost() {
  188. // Our consumer has been kicked out of the group and the
  189. // entire assignment is thus lost.
  190. log.Debug().
  191. Str("service", "consumer").
  192. Msg("Assignment lost involuntarily, commit may fail")
  193. }
  194. // The client automatically calls IncrementalUnassign() unless
  195. // the callback has already called that method.
  196. default:
  197. log.Debug().
  198. Str("service", "consumer").
  199. Msgf("unxpected event type: %v", event)
  200. }
  201. return nil
  202. }