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
@@ -12,14 +12,199 @@ module Rdkafka
12
12
  # `each_slice` to consume batches of messages.
13
13
  class Consumer
14
14
  include Enumerable
15
+ include Helpers::Time
16
+ include Helpers::OAuth
17
+ include Helpers::Metadata
18
+ include Helpers::ListOffsets
15
19
 
16
20
  # @private
21
+ # @param native_kafka [NativeKafka] wrapper around the native Kafka consumer handle
17
22
  def initialize(native_kafka)
18
23
  @native_kafka = native_kafka
24
+ # Single-element holder shared with the GC finalizer so it can destroy the lazily created
25
+ # consumer queue without capturing `self` (capturing the consumer in its own finalizer would
26
+ # pin it and prevent it from ever being collected).
27
+ @consumer_queue_holder = []
28
+
29
+ # Makes sure the consumer is closed (consumer queue destroyed and native client destroyed)
30
+ # before it gets GCed by Ruby.
31
+ ObjectSpace.define_finalizer(self, self.class.finalizer(native_kafka, @consumer_queue_holder))
32
+ end
33
+
34
+ # Builds the GC finalizer for a consumer. It mirrors {#close}: close the consumer, destroy the
35
+ # consumer-queue reference, then destroy the native client. The default `NativeKafka#finalizer`
36
+ # went straight to `rd_kafka_destroy`, leaving the consumer-queue reference (from
37
+ # `rd_kafka_queue_get_consumer`, taken by `poll_batch`) dangling - which can make
38
+ # `rd_kafka_destroy` block inside the finalizer (process hang at GC/shutdown) or leak the
39
+ # handle.
40
+ #
41
+ # @private
42
+ # @param native_kafka [NativeKafka] the wrapped native client
43
+ # @param queue_holder [Array] single-element holder carrying the consumer queue pointer
44
+ # (or empty)
45
+ # @return [Proc] finalizer proc that must not reference the consumer instance
46
+ def self.finalizer(native_kafka, queue_holder)
47
+ proc do
48
+ next if native_kafka.closed?
49
+
50
+ native_kafka.synchronize do |inner|
51
+ Rdkafka::Bindings.rd_kafka_consumer_close(inner)
52
+
53
+ queue = queue_holder[0]
54
+ Rdkafka::Bindings.rd_kafka_queue_destroy(queue) if queue
55
+ end
56
+
57
+ native_kafka.close
58
+ end
59
+ end
60
+
61
+ # Starts the native Kafka polling thread and kicks off the init polling
62
+ # @note Not needed to run unless explicit start was disabled
63
+ def start
64
+ @native_kafka.start
19
65
  end
20
66
 
21
- def finalizer
22
- ->(_) { close }
67
+ # @return [String] consumer name
68
+ def name
69
+ @name ||= @native_kafka.with_inner do |inner|
70
+ ::Rdkafka::Bindings.rd_kafka_name(inner)
71
+ end
72
+ end
73
+
74
+ # Enable IO event notifications for fiber scheduler integration
75
+ # When the consumer queue has messages, librdkafka will write to your FD
76
+ #
77
+ # @param fd [Integer] file descriptor to signal (from IO.pipe or eventfd)
78
+ # @param payload [String] data to write to fd (default: "\x01")
79
+ # @return [nil]
80
+ # @raise [ClosedInnerError] when the consumer is closed
81
+ #
82
+ # @example Using with fiber scheduler
83
+ # consumer = config.consumer
84
+ # consumer.subscribe("topic")
85
+ #
86
+ # # Create notification FD
87
+ # signal_r, signal_w = IO.pipe
88
+ #
89
+ # # Enable librdkafka to signal when messages arrive
90
+ # consumer.enable_queue_io_events(signal_w.fileno)
91
+ #
92
+ # # Monitor with select/poll
93
+ # loop do
94
+ # readable, = IO.select([signal_r], nil, nil, timeout)
95
+ # if readable
96
+ # signal_r.read_nonblock(1024) rescue nil # Drain signal
97
+ # while msg = consumer.poll(0)
98
+ # process(msg)
99
+ # end
100
+ # end
101
+ # end
102
+ def enable_queue_io_events(fd, payload = "\x01")
103
+ @native_kafka.enable_main_queue_io_events(fd, payload)
104
+ end
105
+
106
+ # Enable IO event notifications for background events
107
+ # @param fd [Integer] file descriptor to signal (from IO.pipe or eventfd)
108
+ # @param payload [String] data to write to fd (default: "\x01")
109
+ # @return [nil]
110
+ # @raise [ClosedInnerError] when the consumer is closed
111
+ def enable_background_queue_io_events(fd, payload = "\x01")
112
+ @native_kafka.enable_background_queue_io_events(fd, payload)
113
+ end
114
+
115
+ # Polls for events in a non-blocking loop, yielding the count after each iteration.
116
+ #
117
+ # This method processes events (stats, errors, etc.) in a single GVL/mutex session,
118
+ # which is more efficient than repeated individual polls. It uses non-blocking polls
119
+ # internally (no GVL release between polls).
120
+ #
121
+ # Yields the count of events processed after each poll iteration, allowing the caller
122
+ # to implement timeout or other termination logic by returning `:stop`.
123
+ #
124
+ # @yield [count] Called after each poll iteration
125
+ # @yieldparam count [Integer] Number of events processed in this iteration
126
+ # @yieldreturn [Symbol, Object] Return `:stop` to break the loop, any other value continues
127
+ # @return [nil]
128
+ # @raise [Rdkafka::ClosedConsumerError] if called on a closed consumer
129
+ #
130
+ # @example Drain all pending events
131
+ # consumer.events_poll_nb_each { |_count| }
132
+ #
133
+ # @example With timeout control
134
+ # deadline = monotonic_now + timeout_ms
135
+ # consumer.events_poll_nb_each do |_count|
136
+ # :stop if monotonic_now >= deadline
137
+ # end
138
+ # @note This method holds the inner lock until the queue is empty or `:stop` is returned.
139
+ # Other consumer operations will wait until this method returns.
140
+ # @note This method is thread-safe as it uses @native_kafka.with_inner synchronization
141
+ # @note Do NOT use this if `consumer_poll_set` was set to `true`
142
+ def events_poll_nb_each
143
+ closed_consumer_check(__method__)
144
+
145
+ @native_kafka.with_inner do |inner|
146
+ loop do
147
+ count = Rdkafka::Bindings.rd_kafka_poll_nb(inner, 0)
148
+ break if count.zero?
149
+ break if yield(count) == :stop
150
+ end
151
+ end
152
+ end
153
+
154
+ # Polls for messages in a non-blocking loop, yielding each message to the caller.
155
+ #
156
+ # This method processes messages in a single GVL/mutex session until the queue is empty
157
+ # or the caller returns `:stop`. It handles the message pointer lifecycle internally,
158
+ # ensuring proper cleanup via `rd_kafka_message_destroy`.
159
+ #
160
+ # @yield [message] Called for each message received
161
+ # @yieldparam message [Consumer::Message] The received message
162
+ # @yieldreturn [Symbol, Object] Return `:stop` to break the loop, any other value continues
163
+ # @return [nil]
164
+ # @raise [Rdkafka::ClosedConsumerError] if called on a closed consumer
165
+ # @raise [Rdkafka::RdkafkaError] if a Kafka error occurs while polling
166
+ #
167
+ # @example Process messages until queue is empty
168
+ # consumer.poll_nb_each do |message|
169
+ # process(message)
170
+ # end
171
+ #
172
+ # @example Process with early termination
173
+ # count = 0
174
+ # consumer.poll_nb_each do |message|
175
+ # process(message)
176
+ # count += 1
177
+ # :stop if count >= 10
178
+ # end
179
+ # @note This method uses `rd_kafka_consumer_poll` to fetch messages, unlike
180
+ # `events_poll_nb_each` which uses `rd_kafka_poll` for event callbacks (delivery reports,
181
+ # statistics, etc.). For consumers, use this method to receive messages and
182
+ # `events_poll_nb_each` for processing background events.
183
+ # @note This method holds the inner lock for the duration. Other consumer operations
184
+ # will wait until this method returns.
185
+ # @note Timeout/max_messages logic should be implemented by the caller
186
+ def poll_nb_each
187
+ closed_consumer_check(__method__)
188
+
189
+ @native_kafka.with_inner do |inner|
190
+ loop do
191
+ message_ptr = Rdkafka::Bindings.rd_kafka_consumer_poll_nb(inner, 0)
192
+ break if message_ptr.null?
193
+
194
+ begin
195
+ native_message = Rdkafka::Bindings::Message.new(message_ptr)
196
+
197
+ if native_message[:err] != Rdkafka::Bindings::RD_KAFKA_RESP_ERR_NO_ERROR
198
+ raise Rdkafka::RdkafkaError.new(native_message[:err])
199
+ end
200
+
201
+ result = yield Consumer::Message.new(native_message)
202
+ break if result == :stop
203
+ ensure
204
+ Rdkafka::Bindings.rd_kafka_message_destroy(message_ptr)
205
+ end
206
+ end
207
+ end
23
208
  end
