karafka-rdkafka 0.27.2 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +33 -0
  3. data/README.md +1 -0
  4. data/dist/{librdkafka-2.14.1.tar.gz → librdkafka-2.14.2.tar.gz} +0 -0
  5. data/docker-compose-ssl.yml +1 -1
  6. data/docker-compose.yml +1 -1
  7. data/karafka-rdkafka.gemspec +1 -0
  8. data/lib/rdkafka/abstract_handle.rb +37 -4
  9. data/lib/rdkafka/admin/config_binding_result.rb +1 -1
  10. data/lib/rdkafka/admin/create_acl_handle.rb +2 -8
  11. data/lib/rdkafka/admin/create_partitions_handle.rb +1 -20
  12. data/lib/rdkafka/admin/create_topic_handle.rb +1 -20
  13. data/lib/rdkafka/admin/delete_acl_handle.rb +2 -10
  14. data/lib/rdkafka/admin/delete_groups_handle.rb +3 -11
  15. data/lib/rdkafka/admin/delete_topic_handle.rb +1 -20
  16. data/lib/rdkafka/admin/describe_acl_handle.rb +2 -10
  17. data/lib/rdkafka/admin/describe_configs_handle.rb +2 -13
  18. data/lib/rdkafka/admin/describe_configs_report.rb +5 -6
  19. data/lib/rdkafka/admin/incremental_alter_configs_handle.rb +2 -13
  20. data/lib/rdkafka/admin/incremental_alter_configs_report.rb +5 -6
  21. data/lib/rdkafka/admin/list_offsets_handle.rb +2 -13
  22. data/lib/rdkafka/admin/list_offsets_report.rb +5 -2
  23. data/lib/rdkafka/admin.rb +56 -137
  24. data/lib/rdkafka/bindings.rb +12 -3
  25. data/lib/rdkafka/callbacks/base_handler.rb +62 -0
  26. data/lib/rdkafka/callbacks/create_acl_handler.rb +37 -0
  27. data/lib/rdkafka/callbacks/create_partitions_handler.rb +37 -0
  28. data/lib/rdkafka/callbacks/create_topic_handler.rb +37 -0
  29. data/lib/rdkafka/callbacks/delete_acl_handler.rb +42 -0
  30. data/lib/rdkafka/callbacks/delete_groups_handler.rb +37 -0
  31. data/lib/rdkafka/callbacks/delete_topic_handler.rb +37 -0
  32. data/lib/rdkafka/callbacks/describe_acl_handler.rb +35 -0
  33. data/lib/rdkafka/callbacks/describe_configs_handler.rb +42 -0
  34. data/lib/rdkafka/callbacks/incremental_alter_configs_handler.rb +42 -0
  35. data/lib/rdkafka/callbacks/list_offsets_handler.rb +42 -0
  36. data/lib/rdkafka/callbacks.rb +56 -244
  37. data/lib/rdkafka/config.rb +50 -33
  38. data/lib/rdkafka/consumer/headers.rb +19 -5
  39. data/lib/rdkafka/consumer/topic_partition_list.rb +43 -33
  40. data/lib/rdkafka/consumer.rb +164 -23
  41. data/lib/rdkafka/defaults.rb +21 -1
  42. data/lib/rdkafka/error.rb +12 -4
  43. data/lib/rdkafka/helpers/list_offsets.rb +127 -0
  44. data/lib/rdkafka/helpers/metadata.rb +29 -0
  45. data/lib/rdkafka/metadata.rb +84 -19
  46. data/lib/rdkafka/producer/delivery_handle.rb +3 -3
  47. data/lib/rdkafka/producer/partitions_count_cache.rb +24 -38
  48. data/lib/rdkafka/producer.rb +72 -51
  49. data/lib/rdkafka/version.rb +3 -3
  50. data/lib/rdkafka.rb +13 -0
  51. data/package-lock.json +6 -6
  52. data/renovate.json +11 -1
  53. metadata +15 -5
  54. data/Gemfile +0 -13
  55. data/Gemfile.lint +0 -14
  56. data/Gemfile.lint.lock +0 -123
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 28b25d5553da8103cf3ba2840c57d954bc36a957004a01e31a7a4ace76b82382
4
- data.tar.gz: ee834fb05a4afa6ac3bb31d2dcf8735779f6bcd9c7e4b910d95e22ecae74b3fc
3
+ metadata.gz: 04f165f0ef5a6a2a91906f9bfd8ea143acf5197f7e13b4d1d4d1625bce4e792c
4
+ data.tar.gz: 6c03af6f233ed78de1e2d02482170cf4e2d50d98f54399dd555ce08c49bfacc8
5
5
  SHA512:
6
- metadata.gz: d4fe487cab97e1cf1ea5c275a682feee20247d1e20517d257c1a03383d5fb9bcb926404626123e3d0c7e05d9832fa7675c37b0b5f6b0ff484c277324a432c66f
7
- data.tar.gz: 223c61df2cb43ad07df271caf29c535e8daa13f49602a21cfea5ef8ddb030e6378f23fe698f15025a673083fd486b749c04f3078edb6f69d14fa0339cd55658f
6
+ metadata.gz: 622a269eaa8f11e02988ca1de4c26a07fe062d708c5c4a357c19a07486edd34b67c7c1b1e35962ed60125ec08ccc4a10692b9d46e0dc997c199d33e1b20d3195
7
+ data.tar.gz: c668fb57232d3dc6d53e0065db03470ed4a81d3d4820097d018bc5a71991e042e66d12b2051138d1c85955acb3b985f986a7477a610cc94ebdde5fbf4ac7ef2e
data/CHANGELOG.md CHANGED
@@ -1,5 +1,38 @@
1
1
  # Rdkafka Changelog
