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
@@ -114,12 +114,21 @@ module Rdkafka
114
114
  # @see Config#admin
115
115
  NATIVE_KAFKA_POLL_TIMEOUT_MS = 100
116
116
 
117
- # Sleep interval used in NativeKafka#synchronize wait loop
118
- # @see NativeKafka#synchronize
119
- NATIVE_KAFKA_SYNCHRONIZE_SLEEP_INTERVAL_MS = 10
120
-
121
117
  # TTL for partitions count cache entries (30 seconds)
122
- # @see Producer::PartitionsCountCache
123
- PARTITIONS_COUNT_CACHE_TTL_MS = 30_000
118
+ # @see Producer::PartitionCountCache
119
+ PARTITION_COUNT_CACHE_TTL_MS = 30_000
120
+
121
+ # @deprecated Use {PARTITION_COUNT_CACHE_TTL_MS} instead. It will be removed in v1.0.0.
122
+ PARTITIONS_COUNT_CACHE_TTL_MS = PARTITION_COUNT_CACHE_TTL_MS
123
+
124
+ # How long an expired partitions count is served after a refresh failed on a transient
125
+ # (e.g. transport) error, before the next refresh attempt. Longer than one failed metadata
126
+ # refresh (up to ~7 s with retries), so produces are not blocked most of the time
127
+ # @see Producer::PartitionCountCache#get
128
+ PARTITION_COUNT_CACHE_STALE_BACKOFF_MS = 10_000
129
+
130
+ # @deprecated Use {PARTITION_COUNT_CACHE_STALE_BACKOFF_MS} instead.
131
+ # It will be removed in v1.0.0.
132
+ PARTITIONS_COUNT_CACHE_STALE_BACKOFF_MS = PARTITION_COUNT_CACHE_STALE_BACKOFF_MS
124
133
  end
125
134
  end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rdkafka
4
+ module Helpers
5
+ # Shared message build error handling for Consumer and ShareConsumer.
6
+ module MessageBuildError
7
+ private
8
+
9
+ # Rebuilds an error raised while building a message with that message's topic, partition
10
+ # and offset. librdkafka has already returned the message, so the caller needs them to act
11
+ # on it: a consumer seeks back to it, a share consumer acknowledges it.
12
+ # @param native_message [Rdkafka::Bindings::Message] the native message that failed to build
13
+ # @param error [RdkafkaError] the error raised while building it
14
+ # @return [RdkafkaError]
15
+ def message_build_error(native_message, error)
16
+ Rdkafka::RdkafkaError.new(
17
+ error.rdkafka_response,
18
+ error.message_prefix,
19
+ broker_message: error.broker_message,
20
+ details: {
21
+ topic: Rdkafka::Bindings.rd_kafka_topic_name(native_message[:rkt]),
22
+ partition: native_message[:partition],
23
+ offset: native_message[:offset]
24
+ }.freeze,
25
+ instance_name: error.instance_name
26
+ )
27
+ end
28
+ end
29
+ end
30
+ end
@@ -4,6 +4,13 @@ module Rdkafka
4
4
  # @private
5
5
  # A wrapper around a native kafka that polls and cleanly exits
6
6
  class NativeKafka
7
+ # Defers every asynchronous interrupt (`Thread#raise`, `Thread#kill`) for the decrement of the
8
+ # operations in progress counter. Frozen and `compare_by_identity`, so MRI uses it without
9
+ # copying it on every call.
10
+ DEFER_INTERRUPTS = { Object => :never }.compare_by_identity.freeze
11
+
12
+ private_constant :DEFER_INTERRUPTS
13
+
7
14
  # Creates a new NativeKafka wrapper
8
15
  # @param inner [FFI::Pointer] pointer to the native Kafka handle
9
16
  # @param run_polling_thread [Boolean] whether to run a background polling thread
@@ -25,21 +32,15 @@ module Rdkafka
25
32
  @access_mutex = Mutex.new
26
33
  # Lock around internal polling
27
34
  @poll_mutex = Mutex.new
