forked from aembke/fred.rs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterfaces.rs
351 lines (310 loc) · 11.7 KB
/
interfaces.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
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
use crate::{
commands,
error::{RedisError, RedisErrorKind},
modules::inner::RedisClientInner,
protocol::command::{RedisCommand, RouterCommand},
router::commands as router_commands,
types::{
ClientState,
ClusterStateChange,
ConnectHandle,
CustomCommand,
FromRedis,
InfoKind,
PerformanceConfig,
ReconnectPolicy,
RedisConfig,
RedisValue,
RespVersion,
Server,
ShutdownFlags,
},
utils,
};
pub use redis_protocol::resp3::types::Frame as Resp3Frame;
use semver::Version;
use std::{convert::TryInto, sync::Arc};
use tokio::sync::broadcast::Receiver as BroadcastReceiver;
/// Type alias for `Result<T, RedisError>`.
pub type RedisResult<T> = Result<T, RedisError>;
#[cfg(feature = "dns")]
use crate::protocol::types::Resolve;
/// Send a single `RedisCommand` to the router.
pub(crate) fn default_send_command<C>(inner: &Arc<RedisClientInner>, command: C) -> Result<(), RedisError>
where
C: Into<RedisCommand>,
{
let command: RedisCommand = command.into();
_trace!(
inner,
"Sending command {} ({}) to router.",
command.kind.to_str_debug(),
command.debug_id()
);
send_to_router(inner, command.into())
}
/// Send a `RouterCommand` to the router.
pub(crate) fn send_to_router(inner: &RedisClientInner, command: RouterCommand) -> Result<(), RedisError> {
inner.counters.incr_cmd_buffer_len();
if let Err(e) = inner.command_tx.send(command) {
// usually happens if the caller tries to send a command before calling `connect` or after calling `quit`
inner.counters.decr_cmd_buffer_len();
if let RouterCommand::Command(mut command) = e.0 {
_warn!(
inner,
"Fatal error sending {} command to router. Client may be stopped or not yet initialized.",
command.kind.to_str_debug()
);
// if a caller manages to trigger this it means that a connection task is not running
command.respond_to_caller(Err(RedisError::new(
RedisErrorKind::Unknown,
"Client is not initialized.",
)));
} else {
_warn!(
inner,
"Fatal error sending command to router. Client may be stopped or not yet initialized."
);
}
Err(RedisError::new(
RedisErrorKind::Unknown,
"Failed to send command to router.",
))
} else {
Ok(())
}
}
/// Any Redis client that implements any part of the Redis interface.
#[async_trait]
pub trait ClientLike: Clone + Send + Sized {
#[doc(hidden)]
fn inner(&self) -> &Arc<RedisClientInner>;
/// Helper function to intercept and modify a command without affecting how it is sent to the connection layer.
#[doc(hidden)]
fn change_command(&self, _: &mut RedisCommand) {}
/// Helper function to intercept and customize how a command is sent to the connection layer.
#[doc(hidden)]
fn send_command<C>(&self, command: C) -> Result<(), RedisError>
where
C: Into<RedisCommand>,
{
let mut command: RedisCommand = command.into();
self.change_command(&mut command);
default_send_command(&self.inner(), command)
}
/// The unique ID identifying this client and underlying connections.
///
/// All connections created by this client will use `CLIENT SETNAME` with this value unless the `no-client-setname`
/// feature is enabled.
fn id(&self) -> &str {
self.inner().id.as_str()
}
/// Read the config used to initialize the client.
fn client_config(&self) -> RedisConfig {
self.inner().config.as_ref().clone()
}
/// Read the reconnect policy used to initialize the client.
fn client_reconnect_policy(&self) -> Option<ReconnectPolicy> {
self.inner().policy.read().clone()
}
/// Read the RESP version used by the client when communicating with the server.
fn protocol_version(&self) -> RespVersion {
if self.inner().is_resp3() {
RespVersion::RESP3
} else {
RespVersion::RESP2
}
}
/// Whether or not the client has a reconnection policy.
fn has_reconnect_policy(&self) -> bool {
self.inner().policy.read().is_some()
}
/// Whether or not the client will automatically pipeline commands.
fn is_pipelined(&self) -> bool {
self.inner().is_pipelined()
}
/// Whether or not the client is connected to a cluster.
fn is_clustered(&self) -> bool {
self.inner().config.server.is_clustered()
}
/// Whether or not the client uses the sentinel interface.
fn uses_sentinels(&self) -> bool {
self.inner().config.server.is_sentinel()
}
/// Update the internal [PerformanceConfig](crate::types::PerformanceConfig) in place with new values.
fn update_perf_config(&self, config: PerformanceConfig) {
self.inner().update_performance_config(config);
}
/// Read the [PerformanceConfig](crate::types::PerformanceConfig) associated with this client.
fn perf_config(&self) -> PerformanceConfig {
self.inner().performance_config()
}
/// Read the state of the underlying connection(s).
///
/// If running against a cluster the underlying state will reflect the state of the least healthy connection.
fn state(&self) -> ClientState {
self.inner().state.read().clone()
}
/// Whether or not all underlying connections are healthy.
fn is_connected(&self) -> bool {
*self.inner().state.read() == ClientState::Connected
}
/// Read the set of active connections managed by the client.
async fn active_connections(&self) -> Result<Vec<Server>, RedisError> {
commands::client::active_connections(self).await
}
/// Read the server version, if known.
fn server_version(&self) -> Option<Version> {
self.inner().server_state.read().kind.server_version()
}
/// Override the DNS resolution logic for the client.
#[cfg(feature = "dns")]
#[cfg_attr(docsrs, doc(cfg(feature = "dns")))]
async fn set_resolver(&self, resolver: Arc<dyn Resolve>) {
self.inner().set_resolver(resolver).await;
}
/// Connect to the Redis server.
///
/// This function returns a `JoinHandle` to a task that drives the connection. It will not resolve until the
/// connection closes, and if a reconnection policy with unlimited attempts is provided then the `JoinHandle` will
/// run forever, or until `QUIT` is called.
fn connect(&self) -> ConnectHandle {
let inner = self.inner().clone();
tokio::spawn(async move {
let result = router_commands::start(&inner).await;
_trace!(inner, "Ending connection task with {:?}", result);
if let Err(ref e) = result {
inner.notifications.broadcast_connect(Err(e.clone()));
}
utils::set_client_state(&inner.state, ClientState::Disconnected);
result
})
}
/// Force a reconnection to the server(s).
///
/// When running against a cluster this function will also refresh the cached cluster routing table.
async fn force_reconnection(&self) -> RedisResult<()> {
commands::server::force_reconnection(self.inner()).await
}
/// Wait for the result of the next connection attempt.
///
/// This can be used with `on_reconnect` to separate initialization logic that needs to occur only on the next
/// connection attempt vs all subsequent attempts.
async fn wait_for_connect(&self) -> RedisResult<()> {
if utils::read_locked(&self.inner().state) == ClientState::Connected {
debug!("{}: Client is already connected.", self.inner().id);
Ok(())
} else {
self.inner().notifications.connect.load().subscribe().recv().await?
}
}
/// Listen for reconnection notifications.
///
/// This function can be used to receive notifications whenever the client successfully reconnects in order to
/// re-subscribe to channels, etc.
///
/// A reconnection event is also triggered upon first connecting to the server.
fn on_reconnect(&self) -> BroadcastReceiver<()> {
self.inner().notifications.reconnect.load().subscribe()
}
/// Listen for notifications whenever the cluster state changes.
///
/// This is usually triggered in response to a `MOVED` error, but can also happen when connections close
/// unexpectedly.
fn on_cluster_change(&self) -> BroadcastReceiver<Vec<ClusterStateChange>> {
self.inner().notifications.cluster_change.load().subscribe()
}
/// Listen for protocol and connection errors. This stream can be used to more intelligently handle errors that may
/// not appear in the request-response cycle, and so cannot be handled by response futures.
///
/// This function does not need to be called again if the connection closes.
fn on_error(&self) -> BroadcastReceiver<RedisError> {
self.inner().notifications.errors.load().subscribe()
}
/// Close the connection to the Redis server. The returned future resolves when the command has been written to the
/// socket, not when the connection has been fully closed. Some time after this future resolves the future
/// returned by [connect](Self::connect) will resolve which indicates that the connection has been fully closed.
///
/// This function will also close all error, pubsub message, and reconnection event streams.
async fn quit(&self) -> RedisResult<()> {
commands::server::quit(self).await
}
/// Shut down the server and quit the client.
///
/// <https://redis.io/commands/shutdown>
async fn shutdown(&self, flags: Option<ShutdownFlags>) -> RedisResult<()> {
commands::server::shutdown(self, flags).await
}
/// Ping the Redis server.
///
/// <https://redis.io/commands/ping>
async fn ping<R>(&self) -> RedisResult<R>
where
R: FromRedis,
{
commands::server::ping(self).await?.convert()
}
/// Read info about the server.
///
/// <https://redis.io/commands/info>
async fn info<R>(&self, section: Option<InfoKind>) -> RedisResult<R>
where
R: FromRedis,
{
commands::server::info(self, section).await?.convert()
}
/// Run a custom command that is not yet supported via another interface on this client. This is most useful when
/// interacting with third party modules or extensions.
///
/// Callers should use the re-exported [redis_keyslot](crate::util::redis_keyslot) function to hash the command's
/// key, if necessary.
///
/// This interface should be used with caution as it may break the automatic pipeline features in the client if
/// command flags are not properly configured.
async fn custom<R, T>(&self, cmd: CustomCommand, args: Vec<T>) -> RedisResult<R>
where
R: FromRedis,
T: TryInto<RedisValue> + Send,
T::Error: Into<RedisError> + Send,
{
let args = utils::try_into_vec(args)?;
commands::server::custom(self, cmd, args).await?.convert()
}
/// Run a custom command similar to [custom](Self::custom), but return the response frame directly without any
/// parsing.
///
/// Note: RESP2 frames from the server are automatically converted to the RESP3 format when parsed by the client.
async fn custom_raw<T>(&self, cmd: CustomCommand, args: Vec<T>) -> RedisResult<Resp3Frame>
where
T: TryInto<RedisValue> + Send,
T::Error: Into<RedisError> + Send,
{
let args = utils::try_into_vec(args)?;
commands::server::custom_raw(self, cmd, args).await
}
}
pub use crate::commands::interfaces::{
acl::AclInterface,
client::ClientInterface,
cluster::ClusterInterface,
config::ConfigInterface,
geo::GeoInterface,
hashes::HashesInterface,
hyperloglog::HyperloglogInterface,
keys::KeysInterface,
lists::ListInterface,
lua::{FunctionInterface, LuaInterface},
memory::MemoryInterface,
metrics::MetricsInterface,
pubsub::PubsubInterface,
server::{AuthInterface, HeartbeatInterface, ServerInterface},
sets::SetsInterface,
slowlog::SlowlogInterface,
sorted_sets::SortedSetsInterface,
streams::StreamsInterface,
transactions::TransactionInterface,
};
#[cfg(feature = "sentinel-client")]
pub use crate::commands::interfaces::sentinel::SentinelInterface;
#[cfg(feature = "client-tracking")]
pub use crate::commands::interfaces::tracking::TrackingInterface;