rdkafka 0.13.0 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +388 -111
  3. data/{LICENSE → MIT-LICENSE} +2 -1
  4. data/README.md +90 -43
  5. data/Rakefile +21 -23
  6. data/bin/verify_kafka_warnings +44 -0
  7. data/dist/librdkafka-2.15.1.tar.gz +0 -0
  8. data/dist/patches/rdkafka_global_init.patch +15 -0
  9. data/docker-compose-ssl.yml +39 -0
  10. data/docker-compose.yml +22 -17
  11. data/ext/Rakefile +97 -30
  12. data/lib/rdkafka/abstract_handle.rb +113 -34
  13. data/lib/rdkafka/admin/acl_binding_result.rb +51 -0
  14. data/lib/rdkafka/admin/alter_consumer_group_offsets_handle.rb +31 -0
  15. data/lib/rdkafka/admin/alter_consumer_group_offsets_report.rb +50 -0
  16. data/lib/rdkafka/admin/config_binding_result.rb +30 -0
  17. data/lib/rdkafka/admin/config_resource_binding_result.rb +19 -0
  18. data/lib/rdkafka/admin/create_acl_handle.rb +32 -0
  19. data/lib/rdkafka/admin/create_acl_report.rb +26 -0
  20. data/lib/rdkafka/admin/create_partitions_handle.rb +28 -0
  21. data/lib/rdkafka/admin/create_partitions_report.rb +7 -0
  22. data/lib/rdkafka/admin/create_topic_handle.rb +8 -7
  23. data/lib/rdkafka/admin/create_topic_report.rb +4 -1
  24. data/lib/rdkafka/admin/delete_acl_handle.rb +31 -0
  25. data/lib/rdkafka/admin/delete_acl_report.rb +25 -0
  26. data/lib/rdkafka/admin/delete_consumer_group_offsets_handle.rb +31 -0
  27. data/lib/rdkafka/admin/delete_consumer_group_offsets_report.rb +50 -0
  28. data/lib/rdkafka/admin/delete_groups_handle.rb +31 -0
  29. data/lib/rdkafka/admin/delete_groups_report.rb +27 -0
  30. data/lib/rdkafka/admin/delete_records_handle.rb +31 -0
  31. data/lib/rdkafka/admin/delete_records_report.rb +25 -0
  32. data/lib/rdkafka/admin/delete_topic_handle.rb +8 -7
  33. data/lib/rdkafka/admin/delete_topic_report.rb +4 -1
  34. data/lib/rdkafka/admin/describe_acl_handle.rb +31 -0
  35. data/lib/rdkafka/admin/describe_acl_report.rb +27 -0
  36. data/lib/rdkafka/admin/describe_cluster_handle.rb +31 -0
  37. data/lib/rdkafka/admin/describe_cluster_report.rb +48 -0
  38. data/lib/rdkafka/admin/describe_configs_handle.rb +30 -0
  39. data/lib/rdkafka/admin/describe_configs_report.rb +56 -0
  40. data/lib/rdkafka/admin/describe_consumer_groups_handle.rb +31 -0
  41. data/lib/rdkafka/admin/describe_consumer_groups_report.rb +151 -0
  42. data/lib/rdkafka/admin/describe_result_parsing.rb +47 -0
  43. data/lib/rdkafka/admin/describe_topics_handle.rb +31 -0
  44. data/lib/rdkafka/admin/describe_topics_report.rb +118 -0
  45. data/lib/rdkafka/admin/incremental_alter_configs_handle.rb +30 -0
  46. data/lib/rdkafka/admin/incremental_alter_configs_report.rb +56 -0
  47. data/lib/rdkafka/admin/list_consumer_groups_handle.rb +31 -0
  48. data/lib/rdkafka/admin/list_consumer_groups_report.rb +83 -0
  49. data/lib/rdkafka/admin/list_offsets_handle.rb +31 -0
  50. data/lib/rdkafka/admin/list_offsets_report.rb +54 -0
  51. data/lib/rdkafka/admin.rb +1381 -38
  52. data/lib/rdkafka/bindings/admin/acls.rb +85 -0
  53. data/lib/rdkafka/bindings/admin/configs.rb +37 -0
  54. data/lib/rdkafka/bindings/admin/list_offsets.rb +26 -0
  55. data/lib/rdkafka/bindings/admin.rb +197 -0
  56. data/lib/rdkafka/bindings/callbacks.rb +100 -0
  57. data/lib/rdkafka/bindings/configuration.rb +50 -0
  58. data/lib/rdkafka/bindings/consumer.rb +83 -0
  59. data/lib/rdkafka/bindings/errors.rb +15 -0
  60. data/lib/rdkafka/bindings/handle.rb +16 -0
  61. data/lib/rdkafka/bindings/messages.rb +28 -0
  62. data/lib/rdkafka/bindings/metadata.rb +14 -0
  63. data/lib/rdkafka/bindings/polling.rb +17 -0
  64. data/lib/rdkafka/bindings/producer.rb +77 -0
  65. data/lib/rdkafka/bindings/structs.rb +62 -0
  66. data/lib/rdkafka/bindings.rb +69 -294
  67. data/lib/rdkafka/callbacks/alter_consumer_group_offsets_handler.rb +65 -0
  68. data/lib/rdkafka/callbacks/base_handler.rb +62 -0
  69. data/lib/rdkafka/callbacks/create_acl_handler.rb +37 -0
  70. data/lib/rdkafka/callbacks/create_partitions_handler.rb +37 -0
  71. data/lib/rdkafka/callbacks/create_topic_handler.rb +37 -0
  72. data/lib/rdkafka/callbacks/delete_acl_handler.rb +42 -0
  73. data/lib/rdkafka/callbacks/delete_consumer_group_offsets_handler.rb +65 -0
  74. data/lib/rdkafka/callbacks/delete_groups_handler.rb +37 -0
  75. data/lib/rdkafka/callbacks/delete_records_handler.rb +38 -0
  76. data/lib/rdkafka/callbacks/delete_topic_handler.rb +37 -0
  77. data/lib/rdkafka/callbacks/describe_acl_handler.rb +35 -0
  78. data/lib/rdkafka/callbacks/describe_cluster_handler.rb +36 -0
  79. data/lib/rdkafka/callbacks/describe_configs_handler.rb +42 -0
  80. data/lib/rdkafka/callbacks/describe_consumer_groups_handler.rb +36 -0
  81. data/lib/rdkafka/callbacks/describe_topics_handler.rb +36 -0
  82. data/lib/rdkafka/callbacks/incremental_alter_configs_handler.rb +42 -0
  83. data/lib/rdkafka/callbacks/list_consumer_groups_handler.rb +39 -0
  84. data/lib/rdkafka/callbacks/list_offsets_handler.rb +42 -0
  85. data/lib/rdkafka/callbacks.rb +273 -52
  86. data/lib/rdkafka/clients.rb +81 -0
  87. data/lib/rdkafka/config.rb +333 -91
  88. data/lib/rdkafka/consumer/allocator.rb +38 -0
  89. data/lib/rdkafka/consumer/headers.rb +39 -25
  90. data/lib/rdkafka/consumer/message.rb +18 -20
  91. data/lib/rdkafka/consumer/partition.rb +15 -4
  92. data/lib/rdkafka/consumer/topic_partition_list.rb +82 -48
  93. data/lib/rdkafka/consumer.rb +765 -192
  94. data/lib/rdkafka/defaults.rb +123 -0
  95. data/lib/rdkafka/error.rb +40 -14
  96. data/lib/rdkafka/helpers/list_offsets.rb +127 -0
  97. data/lib/rdkafka/helpers/metadata.rb +29 -0
  98. data/lib/rdkafka/helpers/oauth.rb +95 -0
  99. data/lib/rdkafka/helpers/time.rb +19 -0
  100. data/lib/rdkafka/metadata.rb +138 -26
  101. data/lib/rdkafka/native_kafka.rb +142 -22
  102. data/lib/rdkafka/producer/delivery_handle.rb +27 -7
  103. data/lib/rdkafka/producer/delivery_report.rb +71 -4
  104. data/lib/rdkafka/producer/partitions_count_cache.rb +212 -0
  105. data/lib/rdkafka/producer.rb +422 -81
  106. data/lib/rdkafka/version.rb +6 -3
  107. data/lib/rdkafka.rb +73 -1
  108. data/package-lock.json +331 -0
  109. data/package.json +9 -0
  110. data/rdkafka.gemspec +78 -25
  111. data/renovate.json +111 -0
  112. metadata +114 -134
  113. data/.gitignore +0 -8
  114. data/.rspec +0 -1
  115. data/.semaphore/semaphore.yml +0 -27
  116. data/.yardopts +0 -2
  117. data/Gemfile +0 -5
  118. data/Guardfile +0 -19
  119. data/ext/README.md +0 -18
  120. data/spec/rdkafka/abstract_handle_spec.rb +0 -115
  121. data/spec/rdkafka/admin/create_topic_handle_spec.rb +0 -54
  122. data/spec/rdkafka/admin/create_topic_report_spec.rb +0 -18
  123. data/spec/rdkafka/admin/delete_topic_handle_spec.rb +0 -54
  124. data/spec/rdkafka/admin/delete_topic_report_spec.rb +0 -18
  125. data/spec/rdkafka/admin_spec.rb +0 -204
  126. data/spec/rdkafka/bindings_spec.rb +0 -136
  127. data/spec/rdkafka/callbacks_spec.rb +0 -22
  128. data/spec/rdkafka/config_spec.rb +0 -197
  129. data/spec/rdkafka/consumer/headers_spec.rb +0 -62
  130. data/spec/rdkafka/consumer/message_spec.rb +0 -141
  131. data/spec/rdkafka/consumer/partition_spec.rb +0 -59
  132. data/spec/rdkafka/consumer/topic_partition_list_spec.rb +0 -225
  133. data/spec/rdkafka/consumer_spec.rb +0 -1106
  134. data/spec/rdkafka/error_spec.rb +0 -91
  135. data/spec/rdkafka/metadata_spec.rb +0 -80
  136. data/spec/rdkafka/native_kafka_spec.rb +0 -124
  137. data/spec/rdkafka/producer/delivery_handle_spec.rb +0 -47
  138. data/spec/rdkafka/producer/delivery_report_spec.rb +0 -23
  139. data/spec/rdkafka/producer_spec.rb +0 -557
  140. data/spec/spec_helper.rb +0 -155