24
209
 
25
210
  # Close this consumer
@@ -30,6 +215,12 @@ module Rdkafka
30
215
 
31
216
  @native_kafka.synchronize do |inner|
32
217
  Rdkafka::Bindings.rd_kafka_consumer_close(inner)
218
+
219
+ if @consumer_queue
220
+ Rdkafka::Bindings.rd_kafka_queue_destroy(@consumer_queue)
221
+ @consumer_queue = nil
222
+ @consumer_queue_holder[0] = nil
223
+ end
33
224
  end
34
225
 
35
226
  @native_kafka.close
@@ -40,13 +231,11 @@ module Rdkafka
40
231
  @native_kafka.closed?
41
232
  end
42
233
 
43
- # Subscribe to one or more topics letting Kafka handle partition assignments.
234
+ # Subscribes to one or more topics letting Kafka handle partition assignments.
44
235
  #
45
236
  # @param topics [Array<String>] One or more topic names
46
- #
47
- # @raise [RdkafkaError] When subscribing fails
48
- #
49
237
  # @return [nil]
238
+ # @raise [RdkafkaError] When subscribing fails
50
239
  def subscribe(*topics)
51
240
  closed_consumer_check(__method__)
52
241
 
@@ -54,15 +243,15 @@ module Rdkafka
54
243
  tpl = Rdkafka::Bindings.rd_kafka_topic_partition_list_new(topics.length)
55
244
 
56
245
  topics.each do |topic|
57
- Rdkafka::Bindings.rd_kafka_topic_partition_list_add(tpl, topic, -1)
246
+ Rdkafka::Bindings.rd_kafka_topic_partition_list_add(tpl, topic, Rdkafka::Bindings::RD_KAFKA_PARTITION_UA)
58
247
  end
59
248
 
60
249
  # Subscribe to topic partition list and check this was successful
61
250
  response = @native_kafka.with_inner do |inner|
62
251
  Rdkafka::Bindings.rd_kafka_subscribe(inner, tpl)
63
252
  end
64
- if response != 0
65
- raise Rdkafka::RdkafkaError.new(response, "Error subscribing to '#{topics.join(', ')}'")
253
+ if response != Rdkafka::Bindings::RD_KAFKA_RESP_ERR_NO_ERROR
254
+ raise Rdkafka::RdkafkaError.new(response, "Error subscribing to '#{topics.join(", ")}'")
66
255
  end
67
256
  ensure
68
257
  Rdkafka::Bindings.rd_kafka_topic_partition_list_destroy(tpl) unless tpl.nil?
@@ -70,16 +259,15 @@ module Rdkafka
70
259
 
71
260
  # Unsubscribe from all subscribed topics.
72
261
  #
73
- # @raise [RdkafkaError] When unsubscribing fails
74
- #
75
262
  # @return [nil]
263
+ # @raise [RdkafkaError] When unsubscribing fails
76
264
  def unsubscribe
77
265
  closed_consumer_check(__method__)
78
266
 
79
267
  response = @native_kafka.with_inner do |inner|
80
268
  Rdkafka::Bindings.rd_kafka_unsubscribe(inner)
81
269
  end
82
- if response != 0
270
+ if response != Rdkafka::Bindings::RD_KAFKA_RESP_ERR_NO_ERROR
83
271
  raise Rdkafka::RdkafkaError.new(response)
84
272
  end
85
273
  end
@@ -87,10 +275,8 @@ module Rdkafka
87
275
  # Pause producing or consumption for the provided list of partitions
88
276
  #
89
277
  # @param list [TopicPartitionList] The topic with partitions to pause
90
- #
91
- # @raise [RdkafkaTopicPartitionListError] When pausing subscription fails.
92
- #
93
278
  # @return [nil]
279
+ # @raise [RdkafkaTopicPartitionListError] When pausing subscription fails.
94
280
  def pause(list)
95
281
  closed_consumer_check(__method__)
96
282
 
@@ -105,7 +291,7 @@ module Rdkafka
105
291
  Rdkafka::Bindings.rd_kafka_pause_partitions(inner, tpl)
106
292
  end
107
293
 
108
- if response != 0
294
+ if response != Rdkafka::Bindings::RD_KAFKA_RESP_ERR_NO_ERROR
109
295
  list = TopicPartitionList.from_native_tpl(tpl)
110
296
  raise Rdkafka::RdkafkaTopicPartitionListError.new(response, list, "Error pausing '#{list.to_h}'")
111
297
  end
@@ -114,13 +300,11 @@ module Rdkafka
114
300
  end
115
301
  end
116
302
 
117
- # Resume producing consumption for the provided list of partitions
303
+ # Resumes producing consumption for the provided list of partitions
118
304
  #
119
305
  # @param list [TopicPartitionList] The topic with partitions to pause
120
- #
121
- # @raise [RdkafkaError] When resume subscription fails.
122
- #
123
306
  # @return [nil]
307
+ # @raise [RdkafkaError] When resume subscription fails.
124
308
  def resume(list)
125
309
  closed_consumer_check(__method__)
126
310
 
@@ -134,7 +318,7 @@ module Rdkafka
134
318
  response = @native_kafka.with_inner do |inner|
135
319
  Rdkafka::Bindings.rd_kafka_resume_partitions(inner, tpl)
136
320
  end
137
- if response != 0
321
+ if response != Rdkafka::Bindings::RD_KAFKA_RESP_ERR_NO_ERROR
138
322
  raise Rdkafka::RdkafkaError.new(response, "Error resume '#{list.to_h}'")
139
323
  end
140
324
  ensure
@@ -142,11 +326,10 @@ module Rdkafka
142
326
  end
143
327
  end
