forked from amazon-contributing/redis-rs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.rs
2656 lines (2474 loc) · 102 KB
/
mod.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
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
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! This module provides async functionality for Redis Cluster.
//!
//! By default, [`ClusterConnection`] makes use of [`MultiplexedConnection`] and maintains a pool
//! of connections to each node in the cluster. While it generally behaves similarly to
//! the sync cluster module, certain commands do not route identically, due most notably to
//! a current lack of support for routing commands to multiple nodes.
//!
//! Also note that pubsub functionality is not currently provided by this module.
//!
//! # Example
//! ```rust,no_run
//! use redis::cluster::ClusterClient;
//! use redis::AsyncCommands;
//!
//! async fn fetch_an_integer() -> String {
//! let nodes = vec!["redis://127.0.0.1/"];
//! let client = ClusterClient::new(nodes).unwrap();
//! let mut connection = client.get_async_connection(None).await.unwrap();
//! let _: () = connection.set("test", "test_data").await.unwrap();
//! let rv: String = connection.get("test").await.unwrap();
//! return rv;
//! }
//! ```
mod connections_container;
mod connections_logic;
/// Exposed only for testing.
pub mod testing {
pub use super::connections_container::ConnectionWithIp;
pub use super::connections_logic::*;
}
use crate::{
client::GlideConnectionOptions,
cluster_routing::{Routable, RoutingInfo},
cluster_slotmap::SlotMap,
cluster_topology::SLOT_SIZE,
cmd,
commands::cluster_scan::{cluster_scan, ClusterScanArgs, ObjectType, ScanStateRC},
FromRedisValue, InfoDict, ToRedisArgs,
};
#[cfg(all(not(feature = "tokio-comp"), feature = "async-std-comp"))]
use async_std::task::{spawn, JoinHandle};
use dashmap::DashMap;
#[cfg(all(not(feature = "tokio-comp"), feature = "async-std-comp"))]
use futures::executor::block_on;
use std::{
collections::{HashMap, HashSet},
fmt, io, mem,
net::{IpAddr, SocketAddr},
pin::Pin,
sync::{
atomic::{self, AtomicUsize, Ordering},
Arc, Mutex,
},
task::{self, Poll},
time::SystemTime,
};
#[cfg(feature = "tokio-comp")]
use tokio::task::JoinHandle;
#[cfg(feature = "tokio-comp")]
use crate::aio::DisconnectNotifier;
use crate::{
aio::{get_socket_addrs, ConnectionLike, MultiplexedConnection, Runtime},
cluster::slot_cmd,
cluster_async::connections_logic::{
get_host_and_port_from_addr, get_or_create_conn, ConnectionFuture, RefreshConnectionType,
},
cluster_client::{ClusterParams, RetryParams},
cluster_routing::{
self, MultipleNodeRoutingInfo, Redirect, ResponsePolicy, Route, SingleNodeRoutingInfo,
SlotAddr,
},
cluster_topology::{
calculate_topology, get_slot, SlotRefreshState, DEFAULT_NUMBER_OF_REFRESH_SLOTS_RETRIES,
DEFAULT_REFRESH_SLOTS_RETRY_INITIAL_INTERVAL, DEFAULT_REFRESH_SLOTS_RETRY_MAX_INTERVAL,
},
connection::{PubSubSubscriptionInfo, PubSubSubscriptionKind},
push_manager::PushInfo,
Cmd, ConnectionInfo, ErrorKind, IntoConnectionInfo, RedisError, RedisFuture, RedisResult,
Value,
};
use futures::stream::{FuturesUnordered, StreamExt};
use std::time::Duration;
#[cfg(all(not(feature = "tokio-comp"), feature = "async-std-comp"))]
use crate::aio::{async_std::AsyncStd, RedisRuntime};
#[cfg(all(not(feature = "tokio-comp"), feature = "async-std-comp"))]
use backoff_std_async::future::retry;
#[cfg(all(not(feature = "tokio-comp"), feature = "async-std-comp"))]
use backoff_std_async::{Error as BackoffError, ExponentialBackoff};
#[cfg(feature = "tokio-comp")]
use async_trait::async_trait;
#[cfg(feature = "tokio-comp")]
use backoff_tokio::future::retry;
#[cfg(feature = "tokio-comp")]
use backoff_tokio::{Error as BackoffError, ExponentialBackoff};
#[cfg(feature = "tokio-comp")]
use tokio::{sync::Notify, time::timeout};
use dispose::{Disposable, Dispose};
use futures::{future::BoxFuture, prelude::*, ready};
use pin_project_lite::pin_project;
use tokio::sync::{
mpsc,
oneshot::{self, Receiver},
RwLock,
};
use tracing::{debug, info, trace, warn};
use self::{
connections_container::{ConnectionAndAddress, ConnectionType, ConnectionsMap},
connections_logic::connect_and_check,
};
/// This represents an async Redis Cluster connection. It stores the
/// underlying connections maintained for each node in the cluster, as well
/// as common parameters for connecting to nodes and executing commands.
#[derive(Clone)]
pub struct ClusterConnection<C = MultiplexedConnection>(mpsc::Sender<Message<C>>);
impl<C> ClusterConnection<C>
where
C: ConnectionLike + Connect + Clone + Send + Sync + Unpin + 'static,
{
pub(crate) async fn new(
initial_nodes: &[ConnectionInfo],
cluster_params: ClusterParams,
push_sender: Option<mpsc::UnboundedSender<PushInfo>>,
) -> RedisResult<ClusterConnection<C>> {
ClusterConnInner::new(initial_nodes, cluster_params, push_sender)
.await
.map(|inner| {
let (tx, mut rx) = mpsc::channel::<Message<_>>(100);
let stream = async move {
let _ = stream::poll_fn(move |cx| rx.poll_recv(cx))
.map(Ok)
.forward(inner)
.await;
};
#[cfg(feature = "tokio-comp")]
tokio::spawn(stream);
#[cfg(all(not(feature = "tokio-comp"), feature = "async-std-comp"))]
AsyncStd::spawn(stream);
ClusterConnection(tx)
})
}
/// Special handling for `SCAN` command, using `cluster_scan`.
/// If you wish to use a match pattern, use [`cluster_scan_with_pattern`].
/// Perform a `SCAN` command on a Redis cluster, using scan state object in order to handle changes in topology
/// and make sure that all keys that were in the cluster from start to end of the scan are scanned.
/// In order to make sure all keys in the cluster scanned, topology refresh occurs more frequently and may affect performance.
///
/// # Arguments
///
/// * `scan_state_rc` - A reference to the scan state, For initiating new scan send [`ScanStateRC::new()`],
/// for each subsequent iteration use the returned [`ScanStateRC`].
/// * `count` - An optional count of keys requested,
/// the amount returned can vary and not obligated to return exactly count.
/// * `object_type` - An optional [`ObjectType`] enum of requested key redis type.
///
/// # Returns
///
/// A [`ScanStateRC`] for the updated state of the scan and the vector of keys that were found in the scan.
/// structure of returned value:
/// `Ok((ScanStateRC, Vec<Value>))`
///
/// When the scan is finished [`ScanStateRC`] will be None, and can be checked by calling `scan_state_wrapper.is_finished()`.
///
/// # Example
/// ```rust,no_run
/// use redis::cluster::ClusterClient;
/// use redis::{ScanStateRC, FromRedisValue, from_redis_value, Value, ObjectType};
///
/// async fn scan_all_cluster() -> Vec<String> {
/// let nodes = vec!["redis://127.0.0.1/"];
/// let client = ClusterClient::new(nodes).unwrap();
/// let mut connection = client.get_async_connection(None).await.unwrap();
/// let mut scan_state_rc = ScanStateRC::new();
/// let mut keys: Vec<String> = vec![];
/// loop {
/// let (next_cursor, scan_keys): (ScanStateRC, Vec<Value>) =
/// connection.cluster_scan(scan_state_rc, None, None).await.unwrap();
/// scan_state_rc = next_cursor;
/// let mut scan_keys = scan_keys
/// .into_iter()
/// .map(|v| from_redis_value(&v).unwrap())
/// .collect::<Vec<String>>(); // Change the type of `keys` to `Vec<String>`
/// keys.append(&mut scan_keys);
/// if scan_state_rc.is_finished() {
/// break;
/// }
/// }
/// keys
/// }
/// ```
pub async fn cluster_scan(
&mut self,
scan_state_rc: ScanStateRC,
count: Option<usize>,
object_type: Option<ObjectType>,
) -> RedisResult<(ScanStateRC, Vec<Value>)> {
let cluster_scan_args = ClusterScanArgs::new(scan_state_rc, None, count, object_type);
self.route_cluster_scan(cluster_scan_args).await
}
/// Special handling for `SCAN` command, using `cluster_scan_with_pattern`.
/// It is a special case of [`cluster_scan`], with an additional match pattern.
/// Perform a `SCAN` command on a Redis cluster, using scan state object in order to handle changes in topology
/// and make sure that all keys that were in the cluster from start to end of the scan are scanned.
/// In order to make sure all keys in the cluster scanned, topology refresh occurs more frequently and may affect performance.
///
/// # Arguments
///
/// * `scan_state_rc` - A reference to the scan state, For initiating new scan send [`ScanStateRC::new()`],
/// for each subsequent iteration use the returned [`ScanStateRC`].
/// * `match_pattern` - A match pattern of requested keys.
/// * `count` - An optional count of keys requested,
/// the amount returned can vary and not obligated to return exactly count.
/// * `object_type` - An optional [`ObjectType`] enum of requested key redis type.
///
/// # Returns
///
/// A [`ScanStateRC`] for the updated state of the scan and the vector of keys that were found in the scan.
/// structure of returned value:
/// `Ok((ScanStateRC, Vec<Value>))`
///
/// When the scan is finished [`ScanStateRC`] will be None, and can be checked by calling `scan_state_wrapper.is_finished()`.
///
/// # Example
/// ```rust,no_run
/// use redis::cluster::ClusterClient;
/// use redis::{ScanStateRC, FromRedisValue, from_redis_value, Value, ObjectType};
///
/// async fn scan_all_cluster() -> Vec<String> {
/// let nodes = vec!["redis://127.0.0.1/"];
/// let client = ClusterClient::new(nodes).unwrap();
/// let mut connection = client.get_async_connection(None).await.unwrap();
/// let mut scan_state_rc = ScanStateRC::new();
/// let mut keys: Vec<String> = vec![];
/// loop {
/// let (next_cursor, scan_keys): (ScanStateRC, Vec<Value>) =
/// connection.cluster_scan_with_pattern(scan_state_rc, b"my_key", None, None).await.unwrap();
/// scan_state_rc = next_cursor;
/// let mut scan_keys = scan_keys
/// .into_iter()
/// .map(|v| from_redis_value(&v).unwrap())
/// .collect::<Vec<String>>(); // Change the type of `keys` to `Vec<String>`
/// keys.append(&mut scan_keys);
/// if scan_state_rc.is_finished() {
/// break;
/// }
/// }
/// keys
/// }
/// ```
pub async fn cluster_scan_with_pattern<K: ToRedisArgs>(
&mut self,
scan_state_rc: ScanStateRC,
match_pattern: K,
count: Option<usize>,
object_type: Option<ObjectType>,
) -> RedisResult<(ScanStateRC, Vec<Value>)> {
let cluster_scan_args = ClusterScanArgs::new(
scan_state_rc,
Some(match_pattern.to_redis_args().concat()),
count,
object_type,
);
self.route_cluster_scan(cluster_scan_args).await
}
/// Route cluster scan to be handled by internal cluster_scan command
async fn route_cluster_scan(
&mut self,
cluster_scan_args: ClusterScanArgs,
) -> RedisResult<(ScanStateRC, Vec<Value>)> {
let (sender, receiver) = oneshot::channel();
self.0
.send(Message {
cmd: CmdArg::ClusterScan { cluster_scan_args },
sender,
})
.await
.map_err(|_| {
RedisError::from(io::Error::new(
io::ErrorKind::BrokenPipe,
"redis_cluster: Unable to send command",
))
})?;
receiver
.await
.unwrap_or_else(|_| {
Err(RedisError::from(io::Error::new(
io::ErrorKind::BrokenPipe,
"redis_cluster: Unable to receive command",
)))
})
.map(|response| match response {
Response::ClusterScanResult(new_scan_state_ref, key) => (new_scan_state_ref, key),
Response::Single(_) => unreachable!(),
Response::Multiple(_) => unreachable!(),
})
}
/// Send a command to the given `routing`. If `routing` is [None], it will be computed from `cmd`.
pub async fn route_command(
&mut self,
cmd: &Cmd,
routing: cluster_routing::RoutingInfo,
) -> RedisResult<Value> {
trace!("route_command");
let (sender, receiver) = oneshot::channel();
self.0
.send(Message {
cmd: CmdArg::Cmd {
cmd: Arc::new(cmd.clone()),
routing: routing.into(),
},
sender,
})
.await
.map_err(|_| {
RedisError::from(io::Error::new(
io::ErrorKind::BrokenPipe,
"redis_cluster: Unable to send command",
))
})?;
receiver
.await
.unwrap_or_else(|_| {
Err(RedisError::from(io::Error::new(
io::ErrorKind::BrokenPipe,
"redis_cluster: Unable to receive command",
)))
})
.map(|response| match response {
Response::Single(value) => value,
Response::Multiple(_) => unreachable!(),
Response::ClusterScanResult(_, _) => unreachable!(),
})
}
/// Send commands in `pipeline` to the given `route`. If `route` is [None], it will be computed from `pipeline`.
pub async fn route_pipeline<'a>(
&'a mut self,
pipeline: &'a crate::Pipeline,
offset: usize,
count: usize,
route: SingleNodeRoutingInfo,
) -> RedisResult<Vec<Value>> {
let (sender, receiver) = oneshot::channel();
self.0
.send(Message {
cmd: CmdArg::Pipeline {
pipeline: Arc::new(pipeline.clone()),
offset,
count,
route: route.into(),
},
sender,
})
.await
.map_err(|_| RedisError::from(io::Error::from(io::ErrorKind::BrokenPipe)))?;
receiver
.await
.unwrap_or_else(|_| Err(RedisError::from(io::Error::from(io::ErrorKind::BrokenPipe))))
.map(|response| match response {
Response::Multiple(values) => values,
Response::Single(_) => unreachable!(),
Response::ClusterScanResult(_, _) => unreachable!(),
})
}
}
#[cfg(feature = "tokio-comp")]
#[derive(Clone)]
struct TokioDisconnectNotifier {
disconnect_notifier: Arc<Notify>,
}
#[cfg(feature = "tokio-comp")]
#[async_trait]
impl DisconnectNotifier for TokioDisconnectNotifier {
fn notify_disconnect(&mut self) {
self.disconnect_notifier.notify_one();
}
async fn wait_for_disconnect_with_timeout(&self, max_wait: &Duration) {
let _ = timeout(*max_wait, async {
self.disconnect_notifier.notified().await;
})
.await;
}
fn clone_box(&self) -> Box<dyn DisconnectNotifier> {
Box::new(self.clone())
}
}
#[cfg(feature = "tokio-comp")]
impl TokioDisconnectNotifier {
fn new() -> TokioDisconnectNotifier {
TokioDisconnectNotifier {
disconnect_notifier: Arc::new(Notify::new()),
}
}
}
type ConnectionMap<C> = connections_container::ConnectionsMap<ConnectionFuture<C>>;
type ConnectionsContainer<C> =
self::connections_container::ConnectionsContainer<ConnectionFuture<C>>;
pub(crate) struct InnerCore<C> {
pub(crate) conn_lock: RwLock<ConnectionsContainer<C>>,
cluster_params: ClusterParams,
pending_requests: Mutex<Vec<PendingRequest<C>>>,
slot_refresh_state: SlotRefreshState,
initial_nodes: Vec<ConnectionInfo>,
subscriptions_by_address: RwLock<HashMap<String, PubSubSubscriptionInfo>>,
unassigned_subscriptions: RwLock<PubSubSubscriptionInfo>,
glide_connection_options: GlideConnectionOptions,
}
pub(crate) type Core<C> = Arc<InnerCore<C>>;
impl<C> InnerCore<C>
where
C: ConnectionLike + Connect + Clone + Send + Sync + 'static,
{
// return address of node for slot
pub(crate) async fn get_address_from_slot(
&self,
slot: u16,
slot_addr: SlotAddr,
) -> Option<String> {
self.conn_lock
.read()
.await
.slot_map
.get_node_address_for_slot(slot, slot_addr)
}
// return epoch of node
pub(crate) async fn get_address_epoch(&self, node_address: &str) -> Result<u64, RedisError> {
let command = cmd("CLUSTER").arg("INFO").to_owned();
let node_conn = self
.conn_lock
.read()
.await
.connection_for_address(node_address)
.ok_or(RedisError::from((
ErrorKind::ResponseError,
"Failed to parse cluster info",
)))?;
let cluster_info = node_conn.1.await.req_packed_command(&command).await;
match cluster_info {
Ok(value) => {
let info_dict: Result<InfoDict, RedisError> =
FromRedisValue::from_redis_value(&value);
if let Ok(info_dict) = info_dict {
let epoch = info_dict.get("cluster_my_epoch");
if let Some(epoch) = epoch {
Ok(epoch)
} else {
Err(RedisError::from((
ErrorKind::ResponseError,
"Failed to get epoch from cluster info",
)))
}
} else {
Err(RedisError::from((
ErrorKind::ResponseError,
"Failed to parse cluster info",
)))
}
}
Err(redis_error) => Err(redis_error),
}
}
// return slots of node
pub(crate) async fn get_slots_of_address(&self, node_address: &str) -> Vec<u16> {
self.conn_lock
.read()
.await
.slot_map
.get_slots_of_node(node_address)
}
}
pub(crate) struct ClusterConnInner<C> {
pub(crate) inner: Core<C>,
state: ConnectionState,
#[allow(clippy::complexity)]
in_flight_requests: stream::FuturesUnordered<Pin<Box<Request<C>>>>,
refresh_error: Option<RedisError>,
// Handler of the periodic check task.
periodic_checks_handler: Option<JoinHandle<()>>,
// Handler of fast connection validation task
connections_validation_handler: Option<JoinHandle<()>>,
}
impl<C> Dispose for ClusterConnInner<C> {
fn dispose(self) {
if let Some(handle) = self.periodic_checks_handler {
#[cfg(all(not(feature = "tokio-comp"), feature = "async-std-comp"))]
block_on(handle.cancel());
#[cfg(feature = "tokio-comp")]
handle.abort()
}
if let Some(handle) = self.connections_validation_handler {
#[cfg(all(not(feature = "tokio-comp"), feature = "async-std-comp"))]
block_on(handle.cancel());
#[cfg(feature = "tokio-comp")]
handle.abort()
}
}
}
#[derive(Clone)]
pub(crate) enum InternalRoutingInfo<C> {
SingleNode(InternalSingleNodeRouting<C>),
MultiNode((MultipleNodeRoutingInfo, Option<ResponsePolicy>)),
}
#[derive(PartialEq, Clone, Debug)]
/// Represents different policies for refreshing the cluster slots.
pub(crate) enum RefreshPolicy {
/// `Throttable` indicates that the refresh operation can be throttled,
/// meaning it can be delayed or rate-limited if necessary.
Throttable,
/// `NotThrottable` indicates that the refresh operation should not be throttled,
/// meaning it should be executed immediately without any delay or rate-limiting.
NotThrottable,
}
impl<C> From<cluster_routing::RoutingInfo> for InternalRoutingInfo<C> {
fn from(value: cluster_routing::RoutingInfo) -> Self {
match value {
cluster_routing::RoutingInfo::SingleNode(route) => {
InternalRoutingInfo::SingleNode(route.into())
}
cluster_routing::RoutingInfo::MultiNode(routes) => {
InternalRoutingInfo::MultiNode(routes)
}
}
}
}
impl<C> From<InternalSingleNodeRouting<C>> for InternalRoutingInfo<C> {
fn from(value: InternalSingleNodeRouting<C>) -> Self {
InternalRoutingInfo::SingleNode(value)
}
}
#[derive(Clone)]
pub(crate) enum InternalSingleNodeRouting<C> {
Random,
SpecificNode(Route),
ByAddress(String),
Connection {
address: String,
conn: ConnectionFuture<C>,
},
Redirect {
redirect: Redirect,
previous_routing: Box<InternalSingleNodeRouting<C>>,
},
}
impl<C> Default for InternalSingleNodeRouting<C> {
fn default() -> Self {
Self::Random
}
}
impl<C> From<SingleNodeRoutingInfo> for InternalSingleNodeRouting<C> {
fn from(value: SingleNodeRoutingInfo) -> Self {
match value {
SingleNodeRoutingInfo::Random => InternalSingleNodeRouting::Random,
SingleNodeRoutingInfo::SpecificNode(route) => {
InternalSingleNodeRouting::SpecificNode(route)
}
SingleNodeRoutingInfo::RandomPrimary => {
InternalSingleNodeRouting::SpecificNode(Route::new_random_primary())
}
SingleNodeRoutingInfo::ByAddress { host, port } => {
InternalSingleNodeRouting::ByAddress(format!("{host}:{port}"))
}
}
}
}
#[derive(Clone)]
enum CmdArg<C> {
Cmd {
cmd: Arc<Cmd>,
routing: InternalRoutingInfo<C>,
},
Pipeline {
pipeline: Arc<crate::Pipeline>,
offset: usize,
count: usize,
route: InternalSingleNodeRouting<C>,
},
ClusterScan {
// struct containing the arguments for the cluster scan command - scan state cursor, match pattern, count and object type.
cluster_scan_args: ClusterScanArgs,
},
}
fn route_for_pipeline(pipeline: &crate::Pipeline) -> RedisResult<Option<Route>> {
fn route_for_command(cmd: &Cmd) -> Option<Route> {
match cluster_routing::RoutingInfo::for_routable(cmd) {
Some(cluster_routing::RoutingInfo::SingleNode(SingleNodeRoutingInfo::Random)) => None,
Some(cluster_routing::RoutingInfo::SingleNode(
SingleNodeRoutingInfo::SpecificNode(route),
)) => Some(route),
Some(cluster_routing::RoutingInfo::SingleNode(
SingleNodeRoutingInfo::RandomPrimary,
)) => Some(Route::new_random_primary()),
Some(cluster_routing::RoutingInfo::MultiNode(_)) => None,
Some(cluster_routing::RoutingInfo::SingleNode(SingleNodeRoutingInfo::ByAddress {
..
})) => None,
None => None,
}
}
// Find first specific slot and send to it. There's no need to check If later commands
// should be routed to a different slot, since the server will return an error indicating this.
pipeline.cmd_iter().map(route_for_command).try_fold(
None,
|chosen_route, next_cmd_route| match (chosen_route, next_cmd_route) {
(None, _) => Ok(next_cmd_route),
(_, None) => Ok(chosen_route),
(Some(chosen_route), Some(next_cmd_route)) => {
if chosen_route.slot() != next_cmd_route.slot() {
Err((ErrorKind::CrossSlot, "Received crossed slots in pipeline").into())
} else if chosen_route.slot_addr() == SlotAddr::ReplicaOptional {
Ok(Some(next_cmd_route))
} else {
Ok(Some(chosen_route))
}
}
},
)
}
fn boxed_sleep(duration: Duration) -> BoxFuture<'static, ()> {
#[cfg(feature = "tokio-comp")]
return Box::pin(tokio::time::sleep(duration));
#[cfg(all(not(feature = "tokio-comp"), feature = "async-std-comp"))]
return Box::pin(async_std::task::sleep(duration));
}
pub(crate) enum Response {
Single(Value),
ClusterScanResult(ScanStateRC, Vec<Value>),
Multiple(Vec<Value>),
}
pub(crate) enum OperationTarget {
Node { address: String },
FanOut,
NotFound,
}
type OperationResult = Result<Response, (OperationTarget, RedisError)>;
impl From<String> for OperationTarget {
fn from(address: String) -> Self {
OperationTarget::Node { address }
}
}
struct Message<C> {
cmd: CmdArg<C>,
sender: oneshot::Sender<RedisResult<Response>>,
}
enum RecoverFuture {
RecoverSlots(BoxFuture<'static, RedisResult<()>>),
Reconnect(BoxFuture<'static, ()>),
}
enum ConnectionState {
PollComplete,
Recover(RecoverFuture),
}
impl fmt::Debug for ConnectionState {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}",
match self {
ConnectionState::PollComplete => "PollComplete",
ConnectionState::Recover(_) => "Recover",
}
)
}
}
#[derive(Clone)]
struct RequestInfo<C> {
cmd: CmdArg<C>,
}
impl<C> RequestInfo<C> {
fn set_redirect(&mut self, redirect: Option<Redirect>) {
if let Some(redirect) = redirect {
match &mut self.cmd {
CmdArg::Cmd { routing, .. } => match routing {
InternalRoutingInfo::SingleNode(route) => {
let redirect = InternalSingleNodeRouting::Redirect {
redirect,
previous_routing: Box::new(std::mem::take(route)),
}
.into();
*routing = redirect;
}
InternalRoutingInfo::MultiNode(_) => {
panic!("Cannot redirect multinode requests")
}
},
CmdArg::Pipeline { route, .. } => {
let redirect = InternalSingleNodeRouting::Redirect {
redirect,
previous_routing: Box::new(std::mem::take(route)),
};
*route = redirect;
}
// cluster_scan is sent as a normal command internally so we will not reach that point.
CmdArg::ClusterScan { .. } => {
unreachable!()
}
}
}
}
fn reset_routing(&mut self) {
let fix_route = |route: &mut InternalSingleNodeRouting<C>| {
match route {
InternalSingleNodeRouting::Redirect {
previous_routing, ..
} => {
let previous_routing = std::mem::take(previous_routing.as_mut());
*route = previous_routing;
}
// If a specific connection is specified, then reconnecting without resetting the routing
// will mean that the request is still routed to the old connection.
InternalSingleNodeRouting::Connection { address, .. } => {
*route = InternalSingleNodeRouting::ByAddress(address.to_string());
}
_ => {}
}
};
match &mut self.cmd {
CmdArg::Cmd { routing, .. } => {
if let InternalRoutingInfo::SingleNode(route) = routing {
fix_route(route);
}
}
CmdArg::Pipeline { route, .. } => {
fix_route(route);
}
// cluster_scan is sent as a normal command internally so we will not reach that point.
CmdArg::ClusterScan { .. } => {
unreachable!()
}
}
}
}
pin_project! {
#[project = RequestStateProj]
enum RequestState<F> {
None,
Future {
#[pin]
future: F,
},
Sleep {
#[pin]
sleep: BoxFuture<'static, ()>,
},
}
}
struct PendingRequest<C> {
retry: u32,
sender: oneshot::Sender<RedisResult<Response>>,
info: RequestInfo<C>,
}
pin_project! {
struct Request<C> {
retry_params: RetryParams,
request: Option<PendingRequest<C>>,
#[pin]
future: RequestState<BoxFuture<'static, OperationResult>>,
}
}
#[must_use]
enum Next<C> {
Retry {
request: PendingRequest<C>,
},
RetryBusyLoadingError {
request: PendingRequest<C>,
address: String,
},
Reconnect {
// if not set, then a reconnect should happen without sending a request afterwards
request: Option<PendingRequest<C>>,
target: String,
},
RefreshSlots {
// if not set, then a slot refresh should happen without sending a request afterwards
request: Option<PendingRequest<C>>,
sleep_duration: Option<Duration>,
},
ReconnectToInitialNodes {
// if not set, then a reconnect should happen without sending a request afterwards
request: Option<PendingRequest<C>>,
},
Done,
}
impl<C> Future for Request<C> {
type Output = Next<C>;
fn poll(mut self: Pin<&mut Self>, cx: &mut task::Context) -> Poll<Self::Output> {
let mut this = self.as_mut().project();
// If the sender is closed, the caller is no longer waiting for the reply, and it is ambiguous
// whether they expect the side-effect of the request to happen or not.
if this.request.is_none() || this.request.as_ref().unwrap().sender.is_closed() {
return Poll::Ready(Next::Done);
}
let future = match this.future.as_mut().project() {
RequestStateProj::Future { future } => future,
RequestStateProj::Sleep { sleep } => {
ready!(sleep.poll(cx));
return Next::Retry {
request: self.project().request.take().unwrap(),
}
.into();
}
_ => panic!("Request future must be Some"),
};
match ready!(future.poll(cx)) {
Ok(item) => {
self.respond(Ok(item));
Next::Done.into()
}
Err((target, err)) => {
let request = this.request.as_mut().unwrap();
// TODO - would be nice if we didn't need to repeat this code twice, with & without retries.
if request.retry >= this.retry_params.number_of_retries {
let next = if err.kind() == ErrorKind::AllConnectionsUnavailable {
Next::ReconnectToInitialNodes { request: None }.into()
} else if matches!(err.retry_method(), crate::types::RetryMethod::MovedRedirect)
|| matches!(target, OperationTarget::NotFound)
{
Next::RefreshSlots {
request: None,
sleep_duration: None,
}
.into()
} else if matches!(err.retry_method(), crate::types::RetryMethod::Reconnect) {
if let OperationTarget::Node { address } = target {
Next::Reconnect {
request: None,
target: address,
}
.into()
} else {
Next::Done.into()
}
} else {
Next::Done.into()
};
self.respond(Err(err));
return next;
}
request.retry = request.retry.saturating_add(1);
if err.kind() == ErrorKind::AllConnectionsUnavailable {
return Next::ReconnectToInitialNodes {
request: Some(this.request.take().unwrap()),
}
.into();
}
let sleep_duration = this.retry_params.wait_time_for_retry(request.retry);
let address = match target {
OperationTarget::Node { address } => address,
OperationTarget::FanOut => {
trace!("Request error `{}` multi-node request", err);
// Fanout operation are retried per internal request, and don't need additional retries.
self.respond(Err(err));
return Next::Done.into();
}
OperationTarget::NotFound => {
// TODO - this is essentially a repeat of the retirable error. probably can remove duplication.
let mut request = this.request.take().unwrap();
request.info.reset_routing();
return Next::RefreshSlots {
request: Some(request),
sleep_duration: Some(sleep_duration),
}
.into();
}
};
warn!("Received request error {} on node {:?}.", err, address);
match err.retry_method() {
crate::types::RetryMethod::AskRedirect => {
let mut request = this.request.take().unwrap();
request.info.set_redirect(
err.redirect_node()
.map(|(node, _slot)| Redirect::Ask(node.to_string())),
);
Next::Retry { request }.into()
}
crate::types::RetryMethod::MovedRedirect => {
let mut request = this.request.take().unwrap();
request.info.set_redirect(
err.redirect_node()
.map(|(node, _slot)| Redirect::Moved(node.to_string())),
);
Next::RefreshSlots {
request: Some(request),
sleep_duration: None,
}
.into()
}
crate::types::RetryMethod::WaitAndRetry => {
let sleep_duration = this.retry_params.wait_time_for_retry(request.retry);
// Sleep and retry.
this.future.set(RequestState::Sleep {
sleep: boxed_sleep(sleep_duration),
});
self.poll(cx)
}
crate::types::RetryMethod::Reconnect => {
let mut request = this.request.take().unwrap();
// TODO should we reset the redirect here?
request.info.reset_routing();
warn!("disconnected from {:?}", address);
Next::Reconnect {
request: Some(request),
target: address,
}
.into()
}
crate::types::RetryMethod::WaitAndRetryOnPrimaryRedirectOnReplica => {
Next::RetryBusyLoadingError {
request: this.request.take().unwrap(),
address,
}
.into()
}
crate::types::RetryMethod::RetryImmediately => Next::Retry {
request: this.request.take().unwrap(),
}
.into(),
crate::types::RetryMethod::NoRetry => {
self.respond(Err(err));
Next::Done.into()
}
}
}
}
}
}
impl<C> Request<C> {
fn respond(self: Pin<&mut Self>, msg: RedisResult<Response>) {
// If `send` errors the receiver has dropped and thus does not care about the message
let _ = self
.project()
.request
.take()
.expect("Result should only be sent once")
.sender
.send(msg);
}