@@ -1,10 +1,43 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "objspace"
4
-
5
3
  module Rdkafka
6
- # A producer for Kafka messages. To create a producer set up a {Config} and call {Config#producer producer} on that.
4
+ # A producer for Kafka messages. To create a producer set up a {Config} and call
5
+ # {Config#producer producer} on that.
7
6
  class Producer
7
+ include Helpers::Time
8
+ include Helpers::OAuth
9
+ include Helpers::Metadata
10
+
11
+ # @!visibility private
12
+ @@partitions_count_cache = PartitionsCountCache.new
13
+
14
+ # Global (process wide) partitions cache. We use it to store number of topics partitions,
15
+ # either from the librdkafka statistics (if enabled) or via direct inline calls every now and
16
+ # then. Since the partitions count can only grow and should be same for all consumers and
17
+ # producers, we can use a global cache as long as we ensure that updates only move up.
18
+ #
19
+ # @return [Rdkafka::Producer::PartitionsCountCache]
20
+ # @note It is critical to remember, that not all users may have statistics callbacks enabled,
21
+ # hence we should not make assumption that this cache is always updated from the stats.
22
+ def self.partitions_count_cache
23
+ @@partitions_count_cache
24
+ end
25
+
26
+ # @param partitions_count_cache [Rdkafka::Producer::PartitionsCountCache]
27
+ def self.partitions_count_cache=(partitions_count_cache)
28
+ @@partitions_count_cache = partitions_count_cache
29
+ end
30
+
31
+ # Empty hash used as a default
32
+ EMPTY_HASH = {}.freeze
33
+
34
+ private_constant :EMPTY_HASH
35
+
36
+ # Raised when there was a critical issue when invoking rd_kafka_topic_new
37
+ # This is a temporary solution until https://github.com/karafka/rdkafka-ruby/issues/451 is
38
+ # resolved and this is normalized in all the places
39
+ class TopicHandleCreationError < RuntimeError; end
40
+
8
41
  # @private