2
2
 
3
+ ## v0.28.0
4
+ - [Enhancement] Bump librdkafka to `2.14.2`. Maintenance release: fixes duplicate groups in `ListConsumerGroups` when multiple brokers return the same group, a data race in timers, and bumps bundled OpenSSL/libcurl/zstd/zlib/cJSON dependencies (several CVEs).
5
+ - [Enhancement] Add `Consumer#metadata` and `Producer#metadata`, mirroring `Admin#metadata`, so cluster/topic metadata can be fetched from an existing consumer or producer handle without opening a dedicated admin connection.
6
+ - [Enhancement] Name the failing partition and topic in the `RdkafkaError` raised for per-partition `list_offsets` errors (previously a bare error code), preserving the per-partition context the pre-batching `Consumer#lag` watermark errors carried.
7
+ - [Enhancement] Add `Consumer#list_offsets`, mirroring `Admin#list_offsets`, so batched offset queries (one `ListOffsets` request carrying all requested partitions, fanned out to the partition leaders by librdkafka) can be issued on an existing consumer handle without opening a dedicated admin connection, and rebuild `Consumer#lag` on top of it: lag is now computed from a single batched end-offsets query instead of one blocking `query_watermark_offsets` broker roundtrip per partition. To receive the results, consumer clients now register the librdkafka background event callback, so librdkafka spawns its internally-managed background thread for consumers as well. `Consumer#lag` keeps its exact pre-batching semantics: it forwards the consumer's configured `isolation.level` to the batched query (librdkafka resolves the per-partition watermark query with that level, so end offsets stay LSO-based for the default `read_committed`), surfaces a timeout of the batched query as an `RdkafkaError` (`timed_out`), and now also raises `ClosedConsumerError` when called on a closed consumer.
8
+ - [Enhancement] Extract the admin background-event result handlers into one class per operation under `lib/rdkafka/callbacks/` (`CreateTopicHandler`, `DescribeConfigsHandler`, etc., all subclasses of `Callbacks::BaseHandler`). `Callbacks::BackgroundEventCallback` is now a thin dispatcher that maps the event type to its handler and destroys the event. Purely internal reorganization (`Rdkafka::Callbacks` is private) with no behavior or API change.
9
+ - [Enhancement] Expose `replicas` and `isrs` (in-sync replica broker ids) on each partition in topic metadata (`Metadata#topics` partition hashes). The base struct `#to_h` skips FFI pointer members, so these two arrays were dropped entirely and the partition replica assignment was unavailable to callers (e.g. for planning replication-factor changes). `PartitionMetadata#to_h` now dereferences both pointers into arrays of broker ids.
10
+ - [Enhancement] Reuse per-thread scratch pointers in `Consumer::Headers.from_native` instead of allocating them for every consumed message. Previously each message paid one native pointer allocation just to check for headers and three more when headers were present; now the scratch pointers are allocated once per thread/fiber and reused, removing all per-message native scratch allocations from the consumer hot path.
11
+ - [Enhancement] Remove the unused `DeliveryHandle` `:topic_name` struct field and the per-message allocation that populated it. The delivery callback copied the topic name into a native `FFI::MemoryPointer` on every delivered message, retained for the lifetime of the handle, yet nothing ever read it: the topic is already available via `DeliveryHandle#topic` (a Ruby attribute set during `produce`) and `DeliveryReport#topic_name`, both of which work exactly as before.
12
+ - [Fix] Stop `poll_batch`/`poll_batch_nb` from discarding a whole batch when one message fails to build. If building a `Consumer::Message` raised (e.g. a header-read `RdkafkaError`), the exception propagated out of the batch loop and the `ensure` destroyed every remaining message, so all the messages already built in that batch were lost even though their offsets had been stored - permanent silent loss of up to `max_items` messages. A per-message build error is now surfaced inline as an `RdkafkaError` in the returned array (the same way native error events already are), so the rest of the batch is preserved and the failure is visible to the caller. (Single-message `poll`/`poll_nb` still raise as before.)
13
+ - [Fix] Add the missing `closed_consumer_check` to `Consumer#position`. Every sibling offset method guards against a closed consumer, but `position` did not: with an explicit `list` it raised `ClosedInnerError` instead of `ClosedConsumerError`, and with no `list` it raised `ClosedConsumerError` naming `assignment` rather than `position`. It now raises a consistent `ClosedConsumerError` for `position`.
14
+ - [Fix] Stop leaking the native `rd_kafka_topic_conf_t` in `Producer#set_topic_config` when a per-topic config value is rejected. The conf is built with `rd_kafka_topic_conf_new` and only handed to `rd_kafka_topic_new` afterwards; if `rd_kafka_topic_conf_set` returned a non-`:config_ok` result the method raised before `rd_kafka_topic_new` was ever called, so librdkafka never took ownership of the conf and it leaked (repeatable per produce with an invalid `topic_config:`). The conf is now destroyed before raising. The `rd_kafka_topic_new` path is unchanged: librdkafka frees the conf there on both success and failure, so it is never destroyed by us.
15
+ - [Fix] Raise instead of silently dropping a rejected `incremental_alter_configs` entry. `rd_kafka_ConfigResource_add_incremental_config` returns an `rd_kafka_error_t` for an invalid op_type, an empty/nil name, or a nil value on a non-delete op; the result was ignored, so the entry was dropped, the alter request still reported success, and the error object leaked. The error is now surfaced as an `RdkafkaError` (raised before the request is sent) and the native error object is freed.
16
+ - [Fix] Let `PartitionsCountCache` adopt a lower partition count once the cached entry has expired. The cache prioritizes higher counts (partition counts only grow during normal operation), but it did so unconditionally: after the TTL expired it fetched the true lower count, discarded it, and re-armed the TTL on the stale higher count - permanently. A topic recreated with fewer partitions then made `produce` (with a partition key) fail with `unknown_partition` for the dropped partitions until process restart. A lower value is now adopted on the first refresh after expiry, while still being ignored within the TTL window so a transient or racy lower read cannot clobber a correct higher count.
17
+ - [Fix] Make the `Consumer` GC finalizer close the consumer and destroy its consumer queue, not just the native client. The finalizer used the generic `NativeKafka` one, which went straight to `rd_kafka_destroy` and skipped `rd_kafka_consumer_close` and `rd_kafka_queue_destroy`. A consumer that used `poll_batch` (which takes a consumer-queue reference) and was then garbage-collected without an explicit `close` left that reference dangling, which could make `rd_kafka_destroy` block inside the finalizer (process hang at GC/shutdown) or leak the handle. The consumer now installs its own finalizer that mirrors `#close` (the queue pointer is shared with the finalizer via a holder so it never captures the consumer and prevents collection).
18
+ - [Fix] Stop admin operations from leaking when their arguments are rejected. `describe_configs` and `incremental_alter_configs` allocated the background queue and AdminOptions and registered their handle before parsing input, so a missing key raised a `KeyError` out of the building loop that orphaned the handle in the process-global registry forever (and leaked the queue, AdminOptions and any `ConfigResource`s already built); `list_offsets` likewise allocated its native topic-partition list before validating the offset specs. All three now parse and validate input up front, so a bad argument raises with nothing allocated.
19
+ - [Fix] Destroy the native topic-partition list in `TopicPartitionList#to_native_tpl` when population fails partway. The list is allocated with `rd_kafka_topic_partition_list_new` and only handed back (for the caller to destroy) on success; if building it raised - e.g. a non-string metadata value or an offset FFI cannot coerce to int64 - the half-built list leaked, since destruction is fully manual (the previous doc comment claiming GC handled it was wrong). It is now destroyed before the error propagates.
20
+ - [Fix] Allocate the admin result-count out-parameter as `:size_t` instead of `:int32`. Every librdkafka `rd_kafka_*_result_*(result, size_t *cntp)` accessor writes a full native `size_t` (8 bytes on 64-bit), but the count pointer was a 4-byte `FFI::MemoryPointer.new(:int32)` across the create/delete topic, create partitions, create/delete ACL, describe/incremental-alter configs and config-synonyms paths - a 4-byte heap overflow on every admin result parse (benign on little-endian, where the low word still reads the correct count, but undefined behavior). Now uses `:size_t`, matching the already-correct list-offsets and `get_err_descs` paths.
21
+ - [Fix] Destroy admin API background events after processing. librdkafka requires the application to destroy each background event, but `rd_kafka_event_destroy` was never called (nor even bound), so every admin operation leaked its entire result event with all result arrays and strings. Reports are now built inside the callback (copying event-owned memory into Ruby objects) before the event is destroyed, and `DescribeConfigsReport`/`IncrementalAlterConfigsReport` no longer destroy the event-owned ConfigResource array, which also fixes a double free on repeated `wait` calls on the same handle. As part of this, the internal FFI struct fields on admin operation handles (e.g. `handle[:error_string]`, `handle[:result_name]`, `handle[:config_entries]`, `handle[:response_string]`, `handle[:matching_acls]`) were removed; they were never part of the public API (use `handle.wait` and the returned report objects, whose interfaces are unchanged).
22
+ - [Fix] Resolve admin operation handles from the event error when an admin operation fails at the operation level (e.g. brokers unreachable, or the client closed with the request in flight). librdkafka delivers such failures as a result event with the error set and an empty results array, but the create topic, delete topic, create partitions, delete groups, create ACL and delete ACL handlers indexed `results[0]` unconditionally. That raised inside the background event callback, so the handle was never unlocked and `wait` blocked until its own timeout and raised `WaitTimeoutError`, discarding the real error. These handlers now check the event error first and resolve the handle with the actual error code (the describe configs, incremental alter configs, describe ACL and list offsets handlers already did).
23
+ - [Fix] Stop leaking the native `rd_kafka_conf_t` when client creation fails. `native_config` raised `ConfigError` mid-build (e.g. on an invalid option) without destroying the conf, and `native_kafka` raised `ClientCreationError` on a null `rd_kafka_new` without destroying it either. Both paths now call `rd_kafka_conf_destroy` before re-raising (librdkafka keeps app ownership of the conf on `rd_kafka_new` failure, so this is safe). Multi-KB leak per failed creation, relevant for supervisors retrying client creation on transient SASL/SSL misconfig.
24
+ - [Fix] Stop `Metadata` from leaking the native metadata struct (and a topic reference) on every retried fetch. `retry` restarts the `begin` block without running its `ensure`, so each retried attempt reassigned the pointers and only the last attempt's `rd_kafka_metadata` struct was ever destroyed; up to `METADATA_MAX_RETRIES` whole-cluster structs leaked per call (the `leader_not_available` case is routine during topic creation/leader election). Each attempt now frees its own native resources, and a failed fetch that never allocated a struct no longer calls `rd_kafka_metadata_destroy` on a NULL pointer.
25
+ - [Fix] Free the librdkafka-allocated string in `Consumer#cluster_id` and `Consumer#member_id` (previously copied via a `:string` binding but never freed) and fix the `rd_kafka_clusterid` arity to pass `timeout_ms`. `Consumer#cluster_id` now accepts a `timeout_ms` (default `Defaults::CONSUMER_CLUSTER_ID_TIMEOUT_MS`).
26
+ - [Fix] Guard the message delivery callback so a raising user `delivery_callback` can no longer skip the handle unlock or crash the producer. `DeliveryCallback` invoked the user callback and only then unlocked the handle, with no rescue; if the callback raised, the handle stayed pending (so `wait` blocked until its timeout and raised `WaitTimeoutError` for a message that was actually delivered) and the exception unwound out of the FFI callback on librdkafka's polling thread (`abort_on_exception = true`), taking down the whole process. The user callback is now wrapped so exceptions are logged and swallowed (matching the rebalance callback) and the handle is always unlocked in an `ensure`.
27
+ - [Fix] Stop `Producer#produce` from orphaning the delivery handle in the process-global registry when it fails after registering it. The handle was only removed on a non-zero `rd_kafka_producev` return, so any exception between registration and that check (a concurrent `close` making `with_inner` raise `ClosedInnerError`, or a header value whose `#to_s` raises) leaked the handle forever - it survives producer close and accumulates in apps that recreate/close producers. `produce` now removes the handle on any such failure before re-raising.
28
+ - [Fix] Attach `rd_kafka_query_watermark_offsets` with `blocking: true` so it releases the GVL during its broker round-trip. It was the only synchronous network call bound without the flag, so `Consumer#query_watermark_offsets` (and `Consumer#lag`, which calls it once per partition) froze every other Ruby thread in the process - including producer polling threads - for up to `timeout_ms`. Matches the neighboring `rd_kafka_offsets_for_times` binding.
29
+ - [Fix] Stabilize the flaky `Consumer#lag` "calculates the consumer lag" spec on overloaded CI. The manual `consumer.commit` could raise `no_offset` when the default 5s background auto-commit had already committed the stored offsets, or when the auto offset store had not yet caught up with `poll`. The spec now raises `auto.commit.interval.ms` to 60s (matching the existing `#seek`/pause specs) and lets the offset store settle before committing. Backported from rdkafka-ruby (#912).
30
+ - [Fix] Fix the NULL background-queue cleanup branches in `Admin#delete_group`, `Admin#delete_acl` and `Admin#describe_acl`, which referenced undefined local variables (`delete_topic_ptr`/`new_acl_ptr`). When `rd_kafka_queue_get_background` returned NULL, those branches raised a `NameError` instead of the intended `ConfigError` and leaked the already-allocated native request object (the `rd_kafka_DeleteGroup_t` / ACL binding filter), and `delete_group` additionally called the wrong destructor. They now destroy the correct object and raise `ConfigError`.
31
+ - [Fix] Forward `broker_message` and `instance_name` through `RdkafkaError.build`. On the `rd_kafka_error_t` pointer path `build` called `build_from_c` without passing either, so a caller-supplied broker message was discarded (falling back to `rd_kafka_err2str`) and the instance name was lost; the `Bindings::Message` path also dropped `instance_name`. Both are now forwarded, and `build_from_c` accepts `instance_name`.
32
+ - [Fix] Synchronize `AbstractHandle::REGISTRY` mutations. The handle registry is a plain Hash mutated from producing/consuming threads and the background polling thread (which removes handles from FFI callbacks). That is effectively safe on MRI under the GVL but not on JRuby, where a lost write could leave a handle unregistered (never unlocked, so `wait` times out for a delivered message) or never removed (permanent leak). `register`/`remove` now guard the Hash with a mutex.
33
+ - [Fix] Stop the `Metadata` retry loop from clobbering the request timeout and blocking for minutes. Each retry overwrote the per-request timeout with the exponential backoff value, so the first retries ran with a far-too-short request timeout (e.g. 200ms vs the 2,000ms default, near-guaranteeing another timeout) while later ones inflated it to ~100s; the cumulative sleeps alone reached ~204s. The request timeout is now left unchanged across retries, the per-attempt backoff is capped at `Defaults::METADATA_RETRY_BACKOFF_MAX_MS` (1,000ms), and the loop is bounded by a wall-clock budget (`Defaults::METADATA_RETRY_BUDGET_MS`, 5,000ms) after a floor of `Defaults::METADATA_MIN_ATTEMPTS` (3) tries. This keeps a synchronous metadata fetch from blocking for minutes while still giving a slow broker a few attempts: fast-recovering clusters retry quickly within the budget, an unresponsive one fails in ~5s (a bit over if its requests each consume the full timeout), and at least 3 attempts always happen.
34
+ - [Fix] Cache the partition count for a missing topic so `produce` with a `partition_key` to a not-yet-created topic no longer runs a blocking metadata query on every message. The `unknown_topic_or_part` result was resolved to `RD_KAFKA_PARTITION_UA` outside the partition-count cache, so nothing was stored and each call performed a fresh synchronous metadata RPC (the promised negative cache did not exist). The miss is now resolved inside the cache block, so it is cached like any other value and reused for the cache TTL.
35
+
3
36
  ## 0.27.2 (2026-05-21)
4
37
  - [Enhancement] `poll_batch` and `poll_batch_nb` now return error events inline as `RdkafkaError` objects rather than raising on the first error. The return type is `Array<Message, RdkafkaError>` and callers are responsible for handling errors in the result.
5
38
 
data/README.md CHANGED
@@ -63,6 +63,7 @@ Contributions should generally be made to the upstream [rdkafka-ruby repository]
63
63
 
64
64
  | rdkafka-ruby | librdkafka | patches |
65
65
  |-|-|-|
66
+ | 0.28.x (2026-07-12) | 2.14.2 (2026-06-03) | yes |
66
67
  | 0.27.x (2026-05-08) | 2.14.1 (2026-04-15) | yes |
67
68
  | 0.26.x (2026-04-11) | 2.14.0 (2026-04-01) | yes |
68
69
  | 0.25.x (2026-04-02) | 2.13.2 (2026-03-02) | yes |
@@ -1,7 +1,7 @@
1
1
  services:
2
2
  kafka:
3
3
  container_name: kafka
4
- image: confluentinc/cp-kafka:8.2.0
4
+ image: confluentinc/cp-kafka:8.3.0
5
5
  ports:
6
6
  - 9092:9092 # Support PLAINTEXT so we can run one docker setup for SSL and PLAINTEXT
7
7
  - 9093:9093
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.0
4
+ image: confluentinc/cp-kafka:8.3.0
5
5
 
6
6
  ports:
7
7
  - 9092:9092
@@ -19,6 +19,7 @@ Gem::Specification.new do |gem|
19
19
  next true if file.start_with?(".")
20
20
  next true if file.start_with?("spec/")
21
21
  next true if file.start_with?("ext/README.md")
22
+ next true if file.start_with?("Gemfile")
22
23
 
23
24
  false
24
25
  end
@@ -14,9 +14,16 @@ module Rdkafka
14
14
 
15
15
  # Registry for registering all the handles.
16
16
  REGISTRY = {}
17
+ # Guards REGISTRY mutations. The registry is shared across producing/consuming threads and the
18
+ # background polling thread (which removes handles from FFI callbacks), so the Hash must not be
19
+ # mutated concurrently. This is effectively safe on MRI under the GVL but not on JRuby, where a
20
+ # lost write could leave a handle unregistered (never unlocked -> `wait` times out for a
21
+ # delivered message) or never removed (permanent leak).
22
+ REGISTRY_MUTEX = Mutex.new
17
23
  # Default wait timeout is 31 years
18
24
  MAX_WAIT_TIMEOUT_FOREVER = 10_000_000_000
19
25
 
26
+ private_constant :REGISTRY_MUTEX
20
27
  private_constant :MAX_WAIT_TIMEOUT_FOREVER
21
28
 
22
29
  class << self
@@ -25,17 +32,28 @@ module Rdkafka
25
32
  # @param handle [AbstractHandle] any handle we want to register
26
33
  def register(handle)
27
34
  address = handle.to_ptr.address
28
- REGISTRY[address] = handle
35
+ REGISTRY_MUTEX.synchronize { REGISTRY[address] = handle }
29
36
  end
30
37
 
31
38
  # Removes handle from the register based on the handle address
32
39
  #
33
40
  # @param address [Integer] address of the registered handle we want to remove
34
41
  def remove(address)
35
- REGISTRY.delete(address)
42
+ REGISTRY_MUTEX.synchronize { REGISTRY.delete(address) }
36
43
  end
37
44
  end
38
45
 
46
+ # Operation result prepared by the background event callback. Background events are
47
+ # destroyed as soon as the callback returns, so anything the waiting thread needs has to be
48
+ # copied out of event-owned memory into Ruby objects and stored here before `#unlock` runs.
49
+ # When result parsing fails, holds the captured exception so it can be re-raised on the
50
+ # waiting thread.
51
+ attr_accessor :result
52
+
53
+ # Broker-provided error message copied out of event-owned memory by the background event
54
+ # callback, used by `#raise_error`
55
+ attr_accessor :broker_message
56
+
39
57
  def initialize
40
58
  @mutex = Thread::Mutex.new
41
59
  @resource = Thread::ConditionVariable.new
@@ -118,13 +136,28 @@ module Rdkafka
118
136
  end
119
137
 
120
138
  # @return [Object] operation-specific result
139
+ #
140
+ # Defaults to the result prepared by the background event callback (see
141
+ # {#prepared_result}). Subclasses backed by a synchronous callback that writes the result
142
+ # into struct fields (e.g. {Producer::DeliveryHandle}) override this.
121
143
  def create_result
122
- raise "Must be implemented by subclass!"
144
+ prepared_result
145
+ end
146
+
147
+ # Returns the operation result prepared by the background event callback, re-raising an
148
+ # exception that was captured while the event memory was still readable
149
+ #
150
+ # @return [Object] operation-specific result
151
+ # @raise [RdkafkaError] when result parsing in the event callback failed
152
+ def prepared_result
153
+ raise(result) if result.is_a?(Exception)
154
+
155
+ result
123
156
  end
124
157
 
125
158
  # Allow subclasses to override
126
159
  def raise_error
127
- RdkafkaError.validate!(self[:response])
160
+ RdkafkaError.validate!(self[:response], broker_message: broker_message)
128
161
  end
129
162
 
130
163
  # Error that is raised when waiting for the handle to complete
@@ -17,7 +17,7 @@ module Rdkafka
17
17
  @synonyms = []
18
18
 
19
19
  # The code below builds up the config synonyms using same config binding
20
- pointer_to_size_t = FFI::MemoryPointer.new(:int32)
20
+ pointer_to_size_t = FFI::MemoryPointer.new(:size_t)
21
21
  synonym_ptr = Bindings.rd_kafka_ConfigEntry_synonyms(config_ptr, pointer_to_size_t)
22
22
  synonyms_ptr = synonym_ptr.read_array_of_pointer(pointer_to_size_t.read_int)
23
23
 
@@ -5,25 +5,19 @@ module Rdkafka
5
5
  # Handle for create ACL operation
6
6
  class CreateAclHandle < AbstractHandle
7
7
  layout :pending, :bool,
8
- :response, :int,
9
- :response_string, :pointer
8
+ :response, :int
10
9
 
11
10
  # @return [String] the name of the operation
12
11
  def operation_name
13
12
  "create acl"
14
13
  end
15
14
 
16
- # @return [CreateAclReport] instance with rdkafka_response value as 0 and rdkafka_response_string value as empty string if the acl creation was successful
17
- def create_result
18
- CreateAclReport.new(rdkafka_response: self[:response], rdkafka_response_string: self[:response_string])
19
- end
20
-
21
15
  # Raises an error if the operation failed
22
16
  # @raise [RdkafkaError]
23
17
  def raise_error
24
18
  raise RdkafkaError.new(
25
19
  self[:response],
26
- broker_message: self[:response_string].read_string
20
+ broker_message: broker_message
27
21
  )
28
22
  end
29
23
  end
@@ -3,31 +3,12 @@ module Rdkafka
3
3
  # Handle for create partitions operation
4
4
  class CreatePartitionsHandle < AbstractHandle
5
5
  layout :pending, :bool,
6
- :response, :int,
7
- :error_string, :pointer,
8
- :result_name, :pointer
6
+ :response, :int
9
7
 
10
8
  # @return [String] the name of the operation
11
9
  def operation_name
12
10
  "create partitions"
13
11
  end
14
-
15
- # @return [Boolean] whether the create topic was successful
16
- def create_result
17
- CreatePartitionsReport.new(self[:error_string], self[:result_name])
18
- end
19
-
20
- # Raises an error if the operation failed
21
- # @raise [RdkafkaError]
22
- def raise_error
23
- RdkafkaError.validate!(
24
- self[:response],
25
- broker_message: CreatePartitionsReport.new(
26
- self[:error_string],
27
- self[:result_name]
28
- ).error_string
29
- )
30
- end
31
12
  end
32
13
  end
33
14
  end
@@ -5,31 +5,12 @@ module Rdkafka
5
5
  # Handle for create topic operation
6
6
  class CreateTopicHandle < AbstractHandle
7
7
  layout :pending, :bool,
8
- :response, :int,
9
- :error_string, :pointer,
10
- :result_name, :pointer
8
+ :response, :int
11
9
 
12
10
  # @return [String] the name of the operation
13
11
  def operation_name
14
12
  "create topic"
15
13
  end
16
-
17
- # @return [Boolean] whether the create topic was successful
18
- def create_result
19
- CreateTopicReport.new(self[:error_string], self[:result_name])
20
- end
21
-
22
- # Raises an error if the operation failed
23
- # @raise [RdkafkaError]
24
- def raise_error
25
- RdkafkaError.validate!(
26
- self[:response],
27
- broker_message: CreateTopicReport.new(
28
- self[:error_string],
29
- self[:result_name]
30
- ).error_string
31
- )
32
- end
33
14
  end
34
15
  end
35
16
  end
@@ -5,27 +5,19 @@ module Rdkafka
5
5
  # Handle for delete ACL operation
6
6
  class DeleteAclHandle < AbstractHandle
7
7
  layout :pending, :bool,
8
- :response, :int,
9
- :response_string, :pointer,
10
- :matching_acls, :pointer,
11
- :matching_acls_count, :int
8
+ :response, :int
12
9
 
13
10
  # @return [String] the name of the operation
14
11
  def operation_name
15
12
  "delete acl"
16
13
  end
17
14
 
18
- # @return [DeleteAclReport] instance with an array of matching_acls
19
- def create_result
20
- DeleteAclReport.new(matching_acls: self[:matching_acls], matching_acls_count: self[:matching_acls_count])
21
- end
22
-
23
15
  # Raises an error if the operation failed
24
16
  # @raise [RdkafkaError]
25
17
  def raise_error
26
18
  raise RdkafkaError.new(
27
19
  self[:response],
28
- broker_message: self[:response_string].read_string
20
+ broker_message: broker_message
29
21
  )
30
22
  end
31
23
  end
@@ -4,28 +4,20 @@ module Rdkafka
4
4
  class Admin
5
5
  # Handle for delete groups operation
6
6
  class DeleteGroupsHandle < AbstractHandle
7
- layout :pending, :bool, # TODO: ???
8
- :response, :int,
9
- :error_string, :pointer,
10
- :result_name, :pointer
7
+ layout :pending, :bool,
8
+ :response, :int
11
9
 
12
10
  # @return [String] the name of the operation
13
11
  def operation_name
14
12
  "delete groups"
15
13
  end
16
14
 
17
- # Creates the result report
18
- # @return [DeleteGroupsReport]
19
- def create_result
20
- DeleteGroupsReport.new(self[:error_string], self[:result_name])
21
- end
22
-
23
15
  # Raises an error if the operation failed
24
16
  # @raise [RdkafkaError]
25
17
  def raise_error
26
18
  raise RdkafkaError.new(
27
19
  self[:response],
28
- broker_message: create_result.error_string
20
+ broker_message: broker_message
29
21
  )
30
22
  end
31
23
  end
@@ -5,31 +5,12 @@ module Rdkafka
5
5
  # Handle for delete topic operation
6
6
  class DeleteTopicHandle < AbstractHandle
7
7
  layout :pending, :bool,
8
- :response, :int,
9
- :error_string, :pointer,
10
- :result_name, :pointer
8
+ :response, :int
11
9
 
12
10
  # @return [String] the name of the operation
13
11
  def operation_name
14
12
  "delete topic"
15
13
  end
16
-
17
- # @return [Boolean] whether the delete topic was successful
18
- def create_result
19
- DeleteTopicReport.new(self[:error_string], self[:result_name])
20
- end
21
-
22
- # Raises an error if the operation failed
23
- # @raise [RdkafkaError]
24
- def raise_error
25
- RdkafkaError.validate!(
26
- self[:response],
27
- broker_message: DeleteTopicReport.new(
28
- self[:error_string],
29
- self[:result_name]
30
- ).error_string
31
- )
32
- end
33
14
  end
34
15
  end
35
16
  end
@@ -5,27 +5,19 @@ module Rdkafka
5
5
  # Handle for describe ACL operation
6
6
  class DescribeAclHandle < AbstractHandle
7
7
  layout :pending, :bool,
8
- :response, :int,
9
- :response_string, :pointer,
10
- :acls, :pointer,
11
- :acls_count, :int
8
+ :response, :int
12
9
 
13
10
  # @return [String] the name of the operation.
14
11
  def operation_name
15
12
  "describe acl"
16
13
  end
17
14
 
18
- # @return [DescribeAclReport] instance with an array of acls that matches the request filters.
19
- def create_result
20
- DescribeAclReport.new(acls: self[:acls], acls_count: self[:acls_count])
21
- end
22
-
23
15
  # Raises an error if the operation failed
24
16
  # @raise [RdkafkaError]
25
17
  def raise_error
26
18
  raise RdkafkaError.new(
27
19
  self[:response],
28
- broker_message: self[:response_string].read_string
20
+ broker_message: broker_message
29
21
  )
30
22
  end
31
23
  end
@@ -5,30 +5,19 @@ module Rdkafka
5
5
  # Handle for describe configs operation
6
6
  class DescribeConfigsHandle < AbstractHandle
7
7
  layout :pending, :bool,
8
- :response, :int,
9
- :response_string, :pointer,
10
- :config_entries, :pointer,
11
- :entry_count, :int
8
+ :response, :int
12
9
 
13
10
  # @return [String] the name of the operation.
14
11
  def operation_name
15
12
  "describe configs"
16
13
  end
17
14
 
18
- # @return [DescribeAclReport] instance with an array of acls that matches the request filters.
19
- def create_result
20
- DescribeConfigsReport.new(
21
- config_entries: self[:config_entries],
22
- entry_count: self[:entry_count]
23
- )
24
- end
25
-
26
15
  # Raises an error if the operation failed
27
16
  # @raise [RdkafkaError]
28
17
  def raise_error
29
18
  raise RdkafkaError.new(
30
19
  self[:response],
31
- broker_message: self[:response_string].read_string
20
+ broker_message: broker_message
32
21
  )
33
22
  end
34
23
  end
@@ -6,7 +6,10 @@ module Rdkafka
6
6
  class DescribeConfigsReport
7
7
  attr_reader :resources
8
8
 
9
- # @param config_entries [FFI::Pointer] pointer to config entries array
9
+ # @param config_entries [FFI::Pointer] pointer to the event-owned config entries array.
10
+ # It is only read here - the array is destroyed together with the result event by the
11
+ # background event callback, so this report must be built while the event is alive and
12
+ # must copy everything it needs into Ruby objects.
10
13
  # @param entry_count [Integer] number of config entries
11
14
  def initialize(config_entries:, entry_count:)
12
15
  @resources = []
@@ -19,7 +22,7 @@ module Rdkafka
19
22
  .each do |config_resource_result_ptr|
20
23
  config_resource_result = ConfigResourceBindingResult.new(config_resource_result_ptr)
21
24
 
22
- pointer_to_size_t = FFI::MemoryPointer.new(:int32)
25
+ pointer_to_size_t = FFI::MemoryPointer.new(:size_t)
23
26
  configs_ptr = Bindings.rd_kafka_ConfigResource_configs(
24
27
  config_resource_result_ptr,
25
28
  pointer_to_size_t
@@ -32,10 +35,6 @@ module Rdkafka
32
35
 
33
36
  @resources << config_resource_result
34
37
  end
35
- ensure
36
- return if config_entries == FFI::Pointer::NULL
37
-
38
- Bindings.rd_kafka_ConfigResource_destroy_array(config_entries, entry_count)
39
38
  end
40
39
 
41
40
  private
@@ -5,30 +5,19 @@ module Rdkafka
5
5
  # Handle for incremental alter configs operation
6
6
  class IncrementalAlterConfigsHandle < AbstractHandle
7
7
  layout :pending, :bool,
8
- :response, :int,
9
- :response_string, :pointer,
10
- :config_entries, :pointer,
11
- :entry_count, :int
8
+ :response, :int
12
9
 
13
10
  # @return [String] the name of the operation.
14
11
  def operation_name
15
12
  "incremental alter configs"
16
13
  end
17
14
 
18
- # @return [DescribeAclReport] instance with an array of acls that matches the request filters.
19
- def create_result
20
- IncrementalAlterConfigsReport.new(
21
- config_entries: self[:config_entries],
22
- entry_count: self[:entry_count]
23
- )
24
- end
25
-
26
15
  # Raises an error if the operation failed
27
16
  # @raise [RdkafkaError]
28
17
  def raise_error
29
18
  raise RdkafkaError.new(
30
19
  self[:response],
31
- broker_message: self[:response_string].read_string
20
+ broker_message: broker_message
32
21
  )
33
22
  end
34
23
  end
@@ -6,7 +6,10 @@ module Rdkafka
6
6
  class IncrementalAlterConfigsReport
7
7
  attr_reader :resources
8
8
 
9
- # @param config_entries [FFI::Pointer] pointer to config entries array
9
+ # @param config_entries [FFI::Pointer] pointer to the event-owned config entries array.
10
+ # It is only read here - the array is destroyed together with the result event by the
11
+ # background event callback, so this report must be built while the event is alive and
12
+ # must copy everything it needs into Ruby objects.
10
13
  # @param entry_count [Integer] number of config entries
11
14
  def initialize(config_entries:, entry_count:)
12
15
  @resources = []
@@ -19,7 +22,7 @@ module Rdkafka
19
22
  .each do |config_resource_result_ptr|
20
23
  config_resource_result = ConfigResourceBindingResult.new(config_resource_result_ptr)
21
24
 
22
- pointer_to_size_t = FFI::MemoryPointer.new(:int32)
25
+ pointer_to_size_t = FFI::MemoryPointer.new(:size_t)
23
26
  configs_ptr = Bindings.rd_kafka_ConfigResource_configs(
24
27
  config_resource_result_ptr,
25
28
  pointer_to_size_t
@@ -32,10 +35,6 @@ module Rdkafka
32
35
 
33
36
  @resources << config_resource_result
34
37
  end
35
- ensure
36
- return if config_entries == FFI::Pointer::NULL
37
-
38
- Bindings.rd_kafka_ConfigResource_destroy_array(config_entries, entry_count)
39
38
  end
40
39
 
41
40
  private
@@ -5,30 +5,19 @@ module Rdkafka
5
5
  # Handle for list offsets operation
6
6
  class ListOffsetsHandle < AbstractHandle
7
7
  layout :pending, :bool,
8
- :response, :int,
9
- :response_string, :pointer,
10
- :result_infos, :pointer,
11
- :result_count, :int
8
+ :response, :int
12
9
 
13
10
  # @return [String] the name of the operation.
14
11
  def operation_name
15
12
  "list offsets"
16
13
  end
17
14
 
18
- # @return [ListOffsetsReport] instance with partition offset information.
19
- def create_result
20
- ListOffsetsReport.new(
21
- result_infos: self[:result_infos],
22
- result_count: self[:result_count]
23
- )
24
- end
25
-
26
15
  # Raises an error if the operation failed
27
16
  # @raise [RdkafkaError]
28
17
  def raise_error
29
18
  raise RdkafkaError.new(
30
19
  self[:response],
31
- broker_message: self[:response_string].read_string
20
+ broker_message: broker_message
32
21
  )
33
22
  end
34
23
  end
@@ -36,7 +36,7 @@ module Rdkafka
36
36
 
37
37
  # Validates the partition result and raises an error if invalid
38
38
  # @param result_info_ptr [FFI::Pointer] pointer to the result info
39
- # @raise [RdkafkaError] when the partition has an error
39
+ # @raise [RdkafkaError] when the partition has an error, naming the failing partition
40
40
  def validate!(result_info_ptr)
41
41
  tp_ptr = Bindings.rd_kafka_ListOffsetsResultInfo_topic_partition(result_info_ptr)
42
42
  tp = Bindings::TopicPartition.new(tp_ptr)
@@ -44,7 +44,10 @@ module Rdkafka
44
44
 
45
45
  return if code.zero?
46
46
 
47
- raise RdkafkaError.new(code)
47
+ raise RdkafkaError.new(
48
+ code,
49
+ "Error querying offsets for partition #{tp[:partition]} of '#{tp[:topic]}'"
50
+ )
48
51
  end
49
52
  end
50
53
  end