kubemq 1.0.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 (62) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +30 -0
  3. data/LICENSE +201 -0
  4. data/README.md +237 -0
  5. data/lib/kubemq/base_client.rb +180 -0
  6. data/lib/kubemq/cancellation_token.rb +63 -0
  7. data/lib/kubemq/channel_info.rb +84 -0
  8. data/lib/kubemq/configuration.rb +247 -0
  9. data/lib/kubemq/cq/client.rb +446 -0
  10. data/lib/kubemq/cq/command_message.rb +59 -0
  11. data/lib/kubemq/cq/command_received.rb +52 -0
  12. data/lib/kubemq/cq/command_response.rb +44 -0
  13. data/lib/kubemq/cq/command_response_message.rb +58 -0
  14. data/lib/kubemq/cq/commands_subscription.rb +45 -0
  15. data/lib/kubemq/cq/queries_subscription.rb +45 -0
  16. data/lib/kubemq/cq/query_message.rb +70 -0
  17. data/lib/kubemq/cq/query_received.rb +52 -0
  18. data/lib/kubemq/cq/query_response.rb +59 -0
  19. data/lib/kubemq/cq/query_response_message.rb +67 -0
  20. data/lib/kubemq/error_codes.rb +181 -0
  21. data/lib/kubemq/errors/error_mapper.rb +134 -0
  22. data/lib/kubemq/errors.rb +276 -0
  23. data/lib/kubemq/interceptors/auth_interceptor.rb +78 -0
  24. data/lib/kubemq/interceptors/error_mapping_interceptor.rb +75 -0
  25. data/lib/kubemq/interceptors/metrics_interceptor.rb +95 -0
  26. data/lib/kubemq/interceptors/retry_interceptor.rb +119 -0
  27. data/lib/kubemq/proto/kubemq_pb.rb +43 -0
  28. data/lib/kubemq/proto/kubemq_services_pb.rb +35 -0
  29. data/lib/kubemq/pubsub/client.rb +475 -0
  30. data/lib/kubemq/pubsub/event_message.rb +52 -0
  31. data/lib/kubemq/pubsub/event_received.rb +48 -0
  32. data/lib/kubemq/pubsub/event_send_result.rb +31 -0
  33. data/lib/kubemq/pubsub/event_sender.rb +112 -0
  34. data/lib/kubemq/pubsub/event_store_message.rb +53 -0
  35. data/lib/kubemq/pubsub/event_store_received.rb +47 -0
  36. data/lib/kubemq/pubsub/event_store_result.rb +33 -0
  37. data/lib/kubemq/pubsub/event_store_sender.rb +164 -0
  38. data/lib/kubemq/pubsub/events_store_subscription.rb +81 -0
  39. data/lib/kubemq/pubsub/events_subscription.rb +43 -0
  40. data/lib/kubemq/queues/client.rb +366 -0
  41. data/lib/kubemq/queues/downstream_receiver.rb +247 -0
  42. data/lib/kubemq/queues/queue_message.rb +99 -0
  43. data/lib/kubemq/queues/queue_message_received.rb +148 -0
  44. data/lib/kubemq/queues/queue_poll_request.rb +77 -0
  45. data/lib/kubemq/queues/queue_poll_response.rb +138 -0
  46. data/lib/kubemq/queues/queue_send_result.rb +49 -0
  47. data/lib/kubemq/queues/upstream_sender.rb +180 -0
  48. data/lib/kubemq/server_info.rb +57 -0
  49. data/lib/kubemq/subscription.rb +98 -0
  50. data/lib/kubemq/telemetry/otel.rb +64 -0
  51. data/lib/kubemq/telemetry/semconv.rb +51 -0
  52. data/lib/kubemq/transport/channel_manager.rb +212 -0
  53. data/lib/kubemq/transport/converter.rb +287 -0
  54. data/lib/kubemq/transport/grpc_transport.rb +411 -0
  55. data/lib/kubemq/transport/message_buffer.rb +105 -0
  56. data/lib/kubemq/transport/reconnect_manager.rb +111 -0
  57. data/lib/kubemq/transport/state_machine.rb +150 -0
  58. data/lib/kubemq/types.rb +80 -0
  59. data/lib/kubemq/validation/validator.rb +216 -0
  60. data/lib/kubemq/version.rb +6 -0
  61. data/lib/kubemq.rb +118 -0
  62. metadata +138 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: b9f13502c9e35bfc8fd7afb07b4d71d60c57d81647c41d63a11ae714d63bf630