9
42
  # Returns the current delivery callback, by default this is nil.
10
43
  #
@@ -18,19 +51,109 @@ module Rdkafka
18
51
  attr_reader :delivery_callback_arity
19
52
 
20
53
  # @private
21
- def initialize(native_kafka, partitioner_name)
54
+ # @param native_kafka [NativeKafka]
55
+ # @param partitioner [String, nil] name of the partitioner we want to use or nil to use
56
+ # the "consistent_random" default
57
+ def initialize(native_kafka, partitioner)
58
+ @topics_refs_map = {}
59
+ @topics_configs = {}
22
60
  @native_kafka = native_kafka
23
- @partitioner_name = partitioner_name || "consistent_random"
61
+ @partitioner = partitioner || "consistent_random"
24
62
 
25
63
  # Makes sure, that native kafka gets closed before it gets GCed by Ruby
26
64
  ObjectSpace.define_finalizer(self, native_kafka.finalizer)
27
65
  end
28
66
 
67
+ # Sets alternative set of configuration details that can be set per topic
68
+ #
69
+ # @param topic [String] The topic name
70
+ # @param config [Hash] config we want to use per topic basis
71
+ # @param config_hash [Integer] hash of the config. We expect it here instead of computing it,
72
+ # because it is already computed during the retrieval attempt in the `#produce` flow.
73
+ # @note It is not allowed to re-set the same topic config twice because of the underlying
74
+ # librdkafka caching
75
+ def set_topic_config(topic, config, config_hash)
76
+ # Ensure lock on topic reference just in case
77
+ @native_kafka.with_inner do |inner|
78
+ @topics_refs_map[topic] ||= {}
79
+ @topics_configs[topic] ||= {}
80
+
81
+ return if @topics_configs[topic].key?(config_hash)
82
+
83
+ # If config is empty, we create an empty reference that will be used with defaults
84
+ rd_topic_config = if config.empty?
85
+ nil
86
+ else
87
+ Rdkafka::Bindings.rd_kafka_topic_conf_new.tap do |topic_config|
88
+ config.each do |key, value|
89
+ error_buffer = FFI::MemoryPointer.new(:char, 256)
90
+ result = Rdkafka::Bindings.rd_kafka_topic_conf_set(
91
+ topic_config,
92
+ key.to_s,
93
+ value.to_s,
94
+ error_buffer,
95
+ 256
96
+ )
97
+
98
+ unless result == :config_ok
99
+ # rd_kafka_topic_new has not been called yet, so librdkafka has not taken
100
+ # ownership of the config. Destroy it ourselves before raising, otherwise the
101
+ # partially built rd_kafka_topic_conf_t leaks. (On the rd_kafka_topic_new path
102
+ # librdkafka frees the conf on both success and failure, so we never destroy it
103
+ # there.)
104
+ Rdkafka::Bindings.rd_kafka_topic_conf_destroy(topic_config)
105
+ raise Config::ConfigError.new(error_buffer.read_string)
106
+ end
107
+ end
108
+ end
109
+ end
110
+
111
+ topic_handle = Bindings.rd_kafka_topic_new(inner, topic, rd_topic_config)
112
+
113
+ raise TopicHandleCreationError.new("Error creating topic handle for topic #{topic}") if topic_handle.null?
114
+
115
+ @topics_configs[topic][config_hash] = config
116
+ @topics_refs_map[topic][config_hash] = topic_handle
117
+ end
118
+ end
119
+
120
+ # Starts the native Kafka polling thread and kicks off the init polling
121
+ # @note Not needed to run unless explicit start was disabled
122
+ def start
123
+ @native_kafka.start
124
+ end
125
+
126
+ # @return [String] producer name
127
+ def name
128
+ @name ||= @native_kafka.with_inner do |inner|
129
+ ::Rdkafka::Bindings.rd_kafka_name(inner)
130
+ end
131
+ end
132
+
133
+ # Enable IO event notifications for fiber scheduler integration
134
+ # When delivery confirmations arrive, librdkafka will write to your FD
135
+ #
136
+ # @param fd [Integer] file descriptor to signal (from IO.pipe or eventfd)
137
+ # @param payload [String] data to write to fd (default: "\x01")
138
+ # @return [nil]
139
+ # @raise [ClosedInnerError] when the producer is closed
140
+ def enable_queue_io_events(fd, payload = "\x01")
141
+ @native_kafka.enable_main_queue_io_events(fd, payload)
142
+ end
143
+
144
+ # Enable IO event notifications for background events
145
+ # @param fd [Integer] file descriptor to signal (from IO.pipe or eventfd)
146
+ # @param payload [String] data to write to fd (default: "\x01")
147
+ # @return [nil]
148
+ # @raise [ClosedInnerError] when the producer is closed
149
+ def enable_background_queue_io_events(fd, payload = "\x01")
150
+ @native_kafka.enable_background_queue_io_events(fd, payload)
151
+ end
152
+
29
153
  # Set a callback that will be called every time a message is successfully produced.
