waterdrop 2.10.9 → 2.10.11

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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 0e6efd47232839d14e444c45df4cc5fae39661dd7e8ef646639f00d41f62d3b3
4
- data.tar.gz: edd8560d05bb3742d8592a1b90f2dc784410e7150045e8a8d4a0ebf1c0d82e81
3
+ metadata.gz: ea63c502e1050986468202c5b255aeafb4d120579b8a175534156dc5dd423b39
4
+ data.tar.gz: f8c84425802853f77642fbabb63b3ee8b36018d36888ddadb0815e0956105b90
5
5
  SHA512:
6
- metadata.gz: 1532bf1ecbb02ec192bdd8a410b5e7e7579337e11515fe828fb88bd8cf2a2168e31ef669e9d3ba1c334e64720c148069d26b5259d7c3f913d80258d5ddbb711b
7
- data.tar.gz: 87178e647ac42309e0cdbef6c48af8c0f7a902ee32238c3c5cf8cbca2ee7ae80396895bb3a70417c912f98f669834e19ce1066c596a7a5432c7245b29a537248
6
+ metadata.gz: e0983557e2c383ea14a035638f315874ce5a0e5ee830b28618ea2a9a1d42fa046c6b2b726932432ac8c8b842b90f8a887fa494a1da28ef88c632dc50ece22e50
7
+ data.tar.gz: f45f7764bc4787d3ad755a8eeef67a2d939192074f941cf672632cd39519f17ea13b47e5a6ee3fb310a64dc52442f41c25644b4714ac83b0fcd25334f2d23c02
data/.ruby-version CHANGED
@@ -1 +1 @@
1
- 4.0.9
1
+ 4.0.10
data/CHANGELOG.md CHANGED
@@ -1,12 +1,28 @@
1
1
  # WaterDrop changelog
2
2
 
3
+ ## v2.10.11 (2026-11-20)
4
+ - [Feature] Add the `produce` / `produce!`, `produce_many` / `produce_many!`, `tombstone` / `tombstone!`, `tombstone_many` / `tombstone_many!` and `flush` / `flush!` aliases of the `_async` / `_sync` methods.
5
+ - [Change] Require `karafka-core` `>=` `2.6.8`.
6
+ - [Fix] Treat `enable.idempotence` as on only when it is `true` or `"true"`. For a non-transactional producer, any other value (e.g. `"false"`) now makes `Producer#idempotent?` return `false`; it returns a Boolean. This includes values librdkafka reads as true, e.g. `1` and `"TRUE"`.
7
+ - [Fix] Wrap the `Rdkafka::Config::ConfigError` raised at dispatch for an invalid variant `topic_config` in `ProduceError` / `ProduceManyError` and instrument it as `error.occurred`, like the other produce errors.
8
+ - [Fix] Stop `#close` and `#disconnect` of a `:fd` polling producer from writing a stray byte into a file or socket that reuses the poller pipe fd number.
9
+
10
+ ## v2.10.10 (2026-11-10)
11
+ - [Feature] Add the `partition_count_cache_ttl_ms` setting to configure the process-wide karafka-rdkafka partition count cache TTL (default `nil` leaves it untouched).
12
+ - [Change] Require `karafka-rdkafka` `>=` `0.32.0`.
13
+ - [Change] Use the producer id (`ProducerNotTransactionalError`, `EarlyTransactionExitNotAllowedError`) or the event id (`StatisticsNotEnabledError`) as the error message instead of a sentence.
14
+ - [Maintenance] Document the errors raised by `ensure_active!` and `ensure_connection_pool_gem!`, and fix the `MessageInvalidError` namespace in `validate_message!` YARD.
15
+ - [Maintenance] Document that `max_wait_timeout` is omitted, not set to `nil`, to use the producer default in `Producer#with` and `Variant#initialize` YARD.
16
+ - [Fix] Send a message buffered through a variant with that variant's `topic_config` at flush, and a message buffered through the producer with the default one, whichever producer or variant flushes the buffer.
17
+ - [Fix] Raise `VariantInvalidError` instead of `NoMethodError` when `Producer#with` gets a `topic_config` that is not a hash (e.g. `nil`).
18
+ - [Fix] Make `Clients::Buffered` and `Clients::Dummy` safe to produce to from many threads, so on JRuby no buffered message is lost and no offset is assigned twice.
19
+
3
20
  ## 2.10.9 (2026-11-02)
4
21
  - [Maintenance] Rename the positional topic name parameters of `Producer#partition_count`, `Clients::Buffered#messages_for` and the Datadog metrics listener to `topic_name`.
5
22
  - [Maintenance] Rename the positional topic name parameter of `Clients::Dummy::Handle#initialize` to `topic_name`.
6
23
  - [Maintenance] Declare `rake` in the `Gemfile`. It came only through `karafka-rdkafka`, which will stop depending on it for precompiled platform gems.
7
24
  - [Fix] Copy the buffer in `Producer#messages` (and so the `buffer.flushed_async`/`buffer.flushed_sync` payloads) under a dedicated lock, so reading it while other threads buffer no longer raises `ConcurrencyError` on JRuby.
8
25
  - [Fix] Re-buffer the undispatched rest of a `#flush` batch when a concurrent `#close` stops it, and expose the handles dispatched before the close as `ProducerClosedError#dispatched`.
9
- - [Fix] Copy the buffer in `Producer#messages` (and so the `buffer.flushed_async`/`buffer.flushed_sync` payloads) under a dedicated lock, so reading it while other threads buffer no longer raises `ConcurrencyError` on JRuby.
10
26
 
11
27
  ## 2.10.8 (2026-10-25)
12
28
  - [Maintenance] Document that a transaction timeout also raises `:fenced`, indistinguishable from a takeover, and when removing `:fenced` from `non_reloadable_errors` is safe.
data/Gemfile.lock CHANGED
@@ -1,9 +1,9 @@
1
1
  PATH
2
2
  remote: .
3
3
  specs:
