produce_set.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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. }
  55. set = &partitionSet{recordsToSend: newDefaultRecords(batch)}
  56. size = recordBatchOverhead
  57. } else {
  58. set = &partitionSet{recordsToSend: newLegacyRecords(new(MessageSet))}
  59. }
  60. partitions[msg.Partition] = set
  61. }
  62. set.msgs = append(set.msgs, msg)
  63. if ps.parent.conf.Version.IsAtLeast(V0_11_0_0) {
  64. // We are being conservative here to avoid having to prep encode the record
  65. size += maximumRecordOverhead
  66. rec := &Record{
  67. Key: key,
  68. Value: val,
  69. TimestampDelta: timestamp.Sub(set.recordsToSend.recordBatch.FirstTimestamp),
  70. }
  71. size += len(key) + len(val)
  72. if len(msg.Headers) > 0 {
  73. rec.Headers = make([]*RecordHeader, len(msg.Headers))
  74. for i := range msg.Headers {
  75. rec.Headers[i] = &msg.Headers[i]
  76. size += len(rec.Headers[i].Key) + len(rec.Headers[i].Value) + 2*binary.MaxVarintLen32
  77. }
  78. }
  79. set.recordsToSend.recordBatch.addRecord(rec)
  80. } else {
  81. msgToSend := &Message{Codec: CompressionNone, Key: key, Value: val}
  82. if ps.parent.conf.Version.IsAtLeast(V0_10_0_0) {
  83. msgToSend.Timestamp = timestamp
  84. msgToSend.Version = 1
  85. }
  86. set.recordsToSend.msgSet.addMessage(msgToSend)
  87. size = producerMessageOverhead + len(key) + len(val)
  88. }
  89. set.bufferBytes += size
  90. ps.bufferBytes += size
  91. ps.bufferCount++
  92. return nil
  93. }
  94. func (ps *produceSet) buildRequest() *ProduceRequest {
  95. req := &ProduceRequest{
  96. RequiredAcks: ps.parent.conf.Producer.RequiredAcks,
  97. Timeout: int32(ps.parent.conf.Producer.Timeout / time.Millisecond),
  98. }
  99. if ps.parent.conf.Version.IsAtLeast(V0_10_0_0) {
  100. req.Version = 2
  101. }
  102. if ps.parent.conf.Version.IsAtLeast(V0_11_0_0) {
  103. req.Version = 3
  104. }
  105. for topic, partitionSet := range ps.msgs {
  106. for partition, set := range partitionSet {
  107. if req.Version >= 3 {
  108. req.AddBatch(topic, partition, set.recordsToSend.recordBatch)
  109. continue
  110. }
  111. if ps.parent.conf.Producer.Compression == CompressionNone {
  112. req.AddSet(topic, partition, set.recordsToSend.msgSet)
  113. } else {
  114. // When compression is enabled, the entire set for each partition is compressed
  115. // and sent as the payload of a single fake "message" with the appropriate codec
  116. // set and no key. When the server sees a message with a compression codec, it
  117. // decompresses the payload and treats the result as its message set.
  118. if ps.parent.conf.Version.IsAtLeast(V0_10_0_0) {
  119. // If our version is 0.10 or later, assign relative offsets
  120. // to the inner messages. This lets the broker avoid
  121. // recompressing the message set.
  122. // (See https://cwiki.apache.org/confluence/display/KAFKA/KIP-31+-+Move+to+relative+offsets+in+compressed+message+sets
  123. // for details on relative offsets.)
  124. for i, msg := range set.recordsToSend.msgSet.Messages {
  125. msg.Offset = int64(i)
  126. }
  127. }
  128. payload, err := encode(set.recordsToSend.msgSet, ps.parent.conf.MetricRegistry)
  129. if err != nil {
  130. Logger.Println(err) // if this happens, it's basically our fault.
  131. panic(err)
  132. }
  133. compMsg := &Message{
  134. Codec: ps.parent.conf.Producer.Compression,
  135. Key: nil,
  136. Value: payload,
  137. Set: set.recordsToSend.msgSet, // Provide the underlying message set for accurate metrics
  138. }
  139. if ps.parent.conf.Version.IsAtLeast(V0_10_0_0) {
  140. compMsg.Version = 1
  141. compMsg.Timestamp = set.recordsToSend.msgSet.Messages[0].Msg.Timestamp
  142. }
  143. req.AddMessage(topic, partition, compMsg)
  144. }
  145. }
  146. }
  147. return req
  148. }
  149. func (ps *produceSet) eachPartition(cb func(topic string, partition int32, msgs []*ProducerMessage)) {
  150. for topic, partitionSet := range ps.msgs {
  151. for partition, set := range partitionSet {
  152. cb(topic, partition, set.msgs)
  153. }
  154. }
  155. }
  156. func (ps *produceSet) dropPartition(topic string, partition int32) []*ProducerMessage {
  157. if ps.msgs[topic] == nil {
  158. return nil
  159. }
  160. set := ps.msgs[topic][partition]
  161. if set == nil {
  162. return nil
  163. }
  164. ps.bufferBytes -= set.bufferBytes
  165. ps.bufferCount -= len(set.msgs)
  166. delete(ps.msgs[topic], partition)
  167. return set.msgs
  168. }
  169. func (ps *produceSet) wouldOverflow(msg *ProducerMessage) bool {
  170. version := 1
  171. if ps.parent.conf.Version.IsAtLeast(V0_11_0_0) {
  172. version = 2
  173. }
  174. switch {
  175. // Would we overflow our maximum possible size-on-the-wire? 10KiB is arbitrary overhead for safety.
  176. case ps.bufferBytes+msg.byteSize(version) >= int(MaxRequestSize-(10*1024)):
  177. return true
  178. // Would we overflow the size-limit of a compressed message-batch for this partition?
  179. case ps.parent.conf.Producer.Compression != CompressionNone &&
  180. ps.msgs[msg.Topic] != nil && ps.msgs[msg.Topic][msg.Partition] != nil &&
  181. ps.msgs[msg.Topic][msg.Partition].bufferBytes+msg.byteSize(version) >= ps.parent.conf.Producer.MaxMessageBytes:
  182. return true
  183. // Would we overflow simply in number of messages?
  184. case ps.parent.conf.Producer.Flush.MaxMessages > 0 && ps.bufferCount >= ps.parent.conf.Producer.Flush.MaxMessages:
  185. return true
  186. default:
  187. return false
  188. }
  189. }
  190. func (ps *produceSet) readyToFlush() bool {
  191. switch {
  192. // If we don't have any messages, nothing else matters
  193. case ps.empty():
  194. return false
  195. // If all three config values are 0, we always flush as-fast-as-possible
  196. case ps.parent.conf.Producer.Flush.Frequency == 0 && ps.parent.conf.Producer.Flush.Bytes == 0 && ps.parent.conf.Producer.Flush.Messages == 0:
  197. return true
  198. // If we've passed the message trigger-point
  199. case ps.parent.conf.Producer.Flush.Messages > 0 && ps.bufferCount >= ps.parent.conf.Producer.Flush.Messages:
  200. return true
  201. // If we've passed the byte trigger-point
  202. case ps.parent.conf.Producer.Flush.Bytes > 0 && ps.bufferBytes >= ps.parent.conf.Producer.Flush.Bytes:
  203. return true
  204. default:
  205. return false
  206. }
  207. }
  208. func (ps *produceSet) empty() bool {
  209. return ps.bufferCount == 0
  210. }