30
154
  # The callback is called with a {DeliveryReport} and {DeliveryHandle}
31
155
  #
32
- # @param callback [Proc, #call] The callback
33
- #
156
+ # @param callback [Proc, #call] callable object to handle delivery reports
34
157
  # @return [nil]
35
158
  def delivery_callback=(callback)
36
159
  raise TypeError.new("Callback has to be callable") unless callback.respond_to?(:call)
@@ -42,7 +165,18 @@ module Rdkafka
42
165
  def close
43
166
  return if closed?
44
167
  ObjectSpace.undefine_finalizer(self)
45
- @native_kafka.close
168
+
169
+ @native_kafka.close do
170
+ # We need to remove the topics references objects before we destroy the producer,
171
+ # otherwise they would leak out
172
+ @topics_refs_map.each_value do |refs|
173
+ refs.each_value do |ref|
174
+ Rdkafka::Bindings.rd_kafka_topic_destroy(ref)
175
+ end
176
+ end
177
+ end
178
+
179
+ @topics_refs_map.clear
46
180
  end
47
181
 
48
182
  # Whether this producer has closed
@@ -54,138 +188,339 @@ module Rdkafka
54
188
  # in seconds. Call this before closing a producer to ensure delivery of all messages.
55
189
  #
56
190
  # @param timeout_ms [Integer] how long should we wait for flush of all messages
57
- def flush(timeout_ms=5_000)
191
+ # @return [Boolean] true if no more data and all was flushed, false in case there are still
192
+ # outgoing messages after the timeout
193
+ #
194
+ # @note We raise an exception for other errors because based on the librdkafka docs, there
195
+ # should be no other errors.
196
+ #
197
+ # @note For `timed_out` we do not raise an error to keep it backwards compatible
198
+ def flush(timeout_ms = Defaults::PRODUCER_FLUSH_TIMEOUT_MS)
58
199
  closed_producer_check(__method__)
59
200
 
201
+ code = nil
202
+
60
203
  @native_kafka.with_inner do |inner|
