hotkv 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 (52) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +202 -0
  3. data/NOTICE +6 -0
  4. data/README.md +459 -0
  5. data/SECURITY.md +30 -0
  6. data/lib/hotkv/ai/call_result.rb +25 -0
  7. data/lib/hotkv/ai/prompt_cache.rb +135 -0
  8. data/lib/hotkv/ai/semantic_cache.rb +66 -0
  9. data/lib/hotkv/client.rb +201 -0
  10. data/lib/hotkv/cluster/crc16.rb +43 -0
  11. data/lib/hotkv/cluster.rb +184 -0
  12. data/lib/hotkv/commands/admin.rb +36 -0
  13. data/lib/hotkv/commands/all.rb +49 -0
  14. data/lib/hotkv/commands/bitmaps.rb +52 -0
  15. data/lib/hotkv/commands/geo.rb +146 -0
  16. data/lib/hotkv/commands/hashes.rb +169 -0
  17. data/lib/hotkv/commands/hyperloglog.rb +21 -0
  18. data/lib/hotkv/commands/keys.rb +170 -0
  19. data/lib/hotkv/commands/lists.rb +113 -0
  20. data/lib/hotkv/commands/probabilistic.rb +23 -0
  21. data/lib/hotkv/commands/publishing.rb +46 -0
  22. data/lib/hotkv/commands/scan.rb +82 -0
  23. data/lib/hotkv/commands/scripting.rb +128 -0
  24. data/lib/hotkv/commands/server.rb +175 -0
  25. data/lib/hotkv/commands/sets.rb +75 -0
  26. data/lib/hotkv/commands/sorted_sets.rb +258 -0
  27. data/lib/hotkv/commands/streams.rb +207 -0
  28. data/lib/hotkv/commands/strings.rb +178 -0
  29. data/lib/hotkv/commands/support.rb +69 -0
  30. data/lib/hotkv/connection.rb +221 -0
  31. data/lib/hotkv/errors.rb +145 -0
  32. data/lib/hotkv/extensions.rb +118 -0
  33. data/lib/hotkv/future.rb +55 -0
  34. data/lib/hotkv/llm_price.rb +53 -0
  35. data/lib/hotkv/namespaces/admin.rb +261 -0
  36. data/lib/hotkv/namespaces/amem.rb +172 -0
  37. data/lib/hotkv/namespaces/caching.rb +397 -0
  38. data/lib/hotkv/namespaces/core.rb +190 -0
  39. data/lib/hotkv/namespaces/ops.rb +166 -0
  40. data/lib/hotkv/namespaces/probabilistic.rb +180 -0
  41. data/lib/hotkv/namespaces/rag.rb +63 -0
  42. data/lib/hotkv/pipeline.rb +57 -0
  43. data/lib/hotkv/pool.rb +123 -0
  44. data/lib/hotkv/pubsub.rb +60 -0
  45. data/lib/hotkv/resp.rb +176 -0
  46. data/lib/hotkv/transaction.rb +115 -0
  47. data/lib/hotkv/url.rb +100 -0
  48. data/lib/hotkv/usage.rb +42 -0
  49. data/lib/hotkv/version.rb +7 -0
  50. data/lib/hotkv/wire.rb +145 -0
  51. data/lib/hotkv.rb +28 -0
  52. metadata +137 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 78813ce1de713ea3d5d8cf3995236fe16330ce7fd619946a5603dd2e7c8af93a
