karafka-rdkafka 0.31.0-aarch64-linux-gnu → 0.32.1-aarch64-linux-gnu

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 (44) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +100 -35
  3. data/README.md +14 -6
  4. data/ext/librdkafka.so +0 -0
  5. data/karafka-rdkafka.gemspec +4 -3
  6. data/lib/rdkafka/abstract_handle.rb +26 -11
  7. data/lib/rdkafka/admin/acl_binding_result.rb +4 -16
  8. data/lib/rdkafka/admin/alter_consumer_group_offsets_report.rb +2 -2
  9. data/lib/rdkafka/admin/config_binding_result.rb +8 -0
  10. data/lib/rdkafka/admin/create_acl_report.rb +1 -3
  11. data/lib/rdkafka/admin/create_topic_report.rb +2 -6
  12. data/lib/rdkafka/admin/delete_consumer_group_offsets_report.rb +2 -2
  13. data/lib/rdkafka/admin/delete_groups_report.rb +2 -6
  14. data/lib/rdkafka/admin/delete_topic_report.rb +2 -6
  15. data/lib/rdkafka/admin/describe_cluster_report.rb +3 -0
  16. data/lib/rdkafka/admin/list_consumer_group_offsets_handle.rb +31 -0
  17. data/lib/rdkafka/admin/list_consumer_group_offsets_report.rb +52 -0
  18. data/lib/rdkafka/admin.rb +180 -10
  19. data/lib/rdkafka/bindings/admin/configs.rb +12 -1
  20. data/lib/rdkafka/bindings/admin.rb +14 -0
  21. data/lib/rdkafka/bindings/callbacks.rb +16 -9
  22. data/lib/rdkafka/bindings/configuration.rb +3 -3
  23. data/lib/rdkafka/bindings/consumer.rb +44 -2
  24. data/lib/rdkafka/bindings/errors.rb +1 -1
  25. data/lib/rdkafka/bindings/handle.rb +1 -1
  26. data/lib/rdkafka/bindings.rb +3 -0
  27. data/lib/rdkafka/callbacks/list_consumer_group_offsets_handler.rb +62 -0
  28. data/lib/rdkafka/callbacks.rb +5 -6
  29. data/lib/rdkafka/config.rb +70 -0
  30. data/lib/rdkafka/consumer/allocator.rb +0 -2
  31. data/lib/rdkafka/consumer/topic_partition_list.rb +7 -7
  32. data/lib/rdkafka/consumer.rb +133 -52
  33. data/lib/rdkafka/defaults.rb +15 -6
  34. data/lib/rdkafka/helpers/message_build_error.rb +30 -0
  35. data/lib/rdkafka/native_kafka.rb +136 -41
  36. data/lib/rdkafka/producer/partition_count_cache.rb +258 -0
  37. data/lib/rdkafka/producer.rb +196 -81
  38. data/lib/rdkafka/share_consumer.rb +75 -38
  39. data/lib/rdkafka/version.rb +1 -1
  40. data/lib/rdkafka.rb +6 -2
  41. data/package-lock.json +3 -3
  42. data/renovate.json +32 -2
  43. metadata +7 -31
  44. data/lib/rdkafka/producer/partitions_count_cache.rb +0 -212
@@ -9,23 +9,39 @@ module Rdkafka
9
9
  include Helpers::Metadata
10
10
 
11
11
  # @!visibility private
12
- @@partitions_count_cache = PartitionsCountCache.new
12
+ @@partition_count_cache = PartitionCountCache.new
13
13
 
14
14
  # Global (process wide) partitions cache. We use it to store number of topics partitions,
15
15
  # either from the librdkafka statistics (if enabled) or via direct inline calls every now and
16
16
  # then. Since the partitions count can only grow and should be same for all consumers and
17
17
  # producers, we can use a global cache as long as we ensure that updates only move up.
18
18
  #
19
- # @return [Rdkafka::Producer::PartitionsCountCache]
19
+ # @return [Rdkafka::Producer::PartitionCountCache]
20
20
  # @note It is critical to remember, that not all users may have statistics callbacks enabled,
21
21
  # hence we should not make assumption that this cache is always updated from the stats.
22
+ def self.partition_count_cache
23
+ @@partition_count_cache
24
+ end
25
+
26
+ # @param partition_count_cache [Rdkafka::Producer::PartitionCountCache]
27
+ def self.partition_count_cache=(partition_count_cache)
28
+ @@partition_count_cache = partition_count_cache
29
+ end
30
+
31
+ # @deprecated Use {.partition_count_cache} instead
32
+ # @return [Rdkafka::Producer::PartitionCountCache]
22
33
  def self.partitions_count_cache