61
- Rdkafka::Bindings.rd_kafka_flush(inner, timeout_ms)
204
+ code = Rdkafka::Bindings.rd_kafka_flush(inner, timeout_ms)
205
+ end
206
+
207
+ # Early skip not to build the error message
208
+ return true if code.zero?
209
+
210
+ error = Rdkafka::RdkafkaError.new(code)
211
+
212
+ return false if error.code == :timed_out
213
+
214
+ raise(error)
215
+ end
216
+
217
+ # Purges the outgoing queue and releases all resources.
218
+ #
219
+ # Useful when closing the producer with outgoing messages to unstable clusters or when for
220
+ # any other reasons waiting cannot go on anymore. This purges both the queue and all the
221
+ # inflight requests + updates the delivery handles statuses so they can be materialized into
222
+ # `purge_queue` errors.
223
+ def purge
224
+ closed_producer_check(__method__)
225
+
226
+ code = nil
227
+
228
+ @native_kafka.with_inner do |inner|
229
+ code = Bindings.rd_kafka_purge(
230
+ inner,
231
+ Bindings::RD_KAFKA_PURGE_F_QUEUE | Bindings::RD_KAFKA_PURGE_F_INFLIGHT
232
+ )
233
+ end
234
+
235
+ code.zero? || raise(Rdkafka::RdkafkaError.new(code))
236
+
237
+ # Wait for the purge to affect everything
238
+ sleep(Defaults::PRODUCER_PURGE_SLEEP_INTERVAL_MS / 1000.0) until flush(Defaults::PRODUCER_PURGE_FLUSH_TIMEOUT_MS)
239
+
240
+ true
241
+ end
242
+
243
+ # Returns the number of messages and requests waiting to be sent to the broker as well as
244
+ # delivery reports queued for the application.
245
+ #
246
+ # This provides visibility into the producer's internal queue depth, useful for:
247
+ # - Monitoring producer backpressure
248
+ # - Implementing custom flow control
249
+ # - Debugging message delivery issues
250
+ # - Graceful shutdown logic (wait until queue is empty)
251
+ #
252
+ # @return [Integer] the number of messages in the queue
253
+ # @raise [Rdkafka::ClosedProducerError] if called on a closed producer
254
+ #
255
+ # @example
256
+ # producer.queue_size #=> 42
257
+ # @note This method is thread-safe as it uses the @native_kafka.with_inner synchronization
258
+ def queue_size
259
+ closed_producer_check(__method__)
260
+
261
+ @native_kafka.with_inner do |inner|
262
+ Rdkafka::Bindings.rd_kafka_outq_len(inner)
263
+ end
264
+ end
265
+
266
+ alias_method :queue_length, :queue_size
267
+
268
+ # Polls for events in a non-blocking loop, yielding the count after each iteration.
269
+ #
270
+ # This method processes delivery callbacks in a single GVL/mutex session, which is more
271
+ # efficient than repeated individual polls. It uses non-blocking polls internally
272
+ # (no GVL release between polls).
273
+ #
274
+ # Yields the count of events processed after each poll iteration, allowing the caller
275
+ # to implement timeout or other termination logic by returning `:stop`.
276
+ #
277
+ # @yield [count] Called after each poll iteration
278
+ # @yieldparam count [Integer] Number of events processed in this iteration
279
+ # @yieldreturn [Symbol, Object] Return `:stop` to break the loop, any other value continues
280
+ # @return [nil]
281
+ # @raise [Rdkafka::ClosedProducerError] if called on a closed producer
282
+ #
283
+ # @example Drain all pending callbacks
284
+ # producer.events_poll_nb_each { |_count| }
285
+ #
286
+ # @example With timeout control
287
+ # deadline = monotonic_now + timeout_ms
288
+ # producer.events_poll_nb_each do |_count|
289
+ # :stop if monotonic_now >= deadline
290
+ # end
291
+ # @note This method holds the inner lock until the queue is empty or `:stop` is returned.
292
+ # Other producer operations (produce, close, etc.) will wait until this method returns.
293
+ # @note This method is thread-safe as it uses @native_kafka.with_inner synchronization
294
+ def events_poll_nb_each
295
+ closed_producer_check(__method__)
296
+
297
+ @native_kafka.with_inner do |inner|
298
+ loop do
299
+ count = Rdkafka::Bindings.rd_kafka_poll_nb(inner, 0)
300
+ break if count.zero?
301
+ break if yield(count) == :stop
302
+ end
62
303
  end
63
304
  end
64
305
 
65
306
  # Partition count for a given topic.
66
- # NOTE: If 'allow.auto.create.topics' is set to true in the broker, the topic will be auto-created after returning nil.
67
307
  #
68
308
  # @param topic [String] The topic name.
309
+ # @return [Integer] partition count for a given topic or `-1` if it could not be obtained.
310
+ #
311
+ # @note If 'allow.auto.create.topics' is set to true in the broker, the topic will be
312
+ # auto-created after returning nil.
313
+ #
314
+ # @note We cache the partition count for a given topic for given time. If statistics are
315
+ # enabled for any producer or consumer, it will take precedence over per instance fetching.
69
316
  #
70
- # @return partition count [Integer,nil]
317
+ # This prevents us in case someone uses `partition_key` from querying for the count with
318
+ # each message. Instead we query at most once every 30 seconds at most if we have a valid
319
+ # partition count or every 5 seconds in case we were not able to obtain number of partitions.
71
320
  def partition_count(topic)
