forked from aembke/fred.rs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathredis.rs
289 lines (264 loc) · 8.88 KB
/
redis.rs
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
use crate::{
clients::{Node, Pipeline},
commands,
error::{RedisError, RedisErrorKind},
interfaces::{
AclInterface,
AuthInterface,
ClientInterface,
ClusterInterface,
ConfigInterface,
FunctionInterface,
GeoInterface,
HashesInterface,
HeartbeatInterface,
HyperloglogInterface,
KeysInterface,
ListInterface,
LuaInterface,
MemoryInterface,
MetricsInterface,
PubsubInterface,
ServerInterface,
SetsInterface,
SlowlogInterface,
SortedSetsInterface,
TransactionInterface,
},
modules::inner::RedisClientInner,
prelude::{ClientLike, StreamsInterface},
types::*,
};
use bytes_utils::Str;
use futures::Stream;
use std::{fmt, sync::Arc};
#[cfg(feature = "client-tracking")]
use crate::{clients::Caching, interfaces::TrackingInterface};
#[cfg(feature = "replicas")]
use crate::clients::Replicas;
/// The primary Redis client struct.
#[derive(Clone)]
pub struct RedisClient {
pub(crate) inner: Arc<RedisClientInner>,
}
impl Default for RedisClient {
fn default() -> Self {
RedisClient::new(RedisConfig::default(), None, None)
}
}
impl fmt::Display for RedisClient {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RedisClient")
.field("id", &self.inner.id)
.field("state", &self.state())
.finish()
}
}
#[doc(hidden)]
impl<'a> From<&'a Arc<RedisClientInner>> for RedisClient {
fn from(inner: &'a Arc<RedisClientInner>) -> RedisClient {
RedisClient { inner: inner.clone() }
}
}
impl ClientLike for RedisClient {
#[doc(hidden)]
fn inner(&self) -> &Arc<RedisClientInner> {
&self.inner
}
}
impl AclInterface for RedisClient {}
impl ClientInterface for RedisClient {}
impl ClusterInterface for RedisClient {}
impl PubsubInterface for RedisClient {}
impl ConfigInterface for RedisClient {}
impl GeoInterface for RedisClient {}
impl HashesInterface for RedisClient {}
impl HyperloglogInterface for RedisClient {}
impl MetricsInterface for RedisClient {}
impl TransactionInterface for RedisClient {}
impl KeysInterface for RedisClient {}
impl LuaInterface for RedisClient {}
impl ListInterface for RedisClient {}
impl MemoryInterface for RedisClient {}
impl AuthInterface for RedisClient {}
impl ServerInterface for RedisClient {}
impl SlowlogInterface for RedisClient {}
impl SetsInterface for RedisClient {}
impl SortedSetsInterface for RedisClient {}
impl HeartbeatInterface for RedisClient {}
impl StreamsInterface for RedisClient {}
impl FunctionInterface for RedisClient {}
#[cfg(feature = "client-tracking")]
#[cfg_attr(docsrs, doc(cfg(feature = "client-tracking")))]
impl TrackingInterface for RedisClient {}
impl RedisClient {
/// Create a new client instance without connecting to the server.
pub fn new(config: RedisConfig, perf: Option<PerformanceConfig>, policy: Option<ReconnectPolicy>) -> RedisClient {
RedisClient {
inner: RedisClientInner::new(config, perf.unwrap_or_default(), policy),
}
}
/// Create a new `RedisClient` from the config provided to this client.
///
/// The returned client will **not** be connected to the server.
pub fn clone_new(&self) -> Self {
let mut policy = self.inner.policy.read().clone();
if let Some(policy) = policy.as_mut() {
policy.reset_attempts();
}
RedisClient::new(
self.inner.config.as_ref().clone(),
Some(self.inner.performance_config()),
policy,
)
}
/// Split a clustered Redis client into a set of centralized clients - one for each primary node in the cluster.
///
/// Some Redis commands are not designed to work with hash slots against a clustered deployment. For example,
/// `FLUSHDB`, `PING`, etc all work on one node in the cluster, but no interface exists for the client to
/// select a specific node in the cluster against which to run the command. This function allows the caller to
/// create a list of clients such that each connect to one of the primary nodes in the cluster and functions
/// as if it were operating against a single centralized Redis server.
///
/// The clients returned by this function will not be connected to their associated servers. The caller needs to
/// call `connect` on each client before sending any commands.
pub fn split_cluster(&self) -> Result<Vec<RedisClient>, RedisError> {
if self.inner.config.server.is_clustered() {
commands::server::split(&self.inner)
} else {
Err(RedisError::new(
RedisErrorKind::Unknown,
"Client is not using a clustered deployment.",
))
}
}
// --------------- SCANNING ---------------
/// Incrementally iterate over a set of keys matching the `pattern` argument, returning `count` results per page, if
/// specified.
///
/// The scan operation can be canceled by dropping the returned stream.
///
/// <https://redis.io/commands/scan>
pub fn scan<P>(
&self,
pattern: P,
count: Option<u32>,
r#type: Option<ScanType>,
) -> impl Stream<Item = Result<ScanResult, RedisError>>
where
P: Into<Str>,
{
commands::scan::scan(&self.inner, pattern.into(), count, r#type, None)
}
/// Run the `SCAN` command on each primary/main node in a cluster concurrently.
///
/// In order for this function to work reliably the cluster state must not change while scanning. If nodes are added
/// or removed, or hash slots are rebalanced, it may result in missing keys or duplicate keys in the result
/// stream. See [split_cluster](Self::split_cluster) for use cases that require scanning to work while the cluster
/// state changes.
///
/// Unlike `SCAN`, `HSCAN`, etc, the returned stream may continue even if
/// [has_more](crate::types::ScanResult::has_more) returns false on a given page of keys.
pub fn scan_cluster<P>(
&self,
pattern: P,
count: Option<u32>,
r#type: Option<ScanType>,
) -> impl Stream<Item = Result<ScanResult, RedisError>>
where
P: Into<Str>,
{
commands::scan::scan_cluster(&self.inner, pattern.into(), count, r#type)
}
/// Incrementally iterate over pages of the hash map stored at `key`, returning `count` results per page, if
/// specified.
///
/// <https://redis.io/commands/hscan>
pub fn hscan<K, P>(
&self,
key: K,
pattern: P,
count: Option<u32>,
) -> impl Stream<Item = Result<HScanResult, RedisError>>
where
K: Into<RedisKey>,
P: Into<Str>,
{
commands::scan::hscan(&self.inner, key.into(), pattern.into(), count)
}
/// Incrementally iterate over pages of the set stored at `key`, returning `count` results per page, if specified.
///
/// <https://redis.io/commands/sscan>
pub fn sscan<K, P>(
&self,
key: K,
pattern: P,
count: Option<u32>,
) -> impl Stream<Item = Result<SScanResult, RedisError>>
where
K: Into<RedisKey>,
P: Into<Str>,
{
commands::scan::sscan(&self.inner, key.into(), pattern.into(), count)
}
/// Incrementally iterate over pages of the sorted set stored at `key`, returning `count` results per page, if
/// specified.
///
/// <https://redis.io/commands/zscan>
pub fn zscan<K, P>(
&self,
key: K,
pattern: P,
count: Option<u32>,
) -> impl Stream<Item = Result<ZScanResult, RedisError>>
where
K: Into<RedisKey>,
P: Into<Str>,
{
commands::scan::zscan(&self.inner, key.into(), pattern.into(), count)
}
/// Send a series of commands in a [pipeline](https://redis.io/docs/manual/pipelining/).
pub fn pipeline(&self) -> Pipeline<RedisClient> {
Pipeline::from(self.clone())
}
/// Send commands to the provided cluster node.
///
/// The caller will receive a `RedisErrorKind::Cluster` error if the provided server does not exist.
///
/// The client will still automatically follow `MOVED` errors via this interface. Callers may not notice this, but
/// incorrect server arguments here could result in unnecessary calls to refresh the cached cluster routing table.
pub fn with_cluster_node<S>(&self, server: S) -> Node
where
S: Into<Server>,
{
Node::new(&self.inner, server.into())
}
/// Create a client that interacts with replica nodes.
#[cfg(feature = "replicas")]
#[cfg_attr(docsrs, doc(cfg(feature = "replicas")))]
pub fn replicas(&self) -> Replicas {
Replicas::from(&self.inner)
}
/// Send a [CLIENT CACHING yes|no](https://redis.io/commands/client-caching/) command before subsequent commands.
#[cfg(feature = "client-tracking")]
#[cfg_attr(docsrs, doc(cfg(feature = "client-tracking")))]
pub fn caching(&self, enabled: bool) -> Caching {
Caching::new(&self.inner, enabled)
}
}
#[cfg(test)]
mod tests {
use crate::util;
#[test]
fn should_correctly_sha1_hash() {
assert_eq!(
&util::sha1_hash("foobarbaz"),
"5f5513f8822fdbe5145af33b64d8d970dcf95c6e"
);
assert_eq!(&util::sha1_hash("abc123"), "6367c48dd193d56ea7b0baad25b19455e529f5ee");
assert_eq!(
&util::sha1_hash("jakdjfkldajfklej8a4tjkaldsnvkl43kjakljdvk42"),
"45c118f5de7c3fd3a4022135dc6acfb526f3c225"
);
}
}