23
- @@partitions_count_cache
34
+ warn "DEPRECATION WARNING: Rdkafka::Producer.partitions_count_cache is deprecated. " \
35
+ "Use Rdkafka::Producer.partition_count_cache instead. It will be removed in v1.0.0."
36
+ partition_count_cache
24
37
  end
25
38
 
26
- # @param partitions_count_cache [Rdkafka::Producer::PartitionsCountCache]
27
- def self.partitions_count_cache=(partitions_count_cache)
28
- @@partitions_count_cache = partitions_count_cache
39
+ # @deprecated Use {.partition_count_cache=} instead
40
+ # @param partition_count_cache [Rdkafka::Producer::PartitionCountCache]
41
+ def self.partitions_count_cache=(partition_count_cache)
42
+ warn "DEPRECATION WARNING: Rdkafka::Producer.partitions_count_cache= is deprecated. " \
43
+ "Use Rdkafka::Producer.partition_count_cache= instead. It will be removed in v1.0.0."
44
+ self.partition_count_cache = partition_count_cache
29
45
  end
30
46
 
31
47
  # Empty hash used as a default
@@ -33,11 +49,57 @@ module Rdkafka
33
49
 
34
50
  private_constant :EMPTY_HASH
35
51
 
52
+ # FFI types of the `rd_kafka_producev` varargs are resolved once. A variadic call resolves each
53
+ # type argument it gets on every call, unless it already is an `FFI::Type`
54
+
55
+ # `:int` vararg type
56
+ FFI_INT = Rdkafka::Bindings.find_type(:int)
57
+ # `:pointer` vararg type
58
+ FFI_POINTER = Rdkafka::Bindings.find_type(:pointer)
59
+ # `:buffer_in` vararg type
60
+ FFI_BUFFER_IN = Rdkafka::Bindings.find_type(:buffer_in)
61
+ # `:size_t` vararg type
62
+ FFI_SIZE_T = Rdkafka::Bindings.find_type(:size_t)
63
+ # `:int32` vararg type
64
+ FFI_INT32 = Rdkafka::Bindings.find_type(:int32)
65
+ # `:int64` vararg type
66
+ FFI_INT64 = Rdkafka::Bindings.find_type(:int64)
67
+ # `:string` vararg type
68
+ FFI_STRING = Rdkafka::Bindings.find_type(:string)
69
+
70
+ private_constant :FFI_INT, :FFI_POINTER, :FFI_BUFFER_IN, :FFI_SIZE_T, :FFI_INT32, :FFI_INT64,
71
+ :FFI_STRING
72
+
36
73
  # Raised when there was a critical issue when invoking rd_kafka_topic_new
37
74
  # This is a temporary solution until https://github.com/karafka/rdkafka-ruby/issues/451 is
38
75
  # resolved and this is normalized in all the places
39
76
  class TopicHandleCreationError < RuntimeError; end
40
77
 
78
+ # Raised by {#partition_count} when the partition count of a topic could not be fetched.
79
+ # Keeps the code and flags of the original error, which is also its `cause`.
80
+ class PartitionCountError < RdkafkaError
81
+ # @return [String] topic whose partition count could not be fetched
82
+ attr_reader :topic_name
83
+
84
+ # @param topic_name [String] topic whose partition count could not be fetched
85
+ # @param error [RdkafkaError] the original metadata error
86
+ def initialize(topic_name, error)
87
+ super(
88
+ error.rdkafka_response,
89
+ "Could not fetch the partition count of topic '#{topic_name}', so messages with a " \
90
+ "partition_key for it cannot be partitioned",
91
+ broker_message: error.broker_message,
92
+ fatal: error.fatal?,
93
+ retryable: error.retryable?,
94
+ abortable: error.abortable?,
95
+ details: error.details,
96
+ instance_name: error.instance_name
97
+ )
98
+
99
+ @topic_name = topic_name
100
+ end
101
+ end
102
+
41
103
  # @private
42
104
  # Returns the current delivery callback, by default this is nil.
43
105
  #
@@ -55,8 +117,9 @@ module Rdkafka
55
117
  # @param partitioner [String, nil] name of the partitioner we want to use or nil to use
56
118
  # the "consistent_random" default
57
119
  def initialize(native_kafka, partitioner)
58
- @topics_refs_map = {}
59
- @topics_configs = {}
120
+ @topics_refs_map = EMPTY_HASH
121
+ @topics_configs = EMPTY_HASH
122
+ @topics_mutex = Mutex.new
60
123
  @native_kafka = native_kafka
61
124
  @partitioner = partitioner || "consistent_random"
62
125
 
@@ -66,54 +129,27 @@ module Rdkafka
66
129
 