28
- # Lock around decrementing the operations in progress counter
29
- # We have two mutexes - one for increment (`@access_mutex`) and one for decrement mutex
30
- # because they serve different purposes:
31
- #
32
- # - `@access_mutex` allows us to lock the execution and make sure that any operation within
33
- # the `#synchronize` is the only one running and that there are no other running
34
- # operations.
35
- # - `@decrement_mutex` ensures, that our decrement operation is thread-safe for any Ruby
36
- # implementation.
37
- #
38
- # We do not use the same mutex, because it could create a deadlock when an already
39
- # incremented operation cannot decrement because `@access_lock` is now owned by a different
40
- # thread in a synchronized mode and the synchronized mode is waiting on the decrement.
41
- @decrement_mutex = Mutex.new
42
- # counter for operations in progress using inner
35
+ # Signalled when `#synchronize` ends and, only while `#synchronize` waits, when the operations
36
+ # in progress counter reaches zero: no one else waits for zero, so other decrements skip the
37
+ # broadcast. `#synchronize` waits on it with `@access_mutex` released, so operations that
38
+ # started before it can still decrement the counter.
39
+ @operations_done = ConditionVariable.new
40
+ # Set while `#synchronize` runs, so no new operation starts until it ends
41
+ @synchronizing = false
42
+ # counter for operations in progress using inner, changed only under `@access_mutex`, so no
43
+ # update is lost on Rubies without a GVL (JRuby)
43
44
  @operations_in_progress = 0
44
45
 
45
46
  @run_polling_thread = run_polling_thread
@@ -63,8 +64,7 @@ module Rdkafka
63
64
  Rdkafka::Bindings.rd_kafka_poll(@inner, 0)
64
65
 
65
66
  if @run_polling_thread
66
- # Start thread to poll client for delivery callbacks,
67
- # not used in consumer.
67
+ # Start thread to poll client for delivery callbacks, not used in consumer.
68
68
  @polling_thread = Thread.new do
69
69
  loop do
70
70
  @poll_mutex.synchronize do
@@ -90,15 +90,53 @@ module Rdkafka
90
90
  # @return [Object] the result of the block
91
91
  # @raise [ClosedInnerError] when the inner handle is nil
92
92
  def with_inner
93
- if @access_mutex.owned?
94
- @operations_in_progress += 1
95
- else
96
- @access_mutex.synchronize { @operations_in_progress += 1 }
97
- end
93
+ owned = @access_mutex.owned?
94
+ # Set in the same step as the increment, so the `ensure` undoes only an increment that
95
+ # happened, even when `Thread#raise`, `Timeout` or `Thread#kill` interrupts this method
96
+ counted = false
97
+ released = false
98
98
 
99
- @inner.nil? ? raise(ClosedInnerError) : yield(@inner)
100
- ensure
101
- @decrement_mutex.synchronize { @operations_in_progress -= 1 }
99
+ begin
100
+ if owned
101
+ @operations_in_progress += 1
102
+ counted = true
103
+ else
104
+ @access_mutex.synchronize do
105
+ @operations_done.wait(@access_mutex) while @synchronizing
106
+ @operations_in_progress += 1
107
+ counted = true
108
+ end
109
+ end
110
+
111
+ @inner.nil? ? raise(ClosedInnerError) : yield(@inner)
112
+ ensure
113
+ # Deferred from the first step of the `ensure`: an interrupt delivered before the decrement
114
+ # (even at the branches below) would skip it and leave `#synchronize` (and so `#close`)
115
+ # waiting forever. JRuby delivers a `Thread#kill` that arrived during a blocking native
116
+ # call at its first chance after the call, the lock below. Inline, not in
117
+ # `#release_operation`: an extra method call costs every call
118
+ begin
119
+ Thread.handle_interrupt(DEFER_INTERRUPTS) do
120
+ if !counted
121
+ # Interrupted before the increment: nothing to undo
122
+ elsif owned
123
+ @operations_in_progress -= 1
124
+ counted = false
125
+ else
126
+ # Not `lock` / `unlock`: a signal trap handler still runs (and can raise) under the mask
127
+ @access_mutex.synchronize do
128
+ @operations_in_progress -= 1
129
+ counted = false
130
+ @operations_done.broadcast if @synchronizing && @operations_in_progress.zero?
131
+ end
132
+ end
133
+
134
+ released = true
135
+ end
136
+ ensure
137
+ release_operation(owned, counted) unless released
138
+ end
139
+ end
102
140
  end
103
141
 
104
142
  # Executes a block while holding exclusive access to the native Kafka handle