4
- waterdrop (2.10.9)
5
- karafka-core (>= 2.5.12, < 3.0.0)
6
- karafka-rdkafka (>= 0.31.0)
4
+ waterdrop (2.10.11)
5
+ karafka-core (>= 2.6.8, < 3.0.0)
6
+ karafka-rdkafka (>= 0.32.0)
7
7
  zeitwerk (~> 2.3)
8
8
 
9
9
  GEM
@@ -12,11 +12,11 @@ GEM
12
12
  connection_pool (3.0.2)
13
13
  drb (2.2.3)
14
14
  ffi (1.17.4)
15
- json (3.0.2)
16
- karafka-core (2.6.4)
15
+ json (3.1.0)
16
+ karafka-core (2.6.8)
17
17
  karafka-rdkafka (>= 0.20.0)
18
18
  logger (>= 1.6.0)
19
- karafka-rdkafka (0.31.0)
19
+ karafka-rdkafka (0.32.0)
20
20
  ffi (~> 1.17.1)
21
21
  json (> 2.0)
22
22
  logger
@@ -24,13 +24,13 @@ GEM
24
24
  rake (> 12)
25
25
  logger (1.7.0)
26
26
  mini_portile2 (2.8.9)
27
- minitest (6.0.6)
27
+ minitest (6.1.0)
28
28
  drb (~> 2.0)
29
- prism (~> 1.5)
29
+ prism (>= 1.5, < 3)
30
30
  mocha (3.1.0)
31
31
  ruby2_keywords (>= 0.0.5)
32
32
  ostruct (0.6.3)
33
- prism (1.9.0)
33
+ prism (2.1.0)
34
34
  rake (13.4.2)
35
35
  ruby2_keywords (0.0.5)
36
36
  simplecov (1.3.2)
@@ -55,20 +55,20 @@ CHECKSUMS
55
55
  connection_pool (3.0.2) sha256=33fff5ba71a12d2aa26cb72b1db8bba2a1a01823559fb01d29eb74c286e62e0a
56
56
  drb (2.2.3) sha256=0b00d6fdb50995fe4a45dea13663493c841112e4068656854646f418fda13373
57
57
  ffi (1.17.4) sha256=bcd1642e06f0d16fc9e09ac6d49c3a7298b9789bcb58127302f934e437d60acf
58
- json (3.0.2) sha256=8e6d7e7b11384c21230430cef90b71f14849a34a1f4452796670f7c981bd19df
59
- karafka-core (2.6.4) sha256=e08166ca7ef12fadf0500f2a3aba63b5ba918a98533c3feaac9f43c90f159363
60
- karafka-rdkafka (0.31.0) sha256=7d21274122d66ee8d08b8e56a0d06084933deb2306cf2a6e4bd0d073c14e7f9f
58
+ json (3.1.0) sha256=3ce7ccf8fde58960177a3a756c31f292a4c1e1dedee884547096a5b0604e3bd8
59
+ karafka-core (2.6.8) sha256=6a1fdacedc89148068db8f89550925d7ee5f1781fbed12374e92530a7db424ce
60
+ karafka-rdkafka (0.32.0) sha256=07983e15df25e69c958b991fe50ea85f2b6170821816eb05248f77a9de7ffa2b
61
61
  logger (1.7.0) sha256=196edec7cc44b66cfb40f9755ce11b392f21f7967696af15d274dde7edff0203
62
62
  mini_portile2 (2.8.9) sha256=0cd7c7f824e010c072e33f68bc02d85a00aeb6fce05bb4819c03dfd3c140c289
63
- minitest (6.0.6) sha256=153ea36d1d987a62942382b61075745042a2b3123b1cd48f4c3675af9cc7d6f1
63
+ minitest (6.1.0) sha256=ff373595aa8888631e8a5463986a76b3845346ae6d7fa46e139c1633d418076e
64
64
  mocha (3.1.0) sha256=75f42d69ebfb1f10b32489dff8f8431d37a418120ecdfc07afe3bc183d4e1d56
65
65
  ostruct (0.6.3) sha256=95a2ed4a4bd1d190784e666b47b2d3f078e4a9efda2fccf18f84ddc6538ed912
66
- prism (1.9.0) sha256=7b530c6a9f92c24300014919c9dcbc055bf4cdf51ec30aed099b06cd6674ef85
66
+ prism (2.1.0) sha256=1c0a7c6dea0e93183390fb123f007564dbe663198e2f86ad87204151147601f3
67
67
  rake (13.4.2) sha256=cb825b2bd5f1f8e91ca37bddb4b9aaf345551b4731da62949be002fa89283701
68
68
  ruby2_keywords (0.0.5) sha256=ffd13740c573b7301cf7a2e61fc857b2a8e3d3aff32545d6f8300d8bae10e3ef
69
69
  simplecov (1.3.2) sha256=2a22ec1759f1b8db60881a2e038758956fc69ef93ed669be0bde0678de6d0e85
70
70
  warning (1.6.0) sha256=a49cdfae19fb77d19afff2efbe45f8ab759e9cd25b4e4ce2c79dbaf46bdb6c9e
71
- waterdrop (2.10.9)
71
+ waterdrop (2.10.11)
72
72
  zeitwerk (2.8.3) sha256=2c85125a8467ce069e20123d1e709a08955c9d29c118c25b46b7b7fafdbb92e5
73
73
 
74
74
  BUNDLED WITH
@@ -26,6 +26,7 @@ en:
26
26
  non_reloadable_errors_format: must be an array of symbols
27
27
  oauth.token_provider_listener_format: 'must be false or respond to #on_oauthbearer_token_refresh'
28
28
  idle_disconnect_timeout_format: 'must be an integer that is equal to 0 or bigger than 30 000 (30 seconds)'
29
+ partition_count_cache_ttl_ms_format: must be nil or an integer that is equal or bigger than 1
29
30
  statistics_decorator_format: 'must respond to #call'
30
31
  polling.mode_format: must be :thread or :fd
31
32
  polling.poller_format: must be nil or a WaterDrop::Polling::Poller instance
@@ -44,6 +45,7 @@ en:
44
45
  missing: must be present
45
46
  default_format: must be boolean
46
47
  max_wait_timeout_format: must be an integer that is equal or bigger than 0