67
130
  # Sets alternative set of configuration details that can be set per topic
68
131
  #
69
- # @param topic [String] The topic name
132
+ # @param topic_name [String] The topic name
70
133
  # @param config [Hash] config we want to use per topic basis
71
134
  # @param config_hash [Integer] hash of the config. We expect it here instead of computing it,
72
135
  # because it is already computed during the retrieval attempt in the `#produce` flow.
73
136
  # @note It is not allowed to re-set the same topic config twice because of the underlying
74
137
  # librdkafka caching
75
- def set_topic_config(topic, config, config_hash)
76
- # Ensure lock on topic reference just in case
138
+ def set_topic_config(topic_name, config, config_hash)
139
+ # `with_inner` only counts this as an operation in progress; it takes no lock. Concurrent
140
+ # first produces to the same topic are serialized by @topics_mutex, so librdkafka gets one
141
+ # `rd_kafka_topic_new` per topic and config.
77
142
  @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
143
+ @topics_mutex.synchronize do
144
+ return if @topics_refs_map.dig(topic_name, config_hash)
145
+
146
+ store_topic_handle(
147
+ topic_name,
148
+ config,
149
+ config_hash,
150
+ create_topic_handle(inner, topic_name, config)
151
+ )
109
152
  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
153
  end
118
154
  end
119
155
 
@@ -254,14 +290,16 @@ module Rdkafka
254
290
  @native_kafka.close do
255
291
  # We need to remove the topics references objects before we destroy the producer,
256
292
  # otherwise they would leak out
257
- @topics_refs_map.each_value do |refs|
258
- refs.each_value do |ref|
259
- Rdkafka::Bindings.rd_kafka_topic_destroy(ref)
293
+ @topics_mutex.synchronize do
294
+ @topics_refs_map.each_value do |refs|
295
+ refs.each_value do |ref|
296
+ Rdkafka::Bindings.rd_kafka_topic_destroy(ref)
297
+ end
260
298
  end
299
+
300
+ @topics_refs_map = EMPTY_HASH
261
301
  end
262
302
  end
263
-
264
- @topics_refs_map.clear
265
303
  end
266
304
 
267
305
  # Whether this producer has closed
@@ -346,7 +384,7 @@ module Rdkafka
346
384
 
347
385
  # Polls for events in a non-blocking loop, yielding the count after each iteration.
348
386
  #
349
- # This method processes delivery callbacks in a single GVL/mutex session, which is more
387
+ # This method processes delivery callbacks in a single GVL session, which is more
350
388
  # efficient than repeated individual polls. It uses non-blocking polls internally
351
389
  # (no GVL release between polls).
352
390
  #
@@ -367,8 +405,9 @@ module Rdkafka
367
405
  # producer.events_poll_nb_each do |_count|
368
406
  # :stop if monotonic_now >= deadline
369
407
  # end
370
- # @note This method holds the inner lock until the queue is empty or `:stop` is returned.
371
- # Other producer operations (produce, close, etc.) will wait until this method returns.
408
+ # @note This method runs inside `with_inner` and does not hold a lock while it loops.
409
+ # Other operations on the same client run concurrently. `close` waits until this
410
+ # method returns.
372
411
  # @note This method is thread-safe as it uses @native_kafka.with_inner synchronization
373
412
  def events_poll_nb_each
374
413
  closed_producer_check(__method__)
@@ -384,9 +423,11 @@ module Rdkafka
384
423
 
385
424
  # Partition count for a given topic.
386
425
  #
387
- # @param topic [String] The topic name.
388
- # @return [Integer] partition count for a given topic or `RD_KAFKA_PARTITION_UA (-1)` if it
389
- # could not be obtained.
426
+ # @param topic_name [String] The topic name.
427
+ # @return [Integer] partition count for a given topic or `RD_KAFKA_PARTITION_UA (-1)` if the
428
+ # topic does not exist.
429
+ # @raise [PartitionCountError] when the partition count could not be fetched, e.g. when no
430
+ # broker is reachable and no count is cached. Its `cause` is the original metadata error.
390
431
  #
391
432
  # @note If 'allow.auto.create.topics' is set to true in the broker, the topic will be
392
433
  # auto-created after returning nil.
@@ -399,14 +440,14 @@ module Rdkafka
399
440
  # `RD_KAFKA_PARTITION_UA` too, so producing to a not-yet-created topic does not run a
400
441
  # blocking metadata query on every message; the cache TTL still bounds how long that result
401
442
  # is reused before we look again.
402
- def partition_count(topic)
443
+ def partition_count(topic_name)
403
444
  closed_producer_check(__method__)
404
445
 