@@ -106,15 +144,16 @@ module Rdkafka
106
144
  # @yield [FFI::Pointer] the inner native Kafka handle
107
145
  # @return [Object] the result of the block
108
146
  def synchronize(&block)
109
- @access_mutex.synchronize do
110
- # Wait for any commands using the inner to finish
111
- # This can take a while on blocking operations like polling but is essential not to proceed
112
- # with certain types of operations like resources destruction as it can cause the process
113
- # to hang or crash
114
- sleep(Defaults::NATIVE_KAFKA_SYNCHRONIZE_SLEEP_INTERVAL_MS / 1_000.0) until @operations_in_progress.zero?
147
+ exclusively { with_inner(&block) }
148
+ end
115
149
 
116
- with_inner(&block)
117
- end
150
+ # Executes a block while holding exclusive access to the native Kafka handle, unless the handle
151
+ # was closed, also by another thread while this one waited for the access
152
+ # @param block [Proc] block to execute with the native handle
153
+ # @yield [FFI::Pointer] the inner native Kafka handle
154
+ # @return [Object, nil] the result of the block or nil when the handle is closed
155
+ def synchronize_unless_closed(&block)
156
+ exclusively { with_inner(&block) unless @inner.nil? }
118
157
  end
119
158
 
120
159
  # Returns a finalizer proc for closing this native Kafka handle
@@ -202,7 +241,10 @@ module Rdkafka
202
241
  def close(object_id = nil)
203
242
  return if closed?
204
243
 
205
- synchronize do
244
+ exclusively do
245
+ # Another thread closed the handle while this one waited for the access
246
+ return if @inner.nil?
247
+
206
248
  # Indicate to the outside world that we are closing
207
249
  @closing = true
208
250
 
@@ -210,8 +252,7 @@ module Rdkafka
210
252
  # Indicate to polling thread that we're closing
211
253
  @polling_thread[:closing] = true
212
254
 
213
- # Wait for the polling thread to finish up,
214
- # this can be aborted in practice if this
255
+ # Wait for the polling thread to finish up, this can be aborted in practice if this
215
256
  # code runs from a finalizer.
216
257
  @polling_thread.join
217
258
  end
@@ -219,11 +260,6 @@ module Rdkafka
219
260
  # Destroy the client after locking both mutexes
220
261
  @poll_mutex.lock
221
262
 
222
- # This check prevents a race condition, where we would enter the close in two threads
223
- # and after unlocking the primary one that hold the lock but finished, ours would be unlocked
224
- # and would continue to run, trying to destroy inner twice
225
- return unless @inner
226
-
227
263
  yield if block_given?
228
264
 
229
265
  Rdkafka::Bindings.rd_kafka_destroy(@inner)
@@ -233,5 +269,64 @@ module Rdkafka
233
269
  @poll_mutex = nil
234
270
  end
235
271
  end
272
+
273
+ private
274
+
275
+ # Executes a block while holding `@access_mutex`, once all operations in progress are done
276
+ # @yield block to execute with exclusive access
277
+ # @return [Object] the result of the block
278
+ def exclusively
279
+ @access_mutex.synchronize do
280
+ @operations_done.wait(@access_mutex) while @synchronizing
281
+ @synchronizing = true
282
+
283
+ begin
284
+ # Wait for any commands using the inner to finish
285
+ # This can take a while on blocking operations like polling but is essential not to
286
+ # proceed with certain types of operations like resources destruction as it can cause the
287
+ # process to hang or crash
288
+ @operations_done.wait(@access_mutex) until @operations_in_progress.zero?
289
+
290
+ yield
291
+ ensure
292
+ @synchronizing = false
293
+ @operations_done.broadcast
294
+ end
295
+ end
296
+ end
297
+
298
+ # Finishes the release of `#with_inner` when a signal trap handler raised during it
299
+ #
300
+ # A trap handler still runs (and can raise) under the mask, so the `ensure` calls this method
301
+ # again until the release is done, then the error propagates.
302
+ #
303
+ # @param owned [Boolean] whether the caller already holds `@access_mutex`
304
+ # @param counted [Boolean] whether the counter still has to be decremented
305
+ def release_operation(owned, counted)
306
+ released = false
307
+
308
+ Thread.handle_interrupt(DEFER_INTERRUPTS) do
309
+ if owned
310
+ if counted
311
+ @operations_in_progress -= 1
312
+ counted = false
313
+ end
314
+ else
315
+ # Not `lock` / `unlock`: a raise in a trap handler would leave the lock held
316
+ @access_mutex.synchronize do
317
+ if counted
318
+ @operations_in_progress -= 1
319
+ counted = false
320
+ end
321
+
322
+ @operations_done.broadcast if @synchronizing && @operations_in_progress.zero?
323
+ end
324
+ end
325
+
326
+ released = true
327
+ end
328
+ ensure
329
+ release_operation(owned, counted) unless released
330
+ end
236
331
  end