48
+ topic_config_format: must be a hash
47
49
  kafka_key_must_be_a_symbol: All keys under the kafka settings scope need to be symbols
48
50
  kafka_key_not_per_topic: This config option cannot be set on a per topic basis
49
51
  kafka_key_acks_not_changeable: Acks value cannot be redefined for a transactional or idempotent producer
@@ -3,6 +3,9 @@
3
3
  module WaterDrop
4
4
  module Clients
5
5
  # Client used to buffer messages that we send out in specs and other places.
6
+ #
7
+ # It is safe to produce from many threads. Readers (`#messages`, `#messages_for`) return the
8
+ # internal buffers, not copies, so read them once producing is done or `dup` them.
6
9
  class Buffered < Clients::Dummy
7
10
  attr_accessor :messages
8
11
 
@@ -22,38 +25,44 @@ module WaterDrop
22
25
  # @param message [Hash] `WaterDrop::Producer#produce_sync` message hash
23
26
  # @return [Dummy::Handle] fake delivery handle that can be materialized into a report
24
27
  def produce(message)
25
- if @transaction_active
26
- @transaction_topics[message.fetch(:topic)] << message
27
- @transaction_messages << message
28
- else
29
- # We pre-validate the message payload, so topic is ensured to be present
30
- @topics[message.fetch(:topic)] << message
31
- @messages << message
32
- end
28
+ @clients_mutex.synchronize do
29
+ if @transaction_active
30
+ @transaction_topics[message.fetch(:topic)] << message
31
+ @transaction_messages << message
32
+ else
33
+ # We pre-validate the message payload, so topic is ensured to be present
34
+ @topics[message.fetch(:topic)] << message
35
+ @messages << message
36
+ end
33
37
 
34
- super(**message.to_h)
38
+ build_handle(message.fetch(:topic), message.fetch(:partition, 0))
39
+ end
35
40
  end
36
41
 
37
42
  # Starts the transaction on a given level
38
43
  def begin_transaction
39
- @transaction_level += 1
40
- @transaction_active = true
44
+ @clients_mutex.synchronize do
45
+ @transaction_level += 1
46
+ @transaction_active = true
47
+ end
41
48
  end
42
49
 
43
50
  # Finishes given level of transaction
44
51
  def commit_transaction
45
- @transaction_level -= 1
52
+ @clients_mutex.synchronize do
53
+ @transaction_level -= 1
46
54
 
47
- # Transfer transactional data on success
48
- @transaction_topics.each do |topic, messages|
49
- @topics[topic] += messages
50
- end
55
+ # Transfer transactional data on success
56
+ @transaction_topics.each do |topic, messages|
57
+ @topics[topic] += messages
58
+ end
51
59
 
52
- @messages += @transaction_messages
60
+ @messages += @transaction_messages
53
61
 
54
- @transaction_topics.clear
55
- @transaction_messages.clear
56
- @transaction_active = false
62
+ @transaction_topics.clear
63
+ @transaction_messages.clear
64
+ @transaction_active = false
65
+ end
57
66
  end
58
67
 
59
68
  # Fakes storing the offset in a transactional fashion
@@ -68,26 +77,35 @@ module WaterDrop
68
77
 
69
78
  # Aborts the transaction
70
79
  def abort_transaction
71
- @transaction_level -= 1
72
- @transaction_topics.clear
73
- @transaction_messages.clear
74
- @transaction_active = false
80
+ @clients_mutex.synchronize do
81
+ @transaction_level -= 1
82
+ @transaction_topics.clear
83
+ @transaction_messages.clear
84
+ @transaction_active = false
85
+ end
75
86
  end
76
87
 
77
88
  # Returns messages produced to a given topic
78
89
  # @param topic_name [String]
79
90
  def messages_for(topic_name)
91
+ @clients_mutex.synchronize { @topics[topic_name] }
92
+ rescue ThreadError => e
93
+ # Mutex#synchronize raises in a signal trap, so there the buffer is read without the lock.
94
+ raise unless e.message == "can't be called from trap context"
95
+
80
96
  @topics[topic_name]
81
97
  end
82
98
 
83
99
  # Clears internal buffer. Used in between specs so messages do not leak out
84
100
  def reset
85
- @transaction_level = 0
86
- @transaction_active = false
87
- @transaction_topics.clear
88
- @transaction_messages.clear
89
- @messages.clear
90
- @topics.each_value(&:clear)
101
+ @clients_mutex.synchronize do
102
+ @transaction_level = 0
103
+ @transaction_active = false
104
+ @transaction_topics.clear
105
+ @transaction_messages.clear
106
+ @messages.clear
107
+ @topics.each_value(&:clear)
108
+ end
91
109
  end
92
110
  end
93
111
  end
@@ -43,6 +43,7 @@ module WaterDrop
43
43
  # @return [Dummy] dummy instance
44
44
  def initialize(_producer)
45
45
  @counters = Hash.new { |h, k| h[k] = -1 }
46
+ @clients_mutex = Mutex.new
46
47
  end
47
48
 
48
49
  # "Produces" the message
@@ -54,7 +55,7 @@ module WaterDrop
54
55
  # @option _args [Hash, nil] :headers message headers
55
56
  # @return [Handle] delivery handle
56
57
  def produce(topic:, partition: 0, **_args)
57
- Handle.new(topic.to_s, partition, @counters["#{topic}#{partition}"] += 1)
58
+ @clients_mutex.synchronize { build_handle(topic, partition) }
58
59
  end
59
60
 
60
61
  # Returns 0 as dummy client doesn't queue any real messages
@@ -76,6 +77,17 @@ module WaterDrop
76
77
  def method_missing(*_args)
77
78
  self || super
78
79
  end
80
+
81
+ private
82
+
83
+ # Assigns the next offset of the given topic partition. Caller must hold `@clients_mutex`.
84
+ #
85
+ # @param topic [String, Symbol] topic where we want to dispatch message
86
+ # @param partition [Integer] target partition
87
+ # @return [Handle] delivery handle
88
+ def build_handle(topic, partition)
89
+ Handle.new(topic.to_s, partition, @counters["#{topic}#{partition}"] += 1)
90
+ end
79
91
  end