144
328
 
145
- # Return the current subscription to topics and partitions
146
- #
147
- # @raise [RdkafkaError] When getting the subscription fails.
329
+ # Returns the current subscription to topics and partitions
148
330
  #
149
331
  # @return [TopicPartitionList]
332
+ # @raise [RdkafkaError] When getting the subscription fails.
150
333
  def subscription
151
334
  closed_consumer_check(__method__)
152
335
 
@@ -155,7 +338,7 @@ module Rdkafka
155
338
  Rdkafka::Bindings.rd_kafka_subscription(inner, ptr)
156
339
  end
157
340
 
158
- if response != 0
341
+ if response != Rdkafka::Bindings::RD_KAFKA_RESP_ERR_NO_ERROR
159
342
  raise Rdkafka::RdkafkaError.new(response)
160
343
  end
161
344
 
@@ -171,7 +354,6 @@ module Rdkafka
171
354
  # Atomic assignment of partitions to consume
172
355
  #
173
356
  # @param list [TopicPartitionList] The topic with partitions to assign
174
- #
175
357
  # @raise [RdkafkaError] When assigning fails
176
358
  def assign(list)
177
359
  closed_consumer_check(__method__)
@@ -186,7 +368,7 @@ module Rdkafka
186
368
  response = @native_kafka.with_inner do |inner|
187
369
  Rdkafka::Bindings.rd_kafka_assign(inner, tpl)
188
370
  end
189
- if response != 0
371
+ if response != Rdkafka::Bindings::RD_KAFKA_RESP_ERR_NO_ERROR
190
372
  raise Rdkafka::RdkafkaError.new(response, "Error assigning '#{list.to_h}'")
191
373
  end
192
374
  ensure
@@ -196,9 +378,8 @@ module Rdkafka
196
378
 
197
379
  # Returns the current partition assignment.
198
380
  #
199
- # @raise [RdkafkaError] When getting the assignment fails.
200
- #
201
381
  # @return [TopicPartitionList]
382
+ # @raise [RdkafkaError] When getting the assignment fails.
202
383
  def assignment
203
384
  closed_consumer_check(__method__)
204
385
 
@@ -206,7 +387,7 @@ module Rdkafka
206
387
  response = @native_kafka.with_inner do |inner|
207
388
  Rdkafka::Bindings.rd_kafka_assignment(inner, ptr)
208
389
  end
209
- if response != 0
390
+ if response != Rdkafka::Bindings::RD_KAFKA_RESP_ERR_NO_ERROR
210
391
  raise Rdkafka::RdkafkaError.new(response)
211
392
  end
212
393
 
@@ -220,19 +401,28 @@ module Rdkafka
220
401
  end
221
402
  end
222
403
  ensure
223
- ptr.free unless ptr.nil?
404
+ ptr&.free
405
+ end
406
+
407
+ # @return [Boolean] true if our current assignment has been lost involuntarily.
408
+ def assignment_lost?
409
+ closed_consumer_check(__method__)
410
+
411
+ @native_kafka.with_inner do |inner|
412
+ !Rdkafka::Bindings.rd_kafka_assignment_lost(inner).zero?
413
+ end
224
414
  end
225
415
 
226
416
  # Return the current committed offset per partition for this consumer group.
227
- # The offset field of each requested partition will either be set to stored offset or to -1001 in case there was no stored offset for that partition.
417
+ # The offset field of each requested partition will either be set to stored offset or to -1001
418
+ # in case there was no stored offset for that partition.
228
419
  #
229
- # @param list [TopicPartitionList, nil] The topic with partitions to get the offsets for or nil to use the current subscription.
420
+ # @param list [TopicPartitionList, nil] The topic with partitions to get the offsets for or nil
421
+ # to use the current subscription.
230
422
  # @param timeout_ms [Integer] The timeout for fetching this information.
231
- #
232
- # @raise [RdkafkaError] When getting the committed positions fails.
233
- #
234
423
  # @return [TopicPartitionList]
235
- def committed(list=nil, timeout_ms=1200)
424
+ # @raise [RdkafkaError] When getting the committed positions fails.
425
+ def committed(list = nil, timeout_ms = Defaults::CONSUMER_COMMITTED_TIMEOUT_MS)
236
426
  closed_consumer_check(__method__)
237
427
 
238
428
  if list.nil?
@@ -247,7 +437,7 @@ module Rdkafka
247
437
  response = @native_kafka.with_inner do |inner|
248
438
  Rdkafka::Bindings.rd_kafka_committed(inner, tpl, timeout_ms)
249
439
  end
250
- if response != 0
440
+ if response != Rdkafka::Bindings::RD_KAFKA_RESP_ERR_NO_ERROR
251
441
  raise Rdkafka::RdkafkaError.new(response)
252
442
  end
253
443
  TopicPartitionList.from_native_tpl(tpl)
@@ -256,16 +446,48 @@ module Rdkafka
256
446
  end
257
447
  end
258
448
 
449
+ # Return the current positions (offsets) for topics and partitions.
450
+ # The offset field of each requested partition will be set to the offset of the last consumed
451
+ # message + 1, or nil in case there was no previous message.
452
+ #
453
+ # @param list [TopicPartitionList, nil] The topic with partitions to get the offsets for or nil
454
+ # to use the current subscription.
455
+ #
456
+ # @return [TopicPartitionList]
457
+ #
458
+ # @raise [RdkafkaError] When getting the positions fails.
459
+ def position(list = nil)
460
+ closed_consumer_check(__method__)
461
+
462
+ if list.nil?
463
+ list = assignment
464
+ elsif !list.is_a?(TopicPartitionList)
465
+ raise TypeError.new("list has to be nil or a TopicPartitionList")
466
+ end
467
+
468
+ tpl = list.to_native_tpl
469
+
470
+ response = @native_kafka.with_inner do |inner|
471
+ Rdkafka::Bindings.rd_kafka_position(inner, tpl)
472
+ end
473
+
474
+ if response != Rdkafka::Bindings::RD_KAFKA_RESP_ERR_NO_ERROR
475
+ raise Rdkafka::RdkafkaError.new(response)
476
+ end
477
+
478
+ TopicPartitionList.from_native_tpl(tpl)
479
+ ensure
480
+ Rdkafka::Bindings.rd_kafka_topic_partition_list_destroy(tpl) if tpl
481
+ end
482
+
259
483
  # Query broker for low (oldest/beginning) and high (newest/end) offsets for a partition.
260
484
  #
261
485
  # @param topic [String] The topic to query
262
486
  # @param partition [Integer] The partition to query
263
487
  # @param timeout_ms [Integer] The timeout for querying the broker
264
- #
265
- # @raise [RdkafkaError] When querying the broker fails.
266
- #
267
488
  # @return [Integer] The low and high watermark
268
- def query_watermark_offsets(topic, partition, timeout_ms=200)
489
+ # @raise [RdkafkaError] When querying the broker fails.
490
+ def query_watermark_offsets(topic, partition, timeout_ms = Defaults::CONSUMER_QUERY_WATERMARK_TIMEOUT_MS)
269
491
  closed_consumer_check(__method__)
270
492
 
271
493
  low = FFI::MemoryPointer.new(:int64, 1)
@@ -278,17 +500,17 @@ module Rdkafka
278
500
  partition,
279
501
  low,
280
502
  high,
281
- timeout_ms,
503
+ timeout_ms
282
504
  )
