consumer.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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 := &Consumer{
  88. client: client,
  89. topic: topic,
  90. partition: partition,
  91. group: group,
  92. config: *config,
  93. broker: broker,
  94. stopper: make(chan bool),
  95. done: make(chan bool),
  96. events: make(chan *ConsumerEvent, config.EventBufferSize),
  97. }
  98. switch config.OffsetMethod {
  99. case OffsetMethodManual:
  100. if config.OffsetValue < 0 {
  101. return nil, ConfigurationError("OffsetValue cannot be < 0 when OffsetMethod is MANUAL")
  102. }
  103. c.offset = config.OffsetValue
  104. case OffsetMethodNewest:
  105. c.offset, err = c.getOffset(LatestOffsets, true)
  106. if err != nil {
  107. return nil, err
  108. }
  109. case OffsetMethodOldest:
  110. c.offset, err = c.getOffset(EarliestOffset, true)
  111. if err != nil {
  112. return nil, err
  113. }
  114. default:
  115. return nil, ConfigurationError("Invalid OffsetMethod")
  116. }
  117. go c.fetchMessages()
  118. return c, nil
  119. }
  120. // Events returns the read channel for any events (messages or errors) that might be returned by the broker.
  121. func (c *Consumer) Events() <-chan *ConsumerEvent {
  122. return c.events
  123. }
  124. // Close stops the consumer from fetching messages. It is required to call this function before
  125. // a consumer object passes out of scope, as it will otherwise leak memory. You must call this before
  126. // calling Close on the underlying client.
  127. func (c *Consumer) Close() error {
  128. close(c.stopper)
  129. <-c.done
  130. return nil
  131. }
  132. // helper function for safely sending an error on the errors channel
  133. // if it returns true, the error was sent (or was nil)
  134. // if it returns false, the stopper channel signaled that your goroutine should return!
  135. func (c *Consumer) sendError(err error) bool {
  136. if err == nil {
  137. return true
  138. }
  139. select {
  140. case <-c.stopper:
  141. close(c.events)
  142. close(c.done)
  143. return false
  144. case c.events <- &ConsumerEvent{Err: err}:
  145. return true
  146. }
  147. // For backward compatibility with go1.0
  148. return true
  149. }
  150. func (c *Consumer) fetchMessages() {
  151. fetchSize := c.config.DefaultFetchSize
  152. for {
  153. request := new(FetchRequest)
  154. request.MinBytes = c.config.MinFetchSize
  155. request.MaxWaitTime = c.config.MaxWaitTime
  156. request.AddBlock(c.topic, c.partition, c.offset, fetchSize)
  157. response, err := c.broker.Fetch(c.client.id, request)
  158. switch {
  159. case err == nil:
  160. break
  161. case err == EncodingError:
  162. if c.sendError(err) {
  163. continue
  164. } else {
  165. return
  166. }
  167. default:
  168. c.client.disconnectBroker(c.broker)
  169. for c.broker, err = c.client.Leader(c.topic, c.partition); err != nil; c.broker, err = c.client.Leader(c.topic, c.partition) {
  170. if !c.sendError(err) {
  171. return
  172. }
  173. }
  174. continue
  175. }
  176. block := response.GetBlock(c.topic, c.partition)
  177. if block == nil {
  178. if c.sendError(IncompleteResponse) {
  179. continue
  180. } else {
  181. return
  182. }
  183. }
  184. switch block.Err {
  185. case NoError:
  186. break
  187. case UnknownTopicOrPartition, NotLeaderForPartition, LeaderNotAvailable:
  188. err = c.client.RefreshTopicMetadata(c.topic)
  189. if c.sendError(err) {
  190. for c.broker, err = c.client.Leader(c.topic, c.partition); err != nil; c.broker, err = c.client.Leader(c.topic, c.partition) {
  191. if !c.sendError(err) {
  192. return
  193. }
  194. }
  195. continue
  196. } else {
  197. return
  198. }
  199. default:
  200. if c.sendError(block.Err) {
  201. continue
  202. } else {
  203. return
  204. }
  205. }
  206. if len(block.MsgSet.Messages) == 0 {
  207. // We got no messages. If we got a trailing one then we need to ask for more data.
  208. // Otherwise we just poll again and wait for one to be produced...
  209. if block.MsgSet.PartialTrailingMessage {
  210. if c.config.MaxMessageSize == 0 {
  211. fetchSize *= 2
  212. } else {
  213. if fetchSize == c.config.MaxMessageSize {
  214. if c.sendError(MessageTooLarge) {
  215. continue
  216. } else {
  217. return
  218. }
  219. } else {
  220. fetchSize *= 2
  221. if fetchSize > c.config.MaxMessageSize {
  222. fetchSize = c.config.MaxMessageSize
  223. }
  224. }
  225. }
  226. }
  227. select {
  228. case <-c.stopper:
  229. close(c.events)
  230. close(c.done)
  231. return
  232. default:
  233. continue
  234. }
  235. } else {
  236. fetchSize = c.config.DefaultFetchSize
  237. }
  238. for _, msgBlock := range block.MsgSet.Messages {
  239. select {
  240. case <-c.stopper:
  241. close(c.events)
  242. close(c.done)
  243. return
  244. case c.events <- &ConsumerEvent{Key: msgBlock.Msg.Key, Value: msgBlock.Msg.Value, Offset: msgBlock.Offset}:
  245. c.offset++
  246. }
  247. }
  248. }
  249. }
  250. func (c *Consumer) getOffset(where OffsetTime, retry bool) (int64, error) {
  251. request := &OffsetRequest{}
  252. request.AddBlock(c.topic, c.partition, where, 1)
  253. response, err := c.broker.GetAvailableOffsets(c.client.id, request)
  254. switch err {
  255. case nil:
  256. break
  257. case EncodingError:
  258. return -1, err
  259. default:
  260. if !retry {
  261. return -1, err
  262. }
  263. c.client.disconnectBroker(c.broker)
  264. c.broker, err = c.client.Leader(c.topic, c.partition)
  265. if err != nil {
  266. return -1, err
  267. }
  268. return c.getOffset(where, false)
  269. }
  270. block := response.GetBlock(c.topic, c.partition)
  271. if block == nil {
  272. return -1, IncompleteResponse
  273. }
  274. switch block.Err {
  275. case NoError:
  276. if len(block.Offsets) < 1 {
  277. return -1, IncompleteResponse
  278. }
  279. return block.Offsets[0], nil
  280. case UnknownTopicOrPartition, NotLeaderForPartition, LeaderNotAvailable:
  281. if !retry {
  282. return -1, block.Err
  283. }
  284. err = c.client.RefreshTopicMetadata(c.topic)
  285. if err != nil {
  286. return -1, err
  287. }
  288. c.broker, err = c.client.Leader(c.topic, c.partition)
  289. if err != nil {
  290. return -1, err
  291. }
  292. return c.getOffset(where, false)
  293. }
  294. return -1, block.Err
  295. }