80
92
  end
81
93
  end
@@ -149,6 +149,11 @@ module WaterDrop
149
149
  # TCP connections in low-intensity scenarios. Minimum value is 30 seconds (30_000 ms) to
150
150
  # prevent overly aggressive disconnections.
151
151
  setting :idle_disconnect_timeout, default: 0
152
+ # option [Integer, nil] Time-to-live (in ms) of the partition count cache used to route
153
+ # messages with `partition_key`. When `nil` (default), the karafka-rdkafka value is left
154
+ # untouched. Due to how rdkafka works, this setting is global for all the producers and the
155
+ # last producer set up with a non-nil value wins.
156
+ setting :partition_count_cache_ttl_ms, default: nil
152
157
 
153
158
  # option [Karafka::Core::Monitoring::StatisticsDecorator] decorator instance used to compute
154
159
  # deltas (_d) and freeze durations (_fd) on raw librdkafka statistics. The default is
@@ -230,6 +235,10 @@ module WaterDrop
230
235
  Contracts::Config.new.validate!(config.to_h, Errors::ConfigurationInvalidError)
231
236
 
232
237
  ::Rdkafka::Config.logger = config.logger
238
+
239
+ if config.partition_count_cache_ttl_ms
240
+ ::Rdkafka::Config.partition_count_cache_ttl_ms = config.partition_count_cache_ttl_ms
241
+ end
233
242
  end
234
243
 
235
244
  self
@@ -172,6 +172,7 @@ module WaterDrop
172
172
 
173
173
  # Ensures the connection_pool gem is available (class method)
174
174
  # Only requires it when actually needed (lazy loading)
175
+ # @raise [LoadError] when the connection_pool gem is not available
175
176
  def ensure_connection_pool_gem!
176
177
  return if defined?(::ConnectionPool)
177
178
 
@@ -39,6 +39,10 @@ module WaterDrop
39
39
  val.is_a?(Integer) && (val.zero? || val >= 30_000)
40
40
  end
41
41
 
42
+ required(:partition_count_cache_ttl_ms) do |val|
43
+ val.nil? || (val.is_a?(Integer) && val.positive?)
44
+ end
45
+
42
46
  required(:statistics_decorator) { |val| val.respond_to?(:call) }
43
47
 
44
48
  nested(:oauth) do
@@ -34,6 +34,7 @@ module WaterDrop
34
34
 
35
35
  required(:default) { |val| BOOLEANS.include?(val) }
36
36
  required(:max_wait_timeout) { |val| val.is_a?(Numeric) && val >= 0 }
37
+ required(:topic_config) { |val| val.is_a?(Hash) }
37
38
 
38
39
  # Checks if all keys are symbols
39
40
  virtual do |config, errors|
@@ -63,7 +63,8 @@ module WaterDrop
63
63
  # graceful transaction aborting
64
64
  AbortTransaction = Class.new(BaseError)
65
65
 
66
- # Do not use `break`, `return` or `throw` inside of the transaction blocks
66
+ # Do not use `break`, `return` or `throw` inside of the transaction blocks. If the `throw`
67
+ # comes from `Timeout.timeout(duration)`, pass an exception class as its second argument
67
68
  EarlyTransactionExitNotAllowedError = Class.new(BaseError)
68
69
 
69
70
  # Raised when an error occurs in the polling loop
@@ -46,14 +46,7 @@ module WaterDrop
46
46
  # `statistics.emitted` and this monitor has been frozen for statistics
47
47
  def subscribe(event_id_or_listener, &block)
48
48
  if @statistics_listeners_frozen && targets_statistics?(event_id_or_listener, block)
49
- raise Errors::StatisticsNotEnabledError, <<~MSG.tr("\n", " ").strip
50
- Cannot subscribe to `statistics.emitted` after the producer has been connected.
51
- Statistics are disabled because no listener was subscribed before the underlying
52
- rdkafka client was built, so librdkafka is not emitting statistics at all.
53
- Subscribe your listener BEFORE the first producer use (before the underlying
54
- client is lazily initialized), or explicitly keep statistics enabled by leaving
55
- a listener in place at build time.
56
- MSG
49
+ raise Errors::StatisticsNotEnabledError, STATISTICS_EVENT
57
50
  end
58
51
 
59
52
  super
@@ -19,6 +19,7 @@ module WaterDrop
19
19
  # @param client [Rdkafka::Producer] the rdkafka client
20
20
  # @raise [StandardError] if enable_queue_io_events fails
21
21
  def initialize(client)
22
+ @client = client
22
23
  @reader, @writer = IO.pipe
23
24
 
24
25
  # Tell librdkafka to write to our pipe when events arrive on the main queue
@@ -42,14 +43,29 @@ module WaterDrop
42
43
  # Pipe closed during drain
43
44
  end
44
45
 
45
- # Closes both ends of the pipe
46
+ # Disables librdkafka queue IO events and closes both ends of the pipe
47
+ #
48
+ # @note The IO events must be disabled before the pipe is closed. librdkafka keeps the
49
+ # writer fd number and writes to it whenever an op lands on the queue (statistics,
50
+ # errors, delivery reports during destroy). Once the pipe is closed, that number can be
51
+ # reused by any file or socket opened in this process, which would then get the payload.
46
52
  def close
53
+ disable_queue_io_events
47
54
  close_io(@reader)
48
55
  close_io(@writer)
49
56
  end
50
57
 
51
58
  private
52
59
 
60
+ # Tells librdkafka to stop writing to our pipe (fd -1 disables the IO events)
61
+ def disable_queue_io_events
62
+ return if @writer.closed?
63
+
64
+ @client.enable_queue_io_events(-1)
65
+ rescue Rdkafka::ClosedInnerError, Rdkafka::ClosedProducerError
66
+ # Client already closed, librdkafka no longer holds our fd
67
+ end
68
+
53
69
  # Safely closes an IO object
54
70
  # @param io [IO] the IO to close
55
71
  def close_io(io)
@@ -21,7 +21,7 @@ module WaterDrop
21
21
  "message.produced_async",
