produce_set.go 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258
  1. package sarama
  2. import (
  3. "encoding/binary"
  4. "errors"
  5. "time"
  6. )
  7. type partitionSet struct {
  8. msgs []*ProducerMessage
  9. recordsToSend Records
  10. bufferBytes int
  11. }
  12. type produceSet struct {
  13. parent *asyncProducer
  14. msgs map[string]map[int32]*partitionSet
  15. bufferBytes int
  16. bufferCount int
  17. }
  18. func newProduceSet(parent *asyncProducer) *produceSet {
  19. return &produceSet{
  20. msgs: make(map[string]map[int32]*partitionSet),
  21. parent: parent,
  22. }
  23. }
  24. func (ps *produceSet) add(msg *ProducerMessage) error {
  25. var err error
  26. var key, val []byte
  27. if msg.Key != nil {
  28. if key, err = msg.Key.Encode(); err != nil {
  29. return err
  30. }
  31. }
  32. if msg.Value != nil {
  33. if val, err = msg.Value.Encode(); err != nil {
  34. return err
  35. }
  36. }
  37. timestamp := msg.Timestamp
  38. if msg.Timestamp.IsZero() {
  39. timestamp = time.Now()
  40. }
  41. partitions := ps.msgs[msg.Topic]
  42. if partitions == nil {
  43. partitions = make(map[int32]*partitionSet)
  44. ps.msgs[msg.Topic] = partitions
  45. }
  46. var size int
  47. set := partitions[msg.Partition]
  48. if set == nil {
  49. if ps.parent.conf.Version.IsAtLeast(V0_11_0_0) {
  50. batch := &RecordBatch{
  51. FirstTimestamp: timestamp,
  52. Version: 2,
  53. Codec: ps.parent.conf.Producer.Compression,
  54. CompressionLevel: ps.parent.conf.Producer.CompressionLevel,
  55. ProducerID: ps.parent.txnmgr.producerID,
  56. ProducerEpoch: ps.parent.txnmgr.producerEpoch,
  57. }
  58. if ps.parent.conf.Producer.Idempotent {
  59. batch.FirstSequence = msg.sequenceNumber
  60. }
  61. set = &partitionSet{recordsToSend: newDefaultRecords(batch)}
  62. size = recordBatchOverhead
  63. } else {
  64. set = &partitionSet{recordsToSend: newLegacyRecords(new(MessageSet))}
  65. }
  66. partitions[msg.Partition] = set
  67. }
  68. set.msgs = append(set.msgs, msg)
  69. if ps.parent.conf.Version.IsAtLeast(V0_11_0_0) {
  70. if ps.parent.conf.Producer.Idempotent && msg.sequenceNumber < set.recordsToSend.RecordBatch.FirstSequence {
  71. return errors.New("assertion failed: message out of sequence added to a batch")
  72. }
  73. // We are being conservative here to avoid having to prep encode the record
  74. size += maximumRecordOverhead
  75. rec := &Record{
  76. Key: key,
  77. Value: val,
  78. TimestampDelta: timestamp.Sub(set.recordsToSend.RecordBatch.FirstTimestamp),
  79. }
  80. size += len(key) + len(val)
  81. if len(msg.Headers) > 0 {
  82. rec.Headers = make([]*RecordHeader, len(msg.Headers))
  83. for i := range msg.Headers {
  84. rec.Headers[i] = &msg.Headers[i]
  85. size += len(rec.Headers[i].Key) + len(rec.Headers[i].Value) + 2*binary.MaxVarintLen32
  86. }
  87. }
  88. set.recordsToSend.RecordBatch.addRecord(rec)
  89. } else {
  90. msgToSend := &Message{Codec: CompressionNone, Key: key, Value: val}
  91. if ps.parent.conf.Version.IsAtLeast(V0_10_0_0) {
  92. msgToSend.Timestamp = timestamp
  93. msgToSend.Version = 1
  94. }
  95. set.recordsToSend.MsgSet.addMessage(msgToSend)
  96. size = producerMessageOverhead + len(key) + len(val)
  97. }
  98. set.bufferBytes += size
  99. ps.bufferBytes += size
  100. ps.bufferCount++
  101. return nil
  102. }
  103. func (ps *produceSet) buildRequest() *ProduceRequest {
  104. req := &ProduceRequest{
  105. RequiredAcks: ps.parent.conf.Producer.RequiredAcks,
  106. Timeout: int32(ps.parent.conf.Producer.Timeout / time.Millisecond),
  107. }
  108. if ps.parent.conf.Version.IsAtLeast(V0_10_0_0) {
  109. req.Version = 2
  110. }
  111. if ps.parent.conf.Version.IsAtLeast(V0_11_0_0) {
  112. req.Version = 3
  113. }
  114. for topic, partitionSets := range ps.msgs {
  115. for partition, set := range partitionSets {
  116. if req.Version >= 3 {
  117. // If the API version we're hitting is 3 or greater, we need to calculate
  118. // offsets for each record in the batch relative to FirstOffset.
  119. // Additionally, we must set LastOffsetDelta to the value of the last offset
  120. // in the batch. Since the OffsetDelta of the first record is 0, we know that the
  121. // final record of any batch will have an offset of (# of records in batch) - 1.
  122. // (See https://cwiki.apache.org/confluence/display/KAFKA/A+Guide+To+The+Kafka+Protocol#AGuideToTheKafkaProtocol-Messagesets
  123. // under the RecordBatch section for details.)
  124. rb := set.recordsToSend.RecordBatch
  125. if len(rb.Records) > 0 {
  126. rb.LastOffsetDelta = int32(len(rb.Records) - 1)
  127. for i, record := range rb.Records {
  128. record.OffsetDelta = int64(i)
  129. }
  130. }
  131. req.AddBatch(topic, partition, rb)
  132. continue
  133. }
  134. if ps.parent.conf.Producer.Compression == CompressionNone {
  135. req.AddSet(topic, partition, set.recordsToSend.MsgSet)
  136. } else {
  137. // When compression is enabled, the entire set for each partition is compressed
  138. // and sent as the payload of a single fake "message" with the appropriate codec
  139. // set and no key. When the server sees a message with a compression codec, it
  140. // decompresses the payload and treats the result as its message set.
  141. if ps.parent.conf.Version.IsAtLeast(V0_10_0_0) {
  142. // If our version is 0.10 or later, assign relative offsets
  143. // to the inner messages. This lets the broker avoid
  144. // recompressing the message set.
  145. // (See https://cwiki.apache.org/confluence/display/KAFKA/KIP-31+-+Move+to+relative+offsets+in+compressed+message+sets
  146. // for details on relative offsets.)
  147. for i, msg := range set.recordsToSend.MsgSet.Messages {
  148. msg.Offset = int64(i)
  149. }
  150. }
  151. payload, err := encode(set.recordsToSend.MsgSet, ps.parent.conf.MetricRegistry)
  152. if err != nil {
  153. Logger.Println(err) // if this happens, it's basically our fault.
  154. panic(err)
  155. }
  156. compMsg := &Message{
  157. Codec: ps.parent.conf.Producer.Compression,
  158. CompressionLevel: ps.parent.conf.Producer.CompressionLevel,
  159. Key: nil,
  160. Value: payload,
  161. Set: set.recordsToSend.MsgSet, // Provide the underlying message set for accurate metrics
  162. }
  163. if ps.parent.conf.Version.IsAtLeast(V0_10_0_0) {
  164. compMsg.Version = 1
  165. compMsg.Timestamp = set.recordsToSend.MsgSet.Messages[0].Msg.Timestamp
  166. }
  167. req.AddMessage(topic, partition, compMsg)
  168. }
  169. }
  170. }
  171. return req
  172. }
  173. func (ps *produceSet) eachPartition(cb func(topic string, partition int32, pSet *partitionSet)) {
  174. for topic, partitionSet := range ps.msgs {
  175. for partition, set := range partitionSet {
  176. cb(topic, partition, set)
  177. }
  178. }
  179. }
  180. func (ps *produceSet) dropPartition(topic string, partition int32) []*ProducerMessage {
  181. if ps.msgs[topic] == nil {
  182. return nil
  183. }
  184. set := ps.msgs[topic][partition]
  185. if set == nil {
  186. return nil
  187. }
  188. ps.bufferBytes -= set.bufferBytes
  189. ps.bufferCount -= len(set.msgs)
  190. delete(ps.msgs[topic], partition)
  191. return set.msgs
  192. }
  193. func (ps *produceSet) wouldOverflow(msg *ProducerMessage) bool {
  194. version := 1
  195. if ps.parent.conf.Version.IsAtLeast(V0_11_0_0) {
  196. version = 2
  197. }
  198. switch {
  199. // Would we overflow our maximum possible size-on-the-wire? 10KiB is arbitrary overhead for safety.
  200. case ps.bufferBytes+msg.byteSize(version) >= int(MaxRequestSize-(10*1024)):
  201. return true
  202. // Would we overflow the size-limit of a message-batch for this partition?
  203. case ps.msgs[msg.Topic] != nil && ps.msgs[msg.Topic][msg.Partition] != nil &&
  204. ps.msgs[msg.Topic][msg.Partition].bufferBytes+msg.byteSize(version) >= ps.parent.conf.Producer.MaxMessageBytes:
  205. return true
  206. // Would we overflow simply in number of messages?
  207. case ps.parent.conf.Producer.Flush.MaxMessages > 0 && ps.bufferCount >= ps.parent.conf.Producer.Flush.MaxMessages:
  208. return true
  209. default:
  210. return false
  211. }
  212. }
  213. func (ps *produceSet) readyToFlush() bool {
  214. switch {
  215. // If we don't have any messages, nothing else matters
  216. case ps.empty():
  217. return false
  218. // If all three config values are 0, we always flush as-fast-as-possible
  219. case ps.parent.conf.Producer.Flush.Frequency == 0 && ps.parent.conf.Producer.Flush.Bytes == 0 && ps.parent.conf.Producer.Flush.Messages == 0:
  220. return true
  221. // If we've passed the message trigger-point
  222. case ps.parent.conf.Producer.Flush.Messages > 0 && ps.bufferCount >= ps.parent.conf.Producer.Flush.Messages:
  223. return true
  224. // If we've passed the byte trigger-point
  225. case ps.parent.conf.Producer.Flush.Bytes > 0 && ps.bufferBytes >= ps.parent.conf.Producer.Flush.Bytes:
  226. return true
  227. default:
  228. return false
  229. }
  230. }
  231. func (ps *produceSet) empty() bool {
  232. return ps.bufferCount == 0
  233. }