72
321
  closed_producer_check(__method__)
73
- @native_kafka.with_inner do |inner|
74
- Rdkafka::Metadata.new(inner, topic).topics&.first[:partition_count]
322
+
323
+ self.class.partitions_count_cache.get(topic) do
324
+ topic_metadata = nil
325
+
326
+ @native_kafka.with_inner do |inner|
327
+ topic_metadata = ::Rdkafka::Metadata.new(inner, topic).topics&.first
328
+ end
329
+
330
+ topic_metadata ? topic_metadata[:partition_count] : Rdkafka::Bindings::RD_KAFKA_PARTITION_UA
331
+ rescue Rdkafka::RdkafkaError => e
332
+ # A missing topic is an expected, cacheable outcome (the topic may be auto-created on
333
+ # produce, or simply not exist yet). Returning RD_KAFKA_PARTITION_UA from inside the block
334
+ # caches it, so we don't re-run a blocking metadata query on every produce(partition_key:)
335
+ # to that topic. Anything else is a real error and is re-raised.
336
+ raise(e) unless e.code == :unknown_topic_or_part
337
+
338
+ Rdkafka::Bindings::RD_KAFKA_PARTITION_UA
75
339
  end
76
340
  end
77
341
 
78
- # Produces a message to a Kafka topic. The message is added to rdkafka's queue, call {DeliveryHandle#wait wait} on the returned delivery handle to make sure it is delivered.
342
+ # Produces a message to a Kafka topic. The message is added to rdkafka's queue, call
343
+ # {DeliveryHandle#wait wait} on the returned delivery handle to make sure it is delivered.
79
344
  #
80
- # When no partition is specified the underlying Kafka library picks a partition based on the key. If no key is specified, a random partition will be used.
81
- # When a timestamp is provided this is used instead of the auto-generated timestamp.
345
+ # When no partition is specified the underlying Kafka library picks a partition based on the
346
+ # key. If no key is specified, a random partition will be used. When a timestamp is provided
347
+ # this is used instead of the auto-generated timestamp.
82
348
  #
83
349
  # @param topic [String] The topic to produce to
84
- # @param payload [String,nil] The message's payload
85
- # @param key [String, nil] The message's key
86
- # @param partition [Integer,nil] Optional partition to produce to
87
- # @param partition_key [String, nil] Optional partition key based on which partition assignment can happen
88
- # @param timestamp [Time,Integer,nil] Optional timestamp of this message. Integer timestamp is in milliseconds since Jan 1 1970.
89
- # @param headers [Hash<String,String>] Optional message headers
350
+ # @param payload [String, nil]
351
+ # @param key [String, nil]
352
+ # @param partition [Integer, nil] Optional partition to produce to
353
+ # @param partition_key [String, nil] Optional partition key based on which partition
354
+ # assignment can happen
355
+ # @param timestamp [Time, Integer, nil] Optional timestamp of this message. Integer
356
+ # timestamp is in milliseconds since Jan 1 1970.
357
+ # @param headers [Hash{String => String, Array<String>}] Optional message headers. Values
358
+ # can be either a single string or an array of strings to support duplicate headers per
359
+ # KIP-82
360
+ # @param label [Object, nil] a label that can be assigned when producing a message that
361
+ # will be part of the delivery handle and the delivery report
362
+ # @param topic_config [Hash] topic config for given message dispatch. Allows to send
363
+ # messages to topics with different configuration
364
+ # @param partitioner [String] name of the partitioner to use
90
365
  #
91
- # @raise [RdkafkaError] When adding the message to rdkafka's queue failed
366
+ # @return [DeliveryHandle] Delivery handle that can be used to wait for the result of
367
+ # producing this message
92
368
  #
93
- # @return [DeliveryHandle] Delivery handle that can be used to wait for the result of producing this message
94
- def produce(topic:, payload: nil, key: nil, partition: nil, partition_key: nil, timestamp: nil, headers: nil)
369
+ # @raise [RdkafkaError] When adding the message to rdkafka's queue failed
370
+ def produce(
371
+ topic:,
372
+ payload: nil,
373
+ key: nil,
374
+ partition: nil,
375
+ partition_key: nil,
376
+ timestamp: nil,
377
+ headers: nil,
378
+ label: nil,
379
+ topic_config: EMPTY_HASH,
380
+ partitioner: @partitioner
381
+ )
95
382
  closed_producer_check(__method__)
96
383
 
97
384
  # Start by checking and converting the input
98
385
 
99
386
  # Get payload length
100
387
  payload_size = if payload.nil?
101
- 0
102
- else
103
- payload.bytesize
104
- end
388
+ 0
389
+ else
390
+ payload.bytesize
391
+ end
105
392
 
106
393
  # Get key length
107
394
  key_size = if key.nil?