4
+ data.tar.gz: f3cc0fb2fc0368aa2ab29ccef0c2fe3b7d27a173d6ca4f2102741fdf9fabad2e
5
+ SHA512:
6
+ metadata.gz: f17464da4de64259c476f4497f88b81557f0a32870456392b5bd7438f7c8f4a36e281c2e44b36b1eb8e8617d2396467dd139002ce01dc8141e9ee7232ae66dd1
7
+ data.tar.gz: 759f5ce7af864555d87b394b3cc603a37992a06fbf1fcd25d8972f2529eb7664b4e7bdfb4ff30fcf1c0687d2eb97861afe3abfa52f6837027369dc8cdef31f5c
data/CHANGELOG.md ADDED
@@ -0,0 +1,30 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project will be documented in this file.
4
+
5
+ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
+ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
+
8
+ ## [1.0.0] - 2026-04-02
9
+
10
+ ### Added
11
+
12
+ - Initial release of the official KubeMQ Ruby SDK (`kubemq` gem).
13
+ - **Events (Pub/Sub):** `PubSubClient`, `send_event`, `subscribe_to_events`, wildcard channels, consumer groups, streaming senders.
14
+ - **Events Store:** `send_event_store`, `subscribe_to_events_store` with replay start positions (first, last, new, sequence, time, time delta).
15
+ - **Queues — stream API:** `send_queue_message_stream`, `poll` with upstream/downstream streaming, ack/nack, transactions, policies (delay, expiration, dead letter).
16
+ - **Queues — simple API:** `send_queue_message`, `send_queue_messages_batch`, `receive_queue_messages`, peek, ack helpers.
17
+ - **Commands:** `CQClient#send_command`, `subscribe_to_commands`, `send_response`.
18
+ - **Queries:** `send_query`, `subscribe_to_queries`, optional cache key/TTL on queries.
19
+ - **Channel management:** `create_channel`, `delete_channel`, `list_channels`, `purge_queue_channel` via internal query pattern.
20
+ - **Core:** `Configuration` with TLS, keepalive, reconnect policy; `KubeMQ.configure`; ENV `KUBEMQ_ADDRESS`, `KUBEMQ_AUTH_TOKEN`.
21
+ - **Transport:** gRPC client with interceptors (auth, metrics, retry, error mapping), reconnect with exponential backoff and jitter, bounded buffer during disconnect.
22
+ - **Errors:** `KubeMQ::Error` hierarchy with gRPC status mapping, suggestions, and `retryable?`.
23
+ - **Cancellation:** `CancellationToken` for cooperative shutdown of subscriptions.
24
+ - **OpenTelemetry:** optional soft dependency for custom messaging spans.
25
+ - **Proto:** Ruby stubs for KubeMQ API **v1.4.0**, checked into `lib/kubemq/proto/`.
26
+ - **Testing:** RSpec unit and integration suites; SimpleCov minimum 95% line coverage (excluding generated proto).
27
+ - **Examples:** runnable samples under `examples/` (connection, pub/sub, events store, queues, commands, queries, management).
28
+ - **Burn-in:** standalone app under `burnin/` for soak testing and dashboard integration.
29
+
30
+ [1.0.0]: https://github.com/kubemq-io/kubemq-ruby/releases/tag/v1.0.0
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 KubeMQ
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,237 @@
1
+ # KubeMQ Ruby SDK
2
+
3
+ Official Ruby client for [KubeMQ](https://kubemq.io) — Events, Events Store, Queues (stream and simple APIs), Commands, and Queries over gRPC.
4
+
5
+ [![Gem Version](https://img.shields.io/gem/v/kubemq.svg)](https://rubygems.org/gems/kubemq)
6
+ [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE)
7
+ [![CI](https://github.com/kubemq-io/kubemq-ruby/actions/workflows/ci.yml/badge.svg)](https://github.com/kubemq-io/kubemq-ruby/actions/workflows/ci.yml)
8
+
9
+ ## Table of Contents
10
+
11
+ - [Installation](#installation)
12
+ - [Quick start](#quick-start)
13
+ - [Features](#features)
14
+ - [Configuration](#configuration)
15
+ - [Error handling](#error-handling)
16
+ - [Reconnection](#reconnection)
17
+ - [Examples](#examples)
18
+ - [Documentation](#documentation)
19
+ - [Contributing](#contributing)
20
+ - [License](#license)
21
+
22
+ ## Installation
23
+
24
+ Add to your `Gemfile`:
25
+
26
+ ```ruby
27
+ gem "kubemq", "~> 1.0"
28
+ ```
29
+
30
+ Then:
31
+
32
+ ```bash
33
+ bundle install
34
+ ```
35
+
36
+ Or install directly:
37
+
38
+ ```bash
39
+ gem install kubemq
40
+ ```
41
+
42
+ **Requirements:** Ruby **>= 3.1**, `grpc` **~> 1.65**, `google-protobuf` **~> 4.0**. See [COMPATIBILITY.md](COMPATIBILITY.md) for platforms and Ruby 4.0 limitations.
43
+
44
+ ## Quick start
45
+
46
+ All clients connect lazily on first use. Default address is `localhost:50000` unless you override configuration (see below).
47
+
48
+ ### Pub/Sub (Events)
49
+
50
+ ```ruby
51
+ require "kubemq"
52
+
53
+ client = KubeMQ::PubSubClient.new(address: "localhost:50000", client_id: "my-app")
54
+ client.send_event(
55
+ KubeMQ::PubSub::EventMessage.new(channel: "events.hello", body: "Hello, KubeMQ!")
56
+ )
57
+ client.close
58
+ ```
59
+
60
+ ### Queues (simple send / receive)
61
+
62
+ ```ruby
63
+ require "kubemq"
64
+
65
+ qc = KubeMQ::QueuesClient.new(address: "localhost:50000", client_id: "queue-worker")
66
+ msg = KubeMQ::Queues::QueueMessage.new(channel: "jobs", metadata: "type", body: "process-me")
67
+ qc.send_queue_message(msg)
68
+ received = qc.receive_queue_messages(channel: "jobs", max_messages: 1, wait_timeout_seconds: 5)
69
+ received.each { |m| puts m.body }
70
+ qc.close
71
+ ```
72
+
73
+ ### Commands (RPC)
74
+
75
+ Command and query **`timeout` values are in milliseconds** (proto-aligned).
76
+
77
+ ```ruby
78
+ require "kubemq"
79
+
80
+ cq = KubeMQ::CQClient.new(address: "localhost:50000", client_id: "cmd-client")
81
+ response = cq.send_command(
82
+ KubeMQ::CQ::CommandMessage.new(
83
+ channel: "commands",
84
+ metadata: "ping",
85
+ body: "hello",
86
+ timeout: 10_000
87
+ )
88
+ )
89
+ puts "executed=#{response.executed}, error=#{response.error}"
90
+ cq.close
91
+ ```
92
+
93
+ ### Queries (RPC, optional cache)
94
+
95
+ ```ruby
96
+ require "kubemq"
97
+
98
+ cq = KubeMQ::CQClient.new(address: "localhost:50000", client_id: "query-client")
99
+ response = cq.send_query(
100
+ KubeMQ::CQ::QueryMessage.new(
101
+ channel: "queries",
102
+ metadata: "lookup",
103
+ body: "key-1",
104
+ timeout: 10_000
105
+ )
106
+ )
107
+ puts "body=#{response.body}, cache_hit=#{response.cache_hit}"
108
+ cq.close
109
+ ```
110
+
111
+ Subscriptions (events, events store, commands, queries) run on a background thread and take a Ruby block; use `KubeMQ::CancellationToken` to stop them. See the `examples/` directory for full flows.
112
+
113
+ ## Features
114
+
115
+ - **Events** — Fire-and-forget pub/sub, wildcards, consumer groups, streaming batch senders
116
+ - **Events Store** — Durable events with replay from sequence, time, or position policies
117
+ - **Queues — stream** — Upstream/downstream streaming, poll, transactions, ack/nack, policies
118
+ - **Queues — simple** — Unary send/receive/batch helpers
119
+ - **Commands** — Request/response RPC with timeouts
120
+ - **Queries** — RPC with optional cache key / TTL
121
+ - **Channel management** — Create, delete, list, and purge queue channels
122
+ - **Auto-reconnect** — Exponential backoff with jitter; bounded buffer during outages (oldest dropped when full)
123
+ - **TLS / mTLS** — Via `Configuration#tls`
124
+ - **OpenTelemetry** — Optional instrumentation (soft dependency)
125
+
126
+ ## Configuration
127
+
128
+ Settings are resolved in this order (**highest precedence first**):
129
+
130
+ 1. Arguments passed to the client constructor (`address:`, `client_id:`, `auth_token:`, or a full `Configuration` object)
131
+ 2. Values set in `KubeMQ.configure { ... }`
132
+ 3. Environment variables, then built-in defaults
133
+
134
+ ### `KubeMQ.configure`
135
+
136
+ ```ruby
137
+ KubeMQ.configure do |c|
138
+ c.address = "kubemq.example.com:50000"
139
+ c.auth_token = ENV.fetch("KUBEMQ_AUTH_TOKEN", nil)
140
+ c.reconnect_policy.max_delay = 60.0
141
+ end
142
+
143
+ client = KubeMQ::PubSubClient.new # uses global configuration
144
+ ```
145
+
146
+ ### Environment variables
147
+
148
+ | Variable | Purpose |
149
+ | -------- | ------- |
150
+ | `KUBEMQ_ADDRESS` | Broker host:port (default `localhost:50000`) |
151
+ | `KUBEMQ_AUTH_TOKEN` | Optional bearer token sent as gRPC metadata |
152
+
153
+ ### Common defaults (`KubeMQ::Configuration`)
154
+
155
+ | Field | Default | Notes |
156
+ | ----- | ------- | ----- |
157
+ | `address` | `ENV["KUBEMQ_ADDRESS"]` or `localhost:50000` | |
158
+ | `client_id` | Auto-generated id | Prefix `kubemq-ruby-` + random hex |
159
+ | `auth_token` | `ENV["KUBEMQ_AUTH_TOKEN"]` | |
160
+ | `tls` | `TLSConfig` (disabled by default) | Client cert, key, CA, `insecure_skip_verify` |
161
+ | `keepalive` | 10s ping, 5s timeout, `permit_without_calls: true` | |
162
+ | `reconnect_policy` | Enabled, 1s base, 2x multiplier, 30s max, 25% jitter, unlimited attempts (`max_attempts: 0`) | |
163
+ | `max_send_size` / `max_receive_size` | 100 MB each | Client-side gRPC limits |
164
+ | `log_level` | `:warn` | |
165
+
166
+ Queue **`wait_timeout_seconds`** and related simple-API timeouts use **seconds**. Command/query **`timeout`** uses **milliseconds**.
167
+
168
+ ## Error handling
169
+
170
+ All SDK errors inherit `KubeMQ::Error`. Rescue the base type for generic handling, or specific subclasses for targeted logic.
171
+
172
+ ```ruby
173
+ begin
174
+ client.send_event(msg)
175
+ rescue KubeMQ::ValidationError => e
176
+ warn e.suggestion
177
+ rescue KubeMQ::TimeoutError => e
178
+ retry if e.retryable?
179
+ rescue KubeMQ::Error => e
180
+ warn "#{e.class}: #{e.message}"
181
+ end
182
+ ```
183
+
184
+ **Hierarchy (overview):**
185
+
186
+ - `KubeMQ::Error` — base; `#retryable?`, `#code`, `#suggestion`, context fields
187
+ - `KubeMQ::ConnectionError` — connectivity / transport
188
+ - `KubeMQ::AuthenticationError` — auth failures
189
+ - `KubeMQ::TimeoutError` — deadlines exceeded
190
+ - `KubeMQ::ValidationError` — invalid arguments
191
+ - `KubeMQ::ConfigurationError` — invalid config
192
+ - `KubeMQ::ChannelError` — channel-level broker errors
193
+ - `KubeMQ::MessageError` — malformed or rejected messages
194
+ - `KubeMQ::TransactionError` — queue transaction failures
195
+ - `KubeMQ::ClientClosedError` — use after `close`
196
+ - `KubeMQ::ConnectionNotReadyError` — operation before ready
197
+ - `KubeMQ::StreamBrokenError` — broken streaming call (`#unacked_message_ids` where applicable)
198
+ - `KubeMQ::BufferFullError` — reconnect buffer saturated (`#buffer_size`)
199
+ - `KubeMQ::CancellationError` — cooperative cancel
200
+
201
+ gRPC `GRPC::BadStatus` is mapped where appropriate; prefer rescuing `KubeMQ::Error` in application code.
202
+
203
+ ## Reconnection
204
+
205
+ When `reconnect_policy.enabled` is true (default), the transport automatically reconnects after transient failures using exponential backoff (capped by `max_delay`) and jitter. While disconnected, outbound traffic uses a bounded buffer (capacity 1000); when full, **oldest** messages are dropped — same behavior as other official KubeMQ SDKs.
206
+
207
+ Streaming consumers are restarted after reconnect; **queue downstream transactions** are not replayed automatically — a new poll stream is established and server visibility timeouts apply.
208
+
209
+ Call `close` on clients for a clean shutdown; `close` is idempotent.
210
+
211
+ ## Examples
212
+
213
+ Runnable scripts live under the `examples/` directory:
214
+
215
+ - `examples/connection/` — TLS, mTLS, auth, ping, close
216
+ - `examples/pubsub/`, `examples/events_store/`
217
+ - `examples/queues_simple/`, `examples/queues_stream/`
218
+ - `examples/commands/`, `examples/queries/`
219
+ - `examples/management/` — channels and purge
220
+
221
+ Set `KUBEMQ_ADDRESS` if your broker is not on `localhost:50000`.
222
+
223
+ ## Documentation
224
+
225
+ - **Guides:** See the [docs/](docs/) directory for comprehensive guides.
226
+ - **YARD API Reference:** `bundle exec yard doc && open doc/index.html`
227
+ - **KubeMQ Documentation:** [https://docs.kubemq.io](https://docs.kubemq.io)
228
+ - **KubeMQ Website:** [https://kubemq.io](https://kubemq.io)
229
+ - **Community & Support:** [GitHub Issues](https://github.com/kubemq-io/kubemq-ruby/issues)
230
+
231
+ ## Contributing
232
+
233
+ See [CONTRIBUTING.md](CONTRIBUTING.md) for setup, `rake proto:generate`, tests, and the release process.
234
+
235
+ ## License
236
+
237
+ Licensed under the **Apache License 2.0**. See [LICENSE](LICENSE).
@@ -0,0 +1,180 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'securerandom'
4
+
5
+ module KubeMQ
6
+ # Base class for all KubeMQ client types.
7
+ #
8
+ # Provides shared connection management, channel CRUD operations, and
9
+ # lifecycle methods. Not intended for direct instantiation — use
10
+ # {PubSubClient}, {QueuesClient}, or {CQClient} instead.
11
+ #
12
+ # @note This class is thread-safe. The underlying transport and state are
13
+ # protected by a mutex.
14
+ #
15
+ # @see PubSubClient
16
+ # @see QueuesClient
17
+ # @see CQClient
18
+ class BaseClient
19
+ # @!attribute [r] config
20
+ # @return [Configuration] the client's resolved configuration
21
+ # @!attribute [r] transport
22
+ # @return [Transport::GrpcTransport] the underlying gRPC transport
23
+ attr_reader :config, :transport
24
+
25
+ # Creates a new client connected to a KubeMQ broker.
26
+ #
27
+ # Connection is established lazily on first use, not during initialization.
28
+ # Pass individual options or a pre-built {Configuration} object.
29
+ #
30
+ # @param address [String, nil] broker host:port (default: from config or +localhost:50000+)
31
+ # @param client_id [String, nil] unique identifier for this client (auto-generated if nil)
32
+ # @param auth_token [String, nil] bearer token for authentication
33
+ # @param config [Configuration, nil] pre-built configuration (overrides individual options)
34
+ # @param transport [Transport::GrpcTransport, nil] custom transport (for testing)
35
+ # @param options [Hash] additional options forwarded to {Configuration}
36
+ #
37
+ # @raise [ConfigurationError] if the resolved configuration is invalid
38
+ #
39
+ # @example
40
+ # client = KubeMQ::PubSubClient.new(
41
+ # address: "localhost:50000",
42
+ # client_id: "my-publisher"
43
+ # )
44
+ def initialize(address: nil, client_id: nil, auth_token: nil, config: nil, transport: nil, **options)
45
+ @config = config || Configuration.new(
46
+ address: address,
47
+ client_id: client_id,
48
+ auth_token: auth_token,
49
+ **options
50
+ )
51
+ @config.validate!
52
+ @transport = transport || Transport::GrpcTransport.new(@config)
53
+ @closed = false
54
+ @mutex = Mutex.new
55
+ end
56
+
57
+ # Pings the KubeMQ broker and returns server information.
58
+ #
59
+ # @return [ServerInfo] broker host, version, and uptime
60
+ #
61
+ # @raise [ClientClosedError] if the client has been closed
62
+ # @raise [ConnectionError] if unable to reach the broker
63
+ #
64
+ # @example
65
+ # info = client.ping
66
+ # puts "Connected to #{info.host} v#{info.version}"
67
+ def ping
68
+ ensure_not_closed!
69
+ @transport.ensure_connected!
70
+ @transport.ping
71
+ end
72
+
73
+ # Closes the client and releases all resources.
74
+ #
75
+ # Cancels active subscriptions, flushes the message buffer, and closes the
76
+ # gRPC channel. This method is idempotent — calling it multiple times is safe.
77
+ #
78
+ # @return [void]
79
+ def close
80
+ @mutex.synchronize { @closed = true }
81
+ @transport.close
82
+ end
83
+
84
+ # Returns whether the client has been closed.
85
+ #
86
+ # @return [Boolean] +true+ if {#close} has been called or the transport is closed
87
+ def closed?
88
+ @mutex.synchronize { @closed } || @transport.closed?
89
+ end
90
+
91
+ # Creates a channel on the KubeMQ broker.
92
+ #
93
+ # @param channel_name [String] name for the new channel
94
+ # @param channel_type [String] one of {ChannelType}::EVENTS, EVENTS_STORE,
95
+ # COMMANDS, QUERIES, QUEUES
96
+ #
97
+ # @return [Boolean] +true+ on success
98
+ #
99
+ # @raise [ClientClosedError] if the client has been closed
100
+ # @raise [ConnectionError] if unable to reach the broker
101
+ # @raise [ChannelError] if the broker rejects the operation
102
+ # @raise [ValidationError] if +channel_name+ is invalid
103
+ #
104
+ # @see ChannelType
105
+ def create_channel(channel_name:, channel_type:)
106
+ ensure_not_closed!
107
+ @transport.ensure_connected!
108
+ Transport::ChannelManager.create_channel(
109
+ @transport, @config.client_id, channel_name, channel_type
110
+ )
111
+ end
112
+
113
+ # Deletes a channel from the KubeMQ broker.
114
+ #
115
+ # @param channel_name [String] name of the channel to delete
116
+ # @param channel_type [String] one of {ChannelType} constants
117
+ #
118
+ # @return [Boolean] +true+ on success
119
+ #
120
+ # @raise [ClientClosedError] if the client has been closed
121
+ # @raise [ConnectionError] if unable to reach the broker
122
+ # @raise [ChannelError] if the broker rejects the operation
123
+ def delete_channel(channel_name:, channel_type:)
124
+ ensure_not_closed!
125
+ @transport.ensure_connected!
126
+ Transport::ChannelManager.delete_channel(
127
+ @transport, @config.client_id, channel_name, channel_type
128
+ )
129
+ end
130
+
131
+ # Lists channels of the specified type, with optional name filtering.
132
+ #
133
+ # @param channel_type [String] one of {ChannelType} constants
134
+ # @param search [String, nil] substring filter for channel names
135
+ #
136
+ # @return [Array<ChannelInfo>] matching channels with metadata
137
+ #
138
+ # @raise [ClientClosedError] if the client has been closed
139
+ # @raise [ConnectionError] if unable to reach the broker
140
+ # @raise [ChannelError] if the broker rejects the operation
141
+ #
142
+ # @example
143
+ # channels = client.list_channels(channel_type: KubeMQ::ChannelType::EVENTS)
144
+ # channels.each { |ch| puts "#{ch.name} active=#{ch.active?}" }
145
+ def list_channels(channel_type:, search: nil)
146
+ ensure_not_closed!
147
+ @transport.ensure_connected!
148
+ Transport::ChannelManager.list_channels(
149
+ @transport, @config.client_id, channel_type, search
150
+ )
151
+ end
152
+
153
+ # Purges all messages from a queue channel.
154
+ #
155
+ # @param channel_name [String] queue channel to purge
156
+ #
157
+ # @return [Hash] +{ affected_messages: Integer }+
158
+ #
159
+ # @raise [ClientClosedError] if the client has been closed
160
+ # @raise [ChannelError] if the broker rejects the operation
161
+ def purge_queue_channel(channel_name:)
162
+ ensure_not_closed!
163
+ @transport.ensure_connected!
164
+ Transport::ChannelManager.purge_queue(
165
+ @transport, @config.client_id, channel_name
166
+ )
167
+ end
168
+
169
+ private
170
+
171
+ def ensure_not_closed!
172
+ raise ClientClosedError if closed?
173
+ end
174
+
175
+ def ensure_connected!
176
+ ensure_not_closed!
177
+ @transport.ensure_connected!
178
+ end
179
+ end
180
+ end