22
22
  producer_id: id,
23
23
  message: message
24
- ) { produce(message, "produce_async") }
24
+ ) { dispatch(message, "produce_async") }
25
25
  rescue *SUPPORTED_FLOW_ERRORS => e
26
26
  # We use this syntax here because we want to preserve the original `#cause` when we
27
27
  # instrument the error and there is no way to manually assign `#cause` value
@@ -40,6 +40,8 @@ module WaterDrop
40
40
  end
41
41
  end
42
42
 
43
+ alias_method :produce, :produce_async
44
+
43
45
  # Produces many messages to Kafka and does not wait for them to be delivered
44
46
  #
45
47
  # @param messages [Array<Hash>] array with messages that comply with the
@@ -67,7 +69,7 @@ module WaterDrop
67
69
  ) do
68
70
  with_transaction_if_transactional do
69
71
  messages.each do |message|
70
- dispatched << produce(message, "produce_many_async")
72
+ dispatched << dispatch(message, "produce_many_async")
71
73
  end
72
74
  end
73
75
 
@@ -89,6 +91,8 @@ module WaterDrop
89
91
  rescue Errors::ProducerClosedError => e
90
92
  raise Errors::ProducerClosedError.new(e.message, dispatched: dispatched)
91
93
  end
94
+
95
+ alias_method :produce_many, :produce_many_async
92
96
  end
93
97
  end
94
98
  end
@@ -70,9 +70,11 @@ module WaterDrop
70
70
  "buffer.flushed_async",
71
71
  producer_id: id,
72
72
  messages: messages
73
- ) { flush(false) }
73
+ ) { flush_buffer(false) }
74
74
  end
75
75
 
76
+ alias_method :flush, :flush_async
77
+
76
78
  # Flushes the internal buffer to Kafka in a sync way
77
79
  # @return [Array<Rdkafka::Producer::DeliveryHandle>] delivery handles for messages that were
78
80
  # flushed (handles are in final state, call `#create_result` to get delivery report)
@@ -81,9 +83,11 @@ module WaterDrop
81
83
  "buffer.flushed_sync",
82
84
  producer_id: id,
83
85
  messages: messages
84
- ) { flush(true) }
86
+ ) { flush_buffer(true) }
85
87
  end
86
88
 
89
+ alias_method :flush!, :flush_sync
90
+
87
91
  private
88
92
 
89
93
  # Method for triggering the buffer
@@ -94,7 +98,7 @@ module WaterDrop
94
98
  # @raise [Errors::ProducerClosedError] when the producer got closed during flushing
95
99
  # @note We use this method underneath to provide a different instrumentation for sync and
96
100
  # async flushing within the public API
97
- def flush(sync)
101
+ def flush_buffer(sync)
98
102
  fresh = nil
99
103
  requeued = nil
100
104
  data_for_dispatch = []
@@ -139,6 +143,20 @@ module WaterDrop
139
143
  # Do nothing if nothing to flush
140
144
  return data_for_dispatch if data_for_dispatch.empty?
141
145
 
146
+ # Messages buffered through a variant carry its topic config (see Variant#buffer). The rest
147
+ # were buffered through the producer and must not pick up the flushing variant's one.
148
+ unless current_variant.default?
149
+ default_topic_config = @default_variant.topic_config
150
+
151
+ data_for_dispatch = data_for_dispatch.map do |message|
152
+ next message if message.key?(:topic_config)
153
+
154
+ message = message.dup
155
+ message[:topic_config] = default_topic_config
156
+ message
157
+ end
158
+ end
159
+
142
160
  if sync
143
161
  produce_many_sync(data_for_dispatch, run_middleware: false)
144
162
  else
@@ -10,7 +10,9 @@ module WaterDrop
10
10
  return true if transactional?
11
11
  return @idempotent unless @idempotent.nil?
12
12
 
13
- @idempotent = config.kafka.to_h.fetch(:"enable.idempotence", false)
13
+ @idempotent = ::Karafka::Core::Helpers::Kafka::Config.enabled?(
14
+ config.kafka.to_h[:"enable.idempotence"]
15
+ )
14
16
  end
15
17
 
16
18
  # Checks if the given error should trigger an idempotent producer reload
@@ -62,7 +64,7 @@ module WaterDrop
62
64
  # them, but a thread that waited here may arrive after another has already reloaded -
63
65
  # resetting @client to nil and moving the producer to the configured state. Running
64
66
  # reload! again would call methods on a nil @client and raise NoMethodError, so we bail
65
- # out and let #produce retry against the freshly reloaded client. This mirrors the
67
+ # out and let #produce_to_client retry against the freshly reloaded client. This mirrors the
66
68
  # `return if @status.configured?` guard on the transactional reload path.
67
69
  next if @client.nil? || @status.configured?
68
70
 
@@ -24,7 +24,7 @@ module WaterDrop
24
24
  producer_id: id,
25
25
  message: message
26
26
  ) do
27
- wait(produce(message, "produce_sync"))
27
+ wait(dispatch(message, "produce_sync"))
28
28
  end
29
29
  rescue *SUPPORTED_FLOW_ERRORS => e
30
30
  # We use this syntax here because we want to preserve the original `#cause` when we
@@ -44,6 +44,8 @@ module WaterDrop
44
44
  end
45
45
  end
46
46
 
47
+ alias_method :produce!, :produce_sync
48
+
47
49
  # Produces many messages to Kafka and waits for them to be delivered
48
50
  #
49
51
  # @param messages [Array<Hash>] array with messages that comply with the
@@ -89,7 +91,7 @@ module WaterDrop
89
91
  begin
90
92
  with_transaction_if_transactional do
91
93
  messages.each do |message|
92
- dispatched << produce(message, "produce_many_sync")
94
+ dispatched << dispatch(message, "produce_many_sync")
93
95
  end
94
96
  end
95
97
  rescue *SUPPORTED_FLOW_ERRORS => e
@@ -133,6 +135,8 @@ module WaterDrop
133
135
  rescue Errors::ProducerClosedError => e
134
136
  raise Errors::ProducerClosedError.new(e.message, dispatched: dispatched)