237
332
  end
@@ -0,0 +1,258 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rdkafka
4
+ class Producer
5
+ # Caching mechanism for Kafka topic partition counts to avoid frequent cluster queries
6
+ #
7
+ # This cache is designed to optimize the process of obtaining partition counts for topics.
8
+ # It uses several strategies to minimize Kafka cluster queries:
9
+ #
10
+ # @note Design considerations:
11
+ #
12
+ # 1. Statistics-based updates
13
+ # When statistics callbacks are enabled (via `statistics.interval.ms`), we leverage
14
+ # this data to proactively update the partition counts cache. This approach costs
15
+ # approximately 0.02ms of processing time during each statistics interval (typically
16
+ # every 5 seconds) but eliminates the need for explicit blocking metadata queries.
17
+ #
18
+ # 2. Edge case handling
19
+ # If a user configures `statistics.interval.ms` much higher than the default cache TTL
20
+ # ({Defaults::PARTITION_COUNT_CACHE_TTL_MS}ms), the cache will still function correctly.
21
+ # When statistics updates don't occur frequently enough, the cache entries will expire
22
+ # naturally, triggering a blocking refresh when needed.
23
+ #
24
+ # 3. User configuration awareness
25
+ # The cache respects user-defined settings. If `topic.metadata.refresh.interval.ms` is
26
+ # set very high, the responsibility for potentially stale data falls on the user. This
27
+ # is an explicit design choice to honor user configuration preferences and align with
28
+ # librdkafka settings.
29
+ #
30
+ # 4. Process-wide efficiency
31
+ # Since this cache is shared across all Rdkafka producers and consumers within a process,
32
+ # having multiple clients improves overall efficiency. Each client contributes to keeping
33
+ # the cache updated, benefiting all other clients.
34
+ #
35
+ # 5. Thread-safety approach
36
+ # One cache-wide mutex guards every read and write of the cached entries, so the cache stays
37
+ # consistent on Rubies without a GVL (JRuby). The metadata request that refreshes an entry
38
+ # runs outside of it, so a slow lookup for one topic never blocks the others.
39
+ #
40
+ # 6. Topic recreation handling
41
+ # If a topic is deleted and recreated with fewer partitions, the cache keeps reporting the
42
+ # higher count only until the entry's TTL expires. The first refresh after expiry performs
43
+ # an authoritative metadata read and adopts the lower count. Within the TTL window a lower
44
+ # value is still ignored, so a transient or racy lower read cannot clobber a correct higher
45
+ # count.
46
+ #
47
+ # 7. Cluster outages
48
+ # If the refresh of an expired entry fails on a transient error (for example all brokers
49
+ # are unreachable), the last known count is served instead of raising, and the next refresh
50
+ # is attempted after {Defaults::PARTITION_COUNT_CACHE_STALE_BACKOFF_MS}. This lets
51
+ # `partition_key` produces keep buffering in librdkafka during an outage. Without a known
52
+ # count the error is raised. Only one caller refreshes an expired entry at a time; the
53
+ # others get the known count meanwhile.
54
+ class PartitionCountCache
55
+ include Helpers::Time
56
+
57
+ # Refresh errors after which the last known count is still served
58
+ STALE_FALLBACK_ERRORS = %i[
59
+ transport
60
+ timed_out
61
+ all_brokers_down
62
+ resolve
63
+ ].freeze
64
+
65
+ private_constant :STALE_FALLBACK_ERRORS
66
+
67
+ # @return [Integer] time-to-live in milliseconds for cached values
68
+ attr_reader :ttl_ms
69
+
70
+ # Creates a new partition count cache
71
+ #
72
+ # @param ttl [Integer, nil] DEPRECATED: Use ttl_ms instead.
73
+ # Time-to-live in seconds for cached values. Will be removed in v1.0.0.
74
+ # @param ttl_ms [Integer, nil] Time-to-live in milliseconds for cached values.
75
+ # Defaults to {Defaults::PARTITION_COUNT_CACHE_TTL_MS}.
76
+ def initialize(ttl = :not_provided, ttl_ms: :not_provided)
77
+ @counts = {}
78
+ @mutex = Mutex.new
79
+
80
+ # Determine which TTL value to use
81
+ if ttl != :not_provided && ttl_ms != :not_provided
82
+ warn "DEPRECATION WARNING: Both ttl and ttl_ms were provided to PartitionCountCache. " \
83
+ "Using ttl_ms. The ttl parameter is deprecated and will be removed in v1.0.0."
84
+ @ttl_ms = ttl_ms
85
+ elsif ttl != :not_provided
86
+ warn "DEPRECATION WARNING: ttl (seconds) parameter for PartitionCountCache is deprecated. " \
87
+ "Use ttl_ms (milliseconds) instead. This parameter will be removed in v1.0.0."
88
+ @ttl_ms = (ttl * 1000).to_i
89
+ elsif ttl_ms == :not_provided
90
+ @ttl_ms = Defaults::PARTITION_COUNT_CACHE_TTL_MS
91
+ else
92
+ @ttl_ms = ttl_ms
93
+ end
94
+ end
95
+
96
+ # Changes the time-to-live of cached values. Cached entries are kept and expire based on the
97
+ # new value.
98
+ #
99
+ # @param value [Integer] time-to-live in milliseconds
100
+ # @raise [ArgumentError] when the value is not a positive Integer
101
+ def ttl_ms=(value)
102
+ raise ArgumentError.new("ttl_ms has to be a positive Integer") unless value.is_a?(Integer) && value.positive?
103
+
104
+ @ttl_ms = value
105
+ end
106
+
107
+ # Reads partition count for a topic with automatic refresh when expired
108
+ #
109
+ # This method will return the cached partition count if available and not expired.
110
+ # If the value is expired or not available, it will execute the provided block
111
+ # to fetch the current value from Kafka.
112
+ #
113
+ # @param topic_name [String] Kafka topic name
114
+ # @yield Block that returns the current partition count when cache needs refreshing
115
+ # @yieldreturn [Integer] Current partition count retrieved from Kafka
116
+ # @return [Integer] Partition count for the topic
117
+ # @raise [RdkafkaError] when the refresh fails and there is no last known count to serve, or
118
+ # when it fails on a non-transient error
119
+ #
120
+ # @note The metadata request in the block runs outside of the cache-wide mutex.
121
+ def get(topic_name)
122
+ current_info = expired_at = lease = nil
123
+
124
+ # `next` instead of `return`: a return from the block allocates on every cache hit
125
+ cached_count = @mutex.synchronize do
126
+ current_info = @counts[topic_name]
127
+
128
+ next current_info[1] if current_info && !expired?(current_info[0])
129
+
130
+ if current_info
131
+ # While the refresh runs, other callers see a fresh entry and get the known count
132
+ # instead of running their own metadata request. The lease outlasts a failed refresh
133
+ # even with a TTL shorter than one metadata request.
134
+ expired_at = current_info[0]
135
+ lease = monotonic_now_ms + Defaults::PARTITION_COUNT_CACHE_STALE_BACKOFF_MS
136
+ current_info[0] = lease
137
+ end
138
+
139
+ nil
140
+ end
141
+
142
+ return cached_count if cached_count
143
+
144
+ return refresh(topic_name, current_info, expired_at, lease) { yield } if current_info
145
+
146
+ set(topic_name, yield)
147
+
148
+ @mutex.synchronize { @counts[topic_name][1] }
149
+ end
150
+
151
+ # Update partition count for a topic when needed
152
+ #
153
+ # This method updates the partition count for a topic in the cache.
154
+ # The check and the update run under the cache-wide mutex, so concurrent updates never
155
+ # interleave.
156
+ #
157
+ # @param topic_name [String] Kafka topic name
158
+ # @param new_count [Integer] New partition count value
159
+ #
160
+ # @note We prioritize higher partition counts. Within the TTL window a lower value is treated
161
+ # as a stale/racy read and ignored, since partition counts only grow during normal
162
+ # operation. Once the entry has expired a lower value is an authoritative refresh (e.g. the
163
+ # topic was recreated with fewer partitions) and is adopted.
164
+ def set(topic_name, new_count)
165
+ @mutex.synchronize do
166
+ current_info = @counts[topic_name]
167
+
168
+ if current_info.nil?
169
+ # Create new entry
170
+ @counts[topic_name] = [monotonic_now_ms, new_count]
171
+ elsif new_count > current_info[1] || expired?(current_info[0])
172
+ # A higher count always wins; a lower count is accepted only when the existing entry
173
+ # has expired, so a concurrent fresh higher value (which reset the timestamp) is never
174
+ # clobbered by a stale lower one.
175
+ current_info[0] = monotonic_now_ms
176
+ current_info[1] = new_count
177
+ else
178
+ # Same or lower count within the TTL window: refresh the timestamp only
179
+ current_info[0] = monotonic_now_ms
180
+ end
181
+ end
182
+ end
183
+
184
+ # @return [Hash] hash with ttls and partitions counts array
185
+ # @note Returns the live hash without locking: do not read it while other threads use the
186
+ # cache.
187
+ def to_h
188
+ @counts
189
+ end
190
+
191
+ private
192
+
193
+ # Refreshes an expired entry that {#get} leased. Runs the metadata request outside of the
194
+ # cache-wide mutex.
195
+ #
196
+ # The block performs an authoritative metadata read. We hand it to `set`, which adopts a
197
+ # higher count always and a lower count once the entry has expired (e.g. the topic was
198
+ # recreated with fewer partitions). We then return whatever `set` settled on so a concurrent
199
+ # refresh that wrote a higher value still wins.
200
+ #
201
+ # @param topic_name [String] Kafka topic name
202
+ # @param current_info [Array<Integer>] cached timestamp and partition count
203
+ # @param expired_at [Integer] timestamp of the entry before it was leased
204
+ # @param lease [Integer] timestamp {#get} set on the entry for the refresh
205
+ # @yieldreturn [Integer] Current partition count retrieved from Kafka
206
+ # @return [Integer] Partition count for the topic
207
+ # @raise [RdkafkaError] when the refresh fails on a non-transient error
208
+ def refresh(topic_name, current_info, expired_at, lease)
209
+ begin
210
+ new_count = yield
211
+ rescue RdkafkaError => e
212
+ raise unless STALE_FALLBACK_ERRORS.include?(e.code)
213
+ ensure
214
+ @mutex.synchronize do
215
+ # Hand the entry back as expired, unless a concurrent write refreshed it meanwhile
216
+ current_info[0] = expired_at if current_info[0] == lease
217
+ end
218
+ end
219
+
220
+ if new_count.nil?
221
+ return @mutex.synchronize do
222
+ # A concurrent write refreshed the entry, so it keeps its full TTL
223
+ next current_info[1] unless current_info[0] == expired_at
224
+
225
+ serve_stale(current_info)
226
+ end
227
+ end
228
+
229
+ set(topic_name, new_count)
230
+
231
+ @mutex.synchronize { @counts[topic_name][1] }
232
+ end
233
+
234
+ # Keeps serving an expired entry after a failed refresh and schedules the next refresh
235
+ # after {Defaults::PARTITION_COUNT_CACHE_STALE_BACKOFF_MS}. Call it under the cache-wide
236
+ # mutex.
237
+ #
238
+ # @param current_info [Array<Integer>] cached timestamp and partition count
239
+ # @return [Integer] last known partition count
240
+ def serve_stale(current_info)
241
+ current_info[0] = monotonic_now_ms - @ttl_ms + Defaults::PARTITION_COUNT_CACHE_STALE_BACKOFF_MS
242
+
243
+ current_info[1]
244
+ end
245
+
246
+ # Check if a timestamp has expired based on the TTL
247
+ #
248
+ # @param timestamp [Integer] Monotonic timestamp in milliseconds to check
249
+ # @return [Boolean] true if expired, false otherwise
250
+ def expired?(timestamp)
251
+ monotonic_now_ms - timestamp > @ttl_ms
252
+ end
253
+ end
254
+
255
+ # @deprecated Use {PartitionCountCache} instead. It will be removed in v1.0.0.
256
+ PartitionsCountCache = PartitionCountCache
257
+ end
258
+ end