consumer.go 21 KB

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