135
137
  end
138
+
139
+ alias_method :produce_many!, :produce_many_sync
136
140
  end
137
141
  end
138
142
  end
@@ -25,6 +25,8 @@ module WaterDrop
25
25
  produce_sync(prepare_tombstone(message))
26
26
  end
27
27
 
28
+ alias_method :tombstone!, :tombstone_sync
29
+
28
30
  # Produces a tombstone message to Kafka and does not wait for results
29
31
  #
30
32
  # @param message [Hash] hash with at least `:topic`, `:key`, and `:partition` keys.
@@ -37,6 +39,8 @@ module WaterDrop
37
39
  produce_async(prepare_tombstone(message))
38
40
  end
39
41
 
42
+ alias_method :tombstone, :tombstone_async
43
+
40
44
  # Produces many tombstone messages to Kafka and waits for them to be delivered
41
45
  #
42
46
  # @param messages [Array<Hash>] array of hashes, each with `:topic`, `:key`, and
@@ -49,6 +53,8 @@ module WaterDrop
49
53
  produce_many_sync(messages.map { |message| prepare_tombstone(message) })
50
54
  end
51
55
 
56
+ alias_method :tombstone_many!, :tombstone_many_sync
57
+
52
58
  # Produces many tombstone messages to Kafka and does not wait for them to be delivered
53
59
  #
54
60
  # @param messages [Array<Hash>] array of hashes, each with `:topic`, `:key`, and
@@ -61,6 +67,8 @@ module WaterDrop
61
67
  produce_many_async(messages.map { |message| prepare_tombstone(message) })
62
68
  end
63
69
 
70
+ alias_method :tombstone_many, :tombstone_many_async
71
+
64
72
  private
65
73
 
66
74
  # Validates and prepares a tombstone message by ensuring required keys are present
@@ -50,10 +50,7 @@ module WaterDrop
50
50
  # handler.wait
51
51
  def transaction
52
52
  unless transactional?
53
- raise(
54
- Errors::ProducerNotTransactionalError,
55
- "#{id} is not transactional"
56
- )
53
+ raise(Errors::ProducerNotTransactionalError, id)
57
54
  end
58
55
 
59
56
  # This will safely allow us to support one operation transactions so a transactional
@@ -83,14 +80,7 @@ module WaterDrop
83
80
  raise(e)
84
81
  ensure
85
82
  if !e && !finished
86
- raise(
87
- Errors::EarlyTransactionExitNotAllowedError,
88
- <<~ERROR_MSG.tr("\n", " ")
89
- Using `return`, `break` or `throw` to exit a transaction block is not allowed.
90
- If the `throw` came from `Timeout.timeout(duration)`, pass an exception class as
91
- a second argument so it doesn't use `throw` to abort its block.
92
- ERROR_MSG
93
- )
83
+ raise(Errors::EarlyTransactionExitNotAllowedError, id)
94
84
  end
95
85
  end
96
86
 
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ module WaterDrop
4
+ class Producer
5
+ class Variant < SimpleDelegator
6
+ # Buffers belong to the producer, so another variant or the producer itself may flush them.
7
+ # A message buffered through a variant keeps its topic config, so it is sent with it whoever
8
+ # flushes. This lives here and not in Buffer#buffer because resolving `current_variant` there
9
+ # would cost every default-producer #buffer call (~13%).
10
+ class ConfigBuffer
11
+ # @param producer [WaterDrop::Producer] producer that owns the buffer
12
+ # @param topic_config [Hash] topic config of the variant buffering the messages
13
+ def initialize(producer, topic_config)
14
+ @producer = producer
15
+ @topic_config = topic_config
16
+ end
17
+
18
+ # @param message [Hash] message to buffer
19
+ def buffer(message)
20
+ @producer.buffer(with_topic_config(message))
21
+ end
22
+
23
+ # @param messages [Array<Hash>] messages to buffer
24
+ def buffer_many(messages)
25
+ @producer.buffer_many(messages.map { |message| with_topic_config(message) })
26
+ end
27
+
28
+ private
29
+
30
+ # @param message [Hash] user message, never changed in place
31
+ # @return [Hash] copy of the message with the variant topic config
32
+ def with_topic_config(message)
33
+ message = message.dup
34
+ message[:topic_config] = @topic_config
35
+ message
36
+ end
37
+ end
38
+ end
39
+ end
40
+ end
@@ -37,13 +37,16 @@ module WaterDrop
37
37
  # Contract to validate that variant alteration data is correct
38
38
  CONTRACT = Contracts::Variant.new
39
39
 
40
- private_constant :EMPTY_HASH, :CONTRACT
40
+ # Methods a non-default variant runs through its ConfigBuffer
41
+ CONFIG_BUFFERED = %i[buffer buffer_many].freeze
42
+
43
+ private_constant :EMPTY_HASH, :CONTRACT, :CONFIG_BUFFERED, :ConfigBuffer
41
44
 
42
45
  attr_reader :max_wait_timeout, :topic_config, :producer
43
46
 
44
47
  # @param producer [WaterDrop::Producer] producer for which we want to have a variant
45
- # @param max_wait_timeout [Integer, nil] alteration to max wait timeout or nil to use
46
- # default
48
+ # @param max_wait_timeout [Integer] alteration to max wait timeout. Omit it to use the
49
+ # producer default
47
50
  # @param topic_config [Hash] extra topic configuration that can be altered.
48
51
  # @param default [Boolean] is this a default variant or an altered one
49
52
  # @see https://karafka.io/docs/Librdkafka-Configuration/#topic-configuration-properties
@@ -57,6 +60,7 @@ module WaterDrop
57
60
  @max_wait_timeout = max_wait_timeout
58
61
  @topic_config = topic_config
59
62
  @default = default
63
+ @buffer_target = default ? producer : ConfigBuffer.new(producer, topic_config)
60
64
  super(producer)
61
65
 
62
66
  CONTRACT.validate!(to_h, Errors::VariantInvalidError)
@@ -78,6 +82,8 @@ module WaterDrop
78
82
  Transactions
79
83
  ].each do |scope|