4
+ data.tar.gz: e0227c91f5791c9d2a11120d963ab8fb1f0b50bcaf8f994c1c83c6fe9be931a2
5
+ SHA512:
6
+ metadata.gz: de22cd020a446f1683b757b2e86fb99bf87af9e3773d50b5bd99b06643111adc0c5c4ebdd5d27102d3e4c9a5b783df080340ff00816931572fa9263fa7634773
7
+ data.tar.gz: 7391725a1fe8a8d039528687ae8146b4f60da95a7627948b0fdd60661c98caffaf2e77f8933d7d3dd91c9957c724a674eacbcfb6220eb61af9f27e9a53cd807a
data/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
data/NOTICE ADDED
@@ -0,0 +1,6 @@
1
+ the HotKV Ruby client
2
+ Copyright (c) 2026 HotKV Ltd.
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
5
+ "HotKV" and the HotKV logo are trademarks of HotKV Ltd. The license does not grant
6
+ permission to use them, except to describe where the software comes from.
data/README.md ADDED
@@ -0,0 +1,459 @@
1
+ # HotKV Ruby Client
2
+
3
+ [![CI](https://github.com/hotkv-ltd/hotkv-ruby-client/actions/workflows/ci.yml/badge.svg)](https://github.com/hotkv-ltd/hotkv-ruby-client/actions/workflows/ci.yml)
4
+ [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE)
5
+
6
+ A high-performance Ruby client for [HotKV](https://hotkv.com), a RESP2/RESP3-compatible
7
+ in-memory data store with built-in AI and LLM-serving features (semantic and prompt
8
+ caching, agent memory, RAG, feature store, rate limiting, time series and more).
9
+
10
+ Zero runtime dependencies (only Ruby's own socket, openssl, digest and json standard library).
11
+
12
+ ## Install
13
+
14
+ Add it to your Gemfile:
15
+
16
+ ```ruby
17
+ gem "hotkv"
18
+ ```
19
+
20
+ or install it directly:
21
+
22
+ ```
23
+ gem install hotkv
24
+ ```
25
+
26
+ Requires Ruby 3.0 or newer. Built and verified against HotKV server
27
+ v0.3.0 (see [Compatibility](#compatibility)).
28
+
29
+ The gem is built from this repository with `gem build hotkv.gemspec`; a
30
+ `v*` tag runs the publish workflow (`.github/workflows/publish.yml`) that
31
+ pushes it to RubyGems. Until a release has been published, install from a
32
+ checkout: `gem build hotkv.gemspec && gem install ./hotkv-*.gem`.
33
+
34
+ ## Quick start
35
+
36
+ ```ruby
37
+ require "hotkv"
38
+
39
+ client = HotKV::Client.new(url: "hotkv://localhost:6379")
40
+
41
+ client.set("greeting", "hello")
42
+ client.get("greeting") # => "hello"
43
+
44
+ client.close
45
+ ```
46
+
47
+ ## Connection options
48
+
49
+ `HotKV::Client.new` takes a `url:` and/or keyword options; an explicit
50
+ keyword always overrides whatever the URL carried for the same setting.
51
+
52
+ ```ruby
53
+ client = HotKV::Client.new(
54
+ url: "hotkv://localhost:6379",
55
+ username: "app",
56
+ password: ENV.fetch("HOTKV_PASSWORD"),
57
+ db: 2,
58
+ client_name: "billing-service",
59
+ connect_timeout: 5.0, # seconds; nil disables the timeout
60
+ command_timeout: nil, # seconds; nil (the default) never times out a
61
+ # command client side, which matters for
62
+ # blocking commands like BLPOP
63
+ pool_size: 10,
64
+ idle_timeout: 300, # seconds a pooled connection may sit idle
65
+ # before it is PINGed on next checkout
66
+ pool_timeout: 5.0 # seconds to wait for a free pooled connection
67
+ )
68
+ ```
69
+
70
+ Accepted URL schemes: `hotkv://`, `hotkvs://` (TLS), and, for drop in
71
+ migration from a Redis client, `redis://` / `rediss://`. Unix sockets use
72
+ `hotkv+unix:///path/to/socket`. `hotkv://user:pass@host:port/3` sets
73
+ username, password and the database index.
74
+
75
+ ### TLS
76
+
77
+ ```ruby
78
+ client = HotKV::Client.new(
79
+ url: "hotkvs://localhost:6379",
80
+ ca_file: "/etc/ssl/certs/hotkv-ca.pem",
81
+ cert_file: "/etc/ssl/certs/client.pem", # optional client certificate
82
+ key_file: "/etc/ssl/private/client.key",
83
+ server_name: "hotkv.internal" # SNI / hostname verification override
84
+ )
85
+
86
+ # Tests only: skip certificate verification entirely.
87
+ HotKV::Client.new(url: "hotkvs://localhost:6379", insecure_skip_verify: true)
88
+ ```
89
+
90
+ ### Pooling
91
+
92
+ Every `HotKV::Client` keeps a bounded, thread safe connection pool
93
+ (`pool_size`, default 5). Each command checks a connection out, runs, and
94
+ returns it; idle connections older than `idle_timeout` seconds are health
95
+ checked with `PING` before being handed out again. One client instance is
96
+ safe to share across threads.
97
+
98
+ ## Pipelines
99
+
100
+ Batch many commands into a single round trip. A command that fails does
101
+ not abort the batch: its slot in the result Array holds the `HotKV::Error`
102
+ instance instead.
103
+
104
+ ```ruby
105
+ results = client.pipelined do |p|
106
+ p.set("a", "1")
107
+ p.incr("a")
108
+ p.get("a")
109
+ end
110
+ results # => ["OK", 2, "2"]
111
+ ```
112
+
113
+ ## Transactions
114
+
115
+ `multi` runs a server side MULTI/EXEC block on one connection:
116
+
117
+ ```ruby
118
+ result = client.multi do |tx|
119
+ tx.set("balance", "100")
120
+ tx.decrby("balance", "30")
121
+ end
122
+ result # => ["OK", 70]
123
+ ```
124
+
125
+ `watch` holds one connection for optimistic locking: read on it to decide,
126
+ then call `multi` on the same session to commit. `EXEC` returns nil (and so
127
+ does `multi`) if a watched key changed first.
128
+
129
+ ```ruby
130
+ result = client.watch("balance") do |w|
131
+ current = w.get("balance").to_i
132
+ w.multi do |tx|
133
+ tx.set("balance", (current - 30).to_s)
134
+ end
135
+ end
136
+
137
+ if result.nil?
138
+ # someone else changed "balance" first; retry
139
+ end
140
+ ```
141
+
142
+ ## Pub/Sub
143
+
144
+ `subscribe`, `psubscribe` and `ssubscribe` open a dedicated connection and
145
+ block the calling thread, dispatching frames to callbacks:
146
+
147
+ ```ruby
148
+ client.subscribe("orders") do |on|
149
+ on.subscribe { |channel, count| puts "listening on #{channel} (#{count} total)" }
150
+ on.message do |channel, payload|
151
+ puts "#{channel}: #{payload}"
152
+ on.unsubscribe if payload == "stop" # ends the loop once confirmed
153
+ end
154
+ end
155
+ ```
156
+
157
+ Run it in its own `Thread` if you need the rest of your program to keep
158
+ going; `on.unsubscribe`/`on.punsubscribe`/`on.sunsubscribe` (called with no
159
+ block) end the loop from inside a callback.
160
+
161
+ ## Cluster
162
+
163
+ `HotKV::Cluster` discovers the slot map with `CLUSTER SLOTS`, routes each
164
+ command by its key's CRC16 slot (with `{hash tag}` support), and follows
165
+ `MOVED` (refreshing the map) and `ASK` (sending `ASKING` first)
166
+ automatically. It exposes the exact same typed command methods as
167
+ `HotKV::Client`.
168
+
169
+ ```ruby
170
+ cluster = HotKV::Cluster.new(urls: ["hotkv://node-a:6379", "hotkv://node-b:6379"])
171
+ cluster.set("user:42", "active")
172
+ cluster.get("user:42")
173
+ cluster.close
174
+ ```
175
+
176
+ Against a server that is not running in cluster mode, `HotKV::Cluster`
177
+ simply routes every command to the configured seed node(s), so the same
178
+ client also works for local development against a single server.
179
+
180
+ ## HotKV exclusive commands
181
+
182
+ The HotKV specific command families (tags, nanosecond TTLs, GCRA and
183
+ token bucket rate limiting, vector search, time series, feature store,
184
+ semantic/prompt/tool/negative/guard/rerank caches, agent memory, RAG, LLM
185
+ stats and budgets, prompt registry, embedding dedup, tenancy, IAM, audit,
186
+ encryption and replication control) have typed, namespaced helpers
187
+ returning Hash/Struct results:
188
+
189
+ ```ruby
190
+ client.tag.set("doc:1", "vip", "beta")
191
+ client.tag.members("vip") # => ["doc:1", ...]
192
+
193
+ client.nexpire("doc:1", 5_000_000_000) # nanosecond resolution TTL
194
+
195
+ client.ts.create("cpu.load", retention: 86_400_000)
196
+ client.ts.add("cpu.load", 0.42)
197
+ client.ts.range("cpu.load", "-", "+")
198
+
199
+ client.ratelimit.create("api", 100, 60_000)
200
+ client.ratelimit.check("api", "user:42") # => {allowed:, remaining:, ...}
201
+
202
+ client.vsim.createindex("docs", 384)
203
+ client.vsim.set("docs", "doc:1", embedding)
204
+ client.vsim.search("docs", 5, query_embedding)
205
+ ```
206
+
207
+ Enterprise features need a server license that includes them; a command
208
+ whose feature is not licensed raises `HotKV::Error::NotLicensedError`,
209
+ distinct from every other server error so you can detect and handle it
210
+ (for example, to fall back to a simpler code path).
211
+
212
+ ## AI caching
213
+
214
+ `HotKV::AI::PromptCache` builds a deterministic cache key from provider,
215
+ model, the normalized messages/system prompt and generation parameters (so
216
+ the exact same call always hits, across processes and restarts), and only
217
+ calls your LLM on a miss:
218
+
219
+ ```ruby
220
+ prompt_cache = HotKV::AI::PromptCache.new(client, namespace: "chat", stats_bucket: "chat-llm")
221
+
222
+ messages = [{ role: "user", content: "Summarize the HotKV pooling model in one sentence." }]
223
+
224
+ result = prompt_cache.get_or_call(
225
+ provider: "openai",
226
+ model: "gpt-4o",
227
+ messages: messages,
228
+ params: { "temperature" => "0.2" } # generation params are always string valued
229
+ ) do
230
+ # This block only runs on a cache miss.
231
+ response = openai_client.chat(model: "gpt-4o", messages: messages, temperature: 0.2)
232
+ prompt_cache.record_usage(
233
+ input_tokens: response.usage.prompt_tokens,
234
+ output_tokens: response.usage.completion_tokens,
235
+ cost_usd: response.usage.estimated_cost_usd,
236
+ latency_ms: response.latency_ms
237
+ )
238
+ response.text
239
+ end
240
+
241
+ result[:response] # the (cached or freshly generated) text
242
+ result[:cache_hit] # true if this call never touched the LLM
243
+ ```
244
+
245
+ `HotKV::AI::SemanticCache` looks up the nearest cached answer above a
246
+ similarity threshold for a caller supplied embedding vector (the SDK never
247
+ computes embeddings itself, so it works with any provider):
248
+
249
+ ```ruby
250
+ semantic_cache = HotKV::AI::SemanticCache.new(client, dims: 1536, namespace: "faq", threshold: 0.9)
251
+
252
+ question = "How do I enable TLS?"
253
+ embedding = embeddings_client.embed(question)
254
+
255
+ result = semantic_cache.get_or_call(question, embedding) do
256
+ llm_client.answer(question) # only called on a miss
257
+ end
258
+ result[:response]
259
+ ```
260
+
261
+ Both helpers are provider neutral: they never depend on any particular
262
+ LLM or embeddings SDK.
263
+
264
+ **Recording usage so hits report savings**: `get_or_call`'s block may
265
+ return either just the response, or a `[response, usage]` pair (a
266
+ `HotKV::TokenUsage`, the original call's token usage). When it does, that
267
+ usage is stored with the cache entry, so a later hit attributes its
268
+ tokens, and once the model is priced, their exact cost, to the
269
+ namespace's `usage_saved_*` stats:
270
+
271
+ ```ruby
272
+ result = prompt_cache.get_or_call(provider: "anthropic", model: "claude-sonnet-5", messages: messages) do
273
+ response = my_llm_client.chat(model: "claude-sonnet-5", messages: messages)
274
+ usage = HotKV::TokenUsage.new(
275
+ model: "claude-sonnet-5",
276
+ input_tokens: response.usage.input_tokens,
277
+ output_tokens: response.usage.output_tokens
278
+ )
279
+ [response.text, usage] # get_or_call stores `usage` on a miss
280
+ end
281
+ prompt_cache.stats # usage_saved_requests, usage_saved_input_tokens, ..., usage_saved_cost_usd
282
+ ```
283
+
284
+ ## LLM cost tracking
285
+
286
+ `client.llmstats` and `client.llmbudget` track token usage and cost
287
+ independently of caching, e.g. across every call your application makes to
288
+ a given model:
289
+
290
+ ```ruby
291
+ client.llmstats.bucket("chat")
292
+ client.llmstats.record("chat", 100, 20, 0, 0, 120.5, model: "claude-sonnet-5")
293
+ # cost_usd (the 5th argument, 0 above) is ignored and priced by the server when `model` is given
294
+ client.llmstats.get("chat") # requests, cost_usd, cache_write_5m_tokens, ...
295
+
296
+ # Custom pricing for a model not in HotKV's built-in price table
297
+ client.llmstats.price_set("my-fine-tuned-model", 2, 8) # USD per 1,000,000 input/output tokens
298
+ client.llmstats.price_get("my-fine-tuned-model")
299
+
300
+ client.llmbudget.set("team-alpha", 1_000_000, 50.0, 86_400)
301
+ allowed = client.llmbudget.consume(
302
+ "team-alpha", usage: HotKV::TokenUsage.new(model: "claude-sonnet-5", input_tokens: 100, output_tokens: 20)
303
+ )
304
+ ```
305
+
306
+ For OpenAI style responses, whose `prompt_tokens` already includes cache
307
+ hits, pass `prompt_tokens - cached_tokens` as `record`'s `input_tokens`
308
+ argument (`cached_tokens` is always cache-READ tokens, unlike Anthropic,
309
+ which reports it separately).
310
+
311
+ ## Command coverage
312
+
313
+ Typed methods cover strings, keys/expiry, lists, sets, hashes (including
314
+ per field TTL and the newer `HGETDEL`/`HGETEX`/`HSETEX`), sorted sets,
315
+ streams (including `XSETID`, `XCFGSET` and idempotent `XADD`), geospatial,
316
+ bitmaps, HyperLogLog, Bloom/Count-Min/Top-K (`client.bf`, `client.cms`,
317
+ `client.topk`), Pub/Sub publishing and introspection, Lua scripting and
318
+ functions, `SORT`, ACL, the commonly used server and `CLIENT` commands and
319
+ the `SCAN` family (`scan_each`, `hscan_each`, `sscan_each`, `zscan_each`
320
+ return Ruby Enumerators). The newer `MSETEX`, `DELEX`, `DIGEST` and
321
+ `SET ... IFEQ/IFNE/IFDEQ/IFDNE` are typed too.
322
+
323
+ This is **not** every command. Commands without a typed method go through
324
+ the generic `command` method; the main groups are:
325
+
326
+ - `CLIENT TRACKING`/`CACHING`/`GETREDIR`/`TRACKINGINFO`/`REPLY` (they
327
+ change how a connection behaves, so they need a dedicated connection),
328
+ - every `CLUSTER` subcommand, `CLUSTERSCAN`, `SFLUSH`, `TRIMSLOTS`,
329
+ `MIGRATE`, `READONLY`/`READWRITE`,
330
+ - `HIMPORT` (its state lives on one connection),
331
+ - `LATENCY`, `MODULE`, `MONITOR`, `DEBUG`, `REPLICAOF`, `SHUTDOWN`,
332
+ `FAILOVER` and most `MEMORY` subcommands,
333
+ - the internal `*.SYNC` replication helpers.
334
+
335
+ Every one of them is reachable through the generic method, which sends the
336
+ arguments as given (Strings are sent byte for byte) and returns the decoded
337
+ reply:
338
+
339
+ ```ruby
340
+ client.command("LOLWUT")
341
+ client.execute("OBJECT", "HELP") # alias
342
+ client.command("CLUSTER", "KEYSLOT", "user:42")
343
+
344
+ # Connection scoped state needs one connection: run it in a pipeline.
345
+ client.pipelined do |p|
346
+ p.command("HIMPORT", "PREPARE", "user", "name", "age")
347
+ p.command("HIMPORT", "SET", "user:1", "user", "Ada", "36")
348
+ end
349
+ ```
350
+
351
+ ### Numbers
352
+
353
+ Floats are always sent as plain decimal text (`HotKV::Wire.float`): Ruby's
354
+ `1.0e-05` goes out as `0.00001`, so values the server's stricter parsers
355
+ refuse in exponent form (for example `LLMBUDGET.SET`'s cost limit, which is
356
+ a fixed point amount) work. Infinity is sent as `inf`/`-inf` where the
357
+ server takes it (sorted set scores); NaN, and infinity where only finite
358
+ numbers are valid (`INCRBYFLOAT`, coordinates, vector components,
359
+ thresholds), raise `HotKV::Error::ArgumentError` before anything is sent.
360
+ Money amounts (`llmbudget.set`, `llmstats.price_set`) are rounded to the
361
+ micro dollar the server stores, and an amount too small to survive that
362
+ rounding raises instead of silently becoming 0.
363
+
364
+ ### Replica reads
365
+
366
+ `HotKV::Cluster` sends every command to the node that owns the key's slot.
367
+ Reading from replicas (`READONLY`) is not supported, and passing
368
+ `readonly:` or `read_from:` raises `HotKV::Error::ArgumentError` instead of
369
+ being ignored. Point a separate `HotKV::Client` at a replica for read
370
+ only traffic.
371
+
372
+ ## Error handling
373
+
374
+ Every server error raises a typed subclass of `HotKV::Error::ServerError`
375
+ (itself under `HotKV::Error::Base`), keyed off the server's error prefix:
376
+ `HotKV::Error::WrongTypeError`, `NoAuthError`, `NotLicensedError`,
377
+ `ReadOnlyError`, `MovedError`/`AskError` (cluster redirects), and a generic
378
+ `CommandError` for anything else. Connection, timeout and protocol level
379
+ failures raise `HotKV::Error::ConnectionError`, `TimeoutError` and
380
+ `ProtocolError` respectively.
381
+
382
+ ```ruby
383
+ begin
384
+ client.set("readonly-key", "value")
385
+ rescue HotKV::Error::NotLicensedError => e
386
+ logger.warn("HotKV feature not licensed: #{e.message}")
387
+ rescue HotKV::Error::ConnectionError => e
388
+ logger.error("HotKV unreachable: #{e.message}")
389
+ end
390
+ ```
391
+
392
+ A `nil` bulk reply (a missing key, a cache miss, ...) is always a plain
393
+ Ruby `nil`, never an exception.
394
+
395
+ ## Testing
396
+
397
+ Unit tests need no server:
398
+
399
+ ```
400
+ bundle install
401
+ bundle exec rake test:unit
402
+ ```
403
+
404
+ Integration tests run against a real HotKV server, reached through
405
+ `HOTKV_TEST_URL`, and are skipped automatically when that variable is
406
+ unset:
407
+
408
+ ```
409
+ HOTKV_TEST_URL=hotkv://127.0.0.1:6379 bundle exec rake test:integration
410
+ HOTKV_TEST_RESP3=0 HOTKV_TEST_URL=... bundle exec rake test:integration # over RESP2
411
+ ```
412
+
413
+ `bundle exec rake test` runs both. Integration tests for an enterprise
414
+ feature your license does not include skip themselves with a clear reason
415
+ (detecting `HotKV::Error::NotLicensedError`) rather than failing. The
416
+ suite uses unique key and namespace names and cleans up after itself, but
417
+ use a server you do not mind it writing to; the `FLUSHDB`/`SWAPDB` tests
418
+ touch only databases 13 to 15.
419
+
420
+ Further opt-in runs:
421
+
422
+ - `HOTKV_REMOTE_HOST` (with `HOTKV_REMOTE_PORT`, `HOTKV_REMOTE_PASSWORD`,
423
+ `HOTKV_REMOTE_CA`) runs `test/integration/remote_server_test.rb`, a
424
+ customer style session against a TLS and password protected server.
425
+
426
+ ## Compatibility
427
+
428
+ Developed and tested against HotKV server **v0.3.0** (RESP2 and RESP3, with
429
+ the enterprise families licensed). Commands a given server does not know raise a `HotKV::Error::CommandError`;
430
+ unlicensed enterprise commands raise `HotKV::Error::NotLicensedError`.
431
+ Ruby 3.0 to 3.3 are supported; the unit tests run on every one of them in
432
+ the CI matrix.
433
+
434
+ ## Contributing
435
+
436
+ Bug reports and pull requests are welcome. See [CONTRIBUTING.md](CONTRIBUTING.md).
437
+
438
+ ## Support
439
+
440
+ - Bugs and feature requests: [GitHub issues](https://github.com/hotkv-ltd/hotkv-ruby-client/issues)
441
+ - Questions and commercial support: support@hotkv.com
442
+ - Security vulnerabilities: see [SECURITY.md](SECURITY.md)
443
+
444
+ ## License
445
+
446
+ Licensed under the Apache License, Version 2.0: see [LICENSE](LICENSE) and [NOTICE](NOTICE).
447
+
448
+ ## Trademarks and affiliation
449
+
450
+ "HotKV" is a trademark of HotKV Ltd; the license does not grant rights to use it.
451
+ The HotKV server is a separate commercial product, and its enterprise commands need a HotKV license.
452
+
453
+ HotKV is an independent product of HotKV Ltd. It speaks the RESP protocol and implements
454
+ many Redis commands so that existing tools and client habits carry over, but it is not Redis,
455
+ Valkey, Dragonfly or KeyDB, and this SDK is built for and tested against HotKV. HotKV Ltd is not
456
+ affiliated with, endorsed by or sponsored by Redis Ltd., the Valkey project, DragonflyDB or KeyDB.
457
+ Redis is a registered trademark of Redis Ltd. Valkey, Dragonfly, KeyDB and all other product and
458
+ company names are trademarks of their respective owners; they are used here only to describe
459
+ protocol and command compatibility.