consumer.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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) SetPause(f bool) {
  55. if f {
  56. c.state.Set(flagPaused)
  57. } else {
  58. c.state.Remove(flagPaused)
  59. }
  60. }
  61. func (c *_consumer) RegisterHandlers(handlers ...service.ConsumerHandler) {
  62. c.handlers = append(c.handlers, handlers...)
  63. }
  64. func (c *_consumer) Subscribe(topics []string, ch chan *kafka.Message, opts service.ConsumerOptions) error {
  65. if c.Subscribed() {
  66. return fmt.Errorf("illegal state: already subscribed")
  67. }
  68. if err := c.session.SubscribeTopics(topics, rebalanceCallback); err != nil {
  69. return err
  70. }
  71. c.state.Set(flagSubscribed)
  72. for c.Subscribed() && !c.state.Contains(flagPaused) {
  73. message, err := c.poll()
  74. if err != nil {
  75. // silently wait for a next message
  76. if errors.Is(err, ErrNoMessage) {
  77. continue
  78. }
  79. log.Debug().
  80. Str("service", "consumer").
  81. Err(err).
  82. Send()
  83. c.state.Remove(flagSubscribed)
  84. return err
  85. }
  86. if message != nil {
  87. if opts.Counter != nil {
  88. opts.Counter.Inc()
  89. }
  90. ch <- message
  91. }
  92. }
  93. log.Debug().Msg("consumer closed gracefully")
  94. return nil
  95. }
  96. func (c *_consumer) Close() error {
  97. if c.Subscribed() {
  98. c.state.Remove(flagSubscribed)
  99. }
  100. var wg sync.WaitGroup
  101. wg.Add(1)
  102. go func() {
  103. defer wg.Done()
  104. if c.session != nil {
  105. time.Sleep(time.Second)
  106. _ = c.session.Close() //nolint:errcheck
  107. }
  108. }()
  109. wg.Wait()
  110. return nil
  111. }
  112. func (c *_consumer) poll() (*kafka.Message, error) {
  113. var (
  114. ev = c.session.Poll(c.config.Timeout)
  115. err error
  116. )
  117. switch e := ev.(type) {
  118. case *kafka.Message:
  119. for i := range c.handlers {
  120. if err = c.handlers[i](e); err != nil {
  121. return nil, err
  122. }
  123. }
  124. return e, nil
  125. case kafka.Error:
  126. log.Debug().
  127. Str("service", "consumer").
  128. Err(e).
  129. Send()
  130. if e.Code() == kafka.ErrAllBrokersDown {
  131. c.state.Remove(flagSubscribed)
  132. }
  133. return nil, e
  134. default:
  135. if e != nil {
  136. log.Debug().
  137. Str("service", "consumer").
  138. Any("event", e).
  139. Send()
  140. }
  141. return nil, ErrNoMessage
  142. }
  143. }
  144. // rebalanceCallback is called on each group rebalance to assign additional
  145. // partitions, or remove existing partitions, from the consumer's current
  146. // assignment.
  147. //
  148. // The application may use this optional callback to inspect the assignment,
  149. // alter the initial start offset (the .Offset field of each assigned partition),
  150. // and read/write offsets to commit to an alternative store outside of Kafka.
  151. func rebalanceCallback(c *kafka.Consumer, event kafka.Event) error {
  152. switch ev := event.(type) {
  153. case kafka.AssignedPartitions:
  154. log.Debug().
  155. Str("service", "consumer").
  156. Msgf("%s rebalance: %d new partition(s) assigned: %v",
  157. c.GetRebalanceProtocol(),
  158. len(ev.Partitions),
  159. ev.Partitions)
  160. // The application may update the start .Offset of each
  161. // assigned partition and then call IncrementalAssign().
  162. if err := c.IncrementalAssign(ev.Partitions); err != nil {
  163. panic(err)
  164. }
  165. case kafka.RevokedPartitions:
  166. log.Debug().
  167. Str("service", "consumer").
  168. Msgf("%s rebalance: %d partition(s) revoked: %v",
  169. c.GetRebalanceProtocol(),
  170. len(ev.Partitions),
  171. ev.Partitions)
  172. // Usually, the rebalance callback for `RevokedPartitions` is called
  173. // just before the partitions are revoked. We can be certain that a
  174. // partition being revoked is not yet owned by any other consumer.
  175. // This way, logic like storing any pending offsets or committing
  176. // offsets can be handled.
  177. // However, there can be cases where the assignment is lost
  178. // involuntarily. In this case, the partition might already be owned
  179. // by another consumer, and operations including committing
  180. // offsets may not work.
  181. if c.AssignmentLost() {
  182. // Our consumer has been kicked out of the group and the
  183. // entire assignment is thus lost.
  184. log.Debug().
  185. Str("service", "consumer").
  186. Msg("Assignment lost involuntarily, commit may fail")
  187. }
  188. // The client automatically calls IncrementalUnassign() unless
  189. // the callback has already called that method.
  190. default:
  191. log.Debug().
  192. Str("service", "consumer").
  193. Msgf("unxpected event type: %v", event)
  194. }
  195. return nil
  196. }