108
- 0
109
- else
110
- key.bytesize
111
- end
395
+ 0
396
+ else
397
+ key.bytesize
398
+ end
399
+
400
+ topic_config_hash = topic_config.hash
401
+
402
+ # Checks if we have the rdkafka topic reference object ready. It saves us on object
403
+ # allocation and allows to use custom config on demand.
404
+ set_topic_config(topic, topic_config, topic_config_hash) unless @topics_refs_map.dig(topic, topic_config_hash)
405
+ topic_ref = @topics_refs_map.dig(topic, topic_config_hash)
112
406
 
113
407
  if partition_key
114
408
  partition_count = partition_count(topic)
409
+
410
+ # Check if there are no overrides for the partitioner and use the default one only when
411
+ # no per-topic is present.
412
+ selected_partitioner = @topics_configs.dig(topic, topic_config_hash, :partitioner) || partitioner
413
+
115
414
  # If the topic is not present, set to -1
116
- partition = Rdkafka::Bindings.partitioner(partition_key, partition_count, @partitioner_name) if partition_count
415
+ if partition_count.positive?
416
+ partition = Rdkafka::Bindings.partitioner(
417
+ topic_ref,
418
+ partition_key,
419
+ partition_count,
420
+ selected_partitioner
421
+ )
422
+ end
117
423
  end
118
424
 
119
- # If partition is nil, use -1 to let librdafka set the partition randomly or
425
+ # If partition is nil, use RD_KAFKA_PARTITION_UA to let librdafka set the partition randomly or
120
426
  # based on the key when present.
121
- partition ||= -1
427
+ partition ||= Rdkafka::Bindings::RD_KAFKA_PARTITION_UA
122
428
 
123
- # If timestamp is nil use 0 and let Kafka set one. If an integer or time
124
- # use it.
429
+ # If timestamp is nil use 0 and let Kafka set one. If an integer or time use it.
125
430
  raw_timestamp = if timestamp.nil?
126
- 0
127
- elsif timestamp.is_a?(Integer)
128
- timestamp
129
- elsif timestamp.is_a?(Time)
130
- (timestamp.to_i * 1000) + (timestamp.usec / 1000)
131
- else
132
- raise TypeError.new("Timestamp has to be nil, an Integer or a Time")
133
- end
431
+ 0
432
+ elsif timestamp.is_a?(Integer)
433
+ timestamp
434
+ elsif timestamp.is_a?(Time)
435
+ (timestamp.to_i * 1000) + (timestamp.usec / 1000)
436
+ else
437
+ raise TypeError.new("Timestamp has to be nil, an Integer or a Time")
438
+ end
134
439
 
135
440
  delivery_handle = DeliveryHandle.new
441
+ delivery_handle.label = label
442
+ delivery_handle.topic = topic
136
443
  delivery_handle[:pending] = true
137
- delivery_handle[:response] = -1
138
- delivery_handle[:partition] = -1
139
- delivery_handle[:offset] = -1
444
+ delivery_handle[:response] = Rdkafka::Bindings::RD_KAFKA_PARTITION_UA
445
+ delivery_handle[:partition] = Rdkafka::Bindings::RD_KAFKA_PARTITION_UA
446
+ delivery_handle[:offset] = Rdkafka::Bindings::RD_KAFKA_PARTITION_UA
140
447
  DeliveryHandle.register(delivery_handle)
141
448
 
142
- args = [
143
- :int, Rdkafka::Bindings::RD_KAFKA_VTYPE_TOPIC, :string, topic,
144
- :int, Rdkafka::Bindings::RD_KAFKA_VTYPE_MSGFLAGS, :int, Rdkafka::Bindings::RD_KAFKA_MSG_F_COPY,
145
- :int, Rdkafka::Bindings::RD_KAFKA_VTYPE_VALUE, :buffer_in, payload, :size_t, payload_size,
146
- :int, Rdkafka::Bindings::RD_KAFKA_VTYPE_KEY, :buffer_in, key, :size_t, key_size,
147
- :int, Rdkafka::Bindings::RD_KAFKA_VTYPE_PARTITION, :int32, partition,
148
- :int, Rdkafka::Bindings::RD_KAFKA_VTYPE_TIMESTAMP, :int64, raw_timestamp,
149
- :int, Rdkafka::Bindings::RD_KAFKA_VTYPE_OPAQUE, :pointer, delivery_handle,
150
- ]
151
-
152
- if headers
153
- headers.each do |key0, value0|
449
+ begin
450
+ args = [
451
+ :int, Rdkafka::Bindings::RD_KAFKA_VTYPE_RKT, :pointer, topic_ref,
452
+ :int, Rdkafka::Bindings::RD_KAFKA_VTYPE_MSGFLAGS, :int, Rdkafka::Bindings::RD_KAFKA_MSG_F_COPY,
453
+ :int, Rdkafka::Bindings::RD_KAFKA_VTYPE_VALUE, :buffer_in, payload, :size_t, payload_size,
454
+ :int, Rdkafka::Bindings::RD_KAFKA_VTYPE_KEY, :buffer_in, key, :size_t, key_size,
455
+ :int, Rdkafka::Bindings::RD_KAFKA_VTYPE_PARTITION, :int32, partition,
456
+ :int, Rdkafka::Bindings::RD_KAFKA_VTYPE_TIMESTAMP, :int64, raw_timestamp,
457
+ :int, Rdkafka::Bindings::RD_KAFKA_VTYPE_OPAQUE, :pointer, delivery_handle
458
+ ]
459
+
460
+ headers&.each do |key0, value0|
154
461
  key = key0.to_s
