produce_set.go 7.7 KB

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