283
505
  end
284
- if response != 0
506
+ if response != Rdkafka::Bindings::RD_KAFKA_RESP_ERR_NO_ERROR
285
507
  raise Rdkafka::RdkafkaError.new(response, "Error querying watermark offsets for partition #{partition} of #{topic}")
286
508
  end
287
509
 
288
- return low.read_array_of_int64(1).first, high.read_array_of_int64(1).first
510
+ [low.read_array_of_int64(1).first, high.read_array_of_int64(1).first]
289
511
  ensure
290
- low.free unless low.nil?
291
- high.free unless high.nil?
512
+ low&.free
513
+ high&.free
292
514
  end
293
515
 
294
516
  # Calculate the consumer lag per partition for the provided topic partition list.
@@ -296,40 +518,76 @@ module Rdkafka
296
518
  # possible to create one yourself, in this case you have to provide a list that
297
519
  # already contains all the partitions you need the lag for.
298
520
  #
299
- # @param topic_partition_list [TopicPartitionList] The list to calculate lag for.
300
- # @param watermark_timeout_ms [Integer] The timeout for each query watermark call.
521
+ # The end offsets of all requested partitions are fetched in a single batched
522
+ # {#list_offsets} query - librdkafka fans it out to the involved partition leaders
523
+ # internally and concurrently - instead of one blocking {#query_watermark_offsets}
524
+ # broker roundtrip per partition.
301
525
  #
526
+ # @param topic_partition_list [TopicPartitionList] The list to calculate lag for.
527
+ # @param watermark_timeout_ms [Integer] The timeout for the batched end-offsets query.
528
+ # @return [Hash{String => Hash{Integer => Integer}}] A hash containing all topics with the lag
529
+ # per partition
530
+ # @raise [ClosedConsumerError] when the consumer is closed
302
531
  # @raise [RdkafkaError] When querying the broker fails.
303
- #
304
- # @return [Hash<String, Hash<Integer, Integer>>] A hash containing all topics with the lag per partition
305
- def lag(topic_partition_list, watermark_timeout_ms=100)
532
+ def lag(topic_partition_list, watermark_timeout_ms = Defaults::CONSUMER_LAG_TIMEOUT_MS)
533
+ closed_consumer_check(__method__)
534
+
306
535
  out = {}
536
+ request = {}
537
+ partitions_by_topic = topic_partition_list.to_h
538
+
539
+ partitions_by_topic.each do |topic, partitions|
540
+ out[topic] = {}
541
+
542
+ partitions.each do |p|
543
+ next if p.offset.nil?
544
+
545
+ (request[topic] ||= []) << { partition: p.partition, offset: :latest }
546
+ end
547
+ end
307
548
 
308
- topic_partition_list.to_h.each do |topic, partitions|
309
- # Query high watermarks for this topic's partitions
310
- # and compare to the offset in the list.
311
- topic_out = {}
549
+ return out if request.empty?
550
+
551
+ report = begin
552
+ # The isolation level is forwarded so the end offsets match what the old per-partition
553
+ # watermark query returned: librdkafka resolves that query with the consumer's configured
554
+ # `isolation.level` (LSO for the default read_committed), while the admin-style batched
555
+ # query would otherwise default to read_uncommitted (true high watermark).
556
+ list_offsets(request, isolation_level: isolation_level)
557
+ .wait(max_wait_timeout_ms: watermark_timeout_ms)
558
+ rescue AbstractHandle::WaitTimeoutError
559
+ # Keep the pre-batching contract: a slow broker surfaced as a timed-out RdkafkaError
560
+ # from the per-partition watermark query, not as a handle wait timeout.
561
+ raise RdkafkaError.new(
562
+ Rdkafka::Bindings::RD_KAFKA_RESP_ERR__TIMED_OUT,
563
+ "Error querying watermark offsets of '#{request.keys.join(", ")}'"
564
+ )
565
+ end
566
+
567
+ end_offsets = {}
568
+ report.offsets.each do |result|
569
+ (end_offsets[result[:topic]] ||= {})[result[:partition]] = result[:offset]
570
+ end
571
+
572
+ partitions_by_topic.each do |topic, partitions|
312
573
  partitions.each do |p|
313
574
  next if p.offset.nil?
314
- low, high = query_watermark_offsets(
315
- topic,
316
- p.partition,
317
- watermark_timeout_ms
318
- )
319
- topic_out[p.partition] = high - p.offset
575
+
576
+ out[topic][p.partition] = end_offsets.fetch(topic).fetch(p.partition) - p.offset
320
577
  end
321
- out[topic] = topic_out
322
578
  end
579
+
323
580
  out
324
581
  end
325
582
 
326
583
  # Returns the ClusterId as reported in broker metadata.
327
584
  #
585
+ # @param timeout_ms [Integer] timeout in milliseconds to wait for the cluster id
328
586
  # @return [String, nil]
329
- def cluster_id
587
+ def cluster_id(timeout_ms = Defaults::CONSUMER_CLUSTER_ID_TIMEOUT_MS)
330
588
  closed_consumer_check(__method__)
331
589
  @native_kafka.with_inner do |inner|
332
- Rdkafka::Bindings.rd_kafka_clusterid(inner)
590
+ read_and_free_native_string(inner, Rdkafka::Bindings.rd_kafka_clusterid(inner, timeout_ms))
333
591
  end
334
592
  end
335
593
 
@@ -341,7 +599,7 @@ module Rdkafka
341
599
  def member_id
342
600
  closed_consumer_check(__method__)
343
601
  @native_kafka.with_inner do |inner|
344
- Rdkafka::Bindings.rd_kafka_memberid(inner)
602
+ read_and_free_native_string(inner, Rdkafka::Bindings.rd_kafka_memberid(inner))
345
603
  end
346
604
  end
347
605
 
@@ -350,45 +608,70 @@ module Rdkafka
350
608
  # When using this `enable.auto.offset.store` should be set to `false` in the config.
351
609
  #
352
610
  # @param message [Rdkafka::Consumer::Message] The message which offset will be stored
353
- #
354
- # @raise [RdkafkaError] When storing the offset fails
355
- #
611
+ # @param metadata [String, nil] commit metadata string to store alongside the offset
356
612
  # @return [nil]
357
- def store_offset(message)
613
+ # @raise [RdkafkaError] When storing the offset fails
614
+ def store_offset(message, metadata = nil)
358
615
  closed_consumer_check(__method__)
359
616
 