405
- self.class.partitions_count_cache.get(topic) do
446
+ self.class.partition_count_cache.get(topic_name) do
406
447
  topic_metadata = nil
407
448
 
408
449
  @native_kafka.with_inner do |inner|
409
- topic_metadata = ::Rdkafka::Metadata.new(inner, topic).topics&.first
450
+ topic_metadata = ::Rdkafka::Metadata.new(inner, topic_name).topics&.first
410
451
  end
411
452
 
412
453
  topic_metadata ? topic_metadata[:partition_count] : Rdkafka::Bindings::RD_KAFKA_PARTITION_UA
@@ -414,8 +455,10 @@ module Rdkafka
414
455
  # A missing topic is an expected, cacheable outcome (the topic may be auto-created on
415
456
  # produce, or simply not exist yet). Returning RD_KAFKA_PARTITION_UA from inside the block
416
457
  # caches it, so we don't re-run a blocking metadata query on every produce(partition_key:)
417
- # to that topic. Anything else is a real error and is re-raised.
418
- raise(e) unless e.code == :unknown_topic_or_part
458
+ # to that topic. Anything else is a real error.
459
+ unless e.code == :unknown_topic_or_part
460
+ raise(PartitionCountError.new(topic_name, e), cause: e)
461
+ end
419
462
 
420
463
  Rdkafka::Bindings::RD_KAFKA_PARTITION_UA
421
464
  end
@@ -486,6 +529,9 @@ module Rdkafka
486
529
  set_topic_config(topic, topic_config, topic_config_hash) unless @topics_refs_map.dig(topic, topic_config_hash)
487
530
  topic_ref = @topics_refs_map.dig(topic, topic_config_hash)
488
531
 
532
+ # A NULL topic handle would crash librdkafka, so never hand one over
533
+ raise TopicHandleCreationError.new("No topic handle for topic #{topic}") if topic_ref.nil?
534
+
489
535
  if partition_key
490
536
  partition_count = partition_count(topic)
491
537
 
@@ -535,13 +581,15 @@ module Rdkafka
535
581
  # would orphan the handle in the registry forever, since nothing else will ever resolve it.
536
582
  begin
537
583
  args = [
538
- :int, Rdkafka::Bindings::RD_KAFKA_VTYPE_RKT, :pointer, topic_ref,
539
- :int, Rdkafka::Bindings::RD_KAFKA_VTYPE_MSGFLAGS, :int, Rdkafka::Bindings::RD_KAFKA_MSG_F_COPY,
540
- :int, Rdkafka::Bindings::RD_KAFKA_VTYPE_VALUE, :buffer_in, payload, :size_t, payload_size,
541
- :int, Rdkafka::Bindings::RD_KAFKA_VTYPE_KEY, :buffer_in, key, :size_t, key_size,
542
- :int, Rdkafka::Bindings::RD_KAFKA_VTYPE_PARTITION, :int32, partition,
543
- :int, Rdkafka::Bindings::RD_KAFKA_VTYPE_TIMESTAMP, :int64, raw_timestamp,
544
- :int, Rdkafka::Bindings::RD_KAFKA_VTYPE_OPAQUE, :pointer, delivery_handle
584
+ FFI_INT, Rdkafka::Bindings::RD_KAFKA_VTYPE_RKT, FFI_POINTER, topic_ref,
585
+ FFI_INT, Rdkafka::Bindings::RD_KAFKA_VTYPE_MSGFLAGS,
586
+ FFI_INT, Rdkafka::Bindings::RD_KAFKA_MSG_F_COPY,
587
+ FFI_INT, Rdkafka::Bindings::RD_KAFKA_VTYPE_VALUE,
588
+ FFI_BUFFER_IN, payload, FFI_SIZE_T, payload_size,
589
+ FFI_INT, Rdkafka::Bindings::RD_KAFKA_VTYPE_KEY, FFI_BUFFER_IN, key, FFI_SIZE_T, key_size,
590
+ FFI_INT, Rdkafka::Bindings::RD_KAFKA_VTYPE_PARTITION, FFI_INT32, partition,
591
+ FFI_INT, Rdkafka::Bindings::RD_KAFKA_VTYPE_TIMESTAMP, FFI_INT64, raw_timestamp,
592
+ FFI_INT, Rdkafka::Bindings::RD_KAFKA_VTYPE_OPAQUE, FFI_POINTER, delivery_handle
545
593
  ]
546
594
 
547
595
  if headers && !headers.empty?
@@ -553,26 +601,26 @@ module Rdkafka
553
601
  value0.each do |v|
554
602
  value = v.to_s
