pulsar-ruby 0.1.0.pre

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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: f69966a02c965ad73caf5c5f74c457f51b4d815f0d0b67286eb0e16038723740
4
+ data.tar.gz: aa38828340d83fc09f8817936c9c50e4a2b16a7e76fda19c404e2ce0b926264d
5
+ SHA512:
6
+ metadata.gz: 2f0412268a94dacd003510f572f3b6c5ebe1609a95c165dadd907344eb436568603a8526e8786db0e4520a4dffc9770b1fea3d1c6b8dc52906948e1dad9c549f
7
+ data.tar.gz: 9b9871caad93a69d35c381098e8866c9804e001c53d10a787f7be094f084de4ad2175bcfc9d45f1f2fe58e5e514979df4d4e9eceea3324c45be0c3afd43a5deb
data/LICENSE ADDED
@@ -0,0 +1,204 @@
1
+ Copyright 2026 Franky Lau
2
+
3
+
4
+ Apache License
5
+ Version 2.0, January 2004
6
+ http://www.apache.org/licenses/
7
+
8
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
9
+
10
+ 1. Definitions.
11
+
12
+ "License" shall mean the terms and conditions for use, reproduction,
13
+ and distribution as defined by Sections 1 through 9 of this document.
14
+
15
+ "Licensor" shall mean the copyright owner or entity authorized by
16
+ the copyright owner that is granting the License.
17
+
18
+ "Legal Entity" shall mean the union of the acting entity and all
19
+ other entities that control, are controlled by, or are under common
20
+ control with that entity. For the purposes of this definition,
21
+ "control" means (i) the power, direct or indirect, to cause the
22
+ direction or management of such entity, whether by contract or
23
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
24
+ outstanding shares, or (iii) beneficial ownership of such entity.
25
+
26
+ "You" (or "Your") shall mean an individual or Legal Entity
27
+ exercising permissions granted by this License.
28
+
29
+ "Source" form shall mean the preferred form for making modifications,
30
+ including but not limited to software source code, documentation
31
+ source, and configuration files.
32
+
33
+ "Object" form shall mean any form resulting from mechanical
34
+ transformation or translation of a Source form, including but
35
+ not limited to compiled object code, generated documentation,
36
+ and conversions to other media types.
37
+
38
+ "Work" shall mean the work of authorship, whether in Source or
39
+ Object form, made available under the License, as indicated by a
40
+ copyright notice that is included in or attached to the work
41
+ (an example is provided in the Appendix below).
42
+
43
+ "Derivative Works" shall mean any work, whether in Source or Object
44
+ form, that is based on (or derived from) the Work and for which the
45
+ editorial revisions, annotations, elaborations, or other modifications
46
+ represent, as a whole, an original work of authorship. For the purposes
47
+ of this License, Derivative Works shall not include works that remain
48
+ separable from, or merely link (or bind by name) to the interfaces of,
49
+ the Work and Derivative Works thereof.
50
+
51
+ "Contribution" shall mean any work of authorship, including
52
+ the original version of the Work and any modifications or additions
53
+ to that Work or Derivative Works thereof, that is intentionally
54
+ submitted to Licensor for inclusion in the Work by the copyright owner
55
+ or by an individual or Legal Entity authorized to submit on behalf of
56
+ the copyright owner. For the purposes of this definition, "submitted"
57
+ means any form of electronic, verbal, or written communication sent
58
+ to the Licensor or its representatives, including but not limited to
59
+ communication on electronic mailing lists, source code control systems,
60
+ and issue tracking systems that are managed by, or on behalf of, the
61
+ Licensor for the purpose of discussing and improving the Work, but
62
+ excluding communication that is conspicuously marked or otherwise
63
+ designated in writing by the copyright owner as "Not a Contribution."
64
+
65
+ "Contributor" shall mean Licensor and any individual or Legal Entity
66
+ on behalf of whom a Contribution has been received by Licensor and
67
+ subsequently incorporated within the Work.
68
+
69
+ 2. Grant of Copyright License. Subject to the terms and conditions of
70
+ this License, each Contributor hereby grants to You a perpetual,
71
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
72
+ copyright license to reproduce, prepare Derivative Works of,
73
+ publicly display, publicly perform, sublicense, and distribute the
74
+ Work and such Derivative Works in Source or Object form.
75
+
76
+ 3. Grant of Patent License. Subject to the terms and conditions of
77
+ this License, each Contributor hereby grants to You a perpetual,
78
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
79
+ (except as stated in this section) patent license to make, have made,
80
+ use, offer to sell, sell, import, and otherwise transfer the Work,
81
+ where such license applies only to those patent claims licensable
82
+ by such Contributor that are necessarily infringed by their
83
+ Contribution(s) alone or by combination of their Contribution(s)
84
+ with the Work to which such Contribution(s) was submitted. If You
85
+ institute patent litigation against any entity (including a
86
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
87
+ or a Contribution incorporated within the Work constitutes direct
88
+ or contributory patent infringement, then any patent licenses
89
+ granted to You under this License for that Work shall terminate
90
+ as of the date such litigation is filed.
91
+
92
+ 4. Redistribution. You may reproduce and distribute copies of the
93
+ Work or Derivative Works thereof in any medium, with or without
94
+ modifications, and in Source or Object form, provided that You
95
+ meet the following conditions:
96
+
97
+ (a) You must give any other recipients of the Work or
98
+ Derivative Works a copy of this License; and
99
+
100
+ (b) You must cause any modified files to carry prominent notices
101
+ stating that You changed the files; and
102
+
103
+ (c) You must retain, in the Source form of any Derivative Works
104
+ that You distribute, all copyright, patent, trademark, and
105
+ attribution notices from the Source form of the Work,
106
+ excluding those notices that do not pertain to any part of
107
+ the Derivative Works; and
108
+
109
+ (d) If the Work includes a "NOTICE" text file as part of its
110
+ distribution, then any Derivative Works that You distribute must
111
+ include a readable copy of the attribution notices contained
112
+ within such NOTICE file, excluding those notices that do not
113
+ pertain to any part of the Derivative Works, in at least one
114
+ of the following places: within a NOTICE text file distributed
115
+ as part of the Derivative Works; within the Source form or
116
+ documentation, if provided along with the Derivative Works; or,
117
+ within a display generated by the Derivative Works, if and
118
+ wherever such third-party notices normally appear. The contents
119
+ of the NOTICE file are for informational purposes only and
120
+ do not modify the License. You may add Your own attribution
121
+ notices within Derivative Works that You distribute, alongside
122
+ or as an addendum to the NOTICE text from the Work, provided
123
+ that such additional attribution notices cannot be construed
124
+ as modifying the License.
125
+
126
+ You may add Your own copyright statement to Your modifications and
127
+ may provide additional or different license terms and conditions
128
+ for use, reproduction, or distribution of Your modifications, or
129
+ for any such Derivative Works as a whole, provided Your use,
130
+ reproduction, and distribution of the Work otherwise complies with
131
+ the conditions stated in this License.
132
+
133
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
134
+ any Contribution intentionally submitted for inclusion in the Work
135
+ by You to the Licensor shall be under the terms and conditions of
136
+ this License, without any additional terms or conditions.
137
+ Notwithstanding the above, nothing herein shall supersede or modify
138
+ the terms of any separate license agreement you may have executed
139
+ with Licensor regarding such Contributions.
140
+
141
+ 6. Trademarks. This License does not grant permission to use the trade
142
+ names, trademarks, service marks, or product names of the Licensor,
143
+ except as required for reasonable and customary use in describing the
144
+ origin of the Work and reproducing the content of the NOTICE file.
145
+
146
+ 7. Disclaimer of Warranty. Unless required by applicable law or
147
+ agreed to in writing, Licensor provides the Work (and each
148
+ Contributor provides its Contributions) on an "AS IS" BASIS,
149
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
150
+ implied, including, without limitation, any warranties or conditions
151
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
152
+ PARTICULAR PURPOSE. You are solely responsible for determining the
153
+ appropriateness of using or redistributing the Work and assume any
154
+ risks associated with Your exercise of permissions under this License.
155
+
156
+ 8. Limitation of Liability. In no event and under no legal theory,
157
+ whether in tort (including negligence), contract, or otherwise,
158
+ unless required by applicable law (such as deliberate and grossly
159
+ negligent acts) or agreed to in writing, shall any Contributor be
160
+ liable to You for damages, including any direct, indirect, special,
161
+ incidental, or consequential damages of any character arising as a
162
+ result of this License or out of the use or inability to use the
163
+ Work (including but not limited to damages for loss of goodwill,
164
+ work stoppage, computer failure or malfunction, or any and all
165
+ other commercial damages or losses), even if such Contributor
166
+ has been advised of the possibility of such damages.
167
+
168
+ 9. Accepting Warranty or Additional Liability. While redistributing
169
+ the Work or Derivative Works thereof, You may choose to offer,
170
+ and charge a fee for, acceptance of support, warranty, indemnity,
171
+ or other liability obligations and/or rights consistent with this
172
+ License. However, in accepting such obligations, You may act only
173
+ on Your own behalf and on Your sole responsibility, not on behalf
174
+ of any other Contributor, and only if You agree to indemnify,
175
+ defend, and hold each Contributor harmless for any liability
176
+ incurred by, or claims asserted against, such Contributor by reason
177
+ of your accepting any such warranty or additional liability.
178
+
179
+ END OF TERMS AND CONDITIONS
180
+
181
+ APPENDIX: How to apply the Apache License to your work.
182
+
183
+ To apply the Apache License to your work, attach the following
184
+ boilerplate notice, with the fields enclosed by brackets "[]"
185
+ replaced with your own identifying information. (Don't include
186
+ the brackets!) The text should be enclosed in the appropriate
187
+ comment syntax for the file format. We also recommend that a
188
+ file or class name and description of purpose be included on the
189
+ same "printed page" as the copyright notice for easier
190
+ identification within third-party archives.
191
+
192
+ Copyright [yyyy] [name of copyright owner]
193
+
194
+ Licensed under the Apache License, Version 2.0 (the "License");
195
+ you may not use this file except in compliance with the License.
196
+ You may obtain a copy of the License at
197
+
198
+ http://www.apache.org/licenses/LICENSE-2.0
199
+
200
+ Unless required by applicable law or agreed to in writing, software
201
+ distributed under the License is distributed on an "AS IS" BASIS,
202
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
203
+ See the License for the specific language governing permissions and
204
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,198 @@
1
+ # pulsar-ruby
2
+
3
+ A pure Ruby client for [Apache Pulsar](https://pulsar.apache.org/).
4
+
5
+ `pulsar-ruby` implements the Pulsar binary protocol in Ruby (no C++ bindings or native
6
+ extensions). The goal is a small, idiomatic API for producing and consuming messages on a
7
+ local or self-hosted broker, with room to grow into TLS, authentication, batching, and
8
+ other features over time.
9
+
10
+ **Status:** MVP implementation. The public API, protocol definitions, frame
11
+ codec, plaintext TCP transport, connection reader, producer/consumer protocol
12
+ paths, close cleanup, and conservative reconnect are in place. Supported
13
+ integration scenarios are verified against Pulsar standalone.
14
+
15
+ ## Requirements
16
+
17
+ - Ruby >= 3.0
18
+
19
+ ## Installation
20
+
21
+ The gem is not published on [RubyGems](https://rubygems.org/) yet. Install from GitHub:
22
+
23
+ ```ruby
24
+ # Gemfile
25
+ gem "pulsar-ruby", github: "killalau/pulsar-ruby"
26
+ ```
27
+
28
+ Or clone the repository and use Bundler locally:
29
+
30
+ ```bash
31
+ git clone https://github.com/killalau/pulsar-ruby.git
32
+ cd pulsar-ruby
33
+ bundle install
34
+ ```
35
+
36
+ ## Quickstart
37
+
38
+ Start a local standalone broker:
39
+
40
+ ```bash
41
+ docker compose up -d pulsar
42
+ ```
43
+
44
+ Produce, receive, and acknowledge one message:
45
+
46
+ ```ruby
47
+ require "pulsar"
48
+
49
+ Pulsar::Client.open("pulsar://localhost:6650") do |client|
50
+ producer = client.producer(
51
+ topic: "persistent://public/default/orders",
52
+ max_pending_messages: 1000
53
+ )
54
+
55
+ consumer = client.consumer(
56
+ topic: "persistent://public/default/orders",
57
+ subscription: "orders-ruby"
58
+ )
59
+
60
+ message_id = producer.send("created", timeout: 5)
61
+ message = consumer.receive(timeout: 5)
62
+
63
+ puts message.payload
64
+ consumer.ack(message)
65
+ end
66
+ ```
67
+
68
+ `producer.send`, `consumer.receive`, and `consumer.ack` are wired to the
69
+ plaintext Pulsar binary protocol path for non-partitioned topics.
70
+
71
+ ## Supported MVP features
72
+
73
+ - Plaintext `pulsar://` broker connections.
74
+ - Binary protocol connect handshake.
75
+ - Topic lookup before producer or consumer creation.
76
+ - Non-partitioned topic producers.
77
+ - Non-partitioned topic consumers with one subscription.
78
+ - Single, unbatched string or byte payload messages.
79
+ - Message properties, key, event time, and structured message IDs.
80
+ - Individual acknowledgement.
81
+ - Consumer flow permits.
82
+ - Producer pending-send limits.
83
+ - Operation and receive timeouts.
84
+ - Idempotent producer, consumer, and client close.
85
+ - Conservative reconnect after a dropped connection.
86
+
87
+ ## Deferred features
88
+
89
+ - TLS.
90
+ - Authentication.
91
+ - Partitioned topics.
92
+ - Reader API.
93
+ - Multi-topic consumers.
94
+ - Subscription type options beyond the current default broker behavior.
95
+ - Batching.
96
+ - Compression.
97
+ - Chunking.
98
+ - Schemas beyond raw byte/string payloads.
99
+ - Negative ack and delayed reconsume.
100
+ - Dead letter and retry topics.
101
+ - Transactions.
102
+ - Interceptors.
103
+ - Admin API.
104
+ - Metrics and tracing.
105
+
106
+ ## Timeouts and reconnect
107
+
108
+ `Pulsar::Client.new` accepts `operation_timeout:` and `connection_timeout:`.
109
+ `producer.send` and `consumer.receive` also accept `timeout:` for the current
110
+ operation.
111
+
112
+ Reconnect is intentionally conservative. If the socket drops, in-flight
113
+ operations fail with `Pulsar::ConnectionError`. Existing producer and consumer
114
+ objects remain usable; the next operation lazily opens a replacement connection
115
+ and recreates broker-side producer or consumer state. The failed in-flight
116
+ operation is not silently retried.
117
+
118
+ See [docs/design/reconnect-policy.md](docs/design/reconnect-policy.md) for the
119
+ design rationale.
120
+
121
+ ## Development
122
+
123
+ ```bash
124
+ bundle install
125
+ bundle exec rake verify
126
+ ```
127
+
128
+ `bundle exec rake verify` runs RuboCop and the normal RSpec suite.
129
+
130
+ Run the local Pulsar standalone integration spec:
131
+
132
+ ```bash
133
+ docker compose up -d pulsar
134
+ bundle exec rake spec:integration
135
+ ```
136
+
137
+ Build the local gem package:
138
+
139
+ ```bash
140
+ gem build pulsar-ruby.gemspec
141
+ ```
142
+
143
+ Run the installed-gem smoke test against local Pulsar standalone:
144
+
145
+ ```bash
146
+ docker compose up -d pulsar
147
+ bundle exec rake smoke:local
148
+ ```
149
+
150
+ `smoke:local` builds the gem, installs that built artifact into a temporary gem
151
+ home, requires `pulsar`, and performs one produce/consume/ack round trip.
152
+
153
+ ### Git hooks
154
+
155
+ This repository includes a versioned pre-push hook in `.githooks/pre-push`.
156
+ Enable it for this checkout with:
157
+
158
+ ```bash
159
+ git config core.hooksPath .githooks
160
+ ```
161
+
162
+ After that, `git push` runs `bundle exec rake verify` before sending commits.
163
+ The hook does not run standalone integration specs because they require a local
164
+ broker and are slower than the regular push guard.
165
+
166
+ ### Project layout
167
+
168
+ | Path | Purpose |
169
+ |------|---------|
170
+ | `lib/pulsar/` | Public API (`Client`, `Producer`, `Consumer`, `Message`, …) |
171
+ | `lib/pulsar/internal/` | Thread runtime, promises, bounded queues (not public API) |
172
+ | `docs/` | Research, design, and implementation planning |
173
+ | `script/` | Local release and smoke-test scripts |
174
+ | `spec/` | RSpec tests |
175
+
176
+ See [docs/overview.md](docs/overview.md) for the documentation index.
177
+
178
+ ## MVP scope
179
+
180
+ The first release targets plaintext `pulsar://` connections, single-topic producer and
181
+ consumer workflows, unbatched messages, acknowledgements, flow control, and basic
182
+ reconnect behavior. TLS, authentication, partitioned topics, batching, compression, and
183
+ admin APIs are explicitly out of scope for the MVP.
184
+
185
+ Details: [docs/research/mvp-scope.md](docs/research/mvp-scope.md).
186
+
187
+ ## Why another Ruby client?
188
+
189
+ Ruby is not a first-class official Pulsar client today. Existing gems are unmaintained,
190
+ incomplete, or wrap native code. This project aims for a maintained, pure-Ruby
191
+ implementation with a clear public API and testable layers.
192
+
193
+ Background: [docs/research/ruby-client-landscape.md](docs/research/ruby-client-landscape.md).
194
+
195
+ ## License
196
+
197
+ Licensed under the [Apache License, Version 2.0](LICENSE), aligned with the Apache
198
+ Pulsar ecosystem. The software is provided as-is, without warranty.
@@ -0,0 +1,136 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'set'
4
+ require 'uri'
5
+
6
+ module Pulsar
7
+ # Entry point for creating producers and consumers against a Pulsar broker.
8
+ class Client
9
+ DEFAULT_OPERATION_TIMEOUT = 30
10
+ DEFAULT_CONNECTION_TIMEOUT = 10
11
+
12
+ attr_reader :service_url, :operation_timeout, :connection_timeout, :logger
13
+
14
+ def self.open(service_url, **options)
15
+ client = new(service_url, **options)
16
+ return client unless block_given?
17
+
18
+ begin
19
+ yield client
20
+ ensure
21
+ client.close
22
+ end
23
+ end
24
+
25
+ def initialize(service_url, operation_timeout: DEFAULT_OPERATION_TIMEOUT,
26
+ connection_timeout: DEFAULT_CONNECTION_TIMEOUT, logger: nil, **options)
27
+ validate_unsupported_options!(options)
28
+
29
+ @service_url = normalize_service_url(service_url)
30
+ @service_uri = URI(@service_url)
31
+ @operation_timeout = operation_timeout
32
+ @connection_timeout = connection_timeout
33
+ @logger = logger
34
+ @producers = Set.new
35
+ @consumers = Set.new
36
+ @closed = false
37
+ @producer_id = 0
38
+ @consumer_id = 0
39
+ end
40
+
41
+ def producer(topic:, max_pending_messages: 1000, **_options)
42
+ ensure_open!
43
+ lookup_topic(topic)
44
+
45
+ impl = Internal::ProducerImpl.create(
46
+ connection_provider: -> { connection },
47
+ topic: topic,
48
+ producer_id: next_producer_id,
49
+ operation_timeout: operation_timeout,
50
+ max_pending_messages: max_pending_messages
51
+ )
52
+ Producer.new(topic: topic, impl: impl).tap { |producer| @producers.add(producer) }
53
+ end
54
+
55
+ def consumer(topic:, subscription:, **_options)
56
+ ensure_open!
57
+ lookup_topic(topic)
58
+
59
+ impl = Internal::ConsumerImpl.create(
60
+ connection_provider: -> { connection },
61
+ topic: topic,
62
+ subscription: subscription,
63
+ consumer_id: next_consumer_id,
64
+ operation_timeout: operation_timeout,
65
+ receiver_queue_size: 1000
66
+ )
67
+ Consumer.new(topic: topic, subscription: subscription, impl: impl).tap { |consumer| @consumers.add(consumer) }
68
+ end
69
+
70
+ def close
71
+ return if closed?
72
+
73
+ @closed = true
74
+ close_all(@producers)
75
+ close_all(@consumers)
76
+ @connection&.close
77
+ nil
78
+ end
79
+
80
+ def closed?
81
+ @closed
82
+ end
83
+
84
+ private
85
+
86
+ def close_all(resources)
87
+ resources.each(&:close)
88
+ resources.clear
89
+ end
90
+
91
+ def connection
92
+ @connection&.close if @connection && !@connection.connected?
93
+ @connection = nil if @connection && !@connection.connected?
94
+ @connection ||= Internal::Connection.connect(
95
+ host: @service_uri.host,
96
+ port: @service_uri.port || 6650,
97
+ connection_timeout: connection_timeout,
98
+ operation_timeout: operation_timeout,
99
+ client_version: "pulsar-ruby/#{VERSION}"
100
+ )
101
+ end
102
+
103
+ def lookup_topic(topic)
104
+ Internal::LookupService.new(connection: connection, operation_timeout: operation_timeout).lookup(topic)
105
+ end
106
+
107
+ def next_producer_id
108
+ @producer_id += 1
109
+ end
110
+
111
+ def next_consumer_id
112
+ @consumer_id += 1
113
+ end
114
+
115
+ def ensure_open!
116
+ raise ClosedError, 'client is closed' if closed?
117
+ end
118
+
119
+ def normalize_service_url(service_url)
120
+ uri = URI(String(service_url))
121
+ raise ConfigurationError, 'service URL must use pulsar:// scheme' unless uri.scheme == 'pulsar'
122
+ raise ConfigurationError, 'service URL must include a host' if uri.host.nil? || uri.host.empty?
123
+
124
+ uri.to_s
125
+ rescue URI::InvalidURIError => e
126
+ raise ConfigurationError, "invalid service URL: #{e.message}"
127
+ end
128
+
129
+ def validate_unsupported_options!(options)
130
+ unsupported = options.keys & %i[authentication tls]
131
+ return if unsupported.empty?
132
+
133
+ raise ConfigurationError, "unsupported MVP option(s): #{unsupported.join(', ')}"
134
+ end
135
+ end
136
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pulsar
4
+ # Public consumer API for receiving and acknowledging messages.
5
+ class Consumer
6
+ attr_reader :topic, :subscription
7
+
8
+ def initialize(topic:, subscription:, impl: nil)
9
+ @topic = String(topic)
10
+ @subscription = String(subscription)
11
+ @impl = impl
12
+ @closed = false
13
+ end
14
+
15
+ def receive(timeout: nil)
16
+ ensure_open!
17
+ raise UnsupportedFeatureError, 'consumer receive is not implemented yet' unless @impl
18
+
19
+ @impl.receive(timeout: timeout)
20
+ end
21
+
22
+ def ack(message_or_message_id)
23
+ ensure_open!
24
+ raise UnsupportedFeatureError, 'consumer ack is not implemented yet' unless @impl
25
+
26
+ @impl.ack(message_or_message_id)
27
+ end
28
+
29
+ def close
30
+ return if closed?
31
+
32
+ @impl&.close
33
+ @closed = true
34
+ nil
35
+ end
36
+
37
+ def closed?
38
+ @closed
39
+ end
40
+
41
+ private
42
+
43
+ def ensure_open!
44
+ raise ClosedError, 'consumer is closed' if closed?
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pulsar
4
+ class Error < StandardError; end
5
+
6
+ class TimeoutError < Error; end
7
+ class ConnectionError < Error; end
8
+ class ClosedError < Error; end
9
+ class AuthenticationError < Error; end
10
+ class AuthorizationError < Error; end
11
+ class TopicNotFoundError < Error; end
12
+ class ProducerBusyError < Error; end
13
+ class ConsumerBusyError < Error; end
14
+ class BrokerError < Error; end
15
+ class ProtocolError < Error; end
16
+ class ConfigurationError < Error; end
17
+ class UnsupportedFeatureError < Error; end
18
+ end
@@ -0,0 +1,78 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Pulsar
4
+ module Internal
5
+ # Sized queue wrapper with close and timeout behavior.
6
+ class BoundedQueue
7
+ def initialize(capacity:)
8
+ raise ArgumentError, 'capacity must be positive' unless capacity.positive?
9
+
10
+ @queue = SizedQueue.new(capacity)
11
+ @mutex = Mutex.new
12
+ @closed = false
13
+ end
14
+
15
+ def push(value, timeout: nil)
16
+ ensure_open!
17
+
18
+ if timeout
19
+ push_with_timeout(value, timeout)
20
+ else
21
+ push_until_available(value)
22
+ end
23
+
24
+ nil
25
+ end
26
+
27
+ def pop(timeout:)
28
+ ensure_open!
29
+
30
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
31
+
32
+ loop do
33
+ ensure_open!
34
+ return @queue.pop(true)
35
+ rescue ThreadError
36
+ remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
37
+ raise TimeoutError, 'operation timed out' if remaining <= 0
38
+
39
+ sleep([remaining, 0.001].min)
40
+ end
41
+ end
42
+
43
+ def close
44
+ @mutex.synchronize { @closed = true }
45
+ nil
46
+ end
47
+
48
+ private
49
+
50
+ def push_with_timeout(value, timeout)
51
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
52
+
53
+ loop do
54
+ ensure_open!
55
+ return @queue.push(value, true)
56
+ rescue ThreadError
57
+ remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
58
+ raise TimeoutError, 'operation timed out' if remaining <= 0
59
+
60
+ sleep([remaining, 0.001].min)
61
+ end
62
+ end
63
+
64
+ def push_until_available(value)
65
+ loop do
66
+ ensure_open!
67
+ return @queue.push(value, true)
68
+ rescue ThreadError
69
+ sleep 0.001
70
+ end
71
+ end
72
+
73
+ def ensure_open!
74
+ raise ClosedError, 'queue is closed' if @mutex.synchronize { @closed }
75
+ end
76
+ end
77
+ end
78
+ end