80
84
  scope.instance_methods(false).each do |method_name|
85
+ target = CONFIG_BUFFERED.include?(method_name) ? "@buffer_target" : "@producer"
86
+
81
87
  # We save and restore any variant already active for this producer in this fiber rather
82
88
  # than unconditionally deleting it. A variant-wrapped method that yields user code (e.g.
83
89
  # `transaction`) may wrap a nested same-producer variant call; without save/restore the
@@ -103,7 +109,7 @@ module WaterDrop
103
109
  prev = ref[@producer.id]
104
110
  ref[@producer.id] = self
105
111
 
106
- @producer.#{method_name}(*args, &block)
112
+ #{target}.#{method_name}(*args, &block)
107
113
  ensure
108
114
  had ? (ref[@producer.id] = prev) : ref.delete(@producer.id)
109
115
  end
@@ -17,10 +17,14 @@ module WaterDrop
17
17
  # Local storage for given thread waterdrop client references for variants
18
18
  ::Fiber.send(:attr_accessor, :waterdrop_clients)
19
19
 
20
+ # Marks an `Rdkafka::Config::ConfigError` raised by a dispatch (invalid variant `topic_config`).
21
+ DispatchConfigFailure = Module.new
22
+
20
23
  # Which of the inline flow errors do we want to intercept and re-bind
21
24
  SUPPORTED_FLOW_ERRORS = [
22
25
  Rdkafka::RdkafkaError,
23
- Rdkafka::Producer::DeliveryHandle::WaitTimeoutError
26
+ Rdkafka::Producer::DeliveryHandle::WaitTimeoutError,
27
+ DispatchConfigFailure
24
28
  ].freeze
25
29
 
26
30
  # Empty hash to save on memory allocations
@@ -30,7 +34,7 @@ module WaterDrop
30
34
  EMPTY_ARRAY = [].freeze
31
35
 
32
36
  private_constant(
33
- :SUPPORTED_FLOW_ERRORS, :EMPTY_HASH, :EMPTY_ARRAY
37
+ :DispatchConfigFailure, :SUPPORTED_FLOW_ERRORS, :EMPTY_HASH, :EMPTY_ARRAY
34
38
  )
35
39
 
36
40
  def_delegators :config
@@ -268,8 +272,8 @@ module WaterDrop
268
272
  # Builds the variant alteration and returns it.
269
273
  #
270
274
  # @param args [Hash] variant configuration options
271
- # @option args [Integer, nil] :max_wait_timeout alteration to max wait timeout or nil to use
272
- # default
275
+ # @option args [Integer] :max_wait_timeout alteration to max wait timeout. Omit it to use the
276
+ # producer default
273
277
  # @option args [Hash] :topic_config extra topic configuration that can be altered
274
278
  # @option args [Boolean] :default is this a default variant or an altered one
275
279
  # @return [WaterDrop::Producer::Variant] variant proxy to use with alterations
@@ -452,7 +456,7 @@ module WaterDrop
452
456
  # `error.occurred` instrumentation emitted by the dispatch itself, so swallowing the
453
457
  # re-raised wrapper here does not hide it.
454
458
  begin
455
- flush(true)
459
+ flush_buffer(true)
456
460
  rescue Errors::ProduceError
457
461
  nil
458
462
  end
@@ -570,6 +574,9 @@ module WaterDrop
570
574
 
571
575
  # Ensures that we don't run any operations when the producer is not configured or when it
572
576
  # was already closed
577
+ # @raise [Errors::ProducerNotConfiguredError] when the producer is not configured
578
+ # @raise [Errors::ProducerClosedError] when the producer is closing or closed
579
+ # @raise [Errors::StatusInvalidError] when the producer is in an unknown state
573
580
  def ensure_active!
574
581
  # Capture the lifecycle state once. Another thread may be transitioning the producer between
575
582
  # states (for example configured -> connected while reloading the client after a fatal error),
@@ -591,7 +598,7 @@ module WaterDrop
591
598
  # Ensures that the message we want to send out to Kafka is actually valid and that it can be
592
599
  # sent there
593
600
  # @param message [Hash] message we want to send
594
- # @raise [Karafka::Errors::MessageInvalidError]
601
+ # @raise [Errors::MessageInvalidError]
595
602
  def validate_message!(message)
596
603
  @contract.validate!(message, Errors::MessageInvalidError)
597
604
  end
@@ -616,7 +623,7 @@ module WaterDrop
616
623
  #
617
624
  # For a transactional producer we wrap the whole dispatch (including the operations-counter
618
625
  # bookkeeping) in `transaction`, so `@transaction_mutex` is acquired BEFORE
619
- # `@operations_in_progress` is incremented. This makes `#produce` acquire locks in the same
626
+ # `@operations_in_progress` is incremented. This makes `#dispatch` acquire locks in the same
620
627
  # order as `#close` (`@transaction_mutex` -> `@operating_mutex` -> operations counter) and
621
628
  # removes a lock-order inversion: without it, a dispatch that had already counted itself could
622
629
  # block forever on `@transaction_mutex` held by a concurrent `#close` that was itself waiting
@@ -629,7 +636,7 @@ module WaterDrop
629
636
  # we surface in the `message.*` queue-full error type. Passed explicitly by each public entry
630
637
  # point so we never have to walk the call stack to recover it (the number of internal frames
631
638
  # varies because the transactional path wraps the dispatch in a `transaction`).
632
- def produce(message, label)
639
+ def dispatch(message, label)
633
640
  if transactional? && !@transaction_mutex.owned?
634
641
  transaction { produce_to_client(message, label) }
635
642
  else
@@ -660,19 +667,31 @@ module WaterDrop
660
667
  # We basically only duplicate the message hash only if it is needed.
661
668
  # It is needed when user is using a custom settings variant or when symbol is provided as
662
669
  # the topic name. We should never mutate user input message as it may be a hash that the
663
- # user is using for some other operations
664
- if message[:topic].is_a?(Symbol) || !variant.default?
670
+ # user is using for some other operations. A message buffered through a variant already
671
+ # carries that variant's topic config, so it needs no copy for it
672
+ if message[:topic].is_a?(Symbol) || (!variant.default? && !message.key?(:topic_config))
665
673
  message = message.dup
