config.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. package sarama
  2. import "time"
  3. // Config is used to pass multiple configuration options to Sarama's constructors.
  4. type Config struct {
  5. // Net is the namespace for network-level properties used by the Broker, and shared by the Client/Producer/Consumer.
  6. Net struct {
  7. MaxOpenRequests int // How many outstanding requests a connection is allowed to have before sending on it blocks (default 5).
  8. // All three of the below configurations are similar to the `socket.timeout.ms` setting in JVM kafka.
  9. DialTimeout time.Duration // How long to wait for the initial connection to succeed before timing out and returning an error (default 30s).
  10. ReadTimeout time.Duration // How long to wait for a response before timing out and returning an error (default 30s).
  11. WriteTimeout time.Duration // How long to wait for a transmit to succeed before timing out and returning an error (default 30s).
  12. }
  13. // Metadata is the namespace for metadata management properties used by the Client, and shared by the Producer/Consumer.
  14. Metadata struct {
  15. Retry struct {
  16. Max int // The total number of times to retry a metadata request when the cluster is in the middle of a leader election (default 3).
  17. Backoff time.Duration // How long to wait for leader election to occur before retrying (default 250ms). Similar to the JVM's `retry.backoff.ms`.
  18. }
  19. // How frequently to refresh the cluster metadata in the background. Defaults to 10 minutes.
  20. // Set to 0 to disable. Similar to `topic.metadata.refresh.interval.ms` in the JVM version.
  21. RefreshFrequency time.Duration
  22. }
  23. // Producer is the namespace for configuration related to producing messages, used by the Producer.
  24. Producer struct {
  25. // The maximum permitted size of a message (defaults to 1000000). Should be set equal to or smaller than the broker's `message.max.bytes`.
  26. MaxMessageBytes int
  27. // The level of acknowledgement reliability needed from the broker (defaults to WaitForLocal).
  28. // Equivalent to the `request.required.acks` setting of the JVM producer.
  29. RequiredAcks RequiredAcks
  30. // The maximum duration the broker will wait the receipt of the number of RequiredAcks (defaults to 10 seconds).
  31. // This is only relevant when RequiredAcks is set to WaitForAll or a number > 1. Only supports millisecond resolution,
  32. // nanoseconds will be truncated. Equivalent to the JVM producer's `request.timeout.ms` setting.
  33. Timeout time.Duration
  34. // The type of compression to use on messages (defaults to no compression). Similar to `compression.codec` setting of the JVM producer.
  35. Compression CompressionCodec
  36. // Generates partitioners for choosing the partition to send messages to (defaults to hashing the message key).
  37. // Similar to the `partitioner.class` setting for the JVM producer.
  38. Partitioner PartitionerConstructor
  39. // Return specifies what channels will be populated. If they are set to true, you must read from
  40. // the respective channels to prevent deadlock.
  41. Return struct {
  42. // If enabled, successfully delivered messages will be returned on the Successes channel (default disabled).
  43. Successes bool
  44. // If enabled, messages that failed to deliver will be returned on the Errors channel, including error (default enabled).
  45. Errors bool
  46. }
  47. // The following config options control how often messages are batched up and sent to the broker. By default,
  48. // messages are sent as fast as possible, and all messages received while the current batch is in-flight are placed
  49. // into the subsequent batch.
  50. Flush struct {
  51. Bytes int // The best-effort number of bytes needed to trigger a flush. Use the global sarama.MaxRequestSize to set a hard upper limit.
  52. Messages int // The best-effort number of messages needed to trigger a flush. Use `MaxMessages` to set a hard upper limit.
  53. Frequency time.Duration // The best-effort frequency of flushes. Equivalent to `queue.buffering.max.ms` setting of JVM producer.
  54. // The maximum number of messages the producer will send in a single broker request.
  55. // Defaults to 0 for unlimited. Similar to `queue.buffering.max.messages` in the JVM producer.
  56. MaxMessages int
  57. }
  58. Retry struct {
  59. // The total number of times to retry sending a message (default 3).
  60. // Similar to the `message.send.max.retries` setting of the JVM producer.
  61. Max int
  62. // How long to wait for the cluster to settle between retries (default 100ms).
  63. // Similar to the `retry.backoff.ms` setting of the JVM producer.
  64. Backoff time.Duration
  65. }
  66. }
  67. // Consumer is the namespace for configuration related to consuming messages, used by the Consumer.
  68. Consumer struct {
  69. Retry struct {
  70. // How long to wait after a failing to read from a partition before trying again (default 2s).
  71. Backoff time.Duration
  72. }
  73. // Fetch is the namespace for controlling how many bytes are retrieved by any given request.
  74. Fetch struct {
  75. // The minimum number of message bytes to fetch in a request - the broker will wait until at least this many are available.
  76. // The default is 1, as 0 causes the consumer to spin when no messages are available. Equivalent to the JVM's `fetch.min.bytes`.
  77. Min int32
  78. // The default number of message bytes to fetch from the broker in each request (default 32768). This should be larger than the
  79. // majority of your messages, or else the consumer will spend a lot of time negotiating sizes and not actually consuming. Similar
  80. // to the JVM's `fetch.message.max.bytes`.
  81. Default int32
  82. // The maximum number of message bytes to fetch from the broker in a single request. Messages larger than this will return
  83. // ErrMessageTooLarge and will not be consumable, so you must be sure this is at least as large as your largest message.
  84. // Defaults to 0 (no limit). Similar to the JVM's `fetch.message.max.bytes`. The global `sarama.MaxResponseSize` still applies.
  85. Max int32
  86. }
  87. // The maximum amount of time the broker will wait for Consumer.Fetch.Min bytes to become available before it
  88. // returns fewer than that anyways. The default is 250ms, since 0 causes the consumer to spin when no events are available.
  89. // 100-500ms is a reasonable range for most cases. Kafka only supports precision up to milliseconds; nanoseconds will be truncated.
  90. // Equivalent to the JVM's `fetch.wait.max.ms`.
  91. MaxWaitTime time.Duration
  92. // Return specifies what channels will be populated. If they are set to true, you must read from
  93. // them to prevent deadlock.
  94. Return struct {
  95. // If enabled, any errors that occured while consuming are returned on the Errors channel (default disabled).
  96. Errors bool
  97. }
  98. }
  99. // A user-provided string sent with every request to the brokers for logging, debugging, and auditing purposes.
  100. // Defaults to "sarama", but you should probably set it to something specific to your application.
  101. ClientID string
  102. // The number of events to buffer in internal and external channels. This permits the producer and consumer to
  103. // continue processing some messages in the background while user code is working, greatly improving throughput.
  104. // Defaults to 256.
  105. ChannelBufferSize int
  106. }
  107. // NewConfig returns a new configuration instance with sane defaults.
  108. func NewConfig() *Config {
  109. c := &Config{}
  110. c.Net.MaxOpenRequests = 5
  111. c.Net.DialTimeout = 30 * time.Second
  112. c.Net.ReadTimeout = 30 * time.Second
  113. c.Net.WriteTimeout = 30 * time.Second
  114. c.Metadata.Retry.Max = 3
  115. c.Metadata.Retry.Backoff = 250 * time.Millisecond
  116. c.Metadata.RefreshFrequency = 10 * time.Minute
  117. c.Producer.MaxMessageBytes = 1000000
  118. c.Producer.RequiredAcks = WaitForLocal
  119. c.Producer.Timeout = 10 * time.Second
  120. c.Producer.Partitioner = NewHashPartitioner
  121. c.Producer.Retry.Max = 3
  122. c.Producer.Retry.Backoff = 100 * time.Millisecond
  123. c.Producer.Return.Errors = true
  124. c.Consumer.Fetch.Min = 1
  125. c.Consumer.Fetch.Default = 32768
  126. c.Consumer.Retry.Backoff = 2 * time.Second
  127. c.Consumer.MaxWaitTime = 250 * time.Millisecond
  128. c.Consumer.Return.Errors = false
  129. c.ChannelBufferSize = 256
  130. return c
  131. }
  132. // Validate checks a Config instance. It will return a
  133. // ConfigurationError if the specified values don't make sense.
  134. func (c *Config) Validate() error {
  135. // some configuration values should be warned on but not fail completely, do those first
  136. if c.Producer.RequiredAcks > 1 {
  137. Logger.Println("Producer.RequiredAcks > 1 is deprecated and will raise an exception with kafka >= 0.8.2.0.")
  138. }
  139. if c.Producer.MaxMessageBytes >= forceFlushThreshold() {
  140. Logger.Println("Producer.MaxMessageBytes is too close to MaxRequestSize; it will be ignored.")
  141. }
  142. if c.Producer.Flush.Bytes >= forceFlushThreshold() {
  143. Logger.Println("Producer.Flush.Bytes is too close to MaxRequestSize; it will be ignored.")
  144. }
  145. if c.Producer.Timeout%time.Millisecond != 0 {
  146. Logger.Println("Producer.Timeout only supports millisecond resolution; nanoseconds will be truncated.")
  147. }
  148. if c.Consumer.MaxWaitTime < 100*time.Millisecond {
  149. Logger.Println("Consumer.MaxWaitTime is very low, which can cause high CPU and network usage. See documentation for details.")
  150. }
  151. if c.Consumer.MaxWaitTime%time.Millisecond != 0 {
  152. Logger.Println("Consumer.MaxWaitTime only supports millisecond precision; nanoseconds will be truncated.")
  153. }
  154. if c.ClientID == "sarama" {
  155. Logger.Println("ClientID is the default of 'sarama', you should consider setting it to something application-specific.")
  156. }
  157. // validate Net values
  158. switch {
  159. case c.Net.MaxOpenRequests <= 0:
  160. return ConfigurationError("Invalid Net.MaxOpenRequests, must be > 0")
  161. case c.Net.DialTimeout <= 0:
  162. return ConfigurationError("Invalid Net.DialTimeout, must be > 0")
  163. case c.Net.ReadTimeout <= 0:
  164. return ConfigurationError("Invalid Net.ReadTimeout, must be > 0")
  165. case c.Net.WriteTimeout <= 0:
  166. return ConfigurationError("Invalid Net.WriteTimeout, must be > 0")
  167. }
  168. // validate the Metadata values
  169. switch {
  170. case c.Metadata.Retry.Max < 0:
  171. return ConfigurationError("Invalid Metadata.Retry.Max, must be >= 0")
  172. case c.Metadata.Retry.Backoff < 0:
  173. return ConfigurationError("Invalid Metadata.Retry.Backoff, must be >= 0")
  174. case c.Metadata.RefreshFrequency < 0:
  175. return ConfigurationError("Invalid Metadata.RefreshFrequency, must be >= 0")
  176. }
  177. // validate the Producer values
  178. switch {
  179. case c.Producer.MaxMessageBytes <= 0:
  180. return ConfigurationError("Invalid Producer.MaxMessageBytes, must be > 0")
  181. case c.Producer.RequiredAcks < -1:
  182. return ConfigurationError("Invalid Producer.RequiredAcks, must be >= -1")
  183. case c.Producer.Timeout <= 0:
  184. return ConfigurationError("Invalid Producer.Timeout, must be > 0")
  185. case c.Producer.Partitioner == nil:
  186. return ConfigurationError("Invalid Producer.Partitioner, must not be nil")
  187. case c.Producer.Flush.Bytes < 0:
  188. return ConfigurationError("Invalid Producer.Flush.Bytes, must be >= 0")
  189. case c.Producer.Flush.Messages < 0:
  190. return ConfigurationError("Invalid Producer.Flush.Messages, must be >= 0")
  191. case c.Producer.Flush.Frequency < 0:
  192. return ConfigurationError("Invalid Producer.Flush.Frequency, must be >= 0")
  193. case c.Producer.Flush.MaxMessages < 0:
  194. return ConfigurationError("Invalid Producer.Flush.MaxMessages, must be >= 0")
  195. case c.Producer.Flush.MaxMessages > 0 && c.Producer.Flush.MaxMessages < c.Producer.Flush.Messages:
  196. return ConfigurationError("Invalid Producer.Flush.MaxMessages, must be >= Producer.Flush.Messages when set")
  197. case c.Producer.Retry.Max < 0:
  198. return ConfigurationError("Invalid Producer.Retry.Max, must be >= 0")
  199. case c.Producer.Retry.Backoff < 0:
  200. return ConfigurationError("Invalid Producer.Retry.Backoff, must be >= 0")
  201. }
  202. // validate the Consumer values
  203. switch {
  204. case c.Consumer.Fetch.Min <= 0:
  205. return ConfigurationError("Invalid Consumer.Fetch.Min, must be > 0")
  206. case c.Consumer.Fetch.Default <= 0:
  207. return ConfigurationError("Invalid Consumer.Fetch.Default, must be > 0")
  208. case c.Consumer.Fetch.Max < 0:
  209. return ConfigurationError("Invalid Consumer.Fetch.Max, must be >= 0")
  210. case c.Consumer.MaxWaitTime < 1*time.Millisecond:
  211. return ConfigurationError("Invalid Consumer.MaxWaitTime, must be > 1ms")
  212. case c.Consumer.Retry.Backoff < 0:
  213. return ConfigurationError("Invalid Consumer.Retry.Backoff, must be >= 0")
  214. }
  215. // validate misc shared values
  216. switch {
  217. case c.ChannelBufferSize < 0:
  218. return ConfigurationError("Invalid ChannelBufferSize, must be >= 0")
  219. }
  220. return nil
  221. }