555
603
  args.push(
556
- :int, Rdkafka::Bindings::RD_KAFKA_VTYPE_HEADER,
557
- :string, key,
558
- :pointer, value,
559
- :size_t, value.bytesize
604
+ FFI_INT, Rdkafka::Bindings::RD_KAFKA_VTYPE_HEADER,
605
+ FFI_STRING, key,
606
+ FFI_POINTER, value,
607
+ FFI_SIZE_T, value.bytesize
560
608
  )
561
609
  end
562
610
  else
563
611
  # Handle single value
564
612
  value = value0.to_s
565
613
  args.push(
566
- :int, Rdkafka::Bindings::RD_KAFKA_VTYPE_HEADER,
567
- :string, key,
568
- :pointer, value,
569
- :size_t, value.bytesize
614
+ FFI_INT, Rdkafka::Bindings::RD_KAFKA_VTYPE_HEADER,
615
+ FFI_STRING, key,
616
+ FFI_POINTER, value,
617
+ FFI_SIZE_T, value.bytesize
570
618
  )
571
619
  end
572
620
  end
573
621
  end
574
622
 
575
- args.push(:int, Rdkafka::Bindings::RD_KAFKA_VTYPE_END)
623
+ args.push(FFI_INT, Rdkafka::Bindings::RD_KAFKA_VTYPE_END)
576
624
 
577
625
  # Produce the message
578
626
  response = @native_kafka.with_inner do |inner|
@@ -636,5 +684,72 @@ module Rdkafka
636
684
  raise Rdkafka::ClosedProducerError.new(method) if closed?
637
685
  end
638
686
  alias_method :closed_check, :closed_producer_check
687
+
688
+ # Creates a librdkafka topic handle. Callers hold @topics_mutex.
689
+ #
690
+ # @param inner [FFI::Pointer] native producer handle
691
+ # @param topic_name [String] topic name
692
+ # @param config [Hash] per-topic config; empty for the defaults
693
+ # @return [FFI::Pointer] the topic handle
694
+ # @raise [Config::ConfigError] when a per-topic config value is rejected
695
+ # @raise [TopicHandleCreationError] when librdkafka cannot create the handle
696
+ def create_topic_handle(inner, topic_name, config)
697
+ # If config is empty, we create an empty reference that will be used with defaults
698
+ rd_topic_config = if config.empty?
699
+ nil
700
+ else
701
+ Rdkafka::Bindings.rd_kafka_topic_conf_new.tap do |topic_config|
702
+ config.each do |key, value|
703
+ error_buffer = FFI::MemoryPointer.new(:char, 256)
704
+ result = Rdkafka::Bindings.rd_kafka_topic_conf_set(
705
+ topic_config,
706
+ key.to_s,
707
+ value.to_s,
708
+ error_buffer,
709
+ 256
710
+ )
711
+
712
+ unless result == :config_ok
713
+ # rd_kafka_topic_new has not been called yet, so librdkafka has not taken
714
+ # ownership of the config. Destroy it ourselves before raising, otherwise the
715
+ # partially built rd_kafka_topic_conf_t leaks. (On the rd_kafka_topic_new path
716
+ # librdkafka frees the conf on both success and failure, so we never destroy it
717
+ # there.)
718
+ Rdkafka::Bindings.rd_kafka_topic_conf_destroy(topic_config)
719
+ raise Config::ConfigError.new(error_buffer.read_string)
720
+ end
721
+ end
722
+ end
723
+ end
724
+
725
+ topic_handle = Bindings.rd_kafka_topic_new(inner, topic_name, rd_topic_config)
726
+
727
+ raise TopicHandleCreationError.new("Error creating topic handle for topic #{topic_name}") if topic_handle.null?
728
+
729
+ topic_handle
730
+ end
731
+
732
+ # Publishes a topic handle and its config. Callers hold @topics_mutex. Both maps are
733
+ # replaced with frozen copies rather than mutated, and the config goes in first, so a
734
+ # lock-free reader that finds the handle also finds its config.
735
+ #
736
+ # @param topic_name [String] topic name
737
+ # @param config [Hash] per-topic config
738
+ # @param config_hash [Integer] hash of the config
739
+ # @param topic_handle [FFI::Pointer] the topic handle
740
+ def store_topic_handle(topic_name, config, config_hash, topic_handle)
741
+ @topics_configs = with_topic_entry(@topics_configs, topic_name, config_hash, config)
742
+ @topics_refs_map = with_topic_entry(@topics_refs_map, topic_name, config_hash, topic_handle)
743
+ end
744
+
745
+ # @param map [Hash{String => Hash{Integer => Object}}] a frozen topic map
746
+ # @param topic_name [String] topic name
747
+ # @param config_hash [Integer] hash of the config
748
+ # @param value [Object] value to store
749
+ # @return [Hash{String => Hash{Integer => Object}}] a frozen copy of the map with the value
750
+ def with_topic_entry(map, topic_name, config_hash, value)
751
+ entries = map.fetch(topic_name, EMPTY_HASH).merge(config_hash => value).freeze
752
+ map.merge(topic_name => entries).freeze
753
+ end
639
754
  end