360
- # rd_kafka_offset_store is one of the few calls that does not support
361
- # a string as the topic, so create a native topic for it.
362
- native_topic = @native_kafka.with_inner do |inner|
363
- Rdkafka::Bindings.rd_kafka_topic_new(
364
- inner,
617
+ list = TopicPartitionList.new
618
+
619
+ # For metadata aware commits we build the partition reference directly to save on
620
+ # objects allocations
621
+ if metadata
622
+ list.add_topic_and_partitions_with_offsets(
365
623
  message.topic,
366
- nil
624
+ [
625
+ Consumer::Partition.new(
626
+ message.partition,
627
+ message.offset + 1,
628
+ 0,
629
+ metadata
630
+ )
631
+ ]
632
+ )
633
+ else
634
+ list.add_topic_and_partitions_with_offsets(
635
+ message.topic,
636
+ message.partition => message.offset + 1
367
637
  )
368
638
  end
369
- response = Rdkafka::Bindings.rd_kafka_offset_store(
370
- native_topic,
371
- message.partition,
372
- message.offset
373
- )
374
- if response != 0
639
+
640
+ tpl = list.to_native_tpl
641
+
642
+ response = @native_kafka.with_inner do |inner|
643
+ Rdkafka::Bindings.rd_kafka_offsets_store(
644
+ inner,
645
+ tpl
646
+ )
647
+ end
648
+
649
+ if response != Rdkafka::Bindings::RD_KAFKA_RESP_ERR_NO_ERROR
375
650
  raise Rdkafka::RdkafkaError.new(response)
376
651
  end
377
652
  ensure
378
- if native_topic && !native_topic.null?
379
- Rdkafka::Bindings.rd_kafka_topic_destroy(native_topic)
380
- end
653
+ Rdkafka::Bindings.rd_kafka_topic_partition_list_destroy(tpl) if tpl
381
654
  end
382
655
 
383
656
  # Seek to a particular message. The next poll on the topic/partition will return the
384
657
  # message at the given offset.
385
658
  #
386
659
  # @param message [Rdkafka::Consumer::Message] The message to which to seek
387
- #
660
+ # @return [nil]
388
661
  # @raise [RdkafkaError] When seeking fails
662
+ def seek(message)
663
+ seek_by(message.topic, message.partition, message.offset)
664
+ end
665
+
666
+ # Seek to a particular message by providing the topic, partition and offset.
667
+ # The next poll on the topic/partition will return the message at the given offset.
389
668
  #
669
+ # @param topic [String] The topic in which to seek
670
+ # @param partition [Integer] The partition number to seek
671
+ # @param offset [Integer] The partition offset to seek
390
672
  # @return [nil]
391
- def seek(message)
673
+ # @raise [RdkafkaError] When seeking fails
674
+ def seek_by(topic, partition, offset)
392
675
  closed_consumer_check(__method__)
393
676
 
394
677
  # rd_kafka_offset_store is one of the few calls that does not support
@@ -396,17 +679,17 @@ module Rdkafka
396
679
  native_topic = @native_kafka.with_inner do |inner|
397
680
  Rdkafka::Bindings.rd_kafka_topic_new(
398
681
  inner,
399
- message.topic,
682
+ topic,
400
683
  nil
401
684
  )
402
685
  end
403
686
  response = Rdkafka::Bindings.rd_kafka_seek(
404
687
  native_topic,
405
- message.partition,
406
- message.offset,
407
- 0 # timeout
688
+ partition,
689
+ offset,
690
+ Defaults::CONSUMER_SEEK_TIMEOUT_MS
408
691
  )
409
- if response != 0
692
+ if response != Rdkafka::Bindings::RD_KAFKA_RESP_ERR_NO_ERROR
410
693
  raise Rdkafka::RdkafkaError.new(response)
411
694
  end
412
695
  ensure
@@ -415,10 +698,41 @@ module Rdkafka
415
698
  end
416
699
  end
417
700
 
701
+ # Lookup offset for the given partitions by timestamp.
702
+ #
703
+ # @param list [TopicPartitionList] The TopicPartitionList with timestamps instead of offsets
704
+ # @param timeout_ms [Integer] timeout in milliseconds for the operation
705
+ # @return [TopicPartitionList]
706
+ # @raise [RdKafkaError] When the OffsetForTimes lookup fails
707
+ def offsets_for_times(list, timeout_ms = Defaults::CONSUMER_OFFSETS_FOR_TIMES_TIMEOUT_MS)
708
+ closed_consumer_check(__method__)
709
+
710
+ if !list.is_a?(TopicPartitionList)
711
+ raise TypeError.new("list has to be a TopicPartitionList")
712
+ end
713
+
714
+ tpl = list.to_native_tpl
715
+
716
+ response = @native_kafka.with_inner do |inner|
717
+ Rdkafka::Bindings.rd_kafka_offsets_for_times(
718
+ inner,
719
+ tpl,
720
+ timeout_ms # timeout
721
+ )
722
+ end
723
+
724
+ if response != Rdkafka::Bindings::RD_KAFKA_RESP_ERR_NO_ERROR
725
+ raise Rdkafka::RdkafkaError.new(response)
726
+ end
727
+
728
+ TopicPartitionList.from_native_tpl(tpl)
729
+ ensure
730
+ Rdkafka::Bindings.rd_kafka_topic_partition_list_destroy(tpl) if tpl
731
+ end
732
+
418
733
  # Manually commit the current offsets of this consumer.
419
734
  #
420
- # To use this set `enable.auto.commit`to `false` to disable automatic triggering
421
- # of commits.
735
+ # To use this set `enable.auto.commit`to `false` to disable automatic triggering of commits.
422
736
  #
423
737
  # If `enable.auto.offset.store` is set to `true` the offset of the last consumed
424
738
  # message for every partition is used. If set to `false` you can use {store_offset} to
@@ -426,24 +740,22 @@ module Rdkafka
426
740
  #
427
741
  # @param list [TopicPartitionList,nil] The topic with partitions to commit
428
742
  # @param async [Boolean] Whether to commit async or wait for the commit to finish
429
- #
430
- # @raise [RdkafkaError] When committing fails
431
- #
432
743
  # @return [nil]
433
- def commit(list=nil, async=false)
744
+ # @raise [RdkafkaError] When committing fails
745
+ def commit(list = nil, async = false)
434
746
  closed_consumer_check(__method__)
435
747
 
436
748
  if !list.nil? && !list.is_a?(TopicPartitionList)
437
749
  raise TypeError.new("list has to be nil or a TopicPartitionList")
438
750
  end
439
751
 
440
- tpl = list ? list.to_native_tpl : nil
752
+ tpl = list&.to_native_tpl
441
753
 
442
754
  begin
443
755
  response = @native_kafka.with_inner do |inner|
444
756
  Rdkafka::Bindings.rd_kafka_commit(inner, tpl, async)
445
757
  end
446
- if response != 0
758
+ if response != Rdkafka::Bindings::RD_KAFKA_RESP_ERR_NO_ERROR
447
759
  raise Rdkafka::RdkafkaError.new(response)
448
760
  end
449
761
  ensure
@@ -454,10 +766,8 @@ module Rdkafka
454
766
  # Poll for the next message on one of the subscribed topics
455
767
  #
456
768
  # @param timeout_ms [Integer] Timeout of this poll
457
- #
458
- # @raise [RdkafkaError] When polling fails
459
- #
460
769
  # @return [Message, nil] A message or nil if there was no new message within the timeout
770
+ # @raise [RdkafkaError] When polling fails
461
771
  def poll(timeout_ms)
462
772
  closed_consumer_check(__method__)
463
773
 
@@ -470,7 +780,7 @@ module Rdkafka
470
780
  # Create struct wrapper
471
781
  native_message = Rdkafka::Bindings::Message.new(message_ptr)
472
782
  # Raise error if needed
473
- if native_message[:err] != 0
783
+ if native_message[:err] != Rdkafka::Bindings::RD_KAFKA_RESP_ERR_NO_ERROR
474
784
  raise Rdkafka::RdkafkaError.new(native_message[:err])
475
785
  end
476
786
  # Create a message to pass out
@@ -483,125 +793,388 @@ module Rdkafka
483
793
  end
484
794
  end
485
795
 
486
- # Poll for new messages and yield for each received one. Iteration
487
- # will end when the consumer is closed.
796
+ # Poll for the next message without releasing the GVL (Global VM Lock).
488
797
  #
489
- # If `enable.partition.eof` is turned on in the config this will raise an
490
- # error when an eof is reached, so you probably want to disable that when
491
- # using this method of iteration.
798
+ # This is more efficient than regular polling for non-blocking poll(0) calls,
799
+ # particularly useful in fiber scheduler contexts where GVL release/reacquire
800
+ # overhead is wasteful since we don't expect to wait.
492
801
  #
802
+ # @param timeout_ms [Integer] Timeout of this poll (default: 0 for non-blocking)
803
+ # @return [Message, nil] A message or nil if there was no new message within the timeout
493
804
  # @raise [RdkafkaError] When polling fails
494
805
  #
495
- # @yieldparam message [Message] Received message
496
- #
497
- # @return [nil]
498
- def each
499
- loop do
500
- message = poll(250)
501
- if message
502
- yield(message)
503
- else
504
- if closed?
505
- break
506
- else
507
- next
508
- end
806
+ # @example Using with fiber scheduler
807
+ # # After receiving IO notification that messages are available
808
+ # while msg = consumer.poll_nb
809
+ # process(msg)
810
+ # end
811
+ def poll_nb(timeout_ms = 0)
812
+ closed_consumer_check(__method__)
813
+
814
+ message_ptr = @native_kafka.with_inner do |inner|
815
+ Rdkafka::Bindings.rd_kafka_consumer_poll_nb(inner, timeout_ms)
816
+ end
817
+
818
+ if message_ptr.null?
819
+ nil
820
+ else
821
+ # Create struct wrapper
822
+ native_message = Rdkafka::Bindings::Message.new(message_ptr)
823
+ # Raise error if needed
824
+ if native_message[:err] != Rdkafka::Bindings::RD_KAFKA_RESP_ERR_NO_ERROR
825
+ raise Rdkafka::RdkafkaError.new(native_message[:err])
509
826
  end
827
+ # Create a message to pass out
828
+ Rdkafka::Consumer::Message.new(native_message)
829
+ end
830
+ ensure
831
+ # Clean up rdkafka message if there is one
832
+ if message_ptr && !message_ptr.null?
833
+ Rdkafka::Bindings.rd_kafka_message_destroy(message_ptr)
510
834
  end
511
835
  end
512
836
 
513
- # Poll for new messages and yield them in batches that may contain
514
- # messages from more than one partition.
837
+ # Polls the main rdkafka queue (not the consumer one). Do **NOT** use it if `consumer_poll_set`
838
+ # was set to `true`.
515
839
  #
516
- # Rather than yield each message immediately as soon as it is received,
517
- # each_batch will attempt to wait for as long as `timeout_ms` in order
518
- # to create a batch of up to but no more than `max_items` in size.
840
+ # Events will cause application-provided callbacks to be called.
519
841
  #
520
- # Said differently, if more than `max_items` are available within
521
- # `timeout_ms`, then `each_batch` will yield early with `max_items` in the
522
- # array, but if `timeout_ms` passes by with fewer messages arriving, it
523
- # will yield an array of fewer messages, quite possibly zero.
842
+ # Events (in the context of the consumer):
843
+ # - error callbacks
844
+ # - stats callbacks
845
+ # - any other callbacks supported by librdkafka that are not part of the consumer_poll, that
846
+ # would have a callback configured and activated.
524
847
  #
525
- # In order to prevent wrongly auto committing many messages at once across
526
- # possibly many partitions, callers must explicitly indicate which messages
527
- # have been successfully processed as some consumed messages may not have
528
- # been yielded yet. To do this, the caller should set
529
- # `enable.auto.offset.store` to false and pass processed messages to
530
- # {store_offset}. It is also possible, though more complex, to set
531
- # 'enable.auto.commit' to false and then pass a manually assembled
532
- # TopicPartitionList to {commit}.
848
+ # This method needs to be called at regular intervals to serve any queued callbacks waiting to
849
+ # be called. When in use, does **NOT** replace `#poll` but needs to run complementary with it.
533
850
  #
534
- # As with `each`, iteration will end when the consumer is closed.
851
+ # @param timeout_ms [Integer] poll timeout. If set to 0 will run async, when set to -1 will
852
+ # block until any events available.
535
853
  #
536
- # Exception behavior is more complicated than with `each`, in that if
537
- # :yield_on_error is true, and an exception is raised during the
538
- # poll, and messages have already been received, they will be yielded to
539
- # the caller before the exception is allowed to propagate.
854
+ # @note This method technically should be called `#poll` and the current `#poll` should be
855
+ # called `#consumer_poll` though we keep the current naming convention to make it backward
856
+ # compatible.
857
+ def events_poll(timeout_ms = Defaults::CONSUMER_EVENTS_POLL_TIMEOUT_MS)
858
+ @native_kafka.with_inner do |inner|
859
+ Rdkafka::Bindings.rd_kafka_poll(inner, timeout_ms)
860
+ end
861
+ end
862
+
863
+ # Polls the main rdkafka queue without releasing the GVL (Global VM Lock).
540
864
  #
541
- # If you are setting either auto.commit or auto.offset.store to false in
542
- # the consumer configuration, then you should let yield_on_error keep its
543
- # default value of false because you are guaranteed to see these messages
544
- # again. However, if both auto.commit and auto.offset.store are set to
545
- # true, you should set yield_on_error to true so you can process messages
546
- # that you may or may not see again.
865
+ # This is more efficient than regular events_poll for non-blocking poll(0) calls,
866
+ # particularly useful in fiber scheduler contexts where GVL release/reacquire
867
+ # overhead is wasteful since we don't expect to wait.
547
868
  #
548
- # @param max_items [Integer] Maximum size of the yielded array of messages
869
+ # @param timeout_ms [Integer] poll timeout (default: 0 for non-blocking)
870
+ # @return [Integer] the number of events served
549
871
  #
550
- # @param bytes_threshold [Integer] Threshold number of total message bytes in the yielded array of messages
872
+ # @see #events_poll for more details on when to use this method
873
+ def events_poll_nb(timeout_ms = 0)
874
+ @native_kafka.with_inner do |inner|
875
+ Rdkafka::Bindings.rd_kafka_poll_nb(inner, timeout_ms)
876
+ end
877
+ end
878
+
879
+ # Poll for a batch of messages from the consumer queue in a single FFI call.
551
880
  #
552
- # @param timeout_ms [Integer] max time to wait for up to max_items
881
+ # This is more efficient than calling {#poll} in a loop because it crosses the FFI
882
+ # boundary only once to fetch up to `max_items` messages.
553
883
  #
554
- # @raise [RdkafkaError] When polling fails
884
+ # The timeout controls how long to wait for the **first** message. Once any message
885
+ # is available, librdkafka fills the buffer with whatever is immediately ready and
886
+ # returns without further waiting.
555
887
  #
556
- # @yield [messages, pending_exception]
557
- # @yieldparam messages [Array] An array of received Message
558
- # @yieldparam pending_exception [Exception] normally nil, or an exception
559
- # which will be propagated after processing of the partial batch is complete.
888
+ # Error events (e.g. `:partition_eof`) are returned inline as {RdkafkaError} objects
889
+ # rather than raised, so callers receive the complete batch - both messages and errors -
890
+ # and can decide how to handle each. This is particularly useful when multiple partitions
891
+ # signal EOF simultaneously: all signals appear in the returned array rather than only
892
+ # the first one being raised and the rest silently discarded.
560
893
  #
561
- # @return [nil]
562
- def each_batch(max_items: 100, bytes_threshold: Float::INFINITY, timeout_ms: 250, yield_on_error: false, &block)
894
+ # @param timeout_ms [Integer] Timeout waiting for the first message (-1 for infinite)
895
+ # @param max_items [Integer] Maximum number of messages to return per call
896
+ # @return [Array<Message, RdkafkaError>] Batch of messages and/or error events in arrival order
897
+ # @raise [ClosedConsumerError] When called on a closed consumer
898
+ def poll_batch(timeout_ms, max_items: 100)
563
899
  closed_consumer_check(__method__)
564
- slice = []
565
- bytes = 0
566
- end_time = monotonic_now + timeout_ms / 1000.0
567
- loop do
568
- break if closed?
569
- max_wait = end_time - monotonic_now
570
- max_wait_ms = if max_wait <= 0
571
- 0 # should not block, but may retrieve a message
572
- else
573
- (max_wait * 1000).floor
574
- end
575
- message = nil
576
- begin
577
- message = poll max_wait_ms
578
- rescue Rdkafka::RdkafkaError => error
579
- raise unless yield_on_error
580
- raise if slice.empty?
581
- yield slice.dup, error
582
- raise
900
+
901
+ buffer = batch_buffer(max_items)
902
+ results = []
903
+
904
+ count = @native_kafka.with_inner do |_inner|
905
+ Rdkafka::Bindings.rd_kafka_consume_batch_queue(
906
+ consumer_queue,
907
+ timeout_ms,
908
+ buffer,
909
+ max_items
910
+ )
911
+ end
912
+
913
+ return results if count <= 0
914
+
915
+ i = 0
916
+ begin
917
+ while i < count
918
+ ptr = buffer.get_pointer(i * FFI::Pointer.size)
919
+ # Take ownership of this index before processing the pointer: advancing `i` up front means
920
+ # the cleanup loop in the `ensure` below starts past it, so a raise mid-iteration cannot
921
+ # double-free the same message.
922
+ i += 1
923
+
924
+ next if ptr.null?
925
+
926
+ # One `ensure` around the whole body guarantees `ptr` is destroyed exactly once on every
927
+ # path - the error branch, a successful build, a rescued `RdkafkaError`, or any other
928
+ # exception unwinding through here - so nothing leaks in the window before the build.
929
+ begin
930
+ native_message = Rdkafka::Bindings::Message.new(ptr)
931
+
932
+ if native_message[:err] != Rdkafka::Bindings::RD_KAFKA_RESP_ERR_NO_ERROR
933
+ results << Rdkafka::RdkafkaError.new(native_message[:err])
934
+ next
935
+ end
936
+
937
+ begin
938
+ results << Rdkafka::Consumer::Message.new(native_message)
939
+ rescue Rdkafka::RdkafkaError => e
940
+ # A message that fails to build (e.g. a header read error) is surfaced inline as an
941
+ # error event rather than discarding the whole batch - including the messages already
942
+ # built - and raising, which silently lost them once their offsets had been stored.
943
+ results << e
944
+ end
945
+ ensure
946
+ Rdkafka::Bindings.rd_kafka_message_destroy(ptr)
947
+ end
583
948
  end
584
- if message
585
- slice << message
586
- bytes += message.payload.bytesize if message.payload
949
+ ensure
950
+ while i < count
951
+ ptr = buffer.get_pointer(i * FFI::Pointer.size)
952
+ Rdkafka::Bindings.rd_kafka_message_destroy(ptr) unless ptr.null?
953
+ i += 1
954
+ end
955
+ end
956
+
957
+ results
958
+ end
959
+
960
+ # Poll for a batch of messages without releasing the GVL (Global VM Lock).
961
+ #
962
+ # This is more efficient than {#poll_batch} for non-blocking poll(0) calls,
963
+ # particularly useful in fiber scheduler contexts where GVL release/reacquire
964
+ # overhead is wasteful since we don't expect to wait.
965
+ #
966
+ # @param timeout_ms [Integer] Timeout waiting for the first message
967
+ # (default: 0 for non-blocking)
968
+ # @param max_items [Integer] Maximum number of messages to return per call
969
+ # @return [Array<Message, RdkafkaError>] Batch of messages and/or error events in arrival order
970
+ # @raise [ClosedConsumerError] When called on a closed consumer
971
+ # @note Since the GVL is not released, a non-zero timeout_ms will block all Ruby
972
+ # threads/fibers for the duration. Use {#poll_batch} if you need a blocking wait.
973
+ #
974
+ # Error events are returned inline as {RdkafkaError} objects; see {#poll_batch} for details.
975
+ def poll_batch_nb(timeout_ms = 0, max_items: 100)
976
+ closed_consumer_check(__method__)
977
+
978
+ buffer = batch_buffer(max_items)
979
+ results = []
980
+
981
+ count = @native_kafka.with_inner do |_inner|
982
+ Rdkafka::Bindings.rd_kafka_consume_batch_queue_nb(
983
+ consumer_queue,
984
+ timeout_ms,
985
+ buffer,
986
+ max_items
987
+ )
988
+ end
989
+
990
+ return results if count <= 0
991
+
992
+ i = 0
993
+ begin
994
+ while i < count
995
+ ptr = buffer.get_pointer(i * FFI::Pointer.size)
996
+ # Take ownership of this index before processing the pointer: advancing `i` up front means
997
+ # the cleanup loop in the `ensure` below starts past it, so a raise mid-iteration cannot
998
+ # double-free the same message.
999
+ i += 1
1000
+
1001
+ next if ptr.null?
1002
+
1003
+ # One `ensure` around the whole body guarantees `ptr` is destroyed exactly once on every
1004
+ # path - the error branch, a successful build, a rescued `RdkafkaError`, or any other
1005
+ # exception unwinding through here - so nothing leaks in the window before the build.
1006
+ begin
1007
+ native_message = Rdkafka::Bindings::Message.new(ptr)
1008
+
1009
+ if native_message[:err] != Rdkafka::Bindings::RD_KAFKA_RESP_ERR_NO_ERROR
1010
+ results << Rdkafka::RdkafkaError.new(native_message[:err])
1011
+ next
1012
+ end
1013
+
1014
+ begin
1015
+ results << Rdkafka::Consumer::Message.new(native_message)
1016
+ rescue Rdkafka::RdkafkaError => e
1017
+ # A message that fails to build (e.g. a header read error) is surfaced inline as an
1018
+ # error event rather than discarding the whole batch - including the messages already
1019
+ # built - and raising, which silently lost them once their offsets had been stored.
1020
+ results << e
1021
+ end
1022
+ ensure
1023
+ Rdkafka::Bindings.rd_kafka_message_destroy(ptr)
1024
+ end
587
1025
  end
588
- if slice.size == max_items || bytes >= bytes_threshold || monotonic_now >= end_time - 0.001
589
- yield slice.dup, nil
590
- slice.clear
591
- bytes = 0
592
- end_time = monotonic_now + timeout_ms / 1000.0
1026
+ ensure
1027
+ while i < count
1028
+ ptr = buffer.get_pointer(i * FFI::Pointer.size)
1029
+ Rdkafka::Bindings.rd_kafka_message_destroy(ptr) unless ptr.null?
1030
+ i += 1
593
1031
  end
594
1032
  end
1033
+
1034
+ results
595
1035
  end
596
1036
 
597
- private
598
- def monotonic_now
599
- # needed because Time.now can go backwards
600
- Process.clock_gettime(Process::CLOCK_MONOTONIC)
1037
+ # Poll for new messages and yield for each received one. Iteration
1038
+ # will end when the consumer is closed.
1039
+ #
1040
+ # If `enable.partition.eof` is turned on in the config this will raise an error when an eof is
1041
+ # reached, so you probably want to disable that when using this method of iteration.
1042
+ #
1043
+ # @param timeout_ms [Integer] Timeout for each poll iteration
1044
+ # @yieldparam message [Message] Received message
1045
+ # @return [nil]
1046
+ # @raise [RdkafkaError] When polling fails
1047
+ def each(timeout_ms: Defaults::CONSUMER_POLL_TIMEOUT_MS)
1048
+ loop do
1049
+ message = poll(timeout_ms)
1050
+ if message
1051
+ yield(message)
1052
+ elsif closed?
1053
+ break
1054
+ else
1055
+ next
1056
+ end
1057
+ end
601
1058
  end
602
1059
 
1060
+ # @deprecated This method has been removed due to data consistency concerns
1061
+ # @param max_items [Integer] unused
1062
+ # @param bytes_threshold [Numeric] unused
1063
+ # @param timeout_ms [Integer] unused
1064
+ # @param yield_on_error [Boolean] unused
1065
+ # @param block [Proc] unused block
1066
+ # @raise [NotImplementedError] Always raises as this method is no longer supported
1067
+ def each_batch(max_items: 100, bytes_threshold: Float::INFINITY, timeout_ms: 250, yield_on_error: false, &block)
1068
+ raise NotImplementedError, <<~ERROR
1069
+ `each_batch` has been removed due to data consistency concerns.
1070
+
1071
+ This method was removed because it did not properly handle partition reassignments,
1072
+ which could lead to processing messages from partitions that were no longer owned
1073
+ by this consumer, resulting in duplicate message processing and data inconsistencies.
1074
+
1075
+ Recommended alternatives:
1076
+
1077
+ 1. Implement your own batching logic using rebalance callbacks to properly handle
1078
+ partition revocations and ensure message processing correctness.
1079
+
1080
+ 2. Use a high-level batching library that supports proper partition reassignment
1081
+ handling out of the box (such as the Karafka framework).
1082
+ ERROR
1083
+ end
1084
+
1085
+ # Returns pointer to the consumer group metadata. It is used only in the context of
1086
+ # exactly-once-semantics in transactions, this is why it is never remapped to Ruby
1087
+ #
1088
+ # This API is **not** usable by itself from Ruby
1089
+ #
1090
+ # @note This pointer **needs** to be removed with `#rd_kafka_consumer_group_metadata_destroy`
1091
+ #
1092
+ # @private
1093
+ def consumer_group_metadata_pointer
1094
+ closed_consumer_check(__method__)
1095
+
1096
+ @native_kafka.with_inner do |inner|
1097
+ Bindings.rd_kafka_consumer_group_metadata(inner)
1098
+ end
1099
+ end
1100
+
1101
+ private
1102
+
1103
+ # Checks if the consumer is closed and raises an error if so
1104
+ # @param method [Symbol] name of the calling method for error context
1105
+ # @raise [ClosedConsumerError] when the consumer is closed
603
1106
  def closed_consumer_check(method)
604
1107
  raise Rdkafka::ClosedConsumerError.new(method) if closed?
605
1108
  end
1109
+ alias_method :closed_check, :closed_consumer_check
1110
+
1111
+ # Reads a librdkafka-allocated string and frees the underlying native buffer.
1112
+ #
1113
+ # librdkafka returns heap-allocated, caller-owned strings from functions like
1114
+ # `rd_kafka_clusterid`/`rd_kafka_memberid`. The buffer must be released with
1115
+ # `rd_kafka_mem_free`, otherwise it leaks on every call.
1116
+ #
1117
+ # @param inner [FFI::Pointer] the native client handle used to allocate the string
1118
+ # @param ptr [FFI::Pointer] the native string pointer (may be null)
1119
+ # @return [String, nil] the copied Ruby string, or nil when the pointer is null
1120
+ def read_and_free_native_string(inner, ptr)
1121
+ return nil if ptr.null?
1122
+
1123
+ ptr.read_string
1124
+ ensure
1125
+ Rdkafka::Bindings.rd_kafka_mem_free(inner, ptr) unless ptr.null?
1126
+ end
1127
+
1128
+ # Reads this consumer's effective `isolation.level` from the live librdkafka configuration
1129
+ # and maps it to the numeric isolation level constant. Memoized: the value cannot change
1130
+ # after client creation.
1131
+ #
1132
+ # @return [Integer] `RD_KAFKA_ISOLATION_LEVEL_READ_COMMITTED` or
1133
+ # `RD_KAFKA_ISOLATION_LEVEL_READ_UNCOMMITTED`
1134
+ # @raise [Rdkafka::Config::ConfigError] when the property cannot be read
1135
+ def isolation_level
1136
+ @isolation_level ||= @native_kafka.with_inner do |inner|
1137
+ conf = Rdkafka::Bindings.rd_kafka_conf(inner)
1138
+
1139
+ size_ptr = Rdkafka::Bindings::SizePtr.new
1140
+ size_ptr[:value] = 64
1141
+ value_ptr = FFI::MemoryPointer.new(:char, 64)
1142
+
1143
+ result = Rdkafka::Bindings.rd_kafka_conf_get(conf, "isolation.level", value_ptr, size_ptr)
1144
+
1145
+ if result != :config_ok
1146
+ raise Rdkafka::Config::ConfigError.new("Could not read isolation.level: #{result}")
1147
+ end
1148
+
1149
+ if value_ptr.read_string == "read_committed"
1150
+ Rdkafka::Bindings::RD_KAFKA_ISOLATION_LEVEL_READ_COMMITTED
1151
+ else
1152
+ Rdkafka::Bindings::RD_KAFKA_ISOLATION_LEVEL_READ_UNCOMMITTED
1153
+ end
1154
+ end
1155
+ end
1156
+
1157
+ # Returns the consumer queue pointer, lazily initialized
1158
+ # @return [FFI::Pointer] consumer queue handle
1159
+ def consumer_queue
1160
+ @consumer_queue ||= @native_kafka.with_inner do |inner|
1161
+ queue = Rdkafka::Bindings.rd_kafka_queue_get_consumer(inner)
1162
+ # Share the pointer with the finalizer so it is destroyed even if the consumer is GC'd
1163
+ # without an explicit close.
1164
+ @consumer_queue_holder[0] = queue
1165
+ queue
1166
+ end
1167
+ end
1168
+
1169
+ # Returns a reusable FFI buffer for batch polling, growing if needed
1170
+ # @param max_items [Integer] minimum buffer capacity
1171
+ # @return [FFI::MemoryPointer] pointer buffer
1172
+ def batch_buffer(max_items)
1173
+ if @batch_buffer.nil? || @batch_buffer_size < max_items
1174
+ @batch_buffer = FFI::MemoryPointer.new(:pointer, max_items)
1175
+ @batch_buffer_size = max_items
1176
+ end
1177
+ @batch_buffer
1178
+ end
606
1179
  end
607
1180
  end