consumer.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. package sarama
  2. // OffsetMethod is passed in ConsumerConfig to tell the consumer how to determine the starting offset.
  3. type OffsetMethod int
  4. const (
  5. // OffsetMethodManual causes the consumer to interpret the OffsetValue in the ConsumerConfig as the
  6. // offset at which to start, allowing the user to manually specify their desired starting offset.
  7. OffsetMethodManual OffsetMethod = iota
  8. // OffsetMethodNewest causes the consumer to start at the most recent available offset, as
  9. // determined by querying the broker.
  10. OffsetMethodNewest
  11. // OffsetMethodOldest causes the consumer to start at the oldest available offset, as
  12. // determined by querying the broker.
  13. OffsetMethodOldest
  14. )
  15. // ConsumerConfig is used to pass multiple configuration options to NewConsumer.
  16. type ConsumerConfig struct {
  17. // The default (maximum) amount of data to fetch from the broker in each request. The default of 0 is treated as 1024 bytes.
  18. DefaultFetchSize int32
  19. // The minimum amount of data to fetch in a request - the broker will wait until at least this many bytes are available.
  20. // The default of 0 is treated as 'at least one' to prevent the consumer from spinning when no messages are available.
  21. MinFetchSize int32
  22. // The maximum permittable message size - messages larger than this will return MessageTooLarge. The default of 0 is
  23. // treated as no limit.
  24. MaxMessageSize int32
  25. // The maximum amount of time (in ms) the broker will wait for MinFetchSize bytes to become available before it
  26. // returns fewer than that anyways. The default of 0 is treated as no limit.
  27. MaxWaitTime int32
  28. // The method used to determine at which offset to begin consuming messages.
  29. OffsetMethod OffsetMethod
  30. // Interpreted differently according to the value of OffsetMethod.
  31. OffsetValue int64
  32. // The number of events to buffer in the Events channel. Setting this can let the
  33. // consumer continue fetching messages in the background while local code consumes events,
  34. // greatly improving throughput.
  35. EventBufferSize int
  36. }
  37. // ConsumerEvent is what is provided to the user when an event occurs. It is either an error (in which case Err is non-nil) or
  38. // a message (in which case Err is nil and the other fields are all set).
  39. type ConsumerEvent struct {
  40. Key, Value []byte
  41. Offset int64
  42. Err error
  43. }
  44. // Consumer processes Kafka messages from a given topic and partition.
  45. // You MUST call Close() on a consumer to avoid leaks, it will not be garbage-collected automatically when
  46. // it passes out of scope (this is in addition to calling Close on the underlying client, which is still necessary).
  47. type Consumer struct {
  48. client *Client
  49. topic string
  50. partition int32
  51. group string
  52. config ConsumerConfig
  53. offset int64
  54. broker *Broker
  55. stopper, done chan bool
  56. events chan *ConsumerEvent
  57. }
  58. // NewConsumer creates a new consumer attached to the given client. It will read messages from the given topic and partition, as
  59. // part of the named consumer group.
  60. func NewConsumer(client *Client, topic string, partition int32, group string, config *ConsumerConfig) (*Consumer, error) {
  61. if config == nil {
  62. config = new(ConsumerConfig)
  63. }
  64. if config.DefaultFetchSize < 0 {
  65. return nil, ConfigurationError("Invalid DefaultFetchSize")
  66. } else if config.DefaultFetchSize == 0 {
  67. config.DefaultFetchSize = 1024
  68. }
  69. if config.MinFetchSize < 0 {
  70. return nil, ConfigurationError("Invalid MinFetchSize")
  71. } else if config.MinFetchSize == 0 {
  72. config.MinFetchSize = 1
  73. }
  74. if config.MaxMessageSize < 0 {
  75. return nil, ConfigurationError("Invalid MaxMessageSize")
  76. }
  77. if config.MaxWaitTime < 0 {
  78. return nil, ConfigurationError("Invalid MaxWaitTime")
  79. }
  80. if config.EventBufferSize < 0 {
  81. return nil, ConfigurationError("Invalid EventBufferSize")
  82. }
  83. broker, err := client.Leader(topic, partition)
  84. if err != nil {
  85. return nil, err
  86. }
  87. c := new(Consumer)
  88. c.client = client
  89. c.topic = topic
  90. c.partition = partition
  91. c.group = group
  92. c.config = *config
  93. c.broker = broker
  94. switch config.OffsetMethod {
  95. case OffsetMethodManual:
  96. if config.OffsetValue < 0 {
  97. return nil, ConfigurationError("OffsetValue cannot be < 0 when OffsetMethod is MANUAL")
  98. }
  99. c.offset = config.OffsetValue
  100. case OffsetMethodNewest:
  101. c.offset, err = c.getOffset(LatestOffsets, true)
  102. if err != nil {
  103. return nil, err
  104. }
  105. case OffsetMethodOldest:
  106. c.offset, err = c.getOffset(EarliestOffset, true)
  107. if err != nil {
  108. return nil, err
  109. }
  110. default:
  111. return nil, ConfigurationError("Invalid OffsetMethod")
  112. }
  113. c.stopper = make(chan bool)
  114. c.done = make(chan bool)
  115. c.events = make(chan *ConsumerEvent, config.EventBufferSize)
  116. go c.fetchMessages()
  117. return c, nil
  118. }
  119. // Events returns the read channel for any events (messages or errors) that might be returned by the broker.
  120. func (c *Consumer) Events() <-chan *ConsumerEvent {
  121. return c.events
  122. }
  123. // Close stops the consumer from fetching messages. It is required to call this function before
  124. // a consumer object passes out of scope, as it will otherwise leak memory. You must call this before
  125. // calling Close on the underlying client.
  126. func (c *Consumer) Close() error {
  127. close(c.stopper)
  128. <-c.done
  129. return nil
  130. }
  131. // helper function for safely sending an error on the errors channel
  132. // if it returns true, the error was sent (or was nil)
  133. // if it returns false, the stopper channel signaled that your goroutine should return!
  134. func (c *Consumer) sendError(err error) bool {
  135. if err == nil {
  136. return true
  137. }
  138. select {
  139. case <-c.stopper:
  140. close(c.events)
  141. close(c.done)
  142. return false
  143. case c.events <- &ConsumerEvent{Err: err}:
  144. return true
  145. }
  146. }
  147. func (c *Consumer) fetchMessages() {
  148. fetchSize := c.config.DefaultFetchSize
  149. for {
  150. request := new(FetchRequest)
  151. request.MinBytes = c.config.MinFetchSize
  152. request.MaxWaitTime = c.config.MaxWaitTime
  153. request.AddBlock(c.topic, c.partition, c.offset, fetchSize)
  154. response, err := c.broker.Fetch(c.client.id, request)
  155. switch {
  156. case err == nil:
  157. break
  158. case err == EncodingError:
  159. if c.sendError(err) {
  160. continue
  161. } else {
  162. return
  163. }
  164. default:
  165. c.client.disconnectBroker(c.broker)
  166. for c.broker, err = c.client.Leader(c.topic, c.partition); err != nil; c.broker, err = c.client.Leader(c.topic, c.partition) {
  167. if !c.sendError(err) {
  168. return
  169. }
  170. }
  171. continue
  172. }
  173. block := response.GetBlock(c.topic, c.partition)
  174. if block == nil {
  175. if c.sendError(IncompleteResponse) {
  176. continue
  177. } else {
  178. return
  179. }
  180. }
  181. switch block.Err {
  182. case NoError:
  183. break
  184. case UnknownTopicOrPartition, NotLeaderForPartition, LeaderNotAvailable:
  185. err = c.client.RefreshTopicMetadata(c.topic)
  186. if c.sendError(err) {
  187. for c.broker, err = c.client.Leader(c.topic, c.partition); err != nil; c.broker, err = c.client.Leader(c.topic, c.partition) {
  188. if !c.sendError(err) {
  189. return
  190. }
  191. }
  192. continue
  193. } else {
  194. return
  195. }
  196. default:
  197. if c.sendError(block.Err) {
  198. continue
  199. } else {
  200. return
  201. }
  202. }
  203. if len(block.MsgSet.Messages) == 0 {
  204. // We got no messages. If we got a trailing one then we need to ask for more data.
  205. // Otherwise we just poll again and wait for one to be produced...
  206. if block.MsgSet.PartialTrailingMessage {
  207. if c.config.MaxMessageSize == 0 {
  208. fetchSize *= 2
  209. } else {
  210. if fetchSize == c.config.MaxMessageSize {
  211. if c.sendError(MessageTooLarge) {
  212. continue
  213. } else {
  214. return
  215. }
  216. } else {
  217. fetchSize *= 2
  218. if fetchSize > c.config.MaxMessageSize {
  219. fetchSize = c.config.MaxMessageSize
  220. }
  221. }
  222. }
  223. }
  224. select {
  225. case <-c.stopper:
  226. close(c.events)
  227. close(c.done)
  228. return
  229. default:
  230. continue
  231. }
  232. } else {
  233. fetchSize = c.config.DefaultFetchSize
  234. }
  235. for _, msgBlock := range block.MsgSet.Messages {
  236. select {
  237. case <-c.stopper:
  238. close(c.events)
  239. close(c.done)
  240. return
  241. case c.events <- &ConsumerEvent{Key: msgBlock.Msg.Key, Value: msgBlock.Msg.Value, Offset: msgBlock.Offset}:
  242. c.offset++
  243. }
  244. }
  245. }
  246. }
  247. func (c *Consumer) getOffset(where OffsetTime, retry bool) (int64, error) {
  248. request := &OffsetRequest{}
  249. request.AddBlock(c.topic, c.partition, where, 1)
  250. response, err := c.broker.GetAvailableOffsets(c.client.id, request)
  251. switch err {
  252. case nil:
  253. break
  254. case EncodingError:
  255. return -1, err
  256. default:
  257. if !retry {
  258. return -1, err
  259. }
  260. c.client.disconnectBroker(c.broker)
  261. c.broker, err = c.client.Leader(c.topic, c.partition)
  262. if err != nil {
  263. return -1, err
  264. }
  265. return c.getOffset(where, false)
  266. }
  267. block := response.GetBlock(c.topic, c.partition)
  268. if block == nil {
  269. return -1, IncompleteResponse
  270. }
  271. switch block.Err {
  272. case NoError:
  273. if len(block.Offsets) < 1 {
  274. return -1, IncompleteResponse
  275. }
  276. return block.Offsets[0], nil
  277. case UnknownTopicOrPartition, NotLeaderForPartition, LeaderNotAvailable:
  278. if !retry {
  279. return -1, block.Err
  280. }
  281. err = c.client.RefreshTopicMetadata(c.topic)
  282. if err != nil {
  283. return -1, err
  284. }
  285. c.broker, err = c.client.Leader(c.topic, c.partition)
  286. if err != nil {
  287. return -1, err
  288. }
  289. return c.getOffset(where, false)
  290. }
  291. return -1, block.Err
  292. }