1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
//! A Tower-native Redis client for Rust with typed commands, composable
//! middleware, and complete Redis Stack coverage.
//!
//! Every connection is a `tower::Service`. Commands are typed request/response
//! pairs with compile-time safety. Resilience, caching, and observability are
//! composed via standard Tower layers.
//!
//! # Quick Start
//!
//! ```no_run
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! use redis_tower::{MultiplexedClient, commands::*};
//!
//! // MultiplexedClient is the recommended default: one auto-pipelined
//! // connection, cheap to clone and share across tasks.
//! let client = MultiplexedClient::connect("127.0.0.1:6379").await?;
//! client.execute(Set::new("key", "value")).await?;
//! let val: Option<bytes::Bytes> = client.execute(Get::new("key")).await?;
//! # let _ = val;
//! # Ok(())
//! # }
//! ```
//!
//! # Choosing a client
//!
//! | Client | When to use |
//! |--------|-------------|
//! | [`MultiplexedClient`] | **The default.** One connection, concurrent commands auto-pipelined; cheap to `clone` and share across tasks. |
//! | [`CachedMultiplexedClient`] | Cloneable standalone client-side caching: local hits, auto-pipelined misses, and owned RESP3 invalidation tracking. |
//! | [`RedisConnection`] | A single exclusive connection (`&mut self`), or as a building block for the others. |
//! | [`RedisClient`] | `Arc<Mutex<RedisConnection>>` -- a simple shared handle, but it serializes commands through one lock (lower throughput than `MultiplexedClient`). |
//! | [`ResilientRedisClient`] | A shared handle with automatic reconnection and exponential backoff, for long-running services. |
//! | [`ConnectionPool`] | N connections with configurable [`DispatchStrategy`] -- use for blocking commands (`BLPOP`) or CPU-bound reply parsing, where one multiplexed connection would head-of-line block. |
//! | `MultiplexedClusterClient` (`redis-tower-cluster`) | Redis Cluster, high concurrency. |
//! | `MultiplexedSentinelClient` (`redis-tower-sentinel`) | Sentinel-managed failover, high concurrency. |
//! | `SyncClient` (`redis-tower-sync`) | Blocking (non-`async`) contexts. |
//!
//! Reach for `RedisClient` only when you specifically want serialized,
//! exclusive access; for most workloads `MultiplexedClient` is both simpler and
//! faster. A naive benchmark of `RedisClient` will under-report throughput
//! because every command waits on the mutex.
//!
//! # Commands
//!
//! The [`commands`] module contains 488+ typed command structs spanning core
//! Redis and feature-gated Redis Stack modules. Each command implements the
//! [`Command`] trait, which defines serialization to a RESP [`Frame`] via
//! `to_frame()` and response parsing via `parse_response()`.
//!
//! Commands with optional parameters use builder methods:
//!
//! ```no_run
//! # fn example() {
//! use redis_tower::commands::*;
//!
//! let cmd = Set::new("key", "value").ex(60).nx();
//! let cmd = ZAdd::new("leaderboard").member(100.0, "alice").member(200.0, "bob");
//! # let _ = cmd;
//! # }
//! ```
//!
//! Use [`RedisValueExt::parse_into`] for ergonomic type conversion from
//! command responses:
//!
//! ```no_run
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! use redis_tower::{RedisClient, RedisValueExt, commands::*};
//!
//! let client = RedisClient::connect("127.0.0.1:6379").await?;
//! client.execute(Set::new("counter", "42")).await?;
//! let raw = client.execute(Get::new("counter")).await?;
//! let count: i64 = raw.parse_into()?;
//! # let _ = count;
//! # Ok(())
//! # }
//! ```
//!
//! # Middleware
//!
//! Middleware composes at the *frame* altitude. [`FrameService`] is the
//! `tower::Service<Frame>` at the bottom of the stack, so any Tower layer that
//! speaks `Frame` stacks on top of it. redis-tower also ships built-in layers:
//!
//! - [`TracingLayer`] -- emits tracing spans for each command.
//! - [`MetricsLayer`] -- records command latency and counts via a pluggable
//! [`MetricsRecorder`].
//! - [`CacheLayer`] / [`CacheService`] -- client-side frame caching with
//! owned invalidation lifecycle options.
//! - [`ReconnectService`] -- automatic reconnection with configurable backoff.
//!
//! ```no_run
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! use tower::ServiceBuilder;
//! use tower::timeout::TimeoutLayer;
//! use tower::buffer::BufferLayer;
//! use redis_tower::{Frame, FrameService, TracingLayer};
//!
//! let conn = FrameService::connect("127.0.0.1:6379").await?;
//! let svc = ServiceBuilder::new()
//! .layer(BufferLayer::<Frame>::new(64))
//! .layer(TimeoutLayer::new(std::time::Duration::from_secs(5)))
//! .layer(TracingLayer::new())
//! .service(conn);
//! # let _ = svc;
//! # Ok(())
//! # }
//! ```
//!
//! Layers like `BufferLayer` and `TimeoutLayer` box their error type, so a
//! stack that includes them no longer meets [`CommandAdapter`]'s
//! `Error = RedisError` bound. Keep such layers outside the adapter, or stick
//! to layers that preserve [`RedisError`] when you want typed commands on top
//! (see the next section).
//!
//! # Resilience
//!
//! Redis-aware circuit breaking is backed by `tower-resilience`, and automatic
//! reconnection with exponential backoff is built in via
//! [`ResilientRedisClient`]. The high-level clients expose a consuming
//! `with_circuit_breaker` option:
//!
//! ```no_run
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! use std::time::Duration;
//!
//! use redis_tower::{
//! MultiplexedClient, RedisCircuitBreakerConfig,
//! };
//!
//! let client = MultiplexedClient::connect("127.0.0.1:6379")
//! .await?
//! .with_circuit_breaker(RedisCircuitBreakerConfig {
//! failure_threshold: 5,
//! recovery_probe_interval: Duration::from_secs(30),
//! });
//!
//! let handle = client.circuit_breaker_handle();
//! assert_eq!(handle.health_status(), "healthy");
//! # Ok(())
//! # }
//! ```
//!
//! The breaker counts connection, connect-timeout, and command-timeout errors,
//! while ignoring Redis command errors such as `WRONGTYPE`. For
//! process-local fault-tolerance primitives this crate does not ship -- rate
//! limiting and bulkhead isolation -- the
//! [tower-resilience](https://crates.io/crates/tower-resilience) crate family
//! provides layers that compose into the same builder. The companion
//! `redis-tower-primitives` crate provides fenced locks, leader election,
//! expirable semaphores, countdown latches, delayed queues, block-allocated
//! IDs, and a Redis-time GCRA limiter.
//!
//! [`RedisError::is_retryable`] classifies which errors are worth retrying
//! (transient connection errors) versus command errors like WRONGTYPE that are
//! not. Pair it with [`ResilientRedisClient`] for idempotent-aware
//! reconnection.
//!
//! # Auto-Pipelining
//!
//! [`AutoPipelineService`] collects concurrent requests from multiple tasks
//! and sends them as a single Redis pipeline, returning individual responses
//! to each caller. Configure batch size and window via
//! [`AutoPipelineConfig`].
//!
//! ```no_run
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! use redis_tower::{AutoPipelineService, AutoPipelineConfig, CommandAdapter, RedisConnection};
//! use redis_tower::commands::*;
//! use tower::Service;
//!
//! let conn = RedisConnection::connect("127.0.0.1:6379").await?;
//! let mut svc = CommandAdapter::new(
//! AutoPipelineService::new(conn, AutoPipelineConfig::default()),
//! );
//! let val: Option<bytes::Bytes> = svc.call(Get::new("key")).await?;
//! # let _ = val;
//! # Ok(())
//! # }
//! ```
//!
//! # Pipeline and Transactions
//!
//! [`Pipeline`] batches multiple commands into a single roundtrip.
//! [`Transaction`] wraps commands in MULTI/EXEC with optional WATCH support
//! for optimistic locking. The [`transaction()`] helper drives the standard
//! WATCH/read/EXEC retry loop for you, re-running a closure until EXEC commits
//! or a retry cap is hit.
//!
//! ```no_run
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! use redis_tower::{transaction, Pipeline, Transaction, RedisConnection};
//! use redis_tower::commands::{Get, Incr, Set};
//!
//! let mut conn = RedisConnection::connect("127.0.0.1:6379").await?;
//!
//! let pipelined = Pipeline::new()
//! .push(Set::new("a", "1"))
//! .push(Get::new("a"))
//! .execute(&mut conn)
//! .await?;
//!
//! let watched = Transaction::new()
//! .watch(["key"])
//! .push(Incr::new("key"))
//! .execute(&mut conn)
//! .await?;
//!
//! // Optimistic-locking retry loop: read inside the WATCH window, then EXEC,
//! // retrying automatically if another client touches `counter`.
//! let incremented = transaction(&mut conn, ["counter"], async |c| {
//! let current: i64 = match c.execute(Get::new("counter")).await? {
//! Some(bytes) => String::from_utf8_lossy(&bytes).parse().unwrap_or(0),
//! None => 0,
//! };
//! Ok(Transaction::new().push(Set::new("counter", (current + 1).to_string())))
//! })
//! .await?;
//! # let _ = (pipelined, watched, incremented);
//! # Ok(())
//! # }
//! ```
//!
//! # Pub/Sub
//!
//! [`PubSubConnection`] provides a dedicated subscribe/publish interface.
//! Messages are delivered as a [`futures::Stream`] of [`PubSubMessage`]
//! values with channel and payload fields.
//!
//! ```no_run
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! # use futures::StreamExt;
//! use redis_tower::{PubSubConnection, RedisConnection};
//!
//! let conn = RedisConnection::connect("127.0.0.1:6379").await?;
//! let mut pubsub = PubSubConnection::from_connection(conn)?;
//! pubsub.subscribe(&["events"]).await?;
//!
//! while let Some(msg) = pubsub.next().await {
//! let msg = msg?;
//! println!("{}: {:?}", msg.channel, msg.payload);
//! }
//! # Ok(())
//! # }
//! ```
//!
//! # Command Monitoring
//!
//! [`MonitorStream`] consumes a dedicated [`RedisConnection`] and yields the
//! server's `MONITOR` feed as binary-safe [`MonitorEvent`] values. It polls the
//! connection directly without a background worker.
//!
//! `MONITOR` is a short-lived debugging tool, not production telemetry: Redis
//! must format and stream every eligible command to every monitor, and one
//! monitor can reduce server throughput substantially.
//!
//! ```no_run
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! use redis_tower::{MonitorStream, RedisConnection};
//! use tokio_stream::StreamExt;
//!
//! let conn = RedisConnection::connect("127.0.0.1:6379").await?;
//! let mut events = MonitorStream::new(conn).await?;
//! while let Some(event) = events.next().await {
//! let event = event?;
//! println!("{:?} {:?}", event.command, event.arguments);
//! }
//! # Ok(())
//! # }
//! ```
//!
//! # Streams
//!
//! [`StreamConsumer`] wraps XREADGROUP into a Rust [`futures::Stream`] with
//! automatic acknowledgement and consumer group management. Configure batch
//! size, block timeout, and auto-ack behavior via [`ConsumerConfig`].
//!
//! ```no_run
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! use redis_tower::consumer::{StreamConsumer, ConsumerConfig};
//! use redis_tower::RedisConnection;
//! use tokio_stream::StreamExt;
//!
//! let conn = RedisConnection::connect("127.0.0.1:6379").await?;
//! let consumer = StreamConsumer::new("my-group", "worker-1", ["my-stream"])
//! .config(ConsumerConfig { batch_size: 20, auto_ack: true, ..Default::default() });
//!
//! let mut stream = std::pin::pin!(consumer.into_stream(conn));
//! while let Some(msg) = stream.next().await {
//! let msg = msg?;
//! println!("{}: {} fields", msg.id, msg.fields.len());
//! }
//! # Ok(())
//! # }
//! ```
//!
//! # Scripting
//!
//! [`Script`] pre-computes the SHA1 digest at construction time and provides
//! an [`execute`](Script::execute) method that tries EVALSHA first, falling
//! back to EVAL on NOSCRIPT. This avoids sending the full script text on
//! every call.
//!
//! ```no_run
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! # let mut conn = redis_tower::RedisConnection::connect("127.0.0.1:6379").await?;
//! use redis_tower::Script;
//!
//! let script = Script::new("return redis.call('GET', KEYS[1])");
//! let result = script.execute(&mut conn, &["mykey"], &[]).await?;
//! # let _ = result;
//! # Ok(())
//! # }
//! ```
//!
//! # JSON and Search APIs (serde feature)
//!
//! When the `serde` feature is enabled, two high-level APIs are available:
//!
//! - `Json` -- typed wrapper around RedisJSON commands with automatic
//! serde serialization and deserialization.
//! - `Search` -- query builder for RediSearch with automatic result
//! deserialization into user-defined types.
//!
//! ```no_run
//! # #[allow(deprecated)]
//! # async fn example() -> Result<(), Box<dyn std::error::Error>> {
//! # let mut conn = redis_tower::RedisConnection::connect("127.0.0.1:6379").await?;
//! use redis_tower::Json;
//! use serde::{Serialize, Deserialize};
//!
//! #[derive(Serialize, Deserialize)]
//! struct User { name: String, age: u32 }
//!
//! let mut json = Json::new(&mut conn);
//! json.set("user:1", "$", &User { name: "Alice".into(), age: 30 }).await?;
//! let user: User = json.get("user:1", "$").await?;
//! # let _ = user;
//! # Ok(())
//! # }
//! ```
//!
//! # Feature Flags
//!
//! - `commands-stack` (default) -- all Redis Stack module commands
//! - `commands-json` -- RedisJSON commands
//! - `commands-search` -- RediSearch commands
//! - `commands-bloom` -- Bloom filter commands
//! - `commands-sketch` -- Count-Min Sketch commands
//! - `commands-tdigest` -- t-digest commands
//! - `commands-timeseries` -- TimeSeries commands
//! - `commands-vector-sets` -- Vector Set commands
//! - `metrics` -- [`metrics`](https://docs.rs/metrics)-facade recorder plus
//! connection-pool and auto-pipeline stats exporters
//! - `serde` -- `Json` and `Search` high-level APIs
//! - `tls-native-tls` -- TLS via native-tls backend
//! - `tls-rustls` -- TLS via rustls backend
//!
//! # Crate Structure
//!
//! This is the facade crate. It re-exports types from the workspace:
//!
//! | Crate | Role |
//! |---|---|
//! | `redis-tower` | This facade: standalone clients, Tower middleware, pools, caching, scripting, streams, and transactions |
//! | `redis-tower-protocol` | RESP2/RESP3 frame types, codec, limits, and frame helpers |
//! | `redis-tower-core` | [`Command`], [`RedisConnection`], [`FrameService`], transport, URL parsing, and value conversion |
//! | `redis-tower-commands` | 450+ typed commands, re-exported here through [`commands`] |
//! | `redis-tower-client` | One URL-driven client enum for standalone, Cluster, and Sentinel |
//! | `redis-tower-cluster` | Cluster topology, slot routing, MOVED/ASK handling, replica reads, scans, and pipelines |
//! | `redis-tower-sentinel` | Sentinel discovery, replica reads, and failover-aware clients |
//! | `redis-tower-modules` | High-level JSON, Search, TimeSeries, probabilistic, and vector APIs |
//! | `redis-tower-primitives` | Fenced locks, leader election, semaphores, latches, delayed queues, IDs, and rate limits |
//! | `redis-tower-auth-aws` / `redis-tower-auth-azure` | Cloud credential providers for rotating authentication |
//! | `redis-tower-sync` | Blocking wrapper with an internal Tokio runtime |
//! | `redis-tower-test` | Mocks, reusable command tests, and a managed Cluster fixture |
//!
//! The [guide](https://github.com/joshrotenberg/redis-tower/tree/main/docs)
//! goes deeper on production tuning, caching, cloud authentication,
//! distributed-primitives failure semantics, migrations, and compatibility.
/// Internal cache-coordination hooks shared with sibling workspace crates.
///
/// These are not part of the stable user-facing API. They are public because
/// Rust crate boundaries otherwise prevent the cluster client from reusing the
/// standalone cache's key extraction, invalidation, and race-safety logic.
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use RedisClient;
pub use CommandAdapter;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ;
pub use ReconnectService;
pub use ;
pub use ;
pub use ScanStream;
pub use Script;
pub use ;
pub use ;
pub use Json;
pub use ;
// Re-export core types.
pub use ;
// Re-export TLS config when a TLS backend is enabled.
pub use TlsConfig;
/// All typed Redis command structs, re-exported from `redis-tower-commands`.
///
/// Import everything with `use redis_tower::commands::*` for convenient access
/// to the full command set including both core Redis and Redis Stack commands.