155
- value = value0.to_s
156
- args << :int << Rdkafka::Bindings::RD_KAFKA_VTYPE_HEADER
157
- args << :string << key
158
- args << :pointer << value
159
- args << :size_t << value.bytes.size
462
+ if value0.is_a?(Array)
463
+ # Handle array of values per KIP-82
464
+ value0.each do |value|
465
+ value = value.to_s
466
+ args << :int << Rdkafka::Bindings::RD_KAFKA_VTYPE_HEADER
467
+ args << :string << key
468
+ args << :pointer << value
469
+ args << :size_t << value.bytesize
470
+ end
471
+ else
472
+ # Handle single value
473
+ value = value0.to_s
474
+ args << :int << Rdkafka::Bindings::RD_KAFKA_VTYPE_HEADER
475
+ args << :string << key
476
+ args << :pointer << value
477
+ args << :size_t << value.bytesize
478
+ end
160
479
  end
161
- end
162
480
 
163
- args << :int << Rdkafka::Bindings::RD_KAFKA_VTYPE_END
481
+ args << :int << Rdkafka::Bindings::RD_KAFKA_VTYPE_END
164
482
 
165
- # Produce the message
166
- response = @native_kafka.with_inner do |inner|
167
- Rdkafka::Bindings.rd_kafka_producev(
168
- inner,
169
- *args
170
- )
171
- end
483
+ # Produce the message
484
+ response = @native_kafka.with_inner do |inner|
485
+ Rdkafka::Bindings.rd_kafka_producev(
486
+ inner,
487
+ *args
488
+ )
489
+ end
172
490
 
173
- # Raise error if the produce call was not successful
174
- if response != 0
491
+ # Raise error if the produce call was not successful
492
+ if response != Rdkafka::Bindings::RD_KAFKA_RESP_ERR_NO_ERROR
493
+ raise RdkafkaError.new(response)
494
+ end
495
+ rescue Exception
175
496
  DeliveryHandle.remove(delivery_handle.to_ptr.address)
176
- raise RdkafkaError.new(response)
497
+ raise
177
498
  end
178
499
 
179
500
  delivery_handle
180
501
  end
181
502
 
503
+ # Calls (if registered) the delivery callback
504
+ #
505
+ # @param delivery_report [Producer::DeliveryReport]
506
+ # @param delivery_handle [Producer::DeliveryHandle]
182
507
  def call_delivery_callback(delivery_report, delivery_handle)
183
508
  return unless @delivery_callback
184
509
 
185
- args = [delivery_report, delivery_handle].take(@delivery_callback_arity)
186
- @delivery_callback.call(*args)
510
+ case @delivery_callback_arity
511
+ when 0
512
+ @delivery_callback.call
513
+ when 1
514
+ @delivery_callback.call(delivery_report)
515
+ else
516
+ @delivery_callback.call(delivery_report, delivery_handle)
517
+ end
187
518
  end
188
519
 
520
+ # Figures out the arity of a given block/method
521
+ #
522
+ # @param callback [#call, Proc]
523
+ # @return [Integer] arity of the provided block/method
189
524
  def arity(callback)
190
525
  return callback.arity if callback.respond_to?(:arity)
191
526
 
@@ -193,8 +528,14 @@ module Rdkafka
193
528
  end
194
529
 
195
530
  private
531
+
532
+ # Ensures, no operations can happen on a closed producer
533
+ #
534
+ # @param method [Symbol] name of the method that invoked producer
535
+ # @raise [Rdkafka::ClosedProducerError]
196
536
  def closed_producer_check(method)
197
537
  raise Rdkafka::ClosedProducerError.new(method) if closed?
198
538
  end
539
+ alias_method :closed_check, :closed_producer_check
199
540
  end
200
541
  end
@@ -1,7 +1,10 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Rdkafka
4
- VERSION = "0.13.0"
5
- LIBRDKAFKA_VERSION = "2.0.2"
6
- LIBRDKAFKA_SOURCE_SHA256 = "f321bcb1e015a34114c83cf1aa7b99ee260236aab096b85c003170c90a47ca9d"
4
+ # Current rdkafka-ruby gem version
5
+ VERSION = "0.31.0"
6
+ # Target librdkafka version to be used
7
+ LIBRDKAFKA_VERSION = "2.15.1"
8
+ # SHA256 hash of the librdkafka source tarball for verification
9
+ LIBRDKAFKA_SOURCE_SHA256 = "23c8575c7d1ced07246cb9cf200c11325b72201fd4134a02414ca869fbdd8ed3"
7
10
  end