666
674
  # In case someone defines topic as a symbol, we need to convert it into a string as
667
675
  # librdkafka does not accept symbols
668
676
  message[:topic] = message[:topic].to_s
669
- message[:topic_config] = variant.topic_config
677
+ message[:topic_config] ||= variant.topic_config
670
678
  end
671
679
 
672
- result = if transactional?
673
- transaction { client.produce(**message) }
674
- else
675
- client.produce(**message)
680
+ # Built before the rescue below, so an invalid `kafka` config raises as it is. The
681
+ # transactional branch takes the client again under the transaction lock, as a transactional
682
+ # reload done while this thread waits for that lock replaces it
683
+ rd_client = client
684
+
685
+ result = begin
686
+ if transactional?
687
+ transaction { client.produce(**message) }
688
+ else
689
+ rd_client.produce(**message)
690
+ end
691
+ rescue Rdkafka::Config::ConfigError => e
692
+ e.extend(DispatchConfigFailure)
693
+
694
+ raise
676
695
  end
677
696
 
678
697
  # Remember the first delivery handle of the current transaction. Aborting while the very first
@@ -711,7 +730,7 @@ module WaterDrop
711
730
  rescue SUPPORTED_FLOW_ERRORS.first => e
712
731
  # Check if this is a fatal error on an idempotent producer and we should reload.
713
732
  #
714
- # We must never reload while closing. During `#close` the final `flush` runs while this
733
+ # We must never reload while closing. During `#close` the final `flush_buffer` runs while this
715
734
  # thread already owns `@operating_mutex`; the idempotent reload re-acquires that same mutex,
716
735
  # which Ruby rejects with `ThreadError: deadlock; recursive locking`, and it would also try to
717
736
  # rebuild the very client we are tearing down. In that case we let the error propagate so
@@ -2,5 +2,5 @@
2
2
 
3
3
  module WaterDrop
4
4
  # Current WaterDrop version
5
- VERSION = "2.10.9"
5
+ VERSION = "2.10.11"
6
6
  end
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": {
data/renovate.json CHANGED
@@ -1,6 +1,8 @@
1
1
  {
2
2
  "bundler": {
3
- "managerFilePatterns": ["/(^|/)Gemfile\\.lint$/"]
3
+ "managerFilePatterns": [
4
+ "/(^|/)Gemfile\\.lint$/"
5
+ ]
4
6
  },
5
7
  "$schema": "https://docs.renovatebot.com/renovate-schema.json",
6
8
  "extends": [
@@ -51,6 +53,13 @@
51
53
  "ruby/setup-ruby"
52
54
  ],
53
55
  "minimumReleaseAge": "5 days"
56
+ },
57
+ {
58
+ "description": "Major updates stay manual",
59
+ "matchUpdateTypes": [
60
+ "major"
61
+ ],
62
+ "automerge": false
54
63
  }
55
64
  ],
56
65
  "minimumReleaseAge": "7 days",
@@ -62,5 +71,13 @@
62
71
  "schedule": [
63
72
  "before 4am on the first day of the month"
64
73
  ]
74
+ },
75
+ "automerge": true,
76
+ "platformAutomerge": true,
77
+ "osvVulnerabilityAlerts": true,
78
+ "vulnerabilityAlerts": {
79
+ "labels": [
80
+ "security"
81
+ ]
65
82
  }
66
83
  }
data/waterdrop.gemspec CHANGED
@@ -16,8 +16,8 @@ Gem::Specification.new do |spec|
16
16
  spec.description = spec.summary
17
17
  spec.licenses = %w[LGPL-3.0-only Commercial]
18
18
 
19
- spec.add_dependency "karafka-core", ">= 2.5.12", "< 3.0.0"
20
- spec.add_dependency "karafka-rdkafka", ">= 0.31.0"
19
+ spec.add_dependency "karafka-core", ">= 2.6.8", "< 3.0.0"
20
+ spec.add_dependency "karafka-rdkafka", ">= 0.32.0"
21
21
  spec.add_dependency "zeitwerk", "~> 2.3"
22
22
 
23
23
  spec.required_ruby_version = ">= 3.3.0"
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: waterdrop
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.10.9
4
+ version: 2.10.11
5
5
  platform: ruby
6
6
  authors:
7
7
  - Maciej Mensfeld
@@ -15,7 +15,7 @@ dependencies:
15
15
  requirements:
16
16
  - - ">="
17
17
  - !ruby/object:Gem::Version
18
- version: 2.5.12
18
+ version: 2.6.8
19
19
  - - "<"
20
20
  - !ruby/object:Gem::Version
21
21
  version: 3.0.0
@@ -25,7 +25,7 @@ dependencies:
25
25
  requirements:
26
26
  - - ">="
27
27
  - !ruby/object:Gem::Version
28
- version: 2.5.12
28
+ version: 2.6.8
29
29
  - - "<"
30
30
  - !ruby/object:Gem::Version
31
31
  version: 3.0.0
@@ -35,14 +35,14 @@ dependencies:
35
35
  requirements:
36
36
  - - ">="
37
37
  - !ruby/object:Gem::Version
38
- version: 0.31.0
38
+ version: 0.32.0
39
39
  type: :runtime
40
40
  prerelease: false
41
41
  version_requirements: !ruby/object:Gem::Requirement
42
42
  requirements:
43
43
  - - ">="
44
44
  - !ruby/object:Gem::Version
45
- version: 0.31.0
45
+ version: 0.32.0
46
46
  - !ruby/object:Gem::Dependency
47
47
  name: zeitwerk
48
48
  requirement: !ruby/object:Gem::Requirement
@@ -130,6 +130,7 @@ files:
130
130
  - lib/waterdrop/producer/tombstone.rb
131
131
  - lib/waterdrop/producer/transactions.rb
132
132
  - lib/waterdrop/producer/variant.rb
133
+ - lib/waterdrop/producer/variant/config_buffer.rb
133
134
  - lib/waterdrop/version.rb
134
135
  - package-lock.json
135
136
  - package.json