consumer.go 5.0 KB

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