consumer.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749
  1. package sarama
  2. import (
  3. "errors"
  4. "fmt"
  5. "sync"
  6. "sync/atomic"
  7. "time"
  8. )
  9. // ConsumerMessage encapsulates a Kafka message returned by the consumer.
  10. type ConsumerMessage struct {
  11. Key, Value []byte
  12. Topic string
  13. Partition int32
  14. Offset int64
  15. Timestamp time.Time // only set if kafka is version 0.10+, inner message timestamp
  16. BlockTimestamp time.Time // only set if kafka is version 0.10+, outer (compressed) block timestamp
  17. }
  18. // ConsumerError is what is provided to the user when an error occurs.
  19. // It wraps an error and includes the topic and partition.
  20. type ConsumerError struct {
  21. Topic string
  22. Partition int32
  23. Err error
  24. }
  25. func (ce ConsumerError) Error() string {
  26. return fmt.Sprintf("kafka: error while consuming %s/%d: %s", ce.Topic, ce.Partition, ce.Err)
  27. }
  28. // ConsumerErrors is a type that wraps a batch of errors and implements the Error interface.
  29. // It can be returned from the PartitionConsumer's Close methods to avoid the need to manually drain errors
  30. // when stopping.
  31. type ConsumerErrors []*ConsumerError
  32. func (ce ConsumerErrors) Error() string {
  33. return fmt.Sprintf("kafka: %d errors while consuming", len(ce))
  34. }
  35. // Consumer manages PartitionConsumers which process Kafka messages from brokers. You MUST call Close()
  36. // on a consumer to avoid leaks, it will not be garbage-collected automatically when it passes out of
  37. // scope.
  38. //
  39. // Sarama's Consumer type does not currently support automatic consumer-group rebalancing and offset tracking.
  40. // For Zookeeper-based tracking (Kafka 0.8.2 and earlier), the https://github.com/wvanbergen/kafka library
  41. // builds on Sarama to add this support. For Kafka-based tracking (Kafka 0.9 and later), the
  42. // https://github.com/bsm/sarama-cluster library builds on Sarama to add this support.
  43. type Consumer interface {
  44. // Topics returns the set of available topics as retrieved from the cluster
  45. // metadata. This method is the same as Client.Topics(), and is provided for
  46. // convenience.
  47. Topics() ([]string, error)
  48. // Partitions returns the sorted list of all partition IDs for the given topic.
  49. // This method is the same as Client.Partitions(), and is provided for convenience.
  50. Partitions(topic string) ([]int32, error)
  51. // ConsumePartition creates a PartitionConsumer on the given topic/partition with
  52. // the given offset. It will return an error if this Consumer is already consuming
  53. // on the given topic/partition. Offset can be a literal offset, or OffsetNewest
  54. // or OffsetOldest
  55. ConsumePartition(topic string, partition int32, offset int64) (PartitionConsumer, error)
  56. // HighWaterMarks returns the current high water marks for each topic and partition.
  57. // Consistency between partitions is not guaranteed since high water marks are updated separately.
  58. HighWaterMarks() map[string]map[int32]int64
  59. // Close shuts down the consumer. It must be called after all child
  60. // PartitionConsumers have already been closed.
  61. Close() error
  62. }
  63. type consumer struct {
  64. client Client
  65. conf *Config
  66. ownClient bool
  67. lock sync.Mutex
  68. children map[string]map[int32]*partitionConsumer
  69. brokerConsumers map[*Broker]*brokerConsumer
  70. }
  71. // NewConsumer creates a new consumer using the given broker addresses and configuration.
  72. func NewConsumer(addrs []string, config *Config) (Consumer, error) {
  73. client, err := NewClient(addrs, config)
  74. if err != nil {
  75. return nil, err
  76. }
  77. c, err := NewConsumerFromClient(client)
  78. if err != nil {
  79. return nil, err
  80. }
  81. c.(*consumer).ownClient = true
  82. return c, nil
  83. }
  84. // NewConsumerFromClient creates a new consumer using the given client. It is still
  85. // necessary to call Close() on the underlying client when shutting down this consumer.
  86. func NewConsumerFromClient(client Client) (Consumer, error) {
  87. // Check that we are not dealing with a closed Client before processing any other arguments
  88. if client.Closed() {
  89. return nil, ErrClosedClient
  90. }
  91. c := &consumer{
  92. client: client,
  93. conf: client.Config(),
  94. children: make(map[string]map[int32]*partitionConsumer),
  95. brokerConsumers: make(map[*Broker]*brokerConsumer),
  96. }
  97. return c, nil
  98. }
  99. func (c *consumer) Close() error {
  100. if c.ownClient {
  101. return c.client.Close()
  102. }
  103. return nil
  104. }
  105. func (c *consumer) Topics() ([]string, error) {
  106. return c.client.Topics()
  107. }
  108. func (c *consumer) Partitions(topic string) ([]int32, error) {
  109. return c.client.Partitions(topic)
  110. }
  111. func (c *consumer) ConsumePartition(topic string, partition int32, offset int64) (PartitionConsumer, error) {
  112. child := &partitionConsumer{
  113. consumer: c,
  114. conf: c.conf,
  115. topic: topic,
  116. partition: partition,
  117. messages: make(chan *ConsumerMessage, c.conf.ChannelBufferSize),
  118. errors: make(chan *ConsumerError, c.conf.ChannelBufferSize),
  119. feeder: make(chan *FetchResponse, 1),
  120. trigger: make(chan none, 1),
  121. dying: make(chan none),
  122. fetchSize: c.conf.Consumer.Fetch.Default,
  123. }
  124. if err := child.chooseStartingOffset(offset); err != nil {
  125. return nil, err
  126. }
  127. var leader *Broker
  128. var err error
  129. if leader, err = c.client.Leader(child.topic, child.partition); err != nil {
  130. return nil, err
  131. }
  132. if err := c.addChild(child); err != nil {
  133. return nil, err
  134. }
  135. go withRecover(child.dispatcher)
  136. go withRecover(child.responseFeeder)
  137. child.broker = c.refBrokerConsumer(leader)
  138. child.broker.input <- child
  139. return child, nil
  140. }
  141. func (c *consumer) HighWaterMarks() map[string]map[int32]int64 {
  142. c.lock.Lock()
  143. defer c.lock.Unlock()
  144. hwms := make(map[string]map[int32]int64)
  145. for topic, p := range c.children {
  146. hwm := make(map[int32]int64, len(p))
  147. for partition, pc := range p {
  148. hwm[partition] = pc.HighWaterMarkOffset()
  149. }
  150. hwms[topic] = hwm
  151. }
  152. return hwms
  153. }
  154. func (c *consumer) addChild(child *partitionConsumer) error {
  155. c.lock.Lock()
  156. defer c.lock.Unlock()
  157. topicChildren := c.children[child.topic]
  158. if topicChildren == nil {
  159. topicChildren = make(map[int32]*partitionConsumer)
  160. c.children[child.topic] = topicChildren
  161. }
  162. if topicChildren[child.partition] != nil {
  163. return ConfigurationError("That topic/partition is already being consumed")
  164. }
  165. topicChildren[child.partition] = child
  166. return nil
  167. }
  168. func (c *consumer) removeChild(child *partitionConsumer) {
  169. c.lock.Lock()
  170. defer c.lock.Unlock()
  171. delete(c.children[child.topic], child.partition)
  172. }
  173. func (c *consumer) refBrokerConsumer(broker *Broker) *brokerConsumer {
  174. c.lock.Lock()
  175. defer c.lock.Unlock()
  176. bc := c.brokerConsumers[broker]
  177. if bc == nil {
  178. bc = c.newBrokerConsumer(broker)
  179. c.brokerConsumers[broker] = bc
  180. }
  181. bc.refs++
  182. return bc
  183. }
  184. func (c *consumer) unrefBrokerConsumer(brokerWorker *brokerConsumer) {
  185. c.lock.Lock()
  186. defer c.lock.Unlock()
  187. brokerWorker.refs--
  188. if brokerWorker.refs == 0 {
  189. close(brokerWorker.input)
  190. if c.brokerConsumers[brokerWorker.broker] == brokerWorker {
  191. delete(c.brokerConsumers, brokerWorker.broker)
  192. }
  193. }
  194. }
  195. func (c *consumer) abandonBrokerConsumer(brokerWorker *brokerConsumer) {
  196. c.lock.Lock()
  197. defer c.lock.Unlock()
  198. delete(c.brokerConsumers, brokerWorker.broker)
  199. }
  200. // PartitionConsumer
  201. // PartitionConsumer processes Kafka messages from a given topic and partition. You MUST call one of Close() or
  202. // AsyncClose() on a PartitionConsumer to avoid leaks; it will not be garbage-collected automatically when it passes out
  203. // of scope.
  204. //
  205. // The simplest way of using a PartitionConsumer is to loop over its Messages channel using a for/range
  206. // loop. The PartitionConsumer will only stop itself in one case: when the offset being consumed is reported
  207. // as out of range by the brokers. In this case you should decide what you want to do (try a different offset,
  208. // notify a human, etc) and handle it appropriately. For all other error cases, it will just keep retrying.
  209. // By default, it logs these errors to sarama.Logger; if you want to be notified directly of all errors, set
  210. // your config's Consumer.Return.Errors to true and read from the Errors channel, using a select statement
  211. // or a separate goroutine. Check out the Consumer examples to see implementations of these different approaches.
  212. //
  213. // To terminate such a for/range loop while the loop is executing, call AsyncClose. This will kick off the process of
  214. // consumer tear-down & return imediately. Continue to loop, servicing the Messages channel until the teardown process
  215. // AsyncClose initiated closes it (thus terminating the for/range loop). If you've already ceased reading Messages, call
  216. // Close; this will signal the PartitionConsumer's goroutines to begin shutting down (just like AsyncClose), but will
  217. // also drain the Messages channel, harvest all errors & return them once cleanup has completed.
  218. type PartitionConsumer interface {
  219. // AsyncClose initiates a shutdown of the PartitionConsumer. This method will return immediately, after which you
  220. // should continue to service the 'Messages' and 'Errors' channels until they are empty. It is required to call this
  221. // function, or Close before a consumer object passes out of scope, as it will otherwise leak memory. You must call
  222. // this before calling Close on the underlying client.
  223. AsyncClose()
  224. // Close stops the PartitionConsumer from fetching messages. It will initiate a shutdown just like AsyncClose, drain
  225. // the Messages channel, harvest any errors & return them to the caller. Note that if you are continuing to service
  226. // the Messages channel when this function is called, you will be competing with Close for messages; consider
  227. // calling AsyncClose, instead. It is required to call this function (or AsyncClose) before a consumer object passes
  228. // out of scope, as it will otherwise leak memory. You must call this before calling Close on the underlying client.
  229. Close() error
  230. // Messages returns the read channel for the messages that are returned by
  231. // the broker.
  232. Messages() <-chan *ConsumerMessage
  233. // Errors returns a read channel of errors that occurred during consuming, if
  234. // enabled. By default, errors are logged and not returned over this channel.
  235. // If you want to implement any custom error handling, set your config's
  236. // Consumer.Return.Errors setting to true, and read from this channel.
  237. Errors() <-chan *ConsumerError
  238. // HighWaterMarkOffset returns the high water mark offset of the partition,
  239. // i.e. the offset that will be used for the next message that will be produced.
  240. // You can use this to determine how far behind the processing is.
  241. HighWaterMarkOffset() int64
  242. }
  243. type partitionConsumer struct {
  244. highWaterMarkOffset int64 // must be at the top of the struct because https://golang.org/pkg/sync/atomic/#pkg-note-BUG
  245. consumer *consumer
  246. conf *Config
  247. topic string
  248. partition int32
  249. broker *brokerConsumer
  250. messages chan *ConsumerMessage
  251. errors chan *ConsumerError
  252. feeder chan *FetchResponse
  253. trigger, dying chan none
  254. responseResult error
  255. fetchSize int32
  256. offset int64
  257. }
  258. var errTimedOut = errors.New("timed out feeding messages to the user") // not user-facing
  259. func (child *partitionConsumer) sendError(err error) {
  260. cErr := &ConsumerError{
  261. Topic: child.topic,
  262. Partition: child.partition,
  263. Err: err,
  264. }
  265. if child.conf.Consumer.Return.Errors {
  266. child.errors <- cErr
  267. } else {
  268. Logger.Println(cErr)
  269. }
  270. }
  271. func (child *partitionConsumer) dispatcher() {
  272. for range child.trigger {
  273. select {
  274. case <-child.dying:
  275. close(child.trigger)
  276. case <-time.After(child.conf.Consumer.Retry.Backoff):
  277. if child.broker != nil {
  278. child.consumer.unrefBrokerConsumer(child.broker)
  279. child.broker = nil
  280. }
  281. Logger.Printf("consumer/%s/%d finding new broker\n", child.topic, child.partition)
  282. if err := child.dispatch(); err != nil {
  283. child.sendError(err)
  284. child.trigger <- none{}
  285. }
  286. }
  287. }
  288. if child.broker != nil {
  289. child.consumer.unrefBrokerConsumer(child.broker)
  290. }
  291. child.consumer.removeChild(child)
  292. close(child.feeder)
  293. }
  294. func (child *partitionConsumer) dispatch() error {
  295. if err := child.consumer.client.RefreshMetadata(child.topic); err != nil {
  296. return err
  297. }
  298. var leader *Broker
  299. var err error
  300. if leader, err = child.consumer.client.Leader(child.topic, child.partition); err != nil {
  301. return err
  302. }
  303. child.broker = child.consumer.refBrokerConsumer(leader)
  304. child.broker.input <- child
  305. return nil
  306. }
  307. func (child *partitionConsumer) chooseStartingOffset(offset int64) error {
  308. newestOffset, err := child.consumer.client.GetOffset(child.topic, child.partition, OffsetNewest)
  309. if err != nil {
  310. return err
  311. }
  312. oldestOffset, err := child.consumer.client.GetOffset(child.topic, child.partition, OffsetOldest)
  313. if err != nil {
  314. return err
  315. }
  316. switch {
  317. case offset == OffsetNewest:
  318. child.offset = newestOffset
  319. case offset == OffsetOldest:
  320. child.offset = oldestOffset
  321. case offset >= oldestOffset && offset <= newestOffset:
  322. child.offset = offset
  323. default:
  324. return ErrOffsetOutOfRange
  325. }
  326. return nil
  327. }
  328. func (child *partitionConsumer) Messages() <-chan *ConsumerMessage {
  329. return child.messages
  330. }
  331. func (child *partitionConsumer) Errors() <-chan *ConsumerError {
  332. return child.errors
  333. }
  334. func (child *partitionConsumer) AsyncClose() {
  335. // this triggers whatever broker owns this child to abandon it and close its trigger channel, which causes
  336. // the dispatcher to exit its loop, which removes it from the consumer then closes its 'messages' and
  337. // 'errors' channel (alternatively, if the child is already at the dispatcher for some reason, that will
  338. // also just close itself)
  339. close(child.dying)
  340. }
  341. func (child *partitionConsumer) Close() error {
  342. child.AsyncClose()
  343. go withRecover(func() {
  344. for range child.messages {
  345. // drain
  346. }
  347. })
  348. var errors ConsumerErrors
  349. for err := range child.errors {
  350. errors = append(errors, err)
  351. }
  352. if len(errors) > 0 {
  353. return errors
  354. }
  355. return nil
  356. }
  357. func (child *partitionConsumer) HighWaterMarkOffset() int64 {
  358. return atomic.LoadInt64(&child.highWaterMarkOffset)
  359. }
  360. func (child *partitionConsumer) responseFeeder() {
  361. var msgs []*ConsumerMessage
  362. msgSent := false
  363. feederLoop:
  364. for response := range child.feeder {
  365. msgs, child.responseResult = child.parseResponse(response)
  366. expiryTicker := time.NewTicker(child.conf.Consumer.MaxProcessingTime)
  367. for i, msg := range msgs {
  368. messageSelect:
  369. select {
  370. case child.messages <- msg:
  371. msgSent = true
  372. case <-expiryTicker.C:
  373. if !msgSent {
  374. child.responseResult = errTimedOut
  375. child.broker.acks.Done()
  376. for _, msg = range msgs[i:] {
  377. child.messages <- msg
  378. }
  379. child.broker.input <- child
  380. continue feederLoop
  381. } else {
  382. // current message has not been sent, return to select
  383. // statement
  384. msgSent = false
  385. goto messageSelect
  386. }
  387. }
  388. }
  389. expiryTicker.Stop()
  390. child.broker.acks.Done()
  391. }
  392. close(child.messages)
  393. close(child.errors)
  394. }
  395. func (child *partitionConsumer) parseResponse(response *FetchResponse) ([]*ConsumerMessage, error) {
  396. block := response.GetBlock(child.topic, child.partition)
  397. if block == nil {
  398. return nil, ErrIncompleteResponse
  399. }
  400. if block.Err != ErrNoError {
  401. return nil, block.Err
  402. }
  403. if len(block.MsgSet.Messages) == 0 {
  404. // We got no messages. If we got a trailing one then we need to ask for more data.
  405. // Otherwise we just poll again and wait for one to be produced...
  406. if block.MsgSet.PartialTrailingMessage {
  407. if child.conf.Consumer.Fetch.Max > 0 && child.fetchSize == child.conf.Consumer.Fetch.Max {
  408. // we can't ask for more data, we've hit the configured limit
  409. child.sendError(ErrMessageTooLarge)
  410. child.offset++ // skip this one so we can keep processing future messages
  411. } else {
  412. child.fetchSize *= 2
  413. if child.conf.Consumer.Fetch.Max > 0 && child.fetchSize > child.conf.Consumer.Fetch.Max {
  414. child.fetchSize = child.conf.Consumer.Fetch.Max
  415. }
  416. }
  417. }
  418. return nil, nil
  419. }
  420. // we got messages, reset our fetch size in case it was increased for a previous request
  421. child.fetchSize = child.conf.Consumer.Fetch.Default
  422. atomic.StoreInt64(&child.highWaterMarkOffset, block.HighWaterMarkOffset)
  423. incomplete := false
  424. prelude := true
  425. var messages []*ConsumerMessage
  426. for _, msgBlock := range block.MsgSet.Messages {
  427. for _, msg := range msgBlock.Messages() {
  428. offset := msg.Offset
  429. if msg.Msg.Version >= 1 {
  430. baseOffset := msgBlock.Offset - msgBlock.Messages()[len(msgBlock.Messages())-1].Offset
  431. offset += baseOffset
  432. }
  433. if prelude && offset < child.offset {
  434. continue
  435. }
  436. prelude = false
  437. if offset >= child.offset {
  438. messages = append(messages, &ConsumerMessage{
  439. Topic: child.topic,
  440. Partition: child.partition,
  441. Key: msg.Msg.Key,
  442. Value: msg.Msg.Value,
  443. Offset: offset,
  444. Timestamp: msg.Msg.Timestamp,
  445. BlockTimestamp: msgBlock.Msg.Timestamp,
  446. })
  447. child.offset = offset + 1
  448. } else {
  449. incomplete = true
  450. }
  451. }
  452. }
  453. if incomplete || len(messages) == 0 {
  454. return nil, ErrIncompleteResponse
  455. }
  456. return messages, nil
  457. }
  458. // brokerConsumer
  459. type brokerConsumer struct {
  460. consumer *consumer
  461. broker *Broker
  462. input chan *partitionConsumer
  463. newSubscriptions chan []*partitionConsumer
  464. wait chan none
  465. subscriptions map[*partitionConsumer]none
  466. acks sync.WaitGroup
  467. refs int
  468. }
  469. func (c *consumer) newBrokerConsumer(broker *Broker) *brokerConsumer {
  470. bc := &brokerConsumer{
  471. consumer: c,
  472. broker: broker,
  473. input: make(chan *partitionConsumer),
  474. newSubscriptions: make(chan []*partitionConsumer),
  475. wait: make(chan none),
  476. subscriptions: make(map[*partitionConsumer]none),
  477. refs: 0,
  478. }
  479. go withRecover(bc.subscriptionManager)
  480. go withRecover(bc.subscriptionConsumer)
  481. return bc
  482. }
  483. func (bc *brokerConsumer) subscriptionManager() {
  484. var buffer []*partitionConsumer
  485. // The subscriptionManager constantly accepts new subscriptions on `input` (even when the main subscriptionConsumer
  486. // goroutine is in the middle of a network request) and batches it up. The main worker goroutine picks
  487. // up a batch of new subscriptions between every network request by reading from `newSubscriptions`, so we give
  488. // it nil if no new subscriptions are available. We also write to `wait` only when new subscriptions is available,
  489. // so the main goroutine can block waiting for work if it has none.
  490. for {
  491. if len(buffer) > 0 {
  492. select {
  493. case event, ok := <-bc.input:
  494. if !ok {
  495. goto done
  496. }
  497. buffer = append(buffer, event)
  498. case bc.newSubscriptions <- buffer:
  499. buffer = nil
  500. case bc.wait <- none{}:
  501. }
  502. } else {
  503. select {
  504. case event, ok := <-bc.input:
  505. if !ok {
  506. goto done
  507. }
  508. buffer = append(buffer, event)
  509. case bc.newSubscriptions <- nil:
  510. }
  511. }
  512. }
  513. done:
  514. close(bc.wait)
  515. if len(buffer) > 0 {
  516. bc.newSubscriptions <- buffer
  517. }
  518. close(bc.newSubscriptions)
  519. }
  520. func (bc *brokerConsumer) subscriptionConsumer() {
  521. <-bc.wait // wait for our first piece of work
  522. // the subscriptionConsumer ensures we will get nil right away if no new subscriptions is available
  523. for newSubscriptions := range bc.newSubscriptions {
  524. bc.updateSubscriptions(newSubscriptions)
  525. if len(bc.subscriptions) == 0 {
  526. // We're about to be shut down or we're about to receive more subscriptions.
  527. // Either way, the signal just hasn't propagated to our goroutine yet.
  528. <-bc.wait
  529. continue
  530. }
  531. response, err := bc.fetchNewMessages()
  532. if err != nil {
  533. Logger.Printf("consumer/broker/%d disconnecting due to error processing FetchRequest: %s\n", bc.broker.ID(), err)
  534. bc.abort(err)
  535. return
  536. }
  537. bc.acks.Add(len(bc.subscriptions))
  538. for child := range bc.subscriptions {
  539. child.feeder <- response
  540. }
  541. bc.acks.Wait()
  542. bc.handleResponses()
  543. }
  544. }
  545. func (bc *brokerConsumer) updateSubscriptions(newSubscriptions []*partitionConsumer) {
  546. for _, child := range newSubscriptions {
  547. bc.subscriptions[child] = none{}
  548. Logger.Printf("consumer/broker/%d added subscription to %s/%d\n", bc.broker.ID(), child.topic, child.partition)
  549. }
  550. for child := range bc.subscriptions {
  551. select {
  552. case <-child.dying:
  553. Logger.Printf("consumer/broker/%d closed dead subscription to %s/%d\n", bc.broker.ID(), child.topic, child.partition)
  554. close(child.trigger)
  555. delete(bc.subscriptions, child)
  556. default:
  557. break
  558. }
  559. }
  560. }
  561. func (bc *brokerConsumer) handleResponses() {
  562. // handles the response codes left for us by our subscriptions, and abandons ones that have been closed
  563. for child := range bc.subscriptions {
  564. result := child.responseResult
  565. child.responseResult = nil
  566. switch result {
  567. case nil:
  568. break
  569. case errTimedOut:
  570. Logger.Printf("consumer/broker/%d abandoned subscription to %s/%d because consuming was taking too long\n",
  571. bc.broker.ID(), child.topic, child.partition)
  572. delete(bc.subscriptions, child)
  573. case ErrOffsetOutOfRange:
  574. // there's no point in retrying this it will just fail the same way again
  575. // shut it down and force the user to choose what to do
  576. child.sendError(result)
  577. Logger.Printf("consumer/%s/%d shutting down because %s\n", child.topic, child.partition, result)
  578. close(child.trigger)
  579. delete(bc.subscriptions, child)
  580. case ErrUnknownTopicOrPartition, ErrNotLeaderForPartition, ErrLeaderNotAvailable, ErrReplicaNotAvailable:
  581. // not an error, but does need redispatching
  582. Logger.Printf("consumer/broker/%d abandoned subscription to %s/%d because %s\n",
  583. bc.broker.ID(), child.topic, child.partition, result)
  584. child.trigger <- none{}
  585. delete(bc.subscriptions, child)
  586. default:
  587. // dunno, tell the user and try redispatching
  588. child.sendError(result)
  589. Logger.Printf("consumer/broker/%d abandoned subscription to %s/%d because %s\n",
  590. bc.broker.ID(), child.topic, child.partition, result)
  591. child.trigger <- none{}
  592. delete(bc.subscriptions, child)
  593. }
  594. }
  595. }
  596. func (bc *brokerConsumer) abort(err error) {
  597. bc.consumer.abandonBrokerConsumer(bc)
  598. _ = bc.broker.Close() // we don't care about the error this might return, we already have one
  599. for child := range bc.subscriptions {
  600. child.sendError(err)
  601. child.trigger <- none{}
  602. }
  603. for newSubscriptions := range bc.newSubscriptions {
  604. if len(newSubscriptions) == 0 {
  605. <-bc.wait
  606. continue
  607. }
  608. for _, child := range newSubscriptions {
  609. child.sendError(err)
  610. child.trigger <- none{}
  611. }
  612. }
  613. }
  614. func (bc *brokerConsumer) fetchNewMessages() (*FetchResponse, error) {
  615. request := &FetchRequest{
  616. MinBytes: bc.consumer.conf.Consumer.Fetch.Min,
  617. MaxWaitTime: int32(bc.consumer.conf.Consumer.MaxWaitTime / time.Millisecond),
  618. }
  619. if bc.consumer.conf.Version.IsAtLeast(V0_10_0_0) {
  620. request.Version = 2
  621. }
  622. if bc.consumer.conf.Version.IsAtLeast(V0_10_1_0) {
  623. request.Version = 3
  624. request.MaxBytes = MaxResponseSize
  625. }
  626. for child := range bc.subscriptions {
  627. request.AddBlock(child.topic, child.partition, child.offset, child.fetchSize)
  628. }
  629. return bc.broker.Fetch(request)
  630. }