waterdrop 2.10.2 → 2.10.4

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: 1329d22d7f4f960b2df24949a040dd1e1b57ec73002ed779f3bcd0c5ad4dad20
4
- data.tar.gz: b2b9868379d00dd3951df5a2e3b45bdce1b24295284fd5cb6cca410709a38a05
3
+ metadata.gz: 32f1c3b166f74db06dc75080800f4972207facc943d00d7eeab73a6c33668aed
4
+ data.tar.gz: 8de1c8eecf566e241bc375fea7de5f568cd055be35a83effcf5de23b7c92f468
5
5
  SHA512:
6
- metadata.gz: 817244d3151a463cca84a1a7fefd298c5e355337325817430cdef5f5eb1c09013d20f801f9ef95b5e9182539f8cb550f25df62042bf93bc7826e9f50ee4b1caf
7
- data.tar.gz: c60cc27e7b3787a9610229dacdcbe0440fa7332c5659f5e61348409b4ca2c507718a5bbd93bf5e088f8cc7a5d8b91da981eac0f377257ec0c4394e20dcd92994
6
+ metadata.gz: 901c6f6a576c38807eee47641675b12f9ef3907325fb2435c6b2e8656724c4f57be6593a10b7b85348b8cadd317216fe84ba182a9ccfaf3fa0208119c0609686
7
+ data.tar.gz: 25720c9a6ac31520400f181af47b389eae9def35f384cf9b1d89f8466c4cafc904c0390fbe14a1222c6917b3b26fbcc38d9580e9a0fa45db07d1cc9528c3bb85
data/.gitignore CHANGED
@@ -19,6 +19,8 @@ db/*.sqlite3
19
19
  *.rbc
20
20
  *.sassc
21
21
  .redcar/
22
+ .codex
23
+ .claude
22
24
  .capistrano/
23
25
  .sass-cache
24
26
  /config/god/sidekiq.rb
data/.ruby-version CHANGED
@@ -1 +1 @@
1
- 4.0.5
1
+ 4.0.6
data/.yard-lint.yml CHANGED
@@ -61,6 +61,34 @@ Documentation/BlankLineBeforeDefinition:
61
61
  SingleBlankLine: true
62
62
  OrphanedDocs: true
63
63
 
64
+ Documentation/DuplicateNamespaceComment:
65
+ Description: Detects namespaces documented with a YARD comment in more than one file.
66
+ Enabled: true
67
+ Severity: error
68
+
69
+ Documentation/UnderfilledLines:
70
+ Description: Detects documentation prose that wraps too early and wastes horizontal space.
71
+ Enabled: true
72
+ Severity: error
73
+ # Aligned with RuboCop's Layout/LineLength (Max: 100) so documentation prose
74
+ # wraps to the same width as code.
75
+ MaxLength: 100
76
+
77
+ Documentation/LineLength:
78
+ Description: Detects documentation lines that exceed the maximum length.
79
+ Enabled: true
80
+ Severity: error
81
+ # Aligned with RuboCop's Layout/LineLength (Max: 100).
82
+ MaxLength: 100
83
+
84
+ Documentation/TextSubstitution:
85
+ Description: Detects em/en-dashes in documentation and replaces them with hyphens.
86
+ Enabled: true
87
+ Severity: error
88
+ Substitutions:
89
+ "—": "-" # em-dash (U+2014)
90
+ "–": "-" # en-dash (U+2013)
91
+
64
92
  # Tags validators
65
93
  Tags/Order:
66
94
  Description: Enforces consistent ordering of YARD tags.
@@ -141,7 +169,7 @@ Tags/OptionTags:
141
169
  Tags/ExampleSyntax:
142
170
  Description: Validates Ruby syntax in @example tags.
143
171
  Enabled: true
144
- Severity: warning
172
+ Severity: error
145
173
 
146
174
  Tags/RedundantParamDescription:
147
175
  Description: Detects meaningless parameter descriptions that add no value.
data/CHANGELOG.md CHANGED
@@ -1,40 +1,49 @@
1
1
  # WaterDrop changelog
2
2
 
3
+ ## 2.10.4 (2026-08-26)
4
+ - [Fix] Avoid a `FrozenError` on `Producer#close` when the producer is configured with a frozen string id (for example a frozen string literal, `config.id = "rspec"`).
5
+ - [Fix] Emit `connection_pool.shutdown` only once when shutting down the global connection pool.
6
+ - [Fix] Retry a produce that races a concurrent idempotent fatal-error reload instead of leaking a raw `Rdkafka::ClosedProducerError`/`Rdkafka::ClosedInnerError`.
7
+ - [Maintenance] Stop the `#partition_count when topic does not exist` spec from flaking on slow CI runners by waiting for authoritative broker metadata before asserting the count.
8
+
9
+ ## 2.10.3 (2026-07-15)
10
+ - [Feature] Add `wait_timeout_on_transaction_abort` (default `0`, disabled) - an opt-in mitigation for [librdkafka#4849](https://github.com/confluentinc/librdkafka/issues/4849) that waits (up to the given ms) for the first delivery to be acknowledged before aborting, avoiding a fatal `INVALID_TXN_STATE`. Off by default because it changes abort semantics: the awaited message is written to the log (aborted) instead of being purged.
11
+
3
12
  ## 2.10.2 (2026-06-15)
4
- - [Feature] Expose `Producer#current_variant` as a public method. It returns the variant active for the current dispatch on the current fiber - the custom variant while inside a `#with`/`#variant`-wrapped call, otherwise the producer's default variant - so middleware and instrumentation listeners running synchronously within a dispatch can read the effective per-dispatch settings (`topic_config`, `max_wait_timeout`, `default?`). The lookup is fiber-local and dispatch-scoped: outside a variant-wrapped call (or from an asynchronous delivery callback) it returns the default variant.
5
- - [Enhancement] Stop allocating one interpolated string per message in `LoggerListener` batch produce handlers. The quoted topic strings were only ever counted (quoting is a 1:1 mapping), never displayed, so counting the raw topic values yields the identical number with zero string allocations - relevant for large `produce_many_*` batches with the default logger listener attached.
13
+ - [Feature] Expose `Producer#current_variant` as a public method returning the variant active for the current dispatch on the current fiber, so middleware and instrumentation listeners can read the effective per-dispatch settings (`topic_config`, `max_wait_timeout`, `default?`).
14
+ - [Enhancement] Stop allocating one interpolated string per message in `LoggerListener` batch produce handlers.
6
15
  - [Enhancement] Use `Array#concat` in `Producer#buffer_many` instead of appending messages one by one.
7
- - [Enhancement] Skip building the `message.acknowledged` instrumentation payload in the delivery callback when nothing is subscribed to that event. The notifications bus already short-circuits on empty listeners, but only after the payload hash was allocated - once per delivered message on the polling thread. Mirrors the listener guard already used by the statistics callback. Late subscribers keep working as the check happens on each emission.
8
- - [Enhancement] Resolve the fiber-local variant once per `#produce` call and once per `#produce_many_sync` wait phase instead of re-resolving it for every usage and for every waited delivery handle. For a 1,000-message sync batch this removes ~2,000 redundant fiber-local lookups.
9
- - [Enhancement] Do not allocate the fiber-local variants hash on the `Producer#current_variant` read path. Previously every fiber that produced messages got a Hash pinned to it for the fiber's lifetime (per producer use), even when variants were never used - wasteful under fiber-per-request servers (Falcon, async). The hash is now only created by variant wrapper methods that actually need to write to it.
10
- - [Enhancement] Cache the variant validation contract in a constant instead of instantiating a new `Contracts::Variant` on every `Producer#with` / `Producer#variant` call (mirrors the existing `Transactions::CONTRACT` pattern).
11
- - [Enhancement] Cache the tombstone validation contract in a constant instead of instantiating a new `Contracts::Tombstone` per tombstone message, removing per-message allocations in the `tombstone_*` APIs (mirrors the existing `Transactions::CONTRACT` pattern).
12
- - [Enhancement] Replace explicit `Warning[:performance]` opt-in with a dynamic approach using `Warning.categories` (available since Ruby 3.4) to automatically enable all stable opt-in warning categories in the test suite, including `:strict_unused_block` introduced in Ruby 4.0.
13
- - [Fix] Prevent a deadlock between a transactional single-message dispatch and `#close`. A single `produce_sync`/`produce_async` on a transactional producer incremented the operations counter (which `#close` drains while holding `@transaction_mutex`) before acquiring `@transaction_mutex` for its per-message transaction - an inverted lock order. A dispatch that had counted itself but not yet taken `@transaction_mutex` could deadlock a concurrent `#close` permanently (the close wait loop has no timeout). Transactional dispatches now take `@transaction_mutex` before the operation is counted, matching `#close`'s lock order (`@transaction_mutex` -> `@operating_mutex` -> operations counter).
14
- - [Fix] Prevent a deadlock (`ThreadError: deadlock; recursive locking`) when closing an idempotent producer (with `reload_on_idempotent_fatal_error` enabled) that has buffered messages whose final flush surfaces a fatal librdkafka error. `#close` performs the final flush while already holding `@operating_mutex`, and the idempotent fatal-error reload tried to re-acquire that same mutex, leaving the producer stuck in `:closing` with the native client leaked. The idempotent reload is now skipped on the closing path, and the final buffer flush is best-effort so client teardown always completes.
15
- - [Fix] Make concurrent idempotent fatal-error reload thread-safe. When several threads shared an idempotent producer (with `reload_on_idempotent_fatal_error` enabled), a single fatal librdkafka condition failed all their in-flight produces at once and each entered the reload path; the second reload ran `reload!` after the first had already reset `@client` to `nil`, raising `NoMethodError`. The idempotent reload now bails out if another thread already reloaded (mirroring the transactional path's `return if @status.configured?` guard). Additionally, `Status#active?` now classifies the lifecycle from a single atomic read and `Producer#ensure_active!` branches on one snapshot, so a concurrent `configured -> connected` transition during a reload can no longer make `ensure_active!` raise `StatusInvalidError` for a valid, active producer.
16
- - [Fix] Stop `#flush_async` / `#flush_sync` from silently dropping valid buffered messages when the dispatch fails. `#flush` removes the batch from the internal buffer before dispatching it, and a failure (a single invalid message failing validation before anything is sent, or a mid-batch inline error such as queue full) previously discarded the entire taken batch - the removed messages were never restored. A failed flush now re-buffers the messages that never reached librdkafka (the whole batch on validation failure or on a transactional rollback, the unsent remainder otherwise) so they can be retried instead of being lost.
17
- - [Fix] Make `Producer#close` fork-safe so the GC finalizer inherited by a forked child can no longer close the parent's client. `#client` registers an `ObjectSpace` finalizer that calls `#close`; that finalizer is inherited across `fork`, and a child that inherited a used producer, never touched it, and exited normally would run `#close` in the child - flushing and closing (with the real rdkafka client, `rd_kafka_destroy` on a fork-inherited handle, i.e. undefined behavior) a client owned by the parent. `#close` now detects when it runs in a process other than the one that built the client, drops the inherited references and finalizer, and returns without touching the native client (matching the existing fork guard on the `#client` path).
18
- - [Fix] Guard the internal buffer appends in `Producer#buffer` and `Producer#buffer_many` with `@buffer_mutex`. The appends mutated the shared `@messages` buffer without the lock that `flush`/`purge`/`close` hold while swapping it for a fresh array, so a concurrent swap landing between reading `@messages` and appending could drop the message into an orphaned array that is never dispatched - silently losing buffered messages in the documented "buffer in one thread, flush in another" pattern.
19
- - [Fix] Stop a nested same-producer variant call from clobbering the outer variant inside a variant `transaction` block. `transaction` is the only variant-wrapped method that yields user code, so a variant call nested inside it (another `variant.produce_*`, or a raw producer dispatch in the same scope) used to delete the shared `Fiber.current.waterdrop_clients` entry on return, making the rest of the block silently fall back to the default variant and dispatch with default `topic_config` (timeouts, compression, partitioner) instead of the altered one. The wrapper now saves and restores the previous entry instead of unconditionally deleting it (still deleting when there was none, so the fiber-local hash does not accumulate stale keys).
20
- - [Fix] Stop `ConnectionPool#shutdown` and `#reload` from silently dropping in-flight messages. Both closed every pooled producer with `close!` (force), which flushes for the max wait timeout and then purges whatever has not drained - so on a slow or unreachable broker, queued `produce_async` messages were cancelled and lost with no delivery report. They now close producers gracefully by default (`#reload` always; `#shutdown` unless called with the new `force: true`), letting messages flush instead of being purged. Pass `pool.shutdown(force: true)` to keep the old force-and-purge behavior.
21
- - [Fix] Close a race in the FD poller where a producer registered while the last one was being torn down could be left permanently unpolled (sync produces hang until timeout, async deliveries are never acknowledged). The poller thread decided to exit (last producer unregistered) and cleared its thread reference in two separate, unsynchronized steps, so a `register` landing in that gap saw the still-alive exiting thread, skipped starting a fresh one, and then had its producer's state closed by the exiting thread's cleanup. The thread now decides to stop and clears its reference in a single mutex section, so a racing `register` either keeps it running or starts a fresh thread; and the exit cleanup runs only on an abnormal exit, since a normal exit always leaves an empty registry and so can never close a producer registered in the gap.
16
+ - [Enhancement] Skip building the `message.acknowledged` instrumentation payload in the delivery callback when nothing is subscribed to that event.
17
+ - [Enhancement] Resolve the fiber-local variant once per `#produce` call and once per `#produce_many_sync` wait phase instead of re-resolving it for every usage.
18
+ - [Enhancement] Do not allocate the fiber-local variants hash on the `Producer#current_variant` read path when variants are never used.
19
+ - [Enhancement] Cache the variant validation contract in a constant instead of instantiating a new `Contracts::Variant` on every `Producer#with` / `Producer#variant` call.
20
+ - [Enhancement] Cache the tombstone validation contract in a constant instead of instantiating a new `Contracts::Tombstone` per tombstone message.
21
+ - [Enhancement] Replace explicit `Warning[:performance]` opt-in with a dynamic approach using `Warning.categories` to enable all stable opt-in warning categories in the test suite.
22
+ - [Fix] Prevent a deadlock between a transactional single-message dispatch and `#close` caused by an inverted lock order; transactional dispatches now take `@transaction_mutex` before the operation is counted.
23
+ - [Fix] Prevent a deadlock (`ThreadError: deadlock; recursive locking`) when closing an idempotent producer (with `reload_on_idempotent_fatal_error` enabled) whose final buffer flush surfaces a fatal librdkafka error; the idempotent reload is now skipped on the closing path.
24
+ - [Fix] Make concurrent idempotent fatal-error reload thread-safe so a second thread's reload can no longer raise `NoMethodError` after the first reset `@client`.
25
+ - [Fix] Stop `#flush_async` / `#flush_sync` from silently dropping valid buffered messages when the dispatch fails; unsent messages are now re-buffered so they can be retried instead of being lost.
26
+ - [Fix] Make `Producer#close` fork-safe so the GC finalizer inherited by a forked child can no longer flush and close the parent's client.
27
+ - [Fix] Guard the internal buffer appends in `Producer#buffer` and `Producer#buffer_many` with `@buffer_mutex` so a concurrent flush/purge/close swap can no longer drop a message into an orphaned array.
28
+ - [Fix] Stop a nested same-producer variant call from clobbering the outer variant inside a variant `transaction` block; the wrapper now saves and restores the previous fiber-local entry instead of deleting it.
29
+ - [Fix] Stop `ConnectionPool#shutdown` and `#reload` from silently dropping in-flight messages. They now close producers gracefully by default (`#reload` always; `#shutdown` unless called with the new `force: true`); pass `pool.shutdown(force: true)` to keep the old force-and-purge behavior.
30
+ - [Fix] Close a race in the FD poller where a producer registered while the last one was being torn down could be left permanently unpolled; the poller now decides to stop and clears its thread reference in a single mutex section.
22
31
 
23
32
  ## 2.10.1 (2026-05-25)
24
33
  - [Fix] Prevent `Producer#close` from raising `ThreadError: can't be called from trap context` when invoked from a Ruby signal trap context (e.g. Puma's `after_stopped` DSL hook in single mode). `close` now detects this case and delegates to a background thread, joining it so the caller blocks until the producer is fully closed (#866).
25
34
 
26
35
  ## 2.10.0 (2026-05-07)
27
- - [Fix] Clean up native rdkafka client, global instrumentation callbacks, and poller registration when `init_transactions` fails during producer client construction. Previously, each failed attempt permanently leaked native threads, pipe file descriptors, and callback registry entries because the started `rd_kafka_t` handle was abandoned without being destroyed.
28
- - **[Breaking]** Skip emitting librdkafka statistics when nothing is subscribed to `statistics.emitted` at the time the underlying rdkafka client is constructed. When no listener is present at build time, `statistics.interval.ms` is forced to `0` regardless of user configuration and the statistics callback is not registered, saving substantial allocations in the hot path (no JSON parsing, no statistics hash materialization, no decoration work). To use statistics, subscribe a listener to `statistics.emitted` BEFORE the first producer use (before the underlying client is lazily initialized).
29
- - **[Breaking]** Raise `WaterDrop::Errors::StatisticsNotEnabledError` when attempting to subscribe to `statistics.emitted` (either via block or via a listener that responds to `on_statistics_emitted`) on a monitor where librdkafka statistics have been disabled at client build time. This replaces the "silent nothing" failure mode with an immediate, actionable error that pinpoints the timing mistake.
36
+ - [Fix] Clean up native rdkafka client, global instrumentation callbacks, and poller registration when `init_transactions` fails during producer client construction, so failed attempts no longer leak native threads, file descriptors, and callback registry entries.
37
+ - **[Breaking]** Skip emitting librdkafka statistics when nothing is subscribed to `statistics.emitted` at the time the underlying rdkafka client is constructed (`statistics.interval.ms` is forced to `0`), saving substantial allocations in the hot path. To use statistics, subscribe a listener to `statistics.emitted` BEFORE the first producer use.
38
+ - **[Breaking]** Raise `WaterDrop::Errors::StatisticsNotEnabledError` when attempting to subscribe to `statistics.emitted` on a monitor where librdkafka statistics have been disabled at client build time, replacing the previous "silent nothing" failure mode.
30
39
  - [Feature] Add tombstone API (`#tombstone_sync`, `#tombstone_async`, `#tombstone_many_sync`, `#tombstone_many_async`) for producing tombstone records (nil-payload messages) with required key and partition validation. Works with variants.
31
- - [Fix] Add `ensure_same_process!` to `Poller#unregister` for fork safety. Without this, a child process that inherited a pre-fork producer would deadlock on `producer.close` because `unregister` waited on a latch the dead parent poller thread would never release.
40
+ - [Fix] Add `ensure_same_process!` to `Poller#unregister` for fork safety, so a child that inherited a pre-fork producer no longer deadlocks on `producer.close`.
32
41
 
33
42
  ## 2.9.0 (2026-04-08)
34
43
  - [Fix] Use `delete` in the variant ensure block to avoid leaving stale nil entries in `Fiber.current.waterdrop_clients` and prevent memory leaks in long-running processes (#836).
35
44
  - [Fix] Exclude test files, `.github/`, and `log/` directories from gem releases to reduce package size.
36
45
  - **[Breaking]** Switch default polling mode from `:thread` to `:fd`. If you experience any issues, you can revert to the previous behavior by setting `config.polling.mode = :thread`. The `:thread` mode will be deprecated in 2.10 and removed in 2.11.
37
- - **[Breaking]** Statistics decorator now only decorates keys used by the built-in Datadog metrics listener (`tx`, `txretries`, `txerrs`, `rxerrs`) and skips unused subtrees (`topics`, broker window stats). This reduces decoration cost by ~425x on large clusters (10 brokers, 20 topics, 2000 partitions). Users who rely on other `_d` or `_fd` keys in custom instrumentation should provide a custom decorator via `config.statistics_decorator`.
46
+ - **[Breaking]** Statistics decorator now only decorates keys used by the built-in Datadog metrics listener (`tx`, `txretries`, `txerrs`, `rxerrs`) and skips unused subtrees, greatly reducing decoration cost on large clusters. Users who rely on other `_d` or `_fd` keys in custom instrumentation should provide a custom decorator via `config.statistics_decorator`.
38
47
  - [Feature] Add `config.statistics_decorator` setting to allow full control over the `StatisticsDecorator` instance used for statistics decoration. Users can provide a custom decorator with different `only_keys` and `excluded_keys` to match their instrumentation needs.
39
48
  - [Change] Upscale default timeout values 3x closer to librdkafka defaults to prevent intermediate timeouts during node recovery (`message.timeout.ms`: 50s → 150s, `transaction.timeout.ms`: 55s → 165s, `max_wait_timeout`: 60s → 180s).
40
49
 
data/Gemfile.lint.lock CHANGED
@@ -58,11 +58,11 @@ GEM
58
58
  unicode-display_width (3.2.0)
59
59
  unicode-emoji (~> 4.1)
60
60
  unicode-emoji (4.2.0)
61
- yard (0.9.38)
62
- yard-lint (1.4.0)
61
+ yard (0.9.45)
62
+ yard-lint (1.10.1)
63
63
  yard (~> 0.9)
64
64
  zeitwerk (~> 2.6)
65
- zeitwerk (2.7.4)
65
+ zeitwerk (2.8.2)
66
66
 
67
67
  PLATFORMS
68
68
  ruby
@@ -79,6 +79,7 @@ DEPENDENCIES
79
79
 
80
80
  CHECKSUMS
81
81
  ast (2.4.3) sha256=954615157c1d6a382bc27d690d973195e79db7f55e9765ac7c481c60bdb4d383
82
+ bundler (4.0.17) sha256=214e21431b5665dd2f99df8a5511c6b151d7a72e8015c8b38f8b775b61cbb6c1
82
83
  json (2.18.0) sha256=b10506aee4183f5cf49e0efc48073d7b75843ce3782c68dbeb763351c08fd505
83
84
  language_server-protocol (3.17.0.5) sha256=fd1e39a51a28bf3eec959379985a72e296e9f9acfce46f6a79d31ca8760803cc
84
85
  lint_roller (1.1.0) sha256=2c0c845b632a7d172cb849cc90c1bce937a28c5c8ccccb50dfd46a485003cc87
@@ -100,9 +101,9 @@ CHECKSUMS
100
101
  standard-performance (1.9.0) sha256=49483d31be448292951d80e5e67cdcb576c2502103c7b40aec6f1b6e9c88e3f2
101
102
  unicode-display_width (3.2.0) sha256=0cdd96b5681a5949cdbc2c55e7b420facae74c4aaf9a9815eee1087cb1853c42
102
103
  unicode-emoji (4.2.0) sha256=519e69150f75652e40bf736106cfbc8f0f73aa3fb6a65afe62fefa7f80b0f80f
103
- yard (0.9.38) sha256=721fb82afb10532aa49860655f6cc2eaa7130889df291b052e1e6b268283010f
104
- yard-lint (1.4.0) sha256=7dd88fbb08fd77cb840bea899d58812817b36d92291b5693dd0eeb3af9f91f0f
105
- zeitwerk (2.7.4) sha256=2bef90f356bdafe9a6c2bd32bcd804f83a4f9b8bc27f3600fff051eb3edcec8b
104
+ yard (0.9.45) sha256=52e211493f7cb8a3ebf7e104a25a1e73937a3103092545d34cb88fafebb3dc51
105
+ yard-lint (1.10.1) sha256=172ea1905304580bd515c093d82831ec4889e725100c49d5bf77e62101f49129
106
+ zeitwerk (2.8.2) sha256=7212a61311083c604184b1ea2574b9aa05cd14f855a0841c06985cabe9181d12
106
107
 
107
108
  BUNDLED WITH
108
- 2.6.9
109
+ 4.0.17
data/Gemfile.lock CHANGED
@@ -1,7 +1,7 @@
1
1
  PATH
2
2
  remote: .
3
3
  specs:
4
- waterdrop (2.10.2)
4
+ waterdrop (2.10.4)
5
5
  karafka-core (>= 2.5.12, < 3.0.0)
6
6
  karafka-rdkafka (>= 0.24.0)
7
7
  zeitwerk (~> 2.3)
@@ -12,15 +12,14 @@ GEM
12
12
  byebug (13.0.0)
13
13
  reline (>= 0.6.0)
14
14
  connection_pool (3.0.2)
15
- docile (1.4.1)
16
15
  drb (2.2.3)
17
16
  ffi (1.17.4)
18
17
  io-console (0.8.2)
19
- json (2.19.7)
20
- karafka-core (2.5.13)
18
+ json (2.21.2)
19
+ karafka-core (2.6.2)
21
20
  karafka-rdkafka (>= 0.20.0)
22
21
  logger (>= 1.6.0)
23
- karafka-rdkafka (0.27.2)
22
+ karafka-rdkafka (0.28.0)
24
23
  ffi (~> 1.17.1)
25
24
  json (> 2.0)
26
25
  logger
@@ -39,14 +38,9 @@ GEM
39
38
  reline (0.6.3)
40
39
  io-console (~> 0.5)
41
40
  ruby2_keywords (0.0.5)
42
- simplecov (0.22.0)
43
- docile (~> 1.1)
44
- simplecov-html (~> 0.11)
45
- simplecov_json_formatter (~> 0.1)
46
- simplecov-html (0.13.2)
47
- simplecov_json_formatter (0.1.4)
41
+ simplecov (1.1.1)
48
42
  warning (1.6.0)
49
- zeitwerk (2.8.2)
43
+ zeitwerk (2.8.3)
50
44
 
51
45
  PLATFORMS
52
46
  ruby
@@ -65,13 +59,12 @@ DEPENDENCIES
65
59
  CHECKSUMS
66
60
  byebug (13.0.0) sha256=d2263efe751941ca520fa29744b71972d39cbc41839496706f5d9b22e92ae05d
67
61
  connection_pool (3.0.2) sha256=33fff5ba71a12d2aa26cb72b1db8bba2a1a01823559fb01d29eb74c286e62e0a
68
- docile (1.4.1) sha256=96159be799bfa73cdb721b840e9802126e4e03dfc26863db73647204c727f21e
69
62
  drb (2.2.3) sha256=0b00d6fdb50995fe4a45dea13663493c841112e4068656854646f418fda13373
70
63
  ffi (1.17.4) sha256=bcd1642e06f0d16fc9e09ac6d49c3a7298b9789bcb58127302f934e437d60acf
71
64
  io-console (0.8.2) sha256=d6e3ae7a7cc7574f4b8893b4fca2162e57a825b223a177b7afa236c5ef9814cc
72
- json (2.19.7) sha256=fe432c8639f6efff69f9d73b518a3705d9581ab93156f981ea72806e1e5bcc3e
73
- karafka-core (2.5.13) sha256=0acec083043bb6166c4b647a7458091cc7b08066d3b92a026932925ec7e07f61
74
- karafka-rdkafka (0.27.2) sha256=3ccce96306642be70bff8168e4e737fc10f2ffae20bc0ff0a43d88dbb7452d31
65
+ json (2.21.2) sha256=1f1d3b7cf2b3ba1a69beca0bb6db13d5438b80bff3cd54cdaaa620b9b07c1c6a
66
+ karafka-core (2.6.2) sha256=c2fd7f277201b8ca97b824b364ad76bf776b8f5527bc422dafb71f7ae48d3a13
67
+ karafka-rdkafka (0.28.0) sha256=fd845140c42341c5892215cac1e8adacda53b0461688f2e16379d82cb33eb006
75
68
  logger (1.7.0) sha256=196edec7cc44b66cfb40f9755ce11b392f21f7967696af15d274dde7edff0203
76
69
  mini_portile2 (2.8.9) sha256=0cd7c7f824e010c072e33f68bc02d85a00aeb6fce05bb4819c03dfd3c140c289
77
70
  minitest (6.0.6) sha256=153ea36d1d987a62942382b61075745042a2b3123b1cd48f4c3675af9cc7d6f1
@@ -81,12 +74,10 @@ CHECKSUMS
81
74
  rake (13.4.2) sha256=cb825b2bd5f1f8e91ca37bddb4b9aaf345551b4731da62949be002fa89283701
82
75
  reline (0.6.3) sha256=1198b04973565b36ec0f11542ab3f5cfeeec34823f4e54cebde90968092b1835
83
76
  ruby2_keywords (0.0.5) sha256=ffd13740c573b7301cf7a2e61fc857b2a8e3d3aff32545d6f8300d8bae10e3ef
84
- simplecov (0.22.0) sha256=fe2622c7834ff23b98066bb0a854284b2729a569ac659f82621fc22ef36213a5
85
- simplecov-html (0.13.2) sha256=bd0b8e54e7c2d7685927e8d6286466359b6f16b18cb0df47b508e8d73c777246
86
- simplecov_json_formatter (0.1.4) sha256=529418fbe8de1713ac2b2d612aa3daa56d316975d307244399fa4838c601b428
77
+ simplecov (1.1.1) sha256=25825ef13f0b2e74694d769817dad6ab8e90131dabdaa666e522fea105521e78
87
78
  warning (1.6.0) sha256=a49cdfae19fb77d19afff2efbe45f8ab759e9cd25b4e4ce2c79dbaf46bdb6c9e
88
- waterdrop (2.10.2)
89
- zeitwerk (2.8.2) sha256=7212a61311083c604184b1ea2574b9aa05cd14f855a0841c06985cabe9181d12
79
+ waterdrop (2.10.4)
80
+ zeitwerk (2.8.3) sha256=2c85125a8467ce069e20123d1e709a08955c9d29c118c25b46b7b7fafdbb92e5
90
81
 
91
82
  BUNDLED WITH
92
83
  4.0.6
@@ -7,6 +7,18 @@ allowed_patterns=(
7
7
  "Performing controller activation"
8
8
  "registered with feature metadata.version"
9
9
  "TOPIC_ALREADY_EXISTS"
10
+ # The transactional_abort_after_commit_race and transactional_abort_race_canary integration specs
11
+ # deliberately reproduce librdkafka#4849: they abort with the first produce still in flight, so
12
+ # the abort's EndTxn can reach the coordinator before AddPartitionsToTxn registers the new
13
+ # transaction. The coordinator then still holds the *previous* transaction's COMPLETE_COMMIT state
14
+ # and rejects the ABORT marker, logging this warning. It is the broker-side signature of the very
15
+ # defect those specs exist to reproduce, so it is expected there - and scoped to their
16
+ # transactional ids so we still catch the same warning anywhere else.
17
+ #
18
+ # One entry per spec rather than an alternation: `\|` is a GNU extension to POSIX BRE, so on BSD
19
+ # grep (macOS) it would match nothing and the allowance would silently do nothing at all.
20
+ "tx-abort-race-id.*received transaction marker result to send: ABORT"
21
+ "tx-abort-canary-id.*received transaction marker result to send: ABORT"
10
22
  )
11
23
 
12
24
  # Get all warnings
@@ -18,7 +18,7 @@ services:
18
18
  start_period: 90s
19
19
 
20
20
  kafka-oauth:
21
- image: confluentinc/cp-kafka:8.2.1
21
+ image: confluentinc/cp-kafka:8.3.0
22
22
  container_name: kafka-oauth
23
23
  depends_on:
24
24
  keycloak:
@@ -1,6 +1,6 @@
1
1
  services:
2
2
  kafka-sasl:
3
- image: confluentinc/cp-kafka:8.2.1
3
+ image: confluentinc/cp-kafka:8.3.0
4
4
  container_name: kafka-sasl
5
5
  ports:
6
6
  - "9095:9095"
data/docker-compose.yml CHANGED
@@ -1,7 +1,7 @@
1
1
  services:
2
2
  kafka:
3
3
  container_name: kafka
4
- image: confluentinc/cp-kafka:8.2.1
4
+ image: confluentinc/cp-kafka:8.3.0
5
5
 
6
6
  ports:
7
7
  - 9092:9092
@@ -80,8 +80,7 @@ module WaterDrop
80
80
  @topics[topic]
81
81
  end
82
82
 
83
- # Clears internal buffer
84
- # Used in between specs so messages do not leak out
83
+ # Clears internal buffer. Used in between specs so messages do not leak out
85
84
  def reset
86
85
  @transaction_level = 0
87
86
  @transaction_active = false
@@ -51,7 +51,7 @@ module WaterDrop
51
51
  # saves a significant number of allocations on the Ruby side (no JSON parsing, no
52
52
  # statistics hash materialization, no decorator work). Any listener subscribed after
53
53
  # the client has been built will not receive `statistics.emitted` events because
54
- # librdkafka never emits them in the first place to use statistics, subscribe a
54
+ # librdkafka never emits them in the first place - to use statistics, subscribe a
55
55
  # listener BEFORE the first producer use.
56
56
  #
57
57
  # When statistics end up disabled (either because the user explicitly set the interval
@@ -94,7 +94,7 @@ module WaterDrop
94
94
 
95
95
  # Registers the global callbacks (statistics, error, oauth refresh) for this producer
96
96
  # on the shared `Karafka::Core::Instrumentation` managers. The statistics callback is
97
- # only registered when librdkafka is actually going to emit statistics otherwise it
97
+ # only registered when librdkafka is actually going to emit statistics - otherwise it
98
98
  # would never fire and would only waste memory and a manager slot.
99
99
  #
100
100
  # @param producer [WaterDrop::Producer]
@@ -36,7 +36,7 @@ module WaterDrop
36
36
  constructor: ->(id) { id || "waterdrop-#{SecureRandom.hex(6)}" }
37
37
  )
38
38
  # option [Instance] logger that we want to use
39
- # @note Due to how rdkafka works, this setting is global for all the producers
39
+ # Due to how rdkafka works, this setting is global for all the producers
40
40
  setting(
41
41
  :logger,
42
42
  default: false,
@@ -95,6 +95,35 @@ module WaterDrop
95
95
  # option [Integer] How many times to attempt reloading on transactional fatal error before
96
96
  # giving up. This prevents infinite reload loops if the producer never recovers.
97
97
  setting :max_attempts_on_transaction_fatal_error, default: 10
98
+ # option [Numeric] How long to wait **at most** (in ms) for the first delivery of a transaction
99
+ # to be acknowledged before we abort that transaction. `0` (the default) disables the wait.
100
+ #
101
+ # This is a ceiling, not a fixed delay: the wait ends as soon as the delivery is acknowledged,
102
+ # which under normal conditions is immediate. The full timeout is only ever spent when the
103
+ # delivery never arrives at all.
104
+ #
105
+ # This is an opt-in mitigation for a librdkafka defect. librdkafka only flags a transaction as
106
+ # ongoing at the coordinator once the `AddPartitionsToTxn` **response** arrives, but it sends
107
+ # `EndTxn` as soon as that request has merely been **sent**. Aborting with the first produce
108
+ # still in flight can therefore hit a coordinator that does not consider the transaction
109
+ # started yet, failing the abort with a fatal `INVALID_TXN_STATE`.
110
+ # See https://github.com/confluentinc/librdkafka/issues/4849
111
+ #
112
+ # A single acknowledged delivery proves its partition completed registration, and that alone
113
+ # makes the coordinator accept `EndTxn` - no matter how many partitions the transaction spans.
114
+ # So waiting for one delivery before aborting closes the race.
115
+ #
116
+ # It is off by default because it changes abort semantics: waiting for that ack means the
117
+ # first message is actually **delivered** (aborted, so invisible to `read_committed`
118
+ # consumers) instead of being **purged**. Its delivery handle then reports a real offset
119
+ # rather than a `Purged in queue` error, and no `message.purged` event is emitted for it,
120
+ # while the remaining messages of the same transaction are still purged. Enable this only if
121
+ # you hit the defect and prefer that trade over the fatal (which stays recoverable through
122
+ # `reload_on_transaction_fatal_error` either way).
123
+ #
124
+ # The wait is bounded and best-effort: if it expires (broker down, message timeout) we abort
125
+ # exactly as if it were disabled.
126
+ setting :wait_timeout_on_transaction_abort, default: 0
98
127
  # option [Array<Symbol>] List of fatal error codes that should NOT trigger producer reload.
99
128
  # These errors represent states that cannot be recovered by simply recreating the client.
100
129
  #
@@ -140,7 +169,7 @@ module WaterDrop
140
169
  # option [Class] class for usage when creating the underlying client used to dispatch messages
141
170
  setting :client_class, default: Clients::Rdkafka
142
171
  # rdkafka options
143
- # @see https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md
172
+ # See https://github.com/edenhill/librdkafka/blob/master/CONFIGURATION.md
144
173
  setting :kafka, default: {}
145
174
  # Middleware chain that can be expanded with useful middleware steps
146
175
  setting(
@@ -1,6 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- # WaterDrop library
4
3
  module WaterDrop
5
4
  # Connection pool wrapper for WaterDrop producers using the proven connection_pool gem.
6
5
  #
@@ -119,15 +118,11 @@ module WaterDrop
119
118
  def shutdown(force: false)
120
119
  return unless @default_pool
121
120
 
122
- pool = @default_pool
121
+ # The instrumentation event is emitted by the instance-level #shutdown we delegate to
122
+ # (with `pool: self`, i.e. this same global pool). We deliberately do not emit it again
123
+ # here - doing so fired `connection_pool.shutdown` twice for a single global shutdown.
123
124
  @default_pool.shutdown(force: force)
124
125
  @default_pool = nil
125
-
126
- # Emit global event for pool shutdown
127
- WaterDrop.instrumentation.instrument(
128
- "connection_pool.shutdown",
129
- pool: pool
130
- )
131
126
  end
132
127
 
133
128
  # Alias for shutdown to align with producer API
@@ -30,6 +30,7 @@ module WaterDrop
30
30
  required(:max_attempts_on_idempotent_fatal_error) { |val| val.is_a?(Integer) && val >= 1 }
31
31
  required(:wait_backoff_on_transaction_fatal_error) { |val| val.is_a?(Numeric) && val >= 0 }
32
32
  required(:max_attempts_on_transaction_fatal_error) { |val| val.is_a?(Integer) && val >= 1 }
33
+ required(:wait_timeout_on_transaction_abort) { |val| val.is_a?(Numeric) && val >= 0 }
33
34
  required(:non_reloadable_errors) do |val|
34
35
  val.is_a?(Array) && val.all?(Symbol)
35
36
  end
@@ -2,9 +2,8 @@
2
2
 
3
3
  module WaterDrop
4
4
  module Instrumentation
5
- # WaterDrop instrumentation monitor that we use to publish events
6
- # By default uses our internal notifications bus but can be used with
7
- # `ActiveSupport::Notifications` as well
5
+ # WaterDrop instrumentation monitor that we use to publish events. By default uses our internal
6
+ # notifications bus but can be used with `ActiveSupport::Notifications` as well
8
7
  class Monitor < ::Karafka::Core::Monitoring::Monitor
9
8
  # Event name for librdkafka statistics emissions
10
9
  STATISTICS_EVENT = "statistics.emitted"
@@ -29,8 +28,8 @@ module WaterDrop
29
28
  # Marks this monitor as no longer accepting new subscriptions to `statistics.emitted`.
30
29
  # Called by the rdkafka client builder when it decides to leave librdkafka statistics
31
30
  # disabled (because no listener was present at build time). Any subsequent attempt to
32
- # subscribe to `statistics.emitted` either via a block or via a listener object that
33
- # responds to `on_statistics_emitted` will raise
31
+ # subscribe to `statistics.emitted` - either via a block or via a listener object that
32
+ # responds to `on_statistics_emitted` - will raise
34
33
  # `WaterDrop::Errors::StatisticsNotEnabledError` instead of silently doing nothing.
35
34
  def freeze_statistics_listeners!
36
35
  @statistics_listeners_frozen = true
@@ -1,8 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- # WaterDrop main module
4
3
  module WaterDrop
5
- # Namespace for FD-based polling components
6
4
  module Polling
7
5
  # Configuration for the global FD poller singleton
8
6
  # These settings apply to all producers using FD polling mode
@@ -1,8 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module WaterDrop
4
- # Namespace for FD-based polling components
5
- # Contains the global Poller singleton and State class for managing producer polling
6
4
  module Polling
7
5
  # Global poller singleton that manages a single polling thread for all FD-mode producers
8
6
  # This replaces librdkafka's native background polling threads with a single Ruby thread
@@ -272,7 +270,8 @@ module WaterDrop
272
270
 
273
271
  # Collects all IOs to monitor and builds a mapping from IO to State
274
272
  # Uses cached arrays when possible to avoid allocations in the hot path
275
- # @return [Array<Array<IO>, Hash{IO => State}, Array<State>>] tuple of ios, io-to-state map, states
273
+ # @return [Array<Array<IO>, Hash{IO => State}, Array<State>>] tuple of ios, io-to-state map,
274
+ # states
276
275
  def collect_readable_ios
277
276
  # Fast path: return cached result if not dirty (no mutex needed)
278
277
  # Safe because @cached_result is frozen and assigned atomically
@@ -345,9 +344,8 @@ module WaterDrop
345
344
  end
346
345
  end
347
346
 
348
- # Polls all registered producers
349
- # Called when IO.select times out to ensure periodic polling happens
350
- # This ensures OAuth token refresh and statistics callbacks fire for all producers
347
+ # Polls all registered producers. Called when IO.select times out to ensure periodic polling
348
+ # happens. This ensures OAuth token refresh and statistics callbacks fire for all producers
351
349
  def poll_all_producers
352
350
  @cached_states.each { |state| poll_producer(state) }
353
351
  end
@@ -26,7 +26,8 @@ module WaterDrop
26
26
  # @param client [Rdkafka::Producer] the rdkafka producer client
27
27
  # @param monitor [Object] the producer's monitor for error reporting
28
28
  # @param max_poll_time [Integer] max time in ms to poll per cycle
29
- # @param periodic_poll_interval [Integer] max time in ms before this producer needs periodic poll
29
+ # @param periodic_poll_interval [Integer] max time in ms before this producer needs periodic
30
+ # poll
30
31
  # @raise [StandardError] if queue pipe setup fails (FD mode requires this to work)
31
32
  def initialize(producer_id, client, monitor, max_poll_time, periodic_poll_interval)
32
33
  @producer_id = producer_id
@@ -106,9 +107,8 @@ module WaterDrop
106
107
  @last_stale_result = (now - @last_poll_time) >= @periodic_poll_interval
107
108
  end
108
109
 
109
- # Signals the poller to remove this producer
110
- # Called from any thread when the producer is being closed
111
- # Sets closing flag BEFORE signaling to ensure poller sees it
110
+ # Signals the poller to remove this producer. Called from any thread when the producer is
111
+ # being closed. Sets closing flag BEFORE signaling to ensure poller sees it
112
112
  def signal_close
113
113
  @closing = true
114
114
  @queue_pipe.signal
@@ -133,9 +133,8 @@ module WaterDrop
133
133
  @close_latch.release!
134
134
  end
135
135
 
136
- # Waits for this state to be closed
137
- # Used by unregister to ensure synchronous cleanup before returning
138
- # This matches the threaded polling behavior which drains without timeout
136
+ # Waits for this state to be closed. Used by unregister to ensure synchronous cleanup before
137
+ # returning. This matches the threaded polling behavior which drains without timeout
139
138
  def wait_for_close
140
139
  @close_latch.wait
141
140
  end
@@ -1,6 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- # WaterDrop main module
4
3
  module WaterDrop
5
4
  # Namespace for FD-based polling components
6
5
  # Contains the global Poller singleton and State class for managing producer polling
@@ -16,7 +16,7 @@ module WaterDrop
16
16
  # Produces a tombstone message to Kafka and waits for it to be delivered
17
17
  #
18
18
  # @param message [Hash] hash with at least `:topic`, `:key`, and `:partition` keys.
19
- # `:payload` is not accepted it will be silently removed if present.
19
+ # `:payload` is not accepted - it will be silently removed if present.
20
20
  #
21
21
  # @return [Rdkafka::Producer::DeliveryReport] delivery report
22
22
  #
@@ -28,7 +28,7 @@ module WaterDrop
28
28
  # Produces a tombstone message to Kafka and does not wait for results
29
29
  #
30
30
  # @param message [Hash] hash with at least `:topic`, `:key`, and `:partition` keys.
31
- # `:payload` is not accepted it will be silently removed if present.
31
+ # `:payload` is not accepted - it will be silently removed if present.
32
32
  #
33
33
  # @return [Rdkafka::Producer::DeliveryHandle] delivery handle
34
34
  #
@@ -106,9 +106,11 @@ module WaterDrop
106
106
  # This is why we catch this here
107
107
  begin
108
108
  with_transactional_error_handling(:abort) do
109
- transactional_instrument(:aborted) do
110
- client.abort_transaction
111
- end
109
+ # Outside of the `aborted` instrumentation on purpose: that event is supposed to
110
+ # measure `client.abort_transaction`, not our wait
111
+ transactional_await_first_delivery(e)
112
+
113
+ transactional_instrument(:aborted) { client.abort_transaction }
112
114
  end
113
115
  rescue => e
114
116
  # If something from rdkafka leaks here, it means there was a non-retryable error that
@@ -121,6 +123,13 @@ module WaterDrop
121
123
  transactional_reload_client_if_needed(e)
122
124
 
123
125
  raise unless e.is_a?(WaterDrop::Errors::AbortTransaction)
126
+ ensure
127
+ # The first delivery handle is scoped to the transaction that produced it and is only
128
+ # ever read by the abort path (which runs in the rescue above, before this). Clearing it
129
+ # here - on commit, on abort and on a re-raise alike - keeps it from outliving its
130
+ # transaction: otherwise a committed transaction would leave its handle (and everything
131
+ # the delivery report references) pinned to the producer until the next one begins.
132
+ @transaction_first_handle = nil
124
133
  end
125
134
  end
126
135
  end
@@ -255,6 +264,12 @@ module WaterDrop
255
264
  if e.abortable? && allow_abortable
256
265
  # Always attempt to abort but if aborting fails with an abortable error, do not attempt
257
266
  # to abort from abort as this could create an infinite loop
267
+ #
268
+ # We deliberately do NOT wait for the first delivery here (unlike the abort in
269
+ # `#transaction`): we only get here because librdkafka reported an abortable error, so the
270
+ # transaction is already in an error state where it no longer delivers. The queued messages
271
+ # are purged by the abort itself, so the handle would never resolve and we would just stall
272
+ # for the whole `wait_timeout_on_transaction_abort` on a path that is already recovering.
258
273
  with_transactional_error_handling(:abort, allow_abortable: false) do
259
274
  transactional_instrument(:aborted) { client.abort_transaction }
260
275
  end
@@ -263,6 +278,61 @@ module WaterDrop
263
278
  raise
264
279
  end
265
280
 
281
+ # Waits (bounded) for the first delivery of the current transaction before we abort it.
282
+ #
283
+ # librdkafka only marks a transaction as ongoing at the coordinator once the
284
+ # `AddPartitionsToTxn` **response** comes back, but it fires `EndTxn` as soon as that request
285
+ # has merely been **sent** (it gates on `txn_req_cnt`, bumped on send). Aborting with the
286
+ # first produce still in flight can therefore reach a coordinator that does not yet consider
287
+ # the transaction started, which fails the abort with a fatal `INVALID_TXN_STATE`. See
288
+ # https://github.com/confluentinc/librdkafka/issues/4849
289
+ #
290
+ # A delivered message proves its partition completed registration, and that alone puts the
291
+ # transaction in an `ongoing` state at the coordinator - so a single acknowledged delivery is
292
+ # enough to make `EndTxn` valid, regardless of how many partitions the transaction spans.
293
+ #
294
+ # This is best-effort and never fatal: if the delivery does not materialize within the timeout
295
+ # (broker down, message timeout, purge) we abort exactly as before rather than hanging. The
296
+ # fatal, should it still happen, remains recoverable through the client reload.
297
+ #
298
+ # @param error [Exception] the error that is causing us to abort this transaction
299
+ def transactional_await_first_delivery(error)
300
+ handle = @transaction_first_handle
301
+ timeout = config.wait_timeout_on_transaction_abort
302
+
303
+ return if handle.nil?
304
+ return if timeout.zero?
305
+ # Only worth waiting when the transaction is still healthy, that is when we abort because the
306
+ # user asked us to (`AbortTransaction`) or because their own code raised. Once librdkafka
307
+ # itself reported an error, the transaction no longer delivers: the queued messages are
308
+ # purged by the abort, so this handle would never resolve and we would stall for the full
309
+ # timeout on a path that is already recovering from an error.
310
+ return if transactional_error?(error)
311
+
312
+ # An already delivered handle (the common case - any sync dispatch, or a transaction that did
313
+ # some work before aborting) short-circuits inside `#wait` itself, so there is nothing to
314
+ # guard against here: it returns immediately without blocking.
315
+ wait(handle, max_wait_timeout: timeout, raise_response_error: false)
316
+ rescue ::Rdkafka::AbstractHandle::WaitTimeoutError, ::Rdkafka::RdkafkaError
317
+ # These two mean the same thing for us: we could not confirm the registration, either because
318
+ # the delivery did not arrive in time or because it failed outright. Aborting is still the
319
+ # right move, we just lose the mitigation for this one transaction.
320
+ #
321
+ # Deliberately narrow. A broader rescue would also swallow bugs of our own making (a
322
+ # `NoMethodError` on a handle we mis-tracked, say) and turn them into a silently skipped
323
+ # mitigation that nobody would ever notice.
324
+ nil
325
+ end
326
+
327
+ # @param error [Exception] error that caused the abort
328
+ # @return [Boolean] did this error come from librdkafka, meaning the transaction is already in
329
+ # an error state and will not deliver anything anymore
330
+ def transactional_error?(error)
331
+ return true if error.is_a?(::Rdkafka::RdkafkaError)
332
+
333
+ error.cause.is_a?(::Rdkafka::RdkafkaError)
334
+ end
335
+
266
336
  # Reloads the underlying client instance if needed and allowed
267
337
  #
268
338
  # This should be used only in transactions as only then we can get fatal transactional
@@ -122,7 +122,7 @@ module WaterDrop
122
122
  topic_config: topic_config,
123
123
  # We pass this to validation, to make sure no-one alters the `acks` value when operating
124
124
  # in the transactional mode as it causes librdkafka to crash ruby
125
- # @see https://github.com/confluentinc/librdkafka/issues/4710
125
+ # See https://github.com/confluentinc/librdkafka/issues/4710
126
126
  transactional: @producer.transactional?,
127
127
  # We pass this for a similar reason as above
128
128
  idempotent: @producer.idempotent?
@@ -67,6 +67,7 @@ module WaterDrop
67
67
  @poller = nil
68
68
  @idempotent_fatal_error_attempts = 0
69
69
  @transaction_fatal_error_attempts = 0
70
+ @transaction_first_handle = nil
70
71
 
71
72
  @status = Status.new
72
73
  @messages = []
@@ -92,7 +93,9 @@ module WaterDrop
92
93
  .setup(...)
93
94
  .config
94
95
 
95
- @id = @config.id
96
+ # dup so a frozen id (e.g. a frozen string literal) isn't used as the finalizer target, since
97
+ # ObjectSpace.(un)define_finalizer mutates the object and would raise FrozenError on #close
98
+ @id = @config.id.to_s.dup
96
99
  @monitor = @config.monitor
97
100
  @contract = Contracts::Message.new(max_payload_size: @config.max_payload_size)
98
101
  @default_variant = Variant.new(self, default: true)
@@ -589,12 +592,13 @@ module WaterDrop
589
592
  #
590
593
  # For a transactional producer we wrap the whole dispatch (including the operations-counter
591
594
  # bookkeeping) in `transaction`, so `@transaction_mutex` is acquired BEFORE
592
- # `@operations_in_progress` is incremented. This makes `#produce` acquire locks in the same order
593
- # as `#close` (`@transaction_mutex` -> `@operating_mutex` -> operations counter) and removes a
594
- # lock-order inversion: without it, a dispatch that had already counted itself could block forever
595
- # on `@transaction_mutex` held by a concurrent `#close` that was itself waiting for the operations
596
- # counter to drain. When we already own the transaction lock (inside an explicit transaction block
597
- # or the closing flush) the order is already correct, so we dispatch directly.
595
+ # `@operations_in_progress` is incremented. This makes `#produce` acquire locks in the same
596
+ # order as `#close` (`@transaction_mutex` -> `@operating_mutex` -> operations counter) and
597
+ # removes a lock-order inversion: without it, a dispatch that had already counted itself could
598
+ # block forever on `@transaction_mutex` held by a concurrent `#close` that was itself waiting
599
+ # for the operations counter to drain. When we already own the transaction lock (inside an
600
+ # explicit transaction block or the closing flush) the order is already correct, so we dispatch
601
+ # directly.
598
602
  #
599
603
  # @param message [Hash] message we want to send
600
604
  # @param label [String] short name of the public dispatch method (e.g. `"produce_sync"`) that
@@ -647,10 +651,39 @@ module WaterDrop
647
651
  client.produce(**message)
648
652
  end
649
653
 
654
+ # Remember the first delivery handle of the current transaction. Aborting while the very first
655
+ # produce is still in flight is what triggers librdkafka#4849, so the abort path waits on this
656
+ # handle to confirm the transaction is registered at the coordinator. See
657
+ # `#transactional_await_first_delivery`.
658
+ @transaction_first_handle ||= result if transactional? && @transaction_mutex.owned?
659
+
650
660
  # Reset attempts counter on successful produce
651
661
  @idempotent_fatal_error_attempts = 0
652
662
 
653
663
  result
664
+ rescue Rdkafka::ClosedProducerError, Rdkafka::ClosedInnerError
665
+ # A concurrent idempotent fatal-error reload closed the underlying client while this produce
666
+ # was already in flight. Unlike `#close`/`#disconnect`, which drain `@operations_in_progress`
667
+ # before closing the client, the idempotent reload swaps `@client` out from under sibling
668
+ # threads that have already passed the `@operating_mutex` gate and are inside `client.produce`.
669
+ # Racing with `@client.close`, such a thread sees either a producer already flagged closed
670
+ # (`ClosedProducerError`) or a nil inner librdkafka handle (`ClosedInnerError`) - which one
671
+ # depends purely on how far `close` has progressed.
672
+ #
673
+ # This is a benign, recoverable transient rather than a produce failure: the client has just
674
+ # been (or is being) rebuilt, so we retry the dispatch against the fresh client instead of
675
+ # surfacing a raw "closed producer" error to the caller - which would defeat the whole point
676
+ # of the transparent reload. Only the idempotent reload path closes the client with produces
677
+ # in flight, so we scope the retry to that configuration; anywhere else a closed client is a
678
+ # genuine error and must propagate. The retried pass re-runs `ensure_active!`, which raises
679
+ # `ProducerClosedError` once the producer is genuinely closing/closed, so this cannot spin
680
+ # forever.
681
+ raise unless config.reload_on_idempotent_fatal_error
682
+ raise if transactional?
683
+
684
+ @operations_in_progress.decrement
685
+
686
+ retry
654
687
  rescue SUPPORTED_FLOW_ERRORS.first => e
655
688
  # Check if this is a fatal error on an idempotent producer and we should reload.
656
689
  #
@@ -1,7 +1,6 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- # WaterDrop library
4
3
  module WaterDrop
5
4
  # Current WaterDrop version
6
- VERSION = "2.10.2"
5
+ VERSION = "2.10.4"
7
6
  end
data/lib/waterdrop.rb CHANGED
@@ -10,7 +10,6 @@ require "singleton"
10
10
  require "karafka-core"
11
11
  require "pathname"
12
12
 
13
- # WaterDrop library
14
13
  module WaterDrop
15
14
  class << self
16
15
  # @return [String] root path of this gem
data/package-lock.json CHANGED
@@ -286,9 +286,9 @@
286
286
  }
287
287
  },
288
288
  "node_modules/smol-toml": {
289
- "version": "1.6.1",
290
- "resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.6.1.tgz",
291
- "integrity": "sha512-dWUG8F5sIIARXih1DTaQAX4SsiTXhInKf1buxdY9DIg4ZYPZK5nGM1VRIYmEbDbsHt7USo99xSLFu5Q1IqTmsg==",
289
+ "version": "1.7.1",
290
+ "resolved": "https://registry.npmjs.org/smol-toml/-/smol-toml-1.7.1.tgz",
291
+ "integrity": "sha512-PPlsspAZ4jbMBu5DMFhfUGDQLu/vrL4SyBROVS37x8ynnVmFIs1VPBz1Co8Xks3TvpIaZXmU85y4DrQ+UyVFoQ==",
292
292
  "dev": true,
293
293
  "license": "BSD-3-Clause",
294
294
  "engines": {
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.2
4
+ version: 2.10.4
5
5
  platform: ruby
6
6
  authors:
7
7
  - Maciej Mensfeld
@@ -160,7 +160,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
160
160
  - !ruby/object:Gem::Version
161
161
  version: '0'
162
162
  requirements: []
163
- rubygems_version: 4.0.10
163
+ rubygems_version: 4.0.16
164
164
  specification_version: 4
165
165
  summary: Kafka messaging made easy!
166
166
  test_files: []