640
755
  end
@@ -36,6 +36,7 @@ module Rdkafka
36
36
  class ShareConsumer
37
37
  include Enumerable
38
38
  include Helpers::OAuth
39
+ include Helpers::MessageBuildError
39
40
 
40
41
  # Mapping of friendly acknowledge types to their librdkafka enum values
41
42
  ACKNOWLEDGE_TYPES = {
@@ -96,13 +97,17 @@ module Rdkafka
96
97
  # and after close or in a forked child, where the native handle must not be touched.
97
98
  # librdkafka assigns the name at creation, so no broker connection is required.
98
99
  @name = Rdkafka::Bindings.rd_kafka_name(Rdkafka::Bindings::NativeShareConsumer.new(native)[:rkshare_rk])
99
- # Guards handle teardown against in-flight calls: increments happen under this mutex and
100
- # close holds it while draining and destroying (mirrors NativeKafka's approach)
100
+ # Guards handle teardown against in-flight calls: the operations in progress counter
101
+ # changes only under this mutex, and close holds it while destroying (mirrors NativeKafka)
101
102
  @access_mutex = Mutex.new
102
- # Separate mutex for decrements so a blocked close (holding @access_mutex) cannot
103
- # deadlock with an operation trying to finish
104
- @decrement_mutex = Mutex.new
105
- # Number of calls currently using the native handle
103
+ # Signalled when `#close` ends and, only while `#close` waits, when the operations in
104
+ # progress counter reaches zero. `#close` waits on it with `@access_mutex` released, so calls
105
+ # that started before it can still decrement the counter.
106
+ @operations_done = ConditionVariable.new
107
+ # Set while `#close` runs, so no new call starts until it ends
108
+ @closing = false
109
+ # Number of calls currently using the native handle, changed only under `@access_mutex`, so
110
+ # no update is lost on Rubies without a GVL (JRuby)
106
111
  @operations_in_progress = 0
107
112
 
108
113
  ObjectSpace.define_finalizer(self, self.class.finalizer(@state))
@@ -219,8 +224,11 @@ module Rdkafka
219
224
  #
220
225
  # @param timeout_ms [Integer] Timeout of this poll
221
226
  # @return [Array<ShareConsumer::Message, RdkafkaError>] polled messages, empty when the
222
- # timeout expired without records. A message that fails to build (see below) is an
223
- # `RdkafkaError` rather than a `ShareConsumer::Message`.
227
+ # timeout expired without records. A message that fails to build (e.g. its headers cannot
228
+ # be read) comes inline as an `RdkafkaError` rather than a `ShareConsumer::Message`;
229
+ # `details` then holds its `topic`, `partition` and `offset`, so in explicit
230
+ # acknowledgement mode it can be acknowledged (see {#acknowledge}); in implicit mode the
231
+ # next poll accepts it.
224
232
  # @raise [RdkafkaError] When polling fails at the batch level (for example unacknowledged
225
233
  # records in explicit mode)
226
234
  def poll(timeout_ms = Defaults::SHARE_CONSUMER_POLL_TIMEOUT_MS)
@@ -260,7 +268,7 @@ module Rdkafka
260
268
  # error rather than discarding the whole batch - including the messages already
261
269
  # built - and raising, which would silently lose them. Mirrors how
262
270
  # Consumer#poll_batch handles the same failure mode.
263
- e
271
+ message_build_error(native_message, e)
264
272
  end
265
273
  end
266
274
  ensure
@@ -321,7 +329,10 @@ module Rdkafka
321
329
  # Acknowledgements are accumulated locally and sent to the broker on the next {#poll},
322
330
  # {#commit_sync} or {#commit_async}.
323
331
  #
324
- # @param message [ShareConsumer::Message] the message to acknowledge
332
+ # @param message [ShareConsumer::Message, #topic, #partition, #offset] the message to
333
+ # acknowledge: a {ShareConsumer::Message}, or any object responding to `#topic`,
334
+ # `#partition` and `#offset`, such as one built from the `details` of a message build
335
+ # error returned by {#poll}
325
336
  # @param type [Symbol] `:accept` (processed successfully), `:release` (make it available for
326
337
  # redelivery) or `:reject` (do not deliver again, archive)
327
338
  # @return [nil]
@@ -541,31 +552,15 @@ module Rdkafka
541
552
  return if closed?
542
553
 
543
554
  @access_mutex.synchronize do
544
- # Wait for in-flight calls on other threads to finish using the handle. New calls block
545
- # on the mutex above while we hold it.
546
- sleep(Defaults::NATIVE_KAFKA_SYNCHRONIZE_SLEEP_INTERVAL_MS / 1_000.0) until @operations_in_progress.zero?
555
+ @operations_done.wait(@access_mutex) while @closing
556
+ @closing = true
547
557
 
548
- native = @state.native
549
-
550
- # Lost the race against a concurrent close that already finished
551
- return if native.nil?
552
-
553
- # librdkafka leaves the instance intact when close/destroy fail, and validate! raises
554
- # before any reference (or the finalizer) is dropped, so the caller can retry close
555
- # and the handle cannot leak silently.
556
- #
557
- # The close step is skipped when librdkafka already considers the consumer closed
558
- # (e.g. a prior close attempt succeeded but its destroy failed and was retried).
559
- if Rdkafka::Bindings.rd_kafka_share_consumer_closed(native).zero?
560
- Rdkafka::RdkafkaError.validate!(Rdkafka::Bindings.rd_kafka_share_consumer_close(native))
558
+ begin
559
+ close_native
560
+ ensure
561
+ @closing = false
562
+ @operations_done.broadcast
561
563
  end
562
-
563
- Rdkafka::RdkafkaError.validate!(Rdkafka::Bindings.rd_kafka_share_destroy(native))
564
-
565
- # The native handle is gone only now; drop all references and the finalizer
566
- ObjectSpace.undefine_finalizer(self)
567
- @state.native = nil
568
- @state.ack_callback = nil
569
564
  end
570
565
 
571
566
  nil
@@ -573,10 +568,46 @@ module Rdkafka
573
568
 
574
569
  private
575
570
 
571
+ # Destroys the native handle once no other thread uses it. Runs under `@access_mutex`, with
572
+ # `@closing` set so no new call starts.
573
+ #
574
+ # @return [nil]
575
+ # @raise [RdkafkaError] When closing or destroying reported an error
576
+ def close_native
577
+ # Wait for in-flight calls on other threads to finish using the handle. The wait releases
578
+ # `@access_mutex`, so those calls can decrement the counter, while `@closing` keeps new
579
+ # calls out.
580
+ @operations_done.wait(@access_mutex) until @operations_in_progress.zero?
581
+
582
+ native = @state.native
583
+
584
+ # Lost the race against a concurrent close that already finished
585
+ return if native.nil?
586
+
587
+ # librdkafka leaves the instance intact when close/destroy fail, and validate! raises
588
+ # before any reference (or the finalizer) is dropped, so the caller can retry close
589
+ # and the handle cannot leak silently.
590
+ #
591
+ # The close step is skipped when librdkafka already considers the consumer closed
592
+ # (e.g. a prior close attempt succeeded but its destroy failed and was retried).
593
+ if Rdkafka::Bindings.rd_kafka_share_consumer_closed(native).zero?
594
+ Rdkafka::RdkafkaError.validate!(Rdkafka::Bindings.rd_kafka_share_consumer_close(native))
595
+ end
596
+
597
+ Rdkafka::RdkafkaError.validate!(Rdkafka::Bindings.rd_kafka_share_destroy(native))
598
+
599
+ # The native handle is gone only now; drop all references and the finalizer
600
+ ObjectSpace.undefine_finalizer(self)
601
+ @state.native = nil
602
+ @state.ack_callback = nil
603
+
604
+ nil
605
+ end
606
+
576
607
  # Executes a block with the native share handle while tracking the call so {#close} cannot
577
- # tear the handle down mid-call from another thread. Increments happen under the access
578
- # mutex that close holds for the whole teardown, so once close is draining no new call can
579
- # slip in; librdkafka's own single-owner gate still rejects genuinely concurrent API calls.
608
+ # tear the handle down mid-call from another thread. New calls wait while close runs, so once
609
+ # close is draining no new call can slip in; librdkafka's own single-owner gate still rejects
610
+ # genuinely concurrent API calls.
580
611
  #
581
612
  # @param method [Symbol] public method name, used for the ClosedConsumerError
582
613
  # @yield [FFI::Pointer] the native share handle
@@ -586,7 +617,10 @@ module Rdkafka
586
617
  # (the only internal holder) - the handle is going away, so reject before tracking
587
618
  raise Rdkafka::ClosedConsumerError.new(method) if @access_mutex.owned?
588
619
 
589
- @access_mutex.synchronize { @operations_in_progress += 1 }
620
+ @access_mutex.synchronize do
621
+ @operations_done.wait(@access_mutex) while @closing
622
+ @operations_in_progress += 1
623
+ end
590
624
 
591
625
  begin
592
626
  native = @state.native
@@ -597,7 +631,10 @@ module Rdkafka
597
631
 
598
632
  yield(native)
599
633
  ensure
600
- @decrement_mutex.synchronize { @operations_in_progress -= 1 }
634
+ @access_mutex.synchronize do
635
+ @operations_in_progress -= 1
636
+ @operations_done.broadcast if @closing && @operations_in_progress.zero?
637
+ end
601
638
  end
602
639
  end
603
640
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  module Rdkafka
4
4
  # Current rdkafka-ruby gem version
5
- VERSION = "0.31.0"
5
+ VERSION = "0.32.1"
6
6
  # Target librdkafka version to be used
7
7
  LIBRDKAFKA_VERSION = "2.16.0"
8
8
  # SHA256 hash of the librdkafka source tarball for verification
data/lib/rdkafka.rb CHANGED
@@ -11,10 +11,13 @@ require "rdkafka/helpers/time"
11
11
  require "rdkafka/helpers/oauth"
12
12
  require "rdkafka/helpers/metadata"
13
13
  require "rdkafka/helpers/list_offsets"
14
+ require "rdkafka/helpers/message_build_error"
14
15
  require "rdkafka/abstract_handle"
15
16
  require "rdkafka/admin"
16
17
  require "rdkafka/admin/alter_consumer_group_offsets_handle"
17
18
  require "rdkafka/admin/alter_consumer_group_offsets_report"
19
+ require "rdkafka/admin/list_consumer_group_offsets_handle"
20
+ require "rdkafka/admin/list_consumer_group_offsets_report"
18
21
  require "rdkafka/admin/delete_consumer_group_offsets_handle"
19
22
  require "rdkafka/admin/delete_consumer_group_offsets_report"
20
23
  require "rdkafka/admin/create_topic_handle"
@@ -51,6 +54,7 @@ require "rdkafka/admin/describe_consumer_groups_report"
51
54
  require "rdkafka/admin/acl_binding_result"
52
55
  require "rdkafka/admin/config_binding_result"
53
56
  require "rdkafka/admin/config_resource_binding_result"
57
+ require "rdkafka/error"
54
58
  require "rdkafka/bindings"
55
59
  require "rdkafka/callbacks"
56
60
  require "rdkafka/callbacks/base_handler"
@@ -58,6 +62,7 @@ require "rdkafka/callbacks/create_topic_handler"
58
62
  require "rdkafka/callbacks/delete_topic_handler"
59
63
  require "rdkafka/callbacks/create_partitions_handler"
60
64
  require "rdkafka/callbacks/alter_consumer_group_offsets_handler"
65
+ require "rdkafka/callbacks/list_consumer_group_offsets_handler"
61
66
  require "rdkafka/callbacks/delete_consumer_group_offsets_handler"
62
67
  require "rdkafka/callbacks/delete_groups_handler"
63
68
  require "rdkafka/callbacks/delete_records_handler"
@@ -80,10 +85,9 @@ require "rdkafka/consumer/allocator"
80
85
  require "rdkafka/consumer/topic_partition_list"
81
86
  require "rdkafka/share_consumer"
82
87
  require "rdkafka/share_consumer/message"
83
- require "rdkafka/error"
84
88
  require "rdkafka/metadata"
85
89
  require "rdkafka/native_kafka"
86
- require "rdkafka/producer/partitions_count_cache"
90
+ require "rdkafka/producer/partition_count_cache"
87
91
  require "rdkafka/producer"
88
92
  require "rdkafka/producer/delivery_handle"
89
93
  require "rdkafka/producer/delivery_report"
data/package-lock.json CHANGED
@@ -286,9 +286,9 @@
286
286
  }
287
287
  },
288
288
  "node_modules/smol-toml": {
289
- "version": "1.9.0",
290
- "resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.9.0.tgz",
291
- "integrity": "sha512-hpd+HLON7HdZXqYchMM/+LaTTbdK0AU3NngIJ4KVyWbY9bfQqdL9cD+4yf6dUoU2Ap4VsU0JkQi6FxAI1B2mXQ==",
289
+ "version": "1.9.1",
290
+ "resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.9.1.tgz",
291
+ "integrity": "sha512-j7WyPdf0CJoutMzMoPLF/bVXHtKZIT9Rb4eGeEbWw8X2t5oirjPgpL+OpaENZrILYaXqYwnVH+qgUwVbl+pUJQ==",
292
292
  "dev": true,
293
293
  "license": "BSD-3-Clause